ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/JetFitAnalyzer/test/JetFinderAnalyzer.cc
(Generate patch)

Comparing UserCode/JetFitAnalyzer/test/JetFinderAnalyzer.cc (file contents):
Revision 1.3 by dnisson, Thu Sep 3 18:02:35 2009 UTC vs.
Revision 1.27 by dnisson, Fri Jan 22 23:53:10 2010 UTC

# Line 1 | Line 1
1 < /* A simple jet-finding analyzer */
1 > /* A JetFitAnalyzer that makes histograms with smearing */
2  
3   #include "UserCode/JetFitAnalyzer/interface/JetFitAnalyzer.h"
4  
5 #include "fastjet/ClusterSequence.hh"
5   #include "FWCore/ServiceRegistry/interface/Service.h"
6   #include "FWCore/MessageLogger/interface/MessageLogger.h"
7   #include "PhysicsTools/UtilAlgos/interface/TFileService.h"
8  
9 < #include "SimDataFormats/HepMCProduct/interface/HepMCProduct.h"
11 < #include "DataFormats/Candidate/interface/Particle.h"
12 < #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h"
13 < #include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
14 < #include "DataFormats/ParticleFlowReco/interface/PFBlock.h"
15 <
16 < #include <map>
17 < #include <vector>
18 < #include <limits>
19 < #include <cmath>
20 < #include <cstdlib>
21 < #include <fstream>
9 > #include <iostream>
10   #include <sstream>
11  
24 #include "TFormula.h"
12   #include "TF2.h"
13 + #include "TNtuple.h"
14  
15   #define PI 3.141593
16  
17   using namespace std;
30 using namespace fastjet;
31
32 // Class to represent a "generic" particle, whether raw or reconstructed
33 class GenericParticle {
34 public:
35  GenericParticle(double __px, double __py, double __pz, double __e,
36                  double __charge = 0.0)
37  : _px(__px), _py(__py), _pz(__pz), _e(__e), _charge(__charge) {
38  }
39  GenericParticle(const HepMC::GenParticle &genParticle)
40  : _charge(0.0) {
41    _px = genParticle.momentum().px();
42    _py = genParticle.momentum().py();
43    _pz = genParticle.momentum().pz();
44    _e = genParticle.momentum().e();
45  }
46  GenericParticle(const reco::PFCandidate &pfCandidate)
47  : _charge(0.0) {
48    _px = pfCandidate.px();
49    _py = pfCandidate.py();
50    _pz = pfCandidate.pz();
51    _e = pfCandidate.energy();
52  }
53  double px() {
54    return _px;
55  }
56  double py() {
57    return _py;
58  }
59  double pz() {
60    return _pz;
61  }
62  double e() {
63    return _e;
64  }
65  double charge() {
66    return _charge;
67  }
68  double eta() {
69    double theta = acos(_pz/sqrt(_px*_px + _py*_py + _pz*_pz));
70    return -log(tan(theta*0.5));
71  }
72  double phi() {
73    double phi0 = acos(_px/sqrt(_px*_px + _py*_py));
74    return _py > 0.0 ? phi0 : -phi0;
75  }
76  double m() {
77    return sqrt(_e*_e - _px*_px - _py*_py - _pz*_pz);
78  }
79 private:
80  double _px;
81  double _py;
82  double _pz;
83  double _e;
84  double _charge;
85 };
18  
19   class JetFinderAnalyzer : public JetFitAnalyzer {
20   public:
89  struct jet {
90    double energy;
91    double eta;
92    double phi;
93  };
94
21    explicit JetFinderAnalyzer( const edm::ParameterSet&);
22    ~JetFinderAnalyzer() {}
23  
24   private:
25 <  static map<TH2 *, vector< vector<jet> > > unique_jets;
26 <
27 <  static double phi_cutoff_;
102 <
103 <  static double g2int(double xlo, double xhi, double ylo, double yhi,
104 <               double *pval) {
105 <    double sum1 = 0.0;
106 <    double sum2 = 0.0;
107 <    double xmid = 0.5 * (xlo + xhi);
108 <    double ymid = 0.5 * (ylo + yhi);
109 <    double xstep = (xhi - xlo) / 50.0;
110 <    double ystep = (yhi - ylo) / 50.0;
111 <    for (int i = 0; i < 50; i++) {
112 <      double x = (static_cast<double>(i) + 0.5) * xstep + xlo;
113 <      sum1 += xstep * jetfit::fit_fcn(x, ymid, pval);
114 <    }
115 <    for (int i = 0; i < 50; i++) {
116 <      double y = (static_cast<double>(i) + 0.5) * ystep + ylo;
117 <      sum2 += ystep * jetfit::fit_fcn(xmid, y, pval);
118 <    }
119 <    return sum1 * sum2;
120 <  }
121 <
122 <  static void jetfinder(TMinuit *gMinuit, TH2 *hist, int ngauss) {
123 <    double dist_sq = numeric_limits<double>::infinity();
124 <    unique_jets[hist].resize(ngauss);
125 <    int nbinsX = hist->GetXaxis()->GetNbins();
126 <    int nbinsY = hist->GetYaxis()->GetNbins();
127 <    double XbinSize = (hist->GetXaxis()->GetXmax()
128 <                       - hist->GetXaxis()->GetXmin())
129 <      / static_cast<double>(nbinsX);
130 <    double YbinSize = (hist->GetYaxis()->GetXmax()
131 <                       - hist->GetYaxis()->GetXmin())
132 <      / static_cast<double>(nbinsY);
133 <    for (int i = 0; i < ngauss; i++) {
134 <      double N, mu_x, mu_y, sig, err, lo, hi;
135 <      int iuint;
136 <      TString name;
137 <      gMinuit->mnpout(4*i, name, N, err, lo, hi, iuint);
138 <      gMinuit->mnpout(4*i + 1, name, mu_x, err, lo, hi, iuint);
139 <      gMinuit->mnpout(4*i + 2, name, mu_y, err, lo, hi, iuint);
140 <      gMinuit->mnpout(4*i + 3, name, sig, err, lo, hi, iuint);
141 <      for (int j = 0; j < i; j++) {
142 <        double N2, mu_x2, mu_y2, sig2;
143 <        gMinuit->mnpout(4*j, name, N2, err, lo, hi, iuint);
144 <        gMinuit->mnpout(4*j + 1, name, mu_x2, err, lo, hi, iuint);
145 <        gMinuit->mnpout(4*j + 2, name, mu_y2, err, lo, hi, iuint);
146 <        gMinuit->mnpout(4*j + 3, name, sig2, err, lo, hi, iuint);
147 <        double _dist_sq = (mu_x2 - mu_x)*(mu_x2 - mu_x)
148 <          + (mu_y2 - mu_y)*(mu_y2 - mu_y);
149 <        if (_dist_sq < dist_sq)
150 <          dist_sq = _dist_sq;
151 <      }
152 <
153 <      jet j;
154 <      j.energy = N;
155 <      j.eta = mu_x; j.phi = mu_y;
156 <      unique_jets[hist][ngauss-1].push_back(j);
157 <    }
158 <  }
159 <
160 <  virtual void beginJob(const edm::EventSetup&);
161 <  virtual TH2D* make_histo(const edm::Event&, const edm::EventSetup&);
162 <  virtual jetfit::model_def& make_model_def(const edm::Event&,
163 <                                           const edm::EventSetup&,
164 <                                           TH2 *);
165 <  virtual void analyze_results(jetfit::results r,
166 <                               std::vector<jetfit::trouble> t, TH2 *);
167 <  vector<GenericParticle *> get_particles(const edm::Event&);
168 <  void fetchCandidateCollection(edm::Handle<reco::PFCandidateCollection>&,
169 <                                const edm::InputTag&, const edm::Event&) const;
170 <
171 <  fstream ofs;
172 <  edm::InputTag inputTagPFCandidates_;
173 <  int info_type_;
174 <  double smear_;
175 <  int smear_coord_;
25 >  virtual void beginJob(const edm::EventSetup &es);
26 >  virtual void analyze_results(HistoFitter::FitResults, std::vector<HistoFitter::Trouble>,
27 >                               TH2 *);
28   };
29  
178 map<TH2 *, vector< vector< JetFinderAnalyzer::jet > > >
179 JetFinderAnalyzer::unique_jets;
180
30   JetFinderAnalyzer::JetFinderAnalyzer(const edm::ParameterSet &pSet)
31    : JetFitAnalyzer(pSet) // this is important!
32   {
184  info_type_ = pSet.getUntrackedParameter("info_type", 0);
185
186  if (info_type_ == 1) {
187    inputTagPFCandidates_ = pSet.getParameter<edm::InputTag>("PFCandidates");
188  }
189
190  smear_ = pSet.getUntrackedParameter("smear", 0.02);
191  smear_coord_ = pSet.getUntrackedParameter("smear_coord", 0);
192  // 0 = eta-phi smear
193  // 1 = proper angle smear
194  set_user_minuit(jetfinder);
195 }
196
197 void
198 JetFinderAnalyzer::fetchCandidateCollection(edm::Handle<reco::PFCandidateCollection>& c,
199                                      const edm::InputTag& tag,
200                                      const edm::Event& iEvent) const {
201  
202  bool found = iEvent.getByLabel(tag, c);
203  
204  if(!found ) {
205    ostringstream  err;
206    err<<" cannot get PFCandidates: "
207       <<tag<<endl;
208    edm::LogError("PFCandidates")<<err.str();
209    throw cms::Exception( "MissingProduct", err.str());
210  }
211  
212 }
213
214 vector<GenericParticle *> JetFinderAnalyzer::get_particles(const edm::Event &evt) {
215 // fill unreduced histo
216  edm::Handle<edm::HepMCProduct> hRaw;
217  edm::Handle<reco::PFCandidateCollection> hPFlow;
218  if (info_type_ == 0) {
219    evt.getByLabel("source", hRaw);
220  }
221  if (info_type_ == 1) {
222    fetchCandidateCollection(hPFlow,
223                             inputTagPFCandidates_,
224                             evt);
225  }
226    
227  vector<GenericParticle *> particles;
228
229  switch (info_type_) {
230  case 0:
231    const HepMC::GenEvent *hmcEvt = hRaw->GetEvent();
232    for (HepMC::GenEvent::particle_const_iterator
233           pit = hmcEvt->particles_begin(); pit != hmcEvt->particles_end();
234         pit++) {
235      if ((*pit)->status() == 1) {
236        particles.push_back(new GenericParticle(**pit));
237      }
238    }
239    
240    break;
241  case 1:
242    for (unsigned i = 0; i < hPFlow->size(); i++) {
243      particles.push_back(new GenericParticle((*hPFlow)[i]));
244    }
245    break;
246  default:
247    cerr << "Unknown event type" << endl; // TODO use MessageLogger
248  }
249
250  return particles;
251 }
252
253 TH2D * JetFinderAnalyzer::make_histo(const edm::Event &evt, const edm::EventSetup&) {
254  ostringstream oss;
255  oss << "eta_phi_energy_unred"<<evt.id().event() << flush;
256  TH2D *unred_histo = new TH2D(oss.str().c_str(), oss.str().c_str(),
257                               600, -2.5, 2.5, 600, -PI, PI);
258
259  vector<GenericParticle *> particles = get_particles(evt);
260  for (int i = 0; i < particles.size(); i++) {
261    unred_histo->Fill(particles[i]->eta(),
262                      particles[i]->phi(),
263                      particles[i]->e());
264  }
265
266  // reduce histo
267  ostringstream oss2;
268  oss2 << "eta_phi_energy_red"<<evt.id().event() << flush;
269  edm::Service<TFileService> fs;
270  // draw cone of radius 0.5 around highest energy bin, reduce
271  double maxE = 0.0;
272  int max_i = 29, max_j = 29;
273  for (int i = 0; i < unred_histo->GetNbinsX(); i++) {
274    for (int j = 0; j < unred_histo->GetNbinsY(); j++) {
275      double E = unred_histo->GetBinContent(i+1, j+1);
276      if (E > maxE) {
277        maxE = E;
278        max_i = i;
279        max_j = j;
280      }
281    }
282  }
283  
284  double rcone = 0.5;
285  double Xlo = unred_histo->GetXaxis()->GetXmin();
286  double Xhi = unred_histo->GetXaxis()->GetXmax();
287  double Ylo = unred_histo->GetYaxis()->GetXmin();
288  double Yhi = unred_histo->GetYaxis()->GetXmax();
289  double XbinSize = (Xhi - Xlo) /
290    static_cast<double>(unred_histo->GetXaxis()->GetNbins());
291  double YbinSize = (Yhi - Ylo) /
292    static_cast<double>(unred_histo->GetYaxis()->GetNbins());
293  double max_x = (static_cast<double>(max_i) + 0.5) * XbinSize + Xlo;
294  double max_y = (static_cast<double>(max_j) + 0.5) * YbinSize + Ylo;
295  TH2D *histo = fs->make<TH2D>(oss2.str().c_str(), oss2.str().c_str(),
296                               60, max_x-rcone, max_x+rcone,
297                               60, max_y-rcone, max_y+rcone);
298
299  // create an unsmeared reduced histo
300  TH2D *histo_unsmeared = fs->make<TH2D>((oss2.str()+"_unsmeared").c_str(),
301                                         (oss2.str()+"_unsmeared").c_str(),
302                                         60, max_x-rcone, max_x+rcone,
303                                         60, max_y-rcone, max_y+rcone);
304  for (int i = 0; i < particles.size(); i++) {
305    double N = particles[i]->e();
306    double x = particles[i]->eta();
307    double y = particles[i]->phi();
308    histo_unsmeared->Fill(x, y, N);
309  }
310
311  // create a smeared reduced histo
312  // create a temporary 2D vector for smeared energies
313  XbinSize = (histo->GetXaxis()->GetXmax()
314              - histo->GetXaxis()->GetXmin()) /
315    static_cast<double>(histo->GetXaxis()->GetNbins());
316  YbinSize = (histo->GetYaxis()->GetXmax()
317              - histo->GetYaxis()->GetXmin()) /
318    static_cast<double>(histo->GetYaxis()->GetNbins());
319  vector< vector<double> > smeared(60, vector<double>(60, 0.0) );
320  switch (smear_coord_) {
321  case 1:
322    for (int i = 0; i < particles.size(); i++) {
323      double N = particles[i]->e();
324      double x = particles[i]->eta();
325      double y = particles[i]->phi();
326      // loop over bins and add Gaussian in proper angle to smeared
327      for (vector< vector<double> >::size_type i2 = 0; i2 < 60; i2++) {
328        for (vector< double >::size_type j2 = 0; j2 < 60; j2++) {
329          double eta = static_cast<double>((signed int)i2) * XbinSize +
330            max_x - rcone - x;
331          double phi = acos(cos(static_cast<double>((signed int)j2) * YbinSize +
332            max_y - rcone - y));
333          phi = sin(phi) > 0 ? phi : -phi;
334          
335          // transform eta, phi to proper angle
336          double theta = 2.0*atan(exp(-eta));
337          double iota = asin(sin(theta)*sin(phi));
338          
339          smeared[i2][j2] += (N*XbinSize*YbinSize/(2.0*PI*smear_*smear_))
340            * exp(-0.5*(theta*theta + iota*iota)/(smear_*smear_));
341        }
342      }
343    }
344    break;
345  case 0:
346  default:
347    for (int i = 0; i < particles.size(); i++) {
348      double N = particles[i]->e();
349      double x = particles[i]->eta();
350      double y = particles[i]->phi();
351      // loop over bins and add Gaussian to smeared
352      for (vector< vector<double> >::size_type i2 = 0; i2 < 60; i2++) {
353        for (vector< double >::size_type j2 = 0; j2 < 60; j2++) {
354          double eta = static_cast<double>((signed int)i2) * XbinSize
355            + max_x - rcone - x;
356          double phi = acos(cos(static_cast<double>((signed int)j2) * YbinSize
357            + max_y - rcone - y));
358          phi = sin(phi) > 0 ? phi : -phi;
359          smeared[i2][j2] += (N*XbinSize*YbinSize/(2.0*PI*smear_*smear_))
360            * exp(-0.5*(eta*eta + phi*phi)/(smear_*smear_));
361        }
362      }
363    }  
364  }
365  // set histogram to match smear vector
366  for (int i = 1; i <= 60; i++) {
367    for (int j = 1; j <= 60; j++) {
368      histo->SetBinContent(i, j, smeared[i-1][j-1]);
369    }
370  }
371
372  return histo;
373 }
374
375 void seed_with_CA(vector<GenericParticle *> gParticles, TH2 *histo,
376                  jetfit::model_def &_mdef) {
377  // create a PseudoJet vector
378  vector<PseudoJet> particles;
379  for (unsigned i = 0; i < gParticles.size(); i++) {
380    double x_max = (histo->GetXaxis()->GetXmax()
381                    + histo->GetXaxis()->GetXmin()) / 2.0;
382    double y_max = (histo->GetYaxis()->GetXmax()
383                    + histo->GetYaxis()->GetXmin()) / 2.0;
384    valarray<double> pmom(4);
385    pmom[0] = gParticles[i]->px();
386    pmom[1] = gParticles[i]->py();
387    pmom[2] = gParticles[i]->pz();
388    pmom[3] = gParticles[i]->e();
389    double eta = gParticles[i]->eta();
390    double phi = gParticles[i]->phi();
391    if ((eta - x_max)*(eta - x_max) + (phi - y_max)*(phi - y_max) < 0.25) {
392      PseudoJet j(pmom);
393      particles.push_back(j);
394    }
395  }
396
397  // choose a jet definition
398  double R = 0.2;
399  JetDefinition jet_def(cambridge_algorithm, R);
400
401  // run clustering and extract the jets
402  ClusterSequence cs(particles, jet_def);
403  vector<PseudoJet> jets = cs.inclusive_jets();
404
405  double XbinSize = (histo->GetXaxis()->GetXmax()
406                     - histo->GetXaxis()->GetXmin()) /
407    static_cast<double>(histo->GetXaxis()->GetNbins());
408  double YbinSize = (histo->GetYaxis()->GetXmax()
409                     - histo->GetYaxis()->GetXmin()) /
410    static_cast<double>(histo->GetYaxis()->GetNbins());
411
412  // seed with C-A jets
413  int ijset = 0;
414  for (unsigned ij = 0; ij < jets.size(); ij++) {
415    double N = jets[ij].e();
416    if (N > 50.0) {
417      _mdef.set_special_par(ijset, 0, N, _mdef.chisquare_error(N)*0.1,
418                            0.0, 1.0e6);
419      _mdef.set_special_par(ijset, 1, jets[ij].eta(), 0.01,
420                            0.0, 0.0);
421      double mdef_phi = jets[ij].phi() > PI ? jets[ij].phi() - 2*PI
422        : jets[ij].phi();
423      _mdef.set_special_par(ijset, 2, mdef_phi, 0.01,
424                            0.0, 0.0);
425      _mdef.set_special_par(ijset, 3, 0.1, 0.001, 0.0, 0.0);
426      ijset++;
427    }
428  }
429 }
430
431 jetfit::model_def& JetFinderAnalyzer::make_model_def(const edm::Event& evt,
432                                                 const edm::EventSetup&,
433                                                 TH2 *histo) {
434  class jf_model_def : public jetfit::model_def {
435  public:
436    virtual double chisquare_error(double E) {
437      return 0.97*E + 14.0;
438      // study from 08-27-09
439    }
440  };
441
442  jf_model_def *_mdef = new jf_model_def();
443  TFormula *formula = new TFormula("gaus2d",
444                                     "[0]*exp(-0.5*((x-[1])**2 + (y-[2])**2)/([3]**2))/(2*pi*[3]**2)");
445  _mdef->set_formula(formula);
446  _mdef->set_indiv_max_E(0);
447  _mdef->set_indiv_max_x(1);
448  _mdef->set_indiv_max_y(2);
449  _mdef->set_indiv_par(0, string("N"), 0.0, 0.0, 0.0, 1.0e6);
450  _mdef->set_indiv_par(1, string("mu_x"), 0.0, 0.0, 0.0, 0.0);
451  _mdef->set_indiv_par(2, string("mu_y"), 0.0, 0.0, 0.0, 0.0);
452  _mdef->set_indiv_par(3, string("sig"), 0.1, 0.001, 0.0, 0.0);
453
454  seed_with_CA(get_particles(evt), histo, *_mdef);
455
456  jetfit::set_model_def(_mdef);
457
458  // generate initial fit histogram
459  edm::Service<TFileService> fs;
460  TH2D *init_fit_histo = fs->make<TH2D>(("init_fit_"+string(histo->GetName()))
461                                        .c_str(),
462                                        ("Initial fit for "
463                                         +string(histo->GetName())).c_str(),
464                                        histo->GetXaxis()->GetNbins(),
465                                        histo->GetXaxis()->GetXmin(),
466                                        histo->GetXaxis()->GetXmax(),
467                                        histo->GetXaxis()->GetNbins(),
468                                        histo->GetXaxis()->GetXmin(),
469                                        histo->GetXaxis()->GetXmax());
470  double XbinSize = (histo->GetXaxis()->GetXmax()
471                     - histo->GetXaxis()->GetXmin()) /
472    static_cast<double>(histo->GetXaxis()->GetNbins());
473  double YbinSize = (histo->GetYaxis()->GetXmax()
474                     - histo->GetYaxis()->GetXmin()) /
475    static_cast<double>(histo->GetYaxis()->GetNbins());
476  double Xlo = histo->GetXaxis()->GetXmin();
477  double Xhi = histo->GetXaxis()->GetXmax();
478  double Ylo = histo->GetYaxis()->GetXmin();
479  double Yhi = histo->GetYaxis()->GetXmax();
480
481  for (int i = 0; i < 60; i++) {
482    for (int j = 0; j < 60; j++) {
483      double x = (static_cast<double>(i) + 0.5)*XbinSize + Xlo;
484      double y = (static_cast<double>(j) + 0.5)*YbinSize + Ylo;
485      double pval[256];
486      if (_mdef->get_n_special_par_sets() > 64) {
487        cerr << "Parameter overload" << endl;
488        return *_mdef;
489      }
490      else {
491        for (int is = 0; is < _mdef->get_n_special_par_sets(); is++) {
492          for (int ii = 0; ii < 4; ii++) {
493            double spval, sperr, splo, sphi;
494            _mdef->get_special_par(is, ii, spval, sperr, splo, sphi);
495            pval[4*is + ii] = spval;
496          }
497        }
498      }
499      jetfit::set_ngauss(_mdef->get_n_special_par_sets());
500      init_fit_histo->SetBinContent(i+1, j+1,
501                                    jetfit::fit_fcn(x, y, pval));
502    }
503  }
504
505  return *_mdef;
33   }
34  
35   void JetFinderAnalyzer::beginJob(const edm::EventSetup &es) {
509  ofs.open("jetfindlog.txt", ios::out);
510  if (ofs.fail()) {
511    cerr << "Opening jetfindlog.txt FAILED" << endl;
512  }
513  ofs << "Jetfinder log" << endl
514      << "=============" << endl << endl;
515 }
36  
37 < ostream& operator<<(ostream &out, jetfit::trouble t) {
518 <  string action, error_string;
519 <  
520 <  if (t.istat != 3) {
521 <    switch(t.occ) {
522 <    case jetfit::T_NULL:
523 <      action = "Program"; break;
524 <    case jetfit::T_SIMPLEX:
525 <      action = "SIMPLEX"; break;
526 <    case jetfit::T_MIGRAD:
527 <      action = "MIGRAD"; break;
528 <    case jetfit::T_MINOS:
529 <      action = "MINOS"; break;
530 <    default:
531 <      action = "Program"; break;
532 <    }
533 <
534 <    switch (t.istat) {
535 <    case 0:
536 <      error_string = "Unable to calculate error matrix"; break;
537 <    case 1:
538 <      error_string = "Error matrix a diagonal approximation"; break;
539 <    case 2:
540 <      error_string = "Error matrix not positive definite"; break;
541 <    case 3:
542 <      error_string = "Converged successfully"; break;
543 <    default:
544 <      ostringstream oss;
545 <      oss<<"Unknown status code "<<t.istat << flush;
546 <      error_string = oss.str(); break;
547 <    }
37 > }
38  
39 <    if (t.occ != jetfit::T_NULL)
40 <      out << action<<" trouble: "<<error_string;
41 <    else
42 <      out << "Not calculated" << endl;
39 > double evalFitFunction(HistoFitter::FitResults r, double x, double y) {
40 >  unsigned nFits = r.pars.size();
41 >  unsigned nGauss = r.pars[nFits-1].size() / 4;
42 >  double fitVal = 0.0;
43 >  for (unsigned i = 0; i < nGauss; i++) {
44 >    double N = r.pval[nFits-1][4*i];
45 >    double mu_x = r.pval[nFits-1][4*i + 1];
46 >    double mu_y = r.pval[nFits-1][4*i + 2];
47 >    double sig = r.pval[nFits-1][4*i + 3];
48 >
49 >    double rel_x = x - mu_x; double rel_y = y - mu_y;
50 >    fitVal += (N / 2.0 / M_PI / sig / sig)
51 >      * exp(-(rel_x * rel_x + rel_y * rel_y)/2.0/sig/sig);
52    }
53 <
555 <  return out;
53 >  return fitVal;
54   }
55  
56 < void JetFinderAnalyzer::analyze_results(jetfit::results r,
57 <                                     std::vector<jetfit::trouble> t,
56 > void JetFinderAnalyzer::analyze_results(HistoFitter::FitResults r,
57 >                                     std::vector<HistoFitter::Trouble> t,
58                                       TH2 *hist_orig) {
59 <  ofs << "Histogram "<<hist_orig->GetName() << endl;
562 <  for (int i = 0; i < unique_jets[hist_orig].size(); i++) {
563 <    ofs << "For "<<i+1<<" gaussians: " << endl
564 <        << t.at(i) << endl
565 <        << unique_jets[hist_orig][i].size()<<" unique jets found" << endl;
566 <    for (int j = 0; j < unique_jets[hist_orig][i].size(); j++) {
567 <      jet _jet = unique_jets[hist_orig][i][j];
568 <      ofs << "Jet "<<j<<": Energy = "<<_jet.energy<<", eta = "<<_jet.eta
569 <          << ", phi = "<<_jet.phi << endl;
570 <    }
571 <    ofs << endl;
572 <  }
573 <  ofs << endl;
574 <
575 <  // save fit function histograms to root file
59 >  // perform analysis of fit results
60    edm::Service<TFileService> fs;
61 <  for (vector< vector<double> >::size_type i = 0;
62 <       i < r.pval.size(); i++) {
63 <    jetfit::set_ngauss(r.pval[i].size() / 4);
64 <    TF2 *tf2 = new TF2("fit_func", jetfit::fit_fcn_TF2,
65 <                       hist_orig->GetXaxis()->GetXmin(),
66 <                       hist_orig->GetXaxis()->GetXmax(),
67 <                       hist_orig->GetYaxis()->GetXmin(),
68 <                       hist_orig->GetYaxis()->GetXmax(),
69 <                       r.pval[i].size());
70 <    for (vector<double>::size_type j = 0; j < r.pval[i].size(); j++) {
71 <      tf2->SetParameter(j, r.pval[i][j]);
72 <    }
73 <    ostringstream fit_histo_oss;
74 <    fit_histo_oss << hist_orig->GetName()<<"_fit_"<<i << flush;
75 <    tf2->SetNpx(hist_orig->GetXaxis()->GetNbins());
76 <    tf2->SetNpy(hist_orig->GetYaxis()->GetNbins());
77 <    TH2D *fit_histo = fs->make<TH2D>(fit_histo_oss.str().c_str(),
78 <                                     fit_histo_oss.str().c_str(),
79 <                                     hist_orig->GetXaxis()->GetNbins(),
80 <                                     hist_orig->GetXaxis()->GetXmin(),
81 <                                     hist_orig->GetXaxis()->GetXmax(),
82 <                                     hist_orig->GetYaxis()->GetNbins(),
599 <                                     hist_orig->GetYaxis()->GetXmin(),
600 <                                     hist_orig->GetYaxis()->GetXmax());
601 <    TH1 *tf2_histo = tf2->CreateHistogram();
602 <    double XbinSize = (fit_histo->GetXaxis()->GetXmax()
603 <                       - fit_histo->GetXaxis()->GetXmin())
604 <      / static_cast<double>(fit_histo->GetXaxis()->GetNbins());
605 <    double YbinSize = (fit_histo->GetYaxis()->GetXmax()
606 <                       - fit_histo->GetYaxis()->GetXmin())
607 <      / static_cast<double>(fit_histo->GetYaxis()->GetNbins());
608 <    for (int ih = 0; ih < tf2->GetNpx(); ih++) {
609 <      for (int jh = 0; jh < tf2->GetNpy(); jh++) {
610 <        fit_histo->SetBinContent(ih+1, jh+1,
611 <                        tf2_histo->GetBinContent(ih+1, jh+1)
612 <                                 * XbinSize * YbinSize);
613 <      }
61 >  TH2D *fitHisto = fs->make<TH2D>((std::string(hist_orig->GetName())+"_fit").c_str(),
62 >                            ("Fitted distribution to "
63 >                             +std::string(hist_orig->GetName())).c_str(),
64 >                            hist_orig->GetNbinsX(),
65 >                            hist_orig->GetXaxis()->GetXmin(),
66 >                            hist_orig->GetXaxis()->GetXmax(),
67 >                            hist_orig->GetNbinsY(),
68 >                            hist_orig->GetYaxis()->GetXmin(),
69 >                            hist_orig->GetYaxis()->GetXmax());
70 >
71 >  double Xlo = fitHisto->GetXaxis()->GetXmin();
72 >  double Xhi = fitHisto->GetXaxis()->GetXmax();
73 >  double Ylo = fitHisto->GetYaxis()->GetXmin();
74 >  double Yhi = fitHisto->GetYaxis()->GetXmax();
75 >  double XbinSize = (Xhi - Xlo) / static_cast<double>(fitHisto->GetNbinsX());
76 >  double YbinSize = (Yhi - Ylo) / static_cast<double>(fitHisto->GetNbinsY());
77 >
78 >  for (int i = 1; i <= fitHisto->GetNbinsX(); i++) {
79 >    for (int j = 1; j <= fitHisto->GetNbinsY(); j++) {
80 >      double x = (static_cast<double>(i) - 0.5) * XbinSize + Xlo;
81 >      double y = (static_cast<double>(j) - 0.5) * YbinSize + Ylo;
82 >      fitHisto->SetBinContent(i, j, evalFitFunction(r, x, y) * XbinSize * YbinSize);
83      }
84    }
85  
86 <  // save results to file
87 <  ostringstream res_tree_oss, rt_title_oss;
88 <  res_tree_oss << hist_orig->GetName()<<"_results" << flush;
89 <  rt_title_oss << "Fit results for "<<hist_orig->GetName() << flush;
86 >  // save fit results to an ntuple
87 >  TNtuple *rNtuple = fs->make<TNtuple>((std::string(hist_orig->GetName())+"_results").c_str(),
88 >                                       ("Fit results for "+std::string(hist_orig->GetName())).c_str(),
89 >                                       "N:mu_x:mu_y:sigma");
90 >  unsigned nFits = r.pval.size();
91 >  unsigned nGauss = r.pval[nFits-1].size() / 4;
92 >  for (unsigned i = 0; i < nGauss; i++) {
93 >    rNtuple->Fill(r.pval[nFits-1][4*i], r.pval[nFits-1][4*i+1], r.pval[nFits-1][4*i+2],
94 >                  r.pval[nFits-1][4*i+3]);
95 >  }
96 >
97 >  // save chisquares to ntuple
98 >  for (unsigned i = 0; i < r.chisquare.size(); i++) {
99 >    ostringstream csNtupleName, csNtupleTitle;
100 >    csNtupleName << hist_orig->GetName() << "_chi2_" << i << flush;
101 >    csNtupleTitle << "Chisquare "<<i<<" for histo "<<hist_orig->GetName()
102 >                  << flush;
103 >    TNtuple *csNtuple = fs->make<TNtuple>(csNtupleName.str().c_str(),
104 >                                          csNtupleTitle.str().c_str(),
105 >                                          "chisq");
106 >    csNtuple->Fill(r.chisquare[i]);
107 >  }
108   }
109  
110   DEFINE_FWK_MODULE(JetFinderAnalyzer);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines