def deinit(self):
        # Name to use to store things
        suffix='' if self.suffix==None else '_%s'%self.suffix
        prefix='' if self.prefix==None else '%s_'%self.prefix
        name='%s%s%s'%(prefix,os.path.basename(self.name),suffix)
        
        # Prepare the output
        if self.output_type=='root':
            f=OutputFactory.getTFile()

        # Prepare stack
        hs=THStack()
        hs.SetTitle(self.bigtitle)
        hs.SetName(name)

        for hist in self.histograms:
            if hist.Integral()==0: continue
            if self.norm_mode=='1':
                hist.Scale(1./hist.Integral())
            hs.Add(hist)
        if hs.GetHists()==None: return

        # Draw
        c=TCanvas()
        if self.logy:
            c.SetLogy(True)

        hs.Draw('nostack')

        title=self.title
        if self.units!=None:
            title+=' (%s)'%self.units
        hs.GetXaxis().SetTitle(title)

        if len(self.histograms)>1:
            l=c.BuildLegend(.65,.65,.98,.95)
            l.Draw()
        c.Update()

        # Print it out
        outfileName="%s"%(name)
        outfileName=outfileName.replace('/','-')
        if self.output_type=='png':
            c.SaveAs("%s.png"%outfileName)
        elif self.output_type=='eps':
            c.SaveAs("%s.eps"%outfileName)
        elif self.output_type=='root':
            hs.Write()

        # Dump some stats, while we are there..
        print "Statistics:"
        for hist in self.histograms:
            print "\t%s\t%f\t%f"%(hist.GetTitle(),hist.GetMean(),hist.GetRMS())
        c.Close()
Example #2
0
    def run(self):
        OutputFactory.setOutputName(self.name)
        self.init()

        timing=Timing.Timing()

        for eventfileidx in range(len(self.eventfiles)):
            eventfile=self.eventfiles[eventfileidx]
            Variable.eventfile=eventfile
            Variable.event=None
            
            self.eventfile=eventfile

            # Initialzie the cutflow information for this event
            eventfile.cutflow_fh=OutputFactory.getTFile('cutflow_%d.root'%eventfileidx)
            for cutidx in range(len(self.cuts)):
                cut=self.cuts[cutidx]
                # Configure cuts
                cut.eventfile=eventfile
                cut.event=None

                # Create necessary histograms
                minval=cut.variable.minval if cut.variable!=None else 0.
                maxval=cut.variable.maxval if cut.variable!=None else 1.
                nbins=cut.variable.nbins if cut.variable!=None else 1
                title=cut.variable.title if cut.variable!=None and hasattr(cut.variable,'title') else ''
                xtitle='%s (%s)'%(title,cut.variable.units) if cut.variable!=None and hasattr(cut.variable,'units') else title
                cut.passed=TH1D('cut%02d_passed'%cutidx,'',
                                nbins,minval,maxval)
                cut.all=TH1D('cut%02d_all'%cutidx,'',
                                nbins,minval,maxval)
                cut.passed.SetXTitle(xtitle)
                cut.all.SetXTitle(xtitle)
                cut.count=0

            # Open the file
            eventfile.load_tree()
            if eventfile.tree==None:
                print "ERROR: Tree not found!"
                continue
            if eventfile.tree.GetEntries()==0:
                print 'Warning: Tree has no entries!'

            eventfile.tree.SetBranchStatus("*",0)
            
            gROOT.cd()

            # Clear the branch pointers in an event
            Event.branch_pointers={}
            Event.branch_type={}

            self.init_eventfile()

            print "********************************************************************************"
            print "* Event File: %s   Event Tree: %s       "%(eventfile.path,eventfile.treeName)
            print "* Number of Events: %d                  "%eventfile.tree.GetEntries()
            print "********************************************************************************"

            # Loop over every event
            events_passed=0
            events_processed=0
            
            nEvents=0
            if(self.nevents!=None):
                nEvents=self.nevents
            else:
                nEvents=eventfile.tree.GetEntries()

            for evt_idx in range(eventfile.tree.GetEntries()):
                events_processed+=1

                if events_processed>nEvents:
                    events_processed=nEvents
                    break

                self.event=eventfile.event(evt_idx)
                self.event.idx=evt_idx
                Variable.event=self.event

                print "=============================="
                print " Event: %d                    "%self.event.idx
                print "=============================="
                # Check for cuts..
                docut=False
                for cidx in range(len(self.cuts)):
                    cut=self.cuts[cidx]
                    cut.event=self.event

                    values=cut.variable.value() if cut.variable!=None else 0.
                    if(type(values)!=list): values=[values]
                    for value in values:
                        if value==None: continue
                        cut.all.Fill(value)
                    
                    if cut.cut()!=cut.invert:
                        docut=True
                        break
                    for value in values:
                        if value==None: continue
                        cut.passed.Fill(value)
                        cut.count+=1

                        
                if docut:
                    print "!!!! THIS EVENT HAS BEEN CUT !!!!"
                    continue
                else:
                    events_passed+=1
                print ""

                ## Run the user code
                timing.start()
                self.run_event()
                timing.end()

            if events_processed>0: eventfile.eff=1.0*events_passed/events_processed
            else: eventfile.eff=1.
            self.deinit_eventfile()
            # Print out a summary
            print 'Cut Flow:'
            self.eventfile.cutflow_fh.cd()
            for cut in self.cuts:
                cut.passed.Write()
                cut.all.Write()
                print '\tPassing cut %s: %d'%(cut.__class__.__name__,cut.count)
            print "Cut Efficiency: %d/%d = %f"%(events_passed,events_processed,eventfile.eff)

            eventfile.close()
        self.deinit()
        print '== End Statistics =='
        print 'Average Time Per Event: %s'%str(timing.average())
    def deinit(self):
        # Draw everything
        for variable in self.variables:
            c=TCanvas(variable.name,variable.name)
            self.store(c)

            if self.stack:
                variable.histogram.Draw()
            else:
                variable.histogram.Draw('nostack')

            # Build up the axis title
            title=variable.title
            if hasattr(variable,'units') and variable.units!='':
                title+=' (%s)'%variable.units
            variable.histogram.GetXaxis().SetTitle(title)

            # Set the big title
            variable.histogram.SetTitle(self.bigtitle)

            # Add a legend, if necessary
            if variable.histogram.GetHists().GetSize()>1: # Only bother with legend if have more
                                                          # than one event file
                l=c.BuildLegend(.65,.65,.98,.95)
                self.store(l)
                l.Draw()

            # Axis type
            if self.logy:
                # Figure out the best range to all of the events are seen on the log scale
                hist=variable.histogram.GetHistogram()
                binn=hist.GetNbinsX()
                binvals=[]
                for bin in range(binn):
                    binvals.append(None)
                
                for hist in variable.histogram.GetHists():
                    for bin in range(binn):
                        val=hist.GetBinContent(bin+1)
                        if val==0: continue # Only care about bins with something in it

                        if binvals[bin]==None:
                            binvals[bin]=val
                            continue

                        if self.stack:
                            binvals[bin]+=val
                        else:
                            if val<binvals[bin]:
                                binvals[bin]=val

                minval=None
                for bin in range(binn):
                    val=binvals[bin]
                    if val==None: continue
                    
                    if minval==None:
                        minval=val
                    else:
                        if val<minval:
                            minval=val
                        
                if minval!=None:
                    variable.histogram.SetMinimum(minval)

                # Set the log scale
                c.SetLogy(True)
                
            c.Update()

            # Print it out
            outfileName="%s-%s"%(self.name,variable.name)
            outfileName=outfileName.replace('/','-')
            if self.output_type=='png':
                c.SaveAs("%s.png"%outfileName)
            elif self.output_type=='eps':
                c.SaveAs("%s.eps"%outfileName)
            elif self.output_type=='root':
                f=OutputFactory.getTFile()
                f.cd()
                variable.histogram.SetName(variable.name)
                variable.histogram.Write()

            # Dump some stats, while we are there..
            print variable.title
            for hist in variable.histogram.GetHists():
                print "\t%s\t%f\t%f"%(hist.GetTitle(),hist.GetMean(),hist.GetRMS())