Skip to content

Commit

Permalink
Update recently changed python code to use python 2.6/2.7 constructs.
Browse files Browse the repository at this point in the history
futurize -1 -nw -x print_with_import .
  • Loading branch information
ericvaandering committed Aug 31, 2016
1 parent 5486c49 commit d60d023
Show file tree
Hide file tree
Showing 16 changed files with 43 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import collections
import Alignment.MillePedeAlignmentAlgorithm.mpslib.Mpslibclass as mpslib
from Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.helper import checked_out_MPS
from functools import reduce


def get_weight_configs(config):
Expand Down
4 changes: 2 additions & 2 deletions CondCore/Utilities/python/popcon2dropbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ def __init__( self, fileName ):

def authPath( self ):
apath = ''
if self.md.has_key('authenticationPath'):
if 'authenticationPath' in self.md:
apath = self.md.get('authenticationPath')
return apath

def authSys( self ):
asys = 1
if self.md.has_key('authenticationSys'):
if 'authenticationSys' in self.md:
asys = self.md.get('authenticationSystem')
return asys

Expand Down
2 changes: 1 addition & 1 deletion CondCore/Utilities/scripts/uploadConditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,7 +852,7 @@ def re_upload( options ):
def upload(options, arguments):
results = uploadAllFiles(options, arguments)

if not results.has_key('status'):
if 'status' not in results:
print 'Unexpected error.'
return -1
ret = results['status']
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ def unique(seq, keepstr=True):
except TypeError: # hashing didn't work, see if seq is sortable
try:
from itertools import groupby
s = sorted(enumerate(seq),key=lambda (i,v):(v,i))
return t(g.next() for k,g in groupby(s, lambda (i,v): v))
s = sorted(enumerate(seq),key=lambda i_v1:(i_v1[1],i_v1[0]))
return t(next(g) for k,g in groupby(s, lambda i_v: i_v[1]))
except: # not sortable, use brute force
seen = []
return t(c for c in seq if not (c in seen or seen.append(c)))
Expand Down
3 changes: 2 additions & 1 deletion EventFilter/L1TXRawToDigi/python/util/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
from getRunInfo import getRunsForDate, getRunsNewer, today, daysAgo, day, getFilesForRun, runGetDatasetsAvailable
from __future__ import absolute_import
from .getRunInfo import getRunsForDate, getRunsNewer, today, daysAgo, day, getFilesForRun, runGetDatasetsAvailable

5 changes: 3 additions & 2 deletions EventFilter/L1TXRawToDigi/python/util/rrClient.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import absolute_import
import re, json, datetime
from rrapi import RRApi, RRApiError
from .rrapi import RRApi, RRApiError

URL = "http://runregistry.web.cern.ch/runregistry/"

Expand Down Expand Up @@ -31,7 +32,7 @@ def getRunsNewer(run, minLumis):
else :
print "RunRegistry API 'app' != user, who knows why... :<"

except RRApiError, e:
except RRApiError as e:
print e

if __name__ == '__main__' :
Expand Down
2 changes: 1 addition & 1 deletion EventFilter/L1TXRawToDigi/python/util/rrapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def get(self, parts, data = None):
if re.search("json", resp.info().gettype()):
try:
return json.loads(rdata)
except TypeError, e:
except TypeError as e:
self.dprint(e)
return rdata
else:
Expand Down
2 changes: 1 addition & 1 deletion L1Trigger/L1THGCal/test/macros/drawTriggerCells.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def boxlines(box):
triggercell.center.y = treeTriggerCells.y
triggercell.center.z = treeTriggerCells.z
for cellid in treeTriggerCells.c_id:
if not cellid in cells: raise StandardError("Cannot find cell {0} in trigger cell".format(cellid))
if not cellid in cells: raise Exception("Cannot find cell {0} in trigger cell".format(cellid))
cell = cells[cellid]
triggercell.cells.append(cell)
triggercells[triggercell.id] = triggercell
Expand Down
4 changes: 2 additions & 2 deletions L1Trigger/L1THGCal/test/macros/drawTriggerModules.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def boxlines(box):
triggercell.center.y = treeTriggerCells.y
triggercell.center.z = treeTriggerCells.z
for cellid in treeTriggerCells.c_id:
if not cellid in cells: raise StandardError("Cannot find cell {0} in trigger cell".format(cellid))
if not cellid in cells: raise Exception("Cannot find cell {0} in trigger cell".format(cellid))
cell = cells[cellid]
triggercell.cells.append(cell)
triggercells[triggercell.id] = triggercell
Expand All @@ -177,7 +177,7 @@ def boxlines(box):
module.center.y = treeModules.y
module.center.z = treeModules.z
for cellid in treeModules.tc_id:
if not cellid in triggercells: raise StandardError("Cannot find trigger cell {0} in module".format(cellid))
if not cellid in triggercells: raise Exception("Cannot find trigger cell {0} in module".format(cellid))
cell = triggercells[cellid]
module.cells.append(cell)
modules[module.id] = module
Expand Down
4 changes: 2 additions & 2 deletions L1Trigger/L1THGCal/test/macros/drawTriggerModulesHex.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
triggercell.center.y = treeTriggerCells.y
triggercell.center.z = treeTriggerCells.z
for cellid in treeTriggerCells.c_id:
if not cellid in cells: raise StandardError("Cannot find cell {0} in trigger cell".format(cellid))
if not cellid in cells: raise Exception("Cannot find cell {0} in trigger cell".format(cellid))
cell = cells[cellid]
triggercell.cells.append(cell)
triggercells[triggercell.id] = triggercell
Expand All @@ -97,7 +97,7 @@
module.center.y = treeModules.y
module.center.z = treeModules.z
for cellid in treeModules.tc_id:
if not cellid in triggercells: raise StandardError("Cannot find trigger cell {0} in module".format(cellid))
if not cellid in triggercells: raise Exception("Cannot find trigger cell {0} in module".format(cellid))
cell = triggercells[cellid]
module.cells.append(cell)
modules[module.id] = module
Expand Down
6 changes: 3 additions & 3 deletions PhysicsTools/Heppy/python/analyzers/objects/JetAnalyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def __init__(self, cfg_ana, cfg_comp, looperName):
self.addJECShifts = self.cfg_ana.addJECShifts if hasattr(self.cfg_ana, 'addJECShifts') else 0
if self.recalibrateJets == "MC" : self.recalibrateJets = self.cfg_comp.isMC
elif self.recalibrateJets == "Data": self.recalibrateJets = not self.cfg_comp.isMC
elif self.recalibrateJets not in [True,False]: raise RuntimeError, "recalibrateJets must be any of { True, False, 'MC', 'Data' }, while it is %r " % self.recalibrateJets
elif self.recalibrateJets not in [True,False]: raise RuntimeError("recalibrateJets must be any of { True, False, 'MC', 'Data' }, while it is %r " % self.recalibrateJets)

calculateSeparateCorrections = getattr(cfg_ana,"calculateSeparateCorrections", False);
calculateType1METCorrection = getattr(cfg_ana,"calculateType1METCorrection", False);
Expand All @@ -82,7 +82,7 @@ def __init__(self, cfg_ana, cfg_comp, looperName):
doResidual = getattr(cfg_ana, 'applyL2L3Residual', 'Data')
if doResidual == "MC": doResidual = self.cfg_comp.isMC
elif doResidual == "Data": doResidual = not self.cfg_comp.isMC
elif doResidual not in [True,False]: raise RuntimeError, "If specified, applyL2L3Residual must be any of { True, False, 'MC', 'Data'(default)}"
elif doResidual not in [True,False]: raise RuntimeError("If specified, applyL2L3Residual must be any of { True, False, 'MC', 'Data'(default)}")
GT = getattr(cfg_comp, 'jecGT', mcGT if self.cfg_comp.isMC else dataGT)
# Now take care of the optional arguments
kwargs = { 'calculateSeparateCorrections':calculateSeparateCorrections,
Expand All @@ -104,7 +104,7 @@ def __init__(self, cfg_ana, cfg_comp, looperName):
elif (self.jetGammaDR == self.jetLepDR):
self.jetGammaLepDR = self.jetGammaDR
else:
raise RuntimeError, "DR for simultaneous cleaning of jets from leptons and photons is not defined, and dR(gamma, jet)!=dR(lep, jet)"
raise RuntimeError("DR for simultaneous cleaning of jets from leptons and photons is not defined, and dR(gamma, jet)!=dR(lep, jet)")
if(self.cfg_ana.doQG):
qgdefname="{CMSSW_BASE}/src/PhysicsTools/Heppy/data/pdfQG_AK4chs_13TeV_v2b.root"
self.qglcalc = QGLikelihoodCalculator(getattr(self.cfg_ana,"QGpath",qgdefname).format(CMSSW_BASE= os.environ['CMSSW_BASE']))
Expand Down
14 changes: 7 additions & 7 deletions PhysicsTools/Heppy/python/analyzers/objects/LeptonAnalyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ class LeptonAnalyzer( Analyzer ):
def __init__(self, cfg_ana, cfg_comp, looperName ):
super(LeptonAnalyzer,self).__init__(cfg_ana,cfg_comp,looperName)
if hasattr(self.cfg_ana, 'doMuScleFitCorrections'):
raise RuntimeError, "doMuScleFitCorrections is not supported. Please set instead doMuonScaleCorrections = ( 'MuScleFit', <name> )"
raise RuntimeError("doMuScleFitCorrections is not supported. Please set instead doMuonScaleCorrections = ( 'MuScleFit', <name> )")
if hasattr(self.cfg_ana, 'doRochesterCorrections'):
raise RuntimeError, "doRochesterCorrections is not supported. Please set instead doMuonScaleCorrections = ( 'Rochester', <name> )"
raise RuntimeError("doRochesterCorrections is not supported. Please set instead doMuonScaleCorrections = ( 'Rochester', <name> )")
if self.cfg_ana.doMuonScaleCorrections:
algo, options = self.cfg_ana.doMuonScaleCorrections
if algo == "Kalman":
Expand All @@ -41,11 +41,11 @@ def __init__(self, cfg_ana, cfg_comp, looperName ):
elif algo == "MuScleFit":
print "WARNING: the MuScleFit correction in heppy is still from Run 1 (and probably no longer functional)"
if options not in [ "prompt", "prompt-sync", "rereco", "rereco-sync" ]:
raise RuntimeError, 'MuScleFit correction name must be one of [ "prompt", "prompt-sync", "rereco", "rereco-sync" ] '
raise RuntimeError('MuScleFit correction name must be one of [ "prompt", "prompt-sync", "rereco", "rereco-sync" ] ')
rereco = ("prompt" not in self.cfg_ana.doMuScleFitCorrections)
sync = ("sync" in self.cfg_ana.doMuScleFitCorrections)
self.muonScaleCorrector = MuScleFitCorr(cfg_comp.isMC, rereco, sync)
else: raise RuntimeError, "Unknown muon scale correction algorithm"
else: raise RuntimeError("Unknown muon scale correction algorithm")
else:
self.muonScaleCorrector = None
#FIXME: only Embedded works
Expand Down Expand Up @@ -290,7 +290,7 @@ def makeAllMuons(self, event):
elif aeta < 2.200: mu.EffectiveArea03 = 0.0433
else: mu.EffectiveArea03 = 0.0577
mu.EffectiveArea04 = 0 # not computed
else: raise RuntimeError, "Unsupported value for mu_effectiveAreas: can only use Data2012 (rho: ?) and Phys14_25ns_v1 or Spring15_25ns_v1 (rho: fixedGridRhoFastjetAll)"
else: raise RuntimeError("Unsupported value for mu_effectiveAreas: can only use Data2012 (rho: ?) and Phys14_25ns_v1 or Spring15_25ns_v1 (rho: fixedGridRhoFastjetAll)")
# Attach the vertex to them, for dxy/dz calculation
for mu in allmuons:
mu.associatedVertex = event.goodVertices[0] if len(event.goodVertices)>0 else event.vertices[0]
Expand Down Expand Up @@ -386,7 +386,7 @@ def makeAllElectrons(self, event):
else: ele.EffectiveArea03 = 0.2687
# warning: EAs not computed for cone DR=0.4 yet. Do not correct
ele.EffectiveArea04 = 0.0
else: raise RuntimeError, "Unsupported value for ele_effectiveAreas: can only use Data2012 (rho: ?), Phys14_v1 and Spring15_v1 (rho: fixedGridRhoFastjetAll)"
else: raise RuntimeError("Unsupported value for ele_effectiveAreas: can only use Data2012 (rho: ?), Phys14_v1 and Spring15_v1 (rho: fixedGridRhoFastjetAll)")

# Electron scale calibrations
if self.cfg_ana.doElectronScaleCorrections:
Expand Down Expand Up @@ -469,7 +469,7 @@ def attachMiniIsolation(self, mu):
mu.miniAbsIsoPU = self.IsolationComputer.puAbsIso(mu.physObj, mu.miniIsoR, 0.015 if what == "eleE" else 0.0, 0.0,self.IsolationComputer.selfVetoNone);
mu.miniAbsIsoNeutral = max(0.0, mu.miniAbsIsoNeutral - 0.5*mu.miniAbsIsoPU)
elif puCorr != 'raw':
raise RuntimeError, "Unsupported miniIsolationCorr name '" + puCorr + "'! For now only 'rhoArea', 'deltaBeta', 'raw', 'weights' are supported (and 'weights' is not tested)."
raise RuntimeError("Unsupported miniIsolationCorr name '" + puCorr + "'! For now only 'rhoArea', 'deltaBeta', 'raw', 'weights' are supported (and 'weights' is not tested).")

mu.miniAbsIso = mu.miniAbsIsoCharged + mu.miniAbsIsoNeutral
mu.miniRelIso = mu.miniAbsIso/mu.pt()
Expand Down
2 changes: 1 addition & 1 deletion PhysicsTools/Heppy/python/analyzers/objects/METAnalyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ def makeMETs(self, event):
setattr(event,"met_raw.upara_gamma"+self.cfg_ana.collectionPostFix, self.met_raw.upara_gamma)
setattr(event,"met_raw.uperp_gamma"+self.cfg_ana.collectionPostFix, self.met_raw.uperp_gamma)

if hasattr(event,"met"+self.cfg_ana.collectionPostFix): raise RuntimeError, "Event already contains met with the following postfix: "+self.cfg_ana.collectionPostFix
if hasattr(event,"met"+self.cfg_ana.collectionPostFix): raise RuntimeError("Event already contains met with the following postfix: "+self.cfg_ana.collectionPostFix)
setattr(event, "met"+self.cfg_ana.collectionPostFix, self.met)
if self.cfg_ana.doMetNoPU: setattr(event, "metNoPU"+self.cfg_ana.collectionPostFix, self.metNoPU)
setattr(event, "met_sig"+self.cfg_ana.collectionPostFix, self.met_sig)
Expand Down
14 changes: 7 additions & 7 deletions PhysicsTools/Heppy/python/physicsobjects/Electron.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,9 @@ def mvaRun2( self, name, debug = False ):
if name == "NonTrigSpring15MiniAOD" and self.physObj.hasUserFloat("ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Values"):
self._mvaRun2[name] = self.physObj.userFloat("ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Values")
return self._mvaRun2[name]
if name not in ElectronMVAID_ByName: raise RuntimeError, "Unknown electron run2 mva id %s (known ones are: %s)\n" % (name, ElectronMVAID_ByName.keys())
if self.associatedVertex == None: raise RuntimeError, "You need to set electron.associatedVertex before calling any MVA"
if self.rho == None: raise RuntimeError, "You need to set electron.rho before calling any MVA"
if name not in ElectronMVAID_ByName: raise RuntimeError("Unknown electron run2 mva id %s (known ones are: %s)\n" % (name, ElectronMVAID_ByName.keys()))
if self.associatedVertex == None: raise RuntimeError("You need to set electron.associatedVertex before calling any MVA")
if self.rho == None: raise RuntimeError("You need to set electron.rho before calling any MVA")
# -v---- below is correct in Heppy 74X, but probably not functional anyway
self._mvaRun2[name] = ElectronMVAID_ByName[name](self.physObj, self.associatedVertex, self.rho, True, debug)
# -v---- below would be correct for CMGTools 74X witht the updated Spring15 MVA electron ID
Expand Down Expand Up @@ -250,7 +250,7 @@ def mvaIDRun2(self, name, wp):
if (eta < 0.8) : return self.mvaRun2(name) > 0.73;
elif (eta < 1.479): return self.mvaRun2(name) > 0.57;
else : return self.mvaRun2(name) > 0.05;
else: raise RuntimeError, "Ele MVA ID Working point not found"
else: raise RuntimeError("Ele MVA ID Working point not found")
elif name == "NonTrigPhys14Fix":
if wp == "HZZ":
if self.pt() <= 10:
Expand All @@ -261,7 +261,7 @@ def mvaIDRun2(self, name, wp):
if eta < 0.8 : return self.mvaRun2(name) > -0.652;
elif eta < 1.479: return self.mvaRun2(name) > -0.701;
else : return self.mvaRun2(name) > -0.350;
else: raise RuntimeError, "Ele MVA ID Working point not found"
else: raise RuntimeError("Ele MVA ID Working point not found")
elif name in ("NonTrigSpring15","NonTrigSpring15MiniAOD"):
if wp=="VLoose":
if self.pt() <= 10:
Expand Down Expand Up @@ -311,8 +311,8 @@ def mvaIDRun2(self, name, wp):
if eta < 0.8: return self.mvaRun2(name) > -0.083313
elif eta < 1.479: return self.mvaRun2(name) > -0.235222
else: return self.mvaRun2(name) > -0.67099
else: raise RuntimeError, "Ele MVA ID Working point not found"
else: raise RuntimeError, "Ele MVA ID type not found"
else: raise RuntimeError("Ele MVA ID Working point not found")
else: raise RuntimeError("Ele MVA ID type not found")



Expand Down
2 changes: 1 addition & 1 deletion PhysicsTools/Heppy/python/physicsobjects/Jet.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def jetID(self,name=""):
if name == "PAG_monoID_Loose": return (eta<3.0 and chf>0.05 and nhf<0.7 and phf<0.8);
if name == "PAG_monoID_Tight": return (eta<3.0 and chf>0.2 and nhf<0.7 and phf<0.7);

raise RuntimeError, "jetID '%s' not supported" % name
raise RuntimeError("jetID '%s' not supported" % name)

def looseJetId(self):
'''PF Jet ID (loose operation point) [method provided for convenience only]'''
Expand Down
14 changes: 7 additions & 7 deletions PhysicsTools/HeppyCore/python/utils/diclist.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,24 @@ def add( self, key, value ):
self.append(value)

def __getitem__(self, index):
'''index can be a dictionary key, or an integer specifying
'''index can be a dictionary key, or an integer specifying
the rank of the value to be accessed
'''
try:
# if index is an integer (the rank), use the list.
# if index is an integer (the rank), use the list.
return super(diclist, self).__getitem__(index)
except TypeError, ValueError:
except (TypeError, ValueError):
# else it's the dictionary key.
# use the internal dictionary to get the index,
# use the internal dictionary to get the index,
# and return the corresponding value from the list
return super(diclist, self).__getitem__( self.dico[index] )

def __setitem__(self, index, value):
'''These functions are quite risky...'''
try:
return super(diclist, self).__setitem__(index, value)
except TypeError as ValueError:
return super(diclist, self).__setitem__( self.dico[index], value )





0 comments on commit d60d023

Please sign in to comment.