Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:14:22

0001 """Helper object for configuring the LCIO output file (meta)"""
0002 
0003 from DDSim.Helper.ConfigHelper import ConfigHelper
0004 import datetime
0005 import io
0006 import os
0007 import logging
0008 
0009 logger = logging.getLogger(__name__)
0010 
0011 
0012 class Meta(ConfigHelper):
0013   """Configuration for the LCIO output file settings"""
0014 
0015   def __init__(self):
0016     super(Meta, self).__init__()
0017     self._eventParameters_EXTRA = {'help': "Event parameters to write in every event. "
0018                                            "Use C/F/I ids to specify parameter type. "
0019                                            "E.g parameterName/F=0.42 to set a float parameter",
0020                                    'nargs': '+'}
0021     self.eventParameters = []
0022     self._runNumberOffset_EXTRA = {'help': "The run number offset to write in slcio output file. "
0023                                            "E.g setting it to 42 will start counting runs from 42 instead of 0",
0024                                    'type': int}
0025     self.runNumberOffset = 0
0026     self._eventNumberOffset_EXTRA = {'help': "The event number offset to write in slcio output file."
0027                                              " E.g setting it to 42 will start counting events from 42 instead of 0",
0028                                      'type': int}
0029     self.eventNumberOffset = 0
0030     # no closeProperties, allow adding arbitrary information to runHeader
0031 
0032   def parseEventParameters(self):
0033     """
0034     Parse the event parameters and return 3 event parameter dictionaries, respectively
0035     for string, int and float parameters
0036     """
0037     stringParameters, intParameters, floatParameters, allParameters = {}, {}, {}, []
0038     for p in self.eventParameters:
0039       parameterAndValue = p.split("=", 1)
0040       if len(parameterAndValue) != 2:
0041         raise SyntaxError("ERROR: Couldn't decode event parameter '%s'" % (p))
0042       parameterAndType = parameterAndValue[0].split("/", 1)
0043       if len(parameterAndType) != 2:
0044         raise SyntaxError("ERROR: Couldn't decode event parameter '%s'" % (p))
0045       pname = parameterAndType[0]
0046       ptype = parameterAndType[1]
0047       pvalue = parameterAndValue[1]
0048       if ptype.lower() not in ["c", "f", "i"]:
0049         raise ValueError("ERROR: Event parameter '%s' with invalid type '%s'" % (pname, ptype))
0050       if pname in allParameters:
0051         raise RuntimeError("ERROR: Event parameter '%s' specified twice" % (pname))
0052       if not pvalue:
0053         raise RuntimeError("ERROR: Event parameter '%s' has empty value" % (pname))
0054       allParameters.append(pname)
0055       logger.info("Event parameter '%s', type '%s', value='%s'" % (pname, ptype, pvalue))
0056       if ptype.lower() == "c":
0057         stringParameters[pname] = pvalue
0058       elif ptype.lower() == "f":
0059         floatParameters[pname] = pvalue
0060       elif ptype.lower() == "i":
0061         intParameters[pname] = pvalue
0062     return stringParameters, intParameters, floatParameters
0063 
0064   @staticmethod
0065   def addParametersToRunHeader(sim):
0066     """add the parameters to the (lcio) run Header"""
0067     runHeader = {}
0068     parameters = vars(sim)
0069     for parName, parameter in parameters.items():
0070       if isinstance(parameter, ConfigHelper):
0071         options = parameter.getOptions()
0072         for opt, optionsDict in options.items():
0073           runHeader["%s.%s" % (parName, opt)] = str(optionsDict['default'])
0074       else:
0075         runHeader[parName] = str(parameter)
0076 
0077     # steeringFile content
0078     if sim.steeringFile and os.path.exists(sim.steeringFile) and os.path.isfile(sim.steeringFile):
0079       with io.open(sim.steeringFile) as sFile:
0080         runHeader["SteeringFileContent"] = sFile.read()
0081 
0082     # macroFile content
0083     if sim.macroFile and os.path.exists(sim.macroFile) and os.path.isfile(sim.macroFile):
0084       with io.open(sim.macroFile) as mFile:
0085         runHeader["MacroFileContent"] = mFile.read()
0086 
0087     # add command line
0088     if sim._argv:
0089       runHeader["CommandLine"] = " ".join(sim._argv)
0090 
0091     # add current working directory (where we call from)
0092     runHeader["WorkingDirectory"] = os.getcwd()
0093 
0094     # ILCSoft, LCGEo location from environment variables, names from init_ilcsoft.sh
0095     runHeader["ILCSoft_location"] = os.environ.get("ILCSOFT", "Unknown")
0096     runHeader["lcgeo_location"] = os.environ.get("lcgeo_DIR", "Unknown")
0097 
0098     # add date
0099     runHeader["DateUTC"] = str(datetime.datetime.utcnow()) + " UTC"
0100 
0101     # add User
0102     import getpass
0103     try:
0104         runHeader["User"] = getpass.getuser()
0105     except KeyError:
0106         runHeader["User"] = str(os.getuid())
0107 
0108     return runHeader