diff --git a/Alignment/APEEstimation/interface/EventVariables.h b/Alignment/APEEstimation/interface/EventVariables.h index b64541724c7c1..2079f89fa8371 100644 --- a/Alignment/APEEstimation/interface/EventVariables.h +++ b/Alignment/APEEstimation/interface/EventVariables.h @@ -3,49 +3,73 @@ #include -struct TrackStruct{ - - TrackStruct(){} - - enum HitState{notInTracker, notAssignedToSectors, invalid, negativeError, ok}; - - struct HitParameterStruct{ - - HitParameterStruct(): hitState(ok), - isPixelHit(false), - goodXMeasurement(false), - goodYMeasurement(false), - widthX(0), - baryStripX(-999.F), - widthY(0), - baryStripY(-999.F), - chargePixel(-999.F), - clusterProbabilityXY(-999.F), clusterProbabilityQ(-999.F), - clusterProbabilityXYQ(-999.F), logClusterProbability(-999.F), - isOnEdge(false), hasBadPixels(false), spansTwoRoc(false), - qBin(-1), - isModuleUsable(true), - chargeStrip(0), - maxStrip(0), maxStripInv(0), maxCharge(0), maxIndex(0), - chargeOnEdges(-999.F), chargeAsymmetry(-999.F), - chargeLRplus(-999.F), chargeLRminus(-999.F), - sOverN(-999.F), - projWidth(-999.F), - resX(-999.F), norResX(-999.F), xHit(-999.F), xTrk(-999.F), - errXHit(-999.F), errXTrk(-999.F), errX(-999.F), errX2(-999.F), - errXHitWoApe(-999.F), errXWoApe(-999.F), - probX(-999.F), - resY(-999.F), norResY(-999.F), yHit(-999.F), yTrk(-999.F), - errYHit(-999.F), errYTrk(-999.F), errY(-999.F), errY2(-999.F), - errYHitWoApe(-999.F), errYWoApe(-999.F), - probY(-999.F), - phiSens(-999.F), phiSensX(-999.F), phiSensY(-999.F){} - +struct TrackStruct { + TrackStruct() {} + + enum HitState { notInTracker, notAssignedToSectors, invalid, negativeError, ok }; + + struct HitParameterStruct { + HitParameterStruct() + : hitState(ok), + isPixelHit(false), + goodXMeasurement(false), + goodYMeasurement(false), + widthX(0), + baryStripX(-999.F), + widthY(0), + baryStripY(-999.F), + chargePixel(-999.F), + clusterProbabilityXY(-999.F), + clusterProbabilityQ(-999.F), + clusterProbabilityXYQ(-999.F), + logClusterProbability(-999.F), + isOnEdge(false), + hasBadPixels(false), + spansTwoRoc(false), + qBin(-1), + isModuleUsable(true), + chargeStrip(0), + maxStrip(0), + maxStripInv(0), + maxCharge(0), + maxIndex(0), + chargeOnEdges(-999.F), + chargeAsymmetry(-999.F), + chargeLRplus(-999.F), + chargeLRminus(-999.F), + sOverN(-999.F), + projWidth(-999.F), + resX(-999.F), + norResX(-999.F), + xHit(-999.F), + xTrk(-999.F), + errXHit(-999.F), + errXTrk(-999.F), + errX(-999.F), + errX2(-999.F), + errXHitWoApe(-999.F), + errXWoApe(-999.F), + probX(-999.F), + resY(-999.F), + norResY(-999.F), + yHit(-999.F), + yTrk(-999.F), + errYHit(-999.F), + errYTrk(-999.F), + errY(-999.F), + errY2(-999.F), + errYHitWoApe(-999.F), + errYWoApe(-999.F), + probY(-999.F), + phiSens(-999.F), + phiSensX(-999.F), + phiSensY(-999.F) {} + HitState hitState; bool isPixelHit; bool goodXMeasurement, goodYMeasurement; std::vector v_sector; - + // Cluster parameters // pixel+strip unsigned int widthX; @@ -54,58 +78,58 @@ struct TrackStruct{ unsigned int widthY; float baryStripY; float chargePixel; - float clusterProbabilityXY, clusterProbabilityQ, - clusterProbabilityXYQ, logClusterProbability; + float clusterProbabilityXY, clusterProbabilityQ, clusterProbabilityXYQ, logClusterProbability; bool isOnEdge, hasBadPixels, spansTwoRoc; int qBin; // strip only bool isModuleUsable; unsigned int chargeStrip; unsigned int maxStrip, maxStripInv, maxCharge, maxIndex; - float chargeOnEdges, chargeAsymmetry, - chargeLRplus, chargeLRminus; + float chargeOnEdges, chargeAsymmetry, chargeLRplus, chargeLRminus; float sOverN; float projWidth; - + // trackFit results - float resX, norResX, xHit, xTrk, - errXHit, errXTrk, errX, errX2, - errXHitWoApe, errXWoApe, - probX; - float resY, norResY, yHit, yTrk, - errYHit, errYTrk, errY, errY2, - errYHitWoApe, errYWoApe, - probY; + float resX, norResX, xHit, xTrk, errXHit, errXTrk, errX, errX2, errXHitWoApe, errXWoApe, probX; + float resY, norResY, yHit, yTrk, errYHit, errYTrk, errY, errY2, errYHitWoApe, errYWoApe, probY; float phiSens, phiSensX, phiSensY; }; - - struct TrackParameterStruct{ - - TrackParameterStruct(): hitsSize(-999), hitsValid(-999), hitsInvalid(-999), - hits2D(-999), layersMissed(-999), - hitsPixel(-999), hitsStrip(-999), - charge(-999), - chi2(-999.F), ndof(-999.F), norChi2(-999.F), prob(-999.F), - eta(-999.F), etaErr(-999.F), theta(-999.F), - phi(-999.F), phiErr(-999.F), - d0(-999.F), d0Beamspot(-999.F), d0BeamspotErr(-999.F), - dz(-999.F), dzErr(-999.F), dzBeamspot(-999.F), - p(-999.F), pt(-999.F), ptErr(-999.F), - meanPhiSensToNorm(-999.F){} - - int hitsSize, hitsValid, hitsInvalid, - hits2D, layersMissed, - hitsPixel, hitsStrip, - charge; - float chi2, ndof, norChi2, prob, - eta, etaErr, theta, - phi, phiErr, - d0, d0Beamspot, d0BeamspotErr, - dz, dzErr, dzBeamspot, - p, pt, ptErr, - meanPhiSensToNorm; + + struct TrackParameterStruct { + TrackParameterStruct() + : hitsSize(-999), + hitsValid(-999), + hitsInvalid(-999), + hits2D(-999), + layersMissed(-999), + hitsPixel(-999), + hitsStrip(-999), + charge(-999), + chi2(-999.F), + ndof(-999.F), + norChi2(-999.F), + prob(-999.F), + eta(-999.F), + etaErr(-999.F), + theta(-999.F), + phi(-999.F), + phiErr(-999.F), + d0(-999.F), + d0Beamspot(-999.F), + d0BeamspotErr(-999.F), + dz(-999.F), + dzErr(-999.F), + dzBeamspot(-999.F), + p(-999.F), + pt(-999.F), + ptErr(-999.F), + meanPhiSensToNorm(-999.F) {} + + int hitsSize, hitsValid, hitsInvalid, hits2D, layersMissed, hitsPixel, hitsStrip, charge; + float chi2, ndof, norChi2, prob, eta, etaErr, theta, phi, phiErr, d0, d0Beamspot, d0BeamspotErr, dz, dzErr, + dzBeamspot, p, pt, ptErr, meanPhiSensToNorm; }; - + TrackParameterStruct trkParams; std::vector v_hitParams; }; diff --git a/Alignment/APEEstimation/interface/ReducedTrackerTreeVariables.h b/Alignment/APEEstimation/interface/ReducedTrackerTreeVariables.h index 0e0c1632289f9..c42174edb336b 100644 --- a/Alignment/APEEstimation/interface/ReducedTrackerTreeVariables.h +++ b/Alignment/APEEstimation/interface/ReducedTrackerTreeVariables.h @@ -1,28 +1,21 @@ #ifndef ReducedTrackerTreeVariables_h #define ReducedTrackerTreeVariables_h - // For ROOT types with '_t': #include - - // container to hold those static module parameters needed for correct xPrime-Residual calculation (and others), determined with ideal geometry -struct ReducedTrackerTreeVariables{ - - ReducedTrackerTreeVariables(){this->clear();} - - void clear(){ +struct ReducedTrackerTreeVariables { + ReducedTrackerTreeVariables() { this->clear(); } + + void clear() { subdetId = 0; nStrips = 0; uDirection = vDirection = wDirection = 0; } - - UInt_t subdetId, - nStrips; + + UInt_t subdetId, nStrips; Int_t uDirection, vDirection, wDirection; }; - - #endif diff --git a/Alignment/APEEstimation/interface/TrackerDetectorStruct.h b/Alignment/APEEstimation/interface/TrackerDetectorStruct.h index b057b69df70a3..eaf43af046a52 100644 --- a/Alignment/APEEstimation/interface/TrackerDetectorStruct.h +++ b/Alignment/APEEstimation/interface/TrackerDetectorStruct.h @@ -1,57 +1,71 @@ #ifndef Alignment_APEEstimation_TrackerDetectorStruct_h #define Alignment_APEEstimation_TrackerDetectorStruct_h - #include "TH1.h" #include "TH2.h" #include "TProfile.h" -struct TrackerDetectorStruct{ - - TrackerDetectorStruct(): TrkSize(nullptr), TrkSizeGood(nullptr), - HitsSize(nullptr), HitsValid(nullptr), HitsInvalid(nullptr), Hits2D(nullptr), - HitsGood(nullptr), LayersMissed(nullptr), - HitsPixel(nullptr), HitsStrip(nullptr), - Charge(nullptr), - Chi2(nullptr), Ndof(nullptr), NorChi2(nullptr), Prob(nullptr), - Eta(nullptr), EtaErr(nullptr), EtaSig(nullptr), Theta(nullptr), - Phi(nullptr), PhiErr(nullptr), PhiSig(nullptr), - D0Beamspot(nullptr), D0BeamspotErr(nullptr), D0BeamspotSig(nullptr), - Dz(nullptr), DzErr(nullptr), DzSig(nullptr), - P(nullptr), Pt(nullptr), PtErr(nullptr), PtSig(nullptr), - MeanAngle(nullptr), - HitsGoodVsHitsValid(nullptr), MeanAngleVsHits(nullptr), - HitsPixelVsEta(nullptr), HitsPixelVsTheta(nullptr), - HitsStripVsEta(nullptr), HitsStripVsTheta(nullptr), - PtVsEta(nullptr), PtVsTheta(nullptr), - PHitsGoodVsHitsValid(nullptr), PMeanAngleVsHits(nullptr), - PHitsPixelVsEta(nullptr), PHitsPixelVsTheta(nullptr), - PHitsStripVsEta(nullptr), PHitsStripVsTheta(nullptr), - PPtVsEta(nullptr), PPtVsTheta(nullptr){} - - TH1 *TrkSize, *TrkSizeGood, - *HitsSize, *HitsValid, *HitsInvalid, *Hits2D, - *HitsGood, *LayersMissed, - *HitsPixel, *HitsStrip, - *Charge, - *Chi2, *Ndof, *NorChi2, *Prob, - *Eta, *EtaErr, *EtaSig, *Theta, - *Phi,*PhiErr, *PhiSig, - *D0Beamspot, *D0BeamspotErr, *D0BeamspotSig, - *Dz, *DzErr, *DzSig, - *P, *Pt, *PtErr, *PtSig, - *MeanAngle; - - TH2 *HitsGoodVsHitsValid, *MeanAngleVsHits, - *HitsPixelVsEta, *HitsPixelVsTheta, - *HitsStripVsEta, *HitsStripVsTheta, +struct TrackerDetectorStruct { + TrackerDetectorStruct() + : TrkSize(nullptr), + TrkSizeGood(nullptr), + HitsSize(nullptr), + HitsValid(nullptr), + HitsInvalid(nullptr), + Hits2D(nullptr), + HitsGood(nullptr), + LayersMissed(nullptr), + HitsPixel(nullptr), + HitsStrip(nullptr), + Charge(nullptr), + Chi2(nullptr), + Ndof(nullptr), + NorChi2(nullptr), + Prob(nullptr), + Eta(nullptr), + EtaErr(nullptr), + EtaSig(nullptr), + Theta(nullptr), + Phi(nullptr), + PhiErr(nullptr), + PhiSig(nullptr), + D0Beamspot(nullptr), + D0BeamspotErr(nullptr), + D0BeamspotSig(nullptr), + Dz(nullptr), + DzErr(nullptr), + DzSig(nullptr), + P(nullptr), + Pt(nullptr), + PtErr(nullptr), + PtSig(nullptr), + MeanAngle(nullptr), + HitsGoodVsHitsValid(nullptr), + MeanAngleVsHits(nullptr), + HitsPixelVsEta(nullptr), + HitsPixelVsTheta(nullptr), + HitsStripVsEta(nullptr), + HitsStripVsTheta(nullptr), + PtVsEta(nullptr), + PtVsTheta(nullptr), + PHitsGoodVsHitsValid(nullptr), + PMeanAngleVsHits(nullptr), + PHitsPixelVsEta(nullptr), + PHitsPixelVsTheta(nullptr), + PHitsStripVsEta(nullptr), + PHitsStripVsTheta(nullptr), + PPtVsEta(nullptr), + PPtVsTheta(nullptr) {} + + TH1 *TrkSize, *TrkSizeGood, *HitsSize, *HitsValid, *HitsInvalid, *Hits2D, *HitsGood, *LayersMissed, *HitsPixel, + *HitsStrip, *Charge, *Chi2, *Ndof, *NorChi2, *Prob, *Eta, *EtaErr, *EtaSig, *Theta, *Phi, *PhiErr, *PhiSig, + *D0Beamspot, *D0BeamspotErr, *D0BeamspotSig, *Dz, *DzErr, *DzSig, *P, *Pt, *PtErr, *PtSig, *MeanAngle; + + TH2 *HitsGoodVsHitsValid, *MeanAngleVsHits, *HitsPixelVsEta, *HitsPixelVsTheta, *HitsStripVsEta, *HitsStripVsTheta, *PtVsEta, *PtVsTheta; - - TProfile *PHitsGoodVsHitsValid, *PMeanAngleVsHits, - *PHitsPixelVsEta, *PHitsPixelVsTheta, - *PHitsStripVsEta, *PHitsStripVsTheta, - *PPtVsEta, *PPtVsTheta; - + + TProfile *PHitsGoodVsHitsValid, *PMeanAngleVsHits, *PHitsPixelVsEta, *PHitsPixelVsTheta, *PHitsStripVsEta, + *PHitsStripVsTheta, *PPtVsEta, *PPtVsTheta; }; #endif diff --git a/Alignment/APEEstimation/interface/TrackerSectorStruct.h b/Alignment/APEEstimation/interface/TrackerSectorStruct.h index 81c718d4cc14d..eeab8005ebf1b 100644 --- a/Alignment/APEEstimation/interface/TrackerSectorStruct.h +++ b/Alignment/APEEstimation/interface/TrackerSectorStruct.h @@ -1,7 +1,6 @@ #ifndef Alignment_APEEstimation_TrackerSectorStruct_h #define Alignment_APEEstimation_TrackerSectorStruct_h - #include #include #include "TH1F.h" @@ -12,7 +11,6 @@ #include "Alignment/APEEstimation/interface/EventVariables.h" - #include "TH1.h" #include "TH2.h" #include "TTree.h" @@ -24,323 +22,492 @@ //class TString; //class TFileDirectory; +class TrackerSectorStruct { +public: + inline TrackerSectorStruct(); + inline ~TrackerSectorStruct(); + struct CorrelationHists { + CorrelationHists() + : Variable(nullptr), + NorResXVsVar(nullptr), + ProbXVsVar(nullptr), + SigmaXHitVsVar(nullptr), + SigmaXTrkVsVar(nullptr), + SigmaXVsVar(nullptr), + PNorResXVsVar(nullptr), + PProbXVsVar(nullptr), + PSigmaXHitVsVar(nullptr), + PSigmaXTrkVsVar(nullptr), + PSigmaXVsVar(nullptr){}; + + inline void fillCorrHists(const TString, + const TrackStruct::HitParameterStruct &hitParameterStruct, + double variable); + inline void fillCorrHistsX(const TrackStruct::HitParameterStruct &hitParameterStruct, double variable); + inline void fillCorrHistsY(const TrackStruct::HitParameterStruct &hitParameterStruct, double variable); - - - - - -class TrackerSectorStruct{ - public: - - inline TrackerSectorStruct(); - - inline ~TrackerSectorStruct(); - - - - struct CorrelationHists{ - CorrelationHists():Variable(nullptr), - NorResXVsVar(nullptr), ProbXVsVar(nullptr), - SigmaXHitVsVar(nullptr), SigmaXTrkVsVar(nullptr), SigmaXVsVar(nullptr), - PNorResXVsVar(nullptr), PProbXVsVar(nullptr), - PSigmaXHitVsVar(nullptr), PSigmaXTrkVsVar(nullptr), PSigmaXVsVar(nullptr){}; - - inline void fillCorrHists(const TString, const TrackStruct::HitParameterStruct& hitParameterStruct, double variable); - inline void fillCorrHistsX(const TrackStruct::HitParameterStruct& hitParameterStruct, double variable); - inline void fillCorrHistsY(const TrackStruct::HitParameterStruct& hitParameterStruct, double variable); - TH1F *Variable; - TH2F *NorResXVsVar, *ProbXVsVar, - *SigmaXHitVsVar, *SigmaXTrkVsVar, *SigmaXVsVar; - TProfile *PNorResXVsVar, *PProbXVsVar, - *PSigmaXHitVsVar, *PSigmaXTrkVsVar, *PSigmaXVsVar; + TH2F *NorResXVsVar, *ProbXVsVar, *SigmaXHitVsVar, *SigmaXTrkVsVar, *SigmaXVsVar; + TProfile *PNorResXVsVar, *PProbXVsVar, *PSigmaXHitVsVar, *PSigmaXTrkVsVar, *PSigmaXVsVar; }; - - - inline void setCorrHistParams(TFileDirectory*, double, double, double); - inline CorrelationHists bookCorrHists(TString, TString, TString, TString, TString, int, int, double, double, std::string ="nphtr"); - inline CorrelationHists bookCorrHistsX(TString, TString, TString, TString, int, int, double, double, std::string ="nphtr"); - inline CorrelationHists bookCorrHistsY(TString, TString, TString, TString, int, int, double, double, std::string ="nphtr"); - /// same, but without booking 1D histo - inline CorrelationHists bookCorrHists(TString, TString ,TString ,TString, int, double, double, std::string ="nphtr"); - inline CorrelationHists bookCorrHistsX(TString ,TString ,TString, int, double, double, std::string ="nphtr"); - inline CorrelationHists bookCorrHistsY(TString ,TString ,TString, int, double, double, std::string ="nphtr"); - - - - + + inline void setCorrHistParams(TFileDirectory *, double, double, double); + inline CorrelationHists bookCorrHists( + TString, TString, TString, TString, TString, int, int, double, double, std::string = "nphtr"); + inline CorrelationHists bookCorrHistsX( + TString, TString, TString, TString, int, int, double, double, std::string = "nphtr"); + inline CorrelationHists bookCorrHistsY( + TString, TString, TString, TString, int, int, double, double, std::string = "nphtr"); + /// same, but without booking 1D histo + inline CorrelationHists bookCorrHists(TString, TString, TString, TString, int, double, double, std::string = "nphtr"); + inline CorrelationHists bookCorrHistsX(TString, TString, TString, int, double, double, std::string = "nphtr"); + inline CorrelationHists bookCorrHistsY(TString, TString, TString, int, double, double, std::string = "nphtr"); + TFileDirectory *directory_; - double norResXMax_, sigmaXHitMax_, sigmaXMax_; // Used for x and y - std::map m_correlationHistsX; - std::map m_correlationHistsY; - - + double norResXMax_, sigmaXHitMax_, sigmaXMax_; // Used for x and y + std::map m_correlationHistsX; + std::map m_correlationHistsY; + // Name of sector as string and as title of a histogram std::string name; TH1 *Name; - + // Module IDs of modules in sector std::vector v_rawId; - - - TH1 *ResX, *NorResX, *XHit, *XTrk, - *SigmaX2, *ProbX; - TH2 *WidthVsPhiSensX, *WidthVsWidthProjected, *WidthDiffVsMaxStrip, *WidthDiffVsSigmaXHit, - *PhiSensXVsBarycentreX; + + TH1 *ResX, *NorResX, *XHit, *XTrk, *SigmaX2, *ProbX; + TH2 *WidthVsPhiSensX, *WidthVsWidthProjected, *WidthDiffVsMaxStrip, *WidthDiffVsSigmaXHit, *PhiSensXVsBarycentreX; TProfile *PWidthVsPhiSensX, *PWidthVsWidthProjected, *PWidthDiffVsMaxStrip, *PWidthDiffVsSigmaXHit, *PPhiSensXVsBarycentreX; - std::map > m_sigmaX; - - TH1 *ResY, *NorResY, *YHit, *YTrk, - *SigmaY2, *ProbY; + std::map > m_sigmaX; + + TH1 *ResY, *NorResY, *YHit, *YTrk, *SigmaY2, *ProbY; TH2 *PhiSensYVsBarycentreY; - TProfile *PPhiSensYVsBarycentreY; - std::map > m_sigmaY; - - + TProfile *PPhiSensYVsBarycentreY; + std::map > m_sigmaY; + //for every bin in sigmaX or sigmaY the needful histos to calculate the APE - std::map > m_binnedHists; - - + std::map > m_binnedHists; + //for presenting results TTree *RawId; TH1 *EntriesX; - TH1 *WeightX, *MeanX, *RmsX, *FitMeanX1, *ResidualWidthX1, *CorrectionX1, - *FitMeanX2, *ResidualWidthX2, *CorrectionX2; + TH1 *WeightX, *MeanX, *RmsX, *FitMeanX1, *ResidualWidthX1, *CorrectionX1, *FitMeanX2, *ResidualWidthX2, *CorrectionX2; TH1 *EntriesY; - TH1 *WeightY, *MeanY, *RmsY, *FitMeanY1, *ResidualWidthY1, *CorrectionY1, - *FitMeanY2, *ResidualWidthY2, *CorrectionY2; - + TH1 *WeightY, *MeanY, *RmsY, *FitMeanY1, *ResidualWidthY1, *CorrectionY1, *FitMeanY2, *ResidualWidthY2, *CorrectionY2; + // To book pixel-specific or strip-specific histos only bool isPixel; }; - - - - - - - - -TrackerSectorStruct::TrackerSectorStruct(): directory_(nullptr), - norResXMax_(999.), sigmaXHitMax_(999.), sigmaXMax_(999.), - name("default"), Name(nullptr), - ResX(nullptr), NorResX(nullptr), XHit(nullptr), XTrk(nullptr), - SigmaX2(nullptr), ProbX(nullptr), - WidthVsPhiSensX(nullptr), WidthVsWidthProjected(nullptr), WidthDiffVsMaxStrip(nullptr), WidthDiffVsSigmaXHit(nullptr), - PhiSensXVsBarycentreX(nullptr), - PWidthVsPhiSensX(nullptr), PWidthVsWidthProjected(nullptr), PWidthDiffVsMaxStrip(nullptr), PWidthDiffVsSigmaXHit(nullptr), - PPhiSensXVsBarycentreX(nullptr), - ResY(nullptr), NorResY(nullptr), YHit(nullptr), YTrk(nullptr), - SigmaY2(nullptr), ProbY(nullptr), - PhiSensYVsBarycentreY(nullptr), - PPhiSensYVsBarycentreY(nullptr), - RawId(nullptr), - EntriesX(nullptr), - MeanX(nullptr), RmsX(nullptr), FitMeanX1(nullptr), ResidualWidthX1(nullptr), CorrectionX1(nullptr), - FitMeanX2(nullptr), ResidualWidthX2(nullptr), CorrectionX2(nullptr), - EntriesY(nullptr), - MeanY(nullptr), RmsY(nullptr), FitMeanY1(nullptr), ResidualWidthY1(nullptr), CorrectionY1(nullptr), - FitMeanY2(nullptr), ResidualWidthY2(nullptr), CorrectionY2(nullptr), - isPixel(false){} - - - -TrackerSectorStruct::~TrackerSectorStruct(){} - - - -void -TrackerSectorStruct::setCorrHistParams(TFileDirectory *directory, double norResXMax, double sigmaXHitMax, double sigmaXMax){ +TrackerSectorStruct::TrackerSectorStruct() + : directory_(nullptr), + norResXMax_(999.), + sigmaXHitMax_(999.), + sigmaXMax_(999.), + name("default"), + Name(nullptr), + ResX(nullptr), + NorResX(nullptr), + XHit(nullptr), + XTrk(nullptr), + SigmaX2(nullptr), + ProbX(nullptr), + WidthVsPhiSensX(nullptr), + WidthVsWidthProjected(nullptr), + WidthDiffVsMaxStrip(nullptr), + WidthDiffVsSigmaXHit(nullptr), + PhiSensXVsBarycentreX(nullptr), + PWidthVsPhiSensX(nullptr), + PWidthVsWidthProjected(nullptr), + PWidthDiffVsMaxStrip(nullptr), + PWidthDiffVsSigmaXHit(nullptr), + PPhiSensXVsBarycentreX(nullptr), + ResY(nullptr), + NorResY(nullptr), + YHit(nullptr), + YTrk(nullptr), + SigmaY2(nullptr), + ProbY(nullptr), + PhiSensYVsBarycentreY(nullptr), + PPhiSensYVsBarycentreY(nullptr), + RawId(nullptr), + EntriesX(nullptr), + MeanX(nullptr), + RmsX(nullptr), + FitMeanX1(nullptr), + ResidualWidthX1(nullptr), + CorrectionX1(nullptr), + FitMeanX2(nullptr), + ResidualWidthX2(nullptr), + CorrectionX2(nullptr), + EntriesY(nullptr), + MeanY(nullptr), + RmsY(nullptr), + FitMeanY1(nullptr), + ResidualWidthY1(nullptr), + CorrectionY1(nullptr), + FitMeanY2(nullptr), + ResidualWidthY2(nullptr), + CorrectionY2(nullptr), + isPixel(false) {} + +TrackerSectorStruct::~TrackerSectorStruct() {} + +void TrackerSectorStruct::setCorrHistParams(TFileDirectory *directory, + double norResXMax, + double sigmaXHitMax, + double sigmaXMax) { directory_ = directory; norResXMax_ = norResXMax; sigmaXHitMax_ = sigmaXHitMax; sigmaXMax_ = sigmaXMax; } - - -TrackerSectorStruct::CorrelationHists -TrackerSectorStruct::bookCorrHistsX(TString varName,TString varTitle,TString labelX,TString unitX,int nBinX1D,int nBinX2D,double minBinX,double maxBinX,std::string options){ +TrackerSectorStruct::CorrelationHists TrackerSectorStruct::bookCorrHistsX(TString varName, + TString varTitle, + TString labelX, + TString unitX, + int nBinX1D, + int nBinX2D, + double minBinX, + double maxBinX, + std::string options) { return bookCorrHists("X", varName, varTitle, labelX, unitX, nBinX1D, nBinX2D, minBinX, maxBinX, options); } -TrackerSectorStruct::CorrelationHists -TrackerSectorStruct::bookCorrHistsY(TString varName,TString varTitle,TString labelX,TString unitX,int nBinX1D,int nBinX2D,double minBinX,double maxBinX,std::string options){ +TrackerSectorStruct::CorrelationHists TrackerSectorStruct::bookCorrHistsY(TString varName, + TString varTitle, + TString labelX, + TString unitX, + int nBinX1D, + int nBinX2D, + double minBinX, + double maxBinX, + std::string options) { return bookCorrHists("Y", varName, varTitle, labelX, unitX, nBinX1D, nBinX2D, minBinX, maxBinX, options); } -TrackerSectorStruct::CorrelationHists -TrackerSectorStruct::bookCorrHists(TString xY,TString varName,TString varTitle,TString labelX,TString unitX,int nBinX1D,int nBinX2D,double minBinX,double maxBinX,std::string options){ +TrackerSectorStruct::CorrelationHists TrackerSectorStruct::bookCorrHists(TString xY, + TString varName, + TString varTitle, + TString labelX, + TString unitX, + int nBinX1D, + int nBinX2D, + double minBinX, + double maxBinX, + std::string options) { TString xy; TString suffix; - if(xY=="X"){ + if (xY == "X") { xy = "x"; suffix = ""; } - if(xY=="Y"){ + if (xY == "Y") { xy = "y"; suffix = "_y"; } - - const std::string& o(options); + + const std::string &o(options); CorrelationHists correlationHists; - - if(!(o.find("n") != std::string::npos || o.find("p") != std::string::npos || o.find("h") != std::string::npos || - o.find("t") != std::string::npos || o.find("r") != std::string::npos))return correlationHists; - + + if (!(o.find("n") != std::string::npos || o.find("p") != std::string::npos || o.find("h") != std::string::npos || + o.find("t") != std::string::npos || o.find("r") != std::string::npos)) + return correlationHists; + TFileDirectory *directory(directory_); double norResXMax(norResXMax_), sigmaXHitMax(sigmaXHitMax_), sigmaXMax(sigmaXMax_); - - if(!directory)return correlationHists; - - - correlationHists.Variable = directory->make("h_"+varName+suffix,varTitle+" "+labelX+";"+labelX+" "+unitX+";# hits",nBinX1D,minBinX,maxBinX); - - if(options.find("n") != std::string::npos) - correlationHists.NorResXVsVar = directory->make("h2_norRes"+xY+"Vs"+varName,"r_{"+xy+"}/#sigma_{r,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";("+xy+"_{trk}-"+xy+"_{hit})/#sigma_{r,"+xy+"}",nBinX2D,minBinX,maxBinX,25,-norResXMax,norResXMax); - if(options.find("p") != std::string::npos) - correlationHists.ProbXVsVar = directory->make("h2_prob"+xY+"Vs"+varName,"prob_{"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";prob_{"+xy+"}",nBinX2D,minBinX,maxBinX,60,-0.1,1.1); - if(options.find("h") != std::string::npos) - correlationHists.SigmaXHitVsVar = directory->make("h2_sigma"+xY+"HitVs"+varName,"#sigma_{hit,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{hit,"+xy+"} [#mum]",nBinX2D,minBinX,maxBinX,50,0*10000.,sigmaXHitMax*10000.); - if(options.find("t") != std::string::npos) - correlationHists.SigmaXTrkVsVar = directory->make("h2_sigma"+xY+"TrkVs"+varName,"#sigma_{trk,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{trk,"+xy+"} [#mum]",nBinX2D,minBinX,maxBinX,50,0*10000.,sigmaXMax*10000.); - if(options.find("r") != std::string::npos) - correlationHists.SigmaXVsVar = directory->make("h2_sigma"+xY+"Vs"+varName,"#sigma_{r,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{r,"+xy+"} [#mum]",nBinX2D,minBinX,maxBinX,50,0*10000.,sigmaXMax*10000.); - - if(options.find("n") != std::string::npos) - correlationHists.PNorResXVsVar = directory->make("p_norRes"+xY+"Vs"+varName,"r_{"+xy+"}/#sigma_{r,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";("+xy+"_{trk}-"+xy+"_{hit})/#sigma_{r,"+xy+"}",nBinX2D,minBinX,maxBinX,"s"); - if(options.find("p") != std::string::npos) - correlationHists.PProbXVsVar = directory->make("p_prob"+xY+"Vs"+varName,"prob_{"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";prob_{"+xy+"}",nBinX2D,minBinX,maxBinX,"s"); - if(options.find("h") != std::string::npos) - correlationHists.PSigmaXHitVsVar = directory->make("p_sigma"+xY+"HitVs"+varName,"#sigma_{hit,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{hit,"+xy+"} [#mum]",nBinX2D,minBinX,maxBinX); - if(options.find("t") != std::string::npos) - correlationHists.PSigmaXTrkVsVar = directory->make("p_sigma"+xY+"TrkVs"+varName,"#sigma_{trk,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{trk,"+xy+"} [#mum]",nBinX2D,minBinX,maxBinX); - if(options.find("r") != std::string::npos) - correlationHists.PSigmaXVsVar = directory->make("p_sigma"+xY+"Vs"+varName,"#sigma_{r,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{r,"+xy+"} [#mum]",nBinX2D,minBinX,maxBinX); - - return correlationHists; -} + if (!directory) + return correlationHists; + + correlationHists.Variable = directory->make("h_" + varName + suffix, + varTitle + " " + labelX + ";" + labelX + " " + unitX + ";# hits", + nBinX1D, + minBinX, + maxBinX); + + if (options.find("n") != std::string::npos) + correlationHists.NorResXVsVar = + directory->make("h2_norRes" + xY + "Vs" + varName, + "r_{" + xy + "}/#sigma_{r," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + + ";(" + xy + "_{trk}-" + xy + "_{hit})/#sigma_{r," + xy + "}", + nBinX2D, + minBinX, + maxBinX, + 25, + -norResXMax, + norResXMax); + if (options.find("p") != std::string::npos) + correlationHists.ProbXVsVar = + directory->make("h2_prob" + xY + "Vs" + varName, + "prob_{" + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";prob_{" + xy + "}", + nBinX2D, + minBinX, + maxBinX, + 60, + -0.1, + 1.1); + if (options.find("h") != std::string::npos) + correlationHists.SigmaXHitVsVar = directory->make( + "h2_sigma" + xY + "HitVs" + varName, + "#sigma_{hit," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{hit," + xy + "} [#mum]", + nBinX2D, + minBinX, + maxBinX, + 50, + 0 * 10000., + sigmaXHitMax * 10000.); + if (options.find("t") != std::string::npos) + correlationHists.SigmaXTrkVsVar = directory->make( + "h2_sigma" + xY + "TrkVs" + varName, + "#sigma_{trk," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{trk," + xy + "} [#mum]", + nBinX2D, + minBinX, + maxBinX, + 50, + 0 * 10000., + sigmaXMax * 10000.); + if (options.find("r") != std::string::npos) + correlationHists.SigmaXVsVar = directory->make( + "h2_sigma" + xY + "Vs" + varName, + "#sigma_{r," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{r," + xy + "} [#mum]", + nBinX2D, + minBinX, + maxBinX, + 50, + 0 * 10000., + sigmaXMax * 10000.); + + if (options.find("n") != std::string::npos) + correlationHists.PNorResXVsVar = + directory->make("p_norRes" + xY + "Vs" + varName, + "r_{" + xy + "}/#sigma_{r," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + + ";(" + xy + "_{trk}-" + xy + "_{hit})/#sigma_{r," + xy + "}", + nBinX2D, + minBinX, + maxBinX, + "s"); + if (options.find("p") != std::string::npos) + correlationHists.PProbXVsVar = directory->make( + "p_prob" + xY + "Vs" + varName, + "prob_{" + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";prob_{" + xy + "}", + nBinX2D, + minBinX, + maxBinX, + "s"); + if (options.find("h") != std::string::npos) + correlationHists.PSigmaXHitVsVar = directory->make( + "p_sigma" + xY + "HitVs" + varName, + "#sigma_{hit," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{hit," + xy + "} [#mum]", + nBinX2D, + minBinX, + maxBinX); + if (options.find("t") != std::string::npos) + correlationHists.PSigmaXTrkVsVar = directory->make( + "p_sigma" + xY + "TrkVs" + varName, + "#sigma_{trk," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{trk," + xy + "} [#mum]", + nBinX2D, + minBinX, + maxBinX); + if (options.find("r") != std::string::npos) + correlationHists.PSigmaXVsVar = directory->make( + "p_sigma" + xY + "Vs" + varName, + "#sigma_{r," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{r," + xy + "} [#mum]", + nBinX2D, + minBinX, + maxBinX); + return correlationHists; +} -TrackerSectorStruct::CorrelationHists -TrackerSectorStruct::bookCorrHistsX(TString varName,TString labelX,TString unitX,int nBinX,double minBinX,double maxBinX,std::string options){ +TrackerSectorStruct::CorrelationHists TrackerSectorStruct::bookCorrHistsX( + TString varName, TString labelX, TString unitX, int nBinX, double minBinX, double maxBinX, std::string options) { return bookCorrHists("X", varName, labelX, unitX, nBinX, minBinX, maxBinX, options); } -TrackerSectorStruct::CorrelationHists -TrackerSectorStruct::bookCorrHistsY(TString varName,TString labelX,TString unitX,int nBinX,double minBinX,double maxBinX,std::string options){ +TrackerSectorStruct::CorrelationHists TrackerSectorStruct::bookCorrHistsY( + TString varName, TString labelX, TString unitX, int nBinX, double minBinX, double maxBinX, std::string options) { return bookCorrHists("Y", varName, labelX, unitX, nBinX, minBinX, maxBinX, options); } -TrackerSectorStruct::CorrelationHists -TrackerSectorStruct::bookCorrHists(TString xY,TString varName,TString labelX,TString unitX,int nBinX,double minBinX,double maxBinX,std::string options){ +TrackerSectorStruct::CorrelationHists TrackerSectorStruct::bookCorrHists(TString xY, + TString varName, + TString labelX, + TString unitX, + int nBinX, + double minBinX, + double maxBinX, + std::string options) { TString xy; - if(xY=="X"){ + if (xY == "X") { xy = "x"; } - if(xY=="Y"){ + if (xY == "Y") { xy = "y"; } - - const std::string& o(options); + + const std::string &o(options); CorrelationHists correlationHists; - - if(!(o.find("n") != std::string::npos || o.find("p") != std::string::npos || o.find("h") != std::string::npos || - o.find("t") != std::string::npos || o.find("r") != std::string::npos))return correlationHists; - + + if (!(o.find("n") != std::string::npos || o.find("p") != std::string::npos || o.find("h") != std::string::npos || + o.find("t") != std::string::npos || o.find("r") != std::string::npos)) + return correlationHists; + TFileDirectory *directory(directory_); double norResXMax(norResXMax_), sigmaXHitMax(sigmaXHitMax_), sigmaXMax(sigmaXMax_); - - if(!directory)return correlationHists; - - - if(options.find("n") != std::string::npos) - correlationHists.NorResXVsVar = directory->make("h2_norRes"+xY+"Vs"+varName,"r_{"+xy+"}/#sigma_{r,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";("+xy+"_{trk}-"+xy+"_{hit})/#sigma_{r,"+xy+"}",nBinX,minBinX,maxBinX,25,-norResXMax,norResXMax); - if(options.find("p") != std::string::npos) - correlationHists.ProbXVsVar = directory->make("h2_prob"+xY+"Vs"+varName,"prob_{"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";prob_{"+xy+"}",nBinX,minBinX,maxBinX,60,-0.1,1.1); - if(options.find("h") != std::string::npos) - correlationHists.SigmaXHitVsVar = directory->make("h2_sigma"+xY+"HitVs"+varName,"#sigma_{hit,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{hit,"+xy+"} [#mum]",nBinX,minBinX,maxBinX,50,0*10000.,sigmaXHitMax*10000.); - if(options.find("t") != std::string::npos) - correlationHists.SigmaXTrkVsVar = directory->make("h2_sigma"+xY+"TrkVs"+varName,"#sigma_{trk,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{trk,"+xy+"} [#mum]",nBinX,minBinX,maxBinX,50,0*10000.,sigmaXMax*10000.); - if(options.find("r") != std::string::npos) - correlationHists.SigmaXVsVar = directory->make("h2_sigma"+xY+"Vs"+varName,"#sigma_{r,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{r,"+xy+"} [#mum]",nBinX,minBinX,maxBinX,50,0*10000.,sigmaXMax*10000.); - - if(options.find("n") != std::string::npos) - correlationHists.PNorResXVsVar = directory->make("p_norRes"+xY+"Vs"+varName,"r_{"+xy+"}/#sigma_{r,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";("+xy+"_{trk}-"+xy+"_{hit})/#sigma_{r,"+xy+"}",nBinX,minBinX,maxBinX,"s"); - if(options.find("p") != std::string::npos) - correlationHists.PProbXVsVar = directory->make("p_prob"+xY+"Vs"+varName,"prob_{"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";prob_{"+xy+"}",nBinX,minBinX,maxBinX,"s"); - if(options.find("h") != std::string::npos) - correlationHists.PSigmaXHitVsVar = directory->make("p_sigma"+xY+"HitVs"+varName,"#sigma_{hit,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{hit,"+xy+"} [#mum]",nBinX,minBinX,maxBinX); - if(options.find("t") != std::string::npos) - correlationHists.PSigmaXTrkVsVar = directory->make("p_sigma"+xY+"TrkVs"+varName,"#sigma_{trk,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{trk,"+xy+"} [#mum]",nBinX,minBinX,maxBinX); - if(options.find("r") != std::string::npos) - correlationHists.PSigmaXVsVar = directory->make("p_sigma"+xY+"Vs"+varName,"#sigma_{r,"+xy+"} vs. "+labelX+";"+labelX+" "+unitX+";#sigma_{r,"+xy+"} [#mum]",nBinX,minBinX,maxBinX); - - return correlationHists; -} - + if (!directory) + return correlationHists; + + if (options.find("n") != std::string::npos) + correlationHists.NorResXVsVar = + directory->make("h2_norRes" + xY + "Vs" + varName, + "r_{" + xy + "}/#sigma_{r," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + + ";(" + xy + "_{trk}-" + xy + "_{hit})/#sigma_{r," + xy + "}", + nBinX, + minBinX, + maxBinX, + 25, + -norResXMax, + norResXMax); + if (options.find("p") != std::string::npos) + correlationHists.ProbXVsVar = + directory->make("h2_prob" + xY + "Vs" + varName, + "prob_{" + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";prob_{" + xy + "}", + nBinX, + minBinX, + maxBinX, + 60, + -0.1, + 1.1); + if (options.find("h") != std::string::npos) + correlationHists.SigmaXHitVsVar = directory->make( + "h2_sigma" + xY + "HitVs" + varName, + "#sigma_{hit," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{hit," + xy + "} [#mum]", + nBinX, + minBinX, + maxBinX, + 50, + 0 * 10000., + sigmaXHitMax * 10000.); + if (options.find("t") != std::string::npos) + correlationHists.SigmaXTrkVsVar = directory->make( + "h2_sigma" + xY + "TrkVs" + varName, + "#sigma_{trk," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{trk," + xy + "} [#mum]", + nBinX, + minBinX, + maxBinX, + 50, + 0 * 10000., + sigmaXMax * 10000.); + if (options.find("r") != std::string::npos) + correlationHists.SigmaXVsVar = directory->make( + "h2_sigma" + xY + "Vs" + varName, + "#sigma_{r," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{r," + xy + "} [#mum]", + nBinX, + minBinX, + maxBinX, + 50, + 0 * 10000., + sigmaXMax * 10000.); + + if (options.find("n") != std::string::npos) + correlationHists.PNorResXVsVar = + directory->make("p_norRes" + xY + "Vs" + varName, + "r_{" + xy + "}/#sigma_{r," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + + ";(" + xy + "_{trk}-" + xy + "_{hit})/#sigma_{r," + xy + "}", + nBinX, + minBinX, + maxBinX, + "s"); + if (options.find("p") != std::string::npos) + correlationHists.PProbXVsVar = directory->make( + "p_prob" + xY + "Vs" + varName, + "prob_{" + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";prob_{" + xy + "}", + nBinX, + minBinX, + maxBinX, + "s"); + if (options.find("h") != std::string::npos) + correlationHists.PSigmaXHitVsVar = directory->make( + "p_sigma" + xY + "HitVs" + varName, + "#sigma_{hit," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{hit," + xy + "} [#mum]", + nBinX, + minBinX, + maxBinX); + if (options.find("t") != std::string::npos) + correlationHists.PSigmaXTrkVsVar = directory->make( + "p_sigma" + xY + "TrkVs" + varName, + "#sigma_{trk," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{trk," + xy + "} [#mum]", + nBinX, + minBinX, + maxBinX); + if (options.find("r") != std::string::npos) + correlationHists.PSigmaXVsVar = directory->make( + "p_sigma" + xY + "Vs" + varName, + "#sigma_{r," + xy + "} vs. " + labelX + ";" + labelX + " " + unitX + ";#sigma_{r," + xy + "} [#mum]", + nBinX, + minBinX, + maxBinX); + return correlationHists; +} -void -TrackerSectorStruct::CorrelationHists::fillCorrHistsX(const TrackStruct::HitParameterStruct& hitParameterStruct, double variable){ +void TrackerSectorStruct::CorrelationHists::fillCorrHistsX(const TrackStruct::HitParameterStruct &hitParameterStruct, + double variable) { return fillCorrHists("X", hitParameterStruct, variable); } -void -TrackerSectorStruct::CorrelationHists::fillCorrHistsY(const TrackStruct::HitParameterStruct& hitParameterStruct, double variable){ +void TrackerSectorStruct::CorrelationHists::fillCorrHistsY(const TrackStruct::HitParameterStruct &hitParameterStruct, + double variable) { return fillCorrHists("Y", hitParameterStruct, variable); } -void -TrackerSectorStruct::CorrelationHists::fillCorrHists(const TString xY, const TrackStruct::HitParameterStruct& hitParameterStruct, double variable){ +void TrackerSectorStruct::CorrelationHists::fillCorrHists(const TString xY, + const TrackStruct::HitParameterStruct &hitParameterStruct, + double variable) { float norRes(999.); float prob(999.); float errHit(999.); float errTrk(999.); float err(999.); - if(xY=="X"){ + if (xY == "X") { norRes = hitParameterStruct.norResX; prob = hitParameterStruct.probX; errHit = hitParameterStruct.errXHit; errTrk = hitParameterStruct.errXTrk; err = hitParameterStruct.errX; } - if(xY=="Y"){ + if (xY == "Y") { norRes = hitParameterStruct.norResY; prob = hitParameterStruct.probY; errHit = hitParameterStruct.errYHit; errTrk = hitParameterStruct.errYTrk; err = hitParameterStruct.errY; } - - if(Variable){Variable->Fill(variable);} - - if(NorResXVsVar){ - NorResXVsVar->Fill(variable,norRes); - PNorResXVsVar->Fill(variable,norRes); + + if (Variable) { + Variable->Fill(variable); + } + + if (NorResXVsVar) { + NorResXVsVar->Fill(variable, norRes); + PNorResXVsVar->Fill(variable, norRes); } - if(ProbXVsVar){ - ProbXVsVar->Fill(variable,prob); - PProbXVsVar->Fill(variable,prob); + if (ProbXVsVar) { + ProbXVsVar->Fill(variable, prob); + PProbXVsVar->Fill(variable, prob); } - if(SigmaXHitVsVar){ - SigmaXHitVsVar->Fill(variable,errHit*10000.); - PSigmaXHitVsVar->Fill(variable,errHit*10000.); + if (SigmaXHitVsVar) { + SigmaXHitVsVar->Fill(variable, errHit * 10000.); + PSigmaXHitVsVar->Fill(variable, errHit * 10000.); } - if(SigmaXTrkVsVar){ - SigmaXTrkVsVar->Fill(variable,errTrk*10000.); - PSigmaXTrkVsVar->Fill(variable,errTrk*10000.); + if (SigmaXTrkVsVar) { + SigmaXTrkVsVar->Fill(variable, errTrk * 10000.); + PSigmaXTrkVsVar->Fill(variable, errTrk * 10000.); } - if(SigmaXVsVar){ - SigmaXVsVar->Fill(variable,err*10000.); - PSigmaXVsVar->Fill(variable,err*10000.); + if (SigmaXVsVar) { + SigmaXVsVar->Fill(variable, err * 10000.); + PSigmaXVsVar->Fill(variable, err * 10000.); } - } - - - - #endif diff --git a/Alignment/APEEstimation/plugins/ApeEstimator.cc b/Alignment/APEEstimation/plugins/ApeEstimator.cc index 732b1063922e0..a11e67355186f 100644 --- a/Alignment/APEEstimation/plugins/ApeEstimator.cc +++ b/Alignment/APEEstimation/plugins/ApeEstimator.cc @@ -2,7 +2,7 @@ // // Package: ApeEstimator // Class: ApeEstimator -// +// /**\class ApeEstimator ApeEstimator.cc Alignment/APEEstimation/src/ApeEstimator.cc Description: @@ -18,7 +18,6 @@ // // - // system include files #include #include @@ -92,7 +91,6 @@ #include "Alignment/APEEstimation/interface/EventVariables.h" #include "Alignment/APEEstimation/interface/ReducedTrackerTreeVariables.h" - #include "TH1.h" #include "TH2.h" #include "TProfile.h" @@ -102,7 +100,6 @@ #include "TString.h" #include "TMath.h" - #include "RecoLocalTracker/SiStripRecHitConverter/interface/StripCPE.h" #include "Geometry/CommonTopologies/interface/StripTopology.h" @@ -127,89 +124,86 @@ // class ApeEstimator : public edm::one::EDAnalyzer<> { - public: - explicit ApeEstimator(const edm::ParameterSet&); - ~ApeEstimator() override; - - - private: - struct PositionAndError2{ - PositionAndError2(): posX(-999.F), posY(-999.F), errX2(-999.F), errY2(-999.F) {}; - PositionAndError2(float x, float y, float eX, float eY): posX(x), posY(y), errX2(eX), errY2(eY) {}; - float posX; - float posY; - float errX2; - float errY2; - }; - typedef std::pair StatePositionAndError2; - - void beginJob() override ; - void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override; - - bool isHit2D(const TrackingRecHit&)const; - - void sectorBuilder(); - bool checkIntervalsForSectors(const unsigned int sectorCounter, const std::vector&)const; - bool checkModuleIds(const unsigned int, const std::vector&)const; - bool checkModuleBools(const bool, const std::vector&)const; - bool checkModuleDirections(const int, const std::vector&)const; - bool checkModulePositions(const float, const std::vector&)const; - void statistics(const TrackerSectorStruct&, const int)const; - - void residualErrorBinning(); - - void bookSectorHistsForAnalyzerMode(); - void bookSectorHistsForApeCalculation(); - void bookTrackHists(); - - TrackStruct::TrackParameterStruct fillTrackVariables(const reco::Track&, const Trajectory&, const reco::BeamSpot&); - TrackStruct::HitParameterStruct fillHitVariables(const TrajectoryMeasurement&, const edm::EventSetup&); - - StatePositionAndError2 positionAndError2(const LocalPoint&, const LocalError&, const TransientTrackingRecHit&); - PositionAndError2 rectangularPositionAndError2(const LocalPoint&, const LocalError&); - PositionAndError2 radialPositionAndError2(const LocalPoint&, const LocalError&, const RadialStripTopology&); - - void hitSelection(); - void setHitSelectionMap(const std::string&); - void setHitSelectionMapUInt(const std::string&); - bool hitSelected(TrackStruct::HitParameterStruct&)const; - bool inDoubleInterval(const std::vector&, const float)const; - bool inUintInterval(const std::vector&, const unsigned int, const unsigned int =999)const; - - void fillHistsForAnalyzerMode(const TrackStruct&); - void fillHitHistsXForAnalyzerMode(const TrackStruct::HitParameterStruct&, TrackerSectorStruct&); - void fillHitHistsYForAnalyzerMode(const TrackStruct::HitParameterStruct&, TrackerSectorStruct&); - void fillHistsForApeCalculation(const TrackStruct&); - - void calculateAPE(); - - // ----------member data --------------------------- - const edm::ParameterSet parameterSet_; - std::map m_tkSector_; - TrackerDetectorStruct tkDetector_; - - edm::EDGetTokenT tjTagToken_; - edm::EDGetTokenT offlinebeamSpot_; - - - std::map > m_resErrBins_; - std::map m_tkTreeVar_; - - std::map > m_hitSelection_; - std::map > m_hitSelectionUInt_; - - bool trackCut_; - - const unsigned int maxTracksPerEvent_; - const unsigned int minGoodHitsPerTrack_; - - const bool analyzerMode_; - - const bool calculateApe_; - - unsigned int counter1, counter2, counter3, counter4, counter5, counter6; - +public: + explicit ApeEstimator(const edm::ParameterSet&); + ~ApeEstimator() override; + +private: + struct PositionAndError2 { + PositionAndError2() : posX(-999.F), posY(-999.F), errX2(-999.F), errY2(-999.F){}; + PositionAndError2(float x, float y, float eX, float eY) : posX(x), posY(y), errX2(eX), errY2(eY){}; + float posX; + float posY; + float errX2; + float errY2; + }; + typedef std::pair StatePositionAndError2; + + void beginJob() override; + void analyze(const edm::Event&, const edm::EventSetup&) override; + void endJob() override; + + bool isHit2D(const TrackingRecHit&) const; + + void sectorBuilder(); + bool checkIntervalsForSectors(const unsigned int sectorCounter, const std::vector&) const; + bool checkModuleIds(const unsigned int, const std::vector&) const; + bool checkModuleBools(const bool, const std::vector&) const; + bool checkModuleDirections(const int, const std::vector&) const; + bool checkModulePositions(const float, const std::vector&) const; + void statistics(const TrackerSectorStruct&, const int) const; + + void residualErrorBinning(); + + void bookSectorHistsForAnalyzerMode(); + void bookSectorHistsForApeCalculation(); + void bookTrackHists(); + + TrackStruct::TrackParameterStruct fillTrackVariables(const reco::Track&, const Trajectory&, const reco::BeamSpot&); + TrackStruct::HitParameterStruct fillHitVariables(const TrajectoryMeasurement&, const edm::EventSetup&); + + StatePositionAndError2 positionAndError2(const LocalPoint&, const LocalError&, const TransientTrackingRecHit&); + PositionAndError2 rectangularPositionAndError2(const LocalPoint&, const LocalError&); + PositionAndError2 radialPositionAndError2(const LocalPoint&, const LocalError&, const RadialStripTopology&); + + void hitSelection(); + void setHitSelectionMap(const std::string&); + void setHitSelectionMapUInt(const std::string&); + bool hitSelected(TrackStruct::HitParameterStruct&) const; + bool inDoubleInterval(const std::vector&, const float) const; + bool inUintInterval(const std::vector&, const unsigned int, const unsigned int = 999) const; + + void fillHistsForAnalyzerMode(const TrackStruct&); + void fillHitHistsXForAnalyzerMode(const TrackStruct::HitParameterStruct&, TrackerSectorStruct&); + void fillHitHistsYForAnalyzerMode(const TrackStruct::HitParameterStruct&, TrackerSectorStruct&); + void fillHistsForApeCalculation(const TrackStruct&); + + void calculateAPE(); + + // ----------member data --------------------------- + const edm::ParameterSet parameterSet_; + std::map m_tkSector_; + TrackerDetectorStruct tkDetector_; + + edm::EDGetTokenT tjTagToken_; + edm::EDGetTokenT offlinebeamSpot_; + + std::map > m_resErrBins_; + std::map m_tkTreeVar_; + + std::map > m_hitSelection_; + std::map > m_hitSelectionUInt_; + + bool trackCut_; + + const unsigned int maxTracksPerEvent_; + const unsigned int minGoodHitsPerTrack_; + + const bool analyzerMode_; + + const bool calculateApe_; + + unsigned int counter1, counter2, counter3, counter4, counter5, counter6; }; // @@ -223,23 +217,20 @@ class ApeEstimator : public edm::one::EDAnalyzer<> { // // constructors and destructor // -ApeEstimator::ApeEstimator(const edm::ParameterSet& iConfig): - parameterSet_(iConfig), - tjTagToken_(consumes(parameterSet_.getParameter("tjTkAssociationMapTag"))), - offlinebeamSpot_(consumes(edm::InputTag("offlineBeamSpot"))), - trackCut_(false), maxTracksPerEvent_(parameterSet_.getParameter("maxTracksPerEvent")), - minGoodHitsPerTrack_(parameterSet_.getParameter("minGoodHitsPerTrack")), - analyzerMode_(parameterSet_.getParameter("analyzerMode")), - calculateApe_(parameterSet_.getParameter("calculateApe")) -{ - counter1 = counter2 = counter3 = counter4 = counter5 = counter6 = 0; -} - - -ApeEstimator::~ApeEstimator() -{ +ApeEstimator::ApeEstimator(const edm::ParameterSet& iConfig) + : parameterSet_(iConfig), + tjTagToken_( + consumes(parameterSet_.getParameter("tjTkAssociationMapTag"))), + offlinebeamSpot_(consumes(edm::InputTag("offlineBeamSpot"))), + trackCut_(false), + maxTracksPerEvent_(parameterSet_.getParameter("maxTracksPerEvent")), + minGoodHitsPerTrack_(parameterSet_.getParameter("minGoodHitsPerTrack")), + analyzerMode_(parameterSet_.getParameter("analyzerMode")), + calculateApe_(parameterSet_.getParameter("calculateApe")) { + counter1 = counter2 = counter3 = counter4 = counter5 = counter6 = 0; } +ApeEstimator::~ApeEstimator() {} // // member functions @@ -247,30 +238,28 @@ ApeEstimator::~ApeEstimator() // ----------------------------------------------------------------------------------------------------------- -void -ApeEstimator::sectorBuilder(){ - +void ApeEstimator::sectorBuilder() { TFile* tkTreeFile(TFile::Open((parameterSet_.getParameter("TrackerTreeFile")).c_str())); - if(tkTreeFile){ - edm::LogInfo("SectorBuilder")<<"TrackerTreeFile OK"; - }else{ - edm::LogError("SectorBuilder")<<"TrackerTreeFile not found"; - return; + if (tkTreeFile) { + edm::LogInfo("SectorBuilder") << "TrackerTreeFile OK"; + } else { + edm::LogError("SectorBuilder") << "TrackerTreeFile not found"; + return; } TTree* tkTree(nullptr); - tkTreeFile->GetObject("TrackerTreeGenerator/TrackerTree/TrackerTree",tkTree); - if(tkTree){ - edm::LogInfo("SectorBuilder")<<"TrackerTree OK"; - }else{ - edm::LogError("SectorBuilder")<<"TrackerTree not found in file"; - return; + tkTreeFile->GetObject("TrackerTreeGenerator/TrackerTree/TrackerTree", tkTree); + if (tkTree) { + edm::LogInfo("SectorBuilder") << "TrackerTree OK"; + } else { + edm::LogError("SectorBuilder") << "TrackerTree not found in file"; + return; } - unsigned int rawId(999), subdetId(999), layer(999), side(999), half(999), rod(999), ring(999), petal(999), - blade(999), panel(999), outerInner(999), module(999), nStrips(999); + unsigned int rawId(999), subdetId(999), layer(999), side(999), half(999), rod(999), ring(999), petal(999), blade(999), + panel(999), outerInner(999), module(999), nStrips(999); bool isDoubleSide(false), isRPhi(false), isStereo(false); int uDirection(999), vDirection(999), wDirection(999); - float posR(999.F), posPhi(999.F), posEta(999.F), posX(999.F), posY(999.F), posZ(999.F); - + float posR(999.F), posPhi(999.F), posEta(999.F), posX(999.F), posY(999.F), posZ(999.F); + tkTree->SetBranchAddress("RawId", &rawId); tkTree->SetBranchAddress("SubdetId", &subdetId); tkTree->SetBranchAddress("Layer", &layer); @@ -296,265 +285,296 @@ ApeEstimator::sectorBuilder(){ tkTree->SetBranchAddress("PosX", &posX); tkTree->SetBranchAddress("PosY", &posY); tkTree->SetBranchAddress("PosZ", &posZ); - + int nModules(tkTree->GetEntries()); TrackerSectorStruct allSectors; - + //Loop over all Sectors unsigned int sectorCounter(0); std::vector v_sectorDef(parameterSet_.getParameter >("Sectors")); - edm::LogInfo("SectorBuilder")<<"There are "<("name")); - std::vector v_rawId(parSet.getParameter >("rawId")), - v_subdetId(parSet.getParameter >("subdetId")), - v_layer(parSet.getParameter >("layer")), - v_side(parSet.getParameter >("side")), - v_half(parSet.getParameter >("half")), - v_rod(parSet.getParameter >("rod")), - v_ring(parSet.getParameter >("ring")), - v_petal(parSet.getParameter >("petal")), - v_blade(parSet.getParameter >("blade")), - v_panel(parSet.getParameter >("panel")), - v_outerInner(parSet.getParameter >("outerInner")), - v_module(parSet.getParameter >("module")), - v_nStrips(parSet.getParameter >("nStrips")), - v_isDoubleSide(parSet.getParameter >("isDoubleSide")), - v_isRPhi(parSet.getParameter >("isRPhi")), - v_isStereo(parSet.getParameter >("isStereo")); - std::vector v_uDirection(parSet.getParameter >("uDirection")), - v_vDirection(parSet.getParameter >("vDirection")), - v_wDirection(parSet.getParameter >("wDirection")); - std::vector v_posR(parSet.getParameter >("posR")), - v_posPhi(parSet.getParameter >("posPhi")), - v_posEta(parSet.getParameter >("posEta")), - v_posX(parSet.getParameter >("posX")), - v_posY(parSet.getParameter >("posY")), - v_posZ(parSet.getParameter >("posZ")); - - if(!this->checkIntervalsForSectors(sectorCounter,v_posR) || !this->checkIntervalsForSectors(sectorCounter,v_posPhi) || - !this->checkIntervalsForSectors(sectorCounter,v_posEta) || !this->checkIntervalsForSectors(sectorCounter,v_posX) || - !this->checkIntervalsForSectors(sectorCounter,v_posY) || !this->checkIntervalsForSectors(sectorCounter,v_posZ))continue; - - - TrackerSectorStruct tkSector; - tkSector.name = sectorName; - - ReducedTrackerTreeVariables tkTreeVar; - - //Loop over all Modules - for(int module = 0; module < nModules; ++module){ - tkTree->GetEntry(module); - - if(sectorCounter==1){ - tkTreeVar.subdetId = subdetId; - tkTreeVar.nStrips = nStrips; - tkTreeVar.uDirection = uDirection; - tkTreeVar.vDirection = vDirection; - tkTreeVar.wDirection = wDirection; - m_tkTreeVar_[rawId] = tkTreeVar; - } - - if(!this->checkModuleIds(rawId,v_rawId))continue; - if(!this->checkModuleIds(subdetId,v_subdetId))continue; - if(!this->checkModuleIds(layer,v_layer))continue; - if(!this->checkModuleIds(side,v_side))continue; - if(!this->checkModuleIds(half,v_half))continue; - if(!this->checkModuleIds(rod,v_rod))continue; - if(!this->checkModuleIds(ring,v_ring))continue; - if(!this->checkModuleIds(petal,v_petal))continue; - if(!this->checkModuleIds(blade,v_blade))continue; - if(!this->checkModuleIds(panel,v_panel))continue; - if(!this->checkModuleIds(outerInner,v_outerInner))continue; - if(!this->checkModuleIds(module,v_module))continue; - if(!this->checkModuleIds(nStrips,v_nStrips))continue; - if(!this->checkModuleBools(isDoubleSide,v_isDoubleSide))continue; - if(!this->checkModuleBools(isRPhi,v_isRPhi))continue; - if(!this->checkModuleBools(isStereo,v_isStereo))continue; - if(!this->checkModuleDirections(uDirection,v_uDirection))continue; - if(!this->checkModuleDirections(vDirection,v_vDirection))continue; - if(!this->checkModuleDirections(wDirection,v_wDirection))continue; - if(!this->checkModulePositions(posR,v_posR))continue; - if(!this->checkModulePositions(posPhi,v_posPhi))continue; - if(!this->checkModulePositions(posEta,v_posEta))continue; - if(!this->checkModulePositions(posX,v_posX))continue; - if(!this->checkModulePositions(posY,v_posY))continue; - if(!this->checkModulePositions(posZ,v_posZ))continue; - - tkSector.v_rawId.push_back(rawId); - bool moduleSelected(false); - for(auto const & i_rawId : allSectors.v_rawId){ - if(rawId == i_rawId)moduleSelected = true; - } - if(!moduleSelected)allSectors.v_rawId.push_back(rawId); - } - - bool isPixel(false); - bool isStrip(false); - for(auto const & i_rawId : tkSector.v_rawId){ - switch (m_tkTreeVar_[i_rawId].subdetId) { - case PixelSubdetector::PixelBarrel: - case PixelSubdetector::PixelEndcap: - isPixel = true; - break; - case StripSubdetector::TIB: - case StripSubdetector::TOB: - case StripSubdetector::TID: - case StripSubdetector::TEC: - isStrip = true; - break; - } + edm::LogInfo("SectorBuilder") << "There are " << v_sectorDef.size() << " Sectors definded"; + for (auto const& parSet : v_sectorDef) { + ++sectorCounter; + const std::string& sectorName(parSet.getParameter("name")); + std::vector v_rawId(parSet.getParameter >("rawId")), + v_subdetId(parSet.getParameter >("subdetId")), + v_layer(parSet.getParameter >("layer")), + v_side(parSet.getParameter >("side")), + v_half(parSet.getParameter >("half")), + v_rod(parSet.getParameter >("rod")), + v_ring(parSet.getParameter >("ring")), + v_petal(parSet.getParameter >("petal")), + v_blade(parSet.getParameter >("blade")), + v_panel(parSet.getParameter >("panel")), + v_outerInner(parSet.getParameter >("outerInner")), + v_module(parSet.getParameter >("module")), + v_nStrips(parSet.getParameter >("nStrips")), + v_isDoubleSide(parSet.getParameter >("isDoubleSide")), + v_isRPhi(parSet.getParameter >("isRPhi")), + v_isStereo(parSet.getParameter >("isStereo")); + std::vector v_uDirection(parSet.getParameter >("uDirection")), + v_vDirection(parSet.getParameter >("vDirection")), + v_wDirection(parSet.getParameter >("wDirection")); + std::vector v_posR(parSet.getParameter >("posR")), + v_posPhi(parSet.getParameter >("posPhi")), + v_posEta(parSet.getParameter >("posEta")), + v_posX(parSet.getParameter >("posX")), + v_posY(parSet.getParameter >("posY")), + v_posZ(parSet.getParameter >("posZ")); + + if (!this->checkIntervalsForSectors(sectorCounter, v_posR) || + !this->checkIntervalsForSectors(sectorCounter, v_posPhi) || + !this->checkIntervalsForSectors(sectorCounter, v_posEta) || + !this->checkIntervalsForSectors(sectorCounter, v_posX) || + !this->checkIntervalsForSectors(sectorCounter, v_posY) || + !this->checkIntervalsForSectors(sectorCounter, v_posZ)) + continue; + + TrackerSectorStruct tkSector; + tkSector.name = sectorName; + + ReducedTrackerTreeVariables tkTreeVar; + + //Loop over all Modules + for (int module = 0; module < nModules; ++module) { + tkTree->GetEntry(module); + + if (sectorCounter == 1) { + tkTreeVar.subdetId = subdetId; + tkTreeVar.nStrips = nStrips; + tkTreeVar.uDirection = uDirection; + tkTreeVar.vDirection = vDirection; + tkTreeVar.wDirection = wDirection; + m_tkTreeVar_[rawId] = tkTreeVar; } - if(isPixel && isStrip){ - edm::LogError("SectorBuilder")<<"Incorrect Sector Definition: there are pixel and strip modules within one sector" - <<"\n... sector selection is not applied, sector "<checkModuleIds(rawId, v_rawId)) + continue; + if (!this->checkModuleIds(subdetId, v_subdetId)) + continue; + if (!this->checkModuleIds(layer, v_layer)) continue; + if (!this->checkModuleIds(side, v_side)) + continue; + if (!this->checkModuleIds(half, v_half)) + continue; + if (!this->checkModuleIds(rod, v_rod)) + continue; + if (!this->checkModuleIds(ring, v_ring)) + continue; + if (!this->checkModuleIds(petal, v_petal)) + continue; + if (!this->checkModuleIds(blade, v_blade)) + continue; + if (!this->checkModuleIds(panel, v_panel)) + continue; + if (!this->checkModuleIds(outerInner, v_outerInner)) + continue; + if (!this->checkModuleIds(module, v_module)) + continue; + if (!this->checkModuleIds(nStrips, v_nStrips)) + continue; + if (!this->checkModuleBools(isDoubleSide, v_isDoubleSide)) + continue; + if (!this->checkModuleBools(isRPhi, v_isRPhi)) + continue; + if (!this->checkModuleBools(isStereo, v_isStereo)) + continue; + if (!this->checkModuleDirections(uDirection, v_uDirection)) + continue; + if (!this->checkModuleDirections(vDirection, v_vDirection)) + continue; + if (!this->checkModuleDirections(wDirection, v_wDirection)) + continue; + if (!this->checkModulePositions(posR, v_posR)) + continue; + if (!this->checkModulePositions(posPhi, v_posPhi)) + continue; + if (!this->checkModulePositions(posEta, v_posEta)) + continue; + if (!this->checkModulePositions(posX, v_posX)) + continue; + if (!this->checkModulePositions(posY, v_posY)) + continue; + if (!this->checkModulePositions(posZ, v_posZ)) + continue; + + tkSector.v_rawId.push_back(rawId); + bool moduleSelected(false); + for (auto const& i_rawId : allSectors.v_rawId) { + if (rawId == i_rawId) + moduleSelected = true; } - tkSector.isPixel = isPixel; - - m_tkSector_[sectorCounter] = tkSector; - edm::LogInfo("SectorBuilder")<<"There are "<statistics(allSectors, nModules); return; } - - // ----------------------------------------------------------------------------------------------------------- - -bool -ApeEstimator::checkIntervalsForSectors(const unsigned int sectorCounter, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - if(v_id.size()%2==1){ - edm::LogError("SectorBuilder")<<"Incorrect Sector Definition: Position Vectors need even number of arguments (Intervals)" - <<"\n... sector selection is not applied, sector "<& v_id) const { + if (v_id.empty()) + return true; + if (v_id.size() % 2 == 1) { + edm::LogError("SectorBuilder") + << "Incorrect Sector Definition: Position Vectors need even number of arguments (Intervals)" + << "\n... sector selection is not applied, sector " << sectorCounter << " is not built"; return false; } - int entry(0); double intervalBegin(999.); - for(auto const & i_id : v_id){ + int entry(0); + double intervalBegin(999.); + for (auto const& i_id : v_id) { ++entry; - if(entry%2==1) intervalBegin = i_id; - if(entry%2==0 && intervalBegin > i_id){ - edm::LogError("SectorBuilder")<<"Incorrect Sector Definition (Position Vector Intervals): \t" - < i_id) { + edm::LogError("SectorBuilder") << "Incorrect Sector Definition (Position Vector Intervals): \t" << intervalBegin + << " is bigger than " << i_id << " but is expected to be smaller" + << "\n... sector selection is not applied, sector " << sectorCounter + << " is not built"; return false; } } return true; } -bool -ApeEstimator::checkModuleIds(const unsigned int id, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - for(auto const & i_id : v_id){ - if(id==i_id)return true; +bool ApeEstimator::checkModuleIds(const unsigned int id, const std::vector& v_id) const { + if (v_id.empty()) + return true; + for (auto const& i_id : v_id) { + if (id == i_id) + return true; } return false; } -bool -ApeEstimator::checkModuleBools(const bool id, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - for(auto const & i_id : v_id){ - if(1==i_id && id)return true; - if(2==i_id && !id)return true; +bool ApeEstimator::checkModuleBools(const bool id, const std::vector& v_id) const { + if (v_id.empty()) + return true; + for (auto const& i_id : v_id) { + if (1 == i_id && id) + return true; + if (2 == i_id && !id) + return true; } return false; } -bool -ApeEstimator::checkModuleDirections(const int id, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - for(auto const & i_id : v_id){ - if(id==i_id)return true; +bool ApeEstimator::checkModuleDirections(const int id, const std::vector& v_id) const { + if (v_id.empty()) + return true; + for (auto const& i_id : v_id) { + if (id == i_id) + return true; } return false; } -bool -ApeEstimator::checkModulePositions(const float id, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - int entry(0); double intervalBegin(999.); - for(auto const & i_id : v_id){ +bool ApeEstimator::checkModulePositions(const float id, const std::vector& v_id) const { + if (v_id.empty()) + return true; + int entry(0); + double intervalBegin(999.); + for (auto const& i_id : v_id) { ++entry; - if(entry%2==1)intervalBegin = i_id; - if(entry%2==0 && id>=intervalBegin && id= intervalBegin && id < i_id) + return true; } return false; } -void -ApeEstimator::statistics(const TrackerSectorStruct& allSectors, const int nModules)const{ +void ApeEstimator::statistics(const TrackerSectorStruct& allSectors, const int nModules) const { bool commonModules(false); - for(std::map::const_iterator i_sector = m_tkSector_.begin(); i_sector != m_tkSector_.end(); ++i_sector){ - std::map::const_iterator i_sector2(i_sector); - for(++i_sector2; i_sector2 != m_tkSector_.end(); ++i_sector2){ + for (std::map::const_iterator i_sector = m_tkSector_.begin(); + i_sector != m_tkSector_.end(); + ++i_sector) { + std::map::const_iterator i_sector2(i_sector); + for (++i_sector2; i_sector2 != m_tkSector_.end(); ++i_sector2) { unsigned int nCommonModules(0); - for(auto const & i_module : (*i_sector).second.v_rawId){ - for(auto const & i_module2 : (*i_sector2).second.v_rawId){ - if(i_module2 == i_module) ++nCommonModules; + for (auto const& i_module : (*i_sector).second.v_rawId) { + for (auto const& i_module2 : (*i_sector2).second.v_rawId) { + if (i_module2 == i_module) + ++nCommonModules; } } - if(nCommonModules==0) - ;//edm::LogInfo("SectorBuilder")<<"Sector "<<(*i_sector).first<<" and Sector "<<(*i_sector2).first<< " have ZERO Modules in common"; - else{ - edm::LogError("SectorBuilder")<<"Sector "<<(*i_sector).first<<" and Sector "<<(*i_sector2).first<< " have "<(allSectors.v_rawId.size())==nModules) - edm::LogInfo("SectorBuilder")<<"ALL Tracker Modules are contained in the Sectors"; + if (static_cast(allSectors.v_rawId.size()) == nModules) + edm::LogInfo("SectorBuilder") << "ALL Tracker Modules are contained in the Sectors"; else - edm::LogWarning("SectorBuilder")<<"There are "< v_residualErrorBinning(parameterSet_.getParameter >("residualErrorBinning")); - if(v_residualErrorBinning.size()==1){ - edm::LogError("ResidualErrorBinning")<<"Incorrect selection of Residual Error Bins (used for APE calculation): \t" - <<"Only one argument passed, so no interval is specified" - <<"\n... delete whole bin selection"; //m_resErrBins_ remains empty + if (v_residualErrorBinning.size() == 1) { + edm::LogError("ResidualErrorBinning") << "Incorrect selection of Residual Error Bins (used for APE calculation): \t" + << "Only one argument passed, so no interval is specified" + << "\n... delete whole bin selection"; //m_resErrBins_ remains empty return; } double xMin(0.), xMax(0.); unsigned int binCounter(-1); - for(auto const & i_binning : v_residualErrorBinning){ + for (auto const& i_binning : v_residualErrorBinning) { ++binCounter; - if(binCounter == 0){ - xMin = i_binning; - continue; + if (binCounter == 0) { + xMin = i_binning; + continue; } xMax = i_binning; - if(xMax<=xMin){ - edm::LogError("ResidualErrorBinning")<<"Incorrect selection of Residual Error Bins (used for APE calculation): \t" - < v_errHists(parameterSet_.getParameter >("vErrHists")); - for(std::vector::iterator i_errHists = v_errHists.begin(); i_errHists != v_errHists.end(); ++i_errHists){ - for(std::vector::iterator i_errHists2 = i_errHists; i_errHists2 != v_errHists.end();){ + for (std::vector::iterator i_errHists = v_errHists.begin(); i_errHists != v_errHists.end(); + ++i_errHists) { + for (std::vector::iterator i_errHists2 = i_errHists; i_errHists2 != v_errHists.end();) { ++i_errHists2; - if(*i_errHists==*i_errHists2){ - edm::LogError("BookSectorHists")<<"Value of vErrHists in config exists twice: "<<*i_errHists<<"\n... delete one of both"; + if (*i_errHists == *i_errHists2) { + edm::LogError("BookSectorHists") << "Value of vErrHists in config exists twice: " << *i_errHists + << "\n... delete one of both"; v_errHists.erase(i_errHists2); } } } - - - for(auto & i_sector : m_tkSector_){ + + for (auto& i_sector : m_tkSector_) { bool zoomHists(parameterSet_.getParameter("zoomHists")); - + double widthMax = zoomHists ? 20. : 200.; double chargePixelMax = zoomHists ? 200000. : 2000000.; double chargeStripMax = zoomHists ? 1000. : 10000.; double sOverNMax = zoomHists ? 200. : 2000.; double logClusterProbMin = zoomHists ? -5. : -15.; - + double resXAbsMax = zoomHists ? 0.5 : 5.; double norResXAbsMax = zoomHists ? 10. : 50.; - double probXMin = zoomHists ? -0.01 : -0.1; - double probXMax = zoomHists ? 0.11 : 1.1; + double probXMin = zoomHists ? -0.01 : -0.1; + double probXMax = zoomHists ? 0.11 : 1.1; double sigmaXMin = zoomHists ? 0. : -0.05; double sigmaXMax = zoomHists ? 0.02 : 1.; - double sigmaX2Max = sigmaXMax*sigmaXMax; + double sigmaX2Max = sigmaXMax * sigmaXMax; double sigmaXHitMax = zoomHists ? 0.02 : 1.; double phiSensXMax = zoomHists ? 31. : 93.; - + double norChi2Max = zoomHists ? 5. : 1000.; double d0Max = zoomHists ? 0.02 : 40.; // cosmics: 100.|100. double dzMax = zoomHists ? 15. : 100.; // cosmics: 200.|600. double pMax = zoomHists ? 200. : 2000.; - double invPMax = zoomHists ? 0.05 : 10.; //begins at 20GeV, 0.1GeV - - + double invPMax = zoomHists ? 0.05 : 10.; //begins at 20GeV, 0.1GeV + edm::Service fileService; - if(!fileService){ - throw edm::Exception( edm::errors::Configuration, - "TFileService is not registered in cfg file" ); + if (!fileService) { + throw edm::Exception(edm::errors::Configuration, "TFileService is not registered in cfg file"); } - - std::stringstream sector; sector << "Sector_" << i_sector.first; + + std::stringstream sector; + sector << "Sector_" << i_sector.first; TFileDirectory secDir = fileService->mkdir(sector.str()); - + // Dummy histo containing the sector name as title - i_sector.second.Name = secDir.make("z_name",i_sector.second.name.c_str(),1,0,1); - + i_sector.second.Name = secDir.make("z_name", i_sector.second.name.c_str(), 1, 0, 1); + // Do not book histos for empty sectors - if(i_sector.second.v_rawId.empty()){ + if (i_sector.second.v_rawId.empty()) { continue; } // Set parameters for correlationHists - i_sector.second.setCorrHistParams(&secDir,norResXAbsMax,sigmaXHitMax,sigmaXMax); - - + i_sector.second.setCorrHistParams(&secDir, norResXAbsMax, sigmaXHitMax, sigmaXMax); + // Book pixel or strip specific hists const bool pixelSector(i_sector.second.isPixel); - - + // Cluster Parameters - i_sector.second.m_correlationHistsX["WidthX"] = i_sector.second.bookCorrHistsX("WidthX","cluster width","w_{cl,x}","[# channels]",static_cast(widthMax),static_cast(widthMax),0.,widthMax,"nph"); - i_sector.second.m_correlationHistsX["BaryStripX"] = i_sector.second.bookCorrHistsX("BaryStripX","barycenter of cluster charge","b_{cl,x}","[# channels]",800,100,-10.,790.,"nph"); - - if(pixelSector){ - i_sector.second.m_correlationHistsY["WidthY"] = i_sector.second.bookCorrHistsY("WidthY","cluster width","w_{cl,y}","[# channels]",static_cast(widthMax),static_cast(widthMax),0.,widthMax,"nph"); - i_sector.second.m_correlationHistsY["BaryStripY"] = i_sector.second.bookCorrHistsY("BaryStripY","barycenter of cluster charge","b_{cl,y}","[# channels]",800,100,-10.,790.,"nph"); - - i_sector.second.m_correlationHistsX["ChargePixel"] = i_sector.second.bookCorrHistsX("ChargePixel","cluster charge","c_{cl}","[e]",100,50,0.,chargePixelMax,"nph"); - i_sector.second.m_correlationHistsX["ClusterProbXY"] = i_sector.second.bookCorrHistsX("ClusterProbXY","cluster probability xy","prob_{cl,xy}","",100,50,0.,1.,"nph"); - i_sector.second.m_correlationHistsX["ClusterProbQ"] = i_sector.second.bookCorrHistsX("ClusterProbQ","cluster probability q","prob_{cl,q}","",100,50,0.,1.,"nph"); - i_sector.second.m_correlationHistsX["ClusterProbXYQ"] = i_sector.second.bookCorrHistsX("ClusterProbXYQ","cluster probability xyq","prob_{cl,xyq}","",100,50,0.,1.,"nph"); - i_sector.second.m_correlationHistsX["LogClusterProb"] = i_sector.second.bookCorrHistsX("LogClusterProb","cluster probability xy","log(prob_{cl,xy})","",60,30,logClusterProbMin,0.,"nph"); - i_sector.second.m_correlationHistsX["IsOnEdge"] = i_sector.second.bookCorrHistsX("IsOnEdge","IsOnEdge","isOnEdge","",2,2,0,2,"nph"); - i_sector.second.m_correlationHistsX["HasBadPixels"] = i_sector.second.bookCorrHistsX("HasBadPixels","HasBadPixels","hasBadPixels","",2,2,0,2,"nph"); - i_sector.second.m_correlationHistsX["SpansTwoRoc"] = i_sector.second.bookCorrHistsX("SpansTwoRoc","SpansTwoRoc","spansTwoRoc","",2,2,0,2,"nph"); - i_sector.second.m_correlationHistsX["QBin"] = i_sector.second.bookCorrHistsX("QBin","q bin","q bin","",8,8,0,8,"nph"); - - i_sector.second.m_correlationHistsY["ChargePixel"] = i_sector.second.bookCorrHistsY("ChargePixel","cluster charge","c_{cl}","[e]",100,50,0.,chargePixelMax,"nph"); - i_sector.second.m_correlationHistsY["ClusterProbXY"] = i_sector.second.bookCorrHistsY("ClusterProbXY","cluster probability xy","prob_{cl,xy}","",100,50,0.,1.,"nph"); - i_sector.second.m_correlationHistsY["ClusterProbQ"] = i_sector.second.bookCorrHistsY("ClusterProbQ","cluster probability q","prob_{cl,q}","",100,50,0.,1.,"nph"); - i_sector.second.m_correlationHistsY["ClusterProbXYQ"] = i_sector.second.bookCorrHistsY("ClusterProbXYQ","cluster probability xyq","prob_{cl,xyq}","",100,50,0.,1.,"nph"); - i_sector.second.m_correlationHistsY["LogClusterProb"] = i_sector.second.bookCorrHistsY("LogClusterProb","cluster probability xy","log(prob_{cl,xy})","",60,30,logClusterProbMin,0.,"nph"); - i_sector.second.m_correlationHistsY["IsOnEdge"] = i_sector.second.bookCorrHistsY("IsOnEdge","IsOnEdge","isOnEdge","",2,2,0,2,"nph"); - i_sector.second.m_correlationHistsY["HasBadPixels"] = i_sector.second.bookCorrHistsY("HasBadPixels","HasBadPixels","hasBadPixels","",2,2,0,2,"nph"); - i_sector.second.m_correlationHistsY["SpansTwoRoc"] = i_sector.second.bookCorrHistsY("SpansTwoRoc","SpansTwoRoc","spansTwoRoc","",2,2,0,2,"nph"); - i_sector.second.m_correlationHistsY["QBin"] = i_sector.second.bookCorrHistsY("QBin","q bin","q bin","",8,8,0,8,"nph"); + i_sector.second.m_correlationHistsX["WidthX"] = i_sector.second.bookCorrHistsX("WidthX", + "cluster width", + "w_{cl,x}", + "[# channels]", + static_cast(widthMax), + static_cast(widthMax), + 0., + widthMax, + "nph"); + i_sector.second.m_correlationHistsX["BaryStripX"] = i_sector.second.bookCorrHistsX( + "BaryStripX", "barycenter of cluster charge", "b_{cl,x}", "[# channels]", 800, 100, -10., 790., "nph"); + + if (pixelSector) { + i_sector.second.m_correlationHistsY["WidthY"] = i_sector.second.bookCorrHistsY("WidthY", + "cluster width", + "w_{cl,y}", + "[# channels]", + static_cast(widthMax), + static_cast(widthMax), + 0., + widthMax, + "nph"); + i_sector.second.m_correlationHistsY["BaryStripY"] = i_sector.second.bookCorrHistsY( + "BaryStripY", "barycenter of cluster charge", "b_{cl,y}", "[# channels]", 800, 100, -10., 790., "nph"); + + i_sector.second.m_correlationHistsX["ChargePixel"] = i_sector.second.bookCorrHistsX( + "ChargePixel", "cluster charge", "c_{cl}", "[e]", 100, 50, 0., chargePixelMax, "nph"); + i_sector.second.m_correlationHistsX["ClusterProbXY"] = i_sector.second.bookCorrHistsX( + "ClusterProbXY", "cluster probability xy", "prob_{cl,xy}", "", 100, 50, 0., 1., "nph"); + i_sector.second.m_correlationHistsX["ClusterProbQ"] = i_sector.second.bookCorrHistsX( + "ClusterProbQ", "cluster probability q", "prob_{cl,q}", "", 100, 50, 0., 1., "nph"); + i_sector.second.m_correlationHistsX["ClusterProbXYQ"] = i_sector.second.bookCorrHistsX( + "ClusterProbXYQ", "cluster probability xyq", "prob_{cl,xyq}", "", 100, 50, 0., 1., "nph"); + i_sector.second.m_correlationHistsX["LogClusterProb"] = i_sector.second.bookCorrHistsX( + "LogClusterProb", "cluster probability xy", "log(prob_{cl,xy})", "", 60, 30, logClusterProbMin, 0., "nph"); + i_sector.second.m_correlationHistsX["IsOnEdge"] = + i_sector.second.bookCorrHistsX("IsOnEdge", "IsOnEdge", "isOnEdge", "", 2, 2, 0, 2, "nph"); + i_sector.second.m_correlationHistsX["HasBadPixels"] = + i_sector.second.bookCorrHistsX("HasBadPixels", "HasBadPixels", "hasBadPixels", "", 2, 2, 0, 2, "nph"); + i_sector.second.m_correlationHistsX["SpansTwoRoc"] = + i_sector.second.bookCorrHistsX("SpansTwoRoc", "SpansTwoRoc", "spansTwoRoc", "", 2, 2, 0, 2, "nph"); + i_sector.second.m_correlationHistsX["QBin"] = + i_sector.second.bookCorrHistsX("QBin", "q bin", "q bin", "", 8, 8, 0, 8, "nph"); + + i_sector.second.m_correlationHistsY["ChargePixel"] = i_sector.second.bookCorrHistsY( + "ChargePixel", "cluster charge", "c_{cl}", "[e]", 100, 50, 0., chargePixelMax, "nph"); + i_sector.second.m_correlationHistsY["ClusterProbXY"] = i_sector.second.bookCorrHistsY( + "ClusterProbXY", "cluster probability xy", "prob_{cl,xy}", "", 100, 50, 0., 1., "nph"); + i_sector.second.m_correlationHistsY["ClusterProbQ"] = i_sector.second.bookCorrHistsY( + "ClusterProbQ", "cluster probability q", "prob_{cl,q}", "", 100, 50, 0., 1., "nph"); + i_sector.second.m_correlationHistsY["ClusterProbXYQ"] = i_sector.second.bookCorrHistsY( + "ClusterProbXYQ", "cluster probability xyq", "prob_{cl,xyq}", "", 100, 50, 0., 1., "nph"); + i_sector.second.m_correlationHistsY["LogClusterProb"] = i_sector.second.bookCorrHistsY( + "LogClusterProb", "cluster probability xy", "log(prob_{cl,xy})", "", 60, 30, logClusterProbMin, 0., "nph"); + i_sector.second.m_correlationHistsY["IsOnEdge"] = + i_sector.second.bookCorrHistsY("IsOnEdge", "IsOnEdge", "isOnEdge", "", 2, 2, 0, 2, "nph"); + i_sector.second.m_correlationHistsY["HasBadPixels"] = + i_sector.second.bookCorrHistsY("HasBadPixels", "HasBadPixels", "hasBadPixels", "", 2, 2, 0, 2, "nph"); + i_sector.second.m_correlationHistsY["SpansTwoRoc"] = + i_sector.second.bookCorrHistsY("SpansTwoRoc", "SpansTwoRoc", "spansTwoRoc", "", 2, 2, 0, 2, "nph"); + i_sector.second.m_correlationHistsY["QBin"] = + i_sector.second.bookCorrHistsY("QBin", "q bin", "q bin", "", 8, 8, 0, 8, "nph"); } - - else{ - i_sector.second.m_correlationHistsX["ChargeStrip"] = i_sector.second.bookCorrHistsX("ChargeStrip","cluster charge","c_{cl}","[APV counts]",100,50,0.,chargeStripMax,"nph"); - i_sector.second.m_correlationHistsX["MaxStrip"] = i_sector.second.bookCorrHistsX("MaxStrip","strip with max. charge","n_{cl,max}","[# strips]",800,800,-10.,790.,"npht"); - i_sector.second.m_correlationHistsX["MaxCharge"] = i_sector.second.bookCorrHistsX("MaxCharge","charge of strip with max. charge","c_{cl,max}","[APV counts]",300,75,-10.,290.,"nph"); - i_sector.second.m_correlationHistsX["MaxIndex"] = i_sector.second.bookCorrHistsX("MaxIndex","cluster-index of strip with max. charge","i_{cl,max}","[# strips]",10,10,0.,10.,"nph"); - i_sector.second.m_correlationHistsX["ChargeOnEdges"] = i_sector.second.bookCorrHistsX("ChargeOnEdges","fraction of charge on edge strips","(c_{st,L}+c_{st,R})/c_{cl}","",60,60,-0.1,1.1,"nph"); - i_sector.second.m_correlationHistsX["ChargeAsymmetry"] = i_sector.second.bookCorrHistsX("ChargeAsymmetry","asymmetry of charge on edge strips","(c_{st,L}-c_{st,R})/c_{cl}","",110,55,-1.1,1.1,"nph"); - i_sector.second.m_correlationHistsX["ChargeLRplus"] = i_sector.second.bookCorrHistsX("ChargeLRplus","fraction of charge not on maxStrip","(c_{cl,L}+c_{cl,R})/c_{cl}","",60,60,-0.1,1.1,"nph"); - i_sector.second.m_correlationHistsX["ChargeLRminus"] = i_sector.second.bookCorrHistsX("ChargeLRminus","asymmetry of charge L and R of maxStrip","(c_{cl,L}-c_{cl,R})/c_{cl}","",110,55,-1.1,1.1,"nph"); - i_sector.second.m_correlationHistsX["SOverN"] = i_sector.second.bookCorrHistsX("SOverN","signal over noise","s/N","",100,50,0,sOverNMax,"nph"); - i_sector.second.m_correlationHistsX["WidthProj"] = i_sector.second.bookCorrHistsX("WidthProj","projected width","w_{p}","[# strips]",200,20,0.,widthMax,"nph"); - i_sector.second.m_correlationHistsX["WidthDiff"] = i_sector.second.bookCorrHistsX("WidthDiff","width difference","w_{p} - w_{cl}","[# strips]",200,20,-widthMax/2.,widthMax/2.,"nph"); - - i_sector.second.WidthVsWidthProjected = secDir.make("h2_widthVsWidthProj","w_{cl} vs. w_{p};w_{p} [# strips];w_{cl} [# strips]",static_cast(widthMax),0,widthMax,static_cast(widthMax),0,widthMax); - i_sector.second.PWidthVsWidthProjected = secDir.make("p_widthVsWidthProj","w_{cl} vs. w_{p};w_{p} [# strips];w_{cl} [# strips]",static_cast(widthMax),0,widthMax); - - i_sector.second.WidthDiffVsMaxStrip = secDir.make("h2_widthDiffVsMaxStrip","(w_{p} - w_{cl}) vs. n_{cl,max};n_{cl,max};w_{p} - w_{cl} [# strips]",800,-10.,790.,static_cast(widthMax),-widthMax/2.,widthMax/2.); - i_sector.second.PWidthDiffVsMaxStrip = secDir.make("p_widthDiffVsMaxStrip","(w_{p} - w_{cl}) vs. n_{cl,max};n_{cl,max};w_{p} - w_{cl} [# strips]",800,-10.,790.); - - i_sector.second.WidthDiffVsSigmaXHit = secDir.make("h2_widthDiffVsSigmaXHit","(w_{p} - w_{cl}) vs. #sigma_{hit,x};#sigma_{hit,x} [cm];w_{p} - w_{cl} [# strips]",100,0.,sigmaXMax,100,-10.,10.); - i_sector.second.PWidthDiffVsSigmaXHit = secDir.make("p_widthDiffVsSigmaXHit","(w_{p} - w_{cl}) vs. #sigma_{hit,x};#sigma_{hit,x} [cm];w_{p} - w_{cl} [# strips]",100,0.,sigmaXMax); - - i_sector.second.WidthVsPhiSensX = secDir.make("h2_widthVsPhiSensX","w_{cl} vs. #phi_{module,x};#phi_{module,x} [ ^{o}];w_{cl} [# strips]",93,-93,93,static_cast(widthMax),0,widthMax); - i_sector.second.PWidthVsPhiSensX = secDir.make("p_widthVsPhiSensX","w_{cl} vs. #phi_{module,x};#phi_{module,x} [ ^{o}];w_{cl} [# strips]",93,-93,93); + + else { + i_sector.second.m_correlationHistsX["ChargeStrip"] = i_sector.second.bookCorrHistsX( + "ChargeStrip", "cluster charge", "c_{cl}", "[APV counts]", 100, 50, 0., chargeStripMax, "nph"); + i_sector.second.m_correlationHistsX["MaxStrip"] = i_sector.second.bookCorrHistsX( + "MaxStrip", "strip with max. charge", "n_{cl,max}", "[# strips]", 800, 800, -10., 790., "npht"); + i_sector.second.m_correlationHistsX["MaxCharge"] = i_sector.second.bookCorrHistsX( + "MaxCharge", "charge of strip with max. charge", "c_{cl,max}", "[APV counts]", 300, 75, -10., 290., "nph"); + i_sector.second.m_correlationHistsX["MaxIndex"] = i_sector.second.bookCorrHistsX( + "MaxIndex", "cluster-index of strip with max. charge", "i_{cl,max}", "[# strips]", 10, 10, 0., 10., "nph"); + i_sector.second.m_correlationHistsX["ChargeOnEdges"] = + i_sector.second.bookCorrHistsX("ChargeOnEdges", + "fraction of charge on edge strips", + "(c_{st,L}+c_{st,R})/c_{cl}", + "", + 60, + 60, + -0.1, + 1.1, + "nph"); + i_sector.second.m_correlationHistsX["ChargeAsymmetry"] = + i_sector.second.bookCorrHistsX("ChargeAsymmetry", + "asymmetry of charge on edge strips", + "(c_{st,L}-c_{st,R})/c_{cl}", + "", + 110, + 55, + -1.1, + 1.1, + "nph"); + i_sector.second.m_correlationHistsX["ChargeLRplus"] = + i_sector.second.bookCorrHistsX("ChargeLRplus", + "fraction of charge not on maxStrip", + "(c_{cl,L}+c_{cl,R})/c_{cl}", + "", + 60, + 60, + -0.1, + 1.1, + "nph"); + i_sector.second.m_correlationHistsX["ChargeLRminus"] = + i_sector.second.bookCorrHistsX("ChargeLRminus", + "asymmetry of charge L and R of maxStrip", + "(c_{cl,L}-c_{cl,R})/c_{cl}", + "", + 110, + 55, + -1.1, + 1.1, + "nph"); + i_sector.second.m_correlationHistsX["SOverN"] = + i_sector.second.bookCorrHistsX("SOverN", "signal over noise", "s/N", "", 100, 50, 0, sOverNMax, "nph"); + i_sector.second.m_correlationHistsX["WidthProj"] = i_sector.second.bookCorrHistsX( + "WidthProj", "projected width", "w_{p}", "[# strips]", 200, 20, 0., widthMax, "nph"); + i_sector.second.m_correlationHistsX["WidthDiff"] = i_sector.second.bookCorrHistsX("WidthDiff", + "width difference", + "w_{p} - w_{cl}", + "[# strips]", + 200, + 20, + -widthMax / 2., + widthMax / 2., + "nph"); + + i_sector.second.WidthVsWidthProjected = secDir.make("h2_widthVsWidthProj", + "w_{cl} vs. w_{p};w_{p} [# strips];w_{cl} [# strips]", + static_cast(widthMax), + 0, + widthMax, + static_cast(widthMax), + 0, + widthMax); + i_sector.second.PWidthVsWidthProjected = + secDir.make("p_widthVsWidthProj", + "w_{cl} vs. w_{p};w_{p} [# strips];w_{cl} [# strips]", + static_cast(widthMax), + 0, + widthMax); + + i_sector.second.WidthDiffVsMaxStrip = + secDir.make("h2_widthDiffVsMaxStrip", + "(w_{p} - w_{cl}) vs. n_{cl,max};n_{cl,max};w_{p} - w_{cl} [# strips]", + 800, + -10., + 790., + static_cast(widthMax), + -widthMax / 2., + widthMax / 2.); + i_sector.second.PWidthDiffVsMaxStrip = + secDir.make("p_widthDiffVsMaxStrip", + "(w_{p} - w_{cl}) vs. n_{cl,max};n_{cl,max};w_{p} - w_{cl} [# strips]", + 800, + -10., + 790.); + + i_sector.second.WidthDiffVsSigmaXHit = + secDir.make("h2_widthDiffVsSigmaXHit", + "(w_{p} - w_{cl}) vs. #sigma_{hit,x};#sigma_{hit,x} [cm];w_{p} - w_{cl} [# strips]", + 100, + 0., + sigmaXMax, + 100, + -10., + 10.); + i_sector.second.PWidthDiffVsSigmaXHit = + secDir.make("p_widthDiffVsSigmaXHit", + "(w_{p} - w_{cl}) vs. #sigma_{hit,x};#sigma_{hit,x} [cm];w_{p} - w_{cl} [# strips]", + 100, + 0., + sigmaXMax); + + i_sector.second.WidthVsPhiSensX = + secDir.make("h2_widthVsPhiSensX", + "w_{cl} vs. #phi_{module,x};#phi_{module,x} [ ^{o}];w_{cl} [# strips]", + 93, + -93, + 93, + static_cast(widthMax), + 0, + widthMax); + i_sector.second.PWidthVsPhiSensX = secDir.make( + "p_widthVsPhiSensX", "w_{cl} vs. #phi_{module,x};#phi_{module,x} [ ^{o}];w_{cl} [# strips]", 93, -93, 93); } - - + // Hit Parameters (transform errors and residuals from [cm] in [mum]) - i_sector.second.m_correlationHistsX["SigmaXHit"] = i_sector.second.bookCorrHistsX("SigmaXHit","hit error","#sigma_{hit,x}","[#mum]",105,20,sigmaXMin*10000.,sigmaXMax*10000.,"np"); - i_sector.second.m_correlationHistsX["SigmaXTrk"] = i_sector.second.bookCorrHistsX("SigmaXTrk","track error","#sigma_{trk,x}","[#mum]",105,20,sigmaXMin*10000.,sigmaXMax*10000.,"np"); - i_sector.second.m_correlationHistsX["SigmaX"] = i_sector.second.bookCorrHistsX("SigmaX","residual error","#sigma_{r,x}","[#mum]",105,20,sigmaXMin*10000.,sigmaXMax*10000.,"np"); - i_sector.second.m_correlationHistsX["PhiSens"] = i_sector.second.bookCorrHistsX("PhiSens","track angle on sensor","#phi_{module}","[ ^{o}]",96,48,-3,93,"nphtr"); - i_sector.second.m_correlationHistsX["PhiSensX"] = i_sector.second.bookCorrHistsX("PhiSensX","track angle on sensor","#phi_{module,x}","[ ^{o}]",186,93,-phiSensXMax,phiSensXMax,"nphtr"); - i_sector.second.m_correlationHistsX["PhiSensY"] = i_sector.second.bookCorrHistsX("PhiSensY","track angle on sensor","#phi_{module,y}","[ ^{o}]",186,93,-93,93,"nphtr"); - - i_sector.second.XHit = secDir.make("h_XHit"," hit measurement x_{hit};x_{hit} [cm];# hits",100,-20,20); - i_sector.second.XTrk = secDir.make("h_XTrk","track prediction x_{trk};x_{trk} [cm];# hits",100,-20,20); - i_sector.second.SigmaX2 = secDir.make("h_SigmaX2","squared residual error #sigma_{r,x}^{2};#sigma_{r,x}^{2} [#mum^{2}];# hits",105,sigmaXMin*10000.,sigmaX2Max*10000.*10000.); //no mistake ! - i_sector.second.ResX = secDir.make("h_ResX","residual r_{x};x_{trk}-x_{hit} [#mum];# hits",100,-resXAbsMax*10000.,resXAbsMax*10000.); - i_sector.second.NorResX = secDir.make("h_NorResX","normalized residual r_{x}/#sigma_{r,x};(x_{trk}-x_{hit})/#sigma_{r,x};# hits",100,-norResXAbsMax,norResXAbsMax); - i_sector.second.ProbX = secDir.make("h_ProbX","residual probability;prob(r_{x}^{2}/#sigma_{r,x}^{2},1);# hits",60,probXMin,probXMax); - - i_sector.second.PhiSensXVsBarycentreX = secDir.make("h2_phiSensXVsBarycentreX","#phi_{module,x} vs. b_{cl,x};b_{cl,x} [# channels];#phi_{module,x} [ ^{o}]",200,-10.,790.,93,-93,93); - i_sector.second.PPhiSensXVsBarycentreX = secDir.make("p_phiSensXVsBarycentreX","#phi_{module,x} vs. b_{cl,x};b_{cl,x} [# channels];#phi_{module,x} [ ^{o}]",200,-10.,790.); - - if(pixelSector){ - i_sector.second.m_correlationHistsY["SigmaYHit"] = i_sector.second.bookCorrHistsY("SigmaYHit","hit error","#sigma_{hit,y}","[#mum]",105,20,sigmaXMin*10000.,sigmaXMax*10000.,"np"); - i_sector.second.m_correlationHistsY["SigmaYTrk"] = i_sector.second.bookCorrHistsY("SigmaYTrk","track error","#sigma_{trk,y}","[#mum]",105,20,sigmaXMin*10000.,sigmaXMax*10000.,"np"); - i_sector.second.m_correlationHistsY["SigmaY"] = i_sector.second.bookCorrHistsY("SigmaY","residual error","#sigma_{r,y}","[#mum]",105,20,sigmaXMin*10000.,sigmaXMax*10000.,"np"); - i_sector.second.m_correlationHistsY["PhiSens"] = i_sector.second.bookCorrHistsY("PhiSens","track angle on sensor","#phi_{module}","[ ^{o}]",96,48,-3,93,"nphtr"); - i_sector.second.m_correlationHistsY["PhiSensX"] = i_sector.second.bookCorrHistsY("PhiSensX","track angle on sensor","#phi_{module,x}","[ ^{o}]",186,93,-phiSensXMax,phiSensXMax,"nphtr"); - i_sector.second.m_correlationHistsY["PhiSensY"] = i_sector.second.bookCorrHistsY("PhiSensY","track angle on sensor","#phi_{module,y}","[ ^{o}]",186,93,-93,93,"nphtr"); - - i_sector.second.YHit = secDir.make("h_YHit"," hit measurement y_{hit};y_{hit} [cm];# hits",100,-20,20); - i_sector.second.YTrk = secDir.make("h_YTrk","track prediction y_{trk};y_{trk} [cm];# hits",100,-20,20); - i_sector.second.SigmaY2 = secDir.make("h_SigmaY2","squared residual error #sigma_{r,y}^{2};#sigma_{r,y}^{2} [#mum^{2}];# hits",105,sigmaXMin*10000.,sigmaX2Max*10000.*10000.); //no mistake ! - i_sector.second.ResY = secDir.make("h_ResY","residual r_{y};y_{trk}-y_{hit} [#mum];# hits",100,-resXAbsMax*10000.,resXAbsMax*10000.); - i_sector.second.NorResY = secDir.make("h_NorResY","normalized residual r_{y}/#sigma_{r,y};(y_{trk}-y_{hit})/#sigma_{r,y};# hits",100,-norResXAbsMax,norResXAbsMax); - i_sector.second.ProbY = secDir.make("h_ProbY","residual probability;prob(r_{y}^{2}/#sigma_{r,y}^{2},1);# hits",60,probXMin,probXMax); - - i_sector.second.PhiSensYVsBarycentreY = secDir.make("h2_phiSensYVsBarycentreY","#phi_{module,y} vs. b_{cl,y};b_{cl,y} [# channels];#phi_{module,y} [ ^{o}]",200,-10.,790.,93,-93,93); - i_sector.second.PPhiSensYVsBarycentreY = secDir.make("p_phiSensYVsBarycentreY","#phi_{module,y} vs. b_{cl,y};b_{cl,y} [# channels];#phi_{module,y} [ ^{o}]",200,-10.,790.); + i_sector.second.m_correlationHistsX["SigmaXHit"] = i_sector.second.bookCorrHistsX( + "SigmaXHit", "hit error", "#sigma_{hit,x}", "[#mum]", 105, 20, sigmaXMin * 10000., sigmaXMax * 10000., "np"); + i_sector.second.m_correlationHistsX["SigmaXTrk"] = i_sector.second.bookCorrHistsX( + "SigmaXTrk", "track error", "#sigma_{trk,x}", "[#mum]", 105, 20, sigmaXMin * 10000., sigmaXMax * 10000., "np"); + i_sector.second.m_correlationHistsX["SigmaX"] = i_sector.second.bookCorrHistsX( + "SigmaX", "residual error", "#sigma_{r,x}", "[#mum]", 105, 20, sigmaXMin * 10000., sigmaXMax * 10000., "np"); + i_sector.second.m_correlationHistsX["PhiSens"] = i_sector.second.bookCorrHistsX( + "PhiSens", "track angle on sensor", "#phi_{module}", "[ ^{o}]", 96, 48, -3, 93, "nphtr"); + i_sector.second.m_correlationHistsX["PhiSensX"] = i_sector.second.bookCorrHistsX( + "PhiSensX", "track angle on sensor", "#phi_{module,x}", "[ ^{o}]", 186, 93, -phiSensXMax, phiSensXMax, "nphtr"); + i_sector.second.m_correlationHistsX["PhiSensY"] = i_sector.second.bookCorrHistsX( + "PhiSensY", "track angle on sensor", "#phi_{module,y}", "[ ^{o}]", 186, 93, -93, 93, "nphtr"); + + i_sector.second.XHit = secDir.make("h_XHit", " hit measurement x_{hit};x_{hit} [cm];# hits", 100, -20, 20); + i_sector.second.XTrk = secDir.make("h_XTrk", "track prediction x_{trk};x_{trk} [cm];# hits", 100, -20, 20); + i_sector.second.SigmaX2 = + secDir.make("h_SigmaX2", + "squared residual error #sigma_{r,x}^{2};#sigma_{r,x}^{2} [#mum^{2}];# hits", + 105, + sigmaXMin * 10000., + sigmaX2Max * 10000. * 10000.); //no mistake ! + i_sector.second.ResX = secDir.make( + "h_ResX", "residual r_{x};x_{trk}-x_{hit} [#mum];# hits", 100, -resXAbsMax * 10000., resXAbsMax * 10000.); + i_sector.second.NorResX = + secDir.make("h_NorResX", + "normalized residual r_{x}/#sigma_{r,x};(x_{trk}-x_{hit})/#sigma_{r,x};# hits", + 100, + -norResXAbsMax, + norResXAbsMax); + i_sector.second.ProbX = secDir.make( + "h_ProbX", "residual probability;prob(r_{x}^{2}/#sigma_{r,x}^{2},1);# hits", 60, probXMin, probXMax); + + i_sector.second.PhiSensXVsBarycentreX = + secDir.make("h2_phiSensXVsBarycentreX", + "#phi_{module,x} vs. b_{cl,x};b_{cl,x} [# channels];#phi_{module,x} [ ^{o}]", + 200, + -10., + 790., + 93, + -93, + 93); + i_sector.second.PPhiSensXVsBarycentreX = + secDir.make("p_phiSensXVsBarycentreX", + "#phi_{module,x} vs. b_{cl,x};b_{cl,x} [# channels];#phi_{module,x} [ ^{o}]", + 200, + -10., + 790.); + + if (pixelSector) { + i_sector.second.m_correlationHistsY["SigmaYHit"] = i_sector.second.bookCorrHistsY( + "SigmaYHit", "hit error", "#sigma_{hit,y}", "[#mum]", 105, 20, sigmaXMin * 10000., sigmaXMax * 10000., "np"); + i_sector.second.m_correlationHistsY["SigmaYTrk"] = i_sector.second.bookCorrHistsY( + "SigmaYTrk", "track error", "#sigma_{trk,y}", "[#mum]", 105, 20, sigmaXMin * 10000., sigmaXMax * 10000., "np"); + i_sector.second.m_correlationHistsY["SigmaY"] = i_sector.second.bookCorrHistsY( + "SigmaY", "residual error", "#sigma_{r,y}", "[#mum]", 105, 20, sigmaXMin * 10000., sigmaXMax * 10000., "np"); + i_sector.second.m_correlationHistsY["PhiSens"] = i_sector.second.bookCorrHistsY( + "PhiSens", "track angle on sensor", "#phi_{module}", "[ ^{o}]", 96, 48, -3, 93, "nphtr"); + i_sector.second.m_correlationHistsY["PhiSensX"] = i_sector.second.bookCorrHistsY("PhiSensX", + "track angle on sensor", + "#phi_{module,x}", + "[ ^{o}]", + 186, + 93, + -phiSensXMax, + phiSensXMax, + "nphtr"); + i_sector.second.m_correlationHistsY["PhiSensY"] = i_sector.second.bookCorrHistsY( + "PhiSensY", "track angle on sensor", "#phi_{module,y}", "[ ^{o}]", 186, 93, -93, 93, "nphtr"); + + i_sector.second.YHit = secDir.make("h_YHit", " hit measurement y_{hit};y_{hit} [cm];# hits", 100, -20, 20); + i_sector.second.YTrk = secDir.make("h_YTrk", "track prediction y_{trk};y_{trk} [cm];# hits", 100, -20, 20); + i_sector.second.SigmaY2 = + secDir.make("h_SigmaY2", + "squared residual error #sigma_{r,y}^{2};#sigma_{r,y}^{2} [#mum^{2}];# hits", + 105, + sigmaXMin * 10000., + sigmaX2Max * 10000. * 10000.); //no mistake ! + i_sector.second.ResY = secDir.make( + "h_ResY", "residual r_{y};y_{trk}-y_{hit} [#mum];# hits", 100, -resXAbsMax * 10000., resXAbsMax * 10000.); + i_sector.second.NorResY = + secDir.make("h_NorResY", + "normalized residual r_{y}/#sigma_{r,y};(y_{trk}-y_{hit})/#sigma_{r,y};# hits", + 100, + -norResXAbsMax, + norResXAbsMax); + i_sector.second.ProbY = secDir.make( + "h_ProbY", "residual probability;prob(r_{y}^{2}/#sigma_{r,y}^{2},1);# hits", 60, probXMin, probXMax); + + i_sector.second.PhiSensYVsBarycentreY = + secDir.make("h2_phiSensYVsBarycentreY", + "#phi_{module,y} vs. b_{cl,y};b_{cl,y} [# channels];#phi_{module,y} [ ^{o}]", + 200, + -10., + 790., + 93, + -93, + 93); + i_sector.second.PPhiSensYVsBarycentreY = + secDir.make("p_phiSensYVsBarycentreY", + "#phi_{module,y} vs. b_{cl,y};b_{cl,y} [# channels];#phi_{module,y} [ ^{o}]", + 200, + -10., + 790.); } - - + // Track Parameters - i_sector.second.m_correlationHistsX["HitsValid"] = i_sector.second.bookCorrHistsX("HitsValid","# hits","[valid]",50,0,50,"npt"); - i_sector.second.m_correlationHistsX["HitsInvalid"] = i_sector.second.bookCorrHistsX("HitsInvalid","# hits","[invalid]",20,0,20,"npt"); - i_sector.second.m_correlationHistsX["Hits2D"] = i_sector.second.bookCorrHistsX("Hits2D","# hits","[2D]",20,0,20,"npt"); - i_sector.second.m_correlationHistsX["LayersMissed"] = i_sector.second.bookCorrHistsX("LayersMissed","# layers","[missed]",10,0,10,"npt"); - i_sector.second.m_correlationHistsX["HitsPixel"] = i_sector.second.bookCorrHistsX("HitsPixel","# hits","[pixel]",10,0,10,"npt"); - i_sector.second.m_correlationHistsX["HitsStrip"] = i_sector.second.bookCorrHistsX("HitsStrip","# hits","[strip]",40,0,40,"npt"); - i_sector.second.m_correlationHistsX["HitsGood"] = i_sector.second.bookCorrHistsX("HitsGood","# hits","[good]",50,0,50,"npt"); - i_sector.second.m_correlationHistsX["NorChi2"] = i_sector.second.bookCorrHistsX("NorChi2","#chi^{2}/f","",50,0,norChi2Max,"npr"); - i_sector.second.m_correlationHistsX["Theta"] = i_sector.second.bookCorrHistsX("Theta","#theta","[ ^{o}]",40,-10,190,"npt"); - i_sector.second.m_correlationHistsX["Phi"] = i_sector.second.bookCorrHistsX("Phi","#phi","[ ^{o}]",76,-190,190,"npt"); - i_sector.second.m_correlationHistsX["D0Beamspot"] = i_sector.second.bookCorrHistsX("D0Beamspot","d_{0, BS}","[cm]",40,-d0Max,d0Max,"npt"); - i_sector.second.m_correlationHistsX["Dz"] = i_sector.second.bookCorrHistsX("Dz","d_{z}","[cm]",40,-dzMax,dzMax,"npt"); - i_sector.second.m_correlationHistsX["Pt"] = i_sector.second.bookCorrHistsX("Pt","p_{t}","[GeV]",50,0,pMax,"npt"); - i_sector.second.m_correlationHistsX["P"] = i_sector.second.bookCorrHistsX("P","|p|","[GeV]",50,0,pMax,"npt"); - i_sector.second.m_correlationHistsX["InvP"] = i_sector.second.bookCorrHistsX("InvP","1/|p|","[GeV^{-1}]",25,0,invPMax,"t"); - i_sector.second.m_correlationHistsX["MeanAngle"] = i_sector.second.bookCorrHistsX("MeanAngle","<#phi_{module}>","[ ^{o}]",25,-5,95,"npt"); + i_sector.second.m_correlationHistsX["HitsValid"] = + i_sector.second.bookCorrHistsX("HitsValid", "# hits", "[valid]", 50, 0, 50, "npt"); + i_sector.second.m_correlationHistsX["HitsInvalid"] = + i_sector.second.bookCorrHistsX("HitsInvalid", "# hits", "[invalid]", 20, 0, 20, "npt"); + i_sector.second.m_correlationHistsX["Hits2D"] = + i_sector.second.bookCorrHistsX("Hits2D", "# hits", "[2D]", 20, 0, 20, "npt"); + i_sector.second.m_correlationHistsX["LayersMissed"] = + i_sector.second.bookCorrHistsX("LayersMissed", "# layers", "[missed]", 10, 0, 10, "npt"); + i_sector.second.m_correlationHistsX["HitsPixel"] = + i_sector.second.bookCorrHistsX("HitsPixel", "# hits", "[pixel]", 10, 0, 10, "npt"); + i_sector.second.m_correlationHistsX["HitsStrip"] = + i_sector.second.bookCorrHistsX("HitsStrip", "# hits", "[strip]", 40, 0, 40, "npt"); + i_sector.second.m_correlationHistsX["HitsGood"] = + i_sector.second.bookCorrHistsX("HitsGood", "# hits", "[good]", 50, 0, 50, "npt"); + i_sector.second.m_correlationHistsX["NorChi2"] = + i_sector.second.bookCorrHistsX("NorChi2", "#chi^{2}/f", "", 50, 0, norChi2Max, "npr"); + i_sector.second.m_correlationHistsX["Theta"] = + i_sector.second.bookCorrHistsX("Theta", "#theta", "[ ^{o}]", 40, -10, 190, "npt"); + i_sector.second.m_correlationHistsX["Phi"] = + i_sector.second.bookCorrHistsX("Phi", "#phi", "[ ^{o}]", 76, -190, 190, "npt"); + i_sector.second.m_correlationHistsX["D0Beamspot"] = + i_sector.second.bookCorrHistsX("D0Beamspot", "d_{0, BS}", "[cm]", 40, -d0Max, d0Max, "npt"); + i_sector.second.m_correlationHistsX["Dz"] = + i_sector.second.bookCorrHistsX("Dz", "d_{z}", "[cm]", 40, -dzMax, dzMax, "npt"); + i_sector.second.m_correlationHistsX["Pt"] = + i_sector.second.bookCorrHistsX("Pt", "p_{t}", "[GeV]", 50, 0, pMax, "npt"); + i_sector.second.m_correlationHistsX["P"] = i_sector.second.bookCorrHistsX("P", "|p|", "[GeV]", 50, 0, pMax, "npt"); + i_sector.second.m_correlationHistsX["InvP"] = + i_sector.second.bookCorrHistsX("InvP", "1/|p|", "[GeV^{-1}]", 25, 0, invPMax, "t"); + i_sector.second.m_correlationHistsX["MeanAngle"] = + i_sector.second.bookCorrHistsX("MeanAngle", "<#phi_{module}>", "[ ^{o}]", 25, -5, 95, "npt"); //i_sector.second.m_correlationHistsX[""] = i_sector.second.bookCorrHistsX("","","",,,,"nphtr"); - - if(pixelSector){ - i_sector.second.m_correlationHistsY["HitsValid"] = i_sector.second.bookCorrHistsY("HitsValid","# hits","[valid]",50,0,50,"npt"); - i_sector.second.m_correlationHistsY["HitsInvalid"] = i_sector.second.bookCorrHistsY("HitsInvalid","# hits","[invalid]",20,0,20,"npt"); - i_sector.second.m_correlationHistsY["Hits2D"] = i_sector.second.bookCorrHistsY("Hits2D","# hits","[2D]",20,0,20,"npt"); - i_sector.second.m_correlationHistsY["LayersMissed"] = i_sector.second.bookCorrHistsY("LayersMissed","# layers","[missed]",10,0,10,"npt"); - i_sector.second.m_correlationHistsY["HitsPixel"] = i_sector.second.bookCorrHistsY("HitsPixel","# hits","[pixel]",10,0,10,"npt"); - i_sector.second.m_correlationHistsY["HitsStrip"] = i_sector.second.bookCorrHistsY("HitsStrip","# hits","[strip]",40,0,40,"npt"); - i_sector.second.m_correlationHistsY["HitsGood"] = i_sector.second.bookCorrHistsY("HitsGood","# hits","[good]",50,0,50,"npt"); - i_sector.second.m_correlationHistsY["NorChi2"] = i_sector.second.bookCorrHistsY("NorChi2","#chi^{2}/f","",50,0,norChi2Max,"npr"); - i_sector.second.m_correlationHistsY["Theta"] = i_sector.second.bookCorrHistsY("Theta","#theta","[ ^{o}]",40,-10,190,"npt"); - i_sector.second.m_correlationHistsY["Phi"] = i_sector.second.bookCorrHistsY("Phi","#phi","[ ^{o}]",76,-190,190,"npt"); - i_sector.second.m_correlationHistsY["D0Beamspot"] = i_sector.second.bookCorrHistsY("D0Beamspot","d_{0, BS}","[cm]",40,-d0Max,d0Max,"npt"); - i_sector.second.m_correlationHistsY["Dz"] = i_sector.second.bookCorrHistsY("Dz","d_{z}","[cm]",40,-dzMax,dzMax,"npt"); - i_sector.second.m_correlationHistsY["Pt"] = i_sector.second.bookCorrHistsY("Pt","p_{t}","[GeV]",50,0,pMax,"npt"); - i_sector.second.m_correlationHistsY["P"] = i_sector.second.bookCorrHistsY("P","|p|","[GeV]",50,0,pMax,"npt"); - i_sector.second.m_correlationHistsY["InvP"] = i_sector.second.bookCorrHistsY("InvP","1/|p|","[GeV^{-1}]",25,0,invPMax,"t"); - i_sector.second.m_correlationHistsY["MeanAngle"] = i_sector.second.bookCorrHistsY("MeanAngle","<#phi_{module}>","[ ^{o}]",25,-5,95,"npt"); + + if (pixelSector) { + i_sector.second.m_correlationHistsY["HitsValid"] = + i_sector.second.bookCorrHistsY("HitsValid", "# hits", "[valid]", 50, 0, 50, "npt"); + i_sector.second.m_correlationHistsY["HitsInvalid"] = + i_sector.second.bookCorrHistsY("HitsInvalid", "# hits", "[invalid]", 20, 0, 20, "npt"); + i_sector.second.m_correlationHistsY["Hits2D"] = + i_sector.second.bookCorrHistsY("Hits2D", "# hits", "[2D]", 20, 0, 20, "npt"); + i_sector.second.m_correlationHistsY["LayersMissed"] = + i_sector.second.bookCorrHistsY("LayersMissed", "# layers", "[missed]", 10, 0, 10, "npt"); + i_sector.second.m_correlationHistsY["HitsPixel"] = + i_sector.second.bookCorrHistsY("HitsPixel", "# hits", "[pixel]", 10, 0, 10, "npt"); + i_sector.second.m_correlationHistsY["HitsStrip"] = + i_sector.second.bookCorrHistsY("HitsStrip", "# hits", "[strip]", 40, 0, 40, "npt"); + i_sector.second.m_correlationHistsY["HitsGood"] = + i_sector.second.bookCorrHistsY("HitsGood", "# hits", "[good]", 50, 0, 50, "npt"); + i_sector.second.m_correlationHistsY["NorChi2"] = + i_sector.second.bookCorrHistsY("NorChi2", "#chi^{2}/f", "", 50, 0, norChi2Max, "npr"); + i_sector.second.m_correlationHistsY["Theta"] = + i_sector.second.bookCorrHistsY("Theta", "#theta", "[ ^{o}]", 40, -10, 190, "npt"); + i_sector.second.m_correlationHistsY["Phi"] = + i_sector.second.bookCorrHistsY("Phi", "#phi", "[ ^{o}]", 76, -190, 190, "npt"); + i_sector.second.m_correlationHistsY["D0Beamspot"] = + i_sector.second.bookCorrHistsY("D0Beamspot", "d_{0, BS}", "[cm]", 40, -d0Max, d0Max, "npt"); + i_sector.second.m_correlationHistsY["Dz"] = + i_sector.second.bookCorrHistsY("Dz", "d_{z}", "[cm]", 40, -dzMax, dzMax, "npt"); + i_sector.second.m_correlationHistsY["Pt"] = + i_sector.second.bookCorrHistsY("Pt", "p_{t}", "[GeV]", 50, 0, pMax, "npt"); + i_sector.second.m_correlationHistsY["P"] = + i_sector.second.bookCorrHistsY("P", "|p|", "[GeV]", 50, 0, pMax, "npt"); + i_sector.second.m_correlationHistsY["InvP"] = + i_sector.second.bookCorrHistsY("InvP", "1/|p|", "[GeV^{-1}]", 25, 0, invPMax, "t"); + i_sector.second.m_correlationHistsY["MeanAngle"] = + i_sector.second.bookCorrHistsY("MeanAngle", "<#phi_{module}>", "[ ^{o}]", 25, -5, 95, "npt"); } - - + // (transform errors and residuals from [cm] in [mum]) - for(auto const & i_errHists : v_errHists){ - double xMin(0.01*(i_errHists-1)), xMax(0.01*(i_errHists)); + for (auto const& i_errHists : v_errHists) { + double xMin(0.01 * (i_errHists - 1)), xMax(0.01 * (i_errHists)); std::stringstream sigmaXHit, sigmaXTrk, sigmaX; sigmaXHit << "h_sigmaXHit_" << i_errHists; sigmaXTrk << "h_sigmaXTrk_" << i_errHists; - sigmaX << "h_sigmaX_" << i_errHists; - i_sector.second.m_sigmaX["sigmaXHit"].push_back(secDir.make(sigmaXHit.str().c_str(),"hit error #sigma_{hit,x};#sigma_{hit,x} [#mum];# hits",100,xMin*10000.,xMax*10000.)); - i_sector.second.m_sigmaX["sigmaXTrk"].push_back(secDir.make(sigmaXTrk.str().c_str(),"track error #sigma_{trk,x};#sigma_{trk,x} [#mum];# hits",100,xMin*10000.,xMax*10000.)); - i_sector.second.m_sigmaX["sigmaX" ].push_back(secDir.make(sigmaX.str().c_str(),"residual error #sigma_{r,x};#sigma_{r,x} [#mum];# hits",100,xMin*10000.,xMax*10000.)); - if(pixelSector){ + sigmaX << "h_sigmaX_" << i_errHists; + i_sector.second.m_sigmaX["sigmaXHit"].push_back( + secDir.make(sigmaXHit.str().c_str(), + "hit error #sigma_{hit,x};#sigma_{hit,x} [#mum];# hits", + 100, + xMin * 10000., + xMax * 10000.)); + i_sector.second.m_sigmaX["sigmaXTrk"].push_back( + secDir.make(sigmaXTrk.str().c_str(), + "track error #sigma_{trk,x};#sigma_{trk,x} [#mum];# hits", + 100, + xMin * 10000., + xMax * 10000.)); + i_sector.second.m_sigmaX["sigmaX"].push_back( + secDir.make(sigmaX.str().c_str(), + "residual error #sigma_{r,x};#sigma_{r,x} [#mum];# hits", + 100, + xMin * 10000., + xMax * 10000.)); + if (pixelSector) { std::stringstream sigmaYHit, sigmaYTrk, sigmaY; sigmaYHit << "h_sigmaYHit_" << i_errHists; sigmaYTrk << "h_sigmaYTrk_" << i_errHists; - sigmaY << "h_sigmaY_" << i_errHists; - i_sector.second.m_sigmaY["sigmaYHit"].push_back(secDir.make(sigmaYHit.str().c_str(),"hit error #sigma_{hit,y};#sigma_{hit,y} [#mum];# hits",100,xMin*10000.,xMax*10000.)); - i_sector.second.m_sigmaY["sigmaYTrk"].push_back(secDir.make(sigmaYTrk.str().c_str(),"track error #sigma_{trk,y};#sigma_{trk,y} [#mum];# hits",100,xMin*10000.,xMax*10000.)); - i_sector.second.m_sigmaY["sigmaY" ].push_back(secDir.make(sigmaY.str().c_str(),"residual error #sigma_{r,y};#sigma_{r,y} [#mum];# hits",100,xMin*10000.,xMax*10000.)); + sigmaY << "h_sigmaY_" << i_errHists; + i_sector.second.m_sigmaY["sigmaYHit"].push_back( + secDir.make(sigmaYHit.str().c_str(), + "hit error #sigma_{hit,y};#sigma_{hit,y} [#mum];# hits", + 100, + xMin * 10000., + xMax * 10000.)); + i_sector.second.m_sigmaY["sigmaYTrk"].push_back( + secDir.make(sigmaYTrk.str().c_str(), + "track error #sigma_{trk,y};#sigma_{trk,y} [#mum];# hits", + 100, + xMin * 10000., + xMax * 10000.)); + i_sector.second.m_sigmaY["sigmaY"].push_back( + secDir.make(sigmaY.str().c_str(), + "residual error #sigma_{r,y};#sigma_{r,y} [#mum];# hits", + 100, + xMin * 10000., + xMax * 10000.)); } } - } } - - -void -ApeEstimator::bookSectorHistsForApeCalculation(){ +void ApeEstimator::bookSectorHistsForApeCalculation() { std::vector v_errHists(parameterSet_.getParameter >("vErrHists")); - for(std::vector::iterator i_errHists = v_errHists.begin(); i_errHists != v_errHists.end(); ++i_errHists){ - for(std::vector::iterator i_errHists2 = i_errHists; i_errHists2 != v_errHists.end();){ + for (std::vector::iterator i_errHists = v_errHists.begin(); i_errHists != v_errHists.end(); + ++i_errHists) { + for (std::vector::iterator i_errHists2 = i_errHists; i_errHists2 != v_errHists.end();) { ++i_errHists2; - if(*i_errHists==*i_errHists2){ - edm::LogError("BookSectorHists")<<"Value of vErrHists in config exists twice: "<<*i_errHists<<"\n... delete one of both"; + if (*i_errHists == *i_errHists2) { + edm::LogError("BookSectorHists") << "Value of vErrHists in config exists twice: " << *i_errHists + << "\n... delete one of both"; v_errHists.erase(i_errHists2); } } } - - for(auto &i_sector : m_tkSector_){ + + for (auto& i_sector : m_tkSector_) { edm::Service fileService; - if(!fileService){ - throw edm::Exception( edm::errors::Configuration, - "TFileService is not registered in cfg file" ); + if (!fileService) { + throw edm::Exception(edm::errors::Configuration, "TFileService is not registered in cfg file"); } - - std::stringstream sector; sector << "Sector_" << i_sector.first; + + std::stringstream sector; + sector << "Sector_" << i_sector.first; TFileDirectory secDir = fileService->mkdir(sector.str()); - + // Dummy histo containing the sector name as title - i_sector.second.Name = secDir.make("z_name",i_sector.second.name.c_str(),1,0,1); - + i_sector.second.Name = secDir.make("z_name", i_sector.second.name.c_str(), 1, 0, 1); + // Do not book histos for empty sectors - if(i_sector.second.v_rawId.empty()){ + if (i_sector.second.v_rawId.empty()) { continue; } - - + // Distributions in each interval (stay in [cm], to have all calculations in [cm]) - if(m_resErrBins_.empty()){ // default if no selection taken into account: calculate APE with one bin with residual error 0-100um + if (m_resErrBins_ + .empty()) { // default if no selection taken into account: calculate APE with one bin with residual error 0-100um m_resErrBins_[1].first = 0.; m_resErrBins_[1].second = 0.01; - } - for(auto const & i_errBins : m_resErrBins_){ - std::stringstream interval; interval << "Interval_" << i_errBins.first; + } + for (auto const& i_errBins : m_resErrBins_) { + std::stringstream interval; + interval << "Interval_" << i_errBins.first; TFileDirectory intDir = secDir.mkdir(interval.str()); - i_sector.second.m_binnedHists[i_errBins.first]["sigmaX"] = intDir.make("h_sigmaX","residual resolution #sigma_{x};#sigma_{x} [cm];# hits",100,0.,0.01); - i_sector.second.m_binnedHists[i_errBins.first]["norResX"] = intDir.make("h_norResX","normalized residual r_{x}/#sigma_{r,x};(x_{trk}-x_{hit})/#sigma_{r,x};# hits",100,-10,10); - if(i_sector.second.isPixel){ - i_sector.second.m_binnedHists[i_errBins.first]["sigmaY"] = intDir.make("h_sigmaY","residual resolution #sigma_{y};#sigma_{y} [cm];# hits",100,0.,0.01); - i_sector.second.m_binnedHists[i_errBins.first]["norResY"] = intDir.make("h_norResY","normalized residual r_{y}/#sigma_{r,y};(y_{trk}-y_{hit})/#sigma_{r,y};# hits",100,-10,10); + i_sector.second.m_binnedHists[i_errBins.first]["sigmaX"] = + intDir.make("h_sigmaX", "residual resolution #sigma_{x};#sigma_{x} [cm];# hits", 100, 0., 0.01); + i_sector.second.m_binnedHists[i_errBins.first]["norResX"] = intDir.make( + "h_norResX", "normalized residual r_{x}/#sigma_{r,x};(x_{trk}-x_{hit})/#sigma_{r,x};# hits", 100, -10, 10); + if (i_sector.second.isPixel) { + i_sector.second.m_binnedHists[i_errBins.first]["sigmaY"] = + intDir.make("h_sigmaY", "residual resolution #sigma_{y};#sigma_{y} [cm];# hits", 100, 0., 0.01); + i_sector.second.m_binnedHists[i_errBins.first]["norResY"] = intDir.make( + "h_norResY", "normalized residual r_{y}/#sigma_{r,y};(y_{trk}-y_{hit})/#sigma_{r,y};# hits", 100, -10, 10); } } - - + TFileDirectory resDir = secDir.mkdir("Results"); - + // TTree containing rawIds of all modules in sector unsigned int rawId(0); - i_sector.second.RawId = resDir.make("rawIdTree","Tree containing rawIds of all modules in sector"); + i_sector.second.RawId = resDir.make("rawIdTree", "Tree containing rawIds of all modules in sector"); i_sector.second.RawId->Branch("RawId", &rawId, "RawId/i"); - for(auto const & i_rawId : i_sector.second.v_rawId){ + for (auto const& i_rawId : i_sector.second.v_rawId) { rawId = i_rawId; i_sector.second.RawId->Fill(); } - + // Result plots (one hist per sector containing one bin per interval) // (transform errors and residuals from [cm] in [mum]) std::vector v_binX(parameterSet_.getParameter >("residualErrorBinning")); - for(auto & i_binX : v_binX){ + for (auto& i_binX : v_binX) { i_binX *= 10000.; } - i_sector.second.EntriesX = resDir.make("h_entriesX","# hits used;#sigma_{x} [#mum];# hits",v_binX.size()-1,&(v_binX[0])); - if(i_sector.second.isPixel){ - i_sector.second.EntriesY = resDir.make("h_entriesY","# hits used;#sigma_{y} [#mum];# hits",v_binX.size()-1,&(v_binX[0])); + i_sector.second.EntriesX = + resDir.make("h_entriesX", "# hits used;#sigma_{x} [#mum];# hits", v_binX.size() - 1, &(v_binX[0])); + if (i_sector.second.isPixel) { + i_sector.second.EntriesY = + resDir.make("h_entriesY", "# hits used;#sigma_{y} [#mum];# hits", v_binX.size() - 1, &(v_binX[0])); } - + // In fact these are un-needed Analyzer plots, but I want to have them always for every sector visible // (transform errors and residuals from [cm] in [mum]) - i_sector.second.ResX = resDir.make("h_ResX","residual r_{x};x_{trk}-x_{hit} [#mum];# hits",100,-0.03*10000.,0.03*10000.); - i_sector.second.NorResX = resDir.make("h_NorResX","normalized residual r_{x}/#sigma_{r,x};(x_{trk}-x_{hit})/#sigma_{r,x};# hits",100,-5.,5.); - if(i_sector.second.isPixel){ - i_sector.second.ResY = resDir.make("h_ResY","residual r_{y};y_{trk}-y_{hit} [#mum];# hits",100,-0.03*10000.,0.03*10000.); - i_sector.second.NorResY = resDir.make("h_NorResY","normalized residual r_{y}/#sigma_{r,y};(y_{trk}-y_{hit})/#sigma_{r,y};# hits",100,-5.,5.); + i_sector.second.ResX = resDir.make( + "h_ResX", "residual r_{x};x_{trk}-x_{hit} [#mum];# hits", 100, -0.03 * 10000., 0.03 * 10000.); + i_sector.second.NorResX = resDir.make( + "h_NorResX", "normalized residual r_{x}/#sigma_{r,x};(x_{trk}-x_{hit})/#sigma_{r,x};# hits", 100, -5., 5.); + if (i_sector.second.isPixel) { + i_sector.second.ResY = resDir.make( + "h_ResY", "residual r_{y};y_{trk}-y_{hit} [#mum];# hits", 100, -0.03 * 10000., 0.03 * 10000.); + i_sector.second.NorResY = resDir.make( + "h_NorResY", "normalized residual r_{y}/#sigma_{r,y};(y_{trk}-y_{hit})/#sigma_{r,y};# hits", 100, -5., 5.); } } } - // ----------------------------------------------------------------------------------------------------------- -void -ApeEstimator::bookTrackHists(){ +void ApeEstimator::bookTrackHists() { bool zoomHists(parameterSet_.getParameter("zoomHists")); - + int trackSizeBins = zoomHists ? 6 : 201; - double trackSizeMax = trackSizeBins -1; - + double trackSizeMax = trackSizeBins - 1; + double chi2Max = zoomHists ? 100. : 2000.; double norChi2Max = zoomHists ? 5. : 1000.; double d0max = zoomHists ? 0.02 : 40.; // cosmics: 100.|100. double dzmax = zoomHists ? 15. : 100.; // cosmics: 200.|600. double pMax = zoomHists ? 200. : 2000.; - + edm::Service fileService; TFileDirectory evtDir = fileService->mkdir("EventVariables"); - tkDetector_.TrkSize = evtDir.make("h_trackSize","# tracks [all];# tracks;# events",trackSizeBins,-1,trackSizeMax); - tkDetector_.TrkSizeGood = evtDir.make("h_trackSizeGood","# tracks [good];# tracks;# events",trackSizeBins,-1,trackSizeMax); + tkDetector_.TrkSize = + evtDir.make("h_trackSize", "# tracks [all];# tracks;# events", trackSizeBins, -1, trackSizeMax); + tkDetector_.TrkSizeGood = + evtDir.make("h_trackSizeGood", "# tracks [good];# tracks;# events", trackSizeBins, -1, trackSizeMax); TFileDirectory trkDir = fileService->mkdir("TrackVariables"); - tkDetector_.HitsSize = trkDir.make("h_hitsSize","# hits;# hits;# tracks",51,-1,50); - tkDetector_.HitsValid = trkDir.make("h_hitsValid","# hits [valid];# hits [valid];# tracks",51,-1,50); - tkDetector_.HitsInvalid = trkDir.make("h_hitsInvalid","# hits [invalid];# hits [invalid];# tracks",21,-1,20); - tkDetector_.Hits2D = trkDir.make("h_hits2D","# hits [2D];# hits [2D];# tracks",21,-1,20); - tkDetector_.LayersMissed = trkDir.make("h_layersMissed","# layers [missed];# layers [missed];# tracks",11,-1,10); - tkDetector_.HitsPixel = trkDir.make("h_hitsPixel","# hits [pixel];# hits [pixel];# tracks",11,-1,10); - tkDetector_.HitsStrip = trkDir.make("h_hitsStrip","# hits [strip];# hits [strip];# tracks",41,-1,40); - tkDetector_.Charge = trkDir.make("h_charge","charge q;q [e];# tracks",5,-2,3); - tkDetector_.Chi2 = trkDir.make("h_chi2"," #chi^{2};#chi^{2};# tracks",100,0,chi2Max); - tkDetector_.Ndof = trkDir.make("h_ndof","# degrees of freedom f;f;# tracks",101,-1,100); - tkDetector_.NorChi2 = trkDir.make("h_norChi2","normalized #chi^{2};#chi^{2}/f;# tracks",200,0,norChi2Max); - tkDetector_.Prob = trkDir.make("h_prob"," #chi^{2} probability;prob(#chi^{2},f);# tracks",50,0,1); - tkDetector_.Eta = trkDir.make("h_eta","pseudorapidity #eta;#eta;# tracks",100,-5,5); - tkDetector_.EtaErr = trkDir.make("h_etaErr","Error of #eta;#sigma(#eta);# tracks",100,0,0.001); - tkDetector_.EtaSig = trkDir.make("h_etaSig","Significance of #eta;#eta/#sigma(#eta);# tracks",100,-20000,20000); - tkDetector_.Theta = trkDir.make("h_theta","polar angle #theta;#theta [ ^{o}];# tracks",100,-10,190); - tkDetector_.Phi = trkDir.make("h_phi","azimuth angle #phi;#phi [ ^{o}];# tracks",190,-190,190); - tkDetector_.PhiErr = trkDir.make("h_phiErr","Error of #phi;#sigma(#phi) [ ^{o}];# tracks",100,0,0.04); - tkDetector_.PhiSig = trkDir.make("h_phiSig","Significance of #phi;#phi/#sigma(#phi) [ ^{o}];# tracks",100,-50000,50000); - tkDetector_.D0Beamspot = trkDir.make("h_d0Beamspot","Closest approach d_{0} wrt. beamspot;d_{0, BS} [cm];# tracks",200,-d0max,d0max); - tkDetector_.D0BeamspotErr = trkDir.make("h_d0BeamspotErr","Error of d_{0, BS};#sigma(d_{0, BS}) [cm];# tracks",200,0,0.01); - tkDetector_.D0BeamspotSig = trkDir.make("h_d0BeamspotSig","Significance of d_{0, BS};d_{0, BS}/#sigma(d_{0, BS});# tracks",100,-5,5); - tkDetector_.Dz = trkDir.make("h_dz","Closest approach d_{z};d_{z} [cm];# tracks",200,-dzmax,dzmax); - tkDetector_.DzErr = trkDir.make("h_dzErr","Error of d_{z};#sigma(d_{z}) [cm];# tracks",200,0,0.01); - tkDetector_.DzSig = trkDir.make("h_dzSig","Significance of d_{z};d_{z}/#sigma(d_{z});# tracks",100,-10000,10000); - tkDetector_.Pt = trkDir.make("h_pt","transverse momentum p_{t};p_{t} [GeV];# tracks",100,0,pMax); - tkDetector_.PtErr = trkDir.make("h_ptErr","Error of p_{t};#sigma(p_{t}) [GeV];# tracks",100,0,1.6); - tkDetector_.PtSig = trkDir.make("h_ptSig","Significance of p_{t};p_{t}/#sigma(p_{t});# tracks",100,0,200); - tkDetector_.P = trkDir.make("h_p","momentum magnitude |p|;|p| [GeV];# tracks",100,0,pMax); - tkDetector_.MeanAngle = trkDir.make("h_meanAngle","mean angle on module <#phi_{module}>;<#phi_{module}> [ ^{o}];# tracks",100,-5,95); - tkDetector_.HitsGood = trkDir.make("h_hitsGood","# hits [good];# hits [good];# tracks",51,-1,50); - - tkDetector_.MeanAngleVsHits = trkDir.make("h2_meanAngleVsHits","<#phi_{module}> vs. # hits;# hits;<#phi_{module}> [ ^{o}]",51,-1,50,50,-5,95); - tkDetector_.HitsGoodVsHitsValid = trkDir.make("h2_hitsGoodVsHitsValid","# hits [good] vs. # hits [valid];# hits [valid];# hits [good]",51,-1,50,51,-1,50); - tkDetector_.HitsPixelVsEta = trkDir.make("h2_hitsPixelVsEta","# hits [pixel] vs. #eta;#eta;# hits [pixel]",60,-3,3,11,-1,10); - tkDetector_.HitsPixelVsTheta = trkDir.make("h2_hitsPixelVsTheta","# hits [pixel] vs. #theta;#theta;# hits [pixel]",100,-10,190,11,-1,10); - tkDetector_.HitsStripVsEta = trkDir.make("h2_hitsStripVsEta","# hits [strip] vs. #eta;#eta;# hits [strip]",60,-3,3,31,-1,40); - tkDetector_.HitsStripVsTheta = trkDir.make("h2_hitsStripVsTheta","# hits [strip] vs. #theta;#theta;# hits [strip]",100,-10,190,31,-1,40); - tkDetector_.PtVsEta = trkDir.make("h2_ptVsEta","p_{t} vs. #eta;#eta;p_{t} [GeV]",60,-3,3,100,0,pMax); - tkDetector_.PtVsTheta = trkDir.make("h2_ptVsTheta","p_{t} vs. #theta;#theta;p_{t} [GeV]",100,-10,190,100,0,pMax); - - tkDetector_.PMeanAngleVsHits = trkDir.make("p_meanAngleVsHits","<#phi_{module}> vs. # hits;# hits;<#phi_{module}> [ ^{o}]",51,-1,50); - tkDetector_.PHitsGoodVsHitsValid = trkDir.make("p_hitsGoodVsHitsValid","# hits [good] vs. # hits [valid];# hits [valid];# hits [good]",51,-1,50); - tkDetector_.PHitsPixelVsEta = trkDir.make("p_hitsPixelVsEta","# hits [pixel] vs. #eta;#eta;# hits [pixel]",60,-3,3); - tkDetector_.PHitsPixelVsTheta = trkDir.make("p_hitsPixelVsTheta","# hits [pixel] vs. #theta;#theta;# hits [pixel]",100,-10,190); - tkDetector_.PHitsStripVsEta = trkDir.make("p_hitsStripVsEta","# hits [strip] vs. #eta;#eta;# hits [strip]",60,-3,3); - tkDetector_.PHitsStripVsTheta = trkDir.make("p_hitsStripVsTheta","# hits [strip] vs. #theta;#theta;# hits [strip]",100,-10,190); - tkDetector_.PPtVsEta = trkDir.make("p_ptVsEta","p_{t} vs. #eta;#eta;p_{t} [GeV]",60,-3,3); - tkDetector_.PPtVsTheta = trkDir.make("p_ptVsTheta","p_{t} vs. #theta;#theta;p_{t} [GeV]",100,-10,190); + tkDetector_.HitsSize = trkDir.make("h_hitsSize", "# hits;# hits;# tracks", 51, -1, 50); + tkDetector_.HitsValid = trkDir.make("h_hitsValid", "# hits [valid];# hits [valid];# tracks", 51, -1, 50); + tkDetector_.HitsInvalid = + trkDir.make("h_hitsInvalid", "# hits [invalid];# hits [invalid];# tracks", 21, -1, 20); + tkDetector_.Hits2D = trkDir.make("h_hits2D", "# hits [2D];# hits [2D];# tracks", 21, -1, 20); + tkDetector_.LayersMissed = + trkDir.make("h_layersMissed", "# layers [missed];# layers [missed];# tracks", 11, -1, 10); + tkDetector_.HitsPixel = trkDir.make("h_hitsPixel", "# hits [pixel];# hits [pixel];# tracks", 11, -1, 10); + tkDetector_.HitsStrip = trkDir.make("h_hitsStrip", "# hits [strip];# hits [strip];# tracks", 41, -1, 40); + tkDetector_.Charge = trkDir.make("h_charge", "charge q;q [e];# tracks", 5, -2, 3); + tkDetector_.Chi2 = trkDir.make("h_chi2", " #chi^{2};#chi^{2};# tracks", 100, 0, chi2Max); + tkDetector_.Ndof = trkDir.make("h_ndof", "# degrees of freedom f;f;# tracks", 101, -1, 100); + tkDetector_.NorChi2 = trkDir.make("h_norChi2", "normalized #chi^{2};#chi^{2}/f;# tracks", 200, 0, norChi2Max); + tkDetector_.Prob = trkDir.make("h_prob", " #chi^{2} probability;prob(#chi^{2},f);# tracks", 50, 0, 1); + tkDetector_.Eta = trkDir.make("h_eta", "pseudorapidity #eta;#eta;# tracks", 100, -5, 5); + tkDetector_.EtaErr = trkDir.make("h_etaErr", "Error of #eta;#sigma(#eta);# tracks", 100, 0, 0.001); + tkDetector_.EtaSig = + trkDir.make("h_etaSig", "Significance of #eta;#eta/#sigma(#eta);# tracks", 100, -20000, 20000); + tkDetector_.Theta = trkDir.make("h_theta", "polar angle #theta;#theta [ ^{o}];# tracks", 100, -10, 190); + tkDetector_.Phi = trkDir.make("h_phi", "azimuth angle #phi;#phi [ ^{o}];# tracks", 190, -190, 190); + tkDetector_.PhiErr = trkDir.make("h_phiErr", "Error of #phi;#sigma(#phi) [ ^{o}];# tracks", 100, 0, 0.04); + tkDetector_.PhiSig = + trkDir.make("h_phiSig", "Significance of #phi;#phi/#sigma(#phi) [ ^{o}];# tracks", 100, -50000, 50000); + tkDetector_.D0Beamspot = trkDir.make( + "h_d0Beamspot", "Closest approach d_{0} wrt. beamspot;d_{0, BS} [cm];# tracks", 200, -d0max, d0max); + tkDetector_.D0BeamspotErr = + trkDir.make("h_d0BeamspotErr", "Error of d_{0, BS};#sigma(d_{0, BS}) [cm];# tracks", 200, 0, 0.01); + tkDetector_.D0BeamspotSig = trkDir.make( + "h_d0BeamspotSig", "Significance of d_{0, BS};d_{0, BS}/#sigma(d_{0, BS});# tracks", 100, -5, 5); + tkDetector_.Dz = trkDir.make("h_dz", "Closest approach d_{z};d_{z} [cm];# tracks", 200, -dzmax, dzmax); + tkDetector_.DzErr = trkDir.make("h_dzErr", "Error of d_{z};#sigma(d_{z}) [cm];# tracks", 200, 0, 0.01); + tkDetector_.DzSig = + trkDir.make("h_dzSig", "Significance of d_{z};d_{z}/#sigma(d_{z});# tracks", 100, -10000, 10000); + tkDetector_.Pt = trkDir.make("h_pt", "transverse momentum p_{t};p_{t} [GeV];# tracks", 100, 0, pMax); + tkDetector_.PtErr = trkDir.make("h_ptErr", "Error of p_{t};#sigma(p_{t}) [GeV];# tracks", 100, 0, 1.6); + tkDetector_.PtSig = trkDir.make("h_ptSig", "Significance of p_{t};p_{t}/#sigma(p_{t});# tracks", 100, 0, 200); + tkDetector_.P = trkDir.make("h_p", "momentum magnitude |p|;|p| [GeV];# tracks", 100, 0, pMax); + tkDetector_.MeanAngle = trkDir.make( + "h_meanAngle", "mean angle on module <#phi_{module}>;<#phi_{module}> [ ^{o}];# tracks", 100, -5, 95); + tkDetector_.HitsGood = trkDir.make("h_hitsGood", "# hits [good];# hits [good];# tracks", 51, -1, 50); + + tkDetector_.MeanAngleVsHits = trkDir.make( + "h2_meanAngleVsHits", "<#phi_{module}> vs. # hits;# hits;<#phi_{module}> [ ^{o}]", 51, -1, 50, 50, -5, 95); + tkDetector_.HitsGoodVsHitsValid = + trkDir.make("h2_hitsGoodVsHitsValid", + "# hits [good] vs. # hits [valid];# hits [valid];# hits [good]", + 51, + -1, + 50, + 51, + -1, + 50); + tkDetector_.HitsPixelVsEta = + trkDir.make("h2_hitsPixelVsEta", "# hits [pixel] vs. #eta;#eta;# hits [pixel]", 60, -3, 3, 11, -1, 10); + tkDetector_.HitsPixelVsTheta = trkDir.make( + "h2_hitsPixelVsTheta", "# hits [pixel] vs. #theta;#theta;# hits [pixel]", 100, -10, 190, 11, -1, 10); + tkDetector_.HitsStripVsEta = + trkDir.make("h2_hitsStripVsEta", "# hits [strip] vs. #eta;#eta;# hits [strip]", 60, -3, 3, 31, -1, 40); + tkDetector_.HitsStripVsTheta = trkDir.make( + "h2_hitsStripVsTheta", "# hits [strip] vs. #theta;#theta;# hits [strip]", 100, -10, 190, 31, -1, 40); + tkDetector_.PtVsEta = trkDir.make("h2_ptVsEta", "p_{t} vs. #eta;#eta;p_{t} [GeV]", 60, -3, 3, 100, 0, pMax); + tkDetector_.PtVsTheta = + trkDir.make("h2_ptVsTheta", "p_{t} vs. #theta;#theta;p_{t} [GeV]", 100, -10, 190, 100, 0, pMax); + + tkDetector_.PMeanAngleVsHits = trkDir.make( + "p_meanAngleVsHits", "<#phi_{module}> vs. # hits;# hits;<#phi_{module}> [ ^{o}]", 51, -1, 50); + tkDetector_.PHitsGoodVsHitsValid = trkDir.make( + "p_hitsGoodVsHitsValid", "# hits [good] vs. # hits [valid];# hits [valid];# hits [good]", 51, -1, 50); + tkDetector_.PHitsPixelVsEta = + trkDir.make("p_hitsPixelVsEta", "# hits [pixel] vs. #eta;#eta;# hits [pixel]", 60, -3, 3); + tkDetector_.PHitsPixelVsTheta = + trkDir.make("p_hitsPixelVsTheta", "# hits [pixel] vs. #theta;#theta;# hits [pixel]", 100, -10, 190); + tkDetector_.PHitsStripVsEta = + trkDir.make("p_hitsStripVsEta", "# hits [strip] vs. #eta;#eta;# hits [strip]", 60, -3, 3); + tkDetector_.PHitsStripVsTheta = + trkDir.make("p_hitsStripVsTheta", "# hits [strip] vs. #theta;#theta;# hits [strip]", 100, -10, 190); + tkDetector_.PPtVsEta = trkDir.make("p_ptVsEta", "p_{t} vs. #eta;#eta;p_{t} [GeV]", 60, -3, 3); + tkDetector_.PPtVsTheta = trkDir.make("p_ptVsTheta", "p_{t} vs. #theta;#theta;p_{t} [GeV]", 100, -10, 190); } - - // ----------------------------------------------------------------------------------------------------------- +TrackStruct::TrackParameterStruct ApeEstimator::fillTrackVariables(const reco::Track& track, + const Trajectory& traj, + const reco::BeamSpot& beamSpot) { + const math::XYZPoint beamPoint(beamSpot.x0(), beamSpot.y0(), beamSpot.z0()); + double d0BeamspotErr = + std::sqrt(track.d0Error() * track.d0Error() + 0.5 * beamSpot.BeamWidthX() * beamSpot.BeamWidthX() + + 0.5 * beamSpot.BeamWidthY() * beamSpot.BeamWidthY()); -TrackStruct::TrackParameterStruct -ApeEstimator::fillTrackVariables(const reco::Track& track, const Trajectory& traj, const reco::BeamSpot& beamSpot){ - const math::XYZPoint beamPoint(beamSpot.x0(),beamSpot.y0(), beamSpot.z0()); - double d0BeamspotErr = std::sqrt( track.d0Error()*track.d0Error() + 0.5*beamSpot.BeamWidthX()*beamSpot.BeamWidthX() + 0.5*beamSpot.BeamWidthY()*beamSpot.BeamWidthY() ); - const static TrajectoryStateCombiner tsoscomb; - + const reco::HitPattern& hitPattern(track.hitPattern()); - + TrackStruct::TrackParameterStruct trkParams; - - trkParams.hitsSize = track.recHitsSize(); - trkParams.hitsValid = track.found(); // invalid is every hit from every single module that expects a hit - trkParams.hitsInvalid = trkParams.hitsSize-trkParams.hitsValid; - trkParams.layersMissed = track.lost(); // lost hit means, that a crossed layer doesn't contain a hit (can be more than one invalid hit) - trkParams.hitsPixel = hitPattern.numberOfValidPixelHits(); - trkParams.hitsStrip = hitPattern.numberOfValidStripHits(); - trkParams.charge = track.charge(); - trkParams.chi2 = track.chi2(); - trkParams.ndof = track.ndof(); - trkParams.norChi2 = trkParams.chi2/trkParams.ndof; - trkParams.prob = TMath::Prob(trkParams.chi2,trkParams.ndof); - trkParams.eta = track.eta(); - trkParams.etaErr = track.etaError(); - trkParams.theta = track.theta(); - trkParams.phi = track.phi(); - trkParams.phiErr = track.phiError(); - trkParams.d0 = track.d0(); - trkParams.d0Beamspot = -1.*track.dxy(beamPoint); + + trkParams.hitsSize = track.recHitsSize(); + trkParams.hitsValid = track.found(); // invalid is every hit from every single module that expects a hit + trkParams.hitsInvalid = trkParams.hitsSize - trkParams.hitsValid; + trkParams.layersMissed = + track.lost(); // lost hit means, that a crossed layer doesn't contain a hit (can be more than one invalid hit) + trkParams.hitsPixel = hitPattern.numberOfValidPixelHits(); + trkParams.hitsStrip = hitPattern.numberOfValidStripHits(); + trkParams.charge = track.charge(); + trkParams.chi2 = track.chi2(); + trkParams.ndof = track.ndof(); + trkParams.norChi2 = trkParams.chi2 / trkParams.ndof; + trkParams.prob = TMath::Prob(trkParams.chi2, trkParams.ndof); + trkParams.eta = track.eta(); + trkParams.etaErr = track.etaError(); + trkParams.theta = track.theta(); + trkParams.phi = track.phi(); + trkParams.phiErr = track.phiError(); + trkParams.d0 = track.d0(); + trkParams.d0Beamspot = -1. * track.dxy(beamPoint); trkParams.d0BeamspotErr = d0BeamspotErr; - trkParams.dz = track.dz(); - trkParams.dzErr = track.dzError(); - trkParams.dzBeamspot = track.dz(beamPoint); - trkParams.p = track.p(); - trkParams.pt = track.pt(); - trkParams.ptErr = track.ptError(); - + trkParams.dz = track.dz(); + trkParams.dzErr = track.dzError(); + trkParams.dzBeamspot = track.dz(beamPoint); + trkParams.p = track.p(); + trkParams.pt = track.pt(); + trkParams.ptErr = track.ptError(); + const std::vector& v_meas = traj.measurements(); - - int count2D(0); float meanPhiSensToNorm(0.F); - for(auto const & i_meas : v_meas){ + + int count2D(0); + float meanPhiSensToNorm(0.F); + for (auto const& i_meas : v_meas) { const TrajectoryMeasurement& meas = i_meas; const TransientTrackingRecHit& hit = *meas.recHit(); const TrackingRecHit& recHit = *hit.hit(); - if(this->isHit2D(recHit)) ++count2D; - - TrajectoryStateOnSurface tsos = tsoscomb(meas.forwardPredictedState(),meas.backwardPredictedState()); + if (this->isHit2D(recHit)) + ++count2D; + + TrajectoryStateOnSurface tsos = tsoscomb(meas.forwardPredictedState(), meas.backwardPredictedState()); const align::LocalVector mom(tsos.localDirection()); - meanPhiSensToNorm += atan(fabs(sqrt(mom.x()*mom.x()+mom.y()*mom.y())/mom.z())); + meanPhiSensToNorm += atan(fabs(sqrt(mom.x() * mom.x() + mom.y() * mom.y()) / mom.z())); } - meanPhiSensToNorm *= (1./static_cast(trkParams.hitsSize)); - - trkParams.hits2D = count2D; + meanPhiSensToNorm *= (1. / static_cast(trkParams.hitsSize)); + + trkParams.hits2D = count2D; trkParams.meanPhiSensToNorm = meanPhiSensToNorm; - - if(parameterSet_.getParameter("applyTrackCuts")){ + + if (parameterSet_.getParameter("applyTrackCuts")) { trackCut_ = false; - if(trkParams.hitsStrip<11 || trkParams.hits2D<2 || trkParams.hitsPixel<2 || //trkParams.hitsInvalid>2 || - trkParams.hitsStrip>35 || trkParams.hitsPixel>7 || - trkParams.norChi2>5. || - trkParams.pt<25. || trkParams.pt>150. || - std::abs(trkParams.d0Beamspot)>0.02 || std::abs(trkParams.dz)>15.)trackCut_ = true; - } - else{ + if (trkParams.hitsStrip < 11 || trkParams.hits2D < 2 || trkParams.hitsPixel < 2 || //trkParams.hitsInvalid>2 || + trkParams.hitsStrip > 35 || trkParams.hitsPixel > 7 || trkParams.norChi2 > 5. || trkParams.pt < 25. || + trkParams.pt > 150. || std::abs(trkParams.d0Beamspot) > 0.02 || std::abs(trkParams.dz) > 15.) + trackCut_ = true; + } else { trackCut_ = false; } - + return trkParams; } - - -TrackStruct::HitParameterStruct -ApeEstimator::fillHitVariables(const TrajectoryMeasurement& i_meas, const edm::EventSetup& iSetup){ +TrackStruct::HitParameterStruct ApeEstimator::fillHitVariables(const TrajectoryMeasurement& i_meas, + const edm::EventSetup& iSetup) { TrackStruct::HitParameterStruct hitParams; - + const static TrajectoryStateCombiner tsoscomb; - + const TrajectoryMeasurement& meas = i_meas; const TransientTrackingRecHit& hit = *meas.recHit(); const TrackingRecHit& recHit = *hit.hit(); - const TrajectoryStateOnSurface& tsos = tsoscomb(meas.forwardPredictedState(),meas.backwardPredictedState()); - + const TrajectoryStateOnSurface& tsos = tsoscomb(meas.forwardPredictedState(), meas.backwardPredictedState()); + const DetId& detId(hit.geographicalId()); - const DetId::Detector& detector = detId.det(); if(detector != DetId::Tracker){hitParams.hitState = TrackStruct::notInTracker; return hitParams;} + const DetId::Detector& detector = detId.det(); + if (detector != DetId::Tracker) { + hitParams.hitState = TrackStruct::notInTracker; + return hitParams; + } const uint32_t rawId(detId.rawId()); - - for(auto & i_sector : m_tkSector_){ - for(auto const & i_rawId : i_sector.second.v_rawId){ - if(rawId==i_rawId){hitParams.v_sector.push_back(i_sector.first); break;} + + for (auto& i_sector : m_tkSector_) { + for (auto const& i_rawId : i_sector.second.v_rawId) { + if (rawId == i_rawId) { + hitParams.v_sector.push_back(i_sector.first); + break; + } } } - + const align::LocalVector& mom(tsos.localDirection()); int xMomentum(0), yMomentum(0), zMomentum(0); - xMomentum = mom.x()>0. ? 1 : -1; - yMomentum = mom.y()>0. ? 1 : -1; - zMomentum = mom.z()>0. ? 1 : -1; - float phiSensX = std::atan(std::fabs(mom.x()/mom.z()))*static_cast(m_tkTreeVar_[rawId].vDirection); // check for orientation of E- and B- Field (thoughts for barrel) - float phiSensY = std::atan(std::fabs(mom.y()/mom.z()))*static_cast(m_tkTreeVar_[rawId].vDirection); - hitParams.phiSens = std::atan(std::fabs(std::sqrt(mom.x()*mom.x()+mom.y()*mom.y())/mom.z())); - hitParams.phiSensX = (xMomentum==zMomentum ? phiSensX : -phiSensX ); - hitParams.phiSensY = (yMomentum==zMomentum ? phiSensY : -phiSensY ); - - if(!hit.isValid()){ - hitParams.hitState = TrackStruct::invalid; + xMomentum = mom.x() > 0. ? 1 : -1; + yMomentum = mom.y() > 0. ? 1 : -1; + zMomentum = mom.z() > 0. ? 1 : -1; + float phiSensX = + std::atan(std::fabs(mom.x() / mom.z())) * + static_cast( + m_tkTreeVar_[rawId].vDirection); // check for orientation of E- and B- Field (thoughts for barrel) + float phiSensY = std::atan(std::fabs(mom.y() / mom.z())) * static_cast(m_tkTreeVar_[rawId].vDirection); + hitParams.phiSens = std::atan(std::fabs(std::sqrt(mom.x() * mom.x() + mom.y() * mom.y()) / mom.z())); + hitParams.phiSensX = (xMomentum == zMomentum ? phiSensX : -phiSensX); + hitParams.phiSensY = (yMomentum == zMomentum ? phiSensY : -phiSensY); + + if (!hit.isValid()) { + hitParams.hitState = TrackStruct::invalid; return hitParams; } - + // Get local positions and errors of hit and track const LocalPoint& lPHit = hit.localPosition(); const LocalPoint& lPTrk = tsos.localPosition(); - + // use APE also for the hit error, while APE is automatically included in tsos error // // no need to add APE to hitError anymore by Ajay 27 Oct 2014 const LocalError& errHitApe = hit.localPositionError(); // now sum of CPE+APE as said by MARCO? LocalError errorWithoutAPE; - + bool Pixel(false); bool Strip(false); - if( m_tkTreeVar_[rawId].subdetId==PixelSubdetector::PixelBarrel || m_tkTreeVar_[rawId].subdetId==PixelSubdetector::PixelEndcap){ + if (m_tkTreeVar_[rawId].subdetId == PixelSubdetector::PixelBarrel || + m_tkTreeVar_[rawId].subdetId == PixelSubdetector::PixelEndcap) { Pixel = true; - }else if( m_tkTreeVar_[rawId].subdetId==StripSubdetector::TIB || m_tkTreeVar_[rawId].subdetId==StripSubdetector::TOB || - m_tkTreeVar_[rawId].subdetId==StripSubdetector::TID || m_tkTreeVar_[rawId].subdetId==StripSubdetector::TEC){ + } else if (m_tkTreeVar_[rawId].subdetId == StripSubdetector::TIB || + m_tkTreeVar_[rawId].subdetId == StripSubdetector::TOB || + m_tkTreeVar_[rawId].subdetId == StripSubdetector::TID || + m_tkTreeVar_[rawId].subdetId == StripSubdetector::TEC) { Strip = true; - }else{ - edm::LogWarning("FillHitVariables")<<"cant identify wether hit is from pixel or strip"; - hitParams.hitState = TrackStruct::invalid; return hitParams; + } else { + edm::LogWarning("FillHitVariables") << "cant identify wether hit is from pixel or strip"; + hitParams.hitState = TrackStruct::invalid; + return hitParams; } - if(!hit.detUnit()){ - hitParams.hitState = TrackStruct::invalid; + if (!hit.detUnit()) { + hitParams.hitState = TrackStruct::invalid; return hitParams; - } // is it a single physical module? + } // is it a single physical module? const GeomDetUnit& detUnit = *hit.detUnit(); - if(Pixel){ - if(!dynamic_cast(&detUnit.type().topology())){ - hitParams.hitState = TrackStruct::invalid; + if (Pixel) { + if (!dynamic_cast(&detUnit.type().topology())) { + hitParams.hitState = TrackStruct::invalid; return hitParams; } - const PixelGeomDetUnit * pixelDet = (const PixelGeomDetUnit*)(&detUnit); + const PixelGeomDetUnit* pixelDet = (const PixelGeomDetUnit*)(&detUnit); const LocalError& lape = pixelDet->localAlignmentError(); - if (lape.valid()){ - errorWithoutAPE = LocalError(errHitApe.xx() -lape.xx(), errHitApe.xy()- lape.xy(), errHitApe.yy()-lape.yy()); + if (lape.valid()) { + errorWithoutAPE = LocalError(errHitApe.xx() - lape.xx(), errHitApe.xy() - lape.xy(), errHitApe.yy() - lape.yy()); } } - if(Strip){ - if(!dynamic_cast(&detUnit.type().topology())){ - hitParams.hitState = TrackStruct::invalid; + if (Strip) { + if (!dynamic_cast(&detUnit.type().topology())) { + hitParams.hitState = TrackStruct::invalid; return hitParams; } - const StripGeomDetUnit * stripDet = (const StripGeomDetUnit*)(&detUnit); + const StripGeomDetUnit* stripDet = (const StripGeomDetUnit*)(&detUnit); const LocalError& lape = stripDet->localAlignmentError(); - if (lape.valid()) - { errorWithoutAPE = LocalError(errHitApe.xx() -lape.xx(), errHitApe.xy()- lape.xy(), errHitApe.yy()-lape.yy()); + if (lape.valid()) { + errorWithoutAPE = LocalError(errHitApe.xx() - lape.xx(), errHitApe.xy() - lape.xy(), errHitApe.yy() - lape.yy()); } } - const LocalError& errHitWoApe = errorWithoutAPE; const LocalError& errTrk = tsos.localError().positionError(); - + const StatePositionAndError2 positionAndError2Hit = this->positionAndError2(lPHit, errHitApe, hit); const StatePositionAndError2 positionAndError2HitWoApe = this->positionAndError2(lPHit, errHitWoApe, hit); - edm::LogInfo("CalculateAPE")<<"errHitWoApe "<positionAndError2(lPTrk, errTrk, hit); - + const TrackStruct::HitState& stateHit(positionAndError2Hit.first); const TrackStruct::HitState& stateHitWoApe(positionAndError2HitWoApe.first); const TrackStruct::HitState& stateTrk(positionAndError2Trk.first); - - if(stateHit==TrackStruct::invalid || stateHitWoApe==TrackStruct::invalid || stateTrk==TrackStruct::invalid){ + + if (stateHit == TrackStruct::invalid || stateHitWoApe == TrackStruct::invalid || stateTrk == TrackStruct::invalid) { hitParams.hitState = TrackStruct::invalid; return hitParams; - }else if(stateHit==TrackStruct::negativeError || stateHitWoApe==TrackStruct::negativeError || stateTrk==TrackStruct::negativeError){ + } else if (stateHit == TrackStruct::negativeError || stateHitWoApe == TrackStruct::negativeError || + stateTrk == TrackStruct::negativeError) { ++counter1; // Do not print error message by default //std::stringstream ss_error; @@ -1143,265 +1467,271 @@ ApeEstimator::fillHitVariables(const TrajectoryMeasurement& i_meas, const edm::E hitParams.hitState = TrackStruct::negativeError; return hitParams; } - - + // Calculate residuals - + const float xHit = positionAndError2Hit.second.posX; const float xTrk = positionAndError2Trk.second.posX; const float yHit = positionAndError2Hit.second.posY; const float yTrk = positionAndError2Trk.second.posY; - + const float errXHit2(positionAndError2Hit.second.errX2); const float errXHitWoApe2(positionAndError2HitWoApe.second.errX2); const float errXTrk2(positionAndError2Trk.second.errX2); const float errYHit2(positionAndError2Hit.second.errY2); const float errYHitWoApe2(positionAndError2HitWoApe.second.errY2); const float errYTrk2(positionAndError2Trk.second.errY2); - + const float errXHit = std::sqrt(positionAndError2Hit.second.errX2); const float errXHitWoApe = std::sqrt(positionAndError2HitWoApe.second.errX2); const float errXTrk = std::sqrt(positionAndError2Trk.second.errX2); const float errYHit = std::sqrt(positionAndError2Hit.second.errY2); const float errYHitWoApe = std::sqrt(positionAndError2HitWoApe.second.errY2); const float errYTrk = std::sqrt(positionAndError2Trk.second.errY2); - + const float resX = xTrk - xHit; const float resY = yTrk - yHit; - + const float errX = std::sqrt(errXHit2 + errXTrk2); const float errXWoApe2 = errXHitWoApe2 + errXTrk2; const float errXWoApe = std::sqrt(errXWoApe2); const float errY = std::sqrt(errYHit2 + errYTrk2); const float errYWoApe2 = errYHitWoApe2 + errYTrk2; const float errYWoApe = std::sqrt(errYWoApe2); - - const float norResX = resX/errX; - const float norResY = resY/errY; - - + + const float norResX = resX / errX; + const float norResY = resY / errY; + // Take global orientation into account for residuals (sign is not important for errors) - + float resXprime(999.F), resYprime(999.F), norResXprime(999.F), norResYprime(999.F); - if(m_tkTreeVar_[rawId].uDirection == 1){ - resXprime = resX; + if (m_tkTreeVar_[rawId].uDirection == 1) { + resXprime = resX; norResXprime = norResX; - }else if(m_tkTreeVar_[rawId].uDirection == -1){ - resXprime = -resX; + } else if (m_tkTreeVar_[rawId].uDirection == -1) { + resXprime = -resX; norResXprime = -norResX; - }else{ - edm::LogError("FillHitVariables")<<"Incorrect value of uDirection, which gives global module orientation"; - hitParams.hitState = TrackStruct::invalid; + } else { + edm::LogError("FillHitVariables") << "Incorrect value of uDirection, which gives global module orientation"; + hitParams.hitState = TrackStruct::invalid; return hitParams; } - if(m_tkTreeVar_[rawId].vDirection == 1){ - resYprime = resY; + if (m_tkTreeVar_[rawId].vDirection == 1) { + resYprime = resY; norResYprime = norResY; - }else if(m_tkTreeVar_[rawId].vDirection == -1){ - resYprime = -resY; + } else if (m_tkTreeVar_[rawId].vDirection == -1) { + resYprime = -resY; norResYprime = -norResY; - }else{ - edm::LogError("FillHitVariables")<<"Incorrect value of vDirection, which gives global module orientation"; - hitParams.hitState = TrackStruct::invalid; + } else { + edm::LogError("FillHitVariables") << "Incorrect value of vDirection, which gives global module orientation"; + hitParams.hitState = TrackStruct::invalid; return hitParams; } - + hitParams.xHit = xHit; hitParams.xTrk = xTrk; - + hitParams.errXHit = errXHit; hitParams.errXHitWoApe = errXHitWoApe; hitParams.errXTrk = errXTrk; - - hitParams.errX2 = errX*errX; + + hitParams.errX2 = errX * errX; hitParams.errX = errX; hitParams.errXWoApe = errXWoApe; hitParams.resX = resXprime; hitParams.norResX = norResXprime; - - const float norResX2(norResXprime*norResXprime); - hitParams.probX = TMath::Prob(norResX2,1); - - + + const float norResX2(norResXprime * norResXprime); + hitParams.probX = TMath::Prob(norResX2, 1); + hitParams.yHit = yHit; hitParams.yTrk = yTrk; - + hitParams.errYHit = errYHit; hitParams.errYHitWoApe = errYHitWoApe; hitParams.errYTrk = errYTrk; - - hitParams.errY2 = errY*errY; + + hitParams.errY2 = errY * errY; hitParams.errY = errY; hitParams.errYWoApe = errYWoApe; hitParams.resY = resYprime; hitParams.norResY = norResYprime; - - const float norResY2(norResYprime*norResYprime); - hitParams.probY = TMath::Prob(norResY2,1); - - + + const float norResY2(norResYprime * norResYprime); + hitParams.probY = TMath::Prob(norResY2, 1); + // Cluster parameters - - if(m_tkTreeVar_[rawId].subdetId==PixelSubdetector::PixelBarrel || m_tkTreeVar_[rawId].subdetId==PixelSubdetector::PixelEndcap){ + + if (m_tkTreeVar_[rawId].subdetId == PixelSubdetector::PixelBarrel || + m_tkTreeVar_[rawId].subdetId == PixelSubdetector::PixelEndcap) { const SiPixelRecHit& pixelHit = dynamic_cast(recHit); const SiPixelCluster& pixelCluster = *pixelHit.cluster(); - + hitParams.chargePixel = pixelCluster.charge(); hitParams.widthX = pixelCluster.sizeX(); hitParams.baryStripX = pixelCluster.x(); hitParams.widthY = pixelCluster.sizeY(); hitParams.baryStripY = pixelCluster.y(); - + hitParams.clusterProbabilityXY = pixelHit.clusterProbability(0); hitParams.clusterProbabilityQ = pixelHit.clusterProbability(2); hitParams.clusterProbabilityXYQ = pixelHit.clusterProbability(1); hitParams.logClusterProbability = std::log10(hitParams.clusterProbabilityXY); - + hitParams.isOnEdge = pixelHit.isOnEdge(); hitParams.hasBadPixels = pixelHit.hasBadPixels(); hitParams.spansTwoRoc = pixelHit.spansTwoROCs(); hitParams.qBin = pixelHit.qBin(); - + hitParams.isPixelHit = true; - }else if( m_tkTreeVar_[rawId].subdetId==StripSubdetector::TIB || m_tkTreeVar_[rawId].subdetId==StripSubdetector::TOB || - m_tkTreeVar_[rawId].subdetId==StripSubdetector::TID || m_tkTreeVar_[rawId].subdetId==StripSubdetector::TEC){ - if(!(dynamic_cast(&recHit) || dynamic_cast(&recHit))){ - edm::LogError("FillHitVariables")<<"RecHit in Strip is 'Matched' or 'Projected', but here all should be monohits per module"; - hitParams.hitState = TrackStruct::invalid; return hitParams; + } else if (m_tkTreeVar_[rawId].subdetId == StripSubdetector::TIB || + m_tkTreeVar_[rawId].subdetId == StripSubdetector::TOB || + m_tkTreeVar_[rawId].subdetId == StripSubdetector::TID || + m_tkTreeVar_[rawId].subdetId == StripSubdetector::TEC) { + if (!(dynamic_cast(&recHit) || dynamic_cast(&recHit))) { + edm::LogError("FillHitVariables") + << "RecHit in Strip is 'Matched' or 'Projected', but here all should be monohits per module"; + hitParams.hitState = TrackStruct::invalid; + return hitParams; } const SiStripCluster* clusterPtr(nullptr); - if( m_tkTreeVar_[rawId].subdetId==StripSubdetector::TIB || m_tkTreeVar_[rawId].subdetId==StripSubdetector::TOB){ - if(dynamic_cast(&recHit)){ + if (m_tkTreeVar_[rawId].subdetId == StripSubdetector::TIB || + m_tkTreeVar_[rawId].subdetId == StripSubdetector::TOB) { + if (dynamic_cast(&recHit)) { const SiStripRecHit1D& stripHit = dynamic_cast(recHit); clusterPtr = &(*stripHit.cluster()); - }else if(dynamic_cast(&recHit)){ - edm::LogWarning("FillHitVariables")<<"Data has TIB/TOB hits as SiStripRecHit2D and not 1D. Probably data is processed with CMSSW<34X. Nevertheless everything should work fine"; + } else if (dynamic_cast(&recHit)) { + edm::LogWarning("FillHitVariables") << "Data has TIB/TOB hits as SiStripRecHit2D and not 1D. Probably data is " + "processed with CMSSW<34X. Nevertheless everything should work fine"; const SiStripRecHit2D& stripHit = dynamic_cast(recHit); clusterPtr = &(*stripHit.cluster()); } - }else if( m_tkTreeVar_[rawId].subdetId==StripSubdetector::TID || m_tkTreeVar_[rawId].subdetId==StripSubdetector::TEC){ - const SiStripRecHit2D& stripHit = dynamic_cast(recHit); - clusterPtr = &(*stripHit.cluster()); + } else if (m_tkTreeVar_[rawId].subdetId == StripSubdetector::TID || + m_tkTreeVar_[rawId].subdetId == StripSubdetector::TEC) { + const SiStripRecHit2D& stripHit = dynamic_cast(recHit); + clusterPtr = &(*stripHit.cluster()); } - if(!clusterPtr){ - edm::LogError("FillHitVariables")<<"Pointer to cluster not valid!!! This should never happen..."; - hitParams.hitState = TrackStruct::invalid; return hitParams; + if (!clusterPtr) { + edm::LogError("FillHitVariables") << "Pointer to cluster not valid!!! This should never happen..."; + hitParams.hitState = TrackStruct::invalid; + return hitParams; } const SiStripCluster& stripCluster(*clusterPtr); - - const SiStripClusterInfo clusterInfo =SiStripClusterInfo(stripCluster,iSetup,rawId,std::string("")); + + const SiStripClusterInfo clusterInfo = SiStripClusterInfo(stripCluster, iSetup, rawId, std::string("")); const std::vector::const_iterator stripChargeL(clusterInfo.stripCharges().begin()); const std::vector::const_iterator stripChargeR(--(clusterInfo.stripCharges().end())); - const std::pair stripChargeLR = std::make_pair(*stripChargeL,*stripChargeR); - - hitParams.chargeStrip = clusterInfo.charge(); - hitParams.widthX = clusterInfo.width(); - hitParams.baryStripX = clusterInfo.baryStrip() +1.; - hitParams.isModuleUsable = clusterInfo.IsModuleUsable(); - hitParams.maxStrip = clusterInfo.maxStrip() +1; - hitParams.maxStripInv = m_tkTreeVar_[rawId].nStrips - hitParams.maxStrip +1; - hitParams.maxCharge = clusterInfo.maxCharge(); - hitParams.maxIndex = clusterInfo.maxIndex(); - hitParams.chargeOnEdges = static_cast(stripChargeLR.first + stripChargeLR.second)/static_cast(hitParams.chargeStrip); - hitParams.chargeAsymmetry = static_cast(stripChargeLR.first - stripChargeLR.second)/static_cast(stripChargeLR.first + stripChargeLR.second); - hitParams.chargeLRplus = static_cast(clusterInfo.chargeLR().first + clusterInfo.chargeLR().second)/static_cast(hitParams.chargeStrip); - hitParams.chargeLRminus = static_cast(clusterInfo.chargeLR().first - clusterInfo.chargeLR().second)/static_cast(hitParams.chargeStrip); - hitParams.sOverN = clusterInfo.signalOverNoise(); - + const std::pair stripChargeLR = std::make_pair(*stripChargeL, *stripChargeR); + + hitParams.chargeStrip = clusterInfo.charge(); + hitParams.widthX = clusterInfo.width(); + hitParams.baryStripX = clusterInfo.baryStrip() + 1.; + hitParams.isModuleUsable = clusterInfo.IsModuleUsable(); + hitParams.maxStrip = clusterInfo.maxStrip() + 1; + hitParams.maxStripInv = m_tkTreeVar_[rawId].nStrips - hitParams.maxStrip + 1; + hitParams.maxCharge = clusterInfo.maxCharge(); + hitParams.maxIndex = clusterInfo.maxIndex(); + hitParams.chargeOnEdges = + static_cast(stripChargeLR.first + stripChargeLR.second) / static_cast(hitParams.chargeStrip); + hitParams.chargeAsymmetry = static_cast(stripChargeLR.first - stripChargeLR.second) / + static_cast(stripChargeLR.first + stripChargeLR.second); + hitParams.chargeLRplus = static_cast(clusterInfo.chargeLR().first + clusterInfo.chargeLR().second) / + static_cast(hitParams.chargeStrip); + hitParams.chargeLRminus = static_cast(clusterInfo.chargeLR().first - clusterInfo.chargeLR().second) / + static_cast(hitParams.chargeStrip); + hitParams.sOverN = clusterInfo.signalOverNoise(); // Calculate projection length corrected by drift - if(!hit.detUnit()){ - hitParams.hitState = TrackStruct::invalid; + if (!hit.detUnit()) { + hitParams.hitState = TrackStruct::invalid; return hitParams; - } // is it a single physical module? + } // is it a single physical module? const GeomDetUnit& detUnit = *hit.detUnit(); - if(!dynamic_cast(&detUnit.type().topology())){ - hitParams.hitState = TrackStruct::invalid; + if (!dynamic_cast(&detUnit.type().topology())) { + hitParams.hitState = TrackStruct::invalid; return hitParams; } - - + edm::ESHandle magFieldHandle; iSetup.get().get(magFieldHandle); - + edm::ESHandle lorentzAngleHandle; iSetup.get().get(lorentzAngleHandle); //MODIFIED BY LOIC QUERTENMONT - - const StripGeomDetUnit * stripDet = (const StripGeomDetUnit*)(&detUnit); - const MagneticField * magField(magFieldHandle.product()); + const StripGeomDetUnit* stripDet = (const StripGeomDetUnit*)(&detUnit); + const MagneticField* magField(magFieldHandle.product()); LocalVector bField = (stripDet->surface()).toLocal(magField->inTesla(stripDet->surface().position())); - const SiStripLorentzAngle * lorentzAngle(lorentzAngleHandle.product()); + const SiStripLorentzAngle* lorentzAngle(lorentzAngleHandle.product()); float tanLorentzAnglePerTesla = lorentzAngle->getLorentzAngle(stripDet->geographicalId().rawId()); float dirX = -tanLorentzAnglePerTesla * bField.y(); float dirY = tanLorentzAnglePerTesla * bField.x(); - float dirZ = 1.; // E field always in z direction - LocalVector driftDirection(dirX,dirY,dirZ); - - + float dirZ = 1.; // E field always in z direction + LocalVector driftDirection(dirX, dirY, dirZ); + const Bounds& bounds = stripDet->specificSurface().bounds(); - float maxLength = std::sqrt(std::pow(bounds.length(),2)+std::pow(bounds.width(),2)); + float maxLength = std::sqrt(std::pow(bounds.length(), 2) + std::pow(bounds.width(), 2)); float thickness = bounds.thickness(); - - - + const StripTopology& topol = dynamic_cast(detUnit.type().topology()); LocalVector momentumDir(tsos.localDirection()); LocalPoint momentumPos(tsos.localPosition()); LocalVector scaledMomentumDir(momentumDir); - if(momentumDir.z() > 0.)scaledMomentumDir *= std::fabs(thickness/momentumDir.z()); - else if(momentumDir.z() < 0.)scaledMomentumDir *= -std::fabs(thickness/momentumDir.z()); - else scaledMomentumDir *= maxLength/momentumDir.mag(); - - float projEdge1 = topol.measurementPosition(momentumPos - 0.5*scaledMomentumDir).x(); - if(projEdge1 < 0.)projEdge1 = 0.; - else if(projEdge1 > m_tkTreeVar_[rawId].nStrips)projEdge1 = m_tkTreeVar_[rawId].nStrips; - float projEdge2 = topol.measurementPosition(momentumPos + 0.5*scaledMomentumDir).x(); - if(projEdge2 < 0.)projEdge1 = 0.; - else if(projEdge2 > m_tkTreeVar_[rawId].nStrips)projEdge1 = m_tkTreeVar_[rawId].nStrips; - - + if (momentumDir.z() > 0.) + scaledMomentumDir *= std::fabs(thickness / momentumDir.z()); + else if (momentumDir.z() < 0.) + scaledMomentumDir *= -std::fabs(thickness / momentumDir.z()); + else + scaledMomentumDir *= maxLength / momentumDir.mag(); + + float projEdge1 = topol.measurementPosition(momentumPos - 0.5 * scaledMomentumDir).x(); + if (projEdge1 < 0.) + projEdge1 = 0.; + else if (projEdge1 > m_tkTreeVar_[rawId].nStrips) + projEdge1 = m_tkTreeVar_[rawId].nStrips; + float projEdge2 = topol.measurementPosition(momentumPos + 0.5 * scaledMomentumDir).x(); + if (projEdge2 < 0.) + projEdge1 = 0.; + else if (projEdge2 > m_tkTreeVar_[rawId].nStrips) + projEdge1 = m_tkTreeVar_[rawId].nStrips; + float coveredStrips = std::fabs(projEdge2 - projEdge1); - + hitParams.projWidth = coveredStrips; - - - } - else{ - edm::LogError("FillHitVariables")<<"Incorrect subdetector ID, hit not associated to tracker"; - hitParams.hitState = TrackStruct::notInTracker; return hitParams; + + } else { + edm::LogError("FillHitVariables") << "Incorrect subdetector ID, hit not associated to tracker"; + hitParams.hitState = TrackStruct::notInTracker; + return hitParams; } - - - if(!hitParams.isModuleUsable){ - hitParams.hitState = TrackStruct::invalid; + + if (!hitParams.isModuleUsable) { + hitParams.hitState = TrackStruct::invalid; return hitParams; } - - if(hitParams.v_sector.empty()){ - hitParams.hitState = TrackStruct::notAssignedToSectors; + + if (hitParams.v_sector.empty()) { + hitParams.hitState = TrackStruct::notAssignedToSectors; return hitParams; } - + return hitParams; -//} + //} } +ApeEstimator::StatePositionAndError2 ApeEstimator::positionAndError2(const LocalPoint& localPoint, + const LocalError& localError, + const TransientTrackingRecHit& hit) { + StatePositionAndError2 vPE2 = std::make_pair(TrackStruct::invalid, PositionAndError2()); - -ApeEstimator::StatePositionAndError2 -ApeEstimator::positionAndError2(const LocalPoint& localPoint, const LocalError& localError, const TransientTrackingRecHit& hit){ - StatePositionAndError2 vPE2 = std::make_pair(TrackStruct::invalid,PositionAndError2()); - const DetId& detId(hit.geographicalId()); const uint32_t& rawId(detId.rawId()); const unsigned int& subdetId(m_tkTreeVar_[rawId].subdetId); - - if(localError.xx()<0. || localError.yy()<0.){ + + if (localError.xx() < 0. || localError.yy() < 0.) { // Do not print error message by default //edm::LogError("Negative error Value")<<"@SUB=ApeEstimator::fillHitVariables" // <<"One of the squared error methods gives negative result\n" @@ -1410,22 +1740,23 @@ ApeEstimator::positionAndError2(const LocalPoint& localPoint, const LocalError& vPE2.first = TrackStruct::negativeError; return vPE2; } - - if(subdetId==PixelSubdetector::PixelBarrel || subdetId==PixelSubdetector::PixelEndcap || - subdetId==StripSubdetector::TIB || subdetId==StripSubdetector::TOB){ + + if (subdetId == PixelSubdetector::PixelBarrel || subdetId == PixelSubdetector::PixelEndcap || + subdetId == StripSubdetector::TIB || subdetId == StripSubdetector::TOB) { // Cartesian coordinates vPE2 = std::make_pair(TrackStruct::ok, this->rectangularPositionAndError2(localPoint, localError)); - } - else if(subdetId==StripSubdetector::TID || subdetId==StripSubdetector::TEC){ + } else if (subdetId == StripSubdetector::TID || subdetId == StripSubdetector::TEC) { // Local x in radial coordinates - if(!hit.detUnit())return vPE2; // is it a single physical module? + if (!hit.detUnit()) + return vPE2; // is it a single physical module? const GeomDetUnit& detUnit = *hit.detUnit(); - - if(!dynamic_cast(&detUnit.type().topology()))return vPE2; + + if (!dynamic_cast(&detUnit.type().topology())) + return vPE2; const RadialStripTopology& topol = dynamic_cast(detUnit.type().topology()); - - MeasurementError measError = topol.measurementError(localPoint,localError); - if(measError.uu()<0. || measError.vv()<0.){ + + MeasurementError measError = topol.measurementError(localPoint, localError); + if (measError.uu() < 0. || measError.vv() < 0.) { // Do not print error message by default //edm::LogError("Negative error Value")<<"@SUB=ApeEstimator::fillHitVariables" // <<"One of the squared error methods gives negative result\n" @@ -1439,67 +1770,58 @@ ApeEstimator::positionAndError2(const LocalPoint& localPoint, const LocalError& return vPE2; } vPE2 = std::make_pair(TrackStruct::ok, this->radialPositionAndError2(localPoint, localError, topol)); - }else{ - edm::LogError("FillHitVariables")<<"Incorrect subdetector ID, hit not associated to tracker"; + } else { + edm::LogError("FillHitVariables") << "Incorrect subdetector ID, hit not associated to tracker"; } - + return vPE2; } - - -ApeEstimator::PositionAndError2 -ApeEstimator::rectangularPositionAndError2(const LocalPoint& lP, const LocalError& lE){ +ApeEstimator::PositionAndError2 ApeEstimator::rectangularPositionAndError2(const LocalPoint& lP, const LocalError& lE) { const float x(lP.x()); const float y(lP.y()); const float errX2(lE.xx()); const float errY2(lE.yy()); - + return PositionAndError2(x, y, errX2, errY2); } - - -ApeEstimator::PositionAndError2 -ApeEstimator::radialPositionAndError2(const LocalPoint& lP, const LocalError& lE, const RadialStripTopology& topol){ +ApeEstimator::PositionAndError2 ApeEstimator::radialPositionAndError2(const LocalPoint& lP, + const LocalError& lE, + const RadialStripTopology& topol) { MeasurementPoint measPos = topol.measurementPosition(lP); - MeasurementError measErr = topol.measurementError(lP,lE); - + MeasurementError measErr = topol.measurementError(lP, lE); + const float r_0 = topol.originToIntersection(); const float stripLength = topol.localStripLength(lP); const float phi = topol.stripAngle(measPos.x()); - + float x(-999.F); float y(-999.F); float errX2(-999.F); float errY2(-999.F); - - x = phi*r_0; + + x = phi * r_0; // Radial y (not symmetric around 0; radial distance with minimum at middle strip at lower edge [0, yMax]) - const float l_0 = r_0 - topol.detHeight()/2; + const float l_0 = r_0 - topol.detHeight() / 2; const float cosPhi(std::cos(phi)); - y = measPos.y()*stripLength - 0.5*stripLength + l_0*(1./cosPhi - 1.); - - const float angularWidth2(topol.angularWidth()*topol.angularWidth()); - const float errPhi2(measErr.uu()*angularWidth2); - - errX2 = errPhi2*r_0*r_0; + y = measPos.y() * stripLength - 0.5 * stripLength + l_0 * (1. / cosPhi - 1.); + + const float angularWidth2(topol.angularWidth() * topol.angularWidth()); + const float errPhi2(measErr.uu() * angularWidth2); + + errX2 = errPhi2 * r_0 * r_0; // Radial y (not symmetric around 0, real radial distance from intersection point) - const float cosPhi4(std::pow(cosPhi,4)), sinPhi2(std::sin(phi)*std::sin(phi)); - const float helpSummand = l_0*l_0*(sinPhi2/cosPhi4*errPhi2); - errY2 = measErr.vv()*stripLength*stripLength + helpSummand; + const float cosPhi4(std::pow(cosPhi, 4)), sinPhi2(std::sin(phi) * std::sin(phi)); + const float helpSummand = l_0 * l_0 * (sinPhi2 / cosPhi4 * errPhi2); + errY2 = measErr.vv() * stripLength * stripLength + helpSummand; return PositionAndError2(x, y, errX2, errY2); } - - - - // ----------------------------------------------------------------------------------------------------------- -void -ApeEstimator::hitSelection(){ +void ApeEstimator::hitSelection() { this->setHitSelectionMapUInt("width"); this->setHitSelectionMap("widthProj"); this->setHitSelectionMap("widthDiff"); @@ -1512,11 +1834,11 @@ ApeEstimator::hitSelection(){ this->setHitSelectionMap("chargeLRplus"); this->setHitSelectionMap("chargeLRminus"); this->setHitSelectionMap("sOverN"); - + this->setHitSelectionMap("chargePixel"); this->setHitSelectionMapUInt("widthX"); this->setHitSelectionMapUInt("widthY"); - + this->setHitSelectionMap("baryStripX"); this->setHitSelectionMap("baryStripY"); this->setHitSelectionMap("clusterProbabilityXY"); @@ -1527,7 +1849,7 @@ ApeEstimator::hitSelection(){ this->setHitSelectionMapUInt("hasBadPixels"); this->setHitSelectionMapUInt("spansTwoRoc"); this->setHitSelectionMapUInt("qBin"); - + this->setHitSelectionMap("phiSens"); this->setHitSelectionMap("phiSensX"); this->setHitSelectionMap("phiSensY"); @@ -1538,7 +1860,7 @@ ApeEstimator::hitSelection(){ this->setHitSelectionMap("errXTrk"); this->setHitSelectionMap("errX"); this->setHitSelectionMap("errX2"); - + this->setHitSelectionMap("resY"); this->setHitSelectionMap("norResY"); this->setHitSelectionMap("probY"); @@ -1546,71 +1868,83 @@ ApeEstimator::hitSelection(){ this->setHitSelectionMap("errYTrk"); this->setHitSelectionMap("errY"); this->setHitSelectionMap("errY2"); - - edm::LogInfo("HitSelector")<<"applying hit cuts ..."; + + edm::LogInfo("HitSelector") << "applying hit cuts ..."; bool emptyMap(true); - for(auto & i_hitSelection : m_hitSelection_){ - if(!i_hitSelection.second.empty()){ - int entry(1); double intervalBegin(999.); - for(std::vector::iterator i_hitInterval = i_hitSelection.second.begin(); i_hitInterval != i_hitSelection.second.end(); ++entry){ - if(entry%2==1){ - intervalBegin = *i_hitInterval; ++i_hitInterval; - }else{ - if(intervalBegin > *i_hitInterval){ - edm::LogError("HitSelector")<<"INVALID Interval selected for "< "<<(*i_hitInterval) - <<"\n ... delete Selection for "<::iterator i_hitInterval = i_hitSelection.second.begin(); + i_hitInterval != i_hitSelection.second.end(); + ++entry) { + if (entry % 2 == 1) { + intervalBegin = *i_hitInterval; + ++i_hitInterval; + } else { + if (intervalBegin > *i_hitInterval) { + edm::LogError("HitSelector") << "INVALID Interval selected for " << i_hitSelection.first << ":\t" + << intervalBegin << " > " << (*i_hitInterval) << "\n ... delete Selection for " + << i_hitSelection.first; + i_hitSelection.second.clear(); + i_hitInterval = i_hitSelection.second.begin(); //emptyMap = true; i_hitSelection = m_hitSelection_.begin(); + } else { + edm::LogInfo("HitSelector") << "Interval selected for " << i_hitSelection.first << ":\t" << intervalBegin + << ", " << (*i_hitInterval); ++i_hitInterval; } } } - if(!i_hitSelection.second.empty())emptyMap = false; + if (!i_hitSelection.second.empty()) + emptyMap = false; } } - - + bool emptyMapUInt(true); - for(auto & i_hitSelection : m_hitSelectionUInt_){ - if(!i_hitSelection.second.empty()){ - int entry(1); unsigned int intervalBegin(999); - for(std::vector::iterator i_hitInterval = i_hitSelection.second.begin(); i_hitInterval != i_hitSelection.second.end(); ++entry){ - if(entry%2==1){ - intervalBegin = *i_hitInterval; + for (auto& i_hitSelection : m_hitSelectionUInt_) { + if (!i_hitSelection.second.empty()) { + int entry(1); + unsigned int intervalBegin(999); + for (std::vector::iterator i_hitInterval = i_hitSelection.second.begin(); + i_hitInterval != i_hitSelection.second.end(); + ++entry) { + if (entry % 2 == 1) { + intervalBegin = *i_hitInterval; ++i_hitInterval; - }else{ - if(intervalBegin > *i_hitInterval){ - edm::LogError("HitSelector")<<"INVALID Interval selected for "< "<<(*i_hitInterval) - <<"\n ... delete Selection for "< *i_hitInterval) { + edm::LogError("HitSelector") << "INVALID Interval selected for " << i_hitSelection.first << ":\t" + << intervalBegin << " > " << (*i_hitInterval) << "\n ... delete Selection for " + << i_hitSelection.first; + i_hitSelection.second.clear(); + i_hitInterval = i_hitSelection.second.begin(); //emptyMap = true; i_hitSelection = m_hitSelection_.begin(); + } else { + edm::LogInfo("HitSelector") << "Interval selected for " << i_hitSelection.first << ":\t" << intervalBegin + << ", " << (*i_hitInterval); ++i_hitInterval; } } } - if(!i_hitSelection.second.empty())emptyMapUInt = false; + if (!i_hitSelection.second.empty()) + emptyMapUInt = false; } } - - if(emptyMap && emptyMapUInt){ + + if (emptyMap && emptyMapUInt) { m_hitSelection_.clear(); m_hitSelectionUInt_.clear(); - edm::LogInfo("HitSelector")<<"NO hit cuts applied"; + edm::LogInfo("HitSelector") << "NO hit cuts applied"; } return; } - - -void -ApeEstimator::setHitSelectionMap(const std::string& cutVariable){ +void ApeEstimator::setHitSelectionMap(const std::string& cutVariable) { edm::ParameterSet parSet(parameterSet_.getParameter("HitSelector")); std::vector v_cutVariable(parSet.getParameter >(cutVariable)); - if(v_cutVariable.size()%2==1){ - edm::LogError("HitSelector")<<"Invalid Hit Selection for "<("HitSelector")); std::vector v_cutVariable(parSet.getParameter >(cutVariable)); - if(v_cutVariable.size()%2==1){ - edm::LogError("HitSelector")<<"Invalid Hit Selection for "<& v_hitSelection(i_hitSelection.second); - if(v_hitSelection.empty())continue; - + if (v_hitSelection.empty()) + continue; + // For pixel and strip sectors in common - if (hitSelection == "phiSens") {if(!this->inDoubleInterval(v_hitSelection, hitParams.phiSens))isGoodHit = false;} - else if(hitSelection == "phiSensX") {if(!this->inDoubleInterval(v_hitSelection, hitParams.phiSensX))isGoodHit = false;} - else if(hitSelection == "phiSensY") {if(!this->inDoubleInterval(v_hitSelection, hitParams.phiSensY))isGoodHit = false;} - - else if(hitSelection == "resX") {if(!this->inDoubleInterval(v_hitSelection, hitParams.resX))isGoodHitX = false;} - else if(hitSelection == "norResX") {if(!this->inDoubleInterval(v_hitSelection, hitParams.norResX))isGoodHitX = false;} - else if(hitSelection == "probX") {if(!this->inDoubleInterval(v_hitSelection, hitParams.probX))isGoodHitX = false;} - else if(hitSelection == "errXHit") {if(!this->inDoubleInterval(v_hitSelection, hitParams.errXHit))isGoodHitX = false;} - else if(hitSelection == "errXTrk") {if(!this->inDoubleInterval(v_hitSelection, hitParams.errXTrk))isGoodHitX = false;} - else if(hitSelection == "errX") {if(!this->inDoubleInterval(v_hitSelection, hitParams.errX))isGoodHitX = false;} - else if(hitSelection == "errX2") {if(!this->inDoubleInterval(v_hitSelection, hitParams.errX2))isGoodHitX = false;} - + if (hitSelection == "phiSens") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.phiSens)) + isGoodHit = false; + } else if (hitSelection == "phiSensX") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.phiSensX)) + isGoodHit = false; + } else if (hitSelection == "phiSensY") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.phiSensY)) + isGoodHit = false; + } + + else if (hitSelection == "resX") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.resX)) + isGoodHitX = false; + } else if (hitSelection == "norResX") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.norResX)) + isGoodHitX = false; + } else if (hitSelection == "probX") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.probX)) + isGoodHitX = false; + } else if (hitSelection == "errXHit") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.errXHit)) + isGoodHitX = false; + } else if (hitSelection == "errXTrk") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.errXTrk)) + isGoodHitX = false; + } else if (hitSelection == "errX") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.errX)) + isGoodHitX = false; + } else if (hitSelection == "errX2") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.errX2)) + isGoodHitX = false; + } + // For pixel only - if(hitParams.isPixelHit){ - if (hitSelection == "chargePixel") {if(!this->inDoubleInterval(v_hitSelection, hitParams.chargePixel))isGoodHit = false;} - else if(hitSelection == "clusterProbabilityXY") {if(!this->inDoubleInterval(v_hitSelection, hitParams.clusterProbabilityXY))isGoodHit = false;} - else if(hitSelection == "clusterProbabilityQ") {if(!this->inDoubleInterval(v_hitSelection, hitParams.clusterProbabilityQ))isGoodHit = false;} - else if(hitSelection == "clusterProbabilityXYQ"){if(!this->inDoubleInterval(v_hitSelection, hitParams.clusterProbabilityXYQ))isGoodHit = false;} - else if(hitSelection == "logClusterProbability"){if(!this->inDoubleInterval(v_hitSelection, hitParams.logClusterProbability))isGoodHit = false;} - - else if(hitSelection == "baryStripX") {if(!this->inDoubleInterval(v_hitSelection, hitParams.baryStripX))isGoodHitX = false;} - else if(hitSelection == "baryStripY") {if(!this->inDoubleInterval(v_hitSelection, hitParams.baryStripY))isGoodHitY = false;} - - - - else if(hitSelection == "resY") {if(!this->inDoubleInterval(v_hitSelection, hitParams.resY))isGoodHitY = false;} - else if(hitSelection == "norResY") {if(!this->inDoubleInterval(v_hitSelection, hitParams.norResY))isGoodHitY = false;} - else if(hitSelection == "probY") {if(!this->inDoubleInterval(v_hitSelection, hitParams.probY))isGoodHitY = false;} - else if(hitSelection == "errYHit") {if(!this->inDoubleInterval(v_hitSelection, hitParams.errYHit))isGoodHitY = false;} - else if(hitSelection == "errYTrk") {if(!this->inDoubleInterval(v_hitSelection, hitParams.errYTrk))isGoodHitY = false;} - else if(hitSelection == "errY") {if(!this->inDoubleInterval(v_hitSelection, hitParams.errY))isGoodHitY = false;} - else if(hitSelection == "errY2") {if(!this->inDoubleInterval(v_hitSelection, hitParams.errY2))isGoodHitY = false;} - }else{ // For strip only - if (hitSelection == "widthProj") {if(!this->inDoubleInterval(v_hitSelection, hitParams.projWidth))isGoodHit = false;} - else if(hitSelection == "widthDiff") {if(!this->inDoubleInterval(v_hitSelection, hitParams.projWidth-static_cast(hitParams.widthX)))isGoodHit = false;} - else if(hitSelection == "charge") {if(!this->inDoubleInterval(v_hitSelection, hitParams.chargeStrip))isGoodHit = false;} - else if(hitSelection == "maxCharge") {if(!this->inDoubleInterval(v_hitSelection, hitParams.maxCharge))isGoodHit = false;} - else if(hitSelection == "chargeOnEdges") {if(!this->inDoubleInterval(v_hitSelection, hitParams.chargeOnEdges))isGoodHit = false;} - else if(hitSelection == "chargeAsymmetry"){if(!this->inDoubleInterval(v_hitSelection, hitParams.chargeAsymmetry))isGoodHit = false;} - else if(hitSelection == "chargeLRplus") {if(!this->inDoubleInterval(v_hitSelection, hitParams.chargeLRplus))isGoodHit = false;} - else if(hitSelection == "chargeLRminus") {if(!this->inDoubleInterval(v_hitSelection, hitParams.chargeLRminus))isGoodHit = false;} - else if(hitSelection == "sOverN") {if(!this->inDoubleInterval(v_hitSelection, hitParams.sOverN))isGoodHit = false;} + if (hitParams.isPixelHit) { + if (hitSelection == "chargePixel") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.chargePixel)) + isGoodHit = false; + } else if (hitSelection == "clusterProbabilityXY") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.clusterProbabilityXY)) + isGoodHit = false; + } else if (hitSelection == "clusterProbabilityQ") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.clusterProbabilityQ)) + isGoodHit = false; + } else if (hitSelection == "clusterProbabilityXYQ") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.clusterProbabilityXYQ)) + isGoodHit = false; + } else if (hitSelection == "logClusterProbability") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.logClusterProbability)) + isGoodHit = false; + } + + else if (hitSelection == "baryStripX") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.baryStripX)) + isGoodHitX = false; + } else if (hitSelection == "baryStripY") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.baryStripY)) + isGoodHitY = false; + } + + else if (hitSelection == "resY") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.resY)) + isGoodHitY = false; + } else if (hitSelection == "norResY") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.norResY)) + isGoodHitY = false; + } else if (hitSelection == "probY") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.probY)) + isGoodHitY = false; + } else if (hitSelection == "errYHit") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.errYHit)) + isGoodHitY = false; + } else if (hitSelection == "errYTrk") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.errYTrk)) + isGoodHitY = false; + } else if (hitSelection == "errY") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.errY)) + isGoodHitY = false; + } else if (hitSelection == "errY2") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.errY2)) + isGoodHitY = false; + } + } else { // For strip only + if (hitSelection == "widthProj") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.projWidth)) + isGoodHit = false; + } else if (hitSelection == "widthDiff") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.projWidth - static_cast(hitParams.widthX))) + isGoodHit = false; + } else if (hitSelection == "charge") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.chargeStrip)) + isGoodHit = false; + } else if (hitSelection == "maxCharge") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.maxCharge)) + isGoodHit = false; + } else if (hitSelection == "chargeOnEdges") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.chargeOnEdges)) + isGoodHit = false; + } else if (hitSelection == "chargeAsymmetry") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.chargeAsymmetry)) + isGoodHit = false; + } else if (hitSelection == "chargeLRplus") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.chargeLRplus)) + isGoodHit = false; + } else if (hitSelection == "chargeLRminus") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.chargeLRminus)) + isGoodHit = false; + } else if (hitSelection == "sOverN") { + if (!this->inDoubleInterval(v_hitSelection, hitParams.sOverN)) + isGoodHit = false; + } } } - - for(auto & i_hitSelection : m_hitSelectionUInt_){ + + for (auto& i_hitSelection : m_hitSelectionUInt_) { const std::string& hitSelection(i_hitSelection.first); const std::vector& v_hitSelection(i_hitSelection.second); - if(v_hitSelection.empty())continue; - + if (v_hitSelection.empty()) + continue; + // For pixel and strip sectors in common - + // For pixel only - if(hitParams.isPixelHit){ - if(hitSelection == "isOnEdge") {if(!this->inUintInterval(v_hitSelection, hitParams.isOnEdge))isGoodHit = false;} - else if(hitSelection == "hasBadPixels") {if(!this->inUintInterval(v_hitSelection, hitParams.hasBadPixels))isGoodHit = false;} - else if(hitSelection == "spansTwoRoc") {if(!this->inUintInterval(v_hitSelection, hitParams.spansTwoRoc))isGoodHit = false;} - else if(hitSelection == "qBin") {if(!this->inUintInterval(v_hitSelection, hitParams.qBin))isGoodHit = false;} - - else if(hitSelection == "widthX") {if(!this->inUintInterval(v_hitSelection, hitParams.widthX))isGoodHitX = false;} - else if(hitSelection == "widthY") {if(!this->inUintInterval(v_hitSelection, hitParams.widthY))isGoodHitY = false;} - }else{ // For strip only - if (hitSelection == "width") {if(!this->inUintInterval(v_hitSelection, hitParams.widthX))isGoodHit = false;} - else if(hitSelection == "edgeStrips"){if(!this->inUintInterval(v_hitSelection, hitParams.maxStrip, hitParams.maxStripInv))isGoodHit = false;} - else if(hitSelection == "maxIndex") {if(!this->inUintInterval(v_hitSelection, hitParams.maxIndex))isGoodHit = false;} + if (hitParams.isPixelHit) { + if (hitSelection == "isOnEdge") { + if (!this->inUintInterval(v_hitSelection, hitParams.isOnEdge)) + isGoodHit = false; + } else if (hitSelection == "hasBadPixels") { + if (!this->inUintInterval(v_hitSelection, hitParams.hasBadPixels)) + isGoodHit = false; + } else if (hitSelection == "spansTwoRoc") { + if (!this->inUintInterval(v_hitSelection, hitParams.spansTwoRoc)) + isGoodHit = false; + } else if (hitSelection == "qBin") { + if (!this->inUintInterval(v_hitSelection, hitParams.qBin)) + isGoodHit = false; + } + + else if (hitSelection == "widthX") { + if (!this->inUintInterval(v_hitSelection, hitParams.widthX)) + isGoodHitX = false; + } else if (hitSelection == "widthY") { + if (!this->inUintInterval(v_hitSelection, hitParams.widthY)) + isGoodHitY = false; + } + } else { // For strip only + if (hitSelection == "width") { + if (!this->inUintInterval(v_hitSelection, hitParams.widthX)) + isGoodHit = false; + } else if (hitSelection == "edgeStrips") { + if (!this->inUintInterval(v_hitSelection, hitParams.maxStrip, hitParams.maxStripInv)) + isGoodHit = false; + } else if (hitSelection == "maxIndex") { + if (!this->inUintInterval(v_hitSelection, hitParams.maxIndex)) + isGoodHit = false; + } } } - - if(hitParams.isPixelHit){ + + if (hitParams.isPixelHit) { hitParams.goodXMeasurement = isGoodHit && isGoodHitX; hitParams.goodYMeasurement = isGoodHit && isGoodHitY; - }else{ + } else { hitParams.goodXMeasurement = isGoodHit && isGoodHitX; hitParams.goodYMeasurement = false; } - - if(!hitParams.goodXMeasurement && !hitParams.goodYMeasurement)return false; - else return true; -} + if (!hitParams.goodXMeasurement && !hitParams.goodYMeasurement) + return false; + else + return true; +} -bool -ApeEstimator::inDoubleInterval(const std::vector& v_hitSelection, const float variable)const{ - int entry(0); double intervalBegin(999.); +bool ApeEstimator::inDoubleInterval(const std::vector& v_hitSelection, const float variable) const { + int entry(0); + double intervalBegin(999.); bool isSelected(false); - for(auto const & i_hitInterval : v_hitSelection){ + for (auto const& i_hitInterval : v_hitSelection) { ++entry; - if(entry%2==1)intervalBegin = i_hitInterval; - else if(variable>=intervalBegin && variable= intervalBegin && variable < i_hitInterval) + isSelected = true; } return isSelected; } - -bool -ApeEstimator::inUintInterval(const std::vector& v_hitSelection, const unsigned int variable, const unsigned int variable2)const{ - int entry(0); unsigned int intervalBegin(999); +bool ApeEstimator::inUintInterval(const std::vector& v_hitSelection, + const unsigned int variable, + const unsigned int variable2) const { + int entry(0); + unsigned int intervalBegin(999); bool isSelected(false); - for(auto i_hitInterval : v_hitSelection ){ + for (auto i_hitInterval : v_hitSelection) { ++entry; - if(entry%2==1)intervalBegin = i_hitInterval; - else if(variable>=intervalBegin && variable<=i_hitInterval){ - if(variable2==999 || (variable2>=intervalBegin && variable2<=i_hitInterval))isSelected = true; + if (entry % 2 == 1) + intervalBegin = i_hitInterval; + else if (variable >= intervalBegin && variable <= i_hitInterval) { + if (variable2 == 999 || (variable2 >= intervalBegin && variable2 <= i_hitInterval)) + isSelected = true; } } return isSelected; } - - // ----------------------------------------------------------------------------------------------------------- - -void -ApeEstimator::fillHistsForAnalyzerMode(const TrackStruct& trackStruct){ +void ApeEstimator::fillHistsForAnalyzerMode(const TrackStruct& trackStruct) { unsigned int goodHitsPerTrack(trackStruct.v_hitParams.size()); tkDetector_.HitsGood->Fill(goodHitsPerTrack); - tkDetector_.HitsGoodVsHitsValid->Fill(trackStruct.trkParams.hitsValid,goodHitsPerTrack); - tkDetector_.PHitsGoodVsHitsValid->Fill(trackStruct.trkParams.hitsValid,goodHitsPerTrack); - - if(parameterSet_.getParameter("applyTrackCuts")){ + tkDetector_.HitsGoodVsHitsValid->Fill(trackStruct.trkParams.hitsValid, goodHitsPerTrack); + tkDetector_.PHitsGoodVsHitsValid->Fill(trackStruct.trkParams.hitsValid, goodHitsPerTrack); + + if (parameterSet_.getParameter("applyTrackCuts")) { // which tracks to take? need min. nr. of selected hits? - if(goodHitsPerTrack < minGoodHitsPerTrack_)return; + if (goodHitsPerTrack < minGoodHitsPerTrack_) + return; } - - tkDetector_.HitsSize ->Fill(trackStruct.trkParams.hitsSize); - tkDetector_.HitsValid ->Fill(trackStruct.trkParams.hitsValid); - tkDetector_.HitsInvalid ->Fill(trackStruct.trkParams.hitsInvalid); - tkDetector_.Hits2D ->Fill(trackStruct.trkParams.hits2D); - tkDetector_.LayersMissed ->Fill(trackStruct.trkParams.layersMissed); - tkDetector_.HitsPixel ->Fill(trackStruct.trkParams.hitsPixel); - tkDetector_.HitsStrip ->Fill(trackStruct.trkParams.hitsStrip); - tkDetector_.Charge ->Fill(trackStruct.trkParams.charge); - tkDetector_.Chi2 ->Fill(trackStruct.trkParams.chi2); - tkDetector_.Ndof ->Fill(trackStruct.trkParams.ndof); - tkDetector_.NorChi2 ->Fill(trackStruct.trkParams.norChi2); - tkDetector_.Prob ->Fill(trackStruct.trkParams.prob); - tkDetector_.Eta ->Fill(trackStruct.trkParams.eta); - tkDetector_.EtaErr ->Fill(trackStruct.trkParams.etaErr); - tkDetector_.EtaSig ->Fill(trackStruct.trkParams.eta/trackStruct.trkParams.etaErr); - tkDetector_.Theta ->Fill(trackStruct.trkParams.theta*180./M_PI); - tkDetector_.Phi ->Fill(trackStruct.trkParams.phi*180./M_PI); - tkDetector_.PhiErr ->Fill(trackStruct.trkParams.phiErr*180./M_PI); - tkDetector_.PhiSig ->Fill(trackStruct.trkParams.phi/trackStruct.trkParams.phiErr); - tkDetector_.D0Beamspot ->Fill(trackStruct.trkParams.d0Beamspot); + + tkDetector_.HitsSize->Fill(trackStruct.trkParams.hitsSize); + tkDetector_.HitsValid->Fill(trackStruct.trkParams.hitsValid); + tkDetector_.HitsInvalid->Fill(trackStruct.trkParams.hitsInvalid); + tkDetector_.Hits2D->Fill(trackStruct.trkParams.hits2D); + tkDetector_.LayersMissed->Fill(trackStruct.trkParams.layersMissed); + tkDetector_.HitsPixel->Fill(trackStruct.trkParams.hitsPixel); + tkDetector_.HitsStrip->Fill(trackStruct.trkParams.hitsStrip); + tkDetector_.Charge->Fill(trackStruct.trkParams.charge); + tkDetector_.Chi2->Fill(trackStruct.trkParams.chi2); + tkDetector_.Ndof->Fill(trackStruct.trkParams.ndof); + tkDetector_.NorChi2->Fill(trackStruct.trkParams.norChi2); + tkDetector_.Prob->Fill(trackStruct.trkParams.prob); + tkDetector_.Eta->Fill(trackStruct.trkParams.eta); + tkDetector_.EtaErr->Fill(trackStruct.trkParams.etaErr); + tkDetector_.EtaSig->Fill(trackStruct.trkParams.eta / trackStruct.trkParams.etaErr); + tkDetector_.Theta->Fill(trackStruct.trkParams.theta * 180. / M_PI); + tkDetector_.Phi->Fill(trackStruct.trkParams.phi * 180. / M_PI); + tkDetector_.PhiErr->Fill(trackStruct.trkParams.phiErr * 180. / M_PI); + tkDetector_.PhiSig->Fill(trackStruct.trkParams.phi / trackStruct.trkParams.phiErr); + tkDetector_.D0Beamspot->Fill(trackStruct.trkParams.d0Beamspot); tkDetector_.D0BeamspotErr->Fill(trackStruct.trkParams.d0BeamspotErr); - tkDetector_.D0BeamspotSig->Fill(trackStruct.trkParams.d0Beamspot/trackStruct.trkParams.d0BeamspotErr); - tkDetector_.Dz ->Fill(trackStruct.trkParams.dz); - tkDetector_.DzErr ->Fill(trackStruct.trkParams.dzErr); - tkDetector_.DzSig ->Fill(trackStruct.trkParams.dz/trackStruct.trkParams.dzErr); - tkDetector_.P ->Fill(trackStruct.trkParams.p); - tkDetector_.Pt ->Fill(trackStruct.trkParams.pt); - tkDetector_.PtErr ->Fill(trackStruct.trkParams.ptErr); - tkDetector_.PtSig ->Fill(trackStruct.trkParams.pt/trackStruct.trkParams.ptErr); - tkDetector_.MeanAngle ->Fill(trackStruct.trkParams.meanPhiSensToNorm*180./M_PI); - - tkDetector_.MeanAngleVsHits ->Fill(trackStruct.trkParams.hitsSize,trackStruct.trkParams.meanPhiSensToNorm*180./M_PI); - tkDetector_.HitsPixelVsEta ->Fill(trackStruct.trkParams.eta,trackStruct.trkParams.hitsPixel); - tkDetector_.HitsPixelVsTheta->Fill(trackStruct.trkParams.theta*180./M_PI,trackStruct.trkParams.hitsPixel); - tkDetector_.HitsStripVsEta ->Fill(trackStruct.trkParams.eta,trackStruct.trkParams.hitsStrip); - tkDetector_.HitsStripVsTheta->Fill(trackStruct.trkParams.theta*180./M_PI,trackStruct.trkParams.hitsStrip); - tkDetector_.PtVsEta ->Fill(trackStruct.trkParams.eta,trackStruct.trkParams.pt); - tkDetector_.PtVsTheta ->Fill(trackStruct.trkParams.theta*180./M_PI,trackStruct.trkParams.pt); - - tkDetector_.PMeanAngleVsHits ->Fill(trackStruct.trkParams.hitsSize,trackStruct.trkParams.meanPhiSensToNorm*180./M_PI); - tkDetector_.PHitsPixelVsEta ->Fill(trackStruct.trkParams.eta,trackStruct.trkParams.hitsPixel); - tkDetector_.PHitsPixelVsTheta->Fill(trackStruct.trkParams.theta*180./M_PI,trackStruct.trkParams.hitsPixel); - tkDetector_.PHitsStripVsEta ->Fill(trackStruct.trkParams.eta,trackStruct.trkParams.hitsStrip); - tkDetector_.PHitsStripVsTheta->Fill(trackStruct.trkParams.theta*180./M_PI,trackStruct.trkParams.hitsStrip); - tkDetector_.PPtVsEta ->Fill(trackStruct.trkParams.eta,trackStruct.trkParams.pt); - tkDetector_.PPtVsTheta ->Fill(trackStruct.trkParams.theta*180./M_PI,trackStruct.trkParams.pt); - - - for(auto & i_hit : trackStruct.v_hitParams){ + tkDetector_.D0BeamspotSig->Fill(trackStruct.trkParams.d0Beamspot / trackStruct.trkParams.d0BeamspotErr); + tkDetector_.Dz->Fill(trackStruct.trkParams.dz); + tkDetector_.DzErr->Fill(trackStruct.trkParams.dzErr); + tkDetector_.DzSig->Fill(trackStruct.trkParams.dz / trackStruct.trkParams.dzErr); + tkDetector_.P->Fill(trackStruct.trkParams.p); + tkDetector_.Pt->Fill(trackStruct.trkParams.pt); + tkDetector_.PtErr->Fill(trackStruct.trkParams.ptErr); + tkDetector_.PtSig->Fill(trackStruct.trkParams.pt / trackStruct.trkParams.ptErr); + tkDetector_.MeanAngle->Fill(trackStruct.trkParams.meanPhiSensToNorm * 180. / M_PI); + + tkDetector_.MeanAngleVsHits->Fill(trackStruct.trkParams.hitsSize, + trackStruct.trkParams.meanPhiSensToNorm * 180. / M_PI); + tkDetector_.HitsPixelVsEta->Fill(trackStruct.trkParams.eta, trackStruct.trkParams.hitsPixel); + tkDetector_.HitsPixelVsTheta->Fill(trackStruct.trkParams.theta * 180. / M_PI, trackStruct.trkParams.hitsPixel); + tkDetector_.HitsStripVsEta->Fill(trackStruct.trkParams.eta, trackStruct.trkParams.hitsStrip); + tkDetector_.HitsStripVsTheta->Fill(trackStruct.trkParams.theta * 180. / M_PI, trackStruct.trkParams.hitsStrip); + tkDetector_.PtVsEta->Fill(trackStruct.trkParams.eta, trackStruct.trkParams.pt); + tkDetector_.PtVsTheta->Fill(trackStruct.trkParams.theta * 180. / M_PI, trackStruct.trkParams.pt); + + tkDetector_.PMeanAngleVsHits->Fill(trackStruct.trkParams.hitsSize, + trackStruct.trkParams.meanPhiSensToNorm * 180. / M_PI); + tkDetector_.PHitsPixelVsEta->Fill(trackStruct.trkParams.eta, trackStruct.trkParams.hitsPixel); + tkDetector_.PHitsPixelVsTheta->Fill(trackStruct.trkParams.theta * 180. / M_PI, trackStruct.trkParams.hitsPixel); + tkDetector_.PHitsStripVsEta->Fill(trackStruct.trkParams.eta, trackStruct.trkParams.hitsStrip); + tkDetector_.PHitsStripVsTheta->Fill(trackStruct.trkParams.theta * 180. / M_PI, trackStruct.trkParams.hitsStrip); + tkDetector_.PPtVsEta->Fill(trackStruct.trkParams.eta, trackStruct.trkParams.pt); + tkDetector_.PPtVsTheta->Fill(trackStruct.trkParams.theta * 180. / M_PI, trackStruct.trkParams.pt); + + for (auto& i_hit : trackStruct.v_hitParams) { const TrackStruct::HitParameterStruct& hit(i_hit); //Put here from earlier method - if(hit.hitState == TrackStruct::notAssignedToSectors)continue; - - for(auto & i_sector : m_tkSector_){ + if (hit.hitState == TrackStruct::notAssignedToSectors) + continue; + + for (auto& i_sector : m_tkSector_) { bool moduleInSector(false); - for(auto const & i_hitSector : hit.v_sector){ - if(i_sector.first == i_hitSector){ - moduleInSector = true; + for (auto const& i_hitSector : hit.v_sector) { + if (i_sector.first == i_hitSector) { + moduleInSector = true; break; } } - if(!moduleInSector)continue; + if (!moduleInSector) + continue; TrackerSectorStruct& sector(i_sector.second); - - if(hit.goodXMeasurement){ - std::map& m_corrHists(sector.m_correlationHistsX); - + + if (hit.goodXMeasurement) { + std::map& m_corrHists(sector.m_correlationHistsX); + // Cluster and Hit Parameters this->fillHitHistsXForAnalyzerMode(hit, sector); - + // Track Parameters - m_corrHists["HitsValid"].fillCorrHistsX(hit,trackStruct.trkParams.hitsValid); - m_corrHists["HitsGood"].fillCorrHistsX(hit,goodHitsPerTrack); - m_corrHists["HitsInvalid"].fillCorrHistsX(hit,trackStruct.trkParams.hitsInvalid); - m_corrHists["Hits2D"].fillCorrHistsX(hit,trackStruct.trkParams.hits2D); - m_corrHists["LayersMissed"].fillCorrHistsX(hit,trackStruct.trkParams.layersMissed); - m_corrHists["HitsPixel"].fillCorrHistsX(hit,trackStruct.trkParams.hitsPixel); - m_corrHists["HitsStrip"].fillCorrHistsX(hit,trackStruct.trkParams.hitsStrip); - m_corrHists["NorChi2"].fillCorrHistsX(hit,trackStruct.trkParams.norChi2); - m_corrHists["Theta"].fillCorrHistsX(hit,trackStruct.trkParams.theta*180./M_PI); - m_corrHists["Phi"].fillCorrHistsX(hit,trackStruct.trkParams.phi*180./M_PI); - m_corrHists["D0Beamspot"].fillCorrHistsX(hit,trackStruct.trkParams.d0Beamspot); - m_corrHists["Dz"].fillCorrHistsX(hit,trackStruct.trkParams.dz); - m_corrHists["Pt"].fillCorrHistsX(hit,trackStruct.trkParams.pt); - m_corrHists["P"].fillCorrHistsX(hit,trackStruct.trkParams.p); - m_corrHists["InvP"].fillCorrHistsX(hit,1./trackStruct.trkParams.p); - m_corrHists["MeanAngle"].fillCorrHistsX(hit,trackStruct.trkParams.meanPhiSensToNorm*180./M_PI); + m_corrHists["HitsValid"].fillCorrHistsX(hit, trackStruct.trkParams.hitsValid); + m_corrHists["HitsGood"].fillCorrHistsX(hit, goodHitsPerTrack); + m_corrHists["HitsInvalid"].fillCorrHistsX(hit, trackStruct.trkParams.hitsInvalid); + m_corrHists["Hits2D"].fillCorrHistsX(hit, trackStruct.trkParams.hits2D); + m_corrHists["LayersMissed"].fillCorrHistsX(hit, trackStruct.trkParams.layersMissed); + m_corrHists["HitsPixel"].fillCorrHistsX(hit, trackStruct.trkParams.hitsPixel); + m_corrHists["HitsStrip"].fillCorrHistsX(hit, trackStruct.trkParams.hitsStrip); + m_corrHists["NorChi2"].fillCorrHistsX(hit, trackStruct.trkParams.norChi2); + m_corrHists["Theta"].fillCorrHistsX(hit, trackStruct.trkParams.theta * 180. / M_PI); + m_corrHists["Phi"].fillCorrHistsX(hit, trackStruct.trkParams.phi * 180. / M_PI); + m_corrHists["D0Beamspot"].fillCorrHistsX(hit, trackStruct.trkParams.d0Beamspot); + m_corrHists["Dz"].fillCorrHistsX(hit, trackStruct.trkParams.dz); + m_corrHists["Pt"].fillCorrHistsX(hit, trackStruct.trkParams.pt); + m_corrHists["P"].fillCorrHistsX(hit, trackStruct.trkParams.p); + m_corrHists["InvP"].fillCorrHistsX(hit, 1. / trackStruct.trkParams.p); + m_corrHists["MeanAngle"].fillCorrHistsX(hit, trackStruct.trkParams.meanPhiSensToNorm * 180. / M_PI); } - - if(hit.goodYMeasurement){ - std::map& m_corrHists(sector.m_correlationHistsY); - + + if (hit.goodYMeasurement) { + std::map& m_corrHists(sector.m_correlationHistsY); + // Cluster and Hit Parameters this->fillHitHistsYForAnalyzerMode(hit, sector); - + // Track Parameters - m_corrHists["HitsValid"].fillCorrHistsY(hit,trackStruct.trkParams.hitsValid); - m_corrHists["HitsGood"].fillCorrHistsY(hit,goodHitsPerTrack); - m_corrHists["HitsInvalid"].fillCorrHistsY(hit,trackStruct.trkParams.hitsInvalid); - m_corrHists["Hits2D"].fillCorrHistsY(hit,trackStruct.trkParams.hits2D); - m_corrHists["LayersMissed"].fillCorrHistsY(hit,trackStruct.trkParams.layersMissed); - m_corrHists["HitsPixel"].fillCorrHistsY(hit,trackStruct.trkParams.hitsPixel); - m_corrHists["HitsStrip"].fillCorrHistsY(hit,trackStruct.trkParams.hitsStrip); - m_corrHists["NorChi2"].fillCorrHistsY(hit,trackStruct.trkParams.norChi2); - m_corrHists["Theta"].fillCorrHistsY(hit,trackStruct.trkParams.theta*180./M_PI); - m_corrHists["Phi"].fillCorrHistsY(hit,trackStruct.trkParams.phi*180./M_PI); - m_corrHists["D0Beamspot"].fillCorrHistsY(hit,trackStruct.trkParams.d0Beamspot); - m_corrHists["Dz"].fillCorrHistsY(hit,trackStruct.trkParams.dz); - m_corrHists["Pt"].fillCorrHistsY(hit,trackStruct.trkParams.pt); - m_corrHists["P"].fillCorrHistsY(hit,trackStruct.trkParams.p); - m_corrHists["InvP"].fillCorrHistsY(hit,1./trackStruct.trkParams.p); - m_corrHists["MeanAngle"].fillCorrHistsY(hit,trackStruct.trkParams.meanPhiSensToNorm*180./M_PI); + m_corrHists["HitsValid"].fillCorrHistsY(hit, trackStruct.trkParams.hitsValid); + m_corrHists["HitsGood"].fillCorrHistsY(hit, goodHitsPerTrack); + m_corrHists["HitsInvalid"].fillCorrHistsY(hit, trackStruct.trkParams.hitsInvalid); + m_corrHists["Hits2D"].fillCorrHistsY(hit, trackStruct.trkParams.hits2D); + m_corrHists["LayersMissed"].fillCorrHistsY(hit, trackStruct.trkParams.layersMissed); + m_corrHists["HitsPixel"].fillCorrHistsY(hit, trackStruct.trkParams.hitsPixel); + m_corrHists["HitsStrip"].fillCorrHistsY(hit, trackStruct.trkParams.hitsStrip); + m_corrHists["NorChi2"].fillCorrHistsY(hit, trackStruct.trkParams.norChi2); + m_corrHists["Theta"].fillCorrHistsY(hit, trackStruct.trkParams.theta * 180. / M_PI); + m_corrHists["Phi"].fillCorrHistsY(hit, trackStruct.trkParams.phi * 180. / M_PI); + m_corrHists["D0Beamspot"].fillCorrHistsY(hit, trackStruct.trkParams.d0Beamspot); + m_corrHists["Dz"].fillCorrHistsY(hit, trackStruct.trkParams.dz); + m_corrHists["Pt"].fillCorrHistsY(hit, trackStruct.trkParams.pt); + m_corrHists["P"].fillCorrHistsY(hit, trackStruct.trkParams.p); + m_corrHists["InvP"].fillCorrHistsY(hit, 1. / trackStruct.trkParams.p); + m_corrHists["MeanAngle"].fillCorrHistsY(hit, trackStruct.trkParams.meanPhiSensToNorm * 180. / M_PI); } - - // Special Histograms - for(auto & i_sigmaX : sector.m_sigmaX){ - for(auto & iHist : i_sigmaX.second){ - if (i_sigmaX.first=="sigmaXHit") iHist->Fill(hit.errXHit*10000.); - else if(i_sigmaX.first=="sigmaXTrk") iHist->Fill(hit.errXTrk*10000.); - else if(i_sigmaX.first=="sigmaX") iHist->Fill(hit.errX*10000.); + + // Special Histograms + for (auto& i_sigmaX : sector.m_sigmaX) { + for (auto& iHist : i_sigmaX.second) { + if (i_sigmaX.first == "sigmaXHit") + iHist->Fill(hit.errXHit * 10000.); + else if (i_sigmaX.first == "sigmaXTrk") + iHist->Fill(hit.errXTrk * 10000.); + else if (i_sigmaX.first == "sigmaX") + iHist->Fill(hit.errX * 10000.); } } - for(auto & i_sigmaY : sector.m_sigmaY){ - for(auto & iHist : i_sigmaY.second){ - if (i_sigmaY.first=="sigmaYHit") iHist->Fill(hit.errYHit*10000.); - else if(i_sigmaY.first=="sigmaYTrk") iHist->Fill(hit.errYTrk*10000.); - else if(i_sigmaY.first=="sigmaY") iHist->Fill(hit.errY*10000.); + for (auto& i_sigmaY : sector.m_sigmaY) { + for (auto& iHist : i_sigmaY.second) { + if (i_sigmaY.first == "sigmaYHit") + iHist->Fill(hit.errYHit * 10000.); + else if (i_sigmaY.first == "sigmaYTrk") + iHist->Fill(hit.errYTrk * 10000.); + else if (i_sigmaY.first == "sigmaY") + iHist->Fill(hit.errY * 10000.); } } } } } - - -void -ApeEstimator::fillHitHistsXForAnalyzerMode(const TrackStruct::HitParameterStruct& hit, TrackerSectorStruct& sector){ +void ApeEstimator::fillHitHistsXForAnalyzerMode(const TrackStruct::HitParameterStruct& hit, + TrackerSectorStruct& sector) { std::map& m_corrHists(sector.m_correlationHistsX); - + // Cluster Parameters m_corrHists["WidthX"].fillCorrHistsX(hit, hit.widthX); m_corrHists["BaryStripX"].fillCorrHistsX(hit, hit.baryStripX); - - if(hit.isPixelHit){ + + if (hit.isPixelHit) { m_corrHists["ChargePixel"].fillCorrHistsX(hit, hit.chargePixel); m_corrHists["ClusterProbXY"].fillCorrHistsX(hit, hit.clusterProbabilityXY); m_corrHists["ClusterProbQ"].fillCorrHistsX(hit, hit.clusterProbabilityQ); @@ -1932,8 +2367,8 @@ ApeEstimator::fillHitHistsXForAnalyzerMode(const TrackStruct::HitParameterStruct m_corrHists["HasBadPixels"].fillCorrHistsX(hit, hit.hasBadPixels); m_corrHists["SpansTwoRoc"].fillCorrHistsX(hit, hit.spansTwoRoc); m_corrHists["QBin"].fillCorrHistsX(hit, hit.qBin); - - }else{ + + } else { m_corrHists["ChargeStrip"].fillCorrHistsX(hit, hit.chargeStrip); m_corrHists["MaxStrip"].fillCorrHistsX(hit, hit.maxStrip); m_corrHists["MaxCharge"].fillCorrHistsX(hit, hit.maxCharge); @@ -1944,55 +2379,54 @@ ApeEstimator::fillHitHistsXForAnalyzerMode(const TrackStruct::HitParameterStruct m_corrHists["ChargeLRminus"].fillCorrHistsX(hit, hit.chargeLRminus); m_corrHists["SOverN"].fillCorrHistsX(hit, hit.sOverN); m_corrHists["WidthProj"].fillCorrHistsX(hit, hit.projWidth); - m_corrHists["WidthDiff"].fillCorrHistsX(hit, hit.projWidth-static_cast( hit.widthX)); - - sector.WidthVsWidthProjected->Fill( hit.projWidth, hit.widthX); - sector.PWidthVsWidthProjected->Fill( hit.projWidth, hit.widthX); - - sector.WidthDiffVsMaxStrip->Fill( hit.maxStrip, hit.projWidth-static_cast( hit.widthX)); - sector.PWidthDiffVsMaxStrip->Fill( hit.maxStrip, hit.projWidth-static_cast( hit.widthX)); - - sector.WidthDiffVsSigmaXHit->Fill( hit.errXHit, hit.projWidth-static_cast( hit.widthX)); - sector.PWidthDiffVsSigmaXHit->Fill( hit.errXHit, hit.projWidth-static_cast( hit.widthX)); - - sector.WidthVsPhiSensX->Fill( hit.phiSensX*180./M_PI, hit.widthX); - sector.PWidthVsPhiSensX->Fill( hit.phiSensX*180./M_PI, hit.widthX); + m_corrHists["WidthDiff"].fillCorrHistsX(hit, hit.projWidth - static_cast(hit.widthX)); + + sector.WidthVsWidthProjected->Fill(hit.projWidth, hit.widthX); + sector.PWidthVsWidthProjected->Fill(hit.projWidth, hit.widthX); + + sector.WidthDiffVsMaxStrip->Fill(hit.maxStrip, hit.projWidth - static_cast(hit.widthX)); + sector.PWidthDiffVsMaxStrip->Fill(hit.maxStrip, hit.projWidth - static_cast(hit.widthX)); + + sector.WidthDiffVsSigmaXHit->Fill(hit.errXHit, hit.projWidth - static_cast(hit.widthX)); + sector.PWidthDiffVsSigmaXHit->Fill(hit.errXHit, hit.projWidth - static_cast(hit.widthX)); + + sector.WidthVsPhiSensX->Fill(hit.phiSensX * 180. / M_PI, hit.widthX); + sector.PWidthVsPhiSensX->Fill(hit.phiSensX * 180. / M_PI, hit.widthX); } - + // Hit Parameters - m_corrHists["SigmaXHit"].fillCorrHistsX(hit, hit.errXHit*10000.); - m_corrHists["SigmaXTrk"].fillCorrHistsX(hit, hit.errXTrk*10000.); - m_corrHists["SigmaX"].fillCorrHistsX(hit, hit.errX*10000.); - - m_corrHists["PhiSens"].fillCorrHistsX(hit, hit.phiSens*180./M_PI); - m_corrHists["PhiSensX"].fillCorrHistsX(hit, hit.phiSensX*180./M_PI); - m_corrHists["PhiSensY"].fillCorrHistsX(hit, hit.phiSensY*180./M_PI); - - sector.XHit ->Fill(hit.xHit); - sector.XTrk ->Fill(hit.xTrk); - sector.SigmaX2->Fill(hit.errX2*10000.*10000.); - - sector.ResX ->Fill(hit.resX*10000.); + m_corrHists["SigmaXHit"].fillCorrHistsX(hit, hit.errXHit * 10000.); + m_corrHists["SigmaXTrk"].fillCorrHistsX(hit, hit.errXTrk * 10000.); + m_corrHists["SigmaX"].fillCorrHistsX(hit, hit.errX * 10000.); + + m_corrHists["PhiSens"].fillCorrHistsX(hit, hit.phiSens * 180. / M_PI); + m_corrHists["PhiSensX"].fillCorrHistsX(hit, hit.phiSensX * 180. / M_PI); + m_corrHists["PhiSensY"].fillCorrHistsX(hit, hit.phiSensY * 180. / M_PI); + + sector.XHit->Fill(hit.xHit); + sector.XTrk->Fill(hit.xTrk); + sector.SigmaX2->Fill(hit.errX2 * 10000. * 10000.); + + sector.ResX->Fill(hit.resX * 10000.); sector.NorResX->Fill(hit.norResX); - - sector.ProbX->Fill(hit.probX); - - sector.PhiSensXVsBarycentreX->Fill(hit.baryStripX, hit.phiSensX*180./M_PI); - sector.PPhiSensXVsBarycentreX->Fill(hit.baryStripX, hit.phiSensX*180./M_PI); -} + sector.ProbX->Fill(hit.probX); + sector.PhiSensXVsBarycentreX->Fill(hit.baryStripX, hit.phiSensX * 180. / M_PI); + sector.PPhiSensXVsBarycentreX->Fill(hit.baryStripX, hit.phiSensX * 180. / M_PI); +} -void -ApeEstimator::fillHitHistsYForAnalyzerMode(const TrackStruct::HitParameterStruct& hit, TrackerSectorStruct& sector){ +void ApeEstimator::fillHitHistsYForAnalyzerMode(const TrackStruct::HitParameterStruct& hit, + TrackerSectorStruct& sector) { std::map& m_corrHists(sector.m_correlationHistsY); // Do not fill anything for strip - if(!hit.isPixelHit)return; - + if (!hit.isPixelHit) + return; + // Cluster Parameters - m_corrHists["WidthY"].fillCorrHistsY(hit,hit.widthY); - m_corrHists["BaryStripY"].fillCorrHistsY(hit,hit.baryStripY); - + m_corrHists["WidthY"].fillCorrHistsY(hit, hit.widthY); + m_corrHists["BaryStripY"].fillCorrHistsY(hit, hit.baryStripY); + m_corrHists["ChargePixel"].fillCorrHistsY(hit, hit.chargePixel); m_corrHists["ClusterProbXY"].fillCorrHistsY(hit, hit.clusterProbabilityXY); m_corrHists["ClusterProbQ"].fillCorrHistsY(hit, hit.clusterProbabilityQ); @@ -2002,113 +2436,106 @@ ApeEstimator::fillHitHistsYForAnalyzerMode(const TrackStruct::HitParameterStruct m_corrHists["HasBadPixels"].fillCorrHistsY(hit, hit.hasBadPixels); m_corrHists["SpansTwoRoc"].fillCorrHistsY(hit, hit.spansTwoRoc); m_corrHists["QBin"].fillCorrHistsY(hit, hit.qBin); - + // Hit Parameters - m_corrHists["SigmaYHit"].fillCorrHistsY(hit, hit.errYHit*10000.); - m_corrHists["SigmaYTrk"].fillCorrHistsY(hit, hit.errYTrk*10000.); - m_corrHists["SigmaY"].fillCorrHistsY(hit, hit.errY*10000.); - - m_corrHists["PhiSens"].fillCorrHistsY(hit, hit.phiSens*180./M_PI); - m_corrHists["PhiSensX"].fillCorrHistsY(hit, hit.phiSensX*180./M_PI); - m_corrHists["PhiSensY"].fillCorrHistsY(hit, hit.phiSensY*180./M_PI); - - sector.YHit ->Fill(hit.yHit); - sector.YTrk ->Fill(hit.yTrk); - sector.SigmaY2->Fill(hit.errY2*10000.*10000.); - - sector.ResY ->Fill(hit.resY*10000.); + m_corrHists["SigmaYHit"].fillCorrHistsY(hit, hit.errYHit * 10000.); + m_corrHists["SigmaYTrk"].fillCorrHistsY(hit, hit.errYTrk * 10000.); + m_corrHists["SigmaY"].fillCorrHistsY(hit, hit.errY * 10000.); + + m_corrHists["PhiSens"].fillCorrHistsY(hit, hit.phiSens * 180. / M_PI); + m_corrHists["PhiSensX"].fillCorrHistsY(hit, hit.phiSensX * 180. / M_PI); + m_corrHists["PhiSensY"].fillCorrHistsY(hit, hit.phiSensY * 180. / M_PI); + + sector.YHit->Fill(hit.yHit); + sector.YTrk->Fill(hit.yTrk); + sector.SigmaY2->Fill(hit.errY2 * 10000. * 10000.); + + sector.ResY->Fill(hit.resY * 10000.); sector.NorResY->Fill(hit.norResY); - - sector.ProbY->Fill(hit.probY); - - sector.PhiSensYVsBarycentreY->Fill(hit.baryStripY, hit.phiSensY*180./M_PI); - sector.PPhiSensYVsBarycentreY->Fill(hit.baryStripY, hit.phiSensY*180./M_PI); -} + sector.ProbY->Fill(hit.probY); + sector.PhiSensYVsBarycentreY->Fill(hit.baryStripY, hit.phiSensY * 180. / M_PI); + sector.PPhiSensYVsBarycentreY->Fill(hit.baryStripY, hit.phiSensY * 180. / M_PI); +} -void -ApeEstimator::fillHistsForApeCalculation(const TrackStruct& trackStruct){ +void ApeEstimator::fillHistsForApeCalculation(const TrackStruct& trackStruct) { unsigned int goodHitsPerTrack(trackStruct.v_hitParams.size()); - - if(parameterSet_.getParameter("applyTrackCuts")){ + + if (parameterSet_.getParameter("applyTrackCuts")) { // which tracks to take? need min. nr. of selected hits? - if(goodHitsPerTrack < minGoodHitsPerTrack_)return; + if (goodHitsPerTrack < minGoodHitsPerTrack_) + return; } - - for(auto const & i_hit : trackStruct.v_hitParams){ + + for (auto const& i_hit : trackStruct.v_hitParams) { // Put here from earlier method - if(i_hit.hitState == TrackStruct::notAssignedToSectors)continue; - - for(auto & i_sector : m_tkSector_){ - + if (i_hit.hitState == TrackStruct::notAssignedToSectors) + continue; + + for (auto& i_sector : m_tkSector_) { bool moduleInSector(false); - for(auto const & i_hitSector : i_hit.v_sector){ - if(i_sector.first == i_hitSector){ - moduleInSector = true; + for (auto const& i_hitSector : i_hit.v_sector) { + if (i_sector.first == i_hitSector) { + moduleInSector = true; break; } } - if(!moduleInSector)continue; - - if(!calculateApe_)continue; - - if(i_hit.goodXMeasurement){ - for(auto const & i_errBins : m_resErrBins_){ + if (!moduleInSector) + continue; + + if (!calculateApe_) + continue; + + if (i_hit.goodXMeasurement) { + for (auto const& i_errBins : m_resErrBins_) { // Separate the bins for residual resolution w/o APE, to be consistent within iterations where APE will change (have same hit always in same bin) // So also fill this value in the histogram sigmaX // But of course use the normalized residual regarding the APE to have its influence in its width - if(i_hit.errXWoApe < i_errBins.second.first || i_hit.errXWoApe >= i_errBins.second.second){ + if (i_hit.errXWoApe < i_errBins.second.first || i_hit.errXWoApe >= i_errBins.second.second) { continue; } - i_sector.second.m_binnedHists[i_errBins.first]["sigmaX"] ->Fill(i_hit.errXWoApe); + i_sector.second.m_binnedHists[i_errBins.first]["sigmaX"]->Fill(i_hit.errXWoApe); i_sector.second.m_binnedHists[i_errBins.first]["norResX"]->Fill(i_hit.norResX); break; } - i_sector.second.ResX->Fill(i_hit.resX*10000.); + i_sector.second.ResX->Fill(i_hit.resX * 10000.); i_sector.second.NorResX->Fill(i_hit.norResX); } - - if(i_hit.goodYMeasurement){ - for(auto const & i_errBins : m_resErrBins_){ - // Separate the bins for residual resolution w/o APE, to be consistent within iterations where APE will change (have same hit always in same bin) - // So also fill this value in the histogram sigmaY - // But of course use the normalized residual regarding the APE to have its influence in its width - if(i_hit.errYWoApe < i_errBins.second.first || i_hit.errYWoApe >= i_errBins.second.second){ - continue; - } - i_sector.second.m_binnedHists[i_errBins.first]["sigmaY"] ->Fill(i_hit.errYWoApe); - i_sector.second.m_binnedHists[i_errBins.first]["norResY"]->Fill(i_hit.norResY); - break; + + if (i_hit.goodYMeasurement) { + for (auto const& i_errBins : m_resErrBins_) { + // Separate the bins for residual resolution w/o APE, to be consistent within iterations where APE will change (have same hit always in same bin) + // So also fill this value in the histogram sigmaY + // But of course use the normalized residual regarding the APE to have its influence in its width + if (i_hit.errYWoApe < i_errBins.second.first || i_hit.errYWoApe >= i_errBins.second.second) { + continue; + } + i_sector.second.m_binnedHists[i_errBins.first]["sigmaY"]->Fill(i_hit.errYWoApe); + i_sector.second.m_binnedHists[i_errBins.first]["norResY"]->Fill(i_hit.norResY); + break; } - i_sector.second.ResY->Fill(i_hit.resY*10000.); + i_sector.second.ResY->Fill(i_hit.resY * 10000.); i_sector.second.NorResY->Fill(i_hit.norResY); } } } } - - - // ----------------------------------------------------------------------------------------------------------- - - -void -ApeEstimator::calculateAPE(){ +void ApeEstimator::calculateAPE() { // Loop over sectors for calculating APE - for(auto & i_sector : m_tkSector_){ - - // Loop over residual error bins to calculate APE for every bin - for(auto const & i_errBins : i_sector.second.m_binnedHists){ - std::map m_Hists = i_errBins.second; - - // Fitting Parameters + for (auto& i_sector : m_tkSector_) { + // Loop over residual error bins to calculate APE for every bin + for (auto const& i_errBins : i_sector.second.m_binnedHists) { + std::map m_Hists = i_errBins.second; + + // Fitting Parameters double integralX = m_Hists["norResX"]->Integral(); i_sector.second.EntriesX->SetBinContent(i_errBins.first, integralX); - - if(i_sector.second.isPixel){ + + if (i_sector.second.isPixel) { double integralY = m_Hists["norResY"]->Integral(); i_sector.second.EntriesY->SetBinContent(i_errBins.first, integralY); } @@ -2116,142 +2543,140 @@ ApeEstimator::calculateAPE(){ } } - - - // ----------------------------------------------------------------------------------------------------------- - -bool -ApeEstimator::isHit2D(const TrackingRecHit &hit) const -{ +bool ApeEstimator::isHit2D(const TrackingRecHit& hit) const { // we count SiStrip stereo modules as 2D if selected via countStereoHitAs2D_ // (since they provide theta information) // --- NO, here it is always set to true --- - if(!hit.isValid() || (hit.dimension() < 2 && !dynamic_cast(&hit))){ - return false; // real RecHit1D - but SiStripRecHit1D depends on countStereoHitAs2D_ - }else{ + if (!hit.isValid() || (hit.dimension() < 2 && !dynamic_cast(&hit))) { + return false; // real RecHit1D - but SiStripRecHit1D depends on countStereoHitAs2D_ + } else { const DetId detId(hit.geographicalId()); - if(detId.det() == DetId::Tracker) { - if(detId.subdetId() == PixelSubdetector::PixelBarrel || detId.subdetId() == PixelSubdetector::PixelEndcap) { - return true; // pixel is always 2D - }else{ // should be SiStrip now + if (detId.det() == DetId::Tracker) { + if (detId.subdetId() == PixelSubdetector::PixelBarrel || detId.subdetId() == PixelSubdetector::PixelEndcap) { + return true; // pixel is always 2D + } else { // should be SiStrip now const SiStripDetId stripId(detId); - if (stripId.stereo()) return true; // stereo modules - else if (dynamic_cast(&hit) || dynamic_cast(&hit)) return false; // rphi modules hit - //the following two are not used any more since ages... - else if (dynamic_cast(&hit)) return true; // matched is 2D + if (stripId.stereo()) + return true; // stereo modules + else if (dynamic_cast(&hit) || dynamic_cast(&hit)) + return false; // rphi modules hit + //the following two are not used any more since ages... + else if (dynamic_cast(&hit)) + return true; // matched is 2D else if (dynamic_cast(&hit)) { const ProjectedSiStripRecHit2D* pH = static_cast(&hit); - return (this->isHit2D(pH->originalHit())); // depends on original... - }else{ + return (this->isHit2D(pH->originalHit())); // depends on original... + } else { edm::LogError("UnkownType") << "@SUB=AlignmentTrackSelector::isHit2D" << "Tracker hit not in pixel, neither SiStripRecHit[12]D nor " << "SiStripMatchedRecHit2D nor ProjectedSiStripRecHit2D."; return false; } } - }else{ // not tracker?? + } else { // not tracker?? edm::LogWarning("DetectorMismatch") << "@SUB=AlignmentTrackSelector::isHit2D" << "Hit not in tracker with 'official' dimension >=2."; - return true; // dimension() >= 2 so accept that... + return true; // dimension() >= 2 so accept that... } } // never reached... } - - // ----------------------------------------------------------------------------------------------------------- // ------------ method called to for each event ------------ -void -ApeEstimator::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - reco::BeamSpot beamSpot; - edm::Handle beamSpotHandle; - iEvent.getByToken(offlinebeamSpot_, beamSpotHandle); - - if (beamSpotHandle.isValid()){ - beamSpot = *beamSpotHandle; - }else{ - edm::LogError("ApeEstimator")<<"No beam spot available from EventSetup" - <<"\n...skip event"; - return; - } - - edm::Handle m_TrajTracksMap; - iEvent.getByToken(tjTagToken_, m_TrajTracksMap); - - if(analyzerMode_)tkDetector_.TrkSize->Fill(m_TrajTracksMap->size()); - - if(maxTracksPerEvent_!=0 && m_TrajTracksMap->size()>maxTracksPerEvent_)return; - - //Creation of (traj,track) - typedef std::pair ConstTrajTrackPair; - typedef std::vector ConstTrajTrackPairCollection; - ConstTrajTrackPairCollection trajTracks; - - TrajTrackAssociationCollection::const_iterator i_trajTrack; - for(i_trajTrack = m_TrajTracksMap->begin();i_trajTrack != m_TrajTracksMap->end();++i_trajTrack){ - trajTracks.push_back(ConstTrajTrackPair(&(*(*i_trajTrack).key), &(*(*i_trajTrack).val))); - } - - - //Loop over Tracks & Hits - unsigned int trackSizeGood(0); - ConstTrajTrackPairCollection::const_iterator iTrack; - for(iTrack = trajTracks.begin(); iTrack != trajTracks.end();++iTrack){ - - const Trajectory *traj = (*iTrack).first; - const reco::Track *track = (*iTrack).second; - - TrackStruct trackStruct; - trackStruct.trkParams = this->fillTrackVariables(*track, *traj, beamSpot); - - if(trackCut_)continue; - - const std::vector v_meas = (*traj).measurements(); - - //Loop over Hits - for(std::vector::const_iterator i_meas = v_meas.begin(); i_meas != v_meas.end(); ++i_meas){ - TrackStruct::HitParameterStruct hitParams = this->fillHitVariables(*i_meas, iSetup); - if(this->hitSelected(hitParams))trackStruct.v_hitParams.push_back(hitParams); - } - - if(analyzerMode_)this->fillHistsForAnalyzerMode(trackStruct); - if(calculateApe_)this->fillHistsForApeCalculation(trackStruct); - - if(!trackStruct.v_hitParams.empty())++trackSizeGood; - } - if(analyzerMode_ && trackSizeGood>0)tkDetector_.TrkSizeGood->Fill(trackSizeGood); -} +void ApeEstimator::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + reco::BeamSpot beamSpot; + edm::Handle beamSpotHandle; + iEvent.getByToken(offlinebeamSpot_, beamSpotHandle); + + if (beamSpotHandle.isValid()) { + beamSpot = *beamSpotHandle; + } else { + edm::LogError("ApeEstimator") << "No beam spot available from EventSetup" + << "\n...skip event"; + return; + } + + edm::Handle m_TrajTracksMap; + iEvent.getByToken(tjTagToken_, m_TrajTracksMap); + if (analyzerMode_) + tkDetector_.TrkSize->Fill(m_TrajTracksMap->size()); + + if (maxTracksPerEvent_ != 0 && m_TrajTracksMap->size() > maxTracksPerEvent_) + return; + + //Creation of (traj,track) + typedef std::pair ConstTrajTrackPair; + typedef std::vector ConstTrajTrackPairCollection; + ConstTrajTrackPairCollection trajTracks; + + TrajTrackAssociationCollection::const_iterator i_trajTrack; + for (i_trajTrack = m_TrajTracksMap->begin(); i_trajTrack != m_TrajTracksMap->end(); ++i_trajTrack) { + trajTracks.push_back(ConstTrajTrackPair(&(*(*i_trajTrack).key), &(*(*i_trajTrack).val))); + } + + //Loop over Tracks & Hits + unsigned int trackSizeGood(0); + ConstTrajTrackPairCollection::const_iterator iTrack; + for (iTrack = trajTracks.begin(); iTrack != trajTracks.end(); ++iTrack) { + const Trajectory* traj = (*iTrack).first; + const reco::Track* track = (*iTrack).second; + + TrackStruct trackStruct; + trackStruct.trkParams = this->fillTrackVariables(*track, *traj, beamSpot); + + if (trackCut_) + continue; + + const std::vector v_meas = (*traj).measurements(); + + //Loop over Hits + for (std::vector::const_iterator i_meas = v_meas.begin(); i_meas != v_meas.end(); ++i_meas) { + TrackStruct::HitParameterStruct hitParams = this->fillHitVariables(*i_meas, iSetup); + if (this->hitSelected(hitParams)) + trackStruct.v_hitParams.push_back(hitParams); + } + + if (analyzerMode_) + this->fillHistsForAnalyzerMode(trackStruct); + if (calculateApe_) + this->fillHistsForApeCalculation(trackStruct); + + if (!trackStruct.v_hitParams.empty()) + ++trackSizeGood; + } + if (analyzerMode_ && trackSizeGood > 0) + tkDetector_.TrkSizeGood->Fill(trackSizeGood); +} // ------------ method called once each job just before starting event loop ------------ -void -ApeEstimator::beginJob(){ - this->hitSelection(); - - this->sectorBuilder(); - - this->residualErrorBinning(); - - if(analyzerMode_)this->bookSectorHistsForAnalyzerMode(); - - if(calculateApe_)this->bookSectorHistsForApeCalculation(); - - if(analyzerMode_)this->bookTrackHists(); - - +void ApeEstimator::beginJob() { + this->hitSelection(); + + this->sectorBuilder(); + + this->residualErrorBinning(); + + if (analyzerMode_) + this->bookSectorHistsForAnalyzerMode(); + + if (calculateApe_) + this->bookSectorHistsForApeCalculation(); + + if (analyzerMode_) + this->bookTrackHists(); } // ------------ method called once each job just after ending the event loop ------------ -void -ApeEstimator::endJob() { - if(calculateApe_)this->calculateAPE(); - - edm::LogInfo("HitSelector")<<"\nThere are "<calculateAPE(); + + edm::LogInfo("HitSelector") << "\nThere are " << counter1 << " negative Errors calculated\n"; } //define this as a plug-in diff --git a/Alignment/APEEstimation/plugins/ApeEstimatorSummary.cc b/Alignment/APEEstimation/plugins/ApeEstimatorSummary.cc index 593a85c2dc369..81ef71063d6e5 100644 --- a/Alignment/APEEstimation/plugins/ApeEstimatorSummary.cc +++ b/Alignment/APEEstimation/plugins/ApeEstimatorSummary.cc @@ -2,7 +2,7 @@ // // Package: ApeEstimatorSummary // Class: ApeEstimatorSummary -// +// /**\class ApeEstimatorSummary ApeEstimatorSummary.cc Alignment/APEEstimation/src/ApeEstimatorSummary.cc Description: [one line class summary] @@ -18,7 +18,6 @@ // // - // system include files #include #include @@ -39,7 +38,6 @@ #include "CLHEP/Matrix/SymMatrix.h" - //#include "CondFormats/AlignmentRecord/interface/TrackerAlignmentRcd.h" #include "CondFormats/AlignmentRecord/interface/TrackerAlignmentErrorExtendedRcd.h" #include "CondFormats/Alignment/interface/AlignmentErrorsExtended.h" @@ -47,7 +45,6 @@ //............... #include "Alignment/APEEstimation/interface/TrackerSectorStruct.h" - #include "TH1.h" #include "TString.h" #include "TFile.h" @@ -60,36 +57,34 @@ // class ApeEstimatorSummary : public edm::one::EDAnalyzer<> { - public: - explicit ApeEstimatorSummary(const edm::ParameterSet&); - ~ApeEstimatorSummary() override; - - - private: - void beginJob() override ; - void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override ; - - void openInputFile(); - void getTrackerSectorStructs(); - void bookHists(); - std::vector residualErrorBinning(); - void writeHists(); - - void calculateApe(); - - enum ApeWeight{wInvalid, wUnity, wEntries, wEntriesOverSigmaX2}; - - // ----------member data --------------------------- - const edm::ParameterSet parameterSet_; - - bool firstEvent=true; - - - TFile* inputFile_; - - std::map m_tkSector_; - unsigned int noSectors_; +public: + explicit ApeEstimatorSummary(const edm::ParameterSet&); + ~ApeEstimatorSummary() override; + +private: + void beginJob() override; + void analyze(const edm::Event&, const edm::EventSetup&) override; + void endJob() override; + + void openInputFile(); + void getTrackerSectorStructs(); + void bookHists(); + std::vector residualErrorBinning(); + void writeHists(); + + void calculateApe(); + + enum ApeWeight { wInvalid, wUnity, wEntries, wEntriesOverSigmaX2 }; + + // ----------member data --------------------------- + const edm::ParameterSet parameterSet_; + + bool firstEvent = true; + + TFile* inputFile_; + + std::map m_tkSector_; + unsigned int noSectors_; }; // @@ -103,192 +98,220 @@ class ApeEstimatorSummary : public edm::one::EDAnalyzer<> { // // constructors and destructor // -ApeEstimatorSummary::ApeEstimatorSummary(const edm::ParameterSet& iConfig): - parameterSet_(iConfig), - inputFile_(nullptr) -{ -} - - -ApeEstimatorSummary::~ApeEstimatorSummary() -{ -} +ApeEstimatorSummary::ApeEstimatorSummary(const edm::ParameterSet& iConfig) + : parameterSet_(iConfig), inputFile_(nullptr) {} +ApeEstimatorSummary::~ApeEstimatorSummary() {} // // member functions // - -void -ApeEstimatorSummary::openInputFile(){ +void ApeEstimatorSummary::openInputFile() { const std::string inputFileName(parameterSet_.getParameter("InputFile")); std::ifstream inputFileStream; // Check if baseline file exists inputFileStream.open(inputFileName.c_str()); - if(inputFileStream.is_open()){ - inputFile_ = new TFile(inputFileName.c_str(),"READ"); - } - if(inputFile_){ - edm::LogInfo("CalculateAPE")<<"Input file from loop over tracks and corresponding hits sucessfully opened"; + if (inputFileStream.is_open()) { + inputFile_ = new TFile(inputFileName.c_str(), "READ"); } - else{ - edm::LogError("CalculateAPE")<<"There is NO input file\n" - <<"...APE calculation stopped. Please check path of input file name in config:\n" - <<"\t"<GetListOfKeys()->At(0)->GetName()); - + pluginName += "/"; TDirectory *sectorDir(nullptr), *intervalDir(nullptr); bool sectorBool(true); unsigned int iSector(1); - for(;sectorBool;++iSector){ + for (; sectorBool; ++iSector) { std::stringstream sectorName, fullSectorName; sectorName << "Sector_" << iSector << "/"; fullSectorName << pluginName << sectorName.str(); TString fullName(fullSectorName.str().c_str()); inputFile_->cd(); sectorDir = (TDirectory*)inputFile_->TDirectory::GetDirectory(fullName); - if(sectorDir){ + if (sectorDir) { TrackerSectorStruct tkSector; sectorDir->GetObject("z_name;1", tkSector.Name); tkSector.name = tkSector.Name->GetTitle(); bool intervalBool(true); - for(unsigned int iInterval(1);intervalBool;++iInterval){ + for (unsigned int iInterval(1); intervalBool; ++iInterval) { std::stringstream intervalName, fullIntervalName; - intervalName << "Interval_" << iInterval <<"/"; + intervalName << "Interval_" << iInterval << "/"; fullIntervalName << fullSectorName.str() << intervalName.str(); fullName = fullIntervalName.str().c_str(); intervalDir = (TDirectory*)inputFile_->TDirectory::GetDirectory(fullName); - if(intervalDir){ + if (intervalDir) { intervalDir->GetObject("h_sigmaX;1", tkSector.m_binnedHists[iInterval]["sigmaX"]); intervalDir->GetObject("h_norResX;1", tkSector.m_binnedHists[iInterval]["norResX"]); intervalDir->GetObject("h_sigmaY;1", tkSector.m_binnedHists[iInterval]["sigmaY"]); intervalDir->GetObject("h_norResY;1", tkSector.m_binnedHists[iInterval]["norResY"]); - if(tkSector.m_binnedHists[iInterval]["sigmaY"] && tkSector.m_binnedHists[iInterval]["norResY"]){ + if (tkSector.m_binnedHists[iInterval]["sigmaY"] && tkSector.m_binnedHists[iInterval]["norResY"]) { tkSector.isPixel = true; } - }else{ + } else { intervalBool = false; - if(iSector==1)edm::LogInfo("CalculateAPE")<<"There are "<TDirectory::GetDirectory(fullName); - if(resultsDir){ + if (resultsDir) { resultsDir->GetObject("h_entriesX;1", tkSector.EntriesX); - if(tkSector.isPixel)resultsDir->GetObject("h_entriesY;1", tkSector.EntriesY); + if (tkSector.isPixel) + resultsDir->GetObject("h_entriesY;1", tkSector.EntriesY); TTree* rawIdTree(nullptr); resultsDir->GetObject("rawIdTree", rawIdTree); unsigned int rawId(0); rawIdTree->SetBranchAddress("RawId", &rawId); - for(int entry=0; entryGetEntries(); ++entry){ + for (int entry = 0; entry < rawIdTree->GetEntries(); ++entry) { rawIdTree->GetEntry(entry); // command "hadd" adds entries in TTree, so rawId are existing as often as number of files are added bool alreadyAdded(false); - for(auto const & i_rawId : tkSector.v_rawId){ - if(rawId==i_rawId)alreadyAdded = true; + for (auto const& i_rawId : tkSector.v_rawId) { + if (rawId == i_rawId) + alreadyAdded = true; } - if(alreadyAdded)break; + if (alreadyAdded) + break; tkSector.v_rawId.push_back(rawId); } } m_tkSector_[iSector] = tkSector; - }else{ + } else { sectorBool = false; - edm::LogInfo("CalculateAPE")<<"There are "< v_binX(this->residualErrorBinning()); - for(auto & i_sector : m_tkSector_){ - i_sector.second.WeightX = new TH1F("h_weightX","relative weight w_{x}/w_{tot,x};#sigma_{x} [#mum];w_{x}/w_{tot,x}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.MeanX = new TH1F("h_meanX","residual mean ;#sigma_{x} [#mum];",v_binX.size()-1,&(v_binX[0])); - i_sector.second.RmsX = new TH1F("h_rmsX","residual rms RMS(r_{x}/#sigma_{r,x});#sigma_{x} [#mum];RMS(r_{x}/#sigma_{r,x})",v_binX.size()-1,&(v_binX[0])); - i_sector.second.FitMeanX1 = new TH1F("h_fitMeanX1","fitted residual mean #mu_{x};#sigma_{x} [#mum];#mu_{x}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.ResidualWidthX1 = new TH1F("h_residualWidthX1","residual width #Delta_{x};#sigma_{x} [#mum];#Delta_{x}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.CorrectionX1 = new TH1F("h_correctionX1","correction to APE_{x};#sigma_{x} [#mum];#Delta#sigma_{align,x} [#mum]",v_binX.size()-1,&(v_binX[0])); - i_sector.second.FitMeanX2 = new TH1F("h_fitMeanX2","fitted residual mean #mu_{x};#sigma_{x} [#mum];#mu_{x}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.ResidualWidthX2 = new TH1F("h_residualWidthX2","residual width #Delta_{x};#sigma_{x} [#mum];#Delta_{x}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.CorrectionX2 = new TH1F("h_correctionX2","correction to APE_{x};#sigma_{x} [#mum];#Delta#sigma_{align,x} [#mum]",v_binX.size()-1,&(v_binX[0])); - - if(i_sector.second.isPixel){ - i_sector.second.WeightY = new TH1F("h_weightY","relative weight w_{y}/w_{tot,y};#sigma_{y} [#mum];w_{y}/w_{tot,y}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.MeanY = new TH1F("h_meanY","residual mean ;#sigma_{y} [#mum];",v_binX.size()-1,&(v_binX[0])); - i_sector.second.RmsY = new TH1F("h_rmsY","residual rms RMS(r_{y}/#sigma_{r,y});#sigma_{y} [#mum];RMS(r_{y}/#sigma_{r,y})",v_binX.size()-1,&(v_binX[0])); - i_sector.second.FitMeanY1 = new TH1F("h_fitMeanY1","fitted residual mean #mu_{y};#sigma_{y} [#mum];#mu_{y}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.ResidualWidthY1 = new TH1F("h_residualWidthY1","residual width #Delta_{y};#sigma_{y} [#mum];#Delta_{y}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.CorrectionY1 = new TH1F("h_correctionY1","correction to APE_{y};#sigma_{y} [#mum];#Delta#sigma_{align,y} [#mum]",v_binX.size()-1,&(v_binX[0])); - i_sector.second.FitMeanY2 = new TH1F("h_fitMeanY2","fitted residual mean #mu_{y};#sigma_{y} [#mum];#mu_{y}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.ResidualWidthY2 = new TH1F("h_residualWidthY2","residual width #Delta_{y};#sigma_{y} [#mum];#Delta_{y}",v_binX.size()-1,&(v_binX[0])); - i_sector.second.CorrectionY2 = new TH1F("h_correctionY2","correction to APE_{y};#sigma_{y} [#mum];#Delta#sigma_{align,y} [#mum]",v_binX.size()-1,&(v_binX[0])); + for (auto& i_sector : m_tkSector_) { + i_sector.second.WeightX = new TH1F("h_weightX", + "relative weight w_{x}/w_{tot,x};#sigma_{x} [#mum];w_{x}/w_{tot,x}", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.MeanX = new TH1F("h_meanX", + "residual mean ;#sigma_{x} [#mum];", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.RmsX = new TH1F("h_rmsX", + "residual rms RMS(r_{x}/#sigma_{r,x});#sigma_{x} [#mum];RMS(r_{x}/#sigma_{r,x})", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.FitMeanX1 = new TH1F( + "h_fitMeanX1", "fitted residual mean #mu_{x};#sigma_{x} [#mum];#mu_{x}", v_binX.size() - 1, &(v_binX[0])); + i_sector.second.ResidualWidthX1 = new TH1F("h_residualWidthX1", + "residual width #Delta_{x};#sigma_{x} [#mum];#Delta_{x}", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.CorrectionX1 = new TH1F("h_correctionX1", + "correction to APE_{x};#sigma_{x} [#mum];#Delta#sigma_{align,x} [#mum]", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.FitMeanX2 = new TH1F( + "h_fitMeanX2", "fitted residual mean #mu_{x};#sigma_{x} [#mum];#mu_{x}", v_binX.size() - 1, &(v_binX[0])); + i_sector.second.ResidualWidthX2 = new TH1F("h_residualWidthX2", + "residual width #Delta_{x};#sigma_{x} [#mum];#Delta_{x}", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.CorrectionX2 = new TH1F("h_correctionX2", + "correction to APE_{x};#sigma_{x} [#mum];#Delta#sigma_{align,x} [#mum]", + v_binX.size() - 1, + &(v_binX[0])); + + if (i_sector.second.isPixel) { + i_sector.second.WeightY = new TH1F("h_weightY", + "relative weight w_{y}/w_{tot,y};#sigma_{y} [#mum];w_{y}/w_{tot,y}", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.MeanY = new TH1F("h_meanY", + "residual mean ;#sigma_{y} [#mum];", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.RmsY = new TH1F("h_rmsY", + "residual rms RMS(r_{y}/#sigma_{r,y});#sigma_{y} [#mum];RMS(r_{y}/#sigma_{r,y})", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.FitMeanY1 = new TH1F( + "h_fitMeanY1", "fitted residual mean #mu_{y};#sigma_{y} [#mum];#mu_{y}", v_binX.size() - 1, &(v_binX[0])); + i_sector.second.ResidualWidthY1 = new TH1F("h_residualWidthY1", + "residual width #Delta_{y};#sigma_{y} [#mum];#Delta_{y}", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.CorrectionY1 = new TH1F("h_correctionY1", + "correction to APE_{y};#sigma_{y} [#mum];#Delta#sigma_{align,y} [#mum]", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.FitMeanY2 = new TH1F( + "h_fitMeanY2", "fitted residual mean #mu_{y};#sigma_{y} [#mum];#mu_{y}", v_binX.size() - 1, &(v_binX[0])); + i_sector.second.ResidualWidthY2 = new TH1F("h_residualWidthY2", + "residual width #Delta_{y};#sigma_{y} [#mum];#Delta_{y}", + v_binX.size() - 1, + &(v_binX[0])); + i_sector.second.CorrectionY2 = new TH1F("h_correctionY2", + "correction to APE_{y};#sigma_{y} [#mum];#Delta#sigma_{align,y} [#mum]", + v_binX.size() - 1, + &(v_binX[0])); } } } - - -std::vector -ApeEstimatorSummary::residualErrorBinning(){ +std::vector ApeEstimatorSummary::residualErrorBinning() { std::vector v_binX; TH1* EntriesX(m_tkSector_[1].EntriesX); - for(int iBin=1; iBin<=EntriesX->GetNbinsX()+1; ++iBin){ + for (int iBin = 1; iBin <= EntriesX->GetNbinsX() + 1; ++iBin) { v_binX.push_back(EntriesX->GetBinLowEdge(iBin)); } return v_binX; } - -void -ApeEstimatorSummary::writeHists(){ +void ApeEstimatorSummary::writeHists() { TFile* resultsFile = new TFile(parameterSet_.getParameter("ResultsFile").c_str(), "RECREATE"); TDirectory* baseDir = resultsFile->mkdir("ApeEstimatorSummary"); - for(auto const & i_sector : m_tkSector_){ + for (auto const& i_sector : m_tkSector_) { std::stringstream dirName; - dirName<<"Sector_" << i_sector.first; + dirName << "Sector_" << i_sector.first; TDirectory* dir = baseDir->mkdir(dirName.str().c_str()); dir->cd(); - + i_sector.second.Name->Write(); - + i_sector.second.WeightX->Write(); i_sector.second.MeanX->Write(); - i_sector.second.RmsX->Write(); - i_sector.second.FitMeanX1->Write(); - i_sector.second.ResidualWidthX1 ->Write(); - i_sector.second.CorrectionX1->Write(); - i_sector.second.FitMeanX2->Write(); + i_sector.second.RmsX->Write(); + i_sector.second.FitMeanX1->Write(); + i_sector.second.ResidualWidthX1->Write(); + i_sector.second.CorrectionX1->Write(); + i_sector.second.FitMeanX2->Write(); i_sector.second.ResidualWidthX2->Write(); i_sector.second.CorrectionX2->Write(); - - if(i_sector.second.isPixel){ + + if (i_sector.second.isPixel) { i_sector.second.WeightY->Write(); i_sector.second.MeanY->Write(); - i_sector.second.RmsY->Write(); - i_sector.second.FitMeanY1->Write(); - i_sector.second.ResidualWidthY1 ->Write(); - i_sector.second.CorrectionY1->Write(); - i_sector.second.FitMeanY2->Write(); + i_sector.second.RmsY->Write(); + i_sector.second.FitMeanY1->Write(); + i_sector.second.ResidualWidthY1->Write(); + i_sector.second.CorrectionY1->Write(); + i_sector.second.FitMeanY2->Write(); i_sector.second.ResidualWidthY2->Write(); i_sector.second.CorrectionY2->Write(); } @@ -296,13 +319,10 @@ ApeEstimatorSummary::writeHists(){ resultsFile->Close(); } - - -void -ApeEstimatorSummary::calculateApe(){ +void ApeEstimatorSummary::calculateApe() { // Set baseline or calculate APE value? const bool setBaseline(parameterSet_.getParameter("setBaseline")); - + // Read in baseline file for calculation of APE value (if not setting baseline) // Has same format as iterationFile const std::string baselineFileName(parameterSet_.getParameter("BaselineFile")); @@ -310,164 +330,170 @@ ApeEstimatorSummary::calculateApe(){ TTree* baselineTreeX(nullptr); TTree* baselineTreeY(nullptr); TTree* sectorNameBaselineTree(nullptr); - if(!setBaseline){ + if (!setBaseline) { std::ifstream baselineFileStream; // Check if baseline file exists baselineFileStream.open(baselineFileName.c_str()); - if(baselineFileStream.is_open()){ + if (baselineFileStream.is_open()) { baselineFileStream.close(); - baselineFile = new TFile(baselineFileName.c_str(),"READ"); + baselineFile = new TFile(baselineFileName.c_str(), "READ"); } - if(baselineFile){ - edm::LogInfo("CalculateAPE")<<"Baseline file for APE values sucessfully opened"; - baselineFile->GetObject("iterTreeX;1",baselineTreeX); - baselineFile->GetObject("iterTreeY;1",baselineTreeY); - baselineFile->GetObject("nameTree;1",sectorNameBaselineTree); - }else{ - edm::LogWarning("CalculateAPE")<<"There is NO baseline file for APE values, so normalized residual width =1 for ideal conditions is assumed"; + if (baselineFile) { + edm::LogInfo("CalculateAPE") << "Baseline file for APE values sucessfully opened"; + baselineFile->GetObject("iterTreeX;1", baselineTreeX); + baselineFile->GetObject("iterTreeY;1", baselineTreeY); + baselineFile->GetObject("nameTree;1", sectorNameBaselineTree); + } else { + edm::LogWarning("CalculateAPE") << "There is NO baseline file for APE values, so normalized residual width =1 " + "for ideal conditions is assumed"; } } - + // Set up root file for iterations on APE value (or for setting baseline in setBaseline mode) - const std::string iterationFileName(setBaseline ? baselineFileName : parameterSet_.getParameter("IterationFile")); + const std::string iterationFileName(setBaseline ? baselineFileName + : parameterSet_.getParameter("IterationFile")); // For iterations, updates are needed to not overwrite the iterations before - TFile* iterationFile = new TFile(iterationFileName.c_str(),setBaseline ? "RECREATE" : "UPDATE"); - - + TFile* iterationFile = new TFile(iterationFileName.c_str(), setBaseline ? "RECREATE" : "UPDATE"); + // Set up TTree for iterative APE values on first pass (first iteration) or read from file (further iterations) TTree* iterationTreeX(nullptr); TTree* iterationTreeY(nullptr); - iterationFile->GetObject("iterTreeX;1",iterationTreeX); - iterationFile->GetObject("iterTreeY;1",iterationTreeY); + iterationFile->GetObject("iterTreeX;1", iterationTreeX); + iterationFile->GetObject("iterTreeY;1", iterationTreeY); // The same for TTree containing the names of the sectors (no additional check, since always handled exactly as iterationTree) TTree* sectorNameTree(nullptr); - iterationFile->GetObject("nameTree;1",sectorNameTree); - + iterationFile->GetObject("nameTree;1", sectorNameTree); + bool firstIter(false); - if(!iterationTreeX){ // should be always true in setBaseline mode, since file is recreated + if (!iterationTreeX) { // should be always true in setBaseline mode, since file is recreated firstIter = true; - if(!setBaseline){ - iterationTreeX = new TTree("iterTreeX","Tree for APE x values of all iterations"); - iterationTreeY = new TTree("iterTreeY","Tree for APE y values of all iterations"); - edm::LogInfo("CalculateAPE")<<"First APE iteration (number 0.), create iteration file with TTree"; - sectorNameTree = new TTree("nameTree","Tree with names of sectors"); - }else{ - iterationTreeX = new TTree("iterTreeX","Tree for baseline x values of normalized residual width"); - iterationTreeY = new TTree("iterTreeY","Tree for baseline y values of normalized residual width"); - edm::LogInfo("CalculateAPE")<<"Set baseline, create baseline file with TTree"; - sectorNameTree = new TTree("nameTree","Tree with names of sectors"); + if (!setBaseline) { + iterationTreeX = new TTree("iterTreeX", "Tree for APE x values of all iterations"); + iterationTreeY = new TTree("iterTreeY", "Tree for APE y values of all iterations"); + edm::LogInfo("CalculateAPE") << "First APE iteration (number 0.), create iteration file with TTree"; + sectorNameTree = new TTree("nameTree", "Tree with names of sectors"); + } else { + iterationTreeX = new TTree("iterTreeX", "Tree for baseline x values of normalized residual width"); + iterationTreeY = new TTree("iterTreeY", "Tree for baseline y values of normalized residual width"); + edm::LogInfo("CalculateAPE") << "Set baseline, create baseline file with TTree"; + sectorNameTree = new TTree("nameTree", "Tree with names of sectors"); } - }else{ + } else { const unsigned int iteration(iterationTreeX->GetEntries()); - edm::LogWarning("CalculateAPE")<<"NOT the first APE iteration (number 0.) but the "<SetBranchAddress(ss_sector.str().c_str(), &a_baselineSectorX[iSector]); baselineTreeX->GetEntry(0); - if(pixelSector){ + if (pixelSector) { baselineTreeY->SetBranchAddress(ss_sector.str().c_str(), &a_baselineSectorY[iSector]); baselineTreeY->GetEntry(0); } sectorNameBaselineTree->SetBranchAddress(ss_sector.str().c_str(), &a_sectorBaselineName[iSector]); sectorNameBaselineTree->GetEntry(0); - }else{ + } else { // Set default ideal normalized residual width to 1 a_baselineSectorX[iSector] = 1.; a_baselineSectorY[iSector] = 1.; } - if(firstIter){ // should be always true in setBaseline mode, since file is recreated + if (firstIter) { // should be always true in setBaseline mode, since file is recreated ss_sectorSuffixed << ss_sector.str() << "/D"; iterationTreeX->Branch(ss_sector.str().c_str(), &a_apeSectorX[iSector], ss_sectorSuffixed.str().c_str()); - if(pixelSector){ + if (pixelSector) { iterationTreeY->Branch(ss_sector.str().c_str(), &a_apeSectorY[iSector], ss_sectorSuffixed.str().c_str()); } sectorNameTree->Branch(ss_sector.str().c_str(), &a_sectorName[iSector], 32000, 00); - }else{ + } else { iterationTreeX->SetBranchAddress(ss_sector.str().c_str(), &a_apeSectorX[iSector]); - iterationTreeX->GetEntry(iterationTreeX->GetEntries()-1); - if(pixelSector){ + iterationTreeX->GetEntry(iterationTreeX->GetEntries() - 1); + if (pixelSector) { iterationTreeY->SetBranchAddress(ss_sector.str().c_str(), &a_apeSectorY[iSector]); - iterationTreeY->GetEntry(iterationTreeY->GetEntries()-1); + iterationTreeY->GetEntry(iterationTreeY->GetEntries() - 1); } sectorNameTree->SetBranchAddress(ss_sector.str().c_str(), &a_sectorName[iSector]); sectorNameTree->GetEntry(0); } } - - + // Check whether sector definitions are identical with the ones of previous iterations and with the ones in baseline file - for(auto & i_sector : m_tkSector_){ + for (auto& i_sector : m_tkSector_) { const std::string& name(i_sector.second.name); - if(!firstIter){ + if (!firstIter) { const std::string& nameLastIter(*a_sectorName[i_sector.first]); - if(name!=nameLastIter){ - edm::LogError("CalculateAPE")<<"Inconsistent sector definition in iterationFile for sector "<("ApeOutputFile")); apeOutputFile.open(apeOutputFileName.c_str()); - if(apeOutputFile.is_open()){ - edm::LogInfo("CalculateAPE")<<"Text file for writing APE values successfully opened"; - }else{ - edm::LogError("CalculateAPE")<<"Text file for writing APE values NOT opened,\n" - <<"...APE calculation stopped. Please check path of text file name in config:\n" - <<"\t"<("apeWeight")); ApeWeight apeWeight(wInvalid); - if(apeWeightName=="unity") apeWeight = wUnity; - else if(apeWeightName=="entries")apeWeight = wEntries; - else if(apeWeightName=="entriesOverSigmaX2")apeWeight = wEntriesOverSigmaX2; - if(apeWeight==wInvalid){ - edm::LogError("CalculateAPE")<<"Invalid parameter 'apeWeight' in cfg file: \""<("minHitsPerInterval")); @@ -475,78 +501,81 @@ ApeEstimatorSummary::calculateApe(){ const double correctionScaling(parameterSet_.getParameter("correctionScaling")); const bool smoothIteration(parameterSet_.getParameter("smoothIteration")); const double smoothFraction(parameterSet_.getParameter("smoothFraction")); - if(smoothFraction<=0. || smoothFraction>1.){ - edm::LogError("CalculateAPE")<<"Incorrect parameter in cfg file," - <<"\nsmoothFraction has to be in [0,1], but is "< 1.) { + edm::LogError("CalculateAPE") << "Incorrect parameter in cfg file," + << "\nsmoothFraction has to be in [0,1], but is " << smoothFraction + << "\n...APE calculation stopped."; return; } - for(auto & i_sector : m_tkSector_){ - typedef std::pair Error2AndResidualWidth2PerBin; - typedef std::pair WeightAndResultsPerBin; + for (auto& i_sector : m_tkSector_) { + typedef std::pair Error2AndResidualWidth2PerBin; + typedef std::pair WeightAndResultsPerBin; std::vector v_weightAndResultsPerBinX; std::vector v_weightAndResultsPerBinY; - + double baselineWidthX2(a_baselineSectorX[i_sector.first]); double baselineWidthY2(a_baselineSectorY[i_sector.first]); - + // Loop over residual error bins to calculate APE for every bin - for(auto const & i_errBins : i_sector.second.m_binnedHists){ - std::map mHists = i_errBins.second; - + for (auto const& i_errBins : i_sector.second.m_binnedHists) { + std::map mHists = i_errBins.second; + double entriesX = mHists["sigmaX"]->GetEntries(); - double meanSigmaX = mHists["sigmaX"]->GetMean(); - + double meanSigmaX = mHists["sigmaX"]->GetMean(); + // Fitting Parameters - double xMin = mHists["norResX"]->GetXaxis()->GetXmin(); - double xMax = mHists["norResX"]->GetXaxis()->GetXmax(); + double xMin = mHists["norResX"]->GetXaxis()->GetXmin(); + double xMax = mHists["norResX"]->GetXaxis()->GetXmax(); double integralX = mHists["norResX"]->Integral(); - double meanX = mHists["norResX"]->GetMean(); - double rmsX = mHists["norResX"]->GetRMS(); - double maximumX = mHists["norResX"]->GetBinContent(mHists["norResX"]->GetMaximumBin()); - + double meanX = mHists["norResX"]->GetMean(); + double rmsX = mHists["norResX"]->GetRMS(); + double maximumX = mHists["norResX"]->GetBinContent(mHists["norResX"]->GetMaximumBin()); + // First Gaus Fit TF1 funcX_1("mygausX", "gaus", xMin, xMax); funcX_1.SetParameters(maximumX, meanX, rmsX); - TString fitOpt("ILERQ"); //TString fitOpt("IMR"); ("IRLL"); ("IRQ"); - if(integralX>minHitsPerInterval){ - if(mHists["norResX"]->Fit(&funcX_1, fitOpt)){ - edm::LogWarning("CalculateAPE")<<"Fit1 did not work: "<Fit(&funcX_1, fitOpt); + TString fitOpt("ILERQ"); //TString fitOpt("IMR"); ("IRLL"); ("IRQ"); + if (integralX > minHitsPerInterval) { + if (mHists["norResX"]->Fit(&funcX_1, fitOpt)) { + edm::LogWarning("CalculateAPE") << "Fit1 did not work: " << mHists["norResX"]->Fit(&funcX_1, fitOpt); continue; } - LogDebug("CalculateAPE")<<"FitResultX1\t"<Fit(&funcX_1, fitOpt)<<"\n"; + LogDebug("CalculateAPE") << "FitResultX1\t" << mHists["norResX"]->Fit(&funcX_1, fitOpt) << "\n"; } - double meanX_1 = funcX_1.GetParameter(1); + double meanX_1 = funcX_1.GetParameter(1); double sigmaX_1 = funcX_1.GetParameter(2); - + // Second gaus fit - TF1 funcX_2("mygausX2","gaus",meanX_1 - sigmaFactorFit*TMath::Abs(sigmaX_1), meanX_1 + sigmaFactorFit*TMath::Abs(sigmaX_1)); - funcX_2.SetParameters(funcX_1.GetParameter(0),meanX_1,sigmaX_1); - if(integralX>minHitsPerInterval){ - if(mHists["norResX"]->Fit(&funcX_2, fitOpt)){ - edm::LogWarning("CalculateAPE")<<"Fit2 did not work for x : "<Fit(&funcX_2, fitOpt); + TF1 funcX_2("mygausX2", + "gaus", + meanX_1 - sigmaFactorFit * TMath::Abs(sigmaX_1), + meanX_1 + sigmaFactorFit * TMath::Abs(sigmaX_1)); + funcX_2.SetParameters(funcX_1.GetParameter(0), meanX_1, sigmaX_1); + if (integralX > minHitsPerInterval) { + if (mHists["norResX"]->Fit(&funcX_2, fitOpt)) { + edm::LogWarning("CalculateAPE") << "Fit2 did not work for x : " << mHists["norResX"]->Fit(&funcX_2, fitOpt); continue; } - LogDebug("CalculateAPE")<<"FitResultX2\t"<Fit(&funcX_2, fitOpt)<<"\n"; + LogDebug("CalculateAPE") << "FitResultX2\t" << mHists["norResX"]->Fit(&funcX_2, fitOpt) << "\n"; } - double meanX_2 = funcX_2.GetParameter(1); + double meanX_2 = funcX_2.GetParameter(1); double sigmaX_2 = funcX_2.GetParameter(2); - + // Now the same for y coordinate double entriesY(0.); double meanSigmaY(0.); - if(i_sector.second.isPixel){ + if (i_sector.second.isPixel) { entriesY = mHists["sigmaY"]->GetEntries(); meanSigmaY = mHists["sigmaY"]->GetMean(); } - + double meanY_1(0.); double sigmaY_1(0.); double meanY_2(0.); double sigmaY_2(0.); double meanY(0.); double rmsY(0.); - if(i_sector.second.isPixel){ + if (i_sector.second.isPixel) { // Fitting Parameters double yMin = mHists["norResY"]->GetXaxis()->GetXmin(); double yMax = mHists["norResY"]->GetXaxis()->GetXmax(); @@ -554,375 +583,400 @@ ApeEstimatorSummary::calculateApe(){ meanY = mHists["norResY"]->GetMean(); rmsY = mHists["norResY"]->GetRMS(); double maximumY = mHists["norResY"]->GetBinContent(mHists["norResY"]->GetMaximumBin()); - + // First Gaus Fit TF1 funcY_1("mygausY", "gaus", yMin, yMax); funcY_1.SetParameters(maximumY, meanY, rmsY); - if(integralY>minHitsPerInterval){ - if(mHists["norResY"]->Fit(&funcY_1, fitOpt)){ - edm::LogWarning("CalculateAPE")<<"Fit1 did not work: "<Fit(&funcY_1, fitOpt); + if (integralY > minHitsPerInterval) { + if (mHists["norResY"]->Fit(&funcY_1, fitOpt)) { + edm::LogWarning("CalculateAPE") << "Fit1 did not work: " << mHists["norResY"]->Fit(&funcY_1, fitOpt); continue; } - LogDebug("CalculateAPE")<<"FitResultY1\t"<Fit(&funcY_1, fitOpt)<<"\n"; + LogDebug("CalculateAPE") << "FitResultY1\t" << mHists["norResY"]->Fit(&funcY_1, fitOpt) << "\n"; } - meanY_1 = funcY_1.GetParameter(1); + meanY_1 = funcY_1.GetParameter(1); sigmaY_1 = funcY_1.GetParameter(2); - + // Second gaus fit - TF1 funcY_2("mygausY2","gaus",meanY_1 - sigmaFactorFit*TMath::Abs(sigmaY_1), meanY_1 + sigmaFactorFit*TMath::Abs(sigmaY_1)); - funcY_2.SetParameters(funcY_1.GetParameter(0),meanY_1,sigmaY_1); - if(integralY>minHitsPerInterval){ - if(mHists["norResY"]->Fit(&funcY_2, fitOpt)){ - edm::LogWarning("CalculateAPE")<<"Fit2 did not work for y : "<Fit(&funcY_2, fitOpt); + TF1 funcY_2("mygausY2", + "gaus", + meanY_1 - sigmaFactorFit * TMath::Abs(sigmaY_1), + meanY_1 + sigmaFactorFit * TMath::Abs(sigmaY_1)); + funcY_2.SetParameters(funcY_1.GetParameter(0), meanY_1, sigmaY_1); + if (integralY > minHitsPerInterval) { + if (mHists["norResY"]->Fit(&funcY_2, fitOpt)) { + edm::LogWarning("CalculateAPE") << "Fit2 did not work for y : " << mHists["norResY"]->Fit(&funcY_2, fitOpt); continue; } - LogDebug("CalculateAPE")<<"FitResultY2\t"<Fit(&funcY_2, fitOpt)<<"\n"; + LogDebug("CalculateAPE") << "FitResultY2\t" << mHists["norResY"]->Fit(&funcY_2, fitOpt) << "\n"; } - meanY_2 = funcY_2.GetParameter(1); + meanY_2 = funcY_2.GetParameter(1); sigmaY_2 = funcY_2.GetParameter(2); } - + // Fill histograms double fitMeanX_1(meanX_1), fitMeanX_2(meanX_2); double residualWidthX_1(sigmaX_1), residualWidthX_2(sigmaX_2); double fitMeanY_1(meanY_1), fitMeanY_2(meanY_2); double residualWidthY_1(sigmaY_1), residualWidthY_2(sigmaY_2); - + double correctionX2_1(-0.0010), correctionX2_2(-0.0010); double correctionY2_1(-0.0010), correctionY2_2(-0.0010); - correctionX2_1 = meanSigmaX*meanSigmaX*(residualWidthX_1*residualWidthX_1 -baselineWidthX2); - correctionX2_2 = meanSigmaX*meanSigmaX*(residualWidthX_2*residualWidthX_2 -baselineWidthX2); - if(i_sector.second.isPixel){ - correctionY2_1 = meanSigmaY*meanSigmaY*(residualWidthY_1*residualWidthY_1 -baselineWidthY2); - correctionY2_2 = meanSigmaY*meanSigmaY*(residualWidthY_2*residualWidthY_2 -baselineWidthY2); - } - - double correctionX_1 = correctionX2_1>=0. ? std::sqrt(correctionX2_1) : -std::sqrt(-correctionX2_1); - double correctionX_2 = correctionX2_2>=0. ? std::sqrt(correctionX2_2) : -std::sqrt(-correctionX2_2); - double correctionY_1 = correctionY2_1>=0. ? std::sqrt(correctionY2_1) : -std::sqrt(-correctionY2_1); - double correctionY_2 = correctionY2_2>=0. ? std::sqrt(correctionY2_2) : -std::sqrt(-correctionY2_2); + correctionX2_1 = meanSigmaX * meanSigmaX * (residualWidthX_1 * residualWidthX_1 - baselineWidthX2); + correctionX2_2 = meanSigmaX * meanSigmaX * (residualWidthX_2 * residualWidthX_2 - baselineWidthX2); + if (i_sector.second.isPixel) { + correctionY2_1 = meanSigmaY * meanSigmaY * (residualWidthY_1 * residualWidthY_1 - baselineWidthY2); + correctionY2_2 = meanSigmaY * meanSigmaY * (residualWidthY_2 * residualWidthY_2 - baselineWidthY2); + } + + double correctionX_1 = correctionX2_1 >= 0. ? std::sqrt(correctionX2_1) : -std::sqrt(-correctionX2_1); + double correctionX_2 = correctionX2_2 >= 0. ? std::sqrt(correctionX2_2) : -std::sqrt(-correctionX2_2); + double correctionY_1 = correctionY2_1 >= 0. ? std::sqrt(correctionY2_1) : -std::sqrt(-correctionY2_1); + double correctionY_2 = correctionY2_2 >= 0. ? std::sqrt(correctionY2_2) : -std::sqrt(-correctionY2_2); // Meanwhile, this got very bad default values, or? (negative corrections allowed) - if(isnan(correctionX_1))correctionX_1 = -0.0010; - if(isnan(correctionX_2))correctionX_2 = -0.0010; - if(isnan(correctionY_1))correctionY_1 = -0.0010; - if(isnan(correctionY_2))correctionY_2 = -0.0010; - - if(entriesXSetBinContent(i_errBins.first,meanX); - i_sector.second.RmsX ->SetBinContent(i_errBins.first,rmsX); - - i_sector.second.FitMeanX1 ->SetBinContent(i_errBins.first,fitMeanX_1); - i_sector.second.ResidualWidthX1->SetBinContent(i_errBins.first,residualWidthX_1); - i_sector.second.CorrectionX1 ->SetBinContent(i_errBins.first,correctionX_1*10000.); - - i_sector.second.FitMeanX2 ->SetBinContent(i_errBins.first,fitMeanX_2); - i_sector.second.ResidualWidthX2->SetBinContent(i_errBins.first,residualWidthX_2); - i_sector.second.CorrectionX2 ->SetBinContent(i_errBins.first,correctionX_2*10000.); - - if(i_sector.second.isPixel){ - i_sector.second.MeanY ->SetBinContent(i_errBins.first,meanY); - i_sector.second.RmsY ->SetBinContent(i_errBins.first,rmsY); - - i_sector.second.FitMeanY1 ->SetBinContent(i_errBins.first,fitMeanY_1); - i_sector.second.ResidualWidthY1->SetBinContent(i_errBins.first,residualWidthY_1); - i_sector.second.CorrectionY1 ->SetBinContent(i_errBins.first,correctionY_1*10000.); - - i_sector.second.FitMeanY2 ->SetBinContent(i_errBins.first,fitMeanY_2); - i_sector.second.ResidualWidthY2->SetBinContent(i_errBins.first,residualWidthY_2); - i_sector.second.CorrectionY2 ->SetBinContent(i_errBins.first,correctionY_2*10000.); - } - - + if (isnan(correctionX_1)) + correctionX_1 = -0.0010; + if (isnan(correctionX_2)) + correctionX_2 = -0.0010; + if (isnan(correctionY_1)) + correctionY_1 = -0.0010; + if (isnan(correctionY_2)) + correctionY_2 = -0.0010; + + if (entriesX < minHitsPerInterval) { + meanX = 0.; + rmsX = -0.0010; + fitMeanX_1 = 0.; + correctionX_1 = residualWidthX_1 = -0.0010; + fitMeanX_2 = 0.; + correctionX_2 = residualWidthX_2 = -0.0010; + } + + if (entriesY < minHitsPerInterval) { + meanY = 0.; + rmsY = -0.0010; + fitMeanY_1 = 0.; + correctionY_1 = residualWidthY_1 = -0.0010; + fitMeanY_2 = 0.; + correctionY_2 = residualWidthY_2 = -0.0010; + } + + i_sector.second.MeanX->SetBinContent(i_errBins.first, meanX); + i_sector.second.RmsX->SetBinContent(i_errBins.first, rmsX); + + i_sector.second.FitMeanX1->SetBinContent(i_errBins.first, fitMeanX_1); + i_sector.second.ResidualWidthX1->SetBinContent(i_errBins.first, residualWidthX_1); + i_sector.second.CorrectionX1->SetBinContent(i_errBins.first, correctionX_1 * 10000.); + + i_sector.second.FitMeanX2->SetBinContent(i_errBins.first, fitMeanX_2); + i_sector.second.ResidualWidthX2->SetBinContent(i_errBins.first, residualWidthX_2); + i_sector.second.CorrectionX2->SetBinContent(i_errBins.first, correctionX_2 * 10000.); + + if (i_sector.second.isPixel) { + i_sector.second.MeanY->SetBinContent(i_errBins.first, meanY); + i_sector.second.RmsY->SetBinContent(i_errBins.first, rmsY); + + i_sector.second.FitMeanY1->SetBinContent(i_errBins.first, fitMeanY_1); + i_sector.second.ResidualWidthY1->SetBinContent(i_errBins.first, residualWidthY_1); + i_sector.second.CorrectionY1->SetBinContent(i_errBins.first, correctionY_1 * 10000.); + + i_sector.second.FitMeanY2->SetBinContent(i_errBins.first, fitMeanY_2); + i_sector.second.ResidualWidthY2->SetBinContent(i_errBins.first, residualWidthY_2); + i_sector.second.CorrectionY2->SetBinContent(i_errBins.first, correctionY_2 * 10000.); + } + // Use result for bin only when entries>=minHitsPerInterval - if(entriesXSetBinContent(i_errBins.first,weightX); + i_sector.second.WeightX->SetBinContent(i_errBins.first, weightX); v_weightAndResultsPerBinX.push_back(weightAndResultsPerBinX); } - - const Error2AndResidualWidth2PerBin error2AndResidualWidth2PerBinY(meanSigmaY*meanSigmaY, residualWidthY_1*residualWidthY_1); + + const Error2AndResidualWidth2PerBin error2AndResidualWidth2PerBinY(meanSigmaY * meanSigmaY, + residualWidthY_1 * residualWidthY_1); const WeightAndResultsPerBin weightAndResultsPerBinY(weightY, error2AndResidualWidth2PerBinY); - if(!(entriesYSetBinContent(i_errBins.first,weightY); + i_sector.second.WeightY->SetBinContent(i_errBins.first, weightY); v_weightAndResultsPerBinY.push_back(weightAndResultsPerBinY); } } - - + // Do the final calculations - - if(v_weightAndResultsPerBinX.empty()){ - edm::LogError("CalculateAPE")<<"NO error interval of sector "<Scale(1/weightSumX); + i_sector.second.WeightX->Scale(1 / weightSumX); double weightSumY(0.); - if(i_sector.second.isPixel){ - for(auto const & i_apeBin : v_weightAndResultsPerBinY){ + if (i_sector.second.isPixel) { + for (auto const& i_apeBin : v_weightAndResultsPerBinY) { weightSumY += i_apeBin.first; } - i_sector.second.WeightY->Scale(1/weightSumY); + i_sector.second.WeightY->Scale(1 / weightSumY); } - - if(!setBaseline){ + + if (!setBaseline) { // Calculate weighted mean bool firstIntervalX(true); - for(auto const & i_apeBin : v_weightAndResultsPerBinX){ - if(firstIntervalX){ - correctionX2 = i_apeBin.first*i_apeBin.second.first*(i_apeBin.second.second - baselineWidthX2); + for (auto const& i_apeBin : v_weightAndResultsPerBinX) { + if (firstIntervalX) { + correctionX2 = i_apeBin.first * i_apeBin.second.first * (i_apeBin.second.second - baselineWidthX2); firstIntervalX = false; - }else{ - correctionX2 += i_apeBin.first*i_apeBin.second.first*(i_apeBin.second.second - baselineWidthX2); + } else { + correctionX2 += i_apeBin.first * i_apeBin.second.first * (i_apeBin.second.second - baselineWidthX2); } } - correctionX2 = correctionX2/weightSumX; - }else{ + correctionX2 = correctionX2 / weightSumX; + } else { double numeratorX(0.), denominatorX(0.); - for(auto const & i_apeBin : v_weightAndResultsPerBinX){ - numeratorX += i_apeBin.first*i_apeBin.second.first*i_apeBin.second.second; - denominatorX += i_apeBin.first*i_apeBin.second.first; + for (auto const& i_apeBin : v_weightAndResultsPerBinX) { + numeratorX += i_apeBin.first * i_apeBin.second.first * i_apeBin.second.second; + denominatorX += i_apeBin.first * i_apeBin.second.first; } - correctionX2 = numeratorX/denominatorX; + correctionX2 = numeratorX / denominatorX; } - - if(i_sector.second.isPixel){ - if(!setBaseline){ + + if (i_sector.second.isPixel) { + if (!setBaseline) { // Calculate weighted mean bool firstIntervalY(true); - for(auto const & i_apeBin : v_weightAndResultsPerBinY){ - if(firstIntervalY){ - correctionY2 = i_apeBin.first*i_apeBin.second.first*(i_apeBin.second.second - baselineWidthY2); + for (auto const& i_apeBin : v_weightAndResultsPerBinY) { + if (firstIntervalY) { + correctionY2 = i_apeBin.first * i_apeBin.second.first * (i_apeBin.second.second - baselineWidthY2); firstIntervalY = false; - }else{ - correctionY2 += i_apeBin.first*i_apeBin.second.first*(i_apeBin.second.second - baselineWidthY2); + } else { + correctionY2 += i_apeBin.first * i_apeBin.second.first * (i_apeBin.second.second - baselineWidthY2); } } - correctionY2 = correctionY2/weightSumY; - }else{ + correctionY2 = correctionY2 / weightSumY; + } else { double numeratorY(0.), denominatorY(0.); - for(auto const & i_apeBin : v_weightAndResultsPerBinY){ - numeratorY += i_apeBin.first*i_apeBin.second.first*i_apeBin.second.second; - denominatorY += i_apeBin.first*i_apeBin.second.first; + for (auto const& i_apeBin : v_weightAndResultsPerBinY) { + numeratorY += i_apeBin.first * i_apeBin.second.first * i_apeBin.second.second; + denominatorY += i_apeBin.first * i_apeBin.second.first; } - correctionY2 = numeratorY/denominatorY; + correctionY2 = numeratorY / denominatorY; } } - - if(!setBaseline){ + + if (!setBaseline) { // Calculate updated squared APE of current iteration double apeX2(999.); double apeY2(999.); - + // old APE value from last iteration - if(firstIter){ + if (firstIter) { apeX2 = 0.; apeY2 = 0.; - } - else{ + } else { apeX2 = a_apeSectorX[i_sector.first]; apeY2 = a_apeSectorY[i_sector.first]; } const double apeX2old = apeX2; const double apeY2old = apeY2; - + // scale APE Correction with value given in cfg (not if smoothed iteration is used) - edm::LogInfo("CalculateAPE")<<"Unscaled correction x for sector "<0. ? +1. : -1.)*std::sqrt(std::fabs(correctionX2)); - if(!smoothIteration || firstIter)correctionX2 = correctionX2*correctionScaling*correctionScaling; - if(i_sector.second.isPixel){ - edm::LogInfo("CalculateAPE")<<"Unscaled correction y for sector "<0. ? +1. : -1.)*std::sqrt(std::fabs(correctionY2)); - if(!smoothIteration || firstIter)correctionY2 = correctionY2*correctionScaling*correctionScaling; + edm::LogInfo("CalculateAPE") << "Unscaled correction x for sector " << i_sector.first << " is " + << (correctionX2 > 0. ? +1. : -1.) * std::sqrt(std::fabs(correctionX2)); + if (!smoothIteration || firstIter) + correctionX2 = correctionX2 * correctionScaling * correctionScaling; + if (i_sector.second.isPixel) { + edm::LogInfo("CalculateAPE") << "Unscaled correction y for sector " << i_sector.first << " is " + << (correctionY2 > 0. ? +1. : -1.) * std::sqrt(std::fabs(correctionY2)); + if (!smoothIteration || firstIter) + correctionY2 = correctionY2 * correctionScaling * correctionScaling; } - + // new APE value // smooth iteration or not? - if(apeX2 + correctionX2 < 0.) correctionX2 = -apeX2; - if(apeY2 + correctionY2 < 0.) correctionY2 = -apeY2; + if (apeX2 + correctionX2 < 0.) + correctionX2 = -apeX2; + if (apeY2 + correctionY2 < 0.) + correctionY2 = -apeY2; const double apeX2new(apeX2old + correctionX2); const double apeY2new(apeY2old + correctionY2); - if(!smoothIteration || firstIter){ + if (!smoothIteration || firstIter) { apeX2 = apeX2new; apeY2 = apeY2new; - }else{ - const double apeXtmp = smoothFraction*std::sqrt(apeX2new) + (1-smoothFraction)*std::sqrt(apeX2old); - const double apeYtmp = smoothFraction*std::sqrt(apeY2new) + (1-smoothFraction)*std::sqrt(apeY2old); - apeX2 = apeXtmp*apeXtmp; - apeY2 = apeYtmp*apeYtmp; + } else { + const double apeXtmp = smoothFraction * std::sqrt(apeX2new) + (1 - smoothFraction) * std::sqrt(apeX2old); + const double apeYtmp = smoothFraction * std::sqrt(apeY2new) + (1 - smoothFraction) * std::sqrt(apeY2old); + apeX2 = apeXtmp * apeXtmp; + apeY2 = apeYtmp * apeYtmp; } - if(apeX2<0. || apeY2<0.)edm::LogError("CalculateAPE")<<"\n\n\tBad APE, but why???\n\n\n"; + if (apeX2 < 0. || apeY2 < 0.) + edm::LogError("CalculateAPE") << "\n\n\tBad APE, but why???\n\n\n"; a_apeSectorX[i_sector.first] = apeX2; a_apeSectorY[i_sector.first] = apeY2; - + // Set the calculated APE spherical for all modules of strip sectors const double apeX(std::sqrt(apeX2)); const double apeY(std::sqrt(apeY2)); - const double apeZ(std::sqrt(0.5*(apeX2+apeY2))); - for(auto const & i_rawId : i_sector.second.v_rawId){ - if(i_sector.second.isPixel){ - apeOutputFile<Fill(); - iterationTreeX->Write("iterTreeX", TObject::kOverwrite); // TObject::kOverwrite needed to not produce another iterTreeX;2 + iterationTreeX->Write("iterTreeX", + TObject::kOverwrite); // TObject::kOverwrite needed to not produce another iterTreeX;2 iterationTreeY->Fill(); - iterationTreeY->Write("iterTreeY", TObject::kOverwrite); // TObject::kOverwrite needed to not produce another iterTreeY;2 - if(firstIter){ + iterationTreeY->Write("iterTreeY", + TObject::kOverwrite); // TObject::kOverwrite needed to not produce another iterTreeY;2 + if (firstIter) { sectorNameTree->Fill(); sectorNameTree->Write("nameTree"); } iterationFile->Close(); delete iterationFile; - - if(baselineFile){ + + if (baselineFile) { baselineFile->Close(); delete baselineFile; - } + } } - - // ------------ method called to for each event ------------ -void -ApeEstimatorSummary::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void ApeEstimatorSummary::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { // Load APEs from the GT and write them to root files similar to the ones from calculateAPE() - - if(firstEvent){ + + if (firstEvent) { // Set baseline or calculate APE value? const bool setBaseline(parameterSet_.getParameter("setBaseline")); - + edm::ESHandle alignmentErrors; iSetup.get().get(alignmentErrors); - + // Read in baseline file for calculation of APE value (if not setting baseline) // Has same format as iterationFile const std::string baselineFileName(parameterSet_.getParameter("BaselineFile")); TFile* baselineFile(nullptr); TTree* sectorNameBaselineTree(nullptr); - if(!setBaseline){ + if (!setBaseline) { std::ifstream baselineFileStream; // Check if baseline file exists baselineFileStream.open(baselineFileName.c_str()); - if(baselineFileStream.is_open()){ + if (baselineFileStream.is_open()) { baselineFileStream.close(); - baselineFile = new TFile(baselineFileName.c_str(),"READ"); + baselineFile = new TFile(baselineFileName.c_str(), "READ"); } - if(baselineFile){ - edm::LogInfo("CalculateAPE")<<"Baseline file for APE values sucessfully opened"; - baselineFile->GetObject("nameTree;1",sectorNameBaselineTree); - }else{ - edm::LogWarning("CalculateAPE")<<"There is NO baseline file for APE values, so normalized residual width =1 for ideal conditions is assumed"; + if (baselineFile) { + edm::LogInfo("CalculateAPE") << "Baseline file for APE values sucessfully opened"; + baselineFile->GetObject("nameTree;1", sectorNameBaselineTree); + } else { + edm::LogWarning("CalculateAPE") << "There is NO baseline file for APE values, so normalized residual width =1 " + "for ideal conditions is assumed"; } } - + // Set up root file for default APE values const std::string defaultFileName(parameterSet_.getParameter("DefaultFile")); - TFile* defaultFile = new TFile(defaultFileName.c_str(),"RECREATE"); - + TFile* defaultFile = new TFile(defaultFileName.c_str(), "RECREATE"); + // Naming in the root files has to be iterTreeX to be consistent for the plotting tool TTree* defaultTreeX(nullptr); TTree* defaultTreeY(nullptr); - defaultFile->GetObject("iterTreeX;1",defaultTreeX); - defaultFile->GetObject("iterTreeY;1",defaultTreeY); + defaultFile->GetObject("iterTreeX;1", defaultTreeX); + defaultFile->GetObject("iterTreeY;1", defaultTreeY); // The same for TTree containing the names of the sectors (no additional check, since always handled exactly as defaultTree) TTree* sectorNameTree(nullptr); - defaultFile->GetObject("nameTree;1",sectorNameTree); - + defaultFile->GetObject("nameTree;1", sectorNameTree); + bool firstIter(false); - if(!defaultTreeX){ // should be always true in setBaseline mode, since file is recreated + if (!defaultTreeX) { // should be always true in setBaseline mode, since file is recreated firstIter = true; - defaultTreeX = new TTree("iterTreeX","Tree for default APE x values from GT"); - defaultTreeY = new TTree("iterTreeY","Tree for default APE y values from GT"); - edm::LogInfo("CalculateAPE")<<"First APE iteration (number 0.), create default file with TTree"; - sectorNameTree = new TTree("nameTree","Tree with names of sectors"); - }else{ - edm::LogWarning("CalculateAPE")<<"NOT the first APE iteration (number 0.), is this wanted or forgot to delete old iteration file with TTree?"; + defaultTreeX = new TTree("iterTreeX", "Tree for default APE x values from GT"); + defaultTreeY = new TTree("iterTreeY", "Tree for default APE y values from GT"); + edm::LogInfo("CalculateAPE") << "First APE iteration (number 0.), create default file with TTree"; + sectorNameTree = new TTree("nameTree", "Tree with names of sectors"); + } else { + edm::LogWarning("CalculateAPE") << "NOT the first APE iteration (number 0.), is this wanted or forgot to delete " + "old iteration file with TTree?"; } - + // Assign the information stored in the trees to arrays double a_defaultSectorX[noSectors_]; double a_defaultSectorY[noSectors_]; - + std::string* a_sectorName[noSectors_]; std::string* a_sectorBaselineName[noSectors_]; - for(auto const & i_sector : m_tkSector_){ + for (auto const& i_sector : m_tkSector_) { const unsigned int iSector(i_sector.first); const bool pixelSector(i_sector.second.isPixel); - + a_defaultSectorX[iSector] = -99.; a_defaultSectorY[iSector] = -99.; - + a_sectorName[iSector] = nullptr; a_sectorBaselineName[iSector] = nullptr; std::stringstream ss_sector, ss_sectorSuffixed; ss_sector << "Ape_Sector_" << iSector; - if(!setBaseline && sectorNameBaselineTree){ + if (!setBaseline && sectorNameBaselineTree) { sectorNameBaselineTree->SetBranchAddress(ss_sector.str().c_str(), &a_sectorBaselineName[iSector]); sectorNameBaselineTree->GetEntry(0); } - - if(firstIter){ // should be always true in setBaseline mode, since file is recreated + + if (firstIter) { // should be always true in setBaseline mode, since file is recreated ss_sectorSuffixed << ss_sector.str() << "/D"; defaultTreeX->Branch(ss_sector.str().c_str(), &a_defaultSectorX[iSector], ss_sectorSuffixed.str().c_str()); - if(pixelSector){ + if (pixelSector) { defaultTreeY->Branch(ss_sector.str().c_str(), &a_defaultSectorY[iSector], ss_sectorSuffixed.str().c_str()); } sectorNameTree->Branch(ss_sector.str().c_str(), &a_sectorName[iSector], 32000, 00); - }else{ + } else { defaultTreeX->SetBranchAddress(ss_sector.str().c_str(), &a_defaultSectorX[iSector]); defaultTreeX->GetEntry(0); - if(pixelSector){ + if (pixelSector) { defaultTreeY->SetBranchAddress(ss_sector.str().c_str(), &a_defaultSectorY[iSector]); defaultTreeY->GetEntry(0); } @@ -930,41 +984,46 @@ ApeEstimatorSummary::analyze(const edm::Event& iEvent, const edm::EventSetup& iS sectorNameTree->GetEntry(0); } } - - + // Check whether sector definitions are identical with the ones of previous iterations and with the ones in baseline file - for(auto & i_sector : m_tkSector_){ + for (auto& i_sector : m_tkSector_) { const std::string& name(i_sector.second.name); - if(!firstIter){ + if (!firstIter) { const std::string& nameLastIter(*a_sectorName[i_sector.first]); - if(name!=nameLastIter){ - edm::LogError("CalculateAPE")<<"Inconsistent sector definition in iterationFile for sector "< alignErrors = alignmentErrors->m_alignError; - for(std::vector::const_iterator i_alignError = alignErrors.begin(); i_alignError != alignErrors.end(); ++i_alignError){ - if(i_rawId == i_alignError->rawId()){ + for (std::vector::const_iterator i_alignError = alignErrors.begin(); + i_alignError != alignErrors.end(); + ++i_alignError) { + if (i_rawId == i_alignError->rawId()) { CLHEP::HepSymMatrix errMatrix = i_alignError->matrix(); defaultApeX += errMatrix[0][0]; defaultApeY += errMatrix[1][1]; @@ -972,8 +1031,8 @@ ApeEstimatorSummary::analyze(const edm::Event& iEvent, const edm::EventSetup& iS } } } - a_defaultSectorX[i_sector.first] = defaultApeX/nModules; - a_defaultSectorY[i_sector.first] = defaultApeY/nModules; + a_defaultSectorX[i_sector.first] = defaultApeX / nModules; + a_defaultSectorY[i_sector.first] = defaultApeY / nModules; } sectorNameTree->Fill(); sectorNameTree->Write("nameTree"); @@ -981,40 +1040,33 @@ ApeEstimatorSummary::analyze(const edm::Event& iEvent, const edm::EventSetup& iS defaultTreeX->Write("iterTreeX"); defaultTreeY->Fill(); defaultTreeY->Write("iterTreeY"); - + defaultFile->Close(); delete defaultFile; - - if(baselineFile){ + + if (baselineFile) { baselineFile->Close(); delete baselineFile; } - - firstEvent = false; + + firstEvent = false; } } - // ------------ method called once each job just before starting event loop ------------ -void -ApeEstimatorSummary::beginJob() -{ +void ApeEstimatorSummary::beginJob() { this->openInputFile(); - + this->getTrackerSectorStructs(); - + this->bookHists(); } // ------------ method called once each job just after ending the event loop ------------ -void -ApeEstimatorSummary::endJob() { - +void ApeEstimatorSummary::endJob() { this->calculateApe(); - + this->writeHists(); - - } //define this as a plug-in diff --git a/Alignment/APEEstimation/plugins/ApeTreeCreateDefault.cc b/Alignment/APEEstimation/plugins/ApeTreeCreateDefault.cc index 13735f842281d..2bd45de515edf 100644 --- a/Alignment/APEEstimation/plugins/ApeTreeCreateDefault.cc +++ b/Alignment/APEEstimation/plugins/ApeTreeCreateDefault.cc @@ -3,7 +3,7 @@ // // Package: DefaultApeTree // Class: DefaultApeTree -// +// /**\class ApeTreeCreateDefault ApeTreeCreateDefault.cc Alignment/APEEstimation/src/ApeTreeCreateDefault.cc Description: [one line class summary] @@ -18,7 +18,6 @@ // // - // system include files #include #include @@ -53,7 +52,6 @@ #include "DataFormats/SiPixelCluster/interface/SiPixelCluster.h" #include "DataFormats/SiStripCluster/interface/SiStripCluster.h" - #include "TString.h" #include "TFile.h" #include "TDirectory.h" @@ -64,33 +62,33 @@ // class ApeTreeCreateDefault : public edm::one::EDAnalyzer<> { - public: - explicit ApeTreeCreateDefault(const edm::ParameterSet&); - ~ApeTreeCreateDefault() override; - - static void fillDescriptions(edm::ConfigurationDescriptions & descriptions); - - private: - void beginJob() override ; - void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override ; - - void sectorBuilder(); - bool checkIntervalsForSectors(const unsigned int sectorCounter, const std::vector&)const; - bool checkModuleIds(const unsigned int, const std::vector&)const; - bool checkModuleBools(const bool, const std::vector&)const; - bool checkModuleDirections(const int, const std::vector&)const; - bool checkModulePositions(const float, const std::vector&)const; - - // ----------member data --------------------------- - const std::string resultFile_; - const std::string trackerTreeFile_; - const std::vector sectors_; - - std::map m_tkSector_; - std::map m_tkTreeVar_; - unsigned int noSectors; -}; +public: + explicit ApeTreeCreateDefault(const edm::ParameterSet&); + ~ApeTreeCreateDefault() override; + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); + +private: + void beginJob() override; + void analyze(const edm::Event&, const edm::EventSetup&) override; + void endJob() override; + + void sectorBuilder(); + bool checkIntervalsForSectors(const unsigned int sectorCounter, const std::vector&) const; + bool checkModuleIds(const unsigned int, const std::vector&) const; + bool checkModuleBools(const bool, const std::vector&) const; + bool checkModuleDirections(const int, const std::vector&) const; + bool checkModulePositions(const float, const std::vector&) const; + + // ----------member data --------------------------- + const std::string resultFile_; + const std::string trackerTreeFile_; + const std::vector sectors_; + + std::map m_tkSector_; + std::map m_tkTreeVar_; + unsigned int noSectors; +}; // // constants, enums and typedefs @@ -103,48 +101,40 @@ class ApeTreeCreateDefault : public edm::one::EDAnalyzer<> { // // constructors and destructor // -ApeTreeCreateDefault::ApeTreeCreateDefault(const edm::ParameterSet& iConfig): - resultFile_(iConfig.getParameter("resultFile")), - trackerTreeFile_(iConfig.getParameter("trackerTreeFile")), - sectors_(iConfig.getParameter >("sectors")) -{ -} - - -ApeTreeCreateDefault::~ApeTreeCreateDefault() -{ -} +ApeTreeCreateDefault::ApeTreeCreateDefault(const edm::ParameterSet& iConfig) + : resultFile_(iConfig.getParameter("resultFile")), + trackerTreeFile_(iConfig.getParameter("trackerTreeFile")), + sectors_(iConfig.getParameter>("sectors")) {} +ApeTreeCreateDefault::~ApeTreeCreateDefault() {} // // member functions // -void -ApeTreeCreateDefault::sectorBuilder() -{ +void ApeTreeCreateDefault::sectorBuilder() { // Same procedure as in ApeEstimator.cc TFile* tkTreeFile(TFile::Open(trackerTreeFile_.c_str())); - if(tkTreeFile){ - edm::LogInfo("SectorBuilder")<<"TrackerTreeFile OK"; - }else{ - edm::LogError("SectorBuilder")<<"TrackerTreeFile not found"; + if (tkTreeFile) { + edm::LogInfo("SectorBuilder") << "TrackerTreeFile OK"; + } else { + edm::LogError("SectorBuilder") << "TrackerTreeFile not found"; return; } TTree* tkTree(nullptr); - tkTreeFile->GetObject("TrackerTreeGenerator/TrackerTree/TrackerTree",tkTree); - if(tkTree){ - edm::LogInfo("SectorBuilder")<<"TrackerTree OK"; - }else{ - edm::LogError("SectorBuilder")<<"TrackerTree not found in file"; + tkTreeFile->GetObject("TrackerTreeGenerator/TrackerTree/TrackerTree", tkTree); + if (tkTree) { + edm::LogInfo("SectorBuilder") << "TrackerTree OK"; + } else { + edm::LogError("SectorBuilder") << "TrackerTree not found in file"; return; } - - unsigned int rawId(999), subdetId(999), layer(999), side(999), half(999), rod(999), ring(999), petal(999), - blade(999), panel(999), outerInner(999), module(999), nStrips(999); + + unsigned int rawId(999), subdetId(999), layer(999), side(999), half(999), rod(999), ring(999), petal(999), blade(999), + panel(999), outerInner(999), module(999), nStrips(999); bool isDoubleSide(false), isRPhi(false), isStereo(false); int uDirection(999), vDirection(999), wDirection(999); - float posR(999.F), posPhi(999.F), posEta(999.F), posX(999.F), posY(999.F), posZ(999.F); - + float posR(999.F), posPhi(999.F), posEta(999.F), posX(999.F), posY(999.F), posZ(999.F); + tkTree->SetBranchAddress("RawId", &rawId); tkTree->SetBranchAddress("SubdetId", &subdetId); tkTree->SetBranchAddress("Layer", &layer); @@ -170,60 +160,63 @@ ApeTreeCreateDefault::sectorBuilder() tkTree->SetBranchAddress("PosX", &posX); tkTree->SetBranchAddress("PosY", &posY); tkTree->SetBranchAddress("PosZ", &posZ); - + int nModules(tkTree->GetEntries()); TrackerSectorStruct allSectors; - + //Loop over all Sectors unsigned int sectorCounter(0); std::vector v_sectorDef(sectors_); - edm::LogInfo("SectorBuilder")<<"There are "<("name")); - std::vector v_rawId(parSet.getParameter >("rawId")), - v_subdetId(parSet.getParameter >("subdetId")), - v_layer(parSet.getParameter >("layer")), - v_side(parSet.getParameter >("side")), - v_half(parSet.getParameter >("half")), - v_rod(parSet.getParameter >("rod")), - v_ring(parSet.getParameter >("ring")), - v_petal(parSet.getParameter >("petal")), - v_blade(parSet.getParameter >("blade")), - v_panel(parSet.getParameter >("panel")), - v_outerInner(parSet.getParameter >("outerInner")), - v_module(parSet.getParameter >("module")), - v_nStrips(parSet.getParameter >("nStrips")), - v_isDoubleSide(parSet.getParameter >("isDoubleSide")), - v_isRPhi(parSet.getParameter >("isRPhi")), - v_isStereo(parSet.getParameter >("isStereo")); - std::vector v_uDirection(parSet.getParameter >("uDirection")), - v_vDirection(parSet.getParameter >("vDirection")), - v_wDirection(parSet.getParameter >("wDirection")); - std::vector v_posR(parSet.getParameter >("posR")), - v_posPhi(parSet.getParameter >("posPhi")), - v_posEta(parSet.getParameter >("posEta")), - v_posX(parSet.getParameter >("posX")), - v_posY(parSet.getParameter >("posY")), - v_posZ(parSet.getParameter >("posZ")); - - if(!this->checkIntervalsForSectors(sectorCounter,v_posR) || !this->checkIntervalsForSectors(sectorCounter,v_posPhi) || - !this->checkIntervalsForSectors(sectorCounter,v_posEta) || !this->checkIntervalsForSectors(sectorCounter,v_posX) || - !this->checkIntervalsForSectors(sectorCounter,v_posY) || !this->checkIntervalsForSectors(sectorCounter,v_posZ)){ + std::vector v_rawId(parSet.getParameter>("rawId")), + v_subdetId(parSet.getParameter>("subdetId")), + v_layer(parSet.getParameter>("layer")), + v_side(parSet.getParameter>("side")), + v_half(parSet.getParameter>("half")), + v_rod(parSet.getParameter>("rod")), + v_ring(parSet.getParameter>("ring")), + v_petal(parSet.getParameter>("petal")), + v_blade(parSet.getParameter>("blade")), + v_panel(parSet.getParameter>("panel")), + v_outerInner(parSet.getParameter>("outerInner")), + v_module(parSet.getParameter>("module")), + v_nStrips(parSet.getParameter>("nStrips")), + v_isDoubleSide(parSet.getParameter>("isDoubleSide")), + v_isRPhi(parSet.getParameter>("isRPhi")), + v_isStereo(parSet.getParameter>("isStereo")); + std::vector v_uDirection(parSet.getParameter>("uDirection")), + v_vDirection(parSet.getParameter>("vDirection")), + v_wDirection(parSet.getParameter>("wDirection")); + std::vector v_posR(parSet.getParameter>("posR")), + v_posPhi(parSet.getParameter>("posPhi")), + v_posEta(parSet.getParameter>("posEta")), + v_posX(parSet.getParameter>("posX")), + v_posY(parSet.getParameter>("posY")), + v_posZ(parSet.getParameter>("posZ")); + + if (!this->checkIntervalsForSectors(sectorCounter, v_posR) || + !this->checkIntervalsForSectors(sectorCounter, v_posPhi) || + !this->checkIntervalsForSectors(sectorCounter, v_posEta) || + !this->checkIntervalsForSectors(sectorCounter, v_posX) || + !this->checkIntervalsForSectors(sectorCounter, v_posY) || + !this->checkIntervalsForSectors(sectorCounter, v_posZ)) { continue; } - + TrackerSectorStruct tkSector; tkSector.name = sectorName; - + ReducedTrackerTreeVariables tkTreeVar; - + //Loop over all Modules - for(int module = 0; module < nModules; ++module){ + for (int module = 0; module < nModules; ++module) { tkTree->GetEntry(module); - - if(sectorCounter==1){ + + if (sectorCounter == 1) { tkTreeVar.subdetId = subdetId; tkTreeVar.nStrips = nStrips; tkTreeVar.uDirection = uDirection; @@ -232,44 +225,71 @@ ApeTreeCreateDefault::sectorBuilder() m_tkTreeVar_[rawId] = tkTreeVar; } //Check if modules from Sector builder equal those from TrackerTree - if(!this->checkModuleIds(rawId,v_rawId))continue; - if(!this->checkModuleIds(subdetId,v_subdetId))continue; - if(!this->checkModuleIds(layer,v_layer))continue; - if(!this->checkModuleIds(side,v_side))continue; - if(!this->checkModuleIds(half,v_half))continue; - if(!this->checkModuleIds(rod,v_rod))continue; - if(!this->checkModuleIds(ring,v_ring))continue; - if(!this->checkModuleIds(petal,v_petal))continue; - if(!this->checkModuleIds(blade,v_blade))continue; - if(!this->checkModuleIds(panel,v_panel))continue; - if(!this->checkModuleIds(outerInner,v_outerInner))continue; - if(!this->checkModuleIds(module,v_module))continue; - if(!this->checkModuleIds(nStrips,v_nStrips))continue; - if(!this->checkModuleBools(isDoubleSide,v_isDoubleSide))continue; - if(!this->checkModuleBools(isRPhi,v_isRPhi))continue; - if(!this->checkModuleBools(isStereo,v_isStereo))continue; - if(!this->checkModuleDirections(uDirection,v_uDirection))continue; - if(!this->checkModuleDirections(vDirection,v_vDirection))continue; - if(!this->checkModuleDirections(wDirection,v_wDirection))continue; - if(!this->checkModulePositions(posR,v_posR))continue; - if(!this->checkModulePositions(posPhi,v_posPhi))continue; - if(!this->checkModulePositions(posEta,v_posEta))continue; - if(!this->checkModulePositions(posX,v_posX))continue; - if(!this->checkModulePositions(posY,v_posY))continue; - if(!this->checkModulePositions(posZ,v_posZ))continue; - + if (!this->checkModuleIds(rawId, v_rawId)) + continue; + if (!this->checkModuleIds(subdetId, v_subdetId)) + continue; + if (!this->checkModuleIds(layer, v_layer)) + continue; + if (!this->checkModuleIds(side, v_side)) + continue; + if (!this->checkModuleIds(half, v_half)) + continue; + if (!this->checkModuleIds(rod, v_rod)) + continue; + if (!this->checkModuleIds(ring, v_ring)) + continue; + if (!this->checkModuleIds(petal, v_petal)) + continue; + if (!this->checkModuleIds(blade, v_blade)) + continue; + if (!this->checkModuleIds(panel, v_panel)) + continue; + if (!this->checkModuleIds(outerInner, v_outerInner)) + continue; + if (!this->checkModuleIds(module, v_module)) + continue; + if (!this->checkModuleIds(nStrips, v_nStrips)) + continue; + if (!this->checkModuleBools(isDoubleSide, v_isDoubleSide)) + continue; + if (!this->checkModuleBools(isRPhi, v_isRPhi)) + continue; + if (!this->checkModuleBools(isStereo, v_isStereo)) + continue; + if (!this->checkModuleDirections(uDirection, v_uDirection)) + continue; + if (!this->checkModuleDirections(vDirection, v_vDirection)) + continue; + if (!this->checkModuleDirections(wDirection, v_wDirection)) + continue; + if (!this->checkModulePositions(posR, v_posR)) + continue; + if (!this->checkModulePositions(posPhi, v_posPhi)) + continue; + if (!this->checkModulePositions(posEta, v_posEta)) + continue; + if (!this->checkModulePositions(posX, v_posX)) + continue; + if (!this->checkModulePositions(posY, v_posY)) + continue; + if (!this->checkModulePositions(posZ, v_posZ)) + continue; + tkSector.v_rawId.push_back(rawId); bool moduleSelected(false); - for(auto const & i_rawId : allSectors.v_rawId){ - if(rawId == i_rawId)moduleSelected = true; + for (auto const& i_rawId : allSectors.v_rawId) { + if (rawId == i_rawId) + moduleSelected = true; } - if(!moduleSelected)allSectors.v_rawId.push_back(rawId); + if (!moduleSelected) + allSectors.v_rawId.push_back(rawId); } - + // Stops you from combining pixel and strip detector into one sector bool isPixel(false); bool isStrip(false); - for(auto const & i_rawId : tkSector.v_rawId){ + for (auto const& i_rawId : tkSector.v_rawId) { switch (m_tkTreeVar_[i_rawId].subdetId) { case PixelSubdetector::PixelBarrel: case PixelSubdetector::PixelEndcap: @@ -284,213 +304,195 @@ ApeTreeCreateDefault::sectorBuilder() } } - if(isPixel && isStrip){ - edm::LogError("SectorBuilder")<<"Incorrect Sector Definition: there are pixel and strip modules within one sector" - <<"\n... sector selection is not applied, sector "<& v_id)const -{ - - if(v_id.empty())return true; - if(v_id.size()%2==1){ - edm::LogError("SectorBuilder")<<"Incorrect Sector Definition: Position Vectors need even number of arguments (Intervals)" - <<"\n... sector selection is not applied, sector "<& v_id) const { + if (v_id.empty()) + return true; + if (v_id.size() % 2 == 1) { + edm::LogError("SectorBuilder") + << "Incorrect Sector Definition: Position Vectors need even number of arguments (Intervals)" + << "\n... sector selection is not applied, sector " << sectorCounter << " is not built"; return false; } - int entry(0); double intervalBegin(999.); - for(auto const & i_id : v_id){ + int entry(0); + double intervalBegin(999.); + for (auto const& i_id : v_id) { ++entry; - if(entry%2==1) intervalBegin = i_id; - if(entry%2==0 && intervalBegin > i_id){ - edm::LogError("SectorBuilder")<<"Incorrect Sector Definition (Position Vector Intervals): \t" - < i_id) { + edm::LogError("SectorBuilder") << "Incorrect Sector Definition (Position Vector Intervals): \t" << intervalBegin + << " is bigger than " << i_id << " but is expected to be smaller" + << "\n... sector selection is not applied, sector " << sectorCounter + << " is not built"; return false; } } return true; } -bool -ApeTreeCreateDefault::checkModuleIds(const unsigned int id, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - for(auto const & i_id : v_id){ - if(id==i_id)return true; +bool ApeTreeCreateDefault::checkModuleIds(const unsigned int id, const std::vector& v_id) const { + if (v_id.empty()) + return true; + for (auto const& i_id : v_id) { + if (id == i_id) + return true; } return false; } -bool -ApeTreeCreateDefault::checkModuleBools(const bool id, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - for(auto const & i_id : v_id){ - if(1==i_id && id)return true; - if(2==i_id && !id)return true; +bool ApeTreeCreateDefault::checkModuleBools(const bool id, const std::vector& v_id) const { + if (v_id.empty()) + return true; + for (auto const& i_id : v_id) { + if (1 == i_id && id) + return true; + if (2 == i_id && !id) + return true; } return false; } -bool -ApeTreeCreateDefault::checkModuleDirections(const int id, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - for(auto const & i_id : v_id){ - if(id==i_id)return true; +bool ApeTreeCreateDefault::checkModuleDirections(const int id, const std::vector& v_id) const { + if (v_id.empty()) + return true; + for (auto const& i_id : v_id) { + if (id == i_id) + return true; } return false; } -bool -ApeTreeCreateDefault::checkModulePositions(const float id, const std::vector& v_id)const -{ - - if(v_id.empty())return true; - int entry(0); double intervalBegin(999.); - for(auto const & i_id : v_id){ +bool ApeTreeCreateDefault::checkModulePositions(const float id, const std::vector& v_id) const { + if (v_id.empty()) + return true; + int entry(0); + double intervalBegin(999.); + for (auto const& i_id : v_id) { ++entry; - if(entry%2==1)intervalBegin = i_id; - if(entry%2==0 && id>=intervalBegin && id= intervalBegin && id < i_id) + return true; } return false; } - - // ------------ method called to for each event ------------ -void -ApeTreeCreateDefault::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void ApeTreeCreateDefault::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { // Same procedure as in ApeEstimatorSummary.cc minus reading of baseline tree - + // Load APEs from the GT and write them to root files similar to the ones from calculateAPE() edm::ESHandle alignmentErrors; - iSetup.get().get(alignmentErrors); - + iSetup.get().get(alignmentErrors); + // Set up root file for default APE values const std::string defaultFileName(resultFile_); - TFile* defaultFile = new TFile(defaultFileName.c_str(),"RECREATE"); - + TFile* defaultFile = new TFile(defaultFileName.c_str(), "RECREATE"); + // Naming in the root files has to be iterTreeX to be consistent for the plotting tool TTree* defaultTreeX(nullptr); TTree* defaultTreeY(nullptr); - defaultFile->GetObject("iterTreeX;1",defaultTreeX); - defaultFile->GetObject("iterTreeY;1",defaultTreeY); + defaultFile->GetObject("iterTreeX;1", defaultTreeX); + defaultFile->GetObject("iterTreeY;1", defaultTreeY); // The same for TTree containing the names of the sectors (no additional check, since always handled exactly as defaultTree) TTree* sectorNameTree(nullptr); - defaultFile->GetObject("nameTree;1",sectorNameTree); - - edm::LogInfo("DefaultAPETree")<<"APE Tree is being created"; - defaultTreeX = new TTree("iterTreeX","Tree for default APE x values from GT"); - defaultTreeY = new TTree("iterTreeY","Tree for default APE y values from GT"); - sectorNameTree = new TTree("nameTree","Tree with names of sectors"); - - + defaultFile->GetObject("nameTree;1", sectorNameTree); + + edm::LogInfo("DefaultAPETree") << "APE Tree is being created"; + defaultTreeX = new TTree("iterTreeX", "Tree for default APE x values from GT"); + defaultTreeY = new TTree("iterTreeY", "Tree for default APE y values from GT"); + sectorNameTree = new TTree("nameTree", "Tree with names of sectors"); + // Assign the information stored in the trees to arrays std::vector a_defaultSectorX; std::vector a_defaultSectorY; - + std::vector a_sectorName; - for(auto const & i_sector : m_tkSector_){ + for (auto const& i_sector : m_tkSector_) { const unsigned int iSector(i_sector.first); const bool pixelSector(i_sector.second.isPixel); - + a_defaultSectorX.push_back(new double(-99.)); a_defaultSectorY.push_back(new double(-99.)); a_sectorName.push_back(new std::string(i_sector.second.name)); - + std::stringstream ss_sector; std::stringstream ss_sectorSuffixed; ss_sector << "Ape_Sector_" << iSector; - + ss_sectorSuffixed << ss_sector.str() << "/D"; - defaultTreeX->Branch(ss_sector.str().c_str(), &(*a_defaultSectorX[iSector-1]), ss_sectorSuffixed.str().c_str()); - - if(pixelSector){ - defaultTreeY->Branch(ss_sector.str().c_str(), &(*a_defaultSectorY[iSector-1]), ss_sectorSuffixed.str().c_str()); + defaultTreeX->Branch(ss_sector.str().c_str(), &(*a_defaultSectorX[iSector - 1]), ss_sectorSuffixed.str().c_str()); + + if (pixelSector) { + defaultTreeY->Branch(ss_sector.str().c_str(), &(*a_defaultSectorY[iSector - 1]), ss_sectorSuffixed.str().c_str()); } - sectorNameTree->Branch(ss_sector.str().c_str(), &(*a_sectorName[iSector-1]), 32000, 00); + sectorNameTree->Branch(ss_sector.str().c_str(), &(*a_sectorName[iSector - 1]), 32000, 00); } - // Loop over sectors for getting default APE - - for(auto & i_sector : m_tkSector_){ - + + for (auto& i_sector : m_tkSector_) { double defaultApeX(0.); double defaultApeY(0.); unsigned int nModules(0); - for(auto const & i_rawId : i_sector.second.v_rawId){ + for (auto const& i_rawId : i_sector.second.v_rawId) { std::vector alignErrors = alignmentErrors->m_alignError; - for(auto const & i_alignError : alignErrors){ - if(i_rawId == i_alignError.rawId()){ + for (auto const& i_alignError : alignErrors) { + if (i_rawId == i_alignError.rawId()) { CLHEP::HepSymMatrix errMatrix = i_alignError.matrix(); defaultApeX += errMatrix[0][0]; defaultApeY += errMatrix[1][1]; nModules++; } } + } + *a_defaultSectorX[i_sector.first - 1] = defaultApeX / nModules; + *a_defaultSectorY[i_sector.first - 1] = defaultApeY / nModules; } - *a_defaultSectorX[i_sector.first-1] = defaultApeX/nModules; - *a_defaultSectorY[i_sector.first-1] = defaultApeY/nModules; - } - - + sectorNameTree->Fill(); sectorNameTree->Write("nameTree"); defaultTreeX->Fill(); defaultTreeX->Write("iterTreeX"); defaultTreeY->Fill(); defaultTreeY->Write("iterTreeY"); - - defaultFile->Close(); + + defaultFile->Close(); delete defaultFile; - for(unsigned int i = 0; i < a_defaultSectorX.size(); i++){ + for (unsigned int i = 0; i < a_defaultSectorX.size(); i++) { delete a_defaultSectorX[i]; delete a_defaultSectorY[i]; delete a_sectorName[i]; } } - - - // ------------ method called once each job just before starting event loop ------------ -void -ApeTreeCreateDefault::beginJob() -{ - this->sectorBuilder(); -} +void ApeTreeCreateDefault::beginJob() { this->sectorBuilder(); } // ------------ method called once each job just after ending the event loop ------------ -void -ApeTreeCreateDefault::endJob() -{ -} +void ApeTreeCreateDefault::endJob() {} -void -ApeTreeCreateDefault::fillDescriptions(edm::ConfigurationDescriptions & descriptions) -{ +void ApeTreeCreateDefault::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; edm::ParameterSetDescription sector; - + std::vector emptyUnsignedIntVector; std::vector emptyIntVector; std::vector emptyDoubleVector; @@ -524,7 +526,7 @@ ApeTreeCreateDefault::fillDescriptions(edm::ConfigurationDescriptions & descript desc.add("resultFile", "defaultAPE.root"); desc.add("trackerTreeFile"); desc.addVPSet("sectors", sector); - + descriptions.add("apeTreeCreateDefault", desc); } diff --git a/Alignment/CocoaApplication/bin/cocoa.cpp b/Alignment/CocoaApplication/bin/cocoa.cpp index 8d27084c63acf..ee55865ab6a7d 100644 --- a/Alignment/CocoaApplication/bin/cocoa.cpp +++ b/Alignment/CocoaApplication/bin/cocoa.cpp @@ -1,43 +1,48 @@ -#include "Alignment/CocoaUtilities/interface/ALIUtils.h" -#include -#include "Alignment/CocoaModel/interface/Model.h" #include "Alignment/CocoaFit/interface/Fit.h" +#include "Alignment/CocoaModel/interface/Model.h" #include "Alignment/CocoaUtilities/interface/ALIFileOut.h" +#include "Alignment/CocoaUtilities/interface/ALIUtils.h" +#include //#include "Analysis/FittedEntriesRoot/interface/FERootDump.h" #include "Alignment/CocoaToDDL/interface/CocoaToDDLMgr.h" #include "Alignment/CocoaUtilities/interface/GlobalOptionMgr.h" -#include +#include -int main( int argc, char** argv ) -{ - char* nam = getenv("COCOA_SDF_FILENAME"); - if(nam != 0) Model::setSDFName( nam ); - nam = getenv("COCOA_REPORT_FILENAME"); - if(nam != 0) Model::setReportFName( nam ); - nam = getenv("COCOA_MATRICES_FILENAME"); - if(nam != 0) Model::setMatricesFName( nam ); +int main(int argc, char** argv) { + char* nam = getenv("COCOA_SDF_FILENAME"); + if (nam != nullptr) + Model::setSDFName(nam); + nam = getenv("COCOA_REPORT_FILENAME"); + if (nam != nullptr) + Model::setReportFName(nam); + nam = getenv("COCOA_MATRICES_FILENAME"); + if (nam != nullptr) + Model::setMatricesFName(nam); ALIstring COCOA_ver = "COCOA_3_2_4"; //---------- Read the input arguments to set file names - switch( argc ){ - case 1: - break; - case 4: - if( ALIstring(argv[3]) != "!" ) Model::setMatricesFName( argv[3] ); - case 3: - if( ALIstring(argv[2]) != "!" ) Model::setReportFName( argv[2] ); - case 2: - if( ALIstring(argv[1]) != "!" ) Model::setSDFName( argv[1] ); - if( ALIstring(argv[1]) == "-v" ) { - std::cerr << "COCOA version = " << COCOA_ver << std::endl; - exit(0); - } - break; - default: - std::cerr << "WARNING: more than two arguments, from third on will not be taken into account " << std::endl; - break; + switch (argc) { + case 1: + break; + case 4: + if (ALIstring(argv[3]) != "!") + Model::setMatricesFName(argv[3]); + case 3: + if (ALIstring(argv[2]) != "!") + Model::setReportFName(argv[2]); + case 2: + if (ALIstring(argv[1]) != "!") + Model::setSDFName(argv[1]); + if (ALIstring(argv[1]) == "-v") { + std::cerr << "COCOA version = " << COCOA_ver << std::endl; + exit(0); + } + break; + default: + std::cerr << "WARNING: more than two arguments, from third on will not be taken into account " << std::endl; + break; } //---------- Build the Model out of the system description text file @@ -48,22 +53,26 @@ int main( int argc, char** argv ) time_t now, time_start; now = clock(); time_start = now; - if(ALIUtils::debug >= 0) std::cout << "TIME:START_READING : " << now << " " << difftime(now, ALIUtils::time_now())/1.E6 << " " << ALIUtils::debug <= 0) + std::cout << "TIME:START_READING : " << now << " " << difftime(now, ALIUtils::time_now()) / 1.E6 << " " + << ALIUtils::debug << std::endl; + ALIUtils::set_time_now(now); Model::readSystemDescription(); now = clock(); - if(ALIUtils::debug >= 0) std::cout << "TIME:ENDED_READING : " << now << " " << difftime(now, ALIUtils::time_now())/1.E6 << " " << ALIUtils::debug << std::endl; - ALIUtils::set_time_now(now); + if (ALIUtils::debug >= 0) + std::cout << "TIME:ENDED_READING : " << now << " " << difftime(now, ALIUtils::time_now()) / 1.E6 << " " + << ALIUtils::debug << std::endl; + ALIUtils::set_time_now(now); ALIdouble go; GlobalOptionMgr* gomgr = GlobalOptionMgr::getInstance(); - gomgr->getGlobalOptionValue("writeXML", go ); + gomgr->getGlobalOptionValue("writeXML", go); - if( ALIint(go) == 1 ){ + if (ALIint(go) == 1) { ALIstring xmlfname = Model::SDFName(); xmlfname += ALIstring(".xml"); - CocoaToDDLMgr::getInstance()->writeDDDFile( xmlfname ); + CocoaToDDLMgr::getInstance()->writeDDDFile(xmlfname); } Fit::getInstance(); @@ -76,18 +85,21 @@ int main( int argc, char** argv ) //analysis code -// FERootDump fehistos; -// std::cout << " call fehistos.MakeHistos " << std::endl; -// fehistos.MakeHistos(); + // FERootDump fehistos; + // std::cout << " call fehistos.MakeHistos " << std::endl; + // fehistos.MakeHistos(); - if(ALIUtils::debug >= 0) std::cout << "............ program ended OK" << std::endl; - if( ALIUtils::report >=1 ) { - ALIFileOut& fileout = ALIFileOut::getInstance( Model::ReportFName() ); + if (ALIUtils::debug >= 0) + std::cout << "............ program ended OK" << std::endl; + if (ALIUtils::report >= 1) { + ALIFileOut& fileout = ALIFileOut::getInstance(Model::ReportFName()); fileout << "............ program ended OK" << std::endl; } now = clock(); - if(ALIUtils::debug >= 0) std::cout << "TIME:PROGRAM ENDED : "<< now << " " << difftime(now, ALIUtils::time_now())/1.E6 << std::endl; - if(ALIUtils::debug >= 0) std::cout << "TIME:TOTAL PROGRAM : "<< now << " " << difftime(now, time_start)/1.E6 << std::endl; + if (ALIUtils::debug >= 0) + std::cout << "TIME:PROGRAM ENDED : " << now << " " << difftime(now, ALIUtils::time_now()) / 1.E6 << std::endl; + if (ALIUtils::debug >= 0) + std::cout << "TIME:TOTAL PROGRAM : " << now << " " << difftime(now, time_start) / 1.E6 << std::endl; exit(0); } diff --git a/Alignment/CocoaDDLObjects/interface/CocoaMaterialElementary.h b/Alignment/CocoaDDLObjects/interface/CocoaMaterialElementary.h index c265e5f539648..4d60f99c228b5 100644 --- a/Alignment/CocoaDDLObjects/interface/CocoaMaterialElementary.h +++ b/Alignment/CocoaDDLObjects/interface/CocoaMaterialElementary.h @@ -1,8 +1,9 @@ // COCOA class header file -//Id: CocoaMaterialElementary.h -//CAT: Model +// Id: CocoaMaterialElementary.h +// CAT: Model // -// Class to manage the sets of fitted entries (one set per each measurement data set) +// Class to manage the sets of fitted entries (one set per each measurement +// data set) // // History: v1.0 // Pedro Arce @@ -12,37 +13,26 @@ #include "Alignment/CocoaUtilities/interface/CocoaGlobals.h" - -class CocoaMaterialElementary -{ - +class CocoaMaterialElementary { public: //---------- Constructors / Destructor - CocoaMaterialElementary( ALIstring name, float density, ALIstring symbol, float A, ALIint Z ); - ~CocoaMaterialElementary(){ }; + CocoaMaterialElementary(ALIstring name, float density, ALIstring symbol, float A, ALIint Z); + ~CocoaMaterialElementary(){}; - ALIstring getName() const { - return theName; } - float getDensity() const { - return theDensity; } - ALIstring getSymbol() const { - return theSymbol; } - float getA() const { - return theA; } - ALIint getZ() const { - return theZ; } + ALIstring getName() const { return theName; } + float getDensity() const { return theDensity; } + ALIstring getSymbol() const { return theSymbol; } + float getA() const { return theA; } + ALIint getZ() const { return theZ; } - ALIbool operator==(const CocoaMaterialElementary& mate ) const; + ALIbool operator==(const CocoaMaterialElementary &mate) const; private: - ALIstring theName; float theDensity; ALIstring theSymbol; float theA; ALIint theZ; - }; #endif - diff --git a/Alignment/CocoaDDLObjects/interface/CocoaSolidShape.h b/Alignment/CocoaDDLObjects/interface/CocoaSolidShape.h index afdf7d61437c1..942bde75b3bbb 100644 --- a/Alignment/CocoaDDLObjects/interface/CocoaSolidShape.h +++ b/Alignment/CocoaDDLObjects/interface/CocoaSolidShape.h @@ -1,10 +1,11 @@ // COCOA class header file -//Id: CocoaSolidShape.h -//CAT: Model +// Id: CocoaSolidShape.h +// CAT: Model // -// Class to manage the sets of fitted entries (one set per each measurement data set) -// -// History: v1.0 +// Class to manage the sets of fitted entries (one set per each measurement +// data set) +// +// History: v1.0 // Pedro Arce #ifndef _CocoaSolidShape_HH @@ -12,25 +13,18 @@ #include "Alignment/CocoaUtilities/interface/CocoaGlobals.h" - -class CocoaSolidShape -{ - +class CocoaSolidShape { public: //---------- Constructors / Destructor - CocoaSolidShape( ALIstring type ); - virtual ~CocoaSolidShape(){ }; + CocoaSolidShape(ALIstring type); + virtual ~CocoaSolidShape(){}; - ALIstring getType() const { - return theType; } + ALIstring getType() const { return theType; } // ALIbool operator==(const CocoaSolidShape& mate ); private: - ALIstring theType; - }; #endif - diff --git a/Alignment/CocoaDDLObjects/interface/CocoaSolidShapeBox.h b/Alignment/CocoaDDLObjects/interface/CocoaSolidShapeBox.h index 6c2a7b8ef6c15..25182e7d7f15d 100644 --- a/Alignment/CocoaDDLObjects/interface/CocoaSolidShapeBox.h +++ b/Alignment/CocoaDDLObjects/interface/CocoaSolidShapeBox.h @@ -1,7 +1,7 @@ // COCOA class header file -//Id: CocoaSolidShapeBox.h +// Id: CocoaSolidShapeBox.h // -// History: v1.0 +// History: v1.0 // Pedro Arce #ifndef _CocoaSolidShapeBox_HH @@ -10,28 +10,20 @@ #include "Alignment/CocoaDDLObjects/interface/CocoaSolidShape.h" #include "Alignment/CocoaUtilities/interface/CocoaGlobals.h" - -class CocoaSolidShapeBox : public CocoaSolidShape -{ - +class CocoaSolidShapeBox : public CocoaSolidShape { public: //---------- Constructors / Destructor - CocoaSolidShapeBox( ALIstring type, ALIfloat xdim, ALIfloat ydim, ALIfloat zdim ); - ~CocoaSolidShapeBox() override{ }; + CocoaSolidShapeBox(ALIstring type, ALIfloat xdim, ALIfloat ydim, ALIfloat zdim); + ~CocoaSolidShapeBox() override{}; - ALIfloat getXHalfLength() const { - return theXHalfLength; } - ALIfloat getYHalfLength() const { - return theYHalfLength; } - ALIfloat getZHalfLength() const { - return theZHalfLength; } + ALIfloat getXHalfLength() const { return theXHalfLength; } + ALIfloat getYHalfLength() const { return theYHalfLength; } + ALIfloat getZHalfLength() const { return theZHalfLength; } private: - ALIfloat theXHalfLength; ALIfloat theYHalfLength; ALIfloat theZHalfLength; }; #endif - diff --git a/Alignment/CocoaDDLObjects/interface/CocoaSolidShapeTubs.h b/Alignment/CocoaDDLObjects/interface/CocoaSolidShapeTubs.h index 7fdb1686c4a2d..a58750af2345e 100644 --- a/Alignment/CocoaDDLObjects/interface/CocoaSolidShapeTubs.h +++ b/Alignment/CocoaDDLObjects/interface/CocoaSolidShapeTubs.h @@ -1,7 +1,7 @@ // COCOA class header file -//Id: CocoaSolidShapeTubs.h +// Id: CocoaSolidShapeTubs.h // -// History: v1.0 +// History: v1.0 // Pedro Arce #ifndef _CocoaSolidShapeTubs_HH @@ -11,33 +11,28 @@ #include "Alignment/CocoaUtilities/interface/CocoaGlobals.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" -class CocoaSolidShapeTubs : public CocoaSolidShape -{ - +class CocoaSolidShapeTubs : public CocoaSolidShape { public: //---------- Constructors / Destructor - CocoaSolidShapeTubs( const ALIstring pType, ALIfloat pRMin, ALIfloat pRMax, ALIfloat pDz, ALIfloat pSPhi = 0.*deg, ALIfloat pDPhi = 360.*deg ); - ~CocoaSolidShapeTubs() override{ }; - ALIfloat getInnerRadius() const { - return theInnerRadius; } - ALIfloat getOuterRadius() const { - return theOuterRadius ; } - ALIfloat getZHalfLength() const { - return theZHalfLength ; } - ALIfloat getStartPhiAngle() const { - return theStartPhiAngle ; } - ALIfloat getDeltaPhiAngle() const { - return theDeltaPhiAngle ; } + CocoaSolidShapeTubs(const ALIstring pType, + ALIfloat pRMin, + ALIfloat pRMax, + ALIfloat pDz, + ALIfloat pSPhi = 0. * deg, + ALIfloat pDPhi = 360. * deg); + ~CocoaSolidShapeTubs() override{}; + ALIfloat getInnerRadius() const { return theInnerRadius; } + ALIfloat getOuterRadius() const { return theOuterRadius; } + ALIfloat getZHalfLength() const { return theZHalfLength; } + ALIfloat getStartPhiAngle() const { return theStartPhiAngle; } + ALIfloat getDeltaPhiAngle() const { return theDeltaPhiAngle; } private: - ALIfloat theInnerRadius; ALIfloat theOuterRadius; ALIfloat theZHalfLength; ALIfloat theStartPhiAngle; ALIfloat theDeltaPhiAngle; - }; #endif - diff --git a/Alignment/CocoaDDLObjects/src/CocoaMaterialElementary.cc b/Alignment/CocoaDDLObjects/src/CocoaMaterialElementary.cc index 0da0aa10be743..b843f34cf9932 100644 --- a/Alignment/CocoaDDLObjects/src/CocoaMaterialElementary.cc +++ b/Alignment/CocoaDDLObjects/src/CocoaMaterialElementary.cc @@ -1,34 +1,23 @@ // COCOA class implementation file -//Id: CocoaMaterialElementary.cc -//CAT: Model +// Id: CocoaMaterialElementary.cc +// CAT: Model // // History: v1.0 // Pedro Arce -#include +#include // include floating-point std::abs functions #include -#include // include floating-point std::abs functions +#include #include "Alignment/CocoaDDLObjects/interface/CocoaMaterialElementary.h" +CocoaMaterialElementary::CocoaMaterialElementary(ALIstring name, float density, ALIstring symbol, float A, ALIint Z) + : theName(name), theDensity(density), theSymbol(symbol), theA(A), theZ(Z) {} -CocoaMaterialElementary::CocoaMaterialElementary( ALIstring name, float density, ALIstring symbol, float A, ALIint Z ) : - theName(name), - theDensity(density), - theSymbol(symbol), - theA(A), - theZ(Z) -{ -} - - -ALIbool CocoaMaterialElementary::operator==(const CocoaMaterialElementary& mate ) const -{ +ALIbool CocoaMaterialElementary::operator==(const CocoaMaterialElementary &mate) const { // GM: Using numeric_limits::epsilon() might be better instead of a // magic number 'kTolerance'. Not changing this to not break code // potentially relying on this number. const float kTolerance = 1.E-9; - return ( std::abs(mate.getDensity() - theDensity) < kTolerance - && mate.getSymbol() == theSymbol - && std::abs(mate.getA() - theA) < kTolerance - && mate.getZ() == theZ ); + return (std::abs(mate.getDensity() - theDensity) < kTolerance && mate.getSymbol() == theSymbol && + std::abs(mate.getA() - theA) < kTolerance && mate.getZ() == theZ); } diff --git a/Alignment/CocoaDDLObjects/src/CocoaSolidShape.cc b/Alignment/CocoaDDLObjects/src/CocoaSolidShape.cc index 69699a12aca4a..60d0bdba7b5bb 100644 --- a/Alignment/CocoaDDLObjects/src/CocoaSolidShape.cc +++ b/Alignment/CocoaDDLObjects/src/CocoaSolidShape.cc @@ -1,17 +1,12 @@ // COCOA class implementation file -//Id: CocoaSolidShape.cc -//CAT: Model +// Id: CocoaSolidShape.cc +// CAT: Model // -// History: v1.0 +// History: v1.0 // Pedro Arce -#include #include +#include #include "Alignment/CocoaDDLObjects/interface/CocoaSolidShape.h" - -CocoaSolidShape::CocoaSolidShape( ALIstring type ) -{ - - theType = type; -} +CocoaSolidShape::CocoaSolidShape(ALIstring type) { theType = type; } diff --git a/Alignment/CocoaDDLObjects/src/CocoaSolidShapeBox.cc b/Alignment/CocoaDDLObjects/src/CocoaSolidShapeBox.cc index 6d3c5ed402eb3..c48c992d44d44 100644 --- a/Alignment/CocoaDDLObjects/src/CocoaSolidShapeBox.cc +++ b/Alignment/CocoaDDLObjects/src/CocoaSolidShapeBox.cc @@ -1,20 +1,17 @@ // COCOA class implementation file -//Id: CocoaSolidShapeBox.cc -//CAT: Model +// Id: CocoaSolidShapeBox.cc +// CAT: Model // -// History: v1.0 +// History: v1.0 // Pedro Arce -#include #include +#include #include "Alignment/CocoaDDLObjects/interface/CocoaSolidShapeBox.h" - -CocoaSolidShapeBox::CocoaSolidShapeBox( ALIstring type, ALIfloat xdim, ALIfloat ydim, ALIfloat zdim ): CocoaSolidShape( type ) -{ - +CocoaSolidShapeBox::CocoaSolidShapeBox(ALIstring type, ALIfloat xdim, ALIfloat ydim, ALIfloat zdim) + : CocoaSolidShape(type) { theXHalfLength = xdim; theYHalfLength = ydim; theZHalfLength = zdim; } - diff --git a/Alignment/CocoaDDLObjects/src/CocoaSolidShapeTubs.cc b/Alignment/CocoaDDLObjects/src/CocoaSolidShapeTubs.cc index 5f4c8854bb78d..c2e282268c211 100644 --- a/Alignment/CocoaDDLObjects/src/CocoaSolidShapeTubs.cc +++ b/Alignment/CocoaDDLObjects/src/CocoaSolidShapeTubs.cc @@ -1,21 +1,20 @@ // COCOA class implementation file -//Id: CocoaSolidShapeTubs.cc -//CAT: Model +// Id: CocoaSolidShapeTubs.cc +// CAT: Model // -// History: v1.0 +// History: v1.0 // Pedro Arce -#include #include +#include #include "Alignment/CocoaDDLObjects/interface/CocoaSolidShapeTubs.h" -CocoaSolidShapeTubs::CocoaSolidShapeTubs( const ALIstring type, ALIfloat pRMin, ALIfloat pRMax, ALIfloat pDz, ALIfloat pSPhi, ALIfloat pDPhi ) : CocoaSolidShape( type ) -{ - +CocoaSolidShapeTubs::CocoaSolidShapeTubs( + const ALIstring type, ALIfloat pRMin, ALIfloat pRMax, ALIfloat pDz, ALIfloat pSPhi, ALIfloat pDPhi) + : CocoaSolidShape(type) { theInnerRadius = pRMin; theOuterRadius = pRMax; theZHalfLength = pDz; theStartPhiAngle = pSPhi; theDeltaPhiAngle = pDPhi; } - diff --git a/Alignment/CocoaModel/src/ALILine.cc b/Alignment/CocoaModel/src/ALILine.cc index af250367facf4..f7cc96e3457df 100644 --- a/Alignment/CocoaModel/src/ALILine.cc +++ b/Alignment/CocoaModel/src/ALILine.cc @@ -65,20 +65,20 @@ CLHEP::Hep3Vector ALILine::intersect( const ALILine& l2, bool notParallel ) } else { - // **************************************************************** // - // **************************************************************** // - // **************************************************************** // - // Determination of Fact // - // // - // Problem : 3D quantity was determined by doing calculation with // - // the 2D projections of the std::vectors. It is possible // - // for projection in a particular plane to be 0 // - // // - // Solution : Test for problem and redo calculation if necessary by // - // projecting into a different plane // - // **************************************************************** // - // **************************************************************** // - // **************************************************************** // + // **************************************************************** // + // **************************************************************** // + // **************************************************************** // + // Determination of Fact // + // // + // Problem : 3D quantity was determined by doing calculation with // + // the 2D projections of the std::vectors. It is possible // + // for projection in a particular plane to be 0 // + // // + // Solution : Test for problem and redo calculation if necessary by // + // projecting into a different plane // + // **************************************************************** // + // **************************************************************** // + // **************************************************************** // diff --git a/Alignment/CocoaModel/src/EntryAngleAffAngles.cc b/Alignment/CocoaModel/src/EntryAngleAffAngles.cc index 6620451028e05..4b9908ada96fa 100644 --- a/Alignment/CocoaModel/src/EntryAngleAffAngles.cc +++ b/Alignment/CocoaModel/src/EntryAngleAffAngles.cc @@ -119,8 +119,8 @@ ALIdouble EntryAngleAffAngles::valueDisplaced() const /* CLHEP::HepRotation rmLocalOrig = OptOCurrent()->parent()->rmGlobOriginal().inverse() * OptOCurrent()->rmGlobOriginal(); - - CLHEP::HepRotation rmLocal = OptOCurrent()->parent()->rmGlob().inverse() * OptOCurrent()->rmGlob(); + + CLHEP::HepRotation rmLocal = OptOCurrent()->parent()->rmGlob().inverse() * OptOCurrent()->rmGlob(); std::vector localrot = OptOCurrent()->getRotationAnglesFromMatrix( rmLocal, OptOCurrent()->CoordinateEntryList() ); std::cout << " localrot " << localrot[0] << " " << localrot[1] << " " << localrot[2] << std::endl; @@ -139,7 +139,7 @@ ALIdouble EntryAngleAffAngles::valueDisplaced() const Yaxis = OptOCurrent()->parent()->rmGlob() * Yaxis; CLHEP::Hep3Vector YaxisOrig(0.,1.,0.); YaxisOrig = OptOCurrent()->parent()->rmGlobOriginal() * YaxisOrig; - + diff = fabs( checkDiff( Yaxis, YaxisOrig, localrot, localrotorig ) ); } diff --git a/Alignment/CocoaModel/src/OptOTiltmeter.cc b/Alignment/CocoaModel/src/OptOTiltmeter.cc index 0e9a25b84d101..cdb40d5b7a46b 100644 --- a/Alignment/CocoaModel/src/OptOTiltmeter.cc +++ b/Alignment/CocoaModel/src/OptOTiltmeter.cc @@ -74,7 +74,7 @@ void OptOTiltmeter::makeMeasurement( LightRay& lightray, Measurement& meas ) CLHEP::Hep3Vector ZAxism(0.,0.,1.); CLHEP::Hep3Vector ZAxism_ori = ZAxism; ZAxism_ori *= rmtori; - + //---------- Measure rotation with respect to original position, around the X axis defined by the original position, in the original YZ plane CLHEP::Hep3Vector ZAxism_rot = ZAxism; CLHEP::HepRotation rmt = rmGlob(); @@ -94,7 +94,7 @@ void OptOTiltmeter::makeMeasurement( LightRay& lightray, Measurement& meas ) ALIdouble measValue = acos( ZAxism.dot(ZAxism_proj)/ZAxism_proj.mag() ); if( ZAxism_proj.x() < 0) measValue *= -1.; meas.setValueSimulated(0 , measValue ); - + if (ALIUtils::debug >= 3) { std::cout << " OptOTiltmeter: Original Z axis " << ZAxism_ori << std::endl; ALIUtils::dumprm(rmt," tiltmeter original rotation matrix"); diff --git a/Alignment/CocoaToDDL/src/CocoaToDDLMgr.cc b/Alignment/CocoaToDDL/src/CocoaToDDLMgr.cc index 15fbcbc5a7537..3eb909c434dea 100644 --- a/Alignment/CocoaToDDL/src/CocoaToDDLMgr.cc +++ b/Alignment/CocoaToDDL/src/CocoaToDDLMgr.cc @@ -333,7 +333,7 @@ std::string solidType = so->getType(); file_ << " IsOpen(); G4int numRZCorner = (dynamic_cast < G4Polycone * > (so))->getNumRZCorner(); - + file_ << " startPhi=\"" << UC(pc->getStartPhi(),"Angle") << "\"" //<< " deltaPhi=\"" << UC(fabs((pc->getEndPhi()/deg - pc->getStartPhi()/deg))*deg,"Angle") << "\"" //<< " deltaPhi=\"" << UC(pc->getEndPhi(),"Angle") << "\"" @@ -342,7 +342,7 @@ std::string solidType = so->getType(); << " >" << std::endl; G4PolyconeSideRZ rz; - + //liendl: FIXME put a switch which decides whether RZ or Rmin,Rmax,Z types should // by generated .... //outPolyZSections(rz, (dynamic_cast < G4Polycone * > (so)), numRZCorner); @@ -362,7 +362,7 @@ std::string solidType = so->getType(); // bool isOpen = (dynamic_cast < G4Polyhedra * > (so))->IsOpen(); G4Polyhedra * ph = (dynamic_cast < G4Polyhedra * > (so)); G4int numRZCorner = ph->getNumRZCorner(); - + file_ << " getNumSide() << "\"" << " startPhi=\"" << UC(ph->getStartPhi(),"Angle") << "\"" diff --git a/Alignment/CocoaUtilities/interface/ALIUtils.h b/Alignment/CocoaUtilities/interface/ALIUtils.h index 991ba668bf00d..3f9c561602315 100644 --- a/Alignment/CocoaUtilities/interface/ALIUtils.h +++ b/Alignment/CocoaUtilities/interface/ALIUtils.h @@ -138,12 +138,10 @@ class ALIUtils template ALIuint FindItemInVector( const T* item, const std::vector& item_vector ) { - std::vector::const_iterator vtcite; ALIuint vfound = 1; for( vtcite = item_vector.begin(); vtcite != item_vector.end(); vtcite++) { if( (*vtcite) == item ) { - } } diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignableData.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignableData.h index 6ec036d0de5f3..be6bd6fd1dc67 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignableData.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignableData.h @@ -10,29 +10,26 @@ /// also surface deformation parameters are foreseen; /// can be used for both absolute and relative positions/rotations -template class AlignableData -{ - +template +class AlignableData { public: - /// constructor /// deformationParameters can be given if detUnit AlignableData(const T& pos, - const align::RotationType& rot, - align::ID id, align::StructureType objid, - const std::vector &deformationParameters = std::vector()) : - thePos(pos), theRot(rot), theObjId(objid), theId(id), - theDeformationParameters(deformationParameters) {} + const align::RotationType& rot, + align::ID id, + align::StructureType objid, + const std::vector& deformationParameters = std::vector()) + : thePos(pos), theRot(rot), theObjId(objid), theId(id), theDeformationParameters(deformationParameters) {} /// accessors const T& pos() const { return thePos; } const align::RotationType& rot() const { return theRot; } align::StructureType objId() const { return theObjId; } align::ID id() const { return theId; } - const std::vector deformationParameters() const { return theDeformationParameters;} + const std::vector deformationParameters() const { return theDeformationParameters; } private: - // data members T thePos; @@ -40,16 +37,14 @@ template class AlignableData align::StructureType theObjId; align::ID theId; std::vector theDeformationParameters; - }; -/// Absolute position/rotation -typedef AlignableData AlignableAbsData; -/// relative position/rotation +/// Absolute position/rotation +typedef AlignableData AlignableAbsData; +/// relative position/rotation typedef AlignableData AlignableRelData; typedef std::vector AlignablePositions; typedef std::vector AlignableShifts; #endif - diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIO.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIO.h index 60d79c3b246cf..c7a243bb856a5 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIO.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIO.h @@ -7,80 +7,74 @@ class Alignable; /// Abstract base class for IO of alignable positions/shifts. -/// Derived concrete class must implement raw read/write methods - -class AlignableDataIO -{ - - protected: +/// Derived concrete class must implement raw read/write methods +class AlignableDataIO { +protected: enum PosType { Abs, Org, Rel }; - /// Constructor - AlignableDataIO(PosType p) : thePosType(p) {}; + /// Constructor + AlignableDataIO(PosType p) : thePosType(p){}; - /// Destructor + /// Destructor virtual ~AlignableDataIO(){}; /// Open IO handle - virtual int open( const char* filename, int iteration, bool writemode ) = 0; + virtual int open(const char* filename, int iteration, bool writemode) = 0; /// Close IO handle virtual int close(void) = 0; - /// Write absolute positions of one Alignable + /// Write absolute positions of one Alignable int writeAbsPos(Alignable* ali, bool validCheck); - /// Write absolute positions of many Alignables + /// Write absolute positions of many Alignables int writeAbsPos(const align::Alignables& alivec, bool validCheck); - /// Read absolute positions of one Alignable + /// Read absolute positions of one Alignable AlignableAbsData readAbsPos(Alignable* ali, int& ierr); - /// Read absolute positions of many Alignables + /// Read absolute positions of many Alignables AlignablePositions readAbsPos(const align::Alignables& alivec, int& ierr); - - /// Write original positions of one Alignable + /// Write original positions of one Alignable int writeOrgPos(Alignable* ali, bool validCheck); - /// Write original positions of many Alignables + /// Write original positions of many Alignables int writeOrgPos(const align::Alignables& alivec, bool validCheck); - /// Read original positions of one Alignable + /// Read original positions of one Alignable AlignableAbsData readOrgPos(Alignable* ali, int& ierr); - /// Read original positions of many Alignables + /// Read original positions of many Alignables AlignablePositions readOrgPos(const align::Alignables& alivec, int& ierr); - - /// Write relative positions of one Alignable + /// Write relative positions of one Alignable int writeRelPos(Alignable* ali, bool validCheck); - /// Write relative positions of many Alignables + /// Write relative positions of many Alignables int writeRelPos(const align::Alignables& alivec, bool validCheck); - /// Read relative positions of one Alignable + /// Read relative positions of one Alignable AlignableRelData readRelPos(Alignable* ali, int& ierr); - /// Read relative positions of many Alignables + /// Read relative positions of many Alignables AlignableShifts readRelPos(const align::Alignables& alivec, int& ierr); // 'raw' read/write methods // must be provided by concrete derived class - /// Write absolute positions - virtual int writeAbsRaw(const AlignableAbsData &ad) =0; - /// Read absolute positions - virtual AlignableAbsData readAbsRaw(Alignable* ali,int& ierr) =0; - /// Write relative positions - virtual int writeRelRaw(const AlignableRelData &ad) =0; - /// Read relative positions - virtual AlignableRelData readRelRaw(Alignable* ali,int& ierr) =0; + /// Write absolute positions + virtual int writeAbsRaw(const AlignableAbsData& ad) = 0; + /// Read absolute positions + virtual AlignableAbsData readAbsRaw(Alignable* ali, int& ierr) = 0; + /// Write relative positions + virtual int writeRelRaw(const AlignableRelData& ad) = 0; + /// Read relative positions + virtual AlignableRelData readRelRaw(Alignable* ali, int& ierr) = 0; // Data members - PosType thePosType; // Defines whether absolute/orig/relative pos. are used - + PosType thePosType; // Defines whether absolute/orig/relative pos. are used }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIORoot.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIORoot.h index 347ab94bdd0ef..d128aba0bcfc3 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIORoot.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIORoot.h @@ -9,32 +9,32 @@ class Alignable; -/// concrete class for ROOT based IO of Alignable positions - -class AlignableDataIORoot : public AlignmentIORootBase, public AlignableDataIO -{ +/// concrete class for ROOT based IO of Alignable positions +class AlignableDataIORoot : public AlignmentIORootBase, public AlignableDataIO { friend class AlignmentIORoot; - private: - /// constructor - AlignableDataIORoot(PosType p); +private: + /// constructor + AlignableDataIORoot(PosType p); - /// open IO - int open(const char* filename, int iteration, bool writemode) override - { newopen=true; return openRoot(filename,iteration,writemode); } + /// open IO + int open(const char* filename, int iteration, bool writemode) override { + newopen = true; + return openRoot(filename, iteration, writemode); + } - /// close IO - int close(void) override{ return closeRoot(); } + /// close IO + int close(void) override { return closeRoot(); } - /// write absolute positions - int writeAbsRaw(const AlignableAbsData &ad) override; - /// read absolute positions - AlignableAbsData readAbsRaw(Alignable* ali,int& ierr) override; - /// write relative positions - int writeRelRaw(const AlignableRelData &ad) override; - /// read relative positions - AlignableRelData readRelRaw(Alignable* ali,int& ierr) override; + /// write absolute positions + int writeAbsRaw(const AlignableAbsData& ad) override; + /// read absolute positions + AlignableAbsData readAbsRaw(Alignable* ali, int& ierr) override; + /// write relative positions + int writeRelRaw(const AlignableRelData& ad) override; + /// read relative positions + AlignableRelData readRelRaw(Alignable* ali, int& ierr) override; int findEntry(align::ID, align::StructureType); void createBranches(void) override; @@ -42,22 +42,19 @@ class AlignableDataIORoot : public AlignmentIORootBase, public AlignableDataIO // data members - /// root tree contents + /// root tree contents align::StructureType ObjId; //unsigned int Id; align::ID Id; Double_t Pos[3]; Double_t Rot[9]; UInt_t numDeformationValues_; - enum {kMaxNumPar = 20}; // slighly above 'two bowed surfaces' limit + enum { kMaxNumPar = 20 }; // slighly above 'two bowed surfaces' limit Float_t deformationValues_[kMaxNumPar]; bool newopen; - typedef std::map< std::pair, int > treemaptype; + typedef std::map, int> treemaptype; treemaptype treemap; - }; - - #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmBase.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmBase.h index bc8e1ace77ef3..51d482e1eb969 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmBase.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmBase.h @@ -16,8 +16,6 @@ * algorithm has to be derived from this class */ - - #include #include @@ -39,90 +37,94 @@ class Trajectory; #include "DataFormats/Alignment/interface/AliClusterValueMapFwd.h" #include "FWCore/Framework/interface/Event.h" -namespace edm { class EventSetup; class ParameterSet; } -namespace reco { class Track; class BeamSpot; } +namespace edm { + class EventSetup; + class ParameterSet; +} // namespace edm +namespace reco { + class Track; + class BeamSpot; +} // namespace reco /*** Global typedefs part I (see EOF for part II) ***/ -typedef std::pair ConstTrajTrackPair; -typedef std::vector< ConstTrajTrackPair > ConstTrajTrackPairs; - -typedef std::vector Calibrations; - - +typedef std::pair ConstTrajTrackPair; +typedef std::vector ConstTrajTrackPairs; -class AlignmentAlgorithmBase -{ +typedef std::vector Calibrations; +class AlignmentAlgorithmBase { public: // TODO: DEPRECATED: For not breaking the interface, used in serveral files. // If possible use the global typedefs above. // With global typedefs one does not have to typedef again like // 'typedef AlignmentAlgorithmBase::ConstTrajTrackPair ConstTrajTrackPair;' // in other files. - typedef std::pair ConstTrajTrackPair; - typedef std::vector< ConstTrajTrackPair > ConstTrajTrackPairCollection; + typedef std::pair ConstTrajTrackPair; + typedef std::vector ConstTrajTrackPairCollection; using RunNumber = align::RunNumber; using RunRange = align::RunRange; /// define event information passed to algorithms class EventInfo { public: - EventInfo(const edm::EventID &theEventId, - const ConstTrajTrackPairCollection &theTrajTrackPairs, - const reco::BeamSpot &theBeamSpot, - const AliClusterValueMap *theClusterValueMap) - : eventId_(theEventId), trajTrackPairs_(theTrajTrackPairs), beamSpot_(theBeamSpot), clusterValueMap_(theClusterValueMap) {} + EventInfo(const edm::EventID &theEventId, + const ConstTrajTrackPairCollection &theTrajTrackPairs, + const reco::BeamSpot &theBeamSpot, + const AliClusterValueMap *theClusterValueMap) + : eventId_(theEventId), + trajTrackPairs_(theTrajTrackPairs), + beamSpot_(theBeamSpot), + clusterValueMap_(theClusterValueMap) {} const edm::EventID eventId() const { return eventId_; } - const ConstTrajTrackPairCollection& trajTrackPairs() const { return trajTrackPairs_; } - const reco::BeamSpot& beamSpot() const { return beamSpot_; } - const AliClusterValueMap* clusterValueMap() const { return clusterValueMap_; }///might be null! - + const ConstTrajTrackPairCollection &trajTrackPairs() const { return trajTrackPairs_; } + const reco::BeamSpot &beamSpot() const { return beamSpot_; } + const AliClusterValueMap *clusterValueMap() const { return clusterValueMap_; } ///might be null! private: - const edm::EventID eventId_; + const edm::EventID eventId_; const ConstTrajTrackPairCollection &trajTrackPairs_; - const reco::BeamSpot &beamSpot_; - const AliClusterValueMap *clusterValueMap_;///might be null! + const reco::BeamSpot &beamSpot_; + const AliClusterValueMap *clusterValueMap_; ///might be null! }; - + /// define run information passed to algorithms (in endRun) class EndRunInfo { public: - EndRunInfo(const edm::RunID &theRunId, const TkFittedLasBeamCollection *theTkLasBeams, - const TsosVectorCollection *theTkLasBeamTsoses) - : runId_(theRunId), tkLasBeams_(theTkLasBeams), tkLasBeamTsoses_(theTkLasBeamTsoses) {} + EndRunInfo(const edm::RunID &theRunId, + const TkFittedLasBeamCollection *theTkLasBeams, + const TsosVectorCollection *theTkLasBeamTsoses) + : runId_(theRunId), tkLasBeams_(theTkLasBeams), tkLasBeamTsoses_(theTkLasBeamTsoses) {} const edm::RunID runId() const { return runId_; } - const TkFittedLasBeamCollection* tkLasBeams() const { return tkLasBeams_; } /// might be null! - const TsosVectorCollection* tkLasBeamTsoses() const { return tkLasBeamTsoses_; } /// might be null! - + const TkFittedLasBeamCollection *tkLasBeams() const { return tkLasBeams_; } /// might be null! + const TsosVectorCollection *tkLasBeamTsoses() const { return tkLasBeamTsoses_; } /// might be null! private: const edm::RunID runId_; - const TkFittedLasBeamCollection *tkLasBeams_; /// might be null! - const TsosVectorCollection *tkLasBeamTsoses_; /// might be null! + const TkFittedLasBeamCollection *tkLasBeams_; /// might be null! + const TsosVectorCollection *tkLasBeamTsoses_; /// might be null! }; - + /// Constructor - AlignmentAlgorithmBase(const edm::ParameterSet&) {}; - + AlignmentAlgorithmBase(const edm::ParameterSet &){}; + /// Destructor - virtual ~AlignmentAlgorithmBase() {}; + virtual ~AlignmentAlgorithmBase(){}; /// Call at beginning of job (must be implemented in derived class) - virtual void initialize( const edm::EventSetup& setup, - AlignableTracker* tracker, - AlignableMuon* muon, - AlignableExtras* extras, - AlignmentParameterStore* store ) = 0; + virtual void initialize(const edm::EventSetup &setup, + AlignableTracker *tracker, + AlignableMuon *muon, + AlignableExtras *extras, + AlignmentParameterStore *store) = 0; /// Returns whether calibrations is supported by algorithm, /// default implementation returns false. virtual bool supportsCalibrations() { return false; } /// Pass integrated calibrations to algorithm, to be called after initialize() /// Calibrations' ownership is NOT passed to algorithm - virtual bool addCalibrations(const Calibrations&) { return false; } + virtual bool addCalibrations(const Calibrations &) { return false; } /// Returns whether algorithm proccesses events in current configuration virtual bool processesEvents() { return true; } @@ -137,32 +139,32 @@ class AlignmentAlgorithmBase virtual void startNewLoop() {} /// Call at end of each loop (must be implemented in derived class) - virtual void terminate(const edm::EventSetup& iSetup) = 0; + virtual void terminate(const edm::EventSetup &iSetup) = 0; /// Called at end of job (must be implemented in derived class) virtual void terminate() {} /// Run the algorithm (must be implemented in derived class) - virtual void run( const edm::EventSetup &setup, const EventInfo &eventInfo) = 0; + virtual void run(const edm::EventSetup &setup, const EventInfo &eventInfo) = 0; /// called at begin of run - virtual void beginRun(const edm::Run&, const edm::EventSetup&, bool changed) {}; + virtual void beginRun(const edm::Run &, const edm::EventSetup &, bool changed){}; /// called at end of run - order of arguments like in EDProducer etc. - virtual void endRun(const EndRunInfo &runInfo, const edm::EventSetup &setup) {}; + virtual void endRun(const EndRunInfo &runInfo, const edm::EventSetup &setup){}; /// called at begin of luminosity block (no lumi block info passed yet) - virtual void beginLuminosityBlock(const edm::EventSetup &setup) {}; + virtual void beginLuminosityBlock(const edm::EventSetup &setup){}; /// called at end of luminosity block (no lumi block info passed yet) - virtual void endLuminosityBlock(const edm::EventSetup &setup) {}; + virtual void endLuminosityBlock(const edm::EventSetup &setup){}; /// called in order to pass parameters to alignables for a specific run /// range in case the algorithm supports run range dependent alignment. - virtual bool setParametersForRunRange(const RunRange& rr) { return false; }; + virtual bool setParametersForRunRange(const RunRange &rr) { return false; }; }; /*** Global typedefs part II ***/ -typedef AlignmentAlgorithmBase::EventInfo EventInfo; +typedef AlignmentAlgorithmBase::EventInfo EventInfo; typedef AlignmentAlgorithmBase::EndRunInfo EndRunInfo; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmPluginFactory.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmPluginFactory.h index de93b72901465..c49c2f06a67ef 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmPluginFactory.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmPluginFactory.h @@ -10,6 +10,6 @@ #include "FWCore/PluginManager/interface/PluginFactory.h" #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmBase.h" -typedef edmplugin::PluginFactory AlignmentAlgorithmPluginFactory; +typedef edmplugin::PluginFactory AlignmentAlgorithmPluginFactory; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIO.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIO.h index 09ea12db136cf..82467dc16a0ff 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIO.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIO.h @@ -3,28 +3,24 @@ #include "Alignment/CommonAlignment/interface/Utilities.h" -/// Abstract base class for IO of Correlations +/// Abstract base class for IO of Correlations -class AlignmentCorrelationsIO -{ +class AlignmentCorrelationsIO { +protected: + /// destructor + virtual ~AlignmentCorrelationsIO() {} - protected: - - /// destructor - virtual ~AlignmentCorrelationsIO(){} - - /// open IO + /// open IO virtual int open(const char* filename, int iteration, bool writemode) = 0; - /// close IO + /// close IO virtual int close(void) = 0; - /// write correlations + /// write correlations virtual int write(const align::Correlations& cor, bool validCheck) = 0; - /// read correlations + /// read correlations virtual align::Correlations read(const align::Alignables& alivec, int& ierr) = 0; - }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIORoot.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIORoot.h index 58376cb0aa466..889885a70e659 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIORoot.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIORoot.h @@ -5,29 +5,27 @@ #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORootBase.h" #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsIO.h" -/// Concrete class for ROOT based IO of Correlations +/// Concrete class for ROOT based IO of Correlations -class AlignmentCorrelationsIORoot : public AlignmentIORootBase, public AlignmentCorrelationsIO -{ +class AlignmentCorrelationsIORoot : public AlignmentIORootBase, public AlignmentCorrelationsIO { friend class AlignmentIORoot; - private: - - /// constructor +private: + /// constructor AlignmentCorrelationsIORoot(); - /// open IO + /// open IO int open(const char* filename, int iteration, bool writemode) override { - return openRoot(filename,iteration,writemode); + return openRoot(filename, iteration, writemode); }; - /// close IO - int close(void) override{ return closeRoot(); }; + /// close IO + int close(void) override { return closeRoot(); }; - /// write correlations + /// write correlations int write(const align::Correlations& cor, bool validCheck) override; - /// read correlations + /// read correlations align::Correlations read(const align::Alignables& alivec, int& ierr) override; void createBranches(void) override; @@ -35,12 +33,11 @@ class AlignmentCorrelationsIORoot : public AlignmentIORootBase, public Alignment // data members - /// correlation tree - align::ID Ali1Id,Ali2Id; - align::StructureType Ali1ObjId,Ali2ObjId; + /// correlation tree + align::ID Ali1Id, Ali2Id; + align::StructureType Ali1ObjId, Ali2ObjId; int corSize; - double CorMatrix[nParMax*nParMax]; - + double CorMatrix[nParMax * nParMax]; }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsStore.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsStore.h index 8f796f3ec4cc0..96bd5a2fafdb0 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsStore.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsStore.h @@ -13,59 +13,57 @@ class Alignable; -class AlignmentCorrelationsStore -{ - +class AlignmentCorrelationsStore { public: + typedef std::map CorrelationsTable; + typedef std::map Correlations; - typedef std::map< Alignable*, AlgebraicMatrix > CorrelationsTable; - typedef std::map< Alignable*, CorrelationsTable* > Correlations; - - AlignmentCorrelationsStore( void ); + AlignmentCorrelationsStore(void); - virtual ~AlignmentCorrelationsStore( void ) {} + virtual ~AlignmentCorrelationsStore(void) {} /// Write correlations directly to the covariance matrix starting at the /// given position. Indices are assumed to start from 0. - virtual void correlations( Alignable* ap1, Alignable* ap2, - AlgebraicSymMatrix& cov, int row, int col ) const; + virtual void correlations(Alignable* ap1, Alignable* ap2, AlgebraicSymMatrix& cov, int row, int col) const; /// Get correlations directly from the given position of the covariance /// matrix and store them. Indices are assumed to start from 0. - virtual void setCorrelations( Alignable* ap1, Alignable* ap2, - const AlgebraicSymMatrix& cov, int row, int col ); + virtual void setCorrelations(Alignable* ap1, Alignable* ap2, const AlgebraicSymMatrix& cov, int row, int col); /// Set correlations. - virtual void setCorrelations( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat ); + virtual void setCorrelations(Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat); /// Check whether correlations are stored for a given pair of alignables. - virtual bool correlationsAvailable( Alignable* ap1, Alignable* ap2 ) const; + virtual bool correlationsAvailable(Alignable* ap1, Alignable* ap2) const; /// Reset correlations. - virtual void resetCorrelations( void ); + virtual void resetCorrelations(void); /// Get number of stored correlations. - virtual unsigned int size( void ) const; + virtual unsigned int size(void) const; private: + void fillCorrelationsTable(Alignable* ap1, + Alignable* ap2, + CorrelationsTable* table, + const AlgebraicSymMatrix& cov, + int row, + int col, + bool transpose); - void fillCorrelationsTable( Alignable* ap1, Alignable* ap2, CorrelationsTable* table, - const AlgebraicSymMatrix& cov, int row, int col, bool transpose ); + void fillCovariance( + Alignable* ap1, Alignable* ap2, const AlgebraicMatrix& entry, AlgebraicSymMatrix& cov, int row, int col) const; - void fillCovariance( Alignable* ap1, Alignable* ap2, const AlgebraicMatrix& entry, - AlgebraicSymMatrix& cov, int row, int col ) const; + void fillCovarianceT( + Alignable* ap1, Alignable* ap2, const AlgebraicMatrix& entry, AlgebraicSymMatrix& cov, int row, int col) const; - void fillCovarianceT( Alignable* ap1, Alignable* ap2, const AlgebraicMatrix& entry, - AlgebraicSymMatrix& cov, int row, int col ) const; + void readFromCovariance( + Alignable* ap1, Alignable* ap2, AlgebraicMatrix& entry, const AlgebraicSymMatrix& cov, int row, int col); - void readFromCovariance( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& entry, - const AlgebraicSymMatrix& cov, int row, int col ); - - void readFromCovarianceT( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& entry, - const AlgebraicSymMatrix& cov, int row, int col ); + void readFromCovarianceT( + Alignable* ap1, Alignable* ap2, AlgebraicMatrix& entry, const AlgebraicSymMatrix& cov, int row, int col); Correlations theCorrelations; - }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsEntry.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsEntry.h index 2a6769092ab4a..d32c8939edbee 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsEntry.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsEntry.h @@ -4,68 +4,63 @@ #include #include "DataFormats/CLHEP/interface/AlgebraicObjects.h" - /// Data container for a correlations matrix (represented by a vector of floats), with /// basic access functions. NOTE: This class is designed specifically for the use within /// AlignmentExtendedCorrelationsStore, and is not intended to be used elsewhere. - -class AlignmentExtendedCorrelationsEntry -{ - +class AlignmentExtendedCorrelationsEntry { public: - /// Default constructor. - AlignmentExtendedCorrelationsEntry( void ); + AlignmentExtendedCorrelationsEntry(void); /// Constructor. Leaves the correlations matrix uninitialized. - explicit AlignmentExtendedCorrelationsEntry( short unsigned int nRows, short unsigned int nCols ); + explicit AlignmentExtendedCorrelationsEntry(short unsigned int nRows, short unsigned int nCols); /// Constructor. Initializes all elements of the correlations matrix to the given value. - explicit AlignmentExtendedCorrelationsEntry( short unsigned int nRows, short unsigned int nCols, const float init ); + explicit AlignmentExtendedCorrelationsEntry(short unsigned int nRows, short unsigned int nCols, const float init); /// Constructor from CLHEP matrix. - explicit AlignmentExtendedCorrelationsEntry( const AlgebraicMatrix& mat ); + explicit AlignmentExtendedCorrelationsEntry(const AlgebraicMatrix& mat); /// Destructor. - ~AlignmentExtendedCorrelationsEntry( void ) {} + ~AlignmentExtendedCorrelationsEntry(void) {} /// Read or write an element of the correlations matrix. NOTE: Indexing starts from [0,0]. - inline float& operator()( short unsigned int iRow, short unsigned int jCol ) { return theData[iRow*theNCols+jCol]; } + inline float& operator()(short unsigned int iRow, short unsigned int jCol) { return theData[iRow * theNCols + jCol]; } /// Read or write an element of the correlations matrix. NOTE: Indexing starts from [0,0]. - inline const float operator()( short unsigned int iRow, short unsigned int jCol ) const { return theData[iRow*theNCols+jCol]; } + inline const float operator()(short unsigned int iRow, short unsigned int jCol) const { + return theData[iRow * theNCols + jCol]; + } /// Get the number of rows of the correlation matrix. - inline const short unsigned int numRow( void ) const { return theNRows; } + inline const short unsigned int numRow(void) const { return theNRows; } /// Get the number of columns of the correlation matrix. - inline const short unsigned int numCol( void ) const { return theNCols; } + inline const short unsigned int numCol(void) const { return theNCols; } /// Multiply all elements of the correlations matrix with a given number. - void operator*=( const float multiply ); + void operator*=(const float multiply); /// Retrieve the correlation matrix in a CLHEP matrix representation; - AlgebraicMatrix matrix( void ) const; + AlgebraicMatrix matrix(void) const; -// /// Get the counter's value. -// inline const int counter( void ) const { return theCounter; } + // /// Get the counter's value. + // inline const int counter( void ) const { return theCounter; } -// /// Increase the counter's value by 1. -// inline void incrementCounter( void ) { ++theCounter; } + // /// Increase the counter's value by 1. + // inline void incrementCounter( void ) { ++theCounter; } -// /// Decrease the counter's value by 1. -// inline void decrementCounter( void ) { --theCounter; } + // /// Decrease the counter's value by 1. + // inline void decrementCounter( void ) { --theCounter; } private: - -// int theCounter; + // int theCounter; short unsigned int theNRows; short unsigned int theNCols; - std::vector< float > theData; - + std::vector theData; }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsStore.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsStore.h index 5f68e5e5c7878..ac1f74d615257 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsStore.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsStore.h @@ -9,78 +9,91 @@ /// If a correlation exceeds a certain value (especially corrupted correlations with /// an absolute value bigger than 1) it is downweighted. - #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsStore.h" #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsEntry.h" -namespace edm { class ParameterSet; } - -class AlignmentExtendedCorrelationsStore : public AlignmentCorrelationsStore -{ +namespace edm { + class ParameterSet; +} +class AlignmentExtendedCorrelationsStore : public AlignmentCorrelationsStore { public: - typedef AlignmentExtendedCorrelationsEntry ExtendedCorrelationsEntry; - typedef std::map< Alignable*, ExtendedCorrelationsEntry > ExtendedCorrelationsTable; - typedef std::map< Alignable*, ExtendedCorrelationsTable* > ExtendedCorrelations; + typedef std::map ExtendedCorrelationsTable; + typedef std::map ExtendedCorrelations; - AlignmentExtendedCorrelationsStore( const edm::ParameterSet& config ); + AlignmentExtendedCorrelationsStore(const edm::ParameterSet& config); - ~AlignmentExtendedCorrelationsStore( void ) override {} + ~AlignmentExtendedCorrelationsStore(void) override {} /// Write correlations directly to the covariance matrix starting at the /// given position. Indices are assumed to start from 0. - void correlations( Alignable* ap1, Alignable* ap2, - AlgebraicSymMatrix& cov, int row, int col ) const override; + void correlations(Alignable* ap1, Alignable* ap2, AlgebraicSymMatrix& cov, int row, int col) const override; /// Get correlations directly from the given position of the covariance /// matrix and store them. Indices are assumed to start from 0. - void setCorrelations( Alignable* ap1, Alignable* ap2, - const AlgebraicSymMatrix& cov, int row, int col ) override; + void setCorrelations(Alignable* ap1, Alignable* ap2, const AlgebraicSymMatrix& cov, int row, int col) override; /// Set correlations without checking whether the maximum /// number of updates has already been reached. - void setCorrelations( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat ) override; + void setCorrelations(Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat) override; /// Get correlations. - virtual void getCorrelations( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat ) const; + virtual void getCorrelations(Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat) const; /// Check whether correlations are stored for a given pair of alignables. - bool correlationsAvailable( Alignable* ap1, Alignable* ap2 ) const override; + bool correlationsAvailable(Alignable* ap1, Alignable* ap2) const override; /// Reset correlations. - void resetCorrelations( void ) override; + void resetCorrelations(void) override; /// Get number of stored correlations. - unsigned int size( void ) const override; + unsigned int size(void) const override; private: - - void fillCorrelationsTable( Alignable* ap1, Alignable* ap2, - ExtendedCorrelationsTable* table, - const AlgebraicSymMatrix& cov, - int row, int col, bool transpose ); - - void fillCovariance( Alignable* ap1, Alignable* ap2, const ExtendedCorrelationsEntry& entry, - AlgebraicSymMatrix& cov, int row, int col ) const; - - void fillCovarianceT( Alignable* ap1, Alignable* ap2, const ExtendedCorrelationsEntry& entry, - AlgebraicSymMatrix& cov, int row, int col ) const; - - void readFromCovariance( Alignable* ap1, Alignable* ap2, ExtendedCorrelationsEntry& entry, - const AlgebraicSymMatrix& cov, int row, int col ); - - void readFromCovarianceT( Alignable* ap1, Alignable* ap2, ExtendedCorrelationsEntry& entry, - const AlgebraicSymMatrix& cov, int row, int col ); - - void resizeCorruptCorrelations( ExtendedCorrelationsEntry& entry, double maxCorr ); + void fillCorrelationsTable(Alignable* ap1, + Alignable* ap2, + ExtendedCorrelationsTable* table, + const AlgebraicSymMatrix& cov, + int row, + int col, + bool transpose); + + void fillCovariance(Alignable* ap1, + Alignable* ap2, + const ExtendedCorrelationsEntry& entry, + AlgebraicSymMatrix& cov, + int row, + int col) const; + + void fillCovarianceT(Alignable* ap1, + Alignable* ap2, + const ExtendedCorrelationsEntry& entry, + AlgebraicSymMatrix& cov, + int row, + int col) const; + + void readFromCovariance(Alignable* ap1, + Alignable* ap2, + ExtendedCorrelationsEntry& entry, + const AlgebraicSymMatrix& cov, + int row, + int col); + + void readFromCovarianceT(Alignable* ap1, + Alignable* ap2, + ExtendedCorrelationsEntry& entry, + const AlgebraicSymMatrix& cov, + int row, + int col); + + void resizeCorruptCorrelations(ExtendedCorrelationsEntry& entry, double maxCorr); ExtendedCorrelations theCorrelations; int theMaxUpdates; double theCut; double theWeight; - }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIO.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIO.h index 9601989094048..418205ef65829 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIO.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIO.h @@ -11,60 +11,65 @@ /// $Revision: 1.3 $ /// (last update by $Author: flucke $) - #include "Alignment/CommonAlignment/interface/Utilities.h" #include "Alignment/CommonAlignmentAlgorithm/interface/AlignableData.h" - -class AlignmentIO -{ - - public: +class AlignmentIO { +public: virtual ~AlignmentIO() = default; - /// write AlignmentParameters - virtual void writeAlignmentParameters (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr) = 0; + /// write AlignmentParameters + virtual void writeAlignmentParameters( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) = 0; - /// read AlignmentParameters - virtual align::Parameters readAlignmentParameters (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) = 0; + /// read AlignmentParameters + virtual align::Parameters readAlignmentParameters(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) = 0; /// write RigidBodyAlignmentParameters as applied on top of original positions - virtual void writeOrigRigidBodyAlignmentParameters (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr) = 0; - - /// write Correlations - virtual void writeCorrelations (const align::Correlations& cormap, - const char* filename, int iter, bool validCheck, int& ierr) = 0; - - /// read Correlations - virtual align::Correlations readCorrelations (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) = 0; - - /// write Alignable current absolute positions - virtual void writeAlignableAbsolutePositions (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr) = 0; - - /// read Alignable current absolute positions - virtual AlignablePositions readAlignableAbsolutePositions (const align::Alignables& - alivec, const char* filename, int iter, int& ierr) = 0; - - /// write Alignable original (before misalignment) absolute positions - virtual void writeAlignableOriginalPositions (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr) = 0; - - /// read Alignable original (before misalignment) absolute positions - virtual AlignablePositions readAlignableOriginalPositions (const align::Alignables& - alivec, const char* filename, int iter, int& ierr) = 0; - - /// write Alignable relative positions (shift,rotation) - virtual void writeAlignableRelativePositions (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr) = 0; - - /// read Alignable relative positions (shift,rotation) - virtual AlignableShifts readAlignableRelativePositions (const align::Alignables& - alivec, const char* filename, int iter, int& ierr) = 0; - + virtual void writeOrigRigidBodyAlignmentParameters( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) = 0; + + /// write Correlations + virtual void writeCorrelations( + const align::Correlations& cormap, const char* filename, int iter, bool validCheck, int& ierr) = 0; + + /// read Correlations + virtual align::Correlations readCorrelations(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) = 0; + + /// write Alignable current absolute positions + virtual void writeAlignableAbsolutePositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) = 0; + + /// read Alignable current absolute positions + virtual AlignablePositions readAlignableAbsolutePositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) = 0; + + /// write Alignable original (before misalignment) absolute positions + virtual void writeAlignableOriginalPositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) = 0; + + /// read Alignable original (before misalignment) absolute positions + virtual AlignablePositions readAlignableOriginalPositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) = 0; + + /// write Alignable relative positions (shift,rotation) + virtual void writeAlignableRelativePositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) = 0; + + /// read Alignable relative positions (shift,rotation) + virtual AlignableShifts readAlignableRelativePositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) = 0; }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORoot.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORoot.h index b02a35844d41d..de6695e3cbf28 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORoot.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORoot.h @@ -3,7 +3,7 @@ /// \class AlignmentIORoot /// -/// concrete class for ROOT-based I/O of Alignment parameters, correlations +/// concrete class for ROOT-based I/O of Alignment parameters, correlations /// and Alignable positions. Derived from AlignmentIO /// /// $Date: 2006/11/30 09:56:03 $ @@ -12,56 +12,62 @@ #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentIO.h" - -class AlignmentIORoot : public AlignmentIO -{ - - public: +class AlignmentIORoot : public AlignmentIO { +public: ~AlignmentIORoot() override = default; - /// write AlignmentParameters - void writeAlignmentParameters (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr ) override; + /// write AlignmentParameters + void writeAlignmentParameters( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) override; - /// read AlignmentParameters - align::Parameters readAlignmentParameters (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) override; + /// read AlignmentParameters + align::Parameters readAlignmentParameters(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) override; /// write RigidBodyAlignmentParameters as applied on top of original positions - void writeOrigRigidBodyAlignmentParameters (const align::Alignables& alivec, const char* filename, - int iter, bool validCheck, int& ierr) override; + void writeOrigRigidBodyAlignmentParameters( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) override; + + /// write Correlations + void writeCorrelations( + const align::Correlations& cormap, const char* filename, int iter, bool validCheck, int& ierr) override; + + /// read Correlations + align::Correlations readCorrelations(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) override; + + /// write Alignable current absolute positions + void writeAlignableAbsolutePositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) override; + + /// read Alignable current absolute positions + AlignablePositions readAlignableAbsolutePositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) override; + + /// write Alignable original (before misalignment) absolute positions + void writeAlignableOriginalPositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) override; - /// write Correlations - void writeCorrelations (const align::Correlations& cormap, - const char* filename, int iter, bool validCheck, int& ierr) override; + /// read Alignable original (before misalignment) absolute positions + AlignablePositions readAlignableOriginalPositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) override; - /// read Correlations - align::Correlations readCorrelations (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) override; - - /// write Alignable current absolute positions - void writeAlignableAbsolutePositions (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr) override; - - /// read Alignable current absolute positions - AlignablePositions readAlignableAbsolutePositions (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) override; - - /// write Alignable original (before misalignment) absolute positions - void writeAlignableOriginalPositions (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr) override; - - /// read Alignable original (before misalignment) absolute positions - AlignablePositions readAlignableOriginalPositions (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) override; - - /// write Alignable relative positions (shift,rotation) - void writeAlignableRelativePositions (const align::Alignables& alivec, - const char* filename, int iter, bool validCheck, int& ierr) override; - - /// read Alignable relative positions (shift,rotation) - AlignableShifts readAlignableRelativePositions (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) override; + /// write Alignable relative positions (shift,rotation) + void writeAlignableRelativePositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) override; + /// read Alignable relative positions (shift,rotation) + AlignableShifts readAlignableRelativePositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) override; }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORootBase.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORootBase.h index bae943e33dbb2..687bf0b010faa 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORootBase.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORootBase.h @@ -6,47 +6,45 @@ class TFile; class TTree; -/// Base class for ROOT-based I/O of Alignment parameters etc. +/// Base class for ROOT-based I/O of Alignment parameters etc. -class AlignmentIORootBase -{ - - protected: +class AlignmentIORootBase { +protected: /// constructor AlignmentIORootBase() : tree(nullptr), myFile(nullptr) {} - /// destructor + /// destructor virtual ~AlignmentIORootBase(); - /// open IO + /// open IO int openRoot(const char* filename, int iteration, bool writemode); - /// close IO + /// close IO int closeRoot(void); - /// create root branches + /// create root branches virtual void createBranches(void) = 0; - /// set root branches + /// set root branches virtual void setBranchAddresses(void) = 0; - /// test if file is existing and if so, what the highest iteration is - int testFile(const char* filename, const TString &tname); + /// test if file is existing and if so, what the highest iteration is + int testFile(const char* filename, const TString& tname); - /// compose tree name - TString treeName(int iter, const TString &tname); + /// compose tree name + TString treeName(int iter, const TString& tname); // data members - TTree* tree; // root tree - TString treename; // tree identifier name - TString treetxt; // tree text - bool bWrite; // if true we are writing, else reading + TTree* tree; // root tree + TString treename; // tree identifier name + TString treetxt; // tree text + bool bWrite; // if true we are writing, else reading - const static int nParMax = 20; // maximal number of Parameters - const static int itermax = 1000; // max iteration to test for + const static int nParMax = 20; // maximal number of Parameters + const static int itermax = 1000; // max iteration to test for - private: - TFile* myFile; // root file +private: + TFile* myFile; // root file }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterBuilder.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterBuilder.h index 6f4f8121b0752..fd52e6e3b2db3 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterBuilder.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterBuilder.h @@ -22,32 +22,31 @@ class AlignableMuon; class AlignmentParameters; class TrackerTopology; -class AlignmentParameterBuilder -{ +class AlignmentParameterBuilder { public: /// Constructor from tracker only - explicit AlignmentParameterBuilder( AlignableTracker *alignableTracker, - AlignableExtras *alignableExtras ); + explicit AlignmentParameterBuilder(AlignableTracker *alignableTracker, AlignableExtras *alignableExtras); /// Constructor from tracker and muon - AlignmentParameterBuilder( AlignableTracker *alignableTracker, AlignableMuon *alignableMuon, - AlignableExtras *alignableExtras ); + AlignmentParameterBuilder(AlignableTracker *alignableTracker, + AlignableMuon *alignableMuon, + AlignableExtras *alignableExtras); /// Constructor adding selections by passing the ParameterSet named 'AlignmentParameterSelector' /// (expected in pSet) to addSelections(..) - AlignmentParameterBuilder( AlignableTracker *alignableTracker, - AlignableExtras *alignableExtras, - const edm::ParameterSet &pSet ); + AlignmentParameterBuilder(AlignableTracker *alignableTracker, + AlignableExtras *alignableExtras, + const edm::ParameterSet &pSet); /// Constructor from tracker and muon, plus selection - AlignmentParameterBuilder( AlignableTracker *alignableTracker, AlignableMuon *alignableMuon, - AlignableExtras *alignableExtras, - const edm::ParameterSet &pSet); - - - /// destructor - virtual ~AlignmentParameterBuilder() {}; - /// master initialisation method, PSet must have form as constructor wants it + AlignmentParameterBuilder(AlignableTracker *alignableTracker, + AlignableMuon *alignableMuon, + AlignableExtras *alignableExtras, + const edm::ParameterSet &pSet); + + /// destructor + virtual ~AlignmentParameterBuilder(){}; + /// master initialisation method, PSet must have form as constructor wants it void addAllSelections(const edm::ParameterSet &pSet); /// Add selections of Alignables, using AlignmenParameterSelector::addSelections. @@ -55,48 +54,46 @@ class AlignmentParameterBuilder /// using the selection of active parameters done in AlignmenParameterSelector, /// e.g. for RigidBody a selection string '11100' selects the degrees of freedom in /// (x,y,z), but not (alpha,beta,gamma). - /// Returns number of added selections - unsigned int addSelections(const edm::ParameterSet &pset, - AlignmentParametersFactory::ParametersType parType); + /// Returns number of added selections + unsigned int addSelections(const edm::ParameterSet &pset, AlignmentParametersFactory::ParametersType parType); /// Add arbitrary selection of Alignables, return number of higher level Alignables unsigned int add(const align::Alignables &alignables, - AlignmentParametersFactory::ParametersType parType, - const std::vector &sel); - /// Add a single Alignable, true if it is higher level, false if it is an AlignableDet - bool add(Alignable *alignable, AlignmentParametersFactory::ParametersType parType, - const std::vector &sel); + AlignmentParametersFactory::ParametersType parType, + const std::vector &sel); + /// Add a single Alignable, true if it is higher level, false if it is an AlignableDet + bool add(Alignable *alignable, AlignmentParametersFactory::ParametersType parType, const std::vector &sel); - /// Get list of alignables for which AlignmentParameters are built - const align::Alignables& alignables() const { return theAlignables; }; + /// Get list of alignables for which AlignmentParameters are built + const align::Alignables &alignables() const { return theAlignables; }; - /// Remove n Alignables from list - void fixAlignables( int n ); + /// Remove n Alignables from list + void fixAlignables(int n); - /// Alignable tracker - const AlignableTracker* alignableTracker() const; + /// Alignable tracker + const AlignableTracker *alignableTracker() const; private: /// First remove all spaces (' ') from char selection 'paramSelChar' (coming /// from ParameterSelector) and then convert the selection to bool (for AlignmentParameters). /// True if (after removal of spaces) anything else than 0 and 1 is found in vector. bool decodeParamSel(std::vector ¶mSelChar, std::vector &result) const; - /// add SelectionUserVariables corresponding to fullSel + /// add SelectionUserVariables corresponding to fullSel bool addFullParamSel(AlignmentParameters *aliPar, const std::vector &fullSel) const; // data members - /// Vector of alignables + /// Vector of alignables align::Alignables theAlignables; - /// Alignable tracker - AlignableTracker* theAlignableTracker; + /// Alignable tracker + AlignableTracker *theAlignableTracker; /// Alignable muon - AlignableMuon* theAlignableMuon; - + AlignableMuon *theAlignableMuon; + /// extra Alignables - AlignableExtras* theAlignableExtras; + AlignableExtras *theAlignableExtras; }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterSelector.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterSelector.h index e93f3355fe922..fc7be5bf8ad7c 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterSelector.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterSelector.h @@ -24,18 +24,19 @@ namespace edm { } class AlignmentParameterSelector { - public: +public: /// Constructor from tracker only or from tracker and muon - explicit AlignmentParameterSelector(AlignableTracker *aliTracker, AlignableMuon *aliMuon = nullptr, - AlignableExtras *aliExtras = nullptr); + explicit AlignmentParameterSelector(AlignableTracker *aliTracker, + AlignableMuon *aliMuon = nullptr, + AlignableExtras *aliExtras = nullptr); /// Destructor virtual ~AlignmentParameterSelector() {} /// vector of alignables selected so far - const align::Alignables& selectedAlignables() const { return theSelectedAlignables; } + const align::Alignables &selectedAlignables() const { return theSelectedAlignables; } /// vector of selection 'strings' for alignables, parallel to selectedAlignables() - const std::vector >& selectedParameters() const { return theSelectedParameters; } + const std::vector > &selectedParameters() const { return theSelectedParameters; } /// remove all selected Alignables and geometrical restrictions void clear(); /// remove all geometrical restrictions @@ -58,11 +59,10 @@ class AlignmentParameterSelector { /// as defined in setSpecials, returns number of added alignables unsigned int addSelection(const std::string &name, const std::vector ¶mSel); /// as addSelection with one argument, but overwriting geometrical restrictions - unsigned int addSelection(const std::string &name, const std::vector ¶mSel, - const edm::ParameterSet &pSet); + unsigned int addSelection(const std::string &name, const std::vector ¶mSel, const edm::ParameterSet &pSet); /// true if layer is deselected via "Layers" or "DS/SS" bool layerDeselected(const Alignable *alignable) const; - /// true if alignable is DetUnit deselected by Unit selection + /// true if alignable is DetUnit deselected by Unit selection bool detUnitDeselected(const Alignable *alignable) const; /// true if geometrical restrictions in eta, phi, r, x, y, z not satisfied bool outsideGeometricalRanges(const Alignable *alignable) const; @@ -72,8 +72,8 @@ class AlignmentParameterSelector { /// ( => false if ranges.empty() == true), if(isPhi==true) takes into account phi periodicity /// for the integer specialized method, true is returned for ranges[i] <= value <= ranges[i+1] /// and isPhi is ignored - template bool insideRanges(T value, const std::vector &ranges, - bool isPhi = false) const; + template + bool insideRanges(T value, const std::vector &ranges, bool isPhi = false) const; /// true if value is member of vector of values bool isMemberOfVector(int value, const std::vector &values) const; /// Decomposing input string 's' into parts separated by 'delimiter' @@ -81,8 +81,8 @@ class AlignmentParameterSelector { /// Converting std::string into std::vector std::vector convertParamSel(const std::string &selString) const; - protected: - /// adding alignables which fulfil geometrical restrictions and special switches +protected: + /// adding alignables which fulfil geometrical restrictions and special switches unsigned int add(const align::Alignables &alignables, const std::vector ¶mSel); /// some helper methods unsigned int addAllDets(const std::vector ¶mSel); @@ -97,12 +97,12 @@ class AlignmentParameterSelector { void setTOBDetIdCuts(const edm::ParameterSet &pSet); void setTECDetIdCuts(const edm::ParameterSet &pSet); - const AlignableTracker* alignableTracker() const; - - private: - AlignableTracker* theTracker; - AlignableMuon* theMuon; - AlignableExtras* theExtras; + const AlignableTracker *alignableTracker() const; + +private: + AlignableTracker *theTracker; + AlignableMuon *theMuon; + AlignableExtras *theExtras; align::Alignables theSelectedAlignables; std::vector > theSelectedParameters; @@ -115,81 +115,92 @@ class AlignmentParameterSelector { std::vector theRangesZ; /// DetId restrictions in eta, phi, r, x, y, z to be applied for next addSelection - std::vector theDetIds; - std::vector theDetIdRanges; - std::vector theExcludedDetIds; - std::vector theExcludedDetIdRanges; + std::vector theDetIds; + std::vector theDetIdRanges; + std::vector theExcludedDetIds; + std::vector theExcludedDetIdRanges; struct PXBDetIdRanges { - std::vector theLadderRanges; - std::vector theLayerRanges; - std::vector theModuleRanges; + std::vector theLadderRanges; + std::vector theLayerRanges; + std::vector theModuleRanges; void clear() { - theLadderRanges.clear(); theLayerRanges.clear(); + theLadderRanges.clear(); + theLayerRanges.clear(); theModuleRanges.clear(); } - } thePXBDetIdRanges; + } thePXBDetIdRanges; struct PXFDetIdRanges { - std::vector theBladeRanges; - std::vector theDiskRanges; - std::vector theModuleRanges; - std::vector thePanelRanges; - std::vector theSideRanges; - void clear() { - theBladeRanges.clear(); theDiskRanges.clear(); - theModuleRanges.clear(); thePanelRanges.clear(); + std::vector theBladeRanges; + std::vector theDiskRanges; + std::vector theModuleRanges; + std::vector thePanelRanges; + std::vector theSideRanges; + void clear() { + theBladeRanges.clear(); + theDiskRanges.clear(); + theModuleRanges.clear(); + thePanelRanges.clear(); theSideRanges.clear(); } - } thePXFDetIdRanges; + } thePXFDetIdRanges; struct TIBDetIdRanges { - std::vector theLayerRanges; - std::vector theModuleRanges; - std::vector theStringRanges; - std::vector theSideRanges; - void clear() { - theLayerRanges.clear(); theModuleRanges.clear(); - theSideRanges.clear(); theStringRanges.clear(); + std::vector theLayerRanges; + std::vector theModuleRanges; + std::vector theStringRanges; + std::vector theSideRanges; + void clear() { + theLayerRanges.clear(); + theModuleRanges.clear(); + theSideRanges.clear(); + theStringRanges.clear(); } - } theTIBDetIdRanges; + } theTIBDetIdRanges; struct TIDDetIdRanges { - std::vector theDiskRanges; - std::vector theModuleRanges; - std::vector theRingRanges; - std::vector theSideRanges; - void clear() { - theDiskRanges.clear(); theModuleRanges.clear(); - theRingRanges.clear(); theSideRanges.clear(); + std::vector theDiskRanges; + std::vector theModuleRanges; + std::vector theRingRanges; + std::vector theSideRanges; + void clear() { + theDiskRanges.clear(); + theModuleRanges.clear(); + theRingRanges.clear(); + theSideRanges.clear(); } - } theTIDDetIdRanges; + } theTIDDetIdRanges; struct TOBDetIdRanges { - std::vector theLayerRanges; - std::vector theModuleRanges; - std::vector theRodRanges; - std::vector theSideRanges; - void clear() { - theLayerRanges.clear(); theModuleRanges.clear(); - theRodRanges.clear(); theSideRanges.clear(); + std::vector theLayerRanges; + std::vector theModuleRanges; + std::vector theRodRanges; + std::vector theSideRanges; + void clear() { + theLayerRanges.clear(); + theModuleRanges.clear(); + theRodRanges.clear(); + theSideRanges.clear(); } - } theTOBDetIdRanges; + } theTOBDetIdRanges; struct TECDetIdRanges { - std::vector theWheelRanges; - std::vector thePetalRanges; - std::vector theModuleRanges; - std::vector theRingRanges; - std::vector theSideRanges; - void clear() { - theWheelRanges.clear(); thePetalRanges.clear(); - theModuleRanges.clear(); theRingRanges.clear(); + std::vector theWheelRanges; + std::vector thePetalRanges; + std::vector theModuleRanges; + std::vector theRingRanges; + std::vector theSideRanges; + void clear() { + theWheelRanges.clear(); + thePetalRanges.clear(); + theModuleRanges.clear(); + theRingRanges.clear(); theSideRanges.clear(); } - } theTECDetIdRanges; - + } theTECDetIdRanges; + // further switches used in add(...) bool theOnlyDS; bool theOnlySS; bool theSelLayers; - int theMinLayer; - int theMaxLayer; - enum RphiOrStereoDetUnit { Stereo, Both, Rphi}; + int theMinLayer; + int theMaxLayer; + enum RphiOrStereoDetUnit { Stereo, Both, Rphi }; RphiOrStereoDetUnit theRphiOrStereoDetUnit; /// Setting the special switches and returning input string, but after removing the 'special /// indicators' from it. Known specials are: @@ -199,11 +210,9 @@ class AlignmentParameterSelector { /// "UnitStereo" and "UnitRphi" anywhere in name: /// for a DetUnit in strip select only if stereo or rphi module (keep 'Unit' in name!) std::string setSpecials(const std::string &name); - }; -template<> bool -AlignmentParameterSelector::insideRanges(int value, const std::vector &ranges, - bool isPhi) const; +template <> +bool AlignmentParameterSelector::insideRanges(int value, const std::vector &ranges, bool isPhi) const; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterStore.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterStore.h index cf062caa0d0ff..073c07adda950 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterStore.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterStore.h @@ -6,80 +6,77 @@ #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentCorrelationsStore.h" #include "Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentParameters.h" -/// \class AlignmentParameterStore +/// \class AlignmentParameterStore /// -/// Basic class for management of alignment parameters and correlations +/// Basic class for management of alignment parameters and correlations /// /// $Date: 2011/05/23 20:50:31 $ /// $Revision: 1.19 $ /// (last update by $Author: mussgill $) -namespace edm { class ParameterSet; } +namespace edm { + class ParameterSet; +} class AlignmentUserVariables; class TrackerTopology; -class AlignmentParameterStore -{ - +class AlignmentParameterStore { public: - typedef std::vector Parameters; - typedef std::map< std::pair,AlgebraicMatrix > Correlations; + typedef std::map, AlgebraicMatrix> Correlations; typedef std::vector DetIds; - /// constructor - AlignmentParameterStore( const align::Alignables &alis, const edm::ParameterSet& config ); + /// constructor + AlignmentParameterStore(const align::Alignables& alis, const edm::ParameterSet& config); - /// destructor + /// destructor virtual ~AlignmentParameterStore(); /// select parameters /// (for backward compatibility, use with vector as argument instead) - CompositeAlignmentParameters - selectParameters( const std::vector & alignabledets ) const; - /// select parameters - CompositeAlignmentParameters - selectParameters( const std::vector & alignabledets ) const; - /// select parameters + CompositeAlignmentParameters selectParameters(const std::vector& alignabledets) const; + /// select parameters + CompositeAlignmentParameters selectParameters(const std::vector& alignabledets) const; + /// select parameters CompositeAlignmentParameters selectParameters(const align::Alignables&) const; - /// update parameters + /// update parameters void updateParameters(const CompositeAlignmentParameters& aap, bool updateCorrelations = true); - /// get all alignables + /// get all alignables const align::Alignables& alignables(void) const { return theAlignables; } - /// get all alignables with valid parameters + /// get all alignables with valid parameters align::Alignables validAlignables(void) const; - /// returns number of alignables + /// returns number of alignables int numObjects(void) const { return theAlignables.size(); } - /// get full correlation map - AlignmentCorrelationsStore* correlationsStore( void ) const { return theCorrelationsStore; } + /// get full correlation map + AlignmentCorrelationsStore* correlationsStore(void) const { return theCorrelationsStore; } - /// get number of correlations between alignables - const unsigned int numCorrelations( void ) const { return theCorrelationsStore->size(); } + /// get number of correlations between alignables + const unsigned int numCorrelations(void) const { return theCorrelationsStore->size(); } /// Obsolete: Use AlignableNavigator::alignableDetFromGeomDet and alignableFromAlignableDet -/* Alignable* alignableFromGeomDet( const GeomDet* geomDet ) const; */ + /* Alignable* alignableFromGeomDet( const GeomDet* geomDet ) const; */ /// get Alignable corresponding to given AlignableDet (non-const ref. argument since might be returned) - Alignable* alignableFromAlignableDet( const AlignableDetOrUnitPtr& alignableDet ) const; + Alignable* alignableFromAlignableDet(const AlignableDetOrUnitPtr& alignableDet) const; /// Obsolete: Use AlignableNavigator::alignableDetFromDetId and alignableFromAlignableDet -/* Alignable* alignableFromDetId(const unsigned int& detId) const; */ + /* Alignable* alignableFromDetId(const unsigned int& detId) const; */ - /// apply all valid parameters to their alignables + /// apply all valid parameters to their alignables void applyParameters(void); - /// apply parameters of a given alignable + /// apply parameters of a given alignable void applyParameters(Alignable* alignable); - /// reset parameters, correlations, user variables + /// reset parameters, correlations, user variables void resetParameters(void); - /// reset parameters of a given alignable + /// reset parameters of a given alignable void resetParameters(Alignable* ali); /// cache the current position, rotation and other parameters @@ -94,40 +91,38 @@ class AlignmentParameterStore /// restore for the given run the previously cached position, rotation and other parameters void restoreCachedTransformations(const align::RunNumber&); - /// acquire shifts/rotations from alignables of the store and copy into - /// alignment parameters (local frame) + /// acquire shifts/rotations from alignables of the store and copy into + /// alignment parameters (local frame) void acquireRelativeParameters(void); - /// apply absolute positions to alignables - void applyAlignableAbsolutePositions( const align::Alignables& alis, - const AlignablePositions& newpos, int& ierr ); + /// apply absolute positions to alignables + void applyAlignableAbsolutePositions(const align::Alignables& alis, const AlignablePositions& newpos, int& ierr); - /// apply relative shifts to alignables - void applyAlignableRelativePositions( const align::Alignables& alivec, - const AlignableShifts& shifts, int& ierr ); + /// apply relative shifts to alignables + void applyAlignableRelativePositions(const align::Alignables& alivec, const AlignableShifts& shifts, int& ierr); - /// Attach alignment parameters to given alignables - void attachAlignmentParameters( const align::Alignables& alivec, const Parameters& parvec, int& ierr ); + /// Attach alignment parameters to given alignables + void attachAlignmentParameters(const align::Alignables& alivec, const Parameters& parvec, int& ierr); /// Attach alignment parameters to alignables void attachAlignmentParameters(const Parameters& parvec, int& ierr); - /// Attach correlations to given alignables - void attachCorrelations( const align::Alignables& alivec, const Correlations& cormap, - bool overwrite, int& ierr ); + /// Attach correlations to given alignables + void attachCorrelations(const align::Alignables& alivec, const Correlations& cormap, bool overwrite, int& ierr); /// Attach correlations to alignables - void attachCorrelations( const Correlations& cormap, bool overwrite, int& ierr ); + void attachCorrelations(const Correlations& cormap, bool overwrite, int& ierr); - /// Attach User Variables to given alignables - void attachUserVariables( const align::Alignables& alivec, - const std::vector& uvarvec, int& ierr); + /// Attach User Variables to given alignables + void attachUserVariables(const align::Alignables& alivec, + const std::vector& uvarvec, + int& ierr); - /// Set Alignment position error - void setAlignmentPositionError( const align::Alignables& alivec, double valshift, double valrot ); + /// Set Alignment position error + void setAlignmentPositionError(const align::Alignables& alivec, double valshift, double valrot); - /// Obtain type and layer from Alignable - std::pair typeAndLayer( const Alignable* ali, const TrackerTopology* tTopo ) const; + /// Obtain type and layer from Alignable + std::pair typeAndLayer(const Alignable* ali, const TrackerTopology* tTopo) const; /// a single alignable parameter of an Alignable typedef std::pair ParameterId; @@ -146,13 +141,14 @@ class AlignmentParameterStore /// parameter of aliMaster, but in principle these can be empty... /// Note that not all combinations of AlignmentParameters classes ar supported. /// If not there will be an exception (and false returned...) - bool hierarchyConstraints(const Alignable *aliMaster, const align::Alignables &aliComps, - std::vector > ¶mIdsVecOut, - std::vector > &factorsVecOut, - bool all, double epsilon) const; + bool hierarchyConstraints(const Alignable* aliMaster, + const align::Alignables& aliComps, + std::vector >& paramIdsVecOut, + std::vector >& factorsVecOut, + bool all, + double epsilon) const; protected: - // storage for correlations AlignmentCorrelationsStore* theCorrelationsStore; @@ -161,11 +157,11 @@ class AlignmentParameterStore // data members - /// alignables + /// alignables align::Alignables theAlignables; /// type of constraints - TypeOfConstraints theTypeOfConstraints; + TypeOfConstraints theTypeOfConstraints; }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIO.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIO.h index 86175b5bb2296..0732a12a3a3f0 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIO.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIO.h @@ -5,43 +5,39 @@ /// \class AlignmentParametersIO /// -/// abstract base class for I/O of AlignmentParameters +/// abstract base class for I/O of AlignmentParameters /// /// $Date: 2007/01/23 16:07:08 $ /// $Revision: 1.4 $ /// (last update by $Author: fronga $) -class AlignmentParametersIO -{ +class AlignmentParametersIO { +protected: + virtual ~AlignmentParametersIO(){}; - protected: + /// open IO + virtual int open(const char* filename, int iteration, bool writemode) = 0; - virtual ~AlignmentParametersIO(){}; + /// close IO + virtual int close(void) = 0; - /// open IO - virtual int open(const char* filename, int iteration, bool writemode) =0; - - /// close IO - virtual int close(void) =0; - - /// write AlignmentParameters of one Alignable + /// write AlignmentParameters of one Alignable virtual int writeOne(Alignable* ali) = 0; /// write original RigidBodyAlignmentParameters (i.e. 3 shifts and 3 rotation) virtual int writeOneOrigRigidBody(Alignable* ali); - /// read AlignmentParameters of one Alignable + /// read AlignmentParameters of one Alignable virtual AlignmentParameters* readOne(Alignable* ali, int& ierr) = 0; - /// write AlignmentParameters of many Alignables + /// write AlignmentParameters of many Alignables int write(const align::Alignables& alivec, bool validCheck); - /// write original RigidBodyAlignmentParameters of many Alignables + /// write original RigidBodyAlignmentParameters of many Alignables int writeOrigRigidBody(const align::Alignables& alivec, bool validCheck); - /// read AlignmentParameters of many Alignables + /// read AlignmentParameters of many Alignables align::Parameters read(const align::Alignables& alivec, int& ierr); - }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIORoot.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIORoot.h index ea72c84f5678e..3a84070b539d1 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIORoot.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIORoot.h @@ -3,7 +3,7 @@ /// \class AlignmentParametersIORoot /// -/// Concrete class for ROOT-based I/O of AlignmentParameters +/// Concrete class for ROOT-based I/O of AlignmentParameters /// /// $Date: 2008/09/02 15:31:23 $ /// $Revision: 1.6 $ @@ -13,26 +13,25 @@ #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORootBase.h" #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIO.h" -class AlignmentParametersIORoot : public AlignmentIORootBase, public AlignmentParametersIO -{ +class AlignmentParametersIORoot : public AlignmentIORootBase, public AlignmentParametersIO { friend class AlignmentIORoot; - private: +private: + /// Constructor + AlignmentParametersIORoot(); - /// Constructor - AlignmentParametersIORoot(); - - /// Write AlignmentParameters of one Alignable + /// Write AlignmentParameters of one Alignable int writeOne(Alignable* ali) override; - /// Read AlignmentParameters of one Alignable + /// Read AlignmentParameters of one Alignable AlignmentParameters* readOne(Alignable* ali, int& ierr) override; - /// Open IO - int open(const char* filename, int iteration, bool writemode) override - {return openRoot(filename,iteration,writemode);}; + /// Open IO + int open(const char* filename, int iteration, bool writemode) override { + return openRoot(filename, iteration, writemode); + }; - /// Close IO + /// Close IO int close(void) override; // helper functions @@ -47,13 +46,12 @@ class AlignmentParametersIORoot : public AlignmentIORootBase, public AlignmentPa /// Set branch adresses void setBranchAddresses(void) override; - // Alignment parameter tree + // Alignment parameter tree int theCovRang, theCovarRang, theHieraLevel, theParamType; align::ID theId; align::StructureType theObjId; - double thePar[nParMax],theCov[nParMax*(nParMax+1)/2]; - + double thePar[nParMax], theCov[nParMax * (nParMax + 1) / 2]; }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentUserVariablesIO.h b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentUserVariablesIO.h index ca0c1ea79acc0..822e8a7fb61bd 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/AlignmentUserVariablesIO.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/AlignmentUserVariablesIO.h @@ -14,32 +14,28 @@ class AlignmentUserVariables; -class AlignmentUserVariablesIO -{ - - protected: - +class AlignmentUserVariablesIO { +protected: virtual ~AlignmentUserVariablesIO() {} /** open IO */ - virtual int open(const char* filename, int iteration, bool writemode) =0; + virtual int open(const char* filename, int iteration, bool writemode) = 0; /** close IO */ - virtual int close(void) =0; + virtual int close(void) = 0; /** write AlignmentUserVariables of one Alignable */ - virtual int writeOne(Alignable* ali) =0; + virtual int writeOne(Alignable* ali) = 0; /** read AlignmentUserVariables of one Alignable, object should be created and has to be deleted */ - virtual AlignmentUserVariables* readOne(Alignable* ali, int& ierr) =0; + virtual AlignmentUserVariables* readOne(Alignable* ali, int& ierr) = 0; /** write AlignmentUserVariables of many Alignables */ int write(const align::Alignables& alivec, bool validCheck); /** read AlignmentUserVariables of many Alignables (using readOne, so take care of memory!) */ std::vector read(const align::Alignables& alivec, int& ierr); - }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationBase.h b/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationBase.h index 83c4add89e01b..20b8a61ab0700 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationBase.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationBase.h @@ -19,7 +19,6 @@ * EventSetup and AlignmentAlgorithmBase::EventInfo. */ - #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmBase.h" #include @@ -33,21 +32,22 @@ class AlignableExtras; class TrajectoryStateOnSurface; class TrackingRecHit; -namespace edm { class EventSetup; class ParameterSet; } +namespace edm { + class EventSetup; + class ParameterSet; +} // namespace edm -class IntegratedCalibrationBase -{ +class IntegratedCalibrationBase { public: - typedef AlignmentAlgorithmBase::EventInfo EventInfo; - typedef std::pair Values; /// x- and y-values - typedef std::pair ValuesIndexPair; /// Values and their parameter index + typedef std::pair Values; /// x- and y-values + typedef std::pair ValuesIndexPair; /// Values and their parameter index /// Constructor explicit IntegratedCalibrationBase(const edm::ParameterSet &cfg); - + /// Destructor - virtual ~IntegratedCalibrationBase() {}; + virtual ~IntegratedCalibrationBase(){}; /// How many parameters does this calibration define? virtual unsigned int numParameters() const = 0; @@ -56,19 +56,19 @@ class IntegratedCalibrationBase /// default implementation uses other derivatives(..) method, /// but can be overwritten in derived class for efficiency. virtual std::vector derivatives(const TrackingRecHit &hit, - const TrajectoryStateOnSurface &tsos, - const edm::EventSetup &setup, - const EventInfo &eventInfo) const; + const TrajectoryStateOnSurface &tsos, + const edm::EventSetup &setup, + const EventInfo &eventInfo) const; /// Return non-zero derivatives for x- (ValuesIndexPair.first.first) /// and y-measurement (ValuesIndexPair.first.second) with their /// indices (ValuesIndexPair.second) by reference. /// Return value is their number. virtual unsigned int derivatives(std::vector &outDerivInds, - const TrackingRecHit &hit, - const TrajectoryStateOnSurface &tsos, - const edm::EventSetup &setup, - const EventInfo &eventInfo) const = 0; + const TrackingRecHit &hit, + const TrajectoryStateOnSurface &tsos, + const edm::EventSetup &setup, + const EventInfo &eventInfo) const = 0; /// Setting the determined parameter identified by index, /// should return false if out-of-bounds, true otherwise. @@ -88,23 +88,21 @@ class IntegratedCalibrationBase /// Call at beginning of job: /// default implementation is dummy, to be overwritten in derived class if useful. - virtual void beginOfJob(AlignableTracker *tracker, - AlignableMuon *muon, - AlignableExtras *extras) {}; + virtual void beginOfJob(AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras){}; /// Call at beginning of run: /// default implementation is dummy, to be overwritten in derived class if useful. - virtual void beginRun(const edm::Run&, const edm::EventSetup&) {}; + virtual void beginRun(const edm::Run &, const edm::EventSetup &){}; /// Called at beginning of a loop of the AlignmentProducer, /// to be used for iterative algorithms, default does nothing. /// FIXME: move call to algorithm? - virtual void startNewLoop() {}; + virtual void startNewLoop(){}; /// Called at end of a loop of the AlignmentProducer, /// to be used for iterative algorithms, default does nothing. /// FIXME: move call to algorithm? - virtual void endOfLoop() {}; + virtual void endOfLoop(){}; /// Called at end of a the job of the AlignmentProducer. /// Do here the necessary stuff with the results that should have been passed @@ -125,10 +123,10 @@ class IntegratedCalibrationBase /* virtual void endLuminosityBlock(const edm::EventSetup &setup) {}; */ /// name of this calibration - const std::string& name() const { return name_;} // non-virtual since refering to private member + const std::string &name() const { return name_; } // non-virtual since refering to private member - private: - const std::string name_; /// name of this calibration (i.e. defining plugin) +private: + const std::string name_; /// name of this calibration (i.e. defining plugin) }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h b/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h index babfc740cfd1a..a1b34c9fc732c 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h @@ -13,7 +13,7 @@ #include "FWCore/PluginManager/interface/PluginFactory.h" #include "Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationBase.h" -typedef edmplugin::PluginFactory - IntegratedCalibrationPluginFactory; +typedef edmplugin::PluginFactory + IntegratedCalibrationPluginFactory; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/SelectionUserVariables.h b/Alignment/CommonAlignmentAlgorithm/interface/SelectionUserVariables.h index c351fffe94e9e..61f3f1a112dc2 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/SelectionUserVariables.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/SelectionUserVariables.h @@ -19,17 +19,16 @@ #include -class SelectionUserVariables : public AlignmentUserVariables -{ - public: - explicit SelectionUserVariables(const std::vector &sel) : myFullSelection(sel) {} +class SelectionUserVariables : public AlignmentUserVariables { +public: + explicit SelectionUserVariables(const std::vector& sel) : myFullSelection(sel) {} ~SelectionUserVariables() override {} - SelectionUserVariables* clone() const override { return new SelectionUserVariables(*this);} + SelectionUserVariables* clone() const override { return new SelectionUserVariables(*this); } - const std::vector& fullSelection() const {return myFullSelection;} + const std::vector& fullSelection() const { return myFullSelection; } - private: - std::vector myFullSelection; +private: + std::vector myFullSelection; }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/interface/TkModuleGroupSelector.h b/Alignment/CommonAlignmentAlgorithm/interface/TkModuleGroupSelector.h index ab5b71e71ca0b..cb955a6e410fb 100644 --- a/Alignment/CommonAlignmentAlgorithm/interface/TkModuleGroupSelector.h +++ b/Alignment/CommonAlignmentAlgorithm/interface/TkModuleGroupSelector.h @@ -23,23 +23,24 @@ #include #include - class AlignableTracker; class AlignableMuon; class AlignableExtras; -namespace edm { class EventSetup; class ParameterSet; } +namespace edm { + class EventSetup; + class ParameterSet; +} // namespace edm -class TkModuleGroupSelector -{ +class TkModuleGroupSelector { public: /// Constructor explicit TkModuleGroupSelector(AlignableTracker *aliTracker, const edm::ParameterSet &cfg, const std::vector &sdets); - + /// Destructor - virtual ~TkModuleGroupSelector() {}; + virtual ~TkModuleGroupSelector(){}; // Returns the number of parameters. unsigned int getNumberOfParameters() const; @@ -53,28 +54,27 @@ class TkModuleGroupSelector /// Index of parameter for given detId (detId not treated => < 0) /// and the given run. int getParameterIndexFromDetId(unsigned int detId, edm::RunNumber_t run) const; - - private: + +private: // Constructs the run-dependent module groups from configuration parameters. void createModuleGroups(AlignableTracker *aliTracker, const edm::VParameterSet &granularityConfig, const std::vector &defaultRunRange, edm::RunNumber_t defaultReferenceRun); - + // Method used to test the provided configuration for unknown parameters void verifyParameterNames(const edm::ParameterSet &pset, unsigned int psetnr) const; - + // Method to test whether the split option has been turned on const bool testSplitOption(const edm::ParameterSet &pset) const; // Add modules to a specific group which is also created in this function. - bool createGroup( - unsigned int &Id, //id of the first run - const std::vector &range, //run range - const std::list &selected_alis, //list of alignables for which a group is created - const edm::RunNumber_t refrun //reference run number - ); - + bool createGroup(unsigned int &Id, //id of the first run + const std::vector &range, //run range + const std::list &selected_alis, //list of alignables for which a group is created + const edm::RunNumber_t refrun //reference run number + ); + // Fill the container which is a map between the det id and the id of the group // to which the module belongs. void fillDetIdMap(const unsigned int detid, const unsigned int groupid); @@ -100,7 +100,6 @@ class TkModuleGroupSelector // Reference run per module group std::vector referenceRun_; - }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/ApeSettingAlgorithm.cc b/Alignment/CommonAlignmentAlgorithm/plugins/ApeSettingAlgorithm.cc index 6a2970951c3ad..bc389013223ba 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/ApeSettingAlgorithm.cc +++ b/Alignment/CommonAlignmentAlgorithm/plugins/ApeSettingAlgorithm.cc @@ -1,4 +1,4 @@ - /** +/** * \file MillePedeAlignmentAlgorithm.cc * * \author : Gero Flucke/Ivan Reid @@ -33,7 +33,7 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" -#include "CondFormats/Alignment/interface/AlignmentErrorsExtended.h" +#include "CondFormats/Alignment/interface/AlignmentErrorsExtended.h" #include "DataFormats/GeometrySurface/interface/GloballyPositioned.h" #include "CLHEP/Matrix/SymMatrix.h" @@ -57,9 +57,8 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" -class ApeSettingAlgorithm : public AlignmentAlgorithmBase -{ - public: +class ApeSettingAlgorithm : public AlignmentAlgorithmBase { +public: /// Constructor ApeSettingAlgorithm(const edm::ParameterSet &cfg); @@ -67,23 +66,25 @@ class ApeSettingAlgorithm : public AlignmentAlgorithmBase ~ApeSettingAlgorithm() override; /// Call at beginning of job - void initialize(const edm::EventSetup &setup, - AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, - AlignmentParameterStore *store) override; + void initialize(const edm::EventSetup &setup, + AlignableTracker *tracker, + AlignableMuon *muon, + AlignableExtras *extras, + AlignmentParameterStore *store) override; /// Call at end of job - void terminate(const edm::EventSetup& iSetup) override; + void terminate(const edm::EventSetup &iSetup) override; /// Run the algorithm void run(const edm::EventSetup &setup, const EventInfo &eventInfo) override; - private: - edm::ParameterSet theConfig; - AlignableNavigator *theAlignableNavigator; - AlignableTracker *theTracker; - bool saveApeToAscii_,readApeFromAscii_,readFullLocalMatrix_; - bool readLocalNotGlobal_,saveLocalNotGlobal_; - bool setComposites_,saveComposites_; +private: + edm::ParameterSet theConfig; + AlignableNavigator *theAlignableNavigator; + AlignableTracker *theTracker; + bool saveApeToAscii_, readApeFromAscii_, readFullLocalMatrix_; + bool readLocalNotGlobal_, saveLocalNotGlobal_; + bool setComposites_, saveComposites_; }; //____________________________________________________ @@ -91,14 +92,12 @@ class ApeSettingAlgorithm : public AlignmentAlgorithmBase //____________________________________________________ //____________________________________________________ - // Constructor ---------------------------------------------------------------- //____________________________________________________ -ApeSettingAlgorithm::ApeSettingAlgorithm(const edm::ParameterSet &cfg) : - AlignmentAlgorithmBase(cfg), theConfig(cfg), - theAlignableNavigator(nullptr) -{ - edm::LogInfo("Alignment") << "@SUB=ApeSettingAlgorithm" << "Start."; +ApeSettingAlgorithm::ApeSettingAlgorithm(const edm::ParameterSet &cfg) + : AlignmentAlgorithmBase(cfg), theConfig(cfg), theAlignableNavigator(nullptr) { + edm::LogInfo("Alignment") << "@SUB=ApeSettingAlgorithm" + << "Start."; saveApeToAscii_ = theConfig.getUntrackedParameter("saveApeToASCII"); saveComposites_ = theConfig.getUntrackedParameter("saveComposites"); saveLocalNotGlobal_ = theConfig.getUntrackedParameter("saveLocalNotGlobal"); @@ -106,121 +105,145 @@ ApeSettingAlgorithm::ApeSettingAlgorithm(const edm::ParameterSet &cfg) : readLocalNotGlobal_ = theConfig.getParameter("readLocalNotGlobal"); readFullLocalMatrix_ = theConfig.getParameter("readFullLocalMatrix"); setComposites_ = theConfig.getParameter("setComposites"); - } // Destructor ---------------------------------------------------------------- //____________________________________________________ -ApeSettingAlgorithm::~ApeSettingAlgorithm() -{ - delete theAlignableNavigator; -} +ApeSettingAlgorithm::~ApeSettingAlgorithm() { delete theAlignableNavigator; } // Call at beginning of job --------------------------------------------------- //____________________________________________________ -void ApeSettingAlgorithm::initialize(const edm::EventSetup &setup, - AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras, - AlignmentParameterStore *store) -{ - theAlignableNavigator = new AlignableNavigator(tracker, muon); - theTracker = tracker; - - if (readApeFromAscii_) - { std::ifstream apeReadFile(theConfig.getParameter("apeASCIIReadFile").fullPath().c_str()); //requires - if (!apeReadFile.good()) - { edm::LogInfo("Alignment") << "@SUB=initialize" <<"Problem opening APE file: skipping" - << theConfig.getParameter("apeASCIIReadFile").fullPath(); - return; - } - std::set apeList; //To avoid duplicates - while (!apeReadFile.eof()) - { int apeId=0; double x11,x21,x22,x31,x32,x33,ignore; - if (!readLocalNotGlobal_ || readFullLocalMatrix_) - { apeReadFile>>apeId>>x11>>x21>>x22>>x31>>x32>>x33>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>ignore>>std::ws;} - else - { apeReadFile>>apeId>>x11>>x22>>x33>>std::ws;} - //idr What sanity checks do we need to put here? - if (apeId != 0) //read appears valid? - { if (apeList.find(apeId) == apeList.end()) //Not previously done - { DetId id(apeId); - AlignableDetOrUnitPtr alidet(theAlignableNavigator->alignableFromDetId(id)); //NULL if none - if (alidet) - { if ((alidet->components().empty()) || setComposites_) //the problem with glued dets... - { GlobalErrorExtended globErr; - if (readLocalNotGlobal_) - { AlgebraicSymMatrix33 as; - if (readFullLocalMatrix_) - { as[0][0]=x11; as[1][0]=x21; as[1][1]=x22; - as[2][0]=x31; as[2][1]=x32; as[2][2]=x33; - } - else - { as[0][0]=x11*x11; as[1][1]=x22*x22; as[2][2]=x33*x33;} //local cov. - align::RotationType rt=alidet->globalRotation(); - AlgebraicMatrix33 am; - am[0][0]=rt.xx(); am[0][1]=rt.xy(); am[0][2]=rt.xz(); - am[1][0]=rt.yx(); am[1][1]=rt.yy(); am[1][2]=rt.yz(); - am[2][0]=rt.zx(); am[2][1]=rt.zy(); am[2][2]=rt.zz(); - globErr = GlobalErrorExtended(ROOT::Math::SimilarityT(am,as)); - } - else - { - if (readFullLocalMatrix_) - globErr = GlobalErrorExtended(x11,x21,x31,0,0,0,x22,x32,0,0,0,x33,0,0,0,0,0,0,0,0,0); - else { - globErr = GlobalErrorExtended(x11*x11,0,0,0,0,0,x22*x22,0,0,0,0,x33*x33,0,0,0,0,0,0,0,0,0); - } - } - alidet->setAlignmentPositionError(globErr, false); // do not propagate down! - apeList.insert(apeId); //Flag it's been set - } - else - { edm::LogInfo("Alignment") << "@SUB=initialize" << "Not Setting APE for Composite DetId "<("apeASCIIReadFile").fullPath().c_str()); //requires + if (!apeReadFile.good()) { + edm::LogInfo("Alignment") << "@SUB=initialize" + << "Problem opening APE file: skipping" + << theConfig.getParameter("apeASCIIReadFile").fullPath(); + return; + } + std::set apeList; //To avoid duplicates + while (!apeReadFile.eof()) { + int apeId = 0; + double x11, x21, x22, x31, x32, x33, ignore; + if (!readLocalNotGlobal_ || readFullLocalMatrix_) { + apeReadFile >> apeId >> x11 >> x21 >> x22 >> x31 >> x32 >> x33 >> ignore >> ignore >> ignore >> ignore >> + ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> + ignore >> std::ws; + } else { + apeReadFile >> apeId >> x11 >> x22 >> x33 >> std::ws; + } + //idr What sanity checks do we need to put here? + if (apeId != 0) //read appears valid? + { + if (apeList.find(apeId) == apeList.end()) //Not previously done + { + DetId id(apeId); + AlignableDetOrUnitPtr alidet(theAlignableNavigator->alignableFromDetId(id)); //NULL if none + if (alidet) { + if ((alidet->components().empty()) || setComposites_) //the problem with glued dets... + { + GlobalErrorExtended globErr; + if (readLocalNotGlobal_) { + AlgebraicSymMatrix33 as; + if (readFullLocalMatrix_) { + as[0][0] = x11; + as[1][0] = x21; + as[1][1] = x22; + as[2][0] = x31; + as[2][1] = x32; + as[2][2] = x33; + } else { + as[0][0] = x11 * x11; + as[1][1] = x22 * x22; + as[2][2] = x33 * x33; + } //local cov. + align::RotationType rt = alidet->globalRotation(); + AlgebraicMatrix33 am; + am[0][0] = rt.xx(); + am[0][1] = rt.xy(); + am[0][2] = rt.xz(); + am[1][0] = rt.yx(); + am[1][1] = rt.yy(); + am[1][2] = rt.yz(); + am[2][0] = rt.zx(); + am[2][1] = rt.zy(); + am[2][2] = rt.zz(); + globErr = GlobalErrorExtended(ROOT::Math::SimilarityT(am, as)); + } else { + if (readFullLocalMatrix_) + globErr = + GlobalErrorExtended(x11, x21, x31, 0, 0, 0, x22, x32, 0, 0, 0, x33, 0, 0, 0, 0, 0, 0, 0, 0, 0); + else { + globErr = GlobalErrorExtended( + x11 * x11, 0, 0, 0, 0, 0, x22 * x22, 0, 0, 0, 0, x33 * x33, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + } + alidet->setAlignmentPositionError(globErr, false); // do not propagate down! + apeList.insert(apeId); //Flag it's been set + } else { + edm::LogInfo("Alignment") << "@SUB=initialize" + << "Not Setting APE for Composite DetId " << apeId; + } + } + } else { + edm::LogInfo("Alignment") << "@SUB=initialize" + << "Skipping duplicate APE for DetId " << apeId; + } + } + } + apeReadFile.close(); + edm::LogInfo("Alignment") << "@SUB=initialize" + << "Set " << apeList.size() << " APE values."; + } } - // Call at end of job --------------------------------------------------------- //____________________________________________________ -void ApeSettingAlgorithm::terminate(const edm::EventSetup& iSetup) -{ - if (saveApeToAscii_) - { AlignmentErrorsExtended* aliErr=theTracker->alignmentErrors(); - int theSize=aliErr->m_alignError.size(); - std::ofstream apeSaveFile(theConfig.getUntrackedParameter("apeASCIISaveFile").c_str()); //requires - for (int i=0; i < theSize; ++i) - { int id= aliErr->m_alignError[i].rawId(); - AlignableDetOrUnitPtr alidet(theAlignableNavigator->alignableFromDetId(DetId(id))); //NULL if none - if (alidet && ((alidet->components().empty()) || saveComposites_)) - { apeSaveFile<m_alignError[i].matrix(); - if (saveLocalNotGlobal_) - { align::RotationType rt=alidet->globalRotation(); - AlgebraicMatrix am(3,3); - am[0][0]=rt.xx(); am[0][1]=rt.xy(); am[0][2]=rt.xz(); - am[1][0]=rt.yx(); am[1][1]=rt.yy(); am[1][2]=rt.yz(); - am[2][0]=rt.zx(); am[2][1]=rt.zy(); am[2][2]=rt.zz(); - sm=sm.similarity(am); //symmetric matrix - } //transform to local - for (int j=0; j < sm.num_row(); ++j) - for (int k=0; k <= j; ++k) - apeSaveFile<<" "<alignmentErrors(); + int theSize = aliErr->m_alignError.size(); + std::ofstream apeSaveFile( + theConfig.getUntrackedParameter("apeASCIISaveFile").c_str()); //requires + for (int i = 0; i < theSize; ++i) { + int id = aliErr->m_alignError[i].rawId(); + AlignableDetOrUnitPtr alidet(theAlignableNavigator->alignableFromDetId(DetId(id))); //NULL if none + if (alidet && ((alidet->components().empty()) || saveComposites_)) { + apeSaveFile << id; + CLHEP::HepSymMatrix sm = aliErr->m_alignError[i].matrix(); + if (saveLocalNotGlobal_) { + align::RotationType rt = alidet->globalRotation(); + AlgebraicMatrix am(3, 3); + am[0][0] = rt.xx(); + am[0][1] = rt.xy(); + am[0][2] = rt.xz(); + am[1][0] = rt.yx(); + am[1][1] = rt.yy(); + am[1][2] = rt.yz(); + am[2][0] = rt.zx(); + am[2][1] = rt.zy(); + am[2][2] = rt.zz(); + sm = sm.similarity(am); //symmetric matrix + } //transform to local + for (int j = 0; j < sm.num_row(); ++j) + for (int k = 0; k <= j; ++k) + apeSaveFile << " " << sm[j][k]; //always write full matrix + + apeSaveFile << std::endl; } + } delete aliErr; apeSaveFile.close(); - } + } // clean up at end: // FIXME: should we delete here or in destructor? delete theAlignableNavigator; theAlignableNavigator = nullptr; @@ -228,11 +251,9 @@ void ApeSettingAlgorithm::terminate(const edm::EventSetup& iSetup) // Run the algorithm on trajectories and tracks ------------------------------- //____________________________________________________ -void ApeSettingAlgorithm::run(const edm::EventSetup &setup, const EventInfo &eventInfo) -{ +void ApeSettingAlgorithm::run(const edm::EventSetup &setup, const EventInfo &eventInfo) { // nothing to do here? } // Plugin definition for the algorithm -DEFINE_EDM_PLUGIN(AlignmentAlgorithmPluginFactory, - ApeSettingAlgorithm, "ApeSettingAlgorithm"); +DEFINE_EDM_PLUGIN(AlignmentAlgorithmPluginFactory, ApeSettingAlgorithm, "ApeSettingAlgorithm"); diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/SiPixelLorentzAngleCalibration.cc b/Alignment/CommonAlignmentAlgorithm/plugins/SiPixelLorentzAngleCalibration.cc index a978ff71d11c8..2b42e4ef29db2 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/SiPixelLorentzAngleCalibration.cc +++ b/Alignment/CommonAlignmentAlgorithm/plugins/SiPixelLorentzAngleCalibration.cc @@ -51,8 +51,7 @@ #include #include -class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase -{ +class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase { public: /// Constructor explicit SiPixelLorentzAngleCalibration(const edm::ParameterSet &cfg); @@ -88,12 +87,10 @@ class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase double getParameterError(unsigned int index) const override; /// Call at beginning of job: - void beginOfJob(AlignableTracker *tracker, - AlignableMuon *muon, - AlignableExtras *extras) override; + void beginOfJob(AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras) override; /// Call at beginning of run: - void beginRun(const edm::Run&, const edm::EventSetup&) override; + void beginRun(const edm::Run &, const edm::EventSetup &) override; /// Called at end of a the job of the AlignmentProducer. /// Write out determined parameters. @@ -103,14 +100,14 @@ class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase /// Input LorentzAngle values: /// - either from EventSetup of first call to derivatives(..) /// - or created from files of passed by configuration (i.e. from parallel processing) - const SiPixelLorentzAngle* getLorentzAnglesInput(const align::RunNumber& = 0); + const SiPixelLorentzAngle *getLorentzAnglesInput(const align::RunNumber & = 0); /// Determined parameter value for this detId (detId not treated => 0.) /// and the given run. double getParameterForDetId(unsigned int detId, edm::RunNumber_t run) const; void writeTree(const SiPixelLorentzAngle *lorentzAngle, - const std::map& treeInfo, + const std::map &treeInfo, const char *treeName) const; SiPixelLorentzAngle createFromTree(const char *fileName, const char *treeName) const; @@ -124,7 +121,7 @@ class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase // const AlignableTracker *alignableTracker_; std::map cachedLorentzAngleInputs_; - SiPixelLorentzAngle* siPixelLorentzAngleInput_{nullptr}; + SiPixelLorentzAngle *siPixelLorentzAngleInput_{nullptr}; align::RunNumber currentIOV_{0}; std::vector parameters_; std::vector paramUncertainties_; @@ -138,37 +135,29 @@ class SiPixelLorentzAngleCalibration : public IntegratedCalibrationBase //====================================================================== SiPixelLorentzAngleCalibration::SiPixelLorentzAngleCalibration(const edm::ParameterSet &cfg) - : IntegratedCalibrationBase(cfg), - saveToDB_(cfg.getParameter("saveToDB")), - recordNameDBwrite_(cfg.getParameter("recordNameDBwrite")), - outFileName_(cfg.getParameter("treeFile")), - mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), - lorentzAngleLabel_(cfg.getParameter("lorentzAngleLabel")), - moduleGroupSelCfg_(cfg.getParameter("LorentzAngleModuleGroups")) -{ - -} + : IntegratedCalibrationBase(cfg), + saveToDB_(cfg.getParameter("saveToDB")), + recordNameDBwrite_(cfg.getParameter("recordNameDBwrite")), + outFileName_(cfg.getParameter("treeFile")), + mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), + lorentzAngleLabel_(cfg.getParameter("lorentzAngleLabel")), + moduleGroupSelCfg_(cfg.getParameter("LorentzAngleModuleGroups")) {} //====================================================================== -unsigned int SiPixelLorentzAngleCalibration::numParameters() const -{ - return parameters_.size(); -} +unsigned int SiPixelLorentzAngleCalibration::numParameters() const { return parameters_.size(); } //====================================================================== -void -SiPixelLorentzAngleCalibration::beginRun(const edm::Run& run, - const edm::EventSetup& setup) { - +void SiPixelLorentzAngleCalibration::beginRun(const edm::Run &run, const edm::EventSetup &setup) { // no action needed if the LA record didn't change - if (!(watchLorentzAngleRcd_.check(setup))) return; + if (!(watchLorentzAngleRcd_.check(setup))) + return; const auto runNumber = run.run(); auto firstRun = cond::timeTypeSpecs[cond::runnumber].beginValue; // avoid infinite loop due to wrap-around of unsigned variable 'i' including // arrow from i to zero and a nice smiley ;) - for (unsigned int i = moduleGroupSelector_->numIovs(); i-->0 ;) { + for (unsigned int i = moduleGroupSelector_->numIovs(); i-- > 0;) { const auto firstRunOfIOV = moduleGroupSelector_->firstRunOfIOV(i); if (runNumber >= firstRunOfIOV) { firstRun = firstRunOfIOV; @@ -177,24 +166,22 @@ SiPixelLorentzAngleCalibration::beginRun(const edm::Run& run, } edm::ESHandle lorentzAngleHandle; - const auto& lorentzAngleRcd = setup.get(); + const auto &lorentzAngleRcd = setup.get(); lorentzAngleRcd.get(lorentzAngleLabel_, lorentzAngleHandle); if (cachedLorentzAngleInputs_.find(firstRun) == cachedLorentzAngleInputs_.end()) { cachedLorentzAngleInputs_.emplace(firstRun, SiPixelLorentzAngle(*lorentzAngleHandle)); } else { if (lorentzAngleRcd.validityInterval().first().eventID().run() > firstRun && - lorentzAngleHandle->getLorentzAngles() // only bad if non-identical values - != cachedLorentzAngleInputs_[firstRun].getLorentzAngles()) { // (comparing maps) + lorentzAngleHandle->getLorentzAngles() // only bad if non-identical values + != cachedLorentzAngleInputs_[firstRun].getLorentzAngles()) { // (comparing maps) // Maps are containers sorted by key, but comparison problems may arise from // 'floating point comparison' problems (FIXME?) - throw cms::Exception("BadInput") - << "Trying to cache SiPixelLorentzAngle payload for a run (" << runNumber - << ") in an IOV (" << firstRun << ") that was already cached.\n" - << "The following record in your input database tag has an IOV " - << "boundary that does not match your IOV definition:\n" - << " - SiPixelLorentzAngleRcd '" << lorentzAngleRcd.key().name() - << "' (since " - << lorentzAngleRcd.validityInterval().first().eventID().run() << ")\n"; + throw cms::Exception("BadInput") << "Trying to cache SiPixelLorentzAngle payload for a run (" << runNumber + << ") in an IOV (" << firstRun << ") that was already cached.\n" + << "The following record in your input database tag has an IOV " + << "boundary that does not match your IOV definition:\n" + << " - SiPixelLorentzAngleRcd '" << lorentzAngleRcd.key().name() << "' (since " + << lorentzAngleRcd.validityInterval().first().eventID().run() << ")\n"; } } @@ -203,31 +190,29 @@ SiPixelLorentzAngleCalibration::beginRun(const edm::Run& run, } //====================================================================== -unsigned int -SiPixelLorentzAngleCalibration::derivatives(std::vector &outDerivInds, - const TransientTrackingRecHit &hit, - const TrajectoryStateOnSurface &tsos, - const edm::EventSetup &setup, - const EventInfo &eventInfo) const -{ +unsigned int SiPixelLorentzAngleCalibration::derivatives(std::vector &outDerivInds, + const TransientTrackingRecHit &hit, + const TrajectoryStateOnSurface &tsos, + const edm::EventSetup &setup, + const EventInfo &eventInfo) const { outDerivInds.clear(); - if (hit.det()) { // otherwise 'constraint hit' or whatever + if (hit.det()) { // otherwise 'constraint hit' or whatever - const int index = moduleGroupSelector_->getParameterIndexFromDetId(hit.det()->geographicalId(), - eventInfo.eventId().run()); - if (index >= 0) { // otherwise not treated + const int index = + moduleGroupSelector_->getParameterIndexFromDetId(hit.det()->geographicalId(), eventInfo.eventId().run()); + if (index >= 0) { // otherwise not treated edm::ESHandle magneticField; setup.get().get(magneticField); const GlobalVector bField(magneticField->inTesla(hit.det()->surface().position())); const LocalVector bFieldLocal(hit.det()->surface().toLocal(bField)); - const double dZ = hit.det()->surface().bounds().thickness(); // it is a float only... + const double dZ = hit.det()->surface().bounds().thickness(); // it is a float only... // shift due to LA: dx = tan(LA) * dz/2 = mobility * B_y * dz/2, // shift due to LA: dy = - mobility * B_x * dz/2, // '-' since we have derivative of the residual r = trk -hit - const double xDerivative = bFieldLocal.y() * dZ * -0.5; // parameter is mobility! - const double yDerivative = bFieldLocal.x() * dZ * 0.5; // parameter is mobility! - if (xDerivative || yDerivative) { // If field is zero, this is zero: do not return it + const double xDerivative = bFieldLocal.y() * dZ * -0.5; // parameter is mobility! + const double yDerivative = bFieldLocal.x() * dZ * 0.5; // parameter is mobility! + if (xDerivative || yDerivative) { // If field is zero, this is zero: do not return it const Values derivs{xDerivative, yDerivative}; outDerivInds.push_back(ValuesIndexPair(derivs, index)); } @@ -241,8 +226,7 @@ SiPixelLorentzAngleCalibration::derivatives(std::vector &outDer } //====================================================================== -bool SiPixelLorentzAngleCalibration::setParameter(unsigned int index, double value) -{ +bool SiPixelLorentzAngleCalibration::setParameter(unsigned int index, double value) { if (index >= parameters_.size()) { return false; } else { @@ -252,8 +236,7 @@ bool SiPixelLorentzAngleCalibration::setParameter(unsigned int index, double val } //====================================================================== -bool SiPixelLorentzAngleCalibration::setParameterError(unsigned int index, double error) -{ +bool SiPixelLorentzAngleCalibration::setParameterError(unsigned int index, double error) { if (index >= paramUncertainties_.size()) { return false; } else { @@ -263,38 +246,31 @@ bool SiPixelLorentzAngleCalibration::setParameterError(unsigned int index, doubl } //====================================================================== -double SiPixelLorentzAngleCalibration::getParameter(unsigned int index) const -{ +double SiPixelLorentzAngleCalibration::getParameter(unsigned int index) const { return (index >= parameters_.size() ? 0. : parameters_[index]); } //====================================================================== -double SiPixelLorentzAngleCalibration::getParameterError(unsigned int index) const -{ +double SiPixelLorentzAngleCalibration::getParameterError(unsigned int index) const { return (index >= paramUncertainties_.size() ? 0. : paramUncertainties_[index]); } - - - //====================================================================== void SiPixelLorentzAngleCalibration::beginOfJob(AlignableTracker *aliTracker, AlignableMuon * /*aliMuon*/, - AlignableExtras * /*aliExtras*/) -{ + AlignableExtras * /*aliExtras*/) { //specify the sub-detectors for which the LA is determined const std::vector sdets = {PixelSubdetector::PixelBarrel, PixelSubdetector::PixelEndcap}; - moduleGroupSelector_ = - std::make_unique(aliTracker, moduleGroupSelCfg_, sdets); + moduleGroupSelector_ = std::make_unique(aliTracker, moduleGroupSelCfg_, sdets); parameters_.resize(moduleGroupSelector_->getNumberOfParameters(), 0.); paramUncertainties_.resize(moduleGroupSelector_->getNumberOfParameters(), 0.); - edm::LogInfo("Alignment") << "@SUB=SiPixelLorentzAngleCalibration" << "Created with name " - << this->name() << "',\n" << this->numParameters() << " parameters to be determined," - << "\n saveToDB = " << saveToDB_ - << "\n outFileName = " << outFileName_ + edm::LogInfo("Alignment") << "@SUB=SiPixelLorentzAngleCalibration" + << "Created with name " << this->name() << "',\n" + << this->numParameters() << " parameters to be determined," + << "\n saveToDB = " << saveToDB_ << "\n outFileName = " << outFileName_ << "\n N(merge files) = " << mergeFileNames_.size() << "\n number of IOVs = " << moduleGroupSelector_->numIovs(); @@ -304,10 +280,8 @@ void SiPixelLorentzAngleCalibration::beginOfJob(AlignableTracker *aliTracker, } } - //====================================================================== -void SiPixelLorentzAngleCalibration::endOfJob() -{ +void SiPixelLorentzAngleCalibration::endOfJob() { // loginfo output std::ostringstream out; out << "Parameter results\n"; @@ -316,17 +290,18 @@ void SiPixelLorentzAngleCalibration::endOfJob() } edm::LogInfo("Alignment") << "@SUB=SiPixelLorentzAngleCalibration::endOfJob" << out.str(); - std::map treeInfo; // map of TreeStruct for each detId + std::map treeInfo; // map of TreeStruct for each detId // now write 'input' tree(s) const std::string treeName{this->name() + '_'}; - std::vector inputs{}; + std::vector inputs{}; inputs.reserve(moduleGroupSelector_->numIovs()); for (unsigned int iIOV = 0; iIOV < moduleGroupSelector_->numIovs(); ++iIOV) { const auto firstRunOfIOV = moduleGroupSelector_->firstRunOfIOV(iIOV); - inputs.push_back(this->getLorentzAnglesInput(firstRunOfIOV)); // never NULL - this->writeTree(inputs.back(), treeInfo, - (treeName + "input_" + std::to_string(firstRunOfIOV)).c_str()); // empty treeInfo for input... + inputs.push_back(this->getLorentzAnglesInput(firstRunOfIOV)); // never NULL + this->writeTree(inputs.back(), + treeInfo, + (treeName + "input_" + std::to_string(firstRunOfIOV)).c_str()); // empty treeInfo for input... if (inputs.back()->getLorentzAngles().empty()) { edm::LogError("Alignment") << "@SUB=SiPixelLorentzAngleCalibration::endOfJob" @@ -335,32 +310,31 @@ void SiPixelLorentzAngleCalibration::endOfJob() } } - const unsigned int nonZeroParamsOrErrors = // Any determined value? - count_if (parameters_.begin(), parameters_.end(), [] (auto c) { return c != 0.;}) - + count_if(paramUncertainties_.begin(), paramUncertainties_.end(), - [](auto c) { return c != 0.;}); + const unsigned int nonZeroParamsOrErrors = // Any determined value? + count_if(parameters_.begin(), parameters_.end(), [](auto c) { return c != 0.; }) + + count_if(paramUncertainties_.begin(), paramUncertainties_.end(), [](auto c) { return c != 0.; }); for (unsigned int iIOV = 0; iIOV < moduleGroupSelector_->numIovs(); ++iIOV) { auto firstRunOfIOV = static_cast(moduleGroupSelector_->firstRunOfIOV(iIOV)); SiPixelLorentzAngle output{}; // Loop on map of values from input and add (possible) parameter results - for (const auto& iterIdValue: inputs[iIOV]->getLorentzAngles()) { + for (const auto &iterIdValue : inputs[iIOV]->getLorentzAngles()) { // type of 'iterIdValue' is pair - const auto detId = iterIdValue.first; // key of map is DetId + const auto detId = iterIdValue.first; // key of map is DetId const auto param = this->getParameterForDetId(detId, firstRunOfIOV); // put result in output, i.e. sum of input and determined parameter, but the nasty // putLorentzAngle(..) takes float by reference - not even const reference: auto value = iterIdValue.second + static_cast(param); output.putLorentzAngle(detId, value); - const int paramIndex = moduleGroupSelector_->getParameterIndexFromDetId(detId,firstRunOfIOV); + const int paramIndex = moduleGroupSelector_->getParameterIndexFromDetId(detId, firstRunOfIOV); treeInfo[detId] = TreeStruct(param, this->getParameterError(paramIndex), paramIndex); } - if (saveToDB_ || nonZeroParamsOrErrors != 0) { // Skip writing mille jobs... + if (saveToDB_ || nonZeroParamsOrErrors != 0) { // Skip writing mille jobs... this->writeTree(&output, treeInfo, (treeName + Form("result_%lld", firstRunOfIOV)).c_str()); } - if (saveToDB_) { // If requested, write out to DB + if (saveToDB_) { // If requested, write out to DB edm::Service dbService; if (dbService.isAvailable()) { dbService->writeOne(&output, firstRunOfIOV, recordNameDBwrite_); @@ -369,21 +343,18 @@ void SiPixelLorentzAngleCalibration::endOfJob() << "No PoolDBOutputService available, but saveToDB true!"; } } - } // end loop on IOVs - + } // end loop on IOVs } //====================================================================== -const SiPixelLorentzAngle* -SiPixelLorentzAngleCalibration::getLorentzAnglesInput(const align::RunNumber& run) -{ - const auto& resolvedRun = run > 0 ? run : currentIOV_; +const SiPixelLorentzAngle *SiPixelLorentzAngleCalibration::getLorentzAnglesInput(const align::RunNumber &run) { + const auto &resolvedRun = run > 0 ? run : currentIOV_; // For parallel processing in Millepede II, create SiPixelLorentzAngle // from info stored in files of parallel jobs and check that they are identical. // If this job has run on data, still check that LA is identical to the ones // from mergeFileNames_. - const std::string treeName{this->name()+"_input_"+std::to_string(resolvedRun)}; - for (const auto& iFile: mergeFileNames_) { + const std::string treeName{this->name() + "_input_" + std::to_string(resolvedRun)}; + for (const auto &iFile : mergeFileNames_) { auto la = this->createFromTree(iFile.c_str(), treeName.c_str()); // siPixelLorentzAngleInput_ could be non-null from previous file of this loop // or from checkLorentzAngleInput(..) when running on data in this job as well @@ -393,18 +364,16 @@ SiPixelLorentzAngleCalibration::getLorentzAnglesInput(const align::RunNumber& ru currentIOV_ = resolvedRun; } else { // FIXME: about comparison of maps see comments in checkLorentzAngleInput - if (!la.getLorentzAngles().empty() && // single job might not have got events + if (!la.getLorentzAngles().empty() && // single job might not have got events la.getLorentzAngles() != siPixelLorentzAngleInput_->getLorentzAngles()) { // Throw exception instead of error? edm::LogError("NoInput") << "@SUB=SiPixelLorentzAngleCalibration::getLorentzAnglesInput" - << "Different input values from tree " << treeName - << " in file " << iFile << "."; - + << "Different input values from tree " << treeName << " in file " << iFile << "."; } } } - if (!siPixelLorentzAngleInput_) { // no files nor ran on events + if (!siPixelLorentzAngleInput_) { // no files nor ran on events // [] operator default-constructs an empty SiPixelLorentzAngle object in place: siPixelLorentzAngleInput_ = &(cachedLorentzAngleInputs_[resolvedRun]); currentIOV_ = resolvedRun; @@ -419,21 +388,19 @@ SiPixelLorentzAngleCalibration::getLorentzAnglesInput(const align::RunNumber& ru } //====================================================================== -double SiPixelLorentzAngleCalibration::getParameterForDetId(unsigned int detId, - edm::RunNumber_t run) const -{ +double SiPixelLorentzAngleCalibration::getParameterForDetId(unsigned int detId, edm::RunNumber_t run) const { const int index = moduleGroupSelector_->getParameterIndexFromDetId(detId, run); return (index < 0 ? 0. : parameters_[index]); } //====================================================================== void SiPixelLorentzAngleCalibration::writeTree(const SiPixelLorentzAngle *lorentzAngle, - const std::map &treeInfo, - const char *treeName) const -{ - if (!lorentzAngle) return; + const std::map &treeInfo, + const char *treeName) const { + if (!lorentzAngle) + return; - TFile* file = TFile::Open(outFileName_.c_str(), "UPDATE"); + TFile *file = TFile::Open(outFileName_.c_str(), "UPDATE"); if (!file) { edm::LogError("BadConfig") << "@SUB=SiPixelLorentzAngleCalibration::writeTree" << "Could not open file '" << outFileName_ << "'."; @@ -449,15 +416,16 @@ void SiPixelLorentzAngleCalibration::writeTree(const SiPixelLorentzAngle *lorent tree->Branch("treeStruct", &treeStruct, TreeStruct::LeafList()); for (auto iterIdValue = lorentzAngle->getLorentzAngles().begin(); - iterIdValue != lorentzAngle->getLorentzAngles().end(); ++iterIdValue) { + iterIdValue != lorentzAngle->getLorentzAngles().end(); + ++iterIdValue) { // type of (*iterIdValue) is pair - id = iterIdValue->first; // key of map is DetId + id = iterIdValue->first; // key of map is DetId value = iterIdValue->second; // type of (*treeStructIter) is pair - auto treeStructIter = treeInfo.find(id); // find info for this id + auto treeStructIter = treeInfo.find(id); // find info for this id if (treeStructIter != treeInfo.end()) { - treeStruct = treeStructIter->second; // info from input map - } else { // if none found, fill at least parameter index (using 1st IOV...) + treeStruct = treeStructIter->second; // info from input map + } else { // if none found, fill at least parameter index (using 1st IOV...) const cond::Time_t run1of1stIov = moduleGroupSelector_->firstRunOfIOV(0); const int ind = moduleGroupSelector_->getParameterIndexFromDetId(id, run1of1stIov); treeStruct = TreeStruct(ind); @@ -465,25 +433,23 @@ void SiPixelLorentzAngleCalibration::writeTree(const SiPixelLorentzAngle *lorent tree->Fill(); } tree->Write(); - delete file; // tree vanishes with the file... (?) - + delete file; // tree vanishes with the file... (?) } //====================================================================== -SiPixelLorentzAngle -SiPixelLorentzAngleCalibration::createFromTree(const char *fileName, const char *treeName) const -{ +SiPixelLorentzAngle SiPixelLorentzAngleCalibration::createFromTree(const char *fileName, const char *treeName) const { // Check for file existence on your own to work around // https://hypernews.cern.ch/HyperNews/CMS/get/swDevelopment/2715.html: - TFile* file = nullptr; - FILE* testFile = fopen(fileName,"r"); + TFile *file = nullptr; + FILE *testFile = fopen(fileName, "r"); if (testFile) { fclose(testFile); file = TFile::Open(fileName, "READ"); - } // else not existing, see error below + } // else not existing, see error below TTree *tree = nullptr; - if (file) file->GetObject(treeName, tree); + if (file) + file->GetObject(treeName, tree); SiPixelLorentzAngle result{}; if (tree) { @@ -497,22 +463,20 @@ SiPixelLorentzAngleCalibration::createFromTree(const char *fileName, const char tree->GetEntry(iEntry); result.putLorentzAngle(id, value); } - } else { // Warning only since could be parallel job on no events. + } else { // Warning only since could be parallel job on no events. edm::LogWarning("Alignment") << "@SUB=SiPixelLorentzAngleCalibration::createFromTree" - << "Could not get TTree '" << treeName << "' from file '" - << fileName << (file ? "'." : "' (file does not exist)."); + << "Could not get TTree '" << treeName << "' from file '" << fileName + << (file ? "'." : "' (file does not exist)."); } - delete file; // tree will vanish with file + delete file; // tree will vanish with file return result; } - //====================================================================== //====================================================================== // Plugin definition #include "Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h" -DEFINE_EDM_PLUGIN(IntegratedCalibrationPluginFactory, - SiPixelLorentzAngleCalibration, "SiPixelLorentzAngleCalibration"); +DEFINE_EDM_PLUGIN(IntegratedCalibrationPluginFactory, SiPixelLorentzAngleCalibration, "SiPixelLorentzAngleCalibration"); diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripBackplaneCalibration.cc b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripBackplaneCalibration.cc index 36c2a75c9b47f..4057ad2d608b7 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripBackplaneCalibration.cc +++ b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripBackplaneCalibration.cc @@ -52,12 +52,11 @@ #include #include -class SiStripBackplaneCalibration : public IntegratedCalibrationBase -{ +class SiStripBackplaneCalibration : public IntegratedCalibrationBase { public: /// Constructor explicit SiStripBackplaneCalibration(const edm::ParameterSet &cfg); - + /// Destructor ~SiStripBackplaneCalibration() override; @@ -75,10 +74,10 @@ class SiStripBackplaneCalibration : public IntegratedCalibrationBase /// Return non-zero derivatives for x- and y-measurements with their indices by reference. /// Return value is their number. unsigned int derivatives(std::vector &outDerivInds, - const TransientTrackingRecHit &hit, - const TrajectoryStateOnSurface &tsos, - const edm::EventSetup &setup, - const EventInfo &eventInfo) const override; + const TransientTrackingRecHit &hit, + const TrajectoryStateOnSurface &tsos, + const edm::EventSetup &setup, + const EventInfo &eventInfo) const override; /// Setting the determined parameter identified by index, /// returns false if out-of-bounds, true otherwise. @@ -97,9 +96,7 @@ class SiStripBackplaneCalibration : public IntegratedCalibrationBase double getParameterError(unsigned int index) const override; // /// Call at beginning of job: - void beginOfJob(AlignableTracker *tracker, - AlignableMuon *muon, - AlignableExtras *extras) override; + void beginOfJob(AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras) override; /// Called at end of a the job of the AlignmentProducer. /// Write out determined parameters. @@ -112,15 +109,16 @@ class SiStripBackplaneCalibration : public IntegratedCalibrationBase /// Input BackPlaneCorrection values: /// - either from EventSetup of first call to derivatives(..) /// - or created from files of passed by configuration (i.e. from parallel processing) - const SiStripBackPlaneCorrection* getBackPlaneCorrectionInput(); + const SiStripBackPlaneCorrection *getBackPlaneCorrectionInput(); /// Determined parameter value for this detId (detId not treated => 0.) /// and the given run. double getParameterForDetId(unsigned int detId, edm::RunNumber_t run) const; void writeTree(const SiStripBackPlaneCorrection *backPlaneCorr, - const std::map &treeInfo, const char *treeName) const; - SiStripBackPlaneCorrection* createFromTree(const char *fileName, const char *treeName) const; + const std::map &treeInfo, + const char *treeName) const; + SiStripBackPlaneCorrection *createFromTree(const char *fileName, const char *treeName) const; const std::string readoutModeName_; int16_t readoutMode_; @@ -138,7 +136,6 @@ class SiStripBackplaneCalibration : public IntegratedCalibrationBase TkModuleGroupSelector *moduleGroupSelector_; const edm::ParameterSet moduleGroupSelCfg_; - }; //====================================================================== @@ -146,17 +143,15 @@ class SiStripBackplaneCalibration : public IntegratedCalibrationBase //====================================================================== SiStripBackplaneCalibration::SiStripBackplaneCalibration(const edm::ParameterSet &cfg) - : IntegratedCalibrationBase(cfg), - readoutModeName_(cfg.getParameter("readoutMode")), - saveToDB_(cfg.getParameter("saveToDB")), - recordNameDBwrite_(cfg.getParameter("recordNameDBwrite")), - outFileName_(cfg.getParameter("treeFile")), - mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), - siStripBackPlaneCorrInput_(nullptr), - moduleGroupSelector_(nullptr), - moduleGroupSelCfg_(cfg.getParameter("BackplaneModuleGroups")) -{ - + : IntegratedCalibrationBase(cfg), + readoutModeName_(cfg.getParameter("readoutMode")), + saveToDB_(cfg.getParameter("saveToDB")), + recordNameDBwrite_(cfg.getParameter("recordNameDBwrite")), + outFileName_(cfg.getParameter("treeFile")), + mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), + siStripBackPlaneCorrInput_(nullptr), + moduleGroupSelector_(nullptr), + moduleGroupSelCfg_(cfg.getParameter("BackplaneModuleGroups")) { // SiStripLatency::singleReadOutMode() returns // 1: all in peak, 0: all in deco, -1: mixed state // (in principle one could treat even mixed state APV by APV...) @@ -165,101 +160,93 @@ SiStripBackplaneCalibration::SiStripBackplaneCalibration(const edm::ParameterSet } else if (readoutModeName_ == "deconvolution") { readoutMode_ = kDeconvolutionMode; } else { - throw cms::Exception("BadConfig") - << "SiStripBackplaneCalibration:\n" << "Unknown mode '" - << readoutModeName_ << "', should be 'peak' or 'deconvolution' .\n"; + throw cms::Exception("BadConfig") << "SiStripBackplaneCalibration:\n" + << "Unknown mode '" << readoutModeName_ + << "', should be 'peak' or 'deconvolution' .\n"; } - } - + //====================================================================== -SiStripBackplaneCalibration::~SiStripBackplaneCalibration() -{ +SiStripBackplaneCalibration::~SiStripBackplaneCalibration() { delete moduleGroupSelector_; // std::cout << "Destroy SiStripBackplaneCalibration named " << this->name() << std::endl; delete siStripBackPlaneCorrInput_; } //====================================================================== -unsigned int SiStripBackplaneCalibration::numParameters() const -{ - return parameters_.size(); -} +unsigned int SiStripBackplaneCalibration::numParameters() const { return parameters_.size(); } //====================================================================== -unsigned int -SiStripBackplaneCalibration::derivatives(std::vector &outDerivInds, - const TransientTrackingRecHit &hit, - const TrajectoryStateOnSurface &tsos, - const edm::EventSetup &setup, - const EventInfo &eventInfo) const -{ +unsigned int SiStripBackplaneCalibration::derivatives(std::vector &outDerivInds, + const TransientTrackingRecHit &hit, + const TrajectoryStateOnSurface &tsos, + const edm::EventSetup &setup, + const EventInfo &eventInfo) const { // ugly const-cast: // But it is either only first initialisation or throwing an exception... - const_cast(this)->checkBackPlaneCorrectionInput(setup, eventInfo); + const_cast(this)->checkBackPlaneCorrectionInput(setup, eventInfo); outDerivInds.clear(); - edm::ESHandle latency; + edm::ESHandle latency; setup.get().get(latency); const int16_t mode = latency->singleReadOutMode(); - if(mode == readoutMode_) { - if (hit.det()) { // otherwise 'constraint hit' or whatever - - const int index = moduleGroupSelector_->getParameterIndexFromDetId(hit.det()->geographicalId(), - eventInfo.eventId().run()); - if (index >= 0) { // otherwise not treated + if (mode == readoutMode_) { + if (hit.det()) { // otherwise 'constraint hit' or whatever + + const int index = + moduleGroupSelector_->getParameterIndexFromDetId(hit.det()->geographicalId(), eventInfo.eventId().run()); + if (index >= 0) { // otherwise not treated edm::ESHandle magneticField; setup.get().get(magneticField); const GlobalVector bField(magneticField->inTesla(hit.det()->surface().position())); const LocalVector bFieldLocal(hit.det()->surface().toLocal(bField)); //std::cout << "SiStripBackplaneCalibration derivatives " << readoutModeName_ << std::endl; - const double dZ = hit.det()->surface().bounds().thickness(); // it's a float only... - const double tanPsi = tsos.localParameters().mixedFormatVector()[1]; //float... + const double dZ = hit.det()->surface().bounds().thickness(); // it's a float only... + const double tanPsi = tsos.localParameters().mixedFormatVector()[1]; //float... - edm::ESHandle lorentzAngleHandle; - setup.get().get(readoutModeName_, lorentzAngleHandle); - // Yes, mobility (= LA/By) stored in object called LA... - const double mobility = lorentzAngleHandle->getLorentzAngle(hit.det()->geographicalId()); + edm::ESHandle lorentzAngleHandle; + setup.get().get(readoutModeName_, lorentzAngleHandle); + // Yes, mobility (= LA/By) stored in object called LA... + const double mobility = lorentzAngleHandle->getLorentzAngle(hit.det()->geographicalId()); // shift due to dead back plane has two parts: - // 1) Lorentz Angle correction formula gets reduced thickness dz*(1-bp) - // 2) 'Direct' effect is shift of effective module position in local z by bp*dz/2 - // (see GF's presentation in alignment meeting 25.10.2012, - // https://indico.cern.ch/conferenceDisplay.py?confId=174266#2012-10-25) + // 1) Lorentz Angle correction formula gets reduced thickness dz*(1-bp) + // 2) 'Direct' effect is shift of effective module position in local z by bp*dz/2 + // (see GF's presentation in alignment meeting 25.10.2012, + // https://indico.cern.ch/conferenceDisplay.py?confId=174266#2012-10-25) // const double xDerivative = 0.5 * dZ * (mobility * bFieldLocal.y() - tanPsi); - //FIXME: +tanPsi? At least that fits the sign of the dr/dw residual + //FIXME: +tanPsi? At least that fits the sign of the dr/dw residual // in KarimakiDerivatives... const double xDerivative = 0.5 * dZ * (mobility * bFieldLocal.y() + tanPsi); - // std::cout << "derivative is " << xDerivative << " for index " << index - // << std::endl; -// if (index >= 10) { -// std::cout << "mobility * y-field " << mobility * bFieldLocal.y() -// << ", \n tanPsi " << tanPsi /*<< ", dZ " << dZ */ << std::endl; -// std::cout << "|tanPsi| - |mobility * y-field| " -// << fabs(tanPsi) - fabs(mobility * bFieldLocal.y()) -// << std::endl; -// } - const Values derivs(xDerivative, 0.); // yDerivative = 0. - outDerivInds.push_back(ValuesIndexPair(derivs, index)); + // std::cout << "derivative is " << xDerivative << " for index " << index + // << std::endl; + // if (index >= 10) { + // std::cout << "mobility * y-field " << mobility * bFieldLocal.y() + // << ", \n tanPsi " << tanPsi /*<< ", dZ " << dZ */ << std::endl; + // std::cout << "|tanPsi| - |mobility * y-field| " + // << fabs(tanPsi) - fabs(mobility * bFieldLocal.y()) + // << std::endl; + // } + const Values derivs(xDerivative, 0.); // yDerivative = 0. + outDerivInds.push_back(ValuesIndexPair(derivs, index)); } } else { edm::LogWarning("Alignment") << "@SUB=SiStripBackplaneCalibration::derivatives1" << "Hit without GeomDet, skip!"; } } else if (mode != kDeconvolutionMode && mode != kPeakMode) { - // warn only if unknown/mixed mode + // warn only if unknown/mixed mode edm::LogWarning("Alignment") << "@SUB=SiStripBackplaneCalibration::derivatives2" - << "Readout mode is " << mode << ", but looking for " - << readoutMode_ << " (" << readoutModeName_ << ")."; + << "Readout mode is " << mode << ", but looking for " << readoutMode_ << " (" + << readoutModeName_ << ")."; } - + return outDerivInds.size(); } //====================================================================== -bool SiStripBackplaneCalibration::setParameter(unsigned int index, double value) -{ +bool SiStripBackplaneCalibration::setParameter(unsigned int index, double value) { if (index >= parameters_.size()) { return false; } else { @@ -269,8 +256,7 @@ bool SiStripBackplaneCalibration::setParameter(unsigned int index, double value) } //====================================================================== -bool SiStripBackplaneCalibration::setParameterError(unsigned int index, double error) -{ +bool SiStripBackplaneCalibration::setParameterError(unsigned int index, double error) { if (index >= paramUncertainties_.size()) { return false; } else { @@ -280,50 +266,44 @@ bool SiStripBackplaneCalibration::setParameterError(unsigned int index, double e } //====================================================================== -double SiStripBackplaneCalibration::getParameter(unsigned int index) const -{ +double SiStripBackplaneCalibration::getParameter(unsigned int index) const { return (index >= parameters_.size() ? 0. : parameters_[index]); } //====================================================================== -double SiStripBackplaneCalibration::getParameterError(unsigned int index) const -{ +double SiStripBackplaneCalibration::getParameterError(unsigned int index) const { return (index >= paramUncertainties_.size() ? 0. : paramUncertainties_[index]); } //====================================================================== void SiStripBackplaneCalibration::beginOfJob(AlignableTracker *aliTracker, AlignableMuon * /*aliMuon*/, - AlignableExtras */*aliExtras*/) -{ + AlignableExtras * /*aliExtras*/) { //specify the sub-detectors for which the back plane correction is determined: all strips - const std::vector sdets = boost::assign::list_of(SiStripDetId::TIB)(SiStripDetId::TID) - (SiStripDetId::TOB)(SiStripDetId::TEC); - + const std::vector sdets = + boost::assign::list_of(SiStripDetId::TIB)(SiStripDetId::TID)(SiStripDetId::TOB)(SiStripDetId::TEC); + moduleGroupSelector_ = new TkModuleGroupSelector(aliTracker, moduleGroupSelCfg_, sdets); - + parameters_.resize(moduleGroupSelector_->getNumberOfParameters(), 0.); paramUncertainties_.resize(moduleGroupSelector_->getNumberOfParameters(), 0.); - edm::LogInfo("Alignment") << "@SUB=SiStripBackplaneCalibration" << "Created with name " - << this->name() << " for readout mode '" << readoutModeName_ - << "',\n" << this->numParameters() << " parameters to be determined." - << "\nsaveToDB = " << saveToDB_ - << "\n outFileName = " << outFileName_ + edm::LogInfo("Alignment") << "@SUB=SiStripBackplaneCalibration" + << "Created with name " << this->name() << " for readout mode '" << readoutModeName_ + << "',\n" + << this->numParameters() << " parameters to be determined." + << "\nsaveToDB = " << saveToDB_ << "\n outFileName = " << outFileName_ << "\n N(merge files) = " << mergeFileNames_.size() << "\n number of IOVs = " << moduleGroupSelector_->numIovs(); - + if (!mergeFileNames_.empty()) { edm::LogInfo("Alignment") << "@SUB=SiStripBackplaneCalibration" << "First file to merge: " << mergeFileNames_[0]; } - } - //====================================================================== -void SiStripBackplaneCalibration::endOfJob() -{ +void SiStripBackplaneCalibration::endOfJob() { // loginfo output std::ostringstream out; out << "Parameter results for readout mode '" << readoutModeName_ << "'\n"; @@ -332,33 +312,33 @@ void SiStripBackplaneCalibration::endOfJob() } edm::LogInfo("Alignment") << "@SUB=SiStripBackplaneCalibration::endOfJob" << out.str(); - std::map treeInfo; // map of TreeStruct for each detId + std::map treeInfo; // map of TreeStruct for each detId // now write 'input' tree - const SiStripBackPlaneCorrection *input = this->getBackPlaneCorrectionInput(); // never NULL + const SiStripBackPlaneCorrection *input = this->getBackPlaneCorrectionInput(); // never NULL const std::string treeName(this->name() + '_' + readoutModeName_ + '_'); - this->writeTree(input, treeInfo, (treeName + "input").c_str()); // empty treeInfo for input... + this->writeTree(input, treeInfo, (treeName + "input").c_str()); // empty treeInfo for input... if (input->getBackPlaneCorrections().empty()) { edm::LogError("Alignment") << "@SUB=SiStripBackplaneCalibration::endOfJob" - << "Input back plane correction map is empty ('" - << readoutModeName_ << "' mode), skip writing output!"; + << "Input back plane correction map is empty ('" << readoutModeName_ + << "' mode), skip writing output!"; return; } - const unsigned int nonZeroParamsOrErrors = // Any determined value? - count_if (parameters_.begin(), parameters_.end(),[](auto c){return c != 0.;}) - + count_if(paramUncertainties_.begin(), paramUncertainties_.end(), - [](auto c){return c!= 0.;}); + const unsigned int nonZeroParamsOrErrors = // Any determined value? + count_if(parameters_.begin(), parameters_.end(), [](auto c) { return c != 0.; }) + + count_if(paramUncertainties_.begin(), paramUncertainties_.end(), [](auto c) { return c != 0.; }); for (unsigned int iIOV = 0; iIOV < moduleGroupSelector_->numIovs(); ++iIOV) { cond::Time_t firstRunOfIOV = moduleGroupSelector_->firstRunOfIOV(iIOV); SiStripBackPlaneCorrection *output = new SiStripBackPlaneCorrection; // Loop on map of values from input and add (possible) parameter results for (auto iterIdValue = input->getBackPlaneCorrections().begin(); - iterIdValue != input->getBackPlaneCorrections().end(); ++iterIdValue) { + iterIdValue != input->getBackPlaneCorrections().end(); + ++iterIdValue) { // type of (*iterIdValue) is pair - const unsigned int detId = iterIdValue->first; // key of map is DetId + const unsigned int detId = iterIdValue->first; // key of map is DetId // Some code one could use to miscalibrate wrt input: // double param = 0.; // const DetId id(detId); @@ -388,34 +368,33 @@ void SiStripBackplaneCalibration::endOfJob() const double param = this->getParameterForDetId(detId, firstRunOfIOV); // put result in output, i.e. sum of input and determined parameter: output->putBackPlaneCorrection(detId, iterIdValue->second + param); - const int paramIndex = moduleGroupSelector_->getParameterIndexFromDetId(detId,firstRunOfIOV); + const int paramIndex = moduleGroupSelector_->getParameterIndexFromDetId(detId, firstRunOfIOV); treeInfo[detId] = TreeStruct(param, this->getParameterError(paramIndex), paramIndex); } - if (saveToDB_ || nonZeroParamsOrErrors != 0) { // Skip writing mille jobs... + if (saveToDB_ || nonZeroParamsOrErrors != 0) { // Skip writing mille jobs... this->writeTree(output, treeInfo, (treeName + Form("result_%lld", firstRunOfIOV)).c_str()); } - if (saveToDB_) { // If requested, write out to DB + if (saveToDB_) { // If requested, write out to DB edm::Service dbService; if (dbService.isAvailable()) { - dbService->writeOne(output, firstRunOfIOV, recordNameDBwrite_); - // no 'delete output;': writeOne(..) took over ownership + dbService->writeOne(output, firstRunOfIOV, recordNameDBwrite_); + // no 'delete output;': writeOne(..) took over ownership } else { - delete output; - edm::LogError("BadConfig") << "@SUB=SiStripBackplaneCalibration::endOfJob" - << "No PoolDBOutputService available, but saveToDB true!"; + delete output; + edm::LogError("BadConfig") << "@SUB=SiStripBackplaneCalibration::endOfJob" + << "No PoolDBOutputService available, but saveToDB true!"; } } else { delete output; } - } // end loop on IOVs + } // end loop on IOVs } //====================================================================== bool SiStripBackplaneCalibration::checkBackPlaneCorrectionInput(const edm::EventSetup &setup, - const EventInfo &eventInfo) -{ + const EventInfo &eventInfo) { edm::ESHandle backPlaneCorrHandle; if (!siStripBackPlaneCorrInput_) { setup.get().get(readoutModeName_, backPlaneCorrHandle); @@ -424,69 +403,63 @@ bool SiStripBackplaneCalibration::checkBackPlaneCorrectionInput(const edm::Event // Otherwise could be that next check has to check via following 'else', though // no new IOV has started... (to be checked) } else { - if (watchBackPlaneCorrRcd_.check(setup)) { // new IOV of input - but how to check peak vs deco? + if (watchBackPlaneCorrRcd_.check(setup)) { // new IOV of input - but how to check peak vs deco? setup.get().get(readoutModeName_, backPlaneCorrHandle); - if (backPlaneCorrHandle->getBackPlaneCorrections() // but only bad if non-identical values - != siStripBackPlaneCorrInput_->getBackPlaneCorrections()) { // (comparing maps) - // Maps are containers sorted by key, but comparison problems may arise from - // 'floating point comparison' problems (FIXME?) - throw cms::Exception("BadInput") - << "SiStripBackplaneCalibration::checkBackPlaneCorrectionInput:\n" - << "Content of SiStripBackPlaneCorrection changed at run " << eventInfo.eventId().run() - << ", but algorithm expects constant input!\n"; - return false; // not reached... + if (backPlaneCorrHandle->getBackPlaneCorrections() // but only bad if non-identical values + != siStripBackPlaneCorrInput_->getBackPlaneCorrections()) { // (comparing maps) + // Maps are containers sorted by key, but comparison problems may arise from + // 'floating point comparison' problems (FIXME?) + throw cms::Exception("BadInput") << "SiStripBackplaneCalibration::checkBackPlaneCorrectionInput:\n" + << "Content of SiStripBackPlaneCorrection changed at run " + << eventInfo.eventId().run() << ", but algorithm expects constant input!\n"; + return false; // not reached... } } } - + return true; } //====================================================================== -const SiStripBackPlaneCorrection* SiStripBackplaneCalibration::getBackPlaneCorrectionInput() -{ +const SiStripBackPlaneCorrection *SiStripBackplaneCalibration::getBackPlaneCorrectionInput() { // For parallel processing in Millepede II, create SiStripBackPlaneCorrection // from info stored in files of parallel jobs and check that they are identical. // If this job has run on events, still check that back plane corrections are // identical to the ones from mergeFileNames_. const std::string treeName(((this->name() + '_') += readoutModeName_) += "_input"); for (auto iFile = mergeFileNames_.begin(); iFile != mergeFileNames_.end(); ++iFile) { - SiStripBackPlaneCorrection* bpCorr = this->createFromTree(iFile->c_str(), treeName.c_str()); + SiStripBackPlaneCorrection *bpCorr = this->createFromTree(iFile->c_str(), treeName.c_str()); // siStripBackPlaneCorrInput_ could be non-null from previous file of this loop // or from checkBackPlaneCorrectionInput(..) when running on data in this job as well if (!siStripBackPlaneCorrInput_ || siStripBackPlaneCorrInput_->getBackPlaneCorrections().empty()) { - delete siStripBackPlaneCorrInput_; // NULL or empty + delete siStripBackPlaneCorrInput_; // NULL or empty siStripBackPlaneCorrInput_ = bpCorr; } else { // about comparison of maps see comments in checkBackPlaneCorrectionInput - if (bpCorr && !bpCorr->getBackPlaneCorrections().empty() && // single job might not have got events + if (bpCorr && !bpCorr->getBackPlaneCorrections().empty() && // single job might not have got events bpCorr->getBackPlaneCorrections() != siStripBackPlaneCorrInput_->getBackPlaneCorrections()) { // Throw exception instead of error? edm::LogError("NoInput") << "@SUB=SiStripBackplaneCalibration::getBackPlaneCorrectionInput" - << "Different input values from tree " << treeName - << " in file " << *iFile << "."; - + << "Different input values from tree " << treeName << " in file " << *iFile << "."; } delete bpCorr; } } - if (!siStripBackPlaneCorrInput_) { // no files nor ran on events + if (!siStripBackPlaneCorrInput_) { // no files nor ran on events siStripBackPlaneCorrInput_ = new SiStripBackPlaneCorrection; edm::LogError("NoInput") << "@SUB=SiStripBackplaneCalibration::getBackPlaneCorrectionInput" - << "No input, create an empty one ('" << readoutModeName_ << "' mode)!"; + << "No input, create an empty one ('" << readoutModeName_ << "' mode)!"; } else if (siStripBackPlaneCorrInput_->getBackPlaneCorrections().empty()) { edm::LogError("NoInput") << "@SUB=SiStripBackplaneCalibration::getBackPlaneCorrectionInput" - << "Empty result ('" << readoutModeName_ << "' mode)!"; + << "Empty result ('" << readoutModeName_ << "' mode)!"; } return siStripBackPlaneCorrInput_; } //====================================================================== -double SiStripBackplaneCalibration::getParameterForDetId(unsigned int detId, - edm::RunNumber_t run) const -{ +double SiStripBackplaneCalibration::getParameterForDetId(unsigned int detId, edm::RunNumber_t run) const { const int index = moduleGroupSelector_->getParameterIndexFromDetId(detId, run); return (index < 0 ? 0. : parameters_[index]); @@ -495,14 +468,14 @@ double SiStripBackplaneCalibration::getParameterForDetId(unsigned int detId, //====================================================================== void SiStripBackplaneCalibration::writeTree(const SiStripBackPlaneCorrection *backPlaneCorrection, const std::map &treeInfo, - const char *treeName) const -{ - if (!backPlaneCorrection) return; + const char *treeName) const { + if (!backPlaneCorrection) + return; - TFile* file = TFile::Open(outFileName_.c_str(), "UPDATE"); + TFile *file = TFile::Open(outFileName_.c_str(), "UPDATE"); if (!file) { edm::LogError("BadConfig") << "@SUB=SiStripBackplaneCalibration::writeTree" - << "Could not open file '" << outFileName_ << "'."; + << "Could not open file '" << outFileName_ << "'."; return; } @@ -515,15 +488,16 @@ void SiStripBackplaneCalibration::writeTree(const SiStripBackPlaneCorrection *ba tree->Branch("treeStruct", &treeStruct, TreeStruct::LeafList()); for (auto iterIdValue = backPlaneCorrection->getBackPlaneCorrections().begin(); - iterIdValue != backPlaneCorrection->getBackPlaneCorrections().end(); ++iterIdValue) { + iterIdValue != backPlaneCorrection->getBackPlaneCorrections().end(); + ++iterIdValue) { // type of (*iterIdValue) is pair - id = iterIdValue->first; // key of map is DetId + id = iterIdValue->first; // key of map is DetId value = iterIdValue->second; // type of (*treeStructIter) is pair - auto treeStructIter = treeInfo.find(id); // find info for this id + auto treeStructIter = treeInfo.find(id); // find info for this id if (treeStructIter != treeInfo.end()) { - treeStruct = treeStructIter->second; // info from input map - } else { // if none found, fill at least parameter index (using 1st IOV...) + treeStruct = treeStructIter->second; // info from input map + } else { // if none found, fill at least parameter index (using 1st IOV...) const cond::Time_t run1of1stIov = moduleGroupSelector_->firstRunOfIOV(0); const int ind = moduleGroupSelector_->getParameterIndexFromDetId(id, run1of1stIov); treeStruct = TreeStruct(ind); @@ -531,25 +505,24 @@ void SiStripBackplaneCalibration::writeTree(const SiStripBackPlaneCorrection *ba tree->Fill(); } tree->Write(); - delete file; // tree vanishes with the file... - + delete file; // tree vanishes with the file... } //====================================================================== -SiStripBackPlaneCorrection* -SiStripBackplaneCalibration::createFromTree(const char *fileName, const char *treeName) const -{ +SiStripBackPlaneCorrection *SiStripBackplaneCalibration::createFromTree(const char *fileName, + const char *treeName) const { // Check for file existence on your own to work around // https://hypernews.cern.ch/HyperNews/CMS/get/swDevelopment/2715.html: - TFile* file = nullptr; - FILE* testFile = fopen(fileName,"r"); + TFile *file = nullptr; + FILE *testFile = fopen(fileName, "r"); if (testFile) { fclose(testFile); file = TFile::Open(fileName, "READ"); - } // else not existing, see error below + } // else not existing, see error below TTree *tree = nullptr; - if (file) file->GetObject(treeName, tree); + if (file) + file->GetObject(treeName, tree); SiStripBackPlaneCorrection *result = nullptr; if (tree) { @@ -564,22 +537,20 @@ SiStripBackplaneCalibration::createFromTree(const char *fileName, const char *tr tree->GetEntry(iEntry); result->putBackPlaneCorrection(id, value); } - } else { // Warning only since could be parallel job on no events. + } else { // Warning only since could be parallel job on no events. edm::LogWarning("Alignment") << "@SUB=SiStripBackplaneCalibration::createFromTree" - << "Could not get TTree '" << treeName << "' from file '" - << fileName << (file ? "'." : "' (file does not exist)."); + << "Could not get TTree '" << treeName << "' from file '" << fileName + << (file ? "'." : "' (file does not exist)."); } - delete file; // tree will vanish with file + delete file; // tree will vanish with file return result; } - //====================================================================== //====================================================================== // Plugin definition #include "Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h" -DEFINE_EDM_PLUGIN(IntegratedCalibrationPluginFactory, - SiStripBackplaneCalibration, "SiStripBackplaneCalibration"); +DEFINE_EDM_PLUGIN(IntegratedCalibrationPluginFactory, SiStripBackplaneCalibration, "SiStripBackplaneCalibration"); diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripLorentzAngleCalibration.cc b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripLorentzAngleCalibration.cc index 7957d822be5d8..b910f6f965f0e 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripLorentzAngleCalibration.cc +++ b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripLorentzAngleCalibration.cc @@ -50,8 +50,7 @@ #include #include -class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase -{ +class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase { public: /// Constructor explicit SiStripLorentzAngleCalibration(const edm::ParameterSet &cfg); @@ -87,12 +86,10 @@ class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase double getParameterError(unsigned int index) const override; // /// Call at beginning of job: - void beginOfJob(AlignableTracker *tracker, - AlignableMuon *muon, - AlignableExtras *extras) override; + void beginOfJob(AlignableTracker *tracker, AlignableMuon *muon, AlignableExtras *extras) override; /// Call at beginning of run: - void beginRun(const edm::Run&, const edm::EventSetup&) override; + void beginRun(const edm::Run &, const edm::EventSetup &) override; /// Called at end of a the job of the AlignmentProducer. /// Write out determined parameters. @@ -102,7 +99,7 @@ class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase /// Input LorentzAngle values: /// - either from EventSetup of first call to derivatives(..) /// - or created from files of passed by configuration (i.e. from parallel processing) - const SiStripLorentzAngle* getLorentzAnglesInput(const align::RunNumber& = 0); + const SiStripLorentzAngle *getLorentzAnglesInput(const align::RunNumber & = 0); /// in non-peak mode the effective thickness is reduced... double effectiveThickness(const GeomDet *det, int16_t mode, const edm::EventSetup &setup) const; @@ -111,7 +108,8 @@ class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase double getParameterForDetId(unsigned int detId, edm::RunNumber_t run) const; void writeTree(const SiStripLorentzAngle *lorentzAngle, - const std::map &treeInfo, const char *treeName) const; + const std::map &treeInfo, + const char *treeName) const; SiStripLorentzAngle createFromTree(const char *fileName, const char *treeName) const; const std::string readoutModeName_; @@ -124,7 +122,7 @@ class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase edm::ESWatcher watchLorentzAngleRcd_; std::map cachedLorentzAngleInputs_; - SiStripLorentzAngle* siStripLorentzAngleInput_{nullptr}; + SiStripLorentzAngle *siStripLorentzAngleInput_{nullptr}; align::RunNumber currentIOV_{0}; std::vector parameters_; @@ -139,15 +137,13 @@ class SiStripLorentzAngleCalibration : public IntegratedCalibrationBase //====================================================================== SiStripLorentzAngleCalibration::SiStripLorentzAngleCalibration(const edm::ParameterSet &cfg) - : IntegratedCalibrationBase(cfg), - readoutModeName_(cfg.getParameter("readoutMode")), - saveToDB_(cfg.getParameter("saveToDB")), - recordNameDBwrite_(cfg.getParameter("recordNameDBwrite")), - outFileName_(cfg.getParameter("treeFile")), - mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), - moduleGroupSelCfg_(cfg.getParameter("LorentzAngleModuleGroups")) -{ - + : IntegratedCalibrationBase(cfg), + readoutModeName_(cfg.getParameter("readoutMode")), + saveToDB_(cfg.getParameter("saveToDB")), + recordNameDBwrite_(cfg.getParameter("recordNameDBwrite")), + outFileName_(cfg.getParameter("treeFile")), + mergeFileNames_(cfg.getParameter >("mergeTreeFiles")), + moduleGroupSelCfg_(cfg.getParameter("LorentzAngleModuleGroups")) { // SiStripLatency::singleReadOutMode() returns // 1: all in peak, 0: all in deco, -1: mixed state // (in principle one could treat even mixed state APV by APV...) @@ -156,33 +152,27 @@ SiStripLorentzAngleCalibration::SiStripLorentzAngleCalibration(const edm::Parame } else if (readoutModeName_ == "deconvolution") { readoutMode_ = kDeconvolutionMode; } else { - throw cms::Exception("BadConfig") - << "SiStripLorentzAngleCalibration:\n" << "Unknown mode '" - << readoutModeName_ << "', should be 'peak' or 'deconvolution' .\n"; + throw cms::Exception("BadConfig") << "SiStripLorentzAngleCalibration:\n" + << "Unknown mode '" << readoutModeName_ + << "', should be 'peak' or 'deconvolution' .\n"; } - } //====================================================================== -unsigned int SiStripLorentzAngleCalibration::numParameters() const -{ - return parameters_.size(); -} +unsigned int SiStripLorentzAngleCalibration::numParameters() const { return parameters_.size(); } //====================================================================== -void -SiStripLorentzAngleCalibration::beginRun(const edm::Run& run, - const edm::EventSetup& setup) { - +void SiStripLorentzAngleCalibration::beginRun(const edm::Run &run, const edm::EventSetup &setup) { // no action needed if the LA record didn't change - if (!(watchLorentzAngleRcd_.check(setup))) return; + if (!(watchLorentzAngleRcd_.check(setup))) + return; const auto runNumber = run.run(); auto firstRun = cond::timeTypeSpecs[cond::runnumber].beginValue; // avoid infinite loop due to wrap-around of unsigned variable 'i' including // arrow from i to zero and a nice smiley ;) - for (unsigned int i = moduleGroupSelector_->numIovs(); i-->0 ;) { + for (unsigned int i = moduleGroupSelector_->numIovs(); i-- > 0;) { const auto firstRunOfIOV = moduleGroupSelector_->firstRunOfIOV(i); if (runNumber >= firstRunOfIOV) { firstRun = firstRunOfIOV; @@ -191,24 +181,22 @@ SiStripLorentzAngleCalibration::beginRun(const edm::Run& run, } edm::ESHandle lorentzAngleHandle; - const auto& lorentzAngleRcd = setup.get(); + const auto &lorentzAngleRcd = setup.get(); lorentzAngleRcd.get(readoutModeName_, lorentzAngleHandle); if (cachedLorentzAngleInputs_.find(firstRun) == cachedLorentzAngleInputs_.end()) { cachedLorentzAngleInputs_.emplace(firstRun, SiStripLorentzAngle(*lorentzAngleHandle)); } else { if (lorentzAngleRcd.validityInterval().first().eventID().run() > firstRun && - lorentzAngleHandle->getLorentzAngles() // only bad if non-identical values - != cachedLorentzAngleInputs_[firstRun].getLorentzAngles()) { // (comparing maps) + lorentzAngleHandle->getLorentzAngles() // only bad if non-identical values + != cachedLorentzAngleInputs_[firstRun].getLorentzAngles()) { // (comparing maps) // Maps are containers sorted by key, but comparison problems may arise from // 'floating point comparison' problems (FIXME?) - throw cms::Exception("BadInput") - << "Trying to cache SiStripLorentzAngle payload for a run (" << runNumber - << ") in an IOV (" << firstRun << ") that was already cached.\n" - << "The following record in your input database tag has an IOV " - << "boundary that does not match your IOV definition:\n" - << " - SiStripLorentzAngleRcd '" << lorentzAngleRcd.key().name() - << "' (since " - << lorentzAngleRcd.validityInterval().first().eventID().run() << ")\n"; + throw cms::Exception("BadInput") << "Trying to cache SiStripLorentzAngle payload for a run (" << runNumber + << ") in an IOV (" << firstRun << ") that was already cached.\n" + << "The following record in your input database tag has an IOV " + << "boundary that does not match your IOV definition:\n" + << " - SiStripLorentzAngleRcd '" << lorentzAngleRcd.key().name() << "' (since " + << lorentzAngleRcd.validityInterval().first().eventID().run() << ")\n"; } } @@ -217,24 +205,22 @@ SiStripLorentzAngleCalibration::beginRun(const edm::Run& run, } //====================================================================== -unsigned int -SiStripLorentzAngleCalibration::derivatives(std::vector &outDerivInds, - const TransientTrackingRecHit &hit, - const TrajectoryStateOnSurface &tsos, - const edm::EventSetup &setup, - const EventInfo &eventInfo) const -{ +unsigned int SiStripLorentzAngleCalibration::derivatives(std::vector &outDerivInds, + const TransientTrackingRecHit &hit, + const TrajectoryStateOnSurface &tsos, + const edm::EventSetup &setup, + const EventInfo &eventInfo) const { outDerivInds.clear(); edm::ESHandle latency; setup.get().get(latency); const int16_t mode = latency->singleReadOutMode(); if (mode == readoutMode_) { - if (hit.det()) { // otherwise 'constraint hit' or whatever + if (hit.det()) { // otherwise 'constraint hit' or whatever - const int index = moduleGroupSelector_->getParameterIndexFromDetId(hit.det()->geographicalId(), - eventInfo.eventId().run()); - if (index >= 0) { // otherwise not treated + const int index = + moduleGroupSelector_->getParameterIndexFromDetId(hit.det()->geographicalId(), eventInfo.eventId().run()); + if (index >= 0) { // otherwise not treated edm::ESHandle magneticField; setup.get().get(magneticField); const GlobalVector bField(magneticField->inTesla(hit.det()->surface().position())); @@ -249,10 +235,10 @@ SiStripLorentzAngleCalibration::derivatives(std::vector &outDer // drift.x = -mobility * by * thickness (full drift from backside) // So '-' already comes from that, not from mobility being part of // track model... - // GM: sign convention is the same as for pixel LA, i.e. adopt it here, too - const double xDerivative = bFieldLocal.y() * dZ * -0.5; // parameter is mobility! - const double yDerivative = bFieldLocal.x() * dZ * 0.5; // parameter is mobility! - if (xDerivative || yDerivative) { // If field is zero, this is zero: do not return it + // GM: sign convention is the same as for pixel LA, i.e. adopt it here, too + const double xDerivative = bFieldLocal.y() * dZ * -0.5; // parameter is mobility! + const double yDerivative = bFieldLocal.x() * dZ * 0.5; // parameter is mobility! + if (xDerivative || yDerivative) { // If field is zero, this is zero: do not return it const Values derivs{xDerivative, yDerivative}; outDerivInds.push_back(ValuesIndexPair(derivs, index)); } @@ -264,16 +250,15 @@ SiStripLorentzAngleCalibration::derivatives(std::vector &outDer } else if (mode != kDeconvolutionMode && mode != kPeakMode) { // warn only if unknown/mixed mode edm::LogWarning("Alignment") << "@SUB=SiStripLorentzAngleCalibration::derivatives2" - << "Readout mode is " << mode << ", but looking for " - << readoutMode_ << " (" << readoutModeName_ << ")."; + << "Readout mode is " << mode << ", but looking for " << readoutMode_ << " (" + << readoutModeName_ << ")."; } return outDerivInds.size(); } //====================================================================== -bool SiStripLorentzAngleCalibration::setParameter(unsigned int index, double value) -{ +bool SiStripLorentzAngleCalibration::setParameter(unsigned int index, double value) { if (index >= parameters_.size()) { return false; } else { @@ -283,8 +268,7 @@ bool SiStripLorentzAngleCalibration::setParameter(unsigned int index, double val } //====================================================================== -bool SiStripLorentzAngleCalibration::setParameterError(unsigned int index, double error) -{ +bool SiStripLorentzAngleCalibration::setParameterError(unsigned int index, double error) { if (index >= paramUncertainties_.size()) { return false; } else { @@ -294,36 +278,31 @@ bool SiStripLorentzAngleCalibration::setParameterError(unsigned int index, doubl } //====================================================================== -double SiStripLorentzAngleCalibration::getParameter(unsigned int index) const -{ +double SiStripLorentzAngleCalibration::getParameter(unsigned int index) const { return (index >= parameters_.size() ? 0. : parameters_[index]); } //====================================================================== -double SiStripLorentzAngleCalibration::getParameterError(unsigned int index) const -{ +double SiStripLorentzAngleCalibration::getParameterError(unsigned int index) const { return (index >= paramUncertainties_.size() ? 0. : paramUncertainties_[index]); } //====================================================================== void SiStripLorentzAngleCalibration::beginOfJob(AlignableTracker *aliTracker, AlignableMuon * /*aliMuon*/, - AlignableExtras * /*aliExtras*/) -{ + AlignableExtras * /*aliExtras*/) { //specify the sub-detectors for which the LA is determined - const std::vector sdets = {SiStripDetId::TIB, SiStripDetId::TOB, - SiStripDetId::TID, SiStripDetId::TEC}; - moduleGroupSelector_ = - std::make_unique(aliTracker, moduleGroupSelCfg_, sdets); + const std::vector sdets = {SiStripDetId::TIB, SiStripDetId::TOB, SiStripDetId::TID, SiStripDetId::TEC}; + moduleGroupSelector_ = std::make_unique(aliTracker, moduleGroupSelCfg_, sdets); parameters_.resize(moduleGroupSelector_->getNumberOfParameters(), 0.); paramUncertainties_.resize(moduleGroupSelector_->getNumberOfParameters(), 0.); - edm::LogInfo("Alignment") << "@SUB=SiStripLorentzAngleCalibration" << "Created with name " - << this->name() << " for readout mode '" << readoutModeName_ - << "',\n" << this->numParameters() << " parameters to be determined." - << "\nsaveToDB = " << saveToDB_ - << "\n outFileName = " << outFileName_ + edm::LogInfo("Alignment") << "@SUB=SiStripLorentzAngleCalibration" + << "Created with name " << this->name() << " for readout mode '" << readoutModeName_ + << "',\n" + << this->numParameters() << " parameters to be determined." + << "\nsaveToDB = " << saveToDB_ << "\n outFileName = " << outFileName_ << "\n N(merge files) = " << mergeFileNames_.size() << "\n number of IOVs = " << moduleGroupSelector_->numIovs(); @@ -333,10 +312,8 @@ void SiStripLorentzAngleCalibration::beginOfJob(AlignableTracker *aliTracker, } } - //====================================================================== -void SiStripLorentzAngleCalibration::endOfJob() -{ +void SiStripLorentzAngleCalibration::endOfJob() { // loginfo output std::ostringstream out; out << "Parameter results for readout mode '" << readoutModeName_ << "'\n"; @@ -345,38 +322,38 @@ void SiStripLorentzAngleCalibration::endOfJob() } edm::LogInfo("Alignment") << "@SUB=SiStripLorentzAngleCalibration::endOfJob" << out.str(); - std::map treeInfo; // map of TreeStruct for each detId + std::map treeInfo; // map of TreeStruct for each detId // now write 'input' tree const std::string treeName{this->name() + '_' + readoutModeName_ + '_'}; - std::vector inputs{}; + std::vector inputs{}; inputs.reserve(moduleGroupSelector_->numIovs()); for (unsigned int iIOV = 0; iIOV < moduleGroupSelector_->numIovs(); ++iIOV) { const auto firstRunOfIOV = moduleGroupSelector_->firstRunOfIOV(iIOV); - inputs.push_back(this->getLorentzAnglesInput(firstRunOfIOV)); // never NULL - this->writeTree(inputs.back(), treeInfo, - (treeName + "input_" + std::to_string(firstRunOfIOV)).c_str()); // empty treeInfo for input... + inputs.push_back(this->getLorentzAnglesInput(firstRunOfIOV)); // never NULL + this->writeTree(inputs.back(), + treeInfo, + (treeName + "input_" + std::to_string(firstRunOfIOV)).c_str()); // empty treeInfo for input... if (inputs.back()->getLorentzAngles().empty()) { edm::LogError("Alignment") << "@SUB=SiStripLorentzAngleCalibration::endOfJob" - << "Input Lorentz angle map is empty ('" - << readoutModeName_ << "' mode), skip writing output!"; + << "Input Lorentz angle map is empty ('" << readoutModeName_ + << "' mode), skip writing output!"; return; } } - const unsigned int nonZeroParamsOrErrors = // Any determined value? - count_if (parameters_.begin(), parameters_.end(), [](auto c){return c!=0.;}) - + count_if(paramUncertainties_.begin(), paramUncertainties_.end(), - [](auto c){return c!=0.;}); + const unsigned int nonZeroParamsOrErrors = // Any determined value? + count_if(parameters_.begin(), parameters_.end(), [](auto c) { return c != 0.; }) + + count_if(paramUncertainties_.begin(), paramUncertainties_.end(), [](auto c) { return c != 0.; }); for (unsigned int iIOV = 0; iIOV < moduleGroupSelector_->numIovs(); ++iIOV) { auto firstRunOfIOV = static_cast(moduleGroupSelector_->firstRunOfIOV(iIOV)); SiStripLorentzAngle output{}; // Loop on map of values from input and add (possible) parameter results - for (const auto& iterIdValue: inputs[iIOV]->getLorentzAngles()) { + for (const auto &iterIdValue : inputs[iIOV]->getLorentzAngles()) { // type of 'iterIdValue' is pair - const auto detId = iterIdValue.first; // key of map is DetId + const auto detId = iterIdValue.first; // key of map is DetId // Some code one could use to miscalibrate wrt input: // double param = 0.; // const DetId id(detId); @@ -389,15 +366,15 @@ void SiStripLorentzAngleCalibration::endOfJob() // put result in output, i.e. sum of input and determined parameter: auto value = iterIdValue.second + static_cast(param); output.putLorentzAngle(detId, value); - const int paramIndex = moduleGroupSelector_->getParameterIndexFromDetId(detId,firstRunOfIOV); + const int paramIndex = moduleGroupSelector_->getParameterIndexFromDetId(detId, firstRunOfIOV); treeInfo[detId] = TreeStruct(param, this->getParameterError(paramIndex), paramIndex); } - if (saveToDB_ || nonZeroParamsOrErrors != 0) { // Skip writing mille jobs... + if (saveToDB_ || nonZeroParamsOrErrors != 0) { // Skip writing mille jobs... this->writeTree(&output, treeInfo, (treeName + Form("result_%lld", firstRunOfIOV)).c_str()); } - if (saveToDB_) { // If requested, write out to DB + if (saveToDB_) { // If requested, write out to DB edm::Service dbService; if (dbService.isAvailable()) { dbService->writeOne(&output, firstRunOfIOV, recordNameDBwrite_); @@ -406,22 +383,22 @@ void SiStripLorentzAngleCalibration::endOfJob() << "No PoolDBOutputService available, but saveToDB true!"; } } - } // end loop on IOVs + } // end loop on IOVs } //====================================================================== double SiStripLorentzAngleCalibration::effectiveThickness(const GeomDet *det, int16_t mode, - const edm::EventSetup &setup) const -{ - if (!det) return 0.; - double dZ = det->surface().bounds().thickness(); // it is a float only... + const edm::EventSetup &setup) const { + if (!det) + return 0.; + double dZ = det->surface().bounds().thickness(); // it is a float only... const SiStripDetId id(det->geographicalId()); edm::ESHandle backPlaneHandle; // FIXME: which one? DepRcd->get(handle) or Rcd->get(readoutModeName_, handle)?? // setup.get().get(backPlaneHandle); // get correct mode setup.get().get(readoutModeName_, backPlaneHandle); - const double bpCor = backPlaneHandle->getBackPlaneCorrection(id); // it's a float... + const double bpCor = backPlaneHandle->getBackPlaneCorrection(id); // it's a float... // std::cout << "bpCor " << bpCor << " in subdet " << id.subdetId() << std::endl; dZ *= (1. - bpCor); @@ -429,17 +406,14 @@ double SiStripLorentzAngleCalibration::effectiveThickness(const GeomDet *det, } //====================================================================== -const SiStripLorentzAngle* -SiStripLorentzAngleCalibration::getLorentzAnglesInput(const align::RunNumber& run) -{ - const auto& resolvedRun = run > 0 ? run : currentIOV_; +const SiStripLorentzAngle *SiStripLorentzAngleCalibration::getLorentzAnglesInput(const align::RunNumber &run) { + const auto &resolvedRun = run > 0 ? run : currentIOV_; // For parallel processing in Millepede II, create SiStripLorentzAngle // from info stored in files of parallel jobs and check that they are identical. // If this job has run on events, still check that LA is identical to the ones // from mergeFileNames_. - const std::string treeName{this->name()+"_"+readoutModeName_+"_input_"+ - std::to_string(resolvedRun)}; - for (const auto& iFile: mergeFileNames_) { + const std::string treeName{this->name() + "_" + readoutModeName_ + "_input_" + std::to_string(resolvedRun)}; + for (const auto &iFile : mergeFileNames_) { auto la = this->createFromTree(iFile.c_str(), treeName.c_str()); // siStripLorentzAngleInput_ could be non-null from previous file of this loop // or from checkLorentzAngleInput(..) when running on data in this job as well @@ -449,18 +423,16 @@ SiStripLorentzAngleCalibration::getLorentzAnglesInput(const align::RunNumber& ru currentIOV_ = resolvedRun; } else { // FIXME: about comparison of maps see comments in checkLorentzAngleInput - if (!la.getLorentzAngles().empty() && // single job might not have got events + if (!la.getLorentzAngles().empty() && // single job might not have got events la.getLorentzAngles() != siStripLorentzAngleInput_->getLorentzAngles()) { // Throw exception instead of error? edm::LogError("NoInput") << "@SUB=SiStripLorentzAngleCalibration::getLorentzAnglesInput" - << "Different input values from tree " << treeName - << " in file " << iFile << "."; - + << "Different input values from tree " << treeName << " in file " << iFile << "."; } } } - if (!siStripLorentzAngleInput_) { // no files nor ran on events + if (!siStripLorentzAngleInput_) { // no files nor ran on events // [] operator default-constructs an empty SiStripLorentzAngle object in place: siStripLorentzAngleInput_ = &(cachedLorentzAngleInputs_[resolvedRun]); currentIOV_ = resolvedRun; @@ -475,9 +447,7 @@ SiStripLorentzAngleCalibration::getLorentzAnglesInput(const align::RunNumber& ru } //====================================================================== -double SiStripLorentzAngleCalibration::getParameterForDetId(unsigned int detId, - edm::RunNumber_t run) const -{ +double SiStripLorentzAngleCalibration::getParameterForDetId(unsigned int detId, edm::RunNumber_t run) const { const int index = moduleGroupSelector_->getParameterIndexFromDetId(detId, run); return (index < 0 ? 0. : parameters_[index]); @@ -486,11 +456,11 @@ double SiStripLorentzAngleCalibration::getParameterForDetId(unsigned int detId, //====================================================================== void SiStripLorentzAngleCalibration::writeTree(const SiStripLorentzAngle *lorentzAngle, const std::map &treeInfo, - const char *treeName) const -{ - if (!lorentzAngle) return; + const char *treeName) const { + if (!lorentzAngle) + return; - TFile* file = TFile::Open(outFileName_.c_str(), "UPDATE"); + TFile *file = TFile::Open(outFileName_.c_str(), "UPDATE"); if (!file) { edm::LogError("BadConfig") << "@SUB=SiStripLorentzAngleCalibration::writeTree" << "Could not open file '" << outFileName_ << "'."; @@ -506,15 +476,16 @@ void SiStripLorentzAngleCalibration::writeTree(const SiStripLorentzAngle *lorent tree->Branch("treeStruct", &treeStruct, TreeStruct::LeafList()); for (auto iterIdValue = lorentzAngle->getLorentzAngles().begin(); - iterIdValue != lorentzAngle->getLorentzAngles().end(); ++iterIdValue) { + iterIdValue != lorentzAngle->getLorentzAngles().end(); + ++iterIdValue) { // type of (*iterIdValue) is pair - id = iterIdValue->first; // key of map is DetId + id = iterIdValue->first; // key of map is DetId value = iterIdValue->second; // type of (*treeStructIter) is pair - auto treeStructIter = treeInfo.find(id); // find info for this id + auto treeStructIter = treeInfo.find(id); // find info for this id if (treeStructIter != treeInfo.end()) { - treeStruct = treeStructIter->second; // info from input map - } else { // if none found, fill at least parameter index (using 1st IOV...) + treeStruct = treeStructIter->second; // info from input map + } else { // if none found, fill at least parameter index (using 1st IOV...) const cond::Time_t run1of1stIov = moduleGroupSelector_->firstRunOfIOV(0); const int ind = moduleGroupSelector_->getParameterIndexFromDetId(id, run1of1stIov); treeStruct = TreeStruct(ind); @@ -522,24 +493,23 @@ void SiStripLorentzAngleCalibration::writeTree(const SiStripLorentzAngle *lorent tree->Fill(); } tree->Write(); - delete file; // tree vanishes with the file... + delete file; // tree vanishes with the file... } //====================================================================== -SiStripLorentzAngle -SiStripLorentzAngleCalibration::createFromTree(const char *fileName, const char *treeName) const -{ +SiStripLorentzAngle SiStripLorentzAngleCalibration::createFromTree(const char *fileName, const char *treeName) const { // Check for file existence on your own to work around // https://hypernews.cern.ch/HyperNews/CMS/get/swDevelopment/2715.html: - TFile* file = nullptr; - FILE* testFile = fopen(fileName,"r"); + TFile *file = nullptr; + FILE *testFile = fopen(fileName, "r"); if (testFile) { fclose(testFile); file = TFile::Open(fileName, "READ"); - } // else not existing, see error below + } // else not existing, see error below TTree *tree = nullptr; - if (file) file->GetObject(treeName, tree); + if (file) + file->GetObject(treeName, tree); SiStripLorentzAngle result{}; if (tree) { @@ -553,22 +523,20 @@ SiStripLorentzAngleCalibration::createFromTree(const char *fileName, const char tree->GetEntry(iEntry); result.putLorentzAngle(id, value); } - } else { // Warning only since could be parallel job on no events. + } else { // Warning only since could be parallel job on no events. edm::LogWarning("Alignment") << "@SUB=SiStripLorentzAngleCalibration::createFromTree" - << "Could not get TTree '" << treeName << "' from file '" - << fileName << (file ? "'." : "' (file does not exist)."); + << "Could not get TTree '" << treeName << "' from file '" << fileName + << (file ? "'." : "' (file does not exist)."); } - delete file; // tree will vanish with file + delete file; // tree will vanish with file return result; } - //====================================================================== //====================================================================== // Plugin definition #include "Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h" -DEFINE_EDM_PLUGIN(IntegratedCalibrationPluginFactory, - SiStripLorentzAngleCalibration, "SiStripLorentzAngleCalibration"); +DEFINE_EDM_PLUGIN(IntegratedCalibrationPluginFactory, SiStripLorentzAngleCalibration, "SiStripLorentzAngleCalibration"); diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripReadoutModeEnums.h b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripReadoutModeEnums.h index 5930b2a85a402..735b156899ba7 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/SiStripReadoutModeEnums.h +++ b/Alignment/CommonAlignmentAlgorithm/plugins/SiStripReadoutModeEnums.h @@ -3,6 +3,6 @@ // SiStripLatency::singleReadOutMode() returns // 1: all in peak, 0: all in deco, -1: mixed state -enum {kDeconvolutionMode = 0, kPeakMode = 1}; +enum { kDeconvolutionMode = 0, kPeakMode = 1 }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/plugins/TreeStruct.h b/Alignment/CommonAlignmentAlgorithm/plugins/TreeStruct.h index 59887f05b1b1b..f99d6aac4ca15 100644 --- a/Alignment/CommonAlignmentAlgorithm/plugins/TreeStruct.h +++ b/Alignment/CommonAlignmentAlgorithm/plugins/TreeStruct.h @@ -3,18 +3,17 @@ /// structure to store algorithm results in a TTree -struct TreeStruct -{ +struct TreeStruct { TreeStruct() : delta(0.f), error(0.f), paramIndex(0) {} TreeStruct(int ind) : delta(0.f), error(0.f), paramIndex(ind) {} TreeStruct(float del, float err, int ind) : delta(del), error(err), paramIndex(ind) {} - + float delta; /// parameter from alignment algorithm (change wrt. start) float error; /// error from alignment algorithm - int paramIndex;/// internal param. index (same index => same delta) + int paramIndex; /// internal param. index (same index => same delta) /// List of leaves to pass as 3rd argument to TTree::Branch(...) if 2nd argument /// is a pointer to TreeStruct - keep in synch with data members above! - static const char* LeafList() {return "delta/F:error/F:paramIndex/I";} + static const char* LeafList() { return "delta/F:error/F:paramIndex/I"; } }; #endif diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignableDataIO.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignableDataIO.cc index 35939ede97e90..75501cbb3d439 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignableDataIO.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignableDataIO.cc @@ -7,213 +7,150 @@ #include "Alignment/CommonAlignmentAlgorithm/interface/AlignableDataIO.h" // ---------------------------------------------------------------------------- -AlignableAbsData AlignableDataIO::readAbsPos(Alignable* ali, int& ierr) -{ - return readAbsRaw(ali,ierr); -} - +AlignableAbsData AlignableDataIO::readAbsPos(Alignable* ali, int& ierr) { return readAbsRaw(ali, ierr); } // ---------------------------------------------------------------------------- -AlignableAbsData AlignableDataIO::readOrgPos(Alignable* ali, int& ierr) -{ - return readAbsRaw(ali,ierr); -} - +AlignableAbsData AlignableDataIO::readOrgPos(Alignable* ali, int& ierr) { return readAbsRaw(ali, ierr); } // ---------------------------------------------------------------------------- -AlignableRelData AlignableDataIO::readRelPos(Alignable* ali, int& ierr) -{ - return readRelRaw(ali,ierr); -} - +AlignableRelData AlignableDataIO::readRelPos(Alignable* ali, int& ierr) { return readRelRaw(ali, ierr); } // ---------------------------------------------------------------------------- -int AlignableDataIO::writeAbsPos(Alignable* ali, bool validCheck) -{ - - if ( !(validCheck) || ali->alignmentParameters()->isValid() ) - { - // position in global frame - align::PositionType pos = ali->surface().position(); - // global rotation - align::RotationType rot = ali->surface().rotation(); - // if a unit: store surface deformation (little kind of hack)... - std::vector pars; - if (ali->alignableObjectId() == align::AlignableDetUnit) { // only detunits have them - std::vector > result; - if (1 == ali->surfaceDeformationIdPairs(result)) { // might not have any... - pars = result[0].second->parameters(); - } +int AlignableDataIO::writeAbsPos(Alignable* ali, bool validCheck) { + if (!(validCheck) || ali->alignmentParameters()->isValid()) { + // position in global frame + align::PositionType pos = ali->surface().position(); + // global rotation + align::RotationType rot = ali->surface().rotation(); + // if a unit: store surface deformation (little kind of hack)... + std::vector pars; + if (ali->alignableObjectId() == align::AlignableDetUnit) { // only detunits have them + std::vector > result; + if (1 == ali->surfaceDeformationIdPairs(result)) { // might not have any... + pars = result[0].second->parameters(); } - - // write - return writeAbsRaw( - AlignableAbsData( pos,rot, - ali->id(), - ali->alignableObjectId(), - pars) - ); } + // write + return writeAbsRaw(AlignableAbsData(pos, rot, ali->id(), ali->alignableObjectId(), pars)); + } + return 1; } - // ---------------------------------------------------------------------------- -int AlignableDataIO::writeRelPos(Alignable* ali, bool validCheck) -{ - if ( !(validCheck) || ali->alignmentParameters()->isValid() ) - { - // rel. shift in global frame - const align::GlobalVector& pos = ali->displacement(); - // rel. rotation in global frame - align::RotationType rot = ali->rotation(); - // FIXME: should add something to store changes of surface deformations... - std::vector pars; - // write - return writeRelRaw(AlignableRelData(pos,rot,ali->id(), - ali->alignableObjectId(), pars)); - } +int AlignableDataIO::writeRelPos(Alignable* ali, bool validCheck) { + if (!(validCheck) || ali->alignmentParameters()->isValid()) { + // rel. shift in global frame + const align::GlobalVector& pos = ali->displacement(); + // rel. rotation in global frame + align::RotationType rot = ali->rotation(); + // FIXME: should add something to store changes of surface deformations... + std::vector pars; + // write + return writeRelRaw(AlignableRelData(pos, rot, ali->id(), ali->alignableObjectId(), pars)); + } return 1; } - // ---------------------------------------------------------------------------- -int AlignableDataIO::writeOrgPos(Alignable* ali, bool validCheck) -{ - if ( !(validCheck) || ali->alignmentParameters()->isValid() ) - { - // orig position - align::PositionType pos = ali->globalPosition() - ali->displacement(); - // orig rotation - align::RotationType rot = ali->globalRotation() * ali->rotation().transposed(); - // FIXME: should add something to store changes of surface deformations... - std::vector pars; - // write - return writeAbsRaw(AlignableAbsData(pos,rot,ali->id(), - ali->alignableObjectId(), pars)); - } +int AlignableDataIO::writeOrgPos(Alignable* ali, bool validCheck) { + if (!(validCheck) || ali->alignmentParameters()->isValid()) { + // orig position + align::PositionType pos = ali->globalPosition() - ali->displacement(); + // orig rotation + align::RotationType rot = ali->globalRotation() * ali->rotation().transposed(); + // FIXME: should add something to store changes of surface deformations... + std::vector pars; + // write + return writeAbsRaw(AlignableAbsData(pos, rot, ali->id(), ali->alignableObjectId(), pars)); + } return 1; } - // ---------------------------------------------------------------------------- -int AlignableDataIO::writeAbsPos(const align::Alignables& alivec, - bool validCheck) -{ - - int icount=0; - for( align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it ) - { - int iret = writeAbsPos(*it,validCheck); - if (iret==0) icount++; - } - LogDebug("WriteAbsPos") << "all,written: " << alivec.size() <<","<< icount; +int AlignableDataIO::writeAbsPos(const align::Alignables& alivec, bool validCheck) { + int icount = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + int iret = writeAbsPos(*it, validCheck); + if (iret == 0) + icount++; + } + LogDebug("WriteAbsPos") << "all,written: " << alivec.size() << "," << icount; return 0; - } - // ---------------------------------------------------------------------------- -AlignablePositions -AlignableDataIO::readAbsPos(const align::Alignables& alivec, int& ierr) -{ - +AlignablePositions AlignableDataIO::readAbsPos(const align::Alignables& alivec, int& ierr) { AlignablePositions retvec; - int ierr2=0; - ierr=0; - for( align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it ) - { - AlignableAbsData ad=readAbsPos(*it, ierr2); - if (ierr2==0) retvec.push_back(ad); - } - - LogDebug("ReadAbsPos") << "all,written: " << alivec.size() <<"," << retvec.size(); + int ierr2 = 0; + ierr = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + AlignableAbsData ad = readAbsPos(*it, ierr2); + if (ierr2 == 0) + retvec.push_back(ad); + } - return retvec; + LogDebug("ReadAbsPos") << "all,written: " << alivec.size() << "," << retvec.size(); + return retvec; } - // ---------------------------------------------------------------------------- -int AlignableDataIO::writeOrgPos( const align::Alignables& alivec, - bool validCheck ) -{ - - int icount=0; - for( align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it ) - { - int iret=writeOrgPos(*it,validCheck); - if (iret==0) icount++; - } - - LogDebug("WriteOrgPos") << "all,written: " << alivec.size() <<"," << icount; - return 0; +int AlignableDataIO::writeOrgPos(const align::Alignables& alivec, bool validCheck) { + int icount = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + int iret = writeOrgPos(*it, validCheck); + if (iret == 0) + icount++; + } + LogDebug("WriteOrgPos") << "all,written: " << alivec.size() << "," << icount; + return 0; } - // ---------------------------------------------------------------------------- -AlignablePositions -AlignableDataIO::readOrgPos(const align::Alignables& alivec, int& ierr) -{ - +AlignablePositions AlignableDataIO::readOrgPos(const align::Alignables& alivec, int& ierr) { AlignablePositions retvec; - int ierr2=0; - ierr=0; - for( align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it ) - { - AlignableAbsData ad=readOrgPos(*it, ierr2); - if (ierr2==0) retvec.push_back(ad); - } + int ierr2 = 0; + ierr = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + AlignableAbsData ad = readOrgPos(*it, ierr2); + if (ierr2 == 0) + retvec.push_back(ad); + } - LogDebug("ReadOrgPos") << "all,read: " << alivec.size() <<", "<< retvec.size(); + LogDebug("ReadOrgPos") << "all,read: " << alivec.size() << ", " << retvec.size(); return retvec; - } - // ---------------------------------------------------------------------------- -int AlignableDataIO::writeRelPos(const align::Alignables& alivec, - bool validCheck ) -{ - - int icount=0; - for( align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it ) { - int iret=writeRelPos(*it,validCheck); - if (iret==0) icount++; +int AlignableDataIO::writeRelPos(const align::Alignables& alivec, bool validCheck) { + int icount = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + int iret = writeRelPos(*it, validCheck); + if (iret == 0) + icount++; } - LogDebug("WriteRelPos") << "all,written: " << alivec.size() <<", "<< icount; + LogDebug("WriteRelPos") << "all,written: " << alivec.size() << ", " << icount; return 0; - } - // ---------------------------------------------------------------------------- -AlignableShifts -AlignableDataIO::readRelPos(const align::Alignables& alivec, int& ierr) -{ - +AlignableShifts AlignableDataIO::readRelPos(const align::Alignables& alivec, int& ierr) { AlignableShifts retvec; - int ierr2=0; - ierr=0; - for( align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it ) - { - AlignableRelData ad=readRelPos(*it, ierr2); - if (ierr2==0) retvec.push_back(ad); - } - LogDebug("ReadRelPos") << "all,read: " << alivec.size() <<", "<< retvec.size(); + int ierr2 = 0; + ierr = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + AlignableRelData ad = readRelPos(*it, ierr2); + if (ierr2 == 0) + retvec.push_back(ad); + } + LogDebug("ReadRelPos") << "all,read: " << alivec.size() << ", " << retvec.size(); return retvec; - } diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignableDataIORoot.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignableDataIORoot.cc index aa309e295be29..11237e42bb6e0 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignableDataIORoot.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignableDataIORoot.cc @@ -7,18 +7,14 @@ // ---------------------------------------------------------------------------- // constructor -AlignableDataIORoot::AlignableDataIORoot(PosType p) : - AlignableDataIO(p) -{ +AlignableDataIORoot::AlignableDataIORoot(PosType p) : AlignableDataIO(p) { if (thePosType == Abs) { treename = "AlignablesAbsPos"; treetxt = "Alignables abs.Pos"; - } - else if (thePosType == Org) { + } else if (thePosType == Org) { treename = "AlignablesOrgPos"; treetxt = "Alignables org.Pos"; - } - else if (thePosType == Rel) { + } else if (thePosType == Rel) { treename = "AlignablesRelPos"; treetxt = "Alignables rel.Pos"; } @@ -27,68 +23,72 @@ AlignableDataIORoot::AlignableDataIORoot(PosType p) : // ---------------------------------------------------------------------------- // create root tree branches (for writing) -void AlignableDataIORoot::createBranches(void) -{ - tree->Branch("Id", &Id, "Id/i"); +void AlignableDataIORoot::createBranches(void) { + tree->Branch("Id", &Id, "Id/i"); tree->Branch("ObjId", &ObjId, "ObjId/I"); - tree->Branch("Pos", &Pos, "Pos[3]/D"); - tree->Branch("Rot", &Rot, "Rot[9]/D"); + tree->Branch("Pos", &Pos, "Pos[3]/D"); + tree->Branch("Rot", &Rot, "Rot[9]/D"); - tree->Branch("NumDeform", &numDeformationValues_, "NumDeform/i"); - tree->Branch("DeformValues", deformationValues_, "DeformValues[NumDeform]/F"); + tree->Branch("NumDeform", &numDeformationValues_, "NumDeform/i"); + tree->Branch("DeformValues", deformationValues_, "DeformValues[NumDeform]/F"); } // ---------------------------------------------------------------------------- // set root tree branch addresses (for reading) -void AlignableDataIORoot::setBranchAddresses(void) -{ - tree->SetBranchAddress("Id", &Id); +void AlignableDataIORoot::setBranchAddresses(void) { + tree->SetBranchAddress("Id", &Id); tree->SetBranchAddress("ObjId", &ObjId); - tree->SetBranchAddress("Pos", &Pos); - tree->SetBranchAddress("Rot", &Rot); + tree->SetBranchAddress("Pos", &Pos); + tree->SetBranchAddress("Rot", &Rot); - tree->SetBranchAddress("NumDeform", &numDeformationValues_); + tree->SetBranchAddress("NumDeform", &numDeformationValues_); tree->SetBranchAddress("DeformValues", deformationValues_); } // ---------------------------------------------------------------------------- // find root tree entry based on IDs -int AlignableDataIORoot::findEntry(align::ID id, align::StructureType comp) -{ - if (newopen) { // we're here first time +int AlignableDataIORoot::findEntry(align::ID id, align::StructureType comp) { + if (newopen) { // we're here first time edm::LogInfo("Alignment") << "@SUB=AlignableDataIORoot::findEntry" << "Filling map ..."; - treemap.erase(treemap.begin(),treemap.end()); - for (int ev = 0;evGetEntries();ev++) { - tree->GetEntry(ev); - treemap[ std::make_pair(Id,ObjId) ] = ev; + treemap.erase(treemap.begin(), treemap.end()); + for (int ev = 0; ev < tree->GetEntries(); ev++) { + tree->GetEntry(ev); + treemap[std::make_pair(Id, ObjId)] = ev; } - newopen=false; + newopen = false; } - + // now we have filled the map - treemaptype::iterator imap = treemap.find( std::make_pair(id,comp) ); - int result=-1; - if (imap != treemap.end()) result=(*imap).second; + treemaptype::iterator imap = treemap.find(std::make_pair(id, comp)); + int result = -1; + if (imap != treemap.end()) + result = (*imap).second; return result; - } // ---------------------------------------------------------------------------- -int AlignableDataIORoot::writeAbsRaw(const AlignableAbsData &ad) -{ +int AlignableDataIORoot::writeAbsRaw(const AlignableAbsData& ad) { const align::GlobalPoint& pos = ad.pos(); align::RotationType rot = ad.rot(); Id = ad.id(); ObjId = ad.objId(); - Pos[0]=pos.x(); Pos[1]=pos.y(); Pos[2]=pos.z(); - Rot[0]=rot.xx(); Rot[1]=rot.xy(); Rot[2]=rot.xz(); - Rot[3]=rot.yx(); Rot[4]=rot.yy(); Rot[5]=rot.yz(); - Rot[6]=rot.zx(); Rot[7]=rot.zy(); Rot[8]=rot.zz(); - - const std::vector &deformPars = ad.deformationParameters(); + Pos[0] = pos.x(); + Pos[1] = pos.y(); + Pos[2] = pos.z(); + Rot[0] = rot.xx(); + Rot[1] = rot.xy(); + Rot[2] = rot.xz(); + Rot[3] = rot.yx(); + Rot[4] = rot.yy(); + Rot[5] = rot.yz(); + Rot[6] = rot.zx(); + Rot[7] = rot.zy(); + Rot[8] = rot.zz(); + + const std::vector& deformPars = ad.deformationParameters(); numDeformationValues_ = (deformPars.size() > kMaxNumPar ? kMaxNumPar : deformPars.size()); for (unsigned int i = 0; i < numDeformationValues_; ++i) { deformationValues_[i] = deformPars[i]; @@ -99,18 +99,25 @@ int AlignableDataIORoot::writeAbsRaw(const AlignableAbsData &ad) } // ---------------------------------------------------------------------------- -int AlignableDataIORoot::writeRelRaw(const AlignableRelData &ad) -{ +int AlignableDataIORoot::writeRelRaw(const AlignableRelData& ad) { const align::GlobalVector& pos = ad.pos(); align::RotationType rot = ad.rot(); Id = ad.id(); ObjId = ad.objId(); - Pos[0]=pos.x(); Pos[1]=pos.y(); Pos[2]=pos.z(); - Rot[0]=rot.xx(); Rot[1]=rot.xy(); Rot[2]=rot.xz(); - Rot[3]=rot.yx(); Rot[4]=rot.yy(); Rot[5]=rot.yz(); - Rot[6]=rot.zx(); Rot[7]=rot.zy(); Rot[8]=rot.zz(); - - const std::vector &deformPars = ad.deformationParameters(); + Pos[0] = pos.x(); + Pos[1] = pos.y(); + Pos[2] = pos.z(); + Rot[0] = rot.xx(); + Rot[1] = rot.xy(); + Rot[2] = rot.xz(); + Rot[3] = rot.yx(); + Rot[4] = rot.yy(); + Rot[5] = rot.yz(); + Rot[6] = rot.zx(); + Rot[7] = rot.zy(); + Rot[8] = rot.zz(); + + const std::vector& deformPars = ad.deformationParameters(); numDeformationValues_ = (deformPars.size() > kMaxNumPar ? kMaxNumPar : deformPars.size()); for (unsigned int i = 0; i < numDeformationValues_; ++i) { deformationValues_[i] = deformPars[i]; @@ -121,62 +128,58 @@ int AlignableDataIORoot::writeRelRaw(const AlignableRelData &ad) } // ---------------------------------------------------------------------------- -AlignableAbsData AlignableDataIORoot::readAbsRaw(Alignable* ali,int& ierr) -{ +AlignableAbsData AlignableDataIORoot::readAbsRaw(Alignable* ali, int& ierr) { align::GlobalPoint pos; align::RotationType rot; align::StructureType typeId = ali->alignableObjectId(); align::ID id = ali->id(); - std::vector deformPars; deformPars.reserve(numDeformationValues_); - int entry = findEntry(id,typeId); - if(entry!=-1) { + std::vector deformPars; + deformPars.reserve(numDeformationValues_); + int entry = findEntry(id, typeId); + if (entry != -1) { tree->GetEntry(entry); - align::GlobalPoint pos2(Pos[0],Pos[1],Pos[2]); - align::RotationType rot2(Rot[0],Rot[1],Rot[2], - Rot[3],Rot[4],Rot[5], - Rot[6],Rot[7],Rot[8]); - pos=pos2; - rot=rot2; + align::GlobalPoint pos2(Pos[0], Pos[1], Pos[2]); + align::RotationType rot2(Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8]); + pos = pos2; + rot = rot2; for (unsigned int i = 0; i < numDeformationValues_; ++i) { deformPars.push_back((double)deformationValues_[i]); } - ierr=0; - } - else ierr=-1; + ierr = 0; + } else + ierr = -1; - return AlignableAbsData(pos,rot,id,typeId,deformPars); + return AlignableAbsData(pos, rot, id, typeId, deformPars); } // ---------------------------------------------------------------------------- -AlignableRelData AlignableDataIORoot::readRelRaw(Alignable* ali,int& ierr) -{ +AlignableRelData AlignableDataIORoot::readRelRaw(Alignable* ali, int& ierr) { align::GlobalVector pos; align::RotationType rot; align::StructureType typeId = ali->alignableObjectId(); align::ID id = ali->id(); - std::vector deformPars; deformPars.reserve(numDeformationValues_); - int entry = findEntry(id,typeId); - if(entry!=-1) { + std::vector deformPars; + deformPars.reserve(numDeformationValues_); + int entry = findEntry(id, typeId); + if (entry != -1) { tree->GetEntry(entry); - align::GlobalVector pos2(Pos[0],Pos[1],Pos[2]); - align::RotationType rot2(Rot[0],Rot[1],Rot[2], - Rot[3],Rot[4],Rot[5], - Rot[6],Rot[7],Rot[8]); - pos=pos2; - rot=rot2; + align::GlobalVector pos2(Pos[0], Pos[1], Pos[2]); + align::RotationType rot2(Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8]); + pos = pos2; + rot = rot2; for (unsigned int i = 0; i < numDeformationValues_; ++i) { deformPars.push_back((double)deformationValues_[i]); } - ierr=0; - } - else ierr=-1; + ierr = 0; + } else + ierr = -1; - return AlignableRelData(pos,rot,id,typeId,deformPars); + return AlignableRelData(pos, rot, id, typeId, deformPars); } diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentAlgorithmPluginFactory.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentAlgorithmPluginFactory.cc index a1e9ce05c34eb..d0f27df02dded 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentAlgorithmPluginFactory.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentAlgorithmPluginFactory.cc @@ -3,11 +3,7 @@ /// \author F. Ronga - CERN /// - #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentAlgorithmPluginFactory.h" // #include "FWCore/ParameterSet/interface/ParameterSet.h" -EDM_REGISTER_PLUGINFACTORY( AlignmentAlgorithmPluginFactory, - "AlignmentAlgorithmPluginFactory" ); - - +EDM_REGISTER_PLUGINFACTORY(AlignmentAlgorithmPluginFactory, "AlignmentAlgorithmPluginFactory"); diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentCorrelationsIORoot.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentCorrelationsIORoot.cc index f155e1e5d7ed7..5360d20f1b060 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentCorrelationsIORoot.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentCorrelationsIORoot.cc @@ -10,112 +10,99 @@ // ---------------------------------------------------------------------------- // constructor -AlignmentCorrelationsIORoot::AlignmentCorrelationsIORoot() -{ +AlignmentCorrelationsIORoot::AlignmentCorrelationsIORoot() { treename = "AlignmentCorrelations"; treetxt = "Correlations"; } // ---------------------------------------------------------------------------- -void AlignmentCorrelationsIORoot::createBranches(void) -{ - tree->Branch("Ali1Id", &Ali1Id, "Ali1Id/i"); - tree->Branch("Ali2Id", &Ali2Id, "Ali2Id/i"); +void AlignmentCorrelationsIORoot::createBranches(void) { + tree->Branch("Ali1Id", &Ali1Id, "Ali1Id/i"); + tree->Branch("Ali2Id", &Ali2Id, "Ali2Id/i"); tree->Branch("Ali1ObjId", &Ali1ObjId, "Ali1ObjId/I"); tree->Branch("Ali2ObjId", &Ali2ObjId, "Ali2ObjId/I"); - tree->Branch("corSize", &corSize, "corSize/I"); + tree->Branch("corSize", &corSize, "corSize/I"); tree->Branch("CorMatrix", &CorMatrix, "CorMatrix[corSize]/D"); } // ---------------------------------------------------------------------------- -void AlignmentCorrelationsIORoot::setBranchAddresses(void) -{ - tree->SetBranchAddress("corSize", &corSize); - tree->SetBranchAddress("Ali1Id", &Ali1Id); - tree->SetBranchAddress("Ali2Id", &Ali2Id); +void AlignmentCorrelationsIORoot::setBranchAddresses(void) { + tree->SetBranchAddress("corSize", &corSize); + tree->SetBranchAddress("Ali1Id", &Ali1Id); + tree->SetBranchAddress("Ali2Id", &Ali2Id); tree->SetBranchAddress("Ali1ObjId", &Ali1ObjId); - tree->SetBranchAddress("Ali2ObjId", &Ali2ObjId); + tree->SetBranchAddress("Ali2ObjId", &Ali2ObjId); tree->SetBranchAddress("CorMatrix", &CorMatrix); } // ---------------------------------------------------------------------------- -int AlignmentCorrelationsIORoot::write(const align::Correlations& cor, bool validCheck) -{ - int icount=0; +int AlignmentCorrelationsIORoot::write(const align::Correlations& cor, bool validCheck) { + int icount = 0; - for(align::Correlations::const_iterator it=cor.begin(); - it!=cor.end();++it) { - AlgebraicMatrix mat=(*it).second; - std::pair Pair = (*it).first; + for (align::Correlations::const_iterator it = cor.begin(); it != cor.end(); ++it) { + AlgebraicMatrix mat = (*it).second; + std::pair Pair = (*it).first; Alignable* ali1 = Pair.first; Alignable* ali2 = Pair.second; - if( (ali1->alignmentParameters()->isValid() - && ali2->alignmentParameters()->isValid()) || !(validCheck)) { - Ali1ObjId = ali1->alignableObjectId(); - Ali2ObjId = ali2->alignableObjectId(); + if ((ali1->alignmentParameters()->isValid() && ali2->alignmentParameters()->isValid()) || !(validCheck)) { + Ali1ObjId = ali1->alignableObjectId(); + Ali2ObjId = ali2->alignableObjectId(); Ali1Id = ali1->id(); Ali2Id = ali2->id(); int maxColumn = mat.num_row(); - corSize = maxColumn*maxColumn; - for(int row = 0;rowFill(); icount++; } } - edm::LogInfo("AlignmentCorrelationsIORoot") << "Writing correlations: all,written: " - << cor.size() << "," << icount; + edm::LogInfo("AlignmentCorrelationsIORoot") << "Writing correlations: all,written: " << cor.size() << "," << icount; return 0; } // ---------------------------------------------------------------------------- // read correlations for those alignables in vector given as argument -align::Correlations -AlignmentCorrelationsIORoot::read(const align::Alignables& alivec, int& ierr) -{ +align::Correlations AlignmentCorrelationsIORoot::read(const align::Alignables& alivec, int& ierr) { align::Correlations theMap; // create ID map for all Alignables in alivec align::Alignables::const_iterator it1; - std::map< std::pair, Alignable* > idAlis; - for( it1=alivec.begin();it1!=alivec.end();++it1 ) - idAlis[std::make_pair((*it1)->id(),(*it1)->alignableObjectId())] = (*it1); + std::map, Alignable*> idAlis; + for (it1 = alivec.begin(); it1 != alivec.end(); ++it1) + idAlis[std::make_pair((*it1)->id(), (*it1)->alignableObjectId())] = (*it1); - std::map,Alignable*>::const_iterator aliSearch1; - std::map,Alignable*>::const_iterator aliSearch2; - int nfound=0; + std::map, Alignable*>::const_iterator aliSearch1; + std::map, Alignable*>::const_iterator aliSearch2; + int nfound = 0; double maxEntry = tree->GetEntries(); - for( int entry = 0;entryGetEntry(entry); - aliSearch1 = idAlis.find(std::make_pair(Ali1Id,Ali1ObjId)); - aliSearch2 = idAlis.find(std::make_pair(Ali2Id,Ali2ObjId)); - if (aliSearch1!=idAlis.end() - && aliSearch2!=idAlis.end()) - { - // Alignables for this pair found - nfound++; - Alignable* myAli1 = (*aliSearch1).second; - Alignable* myAli2 = (*aliSearch2).second; - // FIXME: instead of nParMax in the next few lines one should probably - // use something like sqrt(corSize) - but take care of rounding! - // I have no time to test... :-( GF - AlgebraicMatrix mat(nParMax,nParMax); - for(int row = 0;rowGetEntry(entry); + aliSearch1 = idAlis.find(std::make_pair(Ali1Id, Ali1ObjId)); + aliSearch2 = idAlis.find(std::make_pair(Ali2Id, Ali2ObjId)); + if (aliSearch1 != idAlis.end() && aliSearch2 != idAlis.end()) { + // Alignables for this pair found + nfound++; + Alignable* myAli1 = (*aliSearch1).second; + Alignable* myAli2 = (*aliSearch2).second; + // FIXME: instead of nParMax in the next few lines one should probably + // use something like sqrt(corSize) - but take care of rounding! + // I have no time to test... :-( GF + AlgebraicMatrix mat(nParMax, nParMax); + for (int row = 0; row < nParMax; row++) + for (int col = 0; col < nParMax; col++) + mat[row][col] = CorMatrix[row + col * nParMax]; + theMap[std::make_pair(myAli1, myAli2)] = mat; + } + } + + edm::LogInfo("AlignmentCorrelationsIORoot") << "Read correlations: all,read: " << alivec.size() << "," << nfound; + + ierr = 0; return theMap; } diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentCorrelationsStore.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentCorrelationsStore.cc index 303d0b2ea3b00..5c597a75e37bf 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentCorrelationsStore.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentCorrelationsStore.cc @@ -4,50 +4,42 @@ #include "Alignment/CommonAlignment/interface/AlignmentParameters.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" - -AlignmentCorrelationsStore::AlignmentCorrelationsStore( void ) -{ +AlignmentCorrelationsStore::AlignmentCorrelationsStore(void) { edm::LogInfo("Alignment") << "@SUB=AlignmentCorrelationsStore::AlignmentCorrelationsStore " << "\nCreated."; } - -void AlignmentCorrelationsStore::correlations( Alignable* ap1, Alignable* ap2, - AlgebraicSymMatrix& cov, int row, int col ) const -{ +void AlignmentCorrelationsStore::correlations( + Alignable* ap1, Alignable* ap2, AlgebraicSymMatrix& cov, int row, int col) const { static Alignable* previousAlignable = nullptr; static CorrelationsTable* previousCorrelations; // Needed by 'resetCorrelations()' to reset the static pointer: - if ( ap1 == nullptr ) { previousAlignable = nullptr; return; } - - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); - - if ( ap1 == previousAlignable ) - { - CorrelationsTable::const_iterator itC2 = previousCorrelations->find( ap2 ); - if ( itC2 != previousCorrelations->end() ) - { - transpose ? - fillCovarianceT( ap1, ap2, (*itC2).second, cov, row, col ) : - fillCovariance( ap1, ap2, (*itC2).second, cov, row, col ); - } + if (ap1 == nullptr) { + previousAlignable = nullptr; + return; } - else - { - Correlations::const_iterator itC1 = theCorrelations.find( ap1 ); - if ( itC1 != theCorrelations.end() ) - { + + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); + + if (ap1 == previousAlignable) { + CorrelationsTable::const_iterator itC2 = previousCorrelations->find(ap2); + if (itC2 != previousCorrelations->end()) { + transpose ? fillCovarianceT(ap1, ap2, (*itC2).second, cov, row, col) + : fillCovariance(ap1, ap2, (*itC2).second, cov, row, col); + } + } else { + Correlations::const_iterator itC1 = theCorrelations.find(ap1); + if (itC1 != theCorrelations.end()) { previousAlignable = ap1; previousCorrelations = (*itC1).second; - CorrelationsTable::const_iterator itC2 = (*itC1).second->find( ap2 ); - if ( itC2 != (*itC1).second->end() ) - { - transpose ? - fillCovarianceT( ap1, ap2, (*itC2).second, cov, row, col ) : - fillCovariance( ap1, ap2, (*itC2).second, cov, row, col ); + CorrelationsTable::const_iterator itC2 = (*itC1).second->find(ap2); + if (itC2 != (*itC1).second->end()) { + transpose ? fillCovarianceT(ap1, ap2, (*itC2).second, cov, row, col) + : fillCovariance(ap1, ap2, (*itC2).second, cov, row, col); } } } @@ -56,36 +48,32 @@ void AlignmentCorrelationsStore::correlations( Alignable* ap1, Alignable* ap2, return; } - -void AlignmentCorrelationsStore::setCorrelations( Alignable* ap1, Alignable* ap2, - const AlgebraicSymMatrix& cov, int row, int col ) -{ +void AlignmentCorrelationsStore::setCorrelations( + Alignable* ap1, Alignable* ap2, const AlgebraicSymMatrix& cov, int row, int col) { static Alignable* previousAlignable = nullptr; static CorrelationsTable* previousCorrelations; // Needed by 'resetCorrelations()' to reset the static pointer: - if ( ap1 == nullptr ) { previousAlignable = nullptr; return; } + if (ap1 == nullptr) { + previousAlignable = nullptr; + return; + } - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); - if ( ap1 == previousAlignable ) - { - fillCorrelationsTable( ap1, ap2, previousCorrelations, cov, row, col, transpose ); - } - else - { - Correlations::iterator itC = theCorrelations.find( ap1 ); - if ( itC != theCorrelations.end() ) - { - fillCorrelationsTable( ap1, ap2, itC->second, cov, row, col, transpose ); + if (ap1 == previousAlignable) { + fillCorrelationsTable(ap1, ap2, previousCorrelations, cov, row, col, transpose); + } else { + Correlations::iterator itC = theCorrelations.find(ap1); + if (itC != theCorrelations.end()) { + fillCorrelationsTable(ap1, ap2, itC->second, cov, row, col, transpose); previousAlignable = ap1; previousCorrelations = itC->second; - } - else - { + } else { CorrelationsTable* newTable = new CorrelationsTable; - fillCorrelationsTable( ap1, ap2, newTable, cov, row, col, transpose ); + fillCorrelationsTable(ap1, ap2, newTable, cov, row, col, transpose); theCorrelations[ap1] = newTable; previousAlignable = ap1; @@ -94,139 +82,116 @@ void AlignmentCorrelationsStore::setCorrelations( Alignable* ap1, Alignable* ap2 } } +void AlignmentCorrelationsStore::setCorrelations(Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat) { + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); -void AlignmentCorrelationsStore::setCorrelations( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat ) -{ - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); - - Correlations::iterator itC1 = theCorrelations.find( ap1 ); - if ( itC1 != theCorrelations.end() ) - { + Correlations::iterator itC1 = theCorrelations.find(ap1); + if (itC1 != theCorrelations.end()) { (*itC1->second)[ap2] = transpose ? mat.T() : mat; - } - else - { + } else { CorrelationsTable* newTable = new CorrelationsTable; (*newTable)[ap2] = transpose ? mat.T() : mat; theCorrelations[ap1] = newTable; } } +bool AlignmentCorrelationsStore::correlationsAvailable(Alignable* ap1, Alignable* ap2) const { + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); -bool AlignmentCorrelationsStore::correlationsAvailable( Alignable* ap1, Alignable* ap2 ) const -{ - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); - - Correlations::const_iterator itC1 = theCorrelations.find( ap1 ); - if ( itC1 != theCorrelations.end() ) - { - CorrelationsTable::const_iterator itC2 = itC1->second->find( ap2 ); - if ( itC2 != itC1->second->end() ) return true; + Correlations::const_iterator itC1 = theCorrelations.find(ap1); + if (itC1 != theCorrelations.end()) { + CorrelationsTable::const_iterator itC2 = itC1->second->find(ap2); + if (itC2 != itC1->second->end()) + return true; } return false; } - -void AlignmentCorrelationsStore::resetCorrelations( void ) -{ +void AlignmentCorrelationsStore::resetCorrelations(void) { Correlations::iterator itC; - for ( itC = theCorrelations.begin(); itC != theCorrelations.end(); ++itC ) delete (*itC).second; - theCorrelations.erase( theCorrelations.begin(), theCorrelations.end() ); + for (itC = theCorrelations.begin(); itC != theCorrelations.end(); ++itC) + delete (*itC).second; + theCorrelations.erase(theCorrelations.begin(), theCorrelations.end()); // Reset the static pointers to the 'previous alignables' AlgebraicSymMatrix dummy; - correlations( nullptr, nullptr, dummy, 0, 0 ); - setCorrelations( nullptr, nullptr, dummy, 0, 0 ); + correlations(nullptr, nullptr, dummy, 0, 0); + setCorrelations(nullptr, nullptr, dummy, 0, 0); } - -unsigned int AlignmentCorrelationsStore::size( void ) const -{ +unsigned int AlignmentCorrelationsStore::size(void) const { unsigned int size = 0; Correlations::const_iterator itC; - for ( itC = theCorrelations.begin(); itC != theCorrelations.end(); ++itC ) + for (itC = theCorrelations.begin(); itC != theCorrelations.end(); ++itC) size += itC->second->size(); return size; } - -void -AlignmentCorrelationsStore::fillCorrelationsTable( Alignable* ap1, Alignable* ap2, CorrelationsTable* table, - const AlgebraicSymMatrix& cov, int row, int col, bool transpose ) -{ - CorrelationsTable::iterator itC = table->find( ap2 ); - - if ( itC != table->end() ) - { - transpose ? - readFromCovarianceT( ap1, ap2, itC->second, cov, row, col ) : - readFromCovariance( ap1, ap2, itC->second, cov, row, col ); - } - else - { +void AlignmentCorrelationsStore::fillCorrelationsTable(Alignable* ap1, + Alignable* ap2, + CorrelationsTable* table, + const AlgebraicSymMatrix& cov, + int row, + int col, + bool transpose) { + CorrelationsTable::iterator itC = table->find(ap2); + + if (itC != table->end()) { + transpose ? readFromCovarianceT(ap1, ap2, itC->second, cov, row, col) + : readFromCovariance(ap1, ap2, itC->second, cov, row, col); + } else { int nRow = ap1->alignmentParameters()->numSelected(); int nCol = ap2->alignmentParameters()->numSelected(); - AlgebraicMatrix newEntry( nRow, nCol ); + AlgebraicMatrix newEntry(nRow, nCol); - transpose ? - readFromCovarianceT( ap1, ap2, newEntry, cov, row, col ) : - readFromCovariance( ap1, ap2, newEntry, cov, row, col ); + transpose ? readFromCovarianceT(ap1, ap2, newEntry, cov, row, col) + : readFromCovariance(ap1, ap2, newEntry, cov, row, col); (*table)[ap2] = newEntry; } } - -void -AlignmentCorrelationsStore::fillCovariance( Alignable* ap1, Alignable* ap2, const AlgebraicMatrix& entry, - AlgebraicSymMatrix& cov, int row, int col ) const -{ +void AlignmentCorrelationsStore::fillCovariance( + Alignable* ap1, Alignable* ap2, const AlgebraicMatrix& entry, AlgebraicSymMatrix& cov, int row, int col) const { int nRow = entry.num_row(); int nCol = entry.num_col(); - for ( int iRow = 0; iRow < nRow; ++iRow ) - for ( int jCol = 0; jCol < nCol; ++jCol ) - cov[row+iRow][col+jCol] = entry[iRow][jCol]; + for (int iRow = 0; iRow < nRow; ++iRow) + for (int jCol = 0; jCol < nCol; ++jCol) + cov[row + iRow][col + jCol] = entry[iRow][jCol]; } - -void -AlignmentCorrelationsStore::fillCovarianceT( Alignable* ap1, Alignable* ap2, const AlgebraicMatrix& entry, - AlgebraicSymMatrix& cov, int row, int col ) const -{ +void AlignmentCorrelationsStore::fillCovarianceT( + Alignable* ap1, Alignable* ap2, const AlgebraicMatrix& entry, AlgebraicSymMatrix& cov, int row, int col) const { int nRow = entry.num_row(); int nCol = entry.num_col(); - for ( int iRow = 0; iRow < nRow; ++iRow ) - for ( int jCol = 0; jCol < nCol; ++jCol ) - cov[row+jCol][col+iRow] = entry[iRow][jCol]; + for (int iRow = 0; iRow < nRow; ++iRow) + for (int jCol = 0; jCol < nCol; ++jCol) + cov[row + jCol][col + iRow] = entry[iRow][jCol]; } - -void -AlignmentCorrelationsStore::readFromCovariance( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& entry, - const AlgebraicSymMatrix& cov, int row, int col ) -{ +void AlignmentCorrelationsStore::readFromCovariance( + Alignable* ap1, Alignable* ap2, AlgebraicMatrix& entry, const AlgebraicSymMatrix& cov, int row, int col) { int nRow = entry.num_row(); int nCol = entry.num_col(); - for ( int iRow = 0; iRow < nRow; ++iRow ) - for ( int jCol = 0; jCol < nCol; ++jCol ) - entry[iRow][jCol] = cov[row+iRow][col+jCol]; + for (int iRow = 0; iRow < nRow; ++iRow) + for (int jCol = 0; jCol < nCol; ++jCol) + entry[iRow][jCol] = cov[row + iRow][col + jCol]; } - -void -AlignmentCorrelationsStore::readFromCovarianceT( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& entry, - const AlgebraicSymMatrix& cov, int row, int col ) -{ +void AlignmentCorrelationsStore::readFromCovarianceT( + Alignable* ap1, Alignable* ap2, AlgebraicMatrix& entry, const AlgebraicSymMatrix& cov, int row, int col) { int nRow = entry.num_row(); int nCol = entry.num_col(); - for ( int iRow = 0; iRow < nRow; ++iRow ) - for ( int jCol = 0; jCol < nCol; ++jCol ) - entry[iRow][jCol] = cov[row+jCol][col+iRow]; + for (int iRow = 0; iRow < nRow; ++iRow) + for (int jCol = 0; jCol < nCol; ++jCol) + entry[iRow][jCol] = cov[row + jCol][col + iRow]; } diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsEntry.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsEntry.cc index ab1d9eaa2772d..7c2196f9b836b 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsEntry.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsEntry.cc @@ -1,64 +1,49 @@ #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsEntry.h" - -AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry( void ) : -// theCounter( 0 ), - theNRows( 0 ), - theNCols( 0 ) -{} - - -AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry( short unsigned int nRows, - short unsigned int nCols ) : -// theCounter( 0 ), - theNRows( nRows ), - theNCols( nCols ), - theData( nRows*nCols ) -{} - - -AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry( short unsigned int nRows, - short unsigned int nCols, - const float init ) : -// theCounter( 0 ), - theNRows( nRows ), - theNCols( nCols ), - theData( nRows*nCols, init ) -{} - - -AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry( const AlgebraicMatrix& mat ) : -// theCounter( 0 ), - theNRows( mat.num_row() ), - theNCols( mat.num_col() ), - theData( mat.num_row()*mat.num_col() ) -{ - for ( int i = 0; i < mat.num_row(); ++i ) - { - for ( int j = 0; j < mat.num_col(); ++j ) - { - theData[i*theNCols+j] = mat[i][j]; +AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry(void) + : // theCounter( 0 ), + theNRows(0), + theNCols(0) {} + +AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry(short unsigned int nRows, + short unsigned int nCols) + : // theCounter( 0 ), + theNRows(nRows), + theNCols(nCols), + theData(nRows * nCols) {} + +AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry(short unsigned int nRows, + short unsigned int nCols, + const float init) + : // theCounter( 0 ), + theNRows(nRows), + theNCols(nCols), + theData(nRows * nCols, init) {} + +AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry(const AlgebraicMatrix& mat) + : // theCounter( 0 ), + theNRows(mat.num_row()), + theNCols(mat.num_col()), + theData(mat.num_row() * mat.num_col()) { + for (int i = 0; i < mat.num_row(); ++i) { + for (int j = 0; j < mat.num_col(); ++j) { + theData[i * theNCols + j] = mat[i][j]; } } } - -void AlignmentExtendedCorrelationsEntry::operator*=( const float multiply ) -{ - for ( std::vector< float >::iterator it = theData.begin(); it != theData.end(); ++it ) (*it) *= multiply; +void AlignmentExtendedCorrelationsEntry::operator*=(const float multiply) { + for (std::vector::iterator it = theData.begin(); it != theData.end(); ++it) + (*it) *= multiply; } +AlgebraicMatrix AlignmentExtendedCorrelationsEntry::matrix(void) const { + AlgebraicMatrix result(theNRows, theNCols); -AlgebraicMatrix AlignmentExtendedCorrelationsEntry::matrix( void ) const -{ - AlgebraicMatrix result( theNRows, theNCols ); - - for ( int i = 0; i < theNRows; ++i ) - { - for ( int j = 0; j < theNCols; ++j ) - { - result[i][j] = theData[i*theNCols+j]; + for (int i = 0; i < theNRows; ++i) { + for (int j = 0; j < theNCols; ++j) { + result[i][j] = theData[i * theNCols + j]; } } diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsStore.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsStore.cc index d1f5d65742e8c..265d1f29b8adf 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsStore.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsStore.cc @@ -8,54 +8,46 @@ #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/Utilities/interface/isFinite.h" - -AlignmentExtendedCorrelationsStore::AlignmentExtendedCorrelationsStore( const edm::ParameterSet& config ) -{ - theMaxUpdates = config.getParameter( "MaxUpdates" ); - theCut = config.getParameter( "CutValue" ); - theWeight = config.getParameter( "Weight" ); +AlignmentExtendedCorrelationsStore::AlignmentExtendedCorrelationsStore(const edm::ParameterSet& config) { + theMaxUpdates = config.getParameter("MaxUpdates"); + theCut = config.getParameter("CutValue"); + theWeight = config.getParameter("Weight"); edm::LogInfo("Alignment") << "@SUB=AlignmentExtendedCorrelationsStore::AlignmentExtendedCorrelationsStore" << "Created."; } - -void AlignmentExtendedCorrelationsStore::correlations( Alignable* ap1, Alignable* ap2, - AlgebraicSymMatrix& cov, int row, int col ) const -{ +void AlignmentExtendedCorrelationsStore::correlations( + Alignable* ap1, Alignable* ap2, AlgebraicSymMatrix& cov, int row, int col) const { static Alignable* previousAlignable = nullptr; static ExtendedCorrelationsTable* previousCorrelations; // Needed by 'resetCorrelations()' to reset the static pointer: - if ( ap1 == nullptr ) { previousAlignable = nullptr; return; } - - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); - - if ( ap1 == previousAlignable ) - { - ExtendedCorrelationsTable::const_iterator itC2 = previousCorrelations->find( ap2 ); - if ( itC2 != previousCorrelations->end() ) - { - transpose ? - fillCovarianceT( ap1, ap2, (*itC2).second, cov, row, col ) : - fillCovariance( ap1, ap2, (*itC2).second, cov, row, col ); - } + if (ap1 == nullptr) { + previousAlignable = nullptr; + return; } - else - { - ExtendedCorrelations::const_iterator itC1 = theCorrelations.find( ap1 ); - if ( itC1 != theCorrelations.end() ) - { + + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); + + if (ap1 == previousAlignable) { + ExtendedCorrelationsTable::const_iterator itC2 = previousCorrelations->find(ap2); + if (itC2 != previousCorrelations->end()) { + transpose ? fillCovarianceT(ap1, ap2, (*itC2).second, cov, row, col) + : fillCovariance(ap1, ap2, (*itC2).second, cov, row, col); + } + } else { + ExtendedCorrelations::const_iterator itC1 = theCorrelations.find(ap1); + if (itC1 != theCorrelations.end()) { previousAlignable = ap1; previousCorrelations = (*itC1).second; - ExtendedCorrelationsTable::const_iterator itC2 = (*itC1).second->find( ap2 ); - if ( itC2 != (*itC1).second->end() ) - { - transpose ? - fillCovarianceT( ap1, ap2, (*itC2).second, cov, row, col ) : - fillCovariance( ap1, ap2, (*itC2).second, cov, row, col ); + ExtendedCorrelationsTable::const_iterator itC2 = (*itC1).second->find(ap2); + if (itC2 != (*itC1).second->end()) { + transpose ? fillCovarianceT(ap1, ap2, (*itC2).second, cov, row, col) + : fillCovariance(ap1, ap2, (*itC2).second, cov, row, col); } } } @@ -64,37 +56,33 @@ void AlignmentExtendedCorrelationsStore::correlations( Alignable* ap1, Alignable return; } - -void AlignmentExtendedCorrelationsStore::setCorrelations( Alignable* ap1, Alignable* ap2, - const AlgebraicSymMatrix& cov, int row, int col ) -{ +void AlignmentExtendedCorrelationsStore::setCorrelations( + Alignable* ap1, Alignable* ap2, const AlgebraicSymMatrix& cov, int row, int col) { static Alignable* previousAlignable = nullptr; static ExtendedCorrelationsTable* previousCorrelations; // Needed by 'resetCorrelations()' to reset the static pointer: - if ( ap1 == nullptr ) { previousAlignable = nullptr; return; } + if (ap1 == nullptr) { + previousAlignable = nullptr; + return; + } - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); - if ( ap1 == previousAlignable ) - { - fillCorrelationsTable( ap1, ap2, previousCorrelations, cov, row, col, transpose ); - } - else - { - ExtendedCorrelations::iterator itC = theCorrelations.find( ap1 ); - if ( itC != theCorrelations.end() ) - { - fillCorrelationsTable( ap1, ap2, itC->second, cov, row, col, transpose ); + if (ap1 == previousAlignable) { + fillCorrelationsTable(ap1, ap2, previousCorrelations, cov, row, col, transpose); + } else { + ExtendedCorrelations::iterator itC = theCorrelations.find(ap1); + if (itC != theCorrelations.end()) { + fillCorrelationsTable(ap1, ap2, itC->second, cov, row, col, transpose); previousAlignable = ap1; previousCorrelations = itC->second; - } - else - { + } else { // make new entry ExtendedCorrelationsTable* newTable = new ExtendedCorrelationsTable; - fillCorrelationsTable( ap1, ap2, newTable, cov, row, col, transpose ); + fillCorrelationsTable(ap1, ap2, newTable, cov, row, col, transpose); theCorrelations[ap1] = newTable; @@ -104,45 +92,35 @@ void AlignmentExtendedCorrelationsStore::setCorrelations( Alignable* ap1, Aligna } } - -void AlignmentExtendedCorrelationsStore::setCorrelations( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat ) -{ - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); - - ExtendedCorrelations::iterator itC1 = theCorrelations.find( ap1 ); - if ( itC1 != theCorrelations.end() ) - { - ExtendedCorrelationsTable::iterator itC2 = itC1->second->find( ap1 ); - if ( itC2 != itC1->second->end() ) - { - itC2->second = transpose ? ExtendedCorrelationsEntry( mat.T() ) : ExtendedCorrelationsEntry( mat ); - } - else - { - (*itC1->second)[ap2] = transpose ? ExtendedCorrelationsEntry( mat.T() ) : ExtendedCorrelationsEntry( mat ); +void AlignmentExtendedCorrelationsStore::setCorrelations(Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat) { + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); + + ExtendedCorrelations::iterator itC1 = theCorrelations.find(ap1); + if (itC1 != theCorrelations.end()) { + ExtendedCorrelationsTable::iterator itC2 = itC1->second->find(ap1); + if (itC2 != itC1->second->end()) { + itC2->second = transpose ? ExtendedCorrelationsEntry(mat.T()) : ExtendedCorrelationsEntry(mat); + } else { + (*itC1->second)[ap2] = transpose ? ExtendedCorrelationsEntry(mat.T()) : ExtendedCorrelationsEntry(mat); } - } - else - { + } else { ExtendedCorrelationsTable* newTable = new ExtendedCorrelationsTable; - (*newTable)[ap2] = transpose ? ExtendedCorrelationsEntry( mat.T() ) : ExtendedCorrelationsEntry( mat ); + (*newTable)[ap2] = transpose ? ExtendedCorrelationsEntry(mat.T()) : ExtendedCorrelationsEntry(mat); theCorrelations[ap1] = newTable; } } +void AlignmentExtendedCorrelationsStore::getCorrelations(Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat) const { + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); -void AlignmentExtendedCorrelationsStore::getCorrelations( Alignable* ap1, Alignable* ap2, AlgebraicMatrix& mat ) const -{ - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); - - ExtendedCorrelations::const_iterator itC1 = theCorrelations.find( ap1 ); - if ( itC1 != theCorrelations.end() ) - { - ExtendedCorrelationsTable::const_iterator itC2 = itC1->second->find( ap2 ); - if ( itC2 != itC1->second->end() ) - { + ExtendedCorrelations::const_iterator itC1 = theCorrelations.find(ap1); + if (itC1 != theCorrelations.end()) { + ExtendedCorrelationsTable::const_iterator itC2 = itC1->second->find(ap2); + if (itC2 != itC1->second->end()) { mat = transpose ? itC2->second.matrix().T() : itC2->second.matrix(); return; } @@ -151,206 +129,181 @@ void AlignmentExtendedCorrelationsStore::getCorrelations( Alignable* ap1, Aligna mat = AlgebraicMatrix(); } +bool AlignmentExtendedCorrelationsStore::correlationsAvailable(Alignable* ap1, Alignable* ap2) const { + bool transpose = (ap2 > ap1); + if (transpose) + std::swap(ap1, ap2); -bool AlignmentExtendedCorrelationsStore::correlationsAvailable( Alignable* ap1, Alignable* ap2 ) const -{ - bool transpose = ( ap2 > ap1 ); - if ( transpose ) std::swap( ap1, ap2 ); - - ExtendedCorrelations::const_iterator itC1 = theCorrelations.find( ap1 ); - if ( itC1 != theCorrelations.end() ) - { - ExtendedCorrelationsTable::const_iterator itC2 = itC1->second->find( ap2 ); - if ( itC2 != itC1->second->end() ) return true; + ExtendedCorrelations::const_iterator itC1 = theCorrelations.find(ap1); + if (itC1 != theCorrelations.end()) { + ExtendedCorrelationsTable::const_iterator itC2 = itC1->second->find(ap2); + if (itC2 != itC1->second->end()) + return true; } return false; } - -void AlignmentExtendedCorrelationsStore::resetCorrelations( void ) -{ +void AlignmentExtendedCorrelationsStore::resetCorrelations(void) { ExtendedCorrelations::iterator itC; - for ( itC = theCorrelations.begin(); itC != theCorrelations.end(); ++itC ) delete (*itC).second; - theCorrelations.erase( theCorrelations.begin(), theCorrelations.end() ); + for (itC = theCorrelations.begin(); itC != theCorrelations.end(); ++itC) + delete (*itC).second; + theCorrelations.erase(theCorrelations.begin(), theCorrelations.end()); // Reset the static pointers to the 'previous alignables' AlgebraicSymMatrix dummy; - correlations( nullptr, nullptr, dummy, 0, 0 ); - setCorrelations( nullptr, nullptr, dummy, 0, 0 ); + correlations(nullptr, nullptr, dummy, 0, 0); + setCorrelations(nullptr, nullptr, dummy, 0, 0); } - -unsigned int AlignmentExtendedCorrelationsStore::size( void ) const -{ +unsigned int AlignmentExtendedCorrelationsStore::size(void) const { unsigned int size = 0; ExtendedCorrelations::const_iterator itC; - for ( itC = theCorrelations.begin(); itC != theCorrelations.end(); ++itC ) + for (itC = theCorrelations.begin(); itC != theCorrelations.end(); ++itC) size += itC->second->size(); return size; } +void AlignmentExtendedCorrelationsStore::fillCorrelationsTable(Alignable* ap1, + Alignable* ap2, + ExtendedCorrelationsTable* table, + const AlgebraicSymMatrix& cov, + int row, + int col, + bool transpose) { + ExtendedCorrelationsTable::iterator itC = table->find(ap2); -void -AlignmentExtendedCorrelationsStore::fillCorrelationsTable( Alignable* ap1, Alignable* ap2, - ExtendedCorrelationsTable* table, - const AlgebraicSymMatrix& cov, - int row, int col, bool transpose ) -{ - ExtendedCorrelationsTable::iterator itC = table->find( ap2 ); - - if ( itC != table->end() ) - { + if (itC != table->end()) { //if ( itC->second.counter() > theMaxUpdates ) return; - transpose ? - readFromCovarianceT( ap1, ap2, itC->second, cov, row, col ) : - readFromCovariance( ap1, ap2, itC->second, cov, row, col ); + transpose ? readFromCovarianceT(ap1, ap2, itC->second, cov, row, col) + : readFromCovariance(ap1, ap2, itC->second, cov, row, col); //itC->second.incrementCounter(); - } - else - { + } else { int nRow = ap1->alignmentParameters()->numSelected(); int nCol = ap2->alignmentParameters()->numSelected(); - ExtendedCorrelationsEntry newEntry( nRow, nCol ); + ExtendedCorrelationsEntry newEntry(nRow, nCol); - transpose ? - readFromCovarianceT( ap1, ap2, newEntry, cov, row, col ) : - readFromCovariance( ap1, ap2, newEntry, cov, row, col ); + transpose ? readFromCovarianceT(ap1, ap2, newEntry, cov, row, col) + : readFromCovariance(ap1, ap2, newEntry, cov, row, col); (*table)[ap2] = newEntry; } } - -void -AlignmentExtendedCorrelationsStore::fillCovariance( Alignable* ap1, Alignable* ap2, const ExtendedCorrelationsEntry& entry, - AlgebraicSymMatrix& cov, int row, int col ) const -{ +void AlignmentExtendedCorrelationsStore::fillCovariance(Alignable* ap1, + Alignable* ap2, + const ExtendedCorrelationsEntry& entry, + AlgebraicSymMatrix& cov, + int row, + int col) const { int nRow = entry.numRow(); int nCol = entry.numCol(); - for ( int iRow = 0; iRow < nRow; ++iRow ) - { - double factor = sqrt(cov[row+iRow][row+iRow]); - if ( edm::isNotFinite(factor) ) throw cms::Exception("LogicError") << "[AlignmentExtendedCorrelationsStore::fillCovariance] " - << "NaN-factor: sqrt(" << cov[row+iRow][row+iRow] << ")"; + for (int iRow = 0; iRow < nRow; ++iRow) { + double factor = sqrt(cov[row + iRow][row + iRow]); + if (edm::isNotFinite(factor)) + throw cms::Exception("LogicError") << "[AlignmentExtendedCorrelationsStore::fillCovariance] " + << "NaN-factor: sqrt(" << cov[row + iRow][row + iRow] << ")"; - for ( int jCol = 0; jCol < nCol; ++jCol ) - cov[row+iRow][col+jCol] = entry( iRow, jCol )*factor; + for (int jCol = 0; jCol < nCol; ++jCol) + cov[row + iRow][col + jCol] = entry(iRow, jCol) * factor; } - for ( int jCol = 0; jCol < nCol; ++jCol ) - { - double factor = sqrt(cov[col+jCol][col+jCol]); - if ( edm::isNotFinite(factor) ) throw cms::Exception("LogicError") << "[AlignmentExtendedCorrelationsStore::fillCovariance] " - << "NaN-factor: sqrt(" << cov[col+jCol][col+jCol] << ")"; + for (int jCol = 0; jCol < nCol; ++jCol) { + double factor = sqrt(cov[col + jCol][col + jCol]); + if (edm::isNotFinite(factor)) + throw cms::Exception("LogicError") << "[AlignmentExtendedCorrelationsStore::fillCovariance] " + << "NaN-factor: sqrt(" << cov[col + jCol][col + jCol] << ")"; - for ( int iRow = 0; iRow < nRow; ++iRow ) - cov[row+iRow][col+jCol] *= factor; + for (int iRow = 0; iRow < nRow; ++iRow) + cov[row + iRow][col + jCol] *= factor; } } - -void -AlignmentExtendedCorrelationsStore::fillCovarianceT( Alignable* ap1, Alignable* ap2, const ExtendedCorrelationsEntry& entry, - AlgebraicSymMatrix& cov, int row, int col ) const -{ +void AlignmentExtendedCorrelationsStore::fillCovarianceT(Alignable* ap1, + Alignable* ap2, + const ExtendedCorrelationsEntry& entry, + AlgebraicSymMatrix& cov, + int row, + int col) const { int nRow = entry.numRow(); int nCol = entry.numCol(); - for ( int iRow = 0; iRow < nRow; ++iRow ) - { - double factor = sqrt(cov[col+iRow][col+iRow]); - if ( edm::isNotFinite(factor) ) throw cms::Exception("LogicError") << "[AlignmentExtendedCorrelationsStore::fillCovarianceT] " - << "NaN-factor: sqrt(" << cov[col+iRow][col+iRow] << ")"; - for ( int jCol = 0; jCol < nCol; ++jCol ) - cov[row+jCol][col+iRow] = entry( iRow, jCol )*factor; + for (int iRow = 0; iRow < nRow; ++iRow) { + double factor = sqrt(cov[col + iRow][col + iRow]); + if (edm::isNotFinite(factor)) + throw cms::Exception("LogicError") << "[AlignmentExtendedCorrelationsStore::fillCovarianceT] " + << "NaN-factor: sqrt(" << cov[col + iRow][col + iRow] << ")"; + for (int jCol = 0; jCol < nCol; ++jCol) + cov[row + jCol][col + iRow] = entry(iRow, jCol) * factor; } - for ( int jCol = 0; jCol < nCol; ++jCol ) - { - double factor = sqrt(cov[row+jCol][row+jCol]); - if ( edm::isNotFinite(factor) ) throw cms::Exception("LogicError") << "[AlignmentExtendedCorrelationsStore::fillCovarianceT] " - << "NaN-factor: sqrt(" << cov[row+jCol][row+jCol] << ")"; - for ( int iRow = 0; iRow < nRow; ++iRow ) - cov[row+jCol][col+iRow] *= factor; + for (int jCol = 0; jCol < nCol; ++jCol) { + double factor = sqrt(cov[row + jCol][row + jCol]); + if (edm::isNotFinite(factor)) + throw cms::Exception("LogicError") << "[AlignmentExtendedCorrelationsStore::fillCovarianceT] " + << "NaN-factor: sqrt(" << cov[row + jCol][row + jCol] << ")"; + for (int iRow = 0; iRow < nRow; ++iRow) + cov[row + jCol][col + iRow] *= factor; } - } - -void -AlignmentExtendedCorrelationsStore::readFromCovariance( Alignable* ap1, Alignable* ap2, ExtendedCorrelationsEntry& entry, - const AlgebraicSymMatrix& cov, int row, int col ) -{ +void AlignmentExtendedCorrelationsStore::readFromCovariance( + Alignable* ap1, Alignable* ap2, ExtendedCorrelationsEntry& entry, const AlgebraicSymMatrix& cov, int row, int col) { int nRow = entry.numRow(); int nCol = entry.numCol(); - for ( int iRow = 0; iRow < nRow; ++iRow ) - { - double factor = sqrt(cov[row+iRow][row+iRow]); - for ( int jCol = 0; jCol < nCol; ++jCol ) - entry( iRow, jCol ) = cov[row+iRow][col+jCol]/factor; + for (int iRow = 0; iRow < nRow; ++iRow) { + double factor = sqrt(cov[row + iRow][row + iRow]); + for (int jCol = 0; jCol < nCol; ++jCol) + entry(iRow, jCol) = cov[row + iRow][col + jCol] / factor; } double maxCorr = 0; - for ( int jCol = 0; jCol < nCol; ++jCol ) - { - double factor = sqrt(cov[col+jCol][col+jCol]); - for ( int iRow = 0; iRow < nRow; ++iRow ) - { - entry( iRow, jCol ) /= factor; - if ( fabs( entry( iRow, jCol ) ) > maxCorr ) maxCorr = fabs( entry( iRow, jCol ) ); + for (int jCol = 0; jCol < nCol; ++jCol) { + double factor = sqrt(cov[col + jCol][col + jCol]); + for (int iRow = 0; iRow < nRow; ++iRow) { + entry(iRow, jCol) /= factor; + if (fabs(entry(iRow, jCol)) > maxCorr) + maxCorr = fabs(entry(iRow, jCol)); } } - resizeCorruptCorrelations( entry, maxCorr ); + resizeCorruptCorrelations(entry, maxCorr); } - -void -AlignmentExtendedCorrelationsStore::readFromCovarianceT( Alignable* ap1, Alignable* ap2, ExtendedCorrelationsEntry& entry, - const AlgebraicSymMatrix& cov, int row, int col ) -{ +void AlignmentExtendedCorrelationsStore::readFromCovarianceT( + Alignable* ap1, Alignable* ap2, ExtendedCorrelationsEntry& entry, const AlgebraicSymMatrix& cov, int row, int col) { int nRow = entry.numRow(); int nCol = entry.numCol(); - for ( int iRow = 0; iRow < nRow; ++iRow ) - { - double factor = sqrt(cov[col+iRow][col+iRow]); - for ( int jCol = 0; jCol < nCol; ++jCol ) - entry( iRow, jCol ) = cov[row+jCol][col+iRow]/factor; + for (int iRow = 0; iRow < nRow; ++iRow) { + double factor = sqrt(cov[col + iRow][col + iRow]); + for (int jCol = 0; jCol < nCol; ++jCol) + entry(iRow, jCol) = cov[row + jCol][col + iRow] / factor; } double maxCorr = 0; - for ( int jCol = 0; jCol < nCol; ++jCol ) - { - double factor = sqrt(cov[row+jCol][row+jCol]); - for ( int iRow = 0; iRow < nRow; ++iRow ) - { - entry( iRow, jCol ) /= factor; - if ( fabs( entry( iRow, jCol ) ) > maxCorr ) maxCorr = fabs( entry( iRow, jCol ) ); + for (int jCol = 0; jCol < nCol; ++jCol) { + double factor = sqrt(cov[row + jCol][row + jCol]); + for (int iRow = 0; iRow < nRow; ++iRow) { + entry(iRow, jCol) /= factor; + if (fabs(entry(iRow, jCol)) > maxCorr) + maxCorr = fabs(entry(iRow, jCol)); } } - resizeCorruptCorrelations( entry, maxCorr ); + resizeCorruptCorrelations(entry, maxCorr); } - -void -AlignmentExtendedCorrelationsStore::resizeCorruptCorrelations( ExtendedCorrelationsEntry& entry, - double maxCorr ) -{ - if ( maxCorr > 1. ) - { - entry *= theWeight/maxCorr; - } - else if ( maxCorr > theCut ) - { - entry *= 1. - ( maxCorr - theCut )/( 1. - theCut )*( 1. - theWeight ); +void AlignmentExtendedCorrelationsStore::resizeCorruptCorrelations(ExtendedCorrelationsEntry& entry, double maxCorr) { + if (maxCorr > 1.) { + entry *= theWeight / maxCorr; + } else if (maxCorr > theCut) { + entry *= 1. - (maxCorr - theCut) / (1. - theCut) * (1. - theWeight); } } diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentIORoot.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentIORoot.cc index 1aae40d5bfc72..5765a56e48d03 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentIORoot.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentIORoot.cc @@ -6,139 +6,191 @@ #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentIORoot.h" // ---------------------------------------------------------------------------- -// write alignment parameters +// write alignment parameters -void -AlignmentIORoot::writeAlignmentParameters(const align::Alignables& alivec, - const char* filename, int iter, - bool validCheck, int& ierr) -{ +void AlignmentIORoot::writeAlignmentParameters( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) { AlignmentParametersIORoot theIO; - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,true); - if (iret!=0) { ierr=-1; return;} - iret = theIO.write(alivec,validCheck); - if (iret!=0) { ierr=-2; return;} + iret = theIO.open(filename, iter, true); + if (iret != 0) { + ierr = -1; + return; + } + iret = theIO.write(alivec, validCheck); + if (iret != 0) { + ierr = -2; + return; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return;} + if (iret != 0) { + ierr = -3; + return; + } } // ---------------------------------------------------------------------------- -// read alignment parameters -align::Parameters -AlignmentIORoot::readAlignmentParameters(const align::Alignables& alivec, - const char* filename, int iter, int& ierr) -{ +// read alignment parameters +align::Parameters AlignmentIORoot::readAlignmentParameters(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) { align::Parameters result; AlignmentParametersIORoot theIO; - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,false); - if (iret!=0) { ierr=-1; return result;} - result = theIO.read(alivec,iret); - if (iret!=0) { ierr=-2; return result;} + iret = theIO.open(filename, iter, false); + if (iret != 0) { + ierr = -1; + return result; + } + result = theIO.read(alivec, iret); + if (iret != 0) { + ierr = -2; + return result; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return result;} + if (iret != 0) { + ierr = -3; + return result; + } return result; } // ---------------------------------------------------------------------------- -// write alignment parameters -void -AlignmentIORoot::writeOrigRigidBodyAlignmentParameters -(const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) -{ +// write alignment parameters +void AlignmentIORoot::writeOrigRigidBodyAlignmentParameters( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) { AlignmentParametersIORoot theIO; ierr = 0; int iret = theIO.open(filename, iter, true); - if (iret != 0) { ierr = -1; return;} + if (iret != 0) { + ierr = -1; + return; + } iret = theIO.writeOrigRigidBody(alivec, validCheck); - if (iret != 0) { ierr = -2; return;} + if (iret != 0) { + ierr = -2; + return; + } iret = theIO.close(); - if (iret != 0) { ierr = -3; return;} + if (iret != 0) { + ierr = -3; + return; + } } - // ---------------------------------------------------------------------------- // write correlations -void -AlignmentIORoot::writeCorrelations (const align::Correlations& cormap, - const char* filename, int iter, bool validCheck, int& ierr) -{ +void AlignmentIORoot::writeCorrelations( + const align::Correlations& cormap, const char* filename, int iter, bool validCheck, int& ierr) { AlignmentCorrelationsIORoot theIO; - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,true); - if (iret!=0) { ierr=-1; return;} - iret = theIO.write(cormap,validCheck); - if (iret!=0) { ierr=-2; return;} + iret = theIO.open(filename, iter, true); + if (iret != 0) { + ierr = -1; + return; + } + iret = theIO.write(cormap, validCheck); + if (iret != 0) { + ierr = -2; + return; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return;} + if (iret != 0) { + ierr = -3; + return; + } } // ---------------------------------------------------------------------------- // read correlations -align::Correlations -AlignmentIORoot::readCorrelations (const align::Alignables& alivec, const char* filename, - int iter, int& ierr) -{ +align::Correlations AlignmentIORoot::readCorrelations(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) { align::Correlations result; AlignmentCorrelationsIORoot theIO; - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,false); - if (iret!=0) { ierr=-1; return result;} - result = theIO.read(alivec,iret); - if (iret!=0) { ierr=-2; return result;} + iret = theIO.open(filename, iter, false); + if (iret != 0) { + ierr = -1; + return result; + } + result = theIO.read(alivec, iret); + if (iret != 0) { + ierr = -2; + return result; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return result;} + if (iret != 0) { + ierr = -3; + return result; + } return result; } - // ---------------------------------------------------------------------------- // write absolute position of alignable -void AlignmentIORoot::writeAlignableAbsolutePositions ( const align::Alignables& alivec, - const char* filename, int iter, - bool validCheck, int& ierr) -{ +void AlignmentIORoot::writeAlignableAbsolutePositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) { AlignableDataIORoot theIO(AlignableDataIORoot::Abs); - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,true); - if (iret!=0) { ierr=-1; return;} - iret = theIO.writeAbsPos(alivec,validCheck); - if (iret!=0) { ierr=-2; return;} + iret = theIO.open(filename, iter, true); + if (iret != 0) { + ierr = -1; + return; + } + iret = theIO.writeAbsPos(alivec, validCheck); + if (iret != 0) { + ierr = -2; + return; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return;} + if (iret != 0) { + ierr = -3; + return; + } } // ---------------------------------------------------------------------------- // read absolute position of alignable -AlignablePositions -AlignmentIORoot::readAlignableAbsolutePositions (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) -{ +AlignablePositions AlignmentIORoot::readAlignableAbsolutePositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) { AlignablePositions result; AlignableDataIORoot theIO(AlignableDataIORoot::Abs); - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,false); - if (iret!=0) { ierr=-1; return result;} - result = theIO.readAbsPos(alivec,iret); - if (iret!=0) { ierr=-2; return result;} + iret = theIO.open(filename, iter, false); + if (iret != 0) { + ierr = -1; + return result; + } + result = theIO.readAbsPos(alivec, iret); + if (iret != 0) { + ierr = -2; + return result; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return result;} + if (iret != 0) { + ierr = -3; + return result; + } return result; } @@ -146,39 +198,55 @@ AlignmentIORoot::readAlignableAbsolutePositions (const align::Alignables& alivec // ---------------------------------------------------------------------------- // write original position of alignable -void AlignmentIORoot::writeAlignableOriginalPositions ( const align::Alignables& alivec, - const char* filename, int iter, - bool validCheck, int& ierr) -{ +void AlignmentIORoot::writeAlignableOriginalPositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) { AlignableDataIORoot theIO(AlignableDataIORoot::Org); - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,true); - if (iret!=0) { ierr=-1; return;} - iret = theIO.writeOrgPos(alivec,validCheck); - if (iret!=0) { ierr=-2; return;} + iret = theIO.open(filename, iter, true); + if (iret != 0) { + ierr = -1; + return; + } + iret = theIO.writeOrgPos(alivec, validCheck); + if (iret != 0) { + ierr = -2; + return; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return;} + if (iret != 0) { + ierr = -3; + return; + } } // ---------------------------------------------------------------------------- // read original position of alignable -AlignablePositions -AlignmentIORoot::readAlignableOriginalPositions (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) -{ +AlignablePositions AlignmentIORoot::readAlignableOriginalPositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) { AlignablePositions result; AlignableDataIORoot theIO(AlignableDataIORoot::Org); - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,false); - if (iret!=0) { ierr=-1; return result;} - result = theIO.readOrgPos(alivec,iret); - if (iret!=0) { ierr=-2; return result;} + iret = theIO.open(filename, iter, false); + if (iret != 0) { + ierr = -1; + return result; + } + result = theIO.readOrgPos(alivec, iret); + if (iret != 0) { + ierr = -2; + return result; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return result;} + if (iret != 0) { + ierr = -3; + return result; + } return result; } @@ -186,45 +254,55 @@ AlignmentIORoot::readAlignableOriginalPositions (const align::Alignables& alivec // ---------------------------------------------------------------------------- // write relative position of alignable -void AlignmentIORoot::writeAlignableRelativePositions( const align::Alignables& alivec, - const char* filename, - int iter, bool validCheck, int& ierr) -{ +void AlignmentIORoot::writeAlignableRelativePositions( + const align::Alignables& alivec, const char* filename, int iter, bool validCheck, int& ierr) { AlignableDataIORoot theIO(AlignableDataIORoot::Rel); - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,true); - if (iret!=0) { ierr=-1; return;} - iret = theIO.writeRelPos(alivec,validCheck); - if (iret!=0) { ierr=-2; return;} + iret = theIO.open(filename, iter, true); + if (iret != 0) { + ierr = -1; + return; + } + iret = theIO.writeRelPos(alivec, validCheck); + if (iret != 0) { + ierr = -2; + return; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return;} + if (iret != 0) { + ierr = -3; + return; + } } // ---------------------------------------------------------------------------- // read relative position of alignable -AlignableShifts -AlignmentIORoot::readAlignableRelativePositions (const align::Alignables& alivec, - const char* filename, int iter, int& ierr) -{ +AlignableShifts AlignmentIORoot::readAlignableRelativePositions(const align::Alignables& alivec, + const char* filename, + int iter, + int& ierr) { AlignableShifts result; AlignableDataIORoot theIO(AlignableDataIORoot::Rel); - ierr=0; + ierr = 0; int iret; - iret = theIO.open(filename,iter,false); - if (iret!=0) { ierr=-1; return result;} - result = theIO.readRelPos(alivec,iret); - if (iret!=0) { ierr=-2; return result;} + iret = theIO.open(filename, iter, false); + if (iret != 0) { + ierr = -1; + return result; + } + result = theIO.readRelPos(alivec, iret); + if (iret != 0) { + ierr = -2; + return result; + } iret = theIO.close(); - if (iret!=0) { ierr=-3; return result;} + if (iret != 0) { + ierr = -3; + return result; + } return result; } - - - - - - diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentIORootBase.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentIORootBase.cc index 6f0e36a735ee5..b3d928b2b6d47 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentIORootBase.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentIORootBase.cc @@ -6,85 +6,78 @@ #include "TFile.h" #include "TTree.h" -AlignmentIORootBase::~AlignmentIORootBase() -{ - delete myFile; // tree is deleted automatically with file +AlignmentIORootBase::~AlignmentIORootBase() { + delete myFile; // tree is deleted automatically with file } // ---------------------------------------------------------------------------- // open file/trees for write -int AlignmentIORootBase::openRoot(const char* filename, int iteration, bool write) -{ - bWrite=write; +int AlignmentIORootBase::openRoot(const char* filename, int iteration, bool write) { + bWrite = write; int iter; - edm::LogInfo("AlignmentIORootBase") << "File: " << filename ; + edm::LogInfo("AlignmentIORootBase") << "File: " << filename; - if (bWrite) { // writing + if (bWrite) { // writing - int iterfile = testFile(filename,treename); + int iterfile = testFile(filename, treename); if (iterfile == -1) { - iter=iteration; - edm::LogInfo("AlignmentIORootBase") << "Write to new file; first iteration: " << iter ; - myFile = TFile::Open(filename,"recreate"); + iter = iteration; + edm::LogInfo("AlignmentIORootBase") << "Write to new file; first iteration: " << iter; + myFile = TFile::Open(filename, "recreate"); } else { if (iteration == -1) { - iter=iterfile+1; - edm::LogInfo("AlignmentIORootBase") - << "Write to existing file; highest iteration: " << iter; + iter = iterfile + 1; + edm::LogInfo("AlignmentIORootBase") << "Write to existing file; highest iteration: " << iter; } else { - if (iteration<=iterfile) { - edm::LogError("AlignmentIORootBase") - << "Iteration " << iteration - <<" invalid or already exists for tree " << treename; - return -1; + if (iteration <= iterfile) { + edm::LogError("AlignmentIORootBase") + << "Iteration " << iteration << " invalid or already exists for tree " << treename; + return -1; } iter = iteration; - edm::LogInfo("AlignmentIORootBase") << "Write to new iteration: " << iter; + edm::LogInfo("AlignmentIORootBase") << "Write to new iteration: " << iter; } - myFile = TFile::Open(filename,"update"); - + myFile = TFile::Open(filename, "update"); } // create tree myFile->cd(); - edm::LogInfo("AlignmentIORootBase") << "Tree: " << treeName(iter,treename); - tree = new TTree(treeName(iter,treename),treetxt); + edm::LogInfo("AlignmentIORootBase") << "Tree: " << treeName(iter, treename); + tree = new TTree(treeName(iter, treename), treetxt); createBranches(); - } else { // reading + } else { // reading - int iterfile = testFile(filename,treename); - if ( iterfile == -1 ) { + int iterfile = testFile(filename, treename); + if (iterfile == -1) { edm::LogError("AlignmentIORootBase") << "File does not exist!"; return -1; - } else if ( iterfile == -2 ) { - edm::LogError("AlignmentIORootBase") << "Tree " << treename - << " does not exist in file " << filename; + } else if (iterfile == -2) { + edm::LogError("AlignmentIORootBase") << "Tree " << treename << " does not exist in file " << filename; return -1; } else { if (iteration == -1) { - iter=iterfile; + iter = iterfile; edm::LogInfo("AlignmentIORootBase") << "Read from highest iteration: " << iter; } else { - if (iteration>iterfile) { - edm::LogError("AlignmentIORootBase") - << "Iteration " << iteration << " does not exist for tree " << treename; - return -1; + if (iteration > iterfile) { + edm::LogError("AlignmentIORootBase") << "Iteration " << iteration << " does not exist for tree " << treename; + return -1; } iter = iteration; - edm::LogInfo("AlignmentIORootBase") << "Read from specified iteration: " << iter; + edm::LogInfo("AlignmentIORootBase") << "Read from specified iteration: " << iter; } myFile = TFile::Open(filename, "read"); } myFile->cd(); // set trees - edm::LogInfo("AlignmentIORootBase") <<" Tree: " <Get(treeName(iter,treename)); - if (tree==nullptr) { - edm::LogError("AlignmentIORootBase") <<"Tree does not exist in file!"; + edm::LogInfo("AlignmentIORootBase") << " Tree: " << treeName(iter, treename); + tree = (TTree*)myFile->Get(treeName(iter, treename)); + if (tree == nullptr) { + edm::LogError("AlignmentIORootBase") << "Tree does not exist in file!"; return -1; } setBranchAddresses(); @@ -96,15 +89,14 @@ int AlignmentIORootBase::openRoot(const char* filename, int iteration, bool writ // ---------------------------------------------------------------------------- // write tree and close file -int AlignmentIORootBase::closeRoot(void) -{ - if (bWrite) { //writing +int AlignmentIORootBase::closeRoot(void) { + if (bWrite) { //writing tree->Write(); } delete myFile; myFile = nullptr; - tree = nullptr; // deleted with file + tree = nullptr; // deleted with file return 0; } @@ -113,19 +105,18 @@ int AlignmentIORootBase::closeRoot(void) // returns highest existing iteration in file // if file does not exist: return -1 -int AlignmentIORootBase::testFile(const char* filename, const TString &tname) -{ +int AlignmentIORootBase::testFile(const char* filename, const TString& tname) { FILE* testFILE; - testFILE = fopen(filename,"r"); + testFILE = fopen(filename, "r"); if (testFILE == nullptr) { return -1; } else { fclose(testFILE); - int ihighest=-2; - TFile *aFile = TFile::Open(filename,"read"); - for (int iter=0; iterGet(treeName(iter,tname))) - && (iter>ihighest)) ihighest=iter; + int ihighest = -2; + TFile* aFile = TFile::Open(filename, "read"); + for (int iter = 0; iter < itermax; iter++) { + if ((nullptr != (TTree*)aFile->Get(treeName(iter, tname))) && (iter > ihighest)) + ihighest = iter; } delete aFile; return ihighest; @@ -135,7 +126,4 @@ int AlignmentIORootBase::testFile(const char* filename, const TString &tname) // ---------------------------------------------------------------------------- // create tree name from stub+iteration -TString AlignmentIORootBase::treeName(int iter, const TString &tname) -{ - return TString(tname + Form("_%i",iter)); -} +TString AlignmentIORootBase::treeName(int iter, const TString& tname) { return TString(tname + Form("_%i", iter)); } diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterBuilder.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterBuilder.cc index 9c307198b895c..b0ed1596eb198 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterBuilder.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterBuilder.cc @@ -25,83 +25,69 @@ using namespace AlignmentParametersFactory; //__________________________________________________________________________________________________ -AlignmentParameterBuilder::AlignmentParameterBuilder(AlignableTracker* alignableTracker, - AlignableExtras* alignableExtras) : - theAlignables(), - theAlignableTracker(alignableTracker), - theAlignableMuon(nullptr), - theAlignableExtras(alignableExtras) -{ -} +AlignmentParameterBuilder::AlignmentParameterBuilder(AlignableTracker *alignableTracker, + AlignableExtras *alignableExtras) + : theAlignables(), + theAlignableTracker(alignableTracker), + theAlignableMuon(nullptr), + theAlignableExtras(alignableExtras) {} //__________________________________________________________________________________________________ -AlignmentParameterBuilder::AlignmentParameterBuilder(AlignableTracker* alignableTracker, - AlignableMuon* alignableMuon, - AlignableExtras* alignableExtras) : - theAlignables(), - theAlignableTracker(alignableTracker), - theAlignableMuon(alignableMuon), - theAlignableExtras(alignableExtras) -{ -} - +AlignmentParameterBuilder::AlignmentParameterBuilder(AlignableTracker *alignableTracker, + AlignableMuon *alignableMuon, + AlignableExtras *alignableExtras) + : theAlignables(), + theAlignableTracker(alignableTracker), + theAlignableMuon(alignableMuon), + theAlignableExtras(alignableExtras) {} //__________________________________________________________________________________________________ -AlignmentParameterBuilder::AlignmentParameterBuilder(AlignableTracker* alignableTracker, - AlignableExtras* alignableExtras, - const edm::ParameterSet &pSet) : - theAlignables(), - theAlignableTracker(alignableTracker), - theAlignableMuon(nullptr), - theAlignableExtras(alignableExtras) -{ +AlignmentParameterBuilder::AlignmentParameterBuilder(AlignableTracker *alignableTracker, + AlignableExtras *alignableExtras, + const edm::ParameterSet &pSet) + : theAlignables(), + theAlignableTracker(alignableTracker), + theAlignableMuon(nullptr), + theAlignableExtras(alignableExtras) { this->addAllSelections(pSet); } //__________________________________________________________________________________________________ -AlignmentParameterBuilder::AlignmentParameterBuilder(AlignableTracker* alignableTracker, - AlignableMuon* alignableMuon, - AlignableExtras* alignableExtras, - const edm::ParameterSet &pSet) : - theAlignables(), - theAlignableTracker(alignableTracker), - theAlignableMuon(alignableMuon), - theAlignableExtras(alignableExtras) -{ +AlignmentParameterBuilder::AlignmentParameterBuilder(AlignableTracker *alignableTracker, + AlignableMuon *alignableMuon, + AlignableExtras *alignableExtras, + const edm::ParameterSet &pSet) + : theAlignables(), + theAlignableTracker(alignableTracker), + theAlignableMuon(alignableMuon), + theAlignableExtras(alignableExtras) { this->addAllSelections(pSet); } -const AlignableTracker* AlignmentParameterBuilder::alignableTracker() const -{ - return theAlignableTracker; -} +const AlignableTracker *AlignmentParameterBuilder::alignableTracker() const { return theAlignableTracker; } //__________________________________________________________________________________________________ -void AlignmentParameterBuilder::addAllSelections(const edm::ParameterSet &pSet) -{ +void AlignmentParameterBuilder::addAllSelections(const edm::ParameterSet &pSet) { AlignmentParameterSelector selector(nullptr); std::vector selsTypes(pSet.getParameter >("parameterTypes")); - + for (unsigned int i = 0; i < selsTypes.size(); ++i) { std::vector selSetType(selector.decompose(selsTypes[i], ',')); if (selSetType.size() != 2) { throw cms::Exception("BadConfig") << "AlignmentParameterBuilder" - << "parameterTypes should contain 2 comma separated strings" - << ", but found '" << selsTypes[i] << "'."; + << "parameterTypes should contain 2 comma separated strings" + << ", but found '" << selsTypes[i] << "'."; } this->addSelections(pSet.getParameter(selSetType[0]), - AlignmentParametersFactory::parametersType(selSetType[1])); + AlignmentParametersFactory::parametersType(selSetType[1])); } } //__________________________________________________________________________________________________ -unsigned int AlignmentParameterBuilder::addSelections(const edm::ParameterSet &pSet, - ParametersType parType) -{ - +unsigned int AlignmentParameterBuilder::addSelections(const edm::ParameterSet &pSet, ParametersType parType) { const unsigned int oldAliSize = theAlignables.size(); - AlignmentParameterSelector selector( theAlignableTracker, theAlignableMuon, theAlignableExtras ); + AlignmentParameterSelector selector(theAlignableTracker, theAlignableMuon, theAlignableExtras); const unsigned int addedSets = selector.addSelections(pSet); const align::Alignables &alignables = selector.selectedAlignables(); @@ -113,10 +99,12 @@ unsigned int AlignmentParameterBuilder::addSelections(const edm::ParameterSet &p while (iAli != alignables.end() && iParamSel != paramSels.end()) { std::vector boolParSel; - std::vector parSel(*iParamSel); // copy, since decodeParamSel may manipulate + std::vector parSel(*iParamSel); // copy, since decodeParamSel may manipulate bool charSelIsGeneral = this->decodeParamSel(parSel, boolParSel); - if (this->add(*iAli, parType, boolParSel)) ++nHigherLevel; - if (charSelIsGeneral) this->addFullParamSel((*iAli)->alignmentParameters(), parSel); + if (this->add(*iAli, parType, boolParSel)) + ++nHigherLevel; + if (charSelIsGeneral) + this->addFullParamSel((*iAli)->alignmentParameters(), parSel); ++iAli; ++iParamSel; @@ -126,97 +114,82 @@ unsigned int AlignmentParameterBuilder::addSelections(const edm::ParameterSet &p << " Added " << addedSets << " set(s) of alignables with " << theAlignables.size() - oldAliSize << " alignables in total," << " of which " << nHigherLevel << " are higher level " - << "(using " << parametersTypeName(parType) << "AlignmentParameters)."; - + << "(using " << parametersTypeName(parType) << "AlignmentParameters)."; + return addedSets; } //__________________________________________________________________________________________________ -bool AlignmentParameterBuilder::add(Alignable *alignable, - ParametersType parType, - const std::vector &sel) -{ +bool AlignmentParameterBuilder::add(Alignable *alignable, ParametersType parType, const std::vector &sel) { AlignmentParameters *paras = AlignmentParametersFactory::createParameters(alignable, parType, sel); alignable->setAlignmentParameters(paras); theAlignables.push_back(alignable); const int aliTypeId = alignable->alignableObjectId(); - const bool isHigherLevel = (aliTypeId != align::AlignableDet - && aliTypeId != align::AlignableDetUnit); + const bool isHigherLevel = (aliTypeId != align::AlignableDet && aliTypeId != align::AlignableDetUnit); return isHigherLevel; } - //__________________________________________________________________________________________________ unsigned int AlignmentParameterBuilder::add(const align::Alignables &alignables, - ParametersType parType, const std::vector &sel) -{ - + ParametersType parType, + const std::vector &sel) { unsigned int nHigherLevel = 0; - for (align::Alignables::const_iterator iAli = alignables.begin(); - iAli != alignables.end(); ++iAli) { - if (this->add(*iAli, parType, sel)) ++nHigherLevel; + for (align::Alignables::const_iterator iAli = alignables.begin(); iAli != alignables.end(); ++iAli) { + if (this->add(*iAli, parType, sel)) + ++nHigherLevel; } return nHigherLevel; } - //__________________________________________________________________________________________________ -void AlignmentParameterBuilder::fixAlignables(int n) -{ - - if (n<1 || n>3) { +void AlignmentParameterBuilder::fixAlignables(int n) { + if (n < 1 || n > 3) { edm::LogError("BadArgument") << " n = " << n << " is not in [1,3]"; return; } align::Alignables theNewAlignables; - int i=0; + int i = 0; int imax = theAlignables.size(); - for ( align::Alignables::const_iterator ia=theAlignables.begin(); - ia!=theAlignables.end(); ++ia ) - { - i++; - if ( n==1 && i>1 ) - theNewAlignables.push_back(*ia); - else if ( n==2 && i>1 && i2 && i 1) + theNewAlignables.push_back(*ia); + else if (n == 2 && i > 1 && i < imax) + theNewAlignables.push_back(*ia); + else if (n == 3 && i > 2 && i < imax) + theNewAlignables.push_back(*ia); + } theAlignables = theNewAlignables; edm::LogInfo("Alignment") << "@SUB=AlignmentParameterBuilder::fixAlignables" - << "removing " << n << " alignables, so that " - << theAlignables.size() << " alignables left"; + << "removing " << n << " alignables, so that " << theAlignables.size() + << " alignables left"; } //__________________________________________________________________________________________________ -bool AlignmentParameterBuilder::decodeParamSel(std::vector ¶mSelChar, - std::vector &result) const -{ +bool AlignmentParameterBuilder::decodeParamSel(std::vector ¶mSelChar, std::vector &result) const { result.clear(); // remove all spaces from paramSelChar - useful to group the parameters if they are many - paramSelChar.erase(std::remove(paramSelChar.begin(), paramSelChar.end(), ' '), - paramSelChar.end()); + paramSelChar.erase(std::remove(paramSelChar.begin(), paramSelChar.end(), ' '), paramSelChar.end()); bool anyNon01 = false; for (unsigned int pos = 0; pos < paramSelChar.size(); ++pos) { - switch (paramSelChar[pos]) { - default: - anyNon01 = true; - // no break; - case '1': - result.push_back(true); - break; - case '0': - result.push_back(false); - break; + default: + anyNon01 = true; + // no break; + case '1': + result.push_back(true); + break; + case '0': + result.push_back(false); + break; } } @@ -225,9 +198,9 @@ bool AlignmentParameterBuilder::decodeParamSel(std::vector ¶mSelChar, //__________________________________________________________________________________________________ bool AlignmentParameterBuilder::addFullParamSel(AlignmentParameters *aliParams, - const std::vector &fullSel) const -{ - if (!aliParams) return false; + const std::vector &fullSel) const { + if (!aliParams) + return false; aliParams->setUserVariables(new SelectionUserVariables(fullSel)); diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterSelector.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterSelector.cc index 4ff1cf2f7dce0..3f57ac6f70dc4 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterSelector.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterSelector.cc @@ -21,25 +21,31 @@ #include "FWCore/Utilities/interface/Exception.h" //________________________________________________________________________________ -AlignmentParameterSelector::AlignmentParameterSelector(AlignableTracker *aliTracker, AlignableMuon* aliMuon, - AlignableExtras *aliExtras) : - theTracker(aliTracker), theMuon(aliMuon), theExtras(aliExtras), theSelectedAlignables(), - theRangesEta(), theRangesPhi(), theRangesR(), theRangesX(), theRangesY(), theRangesZ() -{ - this->setSpecials(""); // init theOnlyDS, theOnlySS, theSelLayers, theMinLayer, theMaxLayer, theRphiOrStereoDetUnit +AlignmentParameterSelector::AlignmentParameterSelector(AlignableTracker *aliTracker, + AlignableMuon *aliMuon, + AlignableExtras *aliExtras) + : theTracker(aliTracker), + theMuon(aliMuon), + theExtras(aliExtras), + theSelectedAlignables(), + theRangesEta(), + theRangesPhi(), + theRangesR(), + theRangesX(), + theRangesY(), + theRangesZ() { + this->setSpecials(""); // init theOnlyDS, theOnlySS, theSelLayers, theMinLayer, theMaxLayer, theRphiOrStereoDetUnit } //________________________________________________________________________________ -void AlignmentParameterSelector::clear() -{ +void AlignmentParameterSelector::clear() { theSelectedAlignables.clear(); theSelectedParameters.clear(); this->clearGeometryCuts(); } //________________________________________________________________________________ -void AlignmentParameterSelector::clearGeometryCuts() -{ +void AlignmentParameterSelector::clearGeometryCuts() { theRangesEta.clear(); theRangesPhi.clear(); theRangesR.clear(); @@ -55,27 +61,22 @@ void AlignmentParameterSelector::clearGeometryCuts() theTECDetIdRanges.clear(); } -const AlignableTracker* AlignmentParameterSelector::alignableTracker() const -{ - return theTracker; -} +const AlignableTracker *AlignmentParameterSelector::alignableTracker() const { return theTracker; } //__________________________________________________________________________________________________ -unsigned int AlignmentParameterSelector::addSelections(const edm::ParameterSet &pSet) -{ +unsigned int AlignmentParameterSelector::addSelections(const edm::ParameterSet &pSet) { + const std::vector selections = pSet.getParameter >("alignParams"); - const std::vector selections - = pSet.getParameter >("alignParams"); - unsigned int addedSets = 0; for (unsigned int iSel = 0; iSel < selections.size(); ++iSel) { std::vector decompSel(this->decompose(selections[iSel], ',')); - if (decompSel.empty()) continue; // edm::LogError or even cms::Exception?? + if (decompSel.empty()) + continue; // edm::LogError or even cms::Exception?? if (decompSel.size() < 2) { - throw cms::Exception("BadConfig") << "@SUB=AlignmentParameterSelector::addSelections" - << selections[iSel]<<" from alignableParamSelector: " + throw cms::Exception("BadConfig") << "@SUB=AlignmentParameterSelector::addSelections" << selections[iSel] + << " from alignableParamSelector: " << " should have at least 2 ','-separated parts"; } else if (decompSel.size() > 2) { const edm::ParameterSet geoSel(pSet.getParameter(decompSel[2].c_str())); @@ -84,7 +85,7 @@ unsigned int AlignmentParameterSelector::addSelections(const edm::ParameterSet & this->clearGeometryCuts(); this->addSelection(decompSel[0], this->convertParamSel(decompSel[1])); } - + ++addedSets; } @@ -92,16 +93,15 @@ unsigned int AlignmentParameterSelector::addSelections(const edm::ParameterSet & } //________________________________________________________________________________ -void AlignmentParameterSelector::setGeometryCuts(const edm::ParameterSet &pSet) -{ +void AlignmentParameterSelector::setGeometryCuts(const edm::ParameterSet &pSet) { // Allow non-specified arrays to be interpreted as empty (i.e. no selection), - // but take care that nothing unknown is configured (to fetch typos!). + // but take care that nothing unknown is configured (to fetch typos!). this->clearGeometryCuts(); const std::vector parameterNames(pSet.getParameterNames()); - for (std::vector::const_iterator iParam = parameterNames.begin(), - iEnd = parameterNames.end(); iParam != iEnd; ++iParam) { - + for (std::vector::const_iterator iParam = parameterNames.begin(), iEnd = parameterNames.end(); + iParam != iEnd; + ++iParam) { // Calling swap is more efficient than assignment: if (*iParam == "etaRanges") { pSet.getParameter >(*iParam).swap(theRangesEta); @@ -124,40 +124,39 @@ void AlignmentParameterSelector::setGeometryCuts(const edm::ParameterSet &pSet) } else if (*iParam == "excludedDetIdRanges") { pSet.getParameter >(*iParam).swap(theExcludedDetIdRanges); } else if (*iParam == "pxbDetId") { - const edm::ParameterSet & pxbDetIdPSet = pSet.getParameterSet(*iParam); + const edm::ParameterSet &pxbDetIdPSet = pSet.getParameterSet(*iParam); this->setPXBDetIdCuts(pxbDetIdPSet); } else if (*iParam == "pxfDetId") { - const edm::ParameterSet & pxfDetIdPSet = pSet.getParameterSet(*iParam); + const edm::ParameterSet &pxfDetIdPSet = pSet.getParameterSet(*iParam); this->setPXFDetIdCuts(pxfDetIdPSet); } else if (*iParam == "tibDetId") { - const edm::ParameterSet & tibDetIdPSet = pSet.getParameterSet(*iParam); + const edm::ParameterSet &tibDetIdPSet = pSet.getParameterSet(*iParam); this->setTIBDetIdCuts(tibDetIdPSet); } else if (*iParam == "tidDetId") { - const edm::ParameterSet & tidDetIdPSet = pSet.getParameterSet(*iParam); + const edm::ParameterSet &tidDetIdPSet = pSet.getParameterSet(*iParam); this->setTIDDetIdCuts(tidDetIdPSet); } else if (*iParam == "tobDetId") { - const edm::ParameterSet & tobDetIdPSet = pSet.getParameterSet(*iParam); + const edm::ParameterSet &tobDetIdPSet = pSet.getParameterSet(*iParam); this->setTOBDetIdCuts(tobDetIdPSet); } else if (*iParam == "tecDetId") { - const edm::ParameterSet & tecDetIdPSet = pSet.getParameterSet(*iParam); + const edm::ParameterSet &tecDetIdPSet = pSet.getParameterSet(*iParam); this->setTECDetIdCuts(tecDetIdPSet); } else { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::setGeometryCuts] " - << "Unknown parameter '" << *iParam << "'.\n"; + << "Unknown parameter '" << *iParam << "'.\n"; } } } //________________________________________________________________________________ -void AlignmentParameterSelector::setPXBDetIdCuts(const edm::ParameterSet &pSet) -{ +void AlignmentParameterSelector::setPXBDetIdCuts(const edm::ParameterSet &pSet) { // Allow non-specified arrays to be interpreted as empty (i.e. no selection), - // but take care that nothing unknown is configured (to fetch typos!). + // but take care that nothing unknown is configured (to fetch typos!). const std::vector parameterNames(pSet.getParameterNames()); - for (std::vector::const_iterator iParam = parameterNames.begin(), - iEnd = parameterNames.end(); iParam != iEnd; ++iParam) { - + for (std::vector::const_iterator iParam = parameterNames.begin(), iEnd = parameterNames.end(); + iParam != iEnd; + ++iParam) { // Calling swap is more efficient than assignment: if (*iParam == "ladderRanges") { pSet.getParameter >(*iParam).swap(thePXBDetIdRanges.theLadderRanges); @@ -167,21 +166,20 @@ void AlignmentParameterSelector::setPXBDetIdCuts(const edm::ParameterSet &pSet) pSet.getParameter >(*iParam).swap(thePXBDetIdRanges.theModuleRanges); } else { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::setPXBDetIdCuts] " - << "Unknown parameter '" << *iParam << "'.\n"; + << "Unknown parameter '" << *iParam << "'.\n"; } } } //________________________________________________________________________________ -void AlignmentParameterSelector::setPXFDetIdCuts(const edm::ParameterSet &pSet) -{ +void AlignmentParameterSelector::setPXFDetIdCuts(const edm::ParameterSet &pSet) { // Allow non-specified arrays to be interpreted as empty (i.e. no selection), - // but take care that nothing unknown is configured (to fetch typos!). + // but take care that nothing unknown is configured (to fetch typos!). const std::vector parameterNames(pSet.getParameterNames()); - for (std::vector::const_iterator iParam = parameterNames.begin(), - iEnd = parameterNames.end(); iParam != iEnd; ++iParam) { - + for (std::vector::const_iterator iParam = parameterNames.begin(), iEnd = parameterNames.end(); + iParam != iEnd; + ++iParam) { // Calling swap is more efficient than assignment: if (*iParam == "bladeRanges") { pSet.getParameter >(*iParam).swap(thePXFDetIdRanges.theBladeRanges); @@ -195,21 +193,20 @@ void AlignmentParameterSelector::setPXFDetIdCuts(const edm::ParameterSet &pSet) pSet.getParameter >(*iParam).swap(thePXFDetIdRanges.theSideRanges); } else { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::setPXFDetIdCuts] " - << "Unknown parameter '" << *iParam << "'.\n"; + << "Unknown parameter '" << *iParam << "'.\n"; } } } //________________________________________________________________________________ -void AlignmentParameterSelector::setTIBDetIdCuts(const edm::ParameterSet &pSet) -{ +void AlignmentParameterSelector::setTIBDetIdCuts(const edm::ParameterSet &pSet) { // Allow non-specified arrays to be interpreted as empty (i.e. no selection), - // but take care that nothing unknown is configured (to fetch typos!). + // but take care that nothing unknown is configured (to fetch typos!). const std::vector parameterNames(pSet.getParameterNames()); - for (std::vector::const_iterator iParam = parameterNames.begin(), - iEnd = parameterNames.end(); iParam != iEnd; ++iParam) { - + for (std::vector::const_iterator iParam = parameterNames.begin(), iEnd = parameterNames.end(); + iParam != iEnd; + ++iParam) { // Calling swap is more efficient than assignment: if (*iParam == "layerRanges") { pSet.getParameter >(*iParam).swap(theTIBDetIdRanges.theLayerRanges); @@ -221,21 +218,20 @@ void AlignmentParameterSelector::setTIBDetIdCuts(const edm::ParameterSet &pSet) pSet.getParameter >(*iParam).swap(theTIBDetIdRanges.theSideRanges); } else { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::setTIBDetIdCuts] " - << "Unknown parameter '" << *iParam << "'.\n"; + << "Unknown parameter '" << *iParam << "'.\n"; } } } //________________________________________________________________________________ -void AlignmentParameterSelector::setTIDDetIdCuts(const edm::ParameterSet &pSet) -{ +void AlignmentParameterSelector::setTIDDetIdCuts(const edm::ParameterSet &pSet) { // Allow non-specified arrays to be interpreted as empty (i.e. no selection), - // but take care that nothing unknown is configured (to fetch typos!). + // but take care that nothing unknown is configured (to fetch typos!). const std::vector parameterNames(pSet.getParameterNames()); - for (std::vector::const_iterator iParam = parameterNames.begin(), - iEnd = parameterNames.end(); iParam != iEnd; ++iParam) { - + for (std::vector::const_iterator iParam = parameterNames.begin(), iEnd = parameterNames.end(); + iParam != iEnd; + ++iParam) { // Calling swap is more efficient than assignment: if (*iParam == "diskRanges") { pSet.getParameter >(*iParam).swap(theTIDDetIdRanges.theDiskRanges); @@ -247,21 +243,20 @@ void AlignmentParameterSelector::setTIDDetIdCuts(const edm::ParameterSet &pSet) pSet.getParameter >(*iParam).swap(theTIDDetIdRanges.theSideRanges); } else { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::setTIDDetIdCuts] " - << "Unknown parameter '" << *iParam << "'.\n"; + << "Unknown parameter '" << *iParam << "'.\n"; } } } //________________________________________________________________________________ -void AlignmentParameterSelector::setTOBDetIdCuts(const edm::ParameterSet &pSet) -{ +void AlignmentParameterSelector::setTOBDetIdCuts(const edm::ParameterSet &pSet) { // Allow non-specified arrays to be interpreted as empty (i.e. no selection), - // but take care that nothing unknown is configured (to fetch typos!). + // but take care that nothing unknown is configured (to fetch typos!). const std::vector parameterNames(pSet.getParameterNames()); - for (std::vector::const_iterator iParam = parameterNames.begin(), - iEnd = parameterNames.end(); iParam != iEnd; ++iParam) { - + for (std::vector::const_iterator iParam = parameterNames.begin(), iEnd = parameterNames.end(); + iParam != iEnd; + ++iParam) { // Calling swap is more efficient than assignment: if (*iParam == "layerRanges") { pSet.getParameter >(*iParam).swap(theTOBDetIdRanges.theLayerRanges); @@ -273,21 +268,20 @@ void AlignmentParameterSelector::setTOBDetIdCuts(const edm::ParameterSet &pSet) pSet.getParameter >(*iParam).swap(theTOBDetIdRanges.theRodRanges); } else { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::setTOBDetIdCuts] " - << "Unknown parameter '" << *iParam << "'.\n"; + << "Unknown parameter '" << *iParam << "'.\n"; } } } //________________________________________________________________________________ -void AlignmentParameterSelector::setTECDetIdCuts(const edm::ParameterSet &pSet) -{ +void AlignmentParameterSelector::setTECDetIdCuts(const edm::ParameterSet &pSet) { // Allow non-specified arrays to be interpreted as empty (i.e. no selection), - // but take care that nothing unknown is configured (to fetch typos!). + // but take care that nothing unknown is configured (to fetch typos!). const std::vector parameterNames(pSet.getParameterNames()); - for (std::vector::const_iterator iParam = parameterNames.begin(), - iEnd = parameterNames.end(); iParam != iEnd; ++iParam) { - + for (std::vector::const_iterator iParam = parameterNames.begin(), iEnd = parameterNames.end(); + iParam != iEnd; + ++iParam) { // Calling swap is more efficient than assignment: if (*iParam == "wheelRanges") { pSet.getParameter >(*iParam).swap(theTECDetIdRanges.theWheelRanges); @@ -301,7 +295,7 @@ void AlignmentParameterSelector::setTECDetIdCuts(const edm::ParameterSet &pSet) pSet.getParameter >(*iParam).swap(theTECDetIdRanges.theSideRanges); } else { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::setTECDetIdCuts] " - << "Unknown parameter '" << *iParam << "'.\n"; + << "Unknown parameter '" << *iParam << "'.\n"; } } } @@ -309,54 +303,67 @@ void AlignmentParameterSelector::setTECDetIdCuts(const edm::ParameterSet &pSet) //________________________________________________________________________________ unsigned int AlignmentParameterSelector::addSelection(const std::string &name, const std::vector ¶mSel, - const edm::ParameterSet &pSet) -{ + const edm::ParameterSet &pSet) { this->setGeometryCuts(pSet); return this->addSelection(name, paramSel); } //________________________________________________________________________________ -unsigned int AlignmentParameterSelector::addSelection(const std::string &nameInput, - const std::vector ¶mSel) -{ - const std::string name(this->setSpecials(nameInput)); // possibly changing name +unsigned int AlignmentParameterSelector::addSelection(const std::string &nameInput, const std::vector ¶mSel) { + const std::string name(this->setSpecials(nameInput)); // possibly changing name unsigned int numAli = 0; //////////////////////////////////// // Generic Tracker Section //////////////////////////////////// - if (name.find("Tracker") == 0) { // string starts with "Tracker" + if (name.find("Tracker") == 0) { // string starts with "Tracker" if (!theTracker) { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::addSelection] " - << "Configuration requires access to AlignableTracker" - << " (for " << name << ") that is not initialized"; + << "Configuration requires access to AlignableTracker" + << " (for " << name << ") that is not initialized"; } - const std::string substructName(name, 7); // erase "Tracker" at the beginning + const std::string substructName(name, 7); // erase "Tracker" at the beginning numAli += this->add(theTracker->subStructures(substructName), paramSel); } //////////////////////////////////// // Old hardcoded, but geometry-independent tracker section (NOTE: no check on theTracker != 0) //////////////////////////////////// - else if (name == "AllDets") numAli += this->addAllDets(paramSel); - else if (name == "AllRods") numAli += this->addAllRods(paramSel); - else if (name == "AllLayers") numAli += this->addAllLayers(paramSel); - else if (name == "AllComponents") numAli += this->add(theTracker->components(), paramSel); - else if (name == "AllAlignables") numAli += this->addAllAlignables(paramSel); + else if (name == "AllDets") + numAli += this->addAllDets(paramSel); + else if (name == "AllRods") + numAli += this->addAllRods(paramSel); + else if (name == "AllLayers") + numAli += this->addAllLayers(paramSel); + else if (name == "AllComponents") + numAli += this->add(theTracker->components(), paramSel); + else if (name == "AllAlignables") + numAli += this->addAllAlignables(paramSel); // // TIB+TOB // - else if (name == "BarrelRods") numAli += this->add(theTracker->barrelRods(), paramSel); - else if (name == "BarrelDets") numAli += this->add(theTracker->barrelGeomDets(), paramSel); - else if (name == "BarrelLayers") numAli += this->add(theTracker->barrelLayers(), paramSel); - else if (name == "TOBDets") numAli += this->add(theTracker->outerBarrelGeomDets(), paramSel); - else if (name == "TOBRods") numAli += this->add(theTracker->outerBarrelRods(), paramSel); - else if (name == "TOBLayers") numAli += this->add(theTracker->outerBarrelLayers(), paramSel); - else if (name == "TOBHalfBarrels") numAli += this->add(theTracker->outerHalfBarrels(), paramSel); - else if (name == "TIBDets") numAli += this->add(theTracker->innerBarrelGeomDets(), paramSel); - else if (name == "TIBRods") numAli += this->add(theTracker->innerBarrelRods(), paramSel); - else if (name == "TIBLayers") numAli += this->add(theTracker->innerBarrelLayers(), paramSel); - else if (name == "TIBHalfBarrels") numAli += this->add(theTracker->innerHalfBarrels(), paramSel); + else if (name == "BarrelRods") + numAli += this->add(theTracker->barrelRods(), paramSel); + else if (name == "BarrelDets") + numAli += this->add(theTracker->barrelGeomDets(), paramSel); + else if (name == "BarrelLayers") + numAli += this->add(theTracker->barrelLayers(), paramSel); + else if (name == "TOBDets") + numAli += this->add(theTracker->outerBarrelGeomDets(), paramSel); + else if (name == "TOBRods") + numAli += this->add(theTracker->outerBarrelRods(), paramSel); + else if (name == "TOBLayers") + numAli += this->add(theTracker->outerBarrelLayers(), paramSel); + else if (name == "TOBHalfBarrels") + numAli += this->add(theTracker->outerHalfBarrels(), paramSel); + else if (name == "TIBDets") + numAli += this->add(theTracker->innerBarrelGeomDets(), paramSel); + else if (name == "TIBRods") + numAli += this->add(theTracker->innerBarrelRods(), paramSel); + else if (name == "TIBLayers") + numAli += this->add(theTracker->innerBarrelLayers(), paramSel); + else if (name == "TIBHalfBarrels") + numAli += this->add(theTracker->innerHalfBarrels(), paramSel); // // PXBarrel // @@ -372,11 +379,16 @@ unsigned int AlignmentParameterSelector::addSelection(const std::string &nameInp // // PXEndcap // - else if (name == "PXECDets") numAli += this->add(theTracker->pixelEndcapGeomDets(), paramSel); - else if (name == "PXECPetals") numAli += this->add(theTracker->pixelEndcapPetals(), paramSel); - else if (name == "PXECLayers") numAli += this->add(theTracker->pixelEndcapLayers(), paramSel); - else if (name == "PXECHalfCylinders") numAli += this->add(theTracker->pixelEndcapHalfCylinders(), paramSel); - else if (name == "PXEndCaps") numAli += this->add(theTracker->pixelEndCaps(), paramSel); + else if (name == "PXECDets") + numAli += this->add(theTracker->pixelEndcapGeomDets(), paramSel); + else if (name == "PXECPetals") + numAli += this->add(theTracker->pixelEndcapPetals(), paramSel); + else if (name == "PXECLayers") + numAli += this->add(theTracker->pixelEndcapLayers(), paramSel); + else if (name == "PXECHalfCylinders") + numAli += this->add(theTracker->pixelEndcapHalfCylinders(), paramSel); + else if (name == "PXEndCaps") + numAli += this->add(theTracker->pixelEndCaps(), paramSel); // // Pixel Barrel+endcap // @@ -393,23 +405,31 @@ unsigned int AlignmentParameterSelector::addSelection(const std::string &nameInp // // TID // - else if (name == "TIDs") numAli += this->add(theTracker->TIDs(), paramSel); - else if (name == "TIDLayers") numAli += this->add(theTracker->TIDLayers(), paramSel); - else if (name == "TIDRings") numAli += this->add(theTracker->TIDRings(), paramSel); - else if (name == "TIDDets") numAli += this->add(theTracker->TIDGeomDets(), paramSel); + else if (name == "TIDs") + numAli += this->add(theTracker->TIDs(), paramSel); + else if (name == "TIDLayers") + numAli += this->add(theTracker->TIDLayers(), paramSel); + else if (name == "TIDRings") + numAli += this->add(theTracker->TIDRings(), paramSel); + else if (name == "TIDDets") + numAli += this->add(theTracker->TIDGeomDets(), paramSel); // // TEC // - else if (name == "TECDets") numAli += this->add(theTracker->endcapGeomDets(), paramSel); - else if (name == "TECPetals") numAli += this->add(theTracker->endcapPetals(), paramSel); - else if (name == "TECLayers") numAli += this->add(theTracker->endcapLayers(), paramSel); - else if (name == "TECs") numAli += this->add(theTracker->endCaps(), paramSel); + else if (name == "TECDets") + numAli += this->add(theTracker->endcapGeomDets(), paramSel); + else if (name == "TECPetals") + numAli += this->add(theTracker->endcapPetals(), paramSel); + else if (name == "TECLayers") + numAli += this->add(theTracker->endcapLayers(), paramSel); + else if (name == "TECs") + numAli += this->add(theTracker->endCaps(), paramSel); // // StripEndcap (TID+TEC) // else if (name == "EndcapDets") { numAli += this->add(theTracker->TIDGeomDets(), paramSel); - numAli += this->add(theTracker->endcapGeomDets(), paramSel); + numAli += this->add(theTracker->endcapGeomDets(), paramSel); } else if (name == "EndcapPetals") { numAli += this->add(theTracker->TIDRings(), paramSel); numAli += this->add(theTracker->endcapPetals(), paramSel); @@ -423,7 +443,7 @@ unsigned int AlignmentParameterSelector::addSelection(const std::string &nameInp else if (name == "StripDets") { numAli += this->add(theTracker->barrelGeomDets(), paramSel); numAli += this->add(theTracker->TIDGeomDets(), paramSel); - numAli += this->add(theTracker->endcapGeomDets(), paramSel); + numAli += this->add(theTracker->endcapGeomDets(), paramSel); } else if (name == "StripRods") { numAli += this->add(theTracker->barrelRods(), paramSel); numAli += this->add(theTracker->TIDRings(), paramSel); @@ -438,70 +458,76 @@ unsigned int AlignmentParameterSelector::addSelection(const std::string &nameInp //////////////////////////////////// // Check if name contains muon and react if alignable muon not initialized else if (name.find("Muon") != std::string::npos) { - if (!theMuon) { + if (!theMuon) { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::addSelection] " - << "Configuration requires access to AlignableMuon" - << " which is not initialized"; - } - else if (name == "MuonDTLayers") add(theMuon->DTLayers(), paramSel); - else if (name == "MuonDTSuperLayers") add(theMuon->DTSuperLayers(), paramSel); - else if (name == "MuonDTChambers") add(theMuon->DTChambers(), paramSel); - else if (name == "MuonDTStations") add(theMuon->DTStations(), paramSel); - else if (name == "MuonDTWheels") add(theMuon->DTWheels(), paramSel); - else if (name == "MuonBarrel") add(theMuon->DTBarrel(), paramSel); - else if (name == "MuonCSCLayers") add(theMuon->CSCLayers(), paramSel); - else if (name == "MuonCSCRings") add(theMuon->CSCRings(), paramSel); - else if (name == "MuonCSCChambers") add(theMuon->CSCChambers(), paramSel); - else if (name == "MuonCSCStations") add(theMuon->CSCStations(), paramSel); - else if (name == "MuonEndcaps") add(theMuon->CSCEndcaps(), paramSel); + << "Configuration requires access to AlignableMuon" + << " which is not initialized"; + } else if (name == "MuonDTLayers") + add(theMuon->DTLayers(), paramSel); + else if (name == "MuonDTSuperLayers") + add(theMuon->DTSuperLayers(), paramSel); + else if (name == "MuonDTChambers") + add(theMuon->DTChambers(), paramSel); + else if (name == "MuonDTStations") + add(theMuon->DTStations(), paramSel); + else if (name == "MuonDTWheels") + add(theMuon->DTWheels(), paramSel); + else if (name == "MuonBarrel") + add(theMuon->DTBarrel(), paramSel); + else if (name == "MuonCSCLayers") + add(theMuon->CSCLayers(), paramSel); + else if (name == "MuonCSCRings") + add(theMuon->CSCRings(), paramSel); + else if (name == "MuonCSCChambers") + add(theMuon->CSCChambers(), paramSel); + else if (name == "MuonCSCStations") + add(theMuon->CSCStations(), paramSel); + else if (name == "MuonEndcaps") + add(theMuon->CSCEndcaps(), paramSel); //////////////////////////////////// // not found, but Muon //////////////////////////////////// else { - throw cms::Exception("BadConfig") <<"[AlignmentParameterSelector::addSelection]" - << ": Selection '" << name << "' invalid!"; + throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::addSelection]" + << ": Selection '" << name << "' invalid!"; } } //////////////////////////////////// // Generic Extra Alignable Section //////////////////////////////////// - else if (name.find("Extras") == 0) { // string starts with "Extras" + else if (name.find("Extras") == 0) { // string starts with "Extras" if (!theExtras) { throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::addSelection] " - << "Configuration requires access to AlignableExtras" - << " (for " << name << ") that is not initialized"; + << "Configuration requires access to AlignableExtras" + << " (for " << name << ") that is not initialized"; } - const std::string substructName(name, 6); // erase "Extras" at the beginning + const std::string substructName(name, 6); // erase "Extras" at the beginning numAli += this->add(theExtras->subStructures(substructName), paramSel); } // end of "name.find("Extras") != std::string::npos" else { - throw cms::Exception("BadConfig") <<"[AlignmentParameterSelector::addSelection]" - << ": Selection '" << name << "' invalid!"; + throw cms::Exception("BadConfig") << "[AlignmentParameterSelector::addSelection]" + << ": Selection '" << name << "' invalid!"; } - - this->setSpecials(""); // reset + + this->setSpecials(""); // reset return numAli; } //________________________________________________________________________________ -unsigned int AlignmentParameterSelector::add(const align::Alignables &alignables, - const std::vector ¶mSel) -{ +unsigned int AlignmentParameterSelector::add(const align::Alignables &alignables, const std::vector ¶mSel) { unsigned int numAli = 0; // loop on Alignable objects - for (align::Alignables::const_iterator iAli = alignables.begin(); - iAli != alignables.end(); ++iAli) { - - if (!this->layerDeselected(*iAli) // check layers - && !this->detUnitDeselected(*iAli) // check detunit selection - && !this->outsideGeometricalRanges(*iAli) // check geometrical ranges - && !this->outsideDetIdRanges(*iAli)) { // check DetId ranges + for (align::Alignables::const_iterator iAli = alignables.begin(); iAli != alignables.end(); ++iAli) { + if (!this->layerDeselected(*iAli) // check layers + && !this->detUnitDeselected(*iAli) // check detunit selection + && !this->outsideGeometricalRanges(*iAli) // check geometrical ranges + && !this->outsideDetIdRanges(*iAli)) { // check DetId ranges // all fine, so add to output arrays theSelectedAlignables.push_back(*iAli); theSelectedParameters.push_back(paramSel); @@ -513,248 +539,260 @@ unsigned int AlignmentParameterSelector::add(const align::Alignables &alignables } //_________________________________________________________________________ -bool AlignmentParameterSelector::layerDeselected(const Alignable *ali) const -{ +bool AlignmentParameterSelector::layerDeselected(const Alignable *ali) const { if (theOnlySS || theOnlyDS || theSelLayers) { TrackerAlignableId idProvider; - std::pair typeLayer = idProvider.typeAndLayerFromDetId(ali->id(), alignableTracker()->trackerTopology()); - int type = typeLayer.first; + std::pair typeLayer = idProvider.typeAndLayerFromDetId(ali->id(), alignableTracker()->trackerTopology()); + int type = typeLayer.first; int layer = typeLayer.second; - + // select on single/double sided barrel layers in TIB/TOB - if (theOnlySS // only single sided - && (std::abs(type) == SiStripDetId::TIB || std::abs(type) == SiStripDetId::TOB) - && layer <= 2) { + if (theOnlySS // only single sided + && (std::abs(type) == SiStripDetId::TIB || std::abs(type) == SiStripDetId::TOB) && layer <= 2) { return true; } - if (theOnlyDS // only double sided - && (std::abs(type) == SiStripDetId::TIB || std::abs(type) == SiStripDetId::TOB) - && layer > 2) { + if (theOnlyDS // only double sided + && (std::abs(type) == SiStripDetId::TIB || std::abs(type) == SiStripDetId::TOB) && layer > 2) { return true; } - + // reject layers if (theSelLayers && (layer < theMinLayer || layer > theMaxLayer)) { return true; } } - - return false; // do not deselect... + + return false; // do not deselect... } //_________________________________________________________________________ -bool AlignmentParameterSelector::detUnitDeselected(const Alignable *ali) const -{ - +bool AlignmentParameterSelector::detUnitDeselected(const Alignable *ali) const { if (theRphiOrStereoDetUnit != Both && ali->alignableObjectId() == align::AlignableDetUnit) { - const SiStripDetId detId(ali->geomDetId()); // do not know yet whether right type... - if (detId.det() == DetId::Tracker - && (detId.subdetId() == SiStripDetId::TIB || detId.subdetId() == SiStripDetId::TID || - detId.subdetId() == SiStripDetId::TOB || detId.subdetId() == SiStripDetId::TEC)) { + const SiStripDetId detId(ali->geomDetId()); // do not know yet whether right type... + if (detId.det() == DetId::Tracker && + (detId.subdetId() == SiStripDetId::TIB || detId.subdetId() == SiStripDetId::TID || + detId.subdetId() == SiStripDetId::TOB || detId.subdetId() == SiStripDetId::TEC)) { // We have a DetUnit in strip, so check for a selection of stereo/rphi (DetUnits in 1D layers are rphi): - if ((theRphiOrStereoDetUnit == Stereo && !detId.stereo()) - || (theRphiOrStereoDetUnit == Rphi && detId.stereo())) { - return true; + if ((theRphiOrStereoDetUnit == Stereo && !detId.stereo()) || (theRphiOrStereoDetUnit == Rphi && detId.stereo())) { + return true; } } } - return false; // do not deselect... + return false; // do not deselect... } //_________________________________________________________________________ -bool AlignmentParameterSelector::outsideGeometricalRanges(const Alignable *alignable) const -{ - const align::PositionType& position(alignable->globalPosition()); - - if (!theRangesEta.empty() && !this->insideRanges((position.eta()), theRangesEta)) return true; - if (!theRangesPhi.empty() && !this->insideRanges((position.phi()), theRangesPhi, true))return true; - if (!theRangesR.empty() && !this->insideRanges((position.perp()), theRangesR)) return true; - if (!theRangesX.empty() && !this->insideRanges((position.x()), theRangesX)) return true; - if (!theRangesY.empty() && !this->insideRanges((position.y()), theRangesY)) return true; - if (!theRangesZ.empty() && !this->insideRanges((position.z()), theRangesZ)) return true; - +bool AlignmentParameterSelector::outsideGeometricalRanges(const Alignable *alignable) const { + const align::PositionType &position(alignable->globalPosition()); + + if (!theRangesEta.empty() && !this->insideRanges((position.eta()), theRangesEta)) + return true; + if (!theRangesPhi.empty() && !this->insideRanges((position.phi()), theRangesPhi, true)) + return true; + if (!theRangesR.empty() && !this->insideRanges((position.perp()), theRangesR)) + return true; + if (!theRangesX.empty() && !this->insideRanges((position.x()), theRangesX)) + return true; + if (!theRangesY.empty() && !this->insideRanges((position.y()), theRangesY)) + return true; + if (!theRangesZ.empty() && !this->insideRanges((position.z()), theRangesZ)) + return true; + return false; } //_________________________________________________________________________ -bool AlignmentParameterSelector::outsideDetIdRanges(const Alignable *alignable) const -{ +bool AlignmentParameterSelector::outsideDetIdRanges(const Alignable *alignable) const { //const DetId detId(alignable->geomDetId()); const DetId detId(alignable->id()); const int subdetId = detId.subdetId(); - + if (alignableTracker()) { + const TrackerTopology *tTopo = alignableTracker()->trackerTopology(); - const TrackerTopology* tTopo = alignableTracker()->trackerTopology(); - - if (!theDetIds.empty() && - !this->isMemberOfVector((detId.rawId()), theDetIds)) return true; - if (!theDetIdRanges.empty() && - !this->insideRanges((detId.rawId()), theDetIdRanges)) return true; - if (!theExcludedDetIds.empty() && - this->isMemberOfVector((detId.rawId()), theExcludedDetIds)) return true; - if (!theExcludedDetIdRanges.empty() && - this->insideRanges((detId.rawId()), theExcludedDetIdRanges)) return true; - - if (detId.det()==DetId::Tracker) { - - if (subdetId==static_cast(PixelSubdetector::PixelBarrel)) { - if (!thePXBDetIdRanges.theLadderRanges.empty() && - !this->insideRanges(tTopo->pxbLadder(detId), thePXBDetIdRanges.theLadderRanges)) return true; - if (!thePXBDetIdRanges.theLayerRanges.empty() && - !this->insideRanges(tTopo->pxbLayer(detId), thePXBDetIdRanges.theLayerRanges)) return true; - if (!thePXBDetIdRanges.theModuleRanges.empty() && - !this->insideRanges(tTopo->pxbModule(detId), thePXBDetIdRanges.theModuleRanges)) return true; - } - - if (subdetId==static_cast(PixelSubdetector::PixelEndcap)) { - if (!thePXFDetIdRanges.theBladeRanges.empty() && - !this->insideRanges(tTopo->pxfBlade(detId), thePXFDetIdRanges.theBladeRanges)) return true; - if (!thePXFDetIdRanges.theDiskRanges.empty() && - !this->insideRanges(tTopo->pxfDisk(detId), thePXFDetIdRanges.theDiskRanges)) return true; - if (!thePXFDetIdRanges.theModuleRanges.empty() && - !this->insideRanges(tTopo->pxfModule(detId), thePXFDetIdRanges.theModuleRanges)) return true; - if (!thePXFDetIdRanges.thePanelRanges.empty() && - !this->insideRanges(tTopo->pxfPanel(detId), thePXFDetIdRanges.thePanelRanges)) return true; - if (!thePXFDetIdRanges.theSideRanges.empty() && - !this->insideRanges(tTopo->pxfSide(detId), thePXFDetIdRanges.theSideRanges)) return true; - } - - if (subdetId==static_cast(SiStripDetId::TIB)) { - if (!theTIBDetIdRanges.theLayerRanges.empty() && - !this->insideRanges(tTopo->tibLayer(detId), theTIBDetIdRanges.theLayerRanges)) return true; - if (!theTIBDetIdRanges.theModuleRanges.empty() && - !this->insideRanges(tTopo->tibModule(detId), theTIBDetIdRanges.theModuleRanges)) return true; - if (!theTIBDetIdRanges.theSideRanges.empty() && - !this->insideRanges(tTopo->tibSide(detId), theTIBDetIdRanges.theSideRanges)) return true; - if (!theTIBDetIdRanges.theStringRanges.empty() && - !this->insideRanges(tTopo->tibString(detId), theTIBDetIdRanges.theStringRanges)) return true; - } - - if (subdetId==static_cast(SiStripDetId::TID)) { - if (!theTIDDetIdRanges.theDiskRanges.empty() && - !this->insideRanges(tTopo->tidWheel(detId), theTIDDetIdRanges.theDiskRanges)) return true; - if (!theTIDDetIdRanges.theModuleRanges.empty() && - !this->insideRanges(tTopo->tidModule(detId), theTIDDetIdRanges.theModuleRanges)) return true; - if (!theTIDDetIdRanges.theRingRanges.empty() && - !this->insideRanges(tTopo->tidRing(detId), theTIDDetIdRanges.theRingRanges)) return true; - if (!theTIDDetIdRanges.theSideRanges.empty() && - !this->insideRanges(tTopo->tidSide(detId), theTIDDetIdRanges.theSideRanges)) return true; - } - - if (subdetId==static_cast(SiStripDetId::TOB)) { - if (!theTOBDetIdRanges.theLayerRanges.empty() && - !this->insideRanges(tTopo->tobLayer(detId), theTOBDetIdRanges.theLayerRanges)) return true; - if (!theTOBDetIdRanges.theModuleRanges.empty() && - !this->insideRanges(tTopo->tobModule(detId), theTOBDetIdRanges.theModuleRanges)) return true; - if (!theTOBDetIdRanges.theRodRanges.empty() && - !this->insideRanges(tTopo->tobRod(detId), theTOBDetIdRanges.theRodRanges)) return true; - if (!theTOBDetIdRanges.theSideRanges.empty() && - !this->insideRanges(tTopo->tobSide(detId), theTOBDetIdRanges.theSideRanges)) return true; - } + if (!theDetIds.empty() && !this->isMemberOfVector((detId.rawId()), theDetIds)) + return true; + if (!theDetIdRanges.empty() && !this->insideRanges((detId.rawId()), theDetIdRanges)) + return true; + if (!theExcludedDetIds.empty() && this->isMemberOfVector((detId.rawId()), theExcludedDetIds)) + return true; + if (!theExcludedDetIdRanges.empty() && this->insideRanges((detId.rawId()), theExcludedDetIdRanges)) + return true; + + if (detId.det() == DetId::Tracker) { + if (subdetId == static_cast(PixelSubdetector::PixelBarrel)) { + if (!thePXBDetIdRanges.theLadderRanges.empty() && + !this->insideRanges(tTopo->pxbLadder(detId), thePXBDetIdRanges.theLadderRanges)) + return true; + if (!thePXBDetIdRanges.theLayerRanges.empty() && + !this->insideRanges(tTopo->pxbLayer(detId), thePXBDetIdRanges.theLayerRanges)) + return true; + if (!thePXBDetIdRanges.theModuleRanges.empty() && + !this->insideRanges(tTopo->pxbModule(detId), thePXBDetIdRanges.theModuleRanges)) + return true; + } + + if (subdetId == static_cast(PixelSubdetector::PixelEndcap)) { + if (!thePXFDetIdRanges.theBladeRanges.empty() && + !this->insideRanges(tTopo->pxfBlade(detId), thePXFDetIdRanges.theBladeRanges)) + return true; + if (!thePXFDetIdRanges.theDiskRanges.empty() && + !this->insideRanges(tTopo->pxfDisk(detId), thePXFDetIdRanges.theDiskRanges)) + return true; + if (!thePXFDetIdRanges.theModuleRanges.empty() && + !this->insideRanges(tTopo->pxfModule(detId), thePXFDetIdRanges.theModuleRanges)) + return true; + if (!thePXFDetIdRanges.thePanelRanges.empty() && + !this->insideRanges(tTopo->pxfPanel(detId), thePXFDetIdRanges.thePanelRanges)) + return true; + if (!thePXFDetIdRanges.theSideRanges.empty() && + !this->insideRanges(tTopo->pxfSide(detId), thePXFDetIdRanges.theSideRanges)) + return true; + } + + if (subdetId == static_cast(SiStripDetId::TIB)) { + if (!theTIBDetIdRanges.theLayerRanges.empty() && + !this->insideRanges(tTopo->tibLayer(detId), theTIBDetIdRanges.theLayerRanges)) + return true; + if (!theTIBDetIdRanges.theModuleRanges.empty() && + !this->insideRanges(tTopo->tibModule(detId), theTIBDetIdRanges.theModuleRanges)) + return true; + if (!theTIBDetIdRanges.theSideRanges.empty() && + !this->insideRanges(tTopo->tibSide(detId), theTIBDetIdRanges.theSideRanges)) + return true; + if (!theTIBDetIdRanges.theStringRanges.empty() && + !this->insideRanges(tTopo->tibString(detId), theTIBDetIdRanges.theStringRanges)) + return true; + } - if (subdetId==static_cast(SiStripDetId::TEC)) { - if (!theTECDetIdRanges.theWheelRanges.empty() && - !this->insideRanges(tTopo->tecWheel(detId), theTECDetIdRanges.theWheelRanges)) return true; - if (!theTECDetIdRanges.thePetalRanges.empty() && - !this->insideRanges(tTopo->tecPetalNumber(detId), theTECDetIdRanges.thePetalRanges)) return true; - if (!theTECDetIdRanges.theModuleRanges.empty() && - !this->insideRanges(tTopo->tecModule(detId), theTECDetIdRanges.theModuleRanges)) return true; - if (!theTECDetIdRanges.theRingRanges.empty() && - !this->insideRanges(tTopo->tecRing(detId), theTECDetIdRanges.theRingRanges)) return true; - if (!theTECDetIdRanges.theSideRanges.empty() && - !this->insideRanges(tTopo->tecSide(detId), theTECDetIdRanges.theSideRanges)) return true; + if (subdetId == static_cast(SiStripDetId::TID)) { + if (!theTIDDetIdRanges.theDiskRanges.empty() && + !this->insideRanges(tTopo->tidWheel(detId), theTIDDetIdRanges.theDiskRanges)) + return true; + if (!theTIDDetIdRanges.theModuleRanges.empty() && + !this->insideRanges(tTopo->tidModule(detId), theTIDDetIdRanges.theModuleRanges)) + return true; + if (!theTIDDetIdRanges.theRingRanges.empty() && + !this->insideRanges(tTopo->tidRing(detId), theTIDDetIdRanges.theRingRanges)) + return true; + if (!theTIDDetIdRanges.theSideRanges.empty() && + !this->insideRanges(tTopo->tidSide(detId), theTIDDetIdRanges.theSideRanges)) + return true; + } + + if (subdetId == static_cast(SiStripDetId::TOB)) { + if (!theTOBDetIdRanges.theLayerRanges.empty() && + !this->insideRanges(tTopo->tobLayer(detId), theTOBDetIdRanges.theLayerRanges)) + return true; + if (!theTOBDetIdRanges.theModuleRanges.empty() && + !this->insideRanges(tTopo->tobModule(detId), theTOBDetIdRanges.theModuleRanges)) + return true; + if (!theTOBDetIdRanges.theRodRanges.empty() && + !this->insideRanges(tTopo->tobRod(detId), theTOBDetIdRanges.theRodRanges)) + return true; + if (!theTOBDetIdRanges.theSideRanges.empty() && + !this->insideRanges(tTopo->tobSide(detId), theTOBDetIdRanges.theSideRanges)) + return true; + } + + if (subdetId == static_cast(SiStripDetId::TEC)) { + if (!theTECDetIdRanges.theWheelRanges.empty() && + !this->insideRanges(tTopo->tecWheel(detId), theTECDetIdRanges.theWheelRanges)) + return true; + if (!theTECDetIdRanges.thePetalRanges.empty() && + !this->insideRanges(tTopo->tecPetalNumber(detId), theTECDetIdRanges.thePetalRanges)) + return true; + if (!theTECDetIdRanges.theModuleRanges.empty() && + !this->insideRanges(tTopo->tecModule(detId), theTECDetIdRanges.theModuleRanges)) + return true; + if (!theTECDetIdRanges.theRingRanges.empty() && + !this->insideRanges(tTopo->tecRing(detId), theTECDetIdRanges.theRingRanges)) + return true; + if (!theTECDetIdRanges.theSideRanges.empty() && + !this->insideRanges(tTopo->tecSide(detId), theTECDetIdRanges.theSideRanges)) + return true; + } } } - } - + return false; } //_________________________________________________________________________ -template bool AlignmentParameterSelector::insideRanges(T value, - const std::vector &ranges, - bool isPhi) const -{ +template +bool AlignmentParameterSelector::insideRanges(T value, const std::vector &ranges, bool isPhi) const { // might become templated on ? - if (ranges.size()%2 != 0) { - cms::Exception("BadConfig") << "@SUB=AlignmentParameterSelector::insideRanges" - << " need even number of entries in ranges instead of " - << ranges.size(); + if (ranges.size() % 2 != 0) { + cms::Exception("BadConfig") << "@SUB=AlignmentParameterSelector::insideRanges" + << " need even number of entries in ranges instead of " << ranges.size(); return false; } for (unsigned int i = 0; i < ranges.size(); i += 2) { - if (isPhi) { // mapping into (-pi,+pi] and checking for range including sign flip area + if (isPhi) { // mapping into (-pi,+pi] and checking for range including sign flip area Geom::Phi rangePhi1(ranges[i]); - Geom::Phi rangePhi2(ranges[i+1]); + Geom::Phi rangePhi2(ranges[i + 1]); Geom::Phi valuePhi(value); - if (rangePhi1 <= valuePhi && valuePhi < rangePhi2) { // 'normal' + if (rangePhi1 <= valuePhi && valuePhi < rangePhi2) { // 'normal' return true; } - if (rangePhi2 < rangePhi1 && (rangePhi1 <= valuePhi || valuePhi < rangePhi2)) {// 'sign flip' + if (rangePhi2 < rangePhi1 && (rangePhi1 <= valuePhi || valuePhi < rangePhi2)) { // 'sign flip' return true; } - } else if (ranges[i] <= value && value < ranges[i+1]) { + } else if (ranges[i] <= value && value < ranges[i + 1]) { return true; } } - + return false; } //_________________________________________________________________________ -template<> bool AlignmentParameterSelector::insideRanges(int value, - const std::vector &ranges, - bool /*isPhi*/) const -{ - if (ranges.size()%2 != 0) { - cms::Exception("BadConfig") << "@SUB=AlignmentParameterSelector::insideRanges" - << " need even number of entries in ranges instead of " - << ranges.size(); +template <> +bool AlignmentParameterSelector::insideRanges(int value, const std::vector &ranges, bool /*isPhi*/) const { + if (ranges.size() % 2 != 0) { + cms::Exception("BadConfig") << "@SUB=AlignmentParameterSelector::insideRanges" + << " need even number of entries in ranges instead of " << ranges.size(); return false; } for (unsigned int i = 0; i < ranges.size(); i += 2) { - if (ranges[i] <= value && value <= ranges[i+1]) return true; + if (ranges[i] <= value && value <= ranges[i + 1]) + return true; } - + return false; } -bool AlignmentParameterSelector::isMemberOfVector(int value, const std::vector &values) const -{ - if (std::find(values.begin(), values.end(), value)!=values.end()) return true; +bool AlignmentParameterSelector::isMemberOfVector(int value, const std::vector &values) const { + if (std::find(values.begin(), values.end(), value) != values.end()) + return true; return false; } //__________________________________________________________________________________________________ -std::vector -AlignmentParameterSelector::decompose(const std::string &s, std::string::value_type delimiter) const -{ - +std::vector AlignmentParameterSelector::decompose(const std::string &s, + std::string::value_type delimiter) const { std::vector result; std::string::size_type previousPos = 0; while (true) { const std::string::size_type delimiterPos = s.find(delimiter, previousPos); if (delimiterPos == std::string::npos) { - result.push_back(s.substr(previousPos)); // until end + result.push_back(s.substr(previousPos)); // until end break; } result.push_back(s.substr(previousPos, delimiterPos - previousPos)); - previousPos = delimiterPos + 1; // +1: skip delimiter + previousPos = delimiterPos + 1; // +1: skip delimiter } return result; } //__________________________________________________________________________________________________ -std::vector AlignmentParameterSelector::convertParamSel(const std::string &selString) const -{ - +std::vector AlignmentParameterSelector::convertParamSel(const std::string &selString) const { // Convert selString into vector of same length. // Note: Old implementation in AlignmentParameterBuilder was rigid in length, // expecting RigidBodyAlignmentParameters::N_PARAM. @@ -769,17 +807,15 @@ std::vector AlignmentParameterSelector::convertParamSel(const std::string return result; } - //________________________________________________________________________________ -std::string AlignmentParameterSelector::setSpecials(const std::string &name) -{ +std::string AlignmentParameterSelector::setSpecials(const std::string &name) { // Use new string only, although direct erasing of found indicator causes problems for 'DSS', // but 'DSS' makes absolutely no sense! - std::string newName(name); + std::string newName(name); const std::string::size_type ss = newName.rfind("SS"); if (ss != std::string::npos) { - newName.erase(ss, 2); // 2: length of 'SS' + newName.erase(ss, 2); // 2: length of 'SS' theOnlySS = true; } else { theOnlySS = false; @@ -787,19 +823,19 @@ std::string AlignmentParameterSelector::setSpecials(const std::string &name) const std::string::size_type ds = newName.rfind("DS"); if (ds != std::string::npos) { - newName.erase(ds, 2); // 2: length of 'DS' + newName.erase(ds, 2); // 2: length of 'DS' theOnlyDS = true; } else { theOnlyDS = false; } - + const std::string::size_type size = newName.size(); const std::string::size_type layers = newName.rfind("Layers"); - if (layers != std::string::npos && size - layers - 2 == 6 // 2 digits, 6: length of 'Layers' - && isdigit(newName[size-1]) && isdigit(newName[size-2])) { + if (layers != std::string::npos && size - layers - 2 == 6 // 2 digits, 6: length of 'Layers' + && isdigit(newName[size - 1]) && isdigit(newName[size - 2])) { theSelLayers = true; - theMinLayer = newName[size-2] - '0'; - theMaxLayer = newName[size-1] - '0'; + theMinLayer = newName[size - 2] - '0'; + theMaxLayer = newName[size - 1] - '0'; newName.erase(layers); } else { theSelLayers = false; @@ -811,72 +847,67 @@ std::string AlignmentParameterSelector::setSpecials(const std::string &name) if (newName.rfind("Unit") != std::string::npos) { const std::string::size_type uRph = newName.rfind("UnitRphi"); if (uRph != std::string::npos) { - newName.erase(uRph + 4, 4); // keep 'Unit' (4) and erase 'Rphi' (4) + newName.erase(uRph + 4, 4); // keep 'Unit' (4) and erase 'Rphi' (4) theRphiOrStereoDetUnit = Rphi; } const std::string::size_type uSte = newName.rfind("UnitStereo"); if (uSte != std::string::npos) { - newName.erase(uSte + 4, 6); // keep 'Unit' (4) and erase 'Stereo' (6) + newName.erase(uSte + 4, 6); // keep 'Unit' (4) and erase 'Stereo' (6) theRphiOrStereoDetUnit = Stereo; } } if (newName != name) { - LogDebug("Alignment") << "@SUB=AlignmentParameterSelector::setSpecials" - << name << " becomes " << newName << ", makes theOnlySS " << theOnlySS - << ", theOnlyDS " << theOnlyDS << ", theSelLayers " << theSelLayers - << ", theMinLayer " << theMinLayer << ", theMaxLayer " << theMaxLayer - << ", theRphiOrStereoDetUnit " << theRphiOrStereoDetUnit; + LogDebug("Alignment") << "@SUB=AlignmentParameterSelector::setSpecials" << name << " becomes " << newName + << ", makes theOnlySS " << theOnlySS << ", theOnlyDS " << theOnlyDS << ", theSelLayers " + << theSelLayers << ", theMinLayer " << theMinLayer << ", theMaxLayer " << theMaxLayer + << ", theRphiOrStereoDetUnit " << theRphiOrStereoDetUnit; } return newName; } //________________________________________________________________________________ -unsigned int AlignmentParameterSelector::addAllDets(const std::vector ¶mSel) -{ +unsigned int AlignmentParameterSelector::addAllDets(const std::vector ¶mSel) { unsigned int numAli = 0; - numAli += this->add(theTracker->barrelGeomDets(), paramSel); // TIB+TOB - numAli += this->add(theTracker->endcapGeomDets(), paramSel); // TEC - numAli += this->add(theTracker->TIDGeomDets(), paramSel); // TID - numAli += this->add(theTracker->pixelHalfBarrelGeomDets(), paramSel); // PixelBarrel - numAli += this->add(theTracker->pixelEndcapGeomDets(), paramSel); // PixelEndcap + numAli += this->add(theTracker->barrelGeomDets(), paramSel); // TIB+TOB + numAli += this->add(theTracker->endcapGeomDets(), paramSel); // TEC + numAli += this->add(theTracker->TIDGeomDets(), paramSel); // TID + numAli += this->add(theTracker->pixelHalfBarrelGeomDets(), paramSel); // PixelBarrel + numAli += this->add(theTracker->pixelEndcapGeomDets(), paramSel); // PixelEndcap return numAli; } //________________________________________________________________________________ -unsigned int AlignmentParameterSelector::addAllRods(const std::vector ¶mSel) -{ +unsigned int AlignmentParameterSelector::addAllRods(const std::vector ¶mSel) { unsigned int numAli = 0; - numAli += this->add(theTracker->barrelRods(), paramSel); // TIB+TOB - numAli += this->add(theTracker->pixelHalfBarrelLadders(), paramSel); // PixelBarrel - numAli += this->add(theTracker->endcapPetals(), paramSel); // TEC - numAli += this->add(theTracker->TIDRings(), paramSel); // TID - numAli += this->add(theTracker->pixelEndcapPetals(), paramSel); // PixelEndcap + numAli += this->add(theTracker->barrelRods(), paramSel); // TIB+TOB + numAli += this->add(theTracker->pixelHalfBarrelLadders(), paramSel); // PixelBarrel + numAli += this->add(theTracker->endcapPetals(), paramSel); // TEC + numAli += this->add(theTracker->TIDRings(), paramSel); // TID + numAli += this->add(theTracker->pixelEndcapPetals(), paramSel); // PixelEndcap return numAli; } //________________________________________________________________________________ -unsigned int AlignmentParameterSelector::addAllLayers(const std::vector ¶mSel) -{ +unsigned int AlignmentParameterSelector::addAllLayers(const std::vector ¶mSel) { unsigned int numAli = 0; - numAli += this->add(theTracker->barrelLayers(), paramSel); // TIB+TOB - numAli += this->add(theTracker->pixelHalfBarrelLayers(), paramSel); // PixelBarrel - numAli += this->add(theTracker->endcapLayers(), paramSel); // TEC - numAli += this->add(theTracker->TIDLayers(), paramSel); // TID - numAli += this->add(theTracker->pixelEndcapLayers(), paramSel); // PixelEndcap + numAli += this->add(theTracker->barrelLayers(), paramSel); // TIB+TOB + numAli += this->add(theTracker->pixelHalfBarrelLayers(), paramSel); // PixelBarrel + numAli += this->add(theTracker->endcapLayers(), paramSel); // TEC + numAli += this->add(theTracker->TIDLayers(), paramSel); // TID + numAli += this->add(theTracker->pixelEndcapLayers(), paramSel); // PixelEndcap return numAli; } //________________________________________________________________________________ -unsigned int AlignmentParameterSelector::addAllAlignables(const std::vector ¶mSel) -{ +unsigned int AlignmentParameterSelector::addAllAlignables(const std::vector ¶mSel) { unsigned int numAli = 0; numAli += this->addAllDets(paramSel); diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterStore.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterStore.cc index 1204248e9089a..fb6c77d4b94f9 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterStore.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParameterStore.cc @@ -26,13 +26,11 @@ #include "Geometry/CommonTopologies/interface/SurfaceDeformationFactory.h" //__________________________________________________________________________________________________ -AlignmentParameterStore::AlignmentParameterStore( const align::Alignables &alis, - const edm::ParameterSet& config ) : - theAlignables(alis) -{ +AlignmentParameterStore::AlignmentParameterStore(const align::Alignables& alis, const edm::ParameterSet& config) + : theAlignables(alis) { if (config.getUntrackedParameter("UseExtendedCorrelations")) { - theCorrelationsStore = new AlignmentExtendedCorrelationsStore - (config.getParameter("ExtendedCorrelationsConfig")); + theCorrelationsStore = + new AlignmentExtendedCorrelationsStore(config.getParameter("ExtendedCorrelationsConfig")); } else { theCorrelationsStore = new AlignmentCorrelationsStore(); } @@ -43,240 +41,210 @@ AlignmentParameterStore::AlignmentParameterStore( const align::Alignables &alis, // set hierarchy vs averaging constraints theTypeOfConstraints = NONE; const std::string cfgStrTypeOfConstraints(config.getParameter("TypeOfConstraints")); - if( cfgStrTypeOfConstraints == "hierarchy" ) { + if (cfgStrTypeOfConstraints == "hierarchy") { theTypeOfConstraints = HIERARCHY_CONSTRAINTS; - } else if( cfgStrTypeOfConstraints == "approximate_averaging" ) { + } else if (cfgStrTypeOfConstraints == "approximate_averaging") { theTypeOfConstraints = APPROX_AVERAGING_CONSTRAINTS; - edm::LogWarning("Alignment") << "@SUB=AlignmentParameterStore" - << "\n\n\n******* WARNING ******************************************\n" - << "Using approximate implementation of averaging constraints." - << "This is not recommended." - << "Consider to use 'hierarchy' constraints:" - << " AlignmentProducer.ParameterStore.TypeOfConstraints = cms.string('hierarchy')\n\n\n"; + edm::LogWarning("Alignment") + << "@SUB=AlignmentParameterStore" + << "\n\n\n******* WARNING ******************************************\n" + << "Using approximate implementation of averaging constraints." + << "This is not recommended." + << "Consider to use 'hierarchy' constraints:" + << " AlignmentProducer.ParameterStore.TypeOfConstraints = cms.string('hierarchy')\n\n\n"; } else { edm::LogError("BadArgument") << "@SUB=AlignmentParameterStore" - << "Unknown type of hierarchy constraints '" << cfgStrTypeOfConstraints << "'"; + << "Unknown type of hierarchy constraints '" << cfgStrTypeOfConstraints << "'"; } } //__________________________________________________________________________________________________ -AlignmentParameterStore::~AlignmentParameterStore() -{ - delete theCorrelationsStore; -} +AlignmentParameterStore::~AlignmentParameterStore() { delete theCorrelationsStore; } //__________________________________________________________________________________________________ -CompositeAlignmentParameters -AlignmentParameterStore::selectParameters( const std::vector& alignabledets ) const -{ +CompositeAlignmentParameters AlignmentParameterStore::selectParameters( + const std::vector& alignabledets) const { std::vector detOrUnits; detOrUnits.reserve(alignabledets.size()); std::vector::const_iterator it, iEnd; - for ( it = alignabledets.begin(), iEnd = alignabledets.end(); it != iEnd; ++it) + for (it = alignabledets.begin(), iEnd = alignabledets.end(); it != iEnd; ++it) detOrUnits.push_back(AlignableDetOrUnitPtr(*it)); return this->selectParameters(detOrUnits); } //__________________________________________________________________________________________________ -CompositeAlignmentParameters -AlignmentParameterStore::selectParameters( const std::vector& alignabledets ) const -{ - +CompositeAlignmentParameters AlignmentParameterStore::selectParameters( + const std::vector& alignabledets) const { align::Alignables alignables; - std::map alidettoalimap; - std::map aliposmap; - std::map alilenmap; - int nparam=0; + std::map alidettoalimap; + std::map aliposmap; + std::map alilenmap; + int nparam = 0; // iterate over AlignableDet's - for( std::vector::const_iterator iad = alignabledets.begin(); - iad != alignabledets.end(); ++iad ) - { - Alignable* ali = alignableFromAlignableDet( *iad ); - if ( ali ) - { - alidettoalimap[ *iad ] = ali; // Add to map + for (std::vector::const_iterator iad = alignabledets.begin(); iad != alignabledets.end(); + ++iad) { + Alignable* ali = alignableFromAlignableDet(*iad); + if (ali) { + alidettoalimap[*iad] = ali; // Add to map // Check if Alignable already there, insert into vector if not - if ( find(alignables.begin(),alignables.end(),ali) == alignables.end() ) - { - alignables.push_back(ali); - AlignmentParameters* ap = ali->alignmentParameters(); - nparam += ap->numSelected(); + if (find(alignables.begin(), alignables.end(), ali) == alignables.end()) { + alignables.push_back(ali); + AlignmentParameters* ap = ali->alignmentParameters(); + nparam += ap->numSelected(); } } } - AlgebraicVector* selpar = new AlgebraicVector( nparam, 0 ); - AlgebraicSymMatrix* selcov = new AlgebraicSymMatrix( nparam, 0 ); + AlgebraicVector* selpar = new AlgebraicVector(nparam, 0); + AlgebraicSymMatrix* selcov = new AlgebraicSymMatrix(nparam, 0); // Fill in parameters and corresponding covariance matricess - int ipos = 1; // NOTE: .sub indices start from 1 + int ipos = 1; // NOTE: .sub indices start from 1 align::Alignables::const_iterator it1; - for( it1 = alignables.begin(); it1 != alignables.end(); ++it1 ) - { + for (it1 = alignables.begin(); it1 != alignables.end(); ++it1) { AlignmentParameters* ap = (*it1)->alignmentParameters(); - selpar->sub( ipos, ap->selectedParameters() ); - selcov->sub( ipos, ap->selectedCovariance() ); + selpar->sub(ipos, ap->selectedParameters()); + selcov->sub(ipos, ap->selectedCovariance()); int npar = ap->numSelected(); - aliposmap[*it1]=ipos; - alilenmap[*it1]=npar; - ipos +=npar; + aliposmap[*it1] = ipos; + alilenmap[*it1] = npar; + ipos += npar; } // Fill in the correlations. Has to be an extra loop, because the // AlignmentExtendedCorrelationsStore (if used) needs the // alignables' covariance matrices already present. ipos = 1; - for( it1 = alignables.begin(); it1 != alignables.end(); ++it1 ) - { - int jpos=1; + for (it1 = alignables.begin(); it1 != alignables.end(); ++it1) { + int jpos = 1; // Look for correlations between alignables align::Alignables::const_iterator it2; - for( it2 = alignables.begin(); it2 != it1; ++it2 ) - { - theCorrelationsStore->correlations( *it1, *it2, *selcov, ipos-1, jpos-1 ); + for (it2 = alignables.begin(); it2 != it1; ++it2) { + theCorrelationsStore->correlations(*it1, *it2, *selcov, ipos - 1, jpos - 1); jpos += (*it2)->alignmentParameters()->numSelected(); } ipos += (*it1)->alignmentParameters()->numSelected(); } - AlignmentParametersData::DataContainer data( new AlignmentParametersData( selpar, selcov ) ); - CompositeAlignmentParameters aap( data, alignables, alidettoalimap, aliposmap, alilenmap ); + AlignmentParametersData::DataContainer data(new AlignmentParametersData(selpar, selcov)); + CompositeAlignmentParameters aap(data, alignables, alidettoalimap, aliposmap, alilenmap); return aap; } - //__________________________________________________________________________________________________ -CompositeAlignmentParameters -AlignmentParameterStore::selectParameters( const align::Alignables& alignables ) const -{ - +CompositeAlignmentParameters AlignmentParameterStore::selectParameters(const align::Alignables& alignables) const { align::Alignables selectedAlignables; - std::map alidettoalimap; // This map won't be filled!!! - std::map aliposmap; - std::map alilenmap; - int nparam=0; + std::map alidettoalimap; // This map won't be filled!!! + std::map aliposmap; + std::map alilenmap; + int nparam = 0; // iterate over Alignable's align::Alignables::const_iterator ita; - for ( ita = alignables.begin(); ita != alignables.end(); ++ita ) - { + for (ita = alignables.begin(); ita != alignables.end(); ++ita) { // Check if Alignable already there, insert into vector if not - if ( find(selectedAlignables.begin(), selectedAlignables.end(), *ita) == selectedAlignables.end() ) - { - selectedAlignables.push_back( *ita ); + if (find(selectedAlignables.begin(), selectedAlignables.end(), *ita) == selectedAlignables.end()) { + selectedAlignables.push_back(*ita); AlignmentParameters* ap = (*ita)->alignmentParameters(); nparam += ap->numSelected(); } } - AlgebraicVector* selpar = new AlgebraicVector( nparam, 0 ); - AlgebraicSymMatrix* selcov = new AlgebraicSymMatrix( nparam, 0 ); + AlgebraicVector* selpar = new AlgebraicVector(nparam, 0); + AlgebraicSymMatrix* selcov = new AlgebraicSymMatrix(nparam, 0); // Fill in parameters and corresponding covariance matrices - int ipos = 1; // NOTE: .sub indices start from 1 + int ipos = 1; // NOTE: .sub indices start from 1 align::Alignables::const_iterator it1; - for( it1 = selectedAlignables.begin(); it1 != selectedAlignables.end(); ++it1 ) - { + for (it1 = selectedAlignables.begin(); it1 != selectedAlignables.end(); ++it1) { AlignmentParameters* ap = (*it1)->alignmentParameters(); - selpar->sub( ipos, ap->selectedParameters() ); - selcov->sub( ipos, ap->selectedCovariance() ); + selpar->sub(ipos, ap->selectedParameters()); + selcov->sub(ipos, ap->selectedCovariance()); int npar = ap->numSelected(); - aliposmap[*it1]=ipos; - alilenmap[*it1]=npar; - ipos +=npar; + aliposmap[*it1] = ipos; + alilenmap[*it1] = npar; + ipos += npar; } // Fill in the correlations. Has to be an extra loop, because the // AlignmentExtendedCorrelationsStore (if used) needs the // alignables' covariance matrices already present. ipos = 1; - for( it1 = selectedAlignables.begin(); it1 != selectedAlignables.end(); ++it1 ) - { - int jpos=1; + for (it1 = selectedAlignables.begin(); it1 != selectedAlignables.end(); ++it1) { + int jpos = 1; // Look for correlations between alignables align::Alignables::const_iterator it2; - for( it2 = selectedAlignables.begin(); it2 != it1; ++it2 ) - { - theCorrelationsStore->correlations( *it1, *it2, *selcov, ipos-1, jpos-1 ); + for (it2 = selectedAlignables.begin(); it2 != it1; ++it2) { + theCorrelationsStore->correlations(*it1, *it2, *selcov, ipos - 1, jpos - 1); jpos += (*it2)->alignmentParameters()->numSelected(); } ipos += (*it1)->alignmentParameters()->numSelected(); } - AlignmentParametersData::DataContainer data( new AlignmentParametersData( selpar, selcov ) ); - CompositeAlignmentParameters aap( data, selectedAlignables, alidettoalimap, aliposmap, alilenmap ); + AlignmentParametersData::DataContainer data(new AlignmentParametersData(selpar, selcov)); + CompositeAlignmentParameters aap(data, selectedAlignables, alidettoalimap, aliposmap, alilenmap); return aap; } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::updateParameters( const CompositeAlignmentParameters& aap, bool updateCorrelations ) -{ - +void AlignmentParameterStore::updateParameters(const CompositeAlignmentParameters& aap, bool updateCorrelations) { align::Alignables alignables = aap.components(); const AlgebraicVector& parameters = aap.parameters(); const AlgebraicSymMatrix& covariance = aap.covariance(); - int ipos = 1; // NOTE: .sub indices start from 1 + int ipos = 1; // NOTE: .sub indices start from 1 // Loop over alignables - for( align::Alignables::const_iterator it=alignables.begin(); it != alignables.end(); ++it ) - { - // Update parameters and local covariance + for (align::Alignables::const_iterator it = alignables.begin(); it != alignables.end(); ++it) { + // Update parameters and local covariance AlignmentParameters* ap = (*it)->alignmentParameters(); int nsel = ap->numSelected(); - AlgebraicVector subvec = parameters.sub( ipos, ipos+nsel-1 ); - AlgebraicSymMatrix subcov = covariance.sub( ipos, ipos+nsel-1 ); - AlignmentParameters* apnew = ap->cloneFromSelected( subvec, subcov ); - (*it)->setAlignmentParameters( apnew ); - + AlgebraicVector subvec = parameters.sub(ipos, ipos + nsel - 1); + AlgebraicSymMatrix subcov = covariance.sub(ipos, ipos + nsel - 1); + AlignmentParameters* apnew = ap->cloneFromSelected(subvec, subcov); + (*it)->setAlignmentParameters(apnew); + // Now update correlations between detectors - if ( updateCorrelations ) - { + if (updateCorrelations) { int jpos = 1; - for( align::Alignables::const_iterator it2 = alignables.begin(); it2 != it; ++it2 ) - { - theCorrelationsStore->setCorrelations( *it, *it2, covariance, ipos-1, jpos-1 ); - jpos += (*it2)->alignmentParameters()->numSelected(); + for (align::Alignables::const_iterator it2 = alignables.begin(); it2 != it; ++it2) { + theCorrelationsStore->setCorrelations(*it, *it2, covariance, ipos - 1, jpos - 1); + jpos += (*it2)->alignmentParameters()->numSelected(); } } - ipos+=nsel; + ipos += nsel; } - } - //__________________________________________________________________________________________________ -align::Alignables AlignmentParameterStore::validAlignables(void) const -{ +align::Alignables AlignmentParameterStore::validAlignables(void) const { align::Alignables result; - for (align::Alignables::const_iterator iali = theAlignables.begin(); - iali != theAlignables.end(); ++iali) - if ( (*iali)->alignmentParameters()->isValid() ) result.push_back(*iali); + for (align::Alignables::const_iterator iali = theAlignables.begin(); iali != theAlignables.end(); ++iali) + if ((*iali)->alignmentParameters()->isValid()) + result.push_back(*iali); LogDebug("Alignment") << "@SUB=AlignmentParameterStore::validAlignables" - << "Valid alignables: " << result.size() - << "out of " << theAlignables.size(); + << "Valid alignables: " << result.size() << "out of " << theAlignables.size(); return result; } //__________________________________________________________________________________________________ -Alignable* AlignmentParameterStore::alignableFromAlignableDet( const AlignableDetOrUnitPtr& _alignableDet ) const -{ +Alignable* AlignmentParameterStore::alignableFromAlignableDet(const AlignableDetOrUnitPtr& _alignableDet) const { AlignableDetOrUnitPtr alignableDet = _alignableDet; - Alignable *mother = alignableDet; + Alignable* mother = alignableDet; while (mother) { - if (mother->alignmentParameters()) return mother; + if (mother->alignmentParameters()) + return mother; mother = mother->mother(); } @@ -284,157 +252,129 @@ Alignable* AlignmentParameterStore::alignableFromAlignableDet( const AlignableDe } //__________________________________________________________________________________________________ -void AlignmentParameterStore::applyParameters(void) -{ +void AlignmentParameterStore::applyParameters(void) { align::Alignables::const_iterator iali; - for ( iali = theAlignables.begin(); iali != theAlignables.end(); ++iali) - applyParameters( *iali ); + for (iali = theAlignables.begin(); iali != theAlignables.end(); ++iali) + applyParameters(*iali); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::applyParameters(Alignable* alignable) -{ - - AlignmentParameters *pars = (alignable ? alignable->alignmentParameters() : nullptr); +void AlignmentParameterStore::applyParameters(Alignable* alignable) { + AlignmentParameters* pars = (alignable ? alignable->alignmentParameters() : nullptr); if (!pars) { - throw cms::Exception("BadAlignable") - << "applyParameters: provided alignable does not have alignment parameters"; + throw cms::Exception("BadAlignable") << "applyParameters: provided alignable does not have alignment parameters"; } pars->apply(); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::resetParameters(void) -{ +void AlignmentParameterStore::resetParameters(void) { // Erase contents of correlation map theCorrelationsStore->resetCorrelations(); // Iterate over alignables in the store and reset parameters align::Alignables::const_iterator iali; - for ( iali = theAlignables.begin(); iali != theAlignables.end(); ++iali ) - resetParameters( *iali ); + for (iali = theAlignables.begin(); iali != theAlignables.end(); ++iali) + resetParameters(*iali); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::resetParameters( Alignable* ali ) -{ - if ( ali ) - { +void AlignmentParameterStore::resetParameters(Alignable* ali) { + if (ali) { // Get alignment parameters for this alignable AlignmentParameters* ap = ali->alignmentParameters(); - if ( ap ) - { - int npar=ap->numSelected(); - - AlgebraicVector par(npar,0); - AlgebraicSymMatrix cov(npar,0); - AlignmentParameters* apnew = ap->cloneFromSelected(par,cov); + if (ap) { + int npar = ap->numSelected(); + + AlgebraicVector par(npar, 0); + AlgebraicSymMatrix cov(npar, 0); + AlignmentParameters* apnew = ap->cloneFromSelected(par, cov); ali->setAlignmentParameters(apnew); apnew->setValid(false); - } - else + } else edm::LogError("BadArgument") << "@SUB=AlignmentParameterStore::resetParameters" - << "alignable has no alignment parameter"; - } - else + << "alignable has no alignment parameter"; + } else edm::LogError("BadArgument") << "@SUB=AlignmentParameterStore::resetParameters" << "argument is NULL"; } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::cacheTransformations(void) -{ +void AlignmentParameterStore::cacheTransformations(void) { align::Alignables::const_iterator iali; - for ( iali = theAlignables.begin(); iali != theAlignables.end(); ++iali) + for (iali = theAlignables.begin(); iali != theAlignables.end(); ++iali) (*iali)->cacheTransformation(); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::cacheTransformations(const align::RunNumber& run) -{ - for (const auto& iali: theAlignables) iali->cacheTransformation(run); +void AlignmentParameterStore::cacheTransformations(const align::RunNumber& run) { + for (const auto& iali : theAlignables) + iali->cacheTransformation(run); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::restoreCachedTransformations(void) -{ +void AlignmentParameterStore::restoreCachedTransformations(void) { align::Alignables::const_iterator iali; - for ( iali = theAlignables.begin(); iali != theAlignables.end(); ++iali) + for (iali = theAlignables.begin(); iali != theAlignables.end(); ++iali) (*iali)->restoreCachedTransformation(); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::restoreCachedTransformations(const align::RunNumber& run) -{ - for (const auto& iali: theAlignables) iali->restoreCachedTransformation(run); +void AlignmentParameterStore::restoreCachedTransformations(const align::RunNumber& run) { + for (const auto& iali : theAlignables) + iali->restoreCachedTransformation(run); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::acquireRelativeParameters(void) -{ - +void AlignmentParameterStore::acquireRelativeParameters(void) { unsigned int nAlignables = theAlignables.size(); - for (unsigned int i = 0; i < nAlignables; ++i) - { + for (unsigned int i = 0; i < nAlignables; ++i) { Alignable* ali = theAlignables[i]; - RigidBodyAlignmentParameters* ap = - dynamic_cast( ali->alignmentParameters() ); + RigidBodyAlignmentParameters* ap = dynamic_cast(ali->alignmentParameters()); - if ( !ap ) - throw cms::Exception("BadAlignable") - << "acquireRelativeParameters: " - << "provided alignable does not have rigid body alignment parameters"; + if (!ap) + throw cms::Exception("BadAlignable") << "acquireRelativeParameters: " + << "provided alignable does not have rigid body alignment parameters"; + + AlgebraicVector par(ap->size(), 0); + AlgebraicSymMatrix cov(ap->size(), 0); - AlgebraicVector par( ap->size(),0 ); - AlgebraicSymMatrix cov( ap->size(), 0 ); - // Get displacement and transform global->local - align::LocalVector dloc = ali->surface().toLocal( ali->displacement() ); - par[0]=dloc.x(); - par[1]=dloc.y(); - par[2]=dloc.z(); + align::LocalVector dloc = ali->surface().toLocal(ali->displacement()); + par[0] = dloc.x(); + par[1] = dloc.y(); + par[2] = dloc.z(); // Transform to local euler angles - align::EulerAngles euloc = align::toAngles( ali->surface().toLocal( ali->rotation() ) ); - par[3]=euloc(1); - par[4]=euloc(2); - par[5]=euloc(3); - + align::EulerAngles euloc = align::toAngles(ali->surface().toLocal(ali->rotation())); + par[3] = euloc(1); + par[4] = euloc(2); + par[5] = euloc(3); + // Clone parameters - RigidBodyAlignmentParameters* apnew = ap->clone(par,cov); - + RigidBodyAlignmentParameters* apnew = ap->clone(par, cov); + ali->setAlignmentParameters(apnew); } } - //__________________________________________________________________________________________________ // Get type/layer from Alignable // type: -6 -5 -4 -3 -2 -1 1 2 3 4 5 6 // TEC- TOB- TID- TIB- PxEC- PxBR- PxBr+ PxEC+ TIB+ TID+ TOB+ TEC+ // Layers start from zero -std::pair AlignmentParameterStore::typeAndLayer(const Alignable* ali, const TrackerTopology* tTopo) const -{ - return TrackerAlignableId().typeAndLayerFromDetId( ali->id(), tTopo ); +std::pair AlignmentParameterStore::typeAndLayer(const Alignable* ali, const TrackerTopology* tTopo) const { + return TrackerAlignableId().typeAndLayerFromDetId(ali->id(), tTopo); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore:: -applyAlignableAbsolutePositions(const align::Alignables& alivec, const AlignablePositions& newpos, int& ierr) -{ - unsigned int nappl=0; - ierr=0; +void AlignmentParameterStore::applyAlignableAbsolutePositions(const align::Alignables& alivec, + const AlignablePositions& newpos, + int& ierr) { + unsigned int nappl = 0; + ierr = 0; // Iterate over list of alignables for (align::Alignables::const_iterator iali = alivec.begin(); iali != alivec.end(); ++iali) { @@ -443,14 +383,12 @@ applyAlignableAbsolutePositions(const align::Alignables& alivec, const Alignable align::StructureType typeId = ali->alignableObjectId(); // Find corresponding entry in AlignablePositions - bool found=false; + bool found = false; for (AlignablePositions::const_iterator ipos = newpos.begin(); ipos != newpos.end(); ++ipos) { if (id == ipos->id() && typeId == ipos->objId()) { if (found) { - edm::LogError("DuplicatePosition") - << "New positions for alignable found more than once!"; - } - else { + edm::LogError("DuplicatePosition") << "New positions for alignable found more than once!"; + } else { // New position/rotation const align::PositionType& pnew = ipos->pos(); const align::RotationType& rnew = ipos->rot(); @@ -460,10 +398,10 @@ applyAlignableAbsolutePositions(const align::Alignables& alivec, const Alignable const align::RotationType& rold = ali->globalRotation(); // Current surf. deformation std::vector > dold_id_pairs; - SurfaceDeformation* dold_obj=nullptr; + SurfaceDeformation* dold_obj = nullptr; SurfaceDeformationFactory::Type dtype = SurfaceDeformationFactory::kNoDeformations; std::vector dold; - if (1 == ali->surfaceDeformationIdPairs(dold_id_pairs)){ // might not have any... + if (1 == ali->surfaceDeformationIdPairs(dold_id_pairs)) { // might not have any... dold_obj = dold_id_pairs[0].second; dold = dold_obj->parameters(); dtype = (SurfaceDeformationFactory::Type)dold_obj->type(); @@ -472,7 +410,7 @@ applyAlignableAbsolutePositions(const align::Alignables& alivec, const Alignable // shift needed to move from current to new position align::GlobalVector posDiff = pnew - pold; align::RotationType rotDiff = rold.multiplyInverse(rnew); - align::rectify(rotDiff); // correct for rounding errors + align::rectify(rotDiff); // correct for rounding errors ali->move(posDiff); ali->rotateInGlobalFrame(rotDiff); LogDebug("NewPosition") << "moving by:" << posDiff; @@ -480,25 +418,31 @@ applyAlignableAbsolutePositions(const align::Alignables& alivec, const Alignable // add the surface deformations // If an old surface deformation record exists, ensure that the added deformation has the same type and size. - if (!dold.empty() && dtype != SurfaceDeformationFactory::kNoDeformations && dnew.size()==dold.size()){ - std::vector defDiff; defDiff.reserve(dold.size()); - for (unsigned int i = 0; i < dold.size(); i++) defDiff.push_back(dnew[i] - dold[i]); + if (!dold.empty() && dtype != SurfaceDeformationFactory::kNoDeformations && dnew.size() == dold.size()) { + std::vector defDiff; + defDiff.reserve(dold.size()); + for (unsigned int i = 0; i < dold.size(); i++) + defDiff.push_back(dnew[i] - dold[i]); auto deform = SurfaceDeformationFactory::create(dtype, defDiff); edm::LogInfo("Alignment") << "@SUB=AlignmentParameterStore::applyAlignableAbsolutePositions" - << "Adding surface deformation of type " << SurfaceDeformationFactory::surfaceDeformationTypeName((SurfaceDeformationFactory::Type)deform->type()) - << ", size " << defDiff.size() << " and first element " << defDiff.at(0) - << " to alignable with id / type: " << id << " / " << typeId; + << "Adding surface deformation of type " + << SurfaceDeformationFactory::surfaceDeformationTypeName( + (SurfaceDeformationFactory::Type)deform->type()) + << ", size " << defDiff.size() << " and first element " << defDiff.at(0) + << " to alignable with id / type: " << id << " / " << typeId; ali->addSurfaceDeformation(deform, true); delete deform; } // In case no old surface deformation record exists, only ensure that the new surface deformation record has size>0. Size check is done elsewhere. - else if (!dnew.empty()){ + else if (!dnew.empty()) { auto deform = SurfaceDeformationFactory::create(dnew); edm::LogInfo("Alignment") << "@SUB=AlignmentParameterStore::applyAlignableAbsolutePositions" - << "Setting surface deformation of type " << SurfaceDeformationFactory::surfaceDeformationTypeName((SurfaceDeformationFactory::Type)deform->type()) - << ", size " << dnew.size() << " and first element " << dnew.at(0) - << " to alignable with id / type: " << id << " / " << typeId; - ali->addSurfaceDeformation(deform, true); // Equivalent to setSurfaceDeformation in this case + << "Setting surface deformation of type " + << SurfaceDeformationFactory::surfaceDeformationTypeName( + (SurfaceDeformationFactory::Type)deform->type()) + << ", size " << dnew.size() << " and first element " << dnew.at(0) + << " to alignable with id / type: " << id << " / " << typeId; + ali->addSurfaceDeformation(deform, true); // Equivalent to setSurfaceDeformation in this case delete deform; } // If there is no new surface deformation record, do nothing. @@ -508,29 +452,26 @@ applyAlignableAbsolutePositions(const align::Alignables& alivec, const Alignable // (*iali)->addAlignmentPositionError(ape); // (*iali)->addAlignmentPositionErrorFromRotation(rot); - found=true; + found = true; ++nappl; } } } } - if (nappl< newpos.size()) + if (nappl < newpos.size()) edm::LogError("Mismatch") << "Applied only " << nappl << " new positions" - << " out of " << newpos.size(); - - LogDebug("NewPositions") << "Applied new positions for " << nappl - << " out of " << alivec.size() <<" alignables."; + << " out of " << newpos.size(); + LogDebug("NewPositions") << "Applied new positions for " << nappl << " out of " << alivec.size() << " alignables."; } - //__________________________________________________________________________________________________ -void AlignmentParameterStore:: -applyAlignableRelativePositions(const align::Alignables& alivec, const AlignableShifts& shifts, int& ierr) -{ - ierr=0; - unsigned int nappl=0; +void AlignmentParameterStore::applyAlignableRelativePositions(const align::Alignables& alivec, + const AlignableShifts& shifts, + int& ierr) { + ierr = 0; + unsigned int nappl = 0; unsigned int nAlignables = alivec.size(); for (unsigned int i = 0; i < nAlignables; ++i) { @@ -544,16 +485,14 @@ applyAlignableRelativePositions(const align::Alignables& alivec, const Alignable for (AlignableShifts::const_iterator ipos = shifts.begin(); ipos != shifts.end(); ++ipos) { if (id == ipos->id() && typeId == ipos->objId()) { if (found) { - edm::LogError("DuplicatePosition") - << "New positions for alignable found more than once!"; - } - else { + edm::LogError("DuplicatePosition") << "New positions for alignable found more than once!"; + } else { // Current surf. deformation std::vector > dold_id_pairs; - SurfaceDeformation* dold_obj=nullptr; + SurfaceDeformation* dold_obj = nullptr; SurfaceDeformationFactory::Type dtype = SurfaceDeformationFactory::kNoDeformations; std::vector dold; - if (1 == ali->surfaceDeformationIdPairs(dold_id_pairs)){ // might not have any... + if (1 == ali->surfaceDeformationIdPairs(dold_id_pairs)) { // might not have any... dold_obj = dold_id_pairs[0].second; dold = dold_obj->parameters(); dtype = (SurfaceDeformationFactory::Type)dold_obj->type(); @@ -564,23 +503,27 @@ applyAlignableRelativePositions(const align::Alignables& alivec, const Alignable const std::vector& defDiff = ipos->deformationParameters(); // If an old surface deformation record exists, ensure that the added deformation has the same type and size. - if (!dold.empty() && dtype != SurfaceDeformationFactory::kNoDeformations && defDiff.size()==dold.size()){ + if (!dold.empty() && dtype != SurfaceDeformationFactory::kNoDeformations && defDiff.size() == dold.size()) { auto deform = SurfaceDeformationFactory::create(dtype, defDiff); edm::LogInfo("Alignment") << "@SUB=AlignmentParameterStore::applyAlignableRelativePositions" - << "Adding surface deformation of type " << SurfaceDeformationFactory::surfaceDeformationTypeName((SurfaceDeformationFactory::Type)deform->type()) - << ", size " << defDiff.size() << " and first element " << defDiff.at(0) - << " to alignable with id / type: " << id << " / " << typeId; + << "Adding surface deformation of type " + << SurfaceDeformationFactory::surfaceDeformationTypeName( + (SurfaceDeformationFactory::Type)deform->type()) + << ", size " << defDiff.size() << " and first element " << defDiff.at(0) + << " to alignable with id / type: " << id << " / " << typeId; ali->addSurfaceDeformation(deform, true); delete deform; } // In case no old surface deformation record exists, only ensure that the new surface deformation record has size>0. Size check is done elsewhere. - else if (!defDiff.empty()){ + else if (!defDiff.empty()) { auto deform = SurfaceDeformationFactory::create(defDiff); edm::LogInfo("Alignment") << "@SUB=AlignmentParameterStore::applyAlignableRelativePositions" - << "Setting surface deformation of type " << SurfaceDeformationFactory::surfaceDeformationTypeName((SurfaceDeformationFactory::Type)deform->type()) - << ", size " << defDiff.size() << " and first element " << defDiff.at(0) - << " to alignable with id / type: " << id << " / " << typeId; - ali->addSurfaceDeformation(deform, true); // Equivalent to setSurfaceDeformation in this case + << "Setting surface deformation of type " + << SurfaceDeformationFactory::surfaceDeformationTypeName( + (SurfaceDeformationFactory::Type)deform->type()) + << ", size " << defDiff.size() << " and first element " << defDiff.at(0) + << " to alignable with id / type: " << id << " / " << typeId; + ali->addSurfaceDeformation(deform, true); // Equivalent to setSurfaceDeformation in this case delete deform; } // If there is no new surface deformation record, do nothing. @@ -590,7 +533,7 @@ applyAlignableRelativePositions(const align::Alignables& alivec, const Alignable //ali->addAlignmentPositionError(ape); //ali->addAlignmentPositionErrorFromRotation(rnew); - found=true; + found = true; ++nappl; } } @@ -599,215 +542,197 @@ applyAlignableRelativePositions(const align::Alignables& alivec, const Alignable if (nappl < shifts.size()) edm::LogError("Mismatch") << "Applied only " << nappl << " new positions" - << " out of " << shifts.size(); + << " out of " << shifts.size(); LogDebug("NewPositions") << "Applied new positions for " << nappl << " alignables."; } - - //__________________________________________________________________________________________________ -void AlignmentParameterStore::attachAlignmentParameters( const Parameters& parvec, int& ierr ) -{ - attachAlignmentParameters( theAlignables, parvec, ierr); +void AlignmentParameterStore::attachAlignmentParameters(const Parameters& parvec, int& ierr) { + attachAlignmentParameters(theAlignables, parvec, ierr); } - - //__________________________________________________________________________________________________ -void AlignmentParameterStore::attachAlignmentParameters( const align::Alignables& alivec, - const Parameters& parvec, int& ierr ) -{ +void AlignmentParameterStore::attachAlignmentParameters(const align::Alignables& alivec, + const Parameters& parvec, + int& ierr) { int ipass = 0; int ifail = 0; ierr = 0; // Iterate over alignables - for ( align::Alignables::const_iterator iali = alivec.begin(); iali != alivec.end(); ++iali ) - { + for (align::Alignables::const_iterator iali = alivec.begin(); iali != alivec.end(); ++iali) { // Iterate over Parameters - bool found=false; - for ( Parameters::const_iterator ipar = parvec.begin(); ipar != parvec.end(); ++ipar) - { + bool found = false; + for (Parameters::const_iterator ipar = parvec.begin(); ipar != parvec.end(); ++ipar) { // Get new alignment parameters - AlignmentParameters* ap = *ipar; + AlignmentParameters* ap = *ipar; - // Check if parameters belong to alignable - if ( ap->alignable() == (*iali) ) - { - if (!found) - { + // Check if parameters belong to alignable + if (ap->alignable() == (*iali)) { + if (!found) { (*iali)->setAlignmentParameters(ap); ++ipass; - found=true; - } - else edm::LogError("Alignment") << "@SUB=AlignmentParameterStore::attachAlignmentParameters" - << "More than one parameters for Alignable."; + found = true; + } else + edm::LogError("Alignment") << "@SUB=AlignmentParameterStore::attachAlignmentParameters" + << "More than one parameters for Alignable."; } } - if (!found) ++ifail; + if (!found) + ++ifail; } - if (ifail>0) ierr=-1; - - LogDebug("attachAlignmentParameters") << " Parameters, Alignables: " << parvec.size() << "," - << alivec.size() << "\n pass,fail: " << ipass << ","<< ifail; -} + if (ifail > 0) + ierr = -1; + LogDebug("attachAlignmentParameters") << " Parameters, Alignables: " << parvec.size() << "," << alivec.size() + << "\n pass,fail: " << ipass << "," << ifail; +} //__________________________________________________________________________________________________ -void AlignmentParameterStore::attachCorrelations( const Correlations& cormap, - bool overwrite, int& ierr ) -{ - attachCorrelations( theAlignables, cormap, overwrite, ierr ); +void AlignmentParameterStore::attachCorrelations(const Correlations& cormap, bool overwrite, int& ierr) { + attachCorrelations(theAlignables, cormap, overwrite, ierr); } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::attachCorrelations( const align::Alignables& alivec, - const Correlations& cormap, - bool overwrite, int& ierr ) -{ - ierr=0; - int icount=0; +void AlignmentParameterStore::attachCorrelations(const align::Alignables& alivec, + const Correlations& cormap, + bool overwrite, + int& ierr) { + ierr = 0; + int icount = 0; // Iterate over correlations - for ( Correlations::const_iterator icor = cormap.begin(); icor!=cormap.end(); ++icor ) - { - AlgebraicMatrix mat=(*icor).second; + for (Correlations::const_iterator icor = cormap.begin(); icor != cormap.end(); ++icor) { + AlgebraicMatrix mat = (*icor).second; Alignable* ali1 = (*icor).first.first; Alignable* ali2 = (*icor).first.second; // Check if alignables exist - if ( find( alivec.begin(), alivec.end(), ali1 ) != alivec.end() && - find( alivec.begin(), alivec.end(), ali2 ) != alivec.end() ) - { + if (find(alivec.begin(), alivec.end(), ali1) != alivec.end() && + find(alivec.begin(), alivec.end(), ali2) != alivec.end()) { // Check if correlations already existing between these alignables - if ( !theCorrelationsStore->correlationsAvailable(ali1,ali2) || (overwrite) ) - { - theCorrelationsStore->setCorrelations(ali1,ali2,mat); - ++icount; - } - else edm::LogInfo("AlreadyExists") << "Correlation existing and not overwritten"; - } - else edm::LogInfo("IgnoreCorrelation") << "Ignoring correlation with no alignables!"; + if (!theCorrelationsStore->correlationsAvailable(ali1, ali2) || (overwrite)) { + theCorrelationsStore->setCorrelations(ali1, ali2, mat); + ++icount; + } else + edm::LogInfo("AlreadyExists") << "Correlation existing and not overwritten"; + } else + edm::LogInfo("IgnoreCorrelation") << "Ignoring correlation with no alignables!"; } - LogDebug( "attachCorrelations" ) << " Alignables,Correlations: " << alivec.size() <<","<< cormap.size() - << "\n applied: " << icount ; - + LogDebug("attachCorrelations") << " Alignables,Correlations: " << alivec.size() << "," << cormap.size() + << "\n applied: " << icount; } - //__________________________________________________________________________________________________ -void AlignmentParameterStore:: -attachUserVariables( const align::Alignables& alivec, - const std::vector& uvarvec, int& ierr ) -{ - ierr=0; +void AlignmentParameterStore::attachUserVariables(const align::Alignables& alivec, + const std::vector& uvarvec, + int& ierr) { + ierr = 0; - LogDebug("DumpArguments") << "size of alivec: " << alivec.size() - << "\nsize of uvarvec: " << uvarvec.size(); + LogDebug("DumpArguments") << "size of alivec: " << alivec.size() << "\nsize of uvarvec: " << uvarvec.size(); - std::vector::const_iterator iuvar=uvarvec.begin(); + std::vector::const_iterator iuvar = uvarvec.begin(); - for ( align::Alignables::const_iterator iali=alivec.begin(); iali!=alivec.end(); ++iali, ++iuvar ) - { + for (align::Alignables::const_iterator iali = alivec.begin(); iali != alivec.end(); ++iali, ++iuvar) { AlignmentParameters* ap = (*iali)->alignmentParameters(); AlignmentUserVariables* uvarnew = (*iuvar); ap->setUserVariables(uvarnew); } } - //__________________________________________________________________________________________________ -void AlignmentParameterStore::setAlignmentPositionError( const align::Alignables& alivec, - double valshift, double valrot ) -{ +void AlignmentParameterStore::setAlignmentPositionError(const align::Alignables& alivec, + double valshift, + double valrot) { unsigned int nAlignables = alivec.size(); - for (unsigned int i = 0; i < nAlignables; ++i) - { + for (unsigned int i = 0; i < nAlignables; ++i) { Alignable* ali = alivec[i]; - // First reset APE - AlignmentPositionError nulApe(0,0,0); + // First reset APE + AlignmentPositionError nulApe(0, 0, 0); ali->setAlignmentPositionError(nulApe, true); // Set APE from displacement - AlignmentPositionError ape(valshift,valshift,valshift); - if ( valshift > 0. ) ali->addAlignmentPositionError(ape, true); - else ali->setAlignmentPositionError(ape, true); - // GF: Resetting and setting as above does not really make sense to me, - // and adding to zero or setting is the same! I'd just do + AlignmentPositionError ape(valshift, valshift, valshift); + if (valshift > 0.) + ali->addAlignmentPositionError(ape, true); + else + ali->setAlignmentPositionError(ape, true); + // GF: Resetting and setting as above does not really make sense to me, + // and adding to zero or setting is the same! I'd just do //ali->setAlignmentPositionError(AlignmentPositionError ape(valshift,valshift,valshift),true); // Set APE from rotation align::EulerAngles r(3); - r(1)=valrot; r(2)=valrot; r(3)=valrot; + r(1) = valrot; + r(2) = valrot; + r(3) = valrot; ali->addAlignmentPositionErrorFromRotation(align::toMatrix(r), true); } - LogDebug("StoreAPE") << "Store APE from shift: " << valshift - << "\nStore APE from rotation: " << valrot; + LogDebug("StoreAPE") << "Store APE from shift: " << valshift << "\nStore APE from rotation: " << valrot; } //__________________________________________________________________________________________________ -bool AlignmentParameterStore -::hierarchyConstraints(const Alignable *ali, const align::Alignables &aliComps, - std::vector > ¶mIdsVecOut, - std::vector > &factorsVecOut, - bool all, double epsilon) const -{ +bool AlignmentParameterStore ::hierarchyConstraints(const Alignable* ali, + const align::Alignables& aliComps, + std::vector >& paramIdsVecOut, + std::vector >& factorsVecOut, + bool all, + double epsilon) const { // Weak point if all = false: // Ignores constraints between non-subsequent levels in case the parameter is not considered in // the intermediate level, e.g. global z for dets and layers is aligned, but not for rods! - if (!ali || !ali->alignmentParameters()) return false; + if (!ali || !ali->alignmentParameters()) + return false; - const std::vector &aliSel= ali->alignmentParameters()->selector(); + const std::vector& aliSel = ali->alignmentParameters()->selector(); paramIdsVecOut.clear(); factorsVecOut.clear(); bool firstComp = true; - for (align::Alignables::const_iterator iComp = aliComps.begin(), iCompE = aliComps.end(); - iComp != iCompE; ++iComp) { - + for (align::Alignables::const_iterator iComp = aliComps.begin(), iCompE = aliComps.end(); iComp != iCompE; ++iComp) { const ParametersToParametersDerivatives p2pDerivs(**iComp, *ali); if (!p2pDerivs.isOK()) { // std::cerr << (*iComp)->alignmentParameters()->type() << " " // << ali->alignmentParameters()->type() << std::endl; - throw cms::Exception("BadConfig") - << "AlignmentParameterStore::hierarchyConstraints" - << " Bad match of types of AlignmentParameters classes.\n"; + throw cms::Exception("BadConfig") << "AlignmentParameterStore::hierarchyConstraints" + << " Bad match of types of AlignmentParameters classes.\n"; return false; } - const std::vector &aliCompSel = (*iComp)->alignmentParameters()->selector(); + const std::vector& aliCompSel = (*iComp)->alignmentParameters()->selector(); for (unsigned int iParMast = 0, iParMastUsed = 0; iParMast < aliSel.size(); ++iParMast) { - if (!all && !aliSel[iParMast]) continue;// no higher level parameter & constraint deselected - if (firstComp) { // fill output with empty arrays - paramIdsVecOut.push_back(std::vector()); - factorsVecOut.push_back(std::vector()); + if (!all && !aliSel[iParMast]) + continue; // no higher level parameter & constraint deselected + if (firstComp) { // fill output with empty arrays + paramIdsVecOut.push_back(std::vector()); + factorsVecOut.push_back(std::vector()); } for (unsigned int iParComp = 0; iParComp < aliCompSel.size(); ++iParComp) { - if (aliCompSel[iParComp]) { - double factor = 0.; - if( theTypeOfConstraints == HIERARCHY_CONSTRAINTS ) { - // hierachy constraints - factor = p2pDerivs(iParMast, iParComp); - } else if( theTypeOfConstraints == APPROX_AVERAGING_CONSTRAINTS ) { - // CHK poor mans averaging constraints - factor = p2pDerivs(iParMast, iParComp); - if (iParMast < 3 && (iParComp % 9) >= 3) factor = 0.; - } - if (fabs(factor) > epsilon) { - paramIdsVecOut[iParMastUsed].push_back(ParameterId(*iComp, iParComp)); - factorsVecOut[iParMastUsed].push_back(factor); - } - } + if (aliCompSel[iParComp]) { + double factor = 0.; + if (theTypeOfConstraints == HIERARCHY_CONSTRAINTS) { + // hierachy constraints + factor = p2pDerivs(iParMast, iParComp); + } else if (theTypeOfConstraints == APPROX_AVERAGING_CONSTRAINTS) { + // CHK poor mans averaging constraints + factor = p2pDerivs(iParMast, iParComp); + if (iParMast < 3 && (iParComp % 9) >= 3) + factor = 0.; + } + if (fabs(factor) > epsilon) { + paramIdsVecOut[iParMastUsed].push_back(ParameterId(*iComp, iParComp)); + factorsVecOut[iParMastUsed].push_back(factor); + } + } } ++iParMastUsed; } firstComp = false; - } // end loop on components + } // end loop on components return true; } diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParametersIO.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParametersIO.cc index 9b1b0ce0e1ad4..7c6afe3dd09c3 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParametersIO.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParametersIO.cc @@ -8,34 +8,28 @@ //-------------------------------------------------------------------------------------------------- // write one set of original parameters -int AlignmentParametersIO::writeOneOrigRigidBody(Alignable *ali) -{ - - AlignmentParameters *par = ali->alignmentParameters(); - AlignmentParameters *parBack = (par ? par->clone(par->parameters(), par->covariance()) : nullptr); +int AlignmentParametersIO::writeOneOrigRigidBody(Alignable* ali) { + AlignmentParameters* par = ali->alignmentParameters(); + AlignmentParameters* parBack = (par ? par->clone(par->parameters(), par->covariance()) : nullptr); ali->setAlignmentParameters(new RigidBodyAlignmentParameters(ali, true)); int iret = this->writeOne(ali); - ali->setAlignmentParameters(parBack); // deletes the above created RigidBodyAlignmentParameters + ali->setAlignmentParameters(parBack); // deletes the above created RigidBodyAlignmentParameters return iret; } - //----------------------------------------------------------------------------- // write many parameters -int -AlignmentParametersIO::write(const align::Alignables& alivec, - bool validCheck) -{ - int icount=0; - for(align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it) { +int AlignmentParametersIO::write(const align::Alignables& alivec, bool validCheck) { + int icount = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { if ((*it)->alignmentParameters()->isValid() || !(validCheck)) { icount++; - int iret=writeOne(*it); - if (iret!=0) return iret; + int iret = writeOne(*it); + if (iret != 0) + return iret; } } edm::LogInfo("Alignment") << "@SUB=AlignmentParametersIO::write" @@ -43,39 +37,36 @@ AlignmentParametersIO::write(const align::Alignables& alivec, return 0; } - //----------------------------------------------------------------------------- // write many original parameters -int -AlignmentParametersIO::writeOrigRigidBody(const align::Alignables& alivec, bool validCheck) -{ +int AlignmentParametersIO::writeOrigRigidBody(const align::Alignables& alivec, bool validCheck) { int icount = 0; - for(align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { if (!validCheck || (*it)->alignmentParameters()->isValid()) { ++icount; int iret = this->writeOneOrigRigidBody(*it); - if (iret != 0) return iret; + if (iret != 0) + return iret; } } edm::LogInfo("Alignment") << "@SUB=AlignmentParametersIO::writeOrigRigidBody" - << "Wrote " << icount << " out of " << alivec.size() - << " original parameters."; + << "Wrote " << icount << " out of " << alivec.size() << " original parameters."; return 0; } //----------------------------------------------------------------------------- // read many parameters -align::Parameters -AlignmentParametersIO::read(const align::Alignables& alivec, int& ierr) -{ +align::Parameters AlignmentParametersIO::read(const align::Alignables& alivec, int& ierr) { align::Parameters retvec; int ierr2; - int icount=0; - for(align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it) { - AlignmentParameters* ad=readOne(*it, ierr2); - if (ad!=nullptr && ierr2==0) { retvec.push_back(ad); icount++; } + int icount = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + AlignmentParameters* ad = readOne(*it, ierr2); + if (ad != nullptr && ierr2 == 0) { + retvec.push_back(ad); + icount++; + } } edm::LogInfo("Alignment") << "@SUB-AlignmentParametersIO::write" << "Read " << icount << " out of " << alivec.size() << " parameters"; diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParametersIORoot.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParametersIORoot.cc index cbc4176e6e2d8..a36a57c71e838 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentParametersIORoot.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentParametersIORoot.cc @@ -1,7 +1,7 @@ // this class's header #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParametersIORoot.h" -#include "Alignment/CommonAlignment/interface/Alignable.h" +#include "Alignment/CommonAlignment/interface/Alignable.h" #include "Alignment/CommonAlignment/interface/AlignmentParameters.h" #include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" @@ -9,58 +9,53 @@ #include "TTree.h" - // ---------------------------------------------------------------------------- // constructor -AlignmentParametersIORoot::AlignmentParametersIORoot() -{ +AlignmentParametersIORoot::AlignmentParametersIORoot() { treename = "AlignmentParameters"; treetxt = "Alignment Parameters"; } - // ---------------------------------------------------------------------------- -void AlignmentParametersIORoot::createBranches(void) -{ - tree->Branch("parSize", &theCovRang, "CovRang/I"); - tree->Branch("Id", &theId, "Id/i"); +void AlignmentParametersIORoot::createBranches(void) { + tree->Branch("parSize", &theCovRang, "CovRang/I"); + tree->Branch("Id", &theId, "Id/i"); tree->Branch("paramType", &theParamType, "paramType/I"); - tree->Branch("Par", &thePar, "Par[CovRang]/D"); + tree->Branch("Par", &thePar, "Par[CovRang]/D"); tree->Branch("covarSize", &theCovarRang, "CovarRang/I"); - tree->Branch("Cov", &theCov, "Cov[CovarRang]/D"); - tree->Branch("ObjId", &theObjId, "ObjId/I"); - tree->Branch("HieraLevel",&theHieraLevel,"HieraLevel/I"); + tree->Branch("Cov", &theCov, "Cov[CovarRang]/D"); + tree->Branch("ObjId", &theObjId, "ObjId/I"); + tree->Branch("HieraLevel", &theHieraLevel, "HieraLevel/I"); } - // ---------------------------------------------------------------------------- -void AlignmentParametersIORoot::setBranchAddresses(void) -{ - tree->SetBranchAddress("parSize", &theCovRang); +void AlignmentParametersIORoot::setBranchAddresses(void) { + tree->SetBranchAddress("parSize", &theCovRang); tree->SetBranchAddress("covarSize", &theCovarRang); - tree->SetBranchAddress("Id", &theId); - tree->SetBranchAddress("Par", &thePar); + tree->SetBranchAddress("Id", &theId); + tree->SetBranchAddress("Par", &thePar); tree->SetBranchAddress("paramType", &theParamType); - tree->SetBranchAddress("Cov", &theCov); - tree->SetBranchAddress("ObjId", &theObjId); - tree->SetBranchAddress("HieraLevel",&theHieraLevel); + tree->SetBranchAddress("Cov", &theCov); + tree->SetBranchAddress("ObjId", &theObjId); + tree->SetBranchAddress("HieraLevel", &theHieraLevel); } - // ---------------------------------------------------------------------------- -int AlignmentParametersIORoot::writeOne(Alignable* ali) -{ - const AlignmentParameters* ap =ali->alignmentParameters(); +int AlignmentParametersIORoot::writeOne(Alignable* ali) { + const AlignmentParameters* ap = ali->alignmentParameters(); const AlgebraicVector& params = ap->parameters(); const AlgebraicSymMatrix& cov = ap->covariance(); - theCovRang = params.num_row(); - theCovarRang = theCovRang*(theCovRang+1)/2; - int count=0; - for(int row=0;rowGetEntryWithIndex( ali->id(), ali->alignableObjectId() ) > 0 ) - { +AlignmentParameters* AlignmentParametersIORoot::readOne(Alignable* ali, int& ierr) { + if (tree->GetEntryWithIndex(ali->id(), ali->alignableObjectId()) > 0) { int covsize = theCovRang; - int count=0; + int count = 0; AlgebraicVector par(covsize, 0); AlgebraicSymMatrix cov(covsize, 0); - for(int row=0;rowalignmentParameters() ) - { + AlignmentParameters* alipar1; + if (ali->alignmentParameters()) { const std::vector& sel = ali->alignmentParameters()->selector(); - alipar1 = createParameters(ali, parType, sel); + alipar1 = createParameters(ali, parType, sel); } else { - const std::vector sel( theCovRang, true ); - alipar1 = createParameters(ali, parType, sel); + const std::vector sel(theCovRang, true); + alipar1 = createParameters(ali, parType, sel); } - AlignmentParameters* alipar = alipar1->clone(par,cov); - alipar->setValid(true); - ierr=0; + AlignmentParameters* alipar = alipar1->clone(par, cov); + alipar->setValid(true); + ierr = 0; delete alipar1; return alipar; } - ierr=-1; - return(nullptr); + ierr = -1; + return (nullptr); } - -int AlignmentParametersIORoot::close() -{ - if ( bWrite ) - { - int nIndices = tree->BuildIndex( "Id", "ObjId" ); - edm::LogInfo( "Alignment" ) << "@SUB=AlignmentParametersIORoot::setBranchAddresses" - << "number of indexed entries: " << nIndices; +int AlignmentParametersIORoot::close() { + if (bWrite) { + int nIndices = tree->BuildIndex("Id", "ObjId"); + edm::LogInfo("Alignment") << "@SUB=AlignmentParametersIORoot::setBranchAddresses" + << "number of indexed entries: " << nIndices; } return closeRoot(); diff --git a/Alignment/CommonAlignmentAlgorithm/src/AlignmentUserVariablesIO.cc b/Alignment/CommonAlignmentAlgorithm/src/AlignmentUserVariablesIO.cc index 9111a832403aa..dbff77685b602 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/AlignmentUserVariablesIO.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/AlignmentUserVariablesIO.cc @@ -16,45 +16,40 @@ //----------------------------------------------------------------------------- // write many user variables -int -AlignmentUserVariablesIO::write(const align::Alignables& alivec, - bool validCheck) -{ - int icount=0; - for(align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it) { +int AlignmentUserVariablesIO::write(const align::Alignables& alivec, bool validCheck) { + int icount = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { if ((*it)->alignmentParameters()->isValid() || !(validCheck)) { icount++; - int iret=writeOne(*it); - if (iret!=0) return iret; + int iret = writeOne(*it); + if (iret != 0) + return iret; } } edm::LogInfo("Alignment") << "@SUB=AlignmentUserVariablesIO::write" - << "Write variables all,written: " << alivec.size() <<","<< icount; + << "Write variables all,written: " << alivec.size() << "," << icount; return 0; } //----------------------------------------------------------------------------- // read many user variables -std::vector -AlignmentUserVariablesIO::read(const align::Alignables& alivec, int& ierr) -{ +std::vector AlignmentUserVariablesIO::read(const align::Alignables& alivec, int& ierr) { std::vector retvec; - ierr=0; + ierr = 0; int ierr2; - int icount=0; - int icount2=0; - for(align::Alignables::const_iterator it=alivec.begin(); - it!=alivec.end(); ++it) { - AlignmentUserVariables* ad=readOne(*it, ierr2); // should create with new! - if (ierr2==0) { - retvec.push_back(ad); icount++; - if (ad!=nullptr) icount2++; + int icount = 0; + int icount2 = 0; + for (align::Alignables::const_iterator it = alivec.begin(); it != alivec.end(); ++it) { + AlignmentUserVariables* ad = readOne(*it, ierr2); // should create with new! + if (ierr2 == 0) { + retvec.push_back(ad); + icount++; + if (ad != nullptr) + icount2++; } } edm::LogInfo("Alignment") << "@SUB=AlignmentUserVariablesIO::read" - << "Read variables all,read,valid: " << alivec.size() <<"," - << icount <<","<< icount2; + << "Read variables all,read,valid: " << alivec.size() << "," << icount << "," << icount2; return retvec; } diff --git a/Alignment/CommonAlignmentAlgorithm/src/IntegratedCalibrationBase.cc b/Alignment/CommonAlignmentAlgorithm/src/IntegratedCalibrationBase.cc index 819b0c7e8b91e..95b5de9ebaf48 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/IntegratedCalibrationBase.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/IntegratedCalibrationBase.cc @@ -16,26 +16,21 @@ //#include //============================================================================ -IntegratedCalibrationBase::IntegratedCalibrationBase(const edm::ParameterSet &cfg) - : name_(cfg.getParameter("calibrationName")) -{ -} - +IntegratedCalibrationBase::IntegratedCalibrationBase(const edm::ParameterSet &cfg) + : name_(cfg.getParameter("calibrationName")) {} + //============================================================================ -std::vector -IntegratedCalibrationBase::derivatives(const TrackingRecHit &hit, - const TrajectoryStateOnSurface &tsos, - const edm::EventSetup &setup, - const EventInfo &eventInfo) const -{ +std::vector IntegratedCalibrationBase::derivatives( + const TrackingRecHit &hit, + const TrajectoryStateOnSurface &tsos, + const edm::EventSetup &setup, + const EventInfo &eventInfo) const { // Prepare result vector, initialised all with 0.: - std::vector result(this->numParameters(), Values(0.,0.)); + std::vector result(this->numParameters(), Values(0., 0.)); // Get non-zero derivatives and their index: std::vector derivsIndexPairs; - const unsigned int numNonZero = this->derivatives(derivsIndexPairs, - hit, tsos, setup, - eventInfo); + const unsigned int numNonZero = this->derivatives(derivsIndexPairs, hit, tsos, setup, eventInfo); // Put non-zero values into result: for (unsigned int i = 0; i < numNonZero; ++i) { diff --git a/Alignment/CommonAlignmentAlgorithm/src/IntegratedCalibrationPluginFactory.cc b/Alignment/CommonAlignmentAlgorithm/src/IntegratedCalibrationPluginFactory.cc index b66cb0b29c216..e9d8d0543cbb6 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/IntegratedCalibrationPluginFactory.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/IntegratedCalibrationPluginFactory.cc @@ -7,10 +7,6 @@ /// (last update by $Author: mussgill $) /// - #include "Alignment/CommonAlignmentAlgorithm/interface/IntegratedCalibrationPluginFactory.h" -EDM_REGISTER_PLUGINFACTORY(IntegratedCalibrationPluginFactory, - "IntegratedCalibrationPluginFactory"); - - +EDM_REGISTER_PLUGINFACTORY(IntegratedCalibrationPluginFactory, "IntegratedCalibrationPluginFactory"); diff --git a/Alignment/CommonAlignmentAlgorithm/src/TkModuleGroupSelector.cc b/Alignment/CommonAlignmentAlgorithm/src/TkModuleGroupSelector.cc index e96383f179a09..cacad8c4c3251 100644 --- a/Alignment/CommonAlignmentAlgorithm/src/TkModuleGroupSelector.cc +++ b/Alignment/CommonAlignmentAlgorithm/src/TkModuleGroupSelector.cc @@ -21,229 +21,193 @@ //============================================================================ TkModuleGroupSelector::TkModuleGroupSelector(AlignableTracker *aliTracker, const edm::ParameterSet &cfg, - const std::vector &sdets - ) : nparameters_(0), - subdetids_(sdets) -{ + const std::vector &sdets) + : nparameters_(0), subdetids_(sdets) { //verify that all provided options are known std::vector parameterNames = cfg.getParameterNames(); - for ( std::vector::const_iterator iParam = parameterNames.begin(); - iParam != parameterNames.end(); ++iParam) { + for (std::vector::const_iterator iParam = parameterNames.begin(); iParam != parameterNames.end(); + ++iParam) { const std::string name = (*iParam); - if( - name != "RunRange" && name != "ReferenceRun" && name != "Granularity" - ) { - throw cms::Exception("BadConfig") - << "@SUB=TkModuleGroupSelector::TkModuleGroupSelector:" - << " Unknown parameter name '" << name << "' in PSet. Maybe a typo?"; + if (name != "RunRange" && name != "ReferenceRun" && name != "Granularity") { + throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::TkModuleGroupSelector:" + << " Unknown parameter name '" << name << "' in PSet. Maybe a typo?"; } } - //extract the reference run range if defined - const edm::RunNumber_t defaultReferenceRun - = (cfg.exists("ReferenceRun") ? cfg.getParameter("ReferenceRun") : 0); + const edm::RunNumber_t defaultReferenceRun = + (cfg.exists("ReferenceRun") ? cfg.getParameter("ReferenceRun") : 0); //extract run range to be used for all module groups (if not locally overwritten) - const std::vector defaultRunRange - = (cfg.exists("RunRange") ? cfg.getParameter >("RunRange") - : std::vector()); + const std::vector defaultRunRange = + (cfg.exists("RunRange") ? cfg.getParameter >("RunRange") + : std::vector()); // finally create everything from configuration - this->createModuleGroups(aliTracker, cfg.getParameter("Granularity"), - defaultRunRange, defaultReferenceRun); + this->createModuleGroups( + aliTracker, cfg.getParameter("Granularity"), defaultRunRange, defaultReferenceRun); } //============================================================================ -void TkModuleGroupSelector::fillDetIdMap(const unsigned int detid, const unsigned int groupid) -{ - //only add new entries - if(mapDetIdGroupId_.find(detid) == mapDetIdGroupId_.end()) { +void TkModuleGroupSelector::fillDetIdMap(const unsigned int detid, const unsigned int groupid) { + //only add new entries + if (mapDetIdGroupId_.find(detid) == mapDetIdGroupId_.end()) { mapDetIdGroupId_.insert(std::pair(detid, groupid)); } else { - throw cms::Exception("BadConfig") - << "@SUB=TkModuleGroupSelector:fillDetIdMap:" - << " Module with det ID " << detid << " configured in group " << groupid - << " but it was already selected" - << " in group " << mapDetIdGroupId_[detid] << "."; + throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector:fillDetIdMap:" + << " Module with det ID " << detid << " configured in group " << groupid + << " but it was already selected" + << " in group " << mapDetIdGroupId_[detid] << "."; } } //============================================================================ -const bool TkModuleGroupSelector::testSplitOption(const edm::ParameterSet &pset) const -{ +const bool TkModuleGroupSelector::testSplitOption(const edm::ParameterSet &pset) const { bool split = false; - if(pset.exists("split")) { + if (pset.exists("split")) { split = pset.getParameter("split"); } return split; } //============================================================================ -bool TkModuleGroupSelector::createGroup( - unsigned int &Id, - const std::vector &range, - const std::list &selected_alis, - const edm::RunNumber_t refrun - ) -{ +bool TkModuleGroupSelector::createGroup(unsigned int &Id, + const std::vector &range, + const std::list &selected_alis, + const edm::RunNumber_t refrun) { bool modules_selected = false; referenceRun_.push_back(refrun); firstId_.push_back(Id); runRange_.push_back(range); - for(std::list::const_iterator it = selected_alis.begin(); - it != selected_alis.end(); ++it) { - this->fillDetIdMap((*it)->id(), firstId_.size()-1); + for (std::list::const_iterator it = selected_alis.begin(); it != selected_alis.end(); ++it) { + this->fillDetIdMap((*it)->id(), firstId_.size() - 1); modules_selected = true; } - if(refrun > 0 && !range.empty()) { //FIXME: last condition not really needed? + if (refrun > 0 && !range.empty()) { //FIXME: last condition not really needed? Id += range.size() - 1; nparameters_ += range.size() - 1; } else { Id += range.size(); - nparameters_ += range.size(); + nparameters_ += range.size(); } - if(refrun > 0 && range.front() > refrun) { //range.size() > 0 checked before - throw cms::Exception("BadConfig") - << "@SUB=TkModuleGroupSelector::createGroup:\n" - << "Invalid combination of reference run number and specified run dependence" - << "\n in module group " << firstId_.size() << "." - << "\n Reference run number (" << refrun << ") is smaller than starting run " - << "\n number (" << range.front() << ") of first IOV."; + if (refrun > 0 && range.front() > refrun) { //range.size() > 0 checked before + throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::createGroup:\n" + << "Invalid combination of reference run number and specified run dependence" + << "\n in module group " << firstId_.size() << "." + << "\n Reference run number (" << refrun << ") is smaller than starting run " + << "\n number (" << range.front() << ") of first IOV."; } return modules_selected; } //============================================================================ -void TkModuleGroupSelector::verifyParameterNames(const edm::ParameterSet &pset, unsigned int psetnr) const -{ +void TkModuleGroupSelector::verifyParameterNames(const edm::ParameterSet &pset, unsigned int psetnr) const { std::vector parameterNames = pset.getParameterNames(); - for ( std::vector::const_iterator iParam = parameterNames.begin(); - iParam != parameterNames.end(); ++iParam) { + for (std::vector::const_iterator iParam = parameterNames.begin(); iParam != parameterNames.end(); + ++iParam) { const std::string name = (*iParam); - if( - name != "levels" && name != "RunRange" - && name != "split" && name != "ReferenceRun" - ) { - throw cms::Exception("BadConfig") - << "@SUB=TkModuleGroupSelector::verifyParameterNames:" - << " Unknown parameter name '" << name << "' in PSet number " << psetnr << ". Maybe a typo?"; + if (name != "levels" && name != "RunRange" && name != "split" && name != "ReferenceRun") { + throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::verifyParameterNames:" + << " Unknown parameter name '" << name << "' in PSet number " << psetnr + << ". Maybe a typo?"; } } } - //============================================================================ void TkModuleGroupSelector::createModuleGroups(AlignableTracker *aliTracker, const edm::VParameterSet &granularityConfig, const std::vector &defaultRunRange, - edm::RunNumber_t defaultReferenceRun) -{ + edm::RunNumber_t defaultReferenceRun) { std::set localRunRange; nparameters_ = 0; unsigned int Id = 0; unsigned int psetnr = 0; //loop over all LA groups - for(edm::VParameterSet::const_iterator pset = granularityConfig.begin(); - pset != granularityConfig.end(); - ++pset) { - + for (edm::VParameterSet::const_iterator pset = granularityConfig.begin(); pset != granularityConfig.end(); ++pset) { //test for unknown parameters - this->verifyParameterNames((*pset),psetnr); + this->verifyParameterNames((*pset), psetnr); psetnr++; - bool modules_selected = false; //track whether at all a module has been selected in this group + bool modules_selected = false; //track whether at all a module has been selected in this group const std::vector range = - ((*pset).exists("RunRange") ? pset->getParameter >("RunRange") - : defaultRunRange); - if(range.empty()) { - throw cms::Exception("BadConfig") - << "@SUB=TkModuleGroupSelector::createModuleGroups:\n" - << "Run range array empty!"; + ((*pset).exists("RunRange") ? pset->getParameter >("RunRange") : defaultRunRange); + if (range.empty()) { + throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::createModuleGroups:\n" + << "Run range array empty!"; } const bool split = this->testSplitOption((*pset)); edm::RunNumber_t refrun = 0; - if((*pset).exists("ReferenceRun")) { + if ((*pset).exists("ReferenceRun")) { refrun = (*pset).getParameter("ReferenceRun"); } else { refrun = defaultReferenceRun; } - + AlignmentParameterSelector selector(aliTracker); selector.clear(); - selector.addSelections((*pset).getParameter ("levels")); - - const auto& alis = selector.selectedAlignables(); - std::list selected_alis; - for(const auto& it: alis) { - const auto& aliDaughts = it->deepComponents(); - for (const auto& iD: aliDaughts) { - if(iD->alignableObjectId() == align::AlignableDetUnit || iD->alignableObjectId() == align::AlignableDet) { - if(split) { - modules_selected = this->createGroup(Id, range, std::list(1,iD), refrun); + selector.addSelections((*pset).getParameter("levels")); + + const auto &alis = selector.selectedAlignables(); + std::list selected_alis; + for (const auto &it : alis) { + const auto &aliDaughts = it->deepComponents(); + for (const auto &iD : aliDaughts) { + if (iD->alignableObjectId() == align::AlignableDetUnit || iD->alignableObjectId() == align::AlignableDet) { + if (split) { + modules_selected = this->createGroup(Id, range, std::list(1, iD), refrun); } else { selected_alis.push_back(iD); } } } } - - if(!split) { + + if (!split) { modules_selected = this->createGroup(Id, range, selected_alis, refrun); } - - edm::RunNumber_t firstRun = 0; - for(std::vector::const_iterator iRun = range.begin(); - iRun != range.end(); ++iRun) { + + edm::RunNumber_t firstRun = 0; + for (std::vector::const_iterator iRun = range.begin(); iRun != range.end(); ++iRun) { localRunRange.insert((*iRun)); - if((*iRun) > firstRun) { + if ((*iRun) > firstRun) { firstRun = (*iRun); } else { - throw cms::Exception("BadConfig") - << "@SUB=TkModuleGroupSelector::createModuleGroups:" - << " Run range not sorted."; + throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::createModuleGroups:" + << " Run range not sorted."; } } - if(!modules_selected) { - throw cms::Exception("BadConfig") - << "@SUB=TkModuleGroupSelector:createModuleGroups:" - << " No module was selected in the module group selector in group " << (firstId_.size()-1)<< "."; + if (!modules_selected) { + throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector:createModuleGroups:" + << " No module was selected in the module group selector in group " + << (firstId_.size() - 1) << "."; } } //copy local set into the global vector of run boundaries - for(std::set::const_iterator itRun = localRunRange.begin(); - itRun != localRunRange.end(); ++itRun) { + for (std::set::const_iterator itRun = localRunRange.begin(); itRun != localRunRange.end(); + ++itRun) { globalRunRange_.push_back((*itRun)); } } //============================================================================ -unsigned int TkModuleGroupSelector::getNumberOfParameters() const -{ - return nparameters_; -} +unsigned int TkModuleGroupSelector::getNumberOfParameters() const { return nparameters_; } //============================================================================ -unsigned int TkModuleGroupSelector::numIovs() const -{ - return globalRunRange_.size(); -} +unsigned int TkModuleGroupSelector::numIovs() const { return globalRunRange_.size(); } //============================================================================ -edm::RunNumber_t TkModuleGroupSelector::firstRunOfIOV(unsigned int iovNum) const -{ +edm::RunNumber_t TkModuleGroupSelector::firstRunOfIOV(unsigned int iovNum) const { return iovNum < this->numIovs() ? globalRunRange_.at(iovNum) : 0; } //====================================================================== -int TkModuleGroupSelector::getParameterIndexFromDetId(unsigned int detId, - edm::RunNumber_t run) const -{ +int TkModuleGroupSelector::getParameterIndexFromDetId(unsigned int detId, edm::RunNumber_t run) const { // Return the index of the parameter that is used for this DetId. // If this DetId is not treated, return values < 0. @@ -252,48 +216,47 @@ int TkModuleGroupSelector::getParameterIndexFromDetId(unsigned int detId, int index = -1; bool sel = false; - for(std::vector::const_iterator itSubDets = subdetids_.begin(); - itSubDets != subdetids_.end(); - ++itSubDets) { + for (std::vector::const_iterator itSubDets = subdetids_.begin(); itSubDets != subdetids_.end(); ++itSubDets) { if (temp_id.det() == DetId::Tracker && temp_id.subdetId() == (*itSubDets)) { sel = true; break; } } - if (temp_id.det() != DetId::Tracker || !sel) return -1; - + if (temp_id.det() != DetId::Tracker || !sel) + return -1; + std::map::const_iterator it = mapDetIdGroupId_.find(detId); - if(it != mapDetIdGroupId_.end()) { + if (it != mapDetIdGroupId_.end()) { const unsigned int iAlignableGroup = (*it).second; const std::vector &runs = runRange_.at(iAlignableGroup); const unsigned int id0 = firstId_.at(iAlignableGroup); const edm::RunNumber_t refrun = referenceRun_.at(iAlignableGroup); - unsigned int iovNum = 0; - for ( ; iovNum < runs.size(); ++iovNum) { - if (runs[iovNum] > run) break; + for (; iovNum < runs.size(); ++iovNum) { + if (runs[iovNum] > run) + break; } if (iovNum == 0) { throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::getParameterIndexFromDetId:\n" - << "Run " << run << " not foreseen for detid '"<< detId <<"'" - << " in module group " << iAlignableGroup << "."; + << "Run " << run << " not foreseen for detid '" << detId << "'" + << " in module group " << iAlignableGroup << "."; } else { --iovNum; } //test whether the iov contains the reference run - if(refrun > 0) { //if > 0 a reference run number has been provided - if(iovNum+1 == runs.size()) { - if(refrun >= runs[iovNum]) + if (refrun > 0) { //if > 0 a reference run number has been provided + if (iovNum + 1 == runs.size()) { + if (refrun >= runs[iovNum]) return -1; - } else if( (iovNum+1) < runs.size()) { - if(refrun >= runs[iovNum] && refrun < runs[iovNum+1]) { + } else if ((iovNum + 1) < runs.size()) { + if (refrun >= runs[iovNum] && refrun < runs[iovNum + 1]) { return -1; } - } - if(run > refrun) { + } + if (run > refrun) { //iovNum > 0 due to checks in createGroup(...) and createModuleGroups(...) //remove IOV in which the reference run can be found iovNum -= 1; diff --git a/Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h b/Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h index b94e54b3d7179..b72c6d83ecb07 100644 --- a/Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h +++ b/Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h @@ -1,8 +1,8 @@ -#ifndef Alignment_CommonAlignmentParametrization_AlignmentParametersFactory_h -#define Alignment_CommonAlignmentParametrization_AlignmentParametersFactory_h +#ifndef Alignment_CommonAlignmentParametrization_AlignmentParametersFactory_h +#define Alignment_CommonAlignmentParametrization_AlignmentParametersFactory_h /// \namespace AlignmentParametersFactory -/// +/// /// Factory interface to create AlignmentParameters for the known types, /// defined by the enum AlignmentParametersFactory::ParametersType. /// @@ -10,8 +10,8 @@ /// $Revision: 1.4 $ /// (last update by $Author: mussgill $) -#include #include +#include class Alignable; class AlignmentParameters; @@ -19,25 +19,27 @@ class AlignmentParameters; namespace AlignmentParametersFactory { /// enums for all available AlignmentParameters enum ParametersType { - kRigidBody = 0, // RigidBodyAlignmentParameters - kSurvey, // SurveyParameters GF: do not belong here, so remove in the long term... - kRigidBody4D, // RigidBodyAlignmentParameters4D - kBeamSpot, // BeamSpotAlignmentParameters - kBowedSurface, // BowedSurfaceAlignmentParameters - kTwoBowedSurfaces // TwoBowedSurfacesAlignmentParameters + kRigidBody = 0, // RigidBodyAlignmentParameters + kSurvey, // SurveyParameters GF: do not belong here, so remove in the long + // term... + kRigidBody4D, // RigidBodyAlignmentParameters4D + kBeamSpot, // BeamSpotAlignmentParameters + kBowedSurface, // BowedSurfaceAlignmentParameters + kTwoBowedSurfaces // TwoBowedSurfacesAlignmentParameters }; /// convert string to ParametersType - exception if not known ParametersType parametersType(const std::string &typeString); - /// convert int to ParametersType (if same value) - exception if no corresponding type + /// convert int to ParametersType (if same value) - exception if no + /// corresponding type ParametersType parametersType(int typeInt); - /// convert ParametersType to string understood by parametersType(string &typeString) + /// convert ParametersType to string understood by parametersType(string + /// &typeString) std::string parametersTypeName(ParametersType parType); - /// create AlignmentParameters of type 'parType' for Alignable 'ali' with selection - /// 'sel' for active parameters - AlignmentParameters* createParameters(Alignable *ali, ParametersType parType, - const std::vector &sel); -} + /// create AlignmentParameters of type 'parType' for Alignable 'ali' with + /// selection 'sel' for active parameters + AlignmentParameters *createParameters(Alignable *ali, ParametersType parType, const std::vector &sel); +} // namespace AlignmentParametersFactory #endif diff --git a/Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentDerivatives.h b/Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentDerivatives.h index 89962f82baa51..5fc44988bffe2 100644 --- a/Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentDerivatives.h +++ b/Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentDerivatives.h @@ -13,14 +13,10 @@ class TrajectoryStateOnSurface; -class BeamSpotAlignmentDerivatives -{ +class BeamSpotAlignmentDerivatives { public: - /// Returns 4x2 jacobian matrix AlgebraicMatrix operator()(const TrajectoryStateOnSurface &tsos) const; - }; #endif - diff --git a/Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentParameters.h b/Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentParameters.h index d19b8327457ef..c8faaf0d4933f 100644 --- a/Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentParameters.h +++ b/Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentParameters.h @@ -6,7 +6,7 @@ /// \class BeamSpotAlignmentParameters /// -/// Concrete class for alignment parameters and associated quantities +/// Concrete class for alignment parameters and associated quantities /// [derived from AlignmentParameters]. The number of parameters /// N_PARAM is fixed to 4 (2 translations in x & y, and 2 slopes) /// @@ -18,53 +18,46 @@ class Alignable; class AlignableDetOrUnitPtr; class TrajectoryStateOnSurface; -class BeamSpotAlignmentParameters : public AlignmentParameters -{ - +class BeamSpotAlignmentParameters : public AlignmentParameters { public: - /// Give parameters a name - enum AlignmentParameterName - { - dx = 0, dy, - dxslope, dyslope, - N_PARAM - }; - - /// Constructor with empty parameters/covariance (if calcMis = false) or with parameters - /// (no covariance) created from current (mis-)placement of alignable (if calcMis = true). - BeamSpotAlignmentParameters( Alignable* alignable, bool calcMis ); + enum AlignmentParameterName { dx = 0, dy, dxslope, dyslope, N_PARAM }; + + /// Constructor with empty parameters/covariance (if calcMis = false) or with + /// parameters (no covariance) created from current (mis-)placement of + /// alignable (if calcMis = true). + BeamSpotAlignmentParameters(Alignable *alignable, bool calcMis); /// Constructor for full set of parameters - BeamSpotAlignmentParameters( Alignable* alignable, - const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ); + BeamSpotAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix); - /// Constructor for selection - BeamSpotAlignmentParameters( Alignable* alignable, const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix, - const std::vector& selection ); + /// Constructor for selection + BeamSpotAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection); - /// Destructor + /// Destructor ~BeamSpotAlignmentParameters() override; void apply() override; int type() const override; /// Clone all parameters (for update of parameters) - BeamSpotAlignmentParameters* clone( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const override; - + BeamSpotAlignmentParameters *clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; + /// Clone selected parameters (for update of parameters) - BeamSpotAlignmentParameters* - cloneFromSelected(const AlgebraicVector& parameters, const AlgebraicSymMatrix& covMatrix) const override; - - /// Get all derivatives - AlgebraicMatrix derivatives( const TrajectoryStateOnSurface& tsos, - const AlignableDetOrUnitPtr & ) const override; + BeamSpotAlignmentParameters *cloneFromSelected(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; + + /// Get all derivatives + AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &) const override; /// Get selected derivatives - AlgebraicMatrix selectedDerivatives( const TrajectoryStateOnSurface& tsos, - const AlignableDetOrUnitPtr & ) const override; + AlgebraicMatrix selectedDerivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &) const override; /// Get translation parameters AlgebraicVector translation(void) const; @@ -72,15 +65,15 @@ class BeamSpotAlignmentParameters : public AlignmentParameters /// Get rotation parameters AlgebraicVector rotation(void) const; - /// calculate and return parameters in global frame + /// calculate and return parameters in global frame AlgebraicVector globalParameters(void) const; - /// print parameters to screen + /// print parameters to screen void print(void) const; - /// Calculate parameter vector of misplacements (shift+rotation) from alignable. - /// (If ali=0, return empty AlgebraicVector of proper length.) - static AlgebraicVector displacementFromAlignable(const Alignable* ali); + /// Calculate parameter vector of misplacements (shift+rotation) from + /// alignable. (If ali=0, return empty AlgebraicVector of proper length.) + static AlgebraicVector displacementFromAlignable(const Alignable *ali); }; #endif diff --git a/Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentDerivatives.h b/Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentDerivatives.h index f6627d03df436..ea7cb00277caa 100644 --- a/Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentDerivatives.h +++ b/Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentDerivatives.h @@ -22,26 +22,30 @@ class TrajectoryStateOnSurface; -class BowedSurfaceAlignmentDerivatives -{ +class BowedSurfaceAlignmentDerivatives { public: - enum AlignmentParameterName { - dx = 0, dy, dz, - dslopeX, // NOTE: slope(u) -> k*tan(beta), - dslopeY, // slope(v) -> k*tan(alpha) - drotZ, // rotation around w axis, scaled by gammaScale - dsagittaX, dsagittaXY, dsagittaY, + dx = 0, + dy, + dz, + dslopeX, // NOTE: slope(u) -> k*tan(beta), + dslopeY, // slope(v) -> k*tan(alpha) + drotZ, // rotation around w axis, scaled by gammaScale + dsagittaX, + dsagittaXY, + dsagittaY, N_PARAM }; /// Returns 9x2 jacobian matrix AlgebraicMatrix operator()(const TrajectoryStateOnSurface &tsos, - double uWidth, double vLength, - bool doSplit = false, double ySplit = 0.) const; + double uWidth, + double vLength, + bool doSplit = false, + double ySplit = 0.) const; /// scale to apply to convert drotZ to karimaki-gamma, - /// depending on module width and length (the latter after splitting!) + /// depending on module width and length (the latter after splitting!) static double gammaScale(double width, double splitLength); }; diff --git a/Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentParameters.h b/Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentParameters.h index 5a215828c68e4..d7009029e4376 100644 --- a/Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentParameters.h +++ b/Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentParameters.h @@ -2,15 +2,15 @@ #define Alignment_CommonAlignment_BowedSurfaceAlignmentParameters_h #include "Alignment/CommonAlignment/interface/AlignmentParameters.h" -#include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "CondFormats/Alignment/interface/Definitions.h" +#include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentDerivatives.h" /// \class BowedSurfaceAlignmentParameters /// -/// Concrete class for alignment parameters and associated quantities -/// [derived from AlignmentParameters]. +/// Concrete class for alignment parameters and associated quantities +/// [derived from AlignmentParameters]. /// The number of parameters N_PARAM is 9 /// - 3 translations /// - 3 rotations/slopes @@ -24,8 +24,7 @@ class Alignable; class AlignableDetOrUnitPtr; class TrajectoryStateOnSurface; -class BowedSurfaceAlignmentParameters : public AlignmentParameters -{ +class BowedSurfaceAlignmentParameters : public AlignmentParameters { public: /// Give parameters a name typedef BowedSurfaceAlignmentDerivatives BowedDerivs; @@ -33,9 +32,9 @@ class BowedSurfaceAlignmentParameters : public AlignmentParameters dx = BowedDerivs::dx, dy = BowedDerivs::dy, dz = BowedDerivs::dz, - dslopeX = BowedDerivs::dslopeX, // NOTE: slope(u) -> k*tan(beta), - dslopeY = BowedDerivs::dslopeY, // slope(v) -> l*tan(alpha) - drotZ = BowedDerivs::drotZ, // rot(w) -> m*gamma + dslopeX = BowedDerivs::dslopeX, // NOTE: slope(u) -> k*tan(beta), + dslopeY = BowedDerivs::dslopeY, // slope(v) -> l*tan(alpha) + drotZ = BowedDerivs::drotZ, // rot(w) -> m*gamma dsagittaX = BowedDerivs::dsagittaX, dsagittaXY = BowedDerivs::dsagittaXY, dsagittaY = BowedDerivs::dsagittaY, @@ -46,42 +45,40 @@ class BowedSurfaceAlignmentParameters : public AlignmentParameters BowedSurfaceAlignmentParameters(Alignable *alignable); /// Constructor for full set of parameters - BowedSurfaceAlignmentParameters(Alignable *alignable, - const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix); + BowedSurfaceAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix); - /// Constructor for selection - BowedSurfaceAlignmentParameters(Alignable *alignable, const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix, - const std::vector &selection); + /// Constructor for selection + BowedSurfaceAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection); - /// Destructor - ~BowedSurfaceAlignmentParameters() override {}; + /// Destructor + ~BowedSurfaceAlignmentParameters() override{}; void apply() override; int type() const override; /// Clone all parameters (for update of parameters) - BowedSurfaceAlignmentParameters* clone(const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) const override; - + BowedSurfaceAlignmentParameters *clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; + /// Clone selected parameters (for update of parameters) - BowedSurfaceAlignmentParameters* - cloneFromSelected(const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) const override; - - /// Get all derivatives - AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &aliDet) const override; + BowedSurfaceAlignmentParameters *cloneFromSelected(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; + + /// Get all derivatives + AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &aliDet) const override; /// Get translation parameters in double precision align::LocalVector translation() const; - /// Get rotation parameters + /// Get rotation parameters align::EulerAngles rotation() const; - /// print parameters to screen + /// print parameters to screen void print() const; }; #endif - diff --git a/Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentDerivativesExtractor.h b/Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentDerivativesExtractor.h index 8e3c10a1ad8da..b2ace06ddadb7 100644 --- a/Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentDerivativesExtractor.h +++ b/Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentDerivativesExtractor.h @@ -1,8 +1,8 @@ #ifndef Alignment_CommonAlignmentParametrization_CompositeAlignmentDerivativesExtractor_H #define Alignment_CommonAlignmentParametrization_CompositeAlignmentDerivativesExtractor_H -#include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "Alignment/CommonAlignment/interface/Utilities.h" +#include "DataFormats/CLHEP/interface/AlgebraicObjects.h" /// \class CompositeAlignmentDerivativesExtractor /// @@ -17,42 +17,38 @@ class AlignableDet; class AlignableDetOrUnitPtr; class TrajectoryStateOnSurface; -class CompositeAlignmentDerivativesExtractor -{ - +class CompositeAlignmentDerivativesExtractor { public: - - /// deprecated constructor for backward compatibility (use mor general AlignableDetOrUnitPtr) - CompositeAlignmentDerivativesExtractor( const align::Alignables & alignables, - const std::vector< AlignableDet* > & alignableDets, - const std::vector< TrajectoryStateOnSurface > & tsos ); + /// deprecated constructor for backward compatibility (use mor general + /// AlignableDetOrUnitPtr) + CompositeAlignmentDerivativesExtractor(const align::Alignables &alignables, + const std::vector &alignableDets, + const std::vector &tsos); /// constructor - CompositeAlignmentDerivativesExtractor( const align::Alignables & alignables, - const std::vector< AlignableDetOrUnitPtr > & alignableDets, - const std::vector< TrajectoryStateOnSurface > & tsos ); + CompositeAlignmentDerivativesExtractor(const align::Alignables &alignables, + const std::vector &alignableDets, + const std::vector &tsos); /// destructor - ~CompositeAlignmentDerivativesExtractor( void ) {}; + ~CompositeAlignmentDerivativesExtractor(void){}; + + const AlgebraicMatrix &derivatives(void) const { return theDerivatives; } + const AlgebraicVector &correctionTerm(void) const { return theCorrectionTerm; } - const AlgebraicMatrix & derivatives( void ) const { return theDerivatives; } - const AlgebraicVector & correctionTerm( void ) const { return theCorrectionTerm; } - private: - - void extractCurrentAlignment( const align::Alignables & alignables, - const std::vector< AlignableDetOrUnitPtr > & alignableDets, - const std::vector< TrajectoryStateOnSurface > & tsos ); - - void extractWithoutMultipleHits( const std::vector< AlgebraicVector > & subCorrectionTerm, - const std::vector< AlgebraicMatrix > & subDerivatives ); - - void extractWithMultipleHits( const std::vector< AlgebraicVector > & subCorrectionTerm, - const std::vector< AlgebraicMatrix > & subDerivatives, - const align::Alignables & alignables ); - + void extractCurrentAlignment(const align::Alignables &alignables, + const std::vector &alignableDets, + const std::vector &tsos); + + void extractWithoutMultipleHits(const std::vector &subCorrectionTerm, + const std::vector &subDerivatives); + + void extractWithMultipleHits(const std::vector &subCorrectionTerm, + const std::vector &subDerivatives, + const align::Alignables &alignables); + AlgebraicMatrix theDerivatives; AlgebraicVector theCorrectionTerm; - }; #endif diff --git a/Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentParameters.h b/Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentParameters.h index a5687f6d7fe56..dc9d247304248 100644 --- a/Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentParameters.h +++ b/Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentParameters.h @@ -1,9 +1,8 @@ #ifndef Alignment_CommonAlignmentParametrization_CompositeAlignmentParameters_h #define Alignment_CommonAlignmentParametrization_CompositeAlignmentParameters_h - -#include "Alignment/CommonAlignment/interface/AlignmentParametersData.h" #include "Alignment/CommonAlignment/interface/AlignableDetOrUnitPtr.h" +#include "Alignment/CommonAlignment/interface/AlignmentParametersData.h" #include "Alignment/CommonAlignment/interface/Utilities.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" @@ -14,9 +13,9 @@ /// /// Class for 'concatenated' alignment parameters and associated /// Quantities for a set of Alignables. Provided by AlignmentParameterStore. -/// It does not inherit from AligmentParameters since it does not need to be attached -/// to an Alignable, so it does not need to have implementations of the apply(..) method. -/// It neither needs AlignmentUservariables attached. +/// It does not inherit from AligmentParameters since it does not need to be +/// attached to an Alignable, so it does not need to have implementations of the +/// apply(..) method. It neither needs AlignmentUservariables attached. /// /// $Date: 2007/10/08 15:56:00 $ /// $Revision: 1.12 $ @@ -25,132 +24,129 @@ class AlignableDet; class Alignable; -class CompositeAlignmentParameters -{ - +class CompositeAlignmentParameters { public: - - /// vector of alignable components + /// vector of alignable components typedef align::Alignables Components; - typedef std::map AlignableDetToAlignableMap; - typedef std::map Aliposmap; - typedef std::map Alilenmap; + typedef std::map AlignableDetToAlignableMap; + typedef std::map Aliposmap; + typedef std::map Alilenmap; typedef AlignmentParametersData::DataContainer DataContainer; - /// constructors + /// constructors - CompositeAlignmentParameters(const AlgebraicVector& par, const AlgebraicSymMatrix& cov, - const Components& comp); + CompositeAlignmentParameters(const AlgebraicVector &par, const AlgebraicSymMatrix &cov, const Components &comp); - CompositeAlignmentParameters(const AlgebraicVector& par, const AlgebraicSymMatrix& cov, - const Components& comp, const AlignableDetToAlignableMap& alimap, - const Aliposmap& aliposmap, const Alilenmap& alilenmap); + CompositeAlignmentParameters(const AlgebraicVector &par, + const AlgebraicSymMatrix &cov, + const Components &comp, + const AlignableDetToAlignableMap &alimap, + const Aliposmap &aliposmap, + const Alilenmap &alilenmap); - CompositeAlignmentParameters( const DataContainer& data, - const Components& comp, const AlignableDetToAlignableMap& alimap, - const Aliposmap& aliposmap, const Alilenmap& alilenmap); + CompositeAlignmentParameters(const DataContainer &data, + const Components &comp, + const AlignableDetToAlignableMap &alimap, + const Aliposmap &aliposmap, + const Alilenmap &alilenmap); - /// destructor + /// destructor virtual ~CompositeAlignmentParameters(); /// Get alignment parameters - const AlgebraicVector& parameters() const { return theData->parameters();} + const AlgebraicVector ¶meters() const { return theData->parameters(); } /// Get parameter covariance matrix - const AlgebraicSymMatrix& covariance() const { return theData->covariance();} + const AlgebraicSymMatrix &covariance() const { return theData->covariance(); } /// Clone parameters - CompositeAlignmentParameters* clone( const AlgebraicVector& par, - const AlgebraicSymMatrix& cov) const; + CompositeAlignmentParameters *clone(const AlgebraicVector &par, const AlgebraicSymMatrix &cov) const; /// Clone parameters - CompositeAlignmentParameters* clone( const AlgebraicVector& par, const AlgebraicSymMatrix& cov, - const AlignableDetToAlignableMap& alimap, - const Aliposmap& aliposmap, - const Alilenmap& alilenmap) const; + CompositeAlignmentParameters *clone(const AlgebraicVector &par, + const AlgebraicSymMatrix &cov, + const AlignableDetToAlignableMap &alimap, + const Aliposmap &aliposmap, + const Alilenmap &alilenmap) const; - /// Get vector of alignable components + /// Get vector of alignable components Components components() const; - /// Get derivatives - AlgebraicMatrix derivatives( const TrajectoryStateOnSurface& tsos, const AlignableDetOrUnitPtr &alidet ) const; + /// Get derivatives + AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &alidet) const; /// Get derivatives for selected alignables - AlgebraicMatrix selectedDerivatives( const TrajectoryStateOnSurface& tsos, - const AlignableDetOrUnitPtr &alidet ) const; + AlgebraicMatrix selectedDerivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &alidet) const; /// for backward compatibility, use std::vector - AlgebraicMatrix derivatives( const std::vector& tsosvec, - const std::vector& alidetvec ) const; - AlgebraicMatrix derivatives( const std::vector& tsosvec, - const std::vector& alidetvec ) const; + AlgebraicMatrix derivatives(const std::vector &tsosvec, + const std::vector &alidetvec) const; + AlgebraicMatrix derivatives(const std::vector &tsosvec, + const std::vector &alidetvec) const; /// for backward compatibility, use std::vector - AlgebraicMatrix selectedDerivatives( const std::vector &tsosvec, - const std::vector &alidetvec ) const; - AlgebraicMatrix selectedDerivatives( const std::vector &tsosvec, - const std::vector &alidetvec ) const; + AlgebraicMatrix selectedDerivatives(const std::vector &tsosvec, + const std::vector &alidetvec) const; + AlgebraicMatrix selectedDerivatives(const std::vector &tsosvec, + const std::vector &alidetvec) const; /// for backward compatibility, use std::vector - AlgebraicVector correctionTerm( const std::vector& tsosvec, - const std::vector& alidetvec ) const; - AlgebraicVector correctionTerm( const std::vector& tsosvec, - const std::vector& alidetvec ) const; - /// deprecated due to 'AlignableDet*' interface (legacy code should not be needed anymore) - AlgebraicMatrix derivativesLegacy ( const TrajectoryStateOnSurface& tsos, - AlignableDet* alidet ) const; - /// deprecated due to 'AlignableDet*' interface (legacy code should not be needed anymore) - AlgebraicMatrix selectedDerivativesLegacy( const TrajectoryStateOnSurface& tsos, - AlignableDet* alidet ) const; - /// deprecated due to 'AlignableDet*' interface (legacy code should not be needed anymore) - AlgebraicMatrix derivativesLegacy( const std::vector& tsosvec, - const std::vector& alidetvec ) const; - /// deprecated due to 'AlignableDet*' interface (legacy code should not be needed anymore) - AlgebraicMatrix selectedDerivativesLegacy( const std::vector& tsosvec, - const std::vector& alidetvec ) const; - - /// Get relevant Alignable from AlignableDet - Alignable* alignableFromAlignableDet( const AlignableDetOrUnitPtr& adet ) const; - + AlgebraicVector correctionTerm(const std::vector &tsosvec, + const std::vector &alidetvec) const; + AlgebraicVector correctionTerm(const std::vector &tsosvec, + const std::vector &alidetvec) const; + /// deprecated due to 'AlignableDet*' interface (legacy code should not be + /// needed anymore) + AlgebraicMatrix derivativesLegacy(const TrajectoryStateOnSurface &tsos, AlignableDet *alidet) const; + /// deprecated due to 'AlignableDet*' interface (legacy code should not be + /// needed anymore) + AlgebraicMatrix selectedDerivativesLegacy(const TrajectoryStateOnSurface &tsos, AlignableDet *alidet) const; + /// deprecated due to 'AlignableDet*' interface (legacy code should not be + /// needed anymore) + AlgebraicMatrix derivativesLegacy(const std::vector &tsosvec, + const std::vector &alidetvec) const; + /// deprecated due to 'AlignableDet*' interface (legacy code should not be + /// needed anymore) + AlgebraicMatrix selectedDerivativesLegacy(const std::vector &tsosvec, + const std::vector &alidetvec) const; + + /// Get relevant Alignable from AlignableDet + Alignable *alignableFromAlignableDet(const AlignableDetOrUnitPtr &adet) const; /// Extract parameters for subset of alignables - AlgebraicVector parameterSubset (const align::Alignables&) const; + AlgebraicVector parameterSubset(const align::Alignables &) const; /// Extract covariance matrix for subset of alignables - AlgebraicSymMatrix covarianceSubset(const align::Alignables&) const; + AlgebraicSymMatrix covarianceSubset(const align::Alignables &) const; /// Extract covariance matrix elements between two subsets of alignables - AlgebraicMatrix covarianceSubset (const align::Alignables&, - const align::Alignables&) const; + AlgebraicMatrix covarianceSubset(const align::Alignables &, const align::Alignables &) const; protected: DataContainer theData; private: - /// Extract position and length of parameters for a subset of Alignables. - bool extractPositionAndLength( const align::Alignables& alignables, - std::vector& posvec, - std::vector& lenvec, - int& length ) const; + bool extractPositionAndLength(const align::Alignables &alignables, + std::vector &posvec, + std::vector &lenvec, + int &length) const; /// Return vector of alignables without multiple occurences. - align::Alignables extractAlignables(const align::Alignables&) const; + align::Alignables extractAlignables(const align::Alignables &) const; - /// backward compatibility method to convert vectors from specific AlignableDet - /// to more general AlignableDetOrUnitPtr - void convert(const std::vector &input, - std::vector &output) const; + /// backward compatibility method to convert vectors from specific + /// AlignableDet to more general AlignableDetOrUnitPtr + void convert(const std::vector &input, std::vector &output) const; - /// Vector of alignable components + /// Vector of alignable components Components theComponents; - /// Relate Alignable's and AlignableDet's + /// Relate Alignable's and AlignableDet's AlignableDetToAlignableMap theAlignableDetToAlignableMap; - /// Maps to find parameters/covariance elements for given alignable + /// Maps to find parameters/covariance elements for given alignable Aliposmap theAliposmap; Alilenmap theAlilenmap; - }; #endif diff --git a/Alignment/CommonAlignmentParametrization/interface/FrameToFrameDerivative.h b/Alignment/CommonAlignmentParametrization/interface/FrameToFrameDerivative.h index be6df6ef60c67..07a76dde3d1ac 100644 --- a/Alignment/CommonAlignmentParametrization/interface/FrameToFrameDerivative.h +++ b/Alignment/CommonAlignmentParametrization/interface/FrameToFrameDerivative.h @@ -17,10 +17,8 @@ class Alignable; -class FrameToFrameDerivative -{ - public: - +class FrameToFrameDerivative { +public: /// Return the derivative DeltaFrame(object)/DeltaFrame(composedObject), /// i.e. a 6x6 matrix: /// @@ -34,56 +32,57 @@ class FrameToFrameDerivative /// where u, v, w, a, b, g are shifts and rotations of the object /// and u_c, v_c, w_c, a_c, b_c, g_c those of the composed object. - AlgebraicMatrix frameToFrameDerivative(const Alignable* object, - const Alignable* composedObject) const; + AlgebraicMatrix frameToFrameDerivative(const Alignable *object, const Alignable *composedObject) const; - /// Calculates derivatives DeltaFrame(object)/DeltaFrame(composedobject) - /// using their positions and orientations, see method frameToFrameDerivative(..) - /// for definition. - /// As a new method it gets a new interface avoiding CLHEP that should anyway be - /// replaced by SMatrix at some point... + /// Calculates derivatives DeltaFrame(object)/DeltaFrame(composedobject) + /// using their positions and orientations, see method + /// frameToFrameDerivative(..) for definition. As a new method it gets a new + /// interface avoiding CLHEP that should anyway be replaced by SMatrix at some + /// point... AlgebraicMatrix66 getDerivative(const align::RotationType &objectRot, - const align::RotationType &composeRot, - const align::GlobalPoint &objectPos, - const align::GlobalPoint &composePos) const; + const align::RotationType &composeRot, + const align::GlobalPoint &objectPos, + const align::GlobalPoint &composePos) const; - private: +private: /// Helper to transform from RotationType to AlgebraicMatrix - inline static AlgebraicMatrix transform(const align::RotationType&); + inline static AlgebraicMatrix transform(const align::RotationType &); - /// Calculates derivatives using the orientation Matrixes and the origin difference vector + /// Calculates derivatives using the orientation Matrixes and the origin + /// difference vector AlgebraicMatrix getDerivative(const align::RotationType &objectRot, - const align::RotationType &composeRot, - const align::GlobalVector &posVec) const; - - /// Gets linear approximated euler Angles + const align::RotationType &composeRot, + const align::GlobalVector &posVec) const; + + /// Gets linear approximated euler Angles AlgebraicVector linearEulerAngles(const AlgebraicMatrix &rotDelta) const; - - /// Calculates the derivative DPos/DPos - AlgebraicMatrix derivativePosPos(const AlgebraicMatrix &RotDet, - const AlgebraicMatrix &RotRot) const; - /// Calculates the derivative DPos/DRot - AlgebraicMatrix derivativePosRot(const AlgebraicMatrix &RotDet, - const AlgebraicMatrix &RotRot, - const AlgebraicVector &S) const; + /// Calculates the derivative DPos/DPos + AlgebraicMatrix derivativePosPos(const AlgebraicMatrix &RotDet, const AlgebraicMatrix &RotRot) const; - /// Calculates the derivative DRot/DRot - AlgebraicMatrix derivativeRotRot(const AlgebraicMatrix &RotDet, - const AlgebraicMatrix &RotRot) const; + /// Calculates the derivative DPos/DRot + AlgebraicMatrix derivativePosRot(const AlgebraicMatrix &RotDet, + const AlgebraicMatrix &RotRot, + const AlgebraicVector &S) const; + /// Calculates the derivative DRot/DRot + AlgebraicMatrix derivativeRotRot(const AlgebraicMatrix &RotDet, const AlgebraicMatrix &RotRot) const; }; -AlgebraicMatrix FrameToFrameDerivative::transform(const align::RotationType& rot) -{ +AlgebraicMatrix FrameToFrameDerivative::transform(const align::RotationType &rot) { AlgebraicMatrix R(3, 3); - R(1, 1) = rot.xx(); R(1, 2) = rot.xy(); R(1, 3) = rot.xz(); - R(2, 1) = rot.yx(); R(2, 2) = rot.yy(); R(2, 3) = rot.yz(); - R(3, 1) = rot.zx(); R(3, 2) = rot.zy(); R(3, 3) = rot.zz(); + R(1, 1) = rot.xx(); + R(1, 2) = rot.xy(); + R(1, 3) = rot.xz(); + R(2, 1) = rot.yx(); + R(2, 2) = rot.yy(); + R(2, 3) = rot.yz(); + R(3, 1) = rot.zx(); + R(3, 2) = rot.zy(); + R(3, 3) = rot.zz(); return R; } #endif - diff --git a/Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h b/Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h index bfd42102f33ec..14c052666f812 100644 --- a/Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h +++ b/Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h @@ -13,10 +13,8 @@ class TrajectoryStateOnSurface; -class KarimakiAlignmentDerivatives -{ +class KarimakiAlignmentDerivatives { public: - /// Returns 6x2 jacobian matrix of derivatives of residuals in x and y /// with respect to rigid body aligment parameters: /// @@ -27,8 +25,6 @@ class KarimakiAlignmentDerivatives /// | dr_x/db dr_y/db | /// \ dr_x/dg dr_y/dg / AlgebraicMatrix operator()(const TrajectoryStateOnSurface &tsos) const; - }; #endif - diff --git a/Alignment/CommonAlignmentParametrization/interface/ParametersToParametersDerivatives.h b/Alignment/CommonAlignmentParametrization/interface/ParametersToParametersDerivatives.h index b9efe19ba35cd..3dbe6fb373d97 100644 --- a/Alignment/CommonAlignmentParametrization/interface/ParametersToParametersDerivatives.h +++ b/Alignment/CommonAlignmentParametrization/interface/ParametersToParametersDerivatives.h @@ -18,13 +18,13 @@ /// | . . . | /// \ dpm_l/dpm_i dpm_l/dpm_i ... dpm_l/dpn_i / /// -/// where +/// where /// p1_l, p2_l, ..., pn_l are the n parameters of the composite 'mother' object /// and /// p1_i, p2_i, ..., pm_i are the m parameters of its component. /// /// Note that not all combinations of parameters are supported: -/// Please check method isOK() before accessing the derivatives via +/// Please check method isOK() before accessing the derivatives via /// operator(unsigned int indParMother, unsigned int indParComp). /// /// Currently these parameters are supported: @@ -40,43 +40,42 @@ class Alignable; -class ParametersToParametersDerivatives -{ - public: +class ParametersToParametersDerivatives { +public: ParametersToParametersDerivatives(const Alignable &component, const Alignable &mother); /// Indicate whether able to provide the derivatives. - bool isOK() const { return isOK_;} + bool isOK() const { return isOK_; } /// Return the derivative DeltaParam(mother)/DeltaParam(component). /// Indices start with 0 - but check isOK() first! /// See class description about matrix. - double operator() (unsigned int indParMother, unsigned int indParComp) const; + double operator()(unsigned int indParMother, unsigned int indParComp) const; // Not this - would make the internals public: // const TMatrixD& matrix() const { return derivatives_;} - private: - /// init by choosing the correct detailed init method depending on parameter types - bool init(const Alignable &component, int typeComponent, - const Alignable &mother, int typeMother); +private: + /// init by choosing the correct detailed init method depending on parameter + /// types + bool init(const Alignable &component, int typeComponent, const Alignable &mother, int typeMother); /// init for component and mother both with RigidBody parameters bool initRigidRigid(const Alignable &component, const Alignable &mother); /// init for component with BowedSurface and mother with RigidBody parameters bool initBowedRigid(const Alignable &component, const Alignable &mother); - /// init for component with TwoBowedSurfaces and mother with RigidBody parameters + /// init for component with TwoBowedSurfaces and mother with RigidBody + /// parameters bool init2BowedRigid(const Alignable &component, const Alignable &mother); - typedef ROOT::Math::SMatrix > AlgebraicMatrix69; - /// from d(rigid_mother)/d(rigid_component) to d(rigid_mother)/d(bowed_component) - /// for bad input (length or width zero), set object to invalid: isOK_ = false - AlgebraicMatrix69 dRigid_dBowed(const AlgebraicMatrix66 &dRigidM2dRigidC, - double halfWidth, double halfLength); + typedef ROOT::Math::SMatrix> AlgebraicMatrix69; + /// from d(rigid_mother)/d(rigid_component) to + /// d(rigid_mother)/d(bowed_component) for bad input (length or width zero), + /// set object to invalid: isOK_ = false + AlgebraicMatrix69 dRigid_dBowed(const AlgebraicMatrix66 &dRigidM2dRigidC, double halfWidth, double halfLength); /// data members - bool isOK_; /// can we provide the desired? - TMatrixD derivatives_; /// matrix of derivatives + bool isOK_; /// can we provide the desired? + TMatrixD derivatives_; /// matrix of derivatives }; #endif - diff --git a/Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h b/Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h index 86bdf790896f0..32bb452429cd8 100644 --- a/Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h +++ b/Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h @@ -6,7 +6,7 @@ /// \class RigidBodyAlignmentParameters /// -/// Concrete class for alignment parameters and associated quantities +/// Concrete class for alignment parameters and associated quantities /// [derived from AlignmentParameters]. The number of parameters /// N_PARAM is fixed to 6 (3 translations + 3 rotations) /// @@ -18,53 +18,46 @@ class Alignable; class AlignableDetOrUnitPtr; class TrajectoryStateOnSurface; -class RigidBodyAlignmentParameters : public AlignmentParameters -{ - +class RigidBodyAlignmentParameters : public AlignmentParameters { public: - /// Give parameters a name - enum AlignmentParameterName - { - dx = 0, dy, dz, - dalpha, dbeta, dgamma, - N_PARAM - }; + enum AlignmentParameterName { dx = 0, dy, dz, dalpha, dbeta, dgamma, N_PARAM }; - /// Constructor with empty parameters/covariance (if calcMis = false) or with parameters - /// (no covariance) created from current (mis-)placement of alignable (if calcMis = true). - RigidBodyAlignmentParameters(Alignable* alignable, bool calcMis); + /// Constructor with empty parameters/covariance (if calcMis = false) or with + /// parameters (no covariance) created from current (mis-)placement of + /// alignable (if calcMis = true). + RigidBodyAlignmentParameters(Alignable *alignable, bool calcMis); /// Constructor for full set of parameters - RigidBodyAlignmentParameters( Alignable* alignable, - const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ); - - /// Constructor for selection - RigidBodyAlignmentParameters( Alignable* alignable, const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix, - const std::vector& selection ); - - /// Destructor - ~RigidBodyAlignmentParameters() override {}; + RigidBodyAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix); + + /// Constructor for selection + RigidBodyAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection); + + /// Destructor + ~RigidBodyAlignmentParameters() override{}; void apply() override; int type() const override; /// Clone all parameters (for update of parameters) - RigidBodyAlignmentParameters* clone( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const override; - + RigidBodyAlignmentParameters *clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; + /// Clone selected parameters (for update of parameters) - RigidBodyAlignmentParameters* - cloneFromSelected(const AlgebraicVector& parameters, const AlgebraicSymMatrix& covMatrix) const override; - - /// Get all derivatives - AlgebraicMatrix derivatives( const TrajectoryStateOnSurface& tsos, - const AlignableDetOrUnitPtr & ) const override; + RigidBodyAlignmentParameters *cloneFromSelected(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; + + /// Get all derivatives + AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &) const override; /// Get selected derivatives - AlgebraicMatrix selectedDerivatives( const TrajectoryStateOnSurface& tsos, - const AlignableDetOrUnitPtr & ) const override; + AlgebraicMatrix selectedDerivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &) const override; /// Get translation parameters AlgebraicVector translation(void) const; @@ -72,17 +65,15 @@ class RigidBodyAlignmentParameters : public AlignmentParameters /// Get rotation parameters AlgebraicVector rotation(void) const; - /// calculate and return parameters in global frame + /// calculate and return parameters in global frame AlgebraicVector globalParameters(void) const; - /// print parameters to screen + /// print parameters to screen void print(void) const; - /// Calculate parameter vector of misplacements (shift+rotation) from alignable. - /// (If ali=0, return empty AlgebraicVector of proper length.) - static AlgebraicVector displacementFromAlignable(const Alignable* ali); - + /// Calculate parameter vector of misplacements (shift+rotation) from + /// alignable. (If ali=0, return empty AlgebraicVector of proper length.) + static AlgebraicVector displacementFromAlignable(const Alignable *ali); }; #endif - diff --git a/Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters4D.h b/Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters4D.h index fd492faf76458..a3a6303936036 100644 --- a/Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters4D.h +++ b/Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters4D.h @@ -7,7 +7,7 @@ /// \class RigidBodyAlignmentParameters /// -/// Concrete class for alignment parameters and associated quantities +/// Concrete class for alignment parameters and associated quantities /// [derived from AlignmentParameters]. The number of parameters /// N_PARAM is fixed to 6 (3 translations + 3 rotations) /// @@ -19,48 +19,42 @@ class Alignable; class AlignableDetOrUnitPtr; class TrajectoryStateOnSurface; -class RigidBodyAlignmentParameters4D : public RigidBodyAlignmentParameters -{ - +class RigidBodyAlignmentParameters4D : public RigidBodyAlignmentParameters { public: - - /// Constructor with empty parameters/covariance (if calcMis = false) or with parameters - /// (no covariance) created from current (mis-)placement of alignable (if calcMis = true). - RigidBodyAlignmentParameters4D(Alignable* alignable, bool calcMis): - RigidBodyAlignmentParameters(alignable, calcMis){}; - + /// Constructor with empty parameters/covariance (if calcMis = false) or with + /// parameters (no covariance) created from current (mis-)placement of + /// alignable (if calcMis = true). + RigidBodyAlignmentParameters4D(Alignable *alignable, bool calcMis) + : RigidBodyAlignmentParameters(alignable, calcMis){}; /// Constructor for full set of parameters - RigidBodyAlignmentParameters4D( Alignable* alignable, - const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ): - RigidBodyAlignmentParameters(alignable, parameters, covMatrix){}; + RigidBodyAlignmentParameters4D(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) + : RigidBodyAlignmentParameters(alignable, parameters, covMatrix){}; + + /// Constructor for selection + RigidBodyAlignmentParameters4D(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection) + : RigidBodyAlignmentParameters(alignable, parameters, covMatrix, selection){}; - /// Constructor for selection - RigidBodyAlignmentParameters4D( Alignable* alignable, const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix, - const std::vector& selection ): - RigidBodyAlignmentParameters(alignable, parameters, covMatrix, selection){}; + /// Destructor + ~RigidBodyAlignmentParameters4D() override{}; - /// Destructor - ~RigidBodyAlignmentParameters4D() override {}; - int type() const override; - /// Get all derivatives - AlgebraicMatrix derivatives( const TrajectoryStateOnSurface& tsos, - const AlignableDetOrUnitPtr & ) const override; + /// Get all derivatives + AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &) const override; /// Clone all parameters (for update of parameters) - RigidBodyAlignmentParameters4D* clone( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const override; + RigidBodyAlignmentParameters4D *clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; /// Clone selected parameters (for update of parameters) - RigidBodyAlignmentParameters4D* - cloneFromSelected(const AlgebraicVector& parameters, const AlgebraicSymMatrix& covMatrix) const override; - - + RigidBodyAlignmentParameters4D *cloneFromSelected(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; }; #endif - diff --git a/Alignment/CommonAlignmentParametrization/interface/SegmentAlignmentDerivatives4D.h b/Alignment/CommonAlignmentParametrization/interface/SegmentAlignmentDerivatives4D.h index dce16ea54610c..0d3b76cb1e84e 100644 --- a/Alignment/CommonAlignmentParametrization/interface/SegmentAlignmentDerivatives4D.h +++ b/Alignment/CommonAlignmentParametrization/interface/SegmentAlignmentDerivatives4D.h @@ -13,14 +13,10 @@ class TrajectoryStateOnSurface; -class SegmentAlignmentDerivatives4D -{ +class SegmentAlignmentDerivatives4D { public: - /// Returns 6x4 jacobian matrix AlgebraicMatrix operator()(const TrajectoryStateOnSurface &tsos) const; - }; #endif - diff --git a/Alignment/CommonAlignmentParametrization/interface/TwoBowedSurfacesAlignmentParameters.h b/Alignment/CommonAlignmentParametrization/interface/TwoBowedSurfacesAlignmentParameters.h index a4ef7eeff0ca0..7859141491bf9 100644 --- a/Alignment/CommonAlignmentParametrization/interface/TwoBowedSurfacesAlignmentParameters.h +++ b/Alignment/CommonAlignmentParametrization/interface/TwoBowedSurfacesAlignmentParameters.h @@ -2,16 +2,16 @@ #define Alignment_CommonAlignment_TwoBowedSurfacesAlignmentParameters_h #include "Alignment/CommonAlignment/interface/AlignmentParameters.h" -#include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "CondFormats/Alignment/interface/Definitions.h" +#include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentDerivatives.h" /// \class TwoBowedSurfacesAlignmentParameters /// -/// Concrete class for alignment parameters and associated quantities -/// [derived from AlignmentParameters]. -/// The alignable is assumed to have in fact two surfaces devided at +/// Concrete class for alignment parameters and associated quantities +/// [derived from AlignmentParameters]. +/// The alignable is assumed to have in fact two surfaces devided at /// a specific local ySplit. /// The number of parameters N_PARAM is 2x9, i.e. one set of /// - 3 translations @@ -19,12 +19,15 @@ /// - 3 bows/sagittas (u, v and mixed term) /// for the two surfaces (similar as in BowedSurfaceAlignmentParameters). /// Storage is done differently: -/// The movements and translations are averaged and applied to the +/// The movements and translations are averaged and applied to the /// alignable in the 'classical' way. /// In SurfaceDeformation we store: -/// - the half differences of the movements and rotations, to be taken into account, -/// with positive/negative sign, for corrections for the surface at lower/higher y, -/// - the mean values 'm' and half differences 'hd' of the bows/sagittas of each surface, +/// - the half differences of the movements and rotations, to be taken into +/// account, +/// with positive/negative sign, for corrections for the surface at +/// lower/higher y, +/// - the mean values 'm' and half differences 'hd' of the bows/sagittas of each +/// surface, /// where these corrections have to be applied as m+hd for the one and m-hd /// for the other sensor /// @@ -37,9 +40,8 @@ class Alignable; class AlignableDetOrUnitPtr; class TrajectoryStateOnSurface; -class TwoBowedSurfacesAlignmentParameters : public AlignmentParameters -{ - public: +class TwoBowedSurfacesAlignmentParameters : public AlignmentParameters { +public: /// Give parameters a name (do not change order, see derivatives(..)!) typedef BowedSurfaceAlignmentDerivatives BowedDerivs; enum AlignmentParameterName { @@ -47,22 +49,22 @@ class TwoBowedSurfacesAlignmentParameters : public AlignmentParameters dx1 = BowedDerivs::dx, dy1 = BowedDerivs::dy, dz1 = BowedDerivs::dz, - dslopeX1 = BowedDerivs::dslopeX, // NOTE: slope(u) -> halfWidth*tan(beta), - dslopeY1 = BowedDerivs::dslopeY, // slope(v) -> halfLength*tan(alpha) - drotZ1 = BowedDerivs::drotZ, // rot(w) -> g-scale*gamma - dsagittaX1 = BowedDerivs::dsagittaX, + dslopeX1 = BowedDerivs::dslopeX, // NOTE: slope(u) -> halfWidth*tan(beta), + dslopeY1 = BowedDerivs::dslopeY, // slope(v) -> halfLength*tan(alpha) + drotZ1 = BowedDerivs::drotZ, // rot(w) -> g-scale*gamma + dsagittaX1 = BowedDerivs::dsagittaX, dsagittaXY1 = BowedDerivs::dsagittaXY, - dsagittaY1 = BowedDerivs::dsagittaY, + dsagittaY1 = BowedDerivs::dsagittaY, // 2nd surface dx2 = BowedDerivs::dx + BowedDerivs::N_PARAM, dy2 = BowedDerivs::dy + BowedDerivs::N_PARAM, dz2 = BowedDerivs::dz + BowedDerivs::N_PARAM, - dslopeX2 = BowedDerivs::dslopeX + BowedDerivs::N_PARAM, // NOTE: slope(u) -> k*tan(beta), - dslopeY2 = BowedDerivs::dslopeY + BowedDerivs::N_PARAM, // slope(v) -> k*tan(alpha) - drotZ2 = BowedDerivs::drotZ + BowedDerivs::N_PARAM, // rot(w) -> m*gamma - dsagittaX2 = BowedDerivs::dsagittaX + BowedDerivs::N_PARAM, + dslopeX2 = BowedDerivs::dslopeX + BowedDerivs::N_PARAM, // NOTE: slope(u) -> k*tan(beta), + dslopeY2 = BowedDerivs::dslopeY + BowedDerivs::N_PARAM, // slope(v) -> k*tan(alpha) + drotZ2 = BowedDerivs::drotZ + BowedDerivs::N_PARAM, // rot(w) -> m*gamma + dsagittaX2 = BowedDerivs::dsagittaX + BowedDerivs::N_PARAM, dsagittaXY2 = BowedDerivs::dsagittaXY + BowedDerivs::N_PARAM, - dsagittaY2 = BowedDerivs::dsagittaY + BowedDerivs::N_PARAM, + dsagittaY2 = BowedDerivs::dsagittaY + BowedDerivs::N_PARAM, // number of parameters N_PARAM = BowedDerivs::N_PARAM + BowedDerivs::N_PARAM }; @@ -71,43 +73,41 @@ class TwoBowedSurfacesAlignmentParameters : public AlignmentParameters TwoBowedSurfacesAlignmentParameters(Alignable *alignable); /// Constructor for full set of parameters - TwoBowedSurfacesAlignmentParameters(Alignable *alignable, - const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix); - - /// Constructor for selection - TwoBowedSurfacesAlignmentParameters(Alignable *alignable, const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix, - const std::vector &selection); - - /// Destructor - ~TwoBowedSurfacesAlignmentParameters() override {}; + TwoBowedSurfacesAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix); + + /// Constructor for selection + TwoBowedSurfacesAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection); + + /// Destructor + ~TwoBowedSurfacesAlignmentParameters() override{}; void apply() override; int type() const override; /// Clone all parameters (for update of parameters) - TwoBowedSurfacesAlignmentParameters* clone(const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) const override; - + TwoBowedSurfacesAlignmentParameters *clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; + /// Clone selected parameters (for update of parameters) - TwoBowedSurfacesAlignmentParameters* - cloneFromSelected(const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) const override; - - /// Get all derivatives - AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &aliDet) const override; - - /// print parameters to screen + TwoBowedSurfacesAlignmentParameters *cloneFromSelected(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const override; + + /// Get all derivatives + AlgebraicMatrix derivatives(const TrajectoryStateOnSurface &tsos, const AlignableDetOrUnitPtr &aliDet) const override; + + /// print parameters to screen virtual void print() const; - double ySplit() const { return ySplit_;} + double ySplit() const { return ySplit_; } - private: +private: double ySplitFromAlignable(const Alignable *ali) const; double ySplit_; }; #endif - diff --git a/Alignment/CommonAlignmentParametrization/src/AlignmentParametersFactory.cc b/Alignment/CommonAlignmentParametrization/src/AlignmentParametersFactory.cc index 2cdaad6ac0cd5..b58baa07405fd 100644 --- a/Alignment/CommonAlignmentParametrization/src/AlignmentParametersFactory.cc +++ b/Alignment/CommonAlignmentParametrization/src/AlignmentParametersFactory.cc @@ -3,124 +3,122 @@ /// (last update by $Author: mussgill $) #include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" -#include "Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h" -#include "Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters4D.h" #include "Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentParameters.h" #include "Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentParameters.h" +#include "Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h" +#include "Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters4D.h" #include "Alignment/CommonAlignmentParametrization/interface/TwoBowedSurfacesAlignmentParameters.h" //#include "Alignment/SurveyAnalysis/interface/SurveyParameters.h" #include "DataFormats/CLHEP/interface/AlgebraicObjects.h" -#include "FWCore/Utilities/interface/Exception.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/Utilities/interface/Exception.h" - -#include #include +#include namespace AlignmentParametersFactory { - + //_______________________________________________________________________________________ - ParametersType parametersType(const std::string &typeString) - { - if (typeString == "RigidBody") return kRigidBody; - else if (typeString == "Survey") return kSurvey; //GF: do not belong here, so remove in the long term... - else if (typeString == "RigidBody4D") return kRigidBody4D; - else if (typeString == "BeamSpot") return kBeamSpot; - else if (typeString == "BowedSurface") return kBowedSurface; - else if (typeString == "TwoBowedSurfaces") return kTwoBowedSurfaces; - throw cms::Exception("BadConfig") - << "AlignmentParametersFactory" << " No AlignmentParameters with name '" << typeString << "'."; - - return kRigidBody; // to please compiler... + ParametersType parametersType(const std::string &typeString) { + if (typeString == "RigidBody") + return kRigidBody; + else if (typeString == "Survey") + return kSurvey; // GF: do not belong here, so remove in the long term... + else if (typeString == "RigidBody4D") + return kRigidBody4D; + else if (typeString == "BeamSpot") + return kBeamSpot; + else if (typeString == "BowedSurface") + return kBowedSurface; + else if (typeString == "TwoBowedSurfaces") + return kTwoBowedSurfaces; + throw cms::Exception("BadConfig") << "AlignmentParametersFactory" + << " No AlignmentParameters with name '" << typeString << "'."; + + return kRigidBody; // to please compiler... } //_______________________________________________________________________________________ - ParametersType parametersType(int typeInt) - { - if (typeInt == kRigidBody) return kRigidBody; - if (typeInt == kSurvey) return kSurvey; //GF: do not belong here, so remove in the long term... - if (typeInt == kRigidBody4D) return kRigidBody4D; - if (typeInt == kBeamSpot) return kBeamSpot; - if (typeInt == kBowedSurface) return kBowedSurface; - if (typeInt == kTwoBowedSurfaces) return kTwoBowedSurfaces; - - throw cms::Exception("BadConfig") - << "AlignmentParametersFactory" << " No AlignmentParameters with number " << typeInt << "."; - - return kRigidBody; // to please compiler... + ParametersType parametersType(int typeInt) { + if (typeInt == kRigidBody) + return kRigidBody; + if (typeInt == kSurvey) + return kSurvey; // GF: do not belong here, so remove in the long term... + if (typeInt == kRigidBody4D) + return kRigidBody4D; + if (typeInt == kBeamSpot) + return kBeamSpot; + if (typeInt == kBowedSurface) + return kBowedSurface; + if (typeInt == kTwoBowedSurfaces) + return kTwoBowedSurfaces; + + throw cms::Exception("BadConfig") << "AlignmentParametersFactory" + << " No AlignmentParameters with number " << typeInt << "."; + + return kRigidBody; // to please compiler... } //_______________________________________________________________________________________ - std::string parametersTypeName(ParametersType parType) - { - switch(parType) { - case kRigidBody: - return "RigiBody"; - case kSurvey: //GF: do not belong here, so remove in the long term... - return "Survey"; - case kRigidBody4D: - return "RigiBody4D"; - case kBeamSpot: - return "BeamSpot"; - case kBowedSurface: - return "BowedSurface"; - case kTwoBowedSurfaces: - return "TwoBowedSurfaces"; + std::string parametersTypeName(ParametersType parType) { + switch (parType) { + case kRigidBody: + return "RigiBody"; + case kSurvey: // GF: do not belong here, so remove in the long term... + return "Survey"; + case kRigidBody4D: + return "RigiBody4D"; + case kBeamSpot: + return "BeamSpot"; + case kBowedSurface: + return "BowedSurface"; + case kTwoBowedSurfaces: + return "TwoBowedSurfaces"; } - return "unknown_should_never_reach"; // to please the compiler + return "unknown_should_never_reach"; // to please the compiler } //_______________________________________________________________________________________ - AlignmentParameters* createParameters(Alignable *ali, ParametersType parType, - const std::vector &sel) - { + AlignmentParameters *createParameters(Alignable *ali, ParametersType parType, const std::vector &sel) { switch (parType) { - case kRigidBody: - { - const AlgebraicVector par(RigidBodyAlignmentParameters::N_PARAM, 0); - const AlgebraicSymMatrix cov(RigidBodyAlignmentParameters::N_PARAM, 0); - return new RigidBodyAlignmentParameters(ali, par, cov, sel); - } - break; - case kSurvey: -// creates some unwanted dependencies - and does not fit into AlignmentParameters anyway! - throw cms::Exception("BadConfig") - << "AlignmentParametersFactory cannot create SurveyParameters."; -// edm::LogWarning("Alignment") << "@SUB=createParameters" -// << "Creating SurveyParameters of length 0!"; -// return new SurveyParameters(ali, AlgebraicVector(), AlgebraicSymMatrix()); - break; - case kRigidBody4D: - { - const AlgebraicVector par(RigidBodyAlignmentParameters4D::N_PARAM, 0); - const AlgebraicSymMatrix cov(RigidBodyAlignmentParameters4D::N_PARAM, 0); - return new RigidBodyAlignmentParameters4D(ali, par, cov, sel); - } - break; - case kBeamSpot: - { - const AlgebraicVector par(BeamSpotAlignmentParameters::N_PARAM, 0); - const AlgebraicSymMatrix cov(BeamSpotAlignmentParameters::N_PARAM, 0); - return new BeamSpotAlignmentParameters(ali, par, cov, sel); - } - break; - case kBowedSurface: - { - const AlgebraicVector par(BowedSurfaceAlignmentParameters::N_PARAM, 0); - const AlgebraicSymMatrix cov(BowedSurfaceAlignmentParameters::N_PARAM, 0); - return new BowedSurfaceAlignmentParameters(ali, par, cov, sel); - } - break; - case kTwoBowedSurfaces: - { - const AlgebraicVector par(TwoBowedSurfacesAlignmentParameters::N_PARAM, 0); - const AlgebraicSymMatrix cov(TwoBowedSurfacesAlignmentParameters::N_PARAM, 0); - return new TwoBowedSurfacesAlignmentParameters(ali, par, cov, sel); - } - break; + case kRigidBody: { + const AlgebraicVector par(RigidBodyAlignmentParameters::N_PARAM, 0); + const AlgebraicSymMatrix cov(RigidBodyAlignmentParameters::N_PARAM, 0); + return new RigidBodyAlignmentParameters(ali, par, cov, sel); + } break; + case kSurvey: + // creates some unwanted dependencies - and does not fit into + // AlignmentParameters anyway! + throw cms::Exception("BadConfig") << "AlignmentParametersFactory cannot create SurveyParameters."; + // edm::LogWarning("Alignment") << "@SUB=createParameters" + // << "Creating SurveyParameters of length 0!"; + // return new SurveyParameters(ali, AlgebraicVector(), + // AlgebraicSymMatrix()); + break; + case kRigidBody4D: { + const AlgebraicVector par(RigidBodyAlignmentParameters4D::N_PARAM, 0); + const AlgebraicSymMatrix cov(RigidBodyAlignmentParameters4D::N_PARAM, 0); + return new RigidBodyAlignmentParameters4D(ali, par, cov, sel); + } break; + case kBeamSpot: { + const AlgebraicVector par(BeamSpotAlignmentParameters::N_PARAM, 0); + const AlgebraicSymMatrix cov(BeamSpotAlignmentParameters::N_PARAM, 0); + return new BeamSpotAlignmentParameters(ali, par, cov, sel); + } break; + case kBowedSurface: { + const AlgebraicVector par(BowedSurfaceAlignmentParameters::N_PARAM, 0); + const AlgebraicSymMatrix cov(BowedSurfaceAlignmentParameters::N_PARAM, 0); + return new BowedSurfaceAlignmentParameters(ali, par, cov, sel); + } break; + case kTwoBowedSurfaces: { + const AlgebraicVector par(TwoBowedSurfacesAlignmentParameters::N_PARAM, 0); + const AlgebraicSymMatrix cov(TwoBowedSurfacesAlignmentParameters::N_PARAM, 0); + return new TwoBowedSurfacesAlignmentParameters(ali, par, cov, sel); + } break; } - - return nullptr; // unreached (all ParametersType appear in switch), to please the compiler + + return nullptr; // unreached (all ParametersType appear in switch), to please + // the compiler } -} +} // namespace AlignmentParametersFactory diff --git a/Alignment/CommonAlignmentParametrization/src/BeamSpotAlignmentDerivatives.cc b/Alignment/CommonAlignmentParametrization/src/BeamSpotAlignmentDerivatives.cc index f51639cecbf4d..acbb978b16b9a 100644 --- a/Alignment/CommonAlignmentParametrization/src/BeamSpotAlignmentDerivatives.cc +++ b/Alignment/CommonAlignmentParametrization/src/BeamSpotAlignmentDerivatives.cc @@ -9,17 +9,16 @@ #include "TrackingTools/PatternTools/interface/TwoTrackMinimumDistance.h" -#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "TrackingTools/TrajectoryState/interface/PerigeeConversions.h" +#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentDerivatives.h" -AlgebraicMatrix -BeamSpotAlignmentDerivatives::operator()( const TrajectoryStateOnSurface &tsos ) const -{ - AlgebraicMatrix aliderivs(4,2); +AlgebraicMatrix BeamSpotAlignmentDerivatives::operator()(const TrajectoryStateOnSurface &tsos) const { + AlgebraicMatrix aliderivs(4, 2); - if (!tsos.isValid()) return aliderivs; + if (!tsos.isValid()) + return aliderivs; // lp.x = transverse impact parameter // lp.y = longitudinal impact parameter @@ -29,14 +28,14 @@ BeamSpotAlignmentDerivatives::operator()( const TrajectoryStateOnSurface &tsos ) double sinphi = sin(phi); double cosphi = cos(phi); - aliderivs[0][0]= sinphi; - aliderivs[0][1]= 0.0; - aliderivs[1][0]= -cosphi; - aliderivs[1][1]= 0.0; - aliderivs[2][0]= sinphi*dz; - aliderivs[2][1]= 0.0; - aliderivs[3][0]= -cosphi*dz; - aliderivs[3][1]= 0.0; - - return(aliderivs); + aliderivs[0][0] = sinphi; + aliderivs[0][1] = 0.0; + aliderivs[1][0] = -cosphi; + aliderivs[1][1] = 0.0; + aliderivs[2][0] = sinphi * dz; + aliderivs[2][1] = 0.0; + aliderivs[3][0] = -cosphi * dz; + aliderivs[3][1] = 0.0; + + return (aliderivs); } diff --git a/Alignment/CommonAlignmentParametrization/src/BeamSpotAlignmentParameters.cc b/Alignment/CommonAlignmentParametrization/src/BeamSpotAlignmentParameters.cc index df00c84a1d0a4..db6272a176000 100644 --- a/Alignment/CommonAlignmentParametrization/src/BeamSpotAlignmentParameters.cc +++ b/Alignment/CommonAlignmentParametrization/src/BeamSpotAlignmentParameters.cc @@ -7,120 +7,103 @@ #include "FWCore/Utilities/interface/Exception.h" -#include "Alignment/CommonAlignment/interface/Utilities.h" #include "Alignment/CommonAlignment/interface/Alignable.h" #include "Alignment/CommonAlignment/interface/AlignableDetOrUnitPtr.h" -#include "Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentDerivatives.h" +#include "Alignment/CommonAlignment/interface/Utilities.h" #include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" +#include "Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentDerivatives.h" #include "CondFormats/Alignment/interface/Definitions.h" -// This class's header +// This class's header #include "Alignment/CommonAlignmentParametrization/interface/BeamSpotAlignmentParameters.h" //__________________________________________________________________________________________________ -BeamSpotAlignmentParameters::BeamSpotAlignmentParameters(Alignable* ali, bool calcMis) : - AlignmentParameters(ali, displacementFromAlignable(calcMis ? ali : nullptr), - AlgebraicSymMatrix(N_PARAM, 0)) -{ - -} +BeamSpotAlignmentParameters::BeamSpotAlignmentParameters(Alignable *ali, bool calcMis) + : AlignmentParameters(ali, displacementFromAlignable(calcMis ? ali : nullptr), AlgebraicSymMatrix(N_PARAM, 0)) {} //__________________________________________________________________________________________________ -BeamSpotAlignmentParameters::BeamSpotAlignmentParameters(Alignable* alignable, - const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix) : - AlignmentParameters( alignable, parameters, covMatrix ) -{ +BeamSpotAlignmentParameters::BeamSpotAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) + : AlignmentParameters(alignable, parameters, covMatrix) { if (parameters.num_row() != N_PARAM) { - throw cms::Exception("BadParameters") << "in BeamSpotAlignmentParameters(): " - << parameters.num_row() << " instead of " << N_PARAM - << " parameters."; + throw cms::Exception("BadParameters") + << "in BeamSpotAlignmentParameters(): " << parameters.num_row() << " instead of " << N_PARAM << " parameters."; } } //__________________________________________________________________________________________________ -BeamSpotAlignmentParameters::BeamSpotAlignmentParameters(Alignable* alignable, - const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix, - const std::vector& selection ) : - AlignmentParameters( alignable, parameters, covMatrix, selection ) -{ +BeamSpotAlignmentParameters::BeamSpotAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection) + : AlignmentParameters(alignable, parameters, covMatrix, selection) { if (parameters.num_row() != N_PARAM) { - throw cms::Exception("BadParameters") << "in BeamSpotAlignmentParameters(): " - << parameters.num_row() << " instead of " << N_PARAM - << " parameters."; + throw cms::Exception("BadParameters") + << "in BeamSpotAlignmentParameters(): " << parameters.num_row() << " instead of " << N_PARAM << " parameters."; } } //__________________________________________________________________________________________________ -BeamSpotAlignmentParameters::~BeamSpotAlignmentParameters() -{ - -} +BeamSpotAlignmentParameters::~BeamSpotAlignmentParameters() {} //__________________________________________________________________________________________________ -BeamSpotAlignmentParameters* -BeamSpotAlignmentParameters::clone( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const -{ - BeamSpotAlignmentParameters* rbap = - new BeamSpotAlignmentParameters( alignable(), parameters, covMatrix, selector()); - - if (userVariables()) rbap->setUserVariables(userVariables()->clone()); +BeamSpotAlignmentParameters *BeamSpotAlignmentParameters::clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const { + BeamSpotAlignmentParameters *rbap = new BeamSpotAlignmentParameters(alignable(), parameters, covMatrix, selector()); + + if (userVariables()) + rbap->setUserVariables(userVariables()->clone()); rbap->setValid(isValid()); return rbap; } //__________________________________________________________________________________________________ -BeamSpotAlignmentParameters* -BeamSpotAlignmentParameters::cloneFromSelected( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const -{ - BeamSpotAlignmentParameters* rbap = - new BeamSpotAlignmentParameters(alignable(), expandVector( parameters, selector()), - expandSymMatrix(covMatrix, selector()), selector()); - - if ( userVariables() ) rbap->setUserVariables(userVariables()->clone()); +BeamSpotAlignmentParameters *BeamSpotAlignmentParameters::cloneFromSelected(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const { + BeamSpotAlignmentParameters *rbap = new BeamSpotAlignmentParameters( + alignable(), expandVector(parameters, selector()), expandSymMatrix(covMatrix, selector()), selector()); + + if (userVariables()) + rbap->setUserVariables(userVariables()->clone()); rbap->setValid(isValid()); - + return rbap; } //__________________________________________________________________________________________________ -AlgebraicMatrix -BeamSpotAlignmentParameters::derivatives( const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &alidet ) const -{ - const Alignable *ali = this->alignable(); // Alignable of these parameters +AlgebraicMatrix BeamSpotAlignmentParameters::derivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alidet) const { + const Alignable *ali = this->alignable(); // Alignable of these parameters - if (ali == alidet) { // same alignable => same frame + if (ali == alidet) { // same alignable => same frame return BeamSpotAlignmentDerivatives()(tsos); } else { - throw cms::Exception("MisMatch") - << "BeamSpotAlignmentParameters::derivatives: The hit alignable must match the " - << "aligned one, i.e. these parameters make only sense for AlignableBeamSpot.\n"; - return AlgebraicMatrix(N_PARAM, 2); // please compiler + throw cms::Exception("MisMatch") << "BeamSpotAlignmentParameters::derivatives: The hit alignable must " + "match the " + << "aligned one, i.e. these parameters make only sense for " + "AlignableBeamSpot.\n"; + return AlgebraicMatrix(N_PARAM, 2); // please compiler } } //__________________________________________________________________________________________________ -AlgebraicMatrix -BeamSpotAlignmentParameters::selectedDerivatives( const TrajectoryStateOnSurface& tsos, - const AlignableDetOrUnitPtr &alignableDet ) const -{ - const AlgebraicMatrix dev = this->derivatives( tsos, alignableDet ); +AlgebraicMatrix BeamSpotAlignmentParameters::selectedDerivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alignableDet) const { + const AlgebraicMatrix dev = this->derivatives(tsos, alignableDet); - int ncols = dev.num_col(); - int nrows = dev.num_row(); - int nsel = numSelected(); + int ncols = dev.num_col(); + int nrows = dev.num_row(); + int nsel = numSelected(); - AlgebraicMatrix seldev( nsel, ncols ); + AlgebraicMatrix seldev(nsel, ncols); - int ir2=0; - for ( int irow=0; irowparameters()[i]; + for (int i = 0; i < 2; ++i) + shift[i] = theData->parameters()[i]; shift[2] = 0.0; return shift; } //__________________________________________________________________________________________________ -AlgebraicVector BeamSpotAlignmentParameters::rotation(void) const -{ +AlgebraicVector BeamSpotAlignmentParameters::rotation(void) const { AlgebraicVector rot(3); - double dxdz = theData->parameters()[2]; - double dydz = theData->parameters()[3]; + double dxdz = theData->parameters()[2]; + double dydz = theData->parameters()[3]; double angleY = std::atan(dxdz); double angleX = -std::atan(dydz); - align::RotationType rotY( std::cos(angleY), 0., -std::sin(angleY), - 0., 1., 0., - std::sin(angleY), 0., std::cos(angleY) ); + align::RotationType rotY(std::cos(angleY), 0., -std::sin(angleY), 0., 1., 0., std::sin(angleY), 0., std::cos(angleY)); - align::RotationType rotX( 1., 0., 0., - 0., std::cos(angleX), std::sin(angleX), - 0., -std::sin(angleX), std::cos(angleX) ); + align::RotationType rotX(1., 0., 0., 0., std::cos(angleX), std::sin(angleX), 0., -std::sin(angleX), std::cos(angleX)); align::EulerAngles angles = align::toAngles(rotY * rotX); @@ -166,88 +144,77 @@ AlgebraicVector BeamSpotAlignmentParameters::rotation(void) const } //__________________________________________________________________________________________________ -void BeamSpotAlignmentParameters::apply() -{ +void BeamSpotAlignmentParameters::apply() { Alignable *alignable = this->alignable(); if (!alignable) { - throw cms::Exception("BadParameters") - << "BeamSpotAlignmentParameters::apply: parameters without alignable"; + throw cms::Exception("BadParameters") << "BeamSpotAlignmentParameters::apply: parameters without alignable"; } - + // Translation in local frame - AlgebraicVector shift = this->translation(); // fixme: should be LocalVector - + AlgebraicVector shift = this->translation(); // fixme: should be LocalVector + // Translation local->global align::GlobalVector gv(shift[0], shift[1], shift[2]); - alignable->move( gv ); + alignable->move(gv); // Rotation in local frame align::EulerAngles angles = this->rotation(); // original code: // alignable->rotateInLocalFrame( align::toMatrix(angles) ); // correct for rounding errors: - align::RotationType rot = alignable->surface().toGlobal( align::toMatrix(angles) ); + align::RotationType rot = alignable->surface().toGlobal(align::toMatrix(angles)); align::rectify(rot); alignable->rotateInGlobalFrame(rot); } //__________________________________________________________________________________________________ -int BeamSpotAlignmentParameters::type() const -{ - return AlignmentParametersFactory::kBeamSpot; -} +int BeamSpotAlignmentParameters::type() const { return AlignmentParametersFactory::kBeamSpot; } //__________________________________________________________________________________________________ -AlgebraicVector BeamSpotAlignmentParameters::globalParameters(void) const -{ +AlgebraicVector BeamSpotAlignmentParameters::globalParameters(void) const { AlgebraicVector m_GlobalParameters(N_PARAM, 0); - const AlgebraicVector shift = translation(); // fixme: should return LocalVector + const AlgebraicVector shift = translation(); // fixme: should return LocalVector const align::GlobalVector dg(shift[0], shift[1], 0); - + m_GlobalParameters[0] = dg.x(); m_GlobalParameters[1] = dg.y(); - + align::LocalVector lv(0.0, 0.0, 1.0); align::GlobalVector gv = theAlignable->surface().toGlobal(lv); - - double dxdz = gv.x()/gv.z(); - double dydz = gv.x()/gv.z(); - + + double dxdz = gv.x() / gv.z(); + double dydz = gv.x() / gv.z(); + m_GlobalParameters[2] = dxdz; m_GlobalParameters[3] = dydz; - + return m_GlobalParameters; } //__________________________________________________________________________________________________ -void BeamSpotAlignmentParameters::print(void) const -{ - +void BeamSpotAlignmentParameters::print(void) const { std::cout << "Contents of BeamSpotAlignmentParameters:" - << "\nParameters: " << theData->parameters() - << "\nCovariance: " << theData->covariance() << std::endl; + << "\nParameters: " << theData->parameters() << "\nCovariance: " << theData->covariance() << std::endl; } //__________________________________________________________________________________________________ -AlgebraicVector BeamSpotAlignmentParameters::displacementFromAlignable(const Alignable* ali) -{ +AlgebraicVector BeamSpotAlignmentParameters::displacementFromAlignable(const Alignable *ali) { AlgebraicVector displacement(N_PARAM); if (ali) { - const align::RotationType& dR = ali->rotation(); - - const align::LocalVector shifts( ali->globalRotation() * - ( dR.transposed() * ali->displacement().basicVector() ) ); - + const align::RotationType &dR = ali->rotation(); + + const align::LocalVector shifts(ali->globalRotation() * (dR.transposed() * ali->displacement().basicVector())); + align::GlobalVector gv(0.0, 0.0, 1.0); align::LocalVector lv(dR.transposed() * gv.basicVector()); - + displacement[0] = shifts.x(); displacement[1] = shifts.y(); - displacement[2] = lv.x()/lv.z(); - displacement[3] = lv.y()/lv.z(); + displacement[2] = lv.x() / lv.z(); + displacement[3] = lv.y() / lv.z(); } return displacement; diff --git a/Alignment/CommonAlignmentParametrization/src/BowedSurfaceAlignmentDerivatives.cc b/Alignment/CommonAlignmentParametrization/src/BowedSurfaceAlignmentDerivatives.cc index afc2d75fc5e9e..ccb2adafbf845 100644 --- a/Alignment/CommonAlignmentParametrization/src/BowedSurfaceAlignmentDerivatives.cc +++ b/Alignment/CommonAlignmentParametrization/src/BowedSurfaceAlignmentDerivatives.cc @@ -6,16 +6,12 @@ #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" -#include "Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h" #include "Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentDerivatives.h" +#include "Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h" #include -AlgebraicMatrix -BowedSurfaceAlignmentDerivatives::operator()(const TrajectoryStateOnSurface &tsos, - double uWidth, double vLength, - bool doSplit, double ySplit) const -{ - +AlgebraicMatrix BowedSurfaceAlignmentDerivatives::operator()( + const TrajectoryStateOnSurface &tsos, double uWidth, double vLength, bool doSplit, double ySplit) const { AlgebraicMatrix result(N_PARAM, 2); // track parameters on surface: @@ -26,15 +22,17 @@ BowedSurfaceAlignmentDerivatives::operator()(const TrajectoryStateOnSurface &tso // [4] y : local y-coordinate double myY = tsosPar[4]; double myLengthV = vLength; - if (doSplit) { // re-'calibrate' y length and transform myY to be w.r.t. surface middle - // Some signs depend on whether we are in surface part below or above ySplit: - const double sign = (tsosPar[4] < ySplit ? +1. : -1.); - const double yMiddle = ySplit * 0.5 - sign * vLength * .25; // middle of surface + if (doSplit) { // re-'calibrate' y length and transform myY to be w.r.t. + // surface middle + // Some signs depend on whether we are in surface part below or above + // ySplit: + const double sign = (tsosPar[4] < ySplit ? +1. : -1.); + const double yMiddle = ySplit * 0.5 - sign * vLength * .25; // middle of surface myY = tsosPar[4] - yMiddle; myLengthV = vLength * 0.5 + sign * ySplit; } - const AlgebraicMatrix karimaki(KarimakiAlignmentDerivatives()(tsos)); // it's just 6x2... + const AlgebraicMatrix karimaki(KarimakiAlignmentDerivatives()(tsos)); // it's just 6x2... // copy u, v, w from Karimaki - they are independent of splitting result[dx][0] = karimaki[0][0]; result[dx][1] = karimaki[0][1]; @@ -43,45 +41,52 @@ BowedSurfaceAlignmentDerivatives::operator()(const TrajectoryStateOnSurface &tso result[dz][0] = karimaki[2][0]; result[dz][1] = karimaki[2][1]; const double aScale = gammaScale(uWidth, myLengthV); - result[drotZ][0] = myY / aScale; // Since karimaki[5][0] == vx; + result[drotZ][0] = myY / aScale; // Since karimaki[5][0] == vx; result[drotZ][1] = karimaki[5][1] / aScale; double uRel = 2. * tsosPar[3] / uWidth; // relative u (-1 .. +1) - double vRel = 2. * myY / myLengthV; // relative v (-1 .. +1) + double vRel = 2. * myY / myLengthV; // relative v (-1 .. +1) // 'range check': const double cutOff = 1.5; - if (uRel < -cutOff) { uRel = -cutOff; } else if (uRel > cutOff) { uRel = cutOff; } - if (vRel < -cutOff) { vRel = -cutOff; } else if (vRel > cutOff) { vRel = cutOff; } + if (uRel < -cutOff) { + uRel = -cutOff; + } else if (uRel > cutOff) { + uRel = cutOff; + } + if (vRel < -cutOff) { + vRel = -cutOff; + } else if (vRel > cutOff) { + vRel = cutOff; + } // Legendre polynomials renormalized to LPn(1)-LPn(0)=1 (n>0) const double uLP0 = 1.0; const double uLP1 = uRel; - const double uLP2 = uRel * uRel - 1./3.; + const double uLP2 = uRel * uRel - 1. / 3.; const double vLP0 = 1.0; const double vLP1 = vRel; - const double vLP2 = vRel * vRel - 1./3.; + const double vLP2 = vRel * vRel - 1. / 3.; // 1st order (slopes, replacing angles beta, alpha) result[dslopeX][0] = tsosPar[1] * uLP1 * vLP0; result[dslopeX][1] = tsosPar[2] * uLP1 * vLP0; result[dslopeY][0] = tsosPar[1] * uLP0 * vLP1; result[dslopeY][1] = tsosPar[2] * uLP0 * vLP1; - + // 2nd order (sagitta) - result[dsagittaX ][0] = tsosPar[1] * uLP2 * vLP0; - result[dsagittaX ][1] = tsosPar[2] * uLP2 * vLP0; + result[dsagittaX][0] = tsosPar[1] * uLP2 * vLP0; + result[dsagittaX][1] = tsosPar[2] * uLP2 * vLP0; result[dsagittaXY][0] = tsosPar[1] * uLP1 * vLP1; result[dsagittaXY][1] = tsosPar[2] * uLP1 * vLP1; - result[dsagittaY ][0] = tsosPar[1] * uLP0 * vLP2; - result[dsagittaY ][1] = tsosPar[2] * uLP0 * vLP2; - + result[dsagittaY][0] = tsosPar[1] * uLP0 * vLP2; + result[dsagittaY][1] = tsosPar[2] * uLP0 * vLP2; + return result; } //------------------------------------------------------------------------------ -double BowedSurfaceAlignmentDerivatives::gammaScale(double width, double splitLength) -{ -// return 0.5 * std::sqrt(width*width + splitLength*splitLength); -// return 0.5 * (std::fabs(width) + std::fabs(splitLength)); +double BowedSurfaceAlignmentDerivatives::gammaScale(double width, double splitLength) { + // return 0.5 * std::sqrt(width*width + splitLength*splitLength); + // return 0.5 * (std::fabs(width) + std::fabs(splitLength)); return 0.5 * (width + splitLength); } diff --git a/Alignment/CommonAlignmentParametrization/src/BowedSurfaceAlignmentParameters.cc b/Alignment/CommonAlignmentParametrization/src/BowedSurfaceAlignmentParameters.cc index 4034970b144ce..5e07e9e76c859 100644 --- a/Alignment/CommonAlignmentParametrization/src/BowedSurfaceAlignmentParameters.cc +++ b/Alignment/CommonAlignmentParametrization/src/BowedSurfaceAlignmentParameters.cc @@ -5,119 +5,101 @@ * by : $Author: flucke $ */ -#include "FWCore/Utilities/interface/Exception.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/Utilities/interface/Exception.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "Alignment/CommonAlignment/interface/Alignable.h" #include "Alignment/CommonAlignment/interface/AlignableDetOrUnitPtr.h" -#include "Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h" #include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" +#include "Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h" #include "CondFormats/Alignment/interface/Definitions.h" #include "Geometry/CommonTopologies/interface/BowedSurfaceDeformation.h" - -// This class's header +// This class's header #include "Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentParameters.h" #include //_________________________________________________________________________________________________ -BowedSurfaceAlignmentParameters::BowedSurfaceAlignmentParameters(Alignable *ali) : - AlignmentParameters(ali, AlgebraicVector(N_PARAM), AlgebraicSymMatrix(N_PARAM, 0)) -{ -} +BowedSurfaceAlignmentParameters::BowedSurfaceAlignmentParameters(Alignable *ali) + : AlignmentParameters(ali, AlgebraicVector(N_PARAM), AlgebraicSymMatrix(N_PARAM, 0)) {} //_________________________________________________________________________________________________ -BowedSurfaceAlignmentParameters -::BowedSurfaceAlignmentParameters(Alignable *alignable, - const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) : - AlignmentParameters(alignable, parameters, covMatrix) -{ +BowedSurfaceAlignmentParameters ::BowedSurfaceAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) + : AlignmentParameters(alignable, parameters, covMatrix) { if (parameters.num_row() != N_PARAM) { - throw cms::Exception("BadParameters") << "in BowedSurfaceAlignmentParameters(): " - << parameters.num_row() << " instead of " << N_PARAM - << " parameters."; + throw cms::Exception("BadParameters") << "in BowedSurfaceAlignmentParameters(): " << parameters.num_row() + << " instead of " << N_PARAM << " parameters."; } } //_________________________________________________________________________________________________ -BowedSurfaceAlignmentParameters -::BowedSurfaceAlignmentParameters(Alignable *alignable, - const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix, - const std::vector &selection) : - AlignmentParameters(alignable, parameters, covMatrix, selection) -{ +BowedSurfaceAlignmentParameters ::BowedSurfaceAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection) + : AlignmentParameters(alignable, parameters, covMatrix, selection) { if (parameters.num_row() != N_PARAM) { - throw cms::Exception("BadParameters") << "in BowedSurfaceAlignmentParameters(): " - << parameters.num_row() << " instead of " << N_PARAM - << " parameters."; + throw cms::Exception("BadParameters") << "in BowedSurfaceAlignmentParameters(): " << parameters.num_row() + << " instead of " << N_PARAM << " parameters."; } } //_________________________________________________________________________________________________ -BowedSurfaceAlignmentParameters* -BowedSurfaceAlignmentParameters::clone(const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) const -{ - BowedSurfaceAlignmentParameters* rbap = - new BowedSurfaceAlignmentParameters(this->alignable(), parameters, covMatrix, selector()); - - if (this->userVariables()) rbap->setUserVariables(this->userVariables()->clone()); +BowedSurfaceAlignmentParameters *BowedSurfaceAlignmentParameters::clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const { + BowedSurfaceAlignmentParameters *rbap = + new BowedSurfaceAlignmentParameters(this->alignable(), parameters, covMatrix, selector()); + + if (this->userVariables()) + rbap->setUserVariables(this->userVariables()->clone()); rbap->setValid(this->isValid()); return rbap; } //_________________________________________________________________________________________________ -BowedSurfaceAlignmentParameters* -BowedSurfaceAlignmentParameters::cloneFromSelected(const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) const -{ +BowedSurfaceAlignmentParameters *BowedSurfaceAlignmentParameters::cloneFromSelected( + const AlgebraicVector ¶meters, const AlgebraicSymMatrix &covMatrix) const { return this->clone(this->expandVector(parameters, this->selector()), - this->expandSymMatrix(covMatrix, this->selector())); - + this->expandSymMatrix(covMatrix, this->selector())); } //_________________________________________________________________________________________________ -AlgebraicMatrix -BowedSurfaceAlignmentParameters::derivatives(const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &alidet) const -{ - const Alignable *ali = this->alignable(); // Alignable of these parameters +AlgebraicMatrix BowedSurfaceAlignmentParameters::derivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alidet) const { + const Alignable *ali = this->alignable(); // Alignable of these parameters if (ali == alidet) { const AlignableSurface &surf = ali->surface(); return BowedDerivs()(tsos, surf.width(), surf.length()); } else { - // We could give this a meaning by applying frame-to-frame derivatives + // We could give this a meaning by applying frame-to-frame derivatives // to the first six parameters (be careful that alpha and beta changed // their scale and switched their place compared to RigidBody!) and // keep the remaining three untouched in local meaning. // In this way we could do higher level alignment and determine 'average' // surface structures for the components. - throw cms::Exception("MisMatch") - << "BowedSurfaceAlignmentParameters::derivatives: The hit alignable must match the " - << "aligned one (i.e. bowed surface parameters cannot be used for composed alignables)\n"; - return AlgebraicMatrix(N_PARAM, 2); // please compiler + throw cms::Exception("MisMatch") << "BowedSurfaceAlignmentParameters::derivatives: The hit alignable " + "must match the " + << "aligned one (i.e. bowed surface parameters cannot be used for " + "composed alignables)\n"; + return AlgebraicMatrix(N_PARAM, 2); // please compiler } - } //_________________________________________________________________________________________________ -align::LocalVector BowedSurfaceAlignmentParameters::translation() const -{ +align::LocalVector BowedSurfaceAlignmentParameters::translation() const { // align::LocalVector uses double while LocalVector uses float only! const AlgebraicVector ¶ms = theData->parameters(); return align::LocalVector(params[dx], params[dy], params[dz]); } - //_________________________________________________________________________________________________ -align::EulerAngles BowedSurfaceAlignmentParameters::rotation() const -{ +align::EulerAngles BowedSurfaceAlignmentParameters::rotation() const { const AlgebraicVector ¶ms = theData->parameters(); const Alignable *alignable = this->alignable(); const AlignableSurface &surface = alignable->surface(); @@ -125,23 +107,22 @@ align::EulerAngles BowedSurfaceAlignmentParameters::rotation() const align::EulerAngles eulerAngles(3); // Note that dslopeX <-> -beta and dslopeY <-> alpha: // Should we use atan of these values? Anyway it is small... - eulerAngles[0] = params[dslopeY] * 2. / surface.length(); + eulerAngles[0] = params[dslopeY] * 2. / surface.length(); eulerAngles[1] = -params[dslopeX] * 2. / surface.width(); const double aScale = BowedDerivs::gammaScale(surface.width(), surface.length()); - eulerAngles[2] = params[drotZ] / aScale; + eulerAngles[2] = params[drotZ] / aScale; return eulerAngles; } //_________________________________________________________________________________________________ -void BowedSurfaceAlignmentParameters::apply() -{ +void BowedSurfaceAlignmentParameters::apply() { Alignable *alignable = this->alignable(); if (!alignable) { - throw cms::Exception("BadParameters") - << "BowedSurfaceAlignmentParameters::apply: parameters without alignable"; + throw cms::Exception("BadParameters") << "BowedSurfaceAlignmentParameters::apply: parameters without " + "alignable"; } - + // Get translation in local frame, transform to global and apply: alignable->move(alignable->surface().toGlobal(this->translation())); @@ -156,7 +137,7 @@ void BowedSurfaceAlignmentParameters::apply() // only update the surface deformations if they were selected for alignment if (selector()[dsagittaX] || selector()[dsagittaXY] || selector()[dsagittaY]) { - const auto& params = theData->parameters(); + const auto ¶ms = theData->parameters(); const BowedSurfaceDeformation deform{params[dsagittaX], params[dsagittaXY], params[dsagittaY]}; // FIXME: true to propagate down? @@ -167,15 +148,10 @@ void BowedSurfaceAlignmentParameters::apply() } //_________________________________________________________________________________________________ -int BowedSurfaceAlignmentParameters::type() const -{ - return AlignmentParametersFactory::kBowedSurface; -} +int BowedSurfaceAlignmentParameters::type() const { return AlignmentParametersFactory::kBowedSurface; } //_________________________________________________________________________________________________ -void BowedSurfaceAlignmentParameters::print() const -{ +void BowedSurfaceAlignmentParameters::print() const { std::cout << "Contents of BowedSurfaceAlignmentParameters:" - << "\nParameters: " << theData->parameters() - << "\nCovariance: " << theData->covariance() << std::endl; + << "\nParameters: " << theData->parameters() << "\nCovariance: " << theData->covariance() << std::endl; } diff --git a/Alignment/CommonAlignmentParametrization/src/CompositeAlignmentDerivativesExtractor.cc b/Alignment/CommonAlignmentParametrization/src/CompositeAlignmentDerivativesExtractor.cc index a5d263601c2b5..184b14a5cbab8 100644 --- a/Alignment/CommonAlignmentParametrization/src/CompositeAlignmentDerivativesExtractor.cc +++ b/Alignment/CommonAlignmentParametrization/src/CompositeAlignmentDerivativesExtractor.cc @@ -8,86 +8,77 @@ #include "Alignment/CommonAlignmentParametrization/interface/CompositeAlignmentDerivativesExtractor.h" //-------------------------------------------------------------------------------------- -CompositeAlignmentDerivativesExtractor:: -CompositeAlignmentDerivativesExtractor( const align::Alignables & alignables, - const std::vector< AlignableDet* > & alignableDets, - const std::vector< TrajectoryStateOnSurface > & tsos ) -{ +CompositeAlignmentDerivativesExtractor::CompositeAlignmentDerivativesExtractor( + const align::Alignables &alignables, + const std::vector &alignableDets, + const std::vector &tsos) { std::vector detOrUnits; detOrUnits.reserve(alignableDets.size()); - std::vector::const_iterator it, itEnd; + std::vector::const_iterator it, itEnd; for (it = alignableDets.begin(), itEnd = alignableDets.end(); it != itEnd; ++it) detOrUnits.push_back(AlignableDetOrUnitPtr(*it)); - extractCurrentAlignment( alignables, detOrUnits, tsos ); + extractCurrentAlignment(alignables, detOrUnits, tsos); } //-------------------------------------------------------------------------------------- -CompositeAlignmentDerivativesExtractor:: -CompositeAlignmentDerivativesExtractor( const align::Alignables & alignables, - const std::vector< AlignableDetOrUnitPtr > & alignableDets, - const std::vector< TrajectoryStateOnSurface > & tsos ) -{ - extractCurrentAlignment( alignables, alignableDets, tsos ); +CompositeAlignmentDerivativesExtractor::CompositeAlignmentDerivativesExtractor( + const align::Alignables &alignables, + const std::vector &alignableDets, + const std::vector &tsos) { + extractCurrentAlignment(alignables, alignableDets, tsos); } //-------------------------------------------------------------------------------------- -void CompositeAlignmentDerivativesExtractor:: -extractCurrentAlignment( const align::Alignables & alignables, - const std::vector< AlignableDetOrUnitPtr > & alignableDets, - const std::vector< TrajectoryStateOnSurface > & tsos ) -{ - +void CompositeAlignmentDerivativesExtractor::extractCurrentAlignment( + const align::Alignables &alignables, + const std::vector &alignableDets, + const std::vector &tsos) { // sanity check - if ( alignables.size() != alignableDets.size() ) - { - edm::LogError("CompositeAlignmentDerivativesExtractor") - << "Inconsistent length of arguments: alignables=" << alignables.size() - << ", alignableDets=" << alignableDets.size(); + if (alignables.size() != alignableDets.size()) { + edm::LogError("CompositeAlignmentDerivativesExtractor") + << "Inconsistent length of arguments: alignables=" << alignables.size() + << ", alignableDets=" << alignableDets.size(); return; } - if ( alignables.size() != tsos.size() ) - { - edm::LogError("CompositeAlignmentDerivativesExtractor") - << "Inconsistent length of arguments: alignables=" << alignables.size() - << ", tsos=" << tsos.size(); - return; - } + if (alignables.size() != tsos.size()) { + edm::LogError("CompositeAlignmentDerivativesExtractor") + << "Inconsistent length of arguments: alignables=" << alignables.size() << ", tsos=" << tsos.size(); + return; + } align::Alignables::const_iterator itAlignable = alignables.begin(); - std::vector< AlignableDetOrUnitPtr >::const_iterator itAlignableDet = alignableDets.begin(); - std::vector< TrajectoryStateOnSurface >::const_iterator itTsos = tsos.begin(); + std::vector::const_iterator itAlignableDet = alignableDets.begin(); + std::vector::const_iterator itTsos = tsos.begin(); int nRow = 0; int nCollumn = 0; unsigned int nAlignables = 0; - std::vector< AlgebraicMatrix > subDerivatives; - std::vector< AlgebraicVector > subCorrectionTerm; + std::vector subDerivatives; + std::vector subCorrectionTerm; - - // get the individual derivatives and correction term and determine the dimension - while ( itAlignable != alignables.end() ) - { + // get the individual derivatives and correction term and determine the + // dimension + while (itAlignable != alignables.end()) { // Get the current estimate on the alignment parameters - AlgebraicVector subAlignmentParameters = - ( *itAlignable )->alignmentParameters()->selectedParameters(); + AlgebraicVector subAlignmentParameters = (*itAlignable)->alignmentParameters()->selectedParameters(); - // Get the derivatives or the local coordinates w.r.t. the corresponding alignment parameters + // Get the derivatives or the local coordinates w.r.t. the corresponding + // alignment parameters AlgebraicMatrix subAlignmentDerivatives = - ( *itAlignable )->alignmentParameters()->selectedDerivatives( *itTsos, *itAlignableDet ); + (*itAlignable)->alignmentParameters()->selectedDerivatives(*itTsos, *itAlignableDet); - subDerivatives.push_back( subAlignmentDerivatives.T() ); - subCorrectionTerm.push_back( subAlignmentDerivatives.T()*subAlignmentParameters ); + subDerivatives.push_back(subAlignmentDerivatives.T()); + subCorrectionTerm.push_back(subAlignmentDerivatives.T() * subAlignmentParameters); nRow += 2; // check if it is the first occurrence of this Alignable - if ( count( alignables.begin(), itAlignable, *itAlignable ) == 0 ) - { - // matrix is transposed -> num_row() instead of num_col() + if (count(alignables.begin(), itAlignable, *itAlignable) == 0) { + // matrix is transposed -> num_row() instead of num_col() nCollumn += subAlignmentDerivatives.num_row(); nAlignables++; } @@ -98,40 +89,36 @@ extractCurrentAlignment( const align::Alignables & alignables, } // construct derivatives and correction term with the right dimension - theDerivatives = AlgebraicMatrix( nRow, nCollumn, 0 ); - theCorrectionTerm = AlgebraicVector( nRow, 0 ); + theDerivatives = AlgebraicMatrix(nRow, nCollumn, 0); + theCorrectionTerm = AlgebraicVector(nRow, 0); - if ( alignables.size() == nAlignables ) + if (alignables.size() == nAlignables) // One hit per alignable - extractWithoutMultipleHits( subCorrectionTerm, subDerivatives ); + extractWithoutMultipleHits(subCorrectionTerm, subDerivatives); else // At least one alignable has two hits - extractWithMultipleHits( subCorrectionTerm, subDerivatives, alignables ); + extractWithMultipleHits(subCorrectionTerm, subDerivatives, alignables); return; - } //-------------------------------------------------------------------------------------- -void CompositeAlignmentDerivativesExtractor:: -extractWithoutMultipleHits( const std::vector< AlgebraicVector > & subCorrectionTerm, - const std::vector< AlgebraicMatrix > & subDerivatives ) -{ - std::vector< AlgebraicVector >::const_iterator itSubCorrectionTerm = subCorrectionTerm.begin(); - std::vector< AlgebraicMatrix >::const_iterator itSubDerivatives = subDerivatives.begin(); +void CompositeAlignmentDerivativesExtractor::extractWithoutMultipleHits( + const std::vector &subCorrectionTerm, const std::vector &subDerivatives) { + std::vector::const_iterator itSubCorrectionTerm = subCorrectionTerm.begin(); + std::vector::const_iterator itSubDerivatives = subDerivatives.begin(); int iRow = 1; int iCollumn = 1; // Fill in the individual terms - while ( itSubCorrectionTerm != subCorrectionTerm.end() ) - { - theCorrectionTerm.sub( iRow, *itSubCorrectionTerm ); - theDerivatives.sub( iRow, iCollumn, *itSubDerivatives ); + while (itSubCorrectionTerm != subCorrectionTerm.end()) { + theCorrectionTerm.sub(iRow, *itSubCorrectionTerm); + theDerivatives.sub(iRow, iCollumn, *itSubDerivatives); iRow += 2; - iCollumn += ( *itSubDerivatives ).num_col(); + iCollumn += (*itSubDerivatives).num_col(); ++itSubCorrectionTerm; ++itSubDerivatives; @@ -142,14 +129,12 @@ extractWithoutMultipleHits( const std::vector< AlgebraicVector > & subCorrection //-------------------------------------------------------------------------------------- -void CompositeAlignmentDerivativesExtractor:: -extractWithMultipleHits(const std::vector& subCorrectionTerm, - const std::vector& subDerivatives, - const align::Alignables& alignables) -{ - - std::vector< AlgebraicVector >::const_iterator itSubCorrectionTerm = subCorrectionTerm.begin(); - std::vector< AlgebraicMatrix >::const_iterator itSubDerivatives = subDerivatives.begin(); +void CompositeAlignmentDerivativesExtractor::extractWithMultipleHits( + const std::vector &subCorrectionTerm, + const std::vector &subDerivatives, + const align::Alignables &alignables) { + std::vector::const_iterator itSubCorrectionTerm = subCorrectionTerm.begin(); + std::vector::const_iterator itSubDerivatives = subDerivatives.begin(); align::Alignables::const_iterator itAlignables = alignables.begin(); align::Alignables::const_iterator itPosition; align::Alignables::const_iterator itLastPosition; @@ -157,26 +142,24 @@ extractWithMultipleHits(const std::vector& subCorrectionTerm, int iRow = 1; // Fill in the individual terms - while ( itAlignables != alignables.end() ) - { - theCorrectionTerm.sub( iRow, *itSubCorrectionTerm ); + while (itAlignables != alignables.end()) { + theCorrectionTerm.sub(iRow, *itSubCorrectionTerm); int iCollumn = 1; int iAlignable = 0; - itLastPosition = find( alignables.begin(), itAlignables, *itAlignables ); + itLastPosition = find(alignables.begin(), itAlignables, *itAlignables); - for ( itPosition = alignables.begin(); itPosition != itLastPosition; ++itPosition ) - { - if ( count( alignables.begin(), itPosition, *itPosition ) == 0 ) - iCollumn += subDerivatives[iAlignable].num_col(); - iAlignable++; - } + for (itPosition = alignables.begin(); itPosition != itLastPosition; ++itPosition) { + if (count(alignables.begin(), itPosition, *itPosition) == 0) + iCollumn += subDerivatives[iAlignable].num_col(); + iAlignable++; + } - theDerivatives.sub( iRow, iCollumn, *itSubDerivatives ); + theDerivatives.sub(iRow, iCollumn, *itSubDerivatives); iRow += 2; - + ++itAlignables; ++itSubCorrectionTerm; ++itSubDerivatives; @@ -184,4 +167,3 @@ extractWithMultipleHits(const std::vector& subCorrectionTerm, return; } - diff --git a/Alignment/CommonAlignmentParametrization/src/CompositeAlignmentParameters.cc b/Alignment/CommonAlignmentParametrization/src/CompositeAlignmentParameters.cc index 7a5836450d8f9..a68a5eced429b 100644 --- a/Alignment/CommonAlignmentParametrization/src/CompositeAlignmentParameters.cc +++ b/Alignment/CommonAlignmentParametrization/src/CompositeAlignmentParameters.cc @@ -13,109 +13,86 @@ #include "Alignment/CommonAlignment/interface/AlignmentParameters.h" - //__________________________________________________________________________________________________ -CompositeAlignmentParameters:: -CompositeAlignmentParameters(const AlgebraicVector& par, const AlgebraicSymMatrix& cov, - const Components& comp) : - theData(DataContainer(new AlignmentParametersData(par, cov))), - theComponents(comp) -{} - +CompositeAlignmentParameters::CompositeAlignmentParameters(const AlgebraicVector &par, + const AlgebraicSymMatrix &cov, + const Components &comp) + : theData(DataContainer(new AlignmentParametersData(par, cov))), theComponents(comp) {} //__________________________________________________________________________________________________ -CompositeAlignmentParameters:: -CompositeAlignmentParameters(const AlgebraicVector& par, const AlgebraicSymMatrix& cov, - const Components& comp, const AlignableDetToAlignableMap& alimap, - const Aliposmap& aliposmap, const Alilenmap& alilenmap) : - theData(DataContainer(new AlignmentParametersData(par, cov))), - theComponents(comp) , - theAlignableDetToAlignableMap(alimap), - theAliposmap(aliposmap), - theAlilenmap(alilenmap) -{} - +CompositeAlignmentParameters::CompositeAlignmentParameters(const AlgebraicVector &par, + const AlgebraicSymMatrix &cov, + const Components &comp, + const AlignableDetToAlignableMap &alimap, + const Aliposmap &aliposmap, + const Alilenmap &alilenmap) + : theData(DataContainer(new AlignmentParametersData(par, cov))), + theComponents(comp), + theAlignableDetToAlignableMap(alimap), + theAliposmap(aliposmap), + theAlilenmap(alilenmap) {} //__________________________________________________________________________________________________ -CompositeAlignmentParameters:: -CompositeAlignmentParameters(const DataContainer& data, - const Components& comp, const AlignableDetToAlignableMap& alimap, - const Aliposmap& aliposmap, const Alilenmap& alilenmap) : - theData(data), - theComponents(comp) , - theAlignableDetToAlignableMap(alimap), - theAliposmap(aliposmap), - theAlilenmap(alilenmap) -{} - +CompositeAlignmentParameters::CompositeAlignmentParameters(const DataContainer &data, + const Components &comp, + const AlignableDetToAlignableMap &alimap, + const Aliposmap &aliposmap, + const Alilenmap &alilenmap) + : theData(data), + theComponents(comp), + theAlignableDetToAlignableMap(alimap), + theAliposmap(aliposmap), + theAlilenmap(alilenmap) {} //__________________________________________________________________________________________________ -CompositeAlignmentParameters::~CompositeAlignmentParameters() -{} - +CompositeAlignmentParameters::~CompositeAlignmentParameters() {} //__________________________________________________________________________________________________ -CompositeAlignmentParameters* -CompositeAlignmentParameters::clone( const AlgebraicVector& par, - const AlgebraicSymMatrix& cov) const -{ - CompositeAlignmentParameters* cap = - new CompositeAlignmentParameters(par,cov,components()); +CompositeAlignmentParameters *CompositeAlignmentParameters::clone(const AlgebraicVector &par, + const AlgebraicSymMatrix &cov) const { + CompositeAlignmentParameters *cap = new CompositeAlignmentParameters(par, cov, components()); return cap; } //__________________________________________________________________________________________________ -CompositeAlignmentParameters* -CompositeAlignmentParameters::clone( const AlgebraicVector& par, - const AlgebraicSymMatrix& cov, - const AlignableDetToAlignableMap& alimap, - const Aliposmap& aliposmap, - const Alilenmap& alilenmap ) const -{ - CompositeAlignmentParameters* cap = - new CompositeAlignmentParameters(par,cov,components(),alimap,aliposmap,alilenmap); +CompositeAlignmentParameters *CompositeAlignmentParameters::clone(const AlgebraicVector &par, + const AlgebraicSymMatrix &cov, + const AlignableDetToAlignableMap &alimap, + const Aliposmap &aliposmap, + const Alilenmap &alilenmap) const { + CompositeAlignmentParameters *cap = + new CompositeAlignmentParameters(par, cov, components(), alimap, aliposmap, alilenmap); return cap; } //__________________________________________________________________________________________________ -CompositeAlignmentParameters::Components -CompositeAlignmentParameters::components() const -{ - return theComponents; -} - +CompositeAlignmentParameters::Components CompositeAlignmentParameters::components() const { return theComponents; } //__________________________________________________________________________________________________ // full derivatives for a composed object -AlgebraicMatrix -CompositeAlignmentParameters::derivatives( const std::vector& tsosvec, - const std::vector& alidetvec ) const -{ +AlgebraicMatrix CompositeAlignmentParameters::derivatives(const std::vector &tsosvec, + const std::vector &alidetvec) const { std::vector detOrUnits; this->convert(alidetvec, detOrUnits); return this->derivatives(tsosvec, detOrUnits); } -AlgebraicMatrix -CompositeAlignmentParameters::derivatives( const std::vector& tsosvec, - const std::vector& alidetvec ) const -{ +AlgebraicMatrix CompositeAlignmentParameters::derivatives(const std::vector &tsosvec, + const std::vector &alidetvec) const { align::Alignables alivec; - for (std::vector::const_iterator it=alidetvec.begin(); it!=alidetvec.end(); ++it) + for (std::vector::const_iterator it = alidetvec.begin(); it != alidetvec.end(); ++it) alivec.push_back(alignableFromAlignableDet(*it)); - - CompositeAlignmentDerivativesExtractor extractor(alivec,alidetvec,tsosvec); + + CompositeAlignmentDerivativesExtractor extractor(alivec, alidetvec, tsosvec); return extractor.derivatives(); } //__________________________________________________________________________________________________ -AlgebraicVector -CompositeAlignmentParameters::correctionTerm( const std::vector& tsosvec, - const std::vector& alidetvec) const -{ +AlgebraicVector CompositeAlignmentParameters::correctionTerm(const std::vector &tsosvec, + const std::vector &alidetvec) const { std::vector detOrUnits; this->convert(alidetvec, detOrUnits); @@ -123,157 +100,122 @@ CompositeAlignmentParameters::correctionTerm( const std::vector& tsosvec, - const std::vector& alidetvec) const -{ +AlgebraicVector CompositeAlignmentParameters::correctionTerm( + const std::vector &tsosvec, const std::vector &alidetvec) const { align::Alignables alivec; - for (std::vector::const_iterator it=alidetvec.begin(); it!=alidetvec.end(); ++it ) + for (std::vector::const_iterator it = alidetvec.begin(); it != alidetvec.end(); ++it) alivec.push_back(alignableFromAlignableDet(*it)); - - CompositeAlignmentDerivativesExtractor extractor(alivec,alidetvec,tsosvec); + + CompositeAlignmentDerivativesExtractor extractor(alivec, alidetvec, tsosvec); return extractor.correctionTerm(); } - -//__________________________________________________________________________________________________ + +//__________________________________________________________________________________________________ // assume all are selected -AlgebraicMatrix -CompositeAlignmentParameters::selectedDerivatives( const std::vector& tsosvec, - const std::vector& alidetvec) const -{ - return derivatives(tsosvec,alidetvec); +AlgebraicMatrix CompositeAlignmentParameters::selectedDerivatives(const std::vector &tsosvec, + const std::vector &alidetvec) const { + return derivatives(tsosvec, alidetvec); } -//__________________________________________________________________________________________________ +//__________________________________________________________________________________________________ // assume all are selected -AlgebraicMatrix -CompositeAlignmentParameters::selectedDerivatives( const std::vector& tsosvec, - const std::vector& alidetvec) const -{ - return derivatives(tsosvec,alidetvec); +AlgebraicMatrix CompositeAlignmentParameters::selectedDerivatives( + const std::vector &tsosvec, const std::vector &alidetvec) const { + return derivatives(tsosvec, alidetvec); } -//__________________________________________________________________________________________________ +//__________________________________________________________________________________________________ // only one (tsos,AlignableDet) as argument [for compatibility with base class] -AlgebraicMatrix -CompositeAlignmentParameters::derivatives( const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &alidet) const -{ +AlgebraicMatrix CompositeAlignmentParameters::derivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alidet) const { std::vector tsosvec; std::vector alidetvec; tsosvec.push_back(tsos); alidetvec.push_back(alidet); - return derivatives(tsosvec,alidetvec); + return derivatives(tsosvec, alidetvec); } - -//__________________________________________________________________________________________________ + +//__________________________________________________________________________________________________ // assume all are selected -AlgebraicMatrix -CompositeAlignmentParameters::selectedDerivatives( const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &alidet ) const -{ - return derivatives(tsos,alidet); +AlgebraicMatrix CompositeAlignmentParameters::selectedDerivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alidet) const { + return derivatives(tsos, alidet); } - // Derivatives ---------------------------------------------------------------- // legacy methods // full derivatives for a composed object -AlgebraicMatrix -CompositeAlignmentParameters::derivativesLegacy( const std::vector &tsosvec, - const std::vector& alidetvec ) const -{ +AlgebraicMatrix CompositeAlignmentParameters::derivativesLegacy(const std::vector &tsosvec, + const std::vector &alidetvec) const { // sanity check: length of parameter argument vectors must be equal - if (alidetvec.size() != tsosvec.size()) - { + if (alidetvec.size() != tsosvec.size()) { edm::LogError("BadArgument") << " Inconsistent length of argument vectors! "; - AlgebraicMatrix selderiv(1,0); + AlgebraicMatrix selderiv(1, 0); return selderiv; } std::vector vecderiv; - int nparam=0; - - std::vector::const_iterator itsos=tsosvec.begin(); - for( std::vector::const_iterator it=alidetvec.begin(); - it!=alidetvec.end(); ++it, ++itsos ) - { - AlignableDet* ad = (*it); - Alignable* ali = alignableFromAlignableDet(ad); - AlignmentParameters* ap = ali->alignmentParameters(); - AlgebraicMatrix thisselderiv = ap->selectedDerivatives(*itsos,ad); + int nparam = 0; + + std::vector::const_iterator itsos = tsosvec.begin(); + for (std::vector::const_iterator it = alidetvec.begin(); it != alidetvec.end(); ++it, ++itsos) { + AlignableDet *ad = (*it); + Alignable *ali = alignableFromAlignableDet(ad); + AlignmentParameters *ap = ali->alignmentParameters(); + AlgebraicMatrix thisselderiv = ap->selectedDerivatives(*itsos, ad); vecderiv.push_back(thisselderiv); nparam += thisselderiv.num_row(); } - int ipos=1; - AlgebraicMatrix selderiv(nparam,2); - for ( std::vector::const_iterator imat=vecderiv.begin(); - imat!=vecderiv.end(); ++imat ) - { - AlgebraicMatrix thisselderiv=(*imat); - int npar=thisselderiv.num_row(); - selderiv.sub(ipos,1,thisselderiv); + int ipos = 1; + AlgebraicMatrix selderiv(nparam, 2); + for (std::vector::const_iterator imat = vecderiv.begin(); imat != vecderiv.end(); ++imat) { + AlgebraicMatrix thisselderiv = (*imat); + int npar = thisselderiv.num_row(); + selderiv.sub(ipos, 1, thisselderiv); ipos += npar; } return selderiv; } - //__________________________________________________________________________________________________ // assume all are selected -AlgebraicMatrix -CompositeAlignmentParameters::selectedDerivativesLegacy( const std::vector &tsosvec, - const std::vector& alidetvec ) const -{ - return derivativesLegacy(tsosvec,alidetvec); +AlgebraicMatrix CompositeAlignmentParameters::selectedDerivativesLegacy( + const std::vector &tsosvec, const std::vector &alidetvec) const { + return derivativesLegacy(tsosvec, alidetvec); } - //__________________________________________________________________________________________________ // only one (tsos,AlignableDet) as argument [for compatibility with base class] -AlgebraicMatrix -CompositeAlignmentParameters::derivativesLegacy( const TrajectoryStateOnSurface& tsos, - AlignableDet* alidet ) const -{ +AlgebraicMatrix CompositeAlignmentParameters::derivativesLegacy(const TrajectoryStateOnSurface &tsos, + AlignableDet *alidet) const { std::vector tsosvec; - std::vector alidetvec; + std::vector alidetvec; tsosvec.push_back(tsos); alidetvec.push_back(alidet); - return derivativesLegacy(tsosvec,alidetvec); - + return derivativesLegacy(tsosvec, alidetvec); } - //__________________________________________________________________________________________________ // assume all are selected -AlgebraicMatrix -CompositeAlignmentParameters::selectedDerivativesLegacy( const TrajectoryStateOnSurface& tsos, - AlignableDet* alidet ) const -{ - return derivativesLegacy(tsos,alidet); +AlgebraicMatrix CompositeAlignmentParameters::selectedDerivativesLegacy(const TrajectoryStateOnSurface &tsos, + AlignableDet *alidet) const { + return derivativesLegacy(tsos, alidet); } - //__________________________________________________________________________________________________ // finds Alignable corresponding to AlignableDet -Alignable* -CompositeAlignmentParameters::alignableFromAlignableDet(const AlignableDetOrUnitPtr& adet) const -{ - - AlignableDetToAlignableMap::const_iterator iali = - theAlignableDetToAlignableMap.find(adet); - if ( iali!=theAlignableDetToAlignableMap.end() ) return (*iali).second; - else return nullptr; - +Alignable *CompositeAlignmentParameters::alignableFromAlignableDet(const AlignableDetOrUnitPtr &adet) const { + AlignableDetToAlignableMap::const_iterator iali = theAlignableDetToAlignableMap.find(adet); + if (iali != theAlignableDetToAlignableMap.end()) + return (*iali).second; + else + return nullptr; } - //__________________________________________________________________________________________________ -AlgebraicVector -CompositeAlignmentParameters::parameterSubset( const align::Alignables& vec ) const -{ - const auto& sel = extractAlignables(vec); +AlgebraicVector CompositeAlignmentParameters::parameterSubset(const align::Alignables &vec) const { + const auto &sel = extractAlignables(vec); const unsigned int nali = sel.size(); int ndim = 0; @@ -281,23 +223,23 @@ CompositeAlignmentParameters::parameterSubset( const align::Alignables& vec ) co std::vector posvec; std::vector lenvec; - posvec.reserve( nali ); - lenvec.reserve( nali ); + posvec.reserve(nali); + lenvec.reserve(nali); // iterate over input vector of alignables to determine size of result vector - if ( !extractPositionAndLength( sel, posvec, lenvec, ndim ) ) return AlgebraicVector(); + if (!extractPositionAndLength(sel, posvec, lenvec, ndim)) + return AlgebraicVector(); // OK, let's do the real work now - AlgebraicVector result( ndim ); + AlgebraicVector result(ndim); int resi = 0; - for ( unsigned int iali = 0; iali < nali; ++iali ) - { + for (unsigned int iali = 0; iali < nali; ++iali) { int posi = posvec[iali]; int leni = lenvec[iali]; - for ( int ir = 0; ir < leni; ++ir ) - result[resi+ir] = theData->parameters()[posi-1+ir]; + for (int ir = 0; ir < leni; ++ir) + result[resi + ir] = theData->parameters()[posi - 1 + ir]; resi += leni; } @@ -305,13 +247,10 @@ CompositeAlignmentParameters::parameterSubset( const align::Alignables& vec ) co return result; } - //__________________________________________________________________________________________________ // extract covariance matrix for a subset of alignables -AlgebraicSymMatrix -CompositeAlignmentParameters::covarianceSubset( const align::Alignables& vec ) const -{ - const auto& sel = extractAlignables(vec); +AlgebraicSymMatrix CompositeAlignmentParameters::covarianceSubset(const align::Alignables &vec) const { + const auto &sel = extractAlignables(vec); const unsigned int nali = sel.size(); int ndim = 0; @@ -319,31 +258,30 @@ CompositeAlignmentParameters::covarianceSubset( const align::Alignables& vec ) c std::vector posvec; std::vector lenvec; - posvec.reserve( nali ); - lenvec.reserve( nali ); + posvec.reserve(nali); + lenvec.reserve(nali); // iterate over input vectors of alignables // to determine dimensions of result matrix - if ( !extractPositionAndLength( sel, posvec, lenvec, ndim ) ) return AlgebraicSymMatrix(); + if (!extractPositionAndLength(sel, posvec, lenvec, ndim)) + return AlgebraicSymMatrix(); // OK, let's do the real work now - AlgebraicSymMatrix result( ndim ); + AlgebraicSymMatrix result(ndim); int resi = 0; - for ( unsigned int iali = 0; iali < nali; ++iali ) - { + for (unsigned int iali = 0; iali < nali; ++iali) { int posi = posvec[iali]; int leni = lenvec[iali]; int resj = 0; - for ( unsigned int jali = 0; jali <= iali; ++jali ) - { + for (unsigned int jali = 0; jali <= iali; ++jali) { int posj = posvec[jali]; int lenj = lenvec[jali]; - for ( int ir = 0; ir < leni; ++ir ) - for ( int ic = 0; ic < lenj; ++ic ) - result[resi+ir][resj+ic] = theData->covariance()[posi-1+ir][posj-1+ic]; + for (int ir = 0; ir < leni; ++ir) + for (int ic = 0; ic < lenj; ++ic) + result[resi + ir][resj + ic] = theData->covariance()[posi - 1 + ir][posj - 1 + ic]; resj += lenj; } @@ -353,53 +291,50 @@ CompositeAlignmentParameters::covarianceSubset( const align::Alignables& vec ) c return result; } - //__________________________________________________________________________________________________ // extract covariance matrix elements between two subsets of alignables -AlgebraicMatrix -CompositeAlignmentParameters::covarianceSubset( const align::Alignables& veci, - const align::Alignables& vecj ) const -{ - const auto& seli = extractAlignables( veci ); - const auto& selj = extractAlignables( vecj ); +AlgebraicMatrix CompositeAlignmentParameters::covarianceSubset(const align::Alignables &veci, + const align::Alignables &vecj) const { + const auto &seli = extractAlignables(veci); + const auto &selj = extractAlignables(vecj); - int ndimi=0; - int ndimj=0; + int ndimi = 0; + int ndimj = 0; std::vector posveci; std::vector lenveci; std::vector posvecj; std::vector lenvecj; - posveci.reserve( seli.size() ); - lenveci.reserve( seli.size() ); - posvecj.reserve( selj.size() ); - lenvecj.reserve( selj.size() ); + posveci.reserve(seli.size()); + lenveci.reserve(seli.size()); + posvecj.reserve(selj.size()); + lenvecj.reserve(selj.size()); // iterate over input vectors of alignables // to determine dimensions of result matrix - if ( !extractPositionAndLength( seli, posveci, lenveci, ndimi ) ) return AlgebraicSymMatrix(); + if (!extractPositionAndLength(seli, posveci, lenveci, ndimi)) + return AlgebraicSymMatrix(); // vector vecj - if ( !extractPositionAndLength( selj, posvecj, lenvecj, ndimj ) ) return AlgebraicSymMatrix(); + if (!extractPositionAndLength(selj, posvecj, lenvecj, ndimj)) + return AlgebraicSymMatrix(); // OK, let's do the real work now - AlgebraicMatrix result( ndimi, ndimj ); + AlgebraicMatrix result(ndimi, ndimj); int resi = 0; - for ( unsigned int iali = 0; iali < seli.size(); ++iali ) - { + for (unsigned int iali = 0; iali < seli.size(); ++iali) { int posi = posveci[iali]; int leni = lenveci[iali]; int resj = 0; - for ( unsigned int jali = 0; jali < selj.size(); ++jali ) - { + for (unsigned int jali = 0; jali < selj.size(); ++jali) { int posj = posvecj[jali]; int lenj = lenvecj[jali]; - for ( int ir = 0; ir < leni; ++ir ) - for ( int ic = 0; ic < lenj; ++ic ) - result[resi+ir][resj+ic] = theData->covariance()[posi-1+ir][posj-1+ic]; + for (int ir = 0; ir < leni; ++ir) + for (int ic = 0; ic < lenj; ++ic) + result[resi + ir][resj + ic] = theData->covariance()[posi - 1 + ir][posj - 1 + ic]; resj += lenj; } @@ -409,66 +344,57 @@ CompositeAlignmentParameters::covarianceSubset( const align::Alignables& veci, return result; } - //__________________________________________________________________________________________________ // Extract position and length of parameters for a subset of Alignables. -bool -CompositeAlignmentParameters::extractPositionAndLength( const align::Alignables& alignables, - std::vector& posvec, - std::vector& lenvec, - int& length ) const -{ +bool CompositeAlignmentParameters::extractPositionAndLength(const align::Alignables &alignables, + std::vector &posvec, + std::vector &lenvec, + int &length) const { length = 0; - for (const auto& it: alignables) { - // check if in components - if ( std::find( theComponents.begin(), theComponents.end(), it ) == theComponents.end() ) - { - edm::LogError( "NotFound" ) << "@SUB=CompositeAlignmentParameters::extractPositionAndLength" - << "Alignable not found in components!"; + for (const auto &it : alignables) { + // check if in components + if (std::find(theComponents.begin(), theComponents.end(), it) == theComponents.end()) { + edm::LogError("NotFound") << "@SUB=CompositeAlignmentParameters::extractPositionAndLength" + << "Alignable not found in components!"; return false; } // get pos/length Aliposmap::const_iterator iposmap = theAliposmap.find(it); Alilenmap::const_iterator ilenmap = theAlilenmap.find(it); - if ( iposmap == theAliposmap.end() || ilenmap == theAlilenmap.end() ) - { - edm::LogError( "NotFound" ) << "@SUB=CompositeAlignmentParameters::extractPositionAndLength" - << "position/length not found for Alignable in maps!"; + if (iposmap == theAliposmap.end() || ilenmap == theAlilenmap.end()) { + edm::LogError("NotFound") << "@SUB=CompositeAlignmentParameters::extractPositionAndLength" + << "position/length not found for Alignable in maps!"; return false; } - posvec.push_back( iposmap->second ); - lenvec.push_back( ilenmap->second ); + posvec.push_back(iposmap->second); + lenvec.push_back(ilenmap->second); length += ilenmap->second; } return true; } - //__________________________________________________________________________________________________ -align::Alignables -CompositeAlignmentParameters::extractAlignables(const align::Alignables& alignables) const -{ +align::Alignables CompositeAlignmentParameters::extractAlignables(const align::Alignables &alignables) const { align::Alignables result; - for (const auto& itA: alignables) { - if (std::find( result.begin(), result.end(), itA ) == result.end()) result.push_back(itA); + for (const auto &itA : alignables) { + if (std::find(result.begin(), result.end(), itA) == result.end()) + result.push_back(itA); } return result; } - //__________________________________________________________________________________________________ -void CompositeAlignmentParameters::convert(const std::vector &input, - std::vector &output) const -{ +void CompositeAlignmentParameters::convert(const std::vector &input, + std::vector &output) const { output.clear(); output.reserve(input.size()); - std::vector::const_iterator it, itEnd; + std::vector::const_iterator it, itEnd; for (it = input.begin(), itEnd = input.end(); it != itEnd; ++it) output.push_back(AlignableDetOrUnitPtr(*it)); } diff --git a/Alignment/CommonAlignmentParametrization/src/FrameToFrameDerivative.cc b/Alignment/CommonAlignmentParametrization/src/FrameToFrameDerivative.cc index 284b21eb50390..f4374a38c4d2d 100644 --- a/Alignment/CommonAlignmentParametrization/src/FrameToFrameDerivative.cc +++ b/Alignment/CommonAlignmentParametrization/src/FrameToFrameDerivative.cc @@ -8,39 +8,31 @@ #include "Alignment/CommonAlignment/interface/Alignable.h" -// already in header: #include "DataFormats/Math/interface/AlgebraicROOTObjects.h" +// already in header: #include +// "DataFormats/Math/interface/AlgebraicROOTObjects.h" #include "DataFormats/CLHEP/interface/Migration.h" //__________________________________________________________________________________________________ -AlgebraicMatrix -FrameToFrameDerivative::frameToFrameDerivative(const Alignable* object, - const Alignable* composedObject) const -{ - - return getDerivative( object->globalRotation(), - composedObject->globalRotation(), - composedObject->globalPosition() - object->globalPosition() ); - +AlgebraicMatrix FrameToFrameDerivative::frameToFrameDerivative(const Alignable *object, + const Alignable *composedObject) const { + return getDerivative(object->globalRotation(), + composedObject->globalRotation(), + composedObject->globalPosition() - object->globalPosition()); } //__________________________________________________________________________________________________ -AlgebraicMatrix66 -FrameToFrameDerivative::getDerivative(const align::RotationType &objectRot, - const align::RotationType &composeRot, - const align::GlobalPoint &objectPos, - const align::GlobalPoint &composePos) const -{ - return asSMatrix<6,6>(this->getDerivative(objectRot, composeRot, composePos - objectPos)); +AlgebraicMatrix66 FrameToFrameDerivative::getDerivative(const align::RotationType &objectRot, + const align::RotationType &composeRot, + const align::GlobalPoint &objectPos, + const align::GlobalPoint &composePos) const { + return asSMatrix<6, 6>(this->getDerivative(objectRot, composeRot, composePos - objectPos)); } //__________________________________________________________________________________________________ -AlgebraicMatrix -FrameToFrameDerivative::getDerivative(const align::RotationType &objectRot, - const align::RotationType &composeRot, - const align::GlobalVector &posVec) const -{ - - AlgebraicMatrix rotDet = transform(objectRot); +AlgebraicMatrix FrameToFrameDerivative::getDerivative(const align::RotationType &objectRot, + const align::RotationType &composeRot, + const align::GlobalVector &posVec) const { + AlgebraicMatrix rotDet = transform(objectRot); AlgebraicMatrix rotCompO = transform(composeRot); AlgebraicVector diffVec(3); @@ -49,32 +41,32 @@ FrameToFrameDerivative::getDerivative(const align::RotationType &objectRot, diffVec(2) = posVec.y(); diffVec(3) = posVec.z(); - AlgebraicMatrix derivative(6,6); + AlgebraicMatrix derivative(6, 6); + + AlgebraicMatrix derivAA(3, 3); + AlgebraicMatrix derivAB(3, 3); + AlgebraicMatrix derivBB(3, 3); - AlgebraicMatrix derivAA(3,3); - AlgebraicMatrix derivAB(3,3); - AlgebraicMatrix derivBB(3,3); - - derivAA = derivativePosPos( rotDet, rotCompO ); - derivAB = derivativePosRot( rotDet, rotCompO, diffVec ); - derivBB = derivativeRotRot( rotDet, rotCompO ); + derivAA = derivativePosPos(rotDet, rotCompO); + derivAB = derivativePosRot(rotDet, rotCompO, diffVec); + derivBB = derivativeRotRot(rotDet, rotCompO); derivative[0][0] = derivAA[0][0]; derivative[0][1] = derivAA[0][1]; derivative[0][2] = derivAA[0][2]; - derivative[0][3] = derivAB[0][0]; - derivative[0][4] = derivAB[0][1]; - derivative[0][5] = derivAB[0][2]; + derivative[0][3] = derivAB[0][0]; + derivative[0][4] = derivAB[0][1]; + derivative[0][5] = derivAB[0][2]; derivative[1][0] = derivAA[1][0]; derivative[1][1] = derivAA[1][1]; derivative[1][2] = derivAA[1][2]; - derivative[1][3] = derivAB[1][0]; - derivative[1][4] = derivAB[1][1]; - derivative[1][5] = derivAB[1][2]; + derivative[1][3] = derivAB[1][0]; + derivative[1][4] = derivAB[1][1]; + derivative[1][5] = derivAB[1][2]; derivative[2][0] = derivAA[2][0]; derivative[2][1] = derivAA[2][1]; derivative[2][2] = derivAA[2][2]; - derivative[2][3] = derivAB[2][0]; + derivative[2][3] = derivAB[2][0]; derivative[2][4] = derivAB[2][1]; derivative[2][5] = derivAB[2][2]; derivative[3][0] = 0; @@ -95,118 +87,102 @@ FrameToFrameDerivative::getDerivative(const align::RotationType &objectRot, derivative[5][3] = derivBB[2][0]; derivative[5][4] = derivBB[2][1]; derivative[5][5] = derivBB[2][2]; - + return derivative; } - //__________________________________________________________________________________________________ -AlgebraicMatrix -FrameToFrameDerivative::derivativePosPos(const AlgebraicMatrix &RotDet, - const AlgebraicMatrix &RotRot) const -{ - +AlgebraicMatrix FrameToFrameDerivative::derivativePosPos(const AlgebraicMatrix &RotDet, + const AlgebraicMatrix &RotRot) const { return RotDet * RotRot.T(); - } - //__________________________________________________________________________________________________ -AlgebraicMatrix -FrameToFrameDerivative::derivativePosRot(const AlgebraicMatrix &RotDet, - const AlgebraicMatrix &RotRot, - const AlgebraicVector &S) const -{ - - AlgebraicVector dEulerA(3); - AlgebraicVector dEulerB(3); - AlgebraicVector dEulerC(3); - AlgebraicMatrix RotDa(3,3); - AlgebraicMatrix RotDb(3,3); - AlgebraicMatrix RotDc(3,3); - - RotDa[1][2] = 1; RotDa[2][1] = -1; - RotDb[0][2] = -1; RotDb[2][0] = 1; // New beta sign - RotDc[0][1] = 1; RotDc[1][0] = -1; - - dEulerA = RotDet*( RotRot.T()*RotDa*RotRot*S ); - dEulerB = RotDet*( RotRot.T()*RotDb*RotRot*S ); - dEulerC = RotDet*( RotRot.T()*RotDc*RotRot*S ); - - AlgebraicMatrix eulerDeriv(3,3); - eulerDeriv[0][0] = dEulerA[0]; - eulerDeriv[1][0] = dEulerA[1]; - eulerDeriv[2][0] = dEulerA[2]; - eulerDeriv[0][1] = dEulerB[0]; - eulerDeriv[1][1] = dEulerB[1]; - eulerDeriv[2][1] = dEulerB[2]; - eulerDeriv[0][2] = dEulerC[0]; - eulerDeriv[1][2] = dEulerC[1]; - eulerDeriv[2][2] = dEulerC[2]; - - return eulerDeriv; - +AlgebraicMatrix FrameToFrameDerivative::derivativePosRot(const AlgebraicMatrix &RotDet, + const AlgebraicMatrix &RotRot, + const AlgebraicVector &S) const { + AlgebraicVector dEulerA(3); + AlgebraicVector dEulerB(3); + AlgebraicVector dEulerC(3); + AlgebraicMatrix RotDa(3, 3); + AlgebraicMatrix RotDb(3, 3); + AlgebraicMatrix RotDc(3, 3); + + RotDa[1][2] = 1; + RotDa[2][1] = -1; + RotDb[0][2] = -1; + RotDb[2][0] = 1; // New beta sign + RotDc[0][1] = 1; + RotDc[1][0] = -1; + + dEulerA = RotDet * (RotRot.T() * RotDa * RotRot * S); + dEulerB = RotDet * (RotRot.T() * RotDb * RotRot * S); + dEulerC = RotDet * (RotRot.T() * RotDc * RotRot * S); + + AlgebraicMatrix eulerDeriv(3, 3); + eulerDeriv[0][0] = dEulerA[0]; + eulerDeriv[1][0] = dEulerA[1]; + eulerDeriv[2][0] = dEulerA[2]; + eulerDeriv[0][1] = dEulerB[0]; + eulerDeriv[1][1] = dEulerB[1]; + eulerDeriv[2][1] = dEulerB[2]; + eulerDeriv[0][2] = dEulerC[0]; + eulerDeriv[1][2] = dEulerC[1]; + eulerDeriv[2][2] = dEulerC[2]; + + return eulerDeriv; } - //__________________________________________________________________________________________________ -AlgebraicMatrix -FrameToFrameDerivative::derivativeRotRot(const AlgebraicMatrix &RotDet, - const AlgebraicMatrix &RotRot) const -{ - - AlgebraicVector dEulerA(3); - AlgebraicVector dEulerB(3); - AlgebraicVector dEulerC(3); - AlgebraicMatrix RotDa(3,3); - AlgebraicMatrix RotDb(3,3); - AlgebraicMatrix RotDc(3,3); - - RotDa[1][2] = 1; RotDa[2][1] = -1; - RotDb[0][2] = -1; RotDb[2][0] = 1; // New beta sign - RotDc[0][1] = 1; RotDc[1][0] = -1; - - dEulerA = linearEulerAngles( RotDet*RotRot.T()*RotDa*RotRot*RotDet.T() ); - dEulerB = linearEulerAngles( RotDet*RotRot.T()*RotDb*RotRot*RotDet.T() ); - dEulerC = linearEulerAngles( RotDet*RotRot.T()*RotDc*RotRot*RotDet.T() ); - - AlgebraicMatrix eulerDeriv(3,3); - - eulerDeriv[0][0] = dEulerA[0]; - eulerDeriv[1][0] = dEulerA[1]; - eulerDeriv[2][0] = dEulerA[2]; - eulerDeriv[0][1] = dEulerB[0]; - eulerDeriv[1][1] = dEulerB[1]; - eulerDeriv[2][1] = dEulerB[2]; - eulerDeriv[0][2] = dEulerC[0]; - eulerDeriv[1][2] = dEulerC[1]; - eulerDeriv[2][2] = dEulerC[2]; - - return eulerDeriv; - +AlgebraicMatrix FrameToFrameDerivative::derivativeRotRot(const AlgebraicMatrix &RotDet, + const AlgebraicMatrix &RotRot) const { + AlgebraicVector dEulerA(3); + AlgebraicVector dEulerB(3); + AlgebraicVector dEulerC(3); + AlgebraicMatrix RotDa(3, 3); + AlgebraicMatrix RotDb(3, 3); + AlgebraicMatrix RotDc(3, 3); + + RotDa[1][2] = 1; + RotDa[2][1] = -1; + RotDb[0][2] = -1; + RotDb[2][0] = 1; // New beta sign + RotDc[0][1] = 1; + RotDc[1][0] = -1; + + dEulerA = linearEulerAngles(RotDet * RotRot.T() * RotDa * RotRot * RotDet.T()); + dEulerB = linearEulerAngles(RotDet * RotRot.T() * RotDb * RotRot * RotDet.T()); + dEulerC = linearEulerAngles(RotDet * RotRot.T() * RotDc * RotRot * RotDet.T()); + + AlgebraicMatrix eulerDeriv(3, 3); + + eulerDeriv[0][0] = dEulerA[0]; + eulerDeriv[1][0] = dEulerA[1]; + eulerDeriv[2][0] = dEulerA[2]; + eulerDeriv[0][1] = dEulerB[0]; + eulerDeriv[1][1] = dEulerB[1]; + eulerDeriv[2][1] = dEulerB[2]; + eulerDeriv[0][2] = dEulerC[0]; + eulerDeriv[1][2] = dEulerC[1]; + eulerDeriv[2][2] = dEulerC[2]; + + return eulerDeriv; } - - //__________________________________________________________________________________________________ -AlgebraicVector -FrameToFrameDerivative::linearEulerAngles(const AlgebraicMatrix &rotDelta ) const -{ - - AlgebraicMatrix eulerAB(3,3); +AlgebraicVector FrameToFrameDerivative::linearEulerAngles(const AlgebraicMatrix &rotDelta) const { + AlgebraicMatrix eulerAB(3, 3); AlgebraicVector aB(3); - eulerAB[0][1] = 1; - eulerAB[1][0] = -1; // New beta sign + eulerAB[0][1] = 1; + eulerAB[1][0] = -1; // New beta sign aB[2] = 1; - AlgebraicMatrix eulerC(3,3); + AlgebraicMatrix eulerC(3, 3); AlgebraicVector C(3); eulerC[2][0] = 1; C[1] = 1; AlgebraicVector eulerAngles(3); - eulerAngles = eulerAB*rotDelta*aB + eulerC*rotDelta*C; + eulerAngles = eulerAB * rotDelta * aB + eulerC * rotDelta * C; return eulerAngles; - } - diff --git a/Alignment/CommonAlignmentParametrization/src/KarimakiAlignmentDerivatives.cc b/Alignment/CommonAlignmentParametrization/src/KarimakiAlignmentDerivatives.cc index 99676d73f809f..ff17cf79e362c 100644 --- a/Alignment/CommonAlignmentParametrization/src/KarimakiAlignmentDerivatives.cc +++ b/Alignment/CommonAlignmentParametrization/src/KarimakiAlignmentDerivatives.cc @@ -8,11 +8,7 @@ #include "Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h" - -AlgebraicMatrix -KarimakiAlignmentDerivatives::operator()( const TrajectoryStateOnSurface &tsos ) const -{ - +AlgebraicMatrix KarimakiAlignmentDerivatives::operator()(const TrajectoryStateOnSurface &tsos) const { // Get track parameters on surface AlgebraicVector5 alivec = tsos.localParameters().mixedFormatVector(); @@ -23,26 +19,25 @@ KarimakiAlignmentDerivatives::operator()( const TrajectoryStateOnSurface &tsos ) // [3] x : local x-coordinate // [4] y : local y-coordinate - double tanpsi = alivec[1]; + double tanpsi = alivec[1]; double tantheta = alivec[2]; - double ux = alivec[3]; - double vx = alivec[4]; - - AlgebraicMatrix aliderivs(6,2); - - aliderivs[0][0]= -1.0; - aliderivs[0][1]= 0.0; - aliderivs[1][0]= 0.0; - aliderivs[1][1]= -1.0; - aliderivs[2][0]= tanpsi; - aliderivs[2][1]= tantheta; - aliderivs[3][0]= vx*tanpsi; - aliderivs[3][1]= vx*tantheta; - aliderivs[4][0]= -ux*tanpsi; // New beta sign convention - aliderivs[4][1]= -ux*tantheta; // New beta sign convention - aliderivs[5][0]= vx; - aliderivs[5][1]= -ux; - - return(aliderivs); - + double ux = alivec[3]; + double vx = alivec[4]; + + AlgebraicMatrix aliderivs(6, 2); + + aliderivs[0][0] = -1.0; + aliderivs[0][1] = 0.0; + aliderivs[1][0] = 0.0; + aliderivs[1][1] = -1.0; + aliderivs[2][0] = tanpsi; + aliderivs[2][1] = tantheta; + aliderivs[3][0] = vx * tanpsi; + aliderivs[3][1] = vx * tantheta; + aliderivs[4][0] = -ux * tanpsi; // New beta sign convention + aliderivs[4][1] = -ux * tantheta; // New beta sign convention + aliderivs[5][0] = vx; + aliderivs[5][1] = -ux; + + return (aliderivs); } diff --git a/Alignment/CommonAlignmentParametrization/src/ParametersToParametersDerivatives.cc b/Alignment/CommonAlignmentParametrization/src/ParametersToParametersDerivatives.cc index e0b125ff68615..6d6a15378fe16 100644 --- a/Alignment/CommonAlignmentParametrization/src/ParametersToParametersDerivatives.cc +++ b/Alignment/CommonAlignmentParametrization/src/ParametersToParametersDerivatives.cc @@ -6,13 +6,13 @@ #include "Alignment/CommonAlignmentParametrization/interface/ParametersToParametersDerivatives.h" -#include "CondFormats/Alignment/interface/Definitions.h" #include "Alignment/CommonAlignment/interface/Alignable.h" #include "Alignment/CommonAlignment/interface/AlignmentParameters.h" -#include "Alignment/CommonAlignmentParametrization/interface/FrameToFrameDerivative.h" #include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" #include "Alignment/CommonAlignmentParametrization/interface/BowedSurfaceAlignmentDerivatives.h" +#include "Alignment/CommonAlignmentParametrization/interface/FrameToFrameDerivative.h" #include "Alignment/CommonAlignmentParametrization/interface/TwoBowedSurfacesAlignmentParameters.h" +#include "CondFormats/Alignment/interface/Definitions.h" #include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" @@ -20,57 +20,53 @@ // #include "DataFormats/Math/interface/AlgebraicROOTObjects.h" //_________________________________________________________________________________________________ -ParametersToParametersDerivatives -::ParametersToParametersDerivatives(const Alignable &component, const Alignable &mother) - : isOK_(component.alignmentParameters() && mother.alignmentParameters()) -{ +ParametersToParametersDerivatives ::ParametersToParametersDerivatives(const Alignable &component, + const Alignable &mother) + : isOK_(component.alignmentParameters() && mother.alignmentParameters()) { if (isOK_) { - isOK_ = this->init(component, component.alignmentParameters()->type(), - mother, mother .alignmentParameters()->type()); + isOK_ = + this->init(component, component.alignmentParameters()->type(), mother, mother.alignmentParameters()->type()); } } //_________________________________________________________________________________________________ -bool ParametersToParametersDerivatives::init(const Alignable &component, int typeComponent, - const Alignable &mother, int typeMother) -{ - using namespace AlignmentParametersFactory; // for kRigidBody etc. - if ((typeMother == kRigidBody || typeMother == kRigidBody4D) && +bool ParametersToParametersDerivatives::init(const Alignable &component, + int typeComponent, + const Alignable &mother, + int typeMother) { + using namespace AlignmentParametersFactory; // for kRigidBody etc. + if ((typeMother == kRigidBody || typeMother == kRigidBody4D) && (typeComponent == kRigidBody || typeComponent == kRigidBody4D)) { return this->initRigidRigid(component, mother); - } else if ((typeMother == kRigidBody || typeMother == kRigidBody4D) && - typeComponent == kBowedSurface) { + } else if ((typeMother == kRigidBody || typeMother == kRigidBody4D) && typeComponent == kBowedSurface) { return this->initBowedRigid(component, mother); - } else if ((typeMother == kRigidBody || typeMother == kRigidBody4D) && - typeComponent == kTwoBowedSurfaces) { + } else if ((typeMother == kRigidBody || typeMother == kRigidBody4D) && typeComponent == kTwoBowedSurfaces) { return this->init2BowedRigid(component, mother); } else { - // missing: mother with bows and component without, i.e. having 'common' bow parameters + // missing: mother with bows and component without, i.e. having 'common' bow + // parameters edm::LogError("Alignment") << "@SUB=ParametersToParametersDerivatives::init" - << "Mother " << parametersTypeName(parametersType(typeMother)) - << ", component " << parametersTypeName(parametersType(typeComponent)) - << ": not supported."; + << "Mother " << parametersTypeName(parametersType(typeMother)) << ", component " + << parametersTypeName(parametersType(typeComponent)) << ": not supported."; return false; } - } //_________________________________________________________________________________________________ -bool ParametersToParametersDerivatives::initRigidRigid(const Alignable &component, - const Alignable &mother) -{ +bool ParametersToParametersDerivatives::initRigidRigid(const Alignable &component, const Alignable &mother) { // See G. Flucke's presentation from 20 Feb 2007 // https://indico.cern.ch/contributionDisplay.py?contribId=15&sessionId=1&confId=10930 // and C. Kleinwort's one from 14 Feb 2013 // https://indico.cern.ch/contributionDisplay.py?contribId=14&sessionId=1&confId=224472 FrameToFrameDerivative f2f; - // frame2frame returns dcomponent/dmother for both being rigid body, so we have to invert - AlgebraicMatrix66 m(asSMatrix<6,6>(f2f.frameToFrameDerivative(&component, &mother))); - - if (m.Invert()) { // now matrix is d(rigid_mother)/d(rigid_component) + // frame2frame returns dcomponent/dmother for both being rigid body, so we + // have to invert + AlgebraicMatrix66 m(asSMatrix<6, 6>(f2f.frameToFrameDerivative(&component, &mother))); + + if (m.Invert()) { // now matrix is d(rigid_mother)/d(rigid_component) // copy to TMatrix - derivatives_.ResizeTo(6,6); + derivatives_.ResizeTo(6, 6); derivatives_.SetMatrixArray(m.begin()); return true; } else { @@ -79,22 +75,21 @@ bool ParametersToParametersDerivatives::initRigidRigid(const Alignable &componen } //_________________________________________________________________________________________________ -bool ParametersToParametersDerivatives::initBowedRigid(const Alignable &component, - const Alignable &mother) -{ +bool ParametersToParametersDerivatives::initBowedRigid(const Alignable &component, const Alignable &mother) { // component is bowed surface, mother rigid body FrameToFrameDerivative f2f; - // frame2frame returns dcomponent/dmother for both being rigid body, so we have to invert - AlgebraicMatrix66 rigM2rigC(asSMatrix<6,6>(f2f.frameToFrameDerivative(&component,&mother))); - if (rigM2rigC.Invert()) { // now matrix is d(rigid_mother)/d(rigid_component) - const double halfWidth = 0.5 * component.surface().width(); + // frame2frame returns dcomponent/dmother for both being rigid body, so we + // have to invert + AlgebraicMatrix66 rigM2rigC(asSMatrix<6, 6>(f2f.frameToFrameDerivative(&component, &mother))); + if (rigM2rigC.Invert()) { // now matrix is d(rigid_mother)/d(rigid_component) + const double halfWidth = 0.5 * component.surface().width(); const double halfLength = 0.5 * component.surface().length(); const AlgebraicMatrix69 m(this->dRigid_dBowed(rigM2rigC, halfWidth, halfLength)); // copy to TMatrix - derivatives_.ResizeTo(6,9); + derivatives_.ResizeTo(6, 9); derivatives_.SetMatrixArray(m.begin()); - + return true; } else { return false; @@ -102,54 +97,51 @@ bool ParametersToParametersDerivatives::initBowedRigid(const Alignable &componen } //_________________________________________________________________________________________________ -bool ParametersToParametersDerivatives::init2BowedRigid(const Alignable &component, - const Alignable &mother) -{ +bool ParametersToParametersDerivatives::init2BowedRigid(const Alignable &component, const Alignable &mother) { // component is two bowed surfaces, mother rigid body - const TwoBowedSurfacesAlignmentParameters *aliPar = - dynamic_cast(component.alignmentParameters()); + const TwoBowedSurfacesAlignmentParameters *aliPar = + dynamic_cast(component.alignmentParameters()); if (!aliPar) { edm::LogError("Alignment") << "@SUB=ParametersToParametersDerivatives::init2BowedRigid" - << "dynamic_cast to TwoBowedSurfacesAlignmentParameters failed."; + << "dynamic_cast to TwoBowedSurfacesAlignmentParameters failed."; return false; } // We treat the two surfaces as independent objects, i.e. // 1) get the global position of each surface, depending on the ySplit value, const double ySplit = aliPar->ySplit(); - const double halfWidth = 0.5 * component.surface().width(); - const double halfLength = 0.5 * component.surface().length(); + const double halfWidth = 0.5 * component.surface().width(); + const double halfLength = 0.5 * component.surface().length(); const double halfLength1 = 0.5 * (halfLength + ySplit); const double halfLength2 = 0.5 * (halfLength - ySplit); - const double yM1 = 0.5 * (ySplit - halfLength); // y_mean of surface 1 - const double yM2 = yM1 + halfLength; // y_mean of surface 2 + const double yM1 = 0.5 * (ySplit - halfLength); // y_mean of surface 1 + const double yM2 = yM1 + halfLength; // y_mean of surface 2 // The sensor positions and orientations could be adjusted using // TwoBowedSurfacesDeformation attached to the component, // but that should be 2nd order effect. - const align::GlobalPoint posSurf1(component.surface().toGlobal(align::LocalPoint(0.,yM1,0.))); - const align::GlobalPoint posSurf2(component.surface().toGlobal(align::LocalPoint(0.,yM2,0.))); + const align::GlobalPoint posSurf1(component.surface().toGlobal(align::LocalPoint(0., yM1, 0.))); + const align::GlobalPoint posSurf2(component.surface().toGlobal(align::LocalPoint(0., yM2, 0.))); // 2) get derivatives for both, // getDerivative(..) returns dcomponent/dmother for both being rigid body FrameToFrameDerivative f2fMaker; - AlgebraicMatrix66 f2fSurf1(f2fMaker.getDerivative(component.globalRotation(), - mother.globalRotation(), - posSurf1, mother.globalPosition())); - AlgebraicMatrix66 f2fSurf2(f2fMaker.getDerivative(component.globalRotation(), - mother.globalRotation(), - posSurf2, mother.globalPosition())); + AlgebraicMatrix66 f2fSurf1( + f2fMaker.getDerivative(component.globalRotation(), mother.globalRotation(), posSurf1, mother.globalPosition())); + AlgebraicMatrix66 f2fSurf2( + f2fMaker.getDerivative(component.globalRotation(), mother.globalRotation(), posSurf2, mother.globalPosition())); // We have to invert matrices to get d(rigid_mother)/d(rigid_component): - if (!f2fSurf1.Invert() || !f2fSurf2.Invert()) return false; // bail out if bad inversion + if (!f2fSurf1.Invert() || !f2fSurf2.Invert()) + return false; // bail out if bad inversion // Now get d(rigid_mother)/d(bowed_component): const AlgebraicMatrix69 derivs1(this->dRigid_dBowed(f2fSurf1, halfWidth, halfLength1)); const AlgebraicMatrix69 derivs2(this->dRigid_dBowed(f2fSurf2, halfWidth, halfLength2)); // 3) fill the common matrix by merging the two. - typedef ROOT::Math::SMatrix > AlgebraicMatrix6_18; + typedef ROOT::Math::SMatrix> AlgebraicMatrix6_18; AlgebraicMatrix6_18 derivs; - derivs.Place_at(derivs1, 0, 0); // left half - derivs.Place_at(derivs2, 0, 9); // right half + derivs.Place_at(derivs1, 0, 0); // left half + derivs.Place_at(derivs2, 0, 9); // right half // copy to TMatrix derivatives_.ResizeTo(6, 18); @@ -159,22 +151,20 @@ bool ParametersToParametersDerivatives::init2BowedRigid(const Alignable &compone } //_________________________________________________________________________________________________ -ParametersToParametersDerivatives::AlgebraicMatrix69 -ParametersToParametersDerivatives::dRigid_dBowed(const AlgebraicMatrix66 &dRigidM2dRigidC, - double halfWidth, double halfLength) -{ +ParametersToParametersDerivatives::AlgebraicMatrix69 ParametersToParametersDerivatives::dRigid_dBowed( + const AlgebraicMatrix66 &dRigidM2dRigidC, double halfWidth, double halfLength) { typedef BowedSurfaceAlignmentDerivatives BowedDerivs; - const double gammaScale = BowedDerivs::gammaScale(2.*halfWidth, 2.*halfLength); + const double gammaScale = BowedDerivs::gammaScale(2. * halfWidth, 2. * halfLength); // 'dRigidM2dRigidC' is dmother/dcomponent for both being rigid body - // final matrix will be dmother/dcomponent for mother as rigid body, component with bows - // 1st index (row) is parameter of the mother (0..5), - // 2nd index (column) that of component (0..8): + // final matrix will be dmother/dcomponent for mother as rigid body, component + // with bows 1st index (row) is parameter of the mother (0..5), 2nd index + // (column) that of component (0..8): AlgebraicMatrix69 derivs; if (0. == gammaScale || 0. == halfWidth || 0. == halfLength) { - isOK_ = false; // bad input - we would have to devide by that in the following! + isOK_ = false; // bad input - we would have to devide by that in the following! edm::LogError("Alignment") << "@SUB=ParametersToParametersDerivatives::dRigid_dBowed" - << "Some zero length as input."; + << "Some zero length as input."; return derivs; } @@ -182,25 +172,28 @@ ParametersToParametersDerivatives::dRigid_dBowed(const AlgebraicMatrix66 &dRigid // loop on 6 rigid body parameters of mother // First copy the common rigid body part, e.g.: // (0,0): du_moth/du_comp, (0,1): dv_moth/du_comp, (1,2): dw_moth/dv_comp - for (unsigned int iCol = 0; iCol < 3; ++iCol) { // 3 movements of component - derivs(iRow, iCol) = dRigidM2dRigidC(iRow, iCol); + for (unsigned int iCol = 0; iCol < 3; ++iCol) { // 3 movements of component + derivs(iRow, iCol) = dRigidM2dRigidC(iRow, iCol); } - // Now we have to take care of order, signs and scales for rotation-like parameters, - // see CMS AN-2011/531: - // slopeX = w10 = -halfWidth * beta - // => dpar_m/dslopeX_comp = dpar_m/d(-hw * beta_comp) = -(dpar_m/dbeta_comp)/hw - derivs(iRow, 3) = -dRigidM2dRigidC(iRow, 4)/halfWidth; + // Now we have to take care of order, signs and scales for rotation-like + // parameters, see CMS AN-2011/531: slopeX = w10 = -halfWidth * beta + // => dpar_m/dslopeX_comp = dpar_m/d(-hw * beta_comp) = + // -(dpar_m/dbeta_comp)/hw + derivs(iRow, 3) = -dRigidM2dRigidC(iRow, 4) / halfWidth; // slopeY = w10 = +halfLength * alpha - // => dpar_m/dslopeY_comp = dpar_m/d(+hl * alpha_comp) = (dpar_m/dalpha_comp)/hl - derivs(iRow, 4) = dRigidM2dRigidC(iRow, 3)/halfLength; + // => dpar_m/dslopeY_comp = dpar_m/d(+hl * alpha_comp) = + // (dpar_m/dalpha_comp)/hl + derivs(iRow, 4) = dRigidM2dRigidC(iRow, 3) / halfLength; // rotZ = gammaScale * gamma - // => dpar_m/drotZ_comp = dpar_m/d(gamma_comp * gscale) = (dpar_m/dgamma)/gscale - derivs(iRow, 5) = dRigidM2dRigidC(iRow, 5)/gammaScale; + // => dpar_m/drotZ_comp = dpar_m/d(gamma_comp * gscale) = + // (dpar_m/dgamma)/gscale + derivs(iRow, 5) = dRigidM2dRigidC(iRow, 5) / gammaScale; - // Finally, sensor internals like their curvatures have no influence on mother: + // Finally, sensor internals like their curvatures have no influence on + // mother: for (unsigned int iCol = 6; iCol < AlgebraicMatrix69::kCols; ++iCol) { - derivs(iRow, iCol) = 0.; // 3 sagittae of component + derivs(iRow, iCol) = 0.; // 3 sagittae of component } } @@ -208,9 +201,7 @@ ParametersToParametersDerivatives::dRigid_dBowed(const AlgebraicMatrix66 &dRigid } //_________________________________________________________________________________________________ -double ParametersToParametersDerivatives::operator() (unsigned int indParMother, - unsigned int indParComp) const -{ +double ParametersToParametersDerivatives::operator()(unsigned int indParMother, unsigned int indParComp) const { // Do range checks? return derivatives_(indParMother, indParComp); -} +} diff --git a/Alignment/CommonAlignmentParametrization/src/RigidBodyAlignmentParameters.cc b/Alignment/CommonAlignmentParametrization/src/RigidBodyAlignmentParameters.cc index fffe5ef0f6255..40af0888ad813 100644 --- a/Alignment/CommonAlignmentParametrization/src/RigidBodyAlignmentParameters.cc +++ b/Alignment/CommonAlignmentParametrization/src/RigidBodyAlignmentParameters.cc @@ -9,112 +9,96 @@ #include "Alignment/CommonAlignment/interface/Alignable.h" #include "Alignment/CommonAlignment/interface/AlignableDetOrUnitPtr.h" +#include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" #include "Alignment/CommonAlignmentParametrization/interface/FrameToFrameDerivative.h" #include "Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h" -#include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" #include "CondFormats/Alignment/interface/Definitions.h" -// This class's header +// This class's header #include "Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters.h" //__________________________________________________________________________________________________ -RigidBodyAlignmentParameters::RigidBodyAlignmentParameters(Alignable* ali, bool calcMis) : - AlignmentParameters(ali, displacementFromAlignable(calcMis ? ali : nullptr), - AlgebraicSymMatrix(N_PARAM, 0)) -{ -} +RigidBodyAlignmentParameters::RigidBodyAlignmentParameters(Alignable *ali, bool calcMis) + : AlignmentParameters(ali, displacementFromAlignable(calcMis ? ali : nullptr), AlgebraicSymMatrix(N_PARAM, 0)) {} //__________________________________________________________________________________________________ -RigidBodyAlignmentParameters::RigidBodyAlignmentParameters(Alignable* alignable, - const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix) : - AlignmentParameters( alignable, parameters, covMatrix ) -{ - +RigidBodyAlignmentParameters::RigidBodyAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) + : AlignmentParameters(alignable, parameters, covMatrix) { if (parameters.num_row() != N_PARAM) { - throw cms::Exception("BadParameters") << "in RigidBodyAlignmentParameters(): " - << parameters.num_row() << " instead of " << N_PARAM - << " parameters."; + throw cms::Exception("BadParameters") + << "in RigidBodyAlignmentParameters(): " << parameters.num_row() << " instead of " << N_PARAM << " parameters."; } } //__________________________________________________________________________________________________ -RigidBodyAlignmentParameters::RigidBodyAlignmentParameters(Alignable* alignable, - const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix, - const std::vector& selection ) : - AlignmentParameters( alignable, parameters, covMatrix, selection ) -{ +RigidBodyAlignmentParameters::RigidBodyAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection) + : AlignmentParameters(alignable, parameters, covMatrix, selection) { if (parameters.num_row() != N_PARAM) { - throw cms::Exception("BadParameters") << "in RigidBodyAlignmentParameters(): " - << parameters.num_row() << " instead of " << N_PARAM - << " parameters."; + throw cms::Exception("BadParameters") + << "in RigidBodyAlignmentParameters(): " << parameters.num_row() << " instead of " << N_PARAM << " parameters."; } } //__________________________________________________________________________________________________ -RigidBodyAlignmentParameters* -RigidBodyAlignmentParameters::clone( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const -{ - RigidBodyAlignmentParameters* rbap = - new RigidBodyAlignmentParameters( alignable(), parameters, covMatrix, selector()); - - if (userVariables()) rbap->setUserVariables(userVariables()->clone()); +RigidBodyAlignmentParameters *RigidBodyAlignmentParameters::clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const { + RigidBodyAlignmentParameters *rbap = new RigidBodyAlignmentParameters(alignable(), parameters, covMatrix, selector()); + + if (userVariables()) + rbap->setUserVariables(userVariables()->clone()); rbap->setValid(isValid()); return rbap; } //__________________________________________________________________________________________________ -RigidBodyAlignmentParameters* -RigidBodyAlignmentParameters::cloneFromSelected( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const -{ - RigidBodyAlignmentParameters* rbap = - new RigidBodyAlignmentParameters(alignable(), expandVector( parameters, selector()), - expandSymMatrix(covMatrix, selector()), selector()); - - if ( userVariables() ) rbap->setUserVariables(userVariables()->clone()); +RigidBodyAlignmentParameters *RigidBodyAlignmentParameters::cloneFromSelected( + const AlgebraicVector ¶meters, const AlgebraicSymMatrix &covMatrix) const { + RigidBodyAlignmentParameters *rbap = new RigidBodyAlignmentParameters( + alignable(), expandVector(parameters, selector()), expandSymMatrix(covMatrix, selector()), selector()); + + if (userVariables()) + rbap->setUserVariables(userVariables()->clone()); rbap->setValid(isValid()); return rbap; } //__________________________________________________________________________________________________ -AlgebraicMatrix -RigidBodyAlignmentParameters::derivatives( const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &alidet ) const -{ - const Alignable *ali = this->alignable(); // Alignable of these parameters +AlgebraicMatrix RigidBodyAlignmentParameters::derivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alidet) const { + const Alignable *ali = this->alignable(); // Alignable of these parameters - if (ali == alidet) { // same alignable => same frame + if (ali == alidet) { // same alignable => same frame return KarimakiAlignmentDerivatives()(tsos); - } else { // different alignable => transform into correct frame + } else { // different alignable => transform into correct frame const AlgebraicMatrix deriv = KarimakiAlignmentDerivatives()(tsos); FrameToFrameDerivative ftfd; return ftfd.frameToFrameDerivative(alidet, ali).T() * deriv; } } - //__________________________________________________________________________________________________ -AlgebraicMatrix -RigidBodyAlignmentParameters::selectedDerivatives( const TrajectoryStateOnSurface& tsos, - const AlignableDetOrUnitPtr &alignableDet ) const -{ - const AlgebraicMatrix dev = this->derivatives( tsos, alignableDet ); +AlgebraicMatrix RigidBodyAlignmentParameters::selectedDerivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alignableDet) const { + const AlgebraicMatrix dev = this->derivatives(tsos, alignableDet); - int ncols = dev.num_col(); - int nrows = dev.num_row(); - int nsel = numSelected(); + int ncols = dev.num_col(); + int nrows = dev.num_row(); + int nsel = numSelected(); - AlgebraicMatrix seldev( nsel, ncols ); + AlgebraicMatrix seldev(nsel, ncols); - int ir2=0; - for ( int irow=0; irowparameters()[i]; + for (int i = 0; i < 3; ++i) + shift[i] = theData->parameters()[i]; return shift; } - //__________________________________________________________________________________________________ -AlgebraicVector RigidBodyAlignmentParameters::rotation(void) const -{ +AlgebraicVector RigidBodyAlignmentParameters::rotation(void) const { AlgebraicVector rot(3); - for (int i=0;i<3;++i) rot[i] = theData->parameters()[i+3]; + for (int i = 0; i < 3; ++i) + rot[i] = theData->parameters()[i + 3]; return rot; } //__________________________________________________________________________________________________ -void RigidBodyAlignmentParameters::apply() -{ +void RigidBodyAlignmentParameters::apply() { Alignable *alignable = this->alignable(); if (!alignable) { - throw cms::Exception("BadParameters") - << "RigidBodyAlignmentParameters::apply: parameters without alignable"; + throw cms::Exception("BadParameters") << "RigidBodyAlignmentParameters::apply: parameters without alignable"; } - + // Translation in local frame - AlgebraicVector shift = this->translation(); // fixme: should be LocalVector + AlgebraicVector shift = this->translation(); // fixme: should be LocalVector // Translation local->global align::LocalVector lv(shift[0], shift[1], shift[2]); - alignable->move( alignable->surface().toGlobal(lv) ); + alignable->move(alignable->surface().toGlobal(lv)); // Rotation in local frame align::EulerAngles angles = this->rotation(); // original code: // alignable->rotateInLocalFrame( align::toMatrix(angles) ); // correct for rounding errors: - align::RotationType rot = alignable->surface().toGlobal( align::toMatrix(angles) ); + align::RotationType rot = alignable->surface().toGlobal(align::toMatrix(angles)); align::rectify(rot); alignable->rotateInGlobalFrame(rot); } //__________________________________________________________________________________________________ -int RigidBodyAlignmentParameters::type() const -{ - return AlignmentParametersFactory::kRigidBody; -} +int RigidBodyAlignmentParameters::type() const { return AlignmentParametersFactory::kRigidBody; } //__________________________________________________________________________________________________ -AlgebraicVector RigidBodyAlignmentParameters::globalParameters(void) const -{ +AlgebraicVector RigidBodyAlignmentParameters::globalParameters(void) const { AlgebraicVector m_GlobalParameters(N_PARAM, 0); - const AlgebraicVector shift = translation(); // fixme: should return LocalVector + const AlgebraicVector shift = translation(); // fixme: should return LocalVector const align::LocalVector lv(shift[0], shift[1], shift[2]); const align::GlobalVector dg = theAlignable->surface().toGlobal(lv); @@ -188,38 +164,31 @@ AlgebraicVector RigidBodyAlignmentParameters::globalParameters(void) const m_GlobalParameters[1] = dg.y(); m_GlobalParameters[2] = dg.z(); - const align::EulerAngles eulerglob = theAlignable->surface().toGlobal( rotation() ); + const align::EulerAngles eulerglob = theAlignable->surface().toGlobal(rotation()); - m_GlobalParameters[3]=eulerglob(1); - m_GlobalParameters[4]=eulerglob(2); - m_GlobalParameters[5]=eulerglob(3); + m_GlobalParameters[3] = eulerglob(1); + m_GlobalParameters[4] = eulerglob(2); + m_GlobalParameters[5] = eulerglob(3); return m_GlobalParameters; } - //__________________________________________________________________________________________________ -void RigidBodyAlignmentParameters::print(void) const -{ - +void RigidBodyAlignmentParameters::print(void) const { std::cout << "Contents of RigidBodyAlignmentParameters:" - << "\nParameters: " << theData->parameters() - << "\nCovariance: " << theData->covariance() << std::endl; + << "\nParameters: " << theData->parameters() << "\nCovariance: " << theData->covariance() << std::endl; } - //__________________________________________________________________________________________________ -AlgebraicVector RigidBodyAlignmentParameters::displacementFromAlignable(const Alignable* ali) -{ +AlgebraicVector RigidBodyAlignmentParameters::displacementFromAlignable(const Alignable *ali) { AlgebraicVector displacement(N_PARAM); if (ali) { - const align::RotationType& dR = ali->rotation(); - - const align::LocalVector shifts( ali->globalRotation() * - ( dR.transposed() * ali->displacement().basicVector() ) ); + const align::RotationType &dR = ali->rotation(); + + const align::LocalVector shifts(ali->globalRotation() * (dR.transposed() * ali->displacement().basicVector())); - const align::EulerAngles angles = align::toAngles( ali->surface().toLocal(dR) ); + const align::EulerAngles angles = align::toAngles(ali->surface().toLocal(dR)); displacement[0] = shifts.x(); displacement[1] = shifts.y(); diff --git a/Alignment/CommonAlignmentParametrization/src/RigidBodyAlignmentParameters4D.cc b/Alignment/CommonAlignmentParametrization/src/RigidBodyAlignmentParameters4D.cc index 95e25dbda8a71..83eda266bafc8 100644 --- a/Alignment/CommonAlignmentParametrization/src/RigidBodyAlignmentParameters4D.cc +++ b/Alignment/CommonAlignmentParametrization/src/RigidBodyAlignmentParameters4D.cc @@ -9,24 +9,22 @@ #include "Alignment/CommonAlignment/interface/Alignable.h" #include "Alignment/CommonAlignment/interface/AlignableDetOrUnitPtr.h" +#include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" #include "Alignment/CommonAlignmentParametrization/interface/FrameToFrameDerivative.h" #include "Alignment/CommonAlignmentParametrization/interface/SegmentAlignmentDerivatives4D.h" -#include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" #include "CondFormats/Alignment/interface/Definitions.h" -// This class's header +// This class's header #include "Alignment/CommonAlignmentParametrization/interface/RigidBodyAlignmentParameters4D.h" //__________________________________________________________________________________________________ -AlgebraicMatrix -RigidBodyAlignmentParameters4D::derivatives( const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &alidet ) const -{ - const Alignable *ali = this->alignable(); // Alignable of these parameters +AlgebraicMatrix RigidBodyAlignmentParameters4D::derivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alidet) const { + const Alignable *ali = this->alignable(); // Alignable of these parameters - if (ali == alidet) { // same alignable => same frame + if (ali == alidet) { // same alignable => same frame return SegmentAlignmentDerivatives4D()(tsos); - } else { // different alignable => transform into correct frame + } else { // different alignable => transform into correct frame const AlgebraicMatrix deriv = SegmentAlignmentDerivatives4D()(tsos); FrameToFrameDerivative ftfd; return ftfd.frameToFrameDerivative(alidet, ali).T() * deriv; @@ -34,39 +32,30 @@ RigidBodyAlignmentParameters4D::derivatives( const TrajectoryStateOnSurface &tso } //__________________________________________________________________________________________________ -RigidBodyAlignmentParameters4D* -RigidBodyAlignmentParameters4D::clone( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const -{ - RigidBodyAlignmentParameters4D* rbap = - new RigidBodyAlignmentParameters4D( alignable(), parameters, covMatrix, selector()); +RigidBodyAlignmentParameters4D *RigidBodyAlignmentParameters4D::clone(const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) const { + RigidBodyAlignmentParameters4D *rbap = + new RigidBodyAlignmentParameters4D(alignable(), parameters, covMatrix, selector()); - if (userVariables()) rbap->setUserVariables(userVariables()->clone()); + if (userVariables()) + rbap->setUserVariables(userVariables()->clone()); rbap->setValid(isValid()); return rbap; } //__________________________________________________________________________________________________ -RigidBodyAlignmentParameters4D* -RigidBodyAlignmentParameters4D::cloneFromSelected( const AlgebraicVector& parameters, - const AlgebraicSymMatrix& covMatrix ) const -{ - RigidBodyAlignmentParameters4D* rbap = - new RigidBodyAlignmentParameters4D(alignable(), expandVector( parameters, selector()), - expandSymMatrix(covMatrix, selector()), selector()); +RigidBodyAlignmentParameters4D *RigidBodyAlignmentParameters4D::cloneFromSelected( + const AlgebraicVector ¶meters, const AlgebraicSymMatrix &covMatrix) const { + RigidBodyAlignmentParameters4D *rbap = new RigidBodyAlignmentParameters4D( + alignable(), expandVector(parameters, selector()), expandSymMatrix(covMatrix, selector()), selector()); - if ( userVariables() ) rbap->setUserVariables(userVariables()->clone()); + if (userVariables()) + rbap->setUserVariables(userVariables()->clone()); rbap->setValid(isValid()); return rbap; } - - //__________________________________________________________________________________________________ -int RigidBodyAlignmentParameters4D::type() const -{ - return AlignmentParametersFactory::kRigidBody4D; -} - +int RigidBodyAlignmentParameters4D::type() const { return AlignmentParametersFactory::kRigidBody4D; } diff --git a/Alignment/CommonAlignmentParametrization/src/SegmentAlignmentDerivatives4D.cc b/Alignment/CommonAlignmentParametrization/src/SegmentAlignmentDerivatives4D.cc index 11dffdabaf89c..6307eaf7eda4e 100644 --- a/Alignment/CommonAlignmentParametrization/src/SegmentAlignmentDerivatives4D.cc +++ b/Alignment/CommonAlignmentParametrization/src/SegmentAlignmentDerivatives4D.cc @@ -8,11 +8,7 @@ #include "Alignment/CommonAlignmentParametrization/interface/SegmentAlignmentDerivatives4D.h" - -AlgebraicMatrix -SegmentAlignmentDerivatives4D::operator()( const TrajectoryStateOnSurface &tsos ) const -{ - +AlgebraicMatrix SegmentAlignmentDerivatives4D::operator()(const TrajectoryStateOnSurface &tsos) const { // Get track parameters on surface AlgebraicVector5 alivec = tsos.localParameters().mixedFormatVector(); @@ -23,44 +19,43 @@ SegmentAlignmentDerivatives4D::operator()( const TrajectoryStateOnSurface &tsos // [3] x : local x-coordinate // [4] y : local y-coordinate - double tanpsi = alivec[1]; + double tanpsi = alivec[1]; double tantheta = alivec[2]; - double ux = alivec[3]; - double vx = alivec[4]; - - AlgebraicMatrix aliderivs(6,4); - - //delta_x - aliderivs[0][0]= -1.0; - aliderivs[0][1]= 0.0; - aliderivs[0][2]= 0.0; - aliderivs[0][3]= 0.0; - //delta_y - aliderivs[1][0]= 0.0; - aliderivs[1][1]= -1.0; - aliderivs[1][2]= 0.0; - aliderivs[1][3]= 0.0; - //delta_z - aliderivs[2][0]= tanpsi; - aliderivs[2][1]= tantheta; - aliderivs[2][2]= tanpsi; - aliderivs[2][3]= tantheta; - //alpha - aliderivs[3][0]= vx*tanpsi; - aliderivs[3][1]= vx*tantheta; - aliderivs[3][2]= 0; - aliderivs[3][3]= 1.0; - //beta - aliderivs[4][0]= -ux*tanpsi; // New beta sign convention - aliderivs[4][1]= -ux*tantheta; // New beta sign convention - aliderivs[4][2]= -1.0; - aliderivs[4][3]= 0.0; - //gamma - aliderivs[5][0]= vx; - aliderivs[5][1]= -ux; - aliderivs[5][2]= tantheta; - aliderivs[5][3]= -tanpsi; - - return(aliderivs); - + double ux = alivec[3]; + double vx = alivec[4]; + + AlgebraicMatrix aliderivs(6, 4); + + // delta_x + aliderivs[0][0] = -1.0; + aliderivs[0][1] = 0.0; + aliderivs[0][2] = 0.0; + aliderivs[0][3] = 0.0; + // delta_y + aliderivs[1][0] = 0.0; + aliderivs[1][1] = -1.0; + aliderivs[1][2] = 0.0; + aliderivs[1][3] = 0.0; + // delta_z + aliderivs[2][0] = tanpsi; + aliderivs[2][1] = tantheta; + aliderivs[2][2] = tanpsi; + aliderivs[2][3] = tantheta; + // alpha + aliderivs[3][0] = vx * tanpsi; + aliderivs[3][1] = vx * tantheta; + aliderivs[3][2] = 0; + aliderivs[3][3] = 1.0; + // beta + aliderivs[4][0] = -ux * tanpsi; // New beta sign convention + aliderivs[4][1] = -ux * tantheta; // New beta sign convention + aliderivs[4][2] = -1.0; + aliderivs[4][3] = 0.0; + // gamma + aliderivs[5][0] = vx; + aliderivs[5][1] = -ux; + aliderivs[5][2] = tantheta; + aliderivs[5][3] = -tanpsi; + + return (aliderivs); } diff --git a/Alignment/CommonAlignmentParametrization/src/TwoBowedSurfacesAlignmentParameters.cc b/Alignment/CommonAlignmentParametrization/src/TwoBowedSurfacesAlignmentParameters.cc index c3ab90d1429ce..6cf88198a959e 100644 --- a/Alignment/CommonAlignmentParametrization/src/TwoBowedSurfacesAlignmentParameters.cc +++ b/Alignment/CommonAlignmentParametrization/src/TwoBowedSurfacesAlignmentParameters.cc @@ -5,99 +5,83 @@ * by : $Author: flucke $ */ -#include "FWCore/Utilities/interface/Exception.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" +#include "FWCore/Utilities/interface/Exception.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "Alignment/CommonAlignment/interface/Alignable.h" #include "Alignment/CommonAlignment/interface/AlignableDetOrUnitPtr.h" -#include "Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h" #include "Alignment/CommonAlignmentParametrization/interface/AlignmentParametersFactory.h" +#include "Alignment/CommonAlignmentParametrization/interface/KarimakiAlignmentDerivatives.h" #include "CondFormats/Alignment/interface/Definitions.h" //#include "DataFormats/Alignment/interface/SurfaceDeformation.h" #include "Geometry/CommonTopologies/interface/TwoBowedSurfacesDeformation.h" -// This class's header +// This class's header #include "Alignment/CommonAlignmentParametrization/interface/TwoBowedSurfacesAlignmentParameters.h" #include #include //_________________________________________________________________________________________________ -TwoBowedSurfacesAlignmentParameters::TwoBowedSurfacesAlignmentParameters(Alignable *ali) : - AlignmentParameters(ali, AlgebraicVector(N_PARAM), AlgebraicSymMatrix(N_PARAM, 0)), - ySplit_(this->ySplitFromAlignable(ali)) -{ -} +TwoBowedSurfacesAlignmentParameters::TwoBowedSurfacesAlignmentParameters(Alignable *ali) + : AlignmentParameters(ali, AlgebraicVector(N_PARAM), AlgebraicSymMatrix(N_PARAM, 0)), + ySplit_(this->ySplitFromAlignable(ali)) {} //_________________________________________________________________________________________________ -TwoBowedSurfacesAlignmentParameters -::TwoBowedSurfacesAlignmentParameters(Alignable *alignable, - const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) : - AlignmentParameters(alignable, parameters, covMatrix), - ySplit_(this->ySplitFromAlignable(alignable)) -{ +TwoBowedSurfacesAlignmentParameters ::TwoBowedSurfacesAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix) + : AlignmentParameters(alignable, parameters, covMatrix), ySplit_(this->ySplitFromAlignable(alignable)) { if (parameters.num_row() != N_PARAM) { - throw cms::Exception("BadParameters") << "in TwoBowedSurfacesAlignmentParameters(): " - << parameters.num_row() << " instead of " << N_PARAM - << " parameters."; + throw cms::Exception("BadParameters") << "in TwoBowedSurfacesAlignmentParameters(): " << parameters.num_row() + << " instead of " << N_PARAM << " parameters."; } } //_________________________________________________________________________________________________ -TwoBowedSurfacesAlignmentParameters -::TwoBowedSurfacesAlignmentParameters(Alignable *alignable, - const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix, - const std::vector &selection) : - AlignmentParameters(alignable, parameters, covMatrix, selection), - ySplit_(this->ySplitFromAlignable(alignable)) -{ +TwoBowedSurfacesAlignmentParameters ::TwoBowedSurfacesAlignmentParameters(Alignable *alignable, + const AlgebraicVector ¶meters, + const AlgebraicSymMatrix &covMatrix, + const std::vector &selection) + : AlignmentParameters(alignable, parameters, covMatrix, selection), ySplit_(this->ySplitFromAlignable(alignable)) { if (parameters.num_row() != N_PARAM) { - throw cms::Exception("BadParameters") << "in TwoBowedSurfacesAlignmentParameters(): " - << parameters.num_row() << " instead of " << N_PARAM - << " parameters."; + throw cms::Exception("BadParameters") << "in TwoBowedSurfacesAlignmentParameters(): " << parameters.num_row() + << " instead of " << N_PARAM << " parameters."; } } //_________________________________________________________________________________________________ -TwoBowedSurfacesAlignmentParameters* -TwoBowedSurfacesAlignmentParameters::clone(const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) const -{ - TwoBowedSurfacesAlignmentParameters* rbap = - new TwoBowedSurfacesAlignmentParameters(this->alignable(), parameters, covMatrix, selector()); +TwoBowedSurfacesAlignmentParameters *TwoBowedSurfacesAlignmentParameters::clone( + const AlgebraicVector ¶meters, const AlgebraicSymMatrix &covMatrix) const { + TwoBowedSurfacesAlignmentParameters *rbap = + new TwoBowedSurfacesAlignmentParameters(this->alignable(), parameters, covMatrix, selector()); - if (this->userVariables()) rbap->setUserVariables(this->userVariables()->clone()); + if (this->userVariables()) + rbap->setUserVariables(this->userVariables()->clone()); rbap->setValid(this->isValid()); return rbap; } //_________________________________________________________________________________________________ -TwoBowedSurfacesAlignmentParameters* -TwoBowedSurfacesAlignmentParameters::cloneFromSelected(const AlgebraicVector ¶meters, - const AlgebraicSymMatrix &covMatrix) const -{ +TwoBowedSurfacesAlignmentParameters *TwoBowedSurfacesAlignmentParameters::cloneFromSelected( + const AlgebraicVector ¶meters, const AlgebraicSymMatrix &covMatrix) const { return this->clone(this->expandVector(parameters, this->selector()), - this->expandSymMatrix(covMatrix, this->selector())); + this->expandSymMatrix(covMatrix, this->selector())); } //_________________________________________________________________________________________________ -AlgebraicMatrix -TwoBowedSurfacesAlignmentParameters::derivatives(const TrajectoryStateOnSurface &tsos, - const AlignableDetOrUnitPtr &alidet) const -{ - const Alignable *ali = this->alignable(); // Alignable of these parameters - AlgebraicMatrix result(N_PARAM, 2); // initialised with zeros +AlgebraicMatrix TwoBowedSurfacesAlignmentParameters::derivatives(const TrajectoryStateOnSurface &tsos, + const AlignableDetOrUnitPtr &alidet) const { + const Alignable *ali = this->alignable(); // Alignable of these parameters + AlgebraicMatrix result(N_PARAM, 2); // initialised with zeros if (ali == alidet) { const AlignableSurface &surf = ali->surface(); - - // matrix of dimension BowedDerivs::N_PARAM x 2 - const AlgebraicMatrix derivs(BowedDerivs()(tsos, surf.width(), surf.length(), - true, ySplit_)); // split at ySplit_! + + // matrix of dimension BowedDerivs::N_PARAM x 2 + const AlgebraicMatrix derivs(BowedDerivs()(tsos, surf.width(), surf.length(), true, ySplit_)); // split at ySplit_! // Parameters belong to surface part with y < ySplit_ or y >= ySplit_? const double localY = tsos.localParameters().mixedFormatVector()[4]; @@ -106,82 +90,83 @@ TwoBowedSurfacesAlignmentParameters::derivatives(const TrajectoryStateOnSurface for (unsigned int i = BowedDerivs::dx; i < BowedDerivs::N_PARAM; ++i) { result[indexOffset + i][0] = derivs[i][0]; result[indexOffset + i][1] = derivs[i][1]; - } + } } else { - // The following is even more difficult for TwoBowedSurfacesAlignmentParameters - // than for BowedSurfaceAlignmentParameters where this text comes from: + // The following is even more difficult for + // TwoBowedSurfacesAlignmentParameters than for + // BowedSurfaceAlignmentParameters where this text comes from: // - // We could give this a meaning by applying frame-to-frame derivatives - // to the rigid body part of the parameters (be careful that alpha ~= dslopeY - // and beta ~= -dslopeX, but with changed scale!) - // and keep the surface structure parameters untouched in local meaning. - // In this way we could do higher level alignment and determine 'average' - // surface structures for the components. - throw cms::Exception("MisMatch") - << "TwoBowedSurfacesAlignmentParameters::derivatives: The hit alignable must match the " - << "aligned one (i.e. bowed surface parameters cannot be used for composed alignables)\n"; + // We could give this a meaning by applying frame-to-frame derivatives + // to the rigid body part of the parameters (be careful that alpha ~= + // dslopeY and beta ~= -dslopeX, but with changed scale!) and keep the + // surface structure parameters untouched in local meaning. In this way we + // could do higher level alignment and determine 'average' surface + // structures for the components. + throw cms::Exception("MisMatch") << "TwoBowedSurfacesAlignmentParameters::derivatives: The hit " + "alignable must match the " + << "aligned one (i.e. bowed surface parameters cannot be used for " + "composed alignables)\n"; } return result; } //_________________________________________________________________________________________________ -void TwoBowedSurfacesAlignmentParameters::apply() -{ +void TwoBowedSurfacesAlignmentParameters::apply() { Alignable *alignable = this->alignable(); if (!alignable) { - throw cms::Exception("BadParameters") - << "TwoBowedSurfacesAlignmentParameters::apply: parameters without alignable"; + throw cms::Exception("BadParameters") << "TwoBowedSurfacesAlignmentParameters::apply: parameters without " + "alignable"; } - + // Some repeatedly needed variables const AlignableSurface &surface = alignable->surface(); - const double halfLength = surface.length() * 0.5; // full module - const double halfLength1 = (halfLength + ySplit_) * 0.5; // low-y surface - const double halfLength2 = (halfLength - ySplit_) * 0.5; // high-y surface + const double halfLength = surface.length() * 0.5; // full module + const double halfLength1 = (halfLength + ySplit_) * 0.5; // low-y surface + const double halfLength2 = (halfLength - ySplit_) * 0.5; // high-y surface // first copy the parameters into separate parts for the two surfaces const AlgebraicVector ¶ms = theData->parameters(); - std::vector rigidBowPar1(BowedDerivs::N_PARAM); // 1st surface (y < ySplit_) - std::vector rigidBowPar2(BowedDerivs::N_PARAM); // 2nd surface (y >= ySplit_) + std::vector rigidBowPar1(BowedDerivs::N_PARAM); // 1st surface (y < ySplit_) + std::vector rigidBowPar2(BowedDerivs::N_PARAM); // 2nd surface (y >= ySplit_) for (unsigned int i = 0; i < BowedDerivs::N_PARAM; ++i) { rigidBowPar1[i] = params[i]; rigidBowPar2[i] = params[i + BowedDerivs::N_PARAM]; } - // Now adjust slopes to angles, note that dslopeX <-> -beta & dslopeY <-> alpha, - // see BowedSurfaceAlignmentParameters::rotation(): FIXME: use atan? - rigidBowPar1[3] = params[dslopeY1] / halfLength1; // alpha1 - rigidBowPar2[3] = params[dslopeY2] / halfLength2; // alpha2 - rigidBowPar1[4] = -params[dslopeX1] / (surface.width() * 0.5); // beta1 - rigidBowPar2[4] = -params[dslopeX2] / (surface.width() * 0.5); // beta2 + // Now adjust slopes to angles, note that dslopeX <-> -beta & dslopeY <-> + // alpha, see BowedSurfaceAlignmentParameters::rotation(): FIXME: use atan? + rigidBowPar1[3] = params[dslopeY1] / halfLength1; // alpha1 + rigidBowPar2[3] = params[dslopeY2] / halfLength2; // alpha2 + rigidBowPar1[4] = -params[dslopeX1] / (surface.width() * 0.5); // beta1 + rigidBowPar2[4] = -params[dslopeX2] / (surface.width() * 0.5); // beta2 // gamma is simply scaled - const double gammaScale1 = BowedDerivs::gammaScale(surface.width(), 2.0*halfLength1); + const double gammaScale1 = BowedDerivs::gammaScale(surface.width(), 2.0 * halfLength1); rigidBowPar1[5] = params[drotZ1] / gammaScale1; -// const double gammaScale2 = std::sqrt(halfLength2 * halfLength2 -// + surface.width() * surface.width()/4.); - const double gammaScale2 = BowedDerivs::gammaScale(surface.width(), 2.0*halfLength2); + // const double gammaScale2 = std::sqrt(halfLength2 * halfLength2 + // + surface.width() * surface.width()/4.); + const double gammaScale2 = BowedDerivs::gammaScale(surface.width(), 2.0 * halfLength2); rigidBowPar2[5] = params[drotZ2] / gammaScale2; // Get rigid body rotations of full module as mean of the two surfaces: - align::EulerAngles angles(3); // to become 'common' rotation in local frame + align::EulerAngles angles(3); // to become 'common' rotation in local frame for (unsigned int i = 0; i < 3; ++i) { - angles[i] = (rigidBowPar1[i+3] + rigidBowPar2[i+3]) * 0.5; + angles[i] = (rigidBowPar1[i + 3] + rigidBowPar2[i + 3]) * 0.5; } // Module rotations are around other axes than the one we determined, // so we have to correct that the surfaces are shifted by the rotation around // the module axis - in linear approximation just an additional shift: - const double yMean1 = -halfLength + halfLength1;// y of alpha1 rotation axis in module frame - const double yMean2 = halfLength - halfLength2;// y of alpha2 rotation axis in module frame - rigidBowPar1[dz1] -= angles[0] * yMean1; // correct w1 for alpha - rigidBowPar2[dz1] -= angles[0] * yMean2; // correct w2 for alpha + const double yMean1 = -halfLength + halfLength1; // y of alpha1 rotation axis in module frame + const double yMean2 = halfLength - halfLength2; // y of alpha2 rotation axis in module frame + rigidBowPar1[dz1] -= angles[0] * yMean1; // correct w1 for alpha + rigidBowPar2[dz1] -= angles[0] * yMean2; // correct w2 for alpha // Nothing for beta1/2 since anyway both around the y-axis of the module. - rigidBowPar1[dx1] += angles[2] * yMean1; // correct x1 for gamma - rigidBowPar2[dx1] += angles[2] * yMean2; // correct x1 for gamma + rigidBowPar1[dx1] += angles[2] * yMean1; // correct x1 for gamma + rigidBowPar2[dx1] += angles[2] * yMean2; // correct x1 for gamma // Get rigid body shifts of full module as mean of the two surfaces: - const align::LocalVector shift((rigidBowPar1[dx1] + rigidBowPar2[dx1]) * 0.5, // dx1! - (rigidBowPar1[dy1] + rigidBowPar2[dy1]) * 0.5, // dy1! - (rigidBowPar1[dz1] + rigidBowPar2[dz1]) * 0.5);// dz1! + const align::LocalVector shift((rigidBowPar1[dx1] + rigidBowPar2[dx1]) * 0.5, // dx1! + (rigidBowPar1[dy1] + rigidBowPar2[dy1]) * 0.5, // dy1! + (rigidBowPar1[dz1] + rigidBowPar2[dz1]) * 0.5); // dz1! // Apply module shift and rotation: alignable->move(surface.toGlobal(shift)); // original code: @@ -192,14 +177,16 @@ void TwoBowedSurfacesAlignmentParameters::apply() alignable->rotateInGlobalFrame(rot); // only update the surface deformations if they were selected for alignment - if (selector()[dsagittaX1] || selector()[dsagittaXY1] || selector()[dsagittaY1] || - selector()[dsagittaX2] || selector()[dsagittaXY2] || selector()[dsagittaY2]) { - // Fill surface structures with mean bows and half differences for all parameters: - std::vector deformations; deformations.reserve(13); + if (selector()[dsagittaX1] || selector()[dsagittaXY1] || selector()[dsagittaY1] || selector()[dsagittaX2] || + selector()[dsagittaXY2] || selector()[dsagittaY2]) { + // Fill surface structures with mean bows and half differences for all + // parameters: + std::vector deformations; + deformations.reserve(13); // first part: average bows - deformations.push_back((params[dsagittaX1 ] + params[dsagittaX2 ]) * 0.5); + deformations.push_back((params[dsagittaX1] + params[dsagittaX2]) * 0.5); deformations.push_back((params[dsagittaXY1] + params[dsagittaXY2]) * 0.5); - deformations.push_back((params[dsagittaY1 ] + params[dsagittaY2 ]) * 0.5); + deformations.push_back((params[dsagittaY1] + params[dsagittaY2]) * 0.5); // second part: half difference of all corrections for (unsigned int i = 0; i < BowedDerivs::N_PARAM; ++i) { // sign means that we have to apply e.g. @@ -210,7 +197,7 @@ void TwoBowedSurfacesAlignmentParameters::apply() deformations.push_back((rigidBowPar1[i] - rigidBowPar2[i]) * 0.5); } // finally: keep track of where we have split the module - deformations.push_back(ySplit_); // index is 12 + deformations.push_back(ySplit_); // index is 12 const TwoBowedSurfacesDeformation deform{deformations}; @@ -222,59 +209,54 @@ void TwoBowedSurfacesAlignmentParameters::apply() } //_________________________________________________________________________________________________ -int TwoBowedSurfacesAlignmentParameters::type() const -{ - return AlignmentParametersFactory::kTwoBowedSurfaces; -} +int TwoBowedSurfacesAlignmentParameters::type() const { return AlignmentParametersFactory::kTwoBowedSurfaces; } //_________________________________________________________________________________________________ -void TwoBowedSurfacesAlignmentParameters::print() const -{ - +void TwoBowedSurfacesAlignmentParameters::print() const { std::cout << "Contents of TwoBowedSurfacesAlignmentParameters:" - << "\nParameters: " << theData->parameters() - << "\nCovariance: " << theData->covariance() << std::endl; + << "\nParameters: " << theData->parameters() << "\nCovariance: " << theData->covariance() << std::endl; } //_________________________________________________________________________________________________ -double TwoBowedSurfacesAlignmentParameters::ySplitFromAlignable(const Alignable *ali) const -{ - if (!ali) return 0.; +double TwoBowedSurfacesAlignmentParameters::ySplitFromAlignable(const Alignable *ali) const { + if (!ali) + return 0.; - const align::PositionType pos(ali->globalPosition()); + const align::PositionType pos(ali->globalPosition()); const double r = pos.perp(); // The returned numbers for TEC are calculated as stated below from // what is found in CMS-NOTE 2003/20. // Note that at that time it was planned to use ST sensors for the outer TEC - // while in the end there are only a few of them in the tracker - the others are HPK. - // No idea whether there are subtle changes in geometry. - // The numbers have been cross checked with y-residuals in data, see + // while in the end there are only a few of them in the tracker - the others + // are HPK. No idea whether there are subtle changes in geometry. The numbers + // have been cross checked with y-residuals in data, see // https://hypernews.cern.ch/HyperNews/CMS/get/recoTracking/1018/1/1/2/1/1/1/2/1.html. - if (r < 58.) { // Pixel, TIB, TID or TEC ring 1-4 + if (r < 58.) { // Pixel, TIB, TID or TEC ring 1-4 edm::LogError("Alignment") << "@SUB=TwoBowedSurfacesAlignmentParameters::ySplitFromAlignable" - << "There are no split modules for radii < 58, but r = " << r; + << "There are no split modules for radii < 58, but r = " << r; return 0.; - } else if (fabs(pos.z()) < 118.) { // TOB + } else if (fabs(pos.z()) < 118.) { // TOB return 0.; - } else if (r > 90.) { // TEC ring 7 + } else if (r > 90.) { // TEC ring 7 // W7a Height active= 106.900mm (Tab. 2) (but 106.926 mm p. 40!?) // W7a R min active = 888.400mm (Paragraph 5.5.7) - // W7a R max active = W7a R min active + W7a Height active = + // W7a R max active = W7a R min active + W7a Height active = // = 888.400mm + 106.900mm = 995.300mm // W7b Height active= 94.900mm (Tab. 2) (but 94.876 mm p. 41!?) // W7b R min active = 998.252mm (Paragraph 5.5.8) // W7b R max active = 998.252mm + 94.900mm = 1093.152mm // mean radius module = 0.5*(1093.152mm + 888.400mm) = 990.776mm // mean radius gap = 0.5*(998.252mm + 995.300mm) = 996.776mm - // ySplit = (mean radius gap - mean radius module) // local y and r have same directions! + // ySplit = (mean radius gap - mean radius module) // local y and r have + // same directions! // = 996.776mm - 990.776mm = 6mm return 0.6; - } else if (r > 75.) { // TEC ring 6 + } else if (r > 75.) { // TEC ring 6 // W6a Height active= 96.100mm (Tab. 2) (but 96.136 mm p. 38!?) // W6a R min active = 727.000mm (Paragraph 5.5.5) - // W6a R max active = W6a R min active + W6a Height active = + // W6a R max active = W6a R min active + W6a Height active = // = 727.000mm + 96.100mm = 823.100mm // W6b Height active= 84.900mm (Tab. 2) (but 84.936 mm p. 39!?) // W6b R min active = 826.060mm (Paragraph 5.5.6) @@ -285,10 +267,10 @@ double TwoBowedSurfacesAlignmentParameters::ySplitFromAlignable(const Alignable // ySplit = -1*(mean radius gap - mean radius module) // = -1*(824.580mm - 818.980mm) = -5.6mm return -0.56; - } else { // TEC ring 5 - smaller radii alreay excluded before + } else { // TEC ring 5 - smaller radii alreay excluded before // W5a Height active= 81.200mm (Tab. 2) (but 81.169 mm p. 36!?) // W5a R min active = 603.200mm (Paragraph 5.5.3) - // W5a R max active = W5a R min active + W5a Height active = + // W5a R max active = W5a R min active + W5a Height active = // = 603.200mm + 81.200mm = 684.400mm // W5b Height active= 63.200mm (Tab. 2) (63.198 mm on p. 37) // W5b R min active = 687.293mm (Abschnitt 5.5.4 der note) diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentCSCBeamHaloSelector.h b/Alignment/CommonAlignmentProducer/interface/AlignmentCSCBeamHaloSelector.h index f22bb1c588534..0b002a29081c4 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentCSCBeamHaloSelector.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentCSCBeamHaloSelector.h @@ -6,28 +6,28 @@ #include "DataFormats/TrackReco/interface/Track.h" namespace edm { - class Event; - class ParameterSet; -} + class Event; + class ParameterSet; +} // namespace edm class TrackingRecHit; class AlignmentCSCBeamHaloSelector { - public: - typedef std::vector Tracks; +public: + typedef std::vector Tracks; - /// constructor - AlignmentCSCBeamHaloSelector(const edm::ParameterSet &iConfig, edm::ConsumesCollector & iC); + /// constructor + AlignmentCSCBeamHaloSelector(const edm::ParameterSet &iConfig, edm::ConsumesCollector &iC); - /// destructor - ~AlignmentCSCBeamHaloSelector(); + /// destructor + ~AlignmentCSCBeamHaloSelector(); - /// select tracks - Tracks select(const Tracks &tracks, const edm::Event &iEvent) const; + /// select tracks + Tracks select(const Tracks &tracks, const edm::Event &iEvent) const; - private: - unsigned int m_minStations; - unsigned int m_minHitsPerStation; +private: + unsigned int m_minStations; + unsigned int m_minHitsPerStation; }; #endif diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentCSCOverlapSelector.h b/Alignment/CommonAlignmentProducer/interface/AlignmentCSCOverlapSelector.h index a5dbd8f4f53ae..1b6365f8f297f 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentCSCOverlapSelector.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentCSCOverlapSelector.h @@ -5,28 +5,28 @@ #include "DataFormats/TrackReco/interface/Track.h" namespace edm { - class Event; - class ParameterSet; -} + class Event; + class ParameterSet; +} // namespace edm class TrackingRecHit; class AlignmentCSCOverlapSelector { - public: - typedef std::vector Tracks; +public: + typedef std::vector Tracks; - /// constructor - AlignmentCSCOverlapSelector(const edm::ParameterSet &iConfig); + /// constructor + AlignmentCSCOverlapSelector(const edm::ParameterSet &iConfig); - /// destructor - ~AlignmentCSCOverlapSelector(); + /// destructor + ~AlignmentCSCOverlapSelector(); - /// select tracks - Tracks select(const Tracks &tracks, const edm::Event &iEvent) const; + /// select tracks + Tracks select(const Tracks &tracks, const edm::Event &iEvent) const; - private: - int m_station; - unsigned int m_minHitsPerChamber; +private: + int m_station; + unsigned int m_minHitsPerChamber; }; #endif diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentCSCTrackSelector.h b/Alignment/CommonAlignmentProducer/interface/AlignmentCSCTrackSelector.h index da9dd8e5f2e50..2ad53a5caf7c3 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentCSCTrackSelector.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentCSCTrackSelector.h @@ -8,19 +8,16 @@ namespace edm { class Event; class ParameterSet; -} +} // namespace edm class TrackingRecHit; -class AlignmentCSCTrackSelector -{ - - public: - - typedef std::vector Tracks; +class AlignmentCSCTrackSelector { +public: + typedef std::vector Tracks; /// constructor - AlignmentCSCTrackSelector(const edm::ParameterSet & cfg); + AlignmentCSCTrackSelector(const edm::ParameterSet& cfg); /// destructor ~AlignmentCSCTrackSelector(); @@ -28,12 +25,9 @@ class AlignmentCSCTrackSelector /// select tracks Tracks select(const Tracks& tracks, const edm::Event& evt) const; - private: - +private: edm::InputTag m_src; int m_stationA, m_stationB, m_minHitsDT, m_minHitsPerStation, m_maxHitsPerStation; - }; #endif - diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentGlobalTrackSelector.h b/Alignment/CommonAlignmentProducer/interface/AlignmentGlobalTrackSelector.h index 617198699835d..a544668e644a1 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentGlobalTrackSelector.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentGlobalTrackSelector.h @@ -11,18 +11,20 @@ //STL #include -namespace reco {class Track;} -namespace edm {class Event; class EventSetup;} - -class AlignmentGlobalTrackSelector -{ - - public: - - typedef std::vector Tracks; +namespace reco { + class Track; +} +namespace edm { + class Event; + class EventSetup; +} // namespace edm + +class AlignmentGlobalTrackSelector { +public: + typedef std::vector Tracks; /// constructor - AlignmentGlobalTrackSelector(const edm::ParameterSet & cfg, edm::ConsumesCollector& iC); + AlignmentGlobalTrackSelector(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); /// destructor ~AlignmentGlobalTrackSelector(); @@ -31,15 +33,14 @@ class AlignmentGlobalTrackSelector Tracks select(const Tracks& tracks, const edm::Event& iEvent, const edm::EventSetup& eSetup); ///returns if any of the Filters is used. bool useThisFilter(); - - private: - + +private: ///returns [tracks] if there are less than theMaxCount Jets with theMinJetPt and an empty set if not - Tracks checkJetCount(const Tracks& cands,const edm::Event& iEvent)const; + Tracks checkJetCount(const Tracks& cands, const edm::Event& iEvent) const; ///returns only isolated tracks in [cands] - Tracks checkIsolation(const Tracks& cands,const edm::Event& iEvent)const; + Tracks checkIsolation(const Tracks& cands, const edm::Event& iEvent) const; ///filter for Tracks that match the Track of a global Muon - Tracks findMuons(const Tracks& tracks,const edm::Event& iEvent)const; + Tracks findMuons(const Tracks& tracks, const edm::Event& iEvent) const; /// private data members edm::ParameterSet theConf; @@ -75,4 +76,3 @@ class AlignmentGlobalTrackSelector }; #endif - diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentMuonSelector.h b/Alignment/CommonAlignmentProducer/interface/AlignmentMuonSelector.h index 41ab55d9a67e9..db3379bebf0b4 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentMuonSelector.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentMuonSelector.h @@ -19,17 +19,16 @@ #include "CommonTools/RecoAlgos/interface/MuonSelector.h" #include -namespace edm { class Event; } +namespace edm { + class Event; +} -class AlignmentMuonSelector -{ - - public: - - typedef std::vector Muons; +class AlignmentMuonSelector { +public: + typedef std::vector Muons; /// constructor - AlignmentMuonSelector(const edm::ParameterSet & cfg); + AlignmentMuonSelector(const edm::ParameterSet& cfg); /// destructor ~AlignmentMuonSelector(); @@ -37,35 +36,30 @@ class AlignmentMuonSelector /// select muons Muons select(const Muons& muons, const edm::Event& evt) const; - private: - +private: /// apply basic cuts on pt,eta,phi,nhit Muons basicCuts(const Muons& muons) const; /// filter the n highest pt muons Muons theNHighestPtMuons(const Muons& muons) const; - + /// filter only those muons giving best mass pair combination Muons theBestMassPairCombinationMuons(const Muons& muons) const; - + /// compare two muons in pt (used by theNHighestPtMuons) struct ComparePt { - bool operator()( const reco::Muon* t1, const reco::Muon* t2 ) const { - return t1->pt()> t2->pt(); - } + bool operator()(const reco::Muon* t1, const reco::Muon* t2) const { return t1->pt() > t2->pt(); } }; ComparePt ptComparator; /// private data members - bool applyBasicCuts,applyNHighestPt,applyMultiplicityFilter,applyMassPairFilter; - int nHighestPt,minMultiplicity; - double pMin,pMax,ptMin,ptMax,etaMin,etaMax,phiMin,phiMax; - double nHitMinSA,nHitMaxSA,chi2nMaxSA; - double nHitMinGB,nHitMaxGB,chi2nMaxGB; - double nHitMinTO,nHitMaxTO,chi2nMaxTO; - double minMassPair,maxMassPair; - + bool applyBasicCuts, applyNHighestPt, applyMultiplicityFilter, applyMassPairFilter; + int nHighestPt, minMultiplicity; + double pMin, pMax, ptMin, ptMax, etaMin, etaMax, phiMin, phiMax; + double nHitMinSA, nHitMaxSA, chi2nMaxSA; + double nHitMinGB, nHitMaxGB, chi2nMaxGB; + double nHitMinTO, nHitMaxTO, chi2nMaxTO; + double minMassPair, maxMassPair; }; #endif - diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h b/Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h index 9758e9fd43393..25e07cc8c30ca 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h @@ -57,7 +57,6 @@ #include "TrackingTools/PatternTools/interface/TrajTrackAssociation.h" - class AlignTransform; class Alignments; class AlignmentErrorsExtended; @@ -67,9 +66,7 @@ struct SurveyErrors; class TrackerTopology; class TrackerDigiGeometryRecord; - -class AlignmentProducerBase -{ +class AlignmentProducerBase { protected: AlignmentProducerBase(const edm::ParameterSet&); @@ -108,15 +105,11 @@ class AlignmentProducerBase /// @alignmentAlgo_ bool finish(); - virtual bool getTrajTrackAssociationCollection(const edm::Event&, - edm::Handle&) = 0; + virtual bool getTrajTrackAssociationCollection(const edm::Event&, edm::Handle&) = 0; virtual bool getBeamSpot(const edm::Event&, edm::Handle&) = 0; - virtual bool getTkFittedLasBeamCollection(const edm::Run&, - edm::Handle&) = 0; - virtual bool getTsosVectorCollection(const edm::Run&, - edm::Handle&) = 0; - virtual bool getAliClusterValueMap(const edm::Event&, - edm::Handle&) = 0; + virtual bool getTkFittedLasBeamCollection(const edm::Run&, edm::Handle&) = 0; + virtual bool getTsosVectorCollection(const edm::Run&, edm::Handle&) = 0; + virtual bool getAliClusterValueMap(const edm::Event&, edm::Handle&) = 0; std::shared_ptr trackerGeometry_; std::shared_ptr muonDTGeometry_; @@ -136,7 +129,6 @@ class AlignmentProducerBase const edm::InputTag clusterValueMapTag_; private: - /// Creates the choosen alignment algorithm void createAlignmentAlgorithm(); @@ -170,8 +162,7 @@ class AlignmentProducerBase void applyMisalignment(); /// Applies misalignment scenario to @alignableTracker_ - void simpleMisalignment(const align::Alignables&, const std::string&, - float, float, bool); + void simpleMisalignment(const align::Alignables&, const std::string&, float, float, bool); /// Applies Alignments, AlignmentErrors and SurfaceDeformations to /// @trackerGeometry_ @@ -179,11 +170,11 @@ class AlignmentProducerBase /// Applies DB constants belonging to (Err)Rcd to Geometry, taking into /// account 'globalPosition' correction. - template + template void applyDB(G*, const edm::EventSetup&, const AlignTransform&) const; /// Applies DB constants for SurfaceDeformations - template + template void applyDB(G*, const edm::EventSetup&) const; /// Reads in survey records @@ -202,19 +193,20 @@ class AlignmentProducerBase /// Writes Alignments and/or AlignmentErrors to DB for record names /// (removes *globalCoordinates before writing if non-null...). /// Takes over ownership of Alignments and AlignmentErrors. - void writeDB(Alignments*, const std::string&, AlignmentErrorsExtended*, - const std::string&, const AlignTransform*, cond::Time_t) const; + void writeDB(Alignments*, + const std::string&, + AlignmentErrorsExtended*, + const std::string&, + const AlignTransform*, + cond::Time_t) const; /// Writes SurfaceDeformations (bows & kinks) to DB for given record name /// Takes over ownership of AlignmentSurfaceDeformations. - void writeDB(AlignmentSurfaceDeformations*, - const std::string&, cond::Time_t) const; + void writeDB(AlignmentSurfaceDeformations*, const std::string&, cond::Time_t) const; - template + template bool hasParameter(const edm::ParameterSet&, const std::string& name); - - //========================== PRIVATE DATA ==================================== //============================================================================ @@ -237,7 +229,6 @@ class AlignmentProducerBase int nevent_{0}; bool runAtPCL_{false}; - /*** Parameters from config-file ***/ edm::ParameterSet config_; @@ -250,7 +241,6 @@ class AlignmentProducerBase const bool useSurvey_; const bool enableAlignableUpdates_; - /*** ESWatcher ***/ edm::ESWatcher watchIdealGeometryRcd_; @@ -261,7 +251,7 @@ class AlignmentProducerBase edm::ESWatcher watchTrackerSurDeRcd_; edm::ESWatcher watchDTAlRcd_; - edm::ESWatcher watchDTAlErrExtRcd_; + edm::ESWatcher watchDTAlErrExtRcd_; edm::ESWatcher watchCSCAlRcd_; edm::ESWatcher watchCSCAlErrExtRcd_; @@ -272,49 +262,39 @@ class AlignmentProducerBase edm::ESWatcher watchCSCSurveyRcd_; edm::ESWatcher watchCSCSurveyErrExtRcd_; - /*** Survey stuff ***/ size_t surveyIndex_{0}; const Alignments* surveyValues_{nullptr}; const SurveyErrors* surveyErrors_{nullptr}; - /*** Status flags ***/ bool isAlgoInitialized_{false}; - bool isDuringLoop_{false}; // -> needed to ensure correct behaviour in - // both, EDLooper and standard framework - // modules + bool isDuringLoop_{false}; // -> needed to ensure correct behaviour in + // both, EDLooper and standard framework + // modules cond::Time_t firstRun_{cond::timeTypeSpecs[cond::runnumber].endValue}; - }; - - -template -void -AlignmentProducerBase::applyDB(G* geometry, const edm::EventSetup& iSetup, - const AlignTransform& globalCoordinates) const -{ +template +void AlignmentProducerBase::applyDB(G* geometry, + const edm::EventSetup& iSetup, + const AlignTransform& globalCoordinates) const { // 'G' is the geometry class for that DB should be applied, // 'Rcd' is the record class for its Alignments // 'ErrRcd' is the record class for its AlignmentErrorsExtended // 'globalCoordinates' are global transformation for this geometry - const Rcd & record = iSetup.get(); + const Rcd& record = iSetup.get(); if (checkDbAlignmentValidity_) { - const edm::ValidityInterval & validity = record.validityInterval(); + const edm::ValidityInterval& validity = record.validityInterval(); const edm::IOVSyncValue first = validity.first(); const edm::IOVSyncValue last = validity.last(); - if (first!=edm::IOVSyncValue::beginOfTime() || - last!=edm::IOVSyncValue::endOfTime()) { + if (first != edm::IOVSyncValue::beginOfTime() || last != edm::IOVSyncValue::endOfTime()) { throw cms::Exception("DatabaseError") - << "@SUB=AlignmentProducerBase::applyDB" - << "\nTrying to apply " - << record.key().name() - << " with multiple IOVs in tag.\n" - << "Validity range is " - << first.eventID().run() << " - " << last.eventID().run(); + << "@SUB=AlignmentProducerBase::applyDB" + << "\nTrying to apply " << record.key().name() << " with multiple IOVs in tag.\n" + << "Validity range is " << first.eventID().run() << " - " << last.eventID().run(); } } @@ -325,32 +305,24 @@ AlignmentProducerBase::applyDB(G* geometry, const edm::EventSetup& iSetup, iSetup.get().get(alignmentErrors); GeometryAligner aligner; - aligner.applyAlignments(geometry, &(*alignments), &(*alignmentErrors), - globalCoordinates); + aligner.applyAlignments(geometry, &(*alignments), &(*alignmentErrors), globalCoordinates); } - -template -void -AlignmentProducerBase::applyDB(G* geometry, const edm::EventSetup& iSetup) const -{ +template +void AlignmentProducerBase::applyDB(G* geometry, const edm::EventSetup& iSetup) const { // 'G' is the geometry class for that DB should be applied, // 'DeformationRcd' is the record class for its surface deformations - const DeformationRcd & record = iSetup.get(); + const DeformationRcd& record = iSetup.get(); if (checkDbAlignmentValidity_) { - const edm::ValidityInterval & validity = record.validityInterval(); + const edm::ValidityInterval& validity = record.validityInterval(); const edm::IOVSyncValue first = validity.first(); const edm::IOVSyncValue last = validity.last(); - if (first!=edm::IOVSyncValue::beginOfTime() || - last!=edm::IOVSyncValue::endOfTime()) { + if (first != edm::IOVSyncValue::beginOfTime() || last != edm::IOVSyncValue::endOfTime()) { throw cms::Exception("DatabaseError") - << "@SUB=AlignmentProducerBase::applyDB" - << "\nTrying to apply " - << record.key().name() - << " with multiple IOVs in tag.\n" - << "Validity range is " - << first.eventID().run() << " - " << last.eventID().run(); + << "@SUB=AlignmentProducerBase::applyDB" + << "\nTrying to apply " << record.key().name() << " with multiple IOVs in tag.\n" + << "Validity range is " << first.eventID().run() << " - " << last.eventID().run(); } } edm::ESHandle surfaceDeformations; @@ -360,5 +332,4 @@ AlignmentProducerBase::applyDB(G* geometry, const edm::EventSetup& iSetup) const aligner.attachSurfaceDeformations(geometry, &(*surfaceDeformations)); } - #endif /* Alignment_CommonAlignmentProducer_AlignmentProducerBase_h */ diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentSeedSelector.h b/Alignment/CommonAlignmentProducer/interface/AlignmentSeedSelector.h index cb2bba5ac5779..0fd51f7f623d9 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentSeedSelector.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentSeedSelector.h @@ -5,17 +5,16 @@ #include "DataFormats/TrajectorySeed/interface/TrajectorySeed.h" #include -namespace edm { class Event; } +namespace edm { + class Event; +} -class AlignmentSeedSelector -{ - - public: - - typedef std::vector Seeds; +class AlignmentSeedSelector { +public: + typedef std::vector Seeds; /// constructor - AlignmentSeedSelector(const edm::ParameterSet & cfg); + AlignmentSeedSelector(const edm::ParameterSet& cfg); /// destructor ~AlignmentSeedSelector(); @@ -23,13 +22,10 @@ class AlignmentSeedSelector /// select tracks Seeds select(const Seeds& seeds, const edm::Event& evt) const; - private: - +private: /// private data members bool applySeedNumber; - int minNSeeds,maxNSeeds; - + int minNSeeds, maxNSeeds; }; #endif - diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentTrackSelector.h b/Alignment/CommonAlignmentProducer/interface/AlignmentTrackSelector.h index 043d8d426c498..1b215eb534cdd 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentTrackSelector.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentTrackSelector.h @@ -14,21 +14,18 @@ namespace edm { class Event; class EventSetup; class ParameterSet; -} +} // namespace edm class TrackingRecHit; class SiStripRecHit1D; class SiStripRecHit2D; -class AlignmentTrackSelector -{ - - public: - - typedef std::vector Tracks; +class AlignmentTrackSelector { +public: + typedef std::vector Tracks; /// constructor - AlignmentTrackSelector(const edm::ParameterSet & cfg, edm::ConsumesCollector& iC); + AlignmentTrackSelector(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); /// destructor ~AlignmentTrackSelector(); @@ -38,18 +35,16 @@ class AlignmentTrackSelector ///returns if any of the Filters is used. bool useThisFilter(); - - private: - +private: /// apply basic cuts on pt,eta,phi,nhit Tracks basicCuts(const Tracks& tracks, const edm::Event& evt, const edm::EventSetup& eSetup) const; /// checking hit requirements beyond simple number of valid hits bool detailedHitsCheck(const reco::Track* track, const edm::Event& evt, const edm::EventSetup& eSetup) const; - bool isHit2D(const TrackingRecHit &hit) const; - /// if valid, check for minimum charge (currently only in strip), if invalid give true + bool isHit2D(const TrackingRecHit& hit) const; + /// if valid, check for minimum charge (currently only in strip), if invalid give true bool isOkCharge(const TrackingRecHit* therechit) const; - bool isOkChargeStripHit(const SiStripRecHit1D &siStripRecHit1D) const; - bool isOkChargeStripHit(const SiStripRecHit2D &siStripRecHit2D) const; + bool isOkChargeStripHit(const SiStripRecHit1D& siStripRecHit1D) const; + bool isOkChargeStripHit(const SiStripRecHit2D& siStripRecHit2D) const; bool isIsolated(const TrackingRecHit* therechit, const edm::Event& evt) const; bool isOkTrkQuality(const reco::Track* track) const; @@ -61,9 +56,7 @@ class AlignmentTrackSelector /// compare two tracks in pt (used by theNHighestPtTracks) struct ComparePt { - bool operator()( const reco::Track* t1, const reco::Track* t2 ) const { - return t1->pt()> t2->pt(); - } + bool operator()(const reco::Track* t1, const reco::Track* t2) const { return t1->pt() > t2->pt(); } }; ComparePt ptComparator; @@ -71,14 +64,14 @@ class AlignmentTrackSelector const int seedOnlyFromAbove_; const bool applyIsolation_, chargeCheck_; const int nHighestPt_, minMultiplicity_, maxMultiplicity_; - const bool multiplicityOnInput_; /// if true, cut min/maxMultiplicity on input instead of on final result - const double ptMin_,ptMax_,pMin_,pMax_,etaMin_,etaMax_,phiMin_,phiMax_; - const double nHitMin_,nHitMax_,chi2nMax_, d0Min_,d0Max_,dzMin_,dzMax_; + const bool multiplicityOnInput_; /// if true, cut min/maxMultiplicity on input instead of on final result + const double ptMin_, ptMax_, pMin_, pMax_, etaMin_, etaMax_, phiMin_, phiMax_; + const double nHitMin_, nHitMax_, chi2nMax_, d0Min_, d0Max_, dzMin_, dzMax_; const int theCharge_; const double minHitChargeStrip_, minHitIsolation_; edm::EDGetTokenT rphirecHitsToken_; edm::EDGetTokenT matchedrecHitsToken_; - const bool countStereoHitAs2D_; // count hits on stereo components of GluedDet for nHitMin2D_? + const bool countStereoHitAs2D_; // count hits on stereo components of GluedDet for nHitMin2D_? const unsigned int nHitMin2D_; const int minHitsinTIB_, minHitsinTOB_, minHitsinTID_, minHitsinTEC_; const int minHitsinBPIX_, minHitsinFPIX_, minHitsinPIX_; @@ -92,7 +85,7 @@ class AlignmentTrackSelector std::vector RorZofLastHitMin_; std::vector RorZofLastHitMax_; - const edm::InputTag clusterValueMapTag_; // ValueMap containing association cluster - flag + const edm::InputTag clusterValueMapTag_; // ValueMap containing association cluster - flag edm::EDGetTokenT clusterValueMapToken_; // ValueMap containing association cluster - flag const int minPrescaledHits_; const bool applyPrescaledHitsFilter_; @@ -105,4 +98,3 @@ class AlignmentTrackSelector }; #endif - diff --git a/Alignment/CommonAlignmentProducer/interface/AlignmentTwoBodyDecayTrackSelector.h b/Alignment/CommonAlignmentProducer/interface/AlignmentTwoBodyDecayTrackSelector.h index 990b626d66730..5473fe4db9c12 100644 --- a/Alignment/CommonAlignmentProducer/interface/AlignmentTwoBodyDecayTrackSelector.h +++ b/Alignment/CommonAlignmentProducer/interface/AlignmentTwoBodyDecayTrackSelector.h @@ -12,16 +12,17 @@ #include #include -namespace edm { class Event; class EventSetup; } +namespace edm { + class Event; + class EventSetup; +} // namespace edm -class AlignmentTwoBodyDecayTrackSelector -{ - public: - - typedef std::vector Tracks; +class AlignmentTwoBodyDecayTrackSelector { +public: + typedef std::vector Tracks; /// constructor - AlignmentTwoBodyDecayTrackSelector(const edm::ParameterSet & cfg, edm::ConsumesCollector& iC); + AlignmentTwoBodyDecayTrackSelector(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); /// destructor ~AlignmentTwoBodyDecayTrackSelector(); @@ -30,17 +31,18 @@ class AlignmentTwoBodyDecayTrackSelector Tracks select(const Tracks& tracks, const edm::Event& iEvent, const edm::EventSetup& iSetup); bool useThisFilter(); - private: + +private: ///checks if the mass of the mother is in the mass region - Tracks checkMass(const Tracks& cands)const; + Tracks checkMass(const Tracks& cands) const; ///checks if the mass of the mother is in the mass region adding missing E_T - Tracks checkMETMass(const Tracks& cands,const edm::Event& iEvent)const; + Tracks checkMETMass(const Tracks& cands, const edm::Event& iEvent) const; ///checks if the mother has charge = [theCharge] - bool checkCharge(const reco::Track* trk1,const reco::Track* trk2 = nullptr)const; + bool checkCharge(const reco::Track* trk1, const reco::Track* trk2 = nullptr) const; ///checks if the [cands] are acoplanar (returns empty set if not) - bool checkAcoplanarity(const reco::Track* trk1,const reco::Track* trk2)const; + bool checkAcoplanarity(const reco::Track* trk1, const reco::Track* trk2) const; ///checks if [cands] contains a acoplanar track w.r.t missing ET (returns empty set if not) - bool checkMETAcoplanarity(const reco::Track* trk,const reco::CaloMET* met)const; + bool checkMETAcoplanarity(const reco::Track* trk, const reco::CaloMET* met) const; /// private data members @@ -55,8 +57,8 @@ class AlignmentTwoBodyDecayTrackSelector double theDaughterMass; unsigned int theCandNumber; bool secThrBool; - double thesecThr ; - //charge filter + double thesecThr; + //charge filter int theCharge; bool theUnsignedSwitch; //missing ET Filter @@ -69,4 +71,3 @@ class AlignmentTwoBodyDecayTrackSelector }; #endif - diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCBeamHaloSelectorModule.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCBeamHaloSelectorModule.cc index 663d12998accf..e0d6620a1fa45 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCBeamHaloSelectorModule.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCBeamHaloSelectorModule.cc @@ -11,37 +11,32 @@ #include "CommonTools/RecoAlgos/interface/TrackSelector.h" struct CSCBeamHaloConfigSelector { - - typedef std::vector container; + typedef std::vector container; typedef container::const_iterator const_iterator; typedef reco::TrackCollection collection; - CSCBeamHaloConfigSelector( const edm::ParameterSet & cfg, edm::ConsumesCollector && iC ) : - CSCBeamHaloConfigSelector(cfg, iC) {} - CSCBeamHaloConfigSelector( const edm::ParameterSet & cfg, edm::ConsumesCollector & iC ) : - theSelector(cfg, iC) {} + CSCBeamHaloConfigSelector(const edm::ParameterSet &cfg, edm::ConsumesCollector &&iC) + : CSCBeamHaloConfigSelector(cfg, iC) {} + CSCBeamHaloConfigSelector(const edm::ParameterSet &cfg, edm::ConsumesCollector &iC) : theSelector(cfg, iC) {} const_iterator begin() const { return selected_.begin(); } const_iterator end() const { return selected_.end(); } size_t size() const { return selected_.size(); } - void select( const edm::Handle & c, const edm::Event & evt, - const edm::EventSetup &/*dummy*/) - { + void select(const edm::Handle &c, const edm::Event &evt, const edm::EventSetup & /*dummy*/) { all_.clear(); selected_.clear(); - for (collection::const_iterator i = c.product()->begin(), iE = c.product()->end(); - i != iE; ++i){ - all_.push_back(& * i ); + for (collection::const_iterator i = c.product()->begin(), iE = c.product()->end(); i != iE; ++i) { + all_.push_back(&*i); } - selected_ = theSelector.select(all_, evt); // might add dummy... + selected_ = theSelector.select(all_, evt); // might add dummy... } private: - container all_,selected_; + container all_, selected_; AlignmentCSCBeamHaloSelector theSelector; }; -typedef ObjectSelectorStream AlignmentCSCBeamHaloSelectorModule; +typedef ObjectSelectorStream AlignmentCSCBeamHaloSelectorModule; -DEFINE_FWK_MODULE( AlignmentCSCBeamHaloSelectorModule ); +DEFINE_FWK_MODULE(AlignmentCSCBeamHaloSelectorModule); diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCOverlapSelectorModule.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCOverlapSelectorModule.cc index d106b9a32a471..f58f48af954e7 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCOverlapSelectorModule.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCOverlapSelectorModule.cc @@ -11,35 +11,30 @@ #include "CommonTools/RecoAlgos/interface/TrackSelector.h" struct CSCOverlapConfigSelector { - - typedef std::vector container; + typedef std::vector container; typedef container::const_iterator const_iterator; typedef reco::TrackCollection collection; - CSCOverlapConfigSelector( const edm::ParameterSet & cfg, edm::ConsumesCollector && iC ) : - theSelector(cfg) {} + CSCOverlapConfigSelector(const edm::ParameterSet &cfg, edm::ConsumesCollector &&iC) : theSelector(cfg) {} const_iterator begin() const { return selected_.begin(); } const_iterator end() const { return selected_.end(); } size_t size() const { return selected_.size(); } - void select( const edm::Handle & c, const edm::Event & evt, - const edm::EventSetup &/*dummy*/) - { + void select(const edm::Handle &c, const edm::Event &evt, const edm::EventSetup & /*dummy*/) { all_.clear(); selected_.clear(); - for (collection::const_iterator i = c.product()->begin(), iE = c.product()->end(); - i != iE; ++i){ - all_.push_back(& * i ); + for (collection::const_iterator i = c.product()->begin(), iE = c.product()->end(); i != iE; ++i) { + all_.push_back(&*i); } - selected_ = theSelector.select(all_, evt); // might add dummy... + selected_ = theSelector.select(all_, evt); // might add dummy... } private: - container all_,selected_; + container all_, selected_; AlignmentCSCOverlapSelector theSelector; }; -typedef ObjectSelectorStream AlignmentCSCOverlapSelectorModule; +typedef ObjectSelectorStream AlignmentCSCOverlapSelectorModule; -DEFINE_FWK_MODULE( AlignmentCSCOverlapSelectorModule ); +DEFINE_FWK_MODULE(AlignmentCSCOverlapSelectorModule); diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCTrackSelectorModule.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCTrackSelectorModule.cc index 8cc3555a59e7d..d03ae59a79453 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCTrackSelectorModule.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentCSCTrackSelectorModule.cc @@ -15,32 +15,30 @@ #include "CommonTools/RecoAlgos/interface/TrackSelector.h" struct CSCTrackConfigSelector { + typedef std::vector container; + typedef container::const_iterator const_iterator; + typedef reco::TrackCollection collection; - typedef std::vector container; - typedef container::const_iterator const_iterator; - typedef reco::TrackCollection collection; + CSCTrackConfigSelector(const edm::ParameterSet &cfg, edm::ConsumesCollector &&iC) : theBaseSelector(cfg) {} - CSCTrackConfigSelector( const edm::ParameterSet & cfg, edm::ConsumesCollector && iC ) : theBaseSelector(cfg) {} + const_iterator begin() const { return theSelectedTracks.begin(); } + const_iterator end() const { return theSelectedTracks.end(); } + size_t size() const { return theSelectedTracks.size(); } - const_iterator begin() const { return theSelectedTracks.begin(); } - const_iterator end() const { return theSelectedTracks.end(); } - size_t size() const { return theSelectedTracks.size(); } + void select(const edm::Handle &c, const edm::Event &evt, const edm::EventSetup & /*dummy*/) { + container all; + for (reco::TrackCollection::const_iterator i = c.product()->begin(); i != c.product()->end(); ++i) { + all.push_back(&*i); + } + theSelectedTracks = theBaseSelector.select(all, evt); // might add dummy + } - void select( const edm::Handle & c, const edm::Event & evt, const edm::EventSetup &/*dummy*/) - { - container all; - for( reco::TrackCollection::const_iterator i=c.product()->begin();i!=c.product()->end();++i){ - all.push_back(& * i ); - } - theSelectedTracks = theBaseSelector.select(all, evt); // might add dummy - } +private: + container theSelectedTracks; - private: - container theSelectedTracks; - - AlignmentCSCTrackSelector theBaseSelector; + AlignmentCSCTrackSelector theBaseSelector; }; -typedef ObjectSelectorStream AlignmentCSCTrackSelectorModule; +typedef ObjectSelectorStream AlignmentCSCTrackSelectorModule; -DEFINE_FWK_MODULE( AlignmentCSCTrackSelectorModule ); +DEFINE_FWK_MODULE(AlignmentCSCTrackSelectorModule); diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentMuonHIPTrajectorySelector.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentMuonHIPTrajectorySelector.cc index 43b783e8e2383..417ed047241a4 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentMuonHIPTrajectorySelector.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentMuonHIPTrajectorySelector.cc @@ -2,7 +2,7 @@ // // Package: AlignmentMuonHIPTrajectorySelector // Class: AlignmentMuonHIPTrajectorySelector -// +// /**\class AlignmentMuonHIPTrajectorySelector AlignmentMuonHIPTrajectorySelector.cc Alignment/CommonAlignmentProducer/plugins/AlignmentMuonHIPTrajectorySelector.cc Description: @@ -17,7 +17,6 @@ // // - // system include files #include #include @@ -53,30 +52,29 @@ // class AlignmentMuonHIPTrajectorySelector : public edm::EDProducer { - public: - explicit AlignmentMuonHIPTrajectorySelector(const edm::ParameterSet&); - ~AlignmentMuonHIPTrajectorySelector() override; - - private: - void produce(edm::Event&, const edm::EventSetup&) override; - - // ---------- member data -------------------------------- - edm::InputTag m_input; - double m_minPt; - double m_maxTrackerForwardRedChi2; - int m_minTrackerDOF; - double m_maxMuonResidual; - - bool m_hists; - TH1F *m_pt, *m_tracker_forwardredchi2, *m_tracker_dof; - TH1F *m_resid_before, *m_resid_after; +public: + explicit AlignmentMuonHIPTrajectorySelector(const edm::ParameterSet&); + ~AlignmentMuonHIPTrajectorySelector() override; + +private: + void produce(edm::Event&, const edm::EventSetup&) override; + + // ---------- member data -------------------------------- + edm::InputTag m_input; + double m_minPt; + double m_maxTrackerForwardRedChi2; + int m_minTrackerDOF; + double m_maxMuonResidual; + + bool m_hists; + TH1F *m_pt, *m_tracker_forwardredchi2, *m_tracker_dof; + TH1F *m_resid_before, *m_resid_after; }; // // constants, enums and typedefs // - // // static data member definitions // @@ -85,125 +83,133 @@ class AlignmentMuonHIPTrajectorySelector : public edm::EDProducer { // constructors and destructor // AlignmentMuonHIPTrajectorySelector::AlignmentMuonHIPTrajectorySelector(const edm::ParameterSet& iConfig) - : m_input(iConfig.getParameter("input")) - , m_minPt(iConfig.getParameter("minPt")) - , m_maxTrackerForwardRedChi2(iConfig.getParameter("maxTrackerForwardRedChi2")) - , m_minTrackerDOF(iConfig.getParameter("minTrackerDOF")) - , m_maxMuonResidual(iConfig.getParameter("maxMuonResidual")) - , m_hists(iConfig.getParameter("hists")) - , m_pt(nullptr), m_tracker_forwardredchi2(nullptr), m_tracker_dof(nullptr) -{ - produces(); - - if (m_hists) { - edm::Service fs; - m_pt = fs->make("pt", "Transverse momentum (GeV)", 100, 0., 100.); - m_tracker_forwardredchi2 = fs->make("trackerForwardRedChi2", "forward-biased reduced chi2 in tracker", 100, 0., 5.); - m_tracker_dof = fs->make("trackerDOF", "DOF in tracker", 61, -0.5, 60.5); - m_resid_before = fs->make("residBefore", "muon residuals before cut (cm)", 100, -20, 20); - m_resid_after = fs->make("residAfter", "muon residuals after cut (cm)", 100, -20, 20); - } + : m_input(iConfig.getParameter("input")), + m_minPt(iConfig.getParameter("minPt")), + m_maxTrackerForwardRedChi2(iConfig.getParameter("maxTrackerForwardRedChi2")), + m_minTrackerDOF(iConfig.getParameter("minTrackerDOF")), + m_maxMuonResidual(iConfig.getParameter("maxMuonResidual")), + m_hists(iConfig.getParameter("hists")), + m_pt(nullptr), + m_tracker_forwardredchi2(nullptr), + m_tracker_dof(nullptr) { + produces(); + + if (m_hists) { + edm::Service fs; + m_pt = fs->make("pt", "Transverse momentum (GeV)", 100, 0., 100.); + m_tracker_forwardredchi2 = + fs->make("trackerForwardRedChi2", "forward-biased reduced chi2 in tracker", 100, 0., 5.); + m_tracker_dof = fs->make("trackerDOF", "DOF in tracker", 61, -0.5, 60.5); + m_resid_before = fs->make("residBefore", "muon residuals before cut (cm)", 100, -20, 20); + m_resid_after = fs->make("residAfter", "muon residuals after cut (cm)", 100, -20, 20); + } } - AlignmentMuonHIPTrajectorySelector::~AlignmentMuonHIPTrajectorySelector() {} - // // member functions // // ------------ method called to produce the data ------------ -void -AlignmentMuonHIPTrajectorySelector::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - // input - edm::Handle originalTrajTrackMap; - iEvent.getByLabel(m_input, originalTrajTrackMap); - - // output - auto newTrajTrackMap = std::make_unique(); - - TrajectoryStateCombiner tsoscomb; - - for (TrajTrackAssociationCollection::const_iterator iPair = originalTrajTrackMap->begin(); iPair != originalTrajTrackMap->end(); ++iPair) { - if (m_hists) { - m_pt->Fill((*(*iPair).val).pt()); +void AlignmentMuonHIPTrajectorySelector::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { + // input + edm::Handle originalTrajTrackMap; + iEvent.getByLabel(m_input, originalTrajTrackMap); + + // output + auto newTrajTrackMap = std::make_unique(); + + TrajectoryStateCombiner tsoscomb; + + for (TrajTrackAssociationCollection::const_iterator iPair = originalTrajTrackMap->begin(); + iPair != originalTrajTrackMap->end(); + ++iPair) { + if (m_hists) { + m_pt->Fill((*(*iPair).val).pt()); + } + + if ((*(*iPair).val).pt() > m_minPt) { + std::vector measurements = (*(*iPair).key).measurements(); + + bool has_bad_residual = false; + + double tracker_forwardchi2 = 0.; + double tracker_dof = 0.; + for (std::vector::const_iterator im = measurements.begin(); im != measurements.end(); + ++im) { + const TrajectoryMeasurement meas = *im; + auto hit = &(*meas.recHit()); + const DetId id = hit->geographicalId(); + + if (hit->isValid() && id.det() == DetId::Tracker) { + if (hit->dimension() == 1) { + double residual = meas.forwardPredictedState().localPosition().x() - hit->localPosition().x(); + double error2 = + meas.forwardPredictedState().localError().positionError().xx() + hit->localPositionError().xx(); + + tracker_forwardchi2 += residual * residual / error2; + tracker_dof += 1.; + } else if (hit->dimension() == 2) { + double residualx = meas.forwardPredictedState().localPosition().x() - hit->localPosition().x(); + double residualy = meas.forwardPredictedState().localPosition().y() - hit->localPosition().y(); + double errorxx2 = + meas.forwardPredictedState().localError().positionError().xx() + hit->localPositionError().xx(); + double errorxy2 = + meas.forwardPredictedState().localError().positionError().xy() + hit->localPositionError().xy(); + double erroryy2 = + meas.forwardPredictedState().localError().positionError().yy() + hit->localPositionError().yy(); + + tracker_forwardchi2 += + (residualx * residualx + residualy * residualy) / (errorxx2 + 2. * errorxy2 + erroryy2); + tracker_dof += 2.; + } + } // end if a tracker hit + + if (hit->isValid() && id.det() == DetId::Muon && + (id.subdetId() == MuonSubdetId::DT || id.subdetId() == MuonSubdetId::CSC)) { + TrajectoryStateOnSurface tsosc = + tsoscomb.combine(meas.forwardPredictedState(), meas.backwardPredictedState()); + double residual = tsosc.localPosition().x() - hit->localPosition().x(); + m_resid_before->Fill(residual); + if (fabs(residual) > m_maxMuonResidual) { + has_bad_residual = true; + } + } // end if a muon hit } + tracker_dof -= 5.; + double tracker_forwardredchi2 = tracker_forwardchi2 / tracker_dof; - if ((*(*iPair).val).pt() > m_minPt) { - - std::vector measurements = (*(*iPair).key).measurements(); - - bool has_bad_residual = false; - - double tracker_forwardchi2 = 0.; - double tracker_dof = 0.; - for (std::vector::const_iterator im = measurements.begin(); im != measurements.end(); ++im) { - const TrajectoryMeasurement meas = *im; - auto hit = &(*meas.recHit()); - const DetId id = hit->geographicalId(); - - if (hit->isValid() && id.det() == DetId::Tracker) { - if (hit->dimension() == 1) { - double residual = meas.forwardPredictedState().localPosition().x() - hit->localPosition().x(); - double error2 = meas.forwardPredictedState().localError().positionError().xx() + hit->localPositionError().xx(); - - tracker_forwardchi2 += residual * residual / error2; - tracker_dof += 1.; - } - else if (hit->dimension() == 2) { - double residualx = meas.forwardPredictedState().localPosition().x() - hit->localPosition().x(); - double residualy = meas.forwardPredictedState().localPosition().y() - hit->localPosition().y(); - double errorxx2 = meas.forwardPredictedState().localError().positionError().xx() + hit->localPositionError().xx(); - double errorxy2 = meas.forwardPredictedState().localError().positionError().xy() + hit->localPositionError().xy(); - double erroryy2 = meas.forwardPredictedState().localError().positionError().yy() + hit->localPositionError().yy(); - - tracker_forwardchi2 += (residualx * residualx + residualy * residualy) / (errorxx2 + 2.*errorxy2 + erroryy2); - tracker_dof += 2.; - } - } // end if a tracker hit - - if (hit->isValid() && id.det() == DetId::Muon && (id.subdetId() == MuonSubdetId::DT || id.subdetId() == MuonSubdetId::CSC)) { - TrajectoryStateOnSurface tsosc = tsoscomb.combine(meas.forwardPredictedState(), meas.backwardPredictedState()); - double residual = tsosc.localPosition().x() - hit->localPosition().x(); - m_resid_before->Fill(residual); - if (fabs(residual) > m_maxMuonResidual) { - has_bad_residual = true; - } - } // end if a muon hit - - } - tracker_dof -= 5.; - double tracker_forwardredchi2 = tracker_forwardchi2 / tracker_dof; - - if (m_hists) { - m_tracker_forwardredchi2->Fill(tracker_forwardredchi2); - m_tracker_dof->Fill(tracker_dof); - - for (std::vector::const_iterator im = measurements.begin(); im != measurements.end(); ++im) { - const TrajectoryMeasurement meas = *im; - auto hit = &(*meas.recHit()); - const DetId id = hit->geographicalId(); - - if (!has_bad_residual) { - if (hit->isValid() && id.det() == DetId::Muon && (id.subdetId() == MuonSubdetId::DT || id.subdetId() == MuonSubdetId::CSC)) { - TrajectoryStateOnSurface tsosc = tsoscomb.combine(meas.forwardPredictedState(), meas.backwardPredictedState()); - double residual = tsosc.localPosition().x() - hit->localPosition().x(); - m_resid_after->Fill(residual); - } - } // end if residuals pass cut - } // end second loop over hits - } // end if filling histograms - - if (tracker_forwardredchi2 < m_maxTrackerForwardRedChi2 && tracker_dof >= m_minTrackerDOF && !has_bad_residual) { - newTrajTrackMap->insert((*iPair).key, (*iPair).val); - } // end if passes tracker cuts - } // end if passes pT cut - } // end loop over original trajTrackMap - - // put it in the Event - iEvent.put(std::move(newTrajTrackMap)); + if (m_hists) { + m_tracker_forwardredchi2->Fill(tracker_forwardredchi2); + m_tracker_dof->Fill(tracker_dof); + + for (std::vector::const_iterator im = measurements.begin(); im != measurements.end(); + ++im) { + const TrajectoryMeasurement meas = *im; + auto hit = &(*meas.recHit()); + const DetId id = hit->geographicalId(); + + if (!has_bad_residual) { + if (hit->isValid() && id.det() == DetId::Muon && + (id.subdetId() == MuonSubdetId::DT || id.subdetId() == MuonSubdetId::CSC)) { + TrajectoryStateOnSurface tsosc = + tsoscomb.combine(meas.forwardPredictedState(), meas.backwardPredictedState()); + double residual = tsosc.localPosition().x() - hit->localPosition().x(); + m_resid_after->Fill(residual); + } + } // end if residuals pass cut + } // end second loop over hits + } // end if filling histograms + + if (tracker_forwardredchi2 < m_maxTrackerForwardRedChi2 && tracker_dof >= m_minTrackerDOF && !has_bad_residual) { + newTrajTrackMap->insert((*iPair).key, (*iPair).val); + } // end if passes tracker cuts + } // end if passes pT cut + } // end loop over original trajTrackMap + + // put it in the Event + iEvent.put(std::move(newTrajTrackMap)); } //define this as a plug-in diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentMuonSelectorModule.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentMuonSelectorModule.cc index 97c0cbdbe1fc6..a808e285e263a 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentMuonSelectorModule.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentMuonSelectorModule.cc @@ -24,35 +24,30 @@ // tracks have only the recoMuons branch! struct MuonConfigSelector { - - typedef std::vector container; + typedef std::vector container; typedef container::const_iterator const_iterator; typedef reco::MuonCollection collection; - MuonConfigSelector( const edm::ParameterSet & cfg, edm::ConsumesCollector && iC ) : - theSelector(cfg) {} + MuonConfigSelector(const edm::ParameterSet &cfg, edm::ConsumesCollector &&iC) : theSelector(cfg) {} const_iterator begin() const { return selected_.begin(); } const_iterator end() const { return selected_.end(); } size_t size() const { return selected_.size(); } - void select( const edm::Handle & c, const edm::Event & evt, const edm::EventSetup &/* dummy*/) - { + void select(const edm::Handle &c, const edm::Event &evt, const edm::EventSetup & /* dummy*/) { all_.clear(); selected_.clear(); - for (collection::const_iterator i = c.product()->begin(), iE = c.product()->end(); - i != iE; ++i){ - all_.push_back(& * i ); + for (collection::const_iterator i = c.product()->begin(), iE = c.product()->end(); i != iE; ++i) { + all_.push_back(&*i); } - selected_ = theSelector.select(all_, evt); // might add dummy + selected_ = theSelector.select(all_, evt); // might add dummy } private: - container all_,selected_; + container all_, selected_; AlignmentMuonSelector theSelector; }; -typedef ObjectSelector AlignmentMuonSelectorModule; - -DEFINE_FWK_MODULE( AlignmentMuonSelectorModule ); +typedef ObjectSelector AlignmentMuonSelectorModule; +DEFINE_FWK_MODULE(AlignmentMuonSelectorModule); diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.cc index 10cbb7c777339..1000476eef3e3 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.cc @@ -2,7 +2,6 @@ /// /// \author : Frederic Ronga - #include "AlignmentProducer.h" #include "FWCore/Framework/interface/LooperFactory.h" @@ -10,12 +9,9 @@ #include "Geometry/Records/interface/MuonGeometryRecord.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" - //------------------------------------------------------------------------------ -AlignmentProducer::AlignmentProducer(const edm::ParameterSet& config) : - AlignmentProducerBase{config}, - maxLoops_{config.getUntrackedParameter("maxLoops")} -{ +AlignmentProducer::AlignmentProducer(const edm::ParameterSet &config) + : AlignmentProducerBase{config}, maxLoops_{config.getUntrackedParameter("maxLoops")} { edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::AlignmentProducer"; // Tell the framework what data is being produced @@ -28,130 +24,93 @@ AlignmentProducer::AlignmentProducer(const edm::ParameterSet& config) : } } - //------------------------------------------------------------------------------ -std::shared_ptr -AlignmentProducer::produceTracker(const TrackerDigiGeometryRecord&) -{ +std::shared_ptr AlignmentProducer::produceTracker(const TrackerDigiGeometryRecord &) { edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::produceTracker"; return trackerGeometry_; } - //------------------------------------------------------------------------------ -std::shared_ptr -AlignmentProducer::produceDT(const MuonGeometryRecord&) -{ +std::shared_ptr AlignmentProducer::produceDT(const MuonGeometryRecord &) { edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::produceDT"; return muonDTGeometry_; } - //------------------------------------------------------------------------------ -std::shared_ptr -AlignmentProducer::produceCSC(const MuonGeometryRecord&) -{ +std::shared_ptr AlignmentProducer::produceCSC(const MuonGeometryRecord &) { edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::produceCSC"; return muonCSCGeometry_; } - //------------------------------------------------------------------------------ -void AlignmentProducer::beginOfJob(const edm::EventSetup& iSetup) -{ +void AlignmentProducer::beginOfJob(const edm::EventSetup &iSetup) { edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::beginOfJob"; initAlignmentAlgorithm(iSetup); } - //------------------------------------------------------------------------------ -void AlignmentProducer::endOfJob() -{ +void AlignmentProducer::endOfJob() { edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::endOfJob"; if (!finish()) { - edm::LogError("Alignment") - << "@SUB=AlignmentProducer::endOfJob" - << "Did not process any events in last loop, do not dare to store to DB."; + edm::LogError("Alignment") << "@SUB=AlignmentProducer::endOfJob" + << "Did not process any events in last loop, do not dare to store to DB."; } } - //------------------------------------------------------------------------------ -void AlignmentProducer::startingNewLoop(unsigned int iLoop) -{ +void AlignmentProducer::startingNewLoop(unsigned int iLoop) { edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::startingNewLoop" << "Starting loop number " << iLoop; startProcessing(); } - //------------------------------------------------------------------------------ -edm::EDLooper::Status -AlignmentProducer::endOfLoop(const edm::EventSetup& iSetup, unsigned int iLoop) -{ - +edm::EDLooper::Status AlignmentProducer::endOfLoop(const edm::EventSetup &iSetup, unsigned int iLoop) { if (0 == nEvent()) { // beginOfJob is usually called by the framework in the first event of the first loop // (a hack: beginOfJob needs the EventSetup that is not well defined without an event) // and the algorithms rely on the initialisations done in beginOfJob. We cannot call // this->beginOfJob(iSetup); here either since that will access the EventSetup to get // some geometry information that is not defined either without having seen an event. - edm::LogError("Alignment") - << "@SUB=AlignmentProducer::endOfLoop" - << "Did not process any events in loop " << iLoop - << ", stop processing without terminating algorithm."; + edm::LogError("Alignment") << "@SUB=AlignmentProducer::endOfLoop" + << "Did not process any events in loop " << iLoop + << ", stop processing without terminating algorithm."; return kStop; } - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducer::endOfLoop" - << "Ending loop " << iLoop << ", terminating algorithm."; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducer::endOfLoop" + << "Ending loop " << iLoop << ", terminating algorithm."; terminateProcessing(&iSetup); - if ( iLoop == maxLoops_-1 || iLoop >= maxLoops_ ) return kStop; - else return kContinue; + if (iLoop == maxLoops_ - 1 || iLoop >= maxLoops_) + return kStop; + else + return kContinue; } - //------------------------------------------------------------------------------ -edm::EDLooper::Status -AlignmentProducer::duringLoop(const edm::Event& event, - const edm::EventSetup& setup) -{ - if (processEvent(event, setup)) return kContinue; - else return kStop; +edm::EDLooper::Status AlignmentProducer::duringLoop(const edm::Event &event, const edm::EventSetup &setup) { + if (processEvent(event, setup)) + return kContinue; + else + return kStop; } - //------------------------------------------------------------------------------ -void AlignmentProducer::beginRun(const edm::Run &run, const edm::EventSetup &setup) -{ - beginRunImpl(run, setup); -} - +void AlignmentProducer::beginRun(const edm::Run &run, const edm::EventSetup &setup) { beginRunImpl(run, setup); } //------------------------------------------------------------------------------ -void AlignmentProducer::endRun(const edm::Run &run, const edm::EventSetup &setup) -{ - endRunImpl(run, setup); -} - +void AlignmentProducer::endRun(const edm::Run &run, const edm::EventSetup &setup) { endRunImpl(run, setup); } //------------------------------------------------------------------------------ -void AlignmentProducer::beginLuminosityBlock(const edm::LuminosityBlock &lumiBlock, - const edm::EventSetup &setup) -{ +void AlignmentProducer::beginLuminosityBlock(const edm::LuminosityBlock &lumiBlock, const edm::EventSetup &setup) { beginLuminosityBlockImpl(lumiBlock, setup); } - //------------------------------------------------------------------------------ -void AlignmentProducer::endLuminosityBlock(const edm::LuminosityBlock &lumiBlock, - const edm::EventSetup &setup) -{ +void AlignmentProducer::endLuminosityBlock(const edm::LuminosityBlock &lumiBlock, const edm::EventSetup &setup) { endLuminosityBlockImpl(lumiBlock, setup); } - DEFINE_FWK_LOOPER(AlignmentProducer); diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.h b/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.h index 95e27b8b6bc13..65f1d6e7d577a 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.h +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentProducer.h @@ -8,17 +8,12 @@ /// /// \author : Frederic Ronga - #include "Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h" #include "FWCore/Framework/interface/ESProducerLooper.h" #include "FWCore/Framework/interface/Run.h" - -class AlignmentProducer : public AlignmentProducerBase, public edm::ESProducerLooper -{ - +class AlignmentProducer : public AlignmentProducerBase, public edm::ESProducerLooper { public: - /// Constructor AlignmentProducer(const edm::ParameterSet&); @@ -53,73 +48,48 @@ class AlignmentProducer : public AlignmentProducerBase, public edm::ESProducerLo void endRun(const edm::Run&, const edm::EventSetup&) override; /// Called at lumi block start, calling algorithm's beginLuminosityBlock - void beginLuminosityBlock(const edm::LuminosityBlock&, - const edm::EventSetup&) override; + void beginLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&) override; /// Called at lumi block end, calling algorithm's endLuminosityBlock - void endLuminosityBlock(const edm::LuminosityBlock&, - const edm::EventSetup&) override; + void endLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&) override; /// Called at each event Status duringLoop(const edm::Event&, const edm::EventSetup&) override; private: - bool getTrajTrackAssociationCollection(const edm::Event&, - edm::Handle&) override; + bool getTrajTrackAssociationCollection(const edm::Event&, edm::Handle&) override; bool getBeamSpot(const edm::Event&, edm::Handle&) override; - bool getTkFittedLasBeamCollection(const edm::Run&, - edm::Handle&) override; - bool getTsosVectorCollection(const edm::Run&, - edm::Handle&) override; - bool getAliClusterValueMap(const edm::Event&, - edm::Handle&) override; - - const unsigned int maxLoops_; /// Number of loops to loop + bool getTkFittedLasBeamCollection(const edm::Run&, edm::Handle&) override; + bool getTsosVectorCollection(const edm::Run&, edm::Handle&) override; + bool getAliClusterValueMap(const edm::Event&, edm::Handle&) override; + const unsigned int maxLoops_; /// Number of loops to loop }; - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducer::getTrajTrackAssociationCollection(const edm::Event& event, - edm::Handle& result) { +inline bool AlignmentProducer::getTrajTrackAssociationCollection(const edm::Event& event, + edm::Handle& result) { return event.getByLabel(tjTkAssociationMapTag_, result); } - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducer::getBeamSpot(const edm::Event& event, - edm::Handle& result) { +inline bool AlignmentProducer::getBeamSpot(const edm::Event& event, edm::Handle& result) { return event.getByLabel(beamSpotTag_, result); } - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducer::getTkFittedLasBeamCollection(const edm::Run& run, - edm::Handle& result) { +inline bool AlignmentProducer::getTkFittedLasBeamCollection(const edm::Run& run, + edm::Handle& result) { return run.getByLabel(tkLasBeamTag_, result); } - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducer::getTsosVectorCollection(const edm::Run& run, - edm::Handle& result) { +inline bool AlignmentProducer::getTsosVectorCollection(const edm::Run& run, edm::Handle& result) { return run.getByLabel(tkLasBeamTag_, result); } - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducer::getAliClusterValueMap(const edm::Event& event, - edm::Handle& result) { +inline bool AlignmentProducer::getAliClusterValueMap(const edm::Event& event, edm::Handle& result) { return event.getByLabel(clusterValueMapTag_, result); } diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentProducerAsAnalyzer.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentProducerAsAnalyzer.cc index b59737f9afa0c..e9b6ee10c0071 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentProducerAsAnalyzer.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentProducerAsAnalyzer.cc @@ -6,20 +6,15 @@ * @date 2015/07/16 */ - - /*** Header file ***/ #include "AlignmentProducerAsAnalyzer.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "FWCore/Framework/interface/MakerMacros.h" - - //------------------------------------------------------------------------------ -AlignmentProducerAsAnalyzer::AlignmentProducerAsAnalyzer(const edm::ParameterSet& config) : - AlignmentProducerBase{config} -{ +AlignmentProducerAsAnalyzer::AlignmentProducerAsAnalyzer(const edm::ParameterSet& config) + : AlignmentProducerBase{config} { usesResource(TFileService::kSharedResource); tjTkAssociationMapToken_ = consumes(tjTkAssociationMapTag_); @@ -29,72 +24,45 @@ AlignmentProducerAsAnalyzer::AlignmentProducerAsAnalyzer(const edm::ParameterSet clusterValueMapToken_ = consumes(clusterValueMapTag_); } - //------------------------------------------------------------------------------ -void -AlignmentProducerAsAnalyzer::beginJob() -{ -} - +void AlignmentProducerAsAnalyzer::beginJob() {} //------------------------------------------------------------------------------ -void -AlignmentProducerAsAnalyzer::endJob() -{ +void AlignmentProducerAsAnalyzer::endJob() { terminateProcessing(); if (!finish()) { - edm::LogError("Alignment") - << "@SUB=AlignmentProducerAsAnalyzer::endJob" - << "Did not process any events, do not dare to store to DB."; + edm::LogError("Alignment") << "@SUB=AlignmentProducerAsAnalyzer::endJob" + << "Did not process any events, do not dare to store to DB."; } // message is used by the MillePede log parser to check the end of the job - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerAsAnalyzer::endJob" - << "Finished alignment producer job."; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerAsAnalyzer::endJob" + << "Finished alignment producer job."; } - //------------------------------------------------------------------------------ -void -AlignmentProducerAsAnalyzer::beginRun(const edm::Run& run, const edm::EventSetup& setup) -{ +void AlignmentProducerAsAnalyzer::beginRun(const edm::Run& run, const edm::EventSetup& setup) { beginRunImpl(run, setup); } - //------------------------------------------------------------------------------ -void -AlignmentProducerAsAnalyzer::endRun(const edm::Run& run, const edm::EventSetup& setup) -{ - endRunImpl(run, setup); -} - +void AlignmentProducerAsAnalyzer::endRun(const edm::Run& run, const edm::EventSetup& setup) { endRunImpl(run, setup); } //------------------------------------------------------------------------------ -void -AlignmentProducerAsAnalyzer::beginLuminosityBlock(const edm::LuminosityBlock& lumiBlock, - const edm::EventSetup& setup) -{ +void AlignmentProducerAsAnalyzer::beginLuminosityBlock(const edm::LuminosityBlock& lumiBlock, + const edm::EventSetup& setup) { beginLuminosityBlockImpl(lumiBlock, setup); } - //------------------------------------------------------------------------------ -void -AlignmentProducerAsAnalyzer::endLuminosityBlock(const edm::LuminosityBlock& lumiBlock, - const edm::EventSetup& setup) -{ +void AlignmentProducerAsAnalyzer::endLuminosityBlock(const edm::LuminosityBlock& lumiBlock, + const edm::EventSetup& setup) { endLuminosityBlockImpl(lumiBlock, setup); } - //------------------------------------------------------------------------------ -void -AlignmentProducerAsAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& setup) -{ +void AlignmentProducerAsAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& setup) { processEvent(event, setup); } - DEFINE_FWK_MODULE(AlignmentProducerAsAnalyzer); diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentProducerAsAnalyzer.h b/Alignment/CommonAlignmentProducer/plugins/AlignmentProducerAsAnalyzer.h index 1e1b44b653ff3..31392dd2d66ba 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentProducerAsAnalyzer.h +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentProducerAsAnalyzer.h @@ -19,21 +19,15 @@ * */ - #include "Alignment/CommonAlignmentProducer/interface/AlignmentProducerBase.h" #include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Run.h" - -class AlignmentProducerAsAnalyzer : - public AlignmentProducerBase, - public edm::one::EDAnalyzer -{ +class AlignmentProducerAsAnalyzer + : public AlignmentProducerBase, + public edm::one::EDAnalyzer { //========================== PUBLIC METHODS ================================== -public: //==================================================================== - +public: //==================================================================== /// Constructor AlignmentProducerAsAnalyzer(const edm::ParameterSet&); @@ -49,74 +43,51 @@ class AlignmentProducerAsAnalyzer : void beginRun(const edm::Run&, const edm::EventSetup&) override; void endRun(const edm::Run&, const edm::EventSetup&) override; - void beginLuminosityBlock(const edm::LuminosityBlock&, - const edm::EventSetup&) override; - void endLuminosityBlock(const edm::LuminosityBlock&, - const edm::EventSetup&) override; + void beginLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&) override; + void endLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&) override; void analyze(const edm::Event&, const edm::EventSetup&) override; private: - bool getTrajTrackAssociationCollection(const edm::Event&, - edm::Handle&) override; + bool getTrajTrackAssociationCollection(const edm::Event&, edm::Handle&) override; bool getBeamSpot(const edm::Event&, edm::Handle&) override; - bool getTkFittedLasBeamCollection(const edm::Run&, - edm::Handle&) override; - bool getTsosVectorCollection(const edm::Run&, - edm::Handle&) override; - bool getAliClusterValueMap(const edm::Event&, - edm::Handle&) override; + bool getTkFittedLasBeamCollection(const edm::Run&, edm::Handle&) override; + bool getTsosVectorCollection(const edm::Run&, edm::Handle&) override; + bool getAliClusterValueMap(const edm::Event&, edm::Handle&) override; edm::EDGetTokenT tjTkAssociationMapToken_; edm::EDGetTokenT beamSpotToken_; edm::EDGetTokenT tkLasBeamToken_; edm::EDGetTokenT tsosVectorToken_; edm::EDGetTokenT clusterValueMapToken_; - }; - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducerAsAnalyzer::getTrajTrackAssociationCollection(const edm::Event& event, - edm::Handle& result) { +inline bool AlignmentProducerAsAnalyzer::getTrajTrackAssociationCollection( + const edm::Event& event, edm::Handle& result) { return event.getByToken(tjTkAssociationMapToken_, result); } - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducerAsAnalyzer::getBeamSpot(const edm::Event& event, - edm::Handle& result) { +inline bool AlignmentProducerAsAnalyzer::getBeamSpot(const edm::Event& event, edm::Handle& result) { return event.getByToken(beamSpotToken_, result); } - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducerAsAnalyzer::getTkFittedLasBeamCollection(const edm::Run& run, - edm::Handle& result) { +inline bool AlignmentProducerAsAnalyzer::getTkFittedLasBeamCollection(const edm::Run& run, + edm::Handle& result) { return run.getByToken(tkLasBeamToken_, result); } - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducerAsAnalyzer::getTsosVectorCollection(const edm::Run& run, - edm::Handle& result) { +inline bool AlignmentProducerAsAnalyzer::getTsosVectorCollection(const edm::Run& run, + edm::Handle& result) { return run.getByToken(tsosVectorToken_, result); } - //------------------------------------------------------------------------------ -inline -bool -AlignmentProducerAsAnalyzer::getAliClusterValueMap(const edm::Event& event, - edm::Handle& result) { +inline bool AlignmentProducerAsAnalyzer::getAliClusterValueMap(const edm::Event& event, + edm::Handle& result) { return event.getByToken(clusterValueMapToken_, result); } diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentSeedSelectorModule.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentSeedSelectorModule.cc index 41408a0882220..08c7685129406 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentSeedSelectorModule.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentSeedSelectorModule.cc @@ -6,35 +6,30 @@ #include "DataFormats/TrajectorySeed/interface/TrajectorySeedCollection.h" struct SeedConfigSelector { - - typedef std::vector container; + typedef std::vector container; typedef container::const_iterator const_iterator; typedef TrajectorySeedCollection collection; - SeedConfigSelector( const edm::ParameterSet & cfg, edm::ConsumesCollector && iC ) : - theSelector(cfg) {} + SeedConfigSelector(const edm::ParameterSet &cfg, edm::ConsumesCollector &&iC) : theSelector(cfg) {} const_iterator begin() const { return selected_.begin(); } const_iterator end() const { return selected_.end(); } size_t size() const { return selected_.size(); } - void select( const edm::Handle c, const edm::Event & evt, - const edm::EventSetup &/*dummy*/) - { + void select(const edm::Handle c, const edm::Event &evt, const edm::EventSetup & /*dummy*/) { all_.clear(); selected_.clear(); - for (collection::const_iterator i = c.product()->begin(), iE = c.product()->end(); - i != iE; ++i) { - all_.push_back( & * i ); + for (collection::const_iterator i = c.product()->begin(), iE = c.product()->end(); i != iE; ++i) { + all_.push_back(&*i); } - selected_ = theSelector.select(all_, evt); // might add dummy... + selected_ = theSelector.select(all_, evt); // might add dummy... } private: - container all_,selected_; + container all_, selected_; AlignmentSeedSelector theSelector; }; -typedef ObjectSelector AlignmentSeedSelectorModule; +typedef ObjectSelector AlignmentSeedSelectorModule; -DEFINE_FWK_MODULE( AlignmentSeedSelectorModule ); +DEFINE_FWK_MODULE(AlignmentSeedSelectorModule); diff --git a/Alignment/CommonAlignmentProducer/plugins/AlignmentTrackSelectorModule.cc b/Alignment/CommonAlignmentProducer/plugins/AlignmentTrackSelectorModule.cc index 090b7f09eb006..8500dad60bcee 100644 --- a/Alignment/CommonAlignmentProducer/plugins/AlignmentTrackSelectorModule.cc +++ b/Alignment/CommonAlignmentProducer/plugins/AlignmentTrackSelectorModule.cc @@ -17,20 +17,18 @@ #include "CommonTools/RecoAlgos/interface/TrackSelector.h" struct TrackConfigSelector { - typedef std::vector container; typedef container::const_iterator const_iterator; typedef reco::TrackCollection collection; - TrackConfigSelector( const edm::ParameterSet & cfg, edm::ConsumesCollector && iC ) : - theBaseSelector(cfg, iC), - theGlobalSelector(cfg.getParameter("GlobalSelector"), iC), - theTwoBodyDecaySelector(cfg.getParameter("TwoBodyDecaySelector"), iC) - { + TrackConfigSelector(const edm::ParameterSet& cfg, edm::ConsumesCollector&& iC) + : theBaseSelector(cfg, iC), + theGlobalSelector(cfg.getParameter("GlobalSelector"), iC), + theTwoBodyDecaySelector(cfg.getParameter("TwoBodyDecaySelector"), iC) { //TODO Wrap the BaseSelector into its own PSet theBaseSwitch = theBaseSelector.useThisFilter(); - theGlobalSwitch = theGlobalSelector.useThisFilter(); + theGlobalSwitch = theGlobalSelector.useThisFilter(); theTwoBodyDecaySwitch = theTwoBodyDecaySelector.useThisFilter(); } @@ -39,20 +37,18 @@ struct TrackConfigSelector { const_iterator end() const { return theSelectedTracks.end(); } size_t size() const { return theSelectedTracks.size(); } - void select( const edm::Handle & c, const edm::Event & evt, - const edm::EventSetup& eSetup) - { + void select(const edm::Handle& c, const edm::Event& evt, const edm::EventSetup& eSetup) { theSelectedTracks.clear(); - for( reco::TrackCollection::const_iterator i=c.product()->begin();i!=c.product()->end();++i){ - theSelectedTracks.push_back(& * i ); + for (reco::TrackCollection::const_iterator i = c.product()->begin(); i != c.product()->end(); ++i) { + theSelectedTracks.push_back(&*i); } // might add EvetSetup to the select(...) method of the Selectors - if(theBaseSwitch) - theSelectedTracks=theBaseSelector.select(theSelectedTracks,evt,eSetup); - if(theGlobalSwitch) - theSelectedTracks=theGlobalSelector.select(theSelectedTracks,evt,eSetup); - if(theTwoBodyDecaySwitch) - theSelectedTracks=theTwoBodyDecaySelector.select(theSelectedTracks,evt,eSetup); + if (theBaseSwitch) + theSelectedTracks = theBaseSelector.select(theSelectedTracks, evt, eSetup); + if (theGlobalSwitch) + theSelectedTracks = theGlobalSelector.select(theSelectedTracks, evt, eSetup); + if (theTwoBodyDecaySwitch) + theSelectedTracks = theTwoBodyDecaySelector.select(theSelectedTracks, evt, eSetup); } private: @@ -62,9 +58,8 @@ struct TrackConfigSelector { AlignmentTrackSelector theBaseSelector; AlignmentGlobalTrackSelector theGlobalSelector; AlignmentTwoBodyDecayTrackSelector theTwoBodyDecaySelector; - }; -typedef ObjectSelectorStream AlignmentTrackSelectorModule; +typedef ObjectSelectorStream AlignmentTrackSelectorModule; -DEFINE_FWK_MODULE( AlignmentTrackSelectorModule ); +DEFINE_FWK_MODULE(AlignmentTrackSelectorModule); diff --git a/Alignment/CommonAlignmentProducer/plugins/FakeAlignmentProducer.cc b/Alignment/CommonAlignmentProducer/plugins/FakeAlignmentProducer.cc index 9240daca69348..70f668fb99731 100644 --- a/Alignment/CommonAlignmentProducer/plugins/FakeAlignmentProducer.cc +++ b/Alignment/CommonAlignmentProducer/plugins/FakeAlignmentProducer.cc @@ -2,7 +2,7 @@ // // Package: FakeAlignmentProducer // Class: FakeAlignmentProducer -// +// /**\class FakeAlignmentProducer FakeAlignmentProducer.h Alignment/FakeAlignmentProducer/interface/FakeAlignmentProducer.h Description: Producer of fake alignment data for all geometries (currently: Tracker, DT and CSC) @@ -19,7 +19,6 @@ reconstruction Geometry should notice that and not pass to GeometryAligner. // // - // System #include @@ -28,8 +27,6 @@ reconstruction Geometry should notice that and not pass to GeometryAligner. #include "FWCore/Framework/interface/ESProducer.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" - - // Alignment #include "CondFormats/Alignment/interface/Alignments.h" #include "CondFormats/Alignment/interface/AlignmentErrorsExtended.h" @@ -46,14 +43,10 @@ class FakeAlignmentProducer : public edm::ESProducer { FakeAlignmentProducer(const edm::ParameterSet&); ~FakeAlignmentProducer() override {} - std::unique_ptr - produceTkAli(const TrackerAlignmentRcd&) { return std::make_unique();} - std::unique_ptr - produceDTAli(const DTAlignmentRcd&) { return std::make_unique();} - std::unique_ptr - produceCSCAli(const CSCAlignmentRcd&) { return std::make_unique();} - std::unique_ptr - produceGlobals(const GlobalPositionRcd&) {return std::make_unique();} + std::unique_ptr produceTkAli(const TrackerAlignmentRcd&) { return std::make_unique(); } + std::unique_ptr produceDTAli(const DTAlignmentRcd&) { return std::make_unique(); } + std::unique_ptr produceCSCAli(const CSCAlignmentRcd&) { return std::make_unique(); } + std::unique_ptr produceGlobals(const GlobalPositionRcd&) { return std::make_unique(); } std::unique_ptr produceTkAliErr(const TrackerAlignmentErrorExtendedRcd&) { return std::make_unique(); @@ -64,28 +57,24 @@ class FakeAlignmentProducer : public edm::ESProducer { std::unique_ptr produceCSCAliErr(const CSCAlignmentErrorExtendedRcd&) { return std::make_unique(); } - }; -FakeAlignmentProducer::FakeAlignmentProducer(const edm::ParameterSet& iConfig) -{ +FakeAlignmentProducer::FakeAlignmentProducer(const edm::ParameterSet& iConfig) { // This 'appendToDataLabel' is used by the framework to distinguish providers // with different settings and to request a special one by e.g. // iSetup.get().get("theLabel", tkGeomHandle); - edm::LogInfo("Alignments") - << "@SUB=FakeAlignmentProducer" << "Providing data with label '" - << iConfig.getParameter("appendToDataLabel") << "'."; - - setWhatProduced( this, &FakeAlignmentProducer::produceTkAli ); - setWhatProduced( this, &FakeAlignmentProducer::produceTkAliErr ); - setWhatProduced( this, &FakeAlignmentProducer::produceDTAli ); - setWhatProduced( this, &FakeAlignmentProducer::produceDTAliErr ); - setWhatProduced( this, &FakeAlignmentProducer::produceCSCAli ); - setWhatProduced( this, &FakeAlignmentProducer::produceCSCAliErr ); - setWhatProduced( this, &FakeAlignmentProducer::produceGlobals ); - + edm::LogInfo("Alignments") << "@SUB=FakeAlignmentProducer" + << "Providing data with label '" << iConfig.getParameter("appendToDataLabel") + << "'."; + + setWhatProduced(this, &FakeAlignmentProducer::produceTkAli); + setWhatProduced(this, &FakeAlignmentProducer::produceTkAliErr); + setWhatProduced(this, &FakeAlignmentProducer::produceDTAli); + setWhatProduced(this, &FakeAlignmentProducer::produceDTAliErr); + setWhatProduced(this, &FakeAlignmentProducer::produceCSCAli); + setWhatProduced(this, &FakeAlignmentProducer::produceCSCAliErr); + setWhatProduced(this, &FakeAlignmentProducer::produceGlobals); } - //define this as a plug-in DEFINE_FWK_EVENTSETUP_MODULE(FakeAlignmentProducer); diff --git a/Alignment/CommonAlignmentProducer/plugins/FakeAlignmentSource.cc b/Alignment/CommonAlignmentProducer/plugins/FakeAlignmentSource.cc index 3b89e581e126e..fb4de86e236ea 100644 --- a/Alignment/CommonAlignmentProducer/plugins/FakeAlignmentSource.cc +++ b/Alignment/CommonAlignmentProducer/plugins/FakeAlignmentSource.cc @@ -2,7 +2,7 @@ // // Package: FakeAlignmentSource // Class: FakeAlignmentSource -// +// /**\class FakeAlignmentSource FakeAlignmentSource.cc Alignment/FakeAlignmentProducer/plugins/FakeAlignmentSource.cc Description: Producer of fake alignment data for all geometries (currently: Tracker, DT and CSC) @@ -19,7 +19,6 @@ reconstruction Geometry should notice that and not pass to GeometryAligner. // // - // System #include #include @@ -44,53 +43,44 @@ reconstruction Geometry should notice that and not pass to GeometryAligner. #include "CondFormats/AlignmentRecord/interface/GlobalPositionRcd.h" #include "CondFormats/AlignmentRecord/interface/TrackerSurfaceDeformationRcd.h" -class FakeAlignmentSource : public edm::ESProducer, public edm::EventSetupRecordIntervalFinder { +class FakeAlignmentSource : public edm::ESProducer, public edm::EventSetupRecordIntervalFinder { public: FakeAlignmentSource(const edm::ParameterSet&); ~FakeAlignmentSource() override {} /// Tracker and its APE - std::unique_ptr produceTkAli(const TrackerAlignmentRcd&) { - return std::make_unique(); - } - std::unique_ptr produceTkAliErr(const TrackerAlignmentErrorExtendedRcd&) { + std::unique_ptr produceTkAli(const TrackerAlignmentRcd&) { return std::make_unique(); } + std::unique_ptr produceTkAliErr(const TrackerAlignmentErrorExtendedRcd&) { return std::make_unique(); } /// DT and its APE - std::unique_ptr produceDTAli(const DTAlignmentRcd&) { - return std::make_unique(); - } + std::unique_ptr produceDTAli(const DTAlignmentRcd&) { return std::make_unique(); } std::unique_ptr produceDTAliErr(const DTAlignmentErrorExtendedRcd&) { return std::make_unique(); } /// CSC and its APE - std::unique_ptr produceCSCAli(const CSCAlignmentRcd&) { - return std::make_unique(); - } + std::unique_ptr produceCSCAli(const CSCAlignmentRcd&) { return std::make_unique(); } std::unique_ptr produceCSCAliErr(const CSCAlignmentErrorExtendedRcd&) { return std::make_unique(); } /// GlobalPositions - std::unique_ptr produceGlobals(const GlobalPositionRcd&) { - return std::make_unique(); - } + std::unique_ptr produceGlobals(const GlobalPositionRcd&) { return std::make_unique(); } /// Tracker surface deformations - std::unique_ptr - produceTrackerSurfaceDeformation(const TrackerSurfaceDeformationRcd&) { + std::unique_ptr produceTrackerSurfaceDeformation(const TrackerSurfaceDeformationRcd&) { return std::make_unique(); } - protected: +protected: /// provide (dummy) IOV - void setIntervalFor( const edm::eventsetup::EventSetupRecordKey& /*dummy*/, - const edm::IOVSyncValue& ioSyncVal, edm::ValidityInterval& iov) override; - - private: + void setIntervalFor(const edm::eventsetup::EventSetupRecordKey& /*dummy*/, + const edm::IOVSyncValue& ioSyncVal, + edm::ValidityInterval& iov) override; +private: bool produceTracker_; bool produceDT_; bool produceCSC_; @@ -103,20 +93,19 @@ class FakeAlignmentSource : public edm::ESProducer, public edm::EventSetupRecord //________________________________________________________________________________________ FakeAlignmentSource::FakeAlignmentSource(const edm::ParameterSet& iConfig) - :produceTracker_(iConfig.getParameter("produceTracker")), - produceDT_(iConfig.getParameter("produceDT")), - produceCSC_(iConfig.getParameter("produceCSC")), - produceGlobalPosition_(iConfig.getParameter("produceGlobalPosition")), - produceTrackerSurfaceDeformation_(iConfig.getParameter("produceTrackerSurfaceDeformation")) -{ + : produceTracker_(iConfig.getParameter("produceTracker")), + produceDT_(iConfig.getParameter("produceDT")), + produceCSC_(iConfig.getParameter("produceCSC")), + produceGlobalPosition_(iConfig.getParameter("produceGlobalPosition")), + produceTrackerSurfaceDeformation_(iConfig.getParameter("produceTrackerSurfaceDeformation")) { // This 'appendToDataLabel' is used by the framework to distinguish providers // with different settings and to request a special one by e.g. // iSetup.get().get("theLabel", tkGeomHandle); - - edm::LogInfo("Alignments") - << "@SUB=FakeAlignmentSource" << "Providing data with label '" - << iConfig.getParameter("appendToDataLabel") << "'."; - + + edm::LogInfo("Alignments") << "@SUB=FakeAlignmentSource" + << "Providing data with label '" << iConfig.getParameter("appendToDataLabel") + << "'."; + // Tell framework what data is produced by which method: if (produceTracker_) { this->setWhatProduced(this, &FakeAlignmentSource::produceTkAli); @@ -158,10 +147,9 @@ FakeAlignmentSource::FakeAlignmentSource(const edm::ParameterSet& iConfig) } } -void FakeAlignmentSource::setIntervalFor( const edm::eventsetup::EventSetupRecordKey& /*dummy*/, - const edm::IOVSyncValue& ioSyncVal, - edm::ValidityInterval& outValidity ) -{ +void FakeAlignmentSource::setIntervalFor(const edm::eventsetup::EventSetupRecordKey& /*dummy*/, + const edm::IOVSyncValue& ioSyncVal, + edm::ValidityInterval& outValidity) { // Implementation copied from SiStripGainFakeESSource: unlimited IOV outValidity = edm::ValidityInterval(ioSyncVal.beginOfTime(), ioSyncVal.endOfTime()); } diff --git a/Alignment/CommonAlignmentProducer/plugins/GlobalTrackerMuonAlignment.cc b/Alignment/CommonAlignmentProducer/plugins/GlobalTrackerMuonAlignment.cc index 1fbec7ec4b0fb..b72d7b31cd1c7 100644 --- a/Alignment/CommonAlignmentProducer/plugins/GlobalTrackerMuonAlignment.cc +++ b/Alignment/CommonAlignmentProducer/plugins/GlobalTrackerMuonAlignment.cc @@ -2,7 +2,7 @@ // // Package: GlobalTrackerMuonAlignment // Class: GlobalTrackerMuonAlignment -// +// /**\class GlobalTrackerMuonAlignment GlobalTrackerMuonAlignment.cc Alignment/GlobalTrackerMuonAlignment/src/GlobalTrackerMuonAlignment.cc Description: Producer of relative tracker and muon system alignment @@ -63,7 +63,7 @@ #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h" #include "TrackingTools/GeomPropagators/interface/Propagator.h" #include "TrackingTools/GeomPropagators/interface/SmartPropagator.h" -#include "TrackingTools/GeomPropagators/interface/PropagationDirectionChooser.h" +#include "TrackingTools/GeomPropagators/interface/PropagationDirectionChooser.h" #include "TrackingTools/TransientTrack/interface/TransientTrack.h" #include "TrackPropagation/SteppingHelixPropagator/interface/SteppingHelixPropagator.h" #include "TrackPropagation/RungeKutta/interface/defaultRKPropagator.h" @@ -92,13 +92,13 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -using namespace edm; +using namespace edm; using namespace std; using namespace reco; @@ -107,7 +107,7 @@ using namespace reco; // class GlobalTrackerMuonAlignment : public edm::EDAnalyzer { - public: +public: explicit GlobalTrackerMuonAlignment(const edm::ParameterSet&); ~GlobalTrackerMuonAlignment() override; @@ -115,57 +115,62 @@ class GlobalTrackerMuonAlignment : public edm::EDAnalyzer { void analyzeTrackTrajectory(const edm::Event&, const edm::EventSetup&); void bookHist(); void fitHist(); - void trackFitter(reco::TrackRef, reco::TransientTrack&, PropagationDirection, - TrajectoryStateOnSurface&); - void muonFitter(reco::TrackRef, reco::TransientTrack&, PropagationDirection, - TrajectoryStateOnSurface&); + void trackFitter(reco::TrackRef, reco::TransientTrack&, PropagationDirection, TrajectoryStateOnSurface&); + void muonFitter(reco::TrackRef, reco::TransientTrack&, PropagationDirection, TrajectoryStateOnSurface&); void debugTrackHit(const std::string, reco::TrackRef); void debugTrackHit(const std::string, reco::TransientTrack&); void debugTrajectorySOS(const std::string, TrajectoryStateOnSurface&); void debugTrajectorySOSv(const std::string, TrajectoryStateOnSurface); void debugTrajectory(const std::string, Trajectory&); - void gradientGlobal(GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, - GlobalVector&, AlgebraicSymMatrix66&); - void gradientLocal(GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, - GlobalVector&, CLHEP::HepSymMatrix&, CLHEP::HepMatrix&, - CLHEP::HepVector&, AlgebraicVector4&); - void gradientGlobalAlg(GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, - AlgebraicSymMatrix66&); - void misalignMuon(GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, - GlobalVector&, GlobalVector&); - void misalignMuonL(GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, - GlobalVector&, GlobalVector&, AlgebraicVector4&, - TrajectoryStateOnSurface&, TrajectoryStateOnSurface&); - void writeGlPosRcd(CLHEP::HepVector& d3); - inline double CLHEP_dot(const CLHEP::HepVector& a, const CLHEP::HepVector& b) - { - return a(1)*b(1)+a(2)*b(2)+a(3)*b(3); + void gradientGlobal(GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, AlgebraicSymMatrix66&); + void gradientLocal(GlobalVector&, + GlobalVector&, + GlobalVector&, + GlobalVector&, + GlobalVector&, + CLHEP::HepSymMatrix&, + CLHEP::HepMatrix&, + CLHEP::HepVector&, + AlgebraicVector4&); + void gradientGlobalAlg(GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, AlgebraicSymMatrix66&); + void misalignMuon(GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&, GlobalVector&); + void misalignMuonL(GlobalVector&, + GlobalVector&, + GlobalVector&, + GlobalVector&, + GlobalVector&, + GlobalVector&, + AlgebraicVector4&, + TrajectoryStateOnSurface&, + TrajectoryStateOnSurface&); + void writeGlPosRcd(CLHEP::HepVector& d3); + inline double CLHEP_dot(const CLHEP::HepVector& a, const CLHEP::HepVector& b) { + return a(1) * b(1) + a(2) * b(2) + a(3) * b(3); } - private: - - void beginJob() override ; +private: + void beginJob() override; void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override ; - + void endJob() override; + // ----------member data --------------------------- - edm::InputTag trackTags_; // used to select what tracks to read from configuration file - edm::InputTag muonTags_; // used to select what standalone muons - edm::InputTag gmuonTags_; // used to select what global muons - edm::InputTag smuonTags_; // used to select what selected muons - string propagator_; // name of the propagator - bool cosmicMuonMode_; + edm::InputTag trackTags_; // used to select what tracks to read from configuration file + edm::InputTag muonTags_; // used to select what standalone muons + edm::InputTag gmuonTags_; // used to select what global muons + edm::InputTag smuonTags_; // used to select what selected muons + string propagator_; // name of the propagator + bool cosmicMuonMode_; bool isolatedMuonMode_; - bool collectionCosmic; // if true, read muon collection expected for CosmicMu - bool collectionIsolated; // IsolateMu - bool refitMuon_; // if true, refit stand alone muon track - bool refitTrack_; // tracker track + bool collectionCosmic; // if true, read muon collection expected for CosmicMu + bool collectionIsolated; // IsolateMu + bool refitMuon_; // if true, refit stand alone muon track + bool refitTrack_; // tracker track string rootOutFile_; string txtOutFile_; - bool writeDB_; // write results to DB - bool debug_; // run in debugging mode + bool writeDB_; // write results to DB + bool debug_; // run in debugging mode edm::ESWatcher watchTrackingGeometry_; edm::ESHandle theTrackingGeometry; @@ -187,80 +192,76 @@ class GlobalTrackerMuonAlignment : public edm::EDAnalyzer { MuonTransientTrackingRecHitBuilder* MuRHBuilder; const TransientTrackingRecHitBuilder* TTRHBuilder; - // // LSF for global d(3): Inf * d = Gfr - AlgebraicVector3 Gfr; // free terms - AlgebraicSymMatrix33 Inf; // information matrix - // // LSF for global d(6): Hess * d = Grad - CLHEP::HepVector Grad; // gradient of the objective function in global parameters - CLHEP::HepMatrix Hess; // Hessian -- // --- + // // LSF for global d(3): Inf * d = Gfr + AlgebraicVector3 Gfr; // free terms + AlgebraicSymMatrix33 Inf; // information matrix + // // LSF for global d(6): Hess * d = Grad + CLHEP::HepVector Grad; // gradient of the objective function in global parameters + CLHEP::HepMatrix Hess; // Hessian -- // --- - CLHEP::HepVector GradL; // gradient of the objective function in local parameters - CLHEP::HepMatrix HessL; // Hessian -- // --- + CLHEP::HepVector GradL; // gradient of the objective function in local parameters + CLHEP::HepMatrix HessL; // Hessian -- // --- - int N_event; // processed events - int N_track; // selected tracks + int N_event; // processed events + int N_track; // selected tracks - std::vector::const_iterator - iteratorTrackerRcd; // location of Tracker in container globalPositionRcd_->m_aligm - std::vector::const_iterator - iteratorMuonRcd; // Muon - std::vector::const_iterator - iteratorEcalRcd; // Ecal std::vector::const_iterator - iteratorHcalRcd; // Hcal - - CLHEP::HepVector MuGlShift; // evaluated global muon shifts - CLHEP::HepVector MuGlAngle; // evaluated global muon angles - - std::string MuSelect; // what part of muon system is selected for 1st hit - - ofstream OutGlobalTxt; // output the vector of global alignment as text - - TFile * file; - TH1F * histo; - TH1F * histo2; // outerP - TH1F * histo3; // outerLambda = PI/2-outerTheta - TH1F * histo4; // phi - TH1F * histo5; // outerR - TH1F * histo6; // outerZ - TH1F * histo7; // s - TH1F * histo8; // chi^2 of muon-track - - TH1F * histo11; // |Rm-Rt| - TH1F * histo12; // Xm-Xt - TH1F * histo13; // Ym-Yt - TH1F * histo14; // Zm-Zt - TH1F * histo15; // Nxm-Nxt - TH1F * histo16; // Nym-Nyt - TH1F * histo17; // Nzm-Nzt - TH1F * histo18; // Error X of inner track - TH1F * histo19; // Error X of muon - TH1F * histo20; // Error of Xm-Xt - TH1F * histo21; // pull(Xm-Xt) - TH1F * histo22; // pull(Ym-Yt) - TH1F * histo23; // pull(Zm-Zt) - TH1F * histo24; // pull(PXm-PXt) - TH1F * histo25; // pull(PYm-Pyt) - TH1F * histo26; // pull(PZm-PZt) - TH1F * histo27; // Nx of tangent plane - TH1F * histo28; // Ny of tangent plane - TH1F * histo29; // lenght of inner track - TH1F * histo30; // lenght of muon track - TH1F * histo31; // chi2 local - TH1F * histo32; // pull(Pxm/Pzm - Pxt/Pzt) local - TH1F * histo33; // pull(Pym/Pzm - Pyt/Pzt) local - TH1F * histo34; // pull(Xm - Xt) local - TH1F * histo35; // pull(Ym - Yt) local - - TH2F * histo101; // Rtrack/muon vs Ztrack/muon - TH2F * histo102; // Ytrack/muon vs Xtrack/muon + iteratorTrackerRcd; // location of Tracker in container globalPositionRcd_->m_aligm + std::vector::const_iterator iteratorMuonRcd; // Muon + std::vector::const_iterator iteratorEcalRcd; // Ecal + std::vector::const_iterator iteratorHcalRcd; // Hcal + + CLHEP::HepVector MuGlShift; // evaluated global muon shifts + CLHEP::HepVector MuGlAngle; // evaluated global muon angles + + std::string MuSelect; // what part of muon system is selected for 1st hit + + ofstream OutGlobalTxt; // output the vector of global alignment as text + + TFile* file; + TH1F* histo; + TH1F* histo2; // outerP + TH1F* histo3; // outerLambda = PI/2-outerTheta + TH1F* histo4; // phi + TH1F* histo5; // outerR + TH1F* histo6; // outerZ + TH1F* histo7; // s + TH1F* histo8; // chi^2 of muon-track + + TH1F* histo11; // |Rm-Rt| + TH1F* histo12; // Xm-Xt + TH1F* histo13; // Ym-Yt + TH1F* histo14; // Zm-Zt + TH1F* histo15; // Nxm-Nxt + TH1F* histo16; // Nym-Nyt + TH1F* histo17; // Nzm-Nzt + TH1F* histo18; // Error X of inner track + TH1F* histo19; // Error X of muon + TH1F* histo20; // Error of Xm-Xt + TH1F* histo21; // pull(Xm-Xt) + TH1F* histo22; // pull(Ym-Yt) + TH1F* histo23; // pull(Zm-Zt) + TH1F* histo24; // pull(PXm-PXt) + TH1F* histo25; // pull(PYm-Pyt) + TH1F* histo26; // pull(PZm-PZt) + TH1F* histo27; // Nx of tangent plane + TH1F* histo28; // Ny of tangent plane + TH1F* histo29; // lenght of inner track + TH1F* histo30; // lenght of muon track + TH1F* histo31; // chi2 local + TH1F* histo32; // pull(Pxm/Pzm - Pxt/Pzt) local + TH1F* histo33; // pull(Pym/Pzm - Pyt/Pzt) local + TH1F* histo34; // pull(Xm - Xt) local + TH1F* histo35; // pull(Ym - Yt) local + + TH2F* histo101; // Rtrack/muon vs Ztrack/muon + TH2F* histo102; // Ytrack/muon vs Xtrack/muon }; // // constants, enums and typedefs // - // // static data member definitions // @@ -269,42 +270,38 @@ class GlobalTrackerMuonAlignment : public edm::EDAnalyzer { // constructors and destructor // GlobalTrackerMuonAlignment::GlobalTrackerMuonAlignment(const edm::ParameterSet& iConfig) - :trackTags_(iConfig.getParameter("tracks")), - muonTags_(iConfig.getParameter("muons")), - gmuonTags_(iConfig.getParameter("gmuons")), - smuonTags_(iConfig.getParameter("smuons")), - propagator_(iConfig.getParameter("Propagator")), - - cosmicMuonMode_(iConfig.getParameter("cosmics")), - isolatedMuonMode_(iConfig.getParameter("isolated")), - - refitMuon_(iConfig.getParameter("refitmuon")), - refitTrack_(iConfig.getParameter("refittrack")), - - rootOutFile_(iConfig.getUntrackedParameter("rootOutFile")), - txtOutFile_(iConfig.getUntrackedParameter("txtOutFile")), - writeDB_(iConfig.getUntrackedParameter("writeDB")), - debug_(iConfig.getUntrackedParameter("debug")), - defineFitter(true) -{ -#ifdef NO_FALSE_FALSE_MODE - if (cosmicMuonMode_==false && isolatedMuonMode_==false) { + : trackTags_(iConfig.getParameter("tracks")), + muonTags_(iConfig.getParameter("muons")), + gmuonTags_(iConfig.getParameter("gmuons")), + smuonTags_(iConfig.getParameter("smuons")), + propagator_(iConfig.getParameter("Propagator")), + + cosmicMuonMode_(iConfig.getParameter("cosmics")), + isolatedMuonMode_(iConfig.getParameter("isolated")), + + refitMuon_(iConfig.getParameter("refitmuon")), + refitTrack_(iConfig.getParameter("refittrack")), + + rootOutFile_(iConfig.getUntrackedParameter("rootOutFile")), + txtOutFile_(iConfig.getUntrackedParameter("txtOutFile")), + writeDB_(iConfig.getUntrackedParameter("writeDB")), + debug_(iConfig.getUntrackedParameter("debug")), + defineFitter(true) { +#ifdef NO_FALSE_FALSE_MODE + if (cosmicMuonMode_ == false && isolatedMuonMode_ == false) { throw cms::Exception("BadConfig") << "Muon collection not set! " - << "Use from GlobalTrackerMuonAlignment_test_cfg.py."; + << "Use from GlobalTrackerMuonAlignment_test_cfg.py."; } -#endif - if (cosmicMuonMode_==true && isolatedMuonMode_==true) { +#endif + if (cosmicMuonMode_ == true && isolatedMuonMode_ == true) { throw cms::Exception("BadConfig") << "Muon collection can be either cosmic or isolated! " - << "Please set only one to true."; + << "Please set only one to true."; } } -GlobalTrackerMuonAlignment::~GlobalTrackerMuonAlignment() -{ - - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) - +GlobalTrackerMuonAlignment::~GlobalTrackerMuonAlignment() { + // do anything here that needs to be done at desctruction time + // (e.g. close files, deallocate resources etc.) } // @@ -312,43 +309,45 @@ GlobalTrackerMuonAlignment::~GlobalTrackerMuonAlignment() // // ------------ method called to for each event ------------ -void -GlobalTrackerMuonAlignment::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - //GlobalTrackerMuonAlignment::analyzeTrackTrack(iEvent, iSetup); - GlobalTrackerMuonAlignment::analyzeTrackTrajectory(iEvent, iSetup); +void GlobalTrackerMuonAlignment::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + //GlobalTrackerMuonAlignment::analyzeTrackTrack(iEvent, iSetup); + GlobalTrackerMuonAlignment::analyzeTrackTrajectory(iEvent, iSetup); } // ------------ method called once for job just before starting event loop ------------ -void GlobalTrackerMuonAlignment::beginJob() -{ +void GlobalTrackerMuonAlignment::beginJob() { N_event = 0; N_track = 0; - - if (cosmicMuonMode_==true && isolatedMuonMode_==false) { - collectionCosmic = true; collectionIsolated = false;} - else if (cosmicMuonMode_==false && isolatedMuonMode_==true) { - collectionCosmic = false; collectionIsolated = true;} - else { - collectionCosmic = false; collectionIsolated = false;} - for(int i=0; i<=2; i++){ + if (cosmicMuonMode_ == true && isolatedMuonMode_ == false) { + collectionCosmic = true; + collectionIsolated = false; + } else if (cosmicMuonMode_ == false && isolatedMuonMode_ == true) { + collectionCosmic = false; + collectionIsolated = true; + } else { + collectionCosmic = false; + collectionIsolated = false; + } + + for (int i = 0; i <= 2; i++) { Gfr(i) = 0.; - for(int j=0; j<=2; j++){ - Inf(i,j) = 0.; - }} + for (int j = 0; j <= 2; j++) { + Inf(i, j) = 0.; + } + } - Grad = CLHEP::HepVector(6,0); - Hess = CLHEP::HepSymMatrix(6,0); + Grad = CLHEP::HepVector(6, 0); + Hess = CLHEP::HepSymMatrix(6, 0); - GradL = CLHEP::HepVector(6,0); - HessL = CLHEP::HepSymMatrix(6,0); + GradL = CLHEP::HepVector(6, 0); + HessL = CLHEP::HepSymMatrix(6, 0); // histograms - TDirectory * dirsave = gDirectory; + TDirectory* dirsave = gDirectory; - file = new TFile(rootOutFile_.c_str(), "recreate"); - const bool oldAddDir = TH1::AddDirectoryStatus(); + file = new TFile(rootOutFile_.c_str(), "recreate"); + const bool oldAddDir = TH1::AddDirectoryStatus(); TH1::AddDirectory(true); @@ -364,225 +363,235 @@ void GlobalTrackerMuonAlignment::endJob() { this->fitHist(); - AlgebraicVector3 d(0., 0., 0.); // ------------ alignmnet Global Algebraic + AlgebraicVector3 d(0., 0., 0.); // ------------ alignmnet Global Algebraic - AlgebraicSymMatrix33 InfI; // inverse it - for(int i=0; i<=2; i++) - for(int j=0; j<=2; j++){ - if(j < i) continue; - InfI(i,j) += Inf(i,j);} + AlgebraicSymMatrix33 InfI; // inverse it + for (int i = 0; i <= 2; i++) + for (int j = 0; j <= 2; j++) { + if (j < i) + continue; + InfI(i, j) += Inf(i, j); + } bool ierr = !InfI.Invert(); - if( ierr ) { if(alarm) - std::cout<<" Error inverse Inf matrix !!!!!!!!!!!"<Write(); - file->Close(); + file->Write(); + file->Close(); - // write global parameters to text file + // write global parameters to text file OutGlobalTxt.open(txtOutFile_.c_str(), ios::out); - if(!OutGlobalTxt.is_open()) std::cout<<" outglobal.txt is not open !!!!!"<GetXaxis()->SetTitle("momentum [GeV/c]"); - histo3 = new TH1F("outerLambda","#lambda outer",100,-PI/2.,PI/2.); + histo3 = new TH1F("outerLambda", "#lambda outer", 100, -PI / 2., PI / 2.); histo3->GetXaxis()->SetTitle("#lambda outer"); - histo4 = new TH1F("phi","#phi [rad]",100,-PI,PI); + histo4 = new TH1F("phi", "#phi [rad]", 100, -PI, PI); histo4->GetXaxis()->SetTitle("#phi [rad]"); - histo5 = new TH1F("Rmuon","inner muon hit R [cm]",100,0.,800.); + histo5 = new TH1F("Rmuon", "inner muon hit R [cm]", 100, 0., 800.); histo5->GetXaxis()->SetTitle("R of muon [cm]"); - histo6 = new TH1F("Zmuon","inner muon hit Z[cm]",100,-1000.,1000.); + histo6 = new TH1F("Zmuon", "inner muon hit Z[cm]", 100, -1000., 1000.); histo6->GetXaxis()->SetTitle("Z of muon [cm]"); - histo7 = new TH1F("(Pm-Pt)/Pt"," (Pmuon-Ptrack)/Ptrack", 100,-2.,2.); + histo7 = new TH1F("(Pm-Pt)/Pt", " (Pmuon-Ptrack)/Ptrack", 100, -2., 2.); histo7->GetXaxis()->SetTitle("(Pmuon-Ptrack)/Ptrack"); - histo8 = new TH1F("chi muon-track","#chi^{2}(muon-track)", 1000,0.,1000.); + histo8 = new TH1F("chi muon-track", "#chi^{2}(muon-track)", 1000, 0., 1000.); histo8->GetXaxis()->SetTitle("#chi^{2} of muon w.r.t. propagated track"); - histo11 = new TH1F("distance muon-track","distance muon w.r.t track [cm]",100,0.,30.); + histo11 = new TH1F("distance muon-track", "distance muon w.r.t track [cm]", 100, 0., 30.); histo11->GetXaxis()->SetTitle("distance of muon w.r.t. track [cm]"); - histo12 = new TH1F("Xmuon-Xtrack","Xmuon-Xtrack [cm]",200,-20.,20.); - histo12->GetXaxis()->SetTitle("Xmuon - Xtrack [cm]"); - histo13 = new TH1F("Ymuon-Ytrack","Ymuon-Ytrack [cm]",200,-20.,20.); + histo12 = new TH1F("Xmuon-Xtrack", "Xmuon-Xtrack [cm]", 200, -20., 20.); + histo12->GetXaxis()->SetTitle("Xmuon - Xtrack [cm]"); + histo13 = new TH1F("Ymuon-Ytrack", "Ymuon-Ytrack [cm]", 200, -20., 20.); histo13->GetXaxis()->SetTitle("Ymuon - Ytrack [cm]"); - histo14 = new TH1F("Zmuon-Ztrack","Zmuon-Ztrack [cm]",200,-20.,20.); + histo14 = new TH1F("Zmuon-Ztrack", "Zmuon-Ztrack [cm]", 200, -20., 20.); histo14->GetXaxis()->SetTitle("Zmuon-Ztrack [cm]"); - histo15 = new TH1F("NXmuon-NXtrack","NXmuon-NXtrack [rad]",200,-.1,.1); + histo15 = new TH1F("NXmuon-NXtrack", "NXmuon-NXtrack [rad]", 200, -.1, .1); histo15->GetXaxis()->SetTitle("N_{X}(muon)-N_{X}(track) [rad]"); - histo16 = new TH1F("NYmuon-NYtrack","NYmuon-NYtrack [rad]",200,-.1,.1); + histo16 = new TH1F("NYmuon-NYtrack", "NYmuon-NYtrack [rad]", 200, -.1, .1); histo16->GetXaxis()->SetTitle("N_{Y}(muon)-N_{Y}(track) [rad]"); - histo17 = new TH1F("NZmuon-NZtrack","NZmuon-NZtrack [rad]",200,-.1,.1); + histo17 = new TH1F("NZmuon-NZtrack", "NZmuon-NZtrack [rad]", 200, -.1, .1); histo17->GetXaxis()->SetTitle("N_{Z}(muon)-N_{Z}(track) [rad]"); - histo18 = new TH1F("expected error of Xinner","outer hit of inner tracker",100,0,.01); + histo18 = new TH1F("expected error of Xinner", "outer hit of inner tracker", 100, 0, .01); histo18->GetXaxis()->SetTitle("expected error of Xinner [cm]"); - histo19 = new TH1F("expected error of Xmuon","inner hit of muon",100,0,.1); + histo19 = new TH1F("expected error of Xmuon", "inner hit of muon", 100, 0, .1); histo19->GetXaxis()->SetTitle("expected error of Xmuon [cm]"); - histo20 = new TH1F("expected error of Xmuon-Xtrack","muon w.r.t. propagated track",100,0.,10.); + histo20 = new TH1F("expected error of Xmuon-Xtrack", "muon w.r.t. propagated track", 100, 0., 10.); histo20->GetXaxis()->SetTitle("expected error of Xmuon-Xtrack [cm]"); - histo21 = new TH1F("pull of Xmuon-Xtrack","pull of Xmuon-Xtrack",100,-10.,10.); + histo21 = new TH1F("pull of Xmuon-Xtrack", "pull of Xmuon-Xtrack", 100, -10., 10.); histo21->GetXaxis()->SetTitle("(Xmuon-Xtrack)/expected error"); - histo22 = new TH1F("pull of Ymuon-Ytrack","pull of Ymuon-Ytrack",100,-10.,10.); + histo22 = new TH1F("pull of Ymuon-Ytrack", "pull of Ymuon-Ytrack", 100, -10., 10.); histo22->GetXaxis()->SetTitle("(Ymuon-Ytrack)/expected error"); - histo23 = new TH1F("pull of Zmuon-Ztrack","pull of Zmuon-Ztrack",100,-10.,10.); + histo23 = new TH1F("pull of Zmuon-Ztrack", "pull of Zmuon-Ztrack", 100, -10., 10.); histo23->GetXaxis()->SetTitle("(Zmuon-Ztrack)/expected error"); - histo24 = new TH1F("pull of PXmuon-PXtrack","pull of PXmuon-PXtrack",100,-10.,10.); + histo24 = new TH1F("pull of PXmuon-PXtrack", "pull of PXmuon-PXtrack", 100, -10., 10.); histo24->GetXaxis()->SetTitle("(P_{X}(muon)-P_{X}(track))/expected error"); - histo25 = new TH1F("pull of PYmuon-PYtrack","pull of PYmuon-PYtrack",100,-10.,10.); + histo25 = new TH1F("pull of PYmuon-PYtrack", "pull of PYmuon-PYtrack", 100, -10., 10.); histo25->GetXaxis()->SetTitle("(P_{Y}(muon)-P_{Y}(track))/expected error"); - histo26 = new TH1F("pull of PZmuon-PZtrack","pull of PZmuon-PZtrack",100,-10.,10.); + histo26 = new TH1F("pull of PZmuon-PZtrack", "pull of PZmuon-PZtrack", 100, -10., 10.); histo26->GetXaxis()->SetTitle("(P_{Z}(muon)-P_{Z}(track))/expected error"); - histo27 = new TH1F("N_x","Nx of tangent plane",120,-1.1,1.1); + histo27 = new TH1F("N_x", "Nx of tangent plane", 120, -1.1, 1.1); histo27->GetXaxis()->SetTitle("normal vector projection N_{X}"); - histo28 = new TH1F("N_y","Ny of tangent plane",120,-1.1,1.1); + histo28 = new TH1F("N_y", "Ny of tangent plane", 120, -1.1, 1.1); histo28->GetXaxis()->SetTitle("normal vector projection N_{Y}"); - histo29 = new TH1F("lenght of track","lenght of track",200,0.,400); + histo29 = new TH1F("lenght of track", "lenght of track", 200, 0., 400); histo29->GetXaxis()->SetTitle("lenght of track [cm]"); - histo30 = new TH1F("lenght of muon","lenght of muon",200,0.,800); + histo30 = new TH1F("lenght of muon", "lenght of muon", 200, 0., 800); histo30->GetXaxis()->SetTitle("lenght of muon [cm]"); - histo31 = new TH1F("local chi muon-track","#local chi^{2}(muon-track)", 1000,0.,1000.); + histo31 = new TH1F("local chi muon-track", "#local chi^{2}(muon-track)", 1000, 0., 1000.); histo31->GetXaxis()->SetTitle("#local chi^{2} of muon w.r.t. propagated track"); - histo32 = new TH1F("pull of Px/Pz local","pull of Px/Pz local",100,-10.,10.); + histo32 = new TH1F("pull of Px/Pz local", "pull of Px/Pz local", 100, -10., 10.); histo32->GetXaxis()->SetTitle("local (Px/Pz(muon) - Px/Pz(track))/expected error"); - histo33 = new TH1F("pull of Py/Pz local","pull of Py/Pz local",100,-10.,10.); + histo33 = new TH1F("pull of Py/Pz local", "pull of Py/Pz local", 100, -10., 10.); histo33->GetXaxis()->SetTitle("local (Py/Pz(muon) - Py/Pz(track))/expected error"); - histo34 = new TH1F("pull of X local","pull of X local",100,-10.,10.); + histo34 = new TH1F("pull of X local", "pull of X local", 100, -10., 10.); histo34->GetXaxis()->SetTitle("local (Xmuon - Xtrack)/expected error"); - histo35 = new TH1F("pull of Y local","pull of Y local",100,-10.,10.); + histo35 = new TH1F("pull of Y local", "pull of Y local", 100, -10., 10.); histo35->GetXaxis()->SetTitle("local (Ymuon - Ytrack)/expected error"); - histo101 = new TH2F("Rtr/mu vs Ztr/mu","hit of track/muon",100,-800.,800.,100,0.,600.); + histo101 = new TH2F("Rtr/mu vs Ztr/mu", "hit of track/muon", 100, -800., 800., 100, 0., 600.); histo101->GetXaxis()->SetTitle("Z of track/muon [cm]"); histo101->GetYaxis()->SetTitle("R of track/muon [cm]"); - histo102 = new TH2F("Ytr/mu vs Xtr/mu","hit of track/muon",100,-600.,600.,100,-600.,600.); + histo102 = new TH2F("Ytr/mu vs Xtr/mu", "hit of track/muon", 100, -600., 600., 100, -600., 600.); histo102->GetXaxis()->SetTitle("X of track/muon [cm]"); histo102->GetYaxis()->SetTitle("Y of track/muon [cm]"); } // ------------ fit histogram ------------ void GlobalTrackerMuonAlignment::fitHist() { - - histo7->Fit("gaus","Q"); - - histo12->Fit("gaus","Q"); - histo13->Fit("gaus","Q"); - histo14->Fit("gaus","Q"); - histo15->Fit("gaus","Q"); - histo16->Fit("gaus","Q"); - histo17->Fit("gaus","Q"); - - histo21->Fit("gaus","Q"); - histo22->Fit("gaus","Q"); - histo23->Fit("gaus","Q"); - histo24->Fit("gaus","Q"); - histo25->Fit("gaus","Q"); - histo26->Fit("gaus","Q"); - - histo32->Fit("gaus","Q"); - histo33->Fit("gaus","Q"); - histo34->Fit("gaus","Q"); - histo35->Fit("gaus","Q"); + histo7->Fit("gaus", "Q"); + + histo12->Fit("gaus", "Q"); + histo13->Fit("gaus", "Q"); + histo14->Fit("gaus", "Q"); + histo15->Fit("gaus", "Q"); + histo16->Fit("gaus", "Q"); + histo17->Fit("gaus", "Q"); + + histo21->Fit("gaus", "Q"); + histo22->Fit("gaus", "Q"); + histo23->Fit("gaus", "Q"); + histo24->Fit("gaus", "Q"); + histo25->Fit("gaus", "Q"); + histo26->Fit("gaus", "Q"); + + histo32->Fit("gaus", "Q"); + histo33->Fit("gaus", "Q"); + histo34->Fit("gaus", "Q"); + histo35->Fit("gaus", "Q"); } // ------------ method to analyze recoTrack & recoMuon of Global Muon ------------ -void GlobalTrackerMuonAlignment::analyzeTrackTrack -(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void GlobalTrackerMuonAlignment::analyzeTrackTrack(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; - using namespace reco; + using namespace reco; //debug_ = true; bool info = false; bool alarm = false; //bool alarm = true; double PI = 3.1415927; - - cosmicMuonMode_ = true; // true: both Cosmic and IsolatedMuon are treated with 1,2 tracks - isolatedMuonMode_ = !cosmicMuonMode_; //true: only IsolatedMuon are treated with 1 track - + + cosmicMuonMode_ = true; // true: both Cosmic and IsolatedMuon are treated with 1,2 tracks + isolatedMuonMode_ = !cosmicMuonMode_; //true: only IsolatedMuon are treated with 1 track + //if(N_event == 1) //GlobalPositionRcdRead1::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); N_event++; if (info || debug_) { - std::cout << "----- event " << N_event << " -- tracks "< gmuons; Handle smuons; - if (collectionIsolated){ - iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "TrackerOnly", tracks); - iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "StandAlone", muons); - iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "GlobalMuon", gmuons); - iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "SelectedMuons", smuons); - } - else if (collectionCosmic){ - iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "TrackerOnly", tracks); - iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "StandAlone", muons); - iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "GlobalMuon", gmuons); - iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "SelectedMuons", smuons); + if (collectionIsolated) { + iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "TrackerOnly", tracks); + iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "StandAlone", muons); + iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "GlobalMuon", gmuons); + iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "SelectedMuons", smuons); + } else if (collectionCosmic) { + iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "TrackerOnly", tracks); + iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "StandAlone", muons); + iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "GlobalMuon", gmuons); + iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "SelectedMuons", smuons); + } else { + iEvent.getByLabel(trackTags_, tracks); + iEvent.getByLabel(muonTags_, muons); + iEvent.getByLabel(gmuonTags_, gmuons); + iEvent.getByLabel(smuonTags_, smuons); } - else{ - iEvent.getByLabel(trackTags_,tracks); - iEvent.getByLabel(muonTags_,muons); - iEvent.getByLabel(gmuonTags_,gmuons); - iEvent.getByLabel(smuonTags_,smuons); - } if (debug_) { - std::cout << " ievBunch " << iEvent.bunchCrossing() - << " runN " << (int)iEvent.run() <size() << " " <size() - << " "<size() << " " << smuons->size() << std::endl; - for (MuonCollection::const_iterator itMuon = smuons->begin(); - itMuon != smuons->end(); - ++itMuon) { - std::cout << " is isolatValid Matches " << itMuon->isIsolationValid() - << " " <isMatchesValid() << std::endl; + std::cout << " ievBunch " << iEvent.bunchCrossing() << " runN " << (int)iEvent.run() << std::endl; + std::cout << " N tracks s/amu gmu selmu " << tracks->size() << " " << muons->size() << " " << gmuons->size() << " " + << smuons->size() << std::endl; + for (MuonCollection::const_iterator itMuon = smuons->begin(); itMuon != smuons->end(); ++itMuon) { + std::cout << " is isolatValid Matches " << itMuon->isIsolationValid() << " " << itMuon->isMatchesValid() + << std::endl; } } - if (isolatedMuonMode_) { // ---- Only 1 Isolated Muon -------- - if (tracks->size() != 1) return; - if (muons->size() != 1) return; - if (gmuons->size() != 1) return; - if (smuons->size() != 1) return; + if (isolatedMuonMode_) { // ---- Only 1 Isolated Muon -------- + if (tracks->size() != 1) + return; + if (muons->size() != 1) + return; + if (gmuons->size() != 1) + return; + if (smuons->size() != 1) + return; } - - if (cosmicMuonMode_){ // ---- 1,2 Cosmic Muon -------- - if (smuons->size() > 2) return; - if (tracks->size() != smuons->size()) return; - if (muons->size() != smuons->size()) return; - if (gmuons->size() != smuons->size()) return; + + if (cosmicMuonMode_) { // ---- 1,2 Cosmic Muon -------- + if (smuons->size() > 2) + return; + if (tracks->size() != smuons->size()) + return; + if (muons->size() != smuons->size()) + return; + if (gmuons->size() != smuons->size()) + return; } - + // ok mc_isolated_mu //edm::ESHandle trackerGeometry; //iSetup.get().get(trackerGeometry); @@ -646,13 +658,13 @@ void GlobalTrackerMuonAlignment::analyzeTrackTrack // don't work //edm::ESHandle cscGeometry; //iSetup.get().get(cscGeometry); - + if (watchTrackingGeometry_.check(iSetup) || !trackingGeometry_) { edm::ESHandle trackingGeometry; iSetup.get().get(trackingGeometry); trackingGeometry_ = &*trackingGeometry; } - + if (watchMagneticFieldRecord_.check(iSetup) || !magneticField_) { edm::ESHandle magneticField; iSetup.get().get(magneticField); @@ -663,92 +675,95 @@ void GlobalTrackerMuonAlignment::analyzeTrackTrack edm::ESHandle globalPositionRcd; iSetup.get().get(globalPositionRcd); globalPositionRcd_ = &*globalPositionRcd; - for (std::vector::const_iterator i - = globalPositionRcd_->m_align.begin(); - i != globalPositionRcd_->m_align.end(); ++i){ - if(DetId(DetId::Tracker).rawId() == i->rawId()) iteratorTrackerRcd = i; - if(DetId(DetId::Muon).rawId() == i->rawId()) iteratorMuonRcd = i; - if(DetId(DetId::Ecal).rawId() == i->rawId()) iteratorEcalRcd = i; - if(DetId(DetId::Hcal).rawId() == i->rawId()) iteratorHcalRcd = i; + for (std::vector::const_iterator i = globalPositionRcd_->m_align.begin(); + i != globalPositionRcd_->m_align.end(); + ++i) { + if (DetId(DetId::Tracker).rawId() == i->rawId()) + iteratorTrackerRcd = i; + if (DetId(DetId::Muon).rawId() == i->rawId()) + iteratorMuonRcd = i; + if (DetId(DetId::Ecal).rawId() == i->rawId()) + iteratorEcalRcd = i; + if (DetId(DetId::Hcal).rawId() == i->rawId()) + iteratorHcalRcd = i; } - if(true || debug_){ - std::cout << "=== iteratorMuonRcd " << iteratorMuonRcd->rawId()<<" ====\n" - << " translation " << iteratorMuonRcd->translation()<<"\n" - << " angles " << iteratorMuonRcd->rotation().eulerAngles() << std::endl; + if (true || debug_) { + std::cout << "=== iteratorMuonRcd " << iteratorMuonRcd->rawId() << " ====\n" + << " translation " << iteratorMuonRcd->translation() << "\n" + << " angles " << iteratorMuonRcd->rotation().eulerAngles() << std::endl; std::cout << iteratorMuonRcd->rotation() << std::endl; - } - } // end of GlobalPositionRcd - + } + } // end of GlobalPositionRcd + ESHandle propagator; iSetup.get().get(propagator_, propagator); - - SteppingHelixPropagator alongStHePr = - SteppingHelixPropagator(magneticField_, alongMomentum); - SteppingHelixPropagator oppositeStHePr = - SteppingHelixPropagator(magneticField_, oppositeToMomentum); + + SteppingHelixPropagator alongStHePr = SteppingHelixPropagator(magneticField_, alongMomentum); + SteppingHelixPropagator oppositeStHePr = SteppingHelixPropagator(magneticField_, oppositeToMomentum); //double tolerance = 5.e-5; - defaultRKPropagator::Product aprod( magneticField_, alongMomentum, 5.e-5); auto & alongRKPr = aprod.propagator; - defaultRKPropagator::Product oprod( magneticField_, oppositeToMomentum, 5.e-5); auto & oppositeRKPr = oprod.propagator; + defaultRKPropagator::Product aprod(magneticField_, alongMomentum, 5.e-5); + auto& alongRKPr = aprod.propagator; + defaultRKPropagator::Product oprod(magneticField_, oppositeToMomentum, 5.e-5); + auto& oppositeRKPr = oprod.propagator; float epsilon = 5.; - SmartPropagator alongSmPr = - SmartPropagator(alongRKPr, alongStHePr, magneticField_, alongMomentum, epsilon); - SmartPropagator oppositeSmPr = - SmartPropagator(oppositeRKPr, oppositeStHePr, magneticField_, oppositeToMomentum, epsilon); - + SmartPropagator alongSmPr = SmartPropagator(alongRKPr, alongStHePr, magneticField_, alongMomentum, epsilon); + SmartPropagator oppositeSmPr = + SmartPropagator(oppositeRKPr, oppositeStHePr, magneticField_, oppositeToMomentum, epsilon); + // ................................................ selected/global muon - //itMuon --> Jim's globalMuon - for(MuonCollection::const_iterator itMuon = smuons->begin(); - itMuon != smuons->end(); ++itMuon) { - - if(debug_){ - std::cout<<" mu gM is GM Mu SaM tM "<isGlobalMuon()<<" " - <isMuon()<<" "<isStandAloneMuon() - <<" "<isTrackerMuon()<<" " - < Jim's globalMuon + for (MuonCollection::const_iterator itMuon = smuons->begin(); itMuon != smuons->end(); ++itMuon) { + if (debug_) { + std::cout << " mu gM is GM Mu SaM tM " << itMuon->isGlobalMuon() << " " << itMuon->isMuon() << " " + << itMuon->isStandAloneMuon() << " " << itMuon->isTrackerMuon() << " " << std::endl; } - + // get information about the innermost muon hit ------------------------- TransientTrack muTT(itMuon->outerTrack(), magneticField_, trackingGeometry_); TrajectoryStateOnSurface innerMuTSOS = muTT.innermostMeasurementState(); TrajectoryStateOnSurface outerMuTSOS = muTT.outermostMeasurementState(); - + // get information about the outermost tracker hit ----------------------- TransientTrack trackTT(itMuon->track(), magneticField_, trackingGeometry_); TrajectoryStateOnSurface outerTrackTSOS = trackTT.outermostMeasurementState(); TrajectoryStateOnSurface innerTrackTSOS = trackTT.innermostMeasurementState(); - - GlobalPoint pointTrackIn = innerTrackTSOS.globalPosition(); + + GlobalPoint pointTrackIn = innerTrackTSOS.globalPosition(); GlobalPoint pointTrackOut = outerTrackTSOS.globalPosition(); - float lenghtTrack = (pointTrackOut-pointTrackIn).mag(); - GlobalPoint pointMuonIn = innerMuTSOS.globalPosition(); + float lenghtTrack = (pointTrackOut - pointTrackIn).mag(); + GlobalPoint pointMuonIn = innerMuTSOS.globalPosition(); GlobalPoint pointMuonOut = outerMuTSOS.globalPosition(); float lenghtMuon = (pointMuonOut - pointMuonIn).mag(); GlobalVector momentumTrackOut = outerTrackTSOS.globalMomentum(); GlobalVector momentumTrackIn = innerTrackTSOS.globalMomentum(); - float distanceInIn = (pointTrackIn - pointMuonIn).mag(); - float distanceInOut = (pointTrackIn - pointMuonOut).mag(); - float distanceOutIn = (pointTrackOut - pointMuonIn).mag(); + float distanceInIn = (pointTrackIn - pointMuonIn).mag(); + float distanceInOut = (pointTrackIn - pointMuonOut).mag(); + float distanceOutIn = (pointTrackOut - pointMuonIn).mag(); float distanceOutOut = (pointTrackOut - pointMuonOut).mag(); - if(debug_){ - std::cout<<" pointTrackIn "< - tpMuLocal(refSurface.tangentPlane(innerMuTSOS.localPosition())); + if (isolatedMuonMode_) { //------------------------------- Isolated Muon ----- + const Surface& refSurface = innerMuTSOS.surface(); + ConstReferenceCountingPointer tpMuLocal(refSurface.tangentPlane(innerMuTSOS.localPosition())); Nl = tpMuLocal->normalVector(); - ConstReferenceCountingPointer - tpMuGlobal(refSurface.tangentPlane(innerMuTSOS.globalPosition())); + ConstReferenceCountingPointer tpMuGlobal(refSurface.tangentPlane(innerMuTSOS.globalPosition())); GlobalVector Ng = tpMuGlobal->normalVector(); Surface* surf = (Surface*)&refSurface; - const Plane* refPlane = dynamic_cast(surf); + const Plane* refPlane = dynamic_cast(surf); GlobalVector Nlp = refPlane->normalVector(); - - if(debug_){ - std::cout<<" Nlocal "<propagate(outerTrackTSOS, refSurface); - - if(!extrapolationT.isValid()){ - if(false & alarm) - std::cout<<" !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " - //<<"\a\a\a\a\a\a\a\a"< - tpMuGlobal(refSurface.tangentPlane(innerMuTSOS.globalPosition())); - Nl = tpMuGlobal->normalVector(); - - // extrapolation to innermost muon hit - extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); - //extrapolationT = propagator->propagate(outerTrackTSOS, refSurface); - - if(!extrapolationT.isValid()){ - if(false & alarm) - std::cout<<" !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " - //<<"\a\a\a\a\a\a\a\a"<propDir "<propagationDirection()< - tpMuGlobal(refSurface.tangentPlane(outerMuTSOS.globalPosition())); - Nl = tpMuGlobal->normalVector(); - - // extrapolation to outermost muon hit - extrapolationT = oppositeSmPr.propagate(innerTrackTSOS, refSurface); - - if(!extrapolationT.isValid()){ - if(false & alarm) - std::cout<<" !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " - <<"\a\a\a\a\a\a\a\a"<propDir "<propagationDirection()< - tpMuGlobal(refSurface.tangentPlane(outerMuTSOS.globalPosition())); - Nl = tpMuGlobal->normalVector(); - - // extrapolation to outermost muon hit - extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); - - if(!extrapolationT.isValid()){ - if(alarm) - std::cout<<" !!!!!!!!! Catastrophe Out-Out extrapolationT.isValid " - <<"\a\a\a\a\a\a\a\a"< tpMuGlobal(refSurface.tangentPlane(innerMuTSOS.globalPosition())); + Nl = tpMuGlobal->normalVector(); + + // extrapolation to innermost muon hit + extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); + //extrapolationT = propagator->propagate(outerTrackTSOS, refSurface); + + if (!extrapolationT.isValid()) { + if (false & alarm) + std::cout << " !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " + //<<"\a\a\a\a\a\a\a\a"<propDir "<propagationDirection()< tpMuGlobal(refSurface.tangentPlane(outerMuTSOS.globalPosition())); + Nl = tpMuGlobal->normalVector(); + + // extrapolation to outermost muon hit + extrapolationT = oppositeSmPr.propagate(innerTrackTSOS, refSurface); + + if (!extrapolationT.isValid()) { + if (false & alarm) + std::cout << " !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " + << "\a\a\a\a\a\a\a\a" << extrapolationT.isValid() << std::endl; + continue; + } + if (debug_) + std::cout << " extrapolationT.isValid " << extrapolationT.isValid() << std::endl; + + tsosMuonIf = 2; + Rt = GlobalVector((extrapolationT.globalPosition()).x(), + (extrapolationT.globalPosition()).y(), + (extrapolationT.globalPosition()).z()); + + Pt = extrapolationT.globalMomentum(); + // global parameters of muon + GRm = GlobalVector( + (outerMuTSOS.globalPosition()).x(), (outerMuTSOS.globalPosition()).y(), (outerMuTSOS.globalPosition()).z()); + GPm = outerMuTSOS.globalMomentum(); + Rt0 = GlobalVector((innerTrackTSOS.globalPosition()).x(), + (innerTrackTSOS.globalPosition()).y(), + (innerTrackTSOS.globalPosition()).z()); + Cm = AlgebraicSymMatrix66(extrapolationT.cartesianError().matrix() + outerMuTSOS.cartesianError().matrix()); + C0 = AlgebraicSymMatrix66(innerTrackTSOS.cartesianError().matrix()); + Ce = AlgebraicSymMatrix66(extrapolationT.cartesianError().matrix()); + C1 = AlgebraicSymMatrix66(outerMuTSOS.cartesianError().matrix()); + + if (false & debug_) { + //std::cout<<" ->propDir "<propagationDirection()< tpMuGlobal(refSurface.tangentPlane(outerMuTSOS.globalPosition())); + Nl = tpMuGlobal->normalVector(); + + // extrapolation to outermost muon hit + extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); + + if (!extrapolationT.isValid()) { + if (alarm) + std::cout << " !!!!!!!!! Catastrophe Out-Out extrapolationT.isValid " + << "\a\a\a\a\a\a\a\a" << extrapolationT.isValid() << std::endl; + continue; + } + if (debug_) + std::cout << " extrapolationT.isValid " << extrapolationT.isValid() << std::endl; + + tsosMuonIf = 2; + Rt = GlobalVector((extrapolationT.globalPosition()).x(), + (extrapolationT.globalPosition()).y(), + (extrapolationT.globalPosition()).z()); + + Pt = extrapolationT.globalMomentum(); + // global parameters of muon + GRm = GlobalVector( + (outerMuTSOS.globalPosition()).x(), (outerMuTSOS.globalPosition()).y(), (outerMuTSOS.globalPosition()).z()); + GPm = outerMuTSOS.globalMomentum(); + Rt0 = GlobalVector((outerTrackTSOS.globalPosition()).x(), + (outerTrackTSOS.globalPosition()).y(), + (outerTrackTSOS.globalPosition()).z()); + Cm = AlgebraicSymMatrix66(extrapolationT.cartesianError().matrix() + outerMuTSOS.cartesianError().matrix()); + C0 = AlgebraicSymMatrix66(outerTrackTSOS.cartesianError().matrix()); + Ce = AlgebraicSymMatrix66(extrapolationT.cartesianError().matrix()); + C1 = AlgebraicSymMatrix66(outerMuTSOS.cartesianError().matrix()); + + if (debug_) { + PropagationDirectionChooser Chooser; + std::cout << " propDirCh " << Chooser.operator()(*outerTrackTSOS.freeState(), refSurface) << " Ch == along " + << (alongMomentum == Chooser.operator()(*outerTrackTSOS.freeState(), refSurface)) << std::endl; + std::cout << " --- Nlocal " << Nl.x() << " " << Nl.y() << " " << Nl.z() << " " + << " alfa " << int(asin(Nl.x()) * 57.29578) << std::endl; + std::cout << " Nornal " << Nl.x() << " " << Nl.y() << " " << Nl.z() << " " + << " alfa " << int(asin(Nl.x()) * 57.29578) << std::endl; + } + } // enf of ---- Out - Out ----- + else { + if (alarm) + std::cout << " ------- !!!!!!!!!!!!!!! No proper Out - In \a\a\a\a\a\a\a" << std::endl; + continue; } - + } // ------------------------------- end Cosmic Muon ----- - - if(tsosMuonIf == 0) {if(info) {std::cout<<"No tsosMuon !!!!!!"< 50.) continue; // momenum cut > 50GeV //if(Pt.mag() > 100.) continue; // momenum cut > 100GeV //if(trackTT.charge() < 0) continue; // select positive charge //if(trackTT.charge() > 0) continue; // select negative charge - - //if(fabs(resR.x()) > 5.) continue; // strong cut X - //if(fabs(resR.y()) > 5.) continue; // Y + + //if(fabs(resR.x()) > 5.) continue; // strong cut X + //if(fabs(resR.y()) > 5.) continue; // Y //if(fabs(resR.z()) > 5.) continue; // Z //if(fabs(resR.mag()) > 7.5) continue; // dR @@ -1062,8 +1069,8 @@ void GlobalTrackerMuonAlignment::analyzeTrackTrack if(chi_d > 40.) continue; */ - // select Barrel - //if(Rmuon < 400. || Rmuon > 450.) continue; + // select Barrel + //if(Rmuon < 400. || Rmuon > 450.) continue; //if(Zmuon < -600. || Zmuon > 600.) continue; //if(fabs(Nl.z()) > 0.95) continue; //MuSelect = " Barrel"; @@ -1071,51 +1078,51 @@ void GlobalTrackerMuonAlignment::analyzeTrackTrack //if(Rmuon < 120. || Rmuon > 450.) continue; //if(Zmuon < -720.) continue; //if(Zmuon > -580.) continue; - //if(fabs(Nl.z()) < 0.95) continue; + //if(fabs(Nl.z()) < 0.95) continue; //MuSelect = " EndCap1"; // EndCap2 //if(Rmuon < 120. || Rmuon > 450.) continue; //if(Zmuon > 720.) continue; //if(Zmuon < 580.) continue; - //if(fabs(Nl.z()) < 0.95) continue; + //if(fabs(Nl.z()) < 0.95) continue; //MuSelect = " EndCap2"; // select All - if(Rmuon < 120. || Rmuon > 450.) continue; - if(Zmuon < -720. || Zmuon > 720.) continue; + if (Rmuon < 120. || Rmuon > 450.) + continue; + if (Zmuon < -720. || Zmuon > 720.) + continue; MuSelect = " Barrel+EndCaps"; - - if(debug_) - std::cout<<" .............. passed all cuts"<Fill(itMuon->track()->pt()); - - //histo2->Fill(itMuon->track()->outerP()); - histo2->Fill(Pt.mag()); - histo3->Fill((PI/2.-itMuon->track()->outerTheta())); - histo4->Fill(itMuon->track()->phi()); - histo5->Fill(Rmuon); - histo6->Fill(Zmuon); - histo7->Fill(RelMomResidual); - //histo8->Fill(chi); - histo8->Fill(chi_d); - - histo101->Fill(Zmuon, Rmuon); - histo101->Fill(Rt0.z(), Rt0.perp()); - histo102->Fill(Rt0.x(), Rt0.y()); - histo102->Fill(Rm.x(), Rm.y()); - - histo11->Fill(resR.mag()); - if(fabs(Nl.x()) < 0.98) histo12->Fill(resR.x()); - if(fabs(Nl.y()) < 0.98) histo13->Fill(resR.y()); - if(fabs(Nl.z()) < 0.98) histo14->Fill(resR.z()); - histo15->Fill(resP.x()); - histo16->Fill(resP.y()); - histo17->Fill(resP.z()); - - if((fabs(Nl.x()) < 0.98) && (fabs(Nl.y()) < 0.98) &&(fabs(Nl.z()) < 0.98)) - { - histo18->Fill(sqrt(C0(0,0))); - histo19->Fill(sqrt(C1(0,0))); - histo20->Fill(sqrt(C1(0,0)+Ce(0,0))); - } - if(fabs(Nl.x()) < 0.98) histo21->Fill(Vm(0)/sqrt(Cm(0,0))); - if(fabs(Nl.y()) < 0.98) histo22->Fill(Vm(1)/sqrt(Cm(1,1))); - if(fabs(Nl.z()) < 0.98) histo23->Fill(Vm(2)/sqrt(Cm(2,2))); - histo24->Fill(Vm(3)/sqrt(C1(3,3)+Ce(3,3))); - histo25->Fill(Vm(4)/sqrt(C1(4,4)+Ce(4,4))); - histo26->Fill(Vm(5)/sqrt(C1(5,5)+Ce(5,5))); - histo27->Fill(Nl.x()); - histo28->Fill(Nl.y()); - histo29->Fill(lenghtTrack); - histo30->Fill(lenghtMuon); + // ----------------------------------------------------- fill histogram + histo->Fill(itMuon->track()->pt()); + + //histo2->Fill(itMuon->track()->outerP()); + histo2->Fill(Pt.mag()); + histo3->Fill((PI / 2. - itMuon->track()->outerTheta())); + histo4->Fill(itMuon->track()->phi()); + histo5->Fill(Rmuon); + histo6->Fill(Zmuon); + histo7->Fill(RelMomResidual); + //histo8->Fill(chi); + histo8->Fill(chi_d); + + histo101->Fill(Zmuon, Rmuon); + histo101->Fill(Rt0.z(), Rt0.perp()); + histo102->Fill(Rt0.x(), Rt0.y()); + histo102->Fill(Rm.x(), Rm.y()); + + histo11->Fill(resR.mag()); + if (fabs(Nl.x()) < 0.98) + histo12->Fill(resR.x()); + if (fabs(Nl.y()) < 0.98) + histo13->Fill(resR.y()); + if (fabs(Nl.z()) < 0.98) + histo14->Fill(resR.z()); + histo15->Fill(resP.x()); + histo16->Fill(resP.y()); + histo17->Fill(resP.z()); + + if ((fabs(Nl.x()) < 0.98) && (fabs(Nl.y()) < 0.98) && (fabs(Nl.z()) < 0.98)) { + histo18->Fill(sqrt(C0(0, 0))); + histo19->Fill(sqrt(C1(0, 0))); + histo20->Fill(sqrt(C1(0, 0) + Ce(0, 0))); + } + if (fabs(Nl.x()) < 0.98) + histo21->Fill(Vm(0) / sqrt(Cm(0, 0))); + if (fabs(Nl.y()) < 0.98) + histo22->Fill(Vm(1) / sqrt(Cm(1, 1))); + if (fabs(Nl.z()) < 0.98) + histo23->Fill(Vm(2) / sqrt(Cm(2, 2))); + histo24->Fill(Vm(3) / sqrt(C1(3, 3) + Ce(3, 3))); + histo25->Fill(Vm(4) / sqrt(C1(4, 4) + Ce(4, 4))); + histo26->Fill(Vm(5) / sqrt(C1(5, 5) + Ce(5, 5))); + histo27->Fill(Nl.x()); + histo28->Fill(Nl.y()); + histo29->Fill(lenghtTrack); + histo30->Fill(lenghtMuon); histo31->Fill(chi_Loc); - histo32->Fill(Vml(1)/sqrt(Cml(1,1))); - histo33->Fill(Vml(2)/sqrt(Cml(2,2))); - histo34->Fill(Vml(3)/sqrt(Cml(3,3))); - histo35->Fill(Vml(4)/sqrt(Cml(4,4))); - - if (debug_) { //--------------------------------- debug print ---------- - - std::cout<<" diag 0[ "<outerTrack()->p()<<" " - <track()->outerP()<<" " - <<(itMuon->outerTrack()->p() - - itMuon->track()->outerP())/itMuon->track()->outerP()<Fill(Vml(1) / sqrt(Cml(1, 1))); + histo33->Fill(Vml(2) / sqrt(Cml(2, 2))); + histo34->Fill(Vml(3) / sqrt(Cml(3, 3))); + histo35->Fill(Vml(4) / sqrt(Cml(4, 4))); + + if (debug_) { //--------------------------------- debug print ---------- + + std::cout << " diag 0[ " << C0(0, 0) << " " << C0(1, 1) << " " << C0(2, 2) << " " << C0(3, 3) << " " << C0(4, 4) + << " " << C0(5, 5) << " ]" << std::endl; + std::cout << " diag e[ " << Ce(0, 0) << " " << Ce(1, 1) << " " << Ce(2, 2) << " " << Ce(3, 3) << " " << Ce(4, 4) + << " " << Ce(5, 5) << " ]" << std::endl; + std::cout << " diag 1[ " << C1(0, 0) << " " << C1(1, 1) << " " << C1(2, 2) << " " << C1(3, 3) << " " << C1(4, 4) + << " " << C1(5, 5) << " ]" << std::endl; + std::cout << " Rm " << Rm.x() << " " << Rm.y() << " " << Rm.z() << " Pm " << Pm.x() << " " << Pm.y() << " " + << Pm.z() << std::endl; + std::cout << " Rt " << Rt.x() << " " << Rt.y() << " " << Rt.z() << " Pt " << Pt.x() << " " << Pt.y() << " " + << Pt.z() << std::endl; + std::cout << " Nl*(Rm-Rt) " << Nl.dot(Rm - Rt) << std::endl; + std::cout << " resR " << resR.x() << " " << resR.y() << " " << resR.z() << " resP " << resP.x() << " " << resP.y() + << " " << resP.z() << std::endl; + std::cout << " Rm-t " << (Rm - Rt).x() << " " << (Rm - Rt).y() << " " << (Rm - Rt).z() << " Pm-t " + << (Pm - Pt).x() << " " << (Pm - Pt).y() << " " << (Pm - Pt).z() << std::endl; + std::cout << " Vm " << Vm << std::endl; + std::cout << " +- " << sqrt(Cm(0, 0)) << " " << sqrt(Cm(1, 1)) << " " << sqrt(Cm(2, 2)) << " " << sqrt(Cm(3, 3)) + << " " << sqrt(Cm(4, 4)) << " " << sqrt(Cm(5, 5)) << std::endl; + std::cout << " Pmuon Ptrack dP/Ptrack " << itMuon->outerTrack()->p() << " " << itMuon->track()->outerP() << " " + << (itMuon->outerTrack()->p() - itMuon->track()->outerP()) / itMuon->track()->outerP() << std::endl; + std::cout << " cov matrix " << std::endl; + std::cout << Cm << std::endl; + std::cout << " diag [ " << Cm(0, 0) << " " << Cm(1, 1) << " " << Cm(2, 2) << " " << Cm(3, 3) << " " << Cm(4, 4) + << " " << Cm(5, 5) << " ]" << std::endl; + AlgebraicSymMatrix66 Ro; double Diag[6]; - for(int i=0; i<=5; i++) Diag[i] = sqrt(Cm(i,i)); - for(int i=0; i<=5; i++) - for(int j=0; j<=5; j++) - Ro(i,j) = Cm(i,j)/Diag[i]/Diag[j]; - std::cout<<" correlation matrix "< gmuons; Handle smuons; - if (collectionIsolated){ - iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "TrackerOnly", tracks); - iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "StandAlone", muons); - iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "GlobalMuon", gmuons); - iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "SelectedMuons", smuons); - } - else if (collectionCosmic){ - iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "TrackerOnly", tracks); - iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "StandAlone", muons); - iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "GlobalMuon", gmuons); - iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "SelectedMuons", smuons); + if (collectionIsolated) { + iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "TrackerOnly", tracks); + iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "StandAlone", muons); + iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "GlobalMuon", gmuons); + iEvent.getByLabel("ALCARECOMuAlCalIsolatedMu", "SelectedMuons", smuons); + } else if (collectionCosmic) { + iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "TrackerOnly", tracks); + iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "StandAlone", muons); + iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "GlobalMuon", gmuons); + iEvent.getByLabel("ALCARECOMuAlGlobalCosmics", "SelectedMuons", smuons); + } else { + iEvent.getByLabel(trackTags_, tracks); + iEvent.getByLabel(muonTags_, muons); + iEvent.getByLabel(gmuonTags_, gmuons); + iEvent.getByLabel(smuonTags_, smuons); } - else{ - iEvent.getByLabel(trackTags_,tracks); - iEvent.getByLabel(muonTags_,muons); - iEvent.getByLabel(gmuonTags_,gmuons); - iEvent.getByLabel(smuonTags_,smuons); - } if (debug_) { - std::cout << " ievBunch " << iEvent.bunchCrossing() - << " runN " << (int)iEvent.run() <size() << " " <size() - << " "<size() << " " << smuons->size() << std::endl; - for (MuonCollection::const_iterator itMuon = smuons->begin(); - itMuon != smuons->end(); - ++itMuon) { - std::cout << " is isolatValid Matches " << itMuon->isIsolationValid() - << " " <isMatchesValid() << std::endl; + std::cout << " ievBunch " << iEvent.bunchCrossing() << " runN " << (int)iEvent.run() << std::endl; + std::cout << " N tracks s/amu gmu selmu " << tracks->size() << " " << muons->size() << " " << gmuons->size() << " " + << smuons->size() << std::endl; + for (MuonCollection::const_iterator itMuon = smuons->begin(); itMuon != smuons->end(); ++itMuon) { + std::cout << " is isolatValid Matches " << itMuon->isIsolationValid() << " " << itMuon->isMatchesValid() + << std::endl; } } - if (isolatedMuonMode_) { // ---- Only 1 Isolated Muon -------- - if (tracks->size() != 1) return; - if (muons->size() != 1) return; - if (gmuons->size() != 1) return; - if (smuons->size() != 1) return; + if (isolatedMuonMode_) { // ---- Only 1 Isolated Muon -------- + if (tracks->size() != 1) + return; + if (muons->size() != 1) + return; + if (gmuons->size() != 1) + return; + if (smuons->size() != 1) + return; } - - if (cosmicMuonMode_){ // ---- 1,2 Cosmic Muon -------- - if (smuons->size() > 2) return; - if (tracks->size() != smuons->size()) return; - if (muons->size() != smuons->size()) return; - if (gmuons->size() != smuons->size()) return; + + if (cosmicMuonMode_) { // ---- 1,2 Cosmic Muon -------- + if (smuons->size() > 2) + return; + if (tracks->size() != smuons->size()) + return; + if (muons->size() != smuons->size()) + return; + if (gmuons->size() != smuons->size()) + return; } - + // ok mc_isolated_mu //edm::ESHandle trackerGeometry; //iSetup.get().get(trackerGeometry); @@ -1323,14 +1337,14 @@ void GlobalTrackerMuonAlignment::analyzeTrackTrajectory // don't work //edm::ESHandle cscGeometry; //iSetup.get().get(cscGeometry); - + if (watchTrackingGeometry_.check(iSetup) || !trackingGeometry_) { edm::ESHandle trackingGeometry; iSetup.get().get(trackingGeometry); trackingGeometry_ = &*trackingGeometry; theTrackingGeometry = trackingGeometry; } - + if (watchMagneticFieldRecord_.check(iSetup) || !magneticField_) { edm::ESHandle magneticField; iSetup.get().get(magneticField); @@ -1341,128 +1355,126 @@ void GlobalTrackerMuonAlignment::analyzeTrackTrajectory edm::ESHandle globalPositionRcd; iSetup.get().get(globalPositionRcd); globalPositionRcd_ = &*globalPositionRcd; - for (std::vector::const_iterator i - = globalPositionRcd_->m_align.begin(); - i != globalPositionRcd_->m_align.end(); ++i){ - if(DetId(DetId::Tracker).rawId() == i->rawId()) iteratorTrackerRcd = i; - if(DetId(DetId::Muon).rawId() == i->rawId()) iteratorMuonRcd = i; - if(DetId(DetId::Ecal).rawId() == i->rawId()) iteratorEcalRcd = i; - if(DetId(DetId::Hcal).rawId() == i->rawId()) iteratorHcalRcd = i; + for (std::vector::const_iterator i = globalPositionRcd_->m_align.begin(); + i != globalPositionRcd_->m_align.end(); + ++i) { + if (DetId(DetId::Tracker).rawId() == i->rawId()) + iteratorTrackerRcd = i; + if (DetId(DetId::Muon).rawId() == i->rawId()) + iteratorMuonRcd = i; + if (DetId(DetId::Ecal).rawId() == i->rawId()) + iteratorEcalRcd = i; + if (DetId(DetId::Hcal).rawId() == i->rawId()) + iteratorHcalRcd = i; } - if(debug_){ - std::cout << "=== iteratorTrackerRcd " << iteratorTrackerRcd->rawId()<<" ====\n" - << " translation " << iteratorTrackerRcd->translation()<<"\n" - << " angles " << iteratorTrackerRcd->rotation().eulerAngles() << std::endl; + if (debug_) { + std::cout << "=== iteratorTrackerRcd " << iteratorTrackerRcd->rawId() << " ====\n" + << " translation " << iteratorTrackerRcd->translation() << "\n" + << " angles " << iteratorTrackerRcd->rotation().eulerAngles() << std::endl; std::cout << iteratorTrackerRcd->rotation() << std::endl; - std::cout << "=== iteratorMuonRcd " << iteratorMuonRcd->rawId()<<" ====\n" - << " translation " << iteratorMuonRcd->translation()<<"\n" - << " angles " << iteratorMuonRcd->rotation().eulerAngles() << std::endl; + std::cout << "=== iteratorMuonRcd " << iteratorMuonRcd->rawId() << " ====\n" + << " translation " << iteratorMuonRcd->translation() << "\n" + << " angles " << iteratorMuonRcd->rotation().eulerAngles() << std::endl; std::cout << iteratorMuonRcd->rotation() << std::endl; - } - } // end of GlobalPositionRcd - + } + } // end of GlobalPositionRcd + ESHandle propagator; iSetup.get().get(propagator_, propagator); - SteppingHelixPropagator alongStHePr = - SteppingHelixPropagator(magneticField_, alongMomentum); - SteppingHelixPropagator oppositeStHePr = - SteppingHelixPropagator(magneticField_, oppositeToMomentum); + SteppingHelixPropagator alongStHePr = SteppingHelixPropagator(magneticField_, alongMomentum); + SteppingHelixPropagator oppositeStHePr = SteppingHelixPropagator(magneticField_, oppositeToMomentum); //double tolerance = 5.e-5; - defaultRKPropagator::Product aprod( magneticField_, alongMomentum, 5.e-5); auto & alongRKPr = aprod.propagator; - defaultRKPropagator::Product oprod( magneticField_, oppositeToMomentum, 5.e-5); auto & oppositeRKPr = oprod.propagator; + defaultRKPropagator::Product aprod(magneticField_, alongMomentum, 5.e-5); + auto& alongRKPr = aprod.propagator; + defaultRKPropagator::Product oprod(magneticField_, oppositeToMomentum, 5.e-5); + auto& oppositeRKPr = oprod.propagator; float epsilon = 5.; - SmartPropagator alongSmPr = - SmartPropagator(alongRKPr, alongStHePr, magneticField_, alongMomentum, epsilon); - SmartPropagator oppositeSmPr = - SmartPropagator(oppositeRKPr, oppositeStHePr, magneticField_, oppositeToMomentum, epsilon); - - if(defineFitter){ - if(debug_) - std::cout<<" ............... DEFINE FITTER ..................."< builder; - iSetup.get().get("WithTrackAngle",builder); + iSetup.get().get("WithTrackAngle", builder); this->TTRHBuilder = &(*builder); this->MuRHBuilder = new MuonTransientTrackingRecHitBuilder(theTrackingGeometry); - if(debug_){ - std::cout<<" theTrackingGeometry.isValid() "< Jim's globalMuon - for(MuonCollection::const_iterator itMuon = smuons->begin(); - itMuon != smuons->end(); ++itMuon) { - - if(debug_){ - std::cout<<" mu gM is GM Mu SaM tM "<isGlobalMuon()<<" " - <isMuon()<<" "<isStandAloneMuon() - <<" "<isTrackerMuon()<<" " - < Jim's globalMuon + for (MuonCollection::const_iterator itMuon = smuons->begin(); itMuon != smuons->end(); ++itMuon) { + if (debug_) { + std::cout << " mu gM is GM Mu SaM tM " << itMuon->isGlobalMuon() << " " << itMuon->isMuon() << " " + << itMuon->isStandAloneMuon() << " " << itMuon->isTrackerMuon() << " " << std::endl; } - + // get information about the innermost muon hit ------------------------- TransientTrack muTT(itMuon->outerTrack(), magneticField_, trackingGeometry_); TrajectoryStateOnSurface innerMuTSOS = muTT.innermostMeasurementState(); TrajectoryStateOnSurface outerMuTSOS = muTT.outermostMeasurementState(); - + // get information about the outermost tracker hit ----------------------- TransientTrack trackTT(itMuon->track(), magneticField_, trackingGeometry_); TrajectoryStateOnSurface outerTrackTSOS = trackTT.outermostMeasurementState(); TrajectoryStateOnSurface innerTrackTSOS = trackTT.innermostMeasurementState(); - - GlobalPoint pointTrackIn = innerTrackTSOS.globalPosition(); + + GlobalPoint pointTrackIn = innerTrackTSOS.globalPosition(); GlobalPoint pointTrackOut = outerTrackTSOS.globalPosition(); - float lenghtTrack = (pointTrackOut-pointTrackIn).mag(); - GlobalPoint pointMuonIn = innerMuTSOS.globalPosition(); + float lenghtTrack = (pointTrackOut - pointTrackIn).mag(); + GlobalPoint pointMuonIn = innerMuTSOS.globalPosition(); GlobalPoint pointMuonOut = outerMuTSOS.globalPosition(); float lenghtMuon = (pointMuonOut - pointMuonIn).mag(); GlobalVector momentumTrackOut = outerTrackTSOS.globalMomentum(); GlobalVector momentumTrackIn = innerTrackTSOS.globalMomentum(); - float distanceInIn = (pointTrackIn - pointMuonIn).mag(); - float distanceInOut = (pointTrackIn - pointMuonOut).mag(); - float distanceOutIn = (pointTrackOut - pointMuonIn).mag(); + float distanceInIn = (pointTrackIn - pointMuonIn).mag(); + float distanceInOut = (pointTrackIn - pointMuonOut).mag(); + float distanceOutIn = (pointTrackOut - pointMuonIn).mag(); float distanceOutOut = (pointTrackOut - pointMuonOut).mag(); - if(debug_){ - std::cout<<" pointTrackIn "< - tpMuLocal(refSurface.tangentPlane(innerMuTSOS.localPosition())); + if (isolatedMuonMode_) { //------------------------------- Isolated Muon --- Out-In -- + if (debug_) + std::cout << " ------ Isolated (out-in) ----- " << std::endl; + const Surface& refSurface = innerMuTSOS.surface(); + ConstReferenceCountingPointer tpMuLocal(refSurface.tangentPlane(innerMuTSOS.localPosition())); Nl = tpMuLocal->normalVector(); - ConstReferenceCountingPointer - tpMuGlobal(refSurface.tangentPlane(innerMuTSOS.globalPosition())); + ConstReferenceCountingPointer tpMuGlobal(refSurface.tangentPlane(innerMuTSOS.globalPosition())); GlobalVector Ng = tpMuGlobal->normalVector(); Surface* surf = (Surface*)&refSurface; - const Plane* refPlane = dynamic_cast(surf); + const Plane* refPlane = dynamic_cast(surf); GlobalVector Nlp = refPlane->normalVector(); - - if(debug_){ - std::cout<<" Nlocal "<track(), - trackTT,alongMomentum,trackFittedTSOS); - if(trackFittedTSOS.isValid()) - extrapolationT = alongSmPr.propagate(trackFittedTSOS, refSurface); - } - - if(!extrapolationT.isValid()){ - if(false & alarm) - std::cout<<" !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " - //<<"\a\a\a\a\a\a\a\a"<track(), trackTT, alongMomentum, trackFittedTSOS); + if (trackFittedTSOS.isValid()) + extrapolationT = alongSmPr.propagate(trackFittedTSOS, refSurface); + } + + if (!extrapolationT.isValid()) { + if (false & alarm) + std::cout << " !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " + //<<"\a\a\a\a\a\a\a\a"<outerTrack(),muTT,oppositeToMomentum,muonFittedTSOS); + if (refitMuon_) + GlobalTrackerMuonAlignment::muonFitter(itMuon->outerTrack(), muTT, oppositeToMomentum, muonFittedTSOS); } // ------------------------------- end Isolated Muon -- Out - In --- - - - if( cosmicMuonMode_ ){ //------------------------------- Cosmic Muon ----- - - if((distanceOutIn <= distanceInOut) & (distanceOutIn <= distanceInIn) & - (distanceOutIn <= distanceOutOut)){ // ----- Out - In ------ - if(debug_) std::cout<<" ----- Out - In -----"< - tpMuGlobal(refSurface.tangentPlane(innerMuTSOS.globalPosition())); - Nl = tpMuGlobal->normalVector(); - - // extrapolation to innermost muon hit - //extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); - if(!refitTrack_) - extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); - else{ - GlobalTrackerMuonAlignment::trackFitter(itMuon->track(), - trackTT,alongMomentum,trackFittedTSOS); - if(trackFittedTSOS.isValid()) - extrapolationT = alongSmPr.propagate(trackFittedTSOS, refSurface); - } - - if(!extrapolationT.isValid()){ - if(false & alarm) - std::cout<<" !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " - //<<"\a\a\a\a\a\a\a\a"<outerTrack(),muTT,oppositeToMomentum,muonFittedTSOS); - - if(false & debug_){ - //std::cout<<" ->propDir "<propagationDirection()< - tpMuGlobal(refSurface.tangentPlane(outerMuTSOS.globalPosition())); - Nl = tpMuGlobal->normalVector(); - - // extrapolation to outermost muon hit - //extrapolationT = oppositeSmPr.propagate(innerTrackTSOS, refSurface); - if(!refitTrack_) - extrapolationT = oppositeSmPr.propagate(innerTrackTSOS, refSurface); - else{ - GlobalTrackerMuonAlignment::trackFitter(itMuon->track(), - trackTT,oppositeToMomentum,trackFittedTSOS); - if(trackFittedTSOS.isValid()) - extrapolationT = oppositeSmPr.propagate(trackFittedTSOS, refSurface); - } - - if(!extrapolationT.isValid()){ - if(false & alarm) - std::cout<<" !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " - <<"\a\a\a\a\a\a\a\a"<outerTrack(),muTT,alongMomentum,muonFittedTSOS); - - if(false & debug_){ - //std::cout<<" ->propDir "<propagationDirection()< - tpMuGlobal(refSurface.tangentPlane(outerMuTSOS.globalPosition())); - Nl = tpMuGlobal->normalVector(); - - // extrapolation to outermost muon hit - extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); - - if(!extrapolationT.isValid()){ - if(alarm) - std::cout<<" !!!!!!!!! Catastrophe Out-Out extrapolationT.isValid " - <<"\a\a\a\a\a\a\a\a"< tpMuGlobal(refSurface.tangentPlane(innerMuTSOS.globalPosition())); + Nl = tpMuGlobal->normalVector(); + + // extrapolation to innermost muon hit + //extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); + if (!refitTrack_) + extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); + else { + GlobalTrackerMuonAlignment::trackFitter(itMuon->track(), trackTT, alongMomentum, trackFittedTSOS); + if (trackFittedTSOS.isValid()) + extrapolationT = alongSmPr.propagate(trackFittedTSOS, refSurface); + } + + if (!extrapolationT.isValid()) { + if (false & alarm) + std::cout << " !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " + //<<"\a\a\a\a\a\a\a\a"<outerTrack(), muTT, oppositeToMomentum, muonFittedTSOS); + + if (false & debug_) { + //std::cout<<" ->propDir "<propagationDirection()< tpMuGlobal(refSurface.tangentPlane(outerMuTSOS.globalPosition())); + Nl = tpMuGlobal->normalVector(); + + // extrapolation to outermost muon hit + //extrapolationT = oppositeSmPr.propagate(innerTrackTSOS, refSurface); + if (!refitTrack_) + extrapolationT = oppositeSmPr.propagate(innerTrackTSOS, refSurface); + else { + GlobalTrackerMuonAlignment::trackFitter(itMuon->track(), trackTT, oppositeToMomentum, trackFittedTSOS); + if (trackFittedTSOS.isValid()) + extrapolationT = oppositeSmPr.propagate(trackFittedTSOS, refSurface); + } + + if (!extrapolationT.isValid()) { + if (false & alarm) + std::cout << " !!!!!!!!! Catastrophe Out-In extrapolationT.isValid " + << "\a\a\a\a\a\a\a\a" << extrapolationT.isValid() << std::endl; + continue; + } + if (debug_) + std::cout << " extrapolationT.isValid " << extrapolationT.isValid() << std::endl; + + tsosMuonIf = 2; + Rt = GlobalVector((extrapolationT.globalPosition()).x(), + (extrapolationT.globalPosition()).y(), + (extrapolationT.globalPosition()).z()); + + Pt = extrapolationT.globalMomentum(); + // global parameters of muon + GRm = GlobalVector( + (outerMuTSOS.globalPosition()).x(), (outerMuTSOS.globalPosition()).y(), (outerMuTSOS.globalPosition()).z()); + GPm = outerMuTSOS.globalMomentum(); + Rt0 = GlobalVector((innerTrackTSOS.globalPosition()).x(), + (innerTrackTSOS.globalPosition()).y(), + (innerTrackTSOS.globalPosition()).z()); + Cm = AlgebraicSymMatrix66(extrapolationT.cartesianError().matrix() + outerMuTSOS.cartesianError().matrix()); + C0 = AlgebraicSymMatrix66(innerTrackTSOS.cartesianError().matrix()); + Ce = AlgebraicSymMatrix66(extrapolationT.cartesianError().matrix()); + C1 = AlgebraicSymMatrix66(outerMuTSOS.cartesianError().matrix()); + + if (refitMuon_) + GlobalTrackerMuonAlignment::muonFitter(itMuon->outerTrack(), muTT, alongMomentum, muonFittedTSOS); + + if (false & debug_) { + //std::cout<<" ->propDir "<propagationDirection()< tpMuGlobal(refSurface.tangentPlane(outerMuTSOS.globalPosition())); + Nl = tpMuGlobal->normalVector(); + + // extrapolation to outermost muon hit + extrapolationT = alongSmPr.propagate(outerTrackTSOS, refSurface); + + if (!extrapolationT.isValid()) { + if (alarm) + std::cout << " !!!!!!!!! Catastrophe Out-Out extrapolationT.isValid " + << "\a\a\a\a\a\a\a\a" << extrapolationT.isValid() << std::endl; + continue; + } + if (debug_) + std::cout << " extrapolationT.isValid " << extrapolationT.isValid() << std::endl; + + tsosMuonIf = 2; + Rt = GlobalVector((extrapolationT.globalPosition()).x(), + (extrapolationT.globalPosition()).y(), + (extrapolationT.globalPosition()).z()); + + Pt = extrapolationT.globalMomentum(); + // global parameters of muon + GRm = GlobalVector( + (outerMuTSOS.globalPosition()).x(), (outerMuTSOS.globalPosition()).y(), (outerMuTSOS.globalPosition()).z()); + GPm = outerMuTSOS.globalMomentum(); + Rt0 = GlobalVector((outerTrackTSOS.globalPosition()).x(), + (outerTrackTSOS.globalPosition()).y(), + (outerTrackTSOS.globalPosition()).z()); + Cm = AlgebraicSymMatrix66(extrapolationT.cartesianError().matrix() + outerMuTSOS.cartesianError().matrix()); + C0 = AlgebraicSymMatrix66(outerTrackTSOS.cartesianError().matrix()); + Ce = AlgebraicSymMatrix66(extrapolationT.cartesianError().matrix()); + C1 = AlgebraicSymMatrix66(outerMuTSOS.cartesianError().matrix()); + + if (debug_) { + PropagationDirectionChooser Chooser; + std::cout << " propDirCh " << Chooser.operator()(*outerTrackTSOS.freeState(), refSurface) << " Ch == along " + << (alongMomentum == Chooser.operator()(*outerTrackTSOS.freeState(), refSurface)) << std::endl; + std::cout << " --- Nlocal " << Nl.x() << " " << Nl.y() << " " << Nl.z() << " " + << " alfa " << int(asin(Nl.x()) * 57.29578) << std::endl; + std::cout << " Nornal " << Nl.x() << " " << Nl.y() << " " << Nl.z() << " " + << " alfa " << int(asin(Nl.x()) * 57.29578) << std::endl; + } + } // enf of ---- Out - Out ----- + else { + if (alarm) + std::cout << " ------- !!!!!!!!!!!!!!! No proper Out - In \a\a\a\a\a\a\a" << std::endl; + continue; } - + } // ------------------------------- end Cosmic Muon ----- - - if(tsosMuonIf == 0) {if(info) {std::cout<<"No tsosMuon !!!!!!"<debugTrajectorySOS(" trackFittedTSOS ", trackFittedTSOS); + GlobalTrackerMuonAlignment::misalignMuonL(GRm, GPm, Nl, Rt, Rm, Pm, LPRm, extrapolationT, tsosMuon); + + if (refitTrack_) { + if (!trackFittedTSOS.isValid()) { + if (info) + std::cout << " ================= trackFittedTSOS notValid !!!!!!!! " << std::endl; + continue; + } + if (debug_) + this->debugTrajectorySOS(" trackFittedTSOS ", trackFittedTSOS); } - if(refitMuon_){ - if(!muonFittedTSOS.isValid()){ - if(info) std::cout<<" ================= muonFittedTSOS notValid !!!!!!!! "<debugTrajectorySOS(" muonFittedTSOS ", muonFittedTSOS); + if (refitMuon_) { + if (!muonFittedTSOS.isValid()) { + if (info) + std::cout << " ================= muonFittedTSOS notValid !!!!!!!! " << std::endl; + continue; + } + if (debug_) + this->debugTrajectorySOS(" muonFittedTSOS ", muonFittedTSOS); Rm = GlobalVector((muonFittedTSOS.globalPosition()).x(), - (muonFittedTSOS.globalPosition()).y(), - (muonFittedTSOS.globalPosition()).z()); + (muonFittedTSOS.globalPosition()).y(), + (muonFittedTSOS.globalPosition()).z()); Pm = muonFittedTSOS.globalMomentum(); LPRm = AlgebraicVector4(muonFittedTSOS.localParameters().vector()(1), - muonFittedTSOS.localParameters().vector()(2), - muonFittedTSOS.localParameters().vector()(3), - muonFittedTSOS.localParameters().vector()(4)); + muonFittedTSOS.localParameters().vector()(2), + muonFittedTSOS.localParameters().vector()(3), + muonFittedTSOS.localParameters().vector()(4)); } GlobalVector resR = Rm - Rt; GlobalVector resP0 = Pm - Pt; GlobalVector resP = Pm / Pm.mag() - Pt / Pt.mag(); - float RelMomResidual = (Pm.mag() - Pt.mag()) / (Pt.mag() + 1.e-6);; + float RelMomResidual = (Pm.mag() - Pt.mag()) / (Pt.mag() + 1.e-6); + ; AlgebraicVector6 Vm; - Vm(0) = resR.x(); Vm(1) = resR.y(); Vm(2) = resR.z(); - Vm(3) = resP0.x(); Vm(4) = resP0.y(); Vm(5) = resP0.z(); + Vm(0) = resR.x(); + Vm(1) = resR.y(); + Vm(2) = resR.z(); + Vm(3) = resP0.x(); + Vm(4) = resP0.y(); + Vm(5) = resP0.z(); float Rmuon = Rm.perp(); float Zmuon = Rm.z(); - float alfa_x = atan2(Nl.x(),Nl.y())*57.29578; - - if(debug_){ - std::cout<<" Nx Ny Nz alfa_x "< 50.) continue; // momenum cut > 50GeV //if(Pt.mag() > 100.) continue; // momenum cut > 100GeV //if(trackTT.charge() < 0) continue; // select positive charge //if(trackTT.charge() > 0) continue; // select negative charge - - //if(fabs(resR.x()) > 5.) continue; // strong cut X - //if(fabs(resR.y()) > 5.) continue; // Y + + //if(fabs(resR.x()) > 5.) continue; // strong cut X + //if(fabs(resR.y()) > 5.) continue; // Y //if(fabs(resR.z()) > 5.) continue; // Z //if(fabs(resR.mag()) > 7.5) continue; // dR //if(fabs(RelMomResidual) > 0.5) continue; - if(fabs(resR.x()) > 20.) continue; - if(fabs(resR.y()) > 20.) continue; - if(fabs(resR.z()) > 20.) continue; - if(fabs(resR.mag()) > 30.) continue; - if(fabs(resP.x()) > 0.06) continue; - if(fabs(resP.y()) > 0.06) continue; - if(fabs(resP.z()) > 0.06) continue; - if(chi_d > 40.) continue; - - // select Barrel - //if(Rmuon < 400. || Rmuon > 450.) continue; + if (fabs(resR.x()) > 20.) + continue; + if (fabs(resR.y()) > 20.) + continue; + if (fabs(resR.z()) > 20.) + continue; + if (fabs(resR.mag()) > 30.) + continue; + if (fabs(resP.x()) > 0.06) + continue; + if (fabs(resP.y()) > 0.06) + continue; + if (fabs(resP.z()) > 0.06) + continue; + if (chi_d > 40.) + continue; + + // select Barrel + //if(Rmuon < 400. || Rmuon > 450.) continue; //if(Zmuon < -600. || Zmuon > 600.) continue; - //if(fabs(Nl.z()) > 0.95) continue; + //if(fabs(Nl.z()) > 0.95) continue; //MuSelect = " Barrel"; // EndCap1 //if(Rmuon < 120. || Rmuon > 450.) continue; //if(Zmuon < -720.) continue; //if(Zmuon > -580.) continue; - //if(fabs(Nl.z()) < 0.95) continue; + //if(fabs(Nl.z()) < 0.95) continue; //MuSelect = " EndCap1"; // EndCap2 //if(Rmuon < 120. || Rmuon > 450.) continue; //if(Zmuon > 720.) continue; //if(Zmuon < 580.) continue; - //if(fabs(Nl.z()) < 0.95) continue; + //if(fabs(Nl.z()) < 0.95) continue; //MuSelect = " EndCap2"; // select All - if(Rmuon < 120. || Rmuon > 450.) continue; - if(Zmuon < -720. || Zmuon > 720.) continue; + if (Rmuon < 120. || Rmuon > 450.) + continue; + if (Zmuon < -720. || Zmuon > 720.) + continue; MuSelect = " Barrel+EndCaps"; - if(debug_) - std::cout<<" .............. passed all cuts"<Fill(itMuon->track()->pt()); - - //histo2->Fill(itMuon->track()->outerP()); - histo2->Fill(Pt.mag()); - histo3->Fill((PI/2.-itMuon->track()->outerTheta())); - histo4->Fill(itMuon->track()->phi()); - histo5->Fill(Rmuon); - histo6->Fill(Zmuon); - histo7->Fill(RelMomResidual); - //histo8->Fill(chi); - histo8->Fill(chi_d); - - histo101->Fill(Zmuon, Rmuon); - histo101->Fill(Rt0.z(), Rt0.perp()); - histo102->Fill(Rt0.x(), Rt0.y()); - histo102->Fill(Rm.x(), Rm.y()); - - histo11->Fill(resR.mag()); - if(fabs(Nl.x()) < 0.98) histo12->Fill(resR.x()); - if(fabs(Nl.y()) < 0.98) histo13->Fill(resR.y()); - if(fabs(Nl.z()) < 0.98) histo14->Fill(resR.z()); - histo15->Fill(resP.x()); - histo16->Fill(resP.y()); - histo17->Fill(resP.z()); - - if((fabs(Nl.x()) < 0.98) && (fabs(Nl.y()) < 0.98) &&(fabs(Nl.z()) < 0.98)) - { - histo18->Fill(sqrt(C0(0,0))); - histo19->Fill(sqrt(C1(0,0))); - histo20->Fill(sqrt(C1(0,0)+Ce(0,0))); - } - if(fabs(Nl.x()) < 0.98) histo21->Fill(Vm(0)/sqrt(Cm(0,0))); - if(fabs(Nl.y()) < 0.98) histo22->Fill(Vm(1)/sqrt(Cm(1,1))); - if(fabs(Nl.z()) < 0.98) histo23->Fill(Vm(2)/sqrt(Cm(2,2))); - histo24->Fill(Vm(3)/sqrt(C1(3,3)+Ce(3,3))); - histo25->Fill(Vm(4)/sqrt(C1(4,4)+Ce(4,4))); - histo26->Fill(Vm(5)/sqrt(C1(5,5)+Ce(5,5))); - histo27->Fill(Nl.x()); - histo28->Fill(Nl.y()); - histo29->Fill(lenghtTrack); - histo30->Fill(lenghtMuon); + // ----------------------------------------------------- fill histogram + histo->Fill(itMuon->track()->pt()); + + //histo2->Fill(itMuon->track()->outerP()); + histo2->Fill(Pt.mag()); + histo3->Fill((PI / 2. - itMuon->track()->outerTheta())); + histo4->Fill(itMuon->track()->phi()); + histo5->Fill(Rmuon); + histo6->Fill(Zmuon); + histo7->Fill(RelMomResidual); + //histo8->Fill(chi); + histo8->Fill(chi_d); + + histo101->Fill(Zmuon, Rmuon); + histo101->Fill(Rt0.z(), Rt0.perp()); + histo102->Fill(Rt0.x(), Rt0.y()); + histo102->Fill(Rm.x(), Rm.y()); + + histo11->Fill(resR.mag()); + if (fabs(Nl.x()) < 0.98) + histo12->Fill(resR.x()); + if (fabs(Nl.y()) < 0.98) + histo13->Fill(resR.y()); + if (fabs(Nl.z()) < 0.98) + histo14->Fill(resR.z()); + histo15->Fill(resP.x()); + histo16->Fill(resP.y()); + histo17->Fill(resP.z()); + + if ((fabs(Nl.x()) < 0.98) && (fabs(Nl.y()) < 0.98) && (fabs(Nl.z()) < 0.98)) { + histo18->Fill(sqrt(C0(0, 0))); + histo19->Fill(sqrt(C1(0, 0))); + histo20->Fill(sqrt(C1(0, 0) + Ce(0, 0))); + } + if (fabs(Nl.x()) < 0.98) + histo21->Fill(Vm(0) / sqrt(Cm(0, 0))); + if (fabs(Nl.y()) < 0.98) + histo22->Fill(Vm(1) / sqrt(Cm(1, 1))); + if (fabs(Nl.z()) < 0.98) + histo23->Fill(Vm(2) / sqrt(Cm(2, 2))); + histo24->Fill(Vm(3) / sqrt(C1(3, 3) + Ce(3, 3))); + histo25->Fill(Vm(4) / sqrt(C1(4, 4) + Ce(4, 4))); + histo26->Fill(Vm(5) / sqrt(C1(5, 5) + Ce(5, 5))); + histo27->Fill(Nl.x()); + histo28->Fill(Nl.y()); + histo29->Fill(lenghtTrack); + histo30->Fill(lenghtMuon); histo31->Fill(chi_Loc); - histo32->Fill(Vml(1)/sqrt(Cml(1,1))); - histo33->Fill(Vml(2)/sqrt(Cml(2,2))); - histo34->Fill(Vml(3)/sqrt(Cml(3,3))); - histo35->Fill(Vml(4)/sqrt(Cml(4,4))); - - if (debug_) { //--------------------------------- debug print ---------- - - std::cout<<" diag 0[ "<outerTrack()->p()<<" " - <track()->outerP()<<" " - <<(itMuon->outerTrack()->p() - - itMuon->track()->outerP())/itMuon->track()->outerP()<Fill(Vml(1) / sqrt(Cml(1, 1))); + histo33->Fill(Vml(2) / sqrt(Cml(2, 2))); + histo34->Fill(Vml(3) / sqrt(Cml(3, 3))); + histo35->Fill(Vml(4) / sqrt(Cml(4, 4))); + + if (debug_) { //--------------------------------- debug print ---------- + + std::cout << " diag 0[ " << C0(0, 0) << " " << C0(1, 1) << " " << C0(2, 2) << " " << C0(3, 3) << " " << C0(4, 4) + << " " << C0(5, 5) << " ]" << std::endl; + std::cout << " diag e[ " << Ce(0, 0) << " " << Ce(1, 1) << " " << Ce(2, 2) << " " << Ce(3, 3) << " " << Ce(4, 4) + << " " << Ce(5, 5) << " ]" << std::endl; + std::cout << " diag 1[ " << C1(0, 0) << " " << C1(1, 1) << " " << C1(2, 2) << " " << C1(3, 3) << " " << C1(4, 4) + << " " << C1(5, 5) << " ]" << std::endl; + std::cout << " Rm " << Rm.x() << " " << Rm.y() << " " << Rm.z() << " Pm " << Pm.x() << " " << Pm.y() << " " + << Pm.z() << std::endl; + std::cout << " Rt " << Rt.x() << " " << Rt.y() << " " << Rt.z() << " Pt " << Pt.x() << " " << Pt.y() << " " + << Pt.z() << std::endl; + std::cout << " Nl*(Rm-Rt) " << Nl.dot(Rm - Rt) << std::endl; + std::cout << " resR " << resR.x() << " " << resR.y() << " " << resR.z() << " resP " << resP.x() << " " << resP.y() + << " " << resP.z() << std::endl; + std::cout << " Rm-t " << (Rm - Rt).x() << " " << (Rm - Rt).y() << " " << (Rm - Rt).z() << " Pm-t " + << (Pm - Pt).x() << " " << (Pm - Pt).y() << " " << (Pm - Pt).z() << std::endl; + std::cout << " Vm " << Vm << std::endl; + std::cout << " +- " << sqrt(Cm(0, 0)) << " " << sqrt(Cm(1, 1)) << " " << sqrt(Cm(2, 2)) << " " << sqrt(Cm(3, 3)) + << " " << sqrt(Cm(4, 4)) << " " << sqrt(Cm(5, 5)) << std::endl; + std::cout << " Pmuon Ptrack dP/Ptrack " << itMuon->outerTrack()->p() << " " << itMuon->track()->outerP() << " " + << (itMuon->outerTrack()->p() - itMuon->track()->outerP()) / itMuon->track()->outerP() << std::endl; + std::cout << " cov matrix " << std::endl; + std::cout << Cm << std::endl; + std::cout << " diag [ " << Cm(0, 0) << " " << Cm(1, 1) << " " << Cm(2, 2) << " " << Cm(3, 3) << " " << Cm(4, 4) + << " " << Cm(5, 5) << " ]" << std::endl; + AlgebraicSymMatrix66 Ro; double Diag[6]; - for(int i=0; i<=5; i++) Diag[i] = sqrt(Cm(i,i)); - for(int i=0; i<=5; i++) - for(int j=0; j<=5; j++) - Ro(i,j) = Cm(i,j)/Diag[i]/Diag[j]; - std::cout<<" correlation matrix "< 1.e-20) - Wi(i) = 1./Cm(i,i); - else Wi(i) = 1.e-10; + + AlgebraicMatrix33 Jac; + AlgebraicVector3 Wi, R_m, R_t, P_t, Norm, dR; + + R_m(0) = Rm.x(); + R_m(1) = Rm.y(); + R_m(2) = Rm.z(); + R_t(0) = Rt.x(); + R_t(1) = Rt.y(); + R_t(2) = Rt.z(); + P_t(0) = Pt.x(); + P_t(1) = Pt.y(); + P_t(2) = Pt.z(); + Norm(0) = Nl.x(); + Norm(1) = Nl.y(); + Norm(2) = Nl.z(); + + for (int i = 0; i <= 2; i++) { + if (Cm(i, i) > 1.e-20) + Wi(i) = 1. / Cm(i, i); + else + Wi(i) = 1.e-10; dR(i) = R_m(i) - R_t(i); } - - float PtN = P_t(0)*Norm(0) + P_t(1)*Norm(1) + P_t(2)*Norm(2); - - Jac(0,0) = 1. - P_t(0)*Norm(0)/PtN; - Jac(0,1) = - P_t(0)*Norm(1)/PtN; - Jac(0,2) = - P_t(0)*Norm(2)/PtN; - - Jac(1,0) = - P_t(1)*Norm(0)/PtN; - Jac(1,1) = 1. - P_t(1)*Norm(1)/PtN; - Jac(1,2) = - P_t(1)*Norm(2)/PtN; - - Jac(2,0) = - P_t(2)*Norm(0)/PtN; - Jac(2,1) = - P_t(2)*Norm(1)/PtN; - Jac(2,2) = 1. - P_t(2)*Norm(2)/PtN; - + + float PtN = P_t(0) * Norm(0) + P_t(1) * Norm(1) + P_t(2) * Norm(2); + + Jac(0, 0) = 1. - P_t(0) * Norm(0) / PtN; + Jac(0, 1) = -P_t(0) * Norm(1) / PtN; + Jac(0, 2) = -P_t(0) * Norm(2) / PtN; + + Jac(1, 0) = -P_t(1) * Norm(0) / PtN; + Jac(1, 1) = 1. - P_t(1) * Norm(1) / PtN; + Jac(1, 2) = -P_t(1) * Norm(2) / PtN; + + Jac(2, 0) = -P_t(2) * Norm(0) / PtN; + Jac(2, 1) = -P_t(2) * Norm(1) / PtN; + Jac(2, 2) = 1. - P_t(2) * Norm(2) / PtN; + AlgebraicSymMatrix33 Itr; - - for(int i=0; i<=2; i++) - for(int j=0; j<=2; j++){ - if(j < i) continue; - Itr(i,j) = 0.; - //std::cout<<" ij "<= 3) w(i,j) /= PtMom; //if(j >= 3) w(i,j) /= PtMom; - if((i == j) && (i<=3) && (GCov(i-1, j-1) < 1.e-20)) w(i,j) = 1.e20; // w=0 - if(i != j) w(i,j) = 0.; // use diaginal elements + if ((i == j) && (i <= 3) && (GCov(i - 1, j - 1) < 1.e-20)) + w(i, j) = 1.e20; // w=0 + if (i != j) + w(i, j) = 0.; // use diaginal elements } //GPt /= GPt.mag(); //GPm /= GPm.mag(); // end of transform CLHEP::HepVector V(Nd), Rt(3), Pt(3), Rm(3), Pm(3), Norm(3); - Rt(1) = GRt.x(); Rt(2) = GRt.y(); Rt(3) = GRt.z(); - Pt(1) = GPt.x(); Pt(2) = GPt.y(); Pt(3) = GPt.z(); - Rm(1) = GRm.x(); Rm(2) = GRm.y(); Rm(3) = GRm.z(); - Pm(1) = GPm.x(); Pm(2) = GPm.y(); Pm(3) = GPm.z(); - Norm(1) = GNorm.x(); Norm(2) = GNorm.y(); Norm(3) = GNorm.z(); + Rt(1) = GRt.x(); + Rt(2) = GRt.y(); + Rt(3) = GRt.z(); + Pt(1) = GPt.x(); + Pt(2) = GPt.y(); + Pt(3) = GPt.z(); + Rm(1) = GRm.x(); + Rm(2) = GRm.y(); + Rm(3) = GRm.z(); + Pm(1) = GPm.x(); + Pm(2) = GPm.y(); + Pm(3) = GPm.z(); + Norm(1) = GNorm.x(); + Norm(2) = GNorm.y(); + Norm(3) = GNorm.z(); + + V = dsum(Rm - Rt, Pm - Pt); //std::cout<<" V "< 0.95) - std::cout<<" Ecap1 N "< 0.95) + std::cout << " Ecap1 N " << GNorm << std::endl; + else if (GNorm.z() < -0.95) + std::cout << " Ecap2 N " << GNorm << std::endl; else - std::cout<<" Barrel N "< 0.95) - std::cout<<" Ecap1 N "< 0.95) + std::cout << " Ecap1 N " << GNorm << std::endl; + else if (GNorm.z() < -0.95) + std::cout << " Ecap2 N " << GNorm << std::endl; else - std::cout<<" Barrel N "<debugTrackHit(" Tracker track hits ", alongTr); - this->debugTrackHit(" Tracker TransientTrack hits ", alongTTr); + + if (info) + std::cout << " ......... start of trackFitter ......... " << std::endl; + if (false && info) { + this->debugTrackHit(" Tracker track hits ", alongTr); + this->debugTrackHit(" Tracker TransientTrack hits ", alongTTr); } edm::OwnVector recHit; DetId trackDetId = DetId(alongTr->innerDetId()); - for(auto const& hit : alongTr->recHits()) recHit.push_back(hit->clone()); - if(direction != alongMomentum) - { - edm::OwnVector recHitAlong = recHit; - recHit.clear(); - for(unsigned int ihit = recHitAlong.size()-1; ihit+1>0; ihit--){ - recHit.push_back(recHitAlong[ihit]); - } - recHitAlong.clear(); + for (auto const& hit : alongTr->recHits()) + recHit.push_back(hit->clone()); + if (direction != alongMomentum) { + edm::OwnVector recHitAlong = recHit; + recHit.clear(); + for (unsigned int ihit = recHitAlong.size() - 1; ihit + 1 > 0; ihit--) { + recHit.push_back(recHitAlong[ihit]); } - if(info) - std::cout<<" ... Own recHit.size() "<recHits()) recHitTrack.push_back(TTRHBuilder->build(hit)); - - if(info) - std::cout<<" ... recHitTrack.size() "< recHitMu "<recHits()) + recHitTrack.push_back(TTRHBuilder->build(hit)); + + if (info) + std::cout << " ... recHitTrack.size() " << recHit.size() << " " << trackDetId.rawId() << " ======> recHitMu " + << std::endl; MuonTransientTrackingRecHitBuilder::ConstRecHitContainer recHitMu = recHitTrack; /* MuonTransientTrackingRecHitBuilder::ConstRecHitContainer recHitMu = MuRHBuilder->build(alongTTr.recHits().begin(), alongTTr.recHits().end()); */ - if(info) - std::cout<<" ...along.... recHitMu.size() "<0; ihit--){ + for (unsigned int ihit = recHitMuAlong.size() - 1; ihit + 1 > 0; ihit--) { recHitMu.push_back(recHitMuAlong[ihit]); } recHitMuAlong.clear(); } - if(info) - std::cout<<" ...opposite... recHitMu.size() "< trajVec; - if(direction == alongMomentum) trajVec = theFitter->fit(seedT, recHitMu, initialTSOS); - else trajVec = theFitterOp->fit(seedT, recHitMu, initialTSOS); - - if(info){ - this->debugTrajectorySOSv(" innermostTSOS of TransientTrack", - alongTTr.innermostMeasurementState()); - this->debugTrajectorySOSv(" outermostTSOS of TransientTrack", - alongTTr.outermostMeasurementState()); + if (direction == alongMomentum) + trajVec = theFitter->fit(seedT, recHitMu, initialTSOS); + else + trajVec = theFitterOp->fit(seedT, recHitMu, initialTSOS); + + if (info) { + this->debugTrajectorySOSv(" innermostTSOS of TransientTrack", alongTTr.innermostMeasurementState()); + this->debugTrajectorySOSv(" outermostTSOS of TransientTrack", alongTTr.outermostMeasurementState()); this->debugTrajectorySOS(" initialTSOS for theFitter ", initialTSOS); - std::cout<<" . . . . . trajVec.size() "<debugTrajectory(" theFitter trajectory ", trajVec[0]); + std::cout << " . . . . . trajVec.size() " << trajVec.size() << std::endl; + if (!trajVec.empty()) + this->debugTrajectory(" theFitter trajectory ", trajVec[0]); } - if(!smooth){ - if(!trajVec.empty()) trackFittedTSOS = trajVec[0].lastMeasurement().updatedState();} - else{ + if (!smooth) { + if (!trajVec.empty()) + trackFittedTSOS = trajVec[0].lastMeasurement().updatedState(); + } else { std::vector trajSVec; - if (!trajVec.empty()){ - if(direction == alongMomentum) trajSVec = theSmoother->trajectories(*(trajVec.begin())); - else trajSVec = theSmootherOp->trajectories(*(trajVec.begin())); + if (!trajVec.empty()) { + if (direction == alongMomentum) + trajSVec = theSmoother->trajectories(*(trajVec.begin())); + else + trajSVec = theSmootherOp->trajectories(*(trajVec.begin())); } - if(info) std::cout<<" . . . . trajSVec.size() "<debugTrajectorySOSv("smoothed geom InnermostState", - trajSVec[0].geometricalInnermostState()); - if(!trajSVec.empty()) trackFittedTSOS = trajSVec[0].geometricalInnermostState(); + if (info) + std::cout << " . . . . trajSVec.size() " << trajSVec.size() << std::endl; + if (!trajSVec.empty()) + this->debugTrajectorySOSv("smoothed geom InnermostState", trajSVec[0].geometricalInnermostState()); + if (!trajSVec.empty()) + trackFittedTSOS = trajSVec[0].geometricalInnermostState(); } - if(info) this->debugTrajectorySOSv(" trackFittedTSOS ", trackFittedTSOS); + if (info) + this->debugTrajectorySOSv(" trackFittedTSOS ", trackFittedTSOS); -} // end of trackFitter +} // end of trackFitter // ---- refit any direction of muon transient track ------ -void -GlobalTrackerMuonAlignment::muonFitter(reco::TrackRef alongTr, reco::TransientTrack& alongTTr, - PropagationDirection direction, - TrajectoryStateOnSurface& trackFittedTSOS) -{ +void GlobalTrackerMuonAlignment::muonFitter(reco::TrackRef alongTr, + reco::TransientTrack& alongTTr, + PropagationDirection direction, + TrajectoryStateOnSurface& trackFittedTSOS) { bool info = false; bool smooth = false; - - if(info) std::cout<<" ......... start of muonFitter ........"<debugTrackHit(" Muon track hits ", alongTr); - this->debugTrackHit(" Muon TransientTrack hits ", alongTTr); + + if (info) + std::cout << " ......... start of muonFitter ........" << std::endl; + if (false && info) { + this->debugTrackHit(" Muon track hits ", alongTr); + this->debugTrackHit(" Muon TransientTrack hits ", alongTTr); } edm::OwnVector recHit; DetId trackDetId = DetId(alongTr->innerDetId()); - for(auto const& hit : alongTr->recHits()) recHit.push_back(hit->clone()); - if(direction != alongMomentum) - { - edm::OwnVector recHitAlong = recHit; - recHit.clear(); - for(unsigned int ihit = recHitAlong.size()-1; ihit+1>0; ihit--){ - recHit.push_back(recHitAlong[ihit]); - } - recHitAlong.clear(); + for (auto const& hit : alongTr->recHits()) + recHit.push_back(hit->clone()); + if (direction != alongMomentum) { + edm::OwnVector recHitAlong = recHit; + recHit.clear(); + for (unsigned int ihit = recHitAlong.size() - 1; ihit + 1 > 0; ihit--) { + recHit.push_back(recHitAlong[ihit]); } - if(info) - std::cout<<" ... Own recHit.size() DetId==Muon "<build(alongTTr.recHitsBegin(), alongTTr.recHitsEnd()); - if(info) - std::cout<<" ...along.... recHitMu.size() "<build(alongTTr.recHitsBegin(), alongTTr.recHitsEnd()); + if (info) + std::cout << " ...along.... recHitMu.size() " << recHitMu.size() << std::endl; + if (direction != alongMomentum) { MuonTransientTrackingRecHitBuilder::ConstRecHitContainer recHitMuAlong = recHitMu; recHitMu.clear(); - for(unsigned int ihit = recHitMuAlong.size()-1; ihit+1>0; ihit--){ + for (unsigned int ihit = recHitMuAlong.size() - 1; ihit + 1 > 0; ihit--) { recHitMu.push_back(recHitMuAlong[ihit]); } recHitMuAlong.clear(); } - if(info) - std::cout<<" ...opposite... recHitMu.size() "< trajVec; - if(direction == alongMomentum) trajVec = theFitter->fit(seedT, recHitMu, initialTSOS); - else trajVec = theFitterOp->fit(seedT, recHitMu, initialTSOS); - - if(info){ - this->debugTrajectorySOSv(" innermostTSOS of TransientTrack", - alongTTr.innermostMeasurementState()); - this->debugTrajectorySOSv(" outermostTSOS of TransientTrack", - alongTTr.outermostMeasurementState()); + if (direction == alongMomentum) + trajVec = theFitter->fit(seedT, recHitMu, initialTSOS); + else + trajVec = theFitterOp->fit(seedT, recHitMu, initialTSOS); + + if (info) { + this->debugTrajectorySOSv(" innermostTSOS of TransientTrack", alongTTr.innermostMeasurementState()); + this->debugTrajectorySOSv(" outermostTSOS of TransientTrack", alongTTr.outermostMeasurementState()); this->debugTrajectorySOS(" initialTSOS for theFitter ", initialTSOS); - std::cout<<" . . . . . trajVec.size() "<debugTrajectory(" theFitter trajectory ", trajVec[0]); + std::cout << " . . . . . trajVec.size() " << trajVec.size() << std::endl; + if (!trajVec.empty()) + this->debugTrajectory(" theFitter trajectory ", trajVec[0]); } - if(!smooth){ - if(!trajVec.empty()) trackFittedTSOS = trajVec[0].lastMeasurement().updatedState();} - else{ + if (!smooth) { + if (!trajVec.empty()) + trackFittedTSOS = trajVec[0].lastMeasurement().updatedState(); + } else { std::vector trajSVec; - if (!trajVec.empty()){ - if(direction == alongMomentum) trajSVec = theSmoother->trajectories(*(trajVec.begin())); - else trajSVec = theSmootherOp->trajectories(*(trajVec.begin())); + if (!trajVec.empty()) { + if (direction == alongMomentum) + trajSVec = theSmoother->trajectories(*(trajVec.begin())); + else + trajSVec = theSmootherOp->trajectories(*(trajVec.begin())); } - if(info) std::cout<<" . . . . trajSVec.size() "<debugTrajectorySOSv("smoothed geom InnermostState", - trajSVec[0].geometricalInnermostState()); - if(!trajSVec.empty()) trackFittedTSOS = trajSVec[0].geometricalInnermostState(); + if (info) + std::cout << " . . . . trajSVec.size() " << trajSVec.size() << std::endl; + if (!trajSVec.empty()) + this->debugTrajectorySOSv("smoothed geom InnermostState", trajSVec[0].geometricalInnermostState()); + if (!trajSVec.empty()) + trackFittedTSOS = trajSVec[0].geometricalInnermostState(); } -} // end of muonFitter - +} // end of muonFitter // ---- debug printout of hits from TransientTrack ------ -void GlobalTrackerMuonAlignment::debugTrackHit(const std::string title, TransientTrack& alongTr) -{ - std::cout<<" ------- "<geographicalId().det(); - if( (*i)->geographicalId().det() == DetId::Tracker ) std::cout<<" Tracker "; - else if ( (*i)->geographicalId().det() == DetId::Muon ) std::cout<<" Muon "; - else std::cout<<" Unknown "; - if(!(*i)->isValid()) std::cout<<" not valid "<geographicalId().det(); + if ((*i)->geographicalId().det() == DetId::Tracker) + std::cout << " Tracker "; + else if ((*i)->geographicalId().det() == DetId::Muon) + std::cout << " Muon "; + else + std::cout << " Unknown "; + if (!(*i)->isValid()) + std::cout << " not valid " << std::endl; + else + std::cout << std::endl; } } - // ---- debug printout of hits from TrackRef ------ -void GlobalTrackerMuonAlignment::debugTrackHit(const std::string title, reco::TrackRef alongTr) -{ - std::cout<<" ------- "<recHits()) { - std::cout<<" Hit "<geographicalId().det(); - if( hit->geographicalId().det() == DetId::Tracker ) std::cout<<" Tracker "; - else if ( hit->geographicalId().det() == DetId::Muon ) std::cout<<" Muon "; - else std::cout<<" Unknown "; - if(!hit->isValid()) std::cout<<" not valid "<recHits()) { + std::cout << " Hit " << nHit++ << " DetId " << hit->geographicalId().det(); + if (hit->geographicalId().det() == DetId::Tracker) + std::cout << " Tracker "; + else if (hit->geographicalId().det() == DetId::Muon) + std::cout << " Muon "; + else + std::cout << " Unknown "; + if (!hit->isValid()) + std::cout << " not valid " << std::endl; + else + std::cout << std::endl; } } // ---- debug printout TrajectoryStateOnSurface ------ -void GlobalTrackerMuonAlignment::debugTrajectorySOS(const std::string title, - TrajectoryStateOnSurface& trajSOS) -{ - std::cout<<" --- "<>>>"<debugTrajectorySOSv(" firstMeasurementTSOS ",traj.firstMeasurement().updatedState()); +void GlobalTrackerMuonAlignment::debugTrajectory(const std::string title, Trajectory& traj) { + std::cout << "\n" + << " ...... " << title << " ...... " << std::endl; + if (!traj.isValid()) { + std::cout << " Not valid !!!!!!!! " << std::endl; + return; + } + std::cout << " chi2/Nhit " << traj.chiSquared() << " / " << traj.foundHits(); + if (traj.direction() == alongMomentum) + std::cout << " alongMomentum >>>>" << std::endl; + else + std::cout << " oppositeToMomentum <<<<" << std::endl; + this->debugTrajectorySOSv(" firstMeasurementTSOS ", traj.firstMeasurement().updatedState()); //this->debugTrajectorySOSv(" firstMeasurementTSOS ",traj.firstMeasurement().predictedState()); - this->debugTrajectorySOSv(" lastMeasurementTSOS ",traj.lastMeasurement().updatedState()); + this->debugTrajectorySOSv(" lastMeasurementTSOS ", traj.lastMeasurement().updatedState()); //this->debugTrajectorySOSv(" geom InnermostState", traj.geometricalInnermostState()); - std::cout<<" . . . . . . . . . . . . . . . . . . . . . . . . . . . . \n"<translation(), - iteratorTrackerRcd->rotation(), - DetId(DetId::Tracker).rawId()); + AlignTransform tracker( + iteratorTrackerRcd->translation(), iteratorTrackerRcd->rotation(), DetId(DetId::Tracker).rawId()); // Muon CLHEP::Hep3Vector posMuGlRcd = iteratorMuonRcd->translation(); CLHEP::HepRotation rotMuGlRcd = iteratorMuonRcd->rotation(); CLHEP::HepEulerAngles angMuGlRcd = iteratorMuonRcd->rotation().eulerAngles(); - if(debug_) - std::cout<<" Old muon Rcd Euler angles "<translation(), - iteratorMuonRcd->rotation(), - DetId(DetId::Muon).rawId()); - muon = muonNew; - } - else{ - std::cout<<" New + Old muon parameters are stored in Rcd"<translation(), iteratorMuonRcd->rotation(), DetId(DetId::Muon).rawId()); + muon = muonNew; + } else { + std::cout << " New + Old muon parameters are stored in Rcd" << std::endl; + CLHEP::Hep3Vector posMuGlRcdThis = CLHEP::Hep3Vector(paramVec(1), paramVec(2), paramVec(3)); + CLHEP::HepRotation rotMuGlRcdThis = CLHEP::HepRotation(colX, colY, colZ); CLHEP::Hep3Vector posMuGlRcdNew = rotMuGlRcdThis * posMuGlRcd + posMuGlRcdThis; CLHEP::HepRotation rotMuGlRcdNew = rotMuGlRcdThis * rotMuGlRcd; - AlignTransform muonNew(posMuGlRcdNew, - rotMuGlRcdNew, - DetId(DetId::Muon).rawId()); + AlignTransform muonNew(posMuGlRcdNew, rotMuGlRcdNew, DetId(DetId::Muon).rawId()); muon = muonNew; } // Ecal - AlignTransform ecal(iteratorEcalRcd->translation(), - iteratorEcalRcd->rotation(), - DetId(DetId::Ecal).rawId()); + AlignTransform ecal(iteratorEcalRcd->translation(), iteratorEcalRcd->rotation(), DetId(DetId::Ecal).rawId()); // Hcal - AlignTransform hcal(iteratorHcalRcd->translation(), - iteratorHcalRcd->rotation(), - DetId(DetId::Hcal).rawId()); + AlignTransform hcal(iteratorHcalRcd->translation(), iteratorHcalRcd->rotation(), DetId(DetId::Hcal).rawId()); // Calo - AlignTransform calo(AlignTransform::Translation(param0(1), - param0(2), - param0(3)), - AlignTransform::EulerAngles(param0(4), - param0(5), - param0(6)), - DetId(DetId::Calo).rawId()); - - std::cout << "Tracker (" << tracker.rawId() << ") at " << tracker.translation() - << " " << tracker.rotation().eulerAngles() << std::endl; + AlignTransform calo(AlignTransform::Translation(param0(1), param0(2), param0(3)), + AlignTransform::EulerAngles(param0(4), param0(5), param0(6)), + DetId(DetId::Calo).rawId()); + + std::cout << "Tracker (" << tracker.rawId() << ") at " << tracker.translation() << " " + << tracker.rotation().eulerAngles() << std::endl; std::cout << tracker.rotation() << std::endl; - - std::cout << "Muon (" << muon.rawId() << ") at " << muon.translation() - << " " << muon.rotation().eulerAngles() << std::endl; + + std::cout << "Muon (" << muon.rawId() << ") at " << muon.translation() << " " << muon.rotation().eulerAngles() + << std::endl; std::cout << " rotations angles around x,y,z " - << " ( " << -muon.rotation().zy() << " " << muon.rotation().zx() - << " " << -muon.rotation().yx() << " )" << std::endl; - std::cout << muon.rotation() << std::endl; - - std::cout << "Ecal (" << ecal.rawId() << ") at " << ecal.translation() - << " " << ecal.rotation().eulerAngles() << std::endl; - std::cout << ecal.rotation() << std::endl; - - std::cout << "Hcal (" << hcal.rawId() << ") at " << hcal.translation() - << " " << hcal.rotation().eulerAngles() << std::endl; - std::cout << hcal.rotation() << std::endl; - - std::cout << "Calo (" << calo.rawId() << ") at " << calo.translation() - << " " << calo.rotation().eulerAngles() << std::endl; - std::cout << calo.rotation() << std::endl; - - globalPositions->m_align.push_back(tracker); - globalPositions->m_align.push_back(muon); - globalPositions->m_align.push_back(ecal); - globalPositions->m_align.push_back(hcal); - globalPositions->m_align.push_back(calo); - - std::cout << "Uploading to the database..." << std::endl; - - edm::Service poolDbService; - - if (!poolDbService.isAvailable()) - throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; - - // if (poolDbService->isNewTagRequest("GlobalPositionRcd")) { -// poolDbService->createNewIOV(&(*globalPositions), poolDbService->endOfTime(), "GlobalPositionRcd"); -// } else { -// poolDbService->appendSinceTime(&(*globalPositions), poolDbService->currentTime(), "GlobalPositionRcd"); -// } - poolDbService->writeOne(&(*globalPositions), - poolDbService->currentTime(), - //poolDbService->beginOfTime(), - "GlobalPositionRcd"); - std::cout << "done!" << std::endl; - - return; -} + << " ( " << -muon.rotation().zy() << " " << muon.rotation().zx() << " " << -muon.rotation().yx() << " )" + << std::endl; + std::cout << muon.rotation() << std::endl; + + std::cout << "Ecal (" << ecal.rawId() << ") at " << ecal.translation() << " " << ecal.rotation().eulerAngles() + << std::endl; + std::cout << ecal.rotation() << std::endl; + + std::cout << "Hcal (" << hcal.rawId() << ") at " << hcal.translation() << " " << hcal.rotation().eulerAngles() + << std::endl; + std::cout << hcal.rotation() << std::endl; + + std::cout << "Calo (" << calo.rawId() << ") at " << calo.translation() << " " << calo.rotation().eulerAngles() + << std::endl; + std::cout << calo.rotation() << std::endl; + + globalPositions->m_align.push_back(tracker); + globalPositions->m_align.push_back(muon); + globalPositions->m_align.push_back(ecal); + globalPositions->m_align.push_back(hcal); + globalPositions->m_align.push_back(calo); + + std::cout << "Uploading to the database..." << std::endl; + + edm::Service poolDbService; + + if (!poolDbService.isAvailable()) + throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; + + // if (poolDbService->isNewTagRequest("GlobalPositionRcd")) { + // poolDbService->createNewIOV(&(*globalPositions), poolDbService->endOfTime(), "GlobalPositionRcd"); + // } else { + // poolDbService->appendSinceTime(&(*globalPositions), poolDbService->currentTime(), "GlobalPositionRcd"); + // } + poolDbService->writeOne(&(*globalPositions), + poolDbService->currentTime(), + //poolDbService->beginOfTime(), + "GlobalPositionRcd"); + std::cout << "done!" << std::endl; + return; +} //define this as a plug-in DEFINE_FWK_MODULE(GlobalTrackerMuonAlignment); diff --git a/Alignment/CommonAlignmentProducer/plugins/LSNumberFilter.cc b/Alignment/CommonAlignmentProducer/plugins/LSNumberFilter.cc index 3663152367c4f..cb29ee14d6376 100644 --- a/Alignment/CommonAlignmentProducer/plugins/LSNumberFilter.cc +++ b/Alignment/CommonAlignmentProducer/plugins/LSNumberFilter.cc @@ -10,67 +10,48 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" - - // // class declaration // - - class LSNumberFilter : public edm::EDFilter { public: explicit LSNumberFilter(const edm::ParameterSet&); ~LSNumberFilter() override; private: - - void beginJob() override ; + void beginJob() override; bool filter(edm::Event&, const edm::EventSetup&) override; - void endJob() override ; + void endJob() override; unsigned int minLS; }; +LSNumberFilter::LSNumberFilter(const edm::ParameterSet& iConfig) + : minLS(iConfig.getUntrackedParameter("minLS", 21)) {} - -LSNumberFilter::LSNumberFilter(const edm::ParameterSet& iConfig): - minLS(iConfig.getUntrackedParameter("minLS",21)) -{} - - -LSNumberFilter::~LSNumberFilter() -{ - - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) - +LSNumberFilter::~LSNumberFilter() { + // do anything here that needs to be done at desctruction time + // (e.g. close files, deallocate resources etc.) } - // // member functions // // ------------ method called on each new Event ------------ -bool LSNumberFilter::filter(edm::Event& iEvent, - const edm::EventSetup& iSetup) { +bool LSNumberFilter::filter(edm::Event& iEvent, const edm::EventSetup& iSetup) { + if (iEvent.luminosityBlock() < minLS) + return false; - if(iEvent.luminosityBlock() < minLS) return false; - return true; - } // ------------ method called once each job just before starting event loop ------------ -void -LSNumberFilter::beginJob() -{} +void LSNumberFilter::beginJob() {} // ------------ method called once each job just after ending the event loop ------------ -void -LSNumberFilter::endJob() { -} +void LSNumberFilter::endJob() {} //define this as a plug-in DEFINE_FWK_MODULE(LSNumberFilter); diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentCSCBeamHaloSelector.cc b/Alignment/CommonAlignmentProducer/src/AlignmentCSCBeamHaloSelector.cc index 6d90bad37ac4d..6c5a325fdf700 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentCSCBeamHaloSelector.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentCSCBeamHaloSelector.cc @@ -11,12 +11,12 @@ // constructor ---------------------------------------------------------------- -AlignmentCSCBeamHaloSelector::AlignmentCSCBeamHaloSelector(const edm::ParameterSet &iConfig, edm::ConsumesCollector & iC) - : m_minStations(iConfig.getParameter("minStations")) - , m_minHitsPerStation(iConfig.getParameter("minHitsPerStation")) -{ - edm::LogInfo("AlignmentCSCBeamHaloSelector") - << "Acceptable tracks must have at least " << m_minHitsPerStation << " hits in " << m_minStations << " different CSC stations." << std::endl; +AlignmentCSCBeamHaloSelector::AlignmentCSCBeamHaloSelector(const edm::ParameterSet &iConfig, edm::ConsumesCollector &iC) + : m_minStations(iConfig.getParameter("minStations")), + m_minHitsPerStation(iConfig.getParameter("minHitsPerStation")) { + edm::LogInfo("AlignmentCSCBeamHaloSelector") + << "Acceptable tracks must have at least " << m_minHitsPerStation << " hits in " << m_minStations + << " different CSC stations." << std::endl; } // destructor ----------------------------------------------------------------- @@ -25,35 +25,38 @@ AlignmentCSCBeamHaloSelector::~AlignmentCSCBeamHaloSelector() {} // do selection --------------------------------------------------------------- -AlignmentCSCBeamHaloSelector::Tracks -AlignmentCSCBeamHaloSelector::select(const Tracks &tracks, const edm::Event &iEvent) const { - Tracks result; - - for(auto const& track : tracks) { - std::map station_map; - - for(auto const& hit : track->recHits()) { - DetId id = hit->geographicalId(); - if (id.det() == DetId::Muon && id.subdetId() == MuonSubdetId::CSC) { - CSCDetId cscid(id.rawId()); - int station = (cscid.endcap() == 1 ? 1 : -1) * cscid.station(); - - std::map::const_iterator station_iter = station_map.find(station); - if (station_iter == station_map.end()) { - station_map[station] = 0; - } - station_map[station]++; - } // end if it's a CSC hit - } // end loop over hits - - unsigned int stations = 0; - for (std::map::const_iterator station_iter = station_map.begin(); station_iter != station_map.end(); ++station_iter) { - if (station_iter->second > m_minHitsPerStation) stations++; - } - if (stations >= m_minStations) { - result.push_back(track); - } - } // end loop over tracks - - return result; +AlignmentCSCBeamHaloSelector::Tracks AlignmentCSCBeamHaloSelector::select(const Tracks &tracks, + const edm::Event &iEvent) const { + Tracks result; + + for (auto const &track : tracks) { + std::map station_map; + + for (auto const &hit : track->recHits()) { + DetId id = hit->geographicalId(); + if (id.det() == DetId::Muon && id.subdetId() == MuonSubdetId::CSC) { + CSCDetId cscid(id.rawId()); + int station = (cscid.endcap() == 1 ? 1 : -1) * cscid.station(); + + std::map::const_iterator station_iter = station_map.find(station); + if (station_iter == station_map.end()) { + station_map[station] = 0; + } + station_map[station]++; + } // end if it's a CSC hit + } // end loop over hits + + unsigned int stations = 0; + for (std::map::const_iterator station_iter = station_map.begin(); + station_iter != station_map.end(); + ++station_iter) { + if (station_iter->second > m_minHitsPerStation) + stations++; + } + if (stations >= m_minStations) { + result.push_back(track); + } + } // end loop over tracks + + return result; } diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentCSCOverlapSelector.cc b/Alignment/CommonAlignmentProducer/src/AlignmentCSCOverlapSelector.cc index d15876505ac6b..a8edd189e46ee 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentCSCOverlapSelector.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentCSCOverlapSelector.cc @@ -12,17 +12,15 @@ // constructor ---------------------------------------------------------------- AlignmentCSCOverlapSelector::AlignmentCSCOverlapSelector(const edm::ParameterSet &iConfig) - : m_station(iConfig.getParameter("station")) - , m_minHitsPerChamber(iConfig.getParameter("minHitsPerChamber")) -{ - if (m_station == 0) { - edm::LogInfo("AlignmentCSCOverlapSelector") - << "Acceptable tracks must have " << m_minHitsPerChamber << " in two chambers on all stations." << std::endl; - } - else { - edm::LogInfo("AlignmentCSCOverlapSelector") - << "Acceptable tracks must have " << m_minHitsPerChamber << " in two chambers on station " << m_station << "." << std::endl; - } + : m_station(iConfig.getParameter("station")), + m_minHitsPerChamber(iConfig.getParameter("minHitsPerChamber")) { + if (m_station == 0) { + edm::LogInfo("AlignmentCSCOverlapSelector") + << "Acceptable tracks must have " << m_minHitsPerChamber << " in two chambers on all stations." << std::endl; + } else { + edm::LogInfo("AlignmentCSCOverlapSelector") << "Acceptable tracks must have " << m_minHitsPerChamber + << " in two chambers on station " << m_station << "." << std::endl; + } } // destructor ----------------------------------------------------------------- @@ -31,97 +29,115 @@ AlignmentCSCOverlapSelector::~AlignmentCSCOverlapSelector() {} // do selection --------------------------------------------------------------- -AlignmentCSCOverlapSelector::Tracks -AlignmentCSCOverlapSelector::select(const Tracks &tracks, const edm::Event &iEvent) const { - Tracks result; - - for(auto const& track : tracks) { - unsigned int MEminus4_even = 0; - unsigned int MEminus4_odd = 0; - unsigned int MEminus3_even = 0; - unsigned int MEminus3_odd = 0; - unsigned int MEminus2_even = 0; - unsigned int MEminus2_odd = 0; - unsigned int MEminus1_even = 0; - unsigned int MEminus1_odd = 0; - - unsigned int MEplus1_even = 0; - unsigned int MEplus1_odd = 0; - unsigned int MEplus2_even = 0; - unsigned int MEplus2_odd = 0; - unsigned int MEplus3_even = 0; - unsigned int MEplus3_odd = 0; - unsigned int MEplus4_even = 0; - unsigned int MEplus4_odd = 0; - - for(auto const& hit : track->recHits()) { - DetId id = hit->geographicalId(); - if (id.det() == DetId::Muon && id.subdetId() == MuonSubdetId::CSC) { - CSCDetId cscid(id.rawId()); - int station = (cscid.endcap() == 1 ? 1 : -1) * cscid.station(); - - if (station == -4) { - if (cscid.chamber() % 2 == 0) MEminus4_even++; - else MEminus4_odd++; - } - else if (station == -3) { - if (cscid.chamber() % 2 == 0) MEminus3_even++; - else MEminus3_odd++; - } - else if (station == -2) { - if (cscid.chamber() % 2 == 0) MEminus2_even++; - else MEminus2_odd++; - } - else if (station == -1) { - if (cscid.chamber() % 2 == 0) MEminus1_even++; - else MEminus1_odd++; - } - - else if (station == 1) { - if (cscid.chamber() % 2 == 0) MEplus1_even++; - else MEplus1_odd++; - } - else if (station == 2) { - if (cscid.chamber() % 2 == 0) MEplus2_even++; - else MEplus2_odd++; - } - else if (station == 3) { - if (cscid.chamber() % 2 == 0) MEplus3_even++; - else MEplus3_odd++; - } - else if (station == 4) { - if (cscid.chamber() % 2 == 0) MEplus4_even++; - else MEplus4_odd++; - } - - } // end if it's a CSC hit - } // end loop over hits - - if ((m_station == 0 || m_station == -4) && - (MEminus4_even >= m_minHitsPerChamber) && (MEminus4_odd >= m_minHitsPerChamber)) result.push_back(track); - - else if ((m_station == 0 || m_station == -3) && - (MEminus3_even >= m_minHitsPerChamber) && (MEminus3_odd >= m_minHitsPerChamber)) result.push_back(track); - - else if ((m_station == 0 || m_station == -2) && - (MEminus2_even >= m_minHitsPerChamber) && (MEminus2_odd >= m_minHitsPerChamber)) result.push_back(track); - - else if ((m_station == 0 || m_station == -1) && - (MEminus1_even >= m_minHitsPerChamber) && (MEminus1_odd >= m_minHitsPerChamber)) result.push_back(track); - - else if ((m_station == 0 || m_station == 1) && - (MEplus1_even >= m_minHitsPerChamber) && (MEplus1_odd >= m_minHitsPerChamber)) result.push_back(track); - - else if ((m_station == 0 || m_station == 2) && - (MEplus2_even >= m_minHitsPerChamber) && (MEplus2_odd >= m_minHitsPerChamber)) result.push_back(track); - - else if ((m_station == 0 || m_station == 3) && - (MEplus3_even >= m_minHitsPerChamber) && (MEplus3_odd >= m_minHitsPerChamber)) result.push_back(track); - - else if ((m_station == 0 || m_station == 4) && - (MEplus4_even >= m_minHitsPerChamber) && (MEplus4_odd >= m_minHitsPerChamber)) result.push_back(track); - - } // end loop over tracks - - return result; +AlignmentCSCOverlapSelector::Tracks AlignmentCSCOverlapSelector::select(const Tracks &tracks, + const edm::Event &iEvent) const { + Tracks result; + + for (auto const &track : tracks) { + unsigned int MEminus4_even = 0; + unsigned int MEminus4_odd = 0; + unsigned int MEminus3_even = 0; + unsigned int MEminus3_odd = 0; + unsigned int MEminus2_even = 0; + unsigned int MEminus2_odd = 0; + unsigned int MEminus1_even = 0; + unsigned int MEminus1_odd = 0; + + unsigned int MEplus1_even = 0; + unsigned int MEplus1_odd = 0; + unsigned int MEplus2_even = 0; + unsigned int MEplus2_odd = 0; + unsigned int MEplus3_even = 0; + unsigned int MEplus3_odd = 0; + unsigned int MEplus4_even = 0; + unsigned int MEplus4_odd = 0; + + for (auto const &hit : track->recHits()) { + DetId id = hit->geographicalId(); + if (id.det() == DetId::Muon && id.subdetId() == MuonSubdetId::CSC) { + CSCDetId cscid(id.rawId()); + int station = (cscid.endcap() == 1 ? 1 : -1) * cscid.station(); + + if (station == -4) { + if (cscid.chamber() % 2 == 0) + MEminus4_even++; + else + MEminus4_odd++; + } else if (station == -3) { + if (cscid.chamber() % 2 == 0) + MEminus3_even++; + else + MEminus3_odd++; + } else if (station == -2) { + if (cscid.chamber() % 2 == 0) + MEminus2_even++; + else + MEminus2_odd++; + } else if (station == -1) { + if (cscid.chamber() % 2 == 0) + MEminus1_even++; + else + MEminus1_odd++; + } + + else if (station == 1) { + if (cscid.chamber() % 2 == 0) + MEplus1_even++; + else + MEplus1_odd++; + } else if (station == 2) { + if (cscid.chamber() % 2 == 0) + MEplus2_even++; + else + MEplus2_odd++; + } else if (station == 3) { + if (cscid.chamber() % 2 == 0) + MEplus3_even++; + else + MEplus3_odd++; + } else if (station == 4) { + if (cscid.chamber() % 2 == 0) + MEplus4_even++; + else + MEplus4_odd++; + } + + } // end if it's a CSC hit + } // end loop over hits + + if ((m_station == 0 || m_station == -4) && (MEminus4_even >= m_minHitsPerChamber) && + (MEminus4_odd >= m_minHitsPerChamber)) + result.push_back(track); + + else if ((m_station == 0 || m_station == -3) && (MEminus3_even >= m_minHitsPerChamber) && + (MEminus3_odd >= m_minHitsPerChamber)) + result.push_back(track); + + else if ((m_station == 0 || m_station == -2) && (MEminus2_even >= m_minHitsPerChamber) && + (MEminus2_odd >= m_minHitsPerChamber)) + result.push_back(track); + + else if ((m_station == 0 || m_station == -1) && (MEminus1_even >= m_minHitsPerChamber) && + (MEminus1_odd >= m_minHitsPerChamber)) + result.push_back(track); + + else if ((m_station == 0 || m_station == 1) && (MEplus1_even >= m_minHitsPerChamber) && + (MEplus1_odd >= m_minHitsPerChamber)) + result.push_back(track); + + else if ((m_station == 0 || m_station == 2) && (MEplus2_even >= m_minHitsPerChamber) && + (MEplus2_odd >= m_minHitsPerChamber)) + result.push_back(track); + + else if ((m_station == 0 || m_station == 3) && (MEplus3_even >= m_minHitsPerChamber) && + (MEplus3_odd >= m_minHitsPerChamber)) + result.push_back(track); + + else if ((m_station == 0 || m_station == 4) && (MEplus4_even >= m_minHitsPerChamber) && + (MEplus4_odd >= m_minHitsPerChamber)) + result.push_back(track); + + } // end loop over tracks + + return result; } diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentCSCTrackSelector.cc b/Alignment/CommonAlignmentProducer/src/AlignmentCSCTrackSelector.cc index 13eff7639ea92..545258e38ea53 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentCSCTrackSelector.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentCSCTrackSelector.cc @@ -10,65 +10,65 @@ #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/MuonDetId/interface/CSCDetId.h" - // constructor ---------------------------------------------------------------- -AlignmentCSCTrackSelector::AlignmentCSCTrackSelector(const edm::ParameterSet & cfg) - : m_src(cfg.getParameter("src")) - , m_stationA(cfg.getParameter("stationA")) - , m_stationB(cfg.getParameter("stationB")) - , m_minHitsDT(cfg.getParameter("minHitsDT")) - , m_minHitsPerStation(cfg.getParameter("minHitsPerStation")) - , m_maxHitsPerStation(cfg.getParameter("maxHitsPerStation")) -{} +AlignmentCSCTrackSelector::AlignmentCSCTrackSelector(const edm::ParameterSet& cfg) + : m_src(cfg.getParameter("src")), + m_stationA(cfg.getParameter("stationA")), + m_stationB(cfg.getParameter("stationB")), + m_minHitsDT(cfg.getParameter("minHitsDT")), + m_minHitsPerStation(cfg.getParameter("minHitsPerStation")), + m_maxHitsPerStation(cfg.getParameter("maxHitsPerStation")) {} // destructor ----------------------------------------------------------------- -AlignmentCSCTrackSelector::~AlignmentCSCTrackSelector() -{} - +AlignmentCSCTrackSelector::~AlignmentCSCTrackSelector() {} // do selection --------------------------------------------------------------- -AlignmentCSCTrackSelector::Tracks -AlignmentCSCTrackSelector::select(const Tracks& tracks, const edm::Event& evt) const -{ - Tracks result; - - for(auto const& track : tracks) { - int hitsOnStationA = 0; - int hitsOnStationB = 0; - - for(auto const& hit : track->recHits()) { - DetId id = hit->geographicalId(); - - if (id.det() == DetId::Muon && id.subdetId() == MuonSubdetId::DT) { - if (m_stationA == 0) hitsOnStationA++; - if (m_stationB == 0) hitsOnStationB++; - } - else if (id.det() == DetId::Muon && id.subdetId() == MuonSubdetId::CSC) { - CSCDetId cscid(id.rawId()); - int station = (cscid.endcap() == 1 ? 1 : -1) * cscid.station(); - - if (station == m_stationA) hitsOnStationA++; - if (station == m_stationB) hitsOnStationB++; - - } // end if CSC - } // end loop over hits - - bool stationAokay; - if (m_stationA == 0) stationAokay = (m_minHitsDT <= hitsOnStationA); - else stationAokay = (m_minHitsPerStation <= hitsOnStationA && hitsOnStationA <= m_maxHitsPerStation); - - bool stationBokay; - if (m_stationB == 0) stationBokay = (m_minHitsDT <= hitsOnStationB); - else stationBokay = (m_minHitsPerStation <= hitsOnStationB && hitsOnStationB <= m_maxHitsPerStation); - - if (stationAokay && stationBokay) { - result.push_back(track); - } - } // end loop over tracks - - return result; +AlignmentCSCTrackSelector::Tracks AlignmentCSCTrackSelector::select(const Tracks& tracks, const edm::Event& evt) const { + Tracks result; + + for (auto const& track : tracks) { + int hitsOnStationA = 0; + int hitsOnStationB = 0; + + for (auto const& hit : track->recHits()) { + DetId id = hit->geographicalId(); + + if (id.det() == DetId::Muon && id.subdetId() == MuonSubdetId::DT) { + if (m_stationA == 0) + hitsOnStationA++; + if (m_stationB == 0) + hitsOnStationB++; + } else if (id.det() == DetId::Muon && id.subdetId() == MuonSubdetId::CSC) { + CSCDetId cscid(id.rawId()); + int station = (cscid.endcap() == 1 ? 1 : -1) * cscid.station(); + + if (station == m_stationA) + hitsOnStationA++; + if (station == m_stationB) + hitsOnStationB++; + + } // end if CSC + } // end loop over hits + + bool stationAokay; + if (m_stationA == 0) + stationAokay = (m_minHitsDT <= hitsOnStationA); + else + stationAokay = (m_minHitsPerStation <= hitsOnStationA && hitsOnStationA <= m_maxHitsPerStation); + + bool stationBokay; + if (m_stationB == 0) + stationBokay = (m_minHitsDT <= hitsOnStationB); + else + stationBokay = (m_minHitsPerStation <= hitsOnStationB && hitsOnStationB <= m_maxHitsPerStation); + + if (stationAokay && stationBokay) { + result.push_back(track); + } + } // end loop over tracks + + return result; } - diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentGlobalTrackSelector.cc b/Alignment/CommonAlignmentProducer/src/AlignmentGlobalTrackSelector.cc index 940a496625394..a6d82272e3465 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentGlobalTrackSelector.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentGlobalTrackSelector.cc @@ -12,7 +12,7 @@ #include -#include //for the get() Call +#include //for the get() Call #include @@ -21,85 +21,76 @@ #include "Alignment/CommonAlignmentProducer/interface/AlignmentGlobalTrackSelector.h" - using namespace std; -using namespace edm; +using namespace edm; // constructor ---------------------------------------------------------------- -AlignmentGlobalTrackSelector::AlignmentGlobalTrackSelector(const edm::ParameterSet & cfg, edm::ConsumesCollector& iC) : - theGMFilterSwitch(cfg.getParameter("applyGlobalMuonFilter")), - theIsoFilterSwitch(cfg.getParameter("applyIsolationtest")), - theJetCountFilterSwitch(cfg.getParameter("applyJetCountFilter")) -{ +AlignmentGlobalTrackSelector::AlignmentGlobalTrackSelector(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC) + : theGMFilterSwitch(cfg.getParameter("applyGlobalMuonFilter")), + theIsoFilterSwitch(cfg.getParameter("applyIsolationtest")), + theJetCountFilterSwitch(cfg.getParameter("applyJetCountFilter")) { if (theGMFilterSwitch || theIsoFilterSwitch || theJetCountFilterSwitch) LogDebug("Alignment") << "> applying global Trackfilter ..."; if (theGMFilterSwitch) { edm::InputTag theMuonSource = cfg.getParameter("muonSource"); theMuonToken = iC.consumes(theMuonSource); - theMaxTrackDeltaR =cfg.getParameter("maxTrackDeltaR"); + theMaxTrackDeltaR = cfg.getParameter("maxTrackDeltaR"); theMinGlobalMuonCount = cfg.getParameter("minGlobalMuonCount"); - LogDebug("Alignment") << "> GlobalMuonFilter : source, maxTrackDeltaR, min. Count : " - << theMuonSource << " , " - << theMaxTrackDeltaR << " , " - << theMinIsolatedCount; + LogDebug("Alignment") << "> GlobalMuonFilter : source, maxTrackDeltaR, min. Count : " << theMuonSource + << " , " << theMaxTrackDeltaR << " , " << theMinIsolatedCount; } - + if (theIsoFilterSwitch) { edm::InputTag theJetIsoSource = cfg.getParameter("jetIsoSource"); theJetIsoToken = iC.consumes(theJetIsoSource); theMaxJetPt = cfg.getParameter("maxJetPt"); theMinJetDeltaR = cfg.getParameter("minJetDeltaR"); theMinIsolatedCount = cfg.getParameter("minIsolatedCount"); - LogDebug("Alignment") << "> Isolationtest : source, maxJetPt, minJetDeltaR, min. Count: " - << theJetIsoSource << " , " - << theMaxJetPt << " ," - << theMinJetDeltaR << " ," - << theMinGlobalMuonCount; + LogDebug("Alignment") << "> Isolationtest : source, maxJetPt, minJetDeltaR, min. Count: " << theJetIsoSource + << " , " << theMaxJetPt << " ," << theMinJetDeltaR << " ," << theMinGlobalMuonCount; } - + if (theJetCountFilterSwitch) { edm::InputTag theJetCountSource = cfg.getParameter("jetCountSource"); theJetCountToken = iC.consumes(theJetCountSource); theMinJetPt = cfg.getParameter("minJetPt"); theMaxJetCount = cfg.getParameter("maxJetCount"); - LogDebug("Alignment") << "> JetCountFilter : source, minJetPt, maxJetCount : " - << theJetCountSource << " , " - << theMinJetPt << " ," - << theMaxJetCount; + LogDebug("Alignment") << "> JetCountFilter : source, minJetPt, maxJetCount : " << theJetCountSource + << " , " << theMinJetPt << " ," << theMaxJetCount; } } // destructor ----------------------------------------------------------------- -AlignmentGlobalTrackSelector::~AlignmentGlobalTrackSelector() -{} +AlignmentGlobalTrackSelector::~AlignmentGlobalTrackSelector() {} ///returns if any of the Filters is used. -bool AlignmentGlobalTrackSelector::useThisFilter() -{ - return theGMFilterSwitch || theIsoFilterSwitch|| theJetCountFilterSwitch; +bool AlignmentGlobalTrackSelector::useThisFilter() { + return theGMFilterSwitch || theIsoFilterSwitch || theJetCountFilterSwitch; } // do selection --------------------------------------------------------------- -AlignmentGlobalTrackSelector::Tracks -AlignmentGlobalTrackSelector::select(const Tracks& tracks, const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +AlignmentGlobalTrackSelector::Tracks AlignmentGlobalTrackSelector::select(const Tracks& tracks, + const edm::Event& iEvent, + const edm::EventSetup& iSetup) { Tracks result = tracks; - if (theGMFilterSwitch) result = findMuons(result, iEvent); - if (theIsoFilterSwitch) result = checkIsolation(result, iEvent); - if (theJetCountFilterSwitch) result = checkJetCount(result, iEvent); + if (theGMFilterSwitch) + result = findMuons(result, iEvent); + if (theIsoFilterSwitch) + result = checkIsolation(result, iEvent); + if (theJetCountFilterSwitch) + result = checkJetCount(result, iEvent); LogDebug("Alignment") << "> Global: tracks all, kept: " << tracks.size() << ", " << result.size(); -// LogDebug("Alignment")<<"> o kept:"; -// printTracks(result); - + // LogDebug("Alignment")<<"> o kept:"; + // printTracks(result); + return result; } ///filter for Tracks that match the Track of a global Muon -AlignmentGlobalTrackSelector::Tracks -AlignmentGlobalTrackSelector::findMuons(const Tracks& tracks, const edm::Event& iEvent) const -{ +AlignmentGlobalTrackSelector::Tracks AlignmentGlobalTrackSelector::findMuons(const Tracks& tracks, + const edm::Event& iEvent) const { Tracks result; Tracks globalMuons; @@ -108,78 +99,72 @@ AlignmentGlobalTrackSelector::findMuons(const Tracks& tracks, const edm::Event& iEvent.getByToken(theMuonToken, muons); if (muons.isValid()) { - for (reco::MuonCollection::const_iterator itMuon = muons->begin(); - itMuon != muons->end(); - ++itMuon) { + for (reco::MuonCollection::const_iterator itMuon = muons->begin(); itMuon != muons->end(); ++itMuon) { const reco::Track* muonTrack = (*itMuon).get().get(); if (!muonTrack) { - LogDebug("Alignment") << "@SUB=AlignmentGlobalTrackSelector::findMuons" - << "Found muon without track: Standalone Muon!"; + LogDebug("Alignment") << "@SUB=AlignmentGlobalTrackSelector::findMuons" + << "Found muon without track: Standalone Muon!"; } else { - globalMuons.push_back(muonTrack); + globalMuons.push_back(muonTrack); } } } else { LogError("Alignment") << "@SUB=AlignmentGlobalTrackSelector::findMuons" - <<"> could not optain mounCollection!"; + << "> could not optain mounCollection!"; } result = this->matchTracks(tracks, globalMuons); - - if (static_cast(result.size()) < theMinGlobalMuonCount) result.clear(); + + if (static_cast(result.size()) < theMinGlobalMuonCount) + result.clear(); return result; } ///returns only isolated tracks in [cands] -AlignmentGlobalTrackSelector::Tracks -AlignmentGlobalTrackSelector::checkIsolation(const Tracks& cands,const edm::Event& iEvent) const -{ - Tracks result; result.clear(); +AlignmentGlobalTrackSelector::Tracks AlignmentGlobalTrackSelector::checkIsolation(const Tracks& cands, + const edm::Event& iEvent) const { + Tracks result; + result.clear(); Handle jets; iEvent.getByToken(theJetIsoToken, jets); if (jets.isValid()) { - for (Tracks::const_iterator it = cands.begin(); - it!=cands.end(); - ++it) { + for (Tracks::const_iterator it = cands.begin(); it != cands.end(); ++it) { bool isolated = true; - for (reco::CaloJetCollection::const_iterator itJet = jets->begin(); - itJet!=jets->end(); - ++itJet) - isolated &= !((*itJet).pt() > theMaxJetPt && deltaR(*(*it),(*itJet)) < theMinJetDeltaR); - + for (reco::CaloJetCollection::const_iterator itJet = jets->begin(); itJet != jets->end(); ++itJet) + isolated &= !((*itJet).pt() > theMaxJetPt && deltaR(*(*it), (*itJet)) < theMinJetDeltaR); + if (isolated) - result.push_back(*it); + result.push_back(*it); } - // LogDebug("Alignment") << "D Found "< could not optain jetCollection!"; + LogError("Alignment") << "@SUB=AlignmentGlobalTrackSelector::checkIsolation" + << "> could not optain jetCollection!"; - if (static_cast(result.size()) < theMinIsolatedCount) result.clear(); + if (static_cast(result.size()) < theMinIsolatedCount) + result.clear(); return result; } ///returns [tracks] if there are less than theMaxCount Jets with theMinJetPt and an empty set if not -AlignmentGlobalTrackSelector::Tracks -AlignmentGlobalTrackSelector::checkJetCount(const Tracks& tracks, const edm::Event& iEvent) const -{ - Tracks result; result.clear(); +AlignmentGlobalTrackSelector::Tracks AlignmentGlobalTrackSelector::checkJetCount(const Tracks& tracks, + const edm::Event& iEvent) const { + Tracks result; + result.clear(); Handle jets; iEvent.getByToken(theJetCountToken, jets); if (jets.isValid()) { int jetCount = 0; - for (reco::CaloJetCollection::const_iterator itJet = jets->begin(); - itJet!=jets->end(); - ++itJet) { + for (reco::CaloJetCollection::const_iterator itJet = jets->begin(); itJet != jets->end(); ++itJet) { if ((*itJet).pt() > theMinJetPt) - jetCount++; + jetCount++; } if (jetCount <= theMaxJetCount) @@ -188,7 +173,7 @@ AlignmentGlobalTrackSelector::checkJetCount(const Tracks& tracks, const edm::Eve LogDebug("Alignment") << "> found " << jetCount << " Jets"; } else LogError("Alignment") << "@SUB=AlignmentGlobalTrackSelector::checkJetCount" - << "> could not optain jetCollection!"; + << "> could not optain jetCollection!"; return result; } @@ -196,45 +181,34 @@ AlignmentGlobalTrackSelector::checkJetCount(const Tracks& tracks, const edm::Eve //===================HELPERS=================== ///matches [src] with [comp] returns collection with matching Tracks coming from [src] -AlignmentGlobalTrackSelector::Tracks -AlignmentGlobalTrackSelector::matchTracks(const Tracks& src, const Tracks& comp) const -{ +AlignmentGlobalTrackSelector::Tracks AlignmentGlobalTrackSelector::matchTracks(const Tracks& src, + const Tracks& comp) const { Tracks result; - for (Tracks::const_iterator itComp = comp.begin(); - itComp!=comp.end(); - ++itComp) { + for (Tracks::const_iterator itComp = comp.begin(); itComp != comp.end(); ++itComp) { int match = -1; double min = theMaxTrackDeltaR; - for (unsigned int i=0;i Trackmatch dist: "< deltaR(*(src.at(i)),*(*itComp))){ - min = deltaR(*(src.at(i)),*(*itComp)); - match = static_cast(i); + if (min > deltaR(*(src.at(i)), *(*itComp))) { + min = deltaR(*(src.at(i)), *(*itComp)); + match = static_cast(i); } } if (match > -1) - result.push_back(src.at(match)); + result.push_back(src.at(match)); } return result; } ///print Information on Track-Collection -void AlignmentGlobalTrackSelector::printTracks(const Tracks& col) const -{ +void AlignmentGlobalTrackSelector::printTracks(const Tracks& col) const { int count = 0; LogDebug("Alignment") << ">......................................"; - for (Tracks::const_iterator it = col.begin(); - it < col.end(); - ++it,++count) { - LogDebug("Alignment") - << "> Track No. " << count << ": p = (" - << (*it)->px() << "," - << (*it)->py() << "," - << (*it)->pz() << ")\n" - << "> pT = " - << (*it)->pt() << " eta = " - << (*it)->eta() << " charge = " - << (*it)->charge(); + for (Tracks::const_iterator it = col.begin(); it < col.end(); ++it, ++count) { + LogDebug("Alignment") << "> Track No. " << count << ": p = (" << (*it)->px() << "," << (*it)->py() << "," + << (*it)->pz() << ")\n" + << "> pT = " << (*it)->pt() << " eta = " << (*it)->eta() + << " charge = " << (*it)->charge(); } LogDebug("Alignment") << ">......................................"; } diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentMuonSelector.cc b/Alignment/CommonAlignmentProducer/src/AlignmentMuonSelector.cc index 1b54459c5cd16..ee22664772e8b 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentMuonSelector.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentMuonSelector.cc @@ -1,147 +1,132 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "Alignment/CommonAlignmentProducer/interface/AlignmentMuonSelector.h" -#include "FWCore/ParameterSet/interface/ParameterSet.h" +#include "FWCore/ParameterSet/interface/ParameterSet.h" #include "TLorentzVector.h" // constructor ---------------------------------------------------------------- -AlignmentMuonSelector::AlignmentMuonSelector(const edm::ParameterSet & cfg) : - applyBasicCuts( cfg.getParameter( "applyBasicCuts" ) ), - applyNHighestPt( cfg.getParameter( "applyNHighestPt" ) ), - applyMultiplicityFilter( cfg.getParameter( "applyMultiplicityFilter" ) ), - applyMassPairFilter( cfg.getParameter( "applyMassPairFilter" ) ), - nHighestPt( cfg.getParameter( "nHighestPt" ) ), - minMultiplicity ( cfg.getParameter( "minMultiplicity" ) ), - pMin( cfg.getParameter( "pMin" ) ), - pMax( cfg.getParameter( "pMax" ) ), - ptMin( cfg.getParameter( "ptMin" ) ), - ptMax( cfg.getParameter( "ptMax" ) ), - etaMin( cfg.getParameter( "etaMin" ) ), - etaMax( cfg.getParameter( "etaMax" ) ), - phiMin( cfg.getParameter( "phiMin" ) ), - phiMax( cfg.getParameter( "phiMax" ) ), - nHitMinSA( cfg.getParameter( "nHitMinSA" ) ), - nHitMaxSA( cfg.getParameter( "nHitMaxSA" ) ), - chi2nMaxSA( cfg.getParameter( "chi2nMaxSA") ), - nHitMinGB( cfg.getParameter( "nHitMinGB" ) ), - nHitMaxGB( cfg.getParameter( "nHitMaxGB" ) ), - chi2nMaxGB( cfg.getParameter( "chi2nMaxGB") ), - nHitMinTO( cfg.getParameter( "nHitMinTO" ) ), - nHitMaxTO( cfg.getParameter( "nHitMaxTO" ) ), - chi2nMaxTO( cfg.getParameter( "chi2nMaxTO" ) ), - minMassPair( cfg.getParameter( "minMassPair" ) ), - maxMassPair( cfg.getParameter( "maxMassPair" ) ) -{ - +AlignmentMuonSelector::AlignmentMuonSelector(const edm::ParameterSet& cfg) + : applyBasicCuts(cfg.getParameter("applyBasicCuts")), + applyNHighestPt(cfg.getParameter("applyNHighestPt")), + applyMultiplicityFilter(cfg.getParameter("applyMultiplicityFilter")), + applyMassPairFilter(cfg.getParameter("applyMassPairFilter")), + nHighestPt(cfg.getParameter("nHighestPt")), + minMultiplicity(cfg.getParameter("minMultiplicity")), + pMin(cfg.getParameter("pMin")), + pMax(cfg.getParameter("pMax")), + ptMin(cfg.getParameter("ptMin")), + ptMax(cfg.getParameter("ptMax")), + etaMin(cfg.getParameter("etaMin")), + etaMax(cfg.getParameter("etaMax")), + phiMin(cfg.getParameter("phiMin")), + phiMax(cfg.getParameter("phiMax")), + nHitMinSA(cfg.getParameter("nHitMinSA")), + nHitMaxSA(cfg.getParameter("nHitMaxSA")), + chi2nMaxSA(cfg.getParameter("chi2nMaxSA")), + nHitMinGB(cfg.getParameter("nHitMinGB")), + nHitMaxGB(cfg.getParameter("nHitMaxGB")), + chi2nMaxGB(cfg.getParameter("chi2nMaxGB")), + nHitMinTO(cfg.getParameter("nHitMinTO")), + nHitMaxTO(cfg.getParameter("nHitMaxTO")), + chi2nMaxTO(cfg.getParameter("chi2nMaxTO")), + minMassPair(cfg.getParameter("minMassPair")), + maxMassPair(cfg.getParameter("maxMassPair")) { if (applyBasicCuts) - edm::LogInfo("AlignmentMuonSelector") - << "applying basic muon cuts ..." - << "\npmin,pmax: " << pMin << "," << pMax - << "\nptmin,ptmax: " << ptMin << "," << ptMax - << "\netamin,etamax: " << etaMin << "," << etaMax - << "\nphimin,phimax: " << phiMin << "," << phiMax - << "\nnhitminSA,nhitmaxSA: " << nHitMinSA << "," << nHitMaxSA - << "\nchi2nmaxSA: " << chi2nMaxSA<< "," - << "\nnhitminGB,nhitmaxGB: " << nHitMinGB << "," << nHitMaxGB - << "\nchi2nmaxGB: " << chi2nMaxGB<< "," - << "\nnhitminTO,nhitmaxTO: " << nHitMinTO << "," << nHitMaxTO - << "\nchi2nmaxTO: " << chi2nMaxTO; + edm::LogInfo("AlignmentMuonSelector") + << "applying basic muon cuts ..." + << "\npmin,pmax: " << pMin << "," << pMax << "\nptmin,ptmax: " << ptMin << "," << ptMax + << "\netamin,etamax: " << etaMin << "," << etaMax << "\nphimin,phimax: " << phiMin << "," << phiMax + << "\nnhitminSA,nhitmaxSA: " << nHitMinSA << "," << nHitMaxSA << "\nchi2nmaxSA: " << chi2nMaxSA << "," + << "\nnhitminGB,nhitmaxGB: " << nHitMinGB << "," << nHitMaxGB << "\nchi2nmaxGB: " << chi2nMaxGB << "," + << "\nnhitminTO,nhitmaxTO: " << nHitMinTO << "," << nHitMaxTO << "\nchi2nmaxTO: " << chi2nMaxTO; if (applyNHighestPt) - edm::LogInfo("AlignmentMuonSelector") - << "filter N muons with highest Pt N=" << nHighestPt; + edm::LogInfo("AlignmentMuonSelector") << "filter N muons with highest Pt N=" << nHighestPt; if (applyMultiplicityFilter) - edm::LogInfo("AlignmentMuonSelector") - << "apply multiplicity filter N>=" << minMultiplicity; + edm::LogInfo("AlignmentMuonSelector") << "apply multiplicity filter N>=" << minMultiplicity; if (applyMassPairFilter) - edm::LogInfo("AlignmentMuonSelector") - << "apply Mass Pair filter minMassPair=" << minMassPair << " maxMassPair=" << maxMassPair; - + edm::LogInfo("AlignmentMuonSelector") + << "apply Mass Pair filter minMassPair=" << minMassPair << " maxMassPair=" << maxMassPair; } // destructor ----------------------------------------------------------------- -AlignmentMuonSelector::~AlignmentMuonSelector() -{} - +AlignmentMuonSelector::~AlignmentMuonSelector() {} // do selection --------------------------------------------------------------- -AlignmentMuonSelector::Muons -AlignmentMuonSelector::select(const Muons& muons, const edm::Event& evt) const -{ - Muons result=muons; +AlignmentMuonSelector::Muons AlignmentMuonSelector::select(const Muons& muons, const edm::Event& evt) const { + Muons result = muons; // apply basic muon cuts (if selected) - if (applyBasicCuts) result= this->basicCuts(result); + if (applyBasicCuts) + result = this->basicCuts(result); // filter N muons with highest Pt (if selected) - if (applyNHighestPt) result= this->theNHighestPtMuons(result); + if (applyNHighestPt) + result = this->theNHighestPtMuons(result); // apply minimum multiplicity requirement (if selected) if (applyMultiplicityFilter) { - if (result.size()<(unsigned int)minMultiplicity) result.clear(); + if (result.size() < (unsigned int)minMultiplicity) + result.clear(); } // apply mass pair requirement (if selected) if (applyMassPairFilter) { - if (result.size()<2) result.clear(); // at least 2 muons are require for a mass pair... - else result = this->theBestMassPairCombinationMuons(result); + if (result.size() < 2) + result.clear(); // at least 2 muons are require for a mass pair... + else + result = this->theBestMassPairCombinationMuons(result); } edm::LogInfo("AlignmentMuonSelector") << "muons all,kept: " << muons.size() << "," << result.size(); return result; - } // make basic cuts ------------------------------------------------------------ -AlignmentMuonSelector::Muons -AlignmentMuonSelector::basicCuts(const Muons& muons) const -{ +AlignmentMuonSelector::Muons AlignmentMuonSelector::basicCuts(const Muons& muons) const { Muons result; - for(Muons::const_iterator it=muons.begin(); - it!=muons.end();++it) { - const reco::Muon* muonp=*it; - float p=muonp->p(); - float pt=muonp->pt(); - float eta=muonp->eta(); - float phi=muonp->phi(); - - int nhitSA=0;float chi2nSA=9999.; - if(muonp->isStandAloneMuon()){ - nhitSA = muonp->standAloneMuon()->numberOfValidHits();// standAlone Muon - chi2nSA = muonp->standAloneMuon()->normalizedChi2(); // standAlone Muon + for (Muons::const_iterator it = muons.begin(); it != muons.end(); ++it) { + const reco::Muon* muonp = *it; + float p = muonp->p(); + float pt = muonp->pt(); + float eta = muonp->eta(); + float phi = muonp->phi(); + + int nhitSA = 0; + float chi2nSA = 9999.; + if (muonp->isStandAloneMuon()) { + nhitSA = muonp->standAloneMuon()->numberOfValidHits(); // standAlone Muon + chi2nSA = muonp->standAloneMuon()->normalizedChi2(); // standAlone Muon } - int nhitGB=0;float chi2nGB=9999.; - if(muonp->isGlobalMuon()){ - nhitGB = muonp->combinedMuon()->numberOfValidHits();// global Muon - chi2nGB = muonp->combinedMuon()->normalizedChi2(); // global Muon + int nhitGB = 0; + float chi2nGB = 9999.; + if (muonp->isGlobalMuon()) { + nhitGB = muonp->combinedMuon()->numberOfValidHits(); // global Muon + chi2nGB = muonp->combinedMuon()->normalizedChi2(); // global Muon } - int nhitTO=0;float chi2nTO=9999.; - if(muonp->isTrackerMuon()){ - nhitTO = muonp->track()->numberOfValidHits(); // Tracker Only - chi2nTO = muonp->track()->normalizedChi2(); // Tracker Only + int nhitTO = 0; + float chi2nTO = 9999.; + if (muonp->isTrackerMuon()) { + nhitTO = muonp->track()->numberOfValidHits(); // Tracker Only + chi2nTO = muonp->track()->normalizedChi2(); // Tracker Only } - edm::LogInfo("AlignmentMuonSelector") << " pt,eta,phi,nhitSA,chi2nSA,nhitGB,chi2nGB,nhitTO,chi2nTO: " - <pMin && pptMin && ptetaMin && etaphiMin && phi=nHitMinSA && nhitSA<=nHitMaxSA - && chi2nSA=nHitMinGB && nhitGB<=nHitMaxGB - && chi2nGB=nHitMinTO && nhitTO<=nHitMaxTO - && chi2nTO pMin && p < pMax && pt > ptMin && pt < ptMax && eta > etaMin && eta < etaMax && phi > phiMin && + phi < phiMax && nhitSA >= nHitMinSA && nhitSA <= nHitMaxSA && chi2nSA < chi2nMaxSA && nhitGB >= nHitMinGB && + nhitGB <= nHitMaxGB && chi2nGB < chi2nMaxGB && nhitTO >= nHitMinTO && nhitTO <= nHitMaxTO && + chi2nTO < chi2nMaxTO) { result.push_back(muonp); } } @@ -151,20 +136,20 @@ AlignmentMuonSelector::basicCuts(const Muons& muons) const //----------------------------------------------------------------------------- -AlignmentMuonSelector::Muons -AlignmentMuonSelector::theNHighestPtMuons(const Muons& muons) const -{ - Muons sortedMuons=muons; +AlignmentMuonSelector::Muons AlignmentMuonSelector::theNHighestPtMuons(const Muons& muons) const { + Muons sortedMuons = muons; Muons result; // sort in pt - std::sort(sortedMuons.begin(),sortedMuons.end(),ptComparator); + std::sort(sortedMuons.begin(), sortedMuons.end(), ptComparator); // copy theMuonMult highest pt muons to result vector - int n=0; - for (Muons::const_iterator it=sortedMuons.begin(); - it!=sortedMuons.end(); ++it) { - if (nmomentum().x(),(*it1)->momentum().y(),(*it1)->momentum().z(),(*it1)->p()); - mu2 = TLorentzVector((*it2)->momentum().x(),(*it2)->momentum().y(),(*it2)->momentum().z(),(*it2)->p()); - pair=mu1+mu2; - mass = pair.M(); - - if( maxMassPair != minMassPair){ - if(massminMassPair) { result.push_back(*it1); result.push_back(*it2); break;} - } - else{ - if(fabs(mass-maxMassPair)< minDiff) { minDiff=fabs(mass-maxMassPair); result.clear(); result.push_back(*it1); result.push_back(*it2);} - } - } + for (Muons::const_iterator it1 = sortedMuons.begin(); it1 != sortedMuons.end(); ++it1) { + for (Muons::const_iterator it2 = it1 + 1; it2 != sortedMuons.end(); ++it2) { + mu1 = TLorentzVector((*it1)->momentum().x(), (*it1)->momentum().y(), (*it1)->momentum().z(), (*it1)->p()); + mu2 = TLorentzVector((*it2)->momentum().x(), (*it2)->momentum().y(), (*it2)->momentum().z(), (*it2)->p()); + pair = mu1 + mu2; + mass = pair.M(); + + if (maxMassPair != minMassPair) { + if (mass < maxMassPair && mass > minMassPair) { + result.push_back(*it1); + result.push_back(*it2); + break; + } + } else { + if (fabs(mass - maxMassPair) < minDiff) { + minDiff = fabs(mass - maxMassPair); + result.clear(); + result.push_back(*it1); + result.push_back(*it2); + } + } + } } return result; } - diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentProducerBase.cc b/Alignment/CommonAlignmentProducer/src/AlignmentProducerBase.cc index a5a790e48ab67..4a7791a3bfd6c 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentProducerBase.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentProducerBase.cc @@ -30,32 +30,29 @@ #include "Geometry/Records/interface/MuonNumberingRecord.h" #include "Geometry/Records/interface/TrackerTopologyRcd.h" - //------------------------------------------------------------------------------ -AlignmentProducerBase::AlignmentProducerBase(const edm::ParameterSet& config) : - doTracker_{config.getUntrackedParameter("doTracker")}, - doMuon_{config.getUntrackedParameter("doMuon")}, - useExtras_{config.getUntrackedParameter("useExtras")}, - tjTkAssociationMapTag_{config.getParameter("tjTkAssociationMapTag")}, - beamSpotTag_{config.getParameter("beamSpotTag")}, - tkLasBeamTag_{config.getParameter("tkLasBeamTag")}, - clusterValueMapTag_{config.getParameter("hitPrescaleMapTag")}, - uniqueRunRanges_ - {align::makeUniqueRunRanges(config.getParameter("RunRangeSelection"), - cond::timeTypeSpecs[cond::runnumber].beginValue)}, - config_{config}, - stNFixAlignables_{config.getParameter("nFixAlignables")}, - stRandomShift_{config.getParameter("randomShift")}, - stRandomRotation_{config.getParameter("randomRotation")}, - applyDbAlignment_{config.getUntrackedParameter("applyDbAlignment")}, - checkDbAlignmentValidity_{config.getUntrackedParameter("checkDbAlignmentValidity")}, - doMisalignmentScenario_{config.getParameter("doMisalignmentScenario")}, - saveToDB_{config.getParameter("saveToDB")}, - saveApeToDB_{config.getParameter("saveApeToDB")}, - saveDeformationsToDB_{config.getParameter("saveDeformationsToDB")}, - useSurvey_{config.getParameter("useSurvey")}, - enableAlignableUpdates_{config.getParameter("enableAlignableUpdates")} -{ +AlignmentProducerBase::AlignmentProducerBase(const edm::ParameterSet& config) + : doTracker_{config.getUntrackedParameter("doTracker")}, + doMuon_{config.getUntrackedParameter("doMuon")}, + useExtras_{config.getUntrackedParameter("useExtras")}, + tjTkAssociationMapTag_{config.getParameter("tjTkAssociationMapTag")}, + beamSpotTag_{config.getParameter("beamSpotTag")}, + tkLasBeamTag_{config.getParameter("tkLasBeamTag")}, + clusterValueMapTag_{config.getParameter("hitPrescaleMapTag")}, + uniqueRunRanges_{align::makeUniqueRunRanges(config.getParameter("RunRangeSelection"), + cond::timeTypeSpecs[cond::runnumber].beginValue)}, + config_{config}, + stNFixAlignables_{config.getParameter("nFixAlignables")}, + stRandomShift_{config.getParameter("randomShift")}, + stRandomRotation_{config.getParameter("randomRotation")}, + applyDbAlignment_{config.getUntrackedParameter("applyDbAlignment")}, + checkDbAlignmentValidity_{config.getUntrackedParameter("checkDbAlignmentValidity")}, + doMisalignmentScenario_{config.getParameter("doMisalignmentScenario")}, + saveToDB_{config.getParameter("saveToDB")}, + saveApeToDB_{config.getParameter("saveApeToDB")}, + saveDeformationsToDB_{config.getParameter("saveDeformationsToDB")}, + useSurvey_{config.getParameter("useSurvey")}, + enableAlignableUpdates_{config.getParameter("enableAlignableUpdates")} { edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::AlignmentProducerBase"; const auto& algoConfig = config_.getParameterSet("algoConfig"); @@ -63,11 +60,9 @@ AlignmentProducerBase::AlignmentProducerBase(const edm::ParameterSet& config) : // configured in main config? runAtPCL_ = config_.getParameter("runAtPCL"); - if (hasParameter(algoConfig, "runAtPCL") && - (runAtPCL_ != algoConfig.getParameter("runAtPCL"))) { - throw cms::Exception("BadConfig") - << "Inconsistent settings for 'runAtPCL' in configuration of the " - << "alignment producer and the alignment algorithm."; + if (hasParameter(algoConfig, "runAtPCL") && (runAtPCL_ != algoConfig.getParameter("runAtPCL"))) { + throw cms::Exception("BadConfig") << "Inconsistent settings for 'runAtPCL' in configuration of the " + << "alignment producer and the alignment algorithm."; } } else if (hasParameter(algoConfig, "runAtPCL")) { @@ -84,12 +79,10 @@ AlignmentProducerBase::AlignmentProducerBase(const edm::ParameterSet& config) : createCalibrations(); } - - //------------------------------------------------------------------------------ -AlignmentProducerBase::~AlignmentProducerBase() noexcept(false) -{ - for (auto& iCal: calibrations_) delete iCal; +AlignmentProducerBase::~AlignmentProducerBase() noexcept(false) { + for (auto& iCal : calibrations_) + delete iCal; delete alignmentParameterStore_; delete alignableExtras_; @@ -97,22 +90,18 @@ AlignmentProducerBase::~AlignmentProducerBase() noexcept(false) delete alignableMuon_; } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::startProcessing() -{ - if (isDuringLoop_) return; +void AlignmentProducerBase::startProcessing() { + if (isDuringLoop_) + return; - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::startProcessing" - << "Begin"; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::startProcessing" + << "Begin"; if (!isAlgoInitialized_) { - throw cms::Exception("LogicError") - << "@SUB=AlignmentProducerBase::startProcessing\n" - << "Trying to start event processing before initializing the alignment " - << "algorithm."; + throw cms::Exception("LogicError") << "@SUB=AlignmentProducerBase::startProcessing\n" + << "Trying to start event processing before initializing the alignment " + << "algorithm."; } nevent_ = 0; @@ -120,23 +109,22 @@ AlignmentProducerBase::startProcessing() alignmentAlgo_->startNewLoop(); // FIXME: Should this be done in algorithm::startNewLoop()?? - for (const auto& iCal: calibrations_) iCal->startNewLoop(); - for (const auto& monitor: monitors_) monitor->startingNewLoop(); + for (const auto& iCal : calibrations_) + iCal->startNewLoop(); + for (const auto& monitor : monitors_) + monitor->startingNewLoop(); applyAlignmentsToGeometry(); isDuringLoop_ = true; } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::terminateProcessing(const edm::EventSetup* setup) -{ - if (!isDuringLoop_) return; - - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::terminateProcessing" - << "Terminating algorithm."; +void AlignmentProducerBase::terminateProcessing(const edm::EventSetup* setup) { + if (!isDuringLoop_) + return; + + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::terminateProcessing" + << "Terminating algorithm."; if (setup) { alignmentAlgo_->terminate(*setup); } else { @@ -144,22 +132,19 @@ AlignmentProducerBase::terminateProcessing(const edm::EventSetup* setup) } // FIXME: Should this be done in algorithm::terminate()?? - for (const auto& iCal:calibrations_) iCal->endOfLoop(); - for (const auto& monitor: monitors_) monitor->endOfLoop(); + for (const auto& iCal : calibrations_) + iCal->endOfLoop(); + for (const auto& monitor : monitors_) + monitor->endOfLoop(); isDuringLoop_ = false; } - //------------------------------------------------------------------------------ -bool -AlignmentProducerBase::processEvent(const edm::Event& event, - const edm::EventSetup& setup) -{ +bool AlignmentProducerBase::processEvent(const edm::Event& event, const edm::EventSetup& setup) { if (setupChanged(setup)) { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::processEvent" - << "EventSetup-Record changed."; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::processEvent" + << "EventSetup-Record changed."; // updatable alignables are currently not used at PCL, but event setup // changes require a complete re-initialization @@ -170,16 +155,15 @@ AlignmentProducerBase::processEvent(const edm::Event& event, } } - initBeamSpot(event); // must happen every event and before incrementing 'nevent_' + initBeamSpot(event); // must happen every event and before incrementing 'nevent_' ++nevent_; // must happen before the check below; // otherwise subsequent checks fail for "EmptySource" if (!alignmentAlgo_->processesEvents()) { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::processEvent" - << "Skipping event. The current configuration of the alignment algorithm " - << "does not need to process any events."; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::processEvent" + << "Skipping event. The current configuration of the alignment algorithm " + << "does not need to process any events."; return false; } @@ -187,11 +171,10 @@ AlignmentProducerBase::processEvent(const edm::Event& event, readInSurveyRcds(setup); // Printout event number - for ( int i=10; i<10000000; i*=10 ) { - if ( nevent_<10*i && (nevent_%i)==0 ) { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::processEvent" - << "Events processed: " << nevent_; + for (int i = 10; i < 10000000; i *= 10) { + if (nevent_ < 10 * i && (nevent_ % i) == 0) { + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::processEvent" + << "Events processed: " << nevent_; } } @@ -200,12 +183,9 @@ AlignmentProducerBase::processEvent(const edm::Event& event, edm::Handle handleTrajTracksCollection; if (getTrajTrackAssociationCollection(event, handleTrajTracksCollection)) { - // Form pairs of trajectories and tracks ConstTrajTrackPairs trajTracks; - for (auto iter = handleTrajTracksCollection->begin(); - iter != handleTrajTracksCollection->end(); - ++iter) { + for (auto iter = handleTrajTracksCollection->begin(); iter != handleTrajTracksCollection->end(); ++iter) { trajTracks.push_back(ConstTrajTrackPair(&(*(*iter).key), &(*(*iter).val))); } @@ -217,36 +197,26 @@ AlignmentProducerBase::processEvent(const edm::Event& event, clusterValueMapPtr = &(*clusterValueMap); } - - const AlignmentAlgorithmBase::EventInfo eventInfo{event.id(), - trajTracks, - *beamSpot_, - clusterValueMapPtr}; + const AlignmentAlgorithmBase::EventInfo eventInfo{event.id(), trajTracks, *beamSpot_, clusterValueMapPtr}; alignmentAlgo_->run(setup, eventInfo); - - for (const auto& monitor: monitors_) { - monitor->duringLoop(event, setup, trajTracks); // forward eventInfo? + for (const auto& monitor : monitors_) { + monitor->duringLoop(event, setup, trajTracks); // forward eventInfo? } } else { - edm::LogError("Alignment") - << "@SUB=AlignmentProducerBase::processEvent" - << "No track collection found: skipping event"; + edm::LogError("Alignment") << "@SUB=AlignmentProducerBase::processEvent" + << "No track collection found: skipping event"; } return true; } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::beginRunImpl(const edm::Run& run, const edm::EventSetup& setup) -{ +void AlignmentProducerBase::beginRunImpl(const edm::Run& run, const edm::EventSetup& setup) { const bool changed{setupChanged(setup)}; if (changed) { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::beginRunImpl" - << "EventSetup-Record changed."; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::beginRunImpl" + << "EventSetup-Record changed."; // updatable alignables are currently not used at PCL, but event setup // changes require a complete re-initialization @@ -257,10 +227,10 @@ AlignmentProducerBase::beginRunImpl(const edm::Run& run, const edm::EventSetup& } } - alignmentAlgo_->beginRun(run, setup, - changed && (runAtPCL_ || enableAlignableUpdates_)); + alignmentAlgo_->beginRun(run, setup, changed && (runAtPCL_ || enableAlignableUpdates_)); - for (const auto& iCal:calibrations_) iCal->beginRun(run, setup); + for (const auto& iCal : calibrations_) + iCal->beginRun(run, setup); //store the first run analyzed to be used for setting the IOV (for PCL) if (firstRun_ > static_cast(run.id().run())) { @@ -268,11 +238,8 @@ AlignmentProducerBase::beginRunImpl(const edm::Run& run, const edm::EventSetup& } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::endRunImpl(const edm::Run& run, const edm::EventSetup& setup) -{ +void AlignmentProducerBase::endRunImpl(const edm::Run& run, const edm::EventSetup& setup) { if (!tkLasBeamTag_.encode().empty()) { edm::Handle lasBeams; edm::Handle tsoses; @@ -281,71 +248,47 @@ AlignmentProducerBase::endRunImpl(const edm::Run& run, const edm::EventSetup& se alignmentAlgo_->endRun(EndRunInfo(run.id(), &(*lasBeams), &(*tsoses)), setup); } else { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::endRunImpl" - << "No Tk LAS beams to forward to algorithm."; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::endRunImpl" + << "No Tk LAS beams to forward to algorithm."; alignmentAlgo_->endRun(EndRunInfo(run.id(), nullptr, nullptr), setup); } - } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::beginLuminosityBlockImpl(const edm::LuminosityBlock&, - const edm::EventSetup& setup) -{ +void AlignmentProducerBase::beginLuminosityBlockImpl(const edm::LuminosityBlock&, const edm::EventSetup& setup) { // Do not forward edm::LuminosityBlock alignmentAlgo_->beginLuminosityBlock(setup); } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::endLuminosityBlockImpl(const edm::LuminosityBlock&, - const edm::EventSetup& setup) -{ +void AlignmentProducerBase::endLuminosityBlockImpl(const edm::LuminosityBlock&, const edm::EventSetup& setup) { // Do not forward edm::LuminosityBlock alignmentAlgo_->endLuminosityBlock(setup); } - - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::createAlignmentAlgorithm() -{ +void AlignmentProducerBase::createAlignmentAlgorithm() { auto algoConfig = config_.getParameter("algoConfig"); - algoConfig.addUntrackedParameter("RunRangeSelection", - config_.getParameter("RunRangeSelection")); - algoConfig.addUntrackedParameter("firstIOV", - runAtPCL_ ? - 1 : - uniqueRunRanges_.front().first); - algoConfig.addUntrackedParameter("enableAlignableUpdates", - enableAlignableUpdates_); + algoConfig.addUntrackedParameter("RunRangeSelection", config_.getParameter("RunRangeSelection")); + algoConfig.addUntrackedParameter("firstIOV", runAtPCL_ ? 1 : uniqueRunRanges_.front().first); + algoConfig.addUntrackedParameter("enableAlignableUpdates", enableAlignableUpdates_); const auto& algoName = algoConfig.getParameter("algoName"); - alignmentAlgo_ = std::unique_ptr - {AlignmentAlgorithmPluginFactory::get()->create(algoName, algoConfig)}; + alignmentAlgo_ = + std::unique_ptr{AlignmentAlgorithmPluginFactory::get()->create(algoName, algoConfig)}; if (!alignmentAlgo_) { - throw cms::Exception("BadConfig") - << "Couldn't find the called alignment algorithm: " << algoName; + throw cms::Exception("BadConfig") << "Couldn't find the called alignment algorithm: " << algoName; } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::createMonitors() -{ +void AlignmentProducerBase::createMonitors() { const auto& monitorConfig = config_.getParameter("monitorConfig"); auto monitors = monitorConfig.getUntrackedParameter >("monitors"); - for (const auto& miter: monitors) { - std::unique_ptr newMonitor - {AlignmentMonitorPluginFactory::get() - ->create(miter, monitorConfig.getUntrackedParameterSet(miter))}; + for (const auto& miter : monitors) { + std::unique_ptr newMonitor{ + AlignmentMonitorPluginFactory::get()->create(miter, monitorConfig.getUntrackedParameterSet(miter))}; if (!newMonitor) { throw cms::Exception("BadConfig") << "Couldn't find monitor named " << miter; @@ -354,24 +297,17 @@ AlignmentProducerBase::createMonitors() } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::createCalibrations() -{ +void AlignmentProducerBase::createCalibrations() { const auto& calibrations = config_.getParameter("calibrations"); - for (const auto& iCalib: calibrations) { - calibrations_.push_back(IntegratedCalibrationPluginFactory::get() - ->create(iCalib.getParameter("calibrationName"), - iCalib)); + for (const auto& iCalib : calibrations) { + calibrations_.push_back( + IntegratedCalibrationPluginFactory::get()->create(iCalib.getParameter("calibrationName"), iCalib)); } } - //------------------------------------------------------------------------------ -bool -AlignmentProducerBase::setupChanged(const edm::EventSetup& setup) -{ +bool AlignmentProducerBase::setupChanged(const edm::EventSetup& setup) { bool changed{false}; if (watchIdealGeometryRcd_.check(setup)) { @@ -422,15 +358,10 @@ AlignmentProducerBase::setupChanged(const edm::EventSetup& setup) return changed; } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::initAlignmentAlgorithm(const edm::EventSetup& setup, - bool update) -{ - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::initAlignmentAlgorithm" - << "Begin"; +void AlignmentProducerBase::initAlignmentAlgorithm(const edm::EventSetup& setup, bool update) { + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::initAlignmentAlgorithm" + << "Begin"; auto isTrueUpdate = update && isAlgoInitialized_; @@ -449,14 +380,9 @@ AlignmentProducerBase::initAlignmentAlgorithm(const edm::EventSetup& setup, // Initialize alignment algorithm and integrated calibration and pass the // latter to algorithm - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::initAlignmentAlgorithm" - << "Initializing alignment algorithm."; - alignmentAlgo_->initialize(setup, - alignableTracker_, - alignableMuon_, - alignableExtras_, - alignmentParameterStore_); + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::initAlignmentAlgorithm" + << "Initializing alignment algorithm."; + alignmentAlgo_->initialize(setup, alignableTracker_, alignableMuon_, alignableExtras_, alignmentParameterStore_); // Not all algorithms support calibrations - so do not pass empty vector // and throw if non-empty and not supported: @@ -464,10 +390,9 @@ AlignmentProducerBase::initAlignmentAlgorithm(const edm::EventSetup& setup, if (alignmentAlgo_->supportsCalibrations()) { alignmentAlgo_->addCalibrations(calibrations_); } else { - throw cms::Exception("BadConfig") - << "@SUB=AlignmentProducerBase::createCalibrations\n" - << "Configured " << calibrations_.size() << " calibration(s) " - << "for algorithm not supporting it."; + throw cms::Exception("BadConfig") << "@SUB=AlignmentProducerBase::createCalibrations\n" + << "Configured " << calibrations_.size() << " calibration(s) " + << "for algorithm not supporting it."; } } @@ -475,48 +400,36 @@ AlignmentProducerBase::initAlignmentAlgorithm(const edm::EventSetup& setup, applyAlignmentsToGeometry(); - if (!isTrueUpdate) { // only needed the first time - for (const auto& iCal: calibrations_) { + if (!isTrueUpdate) { // only needed the first time + for (const auto& iCal : calibrations_) { iCal->beginOfJob(alignableTracker_, alignableMuon_, alignableExtras_); } - for (const auto& monitor: monitors_) { - monitor->beginOfJob(alignableTracker_, alignableMuon_, alignmentParameterStore_); + for (const auto& monitor : monitors_) { + monitor->beginOfJob(alignableTracker_, alignableMuon_, alignmentParameterStore_); } } - startProcessing(); // needed if derived class is non-EDLooper-based - // has no effect, if called during loop + startProcessing(); // needed if derived class is non-EDLooper-based + // has no effect, if called during loop - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::initAlignmentAlgorithm" - << "End"; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::initAlignmentAlgorithm" + << "End"; } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::initBeamSpot(const edm::Event& event) -{ +void AlignmentProducerBase::initBeamSpot(const edm::Event& event) { getBeamSpot(event, beamSpot_); - if (nevent_== 0 && alignableExtras_) { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::initBeamSpot" - << "Initializing AlignableBeamSpot"; + if (nevent_ == 0 && alignableExtras_) { + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::initBeamSpot" + << "Initializing AlignableBeamSpot"; - alignableExtras_->initializeBeamSpot(beamSpot_->x0(), - beamSpot_->y0(), - beamSpot_->z0(), - beamSpot_->dxdz(), - beamSpot_->dydz()); + alignableExtras_->initializeBeamSpot( + beamSpot_->x0(), beamSpot_->y0(), beamSpot_->z0(), beamSpot_->dxdz(), beamSpot_->dydz()); } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::createGeometries(const edm::EventSetup& iSetup, - const TrackerTopology* tTopo) -{ +void AlignmentProducerBase::createGeometries(const edm::EventSetup& iSetup, const TrackerTopology* tTopo) { if (doTracker_) { edm::ESHandle geometricDet; iSetup.get().get(geometricDet); @@ -526,8 +439,7 @@ AlignmentProducerBase::createGeometries(const edm::EventSetup& iSetup, TrackerGeomBuilderFromGeometricDet trackerBuilder; - trackerGeometry_ = std::shared_ptr - (trackerBuilder.build(&(*geometricDet), *ptp, tTopo)); + trackerGeometry_ = std::shared_ptr(trackerBuilder.build(&(*geometricDet), *ptp, tTopo)); } if (doMuon_) { @@ -540,15 +452,12 @@ AlignmentProducerBase::createGeometries(const edm::EventSetup& iSetup, muonDTGeometry_ = std::make_shared(); DTGeometryBuilder.build(*muonDTGeometry_, &(*cpv), *mdc); muonCSCGeometry_ = std::make_shared(); - CSCGeometryBuilder.build(*muonCSCGeometry_, &(*cpv), *mdc ); + CSCGeometryBuilder.build(*muonCSCGeometry_, &(*cpv), *mdc); } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::applyAlignmentsToDB(const edm::EventSetup& setup) -{ +void AlignmentProducerBase::applyAlignmentsToDB(const edm::EventSetup& setup) { // Retrieve and apply alignments, if requested (requires z setup) if (applyDbAlignment_) { // we need GlobalPositionRcd - and have to keep track for later removal @@ -559,40 +468,24 @@ AlignmentProducerBase::applyAlignmentsToDB(const edm::EventSetup& setup) globalPositions_ = std::make_unique(*globalAlignments); if (doTracker_) { - applyDB - (trackerGeometry_.get(), setup, - align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Tracker)) - ); - - applyDB(trackerGeometry_.get(), setup); + applyDB( + trackerGeometry_.get(), setup, align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Tracker))); + + applyDB(trackerGeometry_.get(), setup); } if (doMuon_) { - applyDB - (muonDTGeometry_.get(), setup, - align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Muon)) - ); - - applyDB - (muonCSCGeometry_.get(), setup, - align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Muon)) - ); + applyDB( + muonDTGeometry_.get(), setup, align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Muon))); + + applyDB( + muonCSCGeometry_.get(), setup, align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Muon))); } } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::createAlignables(const TrackerTopology* tTopo, bool update) -{ +void AlignmentProducerBase::createAlignables(const TrackerTopology* tTopo, bool update) { if (doTracker_) { if (update) { alignableTracker_->update(trackerGeometry_.get(), tTopo); @@ -618,25 +511,17 @@ AlignmentProducerBase::createAlignables(const TrackerTopology* tTopo, bool updat } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::buildParameterStore() -{ +void AlignmentProducerBase::buildParameterStore() { // Create alignment parameter builder - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::buildParameterStore" - << "Creating AlignmentParameterBuilder"; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::buildParameterStore" + << "Creating AlignmentParameterBuilder"; - const auto& alParamBuildCfg = - config_.getParameter("ParameterBuilder"); - const auto& alParamStoreCfg = - config_.getParameter("ParameterStore"); + const auto& alParamBuildCfg = config_.getParameter("ParameterBuilder"); + const auto& alParamStoreCfg = config_.getParameter("ParameterStore"); - AlignmentParameterBuilder alignmentParameterBuilder{alignableTracker_, - alignableMuon_, - alignableExtras_, - alParamBuildCfg}; + AlignmentParameterBuilder alignmentParameterBuilder{ + alignableTracker_, alignableMuon_, alignableExtras_, alParamBuildCfg}; // Fix alignables if requested if (stNFixAlignables_ > 0) { @@ -645,32 +530,24 @@ AlignmentProducerBase::buildParameterStore() // Get list of alignables const auto& alignables = alignmentParameterBuilder.alignables(); - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::buildParameterStore" - << "got " << alignables.size() << " alignables"; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::buildParameterStore" + << "got " << alignables.size() << " alignables"; // Create AlignmentParameterStore - alignmentParameterStore_ = - new AlignmentParameterStore(alignables, alParamStoreCfg); - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::buildParameterStore" - << "AlignmentParameterStore created!"; + alignmentParameterStore_ = new AlignmentParameterStore(alignables, alParamStoreCfg); + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::buildParameterStore" + << "AlignmentParameterStore created!"; } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::applyMisalignment() -{ +void AlignmentProducerBase::applyMisalignment() { // Apply misalignment scenario to alignable tracker and muon if requested // WARNING: this assumes scenarioConfig can be passed to both muon and tracker if (doMisalignmentScenario_ && (doTracker_ || doMuon_)) { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::applyMisalignment" - << "Applying misalignment scenario to " - << (doTracker_ ? "tracker" : "") - << (doMuon_ ? (doTracker_ ? " and muon" : "muon") : "."); + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::applyMisalignment" + << "Applying misalignment scenario to " << (doTracker_ ? "tracker" : "") + << (doMuon_ ? (doTracker_ ? " and muon" : "muon") : "."); const auto& scenarioConfig = config_.getParameterSet("MisalignmentScenario"); @@ -684,155 +561,137 @@ AlignmentProducerBase::applyMisalignment() } } else { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::applyMisalignment" - << "NOT applying misalignment scenario!"; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::applyMisalignment" + << "NOT applying misalignment scenario!"; } // Apply simple misalignment - const auto& sParSel = - config_.getParameter("parameterSelectorSimple"); - simpleMisalignment(alignmentParameterStore_->alignables(), sParSel, - stRandomShift_, stRandomRotation_, true); + const auto& sParSel = config_.getParameter("parameterSelectorSimple"); + simpleMisalignment(alignmentParameterStore_->alignables(), sParSel, stRandomShift_, stRandomRotation_, true); } - // ---------------------------------------------------------------------------- -void -AlignmentProducerBase::simpleMisalignment(const align::Alignables &alivec, - const std::string &selection, - float shift, float rot, bool local) -{ - - std::ostringstream output; // collecting output +void AlignmentProducerBase::simpleMisalignment( + const align::Alignables& alivec, const std::string& selection, float shift, float rot, bool local) { + std::ostringstream output; // collecting output if (shift > 0. || rot > 0.) { - output << "Adding random flat shift of max size " << shift - << " and adding random flat rotation of max size " << rot <<" to "; + output << "Adding random flat shift of max size " << shift << " and adding random flat rotation of max size " << rot + << " to "; std::vector commSel(0); if (selection != "-1") { - AlignmentParameterSelector aSelector(nullptr,nullptr); // no alignable needed here... + AlignmentParameterSelector aSelector(nullptr, nullptr); // no alignable needed here... const std::vector cSel(aSelector.convertParamSel(selection)); if (cSel.size() < RigidBodyAlignmentParameters::N_PARAM) { throw cms::Exception("BadConfig") - << "[AlignmentProducerBase::simpleMisalignment_]\n" - << "Expect selection string '" << selection << "' to be at least of length " - << RigidBodyAlignmentParameters::N_PARAM << " or to be '-1'.\n" - << "(Most probably you have to adjust the parameter 'parameterSelectorSimple'.)"; + << "[AlignmentProducerBase::simpleMisalignment_]\n" + << "Expect selection string '" << selection << "' to be at least of length " + << RigidBodyAlignmentParameters::N_PARAM << " or to be '-1'.\n" + << "(Most probably you have to adjust the parameter 'parameterSelectorSimple'.)"; } - for (const auto& cIter: cSel) { + for (const auto& cIter : cSel) { commSel.push_back(cIter == '0' ? false : true); } - output << "parameters defined by (" << selection - << "), representing (x,y,z,alpha,beta,gamma),"; + output << "parameters defined by (" << selection << "), representing (x,y,z,alpha,beta,gamma),"; } else { output << "the active parameters of each alignable,"; } output << " in " << (local ? "local" : "global") << " frame."; - for (const auto& ali: alivec) { + for (const auto& ali : alivec) { std::vector mysel(commSel.empty() ? ali->alignmentParameters()->selector() : commSel); - if (std::abs(shift)>0.00001) { + if (std::abs(shift) > 0.00001) { double s0 = 0., s1 = 0., s2 = 0.; - if (mysel[RigidBodyAlignmentParameters::dx]) s0 = shift * double(random()%1000-500)/500.; - if (mysel[RigidBodyAlignmentParameters::dy]) s1 = shift * double(random()%1000-500)/500.; - if (mysel[RigidBodyAlignmentParameters::dz]) s2 = shift * double(random()%1000-500)/500.; - - if (local) ali->move(ali->surface().toGlobal(align::LocalVector(s0,s1,s2))); - else ali->move(align::GlobalVector(s0,s1,s2)); + if (mysel[RigidBodyAlignmentParameters::dx]) + s0 = shift * double(random() % 1000 - 500) / 500.; + if (mysel[RigidBodyAlignmentParameters::dy]) + s1 = shift * double(random() % 1000 - 500) / 500.; + if (mysel[RigidBodyAlignmentParameters::dz]) + s2 = shift * double(random() % 1000 - 500) / 500.; + + if (local) + ali->move(ali->surface().toGlobal(align::LocalVector(s0, s1, s2))); + else + ali->move(align::GlobalVector(s0, s1, s2)); //AlignmentPositionError ape(dx,dy,dz); //ali->addAlignmentPositionError(ape); } - if (std::abs(rot)>0.00001) { + if (std::abs(rot) > 0.00001) { align::EulerAngles r(3); - if (mysel[RigidBodyAlignmentParameters::dalpha]) r(1)=rot*double(random()%1000-500)/500.; - if (mysel[RigidBodyAlignmentParameters::dbeta]) r(2)=rot*double(random()%1000-500)/500.; - if (mysel[RigidBodyAlignmentParameters::dgamma]) r(3)=rot*double(random()%1000-500)/500.; + if (mysel[RigidBodyAlignmentParameters::dalpha]) + r(1) = rot * double(random() % 1000 - 500) / 500.; + if (mysel[RigidBodyAlignmentParameters::dbeta]) + r(2) = rot * double(random() % 1000 - 500) / 500.; + if (mysel[RigidBodyAlignmentParameters::dgamma]) + r(3) = rot * double(random() % 1000 - 500) / 500.; const align::RotationType mrot = align::toMatrix(r); - if (local) ali->rotateInLocalFrame(mrot); - else ali->rotateInGlobalFrame(mrot); + if (local) + ali->rotateInLocalFrame(mrot); + else + ali->rotateInGlobalFrame(mrot); //ali->addAlignmentPositionErrorFromRotation(mrot); } - } // end loop on alignables + } // end loop on alignables } else { output << "No simple misalignment added!"; } - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::simpleMisalignment" << output.str(); + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::simpleMisalignment" << output.str(); } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::applyAlignmentsToGeometry() -{ - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::applyAlignmentsToGeometry" - << "Now physically apply alignments to geometry..."; +void AlignmentProducerBase::applyAlignmentsToGeometry() { + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::applyAlignmentsToGeometry" + << "Now physically apply alignments to geometry..."; // Propagate changes to reconstruction geometry (from initialisation or iteration) GeometryAligner aligner; if (doTracker_) { if (!alignableTracker_) { - throw cms::Exception("LogicError") - << "@SUB=AlignmentProducerBase::applyAlignmentsToGeometry\n" - << "Trying to apply tracker alignment before creating it."; + throw cms::Exception("LogicError") << "@SUB=AlignmentProducerBase::applyAlignmentsToGeometry\n" + << "Trying to apply tracker alignment before creating it."; } std::unique_ptr alignments{alignableTracker_->alignments()}; - std::unique_ptr - alignmentErrExt{alignableTracker_->alignmentErrors()}; - std::unique_ptr - aliDeforms{alignableTracker_->surfaceDeformations()}; + std::unique_ptr alignmentErrExt{alignableTracker_->alignmentErrors()}; + std::unique_ptr aliDeforms{alignableTracker_->surfaceDeformations()}; - aligner.applyAlignments(trackerGeometry_.get(), alignments.get(), - alignmentErrExt.get(), AlignTransform()); + aligner.applyAlignments(trackerGeometry_.get(), alignments.get(), alignmentErrExt.get(), AlignTransform()); aligner.attachSurfaceDeformations(trackerGeometry_.get(), aliDeforms.get()); } if (doMuon_) { if (!alignableMuon_) { - throw cms::Exception("LogicError") - << "@SUB=AlignmentProducerBase::applyAlignmentsToGeometry\n" - << "Trying to apply muon alignment before creating it."; + throw cms::Exception("LogicError") << "@SUB=AlignmentProducerBase::applyAlignmentsToGeometry\n" + << "Trying to apply muon alignment before creating it."; } std::unique_ptr dtAlignments{alignableMuon_->dtAlignments()}; std::unique_ptr cscAlignments{alignableMuon_->cscAlignments()}; - std::unique_ptr - dtAlignmentErrExt{alignableMuon_->dtAlignmentErrorsExtended()}; - std::unique_ptr - cscAlignmentErrExt{alignableMuon_->cscAlignmentErrorsExtended()}; + std::unique_ptr dtAlignmentErrExt{alignableMuon_->dtAlignmentErrorsExtended()}; + std::unique_ptr cscAlignmentErrExt{alignableMuon_->cscAlignmentErrorsExtended()}; - aligner.applyAlignments(muonDTGeometry_.get(), dtAlignments.get(), - dtAlignmentErrExt.get(), AlignTransform()); - aligner.applyAlignments(muonCSCGeometry_.get(), cscAlignments.get(), - cscAlignmentErrExt.get(), AlignTransform()); + aligner.applyAlignments(muonDTGeometry_.get(), dtAlignments.get(), dtAlignmentErrExt.get(), AlignTransform()); + aligner.applyAlignments(muonCSCGeometry_.get(), cscAlignments.get(), cscAlignmentErrExt.get(), AlignTransform()); } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::readInSurveyRcds(const edm::EventSetup& iSetup) -{ - +void AlignmentProducerBase::readInSurveyRcds(const edm::EventSetup& iSetup) { // Get Survey Rcds and add Survey Info - if ( doTracker_ && useSurvey_ ){ + if (doTracker_ && useSurvey_) { bool tkSurveyBool = watchTkSurveyRcd_.check(iSetup); bool tkSurveyErrBool = watchTkSurveyErrExtRcd_.check(iSetup); edm::LogInfo("Alignment") << "watcher tksurveyrcd: " << tkSurveyBool; edm::LogInfo("Alignment") << "watcher tksurveyerrrcd: " << tkSurveyErrBool; - if ( tkSurveyBool || tkSurveyErrBool){ - + if (tkSurveyBool || tkSurveyErrBool) { edm::LogInfo("Alignment") << "ADDING THE SURVEY INFORMATION"; edm::ESHandle surveys; edm::ESHandle surveyErrors; @@ -840,20 +699,20 @@ AlignmentProducerBase::readInSurveyRcds(const edm::EventSetup& iSetup) iSetup.get().get(surveys); iSetup.get().get(surveyErrors); - surveyIndex_ = 0; + surveyIndex_ = 0; surveyValues_ = &*surveys; surveyErrors_ = &*surveyErrors; addSurveyInfo(alignableTracker_); } } - if ( doMuon_ && useSurvey_) { + if (doMuon_ && useSurvey_) { bool DTSurveyBool = watchTkSurveyRcd_.check(iSetup); bool DTSurveyErrBool = watchTkSurveyErrExtRcd_.check(iSetup); bool CSCSurveyBool = watchTkSurveyRcd_.check(iSetup); bool CSCSurveyErrBool = watchTkSurveyErrExtRcd_.check(iSetup); - if ( DTSurveyBool || DTSurveyErrBool || CSCSurveyBool || CSCSurveyErrBool ){ + if (DTSurveyBool || DTSurveyErrBool || CSCSurveyBool || CSCSurveyErrBool) { edm::ESHandle dtSurveys; edm::ESHandle dtSurveyErrors; edm::ESHandle cscSurveys; @@ -864,48 +723,42 @@ AlignmentProducerBase::readInSurveyRcds(const edm::EventSetup& iSetup) iSetup.get().get(cscSurveys); iSetup.get().get(cscSurveyErrors); - surveyIndex_ = 0; + surveyIndex_ = 0; surveyValues_ = &*dtSurveys; surveyErrors_ = &*dtSurveyErrors; const auto& barrels = alignableMuon_->DTBarrel(); - for (const auto& barrel: barrels) addSurveyInfo(barrel); + for (const auto& barrel : barrels) + addSurveyInfo(barrel); - surveyIndex_ = 0; + surveyIndex_ = 0; surveyValues_ = &*cscSurveys; surveyErrors_ = &*cscSurveyErrors; const auto& endcaps = alignableMuon_->CSCEndcaps(); - for (const auto& endcap: endcaps) addSurveyInfo(endcap); - + for (const auto& endcap : endcaps) + addSurveyInfo(endcap); } } - } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::addSurveyInfo(Alignable* ali) -{ +void AlignmentProducerBase::addSurveyInfo(Alignable* ali) { const auto& comps = ali->components(); - for (const auto& comp: comps) addSurveyInfo(comp); + for (const auto& comp : comps) + addSurveyInfo(comp); const SurveyError& error = surveyErrors_->m_surveyErrors[surveyIndex_]; - if ( ali->id() != error.rawId() || - ali->alignableObjectId() != error.structureType() ) - { - throw cms::Exception("DatabaseError") - << "Error reading survey info from DB. Mismatched id!"; - } + if (ali->id() != error.rawId() || ali->alignableObjectId() != error.structureType()) { + throw cms::Exception("DatabaseError") << "Error reading survey info from DB. Mismatched id!"; + } const auto& pos = surveyValues_->m_align[surveyIndex_].translation(); const auto& rot = surveyValues_->m_align[surveyIndex_].rotation(); - AlignableSurface surf(align::PositionType(pos.x(), pos.y(), pos.z()), - align::RotationType(rot.xx(), rot.xy(), rot.xz(), - rot.yx(), rot.yy(), rot.yz(), - rot.zx(), rot.zy(), rot.zz())); + AlignableSurface surf( + align::PositionType(pos.x(), pos.y(), pos.z()), + align::RotationType(rot.xx(), rot.xy(), rot.xz(), rot.yx(), rot.yy(), rot.yz(), rot.zx(), rot.zy(), rot.zz())); surf.setWidth(ali->surface().width()); surf.setLength(ali->surface().length()); @@ -915,51 +768,42 @@ AlignmentProducerBase::addSurveyInfo(Alignable* ali) ++surveyIndex_; } - //------------------------------------------------------------------------------ -bool -AlignmentProducerBase::finish() -{ - - for (const auto& monitor: monitors_) monitor->endOfJob(); +bool AlignmentProducerBase::finish() { + for (const auto& monitor : monitors_) + monitor->endOfJob(); if (alignmentAlgo_->processesEvents() && nevent_ == 0) { return false; } if (saveToDB_ || saveApeToDB_ || saveDeformationsToDB_) { - if (alignmentAlgo_->storeAlignments()) storeAlignmentsToDB(); + if (alignmentAlgo_->storeAlignments()) + storeAlignmentsToDB(); } else { - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::finish" - << "No payload to be stored!"; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::finish" + << "No payload to be stored!"; } // takes care of storing output of calibrations, but needs to be called only // after 'storeAlignmentsToDB()' - for (const auto& iCal:calibrations_) iCal->endOfJob(); + for (const auto& iCal : calibrations_) + iCal->endOfJob(); return true; } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::storeAlignmentsToDB() -{ - const auto runRangeSelectionVPSet = - config_.getParameterSetVector("RunRangeSelection"); +void AlignmentProducerBase::storeAlignmentsToDB() { + const auto runRangeSelectionVPSet = config_.getParameterSetVector("RunRangeSelection"); // handle PCL use case const auto& uniqueRunRanges = - (runAtPCL_ ? - align::makeUniqueRunRanges(runRangeSelectionVPSet, firstRun_) : - uniqueRunRanges_); + (runAtPCL_ ? align::makeUniqueRunRanges(runRangeSelectionVPSet, firstRun_) : uniqueRunRanges_); std::vector beamSpotParameters; - for (const auto& iRunRange: uniqueRunRanges) { - + for (const auto& iRunRange : uniqueRunRanges) { alignmentAlgo_->setParametersForRunRange(iRunRange); // Save alignments to database @@ -971,13 +815,11 @@ AlignmentProducerBase::storeAlignmentsToDB() if (alignableExtras_) { auto& alis = alignableExtras_->beamSpot(); if (!alis.empty()) { - auto beamSpotAliPars = - dynamic_cast(alis[0]->alignmentParameters()); + auto beamSpotAliPars = dynamic_cast(alis[0]->alignmentParameters()); if (!beamSpotAliPars) { - throw cms::Exception("LogicError") - << "@SUB=AlignmentProducerBase::storeAlignmentsToDB\n" - << "First alignable of alignableExtras_ does not have " - << "'BeamSpotAlignmentParameters', while it should have."; + throw cms::Exception("LogicError") << "@SUB=AlignmentProducerBase::storeAlignmentsToDB\n" + << "First alignable of alignableExtras_ does not have " + << "'BeamSpotAlignmentParameters', while it should have."; } beamSpotParameters.push_back(beamSpotAliPars->parameters()); @@ -989,37 +831,30 @@ AlignmentProducerBase::storeAlignmentsToDB() std::ostringstream bsOutput; auto itPar = beamSpotParameters.cbegin(); - for (auto iRunRange = uniqueRunRanges.cbegin(); - iRunRange != uniqueRunRanges.cend(); - ++iRunRange, ++itPar) { + for (auto iRunRange = uniqueRunRanges.cbegin(); iRunRange != uniqueRunRanges.cend(); ++iRunRange, ++itPar) { bsOutput << "Run range: " << (*iRunRange).first << " - " << (*iRunRange).second << "\n"; bsOutput << " Displacement: x=" << (*itPar)[0] << ", y=" << (*itPar)[1] << "\n"; bsOutput << " Slope: dx/dz=" << (*itPar)[2] << ", dy/dz=" << (*itPar)[3] << "\n"; } - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::storeAlignmentsToDB" - << "Parameters for alignable beamspot:\n" << bsOutput.str(); + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::storeAlignmentsToDB" + << "Parameters for alignable beamspot:\n" + << bsOutput.str(); } } - //------------------------------------------------------------------------------ -void -AlignmentProducerBase::writeForRunRange(cond::Time_t time) -{ - if (doTracker_) { // first tracker - const AlignTransform* trackerGlobal{nullptr}; // will be 'removed' from constants - if (globalPositions_) { // i.e. applied before in applyDB - trackerGlobal = &align::DetectorGlobalPosition(*globalPositions_, - DetId(DetId::Tracker)); +void AlignmentProducerBase::writeForRunRange(cond::Time_t time) { + if (doTracker_) { // first tracker + const AlignTransform* trackerGlobal{nullptr}; // will be 'removed' from constants + if (globalPositions_) { // i.e. applied before in applyDB + trackerGlobal = &align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Tracker)); } auto alignments = alignableTracker_->alignments(); auto alignmentErrors = alignableTracker_->alignmentErrors(); - this->writeDB(alignments, "TrackerAlignmentRcd", - alignmentErrors, "TrackerAlignmentErrorExtendedRcd", trackerGlobal, - time); + this->writeDB( + alignments, "TrackerAlignmentRcd", alignmentErrors, "TrackerAlignmentErrorExtendedRcd", trackerGlobal, time); // Save surface deformations to database if (saveDeformationsToDB_) { @@ -1028,115 +863,96 @@ AlignmentProducerBase::writeForRunRange(cond::Time_t time) } } - if (doMuon_) { // now muon - const AlignTransform* muonGlobal{nullptr}; // will be 'removed' from constants - if (globalPositions_) { // i.e. applied before in applyDB - muonGlobal = &align::DetectorGlobalPosition(*globalPositions_, - DetId(DetId::Muon)); + if (doMuon_) { // now muon + const AlignTransform* muonGlobal{nullptr}; // will be 'removed' from constants + if (globalPositions_) { // i.e. applied before in applyDB + muonGlobal = &align::DetectorGlobalPosition(*globalPositions_, DetId(DetId::Muon)); } // Get alignments+errors, first DT - ownership taken over by writeDB(..), so no delete auto alignments = alignableMuon_->dtAlignments(); auto alignmentErrors = alignableMuon_->dtAlignmentErrorsExtended(); - this->writeDB(alignments, "DTAlignmentRcd", - alignmentErrors, "DTAlignmentErrorExtendedRcd", muonGlobal, - time); + this->writeDB(alignments, "DTAlignmentRcd", alignmentErrors, "DTAlignmentErrorExtendedRcd", muonGlobal, time); // Get alignments+errors, now CSC - ownership taken over by writeDB(..), so no delete alignments = alignableMuon_->cscAlignments(); alignmentErrors = alignableMuon_->cscAlignmentErrorsExtended(); - this->writeDB(alignments, "CSCAlignmentRcd", - alignmentErrors, "CSCAlignmentErrorExtendedRcd", muonGlobal, - time); + this->writeDB(alignments, "CSCAlignmentRcd", alignmentErrors, "CSCAlignmentErrorExtendedRcd", muonGlobal, time); } } - //------------------------------------------------------------------------------ void AlignmentProducerBase::writeDB(Alignments* alignments, const std::string& alignRcd, AlignmentErrorsExtended* alignmentErrors, const std::string& errRcd, const AlignTransform* globalCoordinates, - cond::Time_t time) const -{ + cond::Time_t time) const { Alignments* tempAlignments = alignments; AlignmentErrorsExtended* tempAlignmentErrorsExtended = alignmentErrors; // Call service edm::Service poolDb; - if (!poolDb.isAvailable()) { // Die if not available - delete tempAlignments; // promised to take over ownership... - delete tempAlignmentErrorsExtended; // dito + if (!poolDb.isAvailable()) { // Die if not available + delete tempAlignments; // promised to take over ownership... + delete tempAlignmentErrorsExtended; // dito throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; } if (globalCoordinates // happens only if (applyDbAlignment_ == true) && globalCoordinates->transform() != AlignTransform::Transform::Identity) { - - tempAlignments = new Alignments(); // temporary storage for + tempAlignments = new Alignments(); // temporary storage for tempAlignmentErrorsExtended = new AlignmentErrorsExtended(); // final alignments and errors GeometryAligner aligner; - aligner.removeGlobalTransform(alignments, alignmentErrors, - *globalCoordinates, - tempAlignments, tempAlignmentErrorsExtended); + aligner.removeGlobalTransform( + alignments, alignmentErrors, *globalCoordinates, tempAlignments, tempAlignmentErrorsExtended); delete alignments; // have to delete original alignments delete alignmentErrors; // same thing for the errors - edm::LogInfo("Alignment") - << "@SUB=AlignmentProducerBase::writeDB" - << "globalCoordinates removed from alignments (" << alignRcd - << ") and errors (" << alignRcd << ")."; + edm::LogInfo("Alignment") << "@SUB=AlignmentProducerBase::writeDB" + << "globalCoordinates removed from alignments (" << alignRcd << ") and errors (" + << alignRcd << ")."; } if (saveToDB_) { - edm::LogInfo("Alignment") << "Writing Alignments for run " << time - << " to " << alignRcd << "."; + edm::LogInfo("Alignment") << "Writing Alignments for run " << time << " to " << alignRcd << "."; poolDb->writeOne(tempAlignments, time, alignRcd); - } else { // poolDb->writeOne(..) takes over 'alignments' ownership,... - delete tempAlignments; // ...otherwise we have to delete, as promised! + } else { // poolDb->writeOne(..) takes over 'alignments' ownership,... + delete tempAlignments; // ...otherwise we have to delete, as promised! } if (saveApeToDB_) { - edm::LogInfo("Alignment") << "Writing AlignmentErrorsExtended for run " << time - << " to " << errRcd << "."; + edm::LogInfo("Alignment") << "Writing AlignmentErrorsExtended for run " << time << " to " << errRcd << "."; poolDb->writeOne(tempAlignmentErrorsExtended, time, errRcd); - } else { // poolDb->writeOne(..) takes over 'alignmentErrors' ownership,... - delete tempAlignmentErrorsExtended; // ...otherwise we have to delete, as promised! + } else { // poolDb->writeOne(..) takes over 'alignmentErrors' ownership,... + delete tempAlignmentErrorsExtended; // ...otherwise we have to delete, as promised! } } - //------------------------------------------------------------------------------ void AlignmentProducerBase::writeDB(AlignmentSurfaceDeformations* alignmentSurfaceDeformations, const std::string& surfaceDeformationRcd, - cond::Time_t time) const -{ + cond::Time_t time) const { // Call service edm::Service poolDb; - if (!poolDb.isAvailable()) { // Die if not available - delete alignmentSurfaceDeformations; // promised to take over ownership... + if (!poolDb.isAvailable()) { // Die if not available + delete alignmentSurfaceDeformations; // promised to take over ownership... throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; } if (saveDeformationsToDB_) { - edm::LogInfo("Alignment") << "Writing AlignmentSurfaceDeformations for run " << time - << " to " << surfaceDeformationRcd << "."; - poolDb->writeOne(alignmentSurfaceDeformations, time, - surfaceDeformationRcd); - } else { // poolDb->writeOne(..) takes over 'surfaceDeformation' ownership,... - delete alignmentSurfaceDeformations; // ...otherwise we have to delete, as promised! + edm::LogInfo("Alignment") << "Writing AlignmentSurfaceDeformations for run " << time << " to " + << surfaceDeformationRcd << "."; + poolDb->writeOne(alignmentSurfaceDeformations, time, surfaceDeformationRcd); + } else { // poolDb->writeOne(..) takes over 'surfaceDeformation' ownership,... + delete alignmentSurfaceDeformations; // ...otherwise we have to delete, as promised! } } - //------------------------------------------------------------------------------ -template -bool -AlignmentProducerBase::hasParameter(const edm::ParameterSet& config, - const std::string& name) -{ +template +bool AlignmentProducerBase::hasParameter(const edm::ParameterSet& config, const std::string& name) { try { config.getParameter(name); } catch (const edm::Exception& e) { diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentSeedSelector.cc b/Alignment/CommonAlignmentProducer/src/AlignmentSeedSelector.cc index fcc5da55ad966..56879b6d543fa 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentSeedSelector.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentSeedSelector.cc @@ -4,38 +4,30 @@ // constructor ---------------------------------------------------------------- -AlignmentSeedSelector::AlignmentSeedSelector(const edm::ParameterSet & cfg) : - applySeedNumber( cfg.getParameter( "applySeedNumber" ) ), - minNSeeds ( cfg.getParameter( "minNSeeds" ) ), - maxNSeeds ( cfg.getParameter( "maxNSeeds" ) ) -{ - +AlignmentSeedSelector::AlignmentSeedSelector(const edm::ParameterSet& cfg) + : applySeedNumber(cfg.getParameter("applySeedNumber")), + minNSeeds(cfg.getParameter("minNSeeds")), + maxNSeeds(cfg.getParameter("maxNSeeds")) { if (applySeedNumber) - edm::LogInfo("AlignmentSeedSelector") - << "apply seedNumber N<=" << minNSeeds; - + edm::LogInfo("AlignmentSeedSelector") << "apply seedNumber N<=" << minNSeeds; } // destructor ----------------------------------------------------------------- -AlignmentSeedSelector::~AlignmentSeedSelector() -{} - +AlignmentSeedSelector::~AlignmentSeedSelector() {} // do selection --------------------------------------------------------------- -AlignmentSeedSelector::Seeds -AlignmentSeedSelector::select(const Seeds& seeds, const edm::Event& evt) const -{ +AlignmentSeedSelector::Seeds AlignmentSeedSelector::select(const Seeds& seeds, const edm::Event& evt) const { Seeds result = seeds; // apply minimum/maximum multiplicity requirement (if selected) if (applySeedNumber) { - if (result.size()<(unsigned int)minNSeeds || result.size()>(unsigned int)maxNSeeds ) result.clear(); + if (result.size() < (unsigned int)minNSeeds || result.size() > (unsigned int)maxNSeeds) + result.clear(); } return result; - } // make basic cuts ------------------------------------------------------------ diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentTrackSelector.cc b/Alignment/CommonAlignmentProducer/src/AlignmentTrackSelector.cc index 98521251d6011..eff9c2d35733d 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentTrackSelector.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentTrackSelector.cc @@ -30,298 +30,285 @@ const int kFPIX = PixelSubdetector::PixelEndcap; // constructor ---------------------------------------------------------------- -AlignmentTrackSelector::AlignmentTrackSelector(const edm::ParameterSet & cfg, edm::ConsumesCollector& iC) : - applyBasicCuts_( cfg.getParameter( "applyBasicCuts" ) ), - applyNHighestPt_( cfg.getParameter( "applyNHighestPt" ) ), - applyMultiplicityFilter_( cfg.getParameter( "applyMultiplicityFilter" ) ), - seedOnlyFromAbove_( cfg.getParameter( "seedOnlyFrom" ) ), - applyIsolation_( cfg.getParameter( "applyIsolationCut" ) ), - chargeCheck_( cfg.getParameter( "applyChargeCheck" ) ), - nHighestPt_( cfg.getParameter( "nHighestPt" ) ), - minMultiplicity_ ( cfg.getParameter( "minMultiplicity" ) ), - maxMultiplicity_ ( cfg.getParameter( "maxMultiplicity" ) ), - multiplicityOnInput_ ( cfg.getParameter( "multiplicityOnInput" ) ), - ptMin_( cfg.getParameter( "ptMin" ) ), - ptMax_( cfg.getParameter( "ptMax" ) ), - pMin_( cfg.getParameter( "pMin" ) ), - pMax_( cfg.getParameter( "pMax" ) ), - etaMin_( cfg.getParameter( "etaMin" ) ), - etaMax_( cfg.getParameter( "etaMax" ) ), - phiMin_( cfg.getParameter( "phiMin" ) ), - phiMax_( cfg.getParameter( "phiMax" ) ), - nHitMin_( cfg.getParameter( "nHitMin" ) ), - nHitMax_( cfg.getParameter( "nHitMax" ) ), - chi2nMax_( cfg.getParameter( "chi2nMax" ) ), - d0Min_( cfg.getParameter( "d0Min" ) ), - d0Max_( cfg.getParameter( "d0Max" ) ), - dzMin_( cfg.getParameter( "dzMin" ) ), - dzMax_( cfg.getParameter( "dzMax" ) ), - theCharge_( cfg.getParameter( "theCharge" ) ), - minHitChargeStrip_( cfg.getParameter( "minHitChargeStrip" ) ), - minHitIsolation_( cfg.getParameter( "minHitIsolation" ) ), - countStereoHitAs2D_( cfg.getParameter( "countStereoHitAs2D" ) ), - nHitMin2D_( cfg.getParameter( "nHitMin2D" ) ), - // Ugly to use the same getParameter n times, but this allows const cut variables... - minHitsinTIB_(cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inTIB" ) ), - minHitsinTOB_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inTOB" ) ), - minHitsinTID_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inTID" ) ), - minHitsinTEC_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inTEC" ) ), - minHitsinBPIX_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inBPIX" ) ), - minHitsinFPIX_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inFPIX" ) ), - minHitsinPIX_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inPIXEL" ) ), - minHitsinTIDplus_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inTIDplus" ) ), - minHitsinTIDminus_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inTIDminus" ) ), - minHitsinTECplus_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inTECplus" ) ), - minHitsinTECminus_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inTECminus" ) ), - minHitsinFPIXplus_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inFPIXplus" ) ), - minHitsinFPIXminus_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inFPIXminus" ) ), - minHitsinENDCAP_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inENDCAP" ) ), - minHitsinENDCAPplus_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inENDCAPplus" ) ), - minHitsinENDCAPminus_ (cfg.getParameter( "minHitsPerSubDet" ).getParameter( "inENDCAPminus" ) ), - maxHitDiffEndcaps_( cfg.getParameter( "maxHitDiffEndcaps" ) ), - nLostHitMax_( cfg.getParameter( "nLostHitMax" ) ), - RorZofFirstHitMin_( cfg.getParameter >( "RorZofFirstHitMin" ) ), - RorZofFirstHitMax_( cfg.getParameter >( "RorZofFirstHitMax" ) ), - RorZofLastHitMin_( cfg.getParameter >( "RorZofLastHitMin" ) ), - RorZofLastHitMax_( cfg.getParameter >( "RorZofLastHitMax" ) ), - clusterValueMapTag_(cfg.getParameter("hitPrescaleMapTag")), - minPrescaledHits_( cfg.getParameter("minPrescaledHits")), - applyPrescaledHitsFilter_(!clusterValueMapTag_.encode().empty() && minPrescaledHits_ > 0) -{ - if(applyIsolation_) { +AlignmentTrackSelector::AlignmentTrackSelector(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC) + : applyBasicCuts_(cfg.getParameter("applyBasicCuts")), + applyNHighestPt_(cfg.getParameter("applyNHighestPt")), + applyMultiplicityFilter_(cfg.getParameter("applyMultiplicityFilter")), + seedOnlyFromAbove_(cfg.getParameter("seedOnlyFrom")), + applyIsolation_(cfg.getParameter("applyIsolationCut")), + chargeCheck_(cfg.getParameter("applyChargeCheck")), + nHighestPt_(cfg.getParameter("nHighestPt")), + minMultiplicity_(cfg.getParameter("minMultiplicity")), + maxMultiplicity_(cfg.getParameter("maxMultiplicity")), + multiplicityOnInput_(cfg.getParameter("multiplicityOnInput")), + ptMin_(cfg.getParameter("ptMin")), + ptMax_(cfg.getParameter("ptMax")), + pMin_(cfg.getParameter("pMin")), + pMax_(cfg.getParameter("pMax")), + etaMin_(cfg.getParameter("etaMin")), + etaMax_(cfg.getParameter("etaMax")), + phiMin_(cfg.getParameter("phiMin")), + phiMax_(cfg.getParameter("phiMax")), + nHitMin_(cfg.getParameter("nHitMin")), + nHitMax_(cfg.getParameter("nHitMax")), + chi2nMax_(cfg.getParameter("chi2nMax")), + d0Min_(cfg.getParameter("d0Min")), + d0Max_(cfg.getParameter("d0Max")), + dzMin_(cfg.getParameter("dzMin")), + dzMax_(cfg.getParameter("dzMax")), + theCharge_(cfg.getParameter("theCharge")), + minHitChargeStrip_(cfg.getParameter("minHitChargeStrip")), + minHitIsolation_(cfg.getParameter("minHitIsolation")), + countStereoHitAs2D_(cfg.getParameter("countStereoHitAs2D")), + nHitMin2D_(cfg.getParameter("nHitMin2D")), + // Ugly to use the same getParameter n times, but this allows const cut variables... + minHitsinTIB_(cfg.getParameter("minHitsPerSubDet").getParameter("inTIB")), + minHitsinTOB_(cfg.getParameter("minHitsPerSubDet").getParameter("inTOB")), + minHitsinTID_(cfg.getParameter("minHitsPerSubDet").getParameter("inTID")), + minHitsinTEC_(cfg.getParameter("minHitsPerSubDet").getParameter("inTEC")), + minHitsinBPIX_(cfg.getParameter("minHitsPerSubDet").getParameter("inBPIX")), + minHitsinFPIX_(cfg.getParameter("minHitsPerSubDet").getParameter("inFPIX")), + minHitsinPIX_(cfg.getParameter("minHitsPerSubDet").getParameter("inPIXEL")), + minHitsinTIDplus_(cfg.getParameter("minHitsPerSubDet").getParameter("inTIDplus")), + minHitsinTIDminus_(cfg.getParameter("minHitsPerSubDet").getParameter("inTIDminus")), + minHitsinTECplus_(cfg.getParameter("minHitsPerSubDet").getParameter("inTECplus")), + minHitsinTECminus_(cfg.getParameter("minHitsPerSubDet").getParameter("inTECminus")), + minHitsinFPIXplus_(cfg.getParameter("minHitsPerSubDet").getParameter("inFPIXplus")), + minHitsinFPIXminus_(cfg.getParameter("minHitsPerSubDet").getParameter("inFPIXminus")), + minHitsinENDCAP_(cfg.getParameter("minHitsPerSubDet").getParameter("inENDCAP")), + minHitsinENDCAPplus_(cfg.getParameter("minHitsPerSubDet").getParameter("inENDCAPplus")), + minHitsinENDCAPminus_(cfg.getParameter("minHitsPerSubDet").getParameter("inENDCAPminus")), + maxHitDiffEndcaps_(cfg.getParameter("maxHitDiffEndcaps")), + nLostHitMax_(cfg.getParameter("nLostHitMax")), + RorZofFirstHitMin_(cfg.getParameter >("RorZofFirstHitMin")), + RorZofFirstHitMax_(cfg.getParameter >("RorZofFirstHitMax")), + RorZofLastHitMin_(cfg.getParameter >("RorZofLastHitMin")), + RorZofLastHitMax_(cfg.getParameter >("RorZofLastHitMax")), + clusterValueMapTag_(cfg.getParameter("hitPrescaleMapTag")), + minPrescaledHits_(cfg.getParameter("minPrescaledHits")), + applyPrescaledHitsFilter_(!clusterValueMapTag_.encode().empty() && minPrescaledHits_ > 0) { + if (applyIsolation_) { rphirecHitsToken_ = iC.consumes(cfg.getParameter("rphirecHits")); - matchedrecHitsToken_ = iC.consumes(cfg.getParameter("matchedrecHits")); + matchedrecHitsToken_ = + iC.consumes(cfg.getParameter("matchedrecHits")); } - if(applyPrescaledHitsFilter_) { + if (applyPrescaledHitsFilter_) { clusterValueMapToken_ = iC.consumes(clusterValueMapTag_); } //convert track quality from string to enum std::vector trkQualityStrings(cfg.getParameter >("trackQualities")); std::string qualities; - if(!trkQualityStrings.empty()){ - applyTrkQualityCheck_=true; + if (!trkQualityStrings.empty()) { + applyTrkQualityCheck_ = true; for (unsigned int i = 0; i < trkQualityStrings.size(); ++i) { (qualities += trkQualityStrings[i]) += ", "; trkQualities_.push_back(reco::TrackBase::qualityByName(trkQualityStrings[i])); } - } - else applyTrkQualityCheck_=false; + } else + applyTrkQualityCheck_ = false; std::vector trkIterStrings(cfg.getParameter >("iterativeTrackingSteps")); - if(!trkIterStrings.empty()){ - applyIterStepCheck_=true; + if (!trkIterStrings.empty()) { + applyIterStepCheck_ = true; std::string tracksteps; for (unsigned int i = 0; i < trkIterStrings.size(); ++i) { (tracksteps += trkIterStrings[i]) += ", "; trkSteps_.push_back(reco::TrackBase::algoByName(trkIterStrings[i])); } - } - else applyIterStepCheck_=false; - - if (applyBasicCuts_){ - edm::LogInfo("AlignmentTrackSelector") - << "applying basic track cuts ..." - << "\nptmin,ptmax: " << ptMin_ << "," << ptMax_ - << "\npmin,pmax: " << pMin_ << "," << pMax_ - << "\netamin,etamax: " << etaMin_ << "," << etaMax_ - << "\nphimin,phimax: " << phiMin_ << "," << phiMax_ - << "\nnhitmin,nhitmax: " << nHitMin_ << "," << nHitMax_ - << "\nnlosthitmax: " << nLostHitMax_ - << "\nnhitmin2D: " << nHitMin2D_ - << (countStereoHitAs2D_ ? "," : ", not") << " counting hits on SiStrip stereo modules as 2D" - << "\nchi2nmax: " << chi2nMax_; - - if (applyIsolation_) - edm::LogInfo("AlignmentTrackSelector") - << "only retain tracks isolated at least by " << minHitIsolation_ << - " cm from other rechits"; - - if (chargeCheck_) - edm::LogInfo("AlignmentTrackSelector") - << "only retain hits with at least " << minHitChargeStrip_ << - " ADC counts of total cluster charge"; - - edm::LogInfo("AlignmentTrackSelector") - << "Minimum number of hits in TIB/TID/TOB/TEC/BPIX/FPIX/PIXEL = " - << minHitsinTIB_ << "/" << minHitsinTID_ << "/" << minHitsinTOB_ - << "/" << minHitsinTEC_ << "/" << minHitsinBPIX_ << "/" << minHitsinFPIX_ << "/" << minHitsinPIX_; - + } else + applyIterStepCheck_ = false; + + if (applyBasicCuts_) { + edm::LogInfo("AlignmentTrackSelector") + << "applying basic track cuts ..." + << "\nptmin,ptmax: " << ptMin_ << "," << ptMax_ << "\npmin,pmax: " << pMin_ << "," << pMax_ + << "\netamin,etamax: " << etaMin_ << "," << etaMax_ << "\nphimin,phimax: " << phiMin_ << "," << phiMax_ + << "\nnhitmin,nhitmax: " << nHitMin_ << "," << nHitMax_ << "\nnlosthitmax: " << nLostHitMax_ + << "\nnhitmin2D: " << nHitMin2D_ << (countStereoHitAs2D_ ? "," : ", not") + << " counting hits on SiStrip stereo modules as 2D" + << "\nchi2nmax: " << chi2nMax_; + + if (applyIsolation_) edm::LogInfo("AlignmentTrackSelector") - << "Minimum number of hits in TID+/TID-/TEC+/TEC-/FPIX+/FPIX- = " - << minHitsinTIDplus_ << "/" << minHitsinTIDminus_ - << "/" << minHitsinTECplus_ << "/" << minHitsinTECminus_ - << "/" << minHitsinFPIXplus_ << "/" << minHitsinFPIXminus_; + << "only retain tracks isolated at least by " << minHitIsolation_ << " cm from other rechits"; + if (chargeCheck_) edm::LogInfo("AlignmentTrackSelector") - << "Minimum number of hits in EndCap (TID+TEC)/EndCap+/EndCap- = " - << minHitsinENDCAP_ << "/" << minHitsinENDCAPplus_ << "/" << minHitsinENDCAPminus_; + << "only retain hits with at least " << minHitChargeStrip_ << " ADC counts of total cluster charge"; - edm::LogInfo("AlignmentTrackSelector") - << "Max value of |nHitsinENDCAPplus - nHitsinENDCAPminus| = " - << maxHitDiffEndcaps_; + edm::LogInfo("AlignmentTrackSelector") + << "Minimum number of hits in TIB/TID/TOB/TEC/BPIX/FPIX/PIXEL = " << minHitsinTIB_ << "/" << minHitsinTID_ + << "/" << minHitsinTOB_ << "/" << minHitsinTEC_ << "/" << minHitsinBPIX_ << "/" << minHitsinFPIX_ << "/" + << minHitsinPIX_; + + edm::LogInfo("AlignmentTrackSelector") + << "Minimum number of hits in TID+/TID-/TEC+/TEC-/FPIX+/FPIX- = " << minHitsinTIDplus_ << "/" + << minHitsinTIDminus_ << "/" << minHitsinTECplus_ << "/" << minHitsinTECminus_ << "/" << minHitsinFPIXplus_ + << "/" << minHitsinFPIXminus_; + + edm::LogInfo("AlignmentTrackSelector") + << "Minimum number of hits in EndCap (TID+TEC)/EndCap+/EndCap- = " << minHitsinENDCAP_ << "/" + << minHitsinENDCAPplus_ << "/" << minHitsinENDCAPminus_; + + edm::LogInfo("AlignmentTrackSelector") + << "Max value of |nHitsinENDCAPplus - nHitsinENDCAPminus| = " << maxHitDiffEndcaps_; - if (!trkQualityStrings.empty()) { - edm::LogInfo("AlignmentTrackSelector") - << "Select tracks with these qualities: " << qualities; - } + if (!trkQualityStrings.empty()) { + edm::LogInfo("AlignmentTrackSelector") << "Select tracks with these qualities: " << qualities; + } } - + if (applyNHighestPt_) - edm::LogInfo("AlignmentTrackSelector") - << "filter N tracks with highest Pt N=" << nHighestPt_; + edm::LogInfo("AlignmentTrackSelector") << "filter N tracks with highest Pt N=" << nHighestPt_; if (applyMultiplicityFilter_) - edm::LogInfo("AlignmentTrackSelector") - << "apply multiplicity filter N>= " << minMultiplicity_ << "and N<= " << maxMultiplicity_ - << " on " << (multiplicityOnInput_ ? "input" : "output"); + edm::LogInfo("AlignmentTrackSelector") + << "apply multiplicity filter N>= " << minMultiplicity_ << "and N<= " << maxMultiplicity_ << " on " + << (multiplicityOnInput_ ? "input" : "output"); if (applyPrescaledHitsFilter_) { - edm::LogInfo("AlignmentTrackSelector") - << "apply cut on number of prescaled hits N>= " << minPrescaledHits_ - << " (prescale info from " << clusterValueMapTag_ << ")"; - + edm::LogInfo("AlignmentTrackSelector") << "apply cut on number of prescaled hits N>= " << minPrescaledHits_ + << " (prescale info from " << clusterValueMapTag_ << ")"; } // Checking whether cuts on positions of first and last track hits are defined properly - if(RorZofFirstHitMin_.size() != 2){ - throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" - << "Wrong configuration of 'RorZofFirstHitMin'." - << " Must have exactly 2 values instead of configured " << RorZofFirstHitMin_.size() << ")"; + if (RorZofFirstHitMin_.size() != 2) { + throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" + << "Wrong configuration of 'RorZofFirstHitMin'." + << " Must have exactly 2 values instead of configured " + << RorZofFirstHitMin_.size() << ")"; } else { - RorZofFirstHitMin_.at(0)=std::fabs(RorZofFirstHitMin_.at(0)); - RorZofFirstHitMin_.at(1)=std::fabs(RorZofFirstHitMin_.at(1)); + RorZofFirstHitMin_.at(0) = std::fabs(RorZofFirstHitMin_.at(0)); + RorZofFirstHitMin_.at(1) = std::fabs(RorZofFirstHitMin_.at(1)); } - if(RorZofFirstHitMax_.size() != 2){ - throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" - << "Wrong configuration of 'RorZofFirstHitMax'." - << " Must have exactly 2 values instead of configured " << RorZofFirstHitMax_.size() << ")"; + if (RorZofFirstHitMax_.size() != 2) { + throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" + << "Wrong configuration of 'RorZofFirstHitMax'." + << " Must have exactly 2 values instead of configured " + << RorZofFirstHitMax_.size() << ")"; } else { RorZofFirstHitMax_.at(0) = std::fabs(RorZofFirstHitMax_.at(0)); RorZofFirstHitMax_.at(1) = std::fabs(RorZofFirstHitMax_.at(1)); } - if(RorZofLastHitMin_.size() != 2){ - throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" - << "Wrong configuration of 'RorZofLastHitMin'." - << " Must have exactly 2 values instead of configured " << RorZofLastHitMin_.size() << ")"; + if (RorZofLastHitMin_.size() != 2) { + throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" + << "Wrong configuration of 'RorZofLastHitMin'." + << " Must have exactly 2 values instead of configured " + << RorZofLastHitMin_.size() << ")"; } else { RorZofLastHitMin_.at(0) = std::fabs(RorZofLastHitMin_.at(0)); RorZofLastHitMin_.at(1) = std::fabs(RorZofLastHitMin_.at(1)); } - if(RorZofLastHitMax_.size() != 2){ - throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" - << "Wrong configuration of 'RorZofLastHitMax'." - << " Must have exactly 2 values instead of configured " << RorZofLastHitMax_.size() << ")"; + if (RorZofLastHitMax_.size() != 2) { + throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" + << "Wrong configuration of 'RorZofLastHitMax'." + << " Must have exactly 2 values instead of configured " + << RorZofLastHitMax_.size() << ")"; } else { RorZofLastHitMax_.at(0) = std::fabs(RorZofLastHitMax_.at(0)); RorZofLastHitMax_.at(1) = std::fabs(RorZofLastHitMax_.at(1)); } // If first hit set to be at larger distance then the last hit - if(RorZofFirstHitMin_.at(0) > RorZofLastHitMax_.at(0) && RorZofFirstHitMin_.at(1) > RorZofLastHitMax_.at(1)){ - throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" - << "Position of the first hit is set to larger distance than the last hit:." - << " First hit(min): [" << RorZofFirstHitMin_.at(0) << ", " << RorZofFirstHitMin_.at(1) << "]; Last hit(max): [" - << RorZofLastHitMax_.at(0) << ", " << RorZofLastHitMax_.at(1) << "];"; + if (RorZofFirstHitMin_.at(0) > RorZofLastHitMax_.at(0) && RorZofFirstHitMin_.at(1) > RorZofLastHitMax_.at(1)) { + throw cms::Exception("BadConfig") << "@SUB=AlignmentTrackSelector::AlignmentTrackSelector" + << "Position of the first hit is set to larger distance than the last hit:." + << " First hit(min): [" << RorZofFirstHitMin_.at(0) << ", " + << RorZofFirstHitMin_.at(1) << "]; Last hit(max): [" << RorZofLastHitMax_.at(0) + << ", " << RorZofLastHitMax_.at(1) << "];"; } - } // destructor ----------------------------------------------------------------- -AlignmentTrackSelector::~AlignmentTrackSelector() -{} - +AlignmentTrackSelector::~AlignmentTrackSelector() {} // do selection --------------------------------------------------------------- -AlignmentTrackSelector::Tracks -AlignmentTrackSelector::select(const Tracks& tracks, const edm::Event& evt, const edm::EventSetup& eSetup) const -{ - - if (applyMultiplicityFilter_ && multiplicityOnInput_ && - (tracks.size() < static_cast(minMultiplicity_) - || tracks.size() > static_cast(maxMultiplicity_))) { - return Tracks(); // empty collection +AlignmentTrackSelector::Tracks AlignmentTrackSelector::select(const Tracks& tracks, + const edm::Event& evt, + const edm::EventSetup& eSetup) const { + if (applyMultiplicityFilter_ && multiplicityOnInput_ && + (tracks.size() < static_cast(minMultiplicity_) || + tracks.size() > static_cast(maxMultiplicity_))) { + return Tracks(); // empty collection } Tracks result = tracks; // apply basic track cuts (if selected) - if (applyBasicCuts_) result= this->basicCuts(result, evt, eSetup); - + if (applyBasicCuts_) + result = this->basicCuts(result, evt, eSetup); + // filter N tracks with highest Pt (if selected) - if (applyNHighestPt_) result = this->theNHighestPtTracks(result); - + if (applyNHighestPt_) + result = this->theNHighestPtTracks(result); + // apply minimum multiplicity requirement (if selected) if (applyMultiplicityFilter_ && !multiplicityOnInput_) { - if (result.size() < static_cast(minMultiplicity_) - || result.size() > static_cast(maxMultiplicity_) ) { - + if (result.size() < static_cast(minMultiplicity_) || + result.size() > static_cast(maxMultiplicity_)) { result.clear(); } } - if(applyPrescaledHitsFilter_){ + if (applyPrescaledHitsFilter_) { result = this->checkPrescaledHits(result, evt); } return result; } - ///returns if any of the Filters is used. -bool AlignmentTrackSelector::useThisFilter() -{ +///returns if any of the Filters is used. +bool AlignmentTrackSelector::useThisFilter() { return applyMultiplicityFilter_ || applyBasicCuts_ || applyNHighestPt_ || applyPrescaledHitsFilter_; - } - // make basic cuts ------------------------------------------------------------ -AlignmentTrackSelector::Tracks -AlignmentTrackSelector::basicCuts(const Tracks& tracks, const edm::Event& evt, const edm::EventSetup& eSetup) const -{ +AlignmentTrackSelector::Tracks AlignmentTrackSelector::basicCuts(const Tracks& tracks, + const edm::Event& evt, + const edm::EventSetup& eSetup) const { Tracks result; - for (Tracks::const_iterator it=tracks.begin(); it != tracks.end(); ++it) { - const reco::Track* trackp=*it; - float pt=trackp->pt(); - float p=trackp->p(); - float eta=trackp->eta(); - float phi=trackp->phi(); - int nhit = trackp->numberOfValidHits(); - int nlosthit = trackp->numberOfLostHits(); + for (Tracks::const_iterator it = tracks.begin(); it != tracks.end(); ++it) { + const reco::Track* trackp = *it; + float pt = trackp->pt(); + float p = trackp->p(); + float eta = trackp->eta(); + float phi = trackp->phi(); + int nhit = trackp->numberOfValidHits(); + int nlosthit = trackp->numberOfLostHits(); float chi2n = trackp->normalizedChi2(); int q = trackp->charge(); bool isChargeOk = false; - if(theCharge_==-1 && q<0) isChargeOk = true; - else if (theCharge_==1 && q>0) isChargeOk = true; - else if (theCharge_==0) isChargeOk = true; + if (theCharge_ == -1 && q < 0) + isChargeOk = true; + else if (theCharge_ == 1 && q > 0) + isChargeOk = true; + else if (theCharge_ == 0) + isChargeOk = true; - float d0 = trackp->d0(); - float dz = trackp->dz(); + float d0 = trackp->d0(); + float dz = trackp->dz(); // edm::LogDebug("AlignmentTrackSelector") << " pt,eta,phi,nhit: " // <ptMin_ && ptpMin_ && petaMin_ && etaphiMin_ && phi=nHitMin_ && nhit<=nHitMax_ - && nlosthit<=nLostHitMax_ - && chi2n=d0Min_ && d0<=d0Max_ - && dz>=dzMin_ && dz<=dzMax_) { - bool trkQualityOk=false ; - if (!applyTrkQualityCheck_ &&!applyIterStepCheck_)trkQualityOk=true ; // nothing required - else trkQualityOk = this->isOkTrkQuality(trackp); - - bool hitsCheckOk=this->detailedHitsCheck(trackp, evt, eSetup); - - if (trkQualityOk && hitsCheckOk ) result.push_back(trackp); + if (pt > ptMin_ && pt < ptMax_ && p > pMin_ && p < pMax_ && eta > etaMin_ && eta < etaMax_ && phi > phiMin_ && + phi < phiMax_ && nhit >= nHitMin_ && nhit <= nHitMax_ && nlosthit <= nLostHitMax_ && chi2n < chi2nMax_ && + isChargeOk && d0 >= d0Min_ && d0 <= d0Max_ && dz >= dzMin_ && dz <= dzMax_) { + bool trkQualityOk = false; + if (!applyTrkQualityCheck_ && !applyIterStepCheck_) + trkQualityOk = true; // nothing required + else + trkQualityOk = this->isOkTrkQuality(trackp); + + bool hitsCheckOk = this->detailedHitsCheck(trackp, evt, eSetup); + + if (trkQualityOk && hitsCheckOk) + result.push_back(trackp); } } @@ -330,9 +317,9 @@ AlignmentTrackSelector::basicCuts(const Tracks& tracks, const edm::Event& evt, c //----------------------------------------------------------------------------- -bool AlignmentTrackSelector::detailedHitsCheck(const reco::Track *trackp, const edm::Event& evt, const edm::EventSetup& eSetup) const -{ - +bool AlignmentTrackSelector::detailedHitsCheck(const reco::Track* trackp, + const edm::Event& evt, + const edm::EventSetup& eSetup) const { //Retrieve tracker topology from geometry edm::ESHandle tTopoHandle; eSetup.get().get(tTopoHandle); @@ -340,18 +327,16 @@ bool AlignmentTrackSelector::detailedHitsCheck(const reco::Track *trackp, const // checking hit requirements beyond simple number of valid hits - if (minHitsinTIB_ || minHitsinTOB_ || minHitsinTID_ || minHitsinTEC_ - || minHitsinENDCAP_ || minHitsinENDCAPplus_ || minHitsinENDCAPminus_ || (maxHitDiffEndcaps_ < 999) - || minHitsinTIDplus_ || minHitsinTIDminus_ - || minHitsinFPIXplus_ || minHitsinFPIXminus_ - || minHitsinTECplus_ || minHitsinTECminus_ - || minHitsinFPIX_ || minHitsinBPIX_ || minHitsinPIX_ ||nHitMin2D_ || chargeCheck_ - || applyIsolation_ || (seedOnlyFromAbove_ == 1 || seedOnlyFromAbove_ == 2) - || !RorZofFirstHitMin_.empty() || !RorZofFirstHitMax_.empty() || !RorZofLastHitMin_.empty() || !RorZofLastHitMax_.empty() ) { + if (minHitsinTIB_ || minHitsinTOB_ || minHitsinTID_ || minHitsinTEC_ || minHitsinENDCAP_ || minHitsinENDCAPplus_ || + minHitsinENDCAPminus_ || (maxHitDiffEndcaps_ < 999) || minHitsinTIDplus_ || minHitsinTIDminus_ || + minHitsinFPIXplus_ || minHitsinFPIXminus_ || minHitsinTECplus_ || minHitsinTECminus_ || minHitsinFPIX_ || + minHitsinBPIX_ || minHitsinPIX_ || nHitMin2D_ || chargeCheck_ || applyIsolation_ || + (seedOnlyFromAbove_ == 1 || seedOnlyFromAbove_ == 2) || !RorZofFirstHitMin_.empty() || + !RorZofFirstHitMax_.empty() || !RorZofLastHitMin_.empty() || !RorZofLastHitMax_.empty()) { // any detailed hit cut is active, so have to check - + int nhitinTIB = 0, nhitinTOB = 0, nhitinTID = 0; - int nhitinTEC = 0, nhitinBPIX = 0, nhitinFPIX = 0, nhitinPIXEL=0; + int nhitinTEC = 0, nhitinBPIX = 0, nhitinFPIX = 0, nhitinPIXEL = 0; int nhitinENDCAP = 0, nhitinENDCAPplus = 0, nhitinENDCAPminus = 0; int nhitinTIDplus = 0, nhitinTIDminus = 0; int nhitinFPIXplus = 0, nhitinFPIXminus = 0; @@ -359,157 +344,164 @@ bool AlignmentTrackSelector::detailedHitsCheck(const reco::Track *trackp, const unsigned int nHit2D = 0; unsigned int thishit = 0; - for(auto const& hit : trackp->recHits()) { + for (auto const& hit : trackp->recHits()) { thishit++; const DetId detId(hit->geographicalId()); - const int subdetId = detId.subdetId(); + const int subdetId = detId.subdetId(); - // *** thishit == 1 means last hit in CTF *** + // *** thishit == 1 means last hit in CTF *** // (FIXME: assumption might change or not be valid for all tracking algorthms) // ==> for cosmics // seedOnlyFrom = 1 is TIB-TOB-TEC tracks only - // seedOnlyFrom = 2 is TOB-TEC tracks only - if (seedOnlyFromAbove_ == 1 && thishit == 1 - && (subdetId == int(SiStripDetId::TOB) || subdetId == int(SiStripDetId::TEC))){ - return false; + // seedOnlyFrom = 2 is TOB-TEC tracks only + if (seedOnlyFromAbove_ == 1 && thishit == 1 && + (subdetId == int(SiStripDetId::TOB) || subdetId == int(SiStripDetId::TEC))) { + return false; } if (seedOnlyFromAbove_ == 2 && thishit == 1 && subdetId == int(SiStripDetId::TIB)) { return false; } - if (!hit->isValid()) continue; // only real hits count as in trackp->numberOfValidHits() + if (!hit->isValid()) + continue; // only real hits count as in trackp->numberOfValidHits() if (detId.det() != DetId::Tracker) { - edm::LogError("DetectorMismatch") << "@SUB=AlignmentTrackSelector::detailedHitsCheck" - << "DetId.det() != DetId::Tracker (=" << DetId::Tracker - << "), but " << detId.det() << "."; + edm::LogError("DetectorMismatch") + << "@SUB=AlignmentTrackSelector::detailedHitsCheck" + << "DetId.det() != DetId::Tracker (=" << DetId::Tracker << "), but " << detId.det() << "."; } - if (chargeCheck_ && !(this->isOkCharge(hit))) return false; - if (applyIsolation_ && (!this->isIsolated(hit, evt))) return false; - if (SiStripDetId::TIB == subdetId) ++nhitinTIB; - else if (SiStripDetId::TOB == subdetId) ++nhitinTOB; + if (chargeCheck_ && !(this->isOkCharge(hit))) + return false; + if (applyIsolation_ && (!this->isIsolated(hit, evt))) + return false; + if (SiStripDetId::TIB == subdetId) + ++nhitinTIB; + else if (SiStripDetId::TOB == subdetId) + ++nhitinTOB; else if (SiStripDetId::TID == subdetId) { ++nhitinTID; ++nhitinENDCAP; - + if (tTopo->tidIsZMinusSide(detId)) { ++nhitinTIDminus; ++nhitinENDCAPminus; - } - else if (tTopo->tidIsZPlusSide(detId)) { + } else if (tTopo->tidIsZPlusSide(detId)) { ++nhitinTIDplus; ++nhitinENDCAPplus; - } - } - else if (SiStripDetId::TEC == subdetId) { + } + } else if (SiStripDetId::TEC == subdetId) { ++nhitinTEC; ++nhitinENDCAP; - + if (tTopo->tecIsZMinusSide(detId)) { ++nhitinTECminus; ++nhitinENDCAPminus; - } - else if (tTopo->tecIsZPlusSide(detId)) { + } else if (tTopo->tecIsZPlusSide(detId)) { ++nhitinTECplus; ++nhitinENDCAPplus; - } - } - else if ( kBPIX == subdetId) {++nhitinBPIX;++nhitinPIXEL;} - else if ( kFPIX == subdetId) { + } + } else if (kBPIX == subdetId) { + ++nhitinBPIX; + ++nhitinPIXEL; + } else if (kFPIX == subdetId) { ++nhitinFPIX; ++nhitinPIXEL; - - if (tTopo->pxfSide(detId)==1) ++nhitinFPIXminus; - else if (tTopo->pxfSide(detId)==2) ++nhitinFPIXplus; + + if (tTopo->pxfSide(detId) == 1) + ++nhitinFPIXminus; + else if (tTopo->pxfSide(detId) == 2) + ++nhitinFPIXplus; } // Do not call isHit2D(..) if already enough 2D hits for performance reason: - if (nHit2D < nHitMin2D_ && this->isHit2D(*hit)) ++nHit2D; - } // end loop on hits - + if (nHit2D < nHitMin2D_ && this->isHit2D(*hit)) + ++nHit2D; + } // end loop on hits // Checking whether the track satisfies requirement of the first and last hit positions bool passedLastHitPositionR = true; bool passedLastHitPositionZ = true; bool passedFirstHitPositionR = true; bool passedFirstHitPositionZ = true; - - if( RorZofFirstHitMin_.at(0) != 0.0 || RorZofFirstHitMin_.at(1) != 0.0 - || RorZofFirstHitMax_.at(0) != 999.0 || RorZofFirstHitMax_.at(1) != 999.0 ) { + if (RorZofFirstHitMin_.at(0) != 0.0 || RorZofFirstHitMin_.at(1) != 0.0 || RorZofFirstHitMax_.at(0) != 999.0 || + RorZofFirstHitMax_.at(1) != 999.0) { const reco::TrackBase::Point& firstPoint(trackp->innerPosition()); - if( (std::fabs(firstPoint.R()) < RorZofFirstHitMin_.at(0) )) passedFirstHitPositionR = false; - if( (std::fabs(firstPoint.R()) > RorZofFirstHitMax_.at(0) )) passedFirstHitPositionR = false; - if( (std::fabs(firstPoint.Z()) < RorZofFirstHitMin_.at(1) )) passedFirstHitPositionZ = false; - if( (std::fabs(firstPoint.Z()) > RorZofFirstHitMax_.at(1) )) passedFirstHitPositionZ = false; + if ((std::fabs(firstPoint.R()) < RorZofFirstHitMin_.at(0))) + passedFirstHitPositionR = false; + if ((std::fabs(firstPoint.R()) > RorZofFirstHitMax_.at(0))) + passedFirstHitPositionR = false; + if ((std::fabs(firstPoint.Z()) < RorZofFirstHitMin_.at(1))) + passedFirstHitPositionZ = false; + if ((std::fabs(firstPoint.Z()) > RorZofFirstHitMax_.at(1))) + passedFirstHitPositionZ = false; } - - if( RorZofLastHitMin_.at(0) != 0.0 || RorZofLastHitMin_.at(1) != 0.0 - || RorZofLastHitMax_.at(0) != 999.0 || RorZofLastHitMax_.at(1) != 999.0 ) { + if (RorZofLastHitMin_.at(0) != 0.0 || RorZofLastHitMin_.at(1) != 0.0 || RorZofLastHitMax_.at(0) != 999.0 || + RorZofLastHitMax_.at(1) != 999.0) { const reco::TrackBase::Point& lastPoint(trackp->outerPosition()); - if( (std::fabs(lastPoint.R()) < RorZofLastHitMin_.at(0) )) passedLastHitPositionR = false; - if( (std::fabs(lastPoint.R()) > RorZofLastHitMax_.at(0) )) passedLastHitPositionR = false; - if( (std::fabs(lastPoint.Z()) < RorZofLastHitMin_.at(1) )) passedLastHitPositionZ = false; - if( (std::fabs(lastPoint.Z()) > RorZofLastHitMax_.at(1) )) passedLastHitPositionZ = false; + if ((std::fabs(lastPoint.R()) < RorZofLastHitMin_.at(0))) + passedLastHitPositionR = false; + if ((std::fabs(lastPoint.R()) > RorZofLastHitMax_.at(0))) + passedLastHitPositionR = false; + if ((std::fabs(lastPoint.Z()) < RorZofLastHitMin_.at(1))) + passedLastHitPositionZ = false; + if ((std::fabs(lastPoint.Z()) > RorZofLastHitMax_.at(1))) + passedLastHitPositionZ = false; } bool passedFirstHitPosition = passedFirstHitPositionR || passedFirstHitPositionZ; bool passedLastHitPosition = passedLastHitPositionR || passedLastHitPositionZ; - - - return (nhitinTIB >= minHitsinTIB_ && nhitinTOB >= minHitsinTOB_ - && nhitinTID >= minHitsinTID_ && nhitinTEC >= minHitsinTEC_ - && nhitinENDCAP >= minHitsinENDCAP_ && nhitinENDCAPplus >= minHitsinENDCAPplus_ && nhitinENDCAPminus >= minHitsinENDCAPminus_ - && std::abs(nhitinENDCAPplus-nhitinENDCAPminus) <= maxHitDiffEndcaps_ - && nhitinTIDplus >= minHitsinTIDplus_ && nhitinTIDminus >= minHitsinTIDminus_ - && nhitinFPIXplus >= minHitsinFPIXplus_ && nhitinFPIXminus >= minHitsinFPIXminus_ - && nhitinTECplus >= minHitsinTECplus_ && nhitinTECminus >= minHitsinTECminus_ - && nhitinBPIX >= minHitsinBPIX_ - && nhitinFPIX >= minHitsinFPIX_ && nhitinPIXEL>=minHitsinPIX_ - && nHit2D >= nHitMin2D_ && passedFirstHitPosition && passedLastHitPosition); - } else { // no cuts set, so we are just fine and can avoid loop on hits + return (nhitinTIB >= minHitsinTIB_ && nhitinTOB >= minHitsinTOB_ && nhitinTID >= minHitsinTID_ && + nhitinTEC >= minHitsinTEC_ && nhitinENDCAP >= minHitsinENDCAP_ && + nhitinENDCAPplus >= minHitsinENDCAPplus_ && nhitinENDCAPminus >= minHitsinENDCAPminus_ && + std::abs(nhitinENDCAPplus - nhitinENDCAPminus) <= maxHitDiffEndcaps_ && + nhitinTIDplus >= minHitsinTIDplus_ && nhitinTIDminus >= minHitsinTIDminus_ && + nhitinFPIXplus >= minHitsinFPIXplus_ && nhitinFPIXminus >= minHitsinFPIXminus_ && + nhitinTECplus >= minHitsinTECplus_ && nhitinTECminus >= minHitsinTECminus_ && + nhitinBPIX >= minHitsinBPIX_ && nhitinFPIX >= minHitsinFPIX_ && nhitinPIXEL >= minHitsinPIX_ && + nHit2D >= nHitMin2D_ && passedFirstHitPosition && passedLastHitPosition); + } else { // no cuts set, so we are just fine and can avoid loop on hits return true; } - } //----------------------------------------------------------------------------- -bool AlignmentTrackSelector::isHit2D(const TrackingRecHit &hit) const -{ +bool AlignmentTrackSelector::isHit2D(const TrackingRecHit& hit) const { // we count SiStrip stereo modules as 2D if selected via countStereoHitAs2D_ // (since they provide theta information) - if (!hit.isValid() || - (hit.dimension() < 2 && !countStereoHitAs2D_ && !dynamic_cast(&hit))){ - return false; // real RecHit1D - but SiStripRecHit1D depends on countStereoHitAs2D_ + if (!hit.isValid() || (hit.dimension() < 2 && !countStereoHitAs2D_ && !dynamic_cast(&hit))) { + return false; // real RecHit1D - but SiStripRecHit1D depends on countStereoHitAs2D_ } else { const DetId detId(hit.geographicalId()); if (detId.det() == DetId::Tracker) { if (detId.subdetId() == kBPIX || detId.subdetId() == kFPIX) { - return true; // pixel is always 2D - } else { // should be SiStrip now - const SiStripDetId stripId(detId); - if (stripId.stereo()) return countStereoHitAs2D_; // stereo modules - else if (dynamic_cast(&hit) - || dynamic_cast(&hit)) return false; // rphi modules hit - //the following two are not used any more since ages... - else if (dynamic_cast(&hit)) return true; // matched is 2D + return true; // pixel is always 2D + } else { // should be SiStrip now + const SiStripDetId stripId(detId); + if (stripId.stereo()) + return countStereoHitAs2D_; // stereo modules + else if (dynamic_cast(&hit) || dynamic_cast(&hit)) + return false; // rphi modules hit + //the following two are not used any more since ages... + else if (dynamic_cast(&hit)) + return true; // matched is 2D else if (dynamic_cast(&hit)) { - const ProjectedSiStripRecHit2D* pH = static_cast(&hit); - return (countStereoHitAs2D_ && this->isHit2D(pH->originalHit())); // depends on original... - } else { + const ProjectedSiStripRecHit2D* pH = static_cast(&hit); + return (countStereoHitAs2D_ && this->isHit2D(pH->originalHit())); // depends on original... + } else { edm::LogError("UnkownType") << "@SUB=AlignmentTrackSelector::isHit2D" << "Tracker hit not in pixel, neither SiStripRecHit[12]D nor " << "SiStripMatchedRecHit2D nor ProjectedSiStripRecHit2D."; return false; } } - } else { // not tracker?? + } else { // not tracker?? edm::LogWarning("DetectorMismatch") << "@SUB=AlignmentTrackSelector::isHit2D" << "Hit not in tracker with 'official' dimension >=2."; - return true; // dimension() >= 2 so accept that... + return true; // dimension() >= 2 so accept that... } } // never reached... @@ -517,78 +509,72 @@ bool AlignmentTrackSelector::isHit2D(const TrackingRecHit &hit) const //----------------------------------------------------------------------------- -bool AlignmentTrackSelector::isOkCharge(const TrackingRecHit* hit) const -{ - if (!hit || !hit->isValid()) return true; +bool AlignmentTrackSelector::isOkCharge(const TrackingRecHit* hit) const { + if (!hit || !hit->isValid()) + return true; // check det and subdet const DetId id(hit->geographicalId()); if (id.det() != DetId::Tracker) { - edm::LogWarning("DetectorMismatch") << "@SUB=isOkCharge" << "Hit not in tracker!"; + edm::LogWarning("DetectorMismatch") << "@SUB=isOkCharge" + << "Hit not in tracker!"; return true; } if (id.subdetId() == kFPIX || id.subdetId() == kBPIX) { - return true; // might add some requirement... + return true; // might add some requirement... } // We are in SiStrip now, so test normal hit: - const std::type_info &type = typeid(*hit); - + const std::type_info& type = typeid(*hit); if (type == typeid(SiStripRecHit2D)) { - const SiStripRecHit2D *stripHit2D = dynamic_cast(hit); + const SiStripRecHit2D* stripHit2D = dynamic_cast(hit); if (stripHit2D) { return this->isOkChargeStripHit(*stripHit2D); } - } - else if(type == typeid(SiStripRecHit1D)){ - const SiStripRecHit1D *stripHit1D = dynamic_cast(hit); + } else if (type == typeid(SiStripRecHit1D)) { + const SiStripRecHit1D* stripHit1D = dynamic_cast(hit); if (stripHit1D) { return this->isOkChargeStripHit(*stripHit1D); - } + } } - else if(type == typeid(SiStripMatchedRecHit2D)){ // or matched (should not occur anymore due to hit splitting since 20X) - const SiStripMatchedRecHit2D *matchedHit = dynamic_cast(hit); - if (matchedHit) { - return (this->isOkChargeStripHit(matchedHit->monoHit()) - && this->isOkChargeStripHit(matchedHit->stereoHit())); + else if (type == + typeid(SiStripMatchedRecHit2D)) { // or matched (should not occur anymore due to hit splitting since 20X) + const SiStripMatchedRecHit2D* matchedHit = dynamic_cast(hit); + if (matchedHit) { + return (this->isOkChargeStripHit(matchedHit->monoHit()) && this->isOkChargeStripHit(matchedHit->stereoHit())); } - } - else if(type == typeid(ProjectedSiStripRecHit2D)){ + } else if (type == typeid(ProjectedSiStripRecHit2D)) { // or projected (should not occur anymore due to hit splitting since 20X): - const ProjectedSiStripRecHit2D *projHit = dynamic_cast(hit); + const ProjectedSiStripRecHit2D* projHit = dynamic_cast(hit); if (projHit) { return this->isOkChargeStripHit(projHit->originalHit()); } - } - else{ - edm::LogError("AlignmentTrackSelector")<< "@SUB=isOkCharge" <<"Unknown type of a valid tracker hit in Strips " - << " SubDet = "<(hit) - << ", BaseTrackerRecHit " << dynamic_cast(hit); - - return true; -} + edm::LogError("AlignmentTrackSelector") << "@SUB=isOkCharge" + << "Unknown valid tracker hit not in pixel, subdet " << id.subdetId() + << ", SiTrackerMultiRecHit " << dynamic_cast(hit) + << ", BaseTrackerRecHit " << dynamic_cast(hit); + return true; +} //----------------------------------------------------------------------------- -bool AlignmentTrackSelector::isOkChargeStripHit(const SiStripRecHit2D & siStripRecHit2D) const -{ +bool AlignmentTrackSelector::isOkChargeStripHit(const SiStripRecHit2D& siStripRecHit2D) const { double charge = 0.; SiStripRecHit2D::ClusterRef cluster(siStripRecHit2D.cluster()); - const auto &litudes = cluster->amplitudes(); + const auto& amplitudes = cluster->amplitudes(); for (size_t ia = 0; ia < amplitudes.size(); ++ia) { charge += amplitudes[ia]; @@ -599,12 +585,11 @@ bool AlignmentTrackSelector::isOkChargeStripHit(const SiStripRecHit2D & siStripR //----------------------------------------------------------------------------- -bool AlignmentTrackSelector::isOkChargeStripHit(const SiStripRecHit1D & siStripRecHit1D) const -{ +bool AlignmentTrackSelector::isOkChargeStripHit(const SiStripRecHit1D& siStripRecHit1D) const { double charge = 0.; SiStripRecHit1D::ClusterRef cluster(siStripRecHit1D.cluster()); - const auto &litudes = cluster->amplitudes(); + const auto& amplitudes = cluster->amplitudes(); for (size_t ia = 0; ia < amplitudes.size(); ++ia) { charge += amplitudes[ia]; @@ -615,8 +600,7 @@ bool AlignmentTrackSelector::isOkChargeStripHit(const SiStripRecHit1D & siStripR //----------------------------------------------------------------------------- -bool AlignmentTrackSelector::isIsolated(const TrackingRecHit* hit, const edm::Event& evt) const -{ +bool AlignmentTrackSelector::isIsolated(const TrackingRecHit* hit, const edm::Event& evt) const { // FIXME: // adapt to changes after introduction of SiStripRecHit1D... // @@ -624,56 +608,60 @@ bool AlignmentTrackSelector::isIsolated(const TrackingRecHit* hit, const edm::Ev edm::Handle rphirecHits; edm::Handle matchedrecHits; // es.get().get(tracker); - evt.getByToken( rphirecHitsToken_, rphirecHits ); - evt.getByToken( matchedrecHitsToken_, matchedrecHits ); + evt.getByToken(rphirecHitsToken_, rphirecHits); + evt.getByToken(matchedrecHitsToken_, matchedrecHits); - SiStripRecHit2DCollection::DataContainer::const_iterator istripSt; - SiStripMatchedRecHit2DCollection::DataContainer::const_iterator istripStm; + SiStripRecHit2DCollection::DataContainer::const_iterator istripSt; + SiStripMatchedRecHit2DCollection::DataContainer::const_iterator istripStm; const SiStripRecHit2DCollection::DataContainer& stripcollSt = rphirecHits->data(); const SiStripMatchedRecHit2DCollection::DataContainer& stripcollStm = matchedrecHits->data(); - - DetId idet = hit->geographicalId(); - - // FIXME: instead of looping the full hit collection, we should explore the features of + + DetId idet = hit->geographicalId(); + + // FIXME: instead of looping the full hit collection, we should explore the features of // SiStripRecHit2DCollection::rangeRphi = rphirecHits.get(idet) and loop // only from rangeRphi.first until rangeRphi.second - for( istripSt=stripcollSt.begin(); istripSt!=stripcollSt.end(); ++istripSt ) { - const SiStripRecHit2D *aHit = &*(istripSt); - DetId mydet1 = aHit->geographicalId(); - if (idet.rawId() != mydet1.rawId()) continue; - float theDistance = ( hit->localPosition() - aHit->localPosition() ).mag(); + for (istripSt = stripcollSt.begin(); istripSt != stripcollSt.end(); ++istripSt) { + const SiStripRecHit2D* aHit = &*(istripSt); + DetId mydet1 = aHit->geographicalId(); + if (idet.rawId() != mydet1.rawId()) + continue; + float theDistance = (hit->localPosition() - aHit->localPosition()).mag(); // std::cout << "theDistance1 = " << theDistance << "\n"; - if (theDistance > 0.001 && theDistance < minHitIsolation_) return false; + if (theDistance > 0.001 && theDistance < minHitIsolation_) + return false; } - + // FIXME: see above - for( istripStm=stripcollStm.begin(); istripStm!=stripcollStm.end(); ++istripStm ) { - const SiStripMatchedRecHit2D *aHit = &*(istripStm); - DetId mydet2 = aHit->geographicalId(); - if (idet.rawId() != mydet2.rawId()) continue; + for (istripStm = stripcollStm.begin(); istripStm != stripcollStm.end(); ++istripStm) { + const SiStripMatchedRecHit2D* aHit = &*(istripStm); + DetId mydet2 = aHit->geographicalId(); + if (idet.rawId() != mydet2.rawId()) + continue; float theDistance = (hit->localPosition() - aHit->localPosition()).mag(); // std::cout << "theDistance1 = " << theDistance << "\n"; - if (theDistance > 0.001 && theDistance < minHitIsolation_) return false; + if (theDistance > 0.001 && theDistance < minHitIsolation_) + return false; } return true; } //----------------------------------------------------------------------------- -AlignmentTrackSelector::Tracks -AlignmentTrackSelector::theNHighestPtTracks(const Tracks& tracks) const -{ - Tracks sortedTracks=tracks; +AlignmentTrackSelector::Tracks AlignmentTrackSelector::theNHighestPtTracks(const Tracks& tracks) const { + Tracks sortedTracks = tracks; Tracks result; // sort in pt - std::sort(sortedTracks.begin(),sortedTracks.end(),ptComparator); + std::sort(sortedTracks.begin(), sortedTracks.end(), ptComparator); // copy theTrackMult highest pt tracks to result vector - int n=0; - for (Tracks::const_iterator it=sortedTracks.begin(); - it!=sortedTracks.end(); ++it) { - if (n fMap; - evt.getByToken( clusterValueMapToken_, fMap); - const AliClusterValueMap &flagMap=*fMap; + evt.getByToken(clusterValueMapToken_, fMap); + const AliClusterValueMap& flagMap = *fMap; //for each track loop on hits and count the number of taken hits - for(auto const& trackp : tracks) { - int ntakenhits=0; + for (auto const& trackp : tracks) { + int ntakenhits = 0; // float pt=trackp->pt(); - for(auto const& hit : trackp->recHits()) { - if(! hit->isValid())continue; + for (auto const& hit : trackp->recHits()) { + if (!hit->isValid()) + continue; DetId detid = hit->geographicalId(); int subDet = detid.subdetId(); AlignmentClusterFlag flag; - bool isPixelHit=(subDet == kFPIX || subDet == kBPIX); - - if (!isPixelHit){ - const std::type_info &type = typeid(*hit); - - if (type == typeid(SiStripRecHit2D)) { - const SiStripRecHit2D* striphit=dynamic_cast(hit); - if(striphit!=nullptr){ - SiStripRecHit2D::ClusterRef stripclust(striphit->cluster()); - flag = flagMap[stripclust]; - } - } - else if(type == typeid(SiStripRecHit1D)){ - const SiStripRecHit1D* striphit = dynamic_cast(hit); - if(striphit!=nullptr){ - SiStripRecHit1D::ClusterRef stripclust(striphit->cluster()); - flag = flagMap[stripclust]; - } - } - else{ - edm::LogError("AlignmentTrackSelector")<<"ERROR in : Dynamic cast of Strip RecHit failed!" - <<" Skipping this hit."; - continue; - } - - - - }//end if hit in Strips - else{ // test explicitely BPIX/FPIX - const SiPixelRecHit* pixelhit= dynamic_cast(hit); - if(pixelhit!=nullptr){ - SiPixelRecHit::ClusterRef pixclust(pixelhit->cluster()); - flag = flagMap[pixclust]; - } - else{ - edm::LogError("AlignmentTrackSelector")<<"ERROR in : Dynamic cast of Pixel RecHit failed! "; - } - }//end else hit is in Pixel - - if(flag.isTaken())ntakenhits++; - - }//end loop on hits - if(ntakenhits >= minPrescaledHits_)result.push_back(trackp); - }//end loop on tracks + bool isPixelHit = (subDet == kFPIX || subDet == kBPIX); + + if (!isPixelHit) { + const std::type_info& type = typeid(*hit); + + if (type == typeid(SiStripRecHit2D)) { + const SiStripRecHit2D* striphit = dynamic_cast(hit); + if (striphit != nullptr) { + SiStripRecHit2D::ClusterRef stripclust(striphit->cluster()); + flag = flagMap[stripclust]; + } + } else if (type == typeid(SiStripRecHit1D)) { + const SiStripRecHit1D* striphit = dynamic_cast(hit); + if (striphit != nullptr) { + SiStripRecHit1D::ClusterRef stripclust(striphit->cluster()); + flag = flagMap[stripclust]; + } + } else { + edm::LogError("AlignmentTrackSelector") + << "ERROR in : Dynamic cast of Strip RecHit failed!" + << " Skipping this hit."; + continue; + } + + } //end if hit in Strips + else { // test explicitely BPIX/FPIX + const SiPixelRecHit* pixelhit = dynamic_cast(hit); + if (pixelhit != nullptr) { + SiPixelRecHit::ClusterRef pixclust(pixelhit->cluster()); + flag = flagMap[pixclust]; + } else { + edm::LogError("AlignmentTrackSelector") + << "ERROR in : Dynamic cast of Pixel RecHit failed! "; + } + } //end else hit is in Pixel + + if (flag.isTaken()) + ntakenhits++; + + } //end loop on hits + if (ntakenhits >= minPrescaledHits_) + result.push_back(trackp); + } //end loop on tracks return result; -}//end checkPrescaledHits +} //end checkPrescaledHits //----------------------------------------------------------------- -bool AlignmentTrackSelector::isOkTrkQuality(const reco::Track* track) const -{ - bool qualityOk=false; - bool iterStepOk=false; +bool AlignmentTrackSelector::isOkTrkQuality(const reco::Track* track) const { + bool qualityOk = false; + bool iterStepOk = false; //check iterative step - if(applyIterStepCheck_){ + if (applyIterStepCheck_) { for (unsigned int i = 0; i < trkSteps_.size(); ++i) { - if (track->algo()==(trkSteps_[i])) { - iterStepOk=true; + if (track->algo() == (trkSteps_[i])) { + iterStepOk = true; } } - } - else iterStepOk=true; + } else + iterStepOk = true; //check track quality - if(applyTrkQualityCheck_){ + if (applyTrkQualityCheck_) { for (unsigned int i = 0; i < trkQualities_.size(); ++i) { if (track->quality(trkQualities_[i])) { - qualityOk=true; + qualityOk = true; } } - } - else qualityOk=true; + } else + qualityOk = true; - return qualityOk&&iterStepOk; -}//end check on track quality + return qualityOk && iterStepOk; +} //end check on track quality diff --git a/Alignment/CommonAlignmentProducer/src/AlignmentTwoBoyDecayTrackSelector.cc b/Alignment/CommonAlignmentProducer/src/AlignmentTwoBoyDecayTrackSelector.cc index 40c34147022d8..ce828ff96d910 100644 --- a/Alignment/CommonAlignmentProducer/src/AlignmentTwoBoyDecayTrackSelector.cc +++ b/Alignment/CommonAlignmentProducer/src/AlignmentTwoBoyDecayTrackSelector.cc @@ -18,77 +18,73 @@ #include "Alignment/CommonAlignmentProducer/interface/AlignmentTwoBodyDecayTrackSelector.h" //TODO put those namespaces into functions? using namespace std; -using namespace edm; +using namespace edm; // constructor ---------------------------------------------------------------- -AlignmentTwoBodyDecayTrackSelector::AlignmentTwoBodyDecayTrackSelector(const edm::ParameterSet & cfg, edm::ConsumesCollector& iC) -{ - LogDebug("Alignment") << "> applying two body decay Trackfilter ..."; - theMassrangeSwitch = cfg.getParameter( "applyMassrangeFilter" ); - if (theMassrangeSwitch){ - theMinMass = cfg.getParameter( "minXMass" ); - theMaxMass = cfg.getParameter( "maxXMass" ); - theDaughterMass = cfg.getParameter( "daughterMass" ); - theCandNumber = cfg.getParameter( "numberOfCandidates" );//Number of candidates to keep - secThrBool = cfg.getParameter ( "applySecThreshold" ); - thesecThr = cfg.getParameter( "secondThreshold" ); - LogDebug("Alignment") << "> Massrange min,max : " << theMinMass << "," << theMaxMass - << "\n> Mass of daughter Particle : " << theDaughterMass; - - }else{ +AlignmentTwoBodyDecayTrackSelector::AlignmentTwoBodyDecayTrackSelector(const edm::ParameterSet& cfg, + edm::ConsumesCollector& iC) { + LogDebug("Alignment") << "> applying two body decay Trackfilter ..."; + theMassrangeSwitch = cfg.getParameter("applyMassrangeFilter"); + if (theMassrangeSwitch) { + theMinMass = cfg.getParameter("minXMass"); + theMaxMass = cfg.getParameter("maxXMass"); + theDaughterMass = cfg.getParameter("daughterMass"); + theCandNumber = cfg.getParameter("numberOfCandidates"); //Number of candidates to keep + secThrBool = cfg.getParameter("applySecThreshold"); + thesecThr = cfg.getParameter("secondThreshold"); + LogDebug("Alignment") << "> Massrange min,max : " << theMinMass << "," << theMaxMass + << "\n> Mass of daughter Particle : " << theDaughterMass; + + } else { theMinMass = 0; theMaxMass = 0; theDaughterMass = 0; } - theChargeSwitch = cfg.getParameter( "applyChargeFilter" ); - if(theChargeSwitch){ - theCharge = cfg.getParameter( "charge" ); - theUnsignedSwitch = cfg.getParameter( "useUnsignedCharge" ); - if(theUnsignedSwitch) - theCharge=std::abs(theCharge); - LogDebug("Alignment") << "> Desired Charge, unsigned: "<("applyChargeFilter"); + if (theChargeSwitch) { + theCharge = cfg.getParameter("charge"); + theUnsignedSwitch = cfg.getParameter("useUnsignedCharge"); + if (theUnsignedSwitch) + theCharge = std::abs(theCharge); + LogDebug("Alignment") << "> Desired Charge, unsigned: " << theCharge << " , " << theUnsignedSwitch; + } else { + theCharge = 0; theUnsignedSwitch = true; } - theMissingETSwitch = cfg.getParameter( "applyMissingETFilter" ); - if(theMissingETSwitch){ - edm::InputTag theMissingETSource = cfg.getParameter( "missingETSource" ); + theMissingETSwitch = cfg.getParameter("applyMissingETFilter"); + if (theMissingETSwitch) { + edm::InputTag theMissingETSource = cfg.getParameter("missingETSource"); theMissingETToken = iC.consumes(theMissingETSource); - LogDebug("Alignment") << "> missing Et Source: "<< theMissingETSource; + LogDebug("Alignment") << "> missing Et Source: " << theMissingETSource; } - theAcoplanarityFilterSwitch = cfg.getParameter( "applyAcoplanarityFilter" ); - if(theAcoplanarityFilterSwitch){ - theAcoplanarDistance = cfg.getParameter( "acoplanarDistance" ); - LogDebug("Alignment") << "> Acoplanar Distance: "<("applyAcoplanarityFilter"); + if (theAcoplanarityFilterSwitch) { + theAcoplanarDistance = cfg.getParameter("acoplanarDistance"); + LogDebug("Alignment") << "> Acoplanar Distance: " << theAcoplanarDistance; } - } // destructor ----------------------------------------------------------------- -AlignmentTwoBodyDecayTrackSelector::~AlignmentTwoBodyDecayTrackSelector() -{} - +AlignmentTwoBodyDecayTrackSelector::~AlignmentTwoBodyDecayTrackSelector() {} ///returns if any of the Filters is used. -bool AlignmentTwoBodyDecayTrackSelector::useThisFilter() -{ +bool AlignmentTwoBodyDecayTrackSelector::useThisFilter() { return theMassrangeSwitch || theChargeSwitch || theAcoplanarityFilterSwitch; } // do selection --------------------------------------------------------------- -AlignmentTwoBodyDecayTrackSelector::Tracks -AlignmentTwoBodyDecayTrackSelector::select(const Tracks& tracks, const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +AlignmentTwoBodyDecayTrackSelector::Tracks AlignmentTwoBodyDecayTrackSelector::select(const Tracks& tracks, + const edm::Event& iEvent, + const edm::EventSetup& iSetup) { Tracks result = tracks; - if (theMassrangeSwitch) { + if (theMassrangeSwitch) { if (theMissingETSwitch) - result = checkMETMass(result,iEvent); + result = checkMETMass(result, iEvent); else - result = checkMass(result); + result = checkMass(result); } LogDebug("Alignment") << "> TwoBodyDecay tracks all,kept: " << tracks.size() << "," << result.size(); @@ -96,76 +92,71 @@ AlignmentTwoBodyDecayTrackSelector::select(const Tracks& tracks, const edm::Even } ///checks if the mass of the X is in the mass region -AlignmentTwoBodyDecayTrackSelector::Tracks -AlignmentTwoBodyDecayTrackSelector::checkMass(const Tracks& cands) const -{ +AlignmentTwoBodyDecayTrackSelector::Tracks AlignmentTwoBodyDecayTrackSelector::checkMass(const Tracks& cands) const { Tracks result; - - LogDebug("Alignment") <<"> cands size : "<< cands.size(); - - if (cands.size()<2) return result; + + LogDebug("Alignment") << "> cands size : " << cands.size(); + + if (cands.size() < 2) + return result; TLorentzVector track0; TLorentzVector track1; TLorentzVector mother; - typedef pair constTrackPair; - typedef pair candCollectionItem; + typedef pair constTrackPair; + typedef pair candCollectionItem; vector candCollection; - + for (unsigned int iCand = 0; iCand < cands.size(); iCand++) { - track0.SetXYZT(cands.at(iCand)->px(), - cands.at(iCand)->py(), - cands.at(iCand)->pz(), - sqrt( cands.at(iCand)->p()*cands.at(iCand)->p() + theDaughterMass*theDaughterMass )); - - for (unsigned int jCand = iCand+1; jCand < cands.size(); jCand++) { + cands.at(iCand)->py(), + cands.at(iCand)->pz(), + sqrt(cands.at(iCand)->p() * cands.at(iCand)->p() + theDaughterMass * theDaughterMass)); + for (unsigned int jCand = iCand + 1; jCand < cands.size(); jCand++) { track1.SetXYZT(cands.at(jCand)->px(), - cands.at(jCand)->py(), - cands.at(jCand)->pz(), - sqrt( cands.at(jCand)->p()*cands.at(jCand)->p() + theDaughterMass*theDaughterMass )); - if (secThrBool==true && track1.Pt() < thesecThr && track0.Pt()< thesecThr) continue; + cands.at(jCand)->py(), + cands.at(jCand)->pz(), + sqrt(cands.at(jCand)->p() * cands.at(jCand)->p() + theDaughterMass * theDaughterMass)); + if (secThrBool == true && track1.Pt() < thesecThr && track0.Pt() < thesecThr) + continue; mother = track0 + track1; - - const reco::Track *trk1 = cands.at(iCand); - const reco::Track *trk2 = cands.at(jCand); + + const reco::Track* trk1 = cands.at(iCand); + const reco::Track* trk2 = cands.at(jCand); bool correctCharge = true; - if (theChargeSwitch) correctCharge = this->checkCharge(trk1, trk2); + if (theChargeSwitch) + correctCharge = this->checkCharge(trk1, trk2); bool acoplanarTracks = true; - if (theAcoplanarityFilterSwitch) acoplanarTracks = this->checkAcoplanarity(trk1, trk2); - - if (mother.M() > theMinMass && - mother.M() < theMaxMass && - correctCharge && - acoplanarTracks) { - candCollection.push_back(candCollectionItem(mother.Pt(), - constTrackPair(trk1, trk2))); + if (theAcoplanarityFilterSwitch) + acoplanarTracks = this->checkAcoplanarity(trk1, trk2); + + if (mother.M() > theMinMass && mother.M() < theMaxMass && correctCharge && acoplanarTracks) { + candCollection.push_back(candCollectionItem(mother.Pt(), constTrackPair(trk1, trk2))); } } } - if (candCollection.empty()) return result; + if (candCollection.empty()) + return result; - sort(candCollection.begin(), candCollection.end(), [](auto& a, auto& b){return a.first > b.first ;}); + sort(candCollection.begin(), candCollection.end(), [](auto& a, auto& b) { return a.first > b.first; }); + + std::map uniqueTrackIndex; + std::map::iterator it; + for (unsigned int i = 0; i < candCollection.size() && i < theCandNumber; i++) { + constTrackPair& trackPair = candCollection[i].second; - std::map uniqueTrackIndex; - std::map::iterator it; - for (unsigned int i=0; - i cands size : "<< cands.size(); - - if (cands.empty()) return result; + + LogDebug("Alignment") << "> cands size : " << cands.size(); + + if (cands.empty()) + return result; TLorentzVector track; TLorentzVector met4; TLorentzVector mother; Handle missingET; - iEvent.getByToken(theMissingETToken ,missingET); + iEvent.getByToken(theMissingETToken, missingET); if (!missingET.isValid()) { - LogError("Alignment")<< "@SUB=AlignmentTwoBodyDecayTrackSelector::checkMETMass" - << "> could not optain missingET Collection!"; + LogError("Alignment") << "@SUB=AlignmentTwoBodyDecayTrackSelector::checkMETMass" + << "> could not optain missingET Collection!"; return result; } - typedef pair candCollectionItem; + typedef pair candCollectionItem; vector candCollection; - for (reco::CaloMETCollection::const_iterator itMET = missingET->begin(); - itMET != missingET->end(); - ++itMET) { - - met4.SetXYZT((*itMET).px(), - (*itMET).py(), - (*itMET).pz(), - (*itMET).p()); - + for (reco::CaloMETCollection::const_iterator itMET = missingET->begin(); itMET != missingET->end(); ++itMET) { + met4.SetXYZT((*itMET).px(), (*itMET).py(), (*itMET).pz(), (*itMET).p()); + for (unsigned int iCand = 0; iCand < cands.size(); iCand++) { - track.SetXYZT(cands.at(iCand)->px(), - cands.at(iCand)->py(), - cands.at(iCand)->pz(), - sqrt( cands.at(iCand)->p()*cands.at(iCand)->p() + theDaughterMass*theDaughterMass )); - + cands.at(iCand)->py(), + cands.at(iCand)->pz(), + sqrt(cands.at(iCand)->p() * cands.at(iCand)->p() + theDaughterMass * theDaughterMass)); + mother = track + met4; - - const reco::Track *trk = cands.at(iCand); - const reco::CaloMET *met = &(*itMET); + + const reco::Track* trk = cands.at(iCand); + const reco::CaloMET* met = &(*itMET); bool correctCharge = true; - if (theChargeSwitch) correctCharge = this->checkCharge(trk); + if (theChargeSwitch) + correctCharge = this->checkCharge(trk); bool acoplanarTracks = true; - if (theAcoplanarityFilterSwitch) acoplanarTracks = this->checkMETAcoplanarity(trk, met); + if (theAcoplanarityFilterSwitch) + acoplanarTracks = this->checkMETAcoplanarity(trk, met); - if (mother.M() > theMinMass && - mother.M() < theMaxMass && - correctCharge && - acoplanarTracks) { - candCollection.push_back(candCollectionItem(mother.Pt(), trk)); + if (mother.M() > theMinMass && mother.M() < theMaxMass && correctCharge && acoplanarTracks) { + candCollection.push_back(candCollectionItem(mother.Pt(), trk)); } } } - if (candCollection.empty()) return result; + if (candCollection.empty()) + return result; + + sort(candCollection.begin(), candCollection.end(), [](auto& a, auto& b) { return a.first > b.first; }); - sort(candCollection.begin(), candCollection.end(), [](auto& a, auto& b){return a.first > b.first ;}); - - std::map uniqueTrackIndex; - std::map::iterator it; - for (unsigned int i=0; - i uniqueTrackIndex; + std::map::iterator it; + for (unsigned int i = 0; i < candCollection.size() && i < theCandNumber; i++) { it = uniqueTrackIndex.find(candCollection[i].second); - if (it==uniqueTrackIndex.end()) { + if (it == uniqueTrackIndex.end()) { result.push_back(candCollection[i].second); uniqueTrackIndex[candCollection[i].second] = i; } @@ -255,45 +237,42 @@ AlignmentTwoBodyDecayTrackSelector::checkMETMass(const Tracks& cands,const edm:: } ///checks if the mother has charge = [theCharge] -bool -AlignmentTwoBodyDecayTrackSelector::checkCharge(const reco::Track* trk1, const reco::Track* trk2)const -{ +bool AlignmentTwoBodyDecayTrackSelector::checkCharge(const reco::Track* trk1, const reco::Track* trk2) const { int sumCharge = trk1->charge(); - if (trk2) sumCharge += trk2->charge(); - if (theUnsignedSwitch) sumCharge = std::abs(sumCharge); - if (sumCharge == theCharge) return true; + if (trk2) + sumCharge += trk2->charge(); + if (theUnsignedSwitch) + sumCharge = std::abs(sumCharge); + if (sumCharge == theCharge) + return true; return false; } ///checks if the [cands] are acoplanar (returns empty set if not) -bool -AlignmentTwoBodyDecayTrackSelector::checkAcoplanarity(const reco::Track* trk1, const reco::Track* trk2)const -{ - if (fabs(deltaPhi(trk1->phi(),trk2->phi()-M_PI)) < theAcoplanarDistance) return true; +bool AlignmentTwoBodyDecayTrackSelector::checkAcoplanarity(const reco::Track* trk1, const reco::Track* trk2) const { + if (fabs(deltaPhi(trk1->phi(), trk2->phi() - M_PI)) < theAcoplanarDistance) + return true; return false; } ///checks if the [cands] are acoplanar (returns empty set if not) -bool -AlignmentTwoBodyDecayTrackSelector::checkMETAcoplanarity(const reco::Track* trk1, const reco::CaloMET* met)const -{ - if (fabs(deltaPhi(trk1->phi(),met->phi()-M_PI)) < theAcoplanarDistance) return true; +bool AlignmentTwoBodyDecayTrackSelector::checkMETAcoplanarity(const reco::Track* trk1, const reco::CaloMET* met) const { + if (fabs(deltaPhi(trk1->phi(), met->phi() - M_PI)) < theAcoplanarDistance) + return true; return false; } //===================HELPERS=================== ///print Information on Track-Collection -void AlignmentTwoBodyDecayTrackSelector::printTracks(const Tracks& col) const -{ +void AlignmentTwoBodyDecayTrackSelector::printTracks(const Tracks& col) const { int count = 0; LogDebug("Alignment") << ">......................................"; - for(Tracks::const_iterator it = col.begin();it < col.end();++it,++count){ - LogDebug("Alignment") - <<"> Track No. "<< count <<": p = ("<<(*it)->px()<<","<<(*it)->py()<<","<<(*it)->pz()<<")\n" - <<"> pT = "<<(*it)->pt()<<" eta = "<<(*it)->eta()<<" charge = "<<(*it)->charge(); + for (Tracks::const_iterator it = col.begin(); it < col.end(); ++it, ++count) { + LogDebug("Alignment") << "> Track No. " << count << ": p = (" << (*it)->px() << "," << (*it)->py() << "," + << (*it)->pz() << ")\n" + << "> pT = " << (*it)->pt() << " eta = " << (*it)->eta() + << " charge = " << (*it)->charge(); } LogDebug("Alignment") << ">......................................"; } - - diff --git a/Alignment/CommonAlignmentProducer/test/AlignmentRcdScan.cpp b/Alignment/CommonAlignmentProducer/test/AlignmentRcdScan.cpp index 842704f29cdf6..6c4116c1d1830 100644 --- a/Alignment/CommonAlignmentProducer/test/AlignmentRcdScan.cpp +++ b/Alignment/CommonAlignmentProducer/test/AlignmentRcdScan.cpp @@ -26,99 +26,84 @@ #include "FWCore/Framework/interface/ESWatcher.h" -class AlignmentRcdScan : public edm::EDAnalyzer -{ +class AlignmentRcdScan : public edm::EDAnalyzer { public: + enum Mode { Unknown = 0, Tk = 1, DT = 2, CSC = 3 }; - enum Mode { - Unknown=0, - Tk=1, - DT=2, - CSC=3 - }; - - explicit AlignmentRcdScan( const edm::ParameterSet& iConfig ); + explicit AlignmentRcdScan(const edm::ParameterSet& iConfig); ~AlignmentRcdScan(); - virtual void analyze(const edm::Event& evt, const edm::EventSetup& evtSetup); + virtual void analyze(const edm::Event& evt, const edm::EventSetup& evtSetup); private: - - void inspectRecord(const std::string & rcdname, - const edm::Event& evt, - const edm::ESHandle & alignments); + void inspectRecord(const std::string& rcdname, const edm::Event& evt, const edm::ESHandle& alignments); int mode_; bool verbose_; edm::ESWatcher watchTk_; - edm::ESWatcher watchDT_; - edm::ESWatcher watchCSC_; + edm::ESWatcher watchDT_; + edm::ESWatcher watchCSC_; - Alignments *refAlignments_; + Alignments* refAlignments_; }; -AlignmentRcdScan::AlignmentRcdScan( const edm::ParameterSet& iConfig ) - :verbose_(iConfig.getUntrackedParameter("verbose")), - refAlignments_(0) -{ +AlignmentRcdScan::AlignmentRcdScan(const edm::ParameterSet& iConfig) + : verbose_(iConfig.getUntrackedParameter("verbose")), refAlignments_(0) { std::string modestring = iConfig.getUntrackedParameter("mode"); - if (modestring=="Tk") { + if (modestring == "Tk") { mode_ = Tk; - } else if (modestring=="DT") { + } else if (modestring == "DT") { mode_ = DT; - } else if (modestring=="CSC") { + } else if (modestring == "CSC") { mode_ = CSC; } else { mode_ = Unknown; } - if (mode_==Unknown) { + if (mode_ == Unknown) { throw cms::Exception("BadConfig") << "Mode " << modestring << " not known"; } } -AlignmentRcdScan::~AlignmentRcdScan() -{ - if (refAlignments_) delete refAlignments_; +AlignmentRcdScan::~AlignmentRcdScan() { + if (refAlignments_) + delete refAlignments_; } -void AlignmentRcdScan::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) -{ - if (mode_==Tk && watchTk_.check(evtSetup)) { +void AlignmentRcdScan::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) { + if (mode_ == Tk && watchTk_.check(evtSetup)) { edm::ESHandle alignments; evtSetup.get().get(alignments); inspectRecord("TrackerAlignmentRcd", evt, alignments); } - if (mode_==DT && watchDT_.check(evtSetup)) { + if (mode_ == DT && watchDT_.check(evtSetup)) { edm::ESHandle alignments; - evtSetup.get().get(alignments); + evtSetup.get().get(alignments); inspectRecord("DTAlignmentRcd", evt, alignments); } - if (mode_==CSC && watchCSC_.check(evtSetup)) { + if (mode_ == CSC && watchCSC_.check(evtSetup)) { edm::ESHandle alignments; - evtSetup.get().get(alignments); + evtSetup.get().get(alignments); inspectRecord("CSCAlignmentRcd", evt, alignments); } } - -void AlignmentRcdScan::inspectRecord(const std::string & rcdname, - const edm::Event& evt, - const edm::ESHandle & alignments) -{ + +void AlignmentRcdScan::inspectRecord(const std::string& rcdname, + const edm::Event& evt, + const edm::ESHandle& alignments) { std::cout << rcdname << " content starting from run " << evt.run(); - - if (verbose_==false) { + + if (verbose_ == false) { std::cout << std::endl; return; } std::cout << " with " << alignments->m_align.size() << " entries" << std::endl; - - if (refAlignments_) { + if (refAlignments_) { std::cout << " Compared to previous record:" << std::endl; - + double meanX = 0; double rmsX = 0; double meanY = 0; @@ -130,30 +115,30 @@ void AlignmentRcdScan::inspectRecord(const std::string & rcdname, double dPhi; double meanPhi = 0; double rmsPhi = 0; - + std::vector::const_iterator iref = refAlignments_->m_align.begin(); - for (std::vector::const_iterator i = alignments->m_align.begin(); - i != alignments->m_align.end(); - ++i, ++iref) { - + for (std::vector::const_iterator i = alignments->m_align.begin(); i != alignments->m_align.end(); + ++i, ++iref) { meanX += i->translation().x() - iref->translation().x(); rmsX += pow(i->translation().x() - iref->translation().x(), 2); - + meanY += i->translation().y() - iref->translation().y(); rmsY += pow(i->translation().y() - iref->translation().y(), 2); - + meanZ += i->translation().z() - iref->translation().z(); rmsZ += pow(i->translation().z() - iref->translation().z(), 2); - + meanR += i->translation().perp() - iref->translation().perp(); rmsR += pow(i->translation().perp() - iref->translation().perp(), 2); dPhi = i->translation().phi() - iref->translation().phi(); - if (dPhi>TMath::Pi()) dPhi -= 2.0*TMath::Pi(); - if (dPhi<-TMath::Pi()) dPhi += 2.0*TMath::Pi(); + if (dPhi > TMath::Pi()) + dPhi -= 2.0 * TMath::Pi(); + if (dPhi < -TMath::Pi()) + dPhi += 2.0 * TMath::Pi(); meanPhi += dPhi; - rmsPhi += dPhi*dPhi; + rmsPhi += dPhi * dPhi; } meanX /= alignments->m_align.size(); @@ -166,23 +151,18 @@ void AlignmentRcdScan::inspectRecord(const std::string & rcdname, rmsR /= alignments->m_align.size(); meanPhi /= alignments->m_align.size(); rmsPhi /= alignments->m_align.size(); - - std::cout << " mean X shift: " - << std::setw(12) << std::scientific << std::setprecision(3) << meanX - << " (RMS = " << sqrt(rmsX) << ")" << std::endl; - std::cout << " mean Y shift: " - << std::setw(12) << std::scientific << std::setprecision(3) << meanY - << " (RMS = " << sqrt(rmsY) << ")" << std::endl; - std::cout << " mean Z shift: " - << std::setw(12) << std::scientific << std::setprecision(3) << meanZ - << " (RMS = " << sqrt(rmsZ) << ")" << std::endl; - std::cout << " mean R shift: " - << std::setw(12) << std::scientific << std::setprecision(3) << meanR - << " (RMS = " << sqrt(rmsR) << ")" << std::endl; - std::cout << " mean Phi shift: " - << std::setw(12) << std::scientific << std::setprecision(3) << meanPhi - << " (RMS = " << sqrt(rmsPhi) << ")" << std::endl; - + + std::cout << " mean X shift: " << std::setw(12) << std::scientific << std::setprecision(3) << meanX + << " (RMS = " << sqrt(rmsX) << ")" << std::endl; + std::cout << " mean Y shift: " << std::setw(12) << std::scientific << std::setprecision(3) << meanY + << " (RMS = " << sqrt(rmsY) << ")" << std::endl; + std::cout << " mean Z shift: " << std::setw(12) << std::scientific << std::setprecision(3) << meanZ + << " (RMS = " << sqrt(rmsZ) << ")" << std::endl; + std::cout << " mean R shift: " << std::setw(12) << std::scientific << std::setprecision(3) << meanR + << " (RMS = " << sqrt(rmsR) << ")" << std::endl; + std::cout << " mean Phi shift: " << std::setw(12) << std::scientific << std::setprecision(3) << meanPhi + << " (RMS = " << sqrt(rmsPhi) << ")" << std::endl; + delete refAlignments_; } diff --git a/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdRead.cpp b/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdRead.cpp index 21fd616607124..49d294153fbe3 100644 --- a/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdRead.cpp +++ b/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdRead.cpp @@ -11,48 +11,40 @@ #include "CondFormats/AlignmentRecord/interface/GlobalPositionRcd.h" #include "DataFormats/DetId/interface/DetId.h" -class GlobalPositionRcdRead : public edm::EDAnalyzer -{ +class GlobalPositionRcdRead : public edm::EDAnalyzer { public: - explicit GlobalPositionRcdRead( const edm::ParameterSet& iConfig ) - : nEventCalls_(0) - {} + explicit GlobalPositionRcdRead(const edm::ParameterSet& iConfig) : nEventCalls_(0) {} ~GlobalPositionRcdRead() {} - virtual void analyze(const edm::Event& evt, const edm::EventSetup& evtSetup); - -private: + virtual void analyze(const edm::Event& evt, const edm::EventSetup& evtSetup); +private: unsigned int nEventCalls_; }; -void GlobalPositionRcdRead::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) -{ - if (nEventCalls_>0) { +void GlobalPositionRcdRead::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) { + if (nEventCalls_ > 0) { std::cout << "Reading from DB to be done only once, " - << "set 'untracked PSet maxEvents = {untracked int32 input = 1}'." << std::endl; - + << "set 'untracked PSet maxEvents = {untracked int32 input = 1}'." << std::endl; + return; } std::cout << "Reading from database in GlobalPositionRcdRead::analyze..." << std::endl; - + edm::ESHandle globalPositionRcd; evtSetup.get().get(globalPositionRcd); - - std::cout << "Expecting entries in " - << DetId(DetId::Tracker).rawId() << " " - << DetId(DetId::Muon).rawId() << " " - << DetId(DetId::Ecal).rawId() << " " - << DetId(DetId::Hcal).rawId() << " " - << DetId(DetId::Calo).rawId() << std::endl; + + std::cout << "Expecting entries in " << DetId(DetId::Tracker).rawId() << " " << DetId(DetId::Muon).rawId() << " " + << DetId(DetId::Ecal).rawId() << " " << DetId(DetId::Hcal).rawId() << " " << DetId(DetId::Calo).rawId() + << std::endl; for (std::vector::const_iterator i = globalPositionRcd->m_align.begin(); - i != globalPositionRcd->m_align.end(); ++i) { - std::cout << "entry " << i->rawId() - << " translation " << i->translation() - << " angles " << i->rotation().eulerAngles() << std::endl; + i != globalPositionRcd->m_align.end(); + ++i) { + std::cout << "entry " << i->rawId() << " translation " << i->translation() << " angles " + << i->rotation().eulerAngles() << std::endl; std::cout << i->rotation() << std::endl; } - + std::cout << "done!" << std::endl; nEventCalls_++; } diff --git a/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdScan.cpp b/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdScan.cpp index df33594204a1e..6ede80231d3ae 100644 --- a/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdScan.cpp +++ b/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdScan.cpp @@ -16,17 +16,15 @@ #include "Alignment/CommonAlignment/interface/Utilities.h" -class GlobalPositionRcdScan : public edm::EDAnalyzer -{ +class GlobalPositionRcdScan : public edm::EDAnalyzer { public: explicit GlobalPositionRcdScan(const edm::ParameterSet& iConfig); virtual ~GlobalPositionRcdScan() {} - virtual void analyze(const edm::Event& evt, const edm::EventSetup& evtSetup); + virtual void analyze(const edm::Event& evt, const edm::EventSetup& evtSetup); virtual void endJob(); private: - edm::ESWatcher watcher_; bool eulerAngles_; @@ -37,88 +35,84 @@ class GlobalPositionRcdScan : public edm::EDAnalyzer }; GlobalPositionRcdScan::GlobalPositionRcdScan(const edm::ParameterSet& iConfig) - : eulerAngles_(false), alignAngles_(false), matrix_(false), - firstRun_(0), lastRun_(0) -{ - + : eulerAngles_(false), alignAngles_(false), matrix_(false), firstRun_(0), lastRun_(0) { const std::string howRot(iConfig.getParameter("rotation")); - - if (howRot == "euler" || howRot == "all") eulerAngles_ = true; - if (howRot == "align" || howRot == "all") alignAngles_ = true; - if (howRot == "matrix" || howRot == "all") matrix_ = true; + + if (howRot == "euler" || howRot == "all") + eulerAngles_ = true; + if (howRot == "align" || howRot == "all") + alignAngles_ = true; + if (howRot == "matrix" || howRot == "all") + matrix_ = true; if (!eulerAngles_ && !alignAngles_ && !matrix_) { edm::LogError("BadConfig") << "@SUB=GlobalPositionRcdScan" - << "Parameter 'rotation' should be 'euler', 'align'," - << "'matrix' or 'all', but is '" << howRot - << "'. Treat as 'all'."; + << "Parameter 'rotation' should be 'euler', 'align'," + << "'matrix' or 'all', but is '" << howRot << "'. Treat as 'all'."; eulerAngles_ = alignAngles_ = matrix_ = true; } - } -void GlobalPositionRcdScan::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) -{ +void GlobalPositionRcdScan::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) { lastRun_ = evt.run(); - if (0 == firstRun_) firstRun_ = lastRun_; + if (0 == firstRun_) + firstRun_ = lastRun_; if (watcher_.check(evtSetup)) { - edm::ESHandle globalPositionRcd; evtSetup.get().get(globalPositionRcd); - std::cout << "=====================================================\n" - << "GlobalPositionRcd content starting from run " << evt.run() << ":" << std::endl; - + std::cout << "=====================================================\n" + << "GlobalPositionRcd content starting from run " << evt.run() << ":" << std::endl; + for (std::vector::const_iterator i = globalPositionRcd->m_align.begin(); - i != globalPositionRcd->m_align.end(); ++i) { + i != globalPositionRcd->m_align.end(); + ++i) { std::cout << " Component "; if (i->rawId() == DetId(DetId::Tracker).rawId()) { - std::cout << "Tracker"; - } - else if (i->rawId() == DetId(DetId::Muon).rawId()) { - std::cout << "Muon "; + std::cout << "Tracker"; + } else if (i->rawId() == DetId(DetId::Muon).rawId()) { + std::cout << "Muon "; + } else if (i->rawId() == DetId(DetId::Ecal).rawId()) { + std::cout << "Ecal "; + } else if (i->rawId() == DetId(DetId::Hcal).rawId()) { + std::cout << "Hcal "; + } else if (i->rawId() == DetId(DetId::Calo).rawId()) { + std::cout << "Calo "; + } else { + std::cout << "Unknown"; } - else if (i->rawId() == DetId(DetId::Ecal).rawId()) { - std::cout << "Ecal "; - } - else if (i->rawId() == DetId(DetId::Hcal).rawId()) { - std::cout << "Hcal "; - } - else if (i->rawId() == DetId(DetId::Calo).rawId()) { - std::cout << "Calo "; - } - else { - std::cout << "Unknown"; - } - std::cout << " entry " << i->rawId() - << "\n translation " << i->translation() << "\n"; + std::cout << " entry " << i->rawId() << "\n translation " << i->translation() << "\n"; const AlignTransform::Rotation hepRot(i->rotation()); if (eulerAngles_) { - std::cout << " euler angles " << hepRot.eulerAngles() << std::endl; + std::cout << " euler angles " << hepRot.eulerAngles() << std::endl; } if (alignAngles_) { - const align::RotationType matrix(hepRot.xx(), hepRot.xy(), hepRot.xz(), - hepRot.yx(), hepRot.yy(), hepRot.yz(), - hepRot.zx(), hepRot.zy(), hepRot.zz()); - const AlgebraicVector angles(align::toAngles(matrix)); - std::cout << " alpha, beta, gamma (" << angles[0] << ", " << angles[1] << ", " - << angles[2] << ')' << std::endl; + const align::RotationType matrix(hepRot.xx(), + hepRot.xy(), + hepRot.xz(), + hepRot.yx(), + hepRot.yy(), + hepRot.yz(), + hepRot.zx(), + hepRot.zy(), + hepRot.zz()); + const AlgebraicVector angles(align::toAngles(matrix)); + std::cout << " alpha, beta, gamma (" << angles[0] << ", " << angles[1] << ", " << angles[2] << ')' + << std::endl; } if (matrix_) { - std::cout << " rotation matrix " << hepRot << std::endl; + std::cout << " rotation matrix " << hepRot << std::endl; } } } } -void GlobalPositionRcdScan::endJob() -{ - std::cout << "\n=====================================================\n" - << "=====================================================\n" - << "Checked run range " << firstRun_ << " to " << lastRun_ << "." << std::endl; +void GlobalPositionRcdScan::endJob() { + std::cout << "\n=====================================================\n" + << "=====================================================\n" + << "Checked run range " << firstRun_ << " to " << lastRun_ << "." << std::endl; } - //define this as a plug-in DEFINE_FWK_MODULE(GlobalPositionRcdScan); diff --git a/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdWrite.cpp b/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdWrite.cpp index 7af926960b6ba..d34780d0b9285 100644 --- a/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdWrite.cpp +++ b/Alignment/CommonAlignmentProducer/test/GlobalPositionRcdWrite.cpp @@ -21,22 +21,20 @@ #include "CondFormats/Alignment/interface/AlignTransform.h" #include "CondFormats/AlignmentRecord/interface/GlobalPositionRcd.h" -class GlobalPositionRcdWrite : public edm::EDAnalyzer { - public: - explicit GlobalPositionRcdWrite(const edm::ParameterSet& iConfig) - : m_useEulerAngles(iConfig.getParameter("useEulerAngles")) - , m_tracker(iConfig.getParameter("tracker")) - , m_muon(iConfig.getParameter("muon")) - , m_ecal(iConfig.getParameter("ecal")) - , m_hcal(iConfig.getParameter("hcal")) - , m_calo(iConfig.getParameter("calo")) - , nEventCalls_(0) - {}; - ~GlobalPositionRcdWrite() {} +class GlobalPositionRcdWrite : public edm::EDAnalyzer { +public: + explicit GlobalPositionRcdWrite(const edm::ParameterSet& iConfig) + : m_useEulerAngles(iConfig.getParameter("useEulerAngles")), + m_tracker(iConfig.getParameter("tracker")), + m_muon(iConfig.getParameter("muon")), + m_ecal(iConfig.getParameter("ecal")), + m_hcal(iConfig.getParameter("hcal")), + m_calo(iConfig.getParameter("calo")), + nEventCalls_(0){}; + ~GlobalPositionRcdWrite() {} virtual void analyze(const edm::Event& evt, const edm::EventSetup& evtSetup); private: - AlignTransform::Rotation toMatrix(double alpha, double beta, double gamma); bool m_useEulerAngles; @@ -44,147 +42,140 @@ class GlobalPositionRcdWrite : public edm::EDAnalyzer { unsigned int nEventCalls_; }; -AlignTransform::Rotation GlobalPositionRcdWrite::toMatrix(double alpha, double beta, double gamma) -{ +AlignTransform::Rotation GlobalPositionRcdWrite::toMatrix(double alpha, double beta, double gamma) { align::EulerAngles angles(3); angles(1) = alpha; angles(2) = beta; angles(3) = gamma; - + align::RotationType alignRotation = align::toMatrix(angles); - return AlignTransform::Rotation(CLHEP::HepRep3x3(alignRotation.xx(), alignRotation.xy(), alignRotation.xz(), - alignRotation.yx(), alignRotation.yy(), alignRotation.yz(), - alignRotation.zx(), alignRotation.zy(), alignRotation.zz())); + return AlignTransform::Rotation(CLHEP::HepRep3x3(alignRotation.xx(), + alignRotation.xy(), + alignRotation.xz(), + alignRotation.yx(), + alignRotation.yy(), + alignRotation.yz(), + alignRotation.zx(), + alignRotation.zy(), + alignRotation.zz())); } -void GlobalPositionRcdWrite::analyze(const edm::Event& evt, const edm::EventSetup& iSetup) -{ - if (nEventCalls_ > 0) { - std::cout << "Writing to DB to be done only once, " - << "set 'untracked PSet maxEvents = {untracked int32 input = 1}'." - << "(Your writing should be fine.)" << std::endl; - return; - } - - Alignments* globalPositions = new Alignments(); - - AlignTransform tracker(AlignTransform::Translation(m_tracker.getParameter("x"), - m_tracker.getParameter("y"), - m_tracker.getParameter("z")), - (m_useEulerAngles != true) ? - this->toMatrix(m_tracker.getParameter("alpha"), - m_tracker.getParameter("beta"), - m_tracker.getParameter("gamma")) - : - AlignTransform::EulerAngles(m_tracker.getParameter("alpha"), - m_tracker.getParameter("beta"), - m_tracker.getParameter("gamma")), - DetId(DetId::Tracker).rawId()); - - AlignTransform muon(AlignTransform::Translation(m_muon.getParameter("x"), - m_muon.getParameter("y"), - m_muon.getParameter("z")), - (m_useEulerAngles != true) ? - this->toMatrix(m_muon.getParameter("alpha"), - m_muon.getParameter("beta"), - m_muon.getParameter("gamma")) - : - AlignTransform::EulerAngles(m_muon.getParameter("alpha"), - m_muon.getParameter("beta"), - m_muon.getParameter("gamma")), - DetId(DetId::Muon).rawId()); - - AlignTransform ecal(AlignTransform::Translation(m_ecal.getParameter("x"), - m_ecal.getParameter("y"), - m_ecal.getParameter("z")), - (m_useEulerAngles != true) ? - this->toMatrix(m_ecal.getParameter("alpha"), - m_ecal.getParameter("beta"), - m_ecal.getParameter("gamma")) - : - AlignTransform::EulerAngles(m_ecal.getParameter("alpha"), - m_ecal.getParameter("beta"), - m_ecal.getParameter("gamma")), - DetId(DetId::Ecal).rawId()); - - AlignTransform hcal(AlignTransform::Translation(m_hcal.getParameter("x"), - m_hcal.getParameter("y"), - m_hcal.getParameter("z")), - (m_useEulerAngles != true) ? - this->toMatrix(m_hcal.getParameter("alpha"), - m_hcal.getParameter("beta"), - m_hcal.getParameter("gamma")) - : - AlignTransform::EulerAngles(m_hcal.getParameter("alpha"), - m_hcal.getParameter("beta"), - m_hcal.getParameter("gamma")), - DetId(DetId::Hcal).rawId()); - - AlignTransform calo(AlignTransform::Translation(m_calo.getParameter("x"), - m_calo.getParameter("y"), - m_calo.getParameter("z")), - (m_useEulerAngles != true) ? - this->toMatrix(m_calo.getParameter("alpha"), - m_calo.getParameter("beta"), - m_calo.getParameter("gamma")) - : - AlignTransform::EulerAngles(m_calo.getParameter("alpha"), - m_calo.getParameter("beta"), - m_calo.getParameter("gamma")), - DetId(DetId::Calo).rawId()); - - std::cout << "\nProvided rotation angles are interpreted as " - << ((m_useEulerAngles != true) ? "rotations around X, Y and Z" : "Euler angles") - << ".\n" << std::endl; - - std::cout << "Tracker (" << tracker.rawId() << ") at " << tracker.translation() - << " " << tracker.rotation().eulerAngles() << std::endl; - std::cout << tracker.rotation() << std::endl; - - std::cout << "Muon (" << muon.rawId() << ") at " << muon.translation() - << " " << muon.rotation().eulerAngles() << std::endl; - std::cout << muon.rotation() << std::endl; - - std::cout << "Ecal (" << ecal.rawId() << ") at " << ecal.translation() - << " " << ecal.rotation().eulerAngles() << std::endl; - std::cout << ecal.rotation() << std::endl; - - std::cout << "Hcal (" << hcal.rawId() << ") at " << hcal.translation() - << " " << hcal.rotation().eulerAngles() << std::endl; - std::cout << hcal.rotation() << std::endl; - - std::cout << "Calo (" << calo.rawId() << ") at " << calo.translation() - << " " << calo.rotation().eulerAngles() << std::endl; - std::cout << calo.rotation() << std::endl; - - globalPositions->m_align.push_back(tracker); - globalPositions->m_align.push_back(muon); - globalPositions->m_align.push_back(ecal); - globalPositions->m_align.push_back(hcal); - globalPositions->m_align.push_back(calo); - - std::cout << "Uploading to the database..." << std::endl; - - edm::Service poolDbService; - - if (!poolDbService.isAvailable()) - throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; - -// if (poolDbService->isNewTagRequest("GlobalPositionRcd")) { -// poolDbService->createNewIOV(&(*globalPositions), poolDbService->endOfTime(), "GlobalPositionRcd"); -// } else { -// poolDbService->appendSinceTime(&(*globalPositions), poolDbService->currentTime(), "GlobalPositionRcd"); -// } - poolDbService->writeOne(&(*globalPositions), - poolDbService->currentTime(), - //poolDbService->beginOfTime(), - "GlobalPositionRcd"); - - - - std::cout << "done!" << std::endl; - nEventCalls_++; +void GlobalPositionRcdWrite::analyze(const edm::Event& evt, const edm::EventSetup& iSetup) { + if (nEventCalls_ > 0) { + std::cout << "Writing to DB to be done only once, " + << "set 'untracked PSet maxEvents = {untracked int32 input = 1}'." + << "(Your writing should be fine.)" << std::endl; + return; + } + + Alignments* globalPositions = new Alignments(); + + AlignTransform tracker(AlignTransform::Translation(m_tracker.getParameter("x"), + m_tracker.getParameter("y"), + m_tracker.getParameter("z")), + (m_useEulerAngles != true) + ? this->toMatrix(m_tracker.getParameter("alpha"), + m_tracker.getParameter("beta"), + m_tracker.getParameter("gamma")) + : AlignTransform::EulerAngles(m_tracker.getParameter("alpha"), + m_tracker.getParameter("beta"), + m_tracker.getParameter("gamma")), + DetId(DetId::Tracker).rawId()); + + AlignTransform muon( + AlignTransform::Translation( + m_muon.getParameter("x"), m_muon.getParameter("y"), m_muon.getParameter("z")), + (m_useEulerAngles != true) ? this->toMatrix(m_muon.getParameter("alpha"), + m_muon.getParameter("beta"), + m_muon.getParameter("gamma")) + : AlignTransform::EulerAngles(m_muon.getParameter("alpha"), + m_muon.getParameter("beta"), + m_muon.getParameter("gamma")), + DetId(DetId::Muon).rawId()); + + AlignTransform ecal( + AlignTransform::Translation( + m_ecal.getParameter("x"), m_ecal.getParameter("y"), m_ecal.getParameter("z")), + (m_useEulerAngles != true) ? this->toMatrix(m_ecal.getParameter("alpha"), + m_ecal.getParameter("beta"), + m_ecal.getParameter("gamma")) + : AlignTransform::EulerAngles(m_ecal.getParameter("alpha"), + m_ecal.getParameter("beta"), + m_ecal.getParameter("gamma")), + DetId(DetId::Ecal).rawId()); + + AlignTransform hcal( + AlignTransform::Translation( + m_hcal.getParameter("x"), m_hcal.getParameter("y"), m_hcal.getParameter("z")), + (m_useEulerAngles != true) ? this->toMatrix(m_hcal.getParameter("alpha"), + m_hcal.getParameter("beta"), + m_hcal.getParameter("gamma")) + : AlignTransform::EulerAngles(m_hcal.getParameter("alpha"), + m_hcal.getParameter("beta"), + m_hcal.getParameter("gamma")), + DetId(DetId::Hcal).rawId()); + + AlignTransform calo( + AlignTransform::Translation( + m_calo.getParameter("x"), m_calo.getParameter("y"), m_calo.getParameter("z")), + (m_useEulerAngles != true) ? this->toMatrix(m_calo.getParameter("alpha"), + m_calo.getParameter("beta"), + m_calo.getParameter("gamma")) + : AlignTransform::EulerAngles(m_calo.getParameter("alpha"), + m_calo.getParameter("beta"), + m_calo.getParameter("gamma")), + DetId(DetId::Calo).rawId()); + + std::cout << "\nProvided rotation angles are interpreted as " + << ((m_useEulerAngles != true) ? "rotations around X, Y and Z" : "Euler angles") << ".\n" + << std::endl; + + std::cout << "Tracker (" << tracker.rawId() << ") at " << tracker.translation() << " " + << tracker.rotation().eulerAngles() << std::endl; + std::cout << tracker.rotation() << std::endl; + + std::cout << "Muon (" << muon.rawId() << ") at " << muon.translation() << " " << muon.rotation().eulerAngles() + << std::endl; + std::cout << muon.rotation() << std::endl; + + std::cout << "Ecal (" << ecal.rawId() << ") at " << ecal.translation() << " " << ecal.rotation().eulerAngles() + << std::endl; + std::cout << ecal.rotation() << std::endl; + + std::cout << "Hcal (" << hcal.rawId() << ") at " << hcal.translation() << " " << hcal.rotation().eulerAngles() + << std::endl; + std::cout << hcal.rotation() << std::endl; + + std::cout << "Calo (" << calo.rawId() << ") at " << calo.translation() << " " << calo.rotation().eulerAngles() + << std::endl; + std::cout << calo.rotation() << std::endl; + + globalPositions->m_align.push_back(tracker); + globalPositions->m_align.push_back(muon); + globalPositions->m_align.push_back(ecal); + globalPositions->m_align.push_back(hcal); + globalPositions->m_align.push_back(calo); + + std::cout << "Uploading to the database..." << std::endl; + + edm::Service poolDbService; + + if (!poolDbService.isAvailable()) + throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; + + // if (poolDbService->isNewTagRequest("GlobalPositionRcd")) { + // poolDbService->createNewIOV(&(*globalPositions), poolDbService->endOfTime(), "GlobalPositionRcd"); + // } else { + // poolDbService->appendSinceTime(&(*globalPositions), poolDbService->currentTime(), "GlobalPositionRcd"); + // } + poolDbService->writeOne(&(*globalPositions), + poolDbService->currentTime(), + //poolDbService->beginOfTime(), + "GlobalPositionRcd"); + + std::cout << "done!" << std::endl; + nEventCalls_++; } //define this as a plug-in diff --git a/Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc b/Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc index 8a97f5256f03c..5f54828c5ecfa 100644 --- a/Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc +++ b/Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc @@ -2,7 +2,7 @@ // // Package: TestAccessGeom // Class: TestAccessGeom -// +// /**\class TestAccessGeom Alignment/CommonAlignmentProducer/test/TestAccessGeom.cc Description: @@ -17,7 +17,6 @@ // // - // system include files #include @@ -31,9 +30,9 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" -#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" -#include "Geometry/DTGeometry/interface/DTGeometry.h" -#include "Geometry/CSCGeometry/interface/CSCGeometry.h" +#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" +#include "Geometry/DTGeometry/interface/DTGeometry.h" +#include "Geometry/CSCGeometry/interface/CSCGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/Records/interface/MuonGeometryRecord.h" @@ -49,19 +48,18 @@ // class TestAccessGeom : public edm::EDAnalyzer { - public: - explicit TestAccessGeom(const edm::ParameterSet&); - ~TestAccessGeom(); - +public: + explicit TestAccessGeom(const edm::ParameterSet&); + ~TestAccessGeom(); - private: - virtual void analyze(const edm::Event&, const edm::EventSetup&); +private: + virtual void analyze(const edm::Event&, const edm::EventSetup&); - // ----------member data --------------------------- + // ----------member data --------------------------- - const std::vector tkGeomLabels_; - const std::vector dtGeomLabels_; - const std::vector cscGeomLabels_; + const std::vector tkGeomLabels_; + const std::vector dtGeomLabels_; + const std::vector cscGeomLabels_; }; // @@ -76,73 +74,63 @@ class TestAccessGeom : public edm::EDAnalyzer { // constructors and destructor // TestAccessGeom::TestAccessGeom(const edm::ParameterSet& iConfig) - : tkGeomLabels_(iConfig.getParameter >("TrackerGeomLabels")), - dtGeomLabels_(iConfig.getParameter >("DTGeomLabels")), - cscGeomLabels_(iConfig.getParameter >("CSCGeomLabels")) -{ - //now do what ever initialization is needed - + : tkGeomLabels_(iConfig.getParameter >("TrackerGeomLabels")), + dtGeomLabels_(iConfig.getParameter >("DTGeomLabels")), + cscGeomLabels_(iConfig.getParameter >("CSCGeomLabels")) { + //now do what ever initialization is needed } - -TestAccessGeom::~TestAccessGeom() -{ - - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) - +TestAccessGeom::~TestAccessGeom() { + // do anything here that needs to be done at desctruction time + // (e.g. close files, deallocate resources etc.) } - // // member functions // // ------------ method called to for each event ------------ -void -TestAccessGeom::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - using std::vector; +void TestAccessGeom::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using std::string; + using std::vector; - edm::LogInfo("Test") << "@SUB=analyze" << "Try to access " << tkGeomLabels_.size() - << " Tracker-, " << dtGeomLabels_.size() << " DT- and " - << cscGeomLabels_.size() << " CSC-geometries."; + edm::LogInfo("Test") << "@SUB=analyze" + << "Try to access " << tkGeomLabels_.size() << " Tracker-, " << dtGeomLabels_.size() + << " DT- and " << cscGeomLabels_.size() << " CSC-geometries."; - for (vector::const_iterator iL = tkGeomLabels_.begin(), iE = tkGeomLabels_.end(); - iL != iE; ++iL) { - TString label(iL->c_str()); label.ReplaceAll(" ", ""); // fix for buggy framework + for (vector::const_iterator iL = tkGeomLabels_.begin(), iE = tkGeomLabels_.end(); iL != iE; ++iL) { + TString label(iL->c_str()); + label.ReplaceAll(" ", ""); // fix for buggy framework edm::LogInfo("Test") << "Try access to tracker geometry with label '" << label << "'."; //*iL << "'."; edm::ESHandle tkGeomHandle; - iSetup.get().get(label, tkGeomHandle);// *iL, tkGeomHandle); + iSetup.get().get(label, tkGeomHandle); // *iL, tkGeomHandle); edm::LogInfo("Test") << "TrackerGeometry pointer: " << tkGeomHandle.product(); } - for (vector::const_iterator iL = dtGeomLabels_.begin(), iE = dtGeomLabels_.end(); - iL != iE; ++iL) { - TString label(iL->c_str()); label.ReplaceAll(" ", ""); // fix for buggy framework + for (vector::const_iterator iL = dtGeomLabels_.begin(), iE = dtGeomLabels_.end(); iL != iE; ++iL) { + TString label(iL->c_str()); + label.ReplaceAll(" ", ""); // fix for buggy framework edm::LogInfo("Test") << "Try access to DT geometry with label '" << label << "'."; //*iL << "'."; edm::ESHandle dtGeomHandle; - iSetup.get().get(label, dtGeomHandle);//*iL, dtGeomHandle); + iSetup.get().get(label, dtGeomHandle); //*iL, dtGeomHandle); edm::LogInfo("Test") << "DTGeometry pointer: " << dtGeomHandle.product(); } - for (vector::const_iterator iL = cscGeomLabels_.begin(), iE = cscGeomLabels_.end(); - iL != iE; ++iL) { - TString label(iL->c_str()); label.ReplaceAll(" ", ""); // fix for buggy framework + for (vector::const_iterator iL = cscGeomLabels_.begin(), iE = cscGeomLabels_.end(); iL != iE; ++iL) { + TString label(iL->c_str()); + label.ReplaceAll(" ", ""); // fix for buggy framework edm::LogInfo("Test") << "Try access to CSC geometry with label '" << label << "'."; //*iL << "'."; edm::ESHandle cscGeomHandle; - iSetup.get().get(label, cscGeomHandle); //*iL, cscGeomHandle); + iSetup.get().get(label, cscGeomHandle); //*iL, cscGeomHandle); edm::LogInfo("Test") << "CSCGeometry pointer: " << cscGeomHandle.product(); } - - edm::LogInfo("Test") << "@SUB=analyze" << "Succesfully accessed " << tkGeomLabels_.size() - << " Tracker-, " << dtGeomLabels_.size() << " DT- and " - << cscGeomLabels_.size() << " CSC-geometries."; + edm::LogInfo("Test") << "@SUB=analyze" + << "Succesfully accessed " << tkGeomLabels_.size() << " Tracker-, " << dtGeomLabels_.size() + << " DT- and " << cscGeomLabels_.size() << " CSC-geometries."; } //define this as a plug-in diff --git a/Alignment/Geners/interface/AbsArchive.hh b/Alignment/Geners/interface/AbsArchive.hh index 74222eb503cfa..a228fb15bd8de 100644 --- a/Alignment/Geners/interface/AbsArchive.hh +++ b/Alignment/Geners/interface/AbsArchive.hh @@ -3,167 +3,156 @@ #include -#include "Alignment/Geners/interface/CPP11_shared_ptr.hh" #include "Alignment/Geners/interface/AbsRecord.hh" #include "Alignment/Geners/interface/AbsReference.hh" +#include "Alignment/Geners/interface/CPP11_shared_ptr.hh" #include "Alignment/Geners/interface/CatalogEntry.hh" #include "Alignment/Geners/interface/SearchSpecifier.hh" namespace gs { - class AbsArchive; + class AbsArchive; } -gs::AbsArchive& operator<<(gs::AbsArchive& ar, const gs::AbsRecord& record); +gs::AbsArchive &operator<<(gs::AbsArchive &ar, const gs::AbsRecord &record); namespace gs { + // + // If you need to retrieve the items, use the interface provided + // by the "Reference" class. Public interface of this class only + // allows to examine the item metadata and to copy items as BLOBs. + // + class AbsArchive { + public: + AbsArchive(const char *name); + inline virtual ~AbsArchive() {} + + // Archive name + const std::string &name() const { return name_; } + + // Is it correctly open? + virtual bool isOpen() const = 0; + + // If an attempt to open the archive failed, call the following + // method to find out why + virtual std::string error() const = 0; + + // Is the archive readable? + virtual bool isReadable() const = 0; + + // Is the archive writable? + virtual bool isWritable() const = 0; + + // Number of items in the archive. Note that id value + // of 0 refers to an invalid item. + virtual unsigned long long size() const = 0; + + // Smallest and largest ids of any item in the archive + virtual unsigned long long smallestId() const = 0; + virtual unsigned long long largestId() const = 0; + + // Are the item ids contiguous between the smallest and + // the largest? + virtual bool idsAreContiguous() const = 0; + + // Check if the item with given id is actually present + // in the archive + virtual bool itemExists(unsigned long long id) const = 0; + + // Search for matching items based on item name and + // category (no type match required) + virtual void itemSearch(const SearchSpecifier &namePattern, + const SearchSpecifier &categoryPattern, + std::vector *found) const = 0; + + // Fetch metadata for the item with given id. NULL pointer is + // returned if there is no item in the archive with the given id + // (and there is an automatic cast from CPP11_shared_ptr to bool). + virtual CPP11_shared_ptr catalogEntry(unsigned long long id) = 0; + + // Dump everything to storage (if the archive is open for writing + // and if this makes sense for the archive) + virtual void flush() = 0; + + // Copy an item from this archive to a destination archive. + // This archive and destination archive must be distinct. + // Note that, while it is always possible to copy an item + // with correct id, a standalone operation like this is + // not necessarily going to make sense because the item + // could be just a part of some distributed object. // - // If you need to retrieve the items, use the interface provided - // by the "Reference" class. Public interface of this class only - // allows to examine the item metadata and to copy items as BLOBs. - // - class AbsArchive - { - public: - AbsArchive(const char* name); - inline virtual ~AbsArchive() {} - - // Archive name - const std::string& name() const {return name_;} - - // Is it correctly open? - virtual bool isOpen() const = 0; - - // If an attempt to open the archive failed, call the following - // method to find out why - virtual std::string error() const = 0; - - // Is the archive readable? - virtual bool isReadable() const = 0; - - // Is the archive writable? - virtual bool isWritable() const = 0; - - // Number of items in the archive. Note that id value - // of 0 refers to an invalid item. - virtual unsigned long long size() const = 0; - - // Smallest and largest ids of any item in the archive - virtual unsigned long long smallestId() const = 0; - virtual unsigned long long largestId() const = 0; - - // Are the item ids contiguous between the smallest and - // the largest? - virtual bool idsAreContiguous() const = 0; - - // Check if the item with given id is actually present - // in the archive - virtual bool itemExists(unsigned long long id) const = 0; - - // Search for matching items based on item name and - // category (no type match required) - virtual void itemSearch(const SearchSpecifier& namePattern, - const SearchSpecifier& categoryPattern, - std::vector* found) const=0; - - // Fetch metadata for the item with given id. NULL pointer is - // returned if there is no item in the archive with the given id - // (and there is an automatic cast from CPP11_shared_ptr to bool). - virtual CPP11_shared_ptr - catalogEntry(unsigned long long id) = 0; - - // Dump everything to storage (if the archive is open for writing - // and if this makes sense for the archive) - virtual void flush() = 0; - - // Copy an item from this archive to a destination archive. - // This archive and destination archive must be distinct. - // Note that, while it is always possible to copy an item - // with correct id, a standalone operation like this is - // not necessarily going to make sense because the item - // could be just a part of some distributed object. - // - // If "newName" and/or "newCategory" arguments are left at their - // default value of 0, the existing name and/or category are used. - // - // This method returns the id of the copy in the destination - // archive. - unsigned long long copyItem(unsigned long long id, - AbsArchive* destination, - const char* newName = 0, - const char* newCategory = 0); - - // The id and the length of the last item written - // (the results make sense only for the archives - // that have been open for writing) - inline unsigned long long lastItemId() const - {return lastItemId_;} - inline unsigned long long lastItemLength() const - {return lastItemLength_;} - - inline bool operator==(const AbsArchive& r) const - {return (typeid(*this) == typeid(r)) && this->isEqual(r);} - inline bool operator!=(const AbsArchive& r) const - {return !(*this == r);} - - protected: - void addItemToReference(AbsReference& r, unsigned long long id) const; - - // Archives which want to implement reasonable comparisons - // should override the function below - virtual bool isEqual(const AbsArchive&) const {return false;} - - private: - friend class AbsReference; - friend gs::AbsArchive& ::operator<<(gs::AbsArchive& ar, - const gs::AbsRecord& record); - - // Search for items which correspond to the given reference. - // The "reference" works both as the input and as the output in - // this query. The concrete implementations should utilize the - // "addItemToReference" method in order to produce results. - virtual void search(AbsReference& reference) = 0; - - // Position the input stream for reading the item with given id. - // The reading must follow immediately, any other operaction on - // the archive can invalidate the result. - // - // The "sz" argument could be NULL in which case it should be - // ignored. If it is not NULL, the *sz value on completion - // should be set as follows: - // - // *sz = -1 -- if the uncompressed object size in the stream - // is the same as in the catalog - // *sz >= 0 -- *sz is the object size after decompression - // (usually not the same as in the catalog) - // - virtual std::istream& inputStream(unsigned long long id, - long long* sz) = 0; - - // Get the stream for writing the next object - virtual std::ostream& outputStream() = 0; - - // The following function should return 0 on failure and - // the item id in the archive on success. The id must be positive. - virtual unsigned long long addToCatalog( - const AbsRecord& record, unsigned compressCode, - unsigned long long itemLength) = 0; - - // The archives which want to support compression should - // override the following two methods - virtual std::ostream& compressedStream(std::ostream& uncompressed) - {return uncompressed;} - - // The following function returns some kind of a code which - // tells us how the item was compressed. Default value of 0 - // means no compression. - virtual unsigned flushCompressedRecord(std::ostream& /* compressed */) - {return 0U;} - - std::string name_; - unsigned long long lastItemId_; - unsigned long long lastItemLength_; - }; -} + // If "newName" and/or "newCategory" arguments are left at their + // default value of 0, the existing name and/or category are used. + // + // This method returns the id of the copy in the destination + // archive. + unsigned long long copyItem(unsigned long long id, + AbsArchive *destination, + const char *newName = nullptr, + const char *newCategory = nullptr); + + // The id and the length of the last item written + // (the results make sense only for the archives + // that have been open for writing) + inline unsigned long long lastItemId() const { return lastItemId_; } + inline unsigned long long lastItemLength() const { return lastItemLength_; } + + inline bool operator==(const AbsArchive &r) const { return (typeid(*this) == typeid(r)) && this->isEqual(r); } + inline bool operator!=(const AbsArchive &r) const { return !(*this == r); } + + protected: + void addItemToReference(AbsReference &r, unsigned long long id) const; + + // Archives which want to implement reasonable comparisons + // should override the function below + virtual bool isEqual(const AbsArchive &) const { return false; } + + private: + friend class AbsReference; + friend gs::AbsArchive & ::operator<<(gs::AbsArchive &ar, const gs::AbsRecord &record); + + // Search for items which correspond to the given reference. + // The "reference" works both as the input and as the output in + // this query. The concrete implementations should utilize the + // "addItemToReference" method in order to produce results. + virtual void search(AbsReference &reference) = 0; + + // Position the input stream for reading the item with given id. + // The reading must follow immediately, any other operaction on + // the archive can invalidate the result. + // + // The "sz" argument could be NULL in which case it should be + // ignored. If it is not NULL, the *sz value on completion + // should be set as follows: + // + // *sz = -1 -- if the uncompressed object size in the stream + // is the same as in the catalog + // *sz >= 0 -- *sz is the object size after decompression + // (usually not the same as in the catalog) + // + virtual std::istream &inputStream(unsigned long long id, long long *sz) = 0; + + // Get the stream for writing the next object + virtual std::ostream &outputStream() = 0; + + // The following function should return 0 on failure and + // the item id in the archive on success. The id must be positive. + virtual unsigned long long addToCatalog(const AbsRecord &record, + unsigned compressCode, + unsigned long long itemLength) = 0; + + // The archives which want to support compression should + // override the following two methods + virtual std::ostream &compressedStream(std::ostream &uncompressed) { return uncompressed; } + + // The following function returns some kind of a code which + // tells us how the item was compressed. Default value of 0 + // means no compression. + virtual unsigned flushCompressedRecord(std::ostream & /* compressed */) { return 0U; } -#endif // GENERS_ABSARCHIVE_HH_ + std::string name_; + unsigned long long lastItemId_; + unsigned long long lastItemLength_; + }; +} // namespace gs +#endif // GENERS_ABSARCHIVE_HH_ diff --git a/Alignment/Geners/interface/AbsCatalog.hh b/Alignment/Geners/interface/AbsCatalog.hh index 6dc82973f8b41..22f343e13fedb 100644 --- a/Alignment/Geners/interface/AbsCatalog.hh +++ b/Alignment/Geners/interface/AbsCatalog.hh @@ -1,86 +1,82 @@ #ifndef GENERS_ABSCATALOG_HH_ #define GENERS_ABSCATALOG_HH_ -#include #include +#include #include "Alignment/Geners/interface/CPP11_shared_ptr.hh" -#include "Alignment/Geners/interface/ItemDescriptor.hh" #include "Alignment/Geners/interface/CatalogEntry.hh" +#include "Alignment/Geners/interface/ItemDescriptor.hh" #include "Alignment/Geners/interface/SearchSpecifier.hh" namespace gs { - // - // This abstract class defines interfaces for adding entries to - // a catalog but not for removing them. Of course, derived classes - // can also implement catalog entry removal if necessary. - // - struct AbsCatalog - { - virtual ~AbsCatalog() {} - - // The number of entries in the catalog - virtual unsigned long long size() const = 0; - - // Smallest and largest ids of any item in the catalog - virtual unsigned long long smallestId() const = 0; - virtual unsigned long long largestId() const = 0; - virtual bool isContiguous() const = 0; - - // Check if an item with the given id is actually present in - // the catalog. Catalogs which support non-contiguous item ids - // (for example, if items can be removed) MUST override this. - virtual bool itemExists(const unsigned long long id) const - { - if (id == 0ULL) return false; - assert(isContiguous()); - return id >= smallestId() && id <= largestId(); - } - - // The following function should return the id of the new entry - virtual unsigned long long makeEntry(const ItemDescriptor& descriptor, - unsigned compressionCode, - unsigned long long itemLength, - const ItemLocation& loc, - unsigned long long offset=0ULL)=0; - - // It must be possible to retrieve the entry made by the last - // "makeEntry" call. If no "makeEntry" calls were made in this - // program (e.g., the catalog was only read and not written), - // null pointer should be returned. The entry should be owned - // by the catalog itself. - virtual const CatalogEntry* lastEntryMade() const = 0; - - // The following function returns a shared pointer to the entry. - // The pointer will contain NULL in case the item is not found. - virtual CPP11_shared_ptr retrieveEntry( - unsigned long long id) const = 0; - - // The following function fetches just the stream position - // associated with the entry. "true" is returned on success. - // Useful for catalogs which serve a single stream. - virtual bool retrieveStreampos( - unsigned long long id, unsigned* compressionCode, - unsigned long long* length, std::streampos* pos) const = 0; - - // Search for matching entries based on item name and category - virtual void search(const SearchSpecifier& namePattern, - const SearchSpecifier& categoryPattern, - std::vector* idsFound) const=0; - - inline bool operator==(const AbsCatalog& r) const - {return (typeid(*this) == typeid(r)) && this->isEqual(r);} - inline bool operator!=(const AbsCatalog& r) const - {return !(*this == r);} - - // Prototypes needed for I/O - virtual ClassId classId() const = 0; - virtual bool write(std::ostream&) const = 0; - - protected: - virtual bool isEqual(const AbsCatalog&) const = 0; - }; -} - -#endif // GENERS_ABSCATALOG_HH_ - + // + // This abstract class defines interfaces for adding entries to + // a catalog but not for removing them. Of course, derived classes + // can also implement catalog entry removal if necessary. + // + struct AbsCatalog { + virtual ~AbsCatalog() {} + + // The number of entries in the catalog + virtual unsigned long long size() const = 0; + + // Smallest and largest ids of any item in the catalog + virtual unsigned long long smallestId() const = 0; + virtual unsigned long long largestId() const = 0; + virtual bool isContiguous() const = 0; + + // Check if an item with the given id is actually present in + // the catalog. Catalogs which support non-contiguous item ids + // (for example, if items can be removed) MUST override this. + virtual bool itemExists(const unsigned long long id) const { + if (id == 0ULL) + return false; + assert(isContiguous()); + return id >= smallestId() && id <= largestId(); + } + + // The following function should return the id of the new entry + virtual unsigned long long makeEntry(const ItemDescriptor &descriptor, + unsigned compressionCode, + unsigned long long itemLength, + const ItemLocation &loc, + unsigned long long offset = 0ULL) = 0; + + // It must be possible to retrieve the entry made by the last + // "makeEntry" call. If no "makeEntry" calls were made in this + // program (e.g., the catalog was only read and not written), + // null pointer should be returned. The entry should be owned + // by the catalog itself. + virtual const CatalogEntry *lastEntryMade() const = 0; + + // The following function returns a shared pointer to the entry. + // The pointer will contain NULL in case the item is not found. + virtual CPP11_shared_ptr retrieveEntry(unsigned long long id) const = 0; + + // The following function fetches just the stream position + // associated with the entry. "true" is returned on success. + // Useful for catalogs which serve a single stream. + virtual bool retrieveStreampos(unsigned long long id, + unsigned *compressionCode, + unsigned long long *length, + std::streampos *pos) const = 0; + + // Search for matching entries based on item name and category + virtual void search(const SearchSpecifier &namePattern, + const SearchSpecifier &categoryPattern, + std::vector *idsFound) const = 0; + + inline bool operator==(const AbsCatalog &r) const { return (typeid(*this) == typeid(r)) && this->isEqual(r); } + inline bool operator!=(const AbsCatalog &r) const { return !(*this == r); } + + // Prototypes needed for I/O + virtual ClassId classId() const = 0; + virtual bool write(std::ostream &) const = 0; + + protected: + virtual bool isEqual(const AbsCatalog &) const = 0; + }; +} // namespace gs + +#endif // GENERS_ABSCATALOG_HH_ diff --git a/Alignment/Geners/interface/AbsReader.hh b/Alignment/Geners/interface/AbsReader.hh index 9607d0205b410..d0b8ef0e4763b 100644 --- a/Alignment/Geners/interface/AbsReader.hh +++ b/Alignment/Geners/interface/AbsReader.hh @@ -25,105 +25,91 @@ #ifndef GENERS_ABSREADER_HH_ #define GENERS_ABSREADER_HH_ +#include "Alignment/Geners/interface/IOException.hh" #include -#include #include -#include "Alignment/Geners/interface/IOException.hh" +#include #include "Alignment/Geners/interface/ClassId.hh" namespace gs { - template - struct AbsReader - { - virtual ~AbsReader() {} - - virtual Base* read(const ClassId& id, std::istream& in) const = 0; - }; - - template - struct ConcreteReader : public AbsReader - { - virtual ~ConcreteReader() {} - - inline Derived* read(const ClassId& id, std::istream& in) const - { - // Assume that Derived::read(id, in) returns a new object - // of type "Derived" allocated on the heap - return Derived::read(id, in); - } - }; - - template - class DefaultReader : public std::map*> - { - public: - typedef Base value_type; - - inline DefaultReader() : std::map*>() {} - - virtual ~DefaultReader() - { - for (typename std::map*>:: - iterator it = this->begin(); it != this->end(); ++it) - delete it->second; - } - - inline Base* read(const ClassId& id, std::istream& in) const - { - typename std::map*>:: - const_iterator it = this->find(id.name()); - if (it == this->end()) - { - std::ostringstream os; - os << "In gs::DefaultReader::read: class \"" - << id.name() << "\" is not mapped to a concrete reader"; - throw gs::IOInvalidArgument(os.str()); - } - return it->second->read(id, in); - } - - private: - DefaultReader(const DefaultReader&); - DefaultReader& operator=(const DefaultReader&); - }; - - // A trivial implementation of the Meyers singleton for use with reader - // factories. Naturally, this assumes that all factories are independent - // from each other (otherwise we are getting into trouble with undefined - // singleton destruction order). Also, this particular code is not - // thread-safe (but should become thread-safe in C++11 if I understand - // static local initialization guarantees correctly). - // - // Assume that "Reader" is derived from "DefaultReader" and that it - // publishes its base class as "Base". - // - template - class StaticReader - { - public: - typedef typename Reader::Base::value_type InheritanceBase; - - static const Reader& instance() - { - static Reader obj; - return obj; - } - - template - static void registerClass() - { - Reader& rd = const_cast(instance()); - const ClassId& id(ClassId::makeId()); - delete rd[id.name()]; - rd[id.name()] = new ConcreteReader(); - } - - private: - // Disable the constructor - StaticReader(); - }; -} - -#endif // GENERS_ABSREADER_HH_ - + template + struct AbsReader { + virtual ~AbsReader() {} + + virtual Base *read(const ClassId &id, std::istream &in) const = 0; + }; + + template + struct ConcreteReader : public AbsReader { + virtual ~ConcreteReader() {} + + inline Derived *read(const ClassId &id, std::istream &in) const { + // Assume that Derived::read(id, in) returns a new object + // of type "Derived" allocated on the heap + return Derived::read(id, in); + } + }; + + template + class DefaultReader : public std::map *> { + public: + typedef Base value_type; + + inline DefaultReader() : std::map *>() {} + + virtual ~DefaultReader() { + for (typename std::map *>::iterator it = this->begin(); it != this->end(); ++it) + delete it->second; + } + + inline Base *read(const ClassId &id, std::istream &in) const { + typename std::map *>::const_iterator it = this->find(id.name()); + if (it == this->end()) { + std::ostringstream os; + os << "In gs::DefaultReader::read: class \"" << id.name() << "\" is not mapped to a concrete reader"; + throw gs::IOInvalidArgument(os.str()); + } + return it->second->read(id, in); + } + + private: + DefaultReader(const DefaultReader &); + DefaultReader &operator=(const DefaultReader &); + }; + + // A trivial implementation of the Meyers singleton for use with reader + // factories. Naturally, this assumes that all factories are independent + // from each other (otherwise we are getting into trouble with undefined + // singleton destruction order). Also, this particular code is not + // thread-safe (but should become thread-safe in C++11 if I understand + // static local initialization guarantees correctly). + // + // Assume that "Reader" is derived from "DefaultReader" and that it + // publishes its base class as "Base". + // + template + class StaticReader { + public: + typedef typename Reader::Base::value_type InheritanceBase; + + static const Reader &instance() { + static Reader obj; + return obj; + } + + template + static void registerClass() { + Reader &rd = const_cast(instance()); + const ClassId &id(ClassId::makeId()); + delete rd[id.name()]; + rd[id.name()] = new ConcreteReader(); + } + + private: + // Disable the constructor + StaticReader(); + }; +} // namespace gs + +#endif // GENERS_ABSREADER_HH_ diff --git a/Alignment/Geners/interface/AbsRecord.hh b/Alignment/Geners/interface/AbsRecord.hh index 2319910d1c708..05ecdfeff4f87 100644 --- a/Alignment/Geners/interface/AbsRecord.hh +++ b/Alignment/Geners/interface/AbsRecord.hh @@ -4,47 +4,42 @@ #include "Alignment/Geners/interface/ItemDescriptor.hh" namespace gs { - class AbsArchive; - class AbsRecord; -} + class AbsArchive; + class AbsRecord; +} // namespace gs -gs::AbsArchive& operator<<(gs::AbsArchive& ar, const gs::AbsRecord& record); +gs::AbsArchive &operator<<(gs::AbsArchive &ar, const gs::AbsRecord &record); namespace gs { - class AbsRecord : public ItemDescriptor - { - public: - inline virtual ~AbsRecord() {} - - // Item id will be set to non-0 value upon writing the item - // into the archive. When the id is not 0, the record can no - // longer be written out (if you really want to write out the - // same item again, make another record). - inline unsigned long long id() const {return itemId_;} - - // Item length will be set to non-0 value upon writing the item - // into the archive. - inline unsigned long long itemLength() const {return itemLength_;} - - protected: - inline AbsRecord() : ItemDescriptor(), itemId_(0), itemLength_(0) {} - inline AbsRecord(const ClassId& classId, const char* ioPrototype, - const char* name, const char* category) - : ItemDescriptor(classId, ioPrototype, name, category), - itemId_(0), itemLength_(0) {} - - private: - friend gs::AbsArchive& ::operator<<(gs::AbsArchive& ar, - const gs::AbsRecord& record); - - // The following functions must be overriden by derived classes. - // "writeData" should return "true" upon success. - virtual bool writeData(std::ostream& os) const = 0; - - mutable unsigned long long itemId_; - mutable unsigned long long itemLength_; - }; -} - -#endif // GENERS_ABSRECORD_HH_ - + class AbsRecord : public ItemDescriptor { + public: + inline ~AbsRecord() override {} + + // Item id will be set to non-0 value upon writing the item + // into the archive. When the id is not 0, the record can no + // longer be written out (if you really want to write out the + // same item again, make another record). + inline unsigned long long id() const { return itemId_; } + + // Item length will be set to non-0 value upon writing the item + // into the archive. + inline unsigned long long itemLength() const { return itemLength_; } + + protected: + inline AbsRecord() : ItemDescriptor(), itemId_(0), itemLength_(0) {} + inline AbsRecord(const ClassId &classId, const char *ioPrototype, const char *name, const char *category) + : ItemDescriptor(classId, ioPrototype, name, category), itemId_(0), itemLength_(0) {} + + private: + friend gs::AbsArchive & ::operator<<(gs::AbsArchive &ar, const gs::AbsRecord &record); + + // The following functions must be overriden by derived classes. + // "writeData" should return "true" upon success. + virtual bool writeData(std::ostream &os) const = 0; + + mutable unsigned long long itemId_; + mutable unsigned long long itemLength_; + }; +} // namespace gs + +#endif // GENERS_ABSRECORD_HH_ diff --git a/Alignment/Geners/interface/AbsReference.hh b/Alignment/Geners/interface/AbsReference.hh index 8f8fbc55f6e54..3fe1ae59696cf 100644 --- a/Alignment/Geners/interface/AbsReference.hh +++ b/Alignment/Geners/interface/AbsReference.hh @@ -1,103 +1,97 @@ #ifndef GENERS_ABSREFERENCE_HH_ #define GENERS_ABSREFERENCE_HH_ -#include #include +#include #include "Alignment/Geners/interface/CPP11_shared_ptr.hh" #include "Alignment/Geners/interface/ClassId.hh" #include "Alignment/Geners/interface/SearchSpecifier.hh" namespace gs { - class AbsArchive; - class CatalogEntry; - - class AbsReference - { - public: - inline virtual ~AbsReference() {} - - inline AbsArchive& archive() const {return archive_;} - inline const ClassId& type() const {return classId_;} - inline const std::string& ioPrototype() const {return ioProto_;} - inline const SearchSpecifier& namePattern() const - {return namePattern_;} - inline const SearchSpecifier& categoryPattern() const - {return categoryPattern_;} - - // Determine if the item in the catalog is compatible for I/O - // purposes with the one referenced here - virtual bool isIOCompatible(const CatalogEntry& r) const; - - // Check I/O prototype only allowing for class id mismatch - bool isSameIOPrototype(const CatalogEntry& r) const; - - // Are there any items referenced? - bool empty() const; - - // Exactly one item referenced? - bool unique() const; - - // How many items are referenced? - unsigned long size() const; - - // The following function throws gs::IOOutOfRange exception - // if the index is out of range - unsigned long long id(unsigned long index) const; - - // Catalog entry retrieval by index in the list of referenced items. - // Throws gs::IOOutOfRange exception if the index is out of range. - CPP11_shared_ptr - indexedCatalogEntry(unsigned long index) const; - - protected: - // Use the following constructor to retrieve an item with - // a known id - AbsReference(AbsArchive& ar, const ClassId& classId, - const char* ioProto, - unsigned long long itemId); - - // Use the following constructor to search for items which - // match name and category patterns - AbsReference(AbsArchive& ar, const ClassId& classId, - const char* ioProto, - const SearchSpecifier& namePattern, - const SearchSpecifier& categoryPattern); - - std::istream& positionInputStream(unsigned long long id) const; - - private: - friend class AbsArchive; - - AbsReference(); - - void initialize() const; - void addItemId(unsigned long long id); - - AbsArchive& archive_; - ClassId classId_; - std::string ioProto_; - - // The following items will be filled or not, - // depending on which constructor was called - unsigned long long searchId_; - SearchSpecifier namePattern_; - SearchSpecifier categoryPattern_; - - // Id for a unique verified item - unsigned long long itemId_; - - // The item list in case ids are not unique - std::vector idList_; - - // We can't talk to the archive from the constructor - // because we need correct "isIOCompatible" which - // can be overriden by derived classes. Therefore, - // we will delay archive searching until the first - // function call. - bool initialized_; - }; -} - -#endif // GENERS_ABSREFERENCE_HH_ + class AbsArchive; + class CatalogEntry; + + class AbsReference { + public: + inline virtual ~AbsReference() {} + + inline AbsArchive &archive() const { return archive_; } + inline const ClassId &type() const { return classId_; } + inline const std::string &ioPrototype() const { return ioProto_; } + inline const SearchSpecifier &namePattern() const { return namePattern_; } + inline const SearchSpecifier &categoryPattern() const { return categoryPattern_; } + + // Determine if the item in the catalog is compatible for I/O + // purposes with the one referenced here + virtual bool isIOCompatible(const CatalogEntry &r) const; + + // Check I/O prototype only allowing for class id mismatch + bool isSameIOPrototype(const CatalogEntry &r) const; + + // Are there any items referenced? + bool empty() const; + + // Exactly one item referenced? + bool unique() const; + + // How many items are referenced? + unsigned long size() const; + + // The following function throws gs::IOOutOfRange exception + // if the index is out of range + unsigned long long id(unsigned long index) const; + + // Catalog entry retrieval by index in the list of referenced items. + // Throws gs::IOOutOfRange exception if the index is out of range. + CPP11_shared_ptr indexedCatalogEntry(unsigned long index) const; + + protected: + // Use the following constructor to retrieve an item with + // a known id + AbsReference(AbsArchive &ar, const ClassId &classId, const char *ioProto, unsigned long long itemId); + + // Use the following constructor to search for items which + // match name and category patterns + AbsReference(AbsArchive &ar, + const ClassId &classId, + const char *ioProto, + const SearchSpecifier &namePattern, + const SearchSpecifier &categoryPattern); + + std::istream &positionInputStream(unsigned long long id) const; + + private: + friend class AbsArchive; + + AbsReference() = delete; + + void initialize() const; + void addItemId(unsigned long long id); + + AbsArchive &archive_; + ClassId classId_; + std::string ioProto_; + + // The following items will be filled or not, + // depending on which constructor was called + unsigned long long searchId_; + SearchSpecifier namePattern_; + SearchSpecifier categoryPattern_; + + // Id for a unique verified item + unsigned long long itemId_; + + // The item list in case ids are not unique + std::vector idList_; + + // We can't talk to the archive from the constructor + // because we need correct "isIOCompatible" which + // can be overriden by derived classes. Therefore, + // we will delay archive searching until the first + // function call. + bool initialized_; + }; +} // namespace gs +#endif // GENERS_ABSREFERENCE_HH_ diff --git a/Alignment/Geners/interface/ArrayAdaptor.hh b/Alignment/Geners/interface/ArrayAdaptor.hh index 2c8620205ab24..7f5c626a82095 100644 --- a/Alignment/Geners/interface/ArrayAdaptor.hh +++ b/Alignment/Geners/interface/ArrayAdaptor.hh @@ -1,197 +1,170 @@ #ifndef GENERS_ARRAYADAPTOR_HH_ #define GENERS_ARRAYADAPTOR_HH_ -#include -#include #include "Alignment/Geners/interface/IOException.hh" +#include +#include -#include "Alignment/Geners/interface/ProcessItem.hh" -#include "Alignment/Geners/interface/InsertContainerItem.hh" #include "Alignment/Geners/interface/IOIsContiguous.hh" +#include "Alignment/Geners/interface/InsertContainerItem.hh" +#include "Alignment/Geners/interface/ProcessItem.hh" #include "Alignment/Geners/interface/binaryIO.hh" namespace gs { - template - struct GenericWriter; - - template - struct GenericReader; - - template - class ArrayAdaptor - { - public: - typedef T value_type; - typedef const T* const_iterator; - - inline ArrayAdaptor(const T* indata, const std::size_t sz, - const bool writeItemClassId = true) - : data_(indata), size_(sz), writetemCl_(writeItemClassId) - {if (sz) assert(data_);} - - inline std::size_t size() const {return size_;} - inline const_iterator begin() const {return data_;} - inline const_iterator end() const {return data_ + size_;} - inline bool writeItemClassId() const {return writetemCl_;} - inline const T& operator[](const std::size_t index) const - {return data_[index];} - inline T& operator[](const std::size_t index) - {return (const_cast(data_))[index];} - inline T& at(const std::size_t index) - { - if (index >= size_) throw gs::IOOutOfRange( - "gs::ArrayAdaptor::at: index out of range"); - return (const_cast(data_))[index]; - } - - private: - ArrayAdaptor(); - - const T* data_; - std::size_t size_; - bool writetemCl_; - }; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct InsertContainerItem > - { - typedef ArrayAdaptor A; - static inline void insert(A& obj, const typename A::value_type& item, - const std::size_t itemNumber) - {obj.at(itemNumber) = item;} - }; - - template - struct InsertContainerItem > - { - typedef ArrayAdaptor A; - static inline void insert(A& obj, const typename A::value_type& item, - const std::size_t itemNumber) - {obj.at(itemNumber) = item;} - }; - - // Ignore array size I/O. The size is provided in the constructor. - // Of course, it still has to be written somewhere, but that code - // is external w.r.t. the array adaptor. - template - struct GenericWriter, InContainerSize> - { - inline static bool process(std::size_t, Stream& os, State*, - const bool processClassId) - {return true;} - }; - - template - struct GenericReader, InContainerSize> - { - inline static bool process(std::size_t, Stream& os, State*, - const bool processClassId) - {return true;} - }; - - template - struct GenericWriter, InPODArray> - { - inline static bool process(const ArrayAdaptor& a, Stream& os, - State*, bool) - { - const std::size_t len = a.size(); - if (len) - write_pod_array(os, &a[0], len); - return !os.fail(); - } - }; - - template - struct GenericReader, InPODArray> - { - inline static bool process(ArrayAdaptor& a, Stream& s, State*, bool) - { - const std::size_t len = a.size(); - if (len) - read_pod_array(s, &a[0], len); - return !s.fail(); - } - }; - - template - struct GenericWriter, InContainerHeader> - { - typedef ArrayAdaptor Container; - - inline static bool process(const Container& c, Stream& os, State*, - const bool processClassId) - { - bool status = processClassId ? - ClassId::makeId().write(os) : true; - if (status && !(IOTraits::IsPOD && - IOTraits::IsContiguous) && - c.writeItemClassId()) - status = ClassId::makeId().write(os); - return status; - } - }; - - template - struct GenericReader, InContainerHeader> - { - typedef ArrayAdaptor Container; - - inline static bool process(Container& a, Stream& is, State* state, - const bool processClassId) - { - bool status = true; - if (processClassId) - { - ClassId id(is, 1); - const ClassId& current = ClassId::makeId(); - status = (id.name() == current.name()); - } - if (status) - { - if (!(IOTraits::IsPOD && IOTraits::IsContiguous)) - if (a.writeItemClassId()) - { - ClassId id(is, 1); - state->push_back(id); - } - } - return status; - } - }; - - template - struct GenericReader, InContainerFooter> - { - typedef ArrayAdaptor Container; - - inline static bool process(Container& a, Stream&, State* state, bool) - { - if (!(IOTraits::IsPOD && IOTraits::IsContiguous)) - if (a.writeItemClassId()) - state->pop_back(); - return true; - } - }; -} + template + struct GenericWriter; + + template + struct GenericReader; + + template + class ArrayAdaptor { + public: + typedef T value_type; + typedef const T *const_iterator; + + inline ArrayAdaptor(const T *indata, const std::size_t sz, const bool writeItemClassId = true) + : data_(indata), size_(sz), writetemCl_(writeItemClassId) { + if (sz) + assert(data_); + } + + inline std::size_t size() const { return size_; } + inline const_iterator begin() const { return data_; } + inline const_iterator end() const { return data_ + size_; } + inline bool writeItemClassId() const { return writetemCl_; } + inline const T &operator[](const std::size_t index) const { return data_[index]; } + inline T &operator[](const std::size_t index) { return (const_cast(data_))[index]; } + inline T &at(const std::size_t index) { + if (index >= size_) + throw gs::IOOutOfRange("gs::ArrayAdaptor::at: index out of range"); + return (const_cast(data_))[index]; + } + + private: + ArrayAdaptor() = delete; + + const T *data_; + std::size_t size_; + bool writetemCl_; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct InsertContainerItem> { + typedef ArrayAdaptor A; + static inline void insert(A &obj, const typename A::value_type &item, const std::size_t itemNumber) { + obj.at(itemNumber) = item; + } + }; + + template + struct InsertContainerItem> { + typedef ArrayAdaptor A; + static inline void insert(A &obj, const typename A::value_type &item, const std::size_t itemNumber) { + obj.at(itemNumber) = item; + } + }; + + // Ignore array size I/O. The size is provided in the constructor. + // Of course, it still has to be written somewhere, but that code + // is external w.r.t. the array adaptor. + template + struct GenericWriter, InContainerSize> { + inline static bool process(std::size_t, Stream &os, State *, const bool processClassId) { return true; } + }; + + template + struct GenericReader, InContainerSize> { + inline static bool process(std::size_t, Stream &os, State *, const bool processClassId) { return true; } + }; + + template + struct GenericWriter, InPODArray> { + inline static bool process(const ArrayAdaptor &a, Stream &os, State *, bool) { + const std::size_t len = a.size(); + if (len) + write_pod_array(os, &a[0], len); + return !os.fail(); + } + }; + + template + struct GenericReader, InPODArray> { + inline static bool process(ArrayAdaptor &a, Stream &s, State *, bool) { + const std::size_t len = a.size(); + if (len) + read_pod_array(s, &a[0], len); + return !s.fail(); + } + }; + + template + struct GenericWriter, InContainerHeader> { + typedef ArrayAdaptor Container; + + inline static bool process(const Container &c, Stream &os, State *, const bool processClassId) { + bool status = processClassId ? ClassId::makeId().write(os) : true; + if (status && !(IOTraits::IsPOD && IOTraits::IsContiguous) && c.writeItemClassId()) + status = ClassId::makeId().write(os); + return status; + } + }; + + template + struct GenericReader, InContainerHeader> { + typedef ArrayAdaptor Container; + + inline static bool process(Container &a, Stream &is, State *state, const bool processClassId) { + bool status = true; + if (processClassId) { + ClassId id(is, 1); + const ClassId ¤t = ClassId::makeId(); + status = (id.name() == current.name()); + } + if (status) { + if (!(IOTraits::IsPOD && IOTraits::IsContiguous)) + if (a.writeItemClassId()) { + ClassId id(is, 1); + state->push_back(id); + } + } + return status; + } + }; + + template + struct GenericReader, InContainerFooter> { + typedef ArrayAdaptor Container; + + inline static bool process(Container &a, Stream &, State *state, bool) { + if (!(IOTraits::IsPOD && IOTraits::IsContiguous)) + if (a.writeItemClassId()) + state->pop_back(); + return true; + } + }; +} // namespace gs gs_specialize_template_id_T(gs::ArrayAdaptor, 0, 1) -#endif // GENERS_ARRAYADAPTOR_HH_ - +#endif // GENERS_ARRAYADAPTOR_HH_ diff --git a/Alignment/Geners/interface/BZ2Handle.hh b/Alignment/Geners/interface/BZ2Handle.hh index 82adfaf96bcb2..9b5333bf54d4d 100644 --- a/Alignment/Geners/interface/BZ2Handle.hh +++ b/Alignment/Geners/interface/BZ2Handle.hh @@ -12,34 +12,31 @@ // is performed, and having it on the stack saves a bit of time. namespace gs { - class BZ2InflateHandle - { - public: - explicit BZ2InflateHandle(bz_stream& strm); - ~BZ2InflateHandle(); - - private: - BZ2InflateHandle(); - BZ2InflateHandle(const BZ2InflateHandle&); - BZ2InflateHandle& operator=(const BZ2InflateHandle&); - - bz_stream* strm_; - }; - - class BZ2DeflateHandle - { - public: - explicit BZ2DeflateHandle(bz_stream& strm); - ~BZ2DeflateHandle(); - - private: - BZ2DeflateHandle(); - BZ2DeflateHandle(const BZ2DeflateHandle&); - BZ2DeflateHandle& operator=(const BZ2DeflateHandle&); - - bz_stream* strm_; - }; -} - -#endif // GENERS_BZ2HANDLE_HH_ - + class BZ2InflateHandle { + public: + explicit BZ2InflateHandle(bz_stream &strm); + ~BZ2InflateHandle(); + + private: + BZ2InflateHandle() = delete; + BZ2InflateHandle(const BZ2InflateHandle &) = delete; + BZ2InflateHandle &operator=(const BZ2InflateHandle &) = delete; + + bz_stream *strm_; + }; + + class BZ2DeflateHandle { + public: + explicit BZ2DeflateHandle(bz_stream &strm); + ~BZ2DeflateHandle(); + + private: + BZ2DeflateHandle() = delete; + BZ2DeflateHandle(const BZ2DeflateHandle &) = delete; + BZ2DeflateHandle &operator=(const BZ2DeflateHandle &) = delete; + + bz_stream *strm_; + }; +} // namespace gs + +#endif // GENERS_BZ2HANDLE_HH_ diff --git a/Alignment/Geners/interface/BinaryArchiveBase.hh b/Alignment/Geners/interface/BinaryArchiveBase.hh index 88ad44576ad15..b4169af649980 100644 --- a/Alignment/Geners/interface/BinaryArchiveBase.hh +++ b/Alignment/Geners/interface/BinaryArchiveBase.hh @@ -4,220 +4,210 @@ #include #include -#include "Alignment/Geners/interface/AbsCatalog.hh" #include "Alignment/Geners/interface/AbsArchive.hh" +#include "Alignment/Geners/interface/AbsCatalog.hh" #include "Alignment/Geners/interface/CStringStream.hh" namespace gs { - class BinaryArchiveBase : public AbsArchive - { - public: - // The "mode" argument is a string which can have one or more - // sections, separated by ":". The first section has the same - // meaning as in the "fopen" call (see "man 3 fopen"). Additional - // sections can specify other aspects of the archive behavior - // using the format "option=value" if the default settings are - // not suitable. The available options are: - // - // "z" -- compression type. Possible option values are - // "n" -- no compression (default) - // "z" -- compress with zlib - // "b" -- compress with bzlib2 - // - // "cl" -- compression level (an integer between -1 and 9, - // -1 is default. Meanigful for zlib compression - // only. See zlib documentation for details. - // - // "cb" -- compression buffer size in bytes (unsigned integer). - // Default is 1 MB. - // - // "cm" -- minimum object size in bytes to compress (unsigned - // integer). Objects whose serialized size is below - // this limit are not compressed. Default is 1 KB. - // - // "cat" -- if the value is set to "i" (which means "internal" - // or "injected"), the catalog data will be injected - // into the data stream in addition to having it in - // a separate catalog file. This allows for catalog - // recovery from the data stream in cases of program - // failure but also increases the data file size. - // The default value of this option is "s" which means - // that the catalog data will be stored separately. - // This option is meaningful for new archives only, - // for existing archives the value of this option is - // taken from the archive header record. - // - // Example: "w+:z=z:cl=9:cm=2048:cat=s". This will compress - // objects with 2 KB or larger size using level 9 zlib compression - // (the best compression ratio possible in zlib which is also - // the slowest). The archive will be open for reading and writing. - // If an archive with the same name already exists, it will be - // overwritten. The catalog will be stored in a separate file - // created when the archive is closed, catalog recovery from the - // data file(s) in case of a catastrophic program failure will not - // be possible. - // - BinaryArchiveBase(const char* name, const char* mode); - - virtual ~BinaryArchiveBase(); - - inline bool isOpen() const {return modeIsValid_ && catalog_;} - - inline bool isReadable() const - {return modeIsValid_ && catalog_ && (mode_ & std::ios_base::in);} - - inline bool isWritable() const - {return modeIsValid_ && catalog_ && (mode_ & std::ios_base::out);} - - // Error message produced in case the archive could not be opened - inline std::string error() const - {return errorStream_ ? errorStream_->str() : std::string("");} - - // Check whether the constructor "mode" argument was valid. - // If it was not, derived classes should behave as if the - // archive could not be opened. - inline bool modeValid() const {return modeIsValid_;} - - inline unsigned long long size() const - {return catalog_ ? catalog_->size() : 0ULL;} - - inline unsigned long long smallestId() const - {return catalog_ ? catalog_->smallestId() : 0ULL;} - - inline unsigned long long largestId() const - {return catalog_ ? catalog_->largestId() : 0ULL;} - - inline bool idsAreContiguous() const - {return catalog_ ? catalog_->isContiguous() : false;} - - inline bool itemExists(const unsigned long long id) const - {return catalog_ ? catalog_->itemExists(id) : false;} - - void itemSearch(const SearchSpecifier& namePattern, - const SearchSpecifier& categoryPattern, - std::vector* idsFound) const; - - inline CPP11_shared_ptr - catalogEntry(const unsigned long long id) - {return catalog_ ? catalog_->retrieveEntry(id) : - CPP11_shared_ptr((const CatalogEntry*)0);} - - // Inspection methods for compression options - inline CStringStream::CompressionMode compressionMode() const - {return cStream_->compressionMode();} - - inline std::size_t compressionBufferSize() const - {return cStream_->bufferSize();} - - inline int compressionLevel() const - {return cStream_->compressionLevel();} - - inline unsigned minSizeToCompress() const - {return cStream_->minSizeToCompress();} - - // Inject metadata into the data stream when writing? If this - // method returns "true", we either had "cat=i" in the opening - // mode for a new archive or a corresponding flag was set in - // the header of an existing archive data file. - inline bool injectMetadata() const {return addCatalogToData_;} - - // The following method moves the "get pointer" of the stream - // to the end of file as a side effect - static bool isEmptyFile(std::fstream& s); - - // The following method converts the first section of the "mode" - // argument into std::ios_base::openmode - static std::ios_base::openmode parseMode(const char* mode); - - protected: - inline AbsCatalog* catalog() const {return catalog_;} - - // Non-null catalog must be set exactly once. This object will - // assume the catalog ownership. Null catalog can be set after - // non-null in case some essential operation on the catalog has - // failed (such as writing it to file) in order to indicate - // failure to open the archive. - void setCatalog(AbsCatalog* c); - - // Set compression mode (can be used when the catalog is read). - // The argment must be consistent with one of the modes defined - // in the CStringStream.hh header. - inline void setCompressionMode(const unsigned cMode) - {cStream_->setCompressionMode( - static_cast(cMode));} - - // Stream for error messages. To be used from constructors - // of derived classes in case of problems, to indicate the - // reason why the archive could not be opened. - inline std::ostringstream& errorStream() - { - if (!errorStream_) errorStream_ = new std::ostringstream(); - return *errorStream_; - } - - // The following method opens a binary archive. It makes sure - // that a proper header is written out in case an empty file - // is open or in case the file is truncated, and that the header - // is there when a non-empty file is open without truncation. - // If the argument fstream is open when this method is invoked, - // it is closed first. After invocation of this method, the - // "injectMetadata()" flag will be properly set up for the - // data file open last. If the method is not successful, it - // closes the stream and throws an exception inherited from - // "IOException". - // - void openDataFile(std::fstream& stream, const char* filename); - - // Stream mode used to open the archive data file(s) - inline std::ios_base::openmode openmode() const {return mode_;} - - // Info needed for catalog recovery. These methods will return - // null pointers if item metadata is not in the data stream. - const ClassId* catalogEntryClassId() const {return storedEntryId_;} - const ClassId* itemLocationClassId() const {return storedLocationId_;} - - private: - BinaryArchiveBase(); - BinaryArchiveBase(const BinaryArchiveBase&); - BinaryArchiveBase& operator=(const BinaryArchiveBase&); - - static bool parseArchiveOptions( - std::ostringstream& errmes, - const char* mode, CStringStream::CompressionMode* m, - int* compressionLevel, unsigned* minSizeToCompress, - unsigned* bufSize, bool* multiplexCatalog); - - void writeHeader(std::ostream& os); - - // The following method returns "true" if a correctly - // formatted header was found - bool readHeader(std::istream& is); - - virtual void search(AbsReference& reference); - - // The derived classes must override the following two methods - virtual std::ostream& plainOutputStream() = 0; - virtual std::istream& plainInputStream(unsigned long long id, - unsigned* compressionCode, - unsigned long long* length) = 0; - - std::istream& inputStream(unsigned long long id, long long* sz); - std::ostream& outputStream(); - std::ostream& compressedStream(std::ostream& uncompressed); - unsigned flushCompressedRecord(std::ostream& compressed); - void releaseClassIds(); - - const std::ios_base::openmode mode_; - std::ostringstream* errorStream_; - CStringStream* cStream_; - AbsCatalog* catalog_; - ClassId* storedEntryId_; - ClassId* storedLocationId_; - bool catalogIsSet_; - bool modeIsValid_; - bool addCatalogToData_; - }; -} - -#endif // GENERS_BINARYARCHIVEBASE_HH_ - + class BinaryArchiveBase : public AbsArchive { + public: + // The "mode" argument is a string which can have one or more + // sections, separated by ":". The first section has the same + // meaning as in the "fopen" call (see "man 3 fopen"). Additional + // sections can specify other aspects of the archive behavior + // using the format "option=value" if the default settings are + // not suitable. The available options are: + // + // "z" -- compression type. Possible option values are + // "n" -- no compression (default) + // "z" -- compress with zlib + // "b" -- compress with bzlib2 + // + // "cl" -- compression level (an integer between -1 and 9, + // -1 is default. Meanigful for zlib compression + // only. See zlib documentation for details. + // + // "cb" -- compression buffer size in bytes (unsigned integer). + // Default is 1 MB. + // + // "cm" -- minimum object size in bytes to compress (unsigned + // integer). Objects whose serialized size is below + // this limit are not compressed. Default is 1 KB. + // + // "cat" -- if the value is set to "i" (which means "internal" + // or "injected"), the catalog data will be injected + // into the data stream in addition to having it in + // a separate catalog file. This allows for catalog + // recovery from the data stream in cases of program + // failure but also increases the data file size. + // The default value of this option is "s" which means + // that the catalog data will be stored separately. + // This option is meaningful for new archives only, + // for existing archives the value of this option is + // taken from the archive header record. + // + // Example: "w+:z=z:cl=9:cm=2048:cat=s". This will compress + // objects with 2 KB or larger size using level 9 zlib compression + // (the best compression ratio possible in zlib which is also + // the slowest). The archive will be open for reading and writing. + // If an archive with the same name already exists, it will be + // overwritten. The catalog will be stored in a separate file + // created when the archive is closed, catalog recovery from the + // data file(s) in case of a catastrophic program failure will not + // be possible. + // + BinaryArchiveBase(const char *name, const char *mode); + + ~BinaryArchiveBase() override; + + inline bool isOpen() const override { return modeIsValid_ && catalog_; } + + inline bool isReadable() const override { return modeIsValid_ && catalog_ && (mode_ & std::ios_base::in); } + + inline bool isWritable() const override { return modeIsValid_ && catalog_ && (mode_ & std::ios_base::out); } + + // Error message produced in case the archive could not be opened + inline std::string error() const override { return errorStream_ ? errorStream_->str() : std::string(""); } + + // Check whether the constructor "mode" argument was valid. + // If it was not, derived classes should behave as if the + // archive could not be opened. + inline bool modeValid() const { return modeIsValid_; } + + inline unsigned long long size() const override { return catalog_ ? catalog_->size() : 0ULL; } + + inline unsigned long long smallestId() const override { return catalog_ ? catalog_->smallestId() : 0ULL; } + + inline unsigned long long largestId() const override { return catalog_ ? catalog_->largestId() : 0ULL; } + + inline bool idsAreContiguous() const override { return catalog_ ? catalog_->isContiguous() : false; } + + inline bool itemExists(const unsigned long long id) const override { + return catalog_ ? catalog_->itemExists(id) : false; + } + + void itemSearch(const SearchSpecifier &namePattern, + const SearchSpecifier &categoryPattern, + std::vector *idsFound) const override; + + inline CPP11_shared_ptr catalogEntry(const unsigned long long id) override { + return catalog_ ? catalog_->retrieveEntry(id) + : CPP11_shared_ptr((const CatalogEntry *)nullptr); + } + + // Inspection methods for compression options + inline CStringStream::CompressionMode compressionMode() const { return cStream_->compressionMode(); } + + inline std::size_t compressionBufferSize() const { return cStream_->bufferSize(); } + + inline int compressionLevel() const { return cStream_->compressionLevel(); } + + inline unsigned minSizeToCompress() const { return cStream_->minSizeToCompress(); } + + // Inject metadata into the data stream when writing? If this + // method returns "true", we either had "cat=i" in the opening + // mode for a new archive or a corresponding flag was set in + // the header of an existing archive data file. + inline bool injectMetadata() const { return addCatalogToData_; } + + // The following method moves the "get pointer" of the stream + // to the end of file as a side effect + static bool isEmptyFile(std::fstream &s); + + // The following method converts the first section of the "mode" + // argument into std::ios_base::openmode + static std::ios_base::openmode parseMode(const char *mode); + + protected: + inline AbsCatalog *catalog() const { return catalog_; } + + // Non-null catalog must be set exactly once. This object will + // assume the catalog ownership. Null catalog can be set after + // non-null in case some essential operation on the catalog has + // failed (such as writing it to file) in order to indicate + // failure to open the archive. + void setCatalog(AbsCatalog *c); + + // Set compression mode (can be used when the catalog is read). + // The argment must be consistent with one of the modes defined + // in the CStringStream.hh header. + inline void setCompressionMode(const unsigned cMode) { + cStream_->setCompressionMode(static_cast(cMode)); + } + + // Stream for error messages. To be used from constructors + // of derived classes in case of problems, to indicate the + // reason why the archive could not be opened. + inline std::ostringstream &errorStream() { + if (!errorStream_) + errorStream_ = new std::ostringstream(); + return *errorStream_; + } + + // The following method opens a binary archive. It makes sure + // that a proper header is written out in case an empty file + // is open or in case the file is truncated, and that the header + // is there when a non-empty file is open without truncation. + // If the argument fstream is open when this method is invoked, + // it is closed first. After invocation of this method, the + // "injectMetadata()" flag will be properly set up for the + // data file open last. If the method is not successful, it + // closes the stream and throws an exception inherited from + // "IOException". + // + void openDataFile(std::fstream &stream, const char *filename); + + // Stream mode used to open the archive data file(s) + inline std::ios_base::openmode openmode() const { return mode_; } + + // Info needed for catalog recovery. These methods will return + // null pointers if item metadata is not in the data stream. + const ClassId *catalogEntryClassId() const { return storedEntryId_; } + const ClassId *itemLocationClassId() const { return storedLocationId_; } + + private: + BinaryArchiveBase() = delete; + BinaryArchiveBase(const BinaryArchiveBase &) = delete; + BinaryArchiveBase &operator=(const BinaryArchiveBase &) = delete; + + static bool parseArchiveOptions(std::ostringstream &errmes, + const char *mode, + CStringStream::CompressionMode *m, + int *compressionLevel, + unsigned *minSizeToCompress, + unsigned *bufSize, + bool *multiplexCatalog); + + void writeHeader(std::ostream &os); + + // The following method returns "true" if a correctly + // formatted header was found + bool readHeader(std::istream &is); + + void search(AbsReference &reference) override; + + // The derived classes must override the following two methods + virtual std::ostream &plainOutputStream() = 0; + virtual std::istream &plainInputStream(unsigned long long id, + unsigned *compressionCode, + unsigned long long *length) = 0; + + std::istream &inputStream(unsigned long long id, long long *sz) override; + std::ostream &outputStream() override; + std::ostream &compressedStream(std::ostream &uncompressed) override; + unsigned flushCompressedRecord(std::ostream &compressed) override; + void releaseClassIds(); + + const std::ios_base::openmode mode_; + std::ostringstream *errorStream_; + CStringStream *cStream_; + AbsCatalog *catalog_; + ClassId *storedEntryId_; + ClassId *storedLocationId_; + bool catalogIsSet_; + bool modeIsValid_; + bool addCatalogToData_; + }; +} // namespace gs + +#endif // GENERS_BINARYARCHIVEBASE_HH_ diff --git a/Alignment/Geners/interface/BinaryFileArchive.hh b/Alignment/Geners/interface/BinaryFileArchive.hh index 411f872863966..9fa10b0558981 100644 --- a/Alignment/Geners/interface/BinaryFileArchive.hh +++ b/Alignment/Geners/interface/BinaryFileArchive.hh @@ -7,61 +7,58 @@ #include "Alignment/Geners/interface/CatalogIO.hh" namespace gs { - class BinaryFileArchive : public BinaryArchiveBase - { - public: - // See the note inside the "BinaryArchiveBase.hh" header - // for the meaning of the "mode" argument - BinaryFileArchive(const char* basename, const char* mode, - const char* annotation = 0, - unsigned dataFileBufferSize = 1048576U, - unsigned catalogFileBufferSize = 131072U); - virtual ~BinaryFileArchive(); + class BinaryFileArchive : public BinaryArchiveBase { + public: + // See the note inside the "BinaryArchiveBase.hh" header + // for the meaning of the "mode" argument + BinaryFileArchive(const char *basename, + const char *mode, + const char *annotation = nullptr, + unsigned dataFileBufferSize = 1048576U, + unsigned catalogFileBufferSize = 131072U); + ~BinaryFileArchive() override; - void flush(); + void flush() override; - private: - void writeCatalog(); - void releaseBuffers(); + private: + void writeCatalog(); + void releaseBuffers(); - template - void readCatalog() - { - assert(!catalog()); - unsigned compressionMode; - setCatalog(readBinaryCatalog( - catStream_, &compressionMode, &catalogMergeLevel_, - &catalogAnnotations_, true)); - assert(catalog()); - setCompressionMode(compressionMode); - } + template + void readCatalog() { + assert(!catalog()); + unsigned compressionMode; + setCatalog( + readBinaryCatalog(catStream_, &compressionMode, &catalogMergeLevel_, &catalogAnnotations_, true)); + assert(catalog()); + setCompressionMode(compressionMode); + } - // The following methods have to be overriden from the base - std::ostream& plainOutputStream(); - std::istream& plainInputStream(unsigned long long id, - unsigned* compressionCode, - unsigned long long* length); + // The following methods have to be overriden from the base + std::ostream &plainOutputStream() override; + std::istream &plainInputStream(unsigned long long id, + unsigned *compressionCode, + unsigned long long *length) override; - unsigned long long addToCatalog( - const AbsRecord& record, unsigned compressionCode, - unsigned long long itemLength); + unsigned long long addToCatalog(const AbsRecord &record, + unsigned compressionCode, + unsigned long long itemLength) override; - char* filebuf_; - char* catabuf_; - std::string annotation_; - std::string dataFileName_; - std::string catalogFileName_; - std::string dataFileURI_; - std::fstream dataStream_; - std::fstream catStream_; - std::streampos lastpos_; - std::streampos jumppos_; - std::vector catalogAnnotations_; - unsigned catalogMergeLevel_; - bool annotationsMerged_; - bool streamFlushed_; - }; -} - -#endif // GENERS_BINARYFILEARCHIVE_HH_ + char *filebuf_; + char *catabuf_; + std::string annotation_; + std::string dataFileName_; + std::string catalogFileName_; + std::string dataFileURI_; + std::fstream dataStream_; + std::fstream catStream_; + std::streampos lastpos_; + std::streampos jumppos_; + std::vector catalogAnnotations_; + unsigned catalogMergeLevel_; + bool annotationsMerged_; + bool streamFlushed_; + }; +} // namespace gs +#endif // GENERS_BINARYFILEARCHIVE_HH_ diff --git a/Alignment/Geners/interface/CPP11_auto_ptr.hh b/Alignment/Geners/interface/CPP11_auto_ptr.hh index bc8d98fec5628..1de84b424a6b1 100644 --- a/Alignment/Geners/interface/CPP11_auto_ptr.hh +++ b/Alignment/Geners/interface/CPP11_auto_ptr.hh @@ -11,5 +11,4 @@ #define CPP11_auto_ptr std::auto_ptr #endif -#endif // GENERS_CPP11_AUTO_PTR_HH_ - +#endif // GENERS_CPP11_AUTO_PTR_HH_ diff --git a/Alignment/Geners/interface/CPP11_config.hh b/Alignment/Geners/interface/CPP11_config.hh index ab30ecf9200f4..f3e0ae462b695 100644 --- a/Alignment/Geners/interface/CPP11_config.hh +++ b/Alignment/Geners/interface/CPP11_config.hh @@ -5,5 +5,4 @@ #define CPP11_STD_AVAILABLE #endif -#endif // GENERS_CPP11_CONFIG_HH_ - +#endif // GENERS_CPP11_CONFIG_HH_ diff --git a/Alignment/Geners/interface/CPP11_shared_ptr.hh b/Alignment/Geners/interface/CPP11_shared_ptr.hh index bbd87bbffd3f8..cc80ba4422ab0 100644 --- a/Alignment/Geners/interface/CPP11_shared_ptr.hh +++ b/Alignment/Geners/interface/CPP11_shared_ptr.hh @@ -11,5 +11,4 @@ #define CPP11_shared_ptr std::tr1::shared_ptr #endif -#endif // GENERS_CPP11_SHARED_PTR_HH_ - +#endif // GENERS_CPP11_SHARED_PTR_HH_ diff --git a/Alignment/Geners/interface/CPP11_type_traits.hh b/Alignment/Geners/interface/CPP11_type_traits.hh index 4f2ad38755dc0..259b6d994fc86 100644 --- a/Alignment/Geners/interface/CPP11_type_traits.hh +++ b/Alignment/Geners/interface/CPP11_type_traits.hh @@ -13,5 +13,4 @@ #define CPP11_is_pointer std::tr1::is_pointer #endif -#endif // GENERS_CPP11_TYPE_TRAITS_HH_ - +#endif // GENERS_CPP11_TYPE_TRAITS_HH_ diff --git a/Alignment/Geners/interface/CStringBuf.hh b/Alignment/Geners/interface/CStringBuf.hh index 8f744c3006e9b..793bd1b9a5bb5 100644 --- a/Alignment/Geners/interface/CStringBuf.hh +++ b/Alignment/Geners/interface/CStringBuf.hh @@ -4,21 +4,17 @@ #include namespace gs { - class CStringBuf : public std::stringbuf - { - public: - explicit CStringBuf(std::ios_base::openmode mode = - std::ios_base::in | std::ios_base::out) - : std::stringbuf(mode) {} + class CStringBuf : public std::stringbuf { + public: + explicit CStringBuf(std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) : std::stringbuf(mode) {} - const char* getGetBuffer(unsigned long long* len) const; - const char* getPutBuffer(unsigned long long* len) const; + const char *getGetBuffer(unsigned long long *len) const; + const char *getPutBuffer(unsigned long long *len) const; - private: - CStringBuf(const CStringBuf&); - CStringBuf& operator=(const CStringBuf&); - }; -} - -#endif // GENERS_CSTRINGBUF_HH_ + private: + CStringBuf(const CStringBuf &) = delete; + CStringBuf &operator=(const CStringBuf &) = delete; + }; +} // namespace gs +#endif // GENERS_CSTRINGBUF_HH_ diff --git a/Alignment/Geners/interface/CStringStream.hh b/Alignment/Geners/interface/CStringStream.hh index c6a1bf8a63d20..f43826f439c8d 100644 --- a/Alignment/Geners/interface/CStringStream.hh +++ b/Alignment/Geners/interface/CStringStream.hh @@ -15,80 +15,70 @@ #ifndef GENERS_CSTRINGSTREAM_HH_ #define GENERS_CSTRINGSTREAM_HH_ -#include #include +#include #include "Alignment/Geners/interface/CPP11_auto_ptr.hh" #include "Alignment/Geners/interface/CStringBuf.hh" #include "Alignment/Geners/interface/ZlibHandle.hh" namespace gs { - class CStringStream : public std::basic_iostream - { - public: - enum CompressionMode - { - NOT_COMPRESSED = 0, - ZLIB, - BZIP2 - }; - - CStringStream(CompressionMode m, int compressionLevel, - unsigned minSizeToCompress, unsigned bufSize); - - // Basic inspectors - inline CompressionMode compressionMode() const {return mode_;} - inline int compressionLevel() const {return compressionLevel_;} - inline unsigned minSizeToCompress() const {return minSizeToCompress_;} - inline std::size_t bufferSize() const {return comprBuf_.size();} - - // "setCompressionMode" calls "reset" internally. - // All unprocessed data will be lost. - void setCompressionMode(CompressionMode m); - - // The sink must be set before calling "writeCompressed". - // This is where the compressed data will be dumped. - inline void setSink(std::ostream& os) {sink_ = &os;} - - // "writeCompressed" compresses the content of this stream - // and dumps them to sink. The write pointer is repositioned - // at the beginning of the stream. The compression mode is - // returned (always NOT_COMPRESSED if the amount of data - // was below "minSizeToCompress"). - CompressionMode writeCompressed(); - - // Fill this stream from compressed data. Could be called - // repetitively. Uncompressed data is appended at the end - // (internal pointers are not reset). - void readCompressed(std::istream& in, unsigned compressionCode, - unsigned long long len); - - // Reposition both read and write pointers of the stream - // at the beginning of the stream - void reset(); - - // Parse the compression mode. Returns "true" on success. - static bool getCompressionModeByName(const char* name, - CompressionMode* m); - - // String representation of the compression mode - static std::string compressionModeName(CompressionMode m, - bool useShortName=true); - private: - CStringStream(const CStringStream&); - CStringStream& operator=(const CStringStream&); - - CStringBuf buf_; - CompressionMode mode_; - int compressionLevel_; - unsigned minSizeToCompress_; - std::vector comprBuf_; - std::vector readBuf_; - std::ostream* sink_; - CPP11_auto_ptr inflator_; - CPP11_auto_ptr deflator_; - }; -} - -#endif // GENERS_CSTRINGSTREAM_HH_ - + class CStringStream : public std::basic_iostream { + public: + enum CompressionMode { NOT_COMPRESSED = 0, ZLIB, BZIP2 }; + + CStringStream(CompressionMode m, int compressionLevel, unsigned minSizeToCompress, unsigned bufSize); + + // Basic inspectors + inline CompressionMode compressionMode() const { return mode_; } + inline int compressionLevel() const { return compressionLevel_; } + inline unsigned minSizeToCompress() const { return minSizeToCompress_; } + inline std::size_t bufferSize() const { return comprBuf_.size(); } + + // "setCompressionMode" calls "reset" internally. + // All unprocessed data will be lost. + void setCompressionMode(CompressionMode m); + + // The sink must be set before calling "writeCompressed". + // This is where the compressed data will be dumped. + inline void setSink(std::ostream &os) { sink_ = &os; } + + // "writeCompressed" compresses the content of this stream + // and dumps them to sink. The write pointer is repositioned + // at the beginning of the stream. The compression mode is + // returned (always NOT_COMPRESSED if the amount of data + // was below "minSizeToCompress"). + CompressionMode writeCompressed(); + + // Fill this stream from compressed data. Could be called + // repetitively. Uncompressed data is appended at the end + // (internal pointers are not reset). + void readCompressed(std::istream &in, unsigned compressionCode, unsigned long long len); + + // Reposition both read and write pointers of the stream + // at the beginning of the stream + void reset(); + + // Parse the compression mode. Returns "true" on success. + static bool getCompressionModeByName(const char *name, CompressionMode *m); + + // String representation of the compression mode + static std::string compressionModeName(CompressionMode m, bool useShortName = true); + + private: + CStringStream(const CStringStream &) = delete; + CStringStream &operator=(const CStringStream &) = delete; + + CStringBuf buf_; + CompressionMode mode_; + int compressionLevel_; + unsigned minSizeToCompress_; + std::vector comprBuf_; + std::vector readBuf_; + std::ostream *sink_; + CPP11_auto_ptr inflator_; + CPP11_auto_ptr deflator_; + }; +} // namespace gs + +#endif // GENERS_CSTRINGSTREAM_HH_ diff --git a/Alignment/Geners/interface/CatalogEntry.hh b/Alignment/Geners/interface/CatalogEntry.hh index a4756b8b8fe01..a9548dfd5cf07 100644 --- a/Alignment/Geners/interface/CatalogEntry.hh +++ b/Alignment/Geners/interface/CatalogEntry.hh @@ -5,63 +5,68 @@ #include "Alignment/Geners/interface/ItemLocation.hh" namespace gs { - class CatalogEntry : public ItemDescriptor - { - public: - // Default constructor returns an invalid entry - CatalogEntry(); + class CatalogEntry : public ItemDescriptor { + public: + // Default constructor returns an invalid entry + CatalogEntry(); - // Use this constructor to build valid entries - CatalogEntry(const ItemDescriptor& descr, - unsigned long long id, - unsigned compressionCode, - unsigned long long itemLength, - const ItemLocation& location, - unsigned long long offset=0ULL); + // Use this constructor to build valid entries + CatalogEntry(const ItemDescriptor &descr, + unsigned long long id, + unsigned compressionCode, + unsigned long long itemLength, + const ItemLocation &location, + unsigned long long offset = 0ULL); - inline virtual ~CatalogEntry() {} + inline ~CatalogEntry() override {} - inline unsigned long long id() const {return id_;} - inline unsigned long long offset() const {return offset_;} - inline const ItemLocation& location() const {return location_;} - inline unsigned long long itemLength() const {return len_;} - inline unsigned compressionCode() const {return compressionCode_;} + inline unsigned long long id() const { return id_; } + inline unsigned long long offset() const { return offset_; } + inline const ItemLocation &location() const { return location_; } + inline unsigned long long itemLength() const { return len_; } + inline unsigned compressionCode() const { return compressionCode_; } - inline CatalogEntry& setStreamPosition(std::streampos pos) - {location_.setStreamPosition(pos); return *this;} - inline CatalogEntry& setURI(const char* newURI) - {location_.setURI(newURI); return *this;} - inline CatalogEntry& setCachedItemURI(const char* newURI) - {location_.setCachedItemURI(newURI); return *this;} - inline CatalogEntry& setOffset(const unsigned long long off) - {offset_ = off; return *this;} + inline CatalogEntry &setStreamPosition(std::streampos pos) { + location_.setStreamPosition(pos); + return *this; + } + inline CatalogEntry &setURI(const char *newURI) { + location_.setURI(newURI); + return *this; + } + inline CatalogEntry &setCachedItemURI(const char *newURI) { + location_.setCachedItemURI(newURI); + return *this; + } + inline CatalogEntry &setOffset(const unsigned long long off) { + offset_ = off; + return *this; + } - // Dump a simple human-readable representation - bool humanReadable(std::ostream& os) const; + // Dump a simple human-readable representation + bool humanReadable(std::ostream &os) const; - // Methods related to I/O for this record itself - inline virtual ClassId classId() const {return ClassId(*this);} - virtual bool write(std::ostream& of) const; + // Methods related to I/O for this record itself + inline virtual ClassId classId() const { return ClassId(*this); } + virtual bool write(std::ostream &of) const; - static inline const char* classname() {return "gs::CatalogEntry";} - static inline unsigned version() {return 1;} + static inline const char *classname() { return "gs::CatalogEntry"; } + static inline unsigned version() { return 1; } - // "locId" is the class id for ItemLocation. Should be written - // out by the catalog together with the CatalogEntry class id. - static CatalogEntry* read(const ClassId& id, const ClassId& locId, - std::istream& in); + // "locId" is the class id for ItemLocation. Should be written + // out by the catalog together with the CatalogEntry class id. + static CatalogEntry *read(const ClassId &id, const ClassId &locId, std::istream &in); - protected: - virtual bool isEqual(const ItemDescriptor&) const; + protected: + bool isEqual(const ItemDescriptor &) const override; - private: - unsigned long long id_; - unsigned long long len_; - unsigned long long offset_; - unsigned compressionCode_; - ItemLocation location_; - }; -} - -#endif // GENERS_CATALOGENTRY_HH_ + private: + unsigned long long id_; + unsigned long long len_; + unsigned long long offset_; + unsigned compressionCode_; + ItemLocation location_; + }; +} // namespace gs +#endif // GENERS_CATALOGENTRY_HH_ diff --git a/Alignment/Geners/interface/CatalogIO.hh b/Alignment/Geners/interface/CatalogIO.hh index 86000a132a9a5..41ed25a553d5f 100644 --- a/Alignment/Geners/interface/CatalogIO.hh +++ b/Alignment/Geners/interface/CatalogIO.hh @@ -16,127 +16,121 @@ #include "Alignment/Geners/interface/AbsCatalog.hh" namespace gs { - struct CatalogFormat1 - { - enum {ID = 713265489}; - }; - - // In the following, it is assumed that the catalog is stored - // in memory and that it has a stream dedicated to it. The - // function returns "true" on success. - // - // Programs which make new catalogs should set "mergeLevel" to 1. - // Programs which combine existing catalogs should add up the - // merge levels of those catalogs to come up with the "mergeLevel". - // - // "annotations" are arbitrary strings (which should be just combined - // when catalogs are merged). - bool writeBinaryCatalog(std::ostream& os, unsigned compressionCode, - unsigned mergeLevel, - const std::vector& annotations, - const AbsCatalog& catalog, - unsigned formatId = CatalogFormat1::ID); - - // In the following, it is assumed that the Catalog class - // has a "read" function which builds the catalog on the heap. - // The "allowReadingByDifferentClass" parameter specifies - // whether the catalog class is allowed to read something - // written by another catalog class. This function returns NULL - // pointer on failure. Note that the user must call "delete" - // on the returned pointer at some point in the future. - template - Catalog* readBinaryCatalog(std::istream& is, unsigned* compressionCode, - unsigned* mergeLevel, - std::vector* annotations, - bool allowReadingByDifferentClass, - unsigned formatId = CatalogFormat1::ID); -} + struct CatalogFormat1 { + enum { ID = 713265489 }; + }; + + // In the following, it is assumed that the catalog is stored + // in memory and that it has a stream dedicated to it. The + // function returns "true" on success. + // + // Programs which make new catalogs should set "mergeLevel" to 1. + // Programs which combine existing catalogs should add up the + // merge levels of those catalogs to come up with the "mergeLevel". + // + // "annotations" are arbitrary strings (which should be just combined + // when catalogs are merged). + bool writeBinaryCatalog(std::ostream &os, + unsigned compressionCode, + unsigned mergeLevel, + const std::vector &annotations, + const AbsCatalog &catalog, + unsigned formatId = CatalogFormat1::ID); + + // In the following, it is assumed that the Catalog class + // has a "read" function which builds the catalog on the heap. + // The "allowReadingByDifferentClass" parameter specifies + // whether the catalog class is allowed to read something + // written by another catalog class. This function returns NULL + // pointer on failure. Note that the user must call "delete" + // on the returned pointer at some point in the future. + template + Catalog *readBinaryCatalog(std::istream &is, + unsigned *compressionCode, + unsigned *mergeLevel, + std::vector *annotations, + bool allowReadingByDifferentClass, + unsigned formatId = CatalogFormat1::ID); +} // namespace gs -#include #include +#include -#include "Alignment/Geners/interface/binaryIO.hh" #include "Alignment/Geners/interface/IOException.hh" +#include "Alignment/Geners/interface/binaryIO.hh" namespace gs { - template - Catalog* readBinaryCatalog(std::istream& is, unsigned* compressionCode, - unsigned* mergeLevel, - std::vector* annotations, - const bool allowReadingByDifferentClass, - const unsigned expectedformatId) - { - assert(compressionCode); - assert(mergeLevel); - assert(annotations); - - is.seekg(0, std::ios_base::beg); - - unsigned formatId = 0, endianness = 0; - unsigned char sizelong = 0; - read_pod(is, &formatId); - read_pod(is, &endianness); - read_pod(is, &sizelong); - - if (is.fail()) throw IOReadFailure( - "In gs::readBinaryCatalog: input stream failure"); - - if (endianness != 0x01020304 || - formatId != expectedformatId || - sizelong != sizeof(long)) - throw IOInvalidData("In gs::readBinaryCatalog: not \"geners\" " - "binary metafile or incompatible system " - "architecture"); - - read_pod(is, compressionCode); - read_pod(is, mergeLevel); - read_pod_vector(is, annotations); - ClassId id(is, 1); - Catalog* readback = 0; - - ClassId catId(ClassId::makeId()); - if (id.name() == catId.name()) - // The reading is done by the same class as the writing. - // Make sure the "read" function gets the correct class version. - readback = Catalog::read(id, is); - else - { - if (!allowReadingByDifferentClass) - { - std::ostringstream os; - os << "In gs::readBinarCatalog: incompatible " - << "catalog class: written by \"" << id.name() - << "\", but reading is attempted by \"" - << catId.name() << '"'; - throw IOInvalidData(os.str()); - } - - // The reading is not done by the same class as the writing. - // All bets are off, and it is up to the user to decide whether - // this makes sense. However, to maintain compatibility with - // version 1 archives, we need to pass this version to the - // catalog read function. - if (id.version() == 1) - catId.setVersion(1); - - readback = Catalog::read(catId, is); - } - - // Catalogs do not necessarily know their size in advance, - // so that they might read until the end of file is encountered. - // However, the eof flag on the stream can result in various - // problems later (for example, in writing to the stream). - // Remove this flag. - if (is.eof() && !is.fail() && !is.bad()) - { - is.clear(); - is.seekg(0, std::ios_base::end); - } - - return readback; + template + Catalog *readBinaryCatalog(std::istream &is, + unsigned *compressionCode, + unsigned *mergeLevel, + std::vector *annotations, + const bool allowReadingByDifferentClass, + const unsigned expectedformatId) { + assert(compressionCode); + assert(mergeLevel); + assert(annotations); + + is.seekg(0, std::ios_base::beg); + + unsigned formatId = 0, endianness = 0; + unsigned char sizelong = 0; + read_pod(is, &formatId); + read_pod(is, &endianness); + read_pod(is, &sizelong); + + if (is.fail()) + throw IOReadFailure("In gs::readBinaryCatalog: input stream failure"); + + if (endianness != 0x01020304 || formatId != expectedformatId || sizelong != sizeof(long)) + throw IOInvalidData( + "In gs::readBinaryCatalog: not \"geners\" " + "binary metafile or incompatible system " + "architecture"); + + read_pod(is, compressionCode); + read_pod(is, mergeLevel); + read_pod_vector(is, annotations); + ClassId id(is, 1); + Catalog *readback = nullptr; + + ClassId catId(ClassId::makeId()); + if (id.name() == catId.name()) + // The reading is done by the same class as the writing. + // Make sure the "read" function gets the correct class version. + readback = Catalog::read(id, is); + else { + if (!allowReadingByDifferentClass) { + std::ostringstream os; + os << "In gs::readBinarCatalog: incompatible " + << "catalog class: written by \"" << id.name() << "\", but reading is attempted by \"" << catId.name() + << '"'; + throw IOInvalidData(os.str()); + } + + // The reading is not done by the same class as the writing. + // All bets are off, and it is up to the user to decide whether + // this makes sense. However, to maintain compatibility with + // version 1 archives, we need to pass this version to the + // catalog read function. + if (id.version() == 1) + catId.setVersion(1); + + readback = Catalog::read(catId, is); } -} + // Catalogs do not necessarily know their size in advance, + // so that they might read until the end of file is encountered. + // However, the eof flag on the stream can result in various + // problems later (for example, in writing to the stream). + // Remove this flag. + if (is.eof() && !is.fail() && !is.bad()) { + is.clear(); + is.seekg(0, std::ios_base::end); + } -#endif // GENERS_CATALOGIO_HH_ + return readback; + } +} // namespace gs +#endif // GENERS_CATALOGIO_HH_ diff --git a/Alignment/Geners/interface/CharBuffer.hh b/Alignment/Geners/interface/CharBuffer.hh index 5ad2f356b2b95..84da1a2b9d5c9 100644 --- a/Alignment/Geners/interface/CharBuffer.hh +++ b/Alignment/Geners/interface/CharBuffer.hh @@ -3,33 +3,29 @@ #include -#include "Alignment/Geners/interface/ClassId.hh" #include "Alignment/Geners/interface/CStringBuf.hh" +#include "Alignment/Geners/interface/ClassId.hh" namespace gs { - class CharBuffer : public std::basic_iostream - { - public: - inline CharBuffer() {this->init(&buf_);} - - unsigned long size() const; + class CharBuffer : public std::basic_iostream { + public: + inline CharBuffer() { this->init(&buf_); } - inline ClassId classId() const {return ClassId(*this);} - bool write(std::ostream& of) const; + unsigned long size() const; - static inline const char* classname() {return "gs::CharBuffer";} - static inline unsigned version() {return 1;} - static void restore(const ClassId& id, std::istream& in, - CharBuffer* buf); + inline ClassId classId() const { return ClassId(*this); } + bool write(std::ostream &of) const; - bool operator==(const CharBuffer& r) const; - inline bool operator!=(const CharBuffer& r) const - {return !(*this == r);} + static inline const char *classname() { return "gs::CharBuffer"; } + static inline unsigned version() { return 1; } + static void restore(const ClassId &id, std::istream &in, CharBuffer *buf); - private: - CStringBuf buf_; - }; -} + bool operator==(const CharBuffer &r) const; + inline bool operator!=(const CharBuffer &r) const { return !(*this == r); } -#endif // GENERS_CHARBUFFER_HH_ + private: + CStringBuf buf_; + }; +} // namespace gs +#endif // GENERS_CHARBUFFER_HH_ diff --git a/Alignment/Geners/interface/ClassId.hh b/Alignment/Geners/interface/ClassId.hh index 521e2650ca56f..9ceb182923606 100644 --- a/Alignment/Geners/interface/ClassId.hh +++ b/Alignment/Geners/interface/ClassId.hh @@ -12,243 +12,215 @@ #ifndef GENERS_CLASSID_HH_ #define GENERS_CLASSID_HH_ -#include -#include #include +#include +#include namespace gs { - class ClassId - { - public: - // Generic constructor using a prefix (which is usually - // a class name) and a version number - inline ClassId(const char* prefix, const unsigned version, - const bool isPtr=false) - {initialize(prefix, version, isPtr);} - - // Generic constructor using a prefix (which is usually - // a class name) and a version number - inline ClassId(const std::string& prefix, const unsigned version, - const bool isPtr=false) - {initialize(prefix.c_str(), version, isPtr);} - - // Use the following constructor in the "classId()" methods - // of user-developed classes. - // - // Implementation note: it is possible to "specialize" - // this constructor by delegating the actual job to the - // "ClassIdSpecialization". Then we would be able to create - // class ids for built-in and user types in a unified - // way. This, however, would incur a performance hit - // due to the necessity of making another ClassId and - // copying the result into the internals of the new object. - // This performance hit was deemed significant. If you - // need a universal way to create class ids at some - // point in your code, use the "itemId" method instead - // (this may or may not incur a performance hit, depending - // on what exactly the compiler does). - template - inline ClassId(const T&) - {initialize(T::classname(), T::version(), false);} - - // Constructor from the class id represented by a string - explicit ClassId(const std::string& id); - - // Use the following constructor in "read" functions. - // Dummy argument "reading" is needed in order to generate - // a distinct function signature (otherwise the templated - // constructor can win). - ClassId(std::istream& in, int reading); - - // Use the following pseudo-constructor in static "read" - // methods in case a type check is desired. It has to be - // made static because constructor without any arguments - // can not be a template. Also, this is the way to construct - // class ids for built-in types (there is no way to specialize - // member methods). - template - static ClassId makeId(); - - // "Universal" item id which also works for built-in types - template - static ClassId itemId(const T&); - - // Inspectors for the class name and version number - inline const std::string& name() const {return name_;} - inline unsigned version() const {return version_;} - - // Is this class a pointer for I/O purposes? - inline bool isPointer() const {return isPtr_;} - - // The following function should return a unique class id string - // which takes version number into account - inline const std::string& id() const {return id_;} - - // The following checks if the class name corresponds to - // a template (using the standard manner of class name forming) - bool isTemplate() const; - - // The following function fills the vector with class template - // parameters (if the class is not a template, the vector is - // cleared). Due to the manner in which things are used in this - // package, the result is actually a vector of (vectors of size 1). - void templateParameters(std::vector >* p) const; - - // Function to write this object out. Returns "true" on success. - bool write(std::ostream& of) const; - - // Comparison operators - inline bool operator==(const ClassId& r) const - {return id_ == r.id_;} - inline bool operator!=(const ClassId& r) const - {return !(*this == r);} - inline bool operator<(const ClassId& r) const - {return id_ < r.id_;} - inline bool operator>(const ClassId& r) const - {return id_ > r.id_;} - - // Modify the version number - void setVersion(unsigned newVersion); - - // The following methods verify that the id/classname/version - // of this object are equal to those of the argument and throw - // "gs::IOInvalidArgument" exception if this is not so - void ensureSameId(const ClassId& id) const; - void ensureSameName(const ClassId& id) const; - void ensureSameVersion(const ClassId& id) const; - - // The following method ensures that the version number of this - // class id is within certain range [min, max], with both limits - // allowed. "gs::IOInvalidArgument" exception is thrown if this - // is not so. - void ensureVersionInRange(unsigned min, unsigned max) const; - - // Sometimes one really needs to make a placeholder class id... - // This is a dangerous function: the code using ClassId class - // will normally assume that a ClassId object is always in a valid - // state. Invalid class ids can be distinguished by their empty - // class names (i.e., name().empty() returns "true"). - static ClassId invalidId(); - - private: - ClassId(); - - void initialize(const char* prefix, unsigned version, bool isPtr); - bool makeName(); - bool makeVersion(); - - std::string name_; - std::string id_; - unsigned version_; - bool isPtr_; - - // Return "true" if the prefix is valid - static bool validatePrefix(const char* prefix); - }; - - - // Simple class id compatibility checkers for use as policy classes - // in templated code - struct SameClassId - { - inline static bool compatible(const ClassId& id1, const ClassId& id2) - {return id1.name() == id2.name();} - }; - - struct SameClassName - { - inline static bool compatible(const ClassId& id1, const ClassId& id2) - {return id1 == id2;} - }; - - - // Specialize the following template in order to be able to construct - // ClassId for classes which do not implement static functions - // "classname()" and "version()". - template - struct ClassIdSpecialization - { - inline static ClassId classId(const bool isPtr=false) - { - return ClassId(T::classname(), T::version(), isPtr); - } - }; + class ClassId { + public: + // Generic constructor using a prefix (which is usually + // a class name) and a version number + inline ClassId(const char *prefix, const unsigned version, const bool isPtr = false) { + initialize(prefix, version, isPtr); + } + // Generic constructor using a prefix (which is usually + // a class name) and a version number + inline ClassId(const std::string &prefix, const unsigned version, const bool isPtr = false) { + initialize(prefix.c_str(), version, isPtr); + } - // Utility functions for naming template classes. The "nInclude" - // argument tells us how many template parameters to include into - // the generated template name. For example, use of - // - // template_class_name("myTemplate",1) - // - // will generate a class name which looks like myTemplate, with - // second template parameter omitted. While the result is equivalent - // to invoking "template_class_name("myTemplate")", having an - // explicit limit is convenient for use from certain higher-level - // functions. Note, however, that in the call with two template - // parameters the class id specialization for Y must be available, - // even though it is not used. + // Use the following constructor in the "classId()" methods + // of user-developed classes. // - // This feature is sometimes helpful when certain template parameters - // specify aspects of template behavior which have nothing to do - // with object data contents and I/O. Typical example of such - // a parameter is std::allocator of STL -- changing this to a custom - // allocator will not affect serialized representation of an STL - // container. - // - template - std::string template_class_name(const char* templateName, - unsigned nInclude=1); - template - std::string template_class_name(const std::string& templateName, - unsigned nInclude=1); - template - std::string template_class_name(const char* templateName, - unsigned nInclude=2); - template - std::string template_class_name(const std::string& templateName, - unsigned nInclude=2); - template - std::string template_class_name(const char* templateName, - unsigned nInclude=3); - template - std::string template_class_name(const std::string& templateName, - unsigned nInclude=3); - template - std::string template_class_name(const char* templateName, - unsigned nInclude=4); - template - std::string template_class_name(const std::string& templateName, - unsigned nInclude=4); - template - std::string template_class_name(const char* templateName, - unsigned nInclude=5); - template - std::string template_class_name(const std::string& templateName, - unsigned nInclude=5); - template - std::string template_class_name(const char* templateName, - unsigned nInclude=6); - template - std::string template_class_name(const std::string& templateName, - unsigned nInclude=6); - - // Utility functions for naming stack-based containers such as std::array - template - std::string stack_container_name(const char* templateName); - - template - std::string stack_container_name(const std::string& templateName); -} + // Implementation note: it is possible to "specialize" + // this constructor by delegating the actual job to the + // "ClassIdSpecialization". Then we would be able to create + // class ids for built-in and user types in a unified + // way. This, however, would incur a performance hit + // due to the necessity of making another ClassId and + // copying the result into the internals of the new object. + // This performance hit was deemed significant. If you + // need a universal way to create class ids at some + // point in your code, use the "itemId" method instead + // (this may or may not incur a performance hit, depending + // on what exactly the compiler does). + template + inline ClassId(const T &) { + initialize(T::classname(), T::version(), false); + } + + // Constructor from the class id represented by a string + explicit ClassId(const std::string &id); + + // Use the following constructor in "read" functions. + // Dummy argument "reading" is needed in order to generate + // a distinct function signature (otherwise the templated + // constructor can win). + ClassId(std::istream &in, int reading); + + // Use the following pseudo-constructor in static "read" + // methods in case a type check is desired. It has to be + // made static because constructor without any arguments + // can not be a template. Also, this is the way to construct + // class ids for built-in types (there is no way to specialize + // member methods). + template + static ClassId makeId(); + + // "Universal" item id which also works for built-in types + template + static ClassId itemId(const T &); + + // Inspectors for the class name and version number + inline const std::string &name() const { return name_; } + inline unsigned version() const { return version_; } + + // Is this class a pointer for I/O purposes? + inline bool isPointer() const { return isPtr_; } + + // The following function should return a unique class id string + // which takes version number into account + inline const std::string &id() const { return id_; } + + // The following checks if the class name corresponds to + // a template (using the standard manner of class name forming) + bool isTemplate() const; + + // The following function fills the vector with class template + // parameters (if the class is not a template, the vector is + // cleared). Due to the manner in which things are used in this + // package, the result is actually a vector of (vectors of size 1). + void templateParameters(std::vector> *p) const; + + // Function to write this object out. Returns "true" on success. + bool write(std::ostream &of) const; + + // Comparison operators + inline bool operator==(const ClassId &r) const { return id_ == r.id_; } + inline bool operator!=(const ClassId &r) const { return !(*this == r); } + inline bool operator<(const ClassId &r) const { return id_ < r.id_; } + inline bool operator>(const ClassId &r) const { return id_ > r.id_; } + + // Modify the version number + void setVersion(unsigned newVersion); + + // The following methods verify that the id/classname/version + // of this object are equal to those of the argument and throw + // "gs::IOInvalidArgument" exception if this is not so + void ensureSameId(const ClassId &id) const; + void ensureSameName(const ClassId &id) const; + void ensureSameVersion(const ClassId &id) const; + + // The following method ensures that the version number of this + // class id is within certain range [min, max], with both limits + // allowed. "gs::IOInvalidArgument" exception is thrown if this + // is not so. + void ensureVersionInRange(unsigned min, unsigned max) const; + + // Sometimes one really needs to make a placeholder class id... + // This is a dangerous function: the code using ClassId class + // will normally assume that a ClassId object is always in a valid + // state. Invalid class ids can be distinguished by their empty + // class names (i.e., name().empty() returns "true"). + static ClassId invalidId(); + + private: + ClassId(); + + void initialize(const char *prefix, unsigned version, bool isPtr); + bool makeName(); + bool makeVersion(); + + std::string name_; + std::string id_; + unsigned version_; + bool isPtr_; + + // Return "true" if the prefix is valid + static bool validatePrefix(const char *prefix); + }; + + // Simple class id compatibility checkers for use as policy classes + // in templated code + struct SameClassId { + inline static bool compatible(const ClassId &id1, const ClassId &id2) { return id1.name() == id2.name(); } + }; + + struct SameClassName { + inline static bool compatible(const ClassId &id1, const ClassId &id2) { return id1 == id2; } + }; + + // Specialize the following template in order to be able to construct + // ClassId for classes which do not implement static functions + // "classname()" and "version()". + template + struct ClassIdSpecialization { + inline static ClassId classId(const bool isPtr = false) { return ClassId(T::classname(), T::version(), isPtr); } + }; + + // Utility functions for naming template classes. The "nInclude" + // argument tells us how many template parameters to include into + // the generated template name. For example, use of + // + // template_class_name("myTemplate",1) + // + // will generate a class name which looks like myTemplate, with + // second template parameter omitted. While the result is equivalent + // to invoking "template_class_name("myTemplate")", having an + // explicit limit is convenient for use from certain higher-level + // functions. Note, however, that in the call with two template + // parameters the class id specialization for Y must be available, + // even though it is not used. + // + // This feature is sometimes helpful when certain template parameters + // specify aspects of template behavior which have nothing to do + // with object data contents and I/O. Typical example of such + // a parameter is std::allocator of STL -- changing this to a custom + // allocator will not affect serialized representation of an STL + // container. + // + template + std::string template_class_name(const char *templateName, unsigned nInclude = 1); + template + std::string template_class_name(const std::string &templateName, unsigned nInclude = 1); + template + std::string template_class_name(const char *templateName, unsigned nInclude = 2); + template + std::string template_class_name(const std::string &templateName, unsigned nInclude = 2); + template + std::string template_class_name(const char *templateName, unsigned nInclude = 3); + template + std::string template_class_name(const std::string &templateName, unsigned nInclude = 3); + template + std::string template_class_name(const char *templateName, unsigned nInclude = 4); + template + std::string template_class_name(const std::string &templateName, unsigned nInclude = 4); + template + std::string template_class_name(const char *templateName, unsigned nInclude = 5); + template + std::string template_class_name(const std::string &templateName, unsigned nInclude = 5); + template + std::string template_class_name(const char *templateName, unsigned nInclude = 6); + template + std::string template_class_name(const std::string &templateName, unsigned nInclude = 6); + + // Utility functions for naming stack-based containers such as std::array + template + std::string stack_container_name(const char *templateName); + + template + std::string stack_container_name(const std::string &templateName); +} // namespace gs #include +#include #include #include -#include -#include "Alignment/Geners/interface/IOIsClassType.hh" #include "Alignment/Geners/interface/IOIsAnyPtr.hh" - +#include "Alignment/Geners/interface/IOIsClassType.hh" #ifdef GENERS_EMPTY_TYPE_QUALIFYER_ #undef GENERS_EMPTY_TYPE_QUALIFYER_ @@ -258,598 +230,517 @@ namespace gs { // Specializations of "ClassIdSpecialization" for built-in classes. // They all look the same, so we want to use a macro -#define gs_specialize_class_helper(qualifyer, name, version) /**/ \ - template<> struct ClassIdSpecialization \ - {inline static ClassId classId(const bool isPtr=false) \ - {return ClassId(#name, version, isPtr);}}; - -#define gs_specialize_class_id(name, version) /**/ \ -namespace gs { \ - gs_specialize_class_helper(GENERS_EMPTY_TYPE_QUALIFYER_, name, version)\ - gs_specialize_class_helper(const, name, version) \ - gs_specialize_class_helper(volatile, name, version) \ - gs_specialize_class_helper(const volatile, name, version) \ -} +#define gs_specialize_class_helper(qualifyer, name, version) /**/ \ + template <> \ + struct ClassIdSpecialization { \ + inline static ClassId classId(const bool isPtr = false) { return ClassId(#name, version, isPtr); } \ + }; + +#define gs_specialize_class_id(name, version) /**/ \ + namespace gs { \ + gs_specialize_class_helper(GENERS_EMPTY_TYPE_QUALIFYER_, name, version) \ + gs_specialize_class_helper(const, name, version) gs_specialize_class_helper(volatile, name, version) \ + gs_specialize_class_helper(const volatile, name, version) \ + } // Specializations of "ClassIdSpecialization" for single-argument templates -#define gs_specialize_template_help_T(qualifyer, name, version, MAX) /**/ \ - template struct ClassIdSpecialization > \ - {inline static ClassId classId(const bool isPtr=false) \ - {return ClassId(template_class_name(#name,MAX), version, isPtr);}}; - -#define gs_specialize_template_id_T(name, version, MAX) /**/ \ -namespace gs { \ - gs_specialize_template_help_T(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX)\ - gs_specialize_template_help_T(const, name, version, MAX) \ - gs_specialize_template_help_T(volatile, name, version, MAX) \ - gs_specialize_template_help_T(const volatile, name, version, MAX) \ -} +#define gs_specialize_template_help_T(qualifyer, name, version, MAX) /**/ \ + template \ + struct ClassIdSpecialization> { \ + inline static ClassId classId(const bool isPtr = false) { \ + return ClassId(template_class_name(#name, MAX), version, isPtr); \ + } \ + }; + +#define gs_specialize_template_id_T(name, version, MAX) /**/ \ + namespace gs { \ + gs_specialize_template_help_T(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX) \ + gs_specialize_template_help_T(const, name, version, MAX) \ + gs_specialize_template_help_T(volatile, name, version, MAX) \ + gs_specialize_template_help_T(const volatile, name, version, MAX) \ + } // Specializations of "ClassIdSpecialization" for two-argument templates -#define gs_specialize_template_help_TT(qualifyer, name, version, MAX) /**/ \ - template \ - struct ClassIdSpecialization > \ - {inline static ClassId classId(const bool isPtr=false) \ - {return ClassId(template_class_name(#name,MAX), version, isPtr);}}; - -#define gs_specialize_template_id_TT(name, version, MAX) /**/ \ -namespace gs { \ - gs_specialize_template_help_TT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX)\ - gs_specialize_template_help_TT(const, name, version, MAX) \ - gs_specialize_template_help_TT(volatile, name, version, MAX) \ - gs_specialize_template_help_TT(const volatile, name, version, MAX) \ -} +#define gs_specialize_template_help_TT(qualifyer, name, version, MAX) /**/ \ + template \ + struct ClassIdSpecialization> { \ + inline static ClassId classId(const bool isPtr = false) { \ + return ClassId(template_class_name(#name, MAX), version, isPtr); \ + } \ + }; + +#define gs_specialize_template_id_TT(name, version, MAX) /**/ \ + namespace gs { \ + gs_specialize_template_help_TT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX) \ + gs_specialize_template_help_TT(const, name, version, MAX) \ + gs_specialize_template_help_TT(volatile, name, version, MAX) \ + gs_specialize_template_help_TT(const volatile, name, version, MAX) \ + } // Specializations of "ClassIdSpecialization" for three-argument templates -#define gs_specialize_template_help_TTT(qualifyer, name, version, MAX) /**/ \ - template \ - struct ClassIdSpecialization > \ - {inline static ClassId classId(const bool isPtr=false) \ - {return ClassId(template_class_name(#name,MAX), version, isPtr);}}; - -#define gs_specialize_template_id_TTT(name, version, MAX) /**/ \ -namespace gs { \ - gs_specialize_template_help_TTT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX)\ - gs_specialize_template_help_TTT(const, name, version, MAX) \ - gs_specialize_template_help_TTT(volatile, name, version, MAX) \ - gs_specialize_template_help_TTT(const volatile, name, version, MAX) \ -} +#define gs_specialize_template_help_TTT(qualifyer, name, version, MAX) /**/ \ + template \ + struct ClassIdSpecialization> { \ + inline static ClassId classId(const bool isPtr = false) { \ + return ClassId(template_class_name(#name, MAX), version, isPtr); \ + } \ + }; + +#define gs_specialize_template_id_TTT(name, version, MAX) /**/ \ + namespace gs { \ + gs_specialize_template_help_TTT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX) \ + gs_specialize_template_help_TTT(const, name, version, MAX) \ + gs_specialize_template_help_TTT(volatile, name, version, MAX) \ + gs_specialize_template_help_TTT(const volatile, name, version, MAX) \ + } // Specializations of "ClassIdSpecialization" for four-argument templates -#define gs_specialize_template_help_TTTT(qualifyer, name, version, MAX) /**/ \ - template \ - struct ClassIdSpecialization > \ - {inline static ClassId classId(const bool isPtr=false) \ - {return ClassId(template_class_name(#name,MAX), version, isPtr);}}; - -#define gs_specialize_template_id_TTTT(name, version, MAX) /**/ \ -namespace gs { \ - gs_specialize_template_help_TTTT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX)\ - gs_specialize_template_help_TTTT(const, name, version, MAX) \ - gs_specialize_template_help_TTTT(volatile, name, version, MAX) \ - gs_specialize_template_help_TTTT(const volatile, name, version, MAX) \ -} +#define gs_specialize_template_help_TTTT(qualifyer, name, version, MAX) /**/ \ + template \ + struct ClassIdSpecialization> { \ + inline static ClassId classId(const bool isPtr = false) { \ + return ClassId(template_class_name(#name, MAX), version, isPtr); \ + } \ + }; + +#define gs_specialize_template_id_TTTT(name, version, MAX) /**/ \ + namespace gs { \ + gs_specialize_template_help_TTTT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX) \ + gs_specialize_template_help_TTTT(const, name, version, MAX) \ + gs_specialize_template_help_TTTT(volatile, name, version, MAX) \ + gs_specialize_template_help_TTTT(const volatile, name, version, MAX) \ + } // Specializations of "ClassIdSpecialization" for five-argument templates -#define gs_specialize_template_hlp_TTTTT(qualifyer, name, version, MAX) /**/ \ - template \ - struct ClassIdSpecialization > \ - {inline static ClassId classId(const bool isPtr=false) \ - {return ClassId(template_class_name(#name,MAX), version, isPtr);}}; - -#define gs_specialize_template_id_TTTTT(name, version, MAX) /**/ \ -namespace gs { \ - gs_specialize_template_hlp_TTTTT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX)\ - gs_specialize_template_hlp_TTTTT(const, name, version, MAX) \ - gs_specialize_template_hlp_TTTTT(volatile, name, version, MAX) \ - gs_specialize_template_hlp_TTTTT(const volatile, name, version, MAX) \ -} +#define gs_specialize_template_hlp_TTTTT(qualifyer, name, version, MAX) /**/ \ + template \ + struct ClassIdSpecialization> { \ + inline static ClassId classId(const bool isPtr = false) { \ + return ClassId(template_class_name(#name, MAX), version, isPtr); \ + } \ + }; + +#define gs_specialize_template_id_TTTTT(name, version, MAX) /**/ \ + namespace gs { \ + gs_specialize_template_hlp_TTTTT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX) \ + gs_specialize_template_hlp_TTTTT(const, name, version, MAX) \ + gs_specialize_template_hlp_TTTTT(volatile, name, version, MAX) \ + gs_specialize_template_hlp_TTTTT(const volatile, name, version, MAX) \ + } // Specializations of "ClassIdSpecialization" for six-argument templates -#define gs_specialize_template_h_TTTTTT(qualifyer, name, version, MAX) /**/ \ - template \ - struct ClassIdSpecialization > \ - {inline static ClassId classId(const bool isPtr=false) \ - {return ClassId(template_class_name(#name,MAX), version, isPtr);}}; - -#define gs_specialize_template_id_TTTTTT(name, version, MAX) /**/ \ -namespace gs { \ - gs_specialize_template_h_TTTTTT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX)\ - gs_specialize_template_h_TTTTTT(const, name, version, MAX) \ - gs_specialize_template_h_TTTTTT(volatile, name, version, MAX) \ - gs_specialize_template_h_TTTTTT(const volatile, name, version, MAX) \ -} +#define gs_specialize_template_h_TTTTTT(qualifyer, name, version, MAX) /**/ \ + template \ + struct ClassIdSpecialization> { \ + inline static ClassId classId(const bool isPtr = false) { \ + return ClassId(template_class_name(#name, MAX), version, isPtr); \ + } \ + }; + +#define gs_specialize_template_id_TTTTTT(name, version, MAX) /**/ \ + namespace gs { \ + gs_specialize_template_h_TTTTTT(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX) \ + gs_specialize_template_h_TTTTTT(const, name, version, MAX) \ + gs_specialize_template_h_TTTTTT(volatile, name, version, MAX) \ + gs_specialize_template_h_TTTTTT(const volatile, name, version, MAX) \ + } // Specializations of "ClassIdSpecialization" for two-argument templates // which include an integer as a second argument (like std::array) -#define gs_specialize_template_help_TN(qualifyer, name, version, MAX) /**/ \ - template \ - struct ClassIdSpecialization > \ - {inline static ClassId classId(const bool isPtr=false) \ - {return ClassId(stack_container_name(#name,MAX), version, isPtr);}}; - -#define gs_specialize_template_id_TN(name, version, MAX) /**/ \ -namespace gs { \ - gs_specialize_template_help_TN(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX)\ - gs_specialize_template_help_TN(const, name, version, MAX) \ - gs_specialize_template_help_TN(volatile, name, version, MAX) \ - gs_specialize_template_help_TN(const volatile, name, version, MAX) \ -} +#define gs_specialize_template_help_TN(qualifyer, name, version, MAX) /**/ \ + template \ + struct ClassIdSpecialization> { \ + inline static ClassId classId(const bool isPtr = false) { \ + return ClassId(stack_container_name(#name, MAX), version, isPtr); \ + } \ + }; + +#define gs_specialize_template_id_TN(name, version, MAX) /**/ \ + namespace gs { \ + gs_specialize_template_help_TN(GENERS_EMPTY_TYPE_QUALIFYER_, name, version, MAX) \ + gs_specialize_template_help_TN(const, name, version, MAX) \ + gs_specialize_template_help_TN(volatile, name, version, MAX) \ + gs_specialize_template_help_TN(const volatile, name, version, MAX) \ + } namespace gs { - // "template_class_name" implementations - template - std::string template_class_name(const char* templateName, - const unsigned nInclude) - { - assert(templateName); - std::string name(templateName); - if (nInclude) - { - name += '<'; - const ClassId& id(ClassIdSpecialization::classId()); - name += id.id(); - name += '>'; - } - return name; - } - - template - inline std::string template_class_name(const std::string& templateName, - const unsigned nInclude) - { - return template_class_name(templateName.c_str(), nInclude); - } - - template - std::string template_class_name(const char* templateName, - const unsigned nInclude) - { - assert(templateName); - std::string name(templateName); - if (nInclude) - { - name += '<'; - const ClassId& id1(ClassIdSpecialization::classId()); - name += id1.id(); - if (nInclude > 1) - { - name += ','; - const ClassId& id2(ClassIdSpecialization::classId()); - name += id2.id(); - } - name += '>'; - } - return name; - } - - template - inline std::string template_class_name(const std::string& templateName, - const unsigned nInclude) - { - return template_class_name(templateName.c_str(), nInclude); - } - - template - std::string template_class_name(const char* templateName, - const unsigned nInclude) - { - assert(templateName); - std::string name(templateName); - if (nInclude) - { - name += '<'; - const ClassId& id1(ClassIdSpecialization::classId()); - name += id1.id(); - if (nInclude > 1) - { - name += ','; - const ClassId& id2(ClassIdSpecialization::classId()); - name += id2.id(); - } - if (nInclude > 2) - { - name += ','; - const ClassId& id3(ClassIdSpecialization::classId()); - name += id3.id(); - } - name += '>'; - } - return name; - } - - template - inline std::string template_class_name(const std::string& templateName, - const unsigned nInclude) - { - return template_class_name(templateName.c_str(), nInclude); - } - - template - std::string template_class_name(const char* templateName, - const unsigned nInclude) - { - assert(templateName); - std::string name(templateName); - if (nInclude) - { - name += '<'; - const ClassId& id1(ClassIdSpecialization::classId()); - name += id1.id(); - if (nInclude > 1) - { - name += ','; - const ClassId& id2(ClassIdSpecialization::classId()); - name += id2.id(); - } - if (nInclude > 2) - { - name += ','; - const ClassId& id3(ClassIdSpecialization::classId()); - name += id3.id(); - } - if (nInclude > 3) - { - name += ','; - const ClassId& id4(ClassIdSpecialization::classId()); - name += id4.id(); - } - name += '>'; - } - return name; - } - - template - inline std::string template_class_name(const std::string& templateName, - const unsigned n) - { - return template_class_name(templateName.c_str(), n); + // "template_class_name" implementations + template + std::string template_class_name(const char *templateName, const unsigned nInclude) { + assert(templateName); + std::string name(templateName); + if (nInclude) { + name += '<'; + const ClassId &id(ClassIdSpecialization::classId()); + name += id.id(); + name += '>'; } - - template - std::string template_class_name(const char* templateName, - const unsigned nInclude) - { - assert(templateName); - std::string name(templateName); - if (nInclude) - { - name += '<'; - const ClassId& id1(ClassIdSpecialization::classId()); - name += id1.id(); - if (nInclude > 1) - { - name += ','; - const ClassId& id2(ClassIdSpecialization::classId()); - name += id2.id(); - } - if (nInclude > 2) - { - name += ','; - const ClassId& id3(ClassIdSpecialization::classId()); - name += id3.id(); - } - if (nInclude > 3) - { - name += ','; - const ClassId& id4(ClassIdSpecialization::classId()); - name += id4.id(); - } - if (nInclude > 4) - { - name += ','; - const ClassId& id5(ClassIdSpecialization::classId()); - name += id5.id(); - } - name += '>'; - } - return name; + return name; + } + + template + inline std::string template_class_name(const std::string &templateName, const unsigned nInclude) { + return template_class_name(templateName.c_str(), nInclude); + } + + template + std::string template_class_name(const char *templateName, const unsigned nInclude) { + assert(templateName); + std::string name(templateName); + if (nInclude) { + name += '<'; + const ClassId &id1(ClassIdSpecialization::classId()); + name += id1.id(); + if (nInclude > 1) { + name += ','; + const ClassId &id2(ClassIdSpecialization::classId()); + name += id2.id(); + } + name += '>'; } - - template - inline std::string template_class_name(const std::string& templateName, - const unsigned n) - { - return template_class_name(templateName.c_str(), n); - } - - template - std::string template_class_name(const char* templateName, - const unsigned nInclude) - { - assert(templateName); - std::string name(templateName); - if (nInclude) - { - name += '<'; - const ClassId& id1(ClassIdSpecialization::classId()); - name += id1.id(); - if (nInclude > 1) - { - name += ','; - const ClassId& id2(ClassIdSpecialization::classId()); - name += id2.id(); - } - if (nInclude > 2) - { - name += ','; - const ClassId& id3(ClassIdSpecialization::classId()); - name += id3.id(); - } - if (nInclude > 3) - { - name += ','; - const ClassId& id4(ClassIdSpecialization::classId()); - name += id4.id(); - } - if (nInclude > 4) - { - name += ','; - const ClassId& id5(ClassIdSpecialization::classId()); - name += id5.id(); - } - if (nInclude > 5) - { - name += ','; - const ClassId& id6(ClassIdSpecialization::classId()); - name += id6.id(); - } - name += '>'; - } - return name; + return name; + } + + template + inline std::string template_class_name(const std::string &templateName, const unsigned nInclude) { + return template_class_name(templateName.c_str(), nInclude); + } + + template + std::string template_class_name(const char *templateName, const unsigned nInclude) { + assert(templateName); + std::string name(templateName); + if (nInclude) { + name += '<'; + const ClassId &id1(ClassIdSpecialization::classId()); + name += id1.id(); + if (nInclude > 1) { + name += ','; + const ClassId &id2(ClassIdSpecialization::classId()); + name += id2.id(); + } + if (nInclude > 2) { + name += ','; + const ClassId &id3(ClassIdSpecialization::classId()); + name += id3.id(); + } + name += '>'; } - - template - inline std::string template_class_name(const std::string& templateName, - const unsigned n) - { - return template_class_name(templateName.c_str(), n); + return name; + } + + template + inline std::string template_class_name(const std::string &templateName, const unsigned nInclude) { + return template_class_name(templateName.c_str(), nInclude); + } + + template + std::string template_class_name(const char *templateName, const unsigned nInclude) { + assert(templateName); + std::string name(templateName); + if (nInclude) { + name += '<'; + const ClassId &id1(ClassIdSpecialization::classId()); + name += id1.id(); + if (nInclude > 1) { + name += ','; + const ClassId &id2(ClassIdSpecialization::classId()); + name += id2.id(); + } + if (nInclude > 2) { + name += ','; + const ClassId &id3(ClassIdSpecialization::classId()); + name += id3.id(); + } + if (nInclude > 3) { + name += ','; + const ClassId &id4(ClassIdSpecialization::classId()); + name += id4.id(); + } + name += '>'; } - - template - std::string stack_container_name(const char* templateName) - { - assert(templateName); - const ClassId& id1(ClassIdSpecialization::classId()); - std::ostringstream os; - os << templateName << '<' << id1.id() << ',' << N << "(0)>"; - return os.str(); + return name; + } + + template + inline std::string template_class_name(const std::string &templateName, const unsigned n) { + return template_class_name(templateName.c_str(), n); + } + + template + std::string template_class_name(const char *templateName, const unsigned nInclude) { + assert(templateName); + std::string name(templateName); + if (nInclude) { + name += '<'; + const ClassId &id1(ClassIdSpecialization::classId()); + name += id1.id(); + if (nInclude > 1) { + name += ','; + const ClassId &id2(ClassIdSpecialization::classId()); + name += id2.id(); + } + if (nInclude > 2) { + name += ','; + const ClassId &id3(ClassIdSpecialization::classId()); + name += id3.id(); + } + if (nInclude > 3) { + name += ','; + const ClassId &id4(ClassIdSpecialization::classId()); + name += id4.id(); + } + if (nInclude > 4) { + name += ','; + const ClassId &id5(ClassIdSpecialization::classId()); + name += id5.id(); + } + name += '>'; } - - template - std::string stack_container_name(const std::string& templateName) - { - return stack_container_name(templateName.c_str()); + return name; + } + + template + inline std::string template_class_name(const std::string &templateName, const unsigned n) { + return template_class_name(templateName.c_str(), n); + } + + template + std::string template_class_name(const char *templateName, const unsigned nInclude) { + assert(templateName); + std::string name(templateName); + if (nInclude) { + name += '<'; + const ClassId &id1(ClassIdSpecialization::classId()); + name += id1.id(); + if (nInclude > 1) { + name += ','; + const ClassId &id2(ClassIdSpecialization::classId()); + name += id2.id(); + } + if (nInclude > 2) { + name += ','; + const ClassId &id3(ClassIdSpecialization::classId()); + name += id3.id(); + } + if (nInclude > 3) { + name += ','; + const ClassId &id4(ClassIdSpecialization::classId()); + name += id4.id(); + } + if (nInclude > 4) { + name += ','; + const ClassId &id5(ClassIdSpecialization::classId()); + name += id5.id(); + } + if (nInclude > 5) { + name += ','; + const ClassId &id6(ClassIdSpecialization::classId()); + name += id6.id(); + } + name += '>'; } - - // Skip references in class ids - template - struct ClassIdSpecialization - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} - }; - - // Skip pointers in class ids - template - struct ClassIdSpecialization - { - inline static ClassId classId(const bool /* isPtr */=false) - {return ClassIdSpecialization::classId(true);} - }; - - template - struct ClassIdSpecialization - { - inline static ClassId classId(const bool /* isPtr */=false) - {return ClassIdSpecialization::classId(true);} - }; - - template - struct ClassIdSpecialization - { - inline static ClassId classId(const bool /* isPtr */=false) - {return ClassIdSpecialization::classId(true);} + return name; + } + + template + inline std::string template_class_name(const std::string &templateName, const unsigned n) { + return template_class_name(templateName.c_str(), n); + } + + template + std::string stack_container_name(const char *templateName) { + assert(templateName); + const ClassId &id1(ClassIdSpecialization::classId()); + std::ostringstream os; + os << templateName << '<' << id1.id() << ',' << N << "(0)>"; + return os.str(); + } + + template + std::string stack_container_name(const std::string &templateName) { + return stack_container_name(templateName.c_str()); + } + + // Skip references in class ids + template + struct ClassIdSpecialization { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + // Skip pointers in class ids + template + struct ClassIdSpecialization { + inline static ClassId classId(const bool /* isPtr */ = false) { return ClassIdSpecialization::classId(true); } + }; + + template + struct ClassIdSpecialization { + inline static ClassId classId(const bool /* isPtr */ = false) { return ClassIdSpecialization::classId(true); } + }; + + template + struct ClassIdSpecialization { + inline static ClassId classId(const bool /* isPtr */ = false) { return ClassIdSpecialization::classId(true); } + }; + + template + struct ClassIdSpecialization { + inline static ClassId classId(const bool /* isPtr */ = false) { return ClassIdSpecialization::classId(true); } + }; + + // Skip shared pointers in class ids + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool /* isPtr */ = false) { return ClassIdSpecialization::classId(true); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool /* isPtr */ = false) { return ClassIdSpecialization::classId(true); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool /* isPtr */ = false) { return ClassIdSpecialization::classId(true); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool /* isPtr */ = false) { return ClassIdSpecialization::classId(true); } + }; + + // Skip IOPtr in class ids and do not turn on the pointer flag + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + // Same thing for IOProxy + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + template + struct ClassIdSpecialization> { + inline static ClassId classId(const bool isPtr = false) { return ClassIdSpecialization::classId(isPtr); } + }; + + // The remaining ClassId static functions + template + inline ClassId ClassId::makeId() { + return ClassIdSpecialization::classId(); + } + + namespace Private { + template + struct CallClassId { + static inline ClassId get(const T &) { return ClassIdSpecialization::classId(); } }; - template - struct ClassIdSpecialization - { - inline static ClassId classId(const bool /* isPtr */=false) - {return ClassIdSpecialization::classId(true);} + template + struct CallClassId { + static inline ClassId get(const T &obj) { return obj.classId(); } }; - // Skip shared pointers in class ids - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool /* isPtr */=false) - {return ClassIdSpecialization::classId(true);} - }; - - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool /* isPtr */=false) - {return ClassIdSpecialization::classId(true);} - }; - - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool /* isPtr */=false) - {return ClassIdSpecialization::classId(true);} - }; + // The following class will check for the existence of two + // possible signatures of the "classId" method: + // "const ClassId& classId() const" and "ClassId classId() const". + template + class TypeHasClassIdHelper { + template + struct TypeCheck; + template + struct FcnType1 { + typedef ClassId (T::*fptr)() const; + }; + template + struct FcnType2 { + typedef const ClassId &(T::*fptr)() const; + }; + + typedef char Yes; + typedef struct { + char a[2]; + } No; + + template + static Yes Has1(TypeCheck::fptr, &T::classId> *); + template + static No Has1(...); + + template + static Yes Has2(TypeCheck::fptr, &T::classId> *); + template + static No Has2(...); - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool /* isPtr */=false) - {return ClassIdSpecialization::classId(true);} - }; - - // Skip IOPtr in class ids and do not turn on the pointer flag - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} - }; - - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} - }; - - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} - }; - - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} - }; - - // Same thing for IOProxy - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} + public: + static const bool value = ((sizeof(Has1(0)) == sizeof(Yes)) || (sizeof(Has2(0)) == sizeof(Yes))); }; - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} + template ::value> + struct TypeHasClassId { + static const bool value = false; }; - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} + template + struct TypeHasClassId { + static const bool value = TypeHasClassIdHelper::value; }; + } // namespace Private - template - struct ClassIdSpecialization > - { - inline static ClassId classId(const bool isPtr=false) - {return ClassIdSpecialization::classId(isPtr);} - }; + template + inline ClassId ClassId::itemId(const T &item) { + // Make sure that item is not a pointer. + static_assert((!IOIsAnyPtr::value), "can not use pointers with this method"); - // The remaining ClassId static functions - template - inline ClassId ClassId::makeId() - { - return ClassIdSpecialization::classId(); - } - - namespace Private { - template - struct CallClassId - { - static inline ClassId get(const T&) - {return ClassIdSpecialization::classId();} - }; - - template - struct CallClassId - { - static inline ClassId get(const T& obj) {return obj.classId();} - }; - - // The following class will check for the existence of two - // possible signatures of the "classId" method: - // "const ClassId& classId() const" and "ClassId classId() const". - template - class TypeHasClassIdHelper - { - template struct TypeCheck; - template struct FcnType1 - {typedef ClassId (T::*fptr)() const;}; - template struct FcnType2 - {typedef const ClassId& (T::*fptr)() const;}; - - typedef char Yes; - typedef struct {char a[2];} No; - - template static Yes Has1( - TypeCheck::fptr, &T::classId>*); - template static No Has1(...); - - template static Yes Has2( - TypeCheck::fptr, &T::classId>*); - template static No Has2(...); - - public: - static const bool value = ((sizeof(Has1(0)) == sizeof(Yes)) || - (sizeof(Has2(0)) == sizeof(Yes))); - }; - - template::value> - struct TypeHasClassId - { - static const bool value = 0; - }; - - template - struct TypeHasClassId - { - static const bool value = TypeHasClassIdHelper::value; - }; - } - - template - inline ClassId ClassId::itemId(const T& item) - { - // Make sure that item is not a pointer. - static_assert((!IOIsAnyPtr::value), "can not use pointers with this method"); - - // If the classId() function is avalable for this item, call it - // (it could be virtual). Otherwise, call the generic method. - return Private::CallClassId< - Private::TypeHasClassId::value,T>::get(item); - } -} + // If the classId() function is avalable for this item, call it + // (it could be virtual). Otherwise, call the generic method. + return Private::CallClassId::value, T>::get(item); + } +} // namespace gs // Class ids for standard types -gs_specialize_class_id(float, 0) -gs_specialize_class_id(double, 0) -gs_specialize_class_id(long double, 0) -gs_specialize_class_id(int, 0) -gs_specialize_class_id(unsigned, 0) -gs_specialize_class_id(long, 0) -gs_specialize_class_id(long long, 0) -gs_specialize_class_id(unsigned long, 0) -gs_specialize_class_id(unsigned long long, 0) -gs_specialize_class_id(short, 0) -gs_specialize_class_id(unsigned short, 0) -gs_specialize_class_id(bool, 0) -gs_specialize_class_id(char, 0) -gs_specialize_class_id(unsigned char, 0) -gs_specialize_class_id(signed char, 0) -gs_specialize_class_id(void, 0) -gs_specialize_class_id(std::string, 0) - -// Class ids for some standard library templates -// used by this I/O package -gs_specialize_template_id_T(std::less, 0, 1) -gs_specialize_template_id_T(std::equal_to, 0, 1) -gs_specialize_template_id_T(std::allocator, 0, 1) -gs_specialize_template_id_T(std::char_traits, 0, 1) -gs_specialize_template_id_TT(std::vector, 0, 1) -gs_specialize_template_id_TT(std::pair, 0, 2) -gs_specialize_template_id_TTT(std::basic_string, 0, 2) - - -#endif // GENERS_CLASSID_HH_ - +gs_specialize_class_id(float, 0) gs_specialize_class_id(double, 0) gs_specialize_class_id(long double, 0) + gs_specialize_class_id(int, 0) gs_specialize_class_id(unsigned, 0) gs_specialize_class_id(long, 0) + gs_specialize_class_id(long long, 0) gs_specialize_class_id(unsigned long, 0) + gs_specialize_class_id(unsigned long long, 0) gs_specialize_class_id(short, 0) + gs_specialize_class_id(unsigned short, 0) gs_specialize_class_id(bool, 0) + gs_specialize_class_id(char, 0) gs_specialize_class_id(unsigned char, 0) + gs_specialize_class_id(signed char, 0) gs_specialize_class_id(void, 0) + gs_specialize_class_id(std::string, 0) + + // Class ids for some standard library templates + // used by this I/O package + gs_specialize_template_id_T(std::less, 0, 1) gs_specialize_template_id_T(std::equal_to, 0, 1) + gs_specialize_template_id_T(std::allocator, 0, 1) gs_specialize_template_id_T(std::char_traits, 0, 1) + gs_specialize_template_id_TT(std::vector, 0, 1) gs_specialize_template_id_TT(std::pair, 0, 2) + gs_specialize_template_id_TTT(std::basic_string, 0, 2) + +#endif // GENERS_CLASSID_HH_ diff --git a/Alignment/Geners/interface/ClearIfPointer.hh b/Alignment/Geners/interface/ClearIfPointer.hh index 303fe012b9519..43c476e09eb7f 100644 --- a/Alignment/Geners/interface/ClearIfPointer.hh +++ b/Alignment/Geners/interface/ClearIfPointer.hh @@ -2,22 +2,21 @@ #define GENERS_CLEARIFPOINTER_HH_ namespace gs { - template - struct ClearIfPointer - { - static void clear(T&) {} - }; + template + struct ClearIfPointer { + static void clear(T &) {} + }; - template - struct ClearIfPointer - { - static void clear(T*& ptr) {ptr = 0;} - }; + template + struct ClearIfPointer { + static void clear(T *&ptr) { ptr = 0; } + }; - // The following will set object value to 0 if object is a pointer - template - void clearIfPointer(T& obj) {ClearIfPointer::clear(obj);} -} - -#endif // GENERS_CLEARIFPOINTER_HH_ + // The following will set object value to 0 if object is a pointer + template + void clearIfPointer(T &obj) { + ClearIfPointer::clear(obj); + } +} // namespace gs +#endif // GENERS_CLEARIFPOINTER_HH_ diff --git a/Alignment/Geners/interface/ColumnBuffer.hh b/Alignment/Geners/interface/ColumnBuffer.hh index d81574f2e58be..69dde408c347f 100644 --- a/Alignment/Geners/interface/ColumnBuffer.hh +++ b/Alignment/Geners/interface/ColumnBuffer.hh @@ -1,66 +1,58 @@ #ifndef GENERS_COLUMNBUFFER_HH_ #define GENERS_COLUMNBUFFER_HH_ -#include #include +#include #include "Alignment/Geners/interface/CharBuffer.hh" #include "Alignment/Geners/interface/ClassId.hh" namespace gs { - namespace Private { - struct ColumnBuffer - { - inline ColumnBuffer() : firstrow(0), lastrowp1(0), podsize(0) {} - - // The actual buffer - CharBuffer buf; - - // The range of rows stored in the buffer is [firstrow, lastrowp1) - unsigned long firstrow; - unsigned long lastrowp1; - - // The following member will be non-0 if the column - // members are PODs for I/O purposes - unsigned long podsize; - - // If the above member is 0, objects in the buffer may have - // variable size. Because of this, we need to store an offset - // of each object separately. To conserve space, the vector - // of object offsets is not filled for PODs. - std::vector offsets; - - // Methods related to I/O - bool write(std::ostream& os) const; - inline const ClassId& classId() const - { - return static_classId(); - } - - // The "restore" method is special and requires - // use of special references. The reason is the - // following: we will likely store a large number - // of these buffers at a time. Storing the class id - // of CharBuffer every time would be a waste of - // storage space. Because of this, we will assume - // that the code that manages these buffers will - // stash the CharBuffer class id somewhere. - static void restore(const ClassId& id, const ClassId& charBufId, - std::istream& in, ColumnBuffer* buf); - - static inline const char* classname() - {return "gs::Private::ColumnBuffer";} - static inline unsigned version() {return 1;} - - bool operator==(const ColumnBuffer& r) const; - inline bool operator!=(const ColumnBuffer& r) const - {return !(*this == r);} - - private: - static const ClassId& static_classId(); - }; - } -} - -#endif // GENERS_COLUMNBUFFER_HH_ - + namespace Private { + struct ColumnBuffer { + inline ColumnBuffer() : firstrow(0), lastrowp1(0), podsize(0) {} + + // The actual buffer + CharBuffer buf; + + // The range of rows stored in the buffer is [firstrow, lastrowp1) + unsigned long firstrow; + unsigned long lastrowp1; + + // The following member will be non-0 if the column + // members are PODs for I/O purposes + unsigned long podsize; + + // If the above member is 0, objects in the buffer may have + // variable size. Because of this, we need to store an offset + // of each object separately. To conserve space, the vector + // of object offsets is not filled for PODs. + std::vector offsets; + + // Methods related to I/O + bool write(std::ostream &os) const; + inline const ClassId &classId() const { return static_classId(); } + + // The "restore" method is special and requires + // use of special references. The reason is the + // following: we will likely store a large number + // of these buffers at a time. Storing the class id + // of CharBuffer every time would be a waste of + // storage space. Because of this, we will assume + // that the code that manages these buffers will + // stash the CharBuffer class id somewhere. + static void restore(const ClassId &id, const ClassId &charBufId, std::istream &in, ColumnBuffer *buf); + + static inline const char *classname() { return "gs::Private::ColumnBuffer"; } + static inline unsigned version() { return 1; } + + bool operator==(const ColumnBuffer &r) const; + inline bool operator!=(const ColumnBuffer &r) const { return !(*this == r); } + + private: + static const ClassId &static_classId(); + }; + } // namespace Private +} // namespace gs + +#endif // GENERS_COLUMNBUFFER_HH_ diff --git a/Alignment/Geners/interface/CompressedIO.hh b/Alignment/Geners/interface/CompressedIO.hh index ae75b21e8d3a3..be107abd91fa2 100644 --- a/Alignment/Geners/interface/CompressedIO.hh +++ b/Alignment/Geners/interface/CompressedIO.hh @@ -8,90 +8,89 @@ #ifndef GENERS_COMPRESSEDIO_HH_ #define GENERS_COMPRESSEDIO_HH_ -#include "Alignment/Geners/interface/GenericIO.hh" #include "Alignment/Geners/interface/CStringStream.hh" +#include "Alignment/Geners/interface/GenericIO.hh" namespace gs { - // The following function returns "true" on success, "false" on failure - template - bool write_compressed_item(std::ostream& os, const Item& item, - CStringStream::CompressionMode m = CStringStream::ZLIB, - int compressionLevel = -1, unsigned minSizeToCompress = 1024U, - unsigned bufSize = 1048576U); + // The following function returns "true" on success, "false" on failure + template + bool write_compressed_item(std::ostream &os, + const Item &item, + CStringStream::CompressionMode m = CStringStream::ZLIB, + int compressionLevel = -1, + unsigned minSizeToCompress = 1024U, + unsigned bufSize = 1048576U); - template - void restore_compressed_item(std::istream& in, Item* item); + template + void restore_compressed_item(std::istream &in, Item *item); - template - CPP11_auto_ptr read_compressed_item(std::istream& in); -} + template + CPP11_auto_ptr read_compressed_item(std::istream &in); +} // namespace gs namespace gs { - template - inline bool write_compressed_item(std::ostream& os, const Item& item, - const CStringStream::CompressionMode m, - const int compressionLevel, const unsigned minSizeToCompress, - const unsigned bufSize) - { - CStringStream cs(m, compressionLevel, minSizeToCompress, bufSize); - unsigned compressionCode = 0; - long long len = 0; - const std::streampos base = os.tellp(); - write_pod(os, len); - write_pod(os, compressionCode); - if (os.fail() || os.bad()) - return false; - const std::streampos start = os.tellp(); - cs.setSink(os); - if (!write_item(cs, item)) - return false; - cs.flush(); - compressionCode = static_cast(cs.writeCompressed()); - const std::streampos now = os.tellp(); - const std::streamoff off = now - start; - len = off; - os.seekp(base); - write_pod(os, len); - write_pod(os, compressionCode); - os.seekp(now); - return !(cs.fail() || cs.bad() || os.fail() || os.bad()); - } - - template - inline void restore_compressed_item(std::istream& is, Item* item) - { - long long len; - read_pod(is, &len); - unsigned compressionCode; - read_pod(is, &compressionCode); - CStringStream::CompressionMode m = - static_cast(compressionCode); - CStringStream cs(m, -1, 1024U, 1048576U); - cs.readCompressed(is, compressionCode, len); - if (!is.good()) - throw IOReadFailure("In restore_compressed_item: " - "input stream failure"); - restore_item(cs, item); - } - - template - inline CPP11_auto_ptr read_compressed_item(std::istream& is) - { - long long len; - read_pod(is, &len); - unsigned compressionCode; - read_pod(is, &compressionCode); - CStringStream::CompressionMode m = - static_cast(compressionCode); - CStringStream cs(m, -1, 1024U, 1048576U); - cs.readCompressed(is, compressionCode, len); - if (!is.good()) - throw IOReadFailure("In read_compressed_item: " - "input stream failure"); - return read_item(cs); - } -} + template + inline bool write_compressed_item(std::ostream &os, + const Item &item, + const CStringStream::CompressionMode m, + const int compressionLevel, + const unsigned minSizeToCompress, + const unsigned bufSize) { + CStringStream cs(m, compressionLevel, minSizeToCompress, bufSize); + unsigned compressionCode = 0; + long long len = 0; + const std::streampos base = os.tellp(); + write_pod(os, len); + write_pod(os, compressionCode); + if (os.fail() || os.bad()) + return false; + const std::streampos start = os.tellp(); + cs.setSink(os); + if (!write_item(cs, item)) + return false; + cs.flush(); + compressionCode = static_cast(cs.writeCompressed()); + const std::streampos now = os.tellp(); + const std::streamoff off = now - start; + len = off; + os.seekp(base); + write_pod(os, len); + write_pod(os, compressionCode); + os.seekp(now); + return !(cs.fail() || cs.bad() || os.fail() || os.bad()); + } + template + inline void restore_compressed_item(std::istream &is, Item *item) { + long long len; + read_pod(is, &len); + unsigned compressionCode; + read_pod(is, &compressionCode); + CStringStream::CompressionMode m = static_cast(compressionCode); + CStringStream cs(m, -1, 1024U, 1048576U); + cs.readCompressed(is, compressionCode, len); + if (!is.good()) + throw IOReadFailure( + "In restore_compressed_item: " + "input stream failure"); + restore_item(cs, item); + } -#endif // GENERS_COMPRESSEDIO_HH_ + template + inline CPP11_auto_ptr read_compressed_item(std::istream &is) { + long long len; + read_pod(is, &len); + unsigned compressionCode; + read_pod(is, &compressionCode); + CStringStream::CompressionMode m = static_cast(compressionCode); + CStringStream cs(m, -1, 1024U, 1048576U); + cs.readCompressed(is, compressionCode, len); + if (!is.good()) + throw IOReadFailure( + "In read_compressed_item: " + "input stream failure"); + return read_item(cs); + } +} // namespace gs +#endif // GENERS_COMPRESSEDIO_HH_ diff --git a/Alignment/Geners/interface/ContiguousCatalog.hh b/Alignment/Geners/interface/ContiguousCatalog.hh index 8cf135b5938a1..778140b1a0f25 100644 --- a/Alignment/Geners/interface/ContiguousCatalog.hh +++ b/Alignment/Geners/interface/ContiguousCatalog.hh @@ -8,76 +8,71 @@ #include "Alignment/Geners/interface/CPP11_shared_ptr.hh" namespace gs { - class ContiguousCatalog : public AbsCatalog - { - public: - // Default constructor creates an empty catalog - inline ContiguousCatalog(const unsigned long long firstId=1) - : firstId_(firstId ? firstId : 1ULL) {} - inline virtual ~ContiguousCatalog() {} - - inline unsigned long long size() const {return records_.size();} - inline unsigned long long smallestId() const {return firstId_;} - inline unsigned long long largestId() const - {return firstId_ + records_.size() - 1;} - inline bool isContiguous() const {return true;} - - CPP11_shared_ptr retrieveEntry( - unsigned long long id) const; - - bool retrieveStreampos( - unsigned long long id, unsigned* compressionCode, - unsigned long long* length, std::streampos* pos) const; - - // Add a new entry without an id (id will be generated internally - // and returned) - unsigned long long makeEntry(const ItemDescriptor& descriptor, - unsigned compressionCode, - unsigned long long itemLength, - const ItemLocation& loc, - unsigned long long offset=0ULL); - - inline const CatalogEntry* lastEntryMade() const - {return lastEntry_.get();} - - // Search for matching entries based on item name and category - void search(const SearchSpecifier& namePattern, - const SearchSpecifier& categoryPattern, - std::vector* idsFound) const; - - // Methods needed for I/O - virtual ClassId classId() const {return ClassId(*this);} - virtual bool write(std::ostream& os) const; - - static inline const char* classname() {return "gs::ContiguousCatalog";} - static inline unsigned version() {return 2;} - static ContiguousCatalog* read(const ClassId& id, std::istream& in); - - protected: - virtual bool isEqual(const AbsCatalog&) const; - - private: - typedef CPP11_shared_ptr SPtr; - - // In the following multimap, item name is the key and - // item id is the value - typedef std::multimap NameMap; - - // In the following map, item category is the key - typedef std::map RecordMap; - - void findByName(const NameMap& nmap, - const SearchSpecifier& namePattern, - std::vector* found) const; - - std::vector records_; - unsigned long long firstId_; - RecordMap recordMap_; - SPtr lastEntry_; - - static ContiguousCatalog* read_v1(std::istream& in); - }; -} - -#endif // GENERS_CONTIGUOUSCATALOG_HH_ - + class ContiguousCatalog : public AbsCatalog { + public: + // Default constructor creates an empty catalog + inline ContiguousCatalog(const unsigned long long firstId = 1) : firstId_(firstId ? firstId : 1ULL) {} + inline ~ContiguousCatalog() override {} + + inline unsigned long long size() const override { return records_.size(); } + inline unsigned long long smallestId() const override { return firstId_; } + inline unsigned long long largestId() const override { return firstId_ + records_.size() - 1; } + inline bool isContiguous() const override { return true; } + + CPP11_shared_ptr retrieveEntry(unsigned long long id) const override; + + bool retrieveStreampos(unsigned long long id, + unsigned *compressionCode, + unsigned long long *length, + std::streampos *pos) const override; + + // Add a new entry without an id (id will be generated internally + // and returned) + unsigned long long makeEntry(const ItemDescriptor &descriptor, + unsigned compressionCode, + unsigned long long itemLength, + const ItemLocation &loc, + unsigned long long offset = 0ULL) override; + + inline const CatalogEntry *lastEntryMade() const override { return lastEntry_.get(); } + + // Search for matching entries based on item name and category + void search(const SearchSpecifier &namePattern, + const SearchSpecifier &categoryPattern, + std::vector *idsFound) const override; + + // Methods needed for I/O + ClassId classId() const override { return ClassId(*this); } + bool write(std::ostream &os) const override; + + static inline const char *classname() { return "gs::ContiguousCatalog"; } + static inline unsigned version() { return 2; } + static ContiguousCatalog *read(const ClassId &id, std::istream &in); + + protected: + bool isEqual(const AbsCatalog &) const override; + + private: + typedef CPP11_shared_ptr SPtr; + + // In the following multimap, item name is the key and + // item id is the value + typedef std::multimap NameMap; + + // In the following map, item category is the key + typedef std::map RecordMap; + + void findByName(const NameMap &nmap, + const SearchSpecifier &namePattern, + std::vector *found) const; + + std::vector records_; + unsigned long long firstId_; + RecordMap recordMap_; + SPtr lastEntry_; + + static ContiguousCatalog *read_v1(std::istream &in); + }; +} // namespace gs + +#endif // GENERS_CONTIGUOUSCATALOG_HH_ diff --git a/Alignment/Geners/interface/GeneralCatalog.hh b/Alignment/Geners/interface/GeneralCatalog.hh index 7a869c3b2fa74..4fa065ec9cf84 100644 --- a/Alignment/Geners/interface/GeneralCatalog.hh +++ b/Alignment/Geners/interface/GeneralCatalog.hh @@ -6,89 +6,85 @@ #include "Alignment/Geners/interface/AbsCatalog.hh" namespace gs { - class GeneralCatalog : public AbsCatalog - { - public: - // Default constructor creates an empty catalog - GeneralCatalog(); - inline virtual ~GeneralCatalog() {} - - inline unsigned long long size() const {return records_.size();} - inline unsigned long long smallestId() const {return smallestId_;} - inline unsigned long long largestId() const {return largestId_;} - inline bool isContiguous() const {return false;} - inline bool itemExists(const unsigned long long id) const - {return records_.find(id) != records_.end();} - - CPP11_shared_ptr retrieveEntry( - const unsigned long long id) const; - - bool retrieveStreampos( - unsigned long long id, unsigned* compressionCode, - unsigned long long* length, std::streampos* pos) const; - - // Add a new entry without an id (id will be generated internally - // and returned) - unsigned long long makeEntry(const ItemDescriptor& descriptor, - unsigned compressionCode, - unsigned long long itemLength, - const ItemLocation& loc, - unsigned long long offset=0ULL); - - inline const CatalogEntry* lastEntryMade() const - {return lastEntry_.get();} - - // Add a new entry with id (presumably, from another catalog). - // Returns "true" on success. The entry is not included (and "false" - // is returned) in case the entry with the given id already exists. - bool addEntry(CPP11_shared_ptr ptr); - - // Remove an entry with the given id. "false" is returned in case - // an entry with the specified id does not exist. - bool removeEntry(unsigned long long id); - - // Search for matching entries based on item name and category - void search(const SearchSpecifier& namePattern, - const SearchSpecifier& categoryPattern, - std::vector* idsFound) const; - - // Methods needed for I/O - virtual ClassId classId() const {return ClassId(*this);} - virtual bool write(std::ostream& os) const; - - static inline const char* classname() {return "gs::GeneralCatalog";} - static inline unsigned version() {return 2;} - static GeneralCatalog* read(const ClassId& id, std::istream& in); - - protected: - virtual bool isEqual(const AbsCatalog&) const; - - private: - typedef CPP11_shared_ptr SPtr; - - // In the following multimap, item name is the key and - // catalog entry pointer is the value - typedef std::multimap NameMap; - - // In the following map, item category is the key - typedef std::map RecordMap; - - // In the following map, item id is the key - typedef std::map IdMap; - - void findByName(const NameMap& nmap, - const SearchSpecifier& namePattern, - std::vector* found) const; - - IdMap records_; - RecordMap recordMap_; - unsigned long long smallestId_; - unsigned long long largestId_; - SPtr lastEntry_; - - static GeneralCatalog* read_v1(std::istream& in); - }; -} - -#endif // GENERS_GENERALCATALOG_HH_ - + class GeneralCatalog : public AbsCatalog { + public: + // Default constructor creates an empty catalog + GeneralCatalog(); + inline ~GeneralCatalog() override {} + + inline unsigned long long size() const override { return records_.size(); } + inline unsigned long long smallestId() const override { return smallestId_; } + inline unsigned long long largestId() const override { return largestId_; } + inline bool isContiguous() const override { return false; } + inline bool itemExists(const unsigned long long id) const override { return records_.find(id) != records_.end(); } + + CPP11_shared_ptr retrieveEntry(const unsigned long long id) const override; + + bool retrieveStreampos(unsigned long long id, + unsigned *compressionCode, + unsigned long long *length, + std::streampos *pos) const override; + + // Add a new entry without an id (id will be generated internally + // and returned) + unsigned long long makeEntry(const ItemDescriptor &descriptor, + unsigned compressionCode, + unsigned long long itemLength, + const ItemLocation &loc, + unsigned long long offset = 0ULL) override; + + inline const CatalogEntry *lastEntryMade() const override { return lastEntry_.get(); } + + // Add a new entry with id (presumably, from another catalog). + // Returns "true" on success. The entry is not included (and "false" + // is returned) in case the entry with the given id already exists. + bool addEntry(CPP11_shared_ptr ptr); + + // Remove an entry with the given id. "false" is returned in case + // an entry with the specified id does not exist. + bool removeEntry(unsigned long long id); + + // Search for matching entries based on item name and category + void search(const SearchSpecifier &namePattern, + const SearchSpecifier &categoryPattern, + std::vector *idsFound) const override; + + // Methods needed for I/O + ClassId classId() const override { return ClassId(*this); } + bool write(std::ostream &os) const override; + + static inline const char *classname() { return "gs::GeneralCatalog"; } + static inline unsigned version() { return 2; } + static GeneralCatalog *read(const ClassId &id, std::istream &in); + + protected: + bool isEqual(const AbsCatalog &) const override; + + private: + typedef CPP11_shared_ptr SPtr; + + // In the following multimap, item name is the key and + // catalog entry pointer is the value + typedef std::multimap NameMap; + + // In the following map, item category is the key + typedef std::map RecordMap; + + // In the following map, item id is the key + typedef std::map IdMap; + + void findByName(const NameMap &nmap, + const SearchSpecifier &namePattern, + std::vector *found) const; + + IdMap records_; + RecordMap recordMap_; + unsigned long long smallestId_; + unsigned long long largestId_; + SPtr lastEntry_; + + static GeneralCatalog *read_v1(std::istream &in); + }; +} // namespace gs + +#endif // GENERS_GENERALCATALOG_HH_ diff --git a/Alignment/Geners/interface/GenericIO.hh b/Alignment/Geners/interface/GenericIO.hh index 9cba477be518c..95e0848f0d1e3 100644 --- a/Alignment/Geners/interface/GenericIO.hh +++ b/Alignment/Geners/interface/GenericIO.hh @@ -1,884 +1,693 @@ -// +// // Top-level API for serializing and deserializing arbitrary classes // #ifndef GENERS_GENERICIO_HH_ #define GENERS_GENERICIO_HH_ -#include "Alignment/Geners/interface/binaryIO.hh" #include "Alignment/Geners/interface/IOPointeeType.hh" +#include "Alignment/Geners/interface/binaryIO.hh" -#include "Alignment/Geners/interface/StrippedType.hh" #include "Alignment/Geners/interface/ArrayAdaptor.hh" #include "Alignment/Geners/interface/ClearIfPointer.hh" +#include "Alignment/Geners/interface/StrippedType.hh" namespace gs { - /** - // Generic top-level function which can be used to write out - // almost anything. Intended mainly for use inside "write" - // methods of user-developed classes and templates. Returns - // "true" if the argument item is successfully written out. - */ - template - inline bool write_item(Stream& os, const Item& item, - const bool writeClassId=true) - { - char* ps = 0; - return process_const_item(item, os, ps, writeClassId); - } - - /** - // A function for overwriting existing objects (which usually live - // on the stack). This function actually skips couple levels of - // indirection which would be generated by a call to "process_item". - */ - template - inline void restore_item(Stream& is, Item* item, - const bool readClassId=true) - { - typedef std::vector State; - assert(item); - State state; - const bool status = GenericReader::ISPOINTER> >::process( - item, is, &state, readClassId); - if (is.fail()) - throw IOReadFailure("In gs::restore_item: input stream failure"); - if (!status) - throw IOInvalidData("In gs::restore_item: invalid input stream data"); - } - - /** - // Function for returning objects on the heap. This function - // requires explicit specification of its first template - // parameter, the type of the item to read. This function - // either succeeds or throws an exception which inherits - // from std::exception. - */ - template - inline CPP11_auto_ptr read_item(Stream& is, const bool readClassId=true) - { - typedef std::vector State; - Item* item = 0; - State state; - const bool status = GenericReader::ISNULLPOINTER> >::process( - item, is, &state, readClassId); - CPP11_auto_ptr ptr(item); - if (is.fail()) - throw IOReadFailure("In gs::read_item: input stream failure"); - if (!status || item == 0) - throw IOInvalidData("In gs::read_item: invalid input stream data"); - return ptr; - } - - /** - // Generic top-level function for writing arrays. Note that - // the length of the array is not written out and that the - // length must be known in advance in the scope from which - // the companion function, "read_array", is called. "true" - // is returned upon success, "false" on failure. - */ - template - inline bool write_array(Stream& os, Item* items, const std::size_t length) - { - char* ps = 0; - return process_const_item( - ArrayAdaptor(items, length), os, ps, false); - } - - /** - // Function for deserializing arrays. The length of the array - // must be known in the scope from which this function is invoked. - */ - template - inline void read_array(Stream& is, Item* items, const std::size_t length) - { - typedef std::vector State; - State state; - ArrayAdaptor adap(items, length); - const bool st = process_item(adap, is, &state, false); - if (is.fail()) - throw IOReadFailure("In gs::read_array: input stream failure"); - if (!st) - throw IOInvalidData("In gs::read_array: invalid input stream data"); - } -} + /** +// Generic top-level function which can be used to write out +// almost anything. Intended mainly for use inside "write" +// methods of user-developed classes and templates. Returns +// "true" if the argument item is successfully written out. +*/ + template + inline bool write_item(Stream &os, const Item &item, const bool writeClassId = true) { + char *ps = nullptr; + return process_const_item(item, os, ps, writeClassId); + } + + /** +// A function for overwriting existing objects (which usually live +// on the stack). This function actually skips couple levels of +// indirection which would be generated by a call to "process_item". +*/ + template + inline void restore_item(Stream &is, Item *item, const bool readClassId = true) { + typedef std::vector State; + assert(item); + State state; + const bool status = GenericReader::ISPOINTER>>::process( + item, is, &state, readClassId); + if (is.fail()) + throw IOReadFailure("In gs::restore_item: input stream failure"); + if (!status) + throw IOInvalidData("In gs::restore_item: invalid input stream data"); + } + + /** +// Function for returning objects on the heap. This function +// requires explicit specification of its first template +// parameter, the type of the item to read. This function +// either succeeds or throws an exception which inherits +// from std::exception. +*/ + template + inline CPP11_auto_ptr read_item(Stream &is, const bool readClassId = true) { + typedef std::vector State; + Item *item = nullptr; + State state; + const bool status = GenericReader::ISNULLPOINTER>>::process( + item, is, &state, readClassId); + CPP11_auto_ptr ptr(item); + if (is.fail()) + throw IOReadFailure("In gs::read_item: input stream failure"); + if (!status || item == nullptr) + throw IOInvalidData("In gs::read_item: invalid input stream data"); + return ptr; + } + + /** +// Generic top-level function for writing arrays. Note that +// the length of the array is not written out and that the +// length must be known in advance in the scope from which +// the companion function, "read_array", is called. "true" +// is returned upon success, "false" on failure. +*/ + template + inline bool write_array(Stream &os, Item *items, const std::size_t length) { + char *ps = nullptr; + return process_const_item(ArrayAdaptor(items, length), os, ps, false); + } + + /** +// Function for deserializing arrays. The length of the array +// must be known in the scope from which this function is invoked. +*/ + template + inline void read_array(Stream &is, Item *items, const std::size_t length) { + typedef std::vector State; + State state; + ArrayAdaptor adap(items, length); + const bool st = process_item(adap, is, &state, false); + if (is.fail()) + throw IOReadFailure("In gs::read_array: input stream failure"); + if (!st) + throw IOInvalidData("In gs::read_array: invalid input stream data"); + } +} // namespace gs namespace gs { - template - struct GenericWriter2 : public GenericWriter {}; - - template - struct GenericReader2 : public GenericReader {}; - - // The reader and writer templates should be specialized - // (that is, their "process" function should be defined) using - // the following processing stage types from "ProcessItem.hh": - // - // Int2Type::ISPOD> (+readIntoPtr) - // InContainerHeader - // InContainerFooter - // InContainerSize - // InPODArray - // Int2Type::ISWRITABLE> - // Int2Type::ISPOINTER> - // Int2Type::ISSHAREDPTR> - // Int2Type::ISPAIR> (+readIntoPtr) - // Int2Type::ISSTRING> (+readIntoPtr) - // - // In addition, the reader should be specialized for the following - // types: - // - // InContainerCycle (process only) - // Int2Type::ISSTDCONTAINER> (readIntoPtr only) - // Int2Type::ISHEAPREADABLE> (readIntoPtr only) - // Int2Type::ISPLACEREADABLE> (readIntoPtr only) - // - // The resulting code is essentially one big compile-time state - // machine with two main switching hubs: "process_item" function - // from "ProcessItem.hh" and "process" function in GenericReader - // template specialized for bare pointers. - // - - //=================================================================== - // - // Processing of a POD - // - //=================================================================== - template - struct GenericWriter::ISPOD> > - { - inline static bool process(const T& s, Stream& os, State*, - const bool processClassId) - { - static const ClassId current(ClassId::makeId()); - const bool status = processClassId ? current.write(os) : true; - if (status) - write_pod(os, s); - return status && !os.fail(); - } - }; - - template - struct GenericReader::ISPOD> > - { - inline static bool readIntoPtr(T*& ptr, Stream& str, State*, - const bool processClassId) - { - CPP11_auto_ptr myptr; - if (ptr == 0) - myptr = CPP11_auto_ptr(new T()); - if (processClassId) - { - static const ClassId current(ClassId::makeId()); - ClassId id(str, 1); - current.ensureSameName(id); - } - read_pod(str, ptr ? ptr : myptr.get()); - if (str.fail()) - return false; - if (ptr == 0) - ptr = myptr.release(); - return true; - } - - inline static bool process(T& s, Stream& os, State* st, - const bool processClassId) - { - T* ps = &s; - return readIntoPtr(ps, os, st, processClassId); - } - }; - - - //=================================================================== - // - // Processing of a container header - // - //=================================================================== - template - struct GenericWriter - { - inline static bool process(const Container&, Stream& os, State*, - const bool processClassId) - { - typedef typename Container::value_type T; - - static const ClassId current(ClassId::makeId()); - bool status = processClassId ? current.write(os) : true; - - // Maybe we do not have to write out the container class id, - // but we do have to write out the item class id -- unless the - // container is just an array of pods. Otherwise we might not - // be able to read the container items back. - if (status && !(IOTraits::IsPOD && - IOTraits::IsContiguous)) - { - static const ClassId itemId(ClassId::makeId()); - status = itemId.write(os); - } - return status; - } - }; - - template - struct GenericReader - { - inline static bool process(Container& a, Stream& is, State* state, - const bool processClassId) - { - typedef typename Container::value_type T; - - if (processClassId) - { - static const ClassId current(ClassId::makeId()); - ClassId id(is, 1); - current.ensureSameName(id); - } - a.clear(); - if (!(IOTraits::IsPOD && IOTraits::IsContiguous)) - { - ClassId id(is, 1); - - // Remember the class id of the contained items. - // We need to do this even if the id is invalid because - // the id will be popped back when the "InContainerFooter" - // stage is processed. - state->push_back(id); - } - return true; - } - }; - - - //=================================================================== - // - // Processing of a container footer - // - //=================================================================== - template - struct GenericWriter - { - inline static bool process(const Container&, Stream&, State*, bool) - {return true;} - }; - - template - struct GenericReader - { - inline static bool process(Container&, Stream&, State* state, bool) - { - typedef typename Container::value_type T; - if (!(IOTraits::IsPOD && IOTraits::IsContiguous)) - state->pop_back(); - return true; - } - }; - - - //=================================================================== - // - // Processing of container size - // - //=================================================================== - template - struct GenericWriter - { - inline static bool process(const std::size_t& sz, Stream& os, State*, - bool /* processClassId */) - { - write_pod(os, sz); - return !os.fail(); - } - }; - - template - struct GenericReader - { - inline static bool process(std::size_t& sz, Stream& is, State*, - bool /* processClassId */) - { - read_pod(is, &sz); - return !is.fail(); - } - }; - - - //=================================================================== - // - // Processing of data in contiguous POD containers - // - //=================================================================== - template - struct GenericWriter - { - inline static bool process(const ArrayLike& a, Stream& os, - State*, bool) - { - const std::size_t len = a.size(); - write_pod(os, len); - if (len) - write_pod_array(os, &a[0], len); - return !os.fail(); - } - }; - - template - struct GenericReader - { - inline static bool process(ArrayLike& a, Stream& s, State*, bool) - { - std::size_t len = 0; - read_pod(s, &len); - if (s.fail()) - return false; - a.resize(len); - if (!len) - return true; - read_pod_array(s, &a[0], len); - return !s.fail(); - } - }; - - //=================================================================== - // - // Processing of "writable" objects - // - //=================================================================== - template - struct GenericWriter::ISWRITABLE> > - { - inline static bool process(const T& s, Stream& os, State*, - const bool processClassId) - { - return (processClassId ? s.classId().write(os) : true) && - s.write(os) && !os.fail(); - } - }; - - template - struct GenericReader::ISWRITABLE> > - { - inline static bool process(T& s, Stream& is, State* st, - const bool processClassId) - { - typedef IOTraits M; - T* ps = &s; - return GenericReader >::readIntoPtr(ps, is, st, processClassId); - } - }; - - - //=================================================================== - // - // Processing of bare pointers. - // - // The writer simply dereferences the pointer. - // - // In the reader, we want to read stuff into the pointee object, - // or want to create an item on the heap if the pointer value is 0. - // - //=================================================================== - template - struct GenericWriter::ISPOINTER> > - { - inline static bool process(const Ptr& ptr, Stream& os, State* s, - const bool processClassId) - { - // Can't have pointers to pointers. This is a design - // decision which simplifies things considerably. - typedef typename IOPointeeType::type Pointee; - typedef IOTraits M; - static_assert((M::Signature & (M::ISPOINTER | - M::ISSHAREDPTR)) == 0, "can not write pointers to pointers"); - - // Can't have NULL pointers either. But this - // can be checked at run time only. - assert(ptr); - return process_const_item( - *ptr, os, s, processClassId); - } - }; - - template - struct GenericReader::ISPOINTER> > - { - inline static bool process(Ptr& ptr, Stream& str, State* s, - const bool processClassId) - { - // We need to figure out the type of the pointee - // and make a swich depending on that type. - // Note that the pointee itself can not be a pointer. - typedef typename IOPointeeType::type Pointee; - typedef IOTraits M; - static_assert((M::Signature & (M::ISPOINTER | - M::ISSHAREDPTR)) == 0, "can not read pointers to pointers"); - - return GenericReader >::readIntoPtr(ptr, str, s, processClassId); - } - }; - - template - struct GenericReader::ISNULLPOINTER> > - { - inline static bool process(Ptr& ptr, Stream& str, State* s, - const bool processClassId) - { - // We need to figure out the type of the pointee - // and make a swich depending on that type. - // Note that the pointee itself can not be a pointer. - typedef typename IOPointeeType::type Pointee; - typedef IOTraits M; - static_assert((M::Signature & (M::ISNULLPOINTER | - M::ISSHAREDPTR)) == 0, "can not read pointers to pointers"); - - return GenericReader >::readIntoPtr(ptr, str, s, processClassId); - } - }; - - - //=================================================================== - // - // Processing of shared pointers -- similar logic to pointers. - // For the reader, handling of the shared pointer is reduced - // to handling of a normal pointer with 0 value. - // - //=================================================================== - template - struct GenericWriter::ISSHAREDPTR> > - { - inline static bool process(const Ptr& ptr, Stream& os, State* s, - const bool processClassId) - { - typedef typename Ptr::element_type Pointee; - typedef IOTraits M; - static_assert((M::Signature & (M::ISPOINTER | - M::ISSHAREDPTR)) == 0, "can not write pointers to pointers"); - assert(ptr.get()); - return process_const_item( - *ptr, os, s, processClassId); - } - }; - - template - struct GenericReader::ISSHAREDPTR> > - { - inline static bool process(ShPtr& a, Stream& str, State* s, - const bool processClassId) - { - typedef typename ShPtr::element_type Pointee; - typedef IOTraits M; - static_assert((M::Signature & (M::ISPOINTER | - M::ISSHAREDPTR)) == 0, "can not read pointers to pointers"); - Pointee* ptr = 0; - const bool status = GenericReader::ISNULLPOINTER> >::process( - ptr, str, s, processClassId); - if (status) - { - assert(ptr); - a = CPP11_shared_ptr(ptr); - return true; - } - else - { - delete ptr; - return false; - } - } - }; - - - //=================================================================== - // - // Processing of std::pair - // - //=================================================================== - template - struct GenericWriter::ISPAIR> > - { - inline static bool process(const T& s, Stream& os, State* st, - const bool processClassId) - { - // Here is a little problem: in this scope "GenericWriter" - // means GenericWriter::ISPAIR> > - // However, we want to use the whole template, unspecialized. - // This is why "GenericWriter2" is introduced: a copy of - // "GenericWriter" via public inheritance. - static const ClassId current(ClassId::makeId()); - return (processClassId ? current.write(os) : true) && - process_const_item(s.first, os, st, false) && - process_const_item(s.second, os, st, false); - } - }; - - template - struct GenericReader::ISPAIR> > - { - inline static bool readIntoPtr(T*& ptr, Stream& str, State* s, - const bool processClassId) - { - CPP11_auto_ptr myptr; - if (ptr == 0) - { - myptr = CPP11_auto_ptr(new T()); - clearIfPointer(myptr.get()->first); - clearIfPointer(myptr.get()->second); - } - std::vector > itemIds; - if (processClassId) - { - static const ClassId current(ClassId::makeId()); - ClassId pairId(str, 1); - current.ensureSameName(pairId); - pairId.templateParameters(&itemIds); - assert(itemIds.size() == 2U); - } - else - { - assert(!s->empty()); - s->back().templateParameters(&itemIds); - if (itemIds.size() != 2U) - { - std::string err("In gs::GenericReader::readIntoPtr: " - "bad class id for std::pair on the " - "class id stack: "); - err += s->back().id(); - throw IOInvalidData(err); - } - } - if (!(process_item( - (ptr ? ptr : myptr.get())->first,str,&itemIds[0],false) && - process_item( - (ptr ? ptr : myptr.get())->second,str,&itemIds[1],false))) - return false; - if (ptr == 0) - ptr = myptr.release(); - return true; - } + template + struct GenericWriter2 : public GenericWriter {}; + + template + struct GenericReader2 : public GenericReader {}; + + // The reader and writer templates should be specialized + // (that is, their "process" function should be defined) using + // the following processing stage types from "ProcessItem.hh": + // + // Int2Type::ISPOD> (+readIntoPtr) + // InContainerHeader + // InContainerFooter + // InContainerSize + // InPODArray + // Int2Type::ISWRITABLE> + // Int2Type::ISPOINTER> + // Int2Type::ISSHAREDPTR> + // Int2Type::ISPAIR> (+readIntoPtr) + // Int2Type::ISSTRING> (+readIntoPtr) + // + // In addition, the reader should be specialized for the following + // types: + // + // InContainerCycle (process only) + // Int2Type::ISSTDCONTAINER> (readIntoPtr only) + // Int2Type::ISHEAPREADABLE> (readIntoPtr only) + // Int2Type::ISPLACEREADABLE> (readIntoPtr only) + // + // The resulting code is essentially one big compile-time state + // machine with two main switching hubs: "process_item" function + // from "ProcessItem.hh" and "process" function in GenericReader + // template specialized for bare pointers. + // + + //=================================================================== + // + // Processing of a POD + // + //=================================================================== + template + struct GenericWriter::ISPOD>> { + inline static bool process(const T &s, Stream &os, State *, const bool processClassId) { + static const ClassId current(ClassId::makeId()); + const bool status = processClassId ? current.write(os) : true; + if (status) + write_pod(os, s); + return status && !os.fail(); + } + }; + + template + struct GenericReader::ISPOD>> { + inline static bool readIntoPtr(T *&ptr, Stream &str, State *, const bool processClassId) { + CPP11_auto_ptr myptr; + if (ptr == 0) + myptr = CPP11_auto_ptr(new T()); + if (processClassId) { + static const ClassId current(ClassId::makeId()); + ClassId id(str, 1); + current.ensureSameName(id); + } + read_pod(str, ptr ? ptr : myptr.get()); + if (str.fail()) + return false; + if (ptr == 0) + ptr = myptr.release(); + return true; + } - inline static bool process(T& s, Stream& os, State* st, - const bool processClassId) - { - T* ps = &s; - return readIntoPtr(ps, os, st, processClassId); - } - }; - - - //=================================================================== - // - // Processing of std::string - // - //=================================================================== - template - struct GenericWriter::ISSTRING> > - { - inline static bool process(const std::string& s, Stream& os, State*, - const bool processClassId) - { - static const ClassId current(ClassId::makeId()); - const bool status = processClassId ? current.write(os) : true; - if (status) - write_string(os, s); - return status && !os.fail(); - } - }; - - template - struct GenericReader::ISSTRING> > - { - inline static bool readIntoPtr(std::string*& ptr, Stream& is, - State* , const bool processClassId) - { - CPP11_auto_ptr myptr; - if (ptr == 0) - myptr = CPP11_auto_ptr(new std::string()); - if (processClassId) - { - static const ClassId current(ClassId::makeId()); - ClassId id(is, 1); - current.ensureSameName(id); - } - read_string(is, ptr ? ptr : myptr.get()); - if (is.fail()) - return false; - if (ptr == 0) - ptr = myptr.release(); - return true; - } + inline static bool process(T &s, Stream &os, State *st, const bool processClassId) { + T *ps = &s; + return readIntoPtr(ps, os, st, processClassId); + } + }; + + //=================================================================== + // + // Processing of a container header + // + //=================================================================== + template + struct GenericWriter { + inline static bool process(const Container &, Stream &os, State *, const bool processClassId) { + typedef typename Container::value_type T; + + static const ClassId current(ClassId::makeId()); + bool status = processClassId ? current.write(os) : true; + + // Maybe we do not have to write out the container class id, + // but we do have to write out the item class id -- unless the + // container is just an array of pods. Otherwise we might not + // be able to read the container items back. + if (status && !(IOTraits::IsPOD && IOTraits::IsContiguous)) { + static const ClassId itemId(ClassId::makeId()); + status = itemId.write(os); + } + return status; + } + }; + + template + struct GenericReader { + inline static bool process(Container &a, Stream &is, State *state, const bool processClassId) { + typedef typename Container::value_type T; + + if (processClassId) { + static const ClassId current(ClassId::makeId()); + ClassId id(is, 1); + current.ensureSameName(id); + } + a.clear(); + if (!(IOTraits::IsPOD && IOTraits::IsContiguous)) { + ClassId id(is, 1); + + // Remember the class id of the contained items. + // We need to do this even if the id is invalid because + // the id will be popped back when the "InContainerFooter" + // stage is processed. + state->push_back(id); + } + return true; + } + }; + + //=================================================================== + // + // Processing of a container footer + // + //=================================================================== + template + struct GenericWriter { + inline static bool process(const Container &, Stream &, State *, bool) { return true; } + }; + + template + struct GenericReader { + inline static bool process(Container &, Stream &, State *state, bool) { + typedef typename Container::value_type T; + if (!(IOTraits::IsPOD && IOTraits::IsContiguous)) + state->pop_back(); + return true; + } + }; + + //=================================================================== + // + // Processing of container size + // + //=================================================================== + template + struct GenericWriter { + inline static bool process(const std::size_t &sz, Stream &os, State *, bool /* processClassId */) { + write_pod(os, sz); + return !os.fail(); + } + }; - inline static bool process(std::string& s, Stream& is, State* st, - const bool processClassId) - { - std::string* ptr = &s; - return readIntoPtr(ptr, is, st, processClassId); - } - }; - - - //=================================================================== - // - // Processing of container readout - // - //=================================================================== - template - struct GenericReader - { - private: - typedef typename Container::value_type item_type; - typedef IOTraits M; - - // Item is a simple pointer - inline static bool process2(Container& obj, Stream& is, - State* st, const std::size_t itemN, - Int2Type<1>) - { - item_type ptr = 0; - const bool status = GenericReader::ISNULLPOINTER> >::process( - ptr, is, st, true); - if (status) - { - assert(ptr); - InsertContainerItem::insert(obj, ptr, itemN); - } - else - delete ptr; - return status; - } + template + struct GenericReader { + inline static bool process(std::size_t &sz, Stream &is, State *, bool /* processClassId */) { + read_pod(is, &sz); + return !is.fail(); + } + }; + + //=================================================================== + // + // Processing of data in contiguous POD containers + // + //=================================================================== + template + struct GenericWriter { + inline static bool process(const ArrayLike &a, Stream &os, State *, bool) { + const std::size_t len = a.size(); + write_pod(os, len); + if (len) + write_pod_array(os, &a[0], len); + return !os.fail(); + } + }; + + template + struct GenericReader { + inline static bool process(ArrayLike &a, Stream &s, State *, bool) { + std::size_t len = 0; + read_pod(s, &len); + if (s.fail()) + return false; + a.resize(len); + if (!len) + return true; + read_pod_array(s, &a[0], len); + return !s.fail(); + } + }; + + //=================================================================== + // + // Processing of "writable" objects + // + //=================================================================== + template + struct GenericWriter::ISWRITABLE>> { + inline static bool process(const T &s, Stream &os, State *, const bool processClassId) { + return (processClassId ? s.classId().write(os) : true) && s.write(os) && !os.fail(); + } + }; + + template + struct GenericReader::ISWRITABLE>> { + inline static bool process(T &s, Stream &is, State *st, const bool processClassId) { + typedef IOTraits M; + T *ps = &s; + return GenericReader>:: + readIntoPtr(ps, is, st, processClassId); + } + }; + + //=================================================================== + // + // Processing of bare pointers. + // + // The writer simply dereferences the pointer. + // + // In the reader, we want to read stuff into the pointee object, + // or want to create an item on the heap if the pointer value is 0. + // + //=================================================================== + template + struct GenericWriter::ISPOINTER>> { + inline static bool process(const Ptr &ptr, Stream &os, State *s, const bool processClassId) { + // Can't have pointers to pointers. This is a design + // decision which simplifies things considerably. + typedef typename IOPointeeType::type Pointee; + typedef IOTraits M; + static_assert((M::Signature & (M::ISPOINTER | M::ISSHAREDPTR)) == 0, "can not write pointers to pointers"); + + // Can't have NULL pointers either. But this + // can be checked at run time only. + assert(ptr); + return process_const_item(*ptr, os, s, processClassId); + } + }; + + template + struct GenericReader::ISPOINTER>> { + inline static bool process(Ptr &ptr, Stream &str, State *s, const bool processClassId) { + // We need to figure out the type of the pointee + // and make a swich depending on that type. + // Note that the pointee itself can not be a pointer. + typedef typename IOPointeeType::type Pointee; + typedef IOTraits M; + static_assert((M::Signature & (M::ISPOINTER | M::ISSHAREDPTR)) == 0, "can not read pointers to pointers"); + + return GenericReader< + Stream, + State, + Pointee, + Int2Type>::readIntoPtr(ptr, str, s, processClassId); + } + }; + + template + struct GenericReader::ISNULLPOINTER>> { + inline static bool process(Ptr &ptr, Stream &str, State *s, const bool processClassId) { + // We need to figure out the type of the pointee + // and make a swich depending on that type. + // Note that the pointee itself can not be a pointer. + typedef typename IOPointeeType::type Pointee; + typedef IOTraits M; + static_assert((M::Signature & (M::ISNULLPOINTER | M::ISSHAREDPTR)) == 0, "can not read pointers to pointers"); + + return GenericReader< + Stream, + State, + Pointee, + Int2Type>::readIntoPtr(ptr, str, s, processClassId); + } + }; + + //=================================================================== + // + // Processing of shared pointers -- similar logic to pointers. + // For the reader, handling of the shared pointer is reduced + // to handling of a normal pointer with 0 value. + // + //=================================================================== + template + struct GenericWriter::ISSHAREDPTR>> { + inline static bool process(const Ptr &ptr, Stream &os, State *s, const bool processClassId) { + typedef typename Ptr::element_type Pointee; + typedef IOTraits M; + static_assert((M::Signature & (M::ISPOINTER | M::ISSHAREDPTR)) == 0, "can not write pointers to pointers"); + assert(ptr.get()); + return process_const_item(*ptr, os, s, processClassId); + } + }; + + template + struct GenericReader::ISSHAREDPTR>> { + inline static bool process(ShPtr &a, Stream &str, State *s, const bool processClassId) { + typedef typename ShPtr::element_type Pointee; + typedef IOTraits M; + static_assert((M::Signature & (M::ISPOINTER | M::ISSHAREDPTR)) == 0, "can not read pointers to pointers"); + Pointee *ptr = 0; + const bool status = GenericReader::ISNULLPOINTER>>::process( + ptr, str, s, processClassId); + if (status) { + assert(ptr); + a = CPP11_shared_ptr(ptr); + return true; + } else { + delete ptr; + return false; + } + } + }; + + //=================================================================== + // + // Processing of std::pair + // + //=================================================================== + template + struct GenericWriter::ISPAIR>> { + inline static bool process(const T &s, Stream &os, State *st, const bool processClassId) { + // Here is a little problem: in this scope "GenericWriter" + // means GenericWriter::ISPAIR> > + // However, we want to use the whole template, unspecialized. + // This is why "GenericWriter2" is introduced: a copy of + // "GenericWriter" via public inheritance. + static const ClassId current(ClassId::makeId()); + return (processClassId ? current.write(os) : true) && + process_const_item(s.first, os, st, false) && + process_const_item(s.second, os, st, false); + } + }; + + template + struct GenericReader::ISPAIR>> { + inline static bool readIntoPtr(T *&ptr, Stream &str, State *s, const bool processClassId) { + CPP11_auto_ptr myptr; + if (ptr == 0) { + myptr = CPP11_auto_ptr(new T()); + clearIfPointer(myptr.get()->first); + clearIfPointer(myptr.get()->second); + } + std::vector> itemIds; + if (processClassId) { + static const ClassId current(ClassId::makeId()); + ClassId pairId(str, 1); + current.ensureSameName(pairId); + pairId.templateParameters(&itemIds); + assert(itemIds.size() == 2U); + } else { + assert(!s->empty()); + s->back().templateParameters(&itemIds); + if (itemIds.size() != 2U) { + std::string err( + "In gs::GenericReader::readIntoPtr: " + "bad class id for std::pair on the " + "class id stack: "); + err += s->back().id(); + throw IOInvalidData(err); + } + } + if (!(process_item((ptr ? ptr : myptr.get())->first, str, &itemIds[0], false) && + process_item((ptr ? ptr : myptr.get())->second, str, &itemIds[1], false))) + return false; + if (ptr == 0) + ptr = myptr.release(); + return true; + } - // Item is a shared pointer - inline static bool process2(Container& obj, Stream& is, - State* st, const std::size_t itemN, - Int2Type<2>) - { - typedef typename item_type::element_type Pointee; - Pointee* ptr = 0; - const bool status = GenericReader::ISNULLPOINTER> >::process( - ptr, is, st, true); - if (status) - { - assert(ptr); - CPP11_shared_ptr sptr(ptr); - InsertContainerItem::insert(obj, sptr, itemN); - } - else - delete ptr; - return status; - } + inline static bool process(T &s, Stream &os, State *st, const bool processClassId) { + T *ps = &s; + return readIntoPtr(ps, os, st, processClassId); + } + }; + + //=================================================================== + // + // Processing of std::string + // + //=================================================================== + template + struct GenericWriter::ISSTRING>> { + inline static bool process(const std::string &s, Stream &os, State *, const bool processClassId) { + static const ClassId current(ClassId::makeId()); + const bool status = processClassId ? current.write(os) : true; + if (status) + write_string(os, s); + return status && !os.fail(); + } + }; + + template + struct GenericReader::ISSTRING>> { + inline static bool readIntoPtr(std::string *&ptr, Stream &is, State *, const bool processClassId) { + CPP11_auto_ptr myptr; + if (ptr == nullptr) + myptr = CPP11_auto_ptr(new std::string()); + if (processClassId) { + static const ClassId current(ClassId::makeId()); + ClassId id(is, 1); + current.ensureSameName(id); + } + read_string(is, ptr ? ptr : myptr.get()); + if (is.fail()) + return false; + if (ptr == nullptr) + ptr = myptr.release(); + return true; + } - // Item is heap-readable - inline static bool process2(Container& obj, Stream& is, - State* st, const std::size_t itemN, - Int2Type<3>) - { - // No class id -- this is a member of a container - assert(!st->empty()); - item_type* ptr = item_type::read(st->back(), is); - if (ptr) - { - InsertContainerItem::insert(obj, *ptr, itemN); - delete ptr; - } - return ptr; - } + inline static bool process(std::string &s, Stream &is, State *st, const bool processClassId) { + std::string *ptr = &s; + return readIntoPtr(ptr, is, st, processClassId); + } + }; + + //=================================================================== + // + // Processing of container readout + // + //=================================================================== + template + struct GenericReader { + private: + typedef typename Container::value_type item_type; + typedef IOTraits M; + + // Item is a simple pointer + inline static bool process2(Container &obj, Stream &is, State *st, const std::size_t itemN, Int2Type<1>) { + item_type ptr = 0; + const bool status = + GenericReader::ISNULLPOINTER>>::process(ptr, is, st, true); + if (status) { + assert(ptr); + InsertContainerItem::insert(obj, ptr, itemN); + } else + delete ptr; + return status; + } - // Item is not a pointer and not heap-readable. - // Assume that it has a default constructor. - inline static bool process2(Container& obj, Stream& is, - State* st, const std::size_t itemN, - Int2Type<4>) - { - typedef typename StrippedType::type NCType; - NCType item; - NCType* pitem = &item; - bool status = GenericReader::ISPOINTER> >::process( - pitem, is, st, false); - if (status) - InsertContainerItem::insert(obj, item, itemN); - return status; - } + // Item is a shared pointer + inline static bool process2(Container &obj, Stream &is, State *st, const std::size_t itemN, Int2Type<2>) { + typedef typename item_type::element_type Pointee; + Pointee *ptr = 0; + const bool status = + GenericReader::ISNULLPOINTER>>::process(ptr, is, st, true); + if (status) { + assert(ptr); + CPP11_shared_ptr sptr(ptr); + InsertContainerItem::insert(obj, sptr, itemN); + } else + delete ptr; + return status; + } - public: - inline static bool process(Container& obj, Stream& is, State* st, - const std::size_t itemN) - { - // By default, we will assume that container starts empty. - // Here, we need to produce a new item. There are 3 options: - // 1) make it on the stack, insert a copy into the container - // 2) make it on the heap, insert a copy, delete original - // 3) the container contains pointers to begin with, so - // we make it on the stack and add a pointer to the container - return process2(obj, is, st, itemN, Int2Type< - M::IsPointer * 1 + - M::IsSharedPtr * 2 + - M::IsHeapReadable * 3 + - !(M::IsPointer || M::IsSharedPtr || - M::IsHeapReadable) * 4>()); - } - }; - - - //=================================================================== - // - // Reading things when a pointer is given - // - //=================================================================== - template - struct GenericReader::ISSTDCONTAINER> > - { - inline static bool readIntoPtr(T*& ptr, Stream& str, State* s, - const bool processClassId) - { - if (ptr) - return process_item( - *ptr, str, s, processClassId); - else - { - CPP11_auto_ptr myptr(new T()); - if (!process_item( - *myptr, str, s, processClassId)) - return false; - ptr = myptr.release(); - return true; - } - } - }; - - template - struct GenericReader::ISHEAPREADABLE> > - { - inline static bool readIntoPtr(T*& ptr, Stream& str, State* s, - const bool processClassId) - { - T* readback = 0; - if (processClassId) - { - ClassId id(str, 1); - readback = T::read(id, str); - } - else - { - assert(!s->empty()); - readback = T::read(s->back(), str); - } - if (readback) - { - if (ptr) - { - try { - // We will assume here that the "read" - // operation takes precedence over constness - *const_cast::type *>(ptr) = - *readback; - } catch (...) { - delete readback; - throw; - } - delete readback; - } - else - ptr = readback; - } - return readback; - } - }; - - template - struct GenericReader::ISPUREHEAPREADABLE> > - { - inline static bool readIntoPtr(T*& ptr, Stream& str, State* s, - const bool processClassId) - { - T* readback = 0; - if (processClassId) - { - ClassId id(str, 1); - readback = T::read(id, str); - } - else - { - assert(!s->empty()); - readback = T::read(s->back(), str); - } - if (readback) - { - assert(!ptr); - ptr = readback; - } - return readback; - } - }; - - template - struct GenericReader::ISPLACEREADABLE> > - { - inline static bool readIntoPtr(T*& ptr, Stream& str, State* s, - const bool processClassId) - { - CPP11_auto_ptr myptr; - if (ptr == 0) - myptr = CPP11_auto_ptr(new T()); - if (processClassId) - { - ClassId id(str, 1); - T::restore(id, str, ptr ? ptr : myptr.get()); - } - else - { - assert(!s->empty()); - T::restore(s->back(), str, ptr ? ptr : myptr.get()); - } - if (ptr == 0) - ptr = myptr.release(); - return ptr; - } - }; -} + // Item is heap-readable + inline static bool process2(Container &obj, Stream &is, State *st, const std::size_t itemN, Int2Type<3>) { + // No class id -- this is a member of a container + assert(!st->empty()); + item_type *ptr = item_type::read(st->back(), is); + if (ptr) { + InsertContainerItem::insert(obj, *ptr, itemN); + delete ptr; + } + return ptr; + } + // Item is not a pointer and not heap-readable. + // Assume that it has a default constructor. + inline static bool process2(Container &obj, Stream &is, State *st, const std::size_t itemN, Int2Type<4>) { + typedef typename StrippedType::type NCType; + NCType item; + NCType *pitem = &item; + bool status = + GenericReader::ISPOINTER>>::process(pitem, is, st, false); + if (status) + InsertContainerItem::insert(obj, item, itemN); + return status; + } -#endif // GENERS_GENERICIO_HH_ + public: + inline static bool process(Container &obj, Stream &is, State *st, const std::size_t itemN) { + // By default, we will assume that container starts empty. + // Here, we need to produce a new item. There are 3 options: + // 1) make it on the stack, insert a copy into the container + // 2) make it on the heap, insert a copy, delete original + // 3) the container contains pointers to begin with, so + // we make it on the stack and add a pointer to the container + return process2(obj, + is, + st, + itemN, + Int2Type()); + } + }; + + //=================================================================== + // + // Reading things when a pointer is given + // + //=================================================================== + template + struct GenericReader::ISSTDCONTAINER>> { + inline static bool readIntoPtr(T *&ptr, Stream &str, State *s, const bool processClassId) { + if (ptr) + return process_item(*ptr, str, s, processClassId); + else { + CPP11_auto_ptr myptr(new T()); + if (!process_item(*myptr, str, s, processClassId)) + return false; + ptr = myptr.release(); + return true; + } + } + }; + + template + struct GenericReader::ISHEAPREADABLE>> { + inline static bool readIntoPtr(T *&ptr, Stream &str, State *s, const bool processClassId) { + T *readback = 0; + if (processClassId) { + ClassId id(str, 1); + readback = T::read(id, str); + } else { + assert(!s->empty()); + readback = T::read(s->back(), str); + } + if (readback) { + if (ptr) { + try { + // We will assume here that the "read" + // operation takes precedence over constness + *const_cast::type *>(ptr) = *readback; + } catch (...) { + delete readback; + throw; + } + delete readback; + } else + ptr = readback; + } + return readback; + } + }; + + template + struct GenericReader::ISPUREHEAPREADABLE>> { + inline static bool readIntoPtr(T *&ptr, Stream &str, State *s, const bool processClassId) { + T *readback = nullptr; + if (processClassId) { + ClassId id(str, 1); + readback = T::read(id, str); + } else { + assert(!s->empty()); + readback = T::read(s->back(), str); + } + if (readback) { + assert(!ptr); + ptr = readback; + } + return readback; + } + }; + + template + struct GenericReader::ISPLACEREADABLE>> { + inline static bool readIntoPtr(T *&ptr, Stream &str, State *s, const bool processClassId) { + CPP11_auto_ptr myptr; + if (ptr == 0) + myptr = CPP11_auto_ptr(new T()); + if (processClassId) { + ClassId id(str, 1); + T::restore(id, str, ptr ? ptr : myptr.get()); + } else { + assert(!s->empty()); + T::restore(s->back(), str, ptr ? ptr : myptr.get()); + } + if (ptr == 0) + ptr = myptr.release(); + return ptr; + } + }; +} // namespace gs +#endif // GENERS_GENERICIO_HH_ diff --git a/Alignment/Geners/interface/IOException.hh b/Alignment/Geners/interface/IOException.hh index d4e63df61eba0..a52c211073c26 100644 --- a/Alignment/Geners/interface/IOException.hh +++ b/Alignment/Geners/interface/IOException.hh @@ -6,128 +6,106 @@ #include "FWCore/Utilities/interface/Exception.h" namespace gs { - /** Base class for the exceptions specific to the Geners I/O library */ - struct IOException : public cms::Exception - { - inline IOException() : cms::Exception("gs::IOException") {} - - inline explicit IOException(const std::string& description) - : cms::Exception(description) {} - - inline explicit IOException(const char* description) - : cms::Exception(description) {} - - virtual ~IOException() throw() {} - }; - - struct IOLengthError : public IOException - { - inline IOLengthError() : IOException("gs::IOLengthError") {} - - inline explicit IOLengthError(const std::string& description) - : IOException(description) {} - - virtual ~IOLengthError() throw() {} - }; - - struct IOOutOfRange : public IOException - { - inline IOOutOfRange() : IOException("gs::IOOutOfRange") {} - - inline explicit IOOutOfRange(const std::string& description) - : IOException(description) {} - - virtual ~IOOutOfRange() throw() {} - }; - - struct IOInvalidArgument : public IOException - { - inline IOInvalidArgument() : IOException("gs::IOInvalidArgument") {} - - inline explicit IOInvalidArgument(const std::string& description) - : IOException(description) {} - - virtual ~IOInvalidArgument() throw() {} - }; - - /* Automatic replacement end} */ - - /** - // Throw this exception to indicate failure of various stream - // opening methods if it is difficult or impossible to clean up - // after the failure in the normal flow of control - */ - class IOOpeningFailure : public IOException - { - inline static std::string fileOpeningFailure( - const std::string& whereInTheCode, - const std::string& filename) - { - std::string msg("In "); - msg += whereInTheCode; - msg += ": failed to open file \""; - msg += filename; - msg += "\""; - return msg; - } - - public: - inline IOOpeningFailure() : IOException("gs::IOOpeningFailure") {} - - inline explicit IOOpeningFailure(const std::string& description) - : IOException(description) {} - - inline IOOpeningFailure(const std::string& whereInTheCode, - const std::string& filename) - : IOException(fileOpeningFailure(whereInTheCode, filename)) {} - - virtual ~IOOpeningFailure() throw() {} - }; - - /** - // Throw this exception to indicate failure in the writing process. - // For example, fail() method of the output stream returns "true", - // and the function is unable to handle this situation locally. - */ - struct IOWriteFailure : public IOException - { - inline IOWriteFailure() : IOException("gs::IOWriteFailure") {} - - inline explicit IOWriteFailure(const std::string& description) - : IOException(description) {} - - virtual ~IOWriteFailure() throw() {} - }; - - /** - // Throw this exception to indicate failure in the reading process. - // For example, fail() method of the input stream returns "true", - // and the function is unable to handle this situation locally. - */ - struct IOReadFailure : public IOException - { - inline IOReadFailure() : IOException("gs::IOReadFailure") {} - - inline explicit IOReadFailure(const std::string& description) - : IOException(description) {} - - virtual ~IOReadFailure() throw() {} - }; - - /** - // Throw this exception when improperly formatted or invalid data - // is detected - */ - struct IOInvalidData : public IOException - { - inline IOInvalidData() : IOException("gs::IOInvalidData") {} - - inline explicit IOInvalidData(const std::string& description) - : IOException(description) {} - - virtual ~IOInvalidData() throw() {} - }; -} - -#endif // GENERS_IOEXCEPTION_HH_ + /** Base class for the exceptions specific to the Geners I/O library */ + struct IOException : public cms::Exception { + inline IOException() : cms::Exception("gs::IOException") {} + inline explicit IOException(const std::string &description) : cms::Exception(description) {} + + inline explicit IOException(const char *description) : cms::Exception(description) {} + + ~IOException() throw() override {} + }; + + struct IOLengthError : public IOException { + inline IOLengthError() : IOException("gs::IOLengthError") {} + + inline explicit IOLengthError(const std::string &description) : IOException(description) {} + + ~IOLengthError() throw() override {} + }; + + struct IOOutOfRange : public IOException { + inline IOOutOfRange() : IOException("gs::IOOutOfRange") {} + + inline explicit IOOutOfRange(const std::string &description) : IOException(description) {} + + ~IOOutOfRange() throw() override {} + }; + + struct IOInvalidArgument : public IOException { + inline IOInvalidArgument() : IOException("gs::IOInvalidArgument") {} + + inline explicit IOInvalidArgument(const std::string &description) : IOException(description) {} + + ~IOInvalidArgument() throw() override {} + }; + + /* Automatic replacement end} */ + + /** +// Throw this exception to indicate failure of various stream +// opening methods if it is difficult or impossible to clean up +// after the failure in the normal flow of control +*/ + class IOOpeningFailure : public IOException { + inline static std::string fileOpeningFailure(const std::string &whereInTheCode, const std::string &filename) { + std::string msg("In "); + msg += whereInTheCode; + msg += ": failed to open file \""; + msg += filename; + msg += "\""; + return msg; + } + + public: + inline IOOpeningFailure() : IOException("gs::IOOpeningFailure") {} + + inline explicit IOOpeningFailure(const std::string &description) : IOException(description) {} + + inline IOOpeningFailure(const std::string &whereInTheCode, const std::string &filename) + : IOException(fileOpeningFailure(whereInTheCode, filename)) {} + + ~IOOpeningFailure() throw() override {} + }; + + /** +// Throw this exception to indicate failure in the writing process. +// For example, fail() method of the output stream returns "true", +// and the function is unable to handle this situation locally. +*/ + struct IOWriteFailure : public IOException { + inline IOWriteFailure() : IOException("gs::IOWriteFailure") {} + + inline explicit IOWriteFailure(const std::string &description) : IOException(description) {} + + ~IOWriteFailure() throw() override {} + }; + + /** +// Throw this exception to indicate failure in the reading process. +// For example, fail() method of the input stream returns "true", +// and the function is unable to handle this situation locally. +*/ + struct IOReadFailure : public IOException { + inline IOReadFailure() : IOException("gs::IOReadFailure") {} + + inline explicit IOReadFailure(const std::string &description) : IOException(description) {} + + ~IOReadFailure() throw() override {} + }; + + /** +// Throw this exception when improperly formatted or invalid data +// is detected +*/ + struct IOInvalidData : public IOException { + inline IOInvalidData() : IOException("gs::IOInvalidData") {} + + inline explicit IOInvalidData(const std::string &description) : IOException(description) {} + + ~IOInvalidData() throw() override {} + }; +} // namespace gs + +#endif // GENERS_IOEXCEPTION_HH_ diff --git a/Alignment/Geners/interface/IOIsAnyPtr.hh b/Alignment/Geners/interface/IOIsAnyPtr.hh index 8e7b5558a1cf6..f23c0c4aa36a1 100644 --- a/Alignment/Geners/interface/IOIsAnyPtr.hh +++ b/Alignment/Geners/interface/IOIsAnyPtr.hh @@ -2,20 +2,16 @@ #define GENERS_IOISANYPTR_HH_ #include "Alignment/Geners/interface/CPP11_type_traits.hh" -#include "Alignment/Geners/interface/IOIsSharedPtr.hh" #include "Alignment/Geners/interface/IOIsIOPtr.hh" +#include "Alignment/Geners/interface/IOIsSharedPtr.hh" namespace gs { - // Here we are taking into account only the types of pointers - // known to the I/O system - template - struct IOIsAnyPtr - { - static const bool value = (CPP11_is_pointer::value || - IOIsSharedPtr::value || - IOIsIOPtr::value); - }; -} - -#endif // GENERS_IOISANYPTR_HH_ + // Here we are taking into account only the types of pointers + // known to the I/O system + template + struct IOIsAnyPtr { + static const bool value = (CPP11_is_pointer::value || IOIsSharedPtr::value || IOIsIOPtr::value); + }; +} // namespace gs +#endif // GENERS_IOISANYPTR_HH_ diff --git a/Alignment/Geners/interface/IOIsClassType.hh b/Alignment/Geners/interface/IOIsClassType.hh index 2adbb0ca5b9d9..a9d1968110c80 100644 --- a/Alignment/Geners/interface/IOIsClassType.hh +++ b/Alignment/Geners/interface/IOIsClassType.hh @@ -2,18 +2,20 @@ #define GENERS_IOISCLASSTYPE_HH_ namespace gs { - template - class IOIsClassType - { - typedef char One; - typedef struct {char a[2];} Two; - template static One test(int C::*); - template static Two test(...); + template + class IOIsClassType { + typedef char One; + typedef struct { + char a[2]; + } Two; + template + static One test(int C::*); + template + static Two test(...); - public: - enum {value = sizeof(IOIsClassType::template test(0)) == 1}; - }; -} - -#endif // GENERS_IOISCLASSTYPE_HH_ + public: + enum { value = sizeof(IOIsClassType::template test(nullptr)) == 1 }; + }; +} // namespace gs +#endif // GENERS_IOISCLASSTYPE_HH_ diff --git a/Alignment/Geners/interface/IOIsContainer.hh b/Alignment/Geners/interface/IOIsContainer.hh index 9b6ffbf27ce5d..2986195dae50c 100644 --- a/Alignment/Geners/interface/IOIsContainer.hh +++ b/Alignment/Geners/interface/IOIsContainer.hh @@ -4,50 +4,48 @@ #include namespace gs { - // In the following template, enum "IsContainer" is evaluated to 1 - // at compile time if T has T::value_type typedef - template - class IOIsContainer - { - private: - typedef char One; - typedef struct {char a[2];} Two; - template static One test(typename C::value_type const*); - template static Two test(...); - - public: - enum {value = sizeof(IOIsContainer::template test(0)) == 1}; - }; - - // Char strings get a special treatment - template <> - class IOIsContainer - { - public: - enum {value = 0}; - }; - - template <> - class IOIsContainer - { - public: - enum {value = 0}; - }; - - template <> - class IOIsContainer - { - public: - enum {value = 0}; - }; - - template <> - class IOIsContainer - { - public: - enum {value = 0}; - }; -} - -#endif // GENERS_IOISCONTAINER_HH_ - + // In the following template, enum "IsContainer" is evaluated to 1 + // at compile time if T has T::value_type typedef + template + class IOIsContainer { + private: + typedef char One; + typedef struct { + char a[2]; + } Two; + template + static One test(typename C::value_type const *); + template + static Two test(...); + + public: + enum { value = sizeof(IOIsContainer::template test(0)) == 1 }; + }; + + // Char strings get a special treatment + template <> + class IOIsContainer { + public: + enum { value = 0 }; + }; + + template <> + class IOIsContainer { + public: + enum { value = 0 }; + }; + + template <> + class IOIsContainer { + public: + enum { value = 0 }; + }; + + template <> + class IOIsContainer { + public: + enum { value = 0 }; + }; +} // namespace gs + +#endif // GENERS_IOISCONTAINER_HH_ diff --git a/Alignment/Geners/interface/IOIsContiguous.hh b/Alignment/Geners/interface/IOIsContiguous.hh index 70eef34c0cf72..779ad3ad6df40 100644 --- a/Alignment/Geners/interface/IOIsContiguous.hh +++ b/Alignment/Geners/interface/IOIsContiguous.hh @@ -5,67 +5,77 @@ #include namespace gs { - template - struct IOIsContiguous - { - enum {value = 0}; - }; - - // String is treated as a pod vector. This will be guaranteed - // to work correctly in the C++11 standard. The current standard - // does not specify that the characters must be stored contuguously - // inside the string -- however, this is always true in practice. - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - // std::vector is used by the package everywhere. No point in not - // having it here. - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - template - struct IOIsContiguous > - {enum {value = 1};}; - - // Hovever, std::vector should be excluded - template <> - struct IOIsContiguous > - {enum {value = 0};}; - - template <> - struct IOIsContiguous > - {enum {value = 0};}; - - template <> - struct IOIsContiguous > - {enum {value = 0};}; - - template <> - struct IOIsContiguous > - {enum {value = 0};}; -} - -#endif // GENERS_IOISCONTIGUOUS_HH_ - + template + struct IOIsContiguous { + enum { value = 0 }; + }; + + // String is treated as a pod vector. This will be guaranteed + // to work correctly in the C++11 standard. The current standard + // does not specify that the characters must be stored contuguously + // inside the string -- however, this is always true in practice. + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + // std::vector is used by the package everywhere. No point in not + // having it here. + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + template + struct IOIsContiguous> { + enum { value = 1 }; + }; + + // Hovever, std::vector should be excluded + template <> + struct IOIsContiguous> { + enum { value = 0 }; + }; + + template <> + struct IOIsContiguous> { + enum { value = 0 }; + }; + + template <> + struct IOIsContiguous> { + enum { value = 0 }; + }; + + template <> + struct IOIsContiguous> { + enum { value = 0 }; + }; +} // namespace gs + +#endif // GENERS_IOISCONTIGUOUS_HH_ diff --git a/Alignment/Geners/interface/IOIsExternal.hh b/Alignment/Geners/interface/IOIsExternal.hh index 94e18520ca087..c46a0c43b3d55 100644 --- a/Alignment/Geners/interface/IOIsExternal.hh +++ b/Alignment/Geners/interface/IOIsExternal.hh @@ -2,55 +2,81 @@ #define GENERS_IOISEXTERNAL_HH_ namespace gs { - template - struct IOIsExternal - { - enum {value = 0}; - }; -} + template + struct IOIsExternal { + enum { value = 0 }; + }; +} // namespace gs // Use the following macro (outside of any namespace) // to declare some type as external for I/O purposes // -#define gs_declare_type_external(T) /**/ \ -namespace gs { \ - template <> struct IOIsExternal {enum {value = 1};}; \ - template <> struct IOIsExternal {enum {value = 1};}; \ - template <> struct IOIsExternal {enum {value = 1};}; \ - template <> struct IOIsExternal {enum {value = 1};}; \ -} +#define gs_declare_type_external(T) /**/ \ + namespace gs { \ + template <> \ + struct IOIsExternal { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsExternal { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsExternal { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsExternal { \ + enum { value = 1 }; \ + }; \ + } // Use the following macro (outside of any namespace) // to declare some template parameterized by one argument // as external for I/O purposes // -#define gs_declare_template_external_T(name) /**/ \ -namespace gs { \ - template struct IOIsExternal< name > \ - {enum {value = 1};}; \ - template struct IOIsExternal > \ - {enum {value = 1};}; \ - template struct IOIsExternal > \ - {enum {value = 1};}; \ - template struct IOIsExternal > \ - {enum {value = 1};}; \ -} +#define gs_declare_template_external_T(name) /**/ \ + namespace gs { \ + template \ + struct IOIsExternal> { \ + enum { value = 1 }; \ + }; \ + template \ + struct IOIsExternal> { \ + enum { value = 1 }; \ + }; \ + template \ + struct IOIsExternal> { \ + enum { value = 1 }; \ + }; \ + template \ + struct IOIsExternal> { \ + enum { value = 1 }; \ + }; \ + } // Use the following macro (outside of any namespace) // to declare some template parameterized by two arguments // as external for I/O purposes // -#define gs_declare_template_external_TT(name) /**/ \ -namespace gs { \ - template struct IOIsExternal< name > \ - {enum {value = 1};}; \ - template struct IOIsExternal > \ - {enum {value = 1};}; \ - template struct IOIsExternal > \ - {enum {value = 1};}; \ - template struct IOIsExternal >\ - {enum {value = 1};}; \ -} - -#endif // GENERS_IOISEXTERNAL_HH_ +#define gs_declare_template_external_TT(name) /**/ \ + namespace gs { \ + template \ + struct IOIsExternal> { \ + enum { value = 1 }; \ + }; \ + template \ + struct IOIsExternal> { \ + enum { value = 1 }; \ + }; \ + template \ + struct IOIsExternal> { \ + enum { value = 1 }; \ + }; \ + template \ + struct IOIsExternal> { \ + enum { value = 1 }; \ + }; \ + } +#endif // GENERS_IOISEXTERNAL_HH_ diff --git a/Alignment/Geners/interface/IOIsIOPtr.hh b/Alignment/Geners/interface/IOIsIOPtr.hh index b8a556ee4f410..7da2fd68b0edf 100644 --- a/Alignment/Geners/interface/IOIsIOPtr.hh +++ b/Alignment/Geners/interface/IOIsIOPtr.hh @@ -4,60 +4,50 @@ #include "Alignment/Geners/interface/IOPtr.hh" namespace gs { - template - struct IOIsIOPtr - { - enum {value = 0}; - }; - - template - struct IOIsIOPtr > - { - enum {value = 1}; - }; - - template - struct IOIsIOPtr > - { - enum {value = 1}; - }; - - template - struct IOIsIOPtr > - { - enum {value = 1}; - }; - - template - struct IOIsIOPtr > - { - enum {value = 1}; - }; - - template - struct IOIsIOPtr > - { - enum {value = 1}; - }; - - template - struct IOIsIOPtr > - { - enum {value = 1}; - }; - - template - struct IOIsIOPtr > - { - enum {value = 1}; - }; - - template - struct IOIsIOPtr > - { - enum {value = 1}; - }; -} - -#endif // GENERS_IOISIOPTR_HH_ - + template + struct IOIsIOPtr { + enum { value = 0 }; + }; + + template + struct IOIsIOPtr> { + enum { value = 1 }; + }; + + template + struct IOIsIOPtr> { + enum { value = 1 }; + }; + + template + struct IOIsIOPtr> { + enum { value = 1 }; + }; + + template + struct IOIsIOPtr> { + enum { value = 1 }; + }; + + template + struct IOIsIOPtr> { + enum { value = 1 }; + }; + + template + struct IOIsIOPtr> { + enum { value = 1 }; + }; + + template + struct IOIsIOPtr> { + enum { value = 1 }; + }; + + template + struct IOIsIOPtr> { + enum { value = 1 }; + }; +} // namespace gs + +#endif // GENERS_IOISIOPTR_HH_ diff --git a/Alignment/Geners/interface/IOIsNumber.hh b/Alignment/Geners/interface/IOIsNumber.hh index 3b61073181714..7b8732665da77 100644 --- a/Alignment/Geners/interface/IOIsNumber.hh +++ b/Alignment/Geners/interface/IOIsNumber.hh @@ -2,35 +2,37 @@ #define GENERS_IOISNUMBER_HH_ namespace gs { - template - struct IOIsNumber - { - enum {value = 0}; - }; -} + template + struct IOIsNumber { + enum { value = 0 }; + }; +} // namespace gs -#define gs_declare_type_as_number(T) /**/ \ -namespace gs { \ - template <> struct IOIsNumber {enum {value = 1};}; \ - template <> struct IOIsNumber {enum {value = 1};}; \ - template <> struct IOIsNumber {enum {value = 1};}; \ - template <> struct IOIsNumber {enum {value = 1};}; \ -} +#define gs_declare_type_as_number(T) /**/ \ + namespace gs { \ + template <> \ + struct IOIsNumber { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsNumber { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsNumber { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsNumber { \ + enum { value = 1 }; \ + }; \ + } -gs_declare_type_as_number(float) -gs_declare_type_as_number(double) -gs_declare_type_as_number(long double) -gs_declare_type_as_number(int) -gs_declare_type_as_number(unsigned) -gs_declare_type_as_number(long) -gs_declare_type_as_number(long long) -gs_declare_type_as_number(unsigned long) -gs_declare_type_as_number(unsigned long long) -gs_declare_type_as_number(short) -gs_declare_type_as_number(unsigned short) -gs_declare_type_as_number(char) -gs_declare_type_as_number(unsigned char) -gs_declare_type_as_number(signed char) - -#endif // GENERS_IOISNUMBER_HH_ +gs_declare_type_as_number(float) gs_declare_type_as_number(double) gs_declare_type_as_number(long double) + gs_declare_type_as_number(int) gs_declare_type_as_number(unsigned) gs_declare_type_as_number(long) + gs_declare_type_as_number(long long) gs_declare_type_as_number(unsigned long) + gs_declare_type_as_number(unsigned long long) gs_declare_type_as_number(short) + gs_declare_type_as_number(unsigned short) gs_declare_type_as_number(char) + gs_declare_type_as_number(unsigned char) gs_declare_type_as_number(signed char) +#endif // GENERS_IOISNUMBER_HH_ diff --git a/Alignment/Geners/interface/IOIsPOD.hh b/Alignment/Geners/interface/IOIsPOD.hh index ab7dc5774de4e..84d9ebf624267 100644 --- a/Alignment/Geners/interface/IOIsPOD.hh +++ b/Alignment/Geners/interface/IOIsPOD.hh @@ -4,25 +4,35 @@ #include "Alignment/Geners/interface/CPP11_type_traits.hh" namespace gs { - // In the following template, enum "IsPOD" is evaluated to 1 - // at compile time if T belongs to one of the known POD types. - template - struct IOIsPOD - { - enum {value = CPP11_is_pod::value}; - }; -} + // In the following template, enum "IsPOD" is evaluated to 1 + // at compile time if T belongs to one of the known POD types. + template + struct IOIsPOD { + enum { value = CPP11_is_pod::value }; + }; +} // namespace gs // Use the following macro (outside of any namespace) // to declare some struct as POD for I/O purposes // -#define gs_declare_type_as_pod(T) /**/ \ -namespace gs { \ - template <> struct IOIsPOD {enum {value = 1};}; \ - template <> struct IOIsPOD {enum {value = 1};}; \ - template <> struct IOIsPOD {enum {value = 1};}; \ - template <> struct IOIsPOD {enum {value = 1};}; \ -} - -#endif // GENERS_IOISPOD_HH_ +#define gs_declare_type_as_pod(T) /**/ \ + namespace gs { \ + template <> \ + struct IOIsPOD { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsPOD { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsPOD { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsPOD { \ + enum { value = 1 }; \ + }; \ + } +#endif // GENERS_IOISPOD_HH_ diff --git a/Alignment/Geners/interface/IOIsPair.hh b/Alignment/Geners/interface/IOIsPair.hh index 107f2626b2cf0..9b9e3b1f8ed44 100644 --- a/Alignment/Geners/interface/IOIsPair.hh +++ b/Alignment/Geners/interface/IOIsPair.hh @@ -4,18 +4,15 @@ #include namespace gs { - template - struct IOIsPair - { - enum {value = 0}; - }; + template + struct IOIsPair { + enum { value = 0 }; + }; - template - struct IOIsPair > - { - enum {value = 1}; - }; -} - -#endif // GENERS_IOISPAIR_HH_ + template + struct IOIsPair> { + enum { value = 1 }; + }; +} // namespace gs +#endif // GENERS_IOISPAIR_HH_ diff --git a/Alignment/Geners/interface/IOIsReadable.hh b/Alignment/Geners/interface/IOIsReadable.hh index 435c206c0550e..7dbabe2ffbb28 100644 --- a/Alignment/Geners/interface/IOIsReadable.hh +++ b/Alignment/Geners/interface/IOIsReadable.hh @@ -6,63 +6,61 @@ #include "Alignment/Geners/interface/StrippedType.hh" namespace gs { - template - class IOIsHeapReadableHelper - { - private: - template struct tester; - typedef char One; - typedef struct {char a[2];} Two; - template static One test(tester<&C::read>*); - template static Two test(...); - - public: - enum {value = sizeof(IOIsHeapReadableHelper::template test(0)) == 1}; - }; - - - template::value> - struct IOIsHeapReadable - { - enum {value = 0}; - }; - - - template - struct IOIsHeapReadable - { - enum {value = IOIsHeapReadableHelper::type>::value}; - }; - - - template - class IOIsPlaceReadableHelper - { - private: - template struct tester; - typedef char One; - typedef struct {char a[2];} Two; - template static One test(tester<&C::restore>*); - template static Two test(...); - - public: - enum {value = sizeof(IOIsPlaceReadableHelper::template test(0)) == 1}; - }; - - - template::value> - struct IOIsPlaceReadable - { - enum {value = 0}; - }; - - - template - struct IOIsPlaceReadable - { - enum {value = IOIsPlaceReadableHelper::type>::value}; - }; -} - -#endif // GENERS_IOISREADABLE_HH_ - + template + class IOIsHeapReadableHelper { + private: + template + struct tester; + typedef char One; + typedef struct { + char a[2]; + } Two; + template + static One test(tester<&C::read> *); + template + static Two test(...); + + public: + enum { value = sizeof(IOIsHeapReadableHelper::template test(nullptr)) == 1 }; + }; + + template ::value> + struct IOIsHeapReadable { + enum { value = 0 }; + }; + + template + struct IOIsHeapReadable { + enum { value = IOIsHeapReadableHelper::type>::value }; + }; + + template + class IOIsPlaceReadableHelper { + private: + template + struct tester; + typedef char One; + typedef struct { + char a[2]; + } Two; + template + static One test(tester<&C::restore> *); + template + static Two test(...); + + public: + enum { value = sizeof(IOIsPlaceReadableHelper::template test(0)) == 1 }; + }; + + template ::value> + struct IOIsPlaceReadable { + enum { value = 0 }; + }; + + template + struct IOIsPlaceReadable { + enum { value = IOIsPlaceReadableHelper::type>::value }; + }; +} // namespace gs + +#endif // GENERS_IOISREADABLE_HH_ diff --git a/Alignment/Geners/interface/IOIsSharedPtr.hh b/Alignment/Geners/interface/IOIsSharedPtr.hh index bcfdbf187ab77..93d419f940aa4 100644 --- a/Alignment/Geners/interface/IOIsSharedPtr.hh +++ b/Alignment/Geners/interface/IOIsSharedPtr.hh @@ -4,36 +4,30 @@ #include "Alignment/Geners/interface/CPP11_shared_ptr.hh" namespace gs { - template - struct IOIsSharedPtr - { - enum {value = 0}; - }; - - template - struct IOIsSharedPtr > - { - enum {value = 1}; - }; - - template - struct IOIsSharedPtr > - { - enum {value = 1}; - }; - - template - struct IOIsSharedPtr > - { - enum {value = 1}; - }; - - template - struct IOIsSharedPtr > - { - enum {value = 1}; - }; -} - -#endif // GENERS_IOISSHAREDPTR_HH_ - + template + struct IOIsSharedPtr { + enum { value = 0 }; + }; + + template + struct IOIsSharedPtr> { + enum { value = 1 }; + }; + + template + struct IOIsSharedPtr> { + enum { value = 1 }; + }; + + template + struct IOIsSharedPtr> { + enum { value = 1 }; + }; + + template + struct IOIsSharedPtr> { + enum { value = 1 }; + }; +} // namespace gs + +#endif // GENERS_IOISSHAREDPTR_HH_ diff --git a/Alignment/Geners/interface/IOIsString.hh b/Alignment/Geners/interface/IOIsString.hh index 5d13f2ddd5ded..415312219c2be 100644 --- a/Alignment/Geners/interface/IOIsString.hh +++ b/Alignment/Geners/interface/IOIsString.hh @@ -4,36 +4,30 @@ #include namespace gs { - template - struct IOIsString - { - enum {value = 0}; - }; - - template <> - struct IOIsString - { - enum {value = 1}; - }; - - template <> - struct IOIsString - { - enum {value = 1}; - }; - - template <> - struct IOIsString - { - enum {value = 1}; - }; - - template <> - struct IOIsString - { - enum {value = 1}; - }; -} - -#endif // GENERS_IOISSTRING_HH_ - + template + struct IOIsString { + enum { value = 0 }; + }; + + template <> + struct IOIsString { + enum { value = 1 }; + }; + + template <> + struct IOIsString { + enum { value = 1 }; + }; + + template <> + struct IOIsString { + enum { value = 1 }; + }; + + template <> + struct IOIsString { + enum { value = 1 }; + }; +} // namespace gs + +#endif // GENERS_IOISSTRING_HH_ diff --git a/Alignment/Geners/interface/IOIsTuple.hh b/Alignment/Geners/interface/IOIsTuple.hh index fb867373b0c6f..e8b20aca7b9e6 100644 --- a/Alignment/Geners/interface/IOIsTuple.hh +++ b/Alignment/Geners/interface/IOIsTuple.hh @@ -2,12 +2,10 @@ #define GENERS_IOISTUPLE_HH_ namespace gs { - template - struct IOIsTuple - { - enum {value = 0}; - }; -} - -#endif // GENERS_IOISTUPLE_HH_ + template + struct IOIsTuple { + enum { value = 0 }; + }; +} // namespace gs +#endif // GENERS_IOISTUPLE_HH_ diff --git a/Alignment/Geners/interface/IOIsUnsigned.hh b/Alignment/Geners/interface/IOIsUnsigned.hh index e39ace3f2096d..ded98d149c84c 100644 --- a/Alignment/Geners/interface/IOIsUnsigned.hh +++ b/Alignment/Geners/interface/IOIsUnsigned.hh @@ -2,26 +2,34 @@ #define GENERS_IOISUNSIGNED_HH_ namespace gs { - template - struct IOIsUnsigned - { - enum {value = 0}; - }; -} + template + struct IOIsUnsigned { + enum { value = 0 }; + }; +} // namespace gs -#define gs_declare_type_as_unsigned(T) /**/ \ -namespace gs { \ - template <> struct IOIsUnsigned {enum {value = 1};}; \ - template <> struct IOIsUnsigned {enum {value = 1};}; \ - template <> struct IOIsUnsigned {enum {value = 1};}; \ - template <> struct IOIsUnsigned {enum {value = 1};}; \ -} +#define gs_declare_type_as_unsigned(T) /**/ \ + namespace gs { \ + template <> \ + struct IOIsUnsigned { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsUnsigned { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsUnsigned { \ + enum { value = 1 }; \ + }; \ + template <> \ + struct IOIsUnsigned { \ + enum { value = 1 }; \ + }; \ + } -gs_declare_type_as_unsigned(unsigned char) -gs_declare_type_as_unsigned(unsigned short) -gs_declare_type_as_unsigned(unsigned int) -gs_declare_type_as_unsigned(unsigned long) -gs_declare_type_as_unsigned(unsigned long long) - -#endif // GENERS_IOISUNSIGNED_HH_ +gs_declare_type_as_unsigned(unsigned char) gs_declare_type_as_unsigned(unsigned short) + gs_declare_type_as_unsigned(unsigned int) gs_declare_type_as_unsigned(unsigned long) + gs_declare_type_as_unsigned(unsigned long long) +#endif // GENERS_IOISUNSIGNED_HH_ diff --git a/Alignment/Geners/interface/IOIsWritable.hh b/Alignment/Geners/interface/IOIsWritable.hh index 35682b42b2bdb..6a7b4d00620b1 100644 --- a/Alignment/Geners/interface/IOIsWritable.hh +++ b/Alignment/Geners/interface/IOIsWritable.hh @@ -6,34 +6,33 @@ #include namespace gs { - template - class IOIsWritableHelper - { - private: - template struct tester; - typedef char One; - typedef struct {char a[2];} Two; - template static One test(tester<&C::write>*); - template static Two test(...); - - public: - enum {value = sizeof(IOIsWritableHelper::template test(0)) == 1}; - }; - - - template::value> - struct IOIsWritable - { - enum {value = 0}; - }; - - - template - struct IOIsWritable - { - enum {value = IOIsWritableHelper::value}; - }; -} - -#endif // GENERS_IOISWRITABLE_HH_ - + template + class IOIsWritableHelper { + private: + template + struct tester; + typedef char One; + typedef struct { + char a[2]; + } Two; + template + static One test(tester<&C::write> *); + template + static Two test(...); + + public: + enum { value = sizeof(IOIsWritableHelper::template test(nullptr)) == 1 }; + }; + + template ::value> + struct IOIsWritable { + enum { value = 0 }; + }; + + template + struct IOIsWritable { + enum { value = IOIsWritableHelper::value }; + }; +} // namespace gs + +#endif // GENERS_IOISWRITABLE_HH_ diff --git a/Alignment/Geners/interface/IOPointeeType.hh b/Alignment/Geners/interface/IOPointeeType.hh index 17d6ca46c3a9c..70de6579a104e 100644 --- a/Alignment/Geners/interface/IOPointeeType.hh +++ b/Alignment/Geners/interface/IOPointeeType.hh @@ -2,33 +2,28 @@ #define GENERS_IOPOINTEETYPE_HH_ namespace gs { - template - struct IOPointeeType; + template + struct IOPointeeType; - template - struct IOPointeeType - { - typedef T type; - }; + template + struct IOPointeeType { + typedef T type; + }; - template - struct IOPointeeType - { - typedef T type; - }; + template + struct IOPointeeType { + typedef T type; + }; - template - struct IOPointeeType - { - typedef T type; - }; + template + struct IOPointeeType { + typedef T type; + }; - template - struct IOPointeeType - { - typedef T type; - }; -} - -#endif // GENERS_IOPOINTEETYPE_HH_ + template + struct IOPointeeType { + typedef T type; + }; +} // namespace gs +#endif // GENERS_IOPOINTEETYPE_HH_ diff --git a/Alignment/Geners/interface/IOPtr.hh b/Alignment/Geners/interface/IOPtr.hh index 75846695a7a0e..94b69a38dcaba 100644 --- a/Alignment/Geners/interface/IOPtr.hh +++ b/Alignment/Geners/interface/IOPtr.hh @@ -1,190 +1,202 @@ #ifndef GENERS_IOPTR_HH_ #define GENERS_IOPTR_HH_ -#include #include "Alignment/Geners/interface/IOException.hh" +#include // "Silent" pointers for the I/O system namespace gs { - template class IOProxy; - - template - class IOPtr - { - template friend class IOProxy; - - public: - typedef T element_type; - - inline IOPtr() : ptr_(0) {} - inline IOPtr(T* ptr) : ptr_(ptr) {} - IOPtr(const IOProxy& p); - - IOPtr& operator=(const IOProxy& p); - inline IOPtr& operator=(const IOPtr& p) - {ptr_ = p.ptr_; return *this;} - - // Typical pointer operations - inline T* get() const {return ptr_;} - inline T* operator->() const - { - if (!ptr_) throw gs::IOInvalidArgument( - "In gs::IOPtr::operator->: attempt to dereference null pointer"); - return ptr_; - } - inline T& operator*() const - { - if (!ptr_) throw gs::IOInvalidArgument( - "In gs::IOPtr::operator*: attempt to dereference null pointer"); - return *ptr_; - } - inline IOPtr& operator++() {++ptr_; return *this;} - inline void operator++(int) {++ptr_;} - inline IOPtr& operator--() {--ptr_; return *this;} - inline void operator--(int) {--ptr_;} - - // Implicit conversion to "bool" - inline operator bool() const {return !(ptr_ == 0);} - - // Names are ignored during comparisons - inline bool operator==(const IOPtr& r) const {return ptr_ == r.ptr_;} - inline bool operator!=(const IOPtr& r) const {return ptr_ != r.ptr_;} - bool operator==(const IOProxy& r) const; - bool operator!=(const IOProxy& r) const; - - // Should be able to work as with bare pointer inside the I/O code - inline T*& getIOReference() {return ptr_;} - inline T* const & getIOReference() const - { - if (!ptr_) throw gs::IOInvalidArgument( - "In gs::IOPtr::getIOReference: unusable " - "const reference to null pointer"); - return ptr_; - } - - private: - T* ptr_; - }; - - template - class IOProxy - { - template friend class IOPtr; - - public: - typedef T element_type; - - inline IOProxy() : ptr_(0) {} - inline IOProxy(T* ptr) : ptr_(ptr) {} - inline IOProxy(T* ptr, const char* varname) - : ptr_(ptr), name_(varname ? varname : "") {} - inline IOProxy(T* ptr, const std::string& varname) - : ptr_(ptr), name_(varname) {} - inline IOProxy(const IOPtr& p) : ptr_(p.ptr_) {} - inline IOProxy(const IOPtr& p, const char* varname) - : ptr_(p.ptr_), name_(varname ? varname : "") {} - inline IOProxy(const IOPtr& p, const std::string& varname) - : ptr_(p.ptr_), name_(varname) {} - - inline IOProxy& operator=(const IOProxy& p) - {ptr_ = p.ptr_; name_ = p.name_; return *this;} - inline IOProxy& operator=(const IOPtr& p) - {ptr_ = p.ptr_; name_ = ""; return *this;} - - // Get name - inline const std::string& name() const {return name_;} - - // Set name - inline IOProxy& setName(const char* varname) - { - name_ = varname ? varname : ""; - return *this; - } - inline IOProxy& setName(const std::string& varname) - { - name_ = varname; - return *this; - } - - // Typical pointer operations - inline T* get() const {return ptr_;} - inline T* operator->() const - { - if (!ptr_) throw gs::IOInvalidArgument( - "In gs::IOProxy::operator->: attempt to dereference null pointer"); - return ptr_; - } - inline T& operator*() const - { - if (!ptr_) throw gs::IOInvalidArgument( - "In gs::IOProxy::operator*: attempt to dereference null pointer"); - return *ptr_; - } - inline IOProxy& operator++() {++ptr_; return *this;} - inline void operator++(int) {++ptr_;} - inline IOProxy& operator--() {--ptr_; return *this;} - inline void operator--(int) {--ptr_;} - - // Implicit conversion to "bool" - inline operator bool() const {return !(ptr_ == 0);} - - // Names are ignored during comparisons - inline bool operator==(const IOProxy& r) const {return ptr_ == r.ptr_;} - inline bool operator!=(const IOProxy& r) const {return ptr_ != r.ptr_;} - inline bool operator==(const IOPtr& r) const {return ptr_== r.ptr_;} - inline bool operator!=(const IOPtr& r) const {return ptr_!= r.ptr_;} - - // Should be able to work as with bare pointer inside the I/O code - inline T*& getIOReference() {return ptr_;} - inline T* const & getIOReference() const - { - if (!ptr_) throw gs::IOInvalidArgument( - "In gs::IOProxy::getIOReference: unusable " - "const reference to null pointer"); - return ptr_; - } - - private: - T* ptr_; - std::string name_; - }; - - // Convenience function for making IOPtr objects - template - inline IOPtr make_IOPtr(T& obj) - { - return IOPtr(&obj); + template + class IOProxy; + + template + class IOPtr { + template + friend class IOProxy; + + public: + typedef T element_type; + + inline IOPtr() : ptr_(0) {} + inline IOPtr(T *ptr) : ptr_(ptr) {} + IOPtr(const IOProxy &p); + + IOPtr &operator=(const IOProxy &p); + inline IOPtr &operator=(const IOPtr &p) { + ptr_ = p.ptr_; + return *this; } - // In the user code, the following function can be usually wrapped - // as follows: - // - // #define io_proxy(obj) gs::make_IOProxy( obj , #obj ) - // - template - inline IOProxy make_IOProxy(T& obj, const char* name) - { - return IOProxy(&obj, name); + // Typical pointer operations + inline T *get() const { return ptr_; } + inline T *operator->() const { + if (!ptr_) + throw gs::IOInvalidArgument("In gs::IOPtr::operator->: attempt to dereference null pointer"); + return ptr_; + } + inline T &operator*() const { + if (!ptr_) + throw gs::IOInvalidArgument("In gs::IOPtr::operator*: attempt to dereference null pointer"); + return *ptr_; + } + inline IOPtr &operator++() { + ++ptr_; + return *this; + } + inline void operator++(int) { ++ptr_; } + inline IOPtr &operator--() { + --ptr_; + return *this; + } + inline void operator--(int) { --ptr_; } + + // Implicit conversion to "bool" + inline operator bool() const { return !(ptr_ == 0); } + + // Names are ignored during comparisons + inline bool operator==(const IOPtr &r) const { return ptr_ == r.ptr_; } + inline bool operator!=(const IOPtr &r) const { return ptr_ != r.ptr_; } + bool operator==(const IOProxy &r) const; + bool operator!=(const IOProxy &r) const; + + // Should be able to work as with bare pointer inside the I/O code + inline T *&getIOReference() { return ptr_; } + inline T *const &getIOReference() const { + if (!ptr_) + throw gs::IOInvalidArgument( + "In gs::IOPtr::getIOReference: unusable " + "const reference to null pointer"); + return ptr_; } -} -// IOPtr methods which could not be defined earlier -namespace gs { - template - inline IOPtr::IOPtr(const IOProxy& p) : ptr_(p.ptr_) {} + private: + T *ptr_; + }; + + template + class IOProxy { + template + friend class IOPtr; + + public: + typedef T element_type; + + inline IOProxy() : ptr_(0) {} + inline IOProxy(T *ptr) : ptr_(ptr) {} + inline IOProxy(T *ptr, const char *varname) : ptr_(ptr), name_(varname ? varname : "") {} + inline IOProxy(T *ptr, const std::string &varname) : ptr_(ptr), name_(varname) {} + inline IOProxy(const IOPtr &p) : ptr_(p.ptr_) {} + inline IOProxy(const IOPtr &p, const char *varname) : ptr_(p.ptr_), name_(varname ? varname : "") {} + inline IOProxy(const IOPtr &p, const std::string &varname) : ptr_(p.ptr_), name_(varname) {} + + inline IOProxy &operator=(const IOProxy &p) { + ptr_ = p.ptr_; + name_ = p.name_; + return *this; + } + inline IOProxy &operator=(const IOPtr &p) { + ptr_ = p.ptr_; + name_ = ""; + return *this; + } - template - inline IOPtr& IOPtr::operator=(const IOProxy& p) - {ptr_ = p.ptr_; return *this;} + // Get name + inline const std::string &name() const { return name_; } - template - inline bool IOPtr::operator==(const IOProxy& r) const - {return ptr_ == r.ptr_;} + // Set name + inline IOProxy &setName(const char *varname) { + name_ = varname ? varname : ""; + return *this; + } + inline IOProxy &setName(const std::string &varname) { + name_ = varname; + return *this; + } - template - inline bool IOPtr::operator!=(const IOProxy& r) const - {return ptr_ != r.ptr_;} -} + // Typical pointer operations + inline T *get() const { return ptr_; } + inline T *operator->() const { + if (!ptr_) + throw gs::IOInvalidArgument("In gs::IOProxy::operator->: attempt to dereference null pointer"); + return ptr_; + } + inline T &operator*() const { + if (!ptr_) + throw gs::IOInvalidArgument("In gs::IOProxy::operator*: attempt to dereference null pointer"); + return *ptr_; + } + inline IOProxy &operator++() { + ++ptr_; + return *this; + } + inline void operator++(int) { ++ptr_; } + inline IOProxy &operator--() { + --ptr_; + return *this; + } + inline void operator--(int) { --ptr_; } + + // Implicit conversion to "bool" + inline operator bool() const { return !(ptr_ == 0); } + + // Names are ignored during comparisons + inline bool operator==(const IOProxy &r) const { return ptr_ == r.ptr_; } + inline bool operator!=(const IOProxy &r) const { return ptr_ != r.ptr_; } + inline bool operator==(const IOPtr &r) const { return ptr_ == r.ptr_; } + inline bool operator!=(const IOPtr &r) const { return ptr_ != r.ptr_; } + + // Should be able to work as with bare pointer inside the I/O code + inline T *&getIOReference() { return ptr_; } + inline T *const &getIOReference() const { + if (!ptr_) + throw gs::IOInvalidArgument( + "In gs::IOProxy::getIOReference: unusable " + "const reference to null pointer"); + return ptr_; + } -#endif // GENERS_IOPTR_HH_ + private: + T *ptr_; + std::string name_; + }; + + // Convenience function for making IOPtr objects + template + inline IOPtr make_IOPtr(T &obj) { + return IOPtr(&obj); + } + + // In the user code, the following function can be usually wrapped + // as follows: + // + // #define io_proxy(obj) gs::make_IOProxy( obj , #obj ) + // + template + inline IOProxy make_IOProxy(T &obj, const char *name) { + return IOProxy(&obj, name); + } +} // namespace gs +// IOPtr methods which could not be defined earlier +namespace gs { + template + inline IOPtr::IOPtr(const IOProxy &p) : ptr_(p.ptr_) {} + + template + inline IOPtr &IOPtr::operator=(const IOProxy &p) { + ptr_ = p.ptr_; + return *this; + } + + template + inline bool IOPtr::operator==(const IOProxy &r) const { + return ptr_ == r.ptr_; + } + + template + inline bool IOPtr::operator!=(const IOProxy &r) const { + return ptr_ != r.ptr_; + } +} // namespace gs + +#endif // GENERS_IOPTR_HH_ diff --git a/Alignment/Geners/interface/IOTraits.hh b/Alignment/Geners/interface/IOTraits.hh index 10cf3451585a3..7c64ee549b2f5 100644 --- a/Alignment/Geners/interface/IOTraits.hh +++ b/Alignment/Geners/interface/IOTraits.hh @@ -3,140 +3,111 @@ #include +#include "Alignment/Geners/interface/IOIsClassType.hh" +#include "Alignment/Geners/interface/IOIsContainer.hh" +#include "Alignment/Geners/interface/IOIsContiguous.hh" +#include "Alignment/Geners/interface/IOIsExternal.hh" +#include "Alignment/Geners/interface/IOIsIOPtr.hh" #include "Alignment/Geners/interface/IOIsPOD.hh" #include "Alignment/Geners/interface/IOIsPair.hh" +#include "Alignment/Geners/interface/IOIsReadable.hh" +#include "Alignment/Geners/interface/IOIsSharedPtr.hh" #include "Alignment/Geners/interface/IOIsString.hh" #include "Alignment/Geners/interface/IOIsTuple.hh" -#include "Alignment/Geners/interface/IOIsContainer.hh" #include "Alignment/Geners/interface/IOIsWritable.hh" -#include "Alignment/Geners/interface/IOIsReadable.hh" -#include "Alignment/Geners/interface/IOIsExternal.hh" -#include "Alignment/Geners/interface/IOIsSharedPtr.hh" -#include "Alignment/Geners/interface/IOIsIOPtr.hh" -#include "Alignment/Geners/interface/IOIsClassType.hh" -#include "Alignment/Geners/interface/IOIsContiguous.hh" namespace gs { - template - struct IOTraits - { - static const bool IsClass = IOIsClassType::value; - enum {ISCLASS = 1}; - - // Pointers are not PODs for I/O purposes. - // - // It looks like std::array of PODs is itself considered - // a POD by the "CPP11_is_pod" template, at least by some - // g++ versions (in particular, 4.4.5). This is a bug/feature - // that we need to avoid. - static const bool IsPOD = (IOIsPOD::value && - !IOIsContainer::value && - !CPP11_is_pointer::value && - !IOIsExternal::value); - enum {ISPOD = 2}; - - static const bool IsWritable = (IOIsWritable::value && - !IOIsExternal::value); - enum {ISWRITABLE = 4}; - - static const bool IsStdContainer = (IOIsContainer::value && - !IOIsWritable::value && - !IOIsExternal::value); - enum {ISSTDCONTAINER = 8}; - - // Readable objects are required to be writable - static const bool IsPlaceReadable = (IOIsPlaceReadable::value && - IOIsWritable::value); - enum {ISPLACEREADABLE = 16}; - - // Prefer place readability to heap readability - static const bool IsHeapReadable = (IOIsHeapReadable::value && - !IOIsPlaceReadable::value && - IOIsWritable::value); - enum {ISHEAPREADABLE = 32}; - - static const bool IsPointer = (CPP11_is_pointer::value && - !IOIsExternal::value); - enum {ISPOINTER = 64}; - - static const bool IsSharedPtr = (IOIsSharedPtr::value && - !IOIsExternal::value); - enum {ISSHAREDPTR = 128}; - - static const bool IsPair = IOIsPair::value; - enum {ISPAIR = 256}; - - static const bool IsString = IOIsString::value; - enum {ISSTRING = 512}; - - // The following trait is relevant for containers only - static const bool IsContiguous = IOIsContiguous::value; - enum {ISCONTIGUOUS = 1024}; - - static const bool IsTuple = IOIsTuple::value; - enum {ISTUPLE = 2048}; - - static const bool IsIOPtr = IOIsIOPtr::value; - enum {ISIOPTR = 4096}; - - // A catch-all definition for externally defined types which - // want to use the template-based I/O within this system but - // do not want to implement the standard "read/write" mechanism. - // The user has to declare the external type by modifying the - // "IOIsExternal" template. - static const bool IsExternal = IOIsExternal::value; - enum {ISEXTERNAL = 8192}; - - // Special enums for heap-readable objects known - // to be called with zero pointer as an argument. - // In this case we will avoid compiling an assignment - // operator for the object. - enum {ISNULLPOINTER = 16384}; - enum {ISPUREHEAPREADABLE = 32768}; - - static const int Signature = - IsClass*ISCLASS + - IsPOD*ISPOD + - IsWritable*ISWRITABLE + - IsStdContainer*ISSTDCONTAINER + - IsPlaceReadable*ISPLACEREADABLE + - IsHeapReadable*ISHEAPREADABLE + - IsPointer*ISPOINTER + - IsSharedPtr*ISSHAREDPTR + - IsPair*ISPAIR + - IsString*ISSTRING + - IsContiguous*ISCONTIGUOUS + - IsTuple*ISTUPLE + - IsIOPtr*ISIOPTR + - IsExternal*ISEXTERNAL + - IsPointer*ISNULLPOINTER + - IsHeapReadable*ISPUREHEAPREADABLE; - }; - - template - inline IOTraits IOItemTraits(const T&) {return IOTraits();} -} + template + struct IOTraits { + static const bool IsClass = IOIsClassType::value; + enum { ISCLASS = 1 }; + + // Pointers are not PODs for I/O purposes. + // + // It looks like std::array of PODs is itself considered + // a POD by the "CPP11_is_pod" template, at least by some + // g++ versions (in particular, 4.4.5). This is a bug/feature + // that we need to avoid. + static const bool IsPOD = + (IOIsPOD::value && !IOIsContainer::value && !CPP11_is_pointer::value && !IOIsExternal::value); + enum { ISPOD = 2 }; + + static const bool IsWritable = (IOIsWritable::value && !IOIsExternal::value); + enum { ISWRITABLE = 4 }; + + static const bool IsStdContainer = (IOIsContainer::value && !IOIsWritable::value && !IOIsExternal::value); + enum { ISSTDCONTAINER = 8 }; + + // Readable objects are required to be writable + static const bool IsPlaceReadable = (IOIsPlaceReadable::value && IOIsWritable::value); + enum { ISPLACEREADABLE = 16 }; + + // Prefer place readability to heap readability + static const bool IsHeapReadable = + (IOIsHeapReadable::value && !IOIsPlaceReadable::value && IOIsWritable::value); + enum { ISHEAPREADABLE = 32 }; + + static const bool IsPointer = (CPP11_is_pointer::value && !IOIsExternal::value); + enum { ISPOINTER = 64 }; + + static const bool IsSharedPtr = (IOIsSharedPtr::value && !IOIsExternal::value); + enum { ISSHAREDPTR = 128 }; + + static const bool IsPair = IOIsPair::value; + enum { ISPAIR = 256 }; + + static const bool IsString = IOIsString::value; + enum { ISSTRING = 512 }; + + // The following trait is relevant for containers only + static const bool IsContiguous = IOIsContiguous::value; + enum { ISCONTIGUOUS = 1024 }; + + static const bool IsTuple = IOIsTuple::value; + enum { ISTUPLE = 2048 }; + + static const bool IsIOPtr = IOIsIOPtr::value; + enum { ISIOPTR = 4096 }; + + // A catch-all definition for externally defined types which + // want to use the template-based I/O within this system but + // do not want to implement the standard "read/write" mechanism. + // The user has to declare the external type by modifying the + // "IOIsExternal" template. + static const bool IsExternal = IOIsExternal::value; + enum { ISEXTERNAL = 8192 }; + + // Special enums for heap-readable objects known + // to be called with zero pointer as an argument. + // In this case we will avoid compiling an assignment + // operator for the object. + enum { ISNULLPOINTER = 16384 }; + enum { ISPUREHEAPREADABLE = 32768 }; + + static const int Signature = IsClass * ISCLASS + IsPOD * ISPOD + IsWritable * ISWRITABLE + + IsStdContainer * ISSTDCONTAINER + IsPlaceReadable * ISPLACEREADABLE + + IsHeapReadable * ISHEAPREADABLE + IsPointer * ISPOINTER + IsSharedPtr * ISSHAREDPTR + + IsPair * ISPAIR + IsString * ISSTRING + IsContiguous * ISCONTIGUOUS + + IsTuple * ISTUPLE + IsIOPtr * ISIOPTR + IsExternal * ISEXTERNAL + + IsPointer * ISNULLPOINTER + IsHeapReadable * ISPUREHEAPREADABLE; + }; + + template + inline IOTraits IOItemTraits(const T &) { + return IOTraits(); + } +} // namespace gs template -std::ostream& operator<<(std::ostream& os, const gs::IOTraits&) -{ - typedef gs::IOTraits Tr; - os << "IsClass = " << Tr::IsClass - << ", IsPOD = " << Tr::IsPOD - << ", IsWritable = " << Tr::IsWritable - << ", IsStdContainer = " << Tr::IsStdContainer - << ", IsPlaceReadable = " << Tr::IsPlaceReadable - << ", IsHeapReadable = " << Tr::IsHeapReadable - << ", IsPointer = " << Tr::IsPointer - << ", IsSharedPtr = " << Tr::IsSharedPtr - << ", IsPair = " << Tr::IsPair - << ", IsString = " << Tr::IsString - << ", IsContiguous = " << Tr::IsContiguous - << ", IsTuple = " << Tr::IsTuple - << ", IsIOPtr = " << Tr::IsIOPtr - << ", IsExternal = " << Tr::IsExternal; - return os; +std::ostream &operator<<(std::ostream &os, const gs::IOTraits &) { + typedef gs::IOTraits Tr; + os << "IsClass = " << Tr::IsClass << ", IsPOD = " << Tr::IsPOD << ", IsWritable = " << Tr::IsWritable + << ", IsStdContainer = " << Tr::IsStdContainer << ", IsPlaceReadable = " << Tr::IsPlaceReadable + << ", IsHeapReadable = " << Tr::IsHeapReadable << ", IsPointer = " << Tr::IsPointer + << ", IsSharedPtr = " << Tr::IsSharedPtr << ", IsPair = " << Tr::IsPair << ", IsString = " << Tr::IsString + << ", IsContiguous = " << Tr::IsContiguous << ", IsTuple = " << Tr::IsTuple << ", IsIOPtr = " << Tr::IsIOPtr + << ", IsExternal = " << Tr::IsExternal; + return os; } -#endif // GENERS_IOTRAITS_HH_ - +#endif // GENERS_IOTRAITS_HH_ diff --git a/Alignment/Geners/interface/InsertContainerItem.hh b/Alignment/Geners/interface/InsertContainerItem.hh index e43237ed2556b..dd1aa6c2845e5 100644 --- a/Alignment/Geners/interface/InsertContainerItem.hh +++ b/Alignment/Geners/interface/InsertContainerItem.hh @@ -4,16 +4,12 @@ #include namespace gs { - template - struct InsertContainerItem - { - static inline void insert(T& obj, const typename T::value_type& item, - const std::size_t /* itemNumber */) - { - obj.push_back(item); - } - }; -} - -#endif // GENERS_INSERTCONTAINERITEM_HH_ - + template + struct InsertContainerItem { + static inline void insert(T &obj, const typename T::value_type &item, const std::size_t /* itemNumber */) { + obj.push_back(item); + } + }; +} // namespace gs + +#endif // GENERS_INSERTCONTAINERITEM_HH_ diff --git a/Alignment/Geners/interface/Int2Type.hh b/Alignment/Geners/interface/Int2Type.hh index 9419390260cff..9d749f2a84d3a 100644 --- a/Alignment/Geners/interface/Int2Type.hh +++ b/Alignment/Geners/interface/Int2Type.hh @@ -4,27 +4,23 @@ #include namespace gs { - namespace Private { - inline std::string makeInt2TypeStage(const int v) - { - std::ostringstream os; - os << "Int2Type::" << v; - return os.str(); - } + namespace Private { + inline std::string makeInt2TypeStage(const int v) { + std::ostringstream os; + os << "Int2Type::" << v; + return os.str(); } + } // namespace Private - template - struct Int2Type - { - enum {value = v}; + template + struct Int2Type { + enum { value = v }; - static const char* stage() - { - static const std::string buf(Private::makeInt2TypeStage(v)); - return buf.c_str(); - } - }; -} - -#endif // GENERS_INT2TYPE_HH_ + static const char *stage() { + static const std::string buf(Private::makeInt2TypeStage(v)); + return buf.c_str(); + } + }; +} // namespace gs +#endif // GENERS_INT2TYPE_HH_ diff --git a/Alignment/Geners/interface/ItemDescriptor.hh b/Alignment/Geners/interface/ItemDescriptor.hh index 6e15005bccae6..a069c40a801b7 100644 --- a/Alignment/Geners/interface/ItemDescriptor.hh +++ b/Alignment/Geners/interface/ItemDescriptor.hh @@ -4,51 +4,44 @@ #define GENERS_ITEMDESCRIPTOR_HH_ #include -#include #include +#include #include "Alignment/Geners/interface/ClassId.hh" namespace gs { - class ItemDescriptor - { - public: - ItemDescriptor(); - ItemDescriptor(const ClassId& classId, const char* ioPrototype, - const char* name, const char* category); - inline virtual ~ItemDescriptor() {} - - inline const ClassId& type() const {return classId_;} - inline const std::string& ioPrototype() const {return ioProto_;} - inline const std::string& name() const {return nameCat_.first;} - inline const std::string& category() const {return nameCat_.second;} - inline const std::pair& nameAndCategory() - const {return nameCat_;} - - inline bool operator==(const ItemDescriptor& r) const - {return (typeid(*this) == typeid(r)) && this->isEqual(r);} - inline bool operator!=(const ItemDescriptor& r) const - {return !(*this == r);} - - // The following returns "true" if the class id and - // I/O prototype of this item coincide with those of - // the argument - bool isSameClassIdandIO(const ItemDescriptor& r) const; - - // The following method checks I/O prototype only - // allowing for class id mismatch - inline bool isSameIOPrototype(const ItemDescriptor& r) const - {return ioProto_ == r.ioProto_;} - - protected: - virtual bool isEqual(const ItemDescriptor&) const; - - private: - ClassId classId_; - std::string ioProto_; - std::pair nameCat_; - }; -} - -#endif // GENERS_ITEMDESCRIPTOR_HH_ - + class ItemDescriptor { + public: + ItemDescriptor(); + ItemDescriptor(const ClassId &classId, const char *ioPrototype, const char *name, const char *category); + inline virtual ~ItemDescriptor() {} + + inline const ClassId &type() const { return classId_; } + inline const std::string &ioPrototype() const { return ioProto_; } + inline const std::string &name() const { return nameCat_.first; } + inline const std::string &category() const { return nameCat_.second; } + inline const std::pair &nameAndCategory() const { return nameCat_; } + + inline bool operator==(const ItemDescriptor &r) const { return (typeid(*this) == typeid(r)) && this->isEqual(r); } + inline bool operator!=(const ItemDescriptor &r) const { return !(*this == r); } + + // The following returns "true" if the class id and + // I/O prototype of this item coincide with those of + // the argument + bool isSameClassIdandIO(const ItemDescriptor &r) const; + + // The following method checks I/O prototype only + // allowing for class id mismatch + inline bool isSameIOPrototype(const ItemDescriptor &r) const { return ioProto_ == r.ioProto_; } + + protected: + virtual bool isEqual(const ItemDescriptor &) const; + + private: + ClassId classId_; + std::string ioProto_; + std::pair nameCat_; + }; +} // namespace gs + +#endif // GENERS_ITEMDESCRIPTOR_HH_ diff --git a/Alignment/Geners/interface/ItemLocation.hh b/Alignment/Geners/interface/ItemLocation.hh index 2deef11395f5a..10f2e9a059b2e 100644 --- a/Alignment/Geners/interface/ItemLocation.hh +++ b/Alignment/Geners/interface/ItemLocation.hh @@ -1,52 +1,43 @@ #ifndef GENERS_ITEMLOCATION_HH_ #define GENERS_ITEMLOCATION_HH_ -#include #include +#include #include "Alignment/Geners/interface/ClassId.hh" namespace gs { - class ItemLocation - { - public: - inline ItemLocation(std::streampos pos, const char* URI, - const char* cachedItemURI=0) - : pos_(pos), - URI_(URI ? URI : ""), - cachedItemURI_(cachedItemURI ? cachedItemURI : "") {} - - inline std::streampos streamPosition() const {return pos_;} - inline const std::string& URI() const {return URI_;} - inline const std::string& cachedItemURI() const - {return cachedItemURI_;} - - inline void setStreamPosition(std::streampos pos) {pos_ = pos;} - inline void setURI(const char* newURI) - {URI_ = newURI ? newURI : "";} - inline void setCachedItemURI(const char* newURI) - {cachedItemURI_ = newURI ? newURI : "";} - - bool operator==(const ItemLocation& r) const; - inline bool operator!=(const ItemLocation& r) const - {return !(*this == r);} - - // Methods related to I/O - inline ClassId classId() const {return ClassId(*this);} - bool write(std::ostream& of) const; - - static inline const char* classname() {return "gs::ItemLocation";} - static inline unsigned version() {return 1;} - static ItemLocation* read(const ClassId& id, std::istream& in); - - private: - ItemLocation(); - - std::streampos pos_; - std::string URI_; - std::string cachedItemURI_; - }; -} - -#endif // GENERS_ITEMLOCATION_HH_ + class ItemLocation { + public: + inline ItemLocation(std::streampos pos, const char *URI, const char *cachedItemURI = nullptr) + : pos_(pos), URI_(URI ? URI : ""), cachedItemURI_(cachedItemURI ? cachedItemURI : "") {} + + inline std::streampos streamPosition() const { return pos_; } + inline const std::string &URI() const { return URI_; } + inline const std::string &cachedItemURI() const { return cachedItemURI_; } + + inline void setStreamPosition(std::streampos pos) { pos_ = pos; } + inline void setURI(const char *newURI) { URI_ = newURI ? newURI : ""; } + inline void setCachedItemURI(const char *newURI) { cachedItemURI_ = newURI ? newURI : ""; } + + bool operator==(const ItemLocation &r) const; + inline bool operator!=(const ItemLocation &r) const { return !(*this == r); } + + // Methods related to I/O + inline ClassId classId() const { return ClassId(*this); } + bool write(std::ostream &of) const; + + static inline const char *classname() { return "gs::ItemLocation"; } + static inline unsigned version() { return 1; } + static ItemLocation *read(const ClassId &id, std::istream &in); + + private: + ItemLocation() = delete; + + std::streampos pos_; + std::string URI_; + std::string cachedItemURI_; + }; +} // namespace gs +#endif // GENERS_ITEMLOCATION_HH_ diff --git a/Alignment/Geners/interface/MultiFileArchive.hh b/Alignment/Geners/interface/MultiFileArchive.hh index aa8c4eaae2030..a040ef4a6b935 100644 --- a/Alignment/Geners/interface/MultiFileArchive.hh +++ b/Alignment/Geners/interface/MultiFileArchive.hh @@ -7,71 +7,68 @@ #include "Alignment/Geners/interface/CatalogIO.hh" namespace gs { - class MultiFileArchive : public BinaryArchiveBase - { - public: - // See the note inside the "BinaryArchiveBase.hh" header - // for the meaning of the "mode" argument - MultiFileArchive(const char* basename, const char* mode, - const char* annotation = 0, - unsigned typicalFileSizeInMB = 1000U, - unsigned dataFileBufferSize = 1048576U, - unsigned catalogFileBufferSize = 131072U); - virtual ~MultiFileArchive(); + class MultiFileArchive : public BinaryArchiveBase { + public: + // See the note inside the "BinaryArchiveBase.hh" header + // for the meaning of the "mode" argument + MultiFileArchive(const char *basename, + const char *mode, + const char *annotation = nullptr, + unsigned typicalFileSizeInMB = 1000U, + unsigned dataFileBufferSize = 1048576U, + unsigned catalogFileBufferSize = 131072U); + ~MultiFileArchive() override; - void flush(); + void flush() override; - private: - void writeCatalog(); - void openWriteStream(); - void setupWriteStream(); - void updateReadStream(const std::string& uri); - void releaseBuffers(); + private: + void writeCatalog(); + void openWriteStream(); + void setupWriteStream(); + void updateReadStream(const std::string &uri); + void releaseBuffers(); - template - void readCatalog() - { - assert(!catalog()); - unsigned compressionMode; - setCatalog(readBinaryCatalog( - catStream_, &compressionMode, &catalogMergeLevel_, - &catalogAnnotations_, true)); - assert(catalog()); - setCompressionMode(compressionMode); - } + template + void readCatalog() { + assert(!catalog()); + unsigned compressionMode; + setCatalog( + readBinaryCatalog(catStream_, &compressionMode, &catalogMergeLevel_, &catalogAnnotations_, true)); + assert(catalog()); + setCompressionMode(compressionMode); + } - // The following methods have to be overriden from the base - std::ostream& plainOutputStream(); - std::istream& plainInputStream(unsigned long long id, - unsigned* compressionCode, - unsigned long long* length); + // The following methods have to be overriden from the base + std::ostream &plainOutputStream() override; + std::istream &plainInputStream(unsigned long long id, + unsigned *compressionCode, + unsigned long long *length) override; - unsigned long long addToCatalog( - const AbsRecord& record, unsigned compressionCode, - unsigned long long itemLength); + unsigned long long addToCatalog(const AbsRecord &record, + unsigned compressionCode, + unsigned long long itemLength) override; - char* filebuf_; - char* readbuf_; - char* catabuf_; - std::string annotation_; - std::string catalogFileName_; - std::string writeFileName_; - std::string writeFileURI_; - std::string readFileName_; - std::string readFileURI_; - std::fstream writeStream_; - std::fstream catStream_; - std::fstream separateReadStream_; - std::streampos lastpos_; - std::streampos jumppos_; - std::streampos maxpos_; - std::vector catalogAnnotations_; - unsigned long writeFileNumber_; - unsigned catalogMergeLevel_; - bool annotationsMerged_; - bool streamFlushed_; - }; -} - -#endif // GENERS_MULTIFILEARCHIVE_HH_ + char *filebuf_; + char *readbuf_; + char *catabuf_; + std::string annotation_; + std::string catalogFileName_; + std::string writeFileName_; + std::string writeFileURI_; + std::string readFileName_; + std::string readFileURI_; + std::fstream writeStream_; + std::fstream catStream_; + std::fstream separateReadStream_; + std::streampos lastpos_; + std::streampos jumppos_; + std::streampos maxpos_; + std::vector catalogAnnotations_; + unsigned long writeFileNumber_; + unsigned catalogMergeLevel_; + bool annotationsMerged_; + bool streamFlushed_; + }; +} // namespace gs +#endif // GENERS_MULTIFILEARCHIVE_HH_ diff --git a/Alignment/Geners/interface/ProcessItem.hh b/Alignment/Geners/interface/ProcessItem.hh index 69e2621b1ccfb..26d2297427fc9 100644 --- a/Alignment/Geners/interface/ProcessItem.hh +++ b/Alignment/Geners/interface/ProcessItem.hh @@ -30,32 +30,27 @@ #include "Alignment/Geners/interface/Int2Type.hh" namespace gs { - // Special types to designate stages in container processing - struct InContainerHeader - { - static const char* stage() {return "InContainerHeader";} - }; + // Special types to designate stages in container processing + struct InContainerHeader { + static const char *stage() { return "InContainerHeader"; } + }; - struct InContainerSize - { - static const char* stage() {return "InContainerSize";} - }; + struct InContainerSize { + static const char *stage() { return "InContainerSize"; } + }; - struct InContainerFooter - { - static const char* stage() {return "InContainerFooter";} - }; + struct InContainerFooter { + static const char *stage() { return "InContainerFooter"; } + }; - struct InContainerCycle - { - static const char* stage() {return "InContainerCycle";} - }; + struct InContainerCycle { + static const char *stage() { return "InContainerCycle"; } + }; - struct InPODArray - { - static const char* stage() {return "InPODArray";} - }; -} + struct InPODArray { + static const char *stage() { return "InPODArray"; } + }; +} // namespace gs // I am not aware of an easy way to have both const and non-const // version of a template defined in the same code fragment. This is @@ -81,8 +76,8 @@ namespace gs { #undef GENERS_CONTAINER_ITERATION_PROC #endif -#ifdef GENERS_GENERIC_ITEM_PROCESSOR -#undef GENERS_GENERIC_ITEM_PROCESSOR +#ifdef GENERS_GENERIC_ITEM_PROCESSOR +#undef GENERS_GENERIC_ITEM_PROCESSOR #endif #ifdef GENERS_GENERATE_CONST_IO_PROCESSOR @@ -98,322 +93,185 @@ namespace gs { #endif namespace gs { - namespace Private { - template - < - template class Visitor, - typename T, - typename Arg1, - typename Arg2, - int Mode - > - struct GENERS_GENERATED_IO_PROCESSOR ; - } -} + namespace Private { + template