Пример #1
0
def extractBINS(configPy, var):
    """
	extractBINS( 'nameConfig.py', ['var1','var2'] ) --> cms.PSet.BINS, 'PT-like', 'ETA-like'

	"""

    #TODO: Better a temporary file
    try:
        shutil.copy(configPy, '_tmpPy.py')
    except IOError:
        message = '\033[1;31mError: There is no config File named %s\033[1;m' % configPy
        raise IOError, message
    # To be sure the first import is FWCore.ParameterSet.Config
    # in order to extract BINS
    _file = open('_tmpPy.py', 'r')
    _lines = _file.readlines()
    _file.close()
    _lines.insert(0, 'import FWCore.ParameterSet.Config as cms\n')
    _file = open('_tmpPy.py', 'w')
    _file.writelines(_lines)
    _file.close()
    # Append the working directory to do the import
    sys.path.append(os.getcwd())
    #------------------------------------------------------------

    try:
        from _tmpPy import BINS
    except ImportError:
        message = '\033[1;31mError: There is no BINS in %s file. Are you sure this is a config python to do the fit?\033[1;m' % configPy
        os.remove('_tmpPy.py')
        raise ImportError, message

    variables = BINS.parameterNames_()
    # Check if the variables introduced by the user are inside
    # the fit config python
    for i in var:
        if i not in variables:
            os.remove('_tmpPy.py')
            message = """\033[1;31mError: The variable %s is not in the parameter BINS of the config python %s. 
Check your config or change your input variable with --var option\033[1;m """ % (
                i, configPy)
            print message
            raise KeyError

    # All was fine. Remember: first variable is the pt-like (construct the weights respect it)
    PT = var[0]
    ETA = var[1]

    #bins = BINS
    try:
        os.remove('_tmpPy.py')
        os.remove('_tmpPy.pyc')
    except OSError:
        pass

    return BINS, PT, ETA
Пример #2
0
def extractBINS( configPy, var ):
	"""
	extractBINS( 'nameConfig.py', ['var1','var2'] ) --> cms.PSet.BINS, 'PT-like', 'ETA-like'

	"""

	#TODO: Better a temporary file
	try:
		shutil.copy( configPy, '_tmpPy.py')
	except IOError:
		message = '\033[1;31mError: There is no config File named %s\033[1;m' % configPy
		raise IOError, message
	# To be sure the first import is FWCore.ParameterSet.Config 
	# in order to extract BINS
	_file = open('_tmpPy.py','r')
	_lines = _file.readlines()
	_file.close()
	_lines.insert(0,'import FWCore.ParameterSet.Config as cms\n')
	_file = open('_tmpPy.py','w')
	_file.writelines(_lines)
	_file.close()
	# Append the working directory to do the import
	sys.path.append( os.getcwd() )
	#------------------------------------------------------------     
	
	try:
		from _tmpPy import BINS
	except ImportError:
		message = '\033[1;31mError: There is no BINS in %s file. Are you sure this is a config python to do the fit?\033[1;m' % configPy
		os.remove('_tmpPy.py')
		raise ImportError, message

	variables = BINS.parameterNames_()
	# Check if the variables introduced by the user are inside
	# the fit config python
	for i in var:
		if i not in variables:
			os.remove('_tmpPy.py')
			message = """\033[1;31mError: The variable %s is not in the parameter BINS of the config python %s. 
Check your config or change your input variable with --var option\033[1;m """ % ( i, configPy)
		        print message
                        raise KeyError

	# All was fine. Remember: first variable is the pt-like (construct the weights respect it)
	PT = var[0]
	ETA = var[1]

	#bins = BINS
	try:
		os.remove( '_tmpPy.py' )
		os.remove( '_tmpPy.pyc' )
	except OSError:
		pass

	return BINS,PT,ETA
Пример #3
0
def getWeightsFromFile(fileW,category,BINS,PT,ETA):
	"""
	getWeightsFromFile( ROOT.TFile, 'category', FWCore.ParameterSet.Config.BINS, 'PT', 'ETA' ) ->
	"""
	mapBinVal = {}
	weights = {}
	k = 0
	for i in xrange(len(BINS.__getattribute__(PT))-1):
		pt = (BINS.__getattribute__(PT)[i],BINS.__getattribute__(PT)[i+1])
		for j in xrange(len(BINS.__getattribute__(ETA))-1):
			eta = (BINS.__getattribute__(ETA)[j],BINS.__getattribute__(ETA)[j+1])
			weights[category+'_bin'+str(k)] = ( eta, pt, fileW.Get(category+'_bin'+str(k)) )
			try:
				weights[category+'_bin'+str(k)][2].GetXaxis().SetLimits( pt[0], pt[1] )  
			except AttributeError:
				# Then we are using a binning different of this one which contains the weight_out file
				message = """\033[1;31mError: The binning defined by the config python file is different than
the defined in the weights_out_*.root files. If your config file is correct,
run this script in another location (to avoid remove the weights_out_*.root 
files). These are the bins used by the config python you have introduced 
%s\033[1;m""" % str(BINS)
				print message
				raise AttributeError
			k += 1

	return weights
Пример #4
0
def getWeightsFromFile(fileW, category, BINS, PT, ETA):
    """
	getWeightsFromFile( ROOT.TFile, 'category', FWCore.ParameterSet.Config.BINS, 'PT', 'ETA' ) ->
	"""
    mapBinVal = {}
    weights = {}
    k = 0
    for i in xrange(len(BINS.__getattribute__(PT)) - 1):
        pt = (BINS.__getattribute__(PT)[i], BINS.__getattribute__(PT)[i + 1])
        for j in xrange(len(BINS.__getattribute__(ETA)) - 1):
            eta = (BINS.__getattribute__(ETA)[j],
                   BINS.__getattribute__(ETA)[j + 1])
            weights[category + '_bin' +
                    str(k)] = (eta, pt, fileW.Get(category + '_bin' + str(k)))
            try:
                weights[category + '_bin' + str(k)][2].GetXaxis().SetLimits(
                    pt[0], pt[1])
            except AttributeError:
                # Then we are using a binning different of this one which contains the weight_out file
                message = """\033[1;31mError: The binning defined by the config python file is different than
the defined in the weights_out_*.root files. If your config file is correct,
run this script in another location (to avoid remove the weights_out_*.root 
files). These are the bins used by the config python you have introduced 
%s\033[1;m""" % str(BINS)
                print message
                raise AttributeError
            k += 1

    return weights
Пример #5
0
def makeWeights(_files,treeName,category,_outputFile, BINS, PT, ETA):
	"""
	makeWeights( _fileDict, 'treename', 'category', 'outputfile' ) -> 
	"""
	ROOT.gROOT.SetBatch(1)

	#treeName = 'histoMuFromTk/fitter_tree'
	_trees = dict( [ ( name, _file.Get(treeName) ) for name,_file in _files.iteritems()] )
	#Check if in both files are the tree
	for _tree in _trees.itervalues():
		if not _tree:
			return None
	
	histos = {}
	weights = {}

	#-- The ':' token in A:B read as 'B conditioned to A' (look this unregular order)
	#-- The categories are datamembers which can be 1 or 0, a condition;
	#-- if we want to weight the pt-distribution of all probes for the L1Mu3 trigger
	#-- category, we must decided with respect which muonID category (Glb, TMLSAT, ...), then
	#-- reduce to a subset which the muonID category == 1 and calculate the weight of the
	#-- pt-distribution
	#-- The category variable can be A:B:C:..., the last one is the only one which we don't 
	#-- want to reduce (see find category)
	condCategory = ''
	storeCategory = 'weight'
	if category.find(':') != -1:
		_catList = category.split(':')
		#-- This for is to include the quality cuts and other possible categories
		for i in xrange(len(_catList)-1):
			condCategory += ' && '+_catList[i]+' == 1 '# BUG------> && '+triggerCat+' == 1' 
			storeCategory += '_'+_catList[i]

	instName = lambda k,pt : PT+'>>h_'+category+name+str(k)+'(50,'+str(pt[0])+','+str(pt[1])+')'
	cuts = lambda pt,eta: PT+' >= '+str(pt[0])+' && '+PT+' <'+str(pt[1])+\
			' && '+ETA+' >= '+str(eta[0])+' && '+ETA+' < '+str(eta[1])+condCategory
	#print cuts #--------------------------> PROVISONAL: PARECE QUE SE RECUPERAN LOS ESPECTROS DE LOS PASSING
	           #-------------------------->               NO DE LOS ALL
	k = 0
	for i in xrange(len(BINS.__getattribute__(PT))-1):
		pt = (BINS.__getattribute__(PT)[i],BINS.__getattribute__(PT)[i+1])
		for j in xrange(len(BINS.__getattribute__(ETA))-1):
			eta = (BINS.__getattribute__(ETA)[j],BINS.__getattribute__(ETA)[j+1])
			for name,_t in _trees.iteritems(): 
				N = _t.Draw( instName(k,pt),cuts(pt,eta) )
				histos[name] = ROOT.gDirectory.Get('h_'+category+name+str(k))
			print '  \033[1;34mDoing bin'+str(k)+' '+PT+'=('+str(pt[0])+','+str(pt[1])+') '+ETA+'=('+str(eta[0])+','+str(eta[1])+')\033[1;m'
			swap =  histos['numerator'].Clone(category+'_bin'+str(k))
			dummy = swap.Divide(histos['denominator'])
			weights[category+'_bin'+str(k)] =( (eta[0],eta[1]), (pt[0],pt[1]), ROOT.gDirectory.Get(category+'_bin'+str(k)) )
			#Acura els limits
			weights[category+'_bin'+str(k)][2].GetXaxis().SetLimits( pt[0], pt[1] )  
			#weights[category+'_bin'+str(k)][2].SetNormFactor(1)  
			k += 1
	_out = ROOT.TFile(_outputFile,'RECREATE')
	for name,(etaBins,ptBins,histo) in weights.iteritems():
		histo.Write()
	_out.Close()	
	return weights
Пример #6
0
def makeWeights(_files, treeName, category, _outputFile, BINS, PT, ETA):
    """
	makeWeights( _fileDict, 'treename', 'category', 'outputfile' ) -> 
	"""
    ROOT.gROOT.SetBatch(1)

    #treeName = 'histoMuFromTk/fitter_tree'
    _trees = dict([(name, _file.Get(treeName))
                   for name, _file in _files.iteritems()])
    #Check if in both files are the tree
    for _tree in _trees.itervalues():
        if not _tree:
            return None

    histos = {}
    weights = {}

    #-- The ':' token in A:B read as 'B conditioned to A' (look this unregular order)
    #-- The categories are datamembers which can be 1 or 0, a condition;
    #-- if we want to weight the pt-distribution of all probes for the L1Mu3 trigger
    #-- category, we must decided with respect which muonID category (Glb, TMLSAT, ...), then
    #-- reduce to a subset which the muonID category == 1 and calculate the weight of the
    #-- pt-distribution
    #-- The category variable can be A:B:C:..., the last one is the only one which we don't
    #-- want to reduce (see find category)
    condCategory = ''
    storeCategory = 'weight'
    if category.find(':') != -1:
        _catList = category.split(':')
        #-- This for is to include the quality cuts and other possible categories
        for i in xrange(len(_catList) - 1):
            condCategory += ' && ' + _catList[
                i] + ' == 1 '  # BUG------> && '+triggerCat+' == 1'
            storeCategory += '_' + _catList[i]

    instName = lambda k, pt: PT + '>>h_' + category + name + str(
        k) + '(50,' + str(pt[0]) + ',' + str(pt[1]) + ')'
    cuts = lambda pt,eta: PT+' >= '+str(pt[0])+' && '+PT+' <'+str(pt[1])+\
      ' && '+ETA+' >= '+str(eta[0])+' && '+ETA+' < '+str(eta[1])+condCategory
    #print cuts #--------------------------> PROVISONAL: PARECE QUE SE RECUPERAN LOS ESPECTROS DE LOS PASSING
    #-------------------------->               NO DE LOS ALL
    k = 0
    for i in xrange(len(BINS.__getattribute__(PT)) - 1):
        pt = (BINS.__getattribute__(PT)[i], BINS.__getattribute__(PT)[i + 1])
        for j in xrange(len(BINS.__getattribute__(ETA)) - 1):
            eta = (BINS.__getattribute__(ETA)[j],
                   BINS.__getattribute__(ETA)[j + 1])
            for name, _t in _trees.iteritems():
                N = _t.Draw(instName(k, pt), cuts(pt, eta))
                histos[name] = ROOT.gDirectory.Get('h_' + category + name +
                                                   str(k))
            print '  \033[1;34mDoing bin' + str(k) + ' ' + PT + '=(' + str(
                pt[0]) + ',' + str(pt[1]) + ') ' + ETA + '=(' + str(
                    eta[0]) + ',' + str(eta[1]) + ')\033[1;m'
            swap = histos['numerator'].Clone(category + '_bin' + str(k))
            dummy = swap.Divide(histos['denominator'])
            weights[category + '_bin' +
                    str(k)] = ((eta[0], eta[1]), (pt[0], pt[1]),
                               ROOT.gDirectory.Get(category + '_bin' + str(k)))
            #Acura els limits
            weights[category + '_bin' + str(k)][2].GetXaxis().SetLimits(
                pt[0], pt[1])
            #weights[category+'_bin'+str(k)][2].SetNormFactor(1)
            k += 1
    _out = ROOT.TFile(_outputFile, 'RECREATE')
    for name, (etaBins, ptBins, histo) in weights.iteritems():
        histo.Write()
    _out.Close()
    return weights