Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Load deformations from HipPy alignments in alignment validation tool #20062

Merged
merged 2 commits into from Aug 22, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
175 changes: 90 additions & 85 deletions Alignment/OfflineValidation/python/TkAlAllInOneTool/alignment.py
Expand Up @@ -3,7 +3,7 @@
import re

import configTemplates
from helperFunctions import replaceByMap, parsecolor, parsestyle
from helperFunctions import conddb, parsecolor, parsestyle, replaceByMap
from TkAlExceptions import AllInOneError

class Alignment(object):
Expand Down Expand Up @@ -37,7 +37,7 @@ def __init__(self, name, config, runGeomComp = "1"):
raise AllInOneError("section %s not found. Please define the "
"alignment!"%section)
config.checkInput(section,
knownSimpleOptions = ['globaltag', 'style', 'color', 'title', 'mp', 'mp_alignments', 'mp_deformations', 'hp', 'sm'],
knownSimpleOptions = ['globaltag', 'style', 'color', 'title', 'mp', 'mp_alignments', 'mp_deformations', 'hp', 'hp_alignments', 'hp_deformations', 'sm', 'sm_alignments', 'sm_deformations'],
knownKeywords = ['condition'])
self.name = name
if config.exists(section,"title"):
Expand All @@ -59,11 +59,11 @@ def __init__(self, name, config, runGeomComp = "1"):

self.color = str(parsecolor(self.color))
self.style = str(parsestyle(self.style))

def __shorthandExists(self, theRcdName, theShorthand):
"""Method which checks, if `theShorthand` is a valid shorthand for the
given `theRcdName`.

Arguments:
- `theRcdName`: String which specifies the database record.
- `theShorthand`: String which specifies the shorthand to check.
Expand All @@ -78,60 +78,94 @@ def __shorthandExists(self, theRcdName, theShorthand):
def __getConditions( self, theConfig, theSection ):
conditions = []
for option in theConfig.options( theSection ):
if option in ("mp", "mp_alignments", "mp_deformations"):
if option in ("mp", "mp_alignments", "mp_deformations", "hp", "hp_alignments", "hp_deformations", "sm", "sm_alignments", "sm_deformations"):
matches = [re.match(_, option) for _ in ("^(..)$", "^(..)_alignments$", "^(..)_deformations$")]
assert sum(bool(_) for _ in matches) == 1, option
condPars = theConfig.get(theSection, option).split(",")
condPars = [_.strip() for _ in condPars]
if len(condPars) == 1:
number, = condPars
jobm = None
elif len(condPars) == 2:
number, jobm = condPars
else:
raise AllInOneError("Up to 2 arguments accepted for {} (job number, and optionally jobm index)".format(option))

if option == "mp":
if matches[0]:
alignments = True
deformations = True
elif option == "mp_alignments":
elif matches[1]:
alignments = True
deformations = False
option = "mp"
elif option == "mp_deformations":
option = matches[1].group(1)
elif matches[2]:
alignments = False
deformations = True
option = "mp"
option = matches[2].group(1)
else:
assert False

folder = "/afs/cern.ch/cms/CAF/CMSALCA/ALCA_TRACKERALIGN/MP/MPproduction/{}{}/".format(option, number)
if not os.path.exists(folder):
raise AllInOneError(folder+" does not exist.")
folder = os.path.join(folder, "jobData")
jobmfolders = set()
if jobm is None:
for filename in os.listdir(folder):
if re.match("jobm([0-9]*)", filename) and os.path.isdir(os.path.join(folder, filename)):
jobmfolders.add(filename)
if len(jobmfolders) == 0:
raise AllInOneError("No jobm or jobm(number) folder in {}".format(folder))
elif len(jobmfolders) == 1:
folder = os.path.join(folder, jobmfolders.pop())
if option == "mp":
if len(condPars) == 1:
number, = condPars
jobm = None
elif len(condPars) == 2:
number, jobm = condPars
else:
raise AllInOneError("Up to 2 arguments accepted for {} (job number, and optionally jobm index)".format(option))

folder = "/afs/cern.ch/cms/CAF/CMSALCA/ALCA_TRACKERALIGN/MP/MPproduction/{}{}/".format(option, number)
if not os.path.exists(folder):
raise AllInOneError(folder+" does not exist.")
folder = os.path.join(folder, "jobData")
jobmfolders = set()
if jobm is None:
for filename in os.listdir(folder):
if re.match("jobm([0-9]*)", filename) and os.path.isdir(os.path.join(folder, filename)):
jobmfolders.add(filename)
if len(jobmfolders) == 0:
raise AllInOneError("No jobm or jobm(number) folder in {}".format(folder))
elif len(jobmfolders) == 1:
folder = os.path.join(folder, jobmfolders.pop())
else:
raise AllInOneError(
"Multiple jobm or jobm(number) folders in {}\n".format(folder)
+ ", ".join(jobmfolders) + "\n"
+ "Please specify 0 for jobm, or a number for one of the others."
)
elif jobm == "0":
folder = os.path.join(folder, "jobm")
if os.path.exists(folder + "0"):
raise AllInOneError("Not set up to handle a folder named jobm0")
else:
raise AllInOneError(
"Multiple jobm or jobm(number) folders in {}\n".format(folder)
+ ", ".join(jobmfolders) + "\n"
+ "Please specify 0 for jobm, or a number for one of the others."
)
elif jobm == "0":
folder = os.path.join(folder, "jobm")
if os.path.exists(folder + "0"):
raise AllInOneError("Not set up to handle a folder named jobm0")
else:
folder = os.path.join(folder, "jobm{}".format(jobm))
folder = os.path.join(folder, "jobm{}".format(jobm))

dbfile = os.path.join(folder, "alignments_MP.db")
if not os.path.exists(dbfile):
raise AllInOneError("No file {}. Maybe your alignment folder is corrupted, or maybe you specified the wrong jobm?".format(dbfile))
dbfile = os.path.join(folder, "alignments_MP.db")
if not os.path.exists(dbfile):
raise AllInOneError("No file {}. Maybe your alignment folder is corrupted, or maybe you specified the wrong jobm?".format(dbfile))

elif option in ("hp", "sm"):
if len(condPars) == 1:
number, = condPars
iteration = None
elif len(condPars) == 2:
number, iteration = condPars
else:
raise AllInOneError("Up to 2 arguments accepted for {} (job number, and optionally iteration)".format(option))
folder = "/afs/cern.ch/cms/CAF/CMSALCA/ALCA_TRACKERALIGN2/HipPy/alignments/{}{}".format(option, number)
if not os.path.exists(folder):
raise AllInOneError(folder+" does not exist.")
if iteration is None:
for filename in os.listdir(folder):
match = re.match("alignments_iter([0-9]*).db", filename)
if match:
if iteration is None or int(match.group(1)) > iteration:
iteration = int(match.group(1))
if iteration is None:
raise AllInOneError("No alignments in {}".format(folder))
dbfile = os.path.join(folder, "alignments_iter{}.db".format(iteration))
if not os.path.exists(dbfile):
raise AllInOneError("No file {}.".format(dbfile))

if "\nDeformations" not in conddb("--db", dbfile, "listTags"):
deformations = False #so that hp = XXXX works whether or not deformations were aligned
if not alignments: #then it's specified with hp_deformations, which is a mistake
raise AllInOneError("{}{} has no deformations".format(option, number))

else:
assert False, option

if alignments:
conditions.append({"rcdName": "TrackerAlignmentRcd",
Expand All @@ -144,35 +178,6 @@ def __getConditions( self, theConfig, theSection ):
"tagName": "Deformations",
"labelName": ""})

elif option in ("hp", "sm"):
condPars = theConfig.get(theSection, option).split(",")
condPars = [_.strip() for _ in condPars]
if len(condPars) == 1:
number, = condPars
iteration = None
elif len(condPars) == 2:
number, iteration = condPars
else:
raise AllInOneError("Up to 2 arguments accepted for {} (job number, and optionally iteration)".format(option))
folder = "/afs/cern.ch/cms/CAF/CMSALCA/ALCA_TRACKERALIGN2/HipPy/alignments/{}{}".format(option, number)
if not os.path.exists(folder):
raise AllInOneError(folder+" does not exist.")
if iteration is None:
for filename in os.listdir(folder):
match = re.match("alignments_iter([0-9]*).db", filename)
if match:
if iteration is None or int(match.group(1)) > iteration:
iteration = int(match.group(1))
if iteration is None:
raise AllInOneError("No alignments in {}".format(folder))
dbfile = os.path.join(folder, "alignments_iter{}.db".format(iteration))
if not os.path.exists(dbfile):
raise AllInOneError("No file {}.".format(dbfile))
conditions.append({"rcdName": "TrackerAlignmentRcd",
"connectString": "sqlite_file:"+dbfile,
"tagName": "Alignments",
"labelName": ""})

elif option.startswith( "condition " ):
rcdName = option.split( "condition " )[1]
condPars = theConfig.get( theSection, option ).split( "," )
Expand Down Expand Up @@ -227,19 +232,19 @@ def __getConditions( self, theConfig, theSection ):
if rcdnames and max(rcdnames.values()) >= 2:
raise AllInOneError("Some conditions are specified multiple times (possibly through mp or hp options)!\n"
+ ", ".join(rcdname for rcdname, count in rcdnames.iteritems() if count >= 2))


for condition in conditions:
self.__testDbExist(condition["connectString"], condition["tagName"])

return conditions

def __testDbExist(self, dbpath):
#FIXME delete return to end train debuging
return
if not dbpath.startswith("sqlite_file:"):
print "WARNING: could not check existence for",dbpath
else:
def __testDbExist(self, dbpath, tagname):
if dbpath.startswith("sqlite_file:"):
if not os.path.exists( dbpath.split("sqlite_file:")[1] ):
raise "could not find file: '%s'"%dbpath.split("sqlite_file:")[1]

raise AllInOneError("could not find file: '%s'"%dbpath.split("sqlite_file:")[1])
elif "\n"+tagname not in conddb("--db", dbpath.split("sqlite_file:")[1], "listTags"):
raise AllInOneError("{} does not exist in {}".format(tagname, dbpath))

def restrictTo( self, restriction ):
result = []
if not restriction == None:
Expand All @@ -257,7 +262,7 @@ def getRepMap( self ):
"runGeomComp": self.runGeomComp,
"GlobalTag": self.globaltag
}
return result
return result

def getConditions(self):
"""This function creates the configuration snippet to override
Expand All @@ -272,7 +277,7 @@ def getConditions(self):
"tag = cms.string('.oO[tagName]Oo.')",
("tag = cms.string('.oO[tagName]Oo.'),"
"\nlabel = cms.untracked.string('.oO[labelName]Oo.')"))
else:
else:
temp = configTemplates.conditionsTemplate
loadCond += replaceByMap( temp, cond )
else:
Expand Down
@@ -1,5 +1,6 @@
import os
import ROOT
import sys
from TkAlExceptions import AllInOneError

####################--- Helpers ---############################
Expand Down Expand Up @@ -190,3 +191,38 @@ def cppboolstring(string, name):
and makes it into a bool string for a C++ template
"""
return pythonboolstring(string, name).lower()

def conddb(*args):
"""
Wrapper for conddb, so that you can run
conddb("--db", "myfile.db", "listTags"),
like from the command line, without explicitly
dealing with all the functions in CondCore/Utilities.
getcommandoutput2(conddb ...) doesn't work, it imports
the wrong sqlalchemy in CondCore/Utilities/python/conddblib.py
"""
from tempfile import NamedTemporaryFile

with open(getCommandOutput2("which conddb").strip()) as f:
conddb = f.read()

def sysexit(number):
if number != 0:
raise AllInOneError("conddb exited with status {}".format(number))
namespace = {"sysexit": sysexit, "conddboutput": ""}

conddb = conddb.replace("sys.exit", "sysexit")

bkpargv = sys.argv
sys.argv[1:] = args
bkpstdout = sys.stdout
with NamedTemporaryFile(bufsize=0) as sys.stdout:
exec conddb in namespace
namespace["main"]()
with open(sys.stdout.name) as f:
result = f.read()

sys.argv[:] = bkpargv
sys.stdout = bkpstdout

return result