Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-05-29 23:13:16

0001 #include <numeric>
0002 #include <iomanip>
0003 #include <sstream>
0004 
0005 #include "Validation/HGCalValidation/interface/HGVHistoProducerAlgo.h"
0006 #include "FWCore/MessageLogger/interface/MessageLogger.h"
0007 #include "SimDataFormats/CaloAnalysis/interface/SimCluster.h"
0008 #include "TMath.h"
0009 #include "TLatex.h"
0010 #include "TF1.h"
0011 
0012 using namespace std;
0013 
0014 //Parameters for the score cut. Later, this will become part of the
0015 //configuration parameter for the HGCAL associator.
0016 const double ScoreCutLCtoCP_ = 0.1;
0017 const double ScoreCutCPtoLC_ = 0.1;
0018 const double ScoreCutLCtoSC_ = 0.1;
0019 const double ScoreCutSCtoLC_ = 0.1;
0020 const double ScoreCutTStoSTSFakeMerge_[] = {0.6, FLT_MIN};  //1.e-09
0021 const double ScoreCutSTStoTSPurDup_[] = {0.2, FLT_MIN};     //1.e-11
0022 
0023 HGVHistoProducerAlgo::HGVHistoProducerAlgo(const edm::ParameterSet& pset)
0024     :  //parameters for eta
0025       minEta_(pset.getParameter<double>("minEta")),
0026       maxEta_(pset.getParameter<double>("maxEta")),
0027       nintEta_(pset.getParameter<int>("nintEta")),
0028       useFabsEta_(pset.getParameter<bool>("useFabsEta")),
0029 
0030       //parameters for energy
0031       minEne_(pset.getParameter<double>("minEne")),
0032       maxEne_(pset.getParameter<double>("maxEne")),
0033       nintEne_(pset.getParameter<int>("nintEne")),
0034 
0035       //parameters for pt
0036       minPt_(pset.getParameter<double>("minPt")),
0037       maxPt_(pset.getParameter<double>("maxPt")),
0038       nintPt_(pset.getParameter<int>("nintPt")),
0039 
0040       //parameters for phi
0041       minPhi_(pset.getParameter<double>("minPhi")),
0042       maxPhi_(pset.getParameter<double>("maxPhi")),
0043       nintPhi_(pset.getParameter<int>("nintPhi")),
0044 
0045       //parameters for counting mixed hits SimClusters
0046       minMixedHitsSimCluster_(pset.getParameter<double>("minMixedHitsSimCluster")),
0047       maxMixedHitsSimCluster_(pset.getParameter<double>("maxMixedHitsSimCluster")),
0048       nintMixedHitsSimCluster_(pset.getParameter<int>("nintMixedHitsSimCluster")),
0049 
0050       //parameters for counting mixed hits clusters
0051       minMixedHitsCluster_(pset.getParameter<double>("minMixedHitsCluster")),
0052       maxMixedHitsCluster_(pset.getParameter<double>("maxMixedHitsCluster")),
0053       nintMixedHitsCluster_(pset.getParameter<int>("nintMixedHitsCluster")),
0054 
0055       //parameters for the total amount of energy clustered by all layer clusters (fraction over CaloParticless)
0056       minEneCl_(pset.getParameter<double>("minEneCl")),
0057       maxEneCl_(pset.getParameter<double>("maxEneCl")),
0058       nintEneCl_(pset.getParameter<int>("nintEneCl")),
0059 
0060       //parameters for the longitudinal depth barycenter.
0061       minLongDepBary_(pset.getParameter<double>("minLongDepBary")),
0062       maxLongDepBary_(pset.getParameter<double>("maxLongDepBary")),
0063       nintLongDepBary_(pset.getParameter<int>("nintLongDepBary")),
0064 
0065       //parameters for z positionof vertex plots
0066       minZpos_(pset.getParameter<double>("minZpos")),
0067       maxZpos_(pset.getParameter<double>("maxZpos")),
0068       nintZpos_(pset.getParameter<int>("nintZpos")),
0069 
0070       //Parameters for the total number of SimClusters per layer
0071       minTotNsimClsperlay_(pset.getParameter<double>("minTotNsimClsperlay")),
0072       maxTotNsimClsperlay_(pset.getParameter<double>("maxTotNsimClsperlay")),
0073       nintTotNsimClsperlay_(pset.getParameter<int>("nintTotNsimClsperlay")),
0074 
0075       //Parameters for the total number of layer clusters per layer
0076       minTotNClsperlay_(pset.getParameter<double>("minTotNClsperlay")),
0077       maxTotNClsperlay_(pset.getParameter<double>("maxTotNClsperlay")),
0078       nintTotNClsperlay_(pset.getParameter<int>("nintTotNClsperlay")),
0079 
0080       //Parameters for the energy clustered by layer clusters per layer (fraction over CaloParticless)
0081       minEneClperlay_(pset.getParameter<double>("minEneClperlay")),
0082       maxEneClperlay_(pset.getParameter<double>("maxEneClperlay")),
0083       nintEneClperlay_(pset.getParameter<int>("nintEneClperlay")),
0084 
0085       //Parameters for the score both for:
0086       //1. calo particle to layer clusters association per layer
0087       //2. layer cluster to calo particles association per layer
0088       minScore_(pset.getParameter<double>("minScore")),
0089       maxScore_(pset.getParameter<double>("maxScore")),
0090       nintScore_(pset.getParameter<int>("nintScore")),
0091 
0092       //Parameters for shared energy fraction. That is:
0093       //1. Fraction of each of the layer clusters energy related to a
0094       //calo particle over that calo particle's energy.
0095       //2. Fraction of each of the calo particles energy
0096       //related to a layer cluster over that layer cluster's energy.
0097       minSharedEneFrac_(pset.getParameter<double>("minSharedEneFrac")),
0098       maxSharedEneFrac_(pset.getParameter<double>("maxSharedEneFrac")),
0099       nintSharedEneFrac_(pset.getParameter<int>("nintSharedEneFrac")),
0100       minTSTSharedEneFracEfficiency_(pset.getParameter<double>("minTSTSharedEneFracEfficiency")),
0101 
0102       //Same as above for Tracksters
0103       minTSTSharedEneFrac_(pset.getParameter<double>("minTSTSharedEneFrac")),
0104       maxTSTSharedEneFrac_(pset.getParameter<double>("maxTSTSharedEneFrac")),
0105       nintTSTSharedEneFrac_(pset.getParameter<int>("nintTSTSharedEneFrac")),
0106 
0107       //Parameters for the total number of SimClusters per thickness
0108       minTotNsimClsperthick_(pset.getParameter<double>("minTotNsimClsperthick")),
0109       maxTotNsimClsperthick_(pset.getParameter<double>("maxTotNsimClsperthick")),
0110       nintTotNsimClsperthick_(pset.getParameter<int>("nintTotNsimClsperthick")),
0111 
0112       //Parameters for the total number of layer clusters per thickness
0113       minTotNClsperthick_(pset.getParameter<double>("minTotNClsperthick")),
0114       maxTotNClsperthick_(pset.getParameter<double>("maxTotNClsperthick")),
0115       nintTotNClsperthick_(pset.getParameter<int>("nintTotNClsperthick")),
0116 
0117       //Parameters for the total number of cells per per thickness per layer
0118       minTotNcellsperthickperlayer_(pset.getParameter<double>("minTotNcellsperthickperlayer")),
0119       maxTotNcellsperthickperlayer_(pset.getParameter<double>("maxTotNcellsperthickperlayer")),
0120       nintTotNcellsperthickperlayer_(pset.getParameter<int>("nintTotNcellsperthickperlayer")),
0121 
0122       //Parameters for the distance of cluster cells to seed cell per thickness per layer
0123       minDisToSeedperthickperlayer_(pset.getParameter<double>("minDisToSeedperthickperlayer")),
0124       maxDisToSeedperthickperlayer_(pset.getParameter<double>("maxDisToSeedperthickperlayer")),
0125       nintDisToSeedperthickperlayer_(pset.getParameter<int>("nintDisToSeedperthickperlayer")),
0126 
0127       //Parameters for the energy weighted distance of cluster cells to seed cell per thickness per layer
0128       minDisToSeedperthickperlayerenewei_(pset.getParameter<double>("minDisToSeedperthickperlayerenewei")),
0129       maxDisToSeedperthickperlayerenewei_(pset.getParameter<double>("maxDisToSeedperthickperlayerenewei")),
0130       nintDisToSeedperthickperlayerenewei_(pset.getParameter<int>("nintDisToSeedperthickperlayerenewei")),
0131 
0132       //Parameters for the distance of cluster cells to max cell per thickness per layer
0133       minDisToMaxperthickperlayer_(pset.getParameter<double>("minDisToMaxperthickperlayer")),
0134       maxDisToMaxperthickperlayer_(pset.getParameter<double>("maxDisToMaxperthickperlayer")),
0135       nintDisToMaxperthickperlayer_(pset.getParameter<int>("nintDisToMaxperthickperlayer")),
0136 
0137       //Parameters for the energy weighted distance of cluster cells to max cell per thickness per layer
0138       minDisToMaxperthickperlayerenewei_(pset.getParameter<double>("minDisToMaxperthickperlayerenewei")),
0139       maxDisToMaxperthickperlayerenewei_(pset.getParameter<double>("maxDisToMaxperthickperlayerenewei")),
0140       nintDisToMaxperthickperlayerenewei_(pset.getParameter<int>("nintDisToMaxperthickperlayerenewei")),
0141 
0142       //Parameters for the distance of seed cell to max cell per thickness per layer
0143       minDisSeedToMaxperthickperlayer_(pset.getParameter<double>("minDisSeedToMaxperthickperlayer")),
0144       maxDisSeedToMaxperthickperlayer_(pset.getParameter<double>("maxDisSeedToMaxperthickperlayer")),
0145       nintDisSeedToMaxperthickperlayer_(pset.getParameter<int>("nintDisSeedToMaxperthickperlayer")),
0146 
0147       //Parameters for the energy of a cluster per thickness per layer
0148       minClEneperthickperlayer_(pset.getParameter<double>("minClEneperthickperlayer")),
0149       maxClEneperthickperlayer_(pset.getParameter<double>("maxClEneperthickperlayer")),
0150       nintClEneperthickperlayer_(pset.getParameter<int>("nintClEneperthickperlayer")),
0151 
0152       //Parameters for the energy density of cluster cells per thickness
0153       minCellsEneDensperthick_(pset.getParameter<double>("minCellsEneDensperthick")),
0154       maxCellsEneDensperthick_(pset.getParameter<double>("maxCellsEneDensperthick")),
0155       nintCellsEneDensperthick_(pset.getParameter<int>("nintCellsEneDensperthick")),
0156 
0157       //Parameters for the total number of Tracksters per event
0158       // Always treat one event as two events, one in +z one in -z
0159       minTotNTSTs_(pset.getParameter<double>("minTotNTSTs")),
0160       maxTotNTSTs_(pset.getParameter<double>("maxTotNTSTs")),
0161       nintTotNTSTs_(pset.getParameter<int>("nintTotNTSTs")),
0162 
0163       //Parameters for the total number of layer clusters in Trackster
0164       minTotNClsinTSTs_(pset.getParameter<double>("minTotNClsinTSTs")),
0165       maxTotNClsinTSTs_(pset.getParameter<double>("maxTotNClsinTSTs")),
0166       nintTotNClsinTSTs_(pset.getParameter<int>("nintTotNClsinTSTs")),
0167 
0168       //Parameters for the total number of layer clusters in Trackster per layer
0169       minTotNClsinTSTsperlayer_(pset.getParameter<double>("minTotNClsinTSTsperlayer")),
0170       maxTotNClsinTSTsperlayer_(pset.getParameter<double>("maxTotNClsinTSTsperlayer")),
0171       nintTotNClsinTSTsperlayer_(pset.getParameter<int>("nintTotNClsinTSTsperlayer")),
0172 
0173       //Parameters for the multiplicity of layer clusters in Trackster
0174       minMplofLCs_(pset.getParameter<double>("minMplofLCs")),
0175       maxMplofLCs_(pset.getParameter<double>("maxMplofLCs")),
0176       nintMplofLCs_(pset.getParameter<int>("nintMplofLCs")),
0177 
0178       //Parameters for cluster size
0179       minSizeCLsinTSTs_(pset.getParameter<double>("minSizeCLsinTSTs")),
0180       maxSizeCLsinTSTs_(pset.getParameter<double>("maxSizeCLsinTSTs")),
0181       nintSizeCLsinTSTs_(pset.getParameter<int>("nintSizeCLsinTSTs")),
0182 
0183       //Parameters for the energy of a cluster per thickness per layer
0184       minClEnepermultiplicity_(pset.getParameter<double>("minClEnepermultiplicity")),
0185       maxClEnepermultiplicity_(pset.getParameter<double>("maxClEnepermultiplicity")),
0186       nintClEnepermultiplicity_(pset.getParameter<int>("nintClEnepermultiplicity")),
0187 
0188       //parameters for x
0189       minX_(pset.getParameter<double>("minX")),
0190       maxX_(pset.getParameter<double>("maxX")),
0191       nintX_(pset.getParameter<int>("nintX")),
0192 
0193       //parameters for y
0194       minY_(pset.getParameter<double>("minY")),
0195       maxY_(pset.getParameter<double>("maxY")),
0196       nintY_(pset.getParameter<int>("nintY")),
0197 
0198       //parameters for z
0199       minZ_(pset.getParameter<double>("minZ")),
0200       maxZ_(pset.getParameter<double>("maxZ")),
0201       nintZ_(pset.getParameter<int>("nintZ")) {}
0202 
0203 HGVHistoProducerAlgo::~HGVHistoProducerAlgo() {}
0204 
0205 void HGVHistoProducerAlgo::bookInfo(DQMStore::IBooker& ibook, Histograms& histograms) {
0206   histograms.lastLayerEEzm = ibook.bookInt("lastLayerEEzm");
0207   histograms.lastLayerFHzm = ibook.bookInt("lastLayerFHzm");
0208   histograms.maxlayerzm = ibook.bookInt("maxlayerzm");
0209   histograms.lastLayerEEzp = ibook.bookInt("lastLayerEEzp");
0210   histograms.lastLayerFHzp = ibook.bookInt("lastLayerFHzp");
0211   histograms.maxlayerzp = ibook.bookInt("maxlayerzp");
0212 }
0213 
0214 void HGVHistoProducerAlgo::bookCaloParticleHistos(DQMStore::IBooker& ibook,
0215                                                   Histograms& histograms,
0216                                                   int pdgid,
0217                                                   unsigned int layers) {
0218   histograms.h_caloparticle_eta[pdgid] =
0219       ibook.book1D("N of caloparticle vs eta", "N of caloParticles vs eta", nintEta_, minEta_, maxEta_);
0220   histograms.h_caloparticle_eta_Zorigin[pdgid] =
0221       ibook.book2D("Eta vs Zorigin", "Eta vs Zorigin", nintEta_, minEta_, maxEta_, nintZpos_, minZpos_, maxZpos_);
0222 
0223   histograms.h_caloparticle_energy[pdgid] =
0224       ibook.book1D("Energy", "Energy of CaloParticles; Energy [GeV]", nintEne_, minEne_, maxEne_);
0225   histograms.h_caloparticle_pt[pdgid] = ibook.book1D("Pt", "Pt of CaloParticles", nintPt_, minPt_, maxPt_);
0226   histograms.h_caloparticle_phi[pdgid] = ibook.book1D("Phi", "Phi of CaloParticles", nintPhi_, minPhi_, maxPhi_);
0227   histograms.h_caloparticle_selfenergy[pdgid] =
0228       ibook.book1D("SelfEnergy", "Total Energy of Hits in Sim Clusters (matched)", nintEne_, minEne_, maxEne_);
0229   histograms.h_caloparticle_energyDifference[pdgid] =
0230       ibook.book1D("EnergyDifference", "(Energy-SelfEnergy)/Energy", 300., -5., 1.);
0231 
0232   histograms.h_caloparticle_nSimClusters[pdgid] =
0233       ibook.book1D("Num Sim Clusters", "Num Sim Clusters in CaloParticles", 100, 0., 100.);
0234   histograms.h_caloparticle_nHitsInSimClusters[pdgid] =
0235       ibook.book1D("Num Hits in Sim Clusters", "Num Hits in Sim Clusters in CaloParticles", 1000, 0., 1000.);
0236   histograms.h_caloparticle_nHitsInSimClusters_matchedtoRecHit[pdgid] = ibook.book1D(
0237       "Num Rec-matched Hits in Sim Clusters", "Num Hits in Sim Clusters (matched) in CaloParticles", 1000, 0., 1000.);
0238 
0239   histograms.h_caloparticle_nHits_matched_energy[pdgid] =
0240       ibook.book1D("Energy of Rec-matched Hits", "Energy of Hits in Sim Clusters (matched)", 100, 0., 10.);
0241   histograms.h_caloparticle_nHits_matched_energy_layer[pdgid] =
0242       ibook.book2D("Energy of Rec-matched Hits vs layer",
0243                    "Energy of Hits in Sim Clusters (matched) vs layer",
0244                    2 * layers,
0245                    0.,
0246                    (float)2 * layers,
0247                    100,
0248                    0.,
0249                    10.);
0250   histograms.h_caloparticle_nHits_matched_energy_layer_1SimCl[pdgid] =
0251       ibook.book2D("Energy of Rec-matched Hits vs layer (1SC)",
0252                    "Energy of Hits only 1 Sim Clusters (matched) vs layer",
0253                    2 * layers,
0254                    0.,
0255                    (float)2 * layers,
0256                    100,
0257                    0.,
0258                    10.);
0259   histograms.h_caloparticle_sum_energy_layer[pdgid] =
0260       ibook.book2D("Rec-matched Hits Sum Energy vs layer",
0261                    "Rescaled Sum Energy of Hits in Sim Clusters (matched) vs layer",
0262                    2 * layers,
0263                    0.,
0264                    (float)2 * layers,
0265                    110,
0266                    0.,
0267                    110.);
0268   histograms.h_caloparticle_fractions[pdgid] =
0269       ibook.book2D("HitFractions", "Hit fractions;Hit fraction;E_{hit}^{2} fraction", 101, 0, 1.01, 100, 0, 1);
0270   histograms.h_caloparticle_fractions_weight[pdgid] = ibook.book2D(
0271       "HitFractions_weighted", "Hit fractions weighted;Hit fraction;E_{hit}^{2} fraction", 101, 0, 1.01, 100, 0, 1);
0272 
0273   histograms.h_caloparticle_firstlayer[pdgid] =
0274       ibook.book1D("First Layer", "First layer of the CaloParticles", 2 * layers, 0., (float)2 * layers);
0275   histograms.h_caloparticle_lastlayer[pdgid] =
0276       ibook.book1D("Last Layer", "Last layer of the CaloParticles", 2 * layers, 0., (float)2 * layers);
0277   histograms.h_caloparticle_layersnum[pdgid] =
0278       ibook.book1D("Number of Layers", "Number of layers of the CaloParticles", 2 * layers, 0., (float)2 * layers);
0279   histograms.h_caloparticle_firstlayer_matchedtoRecHit[pdgid] = ibook.book1D(
0280       "First Layer (rec-matched hit)", "First layer of the CaloParticles (matched)", 2 * layers, 0., (float)2 * layers);
0281   histograms.h_caloparticle_lastlayer_matchedtoRecHit[pdgid] = ibook.book1D(
0282       "Last Layer (rec-matched hit)", "Last layer of the CaloParticles (matched)", 2 * layers, 0., (float)2 * layers);
0283   histograms.h_caloparticle_layersnum_matchedtoRecHit[pdgid] =
0284       ibook.book1D("Number of Layers (rec-matched hit)",
0285                    "Number of layers of the CaloParticles (matched)",
0286                    2 * layers,
0287                    0.,
0288                    (float)2 * layers);
0289 }
0290 
0291 void HGVHistoProducerAlgo::bookSimClusterHistos(DQMStore::IBooker& ibook,
0292                                                 Histograms& histograms,
0293                                                 unsigned int layers,
0294                                                 std::vector<int> thicknesses) {
0295   //---------------------------------------------------------------------------------------------------------------------------
0296   for (unsigned ilayer = 0; ilayer < 2 * layers; ++ilayer) {
0297     auto istr1 = std::to_string(ilayer);
0298     while (istr1.size() < 2) {
0299       istr1.insert(0, "0");
0300     }
0301     // Make a mapping to the regural layer naming plus z- or z+ for convenience
0302     std::string istr2 = "";
0303     // first with the -z endcap
0304     if (ilayer < layers) {
0305       istr2 = std::to_string(ilayer + 1) + " in z-";
0306     } else {  // then for the +z
0307       istr2 = std::to_string(ilayer - (layers - 1)) + " in z+";
0308     }
0309     histograms.h_simclusternum_perlayer[ilayer] = ibook.book1D("totsimclusternum_layer_" + istr1,
0310                                                                "total number of SimClusters for layer " + istr2,
0311                                                                nintTotNsimClsperlay_,
0312                                                                minTotNsimClsperlay_,
0313                                                                maxTotNsimClsperlay_);
0314 
0315   }  //end of loop over layers
0316   //---------------------------------------------------------------------------------------------------------------------------
0317   for (std::vector<int>::iterator it = thicknesses.begin(); it != thicknesses.end(); ++it) {
0318     auto istr = std::to_string(*it);
0319     histograms.h_simclusternum_perthick[(*it)] = ibook.book1D("totsimclusternum_thick_" + istr,
0320                                                               "total number of simclusters for thickness " + istr,
0321                                                               nintTotNsimClsperthick_,
0322                                                               minTotNsimClsperthick_,
0323                                                               maxTotNsimClsperthick_);
0324   }  //end of loop over thicknesses
0325 
0326   //---------------------------------------------------------------------------------------------------------------------------
0327   //z-
0328   histograms.h_mixedhitssimcluster_zminus =
0329       ibook.book1D("mixedhitssimcluster_zminus",
0330                    "N of simclusters that contain hits of more than one kind in z-",
0331                    nintMixedHitsSimCluster_,
0332                    minMixedHitsSimCluster_,
0333                    maxMixedHitsSimCluster_);
0334   //z+
0335   histograms.h_mixedhitssimcluster_zplus =
0336       ibook.book1D("mixedhitssimcluster_zplus",
0337                    "N of simclusters that contain hits of more than one kind in z+",
0338                    nintMixedHitsSimCluster_,
0339                    minMixedHitsSimCluster_,
0340                    maxMixedHitsSimCluster_);
0341 }
0342 
0343 void HGVHistoProducerAlgo::bookSimClusterAssociationHistos(DQMStore::IBooker& ibook,
0344                                                            Histograms& histograms,
0345                                                            unsigned int layers,
0346                                                            std::vector<int> thicknesses) {
0347   std::unordered_map<int, dqm::reco::MonitorElement*> denom_layercl_in_simcl_eta_perlayer;
0348   denom_layercl_in_simcl_eta_perlayer.clear();
0349   std::unordered_map<int, dqm::reco::MonitorElement*> denom_layercl_in_simcl_phi_perlayer;
0350   denom_layercl_in_simcl_phi_perlayer.clear();
0351   std::unordered_map<int, dqm::reco::MonitorElement*> score_layercl2simcluster_perlayer;
0352   score_layercl2simcluster_perlayer.clear();
0353   std::unordered_map<int, dqm::reco::MonitorElement*> sharedenergy_layercl2simcluster_perlayer;
0354   sharedenergy_layercl2simcluster_perlayer.clear();
0355   std::unordered_map<int, dqm::reco::MonitorElement*> energy_vs_score_layercl2simcluster_perlayer;
0356   energy_vs_score_layercl2simcluster_perlayer.clear();
0357   std::unordered_map<int, dqm::reco::MonitorElement*> num_layercl_in_simcl_eta_perlayer;
0358   num_layercl_in_simcl_eta_perlayer.clear();
0359   std::unordered_map<int, dqm::reco::MonitorElement*> num_layercl_in_simcl_phi_perlayer;
0360   num_layercl_in_simcl_phi_perlayer.clear();
0361   std::unordered_map<int, dqm::reco::MonitorElement*> numMerge_layercl_in_simcl_eta_perlayer;
0362   numMerge_layercl_in_simcl_eta_perlayer.clear();
0363   std::unordered_map<int, dqm::reco::MonitorElement*> numMerge_layercl_in_simcl_phi_perlayer;
0364   numMerge_layercl_in_simcl_phi_perlayer.clear();
0365   std::unordered_map<int, dqm::reco::MonitorElement*> sharedenergy_layercl2simcluster_vs_eta_perlayer;
0366   sharedenergy_layercl2simcluster_vs_eta_perlayer.clear();
0367   std::unordered_map<int, dqm::reco::MonitorElement*> sharedenergy_layercl2simcluster_vs_phi_perlayer;
0368   sharedenergy_layercl2simcluster_vs_phi_perlayer.clear();
0369   std::unordered_map<int, dqm::reco::MonitorElement*> denom_simcluster_eta_perlayer;
0370   denom_simcluster_eta_perlayer.clear();
0371   std::unordered_map<int, dqm::reco::MonitorElement*> denom_simcluster_phi_perlayer;
0372   denom_simcluster_phi_perlayer.clear();
0373   std::unordered_map<int, dqm::reco::MonitorElement*> score_simcluster2layercl_perlayer;
0374   score_simcluster2layercl_perlayer.clear();
0375   std::unordered_map<int, dqm::reco::MonitorElement*> sharedenergy_simcluster2layercl_perlayer;
0376   sharedenergy_simcluster2layercl_perlayer.clear();
0377   std::unordered_map<int, dqm::reco::MonitorElement*> energy_vs_score_simcluster2layercl_perlayer;
0378   energy_vs_score_simcluster2layercl_perlayer.clear();
0379   std::unordered_map<int, dqm::reco::MonitorElement*> num_simcluster_eta_perlayer;
0380   num_simcluster_eta_perlayer.clear();
0381   std::unordered_map<int, dqm::reco::MonitorElement*> num_simcluster_phi_perlayer;
0382   num_simcluster_phi_perlayer.clear();
0383   std::unordered_map<int, dqm::reco::MonitorElement*> numDup_simcluster_eta_perlayer;
0384   numDup_simcluster_eta_perlayer.clear();
0385   std::unordered_map<int, dqm::reco::MonitorElement*> numDup_simcluster_phi_perlayer;
0386   numDup_simcluster_phi_perlayer.clear();
0387   std::unordered_map<int, dqm::reco::MonitorElement*> sharedenergy_simcluster2layercl_vs_eta_perlayer;
0388   sharedenergy_simcluster2layercl_vs_eta_perlayer.clear();
0389   std::unordered_map<int, dqm::reco::MonitorElement*> sharedenergy_simcluster2layercl_vs_phi_perlayer;
0390   sharedenergy_simcluster2layercl_vs_phi_perlayer.clear();
0391 
0392   //---------------------------------------------------------------------------------------------------------------------------
0393   for (unsigned ilayer = 0; ilayer < 2 * layers; ++ilayer) {
0394     auto istr1 = std::to_string(ilayer);
0395     while (istr1.size() < 2) {
0396       istr1.insert(0, "0");
0397     }
0398     // Make a mapping to the regural layer naming plus z- or z+ for convenience
0399     std::string istr2 = "";
0400     // first with the -z endcap
0401     if (ilayer < layers) {
0402       istr2 = std::to_string(ilayer + 1) + " in z-";
0403     } else {  // then for the +z
0404       istr2 = std::to_string(ilayer - (layers - 1)) + " in z+";
0405     }
0406     //-------------------------------------------------------------------------------------------------------------------------
0407     denom_layercl_in_simcl_eta_perlayer[ilayer] =
0408         ibook.book1D("Denom_LayerCluster_in_SimCluster_Eta_perlayer" + istr1,
0409                      "Denom LayerCluster in SimCluster Eta per Layer Cluster for layer " + istr2,
0410                      nintEta_,
0411                      minEta_,
0412                      maxEta_);
0413     //-------------------------------------------------------------------------------------------------------------------------
0414     denom_layercl_in_simcl_phi_perlayer[ilayer] =
0415         ibook.book1D("Denom_LayerCluster_in_SimCluster_Phi_perlayer" + istr1,
0416                      "Denom LayerCluster in SimCluster Phi per Layer Cluster for layer " + istr2,
0417                      nintPhi_,
0418                      minPhi_,
0419                      maxPhi_);
0420     //-------------------------------------------------------------------------------------------------------------------------
0421     score_layercl2simcluster_perlayer[ilayer] = ibook.book1D("Score_layercl2simcluster_perlayer" + istr1,
0422                                                              "Score of Layer Cluster per SimCluster for layer " + istr2,
0423                                                              nintScore_,
0424                                                              minScore_,
0425                                                              maxScore_);
0426     //-------------------------------------------------------------------------------------------------------------------------
0427     score_simcluster2layercl_perlayer[ilayer] = ibook.book1D("Score_simcluster2layercl_perlayer" + istr1,
0428                                                              "Score of SimCluster per Layer Cluster for layer " + istr2,
0429                                                              nintScore_,
0430                                                              minScore_,
0431                                                              maxScore_);
0432     //-------------------------------------------------------------------------------------------------------------------------
0433     energy_vs_score_simcluster2layercl_perlayer[ilayer] =
0434         ibook.book2D("Energy_vs_Score_simcluster2layer_perlayer" + istr1,
0435                      "Energy vs Score of SimCluster per Layer Cluster for layer " + istr2,
0436                      nintScore_,
0437                      minScore_,
0438                      maxScore_,
0439                      nintSharedEneFrac_,
0440                      minSharedEneFrac_,
0441                      maxSharedEneFrac_);
0442     //-------------------------------------------------------------------------------------------------------------------------
0443     energy_vs_score_layercl2simcluster_perlayer[ilayer] =
0444         ibook.book2D("Energy_vs_Score_layer2simcluster_perlayer" + istr1,
0445                      "Energy vs Score of Layer Cluster per SimCluster for layer " + istr2,
0446                      nintScore_,
0447                      minScore_,
0448                      maxScore_,
0449                      nintSharedEneFrac_,
0450                      minSharedEneFrac_,
0451                      maxSharedEneFrac_);
0452     //-------------------------------------------------------------------------------------------------------------------------
0453     sharedenergy_simcluster2layercl_perlayer[ilayer] =
0454         ibook.book1D("SharedEnergy_simcluster2layercl_perlayer" + istr1,
0455                      "Shared Energy of SimCluster per Layer Cluster for layer " + istr2,
0456                      nintSharedEneFrac_,
0457                      minSharedEneFrac_,
0458                      maxSharedEneFrac_);
0459     //-------------------------------------------------------------------------------------------------------------------------
0460     sharedenergy_simcluster2layercl_vs_eta_perlayer[ilayer] =
0461         ibook.bookProfile("SharedEnergy_simcluster2layercl_vs_eta_perlayer" + istr1,
0462                           "Shared Energy of SimCluster vs #eta per best Layer Cluster for layer " + istr2,
0463                           nintEta_,
0464                           minEta_,
0465                           maxEta_,
0466                           minSharedEneFrac_,
0467                           maxSharedEneFrac_);
0468     //-------------------------------------------------------------------------------------------------------------------------
0469     sharedenergy_simcluster2layercl_vs_phi_perlayer[ilayer] =
0470         ibook.bookProfile("SharedEnergy_simcluster2layercl_vs_phi_perlayer" + istr1,
0471                           "Shared Energy of SimCluster vs #phi per best Layer Cluster for layer " + istr2,
0472                           nintPhi_,
0473                           minPhi_,
0474                           maxPhi_,
0475                           minSharedEneFrac_,
0476                           maxSharedEneFrac_);
0477     //-------------------------------------------------------------------------------------------------------------------------
0478     sharedenergy_layercl2simcluster_perlayer[ilayer] =
0479         ibook.book1D("SharedEnergy_layercluster2simcluster_perlayer" + istr1,
0480                      "Shared Energy of Layer Cluster per SimCluster for layer " + istr2,
0481                      nintSharedEneFrac_,
0482                      minSharedEneFrac_,
0483                      maxSharedEneFrac_);
0484     //-------------------------------------------------------------------------------------------------------------------------
0485     sharedenergy_layercl2simcluster_vs_eta_perlayer[ilayer] =
0486         ibook.bookProfile("SharedEnergy_layercl2simcluster_vs_eta_perlayer" + istr1,
0487                           "Shared Energy of LayerCluster vs #eta per best SimCluster for layer " + istr2,
0488                           nintEta_,
0489                           minEta_,
0490                           maxEta_,
0491                           minSharedEneFrac_,
0492                           maxSharedEneFrac_);
0493     //-------------------------------------------------------------------------------------------------------------------------
0494     sharedenergy_layercl2simcluster_vs_phi_perlayer[ilayer] =
0495         ibook.bookProfile("SharedEnergy_layercl2simcluster_vs_phi_perlayer" + istr1,
0496                           "Shared Energy of LayerCluster vs #phi per best SimCluster for layer " + istr2,
0497                           nintPhi_,
0498                           minPhi_,
0499                           maxPhi_,
0500                           minSharedEneFrac_,
0501                           maxSharedEneFrac_);
0502     //-------------------------------------------------------------------------------------------------------------------------
0503     num_simcluster_eta_perlayer[ilayer] = ibook.book1D("Num_SimCluster_Eta_perlayer" + istr1,
0504                                                        "Num SimCluster Eta per Layer Cluster for layer " + istr2,
0505                                                        nintEta_,
0506                                                        minEta_,
0507                                                        maxEta_);
0508     //-------------------------------------------------------------------------------------------------------------------------
0509     numDup_simcluster_eta_perlayer[ilayer] =
0510         ibook.book1D("NumDup_SimCluster_Eta_perlayer" + istr1,
0511                      "Num Duplicate SimCluster Eta per Layer Cluster for layer " + istr2,
0512                      nintEta_,
0513                      minEta_,
0514                      maxEta_);
0515     //-------------------------------------------------------------------------------------------------------------------------
0516     denom_simcluster_eta_perlayer[ilayer] = ibook.book1D("Denom_SimCluster_Eta_perlayer" + istr1,
0517                                                          "Denom SimCluster Eta per Layer Cluster for layer " + istr2,
0518                                                          nintEta_,
0519                                                          minEta_,
0520                                                          maxEta_);
0521     //-------------------------------------------------------------------------------------------------------------------------
0522     num_simcluster_phi_perlayer[ilayer] = ibook.book1D("Num_SimCluster_Phi_perlayer" + istr1,
0523                                                        "Num SimCluster Phi per Layer Cluster for layer " + istr2,
0524                                                        nintPhi_,
0525                                                        minPhi_,
0526                                                        maxPhi_);
0527     //-------------------------------------------------------------------------------------------------------------------------
0528     numDup_simcluster_phi_perlayer[ilayer] =
0529         ibook.book1D("NumDup_SimCluster_Phi_perlayer" + istr1,
0530                      "Num Duplicate SimCluster Phi per Layer Cluster for layer " + istr2,
0531                      nintPhi_,
0532                      minPhi_,
0533                      maxPhi_);
0534     //-------------------------------------------------------------------------------------------------------------------------
0535     denom_simcluster_phi_perlayer[ilayer] = ibook.book1D("Denom_SimCluster_Phi_perlayer" + istr1,
0536                                                          "Denom SimCluster Phi per Layer Cluster for layer " + istr2,
0537                                                          nintPhi_,
0538                                                          minPhi_,
0539                                                          maxPhi_);
0540     //-------------------------------------------------------------------------------------------------------------------------
0541     num_layercl_in_simcl_eta_perlayer[ilayer] =
0542         ibook.book1D("Num_LayerCluster_in_SimCluster_Eta_perlayer" + istr1,
0543                      "Num LayerCluster Eta per Layer Cluster in SimCluster for layer " + istr2,
0544                      nintEta_,
0545                      minEta_,
0546                      maxEta_);
0547     //-------------------------------------------------------------------------------------------------------------------------
0548     numMerge_layercl_in_simcl_eta_perlayer[ilayer] =
0549         ibook.book1D("NumMerge_LayerCluster_in_SimCluster_Eta_perlayer" + istr1,
0550                      "Num Merge LayerCluster Eta per Layer Cluster in SimCluster for layer " + istr2,
0551                      nintEta_,
0552                      minEta_,
0553                      maxEta_);
0554     //-------------------------------------------------------------------------------------------------------------------------
0555     num_layercl_in_simcl_phi_perlayer[ilayer] =
0556         ibook.book1D("Num_LayerCluster_in_SimCluster_Phi_perlayer" + istr1,
0557                      "Num LayerCluster Phi per Layer Cluster in SimCluster for layer " + istr2,
0558                      nintPhi_,
0559                      minPhi_,
0560                      maxPhi_);
0561     //-------------------------------------------------------------------------------------------------------------------------
0562     numMerge_layercl_in_simcl_phi_perlayer[ilayer] =
0563         ibook.book1D("NumMerge_LayerCluster_in_SimCluster_Phi_perlayer" + istr1,
0564                      "Num Merge LayerCluster Phi per Layer Cluster in SimCluster for layer " + istr2,
0565                      nintPhi_,
0566                      minPhi_,
0567                      maxPhi_);
0568 
0569   }  //end of loop over layers
0570 
0571   histograms.h_denom_layercl_in_simcl_eta_perlayer.push_back(std::move(denom_layercl_in_simcl_eta_perlayer));
0572   histograms.h_denom_layercl_in_simcl_phi_perlayer.push_back(std::move(denom_layercl_in_simcl_phi_perlayer));
0573   histograms.h_score_layercl2simcluster_perlayer.push_back(std::move(score_layercl2simcluster_perlayer));
0574   histograms.h_sharedenergy_layercl2simcluster_perlayer.push_back(std::move(sharedenergy_layercl2simcluster_perlayer));
0575   histograms.h_energy_vs_score_layercl2simcluster_perlayer.push_back(
0576       std::move(energy_vs_score_layercl2simcluster_perlayer));
0577   histograms.h_num_layercl_in_simcl_eta_perlayer.push_back(std::move(num_layercl_in_simcl_eta_perlayer));
0578   histograms.h_num_layercl_in_simcl_phi_perlayer.push_back(std::move(num_layercl_in_simcl_phi_perlayer));
0579   histograms.h_numMerge_layercl_in_simcl_eta_perlayer.push_back(std::move(numMerge_layercl_in_simcl_eta_perlayer));
0580   histograms.h_numMerge_layercl_in_simcl_phi_perlayer.push_back(std::move(numMerge_layercl_in_simcl_phi_perlayer));
0581   histograms.h_sharedenergy_layercl2simcluster_vs_eta_perlayer.push_back(
0582       std::move(sharedenergy_layercl2simcluster_vs_eta_perlayer));
0583   histograms.h_sharedenergy_layercl2simcluster_vs_phi_perlayer.push_back(
0584       std::move(sharedenergy_layercl2simcluster_vs_phi_perlayer));
0585   histograms.h_denom_simcluster_eta_perlayer.push_back(std::move(denom_simcluster_eta_perlayer));
0586   histograms.h_denom_simcluster_phi_perlayer.push_back(std::move(denom_simcluster_phi_perlayer));
0587   histograms.h_score_simcluster2layercl_perlayer.push_back(std::move(score_simcluster2layercl_perlayer));
0588   histograms.h_sharedenergy_simcluster2layercl_perlayer.push_back(std::move(sharedenergy_simcluster2layercl_perlayer));
0589   histograms.h_energy_vs_score_simcluster2layercl_perlayer.push_back(
0590       std::move(energy_vs_score_simcluster2layercl_perlayer));
0591   histograms.h_num_simcluster_eta_perlayer.push_back(std::move(num_simcluster_eta_perlayer));
0592   histograms.h_num_simcluster_phi_perlayer.push_back(std::move(num_simcluster_phi_perlayer));
0593   histograms.h_numDup_simcluster_eta_perlayer.push_back(std::move(numDup_simcluster_eta_perlayer));
0594   histograms.h_numDup_simcluster_phi_perlayer.push_back(std::move(numDup_simcluster_phi_perlayer));
0595   histograms.h_sharedenergy_simcluster2layercl_vs_eta_perlayer.push_back(
0596       std::move(sharedenergy_simcluster2layercl_vs_eta_perlayer));
0597   histograms.h_sharedenergy_simcluster2layercl_vs_phi_perlayer.push_back(
0598       std::move(sharedenergy_simcluster2layercl_vs_phi_perlayer));
0599 }
0600 void HGVHistoProducerAlgo::bookClusterHistos_ClusterLevel(DQMStore::IBooker& ibook,
0601                                                           Histograms& histograms,
0602                                                           unsigned int layers,
0603                                                           std::vector<int> thicknesses,
0604                                                           std::string pathtomatbudfile) {
0605   //---------------------------------------------------------------------------------------------------------------------------
0606   histograms.h_cluster_eta.push_back(
0607       ibook.book1D("num_reco_cluster_eta", "N of reco clusters vs eta", nintEta_, minEta_, maxEta_));
0608 
0609   //---------------------------------------------------------------------------------------------------------------------------
0610   //z-
0611   histograms.h_mixedhitscluster_zminus.push_back(
0612       ibook.book1D("mixedhitscluster_zminus",
0613                    "N of reco clusters that contain hits of more than one kind in z-",
0614                    nintMixedHitsCluster_,
0615                    minMixedHitsCluster_,
0616                    maxMixedHitsCluster_));
0617   //z+
0618   histograms.h_mixedhitscluster_zplus.push_back(
0619       ibook.book1D("mixedhitscluster_zplus",
0620                    "N of reco clusters that contain hits of more than one kind in z+",
0621                    nintMixedHitsCluster_,
0622                    minMixedHitsCluster_,
0623                    maxMixedHitsCluster_));
0624 
0625   //---------------------------------------------------------------------------------------------------------------------------
0626   //z-
0627   histograms.h_energyclustered_zminus.push_back(
0628       ibook.book1D("energyclustered_zminus",
0629                    "percent of total energy clustered by all layer clusters over CaloParticless energy in z-",
0630                    nintEneCl_,
0631                    minEneCl_,
0632                    maxEneCl_));
0633   //z+
0634   histograms.h_energyclustered_zplus.push_back(
0635       ibook.book1D("energyclustered_zplus",
0636                    "percent of total energy clustered by all layer clusters over CaloParticless energy in z+",
0637                    nintEneCl_,
0638                    minEneCl_,
0639                    maxEneCl_));
0640 
0641   //---------------------------------------------------------------------------------------------------------------------------
0642   //z-
0643   std::string subpathtomat = pathtomatbudfile.substr(pathtomatbudfile.find("Validation"));
0644   histograms.h_longdepthbarycentre_zminus.push_back(
0645       ibook.book1D("longdepthbarycentre_zminus",
0646                    "The longitudinal depth barycentre in z- for " + subpathtomat,
0647                    nintLongDepBary_,
0648                    minLongDepBary_,
0649                    maxLongDepBary_));
0650   //z+
0651   histograms.h_longdepthbarycentre_zplus.push_back(
0652       ibook.book1D("longdepthbarycentre_zplus",
0653                    "The longitudinal depth barycentre in z+ for " + subpathtomat,
0654                    nintLongDepBary_,
0655                    minLongDepBary_,
0656                    maxLongDepBary_));
0657 
0658   //---------------------------------------------------------------------------------------------------------------------------
0659   for (unsigned ilayer = 0; ilayer < 2 * layers; ++ilayer) {
0660     auto istr1 = std::to_string(ilayer);
0661     while (istr1.size() < 2) {
0662       istr1.insert(0, "0");
0663     }
0664     // Make a mapping to the regural layer naming plus z- or z+ for convenience
0665     std::string istr2 = "";
0666     // first with the -z endcap
0667     if (ilayer < layers) {
0668       istr2 = std::to_string(ilayer + 1) + " in z-";
0669     } else {  // then for the +z
0670       istr2 = std::to_string(ilayer - (layers - 1)) + " in z+";
0671     }
0672     histograms.h_clusternum_perlayer[ilayer] = ibook.book1D("totclusternum_layer_" + istr1,
0673                                                             "total number of layer clusters for layer " + istr2,
0674                                                             nintTotNClsperlay_,
0675                                                             minTotNClsperlay_,
0676                                                             maxTotNClsperlay_);
0677     histograms.h_energyclustered_perlayer[ilayer] = ibook.book1D(
0678         "energyclustered_perlayer" + istr1,
0679         "percent of total energy clustered by layer clusters over CaloParticless energy for layer " + istr2,
0680         nintEneClperlay_,
0681         minEneClperlay_,
0682         maxEneClperlay_);
0683   }
0684 
0685   //---------------------------------------------------------------------------------------------------------------------------
0686   for (std::vector<int>::iterator it = thicknesses.begin(); it != thicknesses.end(); ++it) {
0687     auto istr = std::to_string(*it);
0688     histograms.h_clusternum_perthick[(*it)] = ibook.book1D("totclusternum_thick_" + istr,
0689                                                            "total number of layer clusters for thickness " + istr,
0690                                                            nintTotNClsperthick_,
0691                                                            minTotNClsperthick_,
0692                                                            maxTotNClsperthick_);
0693   }
0694   //---------------------------------------------------------------------------------------------------------------------------
0695 }
0696 
0697 void HGVHistoProducerAlgo::bookClusterHistos_LCtoCP_association(DQMStore::IBooker& ibook,
0698                                                                 Histograms& histograms,
0699                                                                 unsigned int layers) {
0700   //----------------------------------------------------------------------------------------------------------------------------
0701   for (unsigned ilayer = 0; ilayer < 2 * layers; ++ilayer) {
0702     auto istr1 = std::to_string(ilayer);
0703     while (istr1.size() < 2) {
0704       istr1.insert(0, "0");
0705     }
0706     // Make a mapping to the regural layer naming plus z- or z+ for convenience
0707     std::string istr2 = "";
0708     // first with the -z endcap
0709     if (ilayer < layers) {
0710       istr2 = std::to_string(ilayer + 1) + " in z-";
0711     } else {  // then for the +z
0712       istr2 = std::to_string(ilayer - (layers - 1)) + " in z+";
0713     }
0714     histograms.h_score_layercl2caloparticle_perlayer[ilayer] =
0715         ibook.book1D("Score_layercl2caloparticle_perlayer" + istr1,
0716                      "Score of Layer Cluster per CaloParticle for layer " + istr2,
0717                      nintScore_,
0718                      minScore_,
0719                      maxScore_);
0720     histograms.h_score_caloparticle2layercl_perlayer[ilayer] =
0721         ibook.book1D("Score_caloparticle2layercl_perlayer" + istr1,
0722                      "Score of CaloParticle per Layer Cluster for layer " + istr2,
0723                      nintScore_,
0724                      minScore_,
0725                      maxScore_);
0726     histograms.h_energy_vs_score_caloparticle2layercl_perlayer[ilayer] =
0727         ibook.book2D("Energy_vs_Score_caloparticle2layer_perlayer" + istr1,
0728                      "Energy vs Score of CaloParticle per Layer Cluster for layer " + istr2,
0729                      nintScore_,
0730                      minScore_,
0731                      maxScore_,
0732                      nintSharedEneFrac_,
0733                      minSharedEneFrac_,
0734                      maxSharedEneFrac_);
0735     histograms.h_energy_vs_score_layercl2caloparticle_perlayer[ilayer] =
0736         ibook.book2D("Energy_vs_Score_layer2caloparticle_perlayer" + istr1,
0737                      "Energy vs Score of Layer Cluster per CaloParticle Layer for layer " + istr2,
0738                      nintScore_,
0739                      minScore_,
0740                      maxScore_,
0741                      nintSharedEneFrac_,
0742                      minSharedEneFrac_,
0743                      maxSharedEneFrac_);
0744     histograms.h_sharedenergy_caloparticle2layercl_perlayer[ilayer] =
0745         ibook.book1D("SharedEnergy_caloparticle2layercl_perlayer" + istr1,
0746                      "Shared Energy of CaloParticle per Layer Cluster for layer " + istr2,
0747                      nintSharedEneFrac_,
0748                      minSharedEneFrac_,
0749                      maxSharedEneFrac_);
0750     histograms.h_sharedenergy_caloparticle2layercl_vs_eta_perlayer[ilayer] =
0751         ibook.bookProfile("SharedEnergy_caloparticle2layercl_vs_eta_perlayer" + istr1,
0752                           "Shared Energy of CaloParticle vs #eta per best Layer Cluster for layer " + istr2,
0753                           nintEta_,
0754                           minEta_,
0755                           maxEta_,
0756                           minSharedEneFrac_,
0757                           maxSharedEneFrac_);
0758     histograms.h_sharedenergy_caloparticle2layercl_vs_phi_perlayer[ilayer] =
0759         ibook.bookProfile("SharedEnergy_caloparticle2layercl_vs_phi_perlayer" + istr1,
0760                           "Shared Energy of CaloParticle vs #phi per best Layer Cluster for layer " + istr2,
0761                           nintPhi_,
0762                           minPhi_,
0763                           maxPhi_,
0764                           minSharedEneFrac_,
0765                           maxSharedEneFrac_);
0766     histograms.h_sharedenergy_layercl2caloparticle_perlayer[ilayer] =
0767         ibook.book1D("SharedEnergy_layercluster2caloparticle_perlayer" + istr1,
0768                      "Shared Energy of Layer Cluster per Layer Calo Particle for layer " + istr2,
0769                      nintSharedEneFrac_,
0770                      minSharedEneFrac_,
0771                      maxSharedEneFrac_);
0772     histograms.h_sharedenergy_layercl2caloparticle_vs_eta_perlayer[ilayer] =
0773         ibook.bookProfile("SharedEnergy_layercl2caloparticle_vs_eta_perlayer" + istr1,
0774                           "Shared Energy of LayerCluster vs #eta per best Calo Particle for layer " + istr2,
0775                           nintEta_,
0776                           minEta_,
0777                           maxEta_,
0778                           minSharedEneFrac_,
0779                           maxSharedEneFrac_);
0780     histograms.h_sharedenergy_layercl2caloparticle_vs_phi_perlayer[ilayer] =
0781         ibook.bookProfile("SharedEnergy_layercl2caloparticle_vs_phi_perlayer" + istr1,
0782                           "Shared Energy of LayerCluster vs #phi per best Calo Particle for layer " + istr2,
0783                           nintPhi_,
0784                           minPhi_,
0785                           maxPhi_,
0786                           minSharedEneFrac_,
0787                           maxSharedEneFrac_);
0788     histograms.h_num_caloparticle_eta_perlayer[ilayer] =
0789         ibook.book1D("Num_CaloParticle_Eta_perlayer" + istr1,
0790                      "Num CaloParticle Eta per Layer Cluster for layer " + istr2,
0791                      nintEta_,
0792                      minEta_,
0793                      maxEta_);
0794     histograms.h_numDup_caloparticle_eta_perlayer[ilayer] =
0795         ibook.book1D("NumDup_CaloParticle_Eta_perlayer" + istr1,
0796                      "Num Duplicate CaloParticle Eta per Layer Cluster for layer " + istr2,
0797                      nintEta_,
0798                      minEta_,
0799                      maxEta_);
0800     histograms.h_denom_caloparticle_eta_perlayer[ilayer] =
0801         ibook.book1D("Denom_CaloParticle_Eta_perlayer" + istr1,
0802                      "Denom CaloParticle Eta per Layer Cluster for layer " + istr2,
0803                      nintEta_,
0804                      minEta_,
0805                      maxEta_);
0806     histograms.h_num_caloparticle_phi_perlayer[ilayer] =
0807         ibook.book1D("Num_CaloParticle_Phi_perlayer" + istr1,
0808                      "Num CaloParticle Phi per Layer Cluster for layer " + istr2,
0809                      nintPhi_,
0810                      minPhi_,
0811                      maxPhi_);
0812     histograms.h_numDup_caloparticle_phi_perlayer[ilayer] =
0813         ibook.book1D("NumDup_CaloParticle_Phi_perlayer" + istr1,
0814                      "Num Duplicate CaloParticle Phi per Layer Cluster for layer " + istr2,
0815                      nintPhi_,
0816                      minPhi_,
0817                      maxPhi_);
0818     histograms.h_denom_caloparticle_phi_perlayer[ilayer] =
0819         ibook.book1D("Denom_CaloParticle_Phi_perlayer" + istr1,
0820                      "Denom CaloParticle Phi per Layer Cluster for layer " + istr2,
0821                      nintPhi_,
0822                      minPhi_,
0823                      maxPhi_);
0824     histograms.h_num_layercl_eta_perlayer[ilayer] =
0825         ibook.book1D("Num_LayerCluster_Eta_perlayer" + istr1,
0826                      "Num LayerCluster Eta per Layer Cluster for layer " + istr2,
0827                      nintEta_,
0828                      minEta_,
0829                      maxEta_);
0830     histograms.h_numMerge_layercl_eta_perlayer[ilayer] =
0831         ibook.book1D("NumMerge_LayerCluster_Eta_perlayer" + istr1,
0832                      "Num Merge LayerCluster Eta per Layer Cluster for layer " + istr2,
0833                      nintEta_,
0834                      minEta_,
0835                      maxEta_);
0836     histograms.h_denom_layercl_eta_perlayer[ilayer] =
0837         ibook.book1D("Denom_LayerCluster_Eta_perlayer" + istr1,
0838                      "Denom LayerCluster Eta per Layer Cluster for layer " + istr2,
0839                      nintEta_,
0840                      minEta_,
0841                      maxEta_);
0842     histograms.h_num_layercl_phi_perlayer[ilayer] =
0843         ibook.book1D("Num_LayerCluster_Phi_perlayer" + istr1,
0844                      "Num LayerCluster Phi per Layer Cluster for layer " + istr2,
0845                      nintPhi_,
0846                      minPhi_,
0847                      maxPhi_);
0848     histograms.h_numMerge_layercl_phi_perlayer[ilayer] =
0849         ibook.book1D("NumMerge_LayerCluster_Phi_perlayer" + istr1,
0850                      "Num Merge LayerCluster Phi per Layer Cluster for layer " + istr2,
0851                      nintPhi_,
0852                      minPhi_,
0853                      maxPhi_);
0854     histograms.h_denom_layercl_phi_perlayer[ilayer] =
0855         ibook.book1D("Denom_LayerCluster_Phi_perlayer" + istr1,
0856                      "Denom LayerCluster Phi per Layer Cluster for layer " + istr2,
0857                      nintPhi_,
0858                      minPhi_,
0859                      maxPhi_);
0860   }
0861   //---------------------------------------------------------------------------------------------------------------------------
0862 }
0863 
0864 void HGVHistoProducerAlgo::bookClusterHistos_CellLevel(DQMStore::IBooker& ibook,
0865                                                        Histograms& histograms,
0866                                                        unsigned int layers,
0867                                                        std::vector<int> thicknesses) {
0868   //----------------------------------------------------------------------------------------------------------------------------
0869   for (unsigned ilayer = 0; ilayer < 2 * layers; ++ilayer) {
0870     auto istr1 = std::to_string(ilayer);
0871     while (istr1.size() < 2) {
0872       istr1.insert(0, "0");
0873     }
0874     // Make a mapping to the regural layer naming plus z- or z+ for convenience
0875     std::string istr2 = "";
0876     // first with the -z endcap
0877     if (ilayer < layers) {
0878       istr2 = std::to_string(ilayer + 1) + " in z-";
0879     } else {  // then for the +z
0880       istr2 = std::to_string(ilayer - (layers - 1)) + " in z+";
0881     }
0882     histograms.h_cellAssociation_perlayer[ilayer] =
0883         ibook.book1D("cellAssociation_perlayer" + istr1, "Cell Association for layer " + istr2, 5, -4., 1.);
0884     histograms.h_cellAssociation_perlayer[ilayer]->setBinLabel(2, "TN(purity)");
0885     histograms.h_cellAssociation_perlayer[ilayer]->setBinLabel(3, "FN(ineff.)");
0886     histograms.h_cellAssociation_perlayer[ilayer]->setBinLabel(4, "FP(fake)");
0887     histograms.h_cellAssociation_perlayer[ilayer]->setBinLabel(5, "TP(eff.)");
0888   }
0889   //----------------------------------------------------------------------------------------------------------------------------
0890   for (std::vector<int>::iterator it = thicknesses.begin(); it != thicknesses.end(); ++it) {
0891     auto istr = std::to_string(*it);
0892     histograms.h_cellsenedens_perthick[(*it)] = ibook.book1D("cellsenedens_thick_" + istr,
0893                                                              "energy density of cluster cells for thickness " + istr,
0894                                                              nintCellsEneDensperthick_,
0895                                                              minCellsEneDensperthick_,
0896                                                              maxCellsEneDensperthick_);
0897   }
0898   //----------------------------------------------------------------------------------------------------------------------------
0899   //Not all combination exists but should keep them all for cross checking reason.
0900   for (std::vector<int>::iterator it = thicknesses.begin(); it != thicknesses.end(); ++it) {
0901     for (unsigned ilayer = 0; ilayer < 2 * layers; ++ilayer) {
0902       auto istr1 = std::to_string(*it);
0903       auto istr2 = std::to_string(ilayer);
0904       while (istr2.size() < 2)
0905         istr2.insert(0, "0");
0906       auto istr = istr1 + "_" + istr2;
0907       // Make a mapping to the regural layer naming plus z- or z+ for convenience
0908       std::string istr3 = "";
0909       // first with the -z endcap
0910       if (ilayer < layers) {
0911         istr3 = std::to_string(ilayer + 1) + " in z- ";
0912       } else {  // then for the +z
0913         istr3 = std::to_string(ilayer - (layers - 1)) + " in z+ ";
0914       }
0915       //---
0916       histograms.h_cellsnum_perthickperlayer[istr] =
0917           ibook.book1D("cellsnum_perthick_perlayer_" + istr,
0918                        "total number of cells for layer " + istr3 + " for thickness " + istr1,
0919                        nintTotNcellsperthickperlayer_,
0920                        minTotNcellsperthickperlayer_,
0921                        maxTotNcellsperthickperlayer_);
0922       //---
0923       histograms.h_distancetoseedcell_perthickperlayer[istr] =
0924           ibook.book1D("distancetoseedcell_perthickperlayer_" + istr,
0925                        "distance of cluster cells to seed cell for layer " + istr3 + " for thickness " + istr1,
0926                        nintDisToSeedperthickperlayer_,
0927                        minDisToSeedperthickperlayer_,
0928                        maxDisToSeedperthickperlayer_);
0929       //---
0930       histograms.h_distancetoseedcell_perthickperlayer_eneweighted[istr] = ibook.book1D(
0931           "distancetoseedcell_perthickperlayer_eneweighted_" + istr,
0932           "energy weighted distance of cluster cells to seed cell for layer " + istr3 + " for thickness " + istr1,
0933           nintDisToSeedperthickperlayerenewei_,
0934           minDisToSeedperthickperlayerenewei_,
0935           maxDisToSeedperthickperlayerenewei_);
0936       //---
0937       histograms.h_distancetomaxcell_perthickperlayer[istr] =
0938           ibook.book1D("distancetomaxcell_perthickperlayer_" + istr,
0939                        "distance of cluster cells to max cell for layer " + istr3 + " for thickness " + istr1,
0940                        nintDisToMaxperthickperlayer_,
0941                        minDisToMaxperthickperlayer_,
0942                        maxDisToMaxperthickperlayer_);
0943       //---
0944       histograms.h_distancetomaxcell_perthickperlayer_eneweighted[istr] = ibook.book1D(
0945           "distancetomaxcell_perthickperlayer_eneweighted_" + istr,
0946           "energy weighted distance of cluster cells to max cell for layer " + istr3 + " for thickness " + istr1,
0947           nintDisToMaxperthickperlayerenewei_,
0948           minDisToMaxperthickperlayerenewei_,
0949           maxDisToMaxperthickperlayerenewei_);
0950       //---
0951       histograms.h_distancebetseedandmaxcell_perthickperlayer[istr] =
0952           ibook.book1D("distancebetseedandmaxcell_perthickperlayer_" + istr,
0953                        "distance of seed cell to max cell for layer " + istr3 + " for thickness " + istr1,
0954                        nintDisSeedToMaxperthickperlayer_,
0955                        minDisSeedToMaxperthickperlayer_,
0956                        maxDisSeedToMaxperthickperlayer_);
0957       //---
0958       histograms.h_distancebetseedandmaxcellvsclusterenergy_perthickperlayer[istr] = ibook.book2D(
0959           "distancebetseedandmaxcellvsclusterenergy_perthickperlayer_" + istr,
0960           "distance of seed cell to max cell vs cluster energy for layer " + istr3 + " for thickness " + istr1,
0961           nintDisSeedToMaxperthickperlayer_,
0962           minDisSeedToMaxperthickperlayer_,
0963           maxDisSeedToMaxperthickperlayer_,
0964           nintClEneperthickperlayer_,
0965           minClEneperthickperlayer_,
0966           maxClEneperthickperlayer_);
0967     }
0968   }
0969 }
0970 //----------------------------------------------------------------------------------------------------------------------------
0971 
0972 void HGVHistoProducerAlgo::bookTracksterHistos(DQMStore::IBooker& ibook, Histograms& histograms, unsigned int layers) {
0973   std::unordered_map<int, dqm::reco::MonitorElement*> clusternum_in_trackster_perlayer;
0974   clusternum_in_trackster_perlayer.clear();
0975 
0976   for (unsigned ilayer = 0; ilayer < 2 * layers; ++ilayer) {
0977     auto istr1 = std::to_string(ilayer);
0978     while (istr1.size() < 2) {
0979       istr1.insert(0, "0");
0980     }
0981     // Make a mapping to the regural layer naming plus z- or z+ for convenience
0982     std::string istr2 = "";
0983     // first with the -z endcap
0984     if (ilayer < layers) {
0985       istr2 = std::to_string(ilayer + 1) + " in z-";
0986     } else {  // then for the +z
0987       istr2 = std::to_string(ilayer - (layers - 1)) + " in z+";
0988     }
0989 
0990     clusternum_in_trackster_perlayer[ilayer] = ibook.book1D("clusternum_in_trackster_perlayer" + istr1,
0991                                                             "Number of layer clusters in Trackster for layer " + istr2,
0992                                                             nintTotNClsinTSTsperlayer_,
0993                                                             minTotNClsinTSTsperlayer_,
0994                                                             maxTotNClsinTSTsperlayer_);
0995   }
0996 
0997   histograms.h_clusternum_in_trackster_perlayer.push_back(std::move(clusternum_in_trackster_perlayer));
0998 
0999   histograms.h_tracksternum.push_back(ibook.book1D(
1000       "tottracksternum", "total number of Tracksters;# of Tracksters", nintTotNTSTs_, minTotNTSTs_, maxTotNTSTs_));
1001 
1002   histograms.h_conttracksternum.push_back(ibook.book1D(
1003       "conttracksternum", "number of Tracksters with 3 contiguous layers", nintTotNTSTs_, minTotNTSTs_, maxTotNTSTs_));
1004 
1005   histograms.h_nonconttracksternum.push_back(ibook.book1D("nonconttracksternum",
1006                                                           "number of Tracksters without 3 contiguous layers",
1007                                                           nintTotNTSTs_,
1008                                                           minTotNTSTs_,
1009                                                           maxTotNTSTs_));
1010 
1011   histograms.h_clusternum_in_trackster.push_back(
1012       ibook.book1D("clusternum_in_trackster",
1013                    "total number of layer clusters in Trackster;# of LayerClusters",
1014                    nintTotNClsinTSTs_,
1015                    minTotNClsinTSTs_,
1016                    maxTotNClsinTSTs_));
1017 
1018   histograms.h_clusternum_in_trackster_vs_layer.push_back(ibook.bookProfile(
1019       "clusternum_in_trackster_vs_layer",
1020       "Profile of 2d layer clusters in Trackster vs layer number;layer number;<2D LayerClusters in Trackster>",
1021       2 * layers,
1022       0.,
1023       2. * layers,
1024       minTotNClsinTSTsperlayer_,
1025       maxTotNClsinTSTsperlayer_));
1026 
1027   histograms.h_multiplicityOfLCinTST.push_back(
1028       ibook.book2D("multiplicityOfLCinTST",
1029                    "Multiplicity vs Layer cluster size in Tracksters;LayerCluster multiplicity in Tracksters;Cluster "
1030                    "size (n_{hits})",
1031                    nintMplofLCs_,
1032                    minMplofLCs_,
1033                    maxMplofLCs_,
1034                    nintSizeCLsinTSTs_,
1035                    minSizeCLsinTSTs_,
1036                    maxSizeCLsinTSTs_));
1037 
1038   histograms.h_multiplicity_numberOfEventsHistogram.push_back(ibook.book1D("multiplicity_numberOfEventsHistogram",
1039                                                                            "multiplicity numberOfEventsHistogram",
1040                                                                            nintMplofLCs_,
1041                                                                            minMplofLCs_,
1042                                                                            maxMplofLCs_));
1043 
1044   histograms.h_multiplicity_zminus_numberOfEventsHistogram.push_back(
1045       ibook.book1D("multiplicity_zminus_numberOfEventsHistogram",
1046                    "multiplicity numberOfEventsHistogram in z-",
1047                    nintMplofLCs_,
1048                    minMplofLCs_,
1049                    maxMplofLCs_));
1050 
1051   histograms.h_multiplicity_zplus_numberOfEventsHistogram.push_back(
1052       ibook.book1D("multiplicity_zplus_numberOfEventsHistogram",
1053                    "multiplicity numberOfEventsHistogram in z+",
1054                    nintMplofLCs_,
1055                    minMplofLCs_,
1056                    maxMplofLCs_));
1057 
1058   histograms.h_multiplicityOfLCinTST_vs_layercluster_zminus.push_back(
1059       ibook.book2D("multiplicityOfLCinTST_vs_layercluster_zminus",
1060                    "Multiplicity vs Layer number in z-;LayerCluster multiplicity in Tracksters;layer number",
1061                    nintMplofLCs_,
1062                    minMplofLCs_,
1063                    maxMplofLCs_,
1064                    layers,
1065                    0.,
1066                    (float)layers));
1067 
1068   histograms.h_multiplicityOfLCinTST_vs_layercluster_zplus.push_back(
1069       ibook.book2D("multiplicityOfLCinTST_vs_layercluster_zplus",
1070                    "Multiplicity vs Layer number in z+;LayerCluster multiplicity in Tracksters;layer number",
1071                    nintMplofLCs_,
1072                    minMplofLCs_,
1073                    maxMplofLCs_,
1074                    layers,
1075                    0.,
1076                    (float)layers));
1077 
1078   histograms.h_multiplicityOfLCinTST_vs_layerclusterenergy.push_back(
1079       ibook.book2D("multiplicityOfLCinTST_vs_layerclusterenergy",
1080                    "Multiplicity vs Layer cluster energy;LayerCluster multiplicity in Tracksters;Cluster energy [GeV]",
1081                    nintMplofLCs_,
1082                    minMplofLCs_,
1083                    maxMplofLCs_,
1084                    nintClEnepermultiplicity_,
1085                    minClEnepermultiplicity_,
1086                    maxClEnepermultiplicity_));
1087 
1088   histograms.h_trackster_pt.push_back(
1089       ibook.book1D("trackster_pt", "Pt of the Trackster;Trackster p_{T} [GeV]", nintPt_, minPt_, maxPt_));
1090   histograms.h_trackster_eta.push_back(
1091       ibook.book1D("trackster_eta", "Eta of the Trackster;Trackster #eta", nintEta_, minEta_, maxEta_));
1092   histograms.h_trackster_phi.push_back(
1093       ibook.book1D("trackster_phi", "Phi of the Trackster;Trackster #phi", nintPhi_, minPhi_, maxPhi_));
1094   histograms.h_trackster_energy.push_back(
1095       ibook.book1D("trackster_energy", "Energy of the Trackster;Trackster energy [GeV]", nintEne_, minEne_, maxEne_));
1096   histograms.h_trackster_x.push_back(
1097       ibook.book1D("trackster_x", "X position of the Trackster;Trackster x", nintX_, minX_, maxX_));
1098   histograms.h_trackster_y.push_back(
1099       ibook.book1D("trackster_y", "Y position of the Trackster;Trackster y", nintY_, minY_, maxY_));
1100   histograms.h_trackster_z.push_back(
1101       ibook.book1D("trackster_z", "Z position of the Trackster;Trackster z", nintZ_, minZ_, maxZ_));
1102   histograms.h_trackster_firstlayer.push_back(ibook.book1D(
1103       "trackster_firstlayer", "First layer of the Trackster;Trackster First Layer", 2 * layers, 0., (float)2 * layers));
1104   histograms.h_trackster_lastlayer.push_back(ibook.book1D(
1105       "trackster_lastlayer", "Last layer of the Trackster;Trackster Last Layer", 2 * layers, 0., (float)2 * layers));
1106   histograms.h_trackster_layersnum.push_back(
1107       ibook.book1D("trackster_layersnum",
1108                    "Number of layers of the Trackster;Trackster Number of Layers",
1109                    2 * layers,
1110                    0.,
1111                    (float)2 * layers));
1112 }
1113 
1114 void HGVHistoProducerAlgo::bookTracksterSTSHistos(DQMStore::IBooker& ibook,
1115                                                   Histograms& histograms,
1116                                                   const validationType valType) {
1117   const string ref[] = {"caloparticle", "simtrackster", "simtrackster_fromCP"};
1118   const string refT[] = {"CaloParticle", "SimTrackster", "SimTrackster_fromCP"};
1119   // Must be in sync with labels in PostProcessorHGCAL_cfi.py
1120   const string val[] = {"_Link", "_PR"};
1121   //const string val[] = {"_CP", "_PR", "_Link"};
1122   const string rtos = ";score Reco-to-Sim";
1123   const string stor = ";score Sim-to-Reco";
1124   const string shREnFr = ";shared Reco energy fraction";
1125   const string shSEnFr = ";shared Sim energy fraction";
1126 
1127   histograms.h_score_trackster2caloparticle[valType].push_back(
1128       ibook.book1D("Score_trackster2" + ref[valType],
1129                    "Score of Trackster per " + refT[valType] + rtos,
1130                    nintScore_,
1131                    minScore_,
1132                    maxScore_));
1133   histograms.h_score_trackster2bestCaloparticle[valType].push_back(
1134       ibook.book1D("ScoreFake_trackster2" + ref[valType],
1135                    "Score of Trackster per best " + refT[valType] + rtos,
1136                    nintScore_,
1137                    minScore_,
1138                    maxScore_));
1139   histograms.h_score_trackster2bestCaloparticle2[valType].push_back(
1140       ibook.book1D("ScoreMerge_trackster2" + ref[valType],
1141                    "Score of Trackster per 2^{nd} best " + refT[valType] + rtos,
1142                    nintScore_,
1143                    minScore_,
1144                    maxScore_));
1145   histograms.h_score_caloparticle2trackster[valType].push_back(
1146       ibook.book1D("Score_" + ref[valType] + "2trackster",
1147                    "Score of " + refT[valType] + " per Trackster" + stor,
1148                    nintScore_,
1149                    minScore_,
1150                    maxScore_));
1151   histograms.h_scorePur_caloparticle2trackster[valType].push_back(
1152       ibook.book1D("ScorePur_" + ref[valType] + "2trackster",
1153                    "Score of " + refT[valType] + " per best Trackster" + stor,
1154                    nintScore_,
1155                    minScore_,
1156                    maxScore_));
1157   histograms.h_scoreDupl_caloparticle2trackster[valType].push_back(
1158       ibook.book1D("ScoreDupl_" + ref[valType] + "2trackster",
1159                    "Score of " + refT[valType] + " per 2^{nd} best Trackster" + stor,
1160                    nintScore_,
1161                    minScore_,
1162                    maxScore_));
1163   histograms.h_energy_vs_score_trackster2caloparticle[valType].push_back(
1164       ibook.book2D("Energy_vs_Score_trackster2" + refT[valType],
1165                    "Energy vs Score of Trackster per " + refT[valType] + rtos + shREnFr,
1166                    nintScore_,
1167                    minScore_,
1168                    maxScore_,
1169                    nintSharedEneFrac_,
1170                    minTSTSharedEneFrac_,
1171                    maxTSTSharedEneFrac_));
1172   histograms.h_energy_vs_score_trackster2bestCaloparticle[valType].push_back(
1173       ibook.book2D("Energy_vs_Score_trackster2best" + refT[valType],
1174                    "Energy vs Score of Trackster per best " + refT[valType] + rtos + shREnFr,
1175                    nintScore_,
1176                    minScore_,
1177                    maxScore_,
1178                    nintSharedEneFrac_,
1179                    minTSTSharedEneFrac_,
1180                    maxTSTSharedEneFrac_));
1181   histograms.h_energy_vs_score_trackster2bestCaloparticle2[valType].push_back(
1182       ibook.book2D("Energy_vs_Score_trackster2secBest" + refT[valType],
1183                    "Energy vs Score of Trackster per 2^{nd} best " + refT[valType] + rtos + shREnFr,
1184                    nintScore_,
1185                    minScore_,
1186                    maxScore_,
1187                    nintSharedEneFrac_,
1188                    minTSTSharedEneFrac_,
1189                    maxTSTSharedEneFrac_));
1190   histograms.h_energy_vs_score_caloparticle2trackster[valType].push_back(
1191       ibook.book2D("Energy_vs_Score_" + ref[valType] + "2Trackster",
1192                    "Energy vs Score of " + refT[valType] + " per Trackster" + stor + shSEnFr,
1193                    nintScore_,
1194                    minScore_,
1195                    maxScore_,
1196                    nintSharedEneFrac_,
1197                    minTSTSharedEneFrac_,
1198                    maxTSTSharedEneFrac_));
1199   histograms.h_energy_vs_score_caloparticle2bestTrackster[valType].push_back(
1200       ibook.book2D("Energy_vs_Score_" + ref[valType] + "2bestTrackster",
1201                    "Energy vs Score of " + refT[valType] + " per best Trackster" + stor + shSEnFr,
1202                    nintScore_,
1203                    minScore_,
1204                    maxScore_,
1205                    nintSharedEneFrac_,
1206                    minTSTSharedEneFrac_,
1207                    maxTSTSharedEneFrac_));
1208   histograms.h_energy_vs_score_caloparticle2bestTrackster2[valType].push_back(
1209       ibook.book2D("Energy_vs_Score_" + ref[valType] + "2secBestTrackster",
1210                    "Energy vs Score of " + refT[valType] + " per 2^{nd} best Trackster" + stor + shSEnFr,
1211                    nintScore_,
1212                    minScore_,
1213                    maxScore_,
1214                    nintSharedEneFrac_,
1215                    minTSTSharedEneFrac_,
1216                    maxTSTSharedEneFrac_));
1217 
1218   // Back to all Tracksters
1219   // eta
1220   histograms.h_num_trackster_eta[valType].push_back(ibook.book1D(
1221       "Num_Trackster_Eta" + val[valType], "Num Trackster Eta per Trackster;#eta", nintEta_, minEta_, maxEta_));
1222   histograms.h_numMerge_trackster_eta[valType].push_back(ibook.book1D("NumMerge_Trackster_Eta" + val[valType],
1223                                                                       "Num Merge Trackster Eta per Trackster;#eta",
1224                                                                       nintEta_,
1225                                                                       minEta_,
1226                                                                       maxEta_));
1227   histograms.h_denom_trackster_eta[valType].push_back(ibook.book1D(
1228       "Denom_Trackster_Eta" + val[valType], "Denom Trackster Eta per Trackster;#eta", nintEta_, minEta_, maxEta_));
1229   // phi
1230   histograms.h_num_trackster_phi[valType].push_back(ibook.book1D(
1231       "Num_Trackster_Phi" + val[valType], "Num Trackster Phi per Trackster;#phi", nintPhi_, minPhi_, maxPhi_));
1232   histograms.h_numMerge_trackster_phi[valType].push_back(ibook.book1D("NumMerge_Trackster_Phi" + val[valType],
1233                                                                       "Num Merge Trackster Phi per Trackster;#phi",
1234                                                                       nintPhi_,
1235                                                                       minPhi_,
1236                                                                       maxPhi_));
1237   histograms.h_denom_trackster_phi[valType].push_back(ibook.book1D(
1238       "Denom_Trackster_Phi" + val[valType], "Denom Trackster Phi per Trackster;#phi", nintPhi_, minPhi_, maxPhi_));
1239   // energy
1240   histograms.h_num_trackster_en[valType].push_back(ibook.book1D("Num_Trackster_Energy" + val[valType],
1241                                                                 "Num Trackster Energy per Trackster;energy [GeV]",
1242                                                                 nintEne_,
1243                                                                 minEne_,
1244                                                                 maxEne_));
1245   histograms.h_numMerge_trackster_en[valType].push_back(
1246       ibook.book1D("NumMerge_Trackster_Energy" + val[valType],
1247                    "Num Merge Trackster Energy per Trackster;energy [GeV]",
1248                    nintEne_,
1249                    minEne_,
1250                    maxEne_));
1251   histograms.h_denom_trackster_en[valType].push_back(ibook.book1D("Denom_Trackster_Energy" + val[valType],
1252                                                                   "Denom Trackster Energy per Trackster;energy [GeV]",
1253                                                                   nintEne_,
1254                                                                   minEne_,
1255                                                                   maxEne_));
1256   // pT
1257   histograms.h_num_trackster_pt[valType].push_back(ibook.book1D(
1258       "Num_Trackster_Pt" + val[valType], "Num Trackster p_{T} per Trackster;p_{T} [GeV]", nintPt_, minPt_, maxPt_));
1259   histograms.h_numMerge_trackster_pt[valType].push_back(
1260       ibook.book1D("NumMerge_Trackster_Pt" + val[valType],
1261                    "Num Merge Trackster p_{T} per Trackster;p_{T} [GeV]",
1262                    nintPt_,
1263                    minPt_,
1264                    maxPt_));
1265   histograms.h_denom_trackster_pt[valType].push_back(ibook.book1D(
1266       "Denom_Trackster_Pt" + val[valType], "Denom Trackster p_{T} per Trackster;p_{T} [GeV]", nintPt_, minPt_, maxPt_));
1267 
1268   histograms.h_sharedenergy_trackster2caloparticle[valType].push_back(
1269       ibook.book1D("SharedEnergy_trackster2" + ref[valType],
1270                    "Shared Energy of Trackster per " + refT[valType] + shREnFr,
1271                    nintSharedEneFrac_,
1272                    minTSTSharedEneFrac_,
1273                    maxTSTSharedEneFrac_));
1274   histograms.h_sharedenergy_trackster2bestCaloparticle[valType].push_back(
1275       ibook.book1D("SharedEnergy_trackster2" + ref[valType] + "_assoc",
1276                    "Shared Energy of Trackster per best " + refT[valType] + shREnFr,
1277                    nintSharedEneFrac_,
1278                    minTSTSharedEneFrac_,
1279                    maxTSTSharedEneFrac_));
1280   histograms.h_sharedenergy_trackster2bestCaloparticle_vs_eta[valType].push_back(
1281       ibook.bookProfile("SharedEnergy_trackster2" + ref[valType] + "_assoc_vs_eta",
1282                         "Shared Energy of Trackster vs #eta per best " + refT[valType] + ";Trackster #eta" + shREnFr,
1283                         nintEta_,
1284                         minEta_,
1285                         maxEta_,
1286                         minTSTSharedEneFrac_,
1287                         maxTSTSharedEneFrac_));
1288   histograms.h_sharedenergy_trackster2bestCaloparticle_vs_phi[valType].push_back(
1289       ibook.bookProfile("SharedEnergy_trackster2" + ref[valType] + "_assoc_vs_phi",
1290                         "Shared Energy of Trackster vs #phi per best " + refT[valType] + ";Trackster #phi" + shREnFr,
1291                         nintPhi_,
1292                         minPhi_,
1293                         maxPhi_,
1294                         minTSTSharedEneFrac_,
1295                         maxTSTSharedEneFrac_));
1296   histograms.h_sharedenergy_trackster2bestCaloparticle2[valType].push_back(
1297       ibook.book1D("SharedEnergy_trackster2" + ref[valType] + "_assoc2",
1298                    "Shared Energy of Trackster per 2^{nd} best " + refT[valType] + shREnFr,
1299                    nintSharedEneFrac_,
1300                    minTSTSharedEneFrac_,
1301                    maxTSTSharedEneFrac_));
1302 
1303   histograms.h_sharedenergy_caloparticle2trackster[valType].push_back(
1304       ibook.book1D("SharedEnergy_" + ref[valType] + "2trackster",
1305                    "Shared Energy of " + refT[valType] + " per Trackster" + shSEnFr,
1306                    nintSharedEneFrac_,
1307                    minTSTSharedEneFrac_,
1308                    maxTSTSharedEneFrac_));
1309   histograms.h_sharedenergy_caloparticle2trackster_assoc[valType].push_back(
1310       ibook.book1D("SharedEnergy_" + ref[valType] + "2trackster_assoc",
1311                    "Shared Energy of " + refT[valType] + " per best Trackster" + shSEnFr,
1312                    nintSharedEneFrac_,
1313                    minTSTSharedEneFrac_,
1314                    maxTSTSharedEneFrac_));
1315   histograms.h_sharedenergy_caloparticle2trackster_assoc_vs_eta[valType].push_back(ibook.bookProfile(
1316       "SharedEnergy_" + ref[valType] + "2trackster_assoc_vs_eta",
1317       "Shared Energy of " + refT[valType] + " vs #eta per best Trackster;" + refT[valType] + " #eta" + shSEnFr,
1318       nintEta_,
1319       minEta_,
1320       maxEta_,
1321       minTSTSharedEneFrac_,
1322       maxTSTSharedEneFrac_));
1323   histograms.h_sharedenergy_caloparticle2trackster_assoc_vs_phi[valType].push_back(ibook.bookProfile(
1324       "SharedEnergy_" + ref[valType] + "2trackster_assoc_vs_phi",
1325       "Shared Energy of " + refT[valType] + " vs #phi per best Trackster;" + refT[valType] + " #phi" + shSEnFr,
1326       nintPhi_,
1327       minPhi_,
1328       maxPhi_,
1329       minTSTSharedEneFrac_,
1330       maxTSTSharedEneFrac_));
1331   histograms.h_sharedenergy_caloparticle2trackster_assoc2[valType].push_back(
1332       ibook.book1D("SharedEnergy_" + ref[valType] + "2trackster_assoc2",
1333                    "Shared Energy of " + refT[valType] + " per 2^{nd} best Trackster;" + shSEnFr,
1334                    nintSharedEneFrac_,
1335                    minTSTSharedEneFrac_,
1336                    maxTSTSharedEneFrac_));
1337 
1338   // eta
1339   histograms.h_numEff_caloparticle_eta[valType].push_back(
1340       ibook.book1D("NumEff_" + refT[valType] + "_Eta",
1341                    "Num Efficiency " + refT[valType] + " Eta per Trackster;#eta",
1342                    nintEta_,
1343                    minEta_,
1344                    maxEta_));
1345   histograms.h_num_caloparticle_eta[valType].push_back(
1346       ibook.book1D("Num_" + refT[valType] + "_Eta",
1347                    "Num Purity " + refT[valType] + " Eta per Trackster;#eta",
1348                    nintEta_,
1349                    minEta_,
1350                    maxEta_));
1351   histograms.h_numDup_trackster_eta[valType].push_back(ibook.book1D(
1352       "NumDup_Trackster_Eta" + val[valType], "Num Duplicate Trackster vs Eta;#eta", nintEta_, minEta_, maxEta_));
1353   histograms.h_denom_caloparticle_eta[valType].push_back(
1354       ibook.book1D("Denom_" + refT[valType] + "_Eta",
1355                    "Denom " + refT[valType] + " Eta per Trackster;#eta",
1356                    nintEta_,
1357                    minEta_,
1358                    maxEta_));
1359   // phi
1360   histograms.h_numEff_caloparticle_phi[valType].push_back(
1361       ibook.book1D("NumEff_" + refT[valType] + "_Phi",
1362                    "Num Efficiency " + refT[valType] + " Phi per Trackster;#phi",
1363                    nintPhi_,
1364                    minPhi_,
1365                    maxPhi_));
1366   histograms.h_num_caloparticle_phi[valType].push_back(
1367       ibook.book1D("Num_" + refT[valType] + "_Phi",
1368                    "Num Purity " + refT[valType] + " Phi per Trackster;#phi",
1369                    nintPhi_,
1370                    minPhi_,
1371                    maxPhi_));
1372   histograms.h_numDup_trackster_phi[valType].push_back(ibook.book1D(
1373       "NumDup_Trackster_Phi" + val[valType], "Num Duplicate Trackster vs Phi;#phi", nintPhi_, minPhi_, maxPhi_));
1374   histograms.h_denom_caloparticle_phi[valType].push_back(
1375       ibook.book1D("Denom_" + refT[valType] + "_Phi",
1376                    "Denom " + refT[valType] + " Phi per Trackster;#phi",
1377                    nintPhi_,
1378                    minPhi_,
1379                    maxPhi_));
1380   // energy
1381   histograms.h_numEff_caloparticle_en[valType].push_back(
1382       ibook.book1D("NumEff_" + refT[valType] + "_Energy",
1383                    "Num Efficiency " + refT[valType] + " Energy per Trackster;energy [GeV]",
1384                    nintEne_,
1385                    minEne_,
1386                    maxEne_));
1387   histograms.h_num_caloparticle_en[valType].push_back(
1388       ibook.book1D("Num_" + refT[valType] + "_Energy",
1389                    "Num Purity " + refT[valType] + " Energy per Trackster;energy [GeV]",
1390                    nintEne_,
1391                    minEne_,
1392                    maxEne_));
1393   histograms.h_numDup_trackster_en[valType].push_back(ibook.book1D("NumDup_Trackster_Energy" + val[valType],
1394                                                                    "Num Duplicate Trackster vs Energy;energy [GeV]",
1395                                                                    nintEne_,
1396                                                                    minEne_,
1397                                                                    maxEne_));
1398   histograms.h_denom_caloparticle_en[valType].push_back(
1399       ibook.book1D("Denom_" + refT[valType] + "_Energy",
1400                    "Denom " + refT[valType] + " Energy per Trackster;energy [GeV]",
1401                    nintEne_,
1402                    minEne_,
1403                    maxEne_));
1404   // pT
1405   histograms.h_numEff_caloparticle_pt[valType].push_back(
1406       ibook.book1D("NumEff_" + refT[valType] + "_Pt",
1407                    "Num Efficiency " + refT[valType] + " p_{T} per Trackster;p_{T} [GeV]",
1408                    nintPt_,
1409                    minPt_,
1410                    maxPt_));
1411   histograms.h_num_caloparticle_pt[valType].push_back(
1412       ibook.book1D("Num_" + refT[valType] + "_Pt",
1413                    "Num Purity " + refT[valType] + " p_{T} per Trackster;p_{T} [GeV]",
1414                    nintPt_,
1415                    minPt_,
1416                    maxPt_));
1417   histograms.h_numDup_trackster_pt[valType].push_back(ibook.book1D(
1418       "NumDup_Trackster_Pt" + val[valType], "Num Duplicate Trackster vs p_{T};p_{T} [GeV]", nintPt_, minPt_, maxPt_));
1419   histograms.h_denom_caloparticle_pt[valType].push_back(
1420       ibook.book1D("Denom_" + refT[valType] + "_Pt",
1421                    "Denom " + refT[valType] + " p_{T} per Trackster;p_{T} [GeV]",
1422                    nintPt_,
1423                    minPt_,
1424                    maxPt_));
1425 }
1426 
1427 void HGVHistoProducerAlgo::fill_info_histos(const Histograms& histograms, unsigned int layers) const {
1428   // Save some info straight from geometry to avoid mistakes from updates
1429   //----------- TODO ----------------------------------------------------------
1430   // For now values returned for 'lastLayerFHzp': '104', 'lastLayerFHzm': '52' are not the one expected.
1431   // Will come back to this when there will be info in CMSSW to put in DQM file.
1432   histograms.lastLayerEEzm->Fill(recHitTools_->lastLayerEE());
1433   histograms.lastLayerFHzm->Fill(recHitTools_->lastLayerFH());
1434   histograms.maxlayerzm->Fill(layers);
1435   histograms.lastLayerEEzp->Fill(recHitTools_->lastLayerEE() + layers);
1436   histograms.lastLayerFHzp->Fill(recHitTools_->lastLayerFH() + layers);
1437   histograms.maxlayerzp->Fill(layers + layers);
1438 }
1439 
1440 void HGVHistoProducerAlgo::fill_caloparticle_histos(const Histograms& histograms,
1441                                                     int pdgid,
1442                                                     const CaloParticle& caloParticle,
1443                                                     std::vector<SimVertex> const& simVertices,
1444                                                     unsigned int layers,
1445                                                     std::unordered_map<DetId, const unsigned int> const& hitMap,
1446                                                     std::vector<HGCRecHit> const& hits) const {
1447   const auto eta = getEta(caloParticle.eta());
1448   if (histograms.h_caloparticle_eta.count(pdgid)) {
1449     histograms.h_caloparticle_eta.at(pdgid)->Fill(eta);
1450   }
1451   if (histograms.h_caloparticle_eta_Zorigin.count(pdgid)) {
1452     histograms.h_caloparticle_eta_Zorigin.at(pdgid)->Fill(
1453         simVertices.at(caloParticle.g4Tracks()[0].vertIndex()).position().z(), eta);
1454   }
1455 
1456   if (histograms.h_caloparticle_energy.count(pdgid)) {
1457     histograms.h_caloparticle_energy.at(pdgid)->Fill(caloParticle.energy());
1458   }
1459   if (histograms.h_caloparticle_pt.count(pdgid)) {
1460     histograms.h_caloparticle_pt.at(pdgid)->Fill(caloParticle.pt());
1461   }
1462   if (histograms.h_caloparticle_phi.count(pdgid)) {
1463     histograms.h_caloparticle_phi.at(pdgid)->Fill(caloParticle.phi());
1464   }
1465 
1466   if (histograms.h_caloparticle_nSimClusters.count(pdgid)) {
1467     histograms.h_caloparticle_nSimClusters.at(pdgid)->Fill(caloParticle.simClusters().size());
1468 
1469     int simHits = 0;
1470     int minLayerId = 999;
1471     int maxLayerId = 0;
1472 
1473     int simHits_matched = 0;
1474     int minLayerId_matched = 999;
1475     int maxLayerId_matched = 0;
1476 
1477     float energy = 0.;
1478     std::map<int, double> totenergy_layer;
1479 
1480     float hitEnergyWeight_invSum = 0;
1481     std::vector<std::pair<DetId, float>> haf_cp;
1482     for (const auto& sc : caloParticle.simClusters()) {
1483       LogDebug("HGCalValidator") << " This sim cluster has " << sc->hits_and_fractions().size() << " simHits and "
1484                                  << sc->energy() << " energy. " << std::endl;
1485       simHits += sc->hits_and_fractions().size();
1486       for (auto const& h_and_f : sc->hits_and_fractions()) {
1487         const auto hitDetId = h_and_f.first;
1488         const int layerId =
1489             recHitTools_->getLayerWithOffset(hitDetId) + layers * ((recHitTools_->zside(hitDetId) + 1) >> 1) - 1;
1490         // set to 0 if matched RecHit not found
1491         int layerId_matched_min = 999;
1492         int layerId_matched_max = 0;
1493         std::unordered_map<DetId, const unsigned int>::const_iterator itcheck = hitMap.find(hitDetId);
1494         if (itcheck != hitMap.end()) {
1495           layerId_matched_min = layerId;
1496           layerId_matched_max = layerId;
1497           simHits_matched++;
1498 
1499           const auto hitEn = (hits[itcheck->second]).energy();
1500           hitEnergyWeight_invSum += pow(hitEn, 2);
1501           const auto hitFr = h_and_f.second;
1502           const auto hitEnFr = hitEn * hitFr;
1503           energy += hitEnFr;
1504           histograms.h_caloparticle_nHits_matched_energy.at(pdgid)->Fill(hitEnFr);
1505           histograms.h_caloparticle_nHits_matched_energy_layer.at(pdgid)->Fill(layerId, hitEnFr);
1506 
1507           if (totenergy_layer.find(layerId) != totenergy_layer.end()) {
1508             totenergy_layer[layerId] = totenergy_layer.at(layerId) + hitEn;
1509           } else {
1510             totenergy_layer.emplace(layerId, hitEn);
1511           }
1512           if (caloParticle.simClusters().size() == 1)
1513             histograms.h_caloparticle_nHits_matched_energy_layer_1SimCl.at(pdgid)->Fill(layerId, hitEnFr);
1514 
1515           auto found = std::find_if(std::begin(haf_cp),
1516                                     std::end(haf_cp),
1517                                     [&hitDetId](const std::pair<DetId, float>& v) { return v.first == hitDetId; });
1518           if (found != haf_cp.end())
1519             found->second += hitFr;
1520           else
1521             haf_cp.emplace_back(hitDetId, hitFr);
1522 
1523         } else {
1524           LogDebug("HGCalValidator") << "   matched to RecHit NOT found !" << std::endl;
1525         }
1526 
1527         minLayerId = std::min(minLayerId, layerId);
1528         maxLayerId = std::max(maxLayerId, layerId);
1529         minLayerId_matched = std::min(minLayerId_matched, layerId_matched_min);
1530         maxLayerId_matched = std::max(maxLayerId_matched, layerId_matched_max);
1531       }
1532       LogDebug("HGCalValidator") << std::endl;
1533     }  // End loop over SimClusters of CaloParticle
1534     if (hitEnergyWeight_invSum)
1535       hitEnergyWeight_invSum = 1 / hitEnergyWeight_invSum;
1536 
1537     histograms.h_caloparticle_firstlayer.at(pdgid)->Fill(minLayerId);
1538     histograms.h_caloparticle_lastlayer.at(pdgid)->Fill(maxLayerId);
1539     histograms.h_caloparticle_layersnum.at(pdgid)->Fill(int(maxLayerId - minLayerId));
1540 
1541     histograms.h_caloparticle_firstlayer_matchedtoRecHit.at(pdgid)->Fill(minLayerId_matched);
1542     histograms.h_caloparticle_lastlayer_matchedtoRecHit.at(pdgid)->Fill(maxLayerId_matched);
1543     histograms.h_caloparticle_layersnum_matchedtoRecHit.at(pdgid)->Fill(int(maxLayerId_matched - minLayerId_matched));
1544 
1545     histograms.h_caloparticle_nHitsInSimClusters.at(pdgid)->Fill((float)simHits);
1546     histograms.h_caloparticle_nHitsInSimClusters_matchedtoRecHit.at(pdgid)->Fill((float)simHits_matched);
1547     histograms.h_caloparticle_selfenergy.at(pdgid)->Fill((float)energy);
1548     histograms.h_caloparticle_energyDifference.at(pdgid)->Fill((float)1. - energy / caloParticle.energy());
1549 
1550     //Calculate sum energy per-layer
1551     auto i = totenergy_layer.begin();
1552     double sum_energy = 0.0;
1553     while (i != totenergy_layer.end()) {
1554       sum_energy += i->second;
1555       histograms.h_caloparticle_sum_energy_layer.at(pdgid)->Fill(i->first, sum_energy / caloParticle.energy() * 100.);
1556       i++;
1557     }
1558 
1559     for (auto const& haf : haf_cp) {
1560       const auto hitEn = (hits[hitMap.find(haf.first)->second]).energy();
1561       const auto weight = pow(hitEn, 2);
1562       histograms.h_caloparticle_fractions.at(pdgid)->Fill(haf.second, weight * hitEnergyWeight_invSum);
1563       histograms.h_caloparticle_fractions_weight.at(pdgid)->Fill(haf.second, weight * hitEnergyWeight_invSum, weight);
1564     }
1565   }
1566 }
1567 
1568 void HGVHistoProducerAlgo::HGVHistoProducerAlgo::fill_simCluster_histos(const Histograms& histograms,
1569                                                                         std::vector<SimCluster> const& simClusters,
1570                                                                         unsigned int layers,
1571                                                                         std::vector<int> thicknesses) const {
1572   //Each event to be treated as two events: an event in +ve endcap,
1573   //plus another event in -ve endcap. In this spirit there will be
1574   //a layer variable (layerid) that maps the layers in :
1575   //-z: 0->49
1576   //+z: 50->99
1577 
1578   //To keep track of total num of simClusters per layer
1579   //tnscpl[layerid]
1580   std::vector<int> tnscpl(1000, 0);  //tnscpl.clear(); tnscpl.reserve(1000);
1581 
1582   //To keep track of the total num of clusters per thickness in plus and in minus endcaps
1583   std::map<std::string, int> tnscpthplus;
1584   tnscpthplus.clear();
1585   std::map<std::string, int> tnscpthminus;
1586   tnscpthminus.clear();
1587   //At the beginning of the event all layers should be initialized to zero total clusters per thickness
1588   for (std::vector<int>::iterator it = thicknesses.begin(); it != thicknesses.end(); ++it) {
1589     tnscpthplus.insert(std::pair<std::string, int>(std::to_string(*it), 0));
1590     tnscpthminus.insert(std::pair<std::string, int>(std::to_string(*it), 0));
1591   }
1592   //To keep track of the total num of simClusters with mixed thickness hits per event
1593   tnscpthplus.insert(std::pair<std::string, int>("mixed", 0));
1594   tnscpthminus.insert(std::pair<std::string, int>("mixed", 0));
1595 
1596   //loop through simClusters
1597   for (const auto& sc : simClusters) {
1598     //Auxillary variables to count the number of different kind of hits in each simCluster
1599     int nthhits120p = 0;
1600     int nthhits200p = 0;
1601     int nthhits300p = 0;
1602     int nthhitsscintp = 0;
1603     int nthhits120m = 0;
1604     int nthhits200m = 0;
1605     int nthhits300m = 0;
1606     int nthhitsscintm = 0;
1607     //For the hits thickness of the layer cluster.
1608     double thickness = 0.;
1609     //To keep track if we added the simCluster in a specific layer
1610     std::vector<int> occurenceSCinlayer(1000, 0);  //[layerid][0 if not added]
1611 
1612     //loop through hits of the simCluster
1613     for (const auto& hAndF : sc.hits_and_fractions()) {
1614       const DetId sh_detid = hAndF.first;
1615 
1616       if (sh_detid.det() == DetId::Forward || sh_detid.det() == DetId::HGCalEE || sh_detid.det() == DetId::HGCalHSi ||
1617           sh_detid.det() == DetId::HGCalHSc) {
1618         //The layer the cluster belongs to. As mentioned in the mapping above, it takes into account -z and +z.
1619         int layerid =
1620             recHitTools_->getLayerWithOffset(sh_detid) + layers * ((recHitTools_->zside(sh_detid) + 1) >> 1) - 1;
1621         //zside that the current cluster belongs to.
1622         int zside = recHitTools_->zside(sh_detid);
1623 
1624         //add the simCluster to the relevant layer. A SimCluster may give contribution to several layers.
1625         if (occurenceSCinlayer[layerid] == 0) {
1626           tnscpl[layerid]++;
1627         }
1628         occurenceSCinlayer[layerid]++;
1629 
1630         if (sh_detid.det() == DetId::HGCalHSc)
1631           thickness = -1;
1632         else
1633           thickness = recHitTools_->getSiThickness(sh_detid);
1634 
1635         if ((thickness == 120.) && (zside > 0.)) {
1636           nthhits120p++;
1637         } else if ((thickness == 120.) && (zside < 0.)) {
1638           nthhits120m++;
1639         } else if ((thickness == 200.) && (zside > 0.)) {
1640           nthhits200p++;
1641         } else if ((thickness == 200.) && (zside < 0.)) {
1642           nthhits200m++;
1643         } else if ((thickness == 300.) && (zside > 0.)) {
1644           nthhits300p++;
1645         } else if ((thickness == 300.) && (zside < 0.)) {
1646           nthhits300m++;
1647         } else if ((thickness == -1) && (zside > 0.)) {
1648           nthhitsscintp++;
1649         } else if ((thickness == -1) && (zside < 0.)) {
1650           nthhitsscintm++;
1651         } else {  //assert(0);
1652           LogDebug("HGCalValidator")
1653               << " You are running a geometry that contains thicknesses different than the normal ones. "
1654               << "\n";
1655         }
1656       }
1657     }  //end of loop through hits
1658 
1659     //Check for simultaneously having hits of different kind. Checking at least two combinations is sufficient.
1660     if ((nthhits120p != 0 && nthhits200p != 0) || (nthhits120p != 0 && nthhits300p != 0) ||
1661         (nthhits120p != 0 && nthhitsscintp != 0) || (nthhits200p != 0 && nthhits300p != 0) ||
1662         (nthhits200p != 0 && nthhitsscintp != 0) || (nthhits300p != 0 && nthhitsscintp != 0)) {
1663       tnscpthplus["mixed"]++;
1664     } else if ((nthhits120p != 0 || nthhits200p != 0 || nthhits300p != 0 || nthhitsscintp != 0)) {
1665       //This is a cluster with hits of one kind
1666       tnscpthplus[std::to_string((int)thickness)]++;
1667     }
1668     if ((nthhits120m != 0 && nthhits200m != 0) || (nthhits120m != 0 && nthhits300m != 0) ||
1669         (nthhits120m != 0 && nthhitsscintm != 0) || (nthhits200m != 0 && nthhits300m != 0) ||
1670         (nthhits200m != 0 && nthhitsscintm != 0) || (nthhits300m != 0 && nthhitsscintm != 0)) {
1671       tnscpthminus["mixed"]++;
1672     } else if ((nthhits120m != 0 || nthhits200m != 0 || nthhits300m != 0 || nthhitsscintm != 0)) {
1673       //This is a cluster with hits of one kind
1674       tnscpthminus[std::to_string((int)thickness)]++;
1675     }
1676   }  //end of loop through SimClusters of the event
1677 
1678   //Per layer : Loop 0->99
1679   for (unsigned ilayer = 0; ilayer < layers * 2; ++ilayer)
1680     if (histograms.h_simclusternum_perlayer.count(ilayer))
1681       histograms.h_simclusternum_perlayer.at(ilayer)->Fill(tnscpl[ilayer]);
1682 
1683   //Per thickness
1684   for (std::vector<int>::iterator it = thicknesses.begin(); it != thicknesses.end(); ++it) {
1685     if (histograms.h_simclusternum_perthick.count(*it)) {
1686       histograms.h_simclusternum_perthick.at(*it)->Fill(tnscpthplus[std::to_string(*it)]);
1687       histograms.h_simclusternum_perthick.at(*it)->Fill(tnscpthminus[std::to_string(*it)]);
1688     }
1689   }
1690   //Mixed thickness clusters
1691   histograms.h_mixedhitssimcluster_zplus->Fill(tnscpthplus["mixed"]);
1692   histograms.h_mixedhitssimcluster_zminus->Fill(tnscpthminus["mixed"]);
1693 }
1694 
1695 void HGVHistoProducerAlgo::HGVHistoProducerAlgo::fill_simClusterAssociation_histos(
1696     const Histograms& histograms,
1697     const int count,
1698     edm::Handle<reco::CaloClusterCollection> clusterHandle,
1699     const reco::CaloClusterCollection& clusters,
1700     edm::Handle<std::vector<SimCluster>> simClusterHandle,
1701     std::vector<SimCluster> const& simClusters,
1702     std::vector<size_t> const& sCIndices,
1703     const std::vector<float>& mask,
1704     std::unordered_map<DetId, const unsigned int> const& hitMap,
1705     unsigned int layers,
1706     const ticl::RecoToSimCollectionWithSimClusters& scsInLayerClusterMap,
1707     const ticl::SimToRecoCollectionWithSimClusters& lcsInSimClusterMap,
1708     std::vector<HGCRecHit> const& hits) const {
1709   //Each event to be treated as two events: an event in +ve endcap,
1710   //plus another event in -ve endcap. In this spirit there will be
1711   //a layer variable (layerid) that maps the layers in :
1712   //-z: 0->49
1713   //+z: 50->99
1714 
1715   //Will add some general plots on the specific mask in the future.
1716 
1717   layerClusters_to_SimClusters(histograms,
1718                                count,
1719                                clusterHandle,
1720                                clusters,
1721                                simClusterHandle,
1722                                simClusters,
1723                                sCIndices,
1724                                mask,
1725                                hitMap,
1726                                layers,
1727                                scsInLayerClusterMap,
1728                                lcsInSimClusterMap,
1729                                hits);
1730 }
1731 
1732 void HGVHistoProducerAlgo::fill_cluster_histos(const Histograms& histograms,
1733                                                const int count,
1734                                                const reco::CaloCluster& cluster) const {
1735   const auto eta = getEta(cluster.eta());
1736   histograms.h_cluster_eta[count]->Fill(eta);
1737 }
1738 
1739 void HGVHistoProducerAlgo::layerClusters_to_CaloParticles(const Histograms& histograms,
1740                                                           edm::Handle<reco::CaloClusterCollection> clusterHandle,
1741                                                           const reco::CaloClusterCollection& clusters,
1742                                                           edm::Handle<std::vector<CaloParticle>> caloParticleHandle,
1743                                                           std::vector<CaloParticle> const& cP,
1744                                                           std::vector<size_t> const& cPIndices,
1745                                                           std::vector<size_t> const& cPSelectedIndices,
1746                                                           std::unordered_map<DetId, const unsigned int> const& hitMap,
1747                                                           unsigned int layers,
1748                                                           const ticl::RecoToSimCollection& cpsInLayerClusterMap,
1749                                                           const ticl::SimToRecoCollection& cPOnLayerMap,
1750                                                           std::vector<HGCRecHit> const& hits) const {
1751   const auto nLayerClusters = clusters.size();
1752 
1753   std::unordered_map<DetId, std::vector<HGVHistoProducerAlgo::detIdInfoInCluster>> detIdToCaloParticleId_Map;
1754   std::unordered_map<DetId, std::vector<HGVHistoProducerAlgo::detIdInfoInCluster>> detIdToLayerClusterId_Map;
1755 
1756   // The association has to be done in an all-vs-all fashion.
1757   // For this reason use the full set of CaloParticles, with the only filter on bx
1758   for (const auto& cpId : cPIndices) {
1759     for (const auto& simCluster : cP[cpId].simClusters()) {
1760       for (const auto& it_haf : simCluster->hits_and_fractions()) {
1761         const DetId hitid = (it_haf.first);
1762         if (hitMap.find(hitid) != hitMap.end()) {
1763           if (detIdToCaloParticleId_Map.find(hitid) == detIdToCaloParticleId_Map.end()) {
1764             detIdToCaloParticleId_Map[hitid] = std::vector<HGVHistoProducerAlgo::detIdInfoInCluster>();
1765             detIdToCaloParticleId_Map[hitid].emplace_back(
1766                 HGVHistoProducerAlgo::detIdInfoInCluster{cpId, it_haf.second});
1767           } else {
1768             auto findHitIt =
1769                 std::find(detIdToCaloParticleId_Map[hitid].begin(),
1770                           detIdToCaloParticleId_Map[hitid].end(),
1771                           HGVHistoProducerAlgo::detIdInfoInCluster{
1772                               cpId, 0.f});  // only the first element is used for the matching (overloaded operator==)
1773             if (findHitIt != detIdToCaloParticleId_Map[hitid].end())
1774               findHitIt->fraction += it_haf.second;
1775             else
1776               detIdToCaloParticleId_Map[hitid].emplace_back(
1777                   HGVHistoProducerAlgo::detIdInfoInCluster{cpId, it_haf.second});
1778           }
1779         }
1780       }
1781     }
1782   }
1783 
1784   for (unsigned int lcId = 0; lcId < nLayerClusters; ++lcId) {
1785     const auto& hits_and_fractions = clusters[lcId].hitsAndFractions();
1786     const auto numberOfHitsInLC = hits_and_fractions.size();
1787 
1788     // This vector will store, for each hit in the Layercluster, the index of
1789     // the CaloParticle that contributed the most, in terms of energy, to it.
1790     // Special values are:
1791     //
1792     // -2  --> the reconstruction fraction of the RecHit is 0 (used in the past to monitor Halo Hits)
1793     // -3  --> same as before with the added condition that no CaloParticle has been linked to this RecHit
1794     // -1  --> the reco fraction is >0, but no CaloParticle has been linked to it
1795     // >=0 --> index of the linked CaloParticle
1796     std::vector<int> hitsToCaloParticleId(numberOfHitsInLC);
1797     const auto firstHitDetId = hits_and_fractions[0].first;
1798     int lcLayerId =
1799         recHitTools_->getLayerWithOffset(firstHitDetId) + layers * ((recHitTools_->zside(firstHitDetId) + 1) >> 1) - 1;
1800 
1801     // This will store the fraction of the CaloParticle energy shared with the LayerCluster: e_shared/cp_energy
1802     std::unordered_map<unsigned, float> CPEnergyInLC;
1803 
1804     for (unsigned int iHit = 0; iHit < numberOfHitsInLC; iHit++) {
1805       const DetId rh_detid = hits_and_fractions[iHit].first;
1806       const auto rhFraction = hits_and_fractions[iHit].second;
1807 
1808       std::unordered_map<DetId, const unsigned int>::const_iterator itcheck = hitMap.find(rh_detid);
1809       const HGCRecHit* hit = &(hits[itcheck->second]);
1810 
1811       if (detIdToLayerClusterId_Map.find(rh_detid) == detIdToLayerClusterId_Map.end()) {
1812         detIdToLayerClusterId_Map[rh_detid] = std::vector<HGVHistoProducerAlgo::detIdInfoInCluster>();
1813       }
1814       detIdToLayerClusterId_Map[rh_detid].emplace_back(HGVHistoProducerAlgo::detIdInfoInCluster{lcId, rhFraction});
1815 
1816       const auto& hit_find_in_CP = detIdToCaloParticleId_Map.find(rh_detid);
1817 
1818       // if the fraction is zero or the hit does not belong to any calo
1819       // particle, set the caloparticleId for the hit to -1 this will
1820       // contribute to the number of noise hits
1821 
1822       // MR Remove the case in which the fraction is 0, since this could be a
1823       // real hit that has been marked as halo.
1824       if (rhFraction == 0.) {
1825         hitsToCaloParticleId[iHit] = -2;
1826       }
1827       if (hit_find_in_CP == detIdToCaloParticleId_Map.end()) {
1828         hitsToCaloParticleId[iHit] -= 1;
1829       } else {
1830         auto maxCPEnergyInLC = 0.f;
1831         auto maxCPId = -1;
1832         for (auto& h : hit_find_in_CP->second) {
1833           const auto iCP = h.clusterId;
1834           CPEnergyInLC[iCP] += h.fraction * hit->energy();
1835           // Keep track of which CaloParticle contributed the most, in terms
1836           // of energy, to this specific LayerCluster.
1837           if (CPEnergyInLC[iCP] > maxCPEnergyInLC) {
1838             maxCPEnergyInLC = CPEnergyInLC[iCP];
1839             maxCPId = iCP;
1840           }
1841         }
1842         hitsToCaloParticleId[iHit] = maxCPId;
1843       }
1844       histograms.h_cellAssociation_perlayer.at(lcLayerId)->Fill(
1845           hitsToCaloParticleId[iHit] > 0. ? 0. : hitsToCaloParticleId[iHit]);
1846     }  // End loop over hits on a LayerCluster
1847 
1848   }  // End of loop over LayerClusters
1849 
1850   // Fill the plots to compute the different metrics linked to
1851   // reco-level, namely fake-rate an merge-rate. In this loop should *not*
1852   // restrict only to the selected caloParaticles.
1853   for (unsigned int lcId = 0; lcId < nLayerClusters; ++lcId) {
1854     const auto firstHitDetId = (clusters[lcId].hitsAndFractions())[0].first;
1855     const int lcLayerId =
1856         recHitTools_->getLayerWithOffset(firstHitDetId) + layers * ((recHitTools_->zside(firstHitDetId) + 1) >> 1) - 1;
1857     histograms.h_denom_layercl_eta_perlayer.at(lcLayerId)->Fill(clusters[lcId].eta());
1858     histograms.h_denom_layercl_phi_perlayer.at(lcLayerId)->Fill(clusters[lcId].phi());
1859     //
1860     const edm::Ref<reco::CaloClusterCollection> lcRef(clusterHandle, lcId);
1861     const auto& cpsIt = cpsInLayerClusterMap.find(lcRef);
1862     if (cpsIt == cpsInLayerClusterMap.end())
1863       continue;
1864 
1865     const auto lc_en = clusters[lcId].energy();
1866     const auto& cps = cpsIt->val;
1867     if (lc_en == 0. && !cps.empty()) {
1868       for (const auto& cpPair : cps)
1869         histograms.h_score_layercl2caloparticle_perlayer.at(lcLayerId)->Fill(cpPair.second);
1870       continue;
1871     }
1872     for (const auto& cpPair : cps) {
1873       LogDebug("HGCalValidator") << "layerCluster Id: \t" << lcId << "\t CP id: \t" << cpPair.first.index()
1874                                  << "\t score \t" << cpPair.second << std::endl;
1875       histograms.h_score_layercl2caloparticle_perlayer.at(lcLayerId)->Fill(cpPair.second);
1876       auto const& cp_linked =
1877           std::find_if(std::begin(cPOnLayerMap[cpPair.first]),
1878                        std::end(cPOnLayerMap[cpPair.first]),
1879                        [&lcRef](const std::pair<edm::Ref<reco::CaloClusterCollection>, std::pair<float, float>>& p) {
1880                          return p.first == lcRef;
1881                        });
1882       if (cp_linked ==
1883           cPOnLayerMap[cpPair.first].end())  // This should never happen by construction of the association maps
1884         continue;
1885       histograms.h_sharedenergy_layercl2caloparticle_perlayer.at(lcLayerId)->Fill(cp_linked->second.first / lc_en,
1886                                                                                   lc_en);
1887       histograms.h_energy_vs_score_layercl2caloparticle_perlayer.at(lcLayerId)->Fill(cpPair.second,
1888                                                                                      cp_linked->second.first / lc_en);
1889     }
1890     const auto assoc =
1891         std::count_if(std::begin(cps), std::end(cps), [](const auto& obj) { return obj.second < ScoreCutLCtoCP_; });
1892     if (assoc) {
1893       histograms.h_num_layercl_eta_perlayer.at(lcLayerId)->Fill(clusters[lcId].eta());
1894       histograms.h_num_layercl_phi_perlayer.at(lcLayerId)->Fill(clusters[lcId].phi());
1895       if (assoc > 1) {
1896         histograms.h_numMerge_layercl_eta_perlayer.at(lcLayerId)->Fill(clusters[lcId].eta());
1897         histograms.h_numMerge_layercl_phi_perlayer.at(lcLayerId)->Fill(clusters[lcId].phi());
1898       }
1899       const auto& best = std::min_element(
1900           std::begin(cps), std::end(cps), [](const auto& obj1, const auto& obj2) { return obj1.second < obj2.second; });
1901       const auto& best_cp_linked =
1902           std::find_if(std::begin(cPOnLayerMap[best->first]),
1903                        std::end(cPOnLayerMap[best->first]),
1904                        [&lcRef](const std::pair<edm::Ref<reco::CaloClusterCollection>, std::pair<float, float>>& p) {
1905                          return p.first == lcRef;
1906                        });
1907       if (best_cp_linked ==
1908           cPOnLayerMap[best->first].end())  // This should never happen by construction of the association maps
1909         continue;
1910       histograms.h_sharedenergy_layercl2caloparticle_vs_eta_perlayer.at(lcLayerId)->Fill(
1911           clusters[lcId].eta(), best_cp_linked->second.first / lc_en);
1912       histograms.h_sharedenergy_layercl2caloparticle_vs_phi_perlayer.at(lcLayerId)->Fill(
1913           clusters[lcId].phi(), best_cp_linked->second.first / lc_en);
1914     }
1915   }  // End of loop over LayerClusters
1916 
1917   // Here Fill the plots to compute the different metrics linked to
1918   // gen-level, namely efficiency and duplicate. In this loop should restrict
1919   // only to the selected caloParaticles.
1920   for (const auto& cpId : cPSelectedIndices) {
1921     const edm::Ref<CaloParticleCollection> cpRef(caloParticleHandle, cpId);
1922     const auto& lcsIt = cPOnLayerMap.find(cpRef);
1923 
1924     std::map<unsigned int, float> cPEnergyOnLayer;
1925     for (unsigned int layerId = 0; layerId < layers * 2; ++layerId)
1926       cPEnergyOnLayer[layerId] = 0;
1927 
1928     for (const auto& simCluster : cP[cpId].simClusters()) {
1929       for (const auto& it_haf : simCluster->hits_and_fractions()) {
1930         const DetId hitid = (it_haf.first);
1931         const auto hitLayerId =
1932             recHitTools_->getLayerWithOffset(hitid) + layers * ((recHitTools_->zside(hitid) + 1) >> 1) - 1;
1933         std::unordered_map<DetId, const unsigned int>::const_iterator itcheck = hitMap.find(hitid);
1934         if (itcheck != hitMap.end()) {
1935           const HGCRecHit* hit = &(hits[itcheck->second]);
1936           cPEnergyOnLayer[hitLayerId] += it_haf.second * hit->energy();
1937         }
1938       }
1939     }
1940 
1941     for (unsigned int layerId = 0; layerId < layers * 2; ++layerId) {
1942       if (!cPEnergyOnLayer[layerId])
1943         continue;
1944 
1945       histograms.h_denom_caloparticle_eta_perlayer.at(layerId)->Fill(cP[cpId].g4Tracks()[0].momentum().eta());
1946       histograms.h_denom_caloparticle_phi_perlayer.at(layerId)->Fill(cP[cpId].g4Tracks()[0].momentum().phi());
1947 
1948       if (lcsIt == cPOnLayerMap.end())
1949         continue;
1950       const auto& lcs = lcsIt->val;
1951 
1952       auto getLCLayerId = [&](const unsigned int lcId) {
1953         const auto firstHitDetId = (clusters[lcId].hitsAndFractions())[0].first;
1954         const auto lcLayerId = recHitTools_->getLayerWithOffset(firstHitDetId) +
1955                                layers * ((recHitTools_->zside(firstHitDetId) + 1) >> 1) - 1;
1956         return lcLayerId;
1957       };
1958 
1959       for (const auto& lcPair : lcs) {
1960         if (getLCLayerId(lcPair.first.index()) != layerId)
1961           continue;
1962         histograms.h_score_caloparticle2layercl_perlayer.at(layerId)->Fill(lcPair.second.second);
1963         histograms.h_sharedenergy_caloparticle2layercl_perlayer.at(layerId)->Fill(
1964             lcPair.second.first / cPEnergyOnLayer[layerId], cPEnergyOnLayer[layerId]);
1965         histograms.h_energy_vs_score_caloparticle2layercl_perlayer.at(layerId)->Fill(
1966             lcPair.second.second, lcPair.second.first / cPEnergyOnLayer[layerId]);
1967       }
1968       const auto assoc = std::count_if(std::begin(lcs), std::end(lcs), [&](const auto& obj) {
1969         if (getLCLayerId(obj.first.index()) != layerId)
1970           return false;
1971         else
1972           return obj.second.second < ScoreCutCPtoLC_;
1973       });
1974       if (assoc) {
1975         histograms.h_num_caloparticle_eta_perlayer.at(layerId)->Fill(cP[cpId].g4Tracks()[0].momentum().eta());
1976         histograms.h_num_caloparticle_phi_perlayer.at(layerId)->Fill(cP[cpId].g4Tracks()[0].momentum().phi());
1977         if (assoc > 1) {
1978           histograms.h_numDup_caloparticle_eta_perlayer.at(layerId)->Fill(cP[cpId].g4Tracks()[0].momentum().eta());
1979           histograms.h_numDup_caloparticle_phi_perlayer.at(layerId)->Fill(cP[cpId].g4Tracks()[0].momentum().phi());
1980         }
1981         const auto best = std::min_element(std::begin(lcs), std::end(lcs), [&](const auto& obj1, const auto& obj2) {
1982           if (getLCLayerId(obj1.first.index()) != layerId)
1983             return false;
1984           else if (getLCLayerId(obj2.first.index()) == layerId)
1985             return obj1.second.second < obj2.second.second;
1986           else
1987             return true;
1988         });
1989         histograms.h_sharedenergy_caloparticle2layercl_vs_eta_perlayer.at(layerId)->Fill(
1990             cP[cpId].g4Tracks()[0].momentum().eta(), best->second.first / cPEnergyOnLayer[layerId]);
1991         histograms.h_sharedenergy_caloparticle2layercl_vs_phi_perlayer.at(layerId)->Fill(
1992             cP[cpId].g4Tracks()[0].momentum().phi(), best->second.first / cPEnergyOnLayer[layerId]);
1993       }
1994     }
1995   }
1996 }
1997 
1998 void HGVHistoProducerAlgo::layerClusters_to_SimClusters(
1999     const Histograms& histograms,
2000     const int count,
2001     edm::Handle<reco::CaloClusterCollection> clusterHandle,
2002     const reco::CaloClusterCollection& clusters,
2003     edm::Handle<std::vector<SimCluster>> simClusterHandle,
2004     std::vector<SimCluster> const& sC,
2005     std::vector<size_t> const& sCIndices,
2006     const std::vector<float>& mask,
2007     std::unordered_map<DetId, const unsigned int> const& hitMap,
2008     unsigned int layers,
2009     const ticl::RecoToSimCollectionWithSimClusters& scsInLayerClusterMap,
2010     const ticl::SimToRecoCollectionWithSimClusters& lcsInSimClusterMap,
2011     std::vector<HGCRecHit> const& hits) const {
2012   // Here fill the plots to compute the different metrics linked to
2013   // reco-level, namely fake-rate and merge-rate. In this loop should *not*
2014   // restrict only to the selected SimClusters.
2015   for (unsigned int lcId = 0; lcId < clusters.size(); ++lcId) {
2016     if (mask[lcId] != 0.) {
2017       LogDebug("HGCalValidator") << "Skipping layer cluster " << lcId << " not belonging to mask" << std::endl;
2018       continue;
2019     }
2020     const auto firstHitDetId = (clusters[lcId].hitsAndFractions())[0].first;
2021     const auto lcLayerId =
2022         recHitTools_->getLayerWithOffset(firstHitDetId) + layers * ((recHitTools_->zside(firstHitDetId) + 1) >> 1) - 1;
2023     //Although the ones below are already created in the LC to CP association, will
2024     //recreate them here since in the post processor it looks in a specific directory.
2025     histograms.h_denom_layercl_in_simcl_eta_perlayer[count].at(lcLayerId)->Fill(clusters[lcId].eta());
2026     histograms.h_denom_layercl_in_simcl_phi_perlayer[count].at(lcLayerId)->Fill(clusters[lcId].phi());
2027     //
2028     const edm::Ref<reco::CaloClusterCollection> lcRef(clusterHandle, lcId);
2029     const auto& scsIt = scsInLayerClusterMap.find(lcRef);
2030     if (scsIt == scsInLayerClusterMap.end())
2031       continue;
2032 
2033     const auto lc_en = clusters[lcId].energy();
2034     const auto& scs = scsIt->val;
2035     // If a reconstructed LayerCluster has energy 0 but is linked to at least a
2036     // SimCluster, then his score should be 1 as set in the associator
2037     if (lc_en == 0. && !scs.empty()) {
2038       for (const auto& scPair : scs) {
2039         histograms.h_score_layercl2simcluster_perlayer[count].at(lcLayerId)->Fill(scPair.second);
2040       }
2041       continue;
2042     }
2043     //Loop through all SimClusters linked to the layer cluster under study
2044     for (const auto& scPair : scs) {
2045       LogDebug("HGCalValidator") << "layerCluster Id: \t" << lcId << "\t SC id: \t" << scPair.first.index()
2046                                  << "\t score \t" << scPair.second << std::endl;
2047       //This should be filled #layerClusters in layer x #linked SimClusters
2048       histograms.h_score_layercl2simcluster_perlayer[count].at(lcLayerId)->Fill(scPair.second);
2049       auto const& sc_linked =
2050           std::find_if(std::begin(lcsInSimClusterMap[scPair.first]),
2051                        std::end(lcsInSimClusterMap[scPair.first]),
2052                        [&lcRef](const std::pair<edm::Ref<reco::CaloClusterCollection>, std::pair<float, float>>& p) {
2053                          return p.first == lcRef;
2054                        });
2055       if (sc_linked ==
2056           lcsInSimClusterMap[scPair.first].end())  // This should never happen by construction of the association maps
2057         continue;
2058       histograms.h_sharedenergy_layercl2simcluster_perlayer[count].at(lcLayerId)->Fill(sc_linked->second.first / lc_en,
2059                                                                                        lc_en);
2060       histograms.h_energy_vs_score_layercl2simcluster_perlayer[count].at(lcLayerId)->Fill(
2061           scPair.second, sc_linked->second.first / lc_en);
2062     }
2063     //Here he counts how many of the linked SimClusters of the layer cluster under study have a score above a certain value.
2064     const auto assoc =
2065         std::count_if(std::begin(scs), std::end(scs), [](const auto& obj) { return obj.second < ScoreCutLCtoSC_; });
2066     if (assoc) {
2067       histograms.h_num_layercl_in_simcl_eta_perlayer[count].at(lcLayerId)->Fill(clusters[lcId].eta());
2068       histograms.h_num_layercl_in_simcl_phi_perlayer[count].at(lcLayerId)->Fill(clusters[lcId].phi());
2069       if (assoc > 1) {
2070         histograms.h_numMerge_layercl_in_simcl_eta_perlayer[count].at(lcLayerId)->Fill(clusters[lcId].eta());
2071         histograms.h_numMerge_layercl_in_simcl_phi_perlayer[count].at(lcLayerId)->Fill(clusters[lcId].phi());
2072       }
2073       const auto& best = std::min_element(
2074           std::begin(scs), std::end(scs), [](const auto& obj1, const auto& obj2) { return obj1.second < obj2.second; });
2075       //From all SimClusters he founds the one with the best (lowest) score and takes his scId
2076       const auto& best_sc_linked =
2077           std::find_if(std::begin(lcsInSimClusterMap[best->first]),
2078                        std::end(lcsInSimClusterMap[best->first]),
2079                        [&lcRef](const std::pair<edm::Ref<reco::CaloClusterCollection>, std::pair<float, float>>& p) {
2080                          return p.first == lcRef;
2081                        });
2082       if (best_sc_linked ==
2083           lcsInSimClusterMap[best->first].end())  // This should never happen by construction of the association maps
2084         continue;
2085       histograms.h_sharedenergy_layercl2simcluster_vs_eta_perlayer[count].at(lcLayerId)->Fill(
2086           clusters[lcId].eta(), best_sc_linked->second.first / lc_en);
2087       histograms.h_sharedenergy_layercl2simcluster_vs_phi_perlayer[count].at(lcLayerId)->Fill(
2088           clusters[lcId].phi(), best_sc_linked->second.first / lc_en);
2089     }
2090   }  // End of loop over LayerClusters
2091 
2092   // Fill the plots to compute the different metrics linked to
2093   // gen-level, namely efficiency and duplicate. In this loop should restrict
2094   // only to the selected SimClusters.
2095   for (const auto& scId : sCIndices) {
2096     const edm::Ref<SimClusterCollection> scRef(simClusterHandle, scId);
2097     const auto& lcsIt = lcsInSimClusterMap.find(scRef);
2098 
2099     std::map<unsigned int, float> sCEnergyOnLayer;
2100     for (unsigned int layerId = 0; layerId < layers * 2; ++layerId)
2101       sCEnergyOnLayer[layerId] = 0;
2102 
2103     for (const auto& it_haf : sC[scId].hits_and_fractions()) {
2104       const DetId hitid = (it_haf.first);
2105       const auto scLayerId =
2106           recHitTools_->getLayerWithOffset(hitid) + layers * ((recHitTools_->zside(hitid) + 1) >> 1) - 1;
2107       std::unordered_map<DetId, const unsigned int>::const_iterator itcheck = hitMap.find(hitid);
2108       if (itcheck != hitMap.end()) {
2109         const HGCRecHit* hit = &(hits[itcheck->second]);
2110         sCEnergyOnLayer[scLayerId] += it_haf.second * hit->energy();
2111       }
2112     }
2113 
2114     for (unsigned int layerId = 0; layerId < layers * 2; ++layerId) {
2115       if (!sCEnergyOnLayer[layerId])
2116         continue;
2117 
2118       histograms.h_denom_simcluster_eta_perlayer[count].at(layerId)->Fill(sC[scId].eta());
2119       histograms.h_denom_simcluster_phi_perlayer[count].at(layerId)->Fill(sC[scId].phi());
2120 
2121       if (lcsIt == lcsInSimClusterMap.end())
2122         continue;
2123       const auto& lcs = lcsIt->val;
2124 
2125       auto getLCLayerId = [&](const unsigned int lcId) {
2126         const auto firstHitDetId = (clusters[lcId].hitsAndFractions())[0].first;
2127         const unsigned int lcLayerId = recHitTools_->getLayerWithOffset(firstHitDetId) +
2128                                        layers * ((recHitTools_->zside(firstHitDetId) + 1) >> 1) - 1;
2129         return lcLayerId;
2130       };
2131 
2132       //Loop through layer clusters linked to the SimCluster under study
2133       for (const auto& lcPair : lcs) {
2134         auto lcId = lcPair.first.index();
2135         if (mask[lcId] != 0.) {
2136           LogDebug("HGCalValidator") << "Skipping layer cluster " << lcId << " not belonging to mask" << std::endl;
2137           continue;
2138         }
2139 
2140         if (getLCLayerId(lcId) != layerId)
2141           continue;
2142         histograms.h_score_simcluster2layercl_perlayer[count].at(layerId)->Fill(lcPair.second.second);
2143         histograms.h_sharedenergy_simcluster2layercl_perlayer[count].at(layerId)->Fill(
2144             lcPair.second.first / sCEnergyOnLayer[layerId], sCEnergyOnLayer[layerId]);
2145         histograms.h_energy_vs_score_simcluster2layercl_perlayer[count].at(layerId)->Fill(
2146             lcPair.second.second, lcPair.second.first / sCEnergyOnLayer[layerId]);
2147       }
2148       const auto assoc = std::count_if(std::begin(lcs), std::end(lcs), [&](const auto& obj) {
2149         if (getLCLayerId(obj.first.index()) != layerId)
2150           return false;
2151         else
2152           return obj.second.second < ScoreCutSCtoLC_;
2153       });
2154       if (assoc) {
2155         histograms.h_num_simcluster_eta_perlayer[count].at(layerId)->Fill(sC[scId].eta());
2156         histograms.h_num_simcluster_phi_perlayer[count].at(layerId)->Fill(sC[scId].phi());
2157         if (assoc > 1) {
2158           histograms.h_numDup_simcluster_eta_perlayer[count].at(layerId)->Fill(sC[scId].eta());
2159           histograms.h_numDup_simcluster_phi_perlayer[count].at(layerId)->Fill(sC[scId].phi());
2160         }
2161         const auto best = std::min_element(std::begin(lcs), std::end(lcs), [&](const auto& obj1, const auto& obj2) {
2162           if (getLCLayerId(obj1.first.index()) != layerId)
2163             return false;
2164           else if (getLCLayerId(obj2.first.index()) == layerId)
2165             return obj1.second.second < obj2.second.second;
2166           else
2167             return true;
2168         });
2169         histograms.h_sharedenergy_simcluster2layercl_vs_eta_perlayer[count].at(layerId)->Fill(
2170             sC[scId].eta(), best->second.first / sCEnergyOnLayer[layerId]);
2171         histograms.h_sharedenergy_simcluster2layercl_vs_phi_perlayer[count].at(layerId)->Fill(
2172             sC[scId].phi(), best->second.first / sCEnergyOnLayer[layerId]);
2173       }
2174     }
2175   }
2176 }
2177 
2178 void HGVHistoProducerAlgo::fill_generic_cluster_histos(const Histograms& histograms,
2179                                                        const int count,
2180                                                        edm::Handle<reco::CaloClusterCollection> clusterHandle,
2181                                                        const reco::CaloClusterCollection& clusters,
2182                                                        edm::Handle<std::vector<CaloParticle>> caloParticleHandle,
2183                                                        std::vector<CaloParticle> const& cP,
2184                                                        std::vector<size_t> const& cPIndices,
2185                                                        std::vector<size_t> const& cPSelectedIndices,
2186                                                        std::unordered_map<DetId, const unsigned int> const& hitMap,
2187                                                        std::map<double, double> cummatbudg,
2188                                                        unsigned int layers,
2189                                                        std::vector<int> thicknesses,
2190                                                        const ticl::RecoToSimCollection& cpsInLayerClusterMap,
2191                                                        const ticl::SimToRecoCollection& cPOnLayerMap,
2192                                                        std::vector<HGCRecHit> const& hits) const {
2193   //Each event to be treated as two events: an event in +ve endcap,
2194   //plus another event in -ve endcap. In this spirit there will be
2195   //a layer variable (layerid) that maps the layers in :
2196   //-z: 0->51
2197   //+z: 52->103
2198 
2199   //To keep track of total num of layer clusters per layer
2200   //tnlcpl[layerid]
2201   std::vector<int> tnlcpl(1000, 0);  //tnlcpl.clear(); tnlcpl.reserve(1000);
2202 
2203   //To keep track of the total num of clusters per thickness in plus and in minus endcaps
2204   std::map<std::string, int> tnlcpthplus;
2205   tnlcpthplus.clear();
2206   std::map<std::string, int> tnlcpthminus;
2207   tnlcpthminus.clear();
2208   //At the beginning of the event all layers should be initialized to zero total clusters per thickness
2209   for (std::vector<int>::iterator it = thicknesses.begin(); it != thicknesses.end(); ++it) {
2210     tnlcpthplus.insert(std::pair<std::string, int>(std::to_string(*it), 0));
2211     tnlcpthminus.insert(std::pair<std::string, int>(std::to_string(*it), 0));
2212   }
2213   //To keep track of the total num of clusters with mixed thickness hits per event
2214   tnlcpthplus.insert(std::pair<std::string, int>("mixed", 0));
2215   tnlcpthminus.insert(std::pair<std::string, int>("mixed", 0));
2216 
2217   layerClusters_to_CaloParticles(histograms,
2218                                  clusterHandle,
2219                                  clusters,
2220                                  caloParticleHandle,
2221                                  cP,
2222                                  cPIndices,
2223                                  cPSelectedIndices,
2224                                  hitMap,
2225                                  layers,
2226                                  cpsInLayerClusterMap,
2227                                  cPOnLayerMap,
2228                                  hits);
2229 
2230   //To find out the total amount of energy clustered per layer
2231   //Initialize with zeros because I see clear gives weird numbers.
2232   std::vector<double> tecpl(1000, 0.0);  //tecpl.clear(); tecpl.reserve(1000);
2233   //for the longitudinal depth barycenter
2234   std::vector<double> ldbar(1000, 0.0);  //ldbar.clear(); ldbar.reserve(1000);
2235 
2236   // Need to compare with the total amount of energy coming from CaloParticles
2237   double caloparteneplus = 0.;
2238   double caloparteneminus = 0.;
2239   for (const auto& cpId : cPIndices) {
2240     if (cP[cpId].eta() >= 0.) {
2241       caloparteneplus = caloparteneplus + cP[cpId].energy();
2242     } else if (cP[cpId].eta() < 0.) {
2243       caloparteneminus = caloparteneminus + cP[cpId].energy();
2244     }
2245   }
2246 
2247   // loop through clusters of the event
2248   for (const auto& lcId : clusters) {
2249     const auto seedid = lcId.seed();
2250     const double seedx = recHitTools_->getPosition(seedid).x();
2251     const double seedy = recHitTools_->getPosition(seedid).y();
2252     DetId maxid = findmaxhit(lcId, hitMap, hits);
2253 
2254     // const DetId maxid = lcId.max();
2255     double maxx = recHitTools_->getPosition(maxid).x();
2256     double maxy = recHitTools_->getPosition(maxid).y();
2257 
2258     //Auxillary variables to count the number of different kind of hits in each cluster
2259     int nthhits120p = 0;
2260     int nthhits200p = 0;
2261     int nthhits300p = 0;
2262     int nthhitsscintp = 0;
2263     int nthhits120m = 0;
2264     int nthhits200m = 0;
2265     int nthhits300m = 0;
2266     int nthhitsscintm = 0;
2267     //For the hits thickness of the layer cluster.
2268     double thickness = 0.;
2269     //The layer the cluster belongs to. As mentioned in the mapping above, it takes into account -z and +z.
2270     int layerid = 0;
2271     // Need another layer variable for the longitudinal material budget file reading.
2272     //In this case need no distinction between -z and +z.
2273     int lay = 0;
2274     // Need to save the combination thick_lay
2275     std::string istr = "";
2276     //boolean to check for the layer that the cluster belong to. Maybe later will check all the layer hits.
2277     bool cluslay = true;
2278     //zside that the current cluster belongs to.
2279     int zside = 0;
2280 
2281     const auto& hits_and_fractions = lcId.hitsAndFractions();
2282     for (std::vector<std::pair<DetId, float>>::const_iterator it_haf = hits_and_fractions.begin();
2283          it_haf != hits_and_fractions.end();
2284          ++it_haf) {
2285       const DetId rh_detid = it_haf->first;
2286       //The layer that the current hit belongs to
2287       layerid = recHitTools_->getLayerWithOffset(rh_detid) + layers * ((recHitTools_->zside(rh_detid) + 1) >> 1) - 1;
2288       lay = recHitTools_->getLayerWithOffset(rh_detid);
2289       zside = recHitTools_->zside(rh_detid);
2290       if (rh_detid.det() == DetId::Forward || rh_detid.det() == DetId::HGCalEE || rh_detid.det() == DetId::HGCalHSi) {
2291         thickness = recHitTools_->getSiThickness(rh_detid);
2292       } else if (rh_detid.det() == DetId::HGCalHSc) {
2293         thickness = -1;
2294       } else {
2295         LogDebug("HGCalValidator") << "These are HGCal layer clusters, you shouldn't be here !!! " << layerid << "\n";
2296         continue;
2297       }
2298 
2299       //Count here only once the layer cluster and save the combination thick_layerid
2300       std::string curistr = std::to_string((int)thickness);
2301       std::string lay_string = std::to_string(layerid);
2302       while (lay_string.size() < 2)
2303         lay_string.insert(0, "0");
2304       curistr += "_" + lay_string;
2305       if (cluslay) {
2306         tnlcpl[layerid]++;
2307         istr = curistr;
2308         cluslay = false;
2309       }
2310 
2311       if ((thickness == 120.) && (recHitTools_->zside(rh_detid) > 0.)) {
2312         nthhits120p++;
2313       } else if ((thickness == 120.) && (recHitTools_->zside(rh_detid) < 0.)) {
2314         nthhits120m++;
2315       } else if ((thickness == 200.) && (recHitTools_->zside(rh_detid) > 0.)) {
2316         nthhits200p++;
2317       } else if ((thickness == 200.) && (recHitTools_->zside(rh_detid) < 0.)) {
2318         nthhits200m++;
2319       } else if ((thickness == 300.) && (recHitTools_->zside(rh_detid) > 0.)) {
2320         nthhits300p++;
2321       } else if ((thickness == 300.) && (recHitTools_->zside(rh_detid) < 0.)) {
2322         nthhits300m++;
2323       } else if ((thickness == -1) && (recHitTools_->zside(rh_detid) > 0.)) {
2324         nthhitsscintp++;
2325       } else if ((thickness == -1) && (recHitTools_->zside(rh_detid) < 0.)) {
2326         nthhitsscintm++;
2327       } else {  //assert(0);
2328         LogDebug("HGCalValidator")
2329             << " You are running a geometry that contains thicknesses different than the normal ones. "
2330             << "\n";
2331       }
2332 
2333       std::unordered_map<DetId, const unsigned int>::const_iterator itcheck = hitMap.find(rh_detid);
2334       if (itcheck == hitMap.end()) {
2335         std::ostringstream st1;
2336         if ((rh_detid.det() == DetId::HGCalEE) || (rh_detid.det() == DetId::HGCalHSi)) {
2337           st1 << HGCSiliconDetId(rh_detid);
2338         } else if (rh_detid.det() == DetId::HGCalHSc) {
2339           st1 << HGCScintillatorDetId(rh_detid);
2340         } else {
2341           st1 << HFNoseDetId(rh_detid);
2342         }
2343         LogDebug("HGCalValidator") << " You shouldn't be here - Unable to find a hit " << rh_detid.rawId() << " "
2344                                    << rh_detid.det() << " " << st1.str() << "\n";
2345         continue;
2346       }
2347 
2348       const HGCRecHit* hit = &(hits[itcheck->second]);
2349       //Here for the per cell plots
2350       //----
2351       const double hit_x = recHitTools_->getPosition(rh_detid).x();
2352       const double hit_y = recHitTools_->getPosition(rh_detid).y();
2353       double distancetoseed = distance(seedx, seedy, hit_x, hit_y);
2354       double distancetomax = distance(maxx, maxy, hit_x, hit_y);
2355       if (distancetoseed != 0. && histograms.h_distancetoseedcell_perthickperlayer.count(curistr)) {
2356         histograms.h_distancetoseedcell_perthickperlayer.at(curistr)->Fill(distancetoseed);
2357       }
2358       //----
2359       if (distancetoseed != 0. && histograms.h_distancetoseedcell_perthickperlayer_eneweighted.count(curistr)) {
2360         histograms.h_distancetoseedcell_perthickperlayer_eneweighted.at(curistr)->Fill(distancetoseed, hit->energy());
2361       }
2362       //----
2363       if (distancetomax != 0. && histograms.h_distancetomaxcell_perthickperlayer.count(curistr)) {
2364         histograms.h_distancetomaxcell_perthickperlayer.at(curistr)->Fill(distancetomax);
2365       }
2366       //----
2367       if (distancetomax != 0. && histograms.h_distancetomaxcell_perthickperlayer_eneweighted.count(curistr)) {
2368         histograms.h_distancetomaxcell_perthickperlayer_eneweighted.at(curistr)->Fill(distancetomax, hit->energy());
2369       }
2370 
2371     }  // end of loop through hits and fractions
2372 
2373     //Check for simultaneously having hits of different kind. Checking at least two combinations is sufficient.
2374     if ((nthhits120p != 0 && nthhits200p != 0) || (nthhits120p != 0 && nthhits300p != 0) ||
2375         (nthhits120p != 0 && nthhitsscintp != 0) || (nthhits200p != 0 && nthhits300p != 0) ||
2376         (nthhits200p != 0 && nthhitsscintp != 0) || (nthhits300p != 0 && nthhitsscintp != 0)) {
2377       tnlcpthplus["mixed"]++;
2378     } else if ((nthhits120p != 0 || nthhits200p != 0 || nthhits300p != 0 || nthhitsscintp != 0)) {
2379       //This is a cluster with hits of one kind
2380       tnlcpthplus[std::to_string((int)thickness)]++;
2381     }
2382     if ((nthhits120m != 0 && nthhits200m != 0) || (nthhits120m != 0 && nthhits300m != 0) ||
2383         (nthhits120m != 0 && nthhitsscintm != 0) || (nthhits200m != 0 && nthhits300m != 0) ||
2384         (nthhits200m != 0 && nthhitsscintm != 0) || (nthhits300m != 0 && nthhitsscintm != 0)) {
2385       tnlcpthminus["mixed"]++;
2386     } else if ((nthhits120m != 0 || nthhits200m != 0 || nthhits300m != 0 || nthhitsscintm != 0)) {
2387       //This is a cluster with hits of one kind
2388       tnlcpthminus[std::to_string((int)thickness)]++;
2389     }
2390 
2391     //To find the thickness with the biggest amount of cells
2392     std::vector<int> bigamoth;
2393     bigamoth.clear();
2394     if (zside > 0) {
2395       bigamoth.push_back(nthhits120p);
2396       bigamoth.push_back(nthhits200p);
2397       bigamoth.push_back(nthhits300p);
2398       bigamoth.push_back(nthhitsscintp);
2399     } else if (zside < 0) {
2400       bigamoth.push_back(nthhits120m);
2401       bigamoth.push_back(nthhits200m);
2402       bigamoth.push_back(nthhits300m);
2403       bigamoth.push_back(nthhitsscintm);
2404     }
2405     auto bgth = std::max_element(bigamoth.begin(), bigamoth.end());
2406     istr = std::to_string(thicknesses[std::distance(bigamoth.begin(), bgth)]);
2407     std::string lay_string = std::to_string(layerid);
2408     while (lay_string.size() < 2)
2409       lay_string.insert(0, "0");
2410     istr += "_" + lay_string;
2411 
2412     //Here for the per cluster plots that need the thickness_layer info
2413     if (histograms.h_cellsnum_perthickperlayer.count(istr)) {
2414       histograms.h_cellsnum_perthickperlayer.at(istr)->Fill(hits_and_fractions.size());
2415     }
2416 
2417     //Now, with the distance between seed and max cell.
2418     double distancebetseedandmax = distance(seedx, seedy, maxx, maxy);
2419     //The thickness_layer combination in this case will use the thickness of the seed as a convention.
2420     std::string seedstr = std::to_string((int)recHitTools_->getSiThickness(seedid)) + "_" + std::to_string(layerid);
2421     seedstr += "_" + lay_string;
2422     if (histograms.h_distancebetseedandmaxcell_perthickperlayer.count(seedstr)) {
2423       histograms.h_distancebetseedandmaxcell_perthickperlayer.at(seedstr)->Fill(distancebetseedandmax);
2424     }
2425     const auto lc_en = lcId.energy();
2426     if (histograms.h_distancebetseedandmaxcellvsclusterenergy_perthickperlayer.count(seedstr)) {
2427       histograms.h_distancebetseedandmaxcellvsclusterenergy_perthickperlayer.at(seedstr)->Fill(distancebetseedandmax,
2428                                                                                                lc_en);
2429     }
2430 
2431     //Energy clustered per layer
2432     tecpl[layerid] = tecpl[layerid] + lc_en;
2433     ldbar[layerid] = ldbar[layerid] + lc_en * cummatbudg[(double)lay];
2434 
2435   }  //end of loop through clusters of the event
2436 
2437   // First a couple of variables to keep the sum of the energy of all clusters
2438   double sumeneallcluspl = 0.;
2439   double sumeneallclusmi = 0.;
2440   // and the longitudinal variable
2441   double sumldbarpl = 0.;
2442   double sumldbarmi = 0.;
2443   //Per layer : Loop 0->103
2444   for (unsigned ilayer = 0; ilayer < layers * 2; ++ilayer) {
2445     if (histograms.h_clusternum_perlayer.count(ilayer)) {
2446       histograms.h_clusternum_perlayer.at(ilayer)->Fill(tnlcpl[ilayer]);
2447     }
2448     // Two times one for plus and one for minus
2449     //First with the -z endcap
2450     if (ilayer < layers) {
2451       if (histograms.h_energyclustered_perlayer.count(ilayer)) {
2452         if (caloparteneminus != 0.) {
2453           histograms.h_energyclustered_perlayer.at(ilayer)->Fill(100. * tecpl[ilayer] / caloparteneminus);
2454         }
2455       }
2456       //Keep here the total energy for the event in -z
2457       sumeneallclusmi = sumeneallclusmi + tecpl[ilayer];
2458       //And for the longitudinal variable
2459       sumldbarmi = sumldbarmi + ldbar[ilayer];
2460     } else {  //Then for the +z
2461       if (histograms.h_energyclustered_perlayer.count(ilayer)) {
2462         if (caloparteneplus != 0.) {
2463           histograms.h_energyclustered_perlayer.at(ilayer)->Fill(100. * tecpl[ilayer] / caloparteneplus);
2464         }
2465       }
2466       //Keep here the total energy for the event in -z
2467       sumeneallcluspl = sumeneallcluspl + tecpl[ilayer];
2468       //And for the longitudinal variable
2469       sumldbarpl = sumldbarpl + ldbar[ilayer];
2470     }  //end of +z loop
2471 
2472   }  //end of loop over layers
2473 
2474   //Per thickness
2475   for (std::vector<int>::iterator it = thicknesses.begin(); it != thicknesses.end(); ++it) {
2476     if (histograms.h_clusternum_perthick.count(*it)) {
2477       histograms.h_clusternum_perthick.at(*it)->Fill(tnlcpthplus[std::to_string(*it)]);
2478       histograms.h_clusternum_perthick.at(*it)->Fill(tnlcpthminus[std::to_string(*it)]);
2479     }
2480   }
2481   //Mixed thickness clusters
2482   histograms.h_mixedhitscluster_zplus[count]->Fill(tnlcpthplus["mixed"]);
2483   histograms.h_mixedhitscluster_zminus[count]->Fill(tnlcpthminus["mixed"]);
2484 
2485   //Total energy clustered from all layer clusters (fraction)
2486   if (caloparteneplus != 0.) {
2487     histograms.h_energyclustered_zplus[count]->Fill(100. * sumeneallcluspl / caloparteneplus);
2488   }
2489   if (caloparteneminus != 0.) {
2490     histograms.h_energyclustered_zminus[count]->Fill(100. * sumeneallclusmi / caloparteneminus);
2491   }
2492 
2493   //For the longitudinal depth barycenter
2494   histograms.h_longdepthbarycentre_zplus[count]->Fill(sumldbarpl / sumeneallcluspl);
2495   histograms.h_longdepthbarycentre_zminus[count]->Fill(sumldbarmi / sumeneallclusmi);
2496 }
2497 
2498 void HGVHistoProducerAlgo::tracksters_to_SimTracksters(
2499     const Histograms& histograms,
2500     const int count,
2501     const ticl::TracksterCollection& tracksters,
2502     const reco::CaloClusterCollection& layerClusters,
2503     const ticl::TracksterCollection& simTSs,
2504     const validationType valType,
2505     const ticl::TracksterCollection& simTSs_fromCP,
2506     const std::map<unsigned int, std::vector<unsigned int>>& cpToSc_SimTrackstersMap,
2507     std::vector<SimCluster> const& sC,
2508     const edm::ProductID& cPHandle_id,
2509     std::vector<CaloParticle> const& cP,
2510     std::vector<size_t> const& cPIndices,
2511     std::vector<size_t> const& cPSelectedIndices,
2512     std::unordered_map<DetId, const unsigned int> const& hitMap,
2513     unsigned int layers,
2514     std::vector<HGCRecHit> const& hits) const {
2515   const auto nTracksters = tracksters.size();
2516   const auto nSimTracksters = simTSs.size();
2517 
2518   std::unordered_map<DetId, std::vector<HGVHistoProducerAlgo::detIdInfoInCluster>> detIdSimTSId_Map;
2519   std::unordered_map<DetId, std::vector<HGVHistoProducerAlgo::detIdInfoInTrackster>> detIdToTracksterId_Map;
2520   std::vector<int> tracksters_FakeMerge(nTracksters, 0);
2521   std::vector<int> tracksters_PurityDuplicate(nSimTracksters, 0);
2522 
2523   // This vector contains the ids of the SimTracksters contributing with at least one hit to the Trackster and the reconstruction error
2524   //stsInTrackster[trackster][STSids]
2525   //Connects a Trackster with all related SimTracksters.
2526   std::vector<std::vector<std::pair<unsigned int, float>>> stsInTrackster;
2527   stsInTrackster.resize(nTracksters);
2528 
2529   // cPOnLayer[caloparticle]:
2530   //1. the sum of all rechits energy times fraction of the relevant simhit related to that calo particle.
2531   //2. the hits and fractions of that calo particle.
2532   //3. the layer clusters with matched rechit id.
2533   std::unordered_map<int, caloParticleOnLayer> cPOnLayer;
2534   std::unordered_map<int, std::vector<caloParticleOnLayer>> sCOnLayer;
2535   //Consider CaloParticles coming from the hard scatterer, excluding the PU contribution.
2536   for (const auto cpIndex : cPIndices) {
2537     cPOnLayer[cpIndex].caloParticleId = cpIndex;
2538     cPOnLayer[cpIndex].energy = 0.f;
2539     cPOnLayer[cpIndex].hits_and_fractions.clear();
2540     const auto nSC_inCP = sC.size();
2541     sCOnLayer[cpIndex].resize(nSC_inCP);
2542     for (unsigned int iSC = 0; iSC < nSC_inCP; iSC++) {
2543       sCOnLayer[cpIndex][iSC].caloParticleId = cpIndex;
2544       sCOnLayer[cpIndex][iSC].energy = 0.f;
2545       sCOnLayer[cpIndex][iSC].hits_and_fractions.clear();
2546     }
2547   }
2548 
2549   auto getCPId = [](const ticl::Trackster& simTS,
2550                     const unsigned int iSTS,
2551                     const edm::ProductID& cPHandle_id,
2552                     const std::map<unsigned int, std::vector<unsigned int>>& cpToSc_SimTrackstersMap,
2553                     const ticl::TracksterCollection& simTSs_fromCP) {
2554     unsigned int cpId = -1;
2555 
2556     const auto productID = simTS.seedID();
2557     if (productID == cPHandle_id) {
2558       cpId = simTS.seedIndex();
2559     } else {  // SimTrackster from SimCluster
2560       const auto findSimTSFromCP = std::find_if(
2561           std::begin(cpToSc_SimTrackstersMap),
2562           std::end(cpToSc_SimTrackstersMap),
2563           [&](const std::pair<unsigned int, std::vector<unsigned int>>& cpToScs) {
2564             return std::find(std::begin(cpToScs.second), std::end(cpToScs.second), iSTS) != std::end(cpToScs.second);
2565           });
2566       if (findSimTSFromCP != std::end(cpToSc_SimTrackstersMap)) {
2567         cpId = simTSs_fromCP[findSimTSFromCP->first].seedIndex();
2568       }
2569     }
2570 
2571     return cpId;
2572   };
2573 
2574   auto getLCId = [](const std::vector<unsigned int>& tst_vertices,
2575                     const reco::CaloClusterCollection& layerClusters,
2576                     const DetId& hitid) {
2577     unsigned int lcId = -1;
2578     std::for_each(std::begin(tst_vertices), std::end(tst_vertices), [&](unsigned int idx) {
2579       const auto& lc_haf = layerClusters[idx].hitsAndFractions();
2580       const auto& hitFound = std::find_if(std::begin(lc_haf),
2581                                           std::end(lc_haf),
2582                                           [&hitid](const std::pair<DetId, float>& v) { return v.first == hitid; });
2583       if (hitFound != lc_haf.end())  // not all hits may be clusterized
2584         lcId = idx;
2585     });
2586     return lcId;
2587   };
2588 
2589   for (unsigned int iSTS = 0; iSTS < nSimTracksters; ++iSTS) {
2590     const auto cpId = getCPId(simTSs[iSTS], iSTS, cPHandle_id, cpToSc_SimTrackstersMap, simTSs_fromCP);
2591     if (std::find(cPIndices.begin(), cPIndices.end(), cpId) == cPIndices.end())
2592       continue;
2593 
2594     // Loop through SimClusters
2595     for (const auto& simCluster : cP[cpId].simClusters()) {
2596       auto iSim = simTSs[iSTS].seedIndex();
2597       if (simTSs[iSTS].seedID() != cPHandle_id) {  // SimTrackster from SimCluster
2598         if (iSim != (&(*simCluster) - &(sC[0])))
2599           continue;
2600       } else
2601         iSim = 0;
2602 
2603       for (const auto& it_haf : simCluster->hits_and_fractions()) {
2604         const auto hitid = (it_haf.first);
2605         const auto lcId = getLCId(simTSs[iSTS].vertices(), layerClusters, hitid);
2606         //V9:maps the layers in -z: 0->51 and in +z: 52->103
2607         //V10:maps the layers in -z: 0->49 and in +z: 50->99
2608         const auto itcheck = hitMap.find(hitid);
2609         //Check whether the current hit belonging to sim cluster has a reconstructed hit
2610         if ((valType == 0 && itcheck != hitMap.end()) || (valType > 0 && int(lcId) >= 0)) {
2611           float lcFraction = 0;
2612           if (valType > 0) {
2613             const auto iLC = std::find(simTSs[iSTS].vertices().begin(), simTSs[iSTS].vertices().end(), lcId);
2614             lcFraction =
2615                 1.f / simTSs[iSTS].vertex_multiplicity(std::distance(std::begin(simTSs[iSTS].vertices()), iLC));
2616           }
2617           const auto elemId = (valType == 0) ? hitid : lcId;
2618           const auto elemFr = (valType == 0) ? it_haf.second : lcFraction;
2619           //Since the current hit from SimCluster has a reconstructed hit {with the same detid, belonging to the corresponding SimTrackster},
2620           //make a map that will connect a {detid,lcID} with:
2621           //1. the SimTracksters that have a SimCluster with {sim hits in, LCs containing} that cell via SimTrackster id.
2622           //2. the sum of all {SimHits, LCs} fractions that contributes to that detid.
2623           //So, keep in mind that in case of multiple CaloParticles contributing in the same cell
2624           //the fraction is the sum over all calo particles. So, something like:
2625           //detid: (caloparticle 1, sum of hits fractions in that detid over all cp) , (caloparticle 2, sum of hits fractions in that detid over all cp), (caloparticle 3, sum of hits fractions in that detid over all cp) ...
2626           if (detIdSimTSId_Map.find(elemId) == detIdSimTSId_Map.end()) {
2627             detIdSimTSId_Map[elemId] = std::vector<HGVHistoProducerAlgo::detIdInfoInCluster>();
2628             detIdSimTSId_Map[elemId].emplace_back(HGVHistoProducerAlgo::detIdInfoInCluster{iSTS, elemFr});
2629           } else {
2630             auto findSTSIt =
2631                 std::find(detIdSimTSId_Map[elemId].begin(),
2632                           detIdSimTSId_Map[elemId].end(),
2633                           HGVHistoProducerAlgo::detIdInfoInCluster{
2634                               iSTS, 0});  // only the first element is used for the matching (overloaded operator==)
2635             if (findSTSIt != detIdSimTSId_Map[elemId].end()) {
2636               if (valType == 0)
2637                 findSTSIt->fraction += elemFr;
2638             } else {
2639               detIdSimTSId_Map[elemId].emplace_back(HGVHistoProducerAlgo::detIdInfoInCluster{iSTS, elemFr});
2640             }
2641           }
2642           const auto hitEn = (hits[itcheck->second]).energy();
2643           //Since the current hit from sim cluster has a reconstructed hit with the same detid,
2644           //fill the cPOnLayer[caloparticle][layer] object with energy (sum of all rechits energy times fraction
2645           //of the relevant simhit) and keep the hit (detid and fraction) that contributed.
2646           cPOnLayer[cpId].energy += it_haf.second * hitEn;
2647           sCOnLayer[cpId][iSim].energy += elemFr * hitEn;
2648           // Need to compress the hits and fractions in order to have a
2649           // reasonable score between CP and LC. Imagine, for example, that a
2650           // CP has detID X used by 2 SimClusters with different fractions. If
2651           // a single LC uses X with fraction 1 and is compared to the 2
2652           // contributions separately, it will be assigned a score != 0, which
2653           // is wrong.
2654           auto& haf = cPOnLayer[cpId].hits_and_fractions;
2655           auto found = std::find_if(
2656               std::begin(haf), std::end(haf), [&hitid](const std::pair<DetId, float>& v) { return v.first == hitid; });
2657           if (found != haf.end())
2658             found->second += it_haf.second;
2659           else
2660             haf.emplace_back(hitid, it_haf.second);
2661           // Same for sCOnLayer
2662           auto& haf_sc = sCOnLayer[cpId][iSim].hits_and_fractions;
2663           auto found_sc = std::find_if(std::begin(haf_sc),
2664                                        std::end(haf_sc),
2665                                        [&hitid](const std::pair<DetId, float>& v) { return v.first == hitid; });
2666           if (found_sc != haf_sc.end())
2667             found_sc->second += it_haf.second;
2668           else
2669             haf_sc.emplace_back(hitid, it_haf.second);
2670         }
2671       }  // end of loop through SimHits
2672     }    // end of loop through SimClusters
2673   }      // end of loop through SimTracksters
2674 
2675   auto apply_LCMultiplicity = [](const ticl::Trackster& trackster, const reco::CaloClusterCollection& layerClusters) {
2676     std::vector<std::pair<DetId, float>> hits_and_fractions_norm;
2677     int lcInTst = 0;
2678     std::for_each(std::begin(trackster.vertices()), std::end(trackster.vertices()), [&](unsigned int idx) {
2679       const auto fraction = 1.f / trackster.vertex_multiplicity(lcInTst++);
2680       for (const auto& cell : layerClusters[idx].hitsAndFractions()) {
2681         hits_and_fractions_norm.emplace_back(
2682             cell.first, cell.second * fraction);  // cell.second is the hit fraction in the layerCluster
2683       }
2684     });
2685     return hits_and_fractions_norm;
2686   };
2687 
2688   auto ScoreCutSTStoTSPurDup = ScoreCutSTStoTSPurDup_[0];
2689   auto ScoreCutTStoSTSFakeMerge = ScoreCutTStoSTSFakeMerge_[0];
2690   // Loop through Tracksters
2691   for (unsigned int tstId = 0; tstId < nTracksters; ++tstId) {
2692     const auto& tst = tracksters[tstId];
2693     if (tstId == 0)
2694       if ((valType > 0) && (tst.ticlIteration() == ticl::Trackster::SIM)) {
2695         ScoreCutSTStoTSPurDup = ScoreCutSTStoTSPurDup_[valType];
2696         ScoreCutTStoSTSFakeMerge = ScoreCutTStoSTSFakeMerge_[valType];
2697       }
2698 
2699     if (tst.vertices().empty())
2700       continue;
2701 
2702     std::unordered_map<unsigned, float> CPEnergyInTS;
2703     int maxCPId_byNumberOfHits = -1;
2704     unsigned int maxCPNumberOfHitsInTS = 0;
2705     int maxCPId_byEnergy = -1;
2706     float maxEnergySharedTSandCP = 0.f;
2707     float energyFractionOfTSinCP = 0.f;
2708     float energyFractionOfCPinTS = 0.f;
2709 
2710     //In case of matched rechit-simhit, so matched
2711     //CaloParticle-LayerCluster-Trackster, he counts and saves the number of
2712     //rechits related to the maximum energy CaloParticle out of all
2713     //CaloParticles related to that layer cluster and Trackster.
2714 
2715     std::unordered_map<unsigned, unsigned> occurrencesCPinTS;
2716     unsigned int numberOfNoiseHitsInTS = 0;
2717 
2718     const auto tst_hitsAndFractions = apply_LCMultiplicity(tst, layerClusters);
2719     const auto numberOfHitsInTS = tst_hitsAndFractions.size();
2720 
2721     //hitsToCaloParticleId is a vector of ints, one for each rechit of the
2722     //layer cluster under study. If negative, there is no simhit from any CaloParticle related.
2723     //If positive, at least one CaloParticle has been found with matched simhit.
2724     //In more detail:
2725     // 1. hitsToCaloParticleId[iHit] = -3
2726     //    TN:  These represent Halo Cells(N) that have not been
2727     //    assigned to any CaloParticle (hence the T).
2728     // 2. hitsToCaloParticleId[iHit] = -2
2729     //    FN: There represent Halo Cells(N) that have been assigned
2730     //    to a CaloParticle (hence the F, since those should have not been marked as halo)
2731     // 3. hitsToCaloParticleId[iHit] = -1
2732     //    FP: These represent Real Cells(P) that have not been
2733     //    assigned to any CaloParticle (hence the F, since these are fakes)
2734     // 4. hitsToCaloParticleId[iHit] >= 0
2735     //    TP There represent Real Cells(P) that have been assigned
2736     //    to a CaloParticle (hence the T)
2737     std::vector<int> hitsToCaloParticleId(numberOfHitsInTS);
2738 
2739     //Loop through the hits of the trackster under study
2740     for (unsigned int iHit = 0; iHit < numberOfHitsInTS; iHit++) {
2741       const auto rh_detid = tst_hitsAndFractions[iHit].first;
2742       const auto rhFraction = tst_hitsAndFractions[iHit].second;
2743 
2744       const auto lcId_r = getLCId(tst.vertices(), layerClusters, rh_detid);
2745       const auto iLC_r = std::find(tst.vertices().begin(), tst.vertices().end(), lcId_r);
2746       const auto lcFraction_r = 1.f / tst.vertex_multiplicity(std::distance(std::begin(tst.vertices()), iLC_r));
2747 
2748       //Make a map that will connect a detid (that belongs to a rechit of the layer cluster under study,
2749       //no need to save others) with:
2750       //1. the layer clusters that have rechits in that detid
2751       //2. the fraction of the rechit of each layer cluster that contributes to that detid.
2752       //So, something like:
2753       //detid: (layer cluster 1, hit fraction) , (layer cluster 2, hit fraction), (layer cluster 3, hit fraction) ...
2754       //here comparing with the calo particle map above the
2755       if (detIdToTracksterId_Map.find(rh_detid) == detIdToTracksterId_Map.end()) {
2756         detIdToTracksterId_Map[rh_detid] = std::vector<HGVHistoProducerAlgo::detIdInfoInTrackster>();
2757         detIdToTracksterId_Map[rh_detid].emplace_back(
2758             HGVHistoProducerAlgo::detIdInfoInTrackster{tstId, lcId_r, rhFraction});
2759       } else {
2760         auto findTSIt =
2761             std::find(detIdToTracksterId_Map[rh_detid].begin(),
2762                       detIdToTracksterId_Map[rh_detid].end(),
2763                       HGVHistoProducerAlgo::detIdInfoInTrackster{
2764                           tstId, 0, 0});  // only the first element is used for the matching (overloaded operator==)
2765         if (findTSIt != detIdToTracksterId_Map[rh_detid].end()) {
2766           if (valType == 0)
2767             findTSIt->fraction += rhFraction;
2768         } else {
2769           detIdToTracksterId_Map[rh_detid].emplace_back(
2770               HGVHistoProducerAlgo::detIdInfoInTrackster{tstId, lcId_r, rhFraction});
2771         }
2772       }
2773 
2774       // if the fraction is zero or the hit does not belong to any calo
2775       // particle, set the caloparticleId for the hit to -1 this will
2776       // contribute to the number of noise hits
2777       // MR Remove the case in which the fraction is 0, since this could be a
2778       // real hit that has been marked as halo.
2779       if (rhFraction == 0.) {
2780         hitsToCaloParticleId[iHit] = -2;
2781       }
2782 
2783       // Check whether the RecHit of the trackster under study has a SimHit in the same cell
2784       const auto elemId = (valType == 0) ? rh_detid.rawId() : lcId_r;
2785       const auto recoFr = (valType == 0) ? rhFraction : lcFraction_r;
2786       const auto& hit_find_in_STS = detIdSimTSId_Map.find(elemId);
2787       if (hit_find_in_STS == detIdSimTSId_Map.end()) {
2788         hitsToCaloParticleId[iHit] -= 1;
2789       } else {
2790         // Since the hit is belonging to the layer cluster, it must be also in the rechits map
2791         const auto hitEn = (hits[hitMap.find(rh_detid)->second]).energy();
2792         //const auto layerId =
2793         //recHitTools_->getLayerWithOffset(rh_detid) + layers * ((recHitTools_->zside(rh_detid) + 1) >> 1) - 1;
2794         //0;
2795 
2796         auto maxCPEnergyInTS = 0.f;
2797         auto maxCPId = -1;
2798         for (const auto& h : hit_find_in_STS->second) {
2799           const auto shared_fraction = std::min(recoFr, h.fraction);
2800           const auto iSTS = h.clusterId;
2801           const auto& simTS = simTSs[iSTS];
2802           auto iSim = simTS.seedIndex();
2803           if (simTSs[iSTS].seedID() == cPHandle_id)  // SimTrackster from CaloParticle
2804             iSim = 0;
2805 
2806           // SimTrackster with simHits connected via detid with the rechit under study
2807           //So, from all layers clusters, find the rechits that are connected with a calo particle and save/calculate the
2808           //energy of that calo particle as the sum over all rechits of the rechits energy weighted
2809           //by the caloparticle's fraction related to that rechit.
2810           const auto cpId = getCPId(simTS, iSTS, cPHandle_id, cpToSc_SimTrackstersMap, simTSs_fromCP);
2811           if (std::find(cPIndices.begin(), cPIndices.end(), cpId) == cPIndices.end())
2812             continue;
2813 
2814           CPEnergyInTS[cpId] += shared_fraction * hitEn;
2815           //Here cPOnLayer[caloparticle][layer] describe above is set.
2816           //Here for Tracksters with matched rechit the CP fraction times hit energy is added and saved .
2817           cPOnLayer[cpId].layerClusterIdToEnergyAndScore[tstId].first += shared_fraction * hitEn;
2818           sCOnLayer[cpId][iSim].layerClusterIdToEnergyAndScore[tstId].first += shared_fraction * hitEn;
2819           cPOnLayer[cpId].layerClusterIdToEnergyAndScore[tstId].second = FLT_MAX;
2820           sCOnLayer[cpId][iSim].layerClusterIdToEnergyAndScore[tstId].second = FLT_MAX;
2821           //stsInTrackster[trackster][STSids]
2822           //Connects a Trackster with all related SimTracksters.
2823           stsInTrackster[tstId].emplace_back(iSTS, FLT_MAX);
2824           //From all CaloParticles related to a layer cluster, it saves id and energy of the calo particle
2825           //that after simhit-rechit matching in layer has the maximum energy.
2826           if (shared_fraction > maxCPEnergyInTS) {
2827             //energy is used only here. cpid is saved for Tracksters
2828             maxCPEnergyInTS = CPEnergyInTS[cpId];
2829             maxCPId = cpId;
2830           }
2831         }
2832         //Keep in mind here maxCPId could be zero. So, below ask for negative not including zero to count noise.
2833         hitsToCaloParticleId[iHit] = maxCPId;
2834       }
2835 
2836     }  //end of loop through rechits of the layer cluster.
2837 
2838     //Loop through all rechits to count how many of them are noise and how many are matched.
2839     //In case of matched rechit-simhit, he counts and saves the number of rechits related to the maximum energy CaloParticle.
2840     for (auto c : hitsToCaloParticleId) {
2841       if (c < 0)
2842         numberOfNoiseHitsInTS++;
2843       else
2844         occurrencesCPinTS[c]++;
2845     }
2846 
2847     //Below from all maximum energy CaloParticles, he saves the one with the largest amount
2848     //of related rechits.
2849     for (auto& c : occurrencesCPinTS) {
2850       if (c.second > maxCPNumberOfHitsInTS) {
2851         maxCPId_byNumberOfHits = c.first;
2852         maxCPNumberOfHitsInTS = c.second;
2853       }
2854     }
2855 
2856     //Find the CaloParticle that has the maximum energy shared with the Trackster under study.
2857     for (auto& c : CPEnergyInTS) {
2858       if (c.second > maxEnergySharedTSandCP) {
2859         maxCPId_byEnergy = c.first;
2860         maxEnergySharedTSandCP = c.second;
2861       }
2862     }
2863     //The energy of the CaloParticle that found to have the maximum energy shared with the Trackster under study.
2864     float totalCPEnergyFromLayerCP = 0.f;
2865     if (maxCPId_byEnergy >= 0) {
2866       totalCPEnergyFromLayerCP += cPOnLayer[maxCPId_byEnergy].energy;
2867       energyFractionOfCPinTS = maxEnergySharedTSandCP / totalCPEnergyFromLayerCP;
2868       if (tst.raw_energy() > 0.f) {
2869         energyFractionOfTSinCP = maxEnergySharedTSandCP / tst.raw_energy();
2870       }
2871     }
2872 
2873     LogDebug("HGCalValidator") << std::setw(12) << "Trackster\t" << std::setw(10) << "energy\t" << std::setw(5)
2874                                << "nhits\t" << std::setw(12) << "noise hits\t" << std::setw(22)
2875                                << "maxCPId_byNumberOfHits\t" << std::setw(8) << "nhitsCP\t" << std::setw(16)
2876                                << "maxCPId_byEnergy\t" << std::setw(23) << "maxEnergySharedTSandCP\t" << std::setw(22)
2877                                << "totalCPEnergyFromAllLayerCP\t" << std::setw(22) << "energyFractionOfTSinCP\t"
2878                                << std::setw(25) << "energyFractionOfCPinTS\t" << std::endl;
2879     LogDebug("HGCalValidator") << std::setw(12) << tstId << "\t"  //LogDebug("HGCalValidator")
2880                                << std::setw(10) << tst.raw_energy() << "\t" << std::setw(5) << numberOfHitsInTS << "\t"
2881                                << std::setw(12) << numberOfNoiseHitsInTS << "\t" << std::setw(22)
2882                                << maxCPId_byNumberOfHits << "\t" << std::setw(8) << maxCPNumberOfHitsInTS << "\t"
2883                                << std::setw(16) << maxCPId_byEnergy << "\t" << std::setw(23) << maxEnergySharedTSandCP
2884                                << "\t" << std::setw(22) << totalCPEnergyFromLayerCP << "\t" << std::setw(22)
2885                                << energyFractionOfTSinCP << "\t" << std::setw(25) << energyFractionOfCPinTS
2886                                << std::endl;
2887 
2888   }  // end of loop through Tracksters
2889 
2890   // Loop through Tracksters
2891   for (unsigned int tstId = 0; tstId < nTracksters; ++tstId) {
2892     const auto& tst = tracksters[tstId];
2893     if (tst.vertices().empty())
2894       continue;
2895 
2896     // find the unique SimTrackster ids contributing to the Trackster
2897     //stsInTrackster[trackster][STSids]
2898     std::sort(stsInTrackster[tstId].begin(), stsInTrackster[tstId].end());
2899     const auto last = std::unique(stsInTrackster[tstId].begin(), stsInTrackster[tstId].end());
2900     stsInTrackster[tstId].erase(last, stsInTrackster[tstId].end());
2901 
2902     if (tst.raw_energy() == 0. && !stsInTrackster[tstId].empty()) {
2903       //Loop through all SimTracksters contributing to Trackster tstId
2904       for (auto& stsPair : stsInTrackster[tstId]) {
2905         // In case of a Trackster with zero energy but related SimTracksters the score is set to 1
2906         stsPair.second = 1.;
2907         LogDebug("HGCalValidator") << "Trackster Id:\t" << tstId << "\tSimTrackster id:\t" << stsPair.first
2908                                    << "\tscore\t" << stsPair.second << std::endl;
2909         histograms.h_score_trackster2caloparticle[valType][count]->Fill(stsPair.second);
2910       }
2911       continue;
2912     }
2913 
2914     const auto tst_hitsAndFractions = apply_LCMultiplicity(tst, layerClusters);
2915 
2916     // Compute the correct normalization
2917     float tracksterEnergy = 0.f, invTracksterEnergyWeight = 0.f;
2918     for (const auto& haf : tst_hitsAndFractions) {
2919       const HGCRecHit* hit = &(hits[hitMap.at(haf.first)]);
2920       float hitFr = 0.f;
2921       if (valType == 0) {
2922         hitFr = haf.second;
2923       } else {
2924         const auto lcId = getLCId(tst.vertices(), layerClusters, haf.first);
2925         const auto iLC = std::find(tst.vertices().begin(), tst.vertices().end(), lcId);
2926         hitFr = 1.f / tst.vertex_multiplicity(std::distance(std::begin(tst.vertices()), iLC));
2927       }
2928       tracksterEnergy += hitFr * hit->energy();
2929       invTracksterEnergyWeight += pow(hitFr * hit->energy(), 2);
2930     }
2931     if (invTracksterEnergyWeight)
2932       invTracksterEnergyWeight = 1.f / invTracksterEnergyWeight;
2933 
2934     for (const auto& haf : tst_hitsAndFractions) {
2935       const auto rh_detid = haf.first;
2936       unsigned int elemId = 0;
2937       float rhFraction = 0.f;
2938       if (valType == 0) {
2939         elemId = rh_detid.rawId();
2940         rhFraction = haf.second;
2941       } else {
2942         const auto lcId = getLCId(tst.vertices(), layerClusters, rh_detid);
2943         elemId = lcId;
2944         const auto iLC = std::find(tst.vertices().begin(), tst.vertices().end(), lcId);
2945         rhFraction = 1.f / tst.vertex_multiplicity(std::distance(std::begin(tst.vertices()), iLC));
2946       }
2947 
2948       bool hitWithNoSTS = false;
2949       if (detIdSimTSId_Map.find(elemId) == detIdSimTSId_Map.end())
2950         hitWithNoSTS = true;
2951       const HGCRecHit* hit = &(hits[hitMap.find(rh_detid)->second]);
2952       const auto hitEnergyWeight = pow(hit->energy(), 2);
2953 
2954       for (auto& stsPair : stsInTrackster[tstId]) {
2955         float cpFraction = 0.f;
2956         if (!hitWithNoSTS) {
2957           const auto& findSTSIt = std::find(
2958               detIdSimTSId_Map[elemId].begin(),
2959               detIdSimTSId_Map[elemId].end(),
2960               HGVHistoProducerAlgo::detIdInfoInCluster{
2961                   stsPair.first, 0.f});  // only the first element is used for the matching (overloaded operator==)
2962           if (findSTSIt != detIdSimTSId_Map[elemId].end())
2963             cpFraction = findSTSIt->fraction;
2964         }
2965         if (stsPair.second == FLT_MAX) {
2966           stsPair.second = 0.f;
2967         }
2968         stsPair.second +=
2969             min(pow(rhFraction - cpFraction, 2), pow(rhFraction, 2)) * hitEnergyWeight * invTracksterEnergyWeight;
2970       }
2971     }  // end of loop through trackster rechits
2972 
2973     //In case of a Trackster with some energy but none related CaloParticles print some info.
2974     if (stsInTrackster[tstId].empty())
2975       LogDebug("HGCalValidator") << "Trackster Id: " << tstId << "\tSimTrackster id: -1"
2976                                  << "\tscore: -1\n";
2977 
2978     tracksters_FakeMerge[tstId] =
2979         std::count_if(std::begin(stsInTrackster[tstId]),
2980                       std::end(stsInTrackster[tstId]),
2981                       [ScoreCutTStoSTSFakeMerge](const auto& obj) { return obj.second < ScoreCutTStoSTSFakeMerge; });
2982 
2983     const auto score = std::min_element(std::begin(stsInTrackster[tstId]),
2984                                         std::end(stsInTrackster[tstId]),
2985                                         [](const auto& obj1, const auto& obj2) { return obj1.second < obj2.second; });
2986     float score2 = -1;
2987     float sharedEneFrac2 = 0;
2988     for (const auto& stsPair : stsInTrackster[tstId]) {
2989       const auto iSTS = stsPair.first;
2990       const auto iScore = stsPair.second;
2991       const auto cpId = getCPId(simTSs[iSTS], iSTS, cPHandle_id, cpToSc_SimTrackstersMap, simTSs_fromCP);
2992       auto iSim = simTSs[iSTS].seedIndex();
2993       if (simTSs[iSTS].seedID() == cPHandle_id)  // SimTrackster from CaloParticle
2994         iSim = 0;
2995       const auto& simOnLayer = (valType == 0) ? cPOnLayer[cpId] : sCOnLayer[cpId][iSim];
2996 
2997       float sharedeneCPallLayers = 0.;
2998       sharedeneCPallLayers += simOnLayer.layerClusterIdToEnergyAndScore.count(tstId)
2999                                   ? simOnLayer.layerClusterIdToEnergyAndScore.at(tstId).first
3000                                   : 0;
3001       if (tracksterEnergy == 0)
3002         continue;
3003       const auto sharedEneFrac = sharedeneCPallLayers / tracksterEnergy;
3004       LogDebug("HGCalValidator") << "\nTrackster id: " << tstId << " (" << tst.vertices().size() << " vertices)"
3005                                  << "\tSimTrackster Id: " << iSTS << " (" << simTSs[iSTS].vertices().size()
3006                                  << " vertices)"
3007                                  << " (CP id: " << cpId << ")\tscore: " << iScore
3008                                  << "\tsharedeneCPallLayers: " << sharedeneCPallLayers << std::endl;
3009 
3010       histograms.h_score_trackster2caloparticle[valType][count]->Fill(iScore);
3011       histograms.h_sharedenergy_trackster2caloparticle[valType][count]->Fill(sharedEneFrac);
3012       histograms.h_energy_vs_score_trackster2caloparticle[valType][count]->Fill(iScore, sharedEneFrac);
3013       if (iSTS == score->first) {
3014         histograms.h_score_trackster2bestCaloparticle[valType][count]->Fill(iScore);
3015         histograms.h_sharedenergy_trackster2bestCaloparticle[valType][count]->Fill(sharedEneFrac);
3016         histograms.h_sharedenergy_trackster2bestCaloparticle_vs_eta[valType][count]->Fill(tst.barycenter().eta(),
3017                                                                                           sharedEneFrac);
3018         histograms.h_sharedenergy_trackster2bestCaloparticle_vs_phi[valType][count]->Fill(tst.barycenter().phi(),
3019                                                                                           sharedEneFrac);
3020         histograms.h_energy_vs_score_trackster2bestCaloparticle[valType][count]->Fill(iScore, sharedEneFrac);
3021       } else if (score2 < 0 || iScore < score2) {
3022         score2 = iScore;
3023         sharedEneFrac2 = sharedEneFrac;
3024       }
3025     }  // end of loop through SimTracksters associated to Trackster
3026     if (score2 > -1) {
3027       histograms.h_score_trackster2bestCaloparticle2[valType][count]->Fill(score2);
3028       histograms.h_sharedenergy_trackster2bestCaloparticle2[valType][count]->Fill(sharedEneFrac2);
3029       histograms.h_energy_vs_score_trackster2bestCaloparticle2[valType][count]->Fill(score2, sharedEneFrac2);
3030     }
3031   }  // end of loop through Tracksters
3032 
3033   std::unordered_map<unsigned int, std::vector<float>> score3d;
3034   std::unordered_map<unsigned int, std::vector<float>> tstSharedEnergy;
3035 
3036   for (unsigned int iSTS = 0; iSTS < nSimTracksters; ++iSTS) {
3037     score3d[iSTS].resize(nTracksters);
3038     tstSharedEnergy[iSTS].resize(nTracksters);
3039     for (unsigned int j = 0; j < nTracksters; ++j) {
3040       score3d[iSTS][j] = FLT_MAX;
3041       tstSharedEnergy[iSTS][j] = 0.f;
3042     }
3043   }
3044 
3045   // Fill the plots to compute the different metrics linked to
3046   // gen-level, namely efficiency, purity and duplicate. In this loop should restrict
3047   // only to the selected caloParaticles.
3048   for (unsigned int iSTS = 0; iSTS < nSimTracksters; ++iSTS) {
3049     const auto& sts = simTSs[iSTS];
3050     const auto& cpId = getCPId(sts, iSTS, cPHandle_id, cpToSc_SimTrackstersMap, simTSs_fromCP);
3051     if (valType == 0 && std::find(cPSelectedIndices.begin(), cPSelectedIndices.end(), cpId) == cPSelectedIndices.end())
3052       continue;
3053 
3054     const auto& hafLC = apply_LCMultiplicity(sts, layerClusters);
3055     float SimEnergy_LC = 0.f;
3056     for (const auto& haf : hafLC) {
3057       const auto lcId = getLCId(sts.vertices(), layerClusters, haf.first);
3058       const auto iLC = std::find(sts.vertices().begin(), sts.vertices().end(), lcId);
3059       const HGCRecHit* hit = &(hits[hitMap.at(haf.first)]);
3060       SimEnergy_LC += hit->energy() / sts.vertex_multiplicity(std::distance(std::begin(sts.vertices()), iLC));
3061     }
3062 
3063     auto iSim = sts.seedIndex();
3064     if (sts.seedID() == cPHandle_id)  // SimTrackster from CaloParticle
3065       iSim = 0;
3066     auto& simOnLayer = (valType == 0) ? cPOnLayer[cpId] : sCOnLayer[cpId][iSim];
3067 
3068     // Keep the Trackster ids that are related to
3069     // SimTrackster under study for the final filling of the score
3070     std::set<unsigned int> stsId_tstId_related;
3071     auto& score3d_iSTS = score3d[iSTS];
3072 
3073     float SimEnergy = 0.f;
3074     float SimEnergyWeight = 0.f, hitsEnergyWeight = 0.f;
3075     //for (unsigned int layerId = 0; layerId < 1/*layers * 2*/; ++layerId) {
3076     const auto SimNumberOfHits = simOnLayer.hits_and_fractions.size();
3077     if (SimNumberOfHits == 0)
3078       continue;
3079     SimEnergy += simOnLayer.energy;
3080     int tstWithMaxEnergyInCP = -1;
3081     //This is the maximum energy related to Trackster per layer.
3082     float maxEnergyTSperlayerinSim = 0.f;
3083     float SimEnergyFractionInTSperlayer = 0.f;
3084     //Remember and not confused by name. layerClusterIdToEnergyAndScore contains the Trackster id.
3085     for (const auto& tst : simOnLayer.layerClusterIdToEnergyAndScore) {
3086       if (tst.second.first > maxEnergyTSperlayerinSim) {
3087         maxEnergyTSperlayerinSim = tst.second.first;
3088         tstWithMaxEnergyInCP = tst.first;
3089       }
3090     }
3091     if (SimEnergy > 0.f)
3092       SimEnergyFractionInTSperlayer = maxEnergyTSperlayerinSim / SimEnergy;
3093 
3094     LogDebug("HGCalValidator") << std::setw(12) << "caloparticle\t" << std::setw(15) << "cp total energy\t"
3095                                << std::setw(15) << "cpEnergyOnLayer\t" << std::setw(14) << "CPNhitsOnLayer\t"
3096                                << std::setw(18) << "tstWithMaxEnergyInCP\t" << std::setw(15) << "maxEnergyTSinCP\t"
3097                                << std::setw(20) << "CPEnergyFractionInTS"
3098                                << "\n";
3099     LogDebug("HGCalValidator") << std::setw(12) << cpId << "\t" << std::setw(15) << sts.raw_energy() << "\t"
3100                                << std::setw(15) << SimEnergy << "\t" << std::setw(14) << SimNumberOfHits << "\t"
3101                                << std::setw(18) << tstWithMaxEnergyInCP << "\t" << std::setw(15)
3102                                << maxEnergyTSperlayerinSim << "\t" << std::setw(20) << SimEnergyFractionInTSperlayer
3103                                << "\n";
3104 
3105     for (const auto& haf : ((valType == 0) ? simOnLayer.hits_and_fractions : hafLC)) {
3106       const auto& hitDetId = haf.first;
3107       // Compute the correct normalization
3108       // Need to loop on the simOnLayer data structure since this is the
3109       // only one that has the compressed information for multiple usage
3110       // of the same DetId by different SimClusters by a single CaloParticle.
3111       const HGCRecHit* hit = &(hits[hitMap.at(hitDetId)]);
3112       SimEnergyWeight += pow(haf.second * hit->energy(), 2);
3113 
3114       const auto lcId = getLCId(sts.vertices(), layerClusters, hitDetId);
3115       float cpFraction = 0.f;
3116       if (valType == 0) {
3117         cpFraction = haf.second;
3118       } else {
3119         const auto iLC = std::find(sts.vertices().begin(), sts.vertices().end(), lcId);
3120         cpFraction = 1.f / sts.vertex_multiplicity(std::distance(std::begin(sts.vertices()), iLC));
3121       }
3122       if (cpFraction == 0.f)
3123         continue;  // hopefully this should never happen
3124 
3125       bool hitWithNoTS = false;
3126       if (detIdToTracksterId_Map.find(hitDetId) == detIdToTracksterId_Map.end())
3127         hitWithNoTS = true;
3128       const auto hitEnergyWeight = pow(hit->energy(), 2);
3129       hitsEnergyWeight += pow(cpFraction, 2) * hitEnergyWeight;
3130 
3131       for (auto& tsPair : simOnLayer.layerClusterIdToEnergyAndScore) {
3132         const auto tstId = tsPair.first;
3133         stsId_tstId_related.insert(tstId);
3134 
3135         float tstFraction = 0.f;
3136         if (!hitWithNoTS) {
3137           const auto findTSIt =
3138               std::find(detIdToTracksterId_Map[hitDetId].begin(),
3139                         detIdToTracksterId_Map[hitDetId].end(),
3140                         HGVHistoProducerAlgo::detIdInfoInTrackster{
3141                             tstId, 0, 0.f});  // only the first element is used for the matching (overloaded operator==)
3142           if (findTSIt != detIdToTracksterId_Map[hitDetId].end()) {
3143             if (valType == 0) {
3144               tstFraction = findTSIt->fraction;
3145             } else {
3146               const auto iLC = std::find(
3147                   tracksters[tstId].vertices().begin(), tracksters[tstId].vertices().end(), findTSIt->clusterId);
3148               if (iLC != tracksters[tstId].vertices().end()) {
3149                 tstFraction = 1.f / tracksters[tstId].vertex_multiplicity(
3150                                         std::distance(std::begin(tracksters[tstId].vertices()), iLC));
3151               }
3152             }
3153           }
3154         }
3155         // Here do not divide as before by the trackster energy weight. Should sum first
3156         // over all layers and divide with the total CP energy over all layers.
3157         if (tsPair.second.second == FLT_MAX) {
3158           tsPair.second.second = 0.f;
3159         }
3160         tsPair.second.second += min(pow(tstFraction - cpFraction, 2), pow(cpFraction, 2)) * hitEnergyWeight;
3161 
3162         LogDebug("HGCalValidator") << "\nTracksterId:\t" << tstId << "\tSimTracksterId:\t" << iSTS << "\tcpId:\t"
3163                                    << cpId << "\ttstfraction, cpfraction:\t" << tstFraction << ", " << cpFraction
3164                                    << "\thitEnergyWeight:\t" << hitEnergyWeight << "\tadded delta:\t"
3165                                    << pow((tstFraction - cpFraction), 2) * hitEnergyWeight
3166                                    << "\tcurrent Sim-score numerator:\t" << tsPair.second.second
3167                                    << "\tshared Sim energy:\t" << tsPair.second.first << '\n';
3168       }
3169     }  // end of loop through SimCluster SimHits on current layer
3170 
3171     if (simOnLayer.layerClusterIdToEnergyAndScore.empty())
3172       LogDebug("HGCalValidator") << "CP Id:\t" << cpId << "\tTS id:\t-1"
3173                                  << " Sub score in \t -1\n";
3174 
3175     for (const auto& tsPair : simOnLayer.layerClusterIdToEnergyAndScore) {
3176       const auto tstId = tsPair.first;
3177       // 3D score here without the denominator at this point
3178       if (score3d_iSTS[tstId] == FLT_MAX) {
3179         score3d_iSTS[tstId] = 0.f;
3180       }
3181       score3d_iSTS[tstId] += tsPair.second.second;
3182       tstSharedEnergy[iSTS][tstId] += tsPair.second.first;
3183     }
3184     //} // end of loop through layers
3185 
3186     const auto scoreDenom = (valType == 0) ? SimEnergyWeight : hitsEnergyWeight;
3187     const auto energyDenom = (valType == 0) ? SimEnergy : SimEnergy_LC;
3188 
3189     const auto sts_eta = sts.barycenter().eta();
3190     const auto sts_phi = sts.barycenter().phi();
3191     const auto sts_en = sts.raw_energy();
3192     const auto sts_pt = sts.raw_pt();
3193     histograms.h_denom_caloparticle_eta[valType][count]->Fill(sts_eta);
3194     histograms.h_denom_caloparticle_phi[valType][count]->Fill(sts_phi);
3195     histograms.h_denom_caloparticle_en[valType][count]->Fill(sts_en);
3196     histograms.h_denom_caloparticle_pt[valType][count]->Fill(sts_pt);
3197 
3198     //Loop through related Tracksters here
3199     // In case the threshold to associate a CaloParticle to a Trackster is
3200     // below 50%, there could be cases in which the CP is linked to more than
3201     // one tracksters, leading to efficiencies >1. This boolean is used to
3202     // avoid "over counting".
3203     bool sts_considered_efficient = false;
3204     bool sts_considered_pure = false;
3205     for (const auto tstId : stsId_tstId_related) {
3206       // Now time for the denominator
3207       score3d_iSTS[tstId] /= scoreDenom;
3208       const auto tstSharedEnergyFrac = tstSharedEnergy[iSTS][tstId] / energyDenom;
3209       LogDebug("HGCalValidator") << "STS id: " << iSTS << "\t(CP id: " << cpId << ")\tTS id: " << tstId
3210                                  << "\nSimEnergy: " << energyDenom << "\tSimEnergyWeight: " << SimEnergyWeight
3211                                  << "\tTrackste energy: " << tracksters[tstId].raw_energy()
3212                                  << "\nscore: " << score3d_iSTS[tstId]
3213                                  << "\tshared energy: " << tstSharedEnergy[iSTS][tstId]
3214                                  << "\tshared energy fraction: " << tstSharedEnergyFrac << "\n";
3215 
3216       histograms.h_score_caloparticle2trackster[valType][count]->Fill(score3d_iSTS[tstId]);
3217       histograms.h_sharedenergy_caloparticle2trackster[valType][count]->Fill(tstSharedEnergyFrac);
3218       histograms.h_energy_vs_score_caloparticle2trackster[valType][count]->Fill(score3d_iSTS[tstId],
3219                                                                                 tstSharedEnergyFrac);
3220       // Fill the numerator for the efficiency calculation. The efficiency is computed by considering the energy shared between a Trackster and a _corresponding_ caloParticle. The threshold is configurable via python.
3221       if (!sts_considered_efficient && (tstSharedEnergyFrac >= minTSTSharedEneFracEfficiency_)) {
3222         sts_considered_efficient = true;
3223         histograms.h_numEff_caloparticle_eta[valType][count]->Fill(sts_eta);
3224         histograms.h_numEff_caloparticle_phi[valType][count]->Fill(sts_phi);
3225         histograms.h_numEff_caloparticle_en[valType][count]->Fill(sts_en);
3226         histograms.h_numEff_caloparticle_pt[valType][count]->Fill(sts_pt);
3227       }
3228 
3229       if (score3d_iSTS[tstId] < ScoreCutSTStoTSPurDup) {
3230         if (tracksters_PurityDuplicate[iSTS] < 1)
3231           tracksters_PurityDuplicate[iSTS]++;  // for Purity
3232         if (sts_considered_pure)
3233           tracksters_PurityDuplicate[iSTS]++;  // for Duplicate
3234         sts_considered_pure = true;
3235       }
3236     }  // end of loop through Tracksters related to SimTrackster
3237 
3238     const auto best = std::min_element(std::begin(score3d_iSTS), std::end(score3d_iSTS));
3239     if (best != score3d_iSTS.end()) {
3240       const auto bestTstId = std::distance(std::begin(score3d_iSTS), best);
3241       const auto bestTstSharedEnergyFrac = tstSharedEnergy[iSTS][bestTstId] / energyDenom;
3242       histograms.h_scorePur_caloparticle2trackster[valType][count]->Fill(*best);
3243       histograms.h_sharedenergy_caloparticle2trackster_assoc[valType][count]->Fill(bestTstSharedEnergyFrac);
3244       histograms.h_sharedenergy_caloparticle2trackster_assoc_vs_eta[valType][count]->Fill(sts_eta,
3245                                                                                           bestTstSharedEnergyFrac);
3246       histograms.h_sharedenergy_caloparticle2trackster_assoc_vs_phi[valType][count]->Fill(sts_phi,
3247                                                                                           bestTstSharedEnergyFrac);
3248       histograms.h_energy_vs_score_caloparticle2bestTrackster[valType][count]->Fill(*best, bestTstSharedEnergyFrac);
3249       LogDebug("HGCalValidator") << count << " " << sts_eta << " " << sts_phi << " "
3250                                  << tracksters[bestTstId].raw_energy() << " " << sts.raw_energy() << " "
3251                                  << bestTstSharedEnergyFrac << "\n";
3252 
3253       if (score3d_iSTS.size() > 1) {
3254         auto best2 = (best == score3d_iSTS.begin()) ? std::next(best, 1) : score3d_iSTS.begin();
3255         for (auto tstId = score3d_iSTS.begin(); tstId != score3d_iSTS.end() && tstId != best; tstId++)
3256           if (*tstId < *best2)
3257             best2 = tstId;
3258         const auto best2TstId = std::distance(std::begin(score3d_iSTS), best2);
3259         const auto best2TstSharedEnergyFrac = tstSharedEnergy[iSTS][best2TstId] / energyDenom;
3260         histograms.h_scoreDupl_caloparticle2trackster[valType][count]->Fill(*best2);
3261         histograms.h_sharedenergy_caloparticle2trackster_assoc2[valType][count]->Fill(best2TstSharedEnergyFrac);
3262         histograms.h_energy_vs_score_caloparticle2bestTrackster2[valType][count]->Fill(*best2,
3263                                                                                        best2TstSharedEnergyFrac);
3264       }
3265     }
3266   }  // end of loop through SimTracksters
3267 
3268   // Fill the plots to compute the different metrics linked to
3269   // sim-level, namely purity and duplicate-rate
3270   for (unsigned int stsId = 0; stsId < nSimTracksters; ++stsId) {
3271     const auto& sts = simTSs[stsId];
3272     if (sts.vertices().empty())
3273       continue;
3274     const auto sts_eta = sts.barycenter().eta();
3275     const auto sts_phi = sts.barycenter().phi();
3276     const auto sts_en = sts.raw_energy();
3277     const auto sts_pt = sts.raw_pt();
3278 
3279     if (tracksters_PurityDuplicate[stsId] > 0) {
3280       histograms.h_num_caloparticle_eta[valType][count]->Fill(sts_eta);
3281       histograms.h_num_caloparticle_phi[valType][count]->Fill(sts_phi);
3282       histograms.h_num_caloparticle_en[valType][count]->Fill(sts_en);
3283       histograms.h_num_caloparticle_pt[valType][count]->Fill(sts_pt);
3284 
3285       if (tracksters_PurityDuplicate[stsId] > 1) {
3286         histograms.h_numDup_trackster_eta[valType][count]->Fill(sts_eta);
3287         histograms.h_numDup_trackster_phi[valType][count]->Fill(sts_phi);
3288         histograms.h_numDup_trackster_en[valType][count]->Fill(sts_en);
3289         histograms.h_numDup_trackster_pt[valType][count]->Fill(sts_pt);
3290       }
3291     }
3292   }
3293 
3294   // Fill the plots to compute the different metrics linked to
3295   // reco-level, namely fake-rate an merge-rate. Should *not*
3296   // restrict only to the selected caloParaticles.
3297   for (unsigned int tstId = 0; tstId < nTracksters; ++tstId) {
3298     const auto& tst = tracksters[tstId];
3299     if (tst.vertices().empty())
3300       continue;
3301     const auto iTS_eta = tst.barycenter().eta();
3302     const auto iTS_phi = tst.barycenter().phi();
3303     const auto iTS_en = tst.raw_energy();
3304     const auto iTS_pt = tst.raw_pt();
3305     histograms.h_denom_trackster_eta[valType][count]->Fill(iTS_eta);
3306     histograms.h_denom_trackster_phi[valType][count]->Fill(iTS_phi);
3307     histograms.h_denom_trackster_en[valType][count]->Fill(iTS_en);
3308     histograms.h_denom_trackster_pt[valType][count]->Fill(iTS_pt);
3309 
3310     if (tracksters_FakeMerge[tstId] > 0) {
3311       histograms.h_num_trackster_eta[valType][count]->Fill(iTS_eta);
3312       histograms.h_num_trackster_phi[valType][count]->Fill(iTS_phi);
3313       histograms.h_num_trackster_en[valType][count]->Fill(iTS_en);
3314       histograms.h_num_trackster_pt[valType][count]->Fill(iTS_pt);
3315 
3316       if (tracksters_FakeMerge[tstId] > 1) {
3317         histograms.h_numMerge_trackster_eta[valType][count]->Fill(iTS_eta);
3318         histograms.h_numMerge_trackster_phi[valType][count]->Fill(iTS_phi);
3319         histograms.h_numMerge_trackster_en[valType][count]->Fill(iTS_en);
3320         histograms.h_numMerge_trackster_pt[valType][count]->Fill(iTS_pt);
3321       }
3322     }
3323   }  // End loop over Tracksters
3324 }
3325 
3326 void HGVHistoProducerAlgo::fill_trackster_histos(
3327     const Histograms& histograms,
3328     const int count,
3329     const ticl::TracksterCollection& tracksters,
3330     const reco::CaloClusterCollection& layerClusters,
3331     const ticl::TracksterCollection& simTSs,
3332     const ticl::TracksterCollection& simTSs_fromCP,
3333     const std::map<unsigned int, std::vector<unsigned int>>& cpToSc_SimTrackstersMap,
3334     std::vector<SimCluster> const& sC,
3335     const edm::ProductID& cPHandle_id,
3336     std::vector<CaloParticle> const& cP,
3337     std::vector<size_t> const& cPIndices,
3338     std::vector<size_t> const& cPSelectedIndices,
3339     std::unordered_map<DetId, const unsigned int> const& hitMap,
3340     unsigned int layers,
3341     std::vector<HGCRecHit> const& hits) const {
3342   //Each event to be treated as two events:
3343   //an event in +ve endcap, plus another event in -ve endcap.
3344 
3345   //To keep track of total num of Tracksters
3346   int totNTstZm = 0;  //-z
3347   int totNTstZp = 0;  //+z
3348   //To count the number of Tracksters with 3 contiguous layers per event.
3349   int totNContTstZp = 0;  //+z
3350   int totNContTstZm = 0;  //-z
3351   //For the number of Tracksters without 3 contiguous layers per event.
3352   int totNNotContTstZp = 0;  //+z
3353   int totNNotContTstZm = 0;  //-z
3354   // Check below the score of cont and non cont Tracksters
3355   std::vector<bool> contTracksters;
3356   contTracksters.clear();
3357 
3358   //[tstId]-> vector of 2d layer clusters size
3359   std::unordered_map<unsigned int, std::vector<unsigned int>> multiplicity;
3360   //[tstId]-> [layer][cluster size]
3361   std::unordered_map<unsigned int, std::vector<unsigned int>> multiplicity_vs_layer;
3362   //We will need for the scale text option
3363   // unsigned int totalLcInTsts = 0;
3364   // for (unsigned int tstId = 0; tstId < nTracksters; ++tstId) {
3365   //   totalLcInTsts = totalLcInTsts + tracksters[tstId].vertices().size();
3366   // }
3367 
3368   const auto nTracksters = tracksters.size();
3369   // loop through Tracksters
3370   for (unsigned int tstId = 0; tstId < nTracksters; ++tstId) {
3371     const auto& tst = tracksters[tstId];
3372     if (tst.vertices().empty())
3373       continue;
3374 
3375     if (tst.barycenter().z() < 0.)
3376       totNTstZm++;
3377     else if (tst.barycenter().z() > 0.)
3378       totNTstZp++;
3379 
3380     //Total number of layer clusters in Trackster
3381     int tnLcInTst = 0;
3382 
3383     //To keep track of total num of layer clusters per Trackster
3384     //tnLcInTstperlaypz[layerid], tnLcInTstperlaymz[layerid]
3385     std::vector<int> tnLcInTstperlay(1000, 0);  //+z
3386 
3387     //For the layers the Trackster expands to. Will use a set because there would be many
3388     //duplicates and then go back to vector for random access, since they say it is faster.
3389     std::set<unsigned int> trackster_layers;
3390 
3391     bool tracksterInZplus = false;
3392     bool tracksterInZminus = false;
3393 
3394     //Loop through layer clusters
3395     for (const auto lcId : tst.vertices()) {
3396       //take the hits and their fraction of the specific layer cluster.
3397       const auto& hits_and_fractions = layerClusters[lcId].hitsAndFractions();
3398 
3399       //For the multiplicity of the 2d layer clusters in Tracksters
3400       multiplicity[tstId].emplace_back(hits_and_fractions.size());
3401 
3402       const auto firstHitDetId = hits_and_fractions[0].first;
3403       //The layer that the layer cluster belongs to
3404       const auto layerid = recHitTools_->getLayerWithOffset(firstHitDetId) +
3405                            layers * ((recHitTools_->zside(firstHitDetId) + 1) >> 1) - 1;
3406       trackster_layers.insert(layerid);
3407       multiplicity_vs_layer[tstId].emplace_back(layerid);
3408 
3409       tnLcInTstperlay[layerid]++;
3410       tnLcInTst++;
3411 
3412       if (recHitTools_->zside(firstHitDetId) > 0.)
3413         tracksterInZplus = true;
3414       else if (recHitTools_->zside(firstHitDetId) < 0.)
3415         tracksterInZminus = true;
3416     }  // end of loop through layerClusters
3417 
3418     // Per layer : Loop 0->99
3419     for (unsigned ilayer = 0; ilayer < layers * 2; ++ilayer) {
3420       if (histograms.h_clusternum_in_trackster_perlayer[count].count(ilayer) && tnLcInTstperlay[ilayer] != 0) {
3421         histograms.h_clusternum_in_trackster_perlayer[count].at(ilayer)->Fill((float)tnLcInTstperlay[ilayer]);
3422       }
3423       // For the profile now of 2d layer cluster in Tracksters vs layer number.
3424       if (tnLcInTstperlay[ilayer] != 0) {
3425         histograms.h_clusternum_in_trackster_vs_layer[count]->Fill((float)ilayer, (float)tnLcInTstperlay[ilayer]);
3426       }
3427     }  // end of loop over layers
3428 
3429     // Looking for Tracksters with 3 contiguous layers per event.
3430     std::vector<int> trackster_layers_vec(trackster_layers.begin(), trackster_layers.end());
3431     // Check also for non contiguous Tracksters
3432     bool contiTrackster = false;
3433     // Start from 1 and go up to size - 1 element.
3434     if (trackster_layers_vec.size() >= 3) {
3435       for (unsigned int iLayer = 1; iLayer < trackster_layers_vec.size() - 1; ++iLayer) {
3436         if ((trackster_layers_vec[iLayer - 1] + 1 == trackster_layers_vec[iLayer]) &&
3437             (trackster_layers_vec[iLayer + 1] - 1 == trackster_layers_vec[iLayer])) {
3438           // Trackster with 3 contiguous layers per event
3439           if (tracksterInZplus)
3440             totNContTstZp++;
3441           else if (tracksterInZminus)
3442             totNContTstZm++;
3443 
3444           contiTrackster = true;
3445           break;
3446         }
3447       }
3448     }
3449     // Count non contiguous Tracksters
3450     if (!contiTrackster) {
3451       if (tracksterInZplus)
3452         totNNotContTstZp++;
3453       else if (tracksterInZminus)
3454         totNNotContTstZm++;
3455     }
3456 
3457     // Save for the score
3458     contTracksters.push_back(contiTrackster);
3459 
3460     histograms.h_clusternum_in_trackster[count]->Fill(tnLcInTst);
3461 
3462     for (unsigned int lc = 0; lc < multiplicity[tstId].size(); ++lc) {
3463       //multiplicity of the current LC
3464       float mlp = std::count(std::begin(multiplicity[tstId]), std::end(multiplicity[tstId]), multiplicity[tstId][lc]);
3465       //LogDebug("HGCalValidator") << "mlp %" << (100. * mlp)/ ((float) nLayerClusters) << std::endl;
3466       // histograms.h_multiplicityOfLCinTST[count]->Fill( mlp , multiplicity[tstId][lc] , 100. / (float) totalLcInTsts );
3467       histograms.h_multiplicityOfLCinTST[count]->Fill(mlp, multiplicity[tstId][lc]);
3468       //When plotting with the text option we want the entries to be the same
3469       //as the % of the current cell over the whole number of layerClusters. For this we need an extra histo.
3470       histograms.h_multiplicity_numberOfEventsHistogram[count]->Fill(mlp);
3471       //For the cluster multiplicity vs layer
3472       //First with the -z endcap (V10:0->49)
3473       if (multiplicity_vs_layer[tstId][lc] < layers) {
3474         histograms.h_multiplicityOfLCinTST_vs_layercluster_zminus[count]->Fill(mlp, multiplicity_vs_layer[tstId][lc]);
3475         histograms.h_multiplicity_zminus_numberOfEventsHistogram[count]->Fill(mlp);
3476       } else {  //Then for the +z (V10:50->99)
3477         histograms.h_multiplicityOfLCinTST_vs_layercluster_zplus[count]->Fill(
3478             mlp, multiplicity_vs_layer[tstId][lc] - layers);
3479         histograms.h_multiplicity_zplus_numberOfEventsHistogram[count]->Fill(mlp);
3480       }
3481       //For the cluster multiplicity vs cluster energy
3482       histograms.h_multiplicityOfLCinTST_vs_layerclusterenergy[count]->Fill(mlp,
3483                                                                             layerClusters[tst.vertices(lc)].energy());
3484     }
3485 
3486     if (!trackster_layers.empty()) {
3487       histograms.h_trackster_x[count]->Fill(tst.barycenter().x());
3488       histograms.h_trackster_y[count]->Fill(tst.barycenter().y());
3489       histograms.h_trackster_z[count]->Fill(tst.barycenter().z());
3490       histograms.h_trackster_eta[count]->Fill(tst.barycenter().eta());
3491       histograms.h_trackster_phi[count]->Fill(tst.barycenter().phi());
3492 
3493       histograms.h_trackster_firstlayer[count]->Fill((float)*trackster_layers.begin());
3494       histograms.h_trackster_lastlayer[count]->Fill((float)*trackster_layers.rbegin());
3495       histograms.h_trackster_layersnum[count]->Fill((float)trackster_layers.size());
3496 
3497       histograms.h_trackster_pt[count]->Fill(tst.raw_pt());
3498       histograms.h_trackster_energy[count]->Fill(tst.raw_energy());
3499     }
3500 
3501   }  //end of loop through Tracksters
3502 
3503   histograms.h_tracksternum[count]->Fill(totNTstZm + totNTstZp);
3504   histograms.h_conttracksternum[count]->Fill(totNContTstZp + totNContTstZm);
3505   histograms.h_nonconttracksternum[count]->Fill(totNNotContTstZp + totNNotContTstZm);
3506 
3507   // CaloParticle
3508   tracksters_to_SimTracksters(histograms,
3509                               count,
3510                               tracksters,
3511                               layerClusters,
3512                               simTSs_fromCP,
3513                               Linking,
3514                               simTSs_fromCP,
3515                               cpToSc_SimTrackstersMap,
3516                               sC,
3517                               cPHandle_id,
3518                               cP,
3519                               cPIndices,
3520                               cPSelectedIndices,
3521                               hitMap,
3522                               layers,
3523                               hits);
3524 
3525   // Pattern recognition
3526   tracksters_to_SimTracksters(histograms,
3527                               count,
3528                               tracksters,
3529                               layerClusters,
3530                               simTSs,
3531                               PatternRecognition,
3532                               simTSs_fromCP,
3533                               cpToSc_SimTrackstersMap,
3534                               sC,
3535                               cPHandle_id,
3536                               cP,
3537                               cPIndices,
3538                               cPSelectedIndices,
3539                               hitMap,
3540                               layers,
3541                               hits);
3542 }
3543 
3544 double HGVHistoProducerAlgo::distance2(const double x1,
3545                                        const double y1,
3546                                        const double x2,
3547                                        const double y2) const {  //distance squared
3548   const double dx = x1 - x2;
3549   const double dy = y1 - y2;
3550   return (dx * dx + dy * dy);
3551 }  //distance squaredq
3552 double HGVHistoProducerAlgo::distance(const double x1,
3553                                       const double y1,
3554                                       const double x2,
3555                                       const double y2) const {  //2-d distance on the layer (x-y)
3556   return std::sqrt(distance2(x1, y1, x2, y2));
3557 }
3558 
3559 void HGVHistoProducerAlgo::setRecHitTools(std::shared_ptr<hgcal::RecHitTools> recHitTools) {
3560   recHitTools_ = recHitTools;
3561 }
3562 
3563 DetId HGVHistoProducerAlgo::findmaxhit(const reco::CaloCluster& cluster,
3564                                        std::unordered_map<DetId, const unsigned int> const& hitMap,
3565                                        std::vector<HGCRecHit> const& hits) const {
3566   const auto& hits_and_fractions = cluster.hitsAndFractions();
3567 
3568   DetId themaxid;
3569   double maxene = 0.;
3570   for (std::vector<std::pair<DetId, float>>::const_iterator it_haf = hits_and_fractions.begin();
3571        it_haf != hits_and_fractions.end();
3572        ++it_haf) {
3573     const DetId rh_detid = it_haf->first;
3574     const auto hitEn = (hits[hitMap.find(rh_detid)->second]).energy();
3575     if (maxene < hitEn) {
3576       maxene = hitEn;
3577       themaxid = rh_detid;
3578     }
3579   }
3580 
3581   return themaxid;
3582 }
3583 
3584 double HGVHistoProducerAlgo::getEta(double eta) const {
3585   if (useFabsEta_)
3586     return fabs(eta);
3587   else
3588     return eta;
3589 }