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

Utilities and fixes for HipPy alignment #25874

Merged
merged 8 commits into from Feb 19, 2019
Merged
Show file tree
Hide file tree
Changes from 6 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
4 changes: 2 additions & 2 deletions Alignment/CommonAlignment/scripts/tkal_create_file_lists.py
Expand Up @@ -215,7 +215,7 @@ def _validate_input(self):
self._args.events = float("inf")
print_msg("Using all tracks for alignment")
elif (self._args.tracks is None) and (self._args.rate is None):
msg = ("either -n/--events-for-alignment or both of "
msg = ("either -n/--events-for-alignment, --all-events, or both of "
"--tracks-for-alignment and --track-rate are required")
self._parser.error(msg)
elif (((self._args.tracks is not None) and (self._args.rate is None)) or
Expand Down Expand Up @@ -461,7 +461,7 @@ def _split_hippy_jobs(self):
eventsinthisjob = float("inf")
for fileinfo in self._files_alignment:
if fileinfo.dataset != dataset: continue
miniiovs = self._get_iovs(fileinfo.runs, useminiiovs=True)
miniiovs = set(self._get_iovs(fileinfo.runs, useminiiovs=True))
if miniiov not in miniiovs: continue
if len(miniiovs) > 1:
hippyjobs[dataset,miniiov] = []
Expand Down
Expand Up @@ -198,7 +198,7 @@ def interpretOptions(self):
self.uniformetaformula=val
## Options for mMin. bias
# Apply vertex constraint
elif (key=="primaryvertextpye" or key=="pvtype"):
elif (key=="primaryvertextype" or key=="pvtype"):
val=val.lower()
if (val=="nobs" or val=="withbs"):
self.PVtype=val
Expand Down
25 changes: 10 additions & 15 deletions Alignment/HIPAlignmentAlgorithm/python/align_tpl_py.txt
Expand Up @@ -31,21 +31,16 @@ if "generic" in optpy.CPEtype: # CPE type is defaulted to "template" in HipPyOpt
sourceFileList=[
<FILE>
]
if strflaglower == "cosmics":
process.source = cms.Source("PoolSource",
#useCSA08Kludge = cms.untracked.bool(True),
fileNames = cms.untracked.vstring(sourceFileList)
)
elif strflaglower == "cdcs":
process.source = cms.Source("PoolSource",
#useCSA08Kludge = cms.untracked.bool(True),
fileNames = cms.untracked.vstring(sourceFileList)
)
else:
process.source = cms.Source("PoolSource",
#useCSA08Kludge = cms.untracked.bool(True),
fileNames = cms.untracked.vstring(sourceFileList)
)
import os, sys
if sys.argv[0] == "cmsRun": __file__ = sys.argv[1]
try:
sourceFileList = [_ for _ in sourceFileList if _ not in open(os.path.join(os.path.dirname(__file__), "../../../run/DataFiles/baddatafiles.txt")).read()]
except IOError:
pass

process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(sourceFileList)
)

if hasattr(optpy, "LumiJSON"):
import FWCore.PythonUtilities.LumiList as LumiList
Expand Down
158 changes: 158 additions & 0 deletions Alignment/HIPAlignmentAlgorithm/scripts/hippyaddtobaddatafiles.py
@@ -0,0 +1,158 @@
#!/usr/bin/env python
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hroskes Could you take consistent indentation rule in the whole script?


import argparse, contextlib, os, re, shutil, subprocess, tempfile, time

if __name__ == "__main__":
def abspath(path):
if not os.path.exists(path): raise ValueError(path+" does not exist")
return os.path.abspath(path)

p = argparse.ArgumentParser()
p.add_argument("cfgfile", type=abspath)
p.add_argument("baddatafileslist", nargs="?", default=None)
args = p.parse_args()

def runcfg(cfgfile, badfilelist):
try:
subprocess.check_output(["cmsRun", cfgfile], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "FallbackFileOpenError" in e.output:
output = e.output.split("An exception of category 'FallbackFileOpenError' occurred while")[1]
filename = re.search("Failed to open the file '[^']*(/store/.*[.]root)", output).group(1)
with OneAtATime(badfilelist+".tmp", 2) as f:
with open(badfilelist) as f:
contents = set(f.read().split())
if filename in contents:
raise RuntimeError(filename+"\nis already in\n"+badfilelist+"\n\nExiting to avoid an infinite loop. Maybe you have this running on the same cfg file multiple times?")
contents.add(filename)
contents = sorted(contents)
with open(badfilelist, "w") as f:
f.write("\n".join(contents)+"\n")
print "found and added a bad file:\n"+filename
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hroskes could you please make this python3 compliant adding parentheses to the print statements and
from future import print_function
at the beginning?

else:
raise
return runcfg(cfgfile, badfilelist)
print "all files left are good"

@contextlib.contextmanager
def cd(newdir):
"""http://stackoverflow.com/a/24176022/5228524"""
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)

def cdtemp(): return cd(tempfile.mkdtemp())

class KeepWhileOpenFile(object):
def __init__(self, name, message=None):
self.filename = name
if message is None: message = LSB_JOBID
self.__message = message
self.pwd = os.getcwd()
self.fd = self.f = None
self.bool = False

@property
def wouldbevalid(self):
if self: return True
with self:
return bool(self)

def __open(self):
self.fd = os.open(self.filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)

def __enter__(self):
with cd(self.pwd):
try:
self.__open()
except OSError:
if self.__message == LSB_JOBID:
try:
with open(self.filename) as f:
oldjobid = int(f.read())
except IOError:
try:
self.__open()
except OSError:
return None
except ValueError:
return None
else:
if jobexists(oldjobid):
return None
else:
try:
os.remove(self.filename)
except OSError: #another job removed it already
pass
try:
self.__open()
except OSError:
return None
else:
return None

self.f = os.fdopen(self.fd, 'w')

if self.__message == LSB_JOBID:
self.__message = self.__message()
try:
if self.__message is not None:
self.f.write(self.__message+"\n")
except IOError:
pass
try:
self.f.close()
except IOError:
pass
self.bool = True
return True

def __exit__(self, *args):
if self:
try:
with cd(self.pwd):
os.remove(self.filename)
except OSError:
pass #ignore it
self.fd = self.f = None
self.bool = False

def __nonzero__(self):
return self.bool

class OneAtATime(KeepWhileOpenFile):
def __init__(self, name, delay, message=None, printmessage=None, task="doing this"):
super(OneAtATime, self).__init__(name, message=message)
self.delay = delay
if printmessage is None:
printmessage = "Another process is already {task}! Waiting {delay} seconds."
printmessage = printmessage.format(delay=delay, task=task)
self.__printmessage = printmessage

def __enter__(self):
while True:
result = super(OneAtATime, self).__enter__()
if result:
return result
print self.__printmessage
time.sleep(self.delay)

def LSB_JOBID():
return os.environ.get("LSB_JOBID", None)

def jobexists(jobid):
return "is not found" not in subprocess.check_output(["bjobs", str(jobid)])

if __name__ == "__main__":
with cdtemp():
shutil.copy(args.cfgfile, ".")

badfilelist = args.badfilelist
if badfilelist is None:
badfilelist = os.path.join(os.path.dirname(cfgfile, "../../../run/DataFiles/baddatafiles.txt")

runcfg(os.path.basename(args.cfgfile), args.badfilelist)
10 changes: 9 additions & 1 deletion Alignment/HIPAlignmentAlgorithm/scripts/makeHippyCampaign.py
Expand Up @@ -21,7 +21,7 @@ def main():
parser.add_argument("--cmssw", default=os.environ["CMSSW_VERSION"])
parser.add_argument("--scram-arch", default=os.environ["SCRAM_ARCH"])
parser.add_argument("--subfolder", default="", help="subfolder within "+basedir+" to make 'foldername' in.")
parser.add_argument("--merge-topic", action="append", help="things to cms-merge-topic within the CMSSW release created")
parser.add_argument("--merge-topic", action="append", help="things to cms-merge-topic within the CMSSW release created", default=[])
parser.add_argument("--print-sys-path", action="store_true", help=argparse.SUPPRESS) #internal, don't use this
args = parser.parse_args()

Expand Down Expand Up @@ -80,6 +80,14 @@ def main():
f.write(os.path.join(os.getcwd(), "cosmics.txt") + ",,COSMICS,Datatype:1 APVMode:deco Bfield:3.8T\n")
f.write(os.path.join(os.getcwd(), "CDCs.txt") + ",,CDCS,Datatype:1 APVMode:deco Bfield:3.8T\n")
subprocess.check_call(["git", "add", "data_example.lst"])
if not os.path.exists("baddatafiles.txt"):
with open("baddatafiles.txt", "w") as f:
f.write("If any data files are bad (e.g. not at CERN), put them here,\n")
f.write("separated by newlines or spaces or nothing or whatever you like.\n")
f.write("Anything else in this file, like these lines, will be ignored.\n")
f.write("You can also run hippyaddtobaddatafiles.py .../align_cfg.py to automatically\n")
f.write("find bad data files.\n")
f.write("Running jobs will automatically pick up changes here next time they resubmit.")

mkdir_p("IOV")
with cd("IOV"):
Expand Down
Expand Up @@ -18,9 +18,9 @@ extraopts="--redirectproxy"
#alignmentname=pick a name
#niterations=pick a number

[ -e $lstfile ] || echo "$lstfile does not exist!"
[ -e $common ] || echo "$common does not exist!"
[ -e $IOVfile ] || echo "$IOVfile does not exist!"
[ -e $lstfile ] || (echo "$lstfile does not exist!"; exit 1)
[ -e $common ] || (echo "$common does not exist!"; exit 1)
[ -e $IOVfile ] || (echo "$IOVfile does not exist!"; exit 1)

commitid=$(git rev-parse HEAD)

Expand Down