9 from __future__
import print_function
15 from FWCore.PythonUtilities.LumiList
import LumiList
17 from pprint
import pprint
18 from datetime
import datetime
20 import Utilities.General.cmssw_das_client
as das_client
24 edmPickEvent.py dataset run1:lumi1:event1 run2:lumi2:event2 28 edmPickEvent.py dataset listOfEvents.txt 30 listOfEvents is a text file: 31 # this line is ignored as a comment 32 # since '#' is a valid comment character 33 run1 lumi_section1 event1 34 run2 lumi_section2 event2 42 run, lumi_section, and event are integers that you can get from 45 dataset: it just a name of the physics dataset, if you don't know exact name 46 you can provide a mask, e.g.: *QCD*RAW 48 For updated information see Wiki: 49 https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookPickEvents 60 splitRE = re.compile (
r'[\s:,]+')
62 pieces = Event.splitRE.split (line.strip())
64 self[
'run'] =
int( pieces[0] )
65 self[
'lumi'] =
int( pieces[1] )
66 self[
'event'] =
int( pieces[2] )
67 self[
'dataset'] = Event.dataset
69 raise RuntimeError(
"Can not parse '%s' as Event object" \
71 if not self[
'dataset']:
72 print(
"No dataset is defined for '%s'. Aborting." % line.strip())
73 raise RuntimeError(
'Missing dataset')
79 return "run = %(run)i, lumi = %(lumi)i, event = %(event)i, dataset = %(dataset)s" % self
87 """Return files for given DAS query""" 88 if client ==
'das_client':
90 elif client ==
'dasgoclient':
93 for path
in os.getenv(
'PATH').
split(
':'):
94 if os.path.isfile(os.path.join(path,
'dasgoclient')):
99 """Return files for given DAS query via das_client""" 102 query =
"file dataset=%(dataset)s run=%(run)i lumi=%(lumi)i | grep file.name" % event
104 status = jsondict[
'status']
106 print(
"DAS query status: %s"%(status))
109 mongo_query = jsondict[
'mongo_query']
110 filters = mongo_query[
'filters']
111 data = jsondict[
'data']
116 if len(file) > 0
and not file
in files:
122 """Return files for given DAS query via dasgoclient""" 123 query =
"file dataset=%(dataset)s run=%(run)i lumi=%(lumi)i" % event
124 cmd = [
'dasgoclient',
'-query', query,
'-json']
125 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
127 err = proc.stderr.read()
129 print(
"DAS error: %s" % err)
130 print(proc.stdout.read())
133 dasout = proc.stdout.read()
135 for row
in json.loads(dasout):
136 for rec
in row.get(
'file', []):
137 fname = rec.get(
'name',
'')
146 base = os.environ.get (
'CMSSW_BASE')
148 raise RuntimeError(
"CMSSW Environment not set")
149 retval =
"%s/src/PhysicsTools/Utilities/configuration/copyPickMerge_cfg.py" \
151 if os.path.exists (retval):
153 base = os.environ.get (
'CMSSW_RELEASE_BASE')
154 retval =
"%s/src/PhysicsTools/Utilities/configuration/copyPickMerge_cfg.py" \
156 if os.path.exists (retval):
158 raise RuntimeError(
"Could not find copyPickMerge_cfg.py")
161 return '%s@%s' % (subprocess.getoutput (
'whoami'),
162 '.'.
join(subprocess.getoutput(
'hostname').
split(
'.')[-2:]))
165 date = datetime.now().strftime(
'%Y%m%d_%H%M%S')
168 crab[
'runEvent'] =
'%s_runEvents.txt' % base
170 crab[
'output'] =
'%s.root' % base
171 crab[
'crabcfg'] =
'%s_crab.py' % base
172 crab[
'json'] =
'%s.json' % base
173 crab[
'dataset'] = Event.dataset
174 crab[
'email'] = options.email
175 crab[
'WorkArea'] = date
176 if options.crabCondor:
177 crab[
'scheduler'] =
'condor' 180 crab[
'scheduler'] =
'remoteGlidein' 182 crab[
'useServer'] =
'' 187 ## Edited By Raman Khurana 189 ## CRAB documentation : https://twiki.cern.ch/twiki/bin/view/CMSPublic/SWGuideCrab 191 ## CRAB 3 parameters : https://twiki.cern.ch/twiki/bin/view/CMSPublic/CRAB3ConfigurationFile#CRAB_configuration_parameters 193 ## Once you are happy with this file, please run 196 ## In CRAB3 the configuration file is in Python language. It consists of creating a Configuration object imported from the WMCore library: 198 from WMCore.Configuration import Configuration 199 config = Configuration() 201 ## Once the Configuration object is created, it is possible to add new sections into it with corresponding parameters 202 config.section_("General") 203 config.General.requestName = 'pickEvents' 204 config.General.workArea = 'crab_pickevents_%(WorkArea)s' 207 config.section_("JobType") 208 config.JobType.pluginName = 'Analysis' 209 config.JobType.psetName = '%(copyPickMerge)s' 210 config.JobType.pyCfgParams = ['eventsToProcess_load=%(runEvent)s', 'outputFile=%(output)s'] 212 config.section_("Data") 213 config.Data.inputDataset = '%(dataset)s' 215 config.Data.inputDBS = 'global' 216 config.Data.splitting = 'LumiBased' 217 config.Data.unitsPerJob = 5 218 config.Data.lumiMask = '%(json)s' 219 #config.Data.publication = True 220 #config.Data.publishDbsUrl = 'phys03' 221 #config.Data.publishDataName = 'CRAB3_CSA_DYJets' 222 #config.JobType.allowNonProductionCMSSW=True 224 config.section_("Site") 225 ## Change site name accordingly 226 config.Site.storageSite = "T2_US_Wisconsin" 236 if __name__ ==
"__main__":
238 parser = optparse.OptionParser (
"Usage: %prog [options] dataset events_or_events.txt", description=
'''This program 239 facilitates picking specific events from a data set. For full details, please visit 240 https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookPickEvents ''')
241 parser.add_option (
'--output', dest=
'base', type=
'string',
242 default=
'pickevents',
243 help=
'Base name to use for output files (root, JSON, run and event list, etc.; default "%default")')
244 parser.add_option (
'--runInteractive', dest=
'runInteractive', action=
'store_true',
245 help =
'Call "cmsRun" command if possible. Can take a long time.')
246 parser.add_option (
'--printInteractive', dest=
'printInteractive', action=
'store_true',
247 help =
'Print "cmsRun" command instead of running it.')
248 parser.add_option (
'--maxEventsInteractive', dest=
'maxEventsInteractive', type=
'int',
250 help =
'Maximum number of events allowed to be processed interactively.')
251 parser.add_option (
'--crab', dest=
'crab', action=
'store_true',
252 help =
'Force CRAB setup instead of interactive mode')
253 parser.add_option (
'--crabCondor', dest=
'crabCondor', action=
'store_true',
254 help =
'Tell CRAB to use Condor scheduler (FNAL or OSG sites).')
255 parser.add_option (
'--email', dest=
'email', type=
'string',
257 help=
"Specify email for CRAB (default '%s')" % email )
259 parser.add_option (
'--das-client', dest=
'das_cli', type=
'string',
261 help=
"Specify das client to use (default '%s')" % das_cli )
262 (options, args) = parser.parse_args()
269 if not options.email:
270 options.email = email
272 Event.dataset = args.pop(0)
273 commentRE = re.compile (
r'#.+$')
274 colonRE = re.compile (
r':')
276 if len (args) > 1
or colonRE.search (args[0]):
280 event = Event (piece)
282 raise RuntimeError(
"'%s' is not a proper event" % piece)
283 eventList.append (event)
286 source = open(args[0],
'r') 288 line = commentRE.sub (
'', line)
292 print(
"Skipping '%s'." % line.strip())
294 eventList.append(event)
298 print(
"No events defined. Aborting.")
301 if len (eventList) > options.maxEventsInteractive:
309 if options.runInteractive:
310 raise RuntimeError(
"This job cannot be run interactively, but rather by crab. Please call without the '--runInteractive' flag or increase the '--maxEventsInteractive' value.")
311 runsAndLumis = [ (event.run, event.lumi)
for event
in eventList]
312 json = LumiList (lumis = runsAndLumis)
314 sorted( [
"%d:%d" % (event.run, event.event)
for event
in eventList ] ) )
315 crabDict = setupCrabDict (options)
316 json.writeJSON (crabDict[
'json'])
317 target = open (crabDict[
'runEvent'],
'w')
318 target.write (
"%s\n" % eventsToProcess)
320 target = open (crabDict[
'crabcfg'],
'w')
321 target.write (crabTemplate % crabDict)
323 print(
"Please visit CRAB twiki for instructions on how to setup environment for CRAB:\nhttps://twiki.cern.ch/twiki/bin/viewauth/CMS/SWGuideCrab\n")
324 if options.crabCondor:
325 print(
"You are running on condor. Please make sure you have read instructions on\nhttps://twiki.cern.ch/twiki/bin/view/CMS/CRABonLPCCAF\n")
326 if not os.path.exists (
'%s/.profile' % os.environ.get(
'HOME')):
327 print(
"** WARNING: ** You are missing ~/.profile file. Please see CRABonLPCCAF instructions above.\n")
328 print(
"Setup your environment for CRAB and edit %(crabcfg)s to make any desired changed. Then run:\n\ncrab submit -c %(crabcfg)s\n" % crabDict)
337 for event
in eventList:
339 if eventFiles == [
'[]']:
340 print(
"** WARNING: ** According to a DAS query, run = %i; lumi = %i; event = %i not contained in %s. Skipping."%(event.run,event.lumi,event.event,event.dataset))
341 eventPurgeList.append( event )
343 files.extend( eventFiles )
345 for event
in eventPurgeList:
346 eventList.remove( event )
350 for filename
in files:
351 if filename
in fileSet:
353 fileSet.add (filename)
354 uniqueFiles.append (filename)
355 source =
','.join (uniqueFiles) +
'\n' 356 eventsToProcess =
','.
join(\
357 sorted( [
"%d:%d" % (event.run, event.event)
for event
in eventList ] ) )
358 command =
'edmCopyPickMerge outputFile=%s.root \\\n eventsToProcess=%s \\\n inputFiles=%s' \
359 % (options.base, eventsToProcess, source)
360 print(
"\n%s" % command)
361 if options.runInteractive
and not options.printInteractive:
def get_value(data, filters, base=10)
def get_data(host, query, idx, limit, debug, threshold=300, ckey=None, cert=None, capath=None, qcache=0, das_headers=True)
def getFileNames_dasgoclient(event)
def getFileNames(event, client=None)
Subroutines ##.
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
def __getattr__(self, key)
def split(sequence, size)
static std::string join(char **cmd)
def getFileNames_das_client(event)
def __init__(self, line, kwargs)
def setupCrabDict(options)