def getMinMax(histosOrGraphs=[]) : def mM(obj) : cname = obj.Class().GetName() if cname.startswith('TH1') : return getMinMaxFromTH1(obj) elif cname.startswith('TGraphAsymmErrors') : return getMinMaxFromTGraphAsymmErrors(obj) elif cname.startswith('TGraph') : return getMinMaxFromTGraph(obj) ms, Ms = verticalSlice([mM(o) for o in histosOrGraphs if o]) return min(ms), max(Ms)
def main(): parser = optparse.OptionParser(usage=usage) parser.add_option('-i', '--input-dir', default='./out/fakerate') parser.add_option('-o', '--output-dir', default='./out/tight_variables_plots', help='dir for plots') parser.add_option('-l', '--lepton', default='el', help='either el or mu') parser.add_option('-r', '--region', help='one of the regions for which we saved the fake ntuples') parser.add_option('-t', '--tag', help='tag used to select the input files (e.g. Apr_04)') parser.add_option('-f', '--fill-histos', action='store_true', default=False, help='force fill (default only if needed)') parser.add_option('-v', '--verbose', action='store_true', default=False) (options, args) = parser.parse_args() inputDir = options.input_dir outputDir = options.output_dir lepton = options.lepton region = options.region tag = options.tag verbose = options.verbose if not tag : parser.error('tag is a required option') if lepton not in ['el', 'mu'] : parser.error("invalid lepton '%s'"%lepton) filestems, treenames = utils.verticalSlice(fakeu.tupleStemsAndNames) regions = filestems assert region in regions,"invalid region '%s', must be one of %s"%(region, str(regions)) templateInputFilename = "*_%(region)s_tuple_%(tag)s.root" % {'tag':tag, 'region':region} templateOutputFilename = "%(region)s_%(l)s_tight_plots.root" % {'region':region, 'l':lepton} treeName = treenames[regions.index(region)] outputDir = outputDir+'/'+region+'/'+lepton # split the output in subdirectories, so we don't overwrite things mkdirIfNeeded(outputDir) outputFileName = os.path.join(outputDir, templateOutputFilename) cacheFileName = outputFileName.replace('.root', '_'+region+'_cache.root') doFillHistograms = options.fill_histos or not os.path.exists(cacheFileName) optionsToPrint = ['inputDir', 'outputDir', 'region', 'tag', 'doFillHistograms'] if verbose : print "working from %s"%os.getcwd() print "being called as : %s"%' '.join(os.sys.argv) print "options:\n"+'\n'.join(["%s : %s"%(o, eval(o)) for o in optionsToPrint]) # collect inputs if verbose : print 'input files ',os.path.join(inputDir, templateInputFilename) tupleFilenames = glob.glob(os.path.join(inputDir, templateInputFilename)) samples = setSameGroupForAllData(fastSamplesFromFilenames(tupleFilenames, verbose)) if not samples : samples = [guessSampleFromFilename(f) for f in tupleFilenames] # if the fast guess didn't work, try the slow one samplesPerGroup = collections.defaultdict(list) filenamesPerGroup = collections.defaultdict(list) for s, f in zip(samples, tupleFilenames) : samplesPerGroup[s.group].append(s) filenamesPerGroup[s.group].append(f) vars = ['pt','eta','d0sig','z0SinTheta','etCone','ptCone','etConeCorr','ptConeCorr'] vars += ['relEtConeStd', 'relPtConeStd', 'relEtConeMod', 'relPtConeMod'] groups = samplesPerGroup.keys() sources = leptonSources #fill histos if doFillHistograms : lepLabel = "(probe %s)"%lepton histosPerGroup = bookHistosPerGroup(vars, groups, lepLabel=lepLabel) histosPerSource = bookHistosPerSource(vars, sources, lepLabel=lepLabel) for group in groups: isData = isDataSample(group) filenames = filenamesPerGroup[group] histosThisGroup = histosPerGroup[group] chain = r.TChain(treeName) [chain.Add(fn) for fn in filenames] print "%s : %d entries"%(group, chain.GetEntries()) fillHistos(chain, histosThisGroup, histosPerSource, isData, lepton, group, verbose) writeHistos(cacheFileName, {'perGroup':histosPerGroup, 'perSource':histosPerSource}, verbose) # compute scale factors histosPerGroup = fetchHistos(cacheFileName, histoNames(vars, groups), verbose) histosPerSource = fetchHistos(cacheFileName, histoNames(vars, sources), verbose) plotStackedHistos(histosPerGroup, outputDir+'/by_group', region, colors=SampleUtils.colors, verbose=verbose) plotStackedHistos(histosPerSource, outputDir+'/by_source', region, colors=fakeu.colorsFillSources(), verbose=verbose) plotIsoComparison(histosPerSource, outputDir+'/', region, lepton, verbose)
def main(): parser = optparse.OptionParser(usage=usage) parser.add_option('-i', '--input-dir', default='./out/fakerate') parser.add_option('-o', '--output-dir', default='./out/fake_scale_factor', help='dir for plots') parser.add_option('-l', '--lepton', default='el', help='either el or mu') parser.add_option('-r', '--region', help='one of the regions for which we saved the fake ntuples') parser.add_option('-t', '--tag', help='tag used to select the input files (e.g. Apr_04)') parser.add_option('-T', '--tight-def', help='on-the-fly tight def, one of defs in fakeUtils.py: fakeu.lepIsTight_std, etc.') parser.add_option('-f', '--fill-histos', action='store_true', default=False, help='force fill (default only if needed)') parser.add_option('-v', '--verbose', action='store_true', default=False) (options, args) = parser.parse_args() inputDir = options.input_dir outputDir = options.output_dir lepton = options.lepton region = options.region tag = options.tag verbose = options.verbose if not tag : parser.error('tag is a required option') if lepton not in ['el', 'mu'] : parser.error("invalid lepton '%s'"%lepton) filestems, treenames = utils.verticalSlice(fakeu.tupleStemsAndNames) regions = filestems assert region in regions,"invalid region '%s', must be one of %s"%(region, str(regions)) templateInputFilename = "*_%(region)s_tuple_%(tag)s.root" % {'tag':tag, 'region':region} templateOutputFilename = "%(region)s_%(l)s_scale_histos.root" % {'region':region, 'l':lepton} treeName = treenames[regions.index(region)] outputDir = outputDir+'/'+region+'/'+lepton # split the output in subdirectories, so we don't overwrite things mkdirIfNeeded(outputDir) outputFileName = os.path.join(outputDir, templateOutputFilename) cacheFileName = outputFileName.replace('.root', '_'+region+'_cache.root') doFillHistograms = options.fill_histos or not os.path.exists(cacheFileName) onthefly_tight_def = eval(options.tight_def) if options.tight_def else None # eval will take care of aborting on typos optionsToPrint = ['inputDir', 'outputDir', 'region', 'tag', 'doFillHistograms', 'onthefly_tight_def'] if verbose : print "working from %s"%os.getcwd() print "being called as : %s"%' '.join(os.sys.argv) print "options:\n"+'\n'.join(["%s : %s"%(o, eval(o)) for o in optionsToPrint]) # collect inputs if verbose : print 'input files ',os.path.join(inputDir, templateInputFilename) tupleFilenames = glob.glob(os.path.join(inputDir, templateInputFilename)) samples = setSameGroupForAllData(fastSamplesFromFilenames(tupleFilenames, verbose)) samplesPerGroup = collections.defaultdict(list) filenamesPerGroup = collections.defaultdict(list) mkdirIfNeeded(outputDir) for s, f in zip(samples, tupleFilenames) : samplesPerGroup[s.group].append(s) filenamesPerGroup[s.group].append(f) vars = ['mt0', 'mt1', 'pt0', 'pt1', 'eta1'] groups = samplesPerGroup.keys() #fill histos if doFillHistograms : start_time = time.clock() num_processed_entries = 0 histosPerGroup = bookHistos(vars, groups, region=region) histosPerSource = bookHistosPerSource(vars, leptonSources, region=region) histosPerGroupPerSource = bookHistosPerSamplePerSource(vars, groups, leptonSources, region=region) for group in groups: isData = isDataSample(group) filenames = filenamesPerGroup[group] if verbose: print " --- group : %s ---".format(group) print '\n\t'.join(filenames) histosThisGroup = histosPerGroup[group] histosThisGroupPerSource = dict((v, histosPerGroupPerSource[v][group]) for v in histosPerGroupPerSource.keys()) chain = r.TChain(treeName) [chain.Add(fn) for fn in filenames] if verbose: print "%s : %d entries"%(group, chain.GetEntries()) num_processed_entries += fillHistos(chain, histosThisGroup, histosPerSource, histosThisGroupPerSource, lepton, group, region, onthefly_tight_def=onthefly_tight_def, verbose=verbose) writeHistos(cacheFileName, histosPerGroup, histosPerSource, histosPerGroupPerSource, verbose) end_time = time.clock() delta_time = end_time - start_time if verbose: print ("processed {0:d} entries ".format(num_processed_entries) +"in "+("{0:d} min ".format(int(delta_time/60)) if delta_time>60 else "{0:.1f} s ".format(delta_time)) +"({0:.1f} kHz)".format(num_processed_entries/delta_time)) # compute scale factors histosPerGroup = fetchHistos(cacheFileName, histoNames(vars, groups, region), verbose) histosPerSource = fetchHistos(cacheFileName, histoNamesPerSource(vars, leptonSources, region), verbose) histosPerSamplePerSource = fetchHistos(cacheFileName, histoNamesPerSamplePerSource(vars, groups, leptonSources, region), verbose) plotStackedHistos(histosPerGroup, outputDir+'/by_group', region, verbose) plotStackedHistosSources(histosPerSource, outputDir+'/by_source', region, verbose) plotPerSourceEff(histosPerVar=histosPerSource, outputDir=outputDir+'/by_source', lepton=lepton, region=region, verbose=verbose) for g in groups: hps = dict((v, histosPerSamplePerSource[v][g])for v in vars) plotPerSourceEff(histosPerVar=hps, outputDir=outputDir, lepton=lepton, region=region, sample=g, verbose=verbose) hn_sf_eta = histoname_sf_vs_eta (lepton) hn_sf_pt = histoname_sf_vs_pt (lepton) hn_da_eta = histoname_data_fake_eff_vs_eta(lepton) hn_da_pt = histoname_data_fake_eff_vs_pt (lepton) objs_eta = subtractRealAndComputeScaleFactor(histosPerGroup, 'eta1', hn_sf_eta, hn_da_eta, outputDir, region, verbose) objs_pt = subtractRealAndComputeScaleFactor(histosPerGroup, 'pt1', hn_sf_pt, hn_da_pt, outputDir, region, verbose) rootUtils.writeObjectsToFile(outputFileName, dictSum(objs_eta, objs_pt), verbose) if verbose : print "saved scale factors to %s" % outputFileName