ATLAS Offline Software
Loading...
Searching...
No Matches
python.CPBaseRunner.CPBaseRunner Class Reference
Inheritance diagram for python.CPBaseRunner.CPBaseRunner:
Collaboration diagram for python.CPBaseRunner.CPBaseRunner:

Public Member Functions

 __init__ (self)
 args (self)
 inputList (self)
 outputName (self)
 printFlags (self)
 addCustomArguments (self)
 makeAlgSequence (self)
 run (self)
 setup (self)
 printAvailableArguments (self)

Static Public Member Functions

 findLocalPathYamlConfig (textConfigPath)
 findRepoPathYamlConfig (textConfigPath)

Public Attributes

 logger = logging.getLogger("CPBaseRunner")
 parser = self._defaultParseArguments()
 config = self._readYamlConfig()
 flags = self._defaultFlagsInitialization()

Protected Member Functions

 _defaultFlagsInitialization (self)
 _defaultParseArguments (self)
 _mergeYamlconfig (self, yaml_path)
 _readYamlConfig (self)
 _findYamlConfig (self, local=True)
 _parseInputFileList (path)

Protected Attributes

 _args = None
list _inputList = None

Detailed Description

Definition at line 8 of file CPBaseRunner.py.

Constructor & Destructor Documentation

◆ __init__()

python.CPBaseRunner.CPBaseRunner.__init__ ( self)

Definition at line 9 of file CPBaseRunner.py.

9 def __init__(self):
10 self.logger = logging.getLogger("CPBaseRunner")
11 self._args = None
12 self._inputList = None
13 self.parser = self._defaultParseArguments()
14 # parse the arguments here is a bad idea
15

Member Function Documentation

◆ _defaultFlagsInitialization()

python.CPBaseRunner.CPBaseRunner._defaultFlagsInitialization ( self)
protected

Definition at line 67 of file CPBaseRunner.py.

67 def _defaultFlagsInitialization(self):
68 from AthenaConfiguration.AllConfigFlags import initConfigFlags
69 flags = initConfigFlags()
70 flags.Input.Files = self.inputList
71 flags.Exec.MaxEvents = self.args.max_events
72 flags.Exec.SkipEvents = self.args.skip_n_events
73 return flags
74

◆ _defaultParseArguments()

python.CPBaseRunner.CPBaseRunner._defaultParseArguments ( self)
protected

Definition at line 75 of file CPBaseRunner.py.

75 def _defaultParseArguments(self):
76 parser = argparse.ArgumentParser(
77 description='Runscript for CP Algorithm unit tests')
78 baseGroup = parser.add_argument_group('Base Script Options')
79 baseGroup.add_argument('-i', '--input-list', dest='input_list',
80 help='path to text file containing list of input files, or a single root file')
81 baseGroup.add_argument('-o','--output-name', dest='output_name', default='output',
82 help='output name of the analysis root file')
83 baseGroup.add_argument('-e', '--max-events', dest='max_events', type=int, default=-1,
84 help='Number of events to run')
85 baseGroup.add_argument('-t', '--text-config', dest='text_config',
86 help='path to the YAML configuration file. Tips: use atlas_install_data(path/to/*.yaml) in CMakeLists.txt can help locating the config just by the config file name.')
87 baseGroup.add_argument('--no-systematics', dest='no_systematics',
88 action='store_true', help='Disable systematics')
89 baseGroup.add_argument('--skip-n-events', dest='skip_n_events', type=int, default=0,
90 help='Skip the first N events in the run, not first N events for each file. This is meant for debugging only. \nIn Eventloop, this option disable the cutbookkeeper algorithms due to technical reasons, and can only be ran in direct-driver.')
91 return parser
92

◆ _findYamlConfig()

python.CPBaseRunner.CPBaseRunner._findYamlConfig ( self,
local = True )
protected

Definition at line 122 of file CPBaseRunner.py.

122 def _findYamlConfig(self, local=True):
123 # Find local and abs path first
124 if local and ((yamlConfig := CPBaseRunner.findLocalPathYamlConfig(self.args.text_config)) is not None):
125 return yamlConfig
126 # Then search in the analysis repository and warn for duplicates
127 elif (yamlConfig := CPBaseRunner.findRepoPathYamlConfig(self.args.text_config)):
128 if len(yamlConfig) > 1:
129 raise FileExistsError(f'Multiple files named \"{self.args.text_config}\" found in the analysis repository. Please provide a more specific path to the config file.\nMatches found:\n' + '\n'.join(yamlConfig))
130 else:
131 return yamlConfig[0]
132 # Finally try the slowest method using AthenaCommon
133 else:
134 from AthenaCommon.Utils.unixtools import find_datafile
135 return find_datafile(self.args.text_config)
136

◆ _mergeYamlconfig()

python.CPBaseRunner.CPBaseRunner._mergeYamlconfig ( self,
yaml_path )
protected

Definition at line 93 of file CPBaseRunner.py.

93 def _mergeYamlconfig(self, yaml_path):
94 with open(yaml_path, "r", encoding="utf-8") as cfg_file:
95 import yaml
96 config_data = yaml.safe_load(cfg_file)
97 from AnalysisAlgorithmsConfig.ConfigText import combineConfigFiles
98 combined = combineConfigFiles(
99 config_data,
100 os.path.dirname(os.path.dirname(yaml_path)),
101 fragment_key="include",
102 )
103 if combined:
104 with open("merged_config.yaml", "w") as cfg:
105 cfg.write(yaml.dump(config_data))
106 return config_data, combined
107

◆ _parseInputFileList()

python.CPBaseRunner.CPBaseRunner._parseInputFileList ( path)
protected

Definition at line 171 of file CPBaseRunner.py.

171 def _parseInputFileList(path):
172 files = []
173 with open(path, 'r') as inputText:
174 for line in inputText.readlines():
175 # Strip the line and skip comments and empty lines
176 line = line.strip()
177 if line.startswith('#') or not line:
178 continue
179 if os.path.isdir(line):
180 if not os.listdir(line):
181 raise FileNotFoundError(f"The directory \"{path}\" is empty. Please provide a directory with .root files.")
182 for root_file in os.listdir(line):
183 if '.root' in root_file:
184 files.append(os.path.join(line, root_file))
185 else:
186 files += line.split(',')
187 # Remove leading/trailing whitespaces from file names
188 files = [file.strip() for file in files]
189 return files
190

◆ _readYamlConfig()

python.CPBaseRunner.CPBaseRunner._readYamlConfig ( self)
protected

Definition at line 108 of file CPBaseRunner.py.

108 def _readYamlConfig(self):
109 yamlconfig = self._findYamlConfig(local=True)
110 if yamlconfig is None:
111 raise FileNotFoundError(f'Failed to locate \"{self.args.text_config}\" config file!'
112 'Check if you have a typo in -t/--text-config argument or missing file in the analysis configuration sub-directory.')
113 self.logger.info(f"Found YAML config at: {yamlconfig}")
114 self.logger.info("Setting up configuration based on YAML config:")
115 config_data, merged = self._mergeYamlconfig(yamlconfig)
116 if merged:
117 self.logger.info("Merged included fragments into main config.")
118 from AnalysisAlgorithmsConfig.ConfigText import TextConfig
119 config = TextConfig(config=config_data)
120 return config
121

◆ addCustomArguments()

python.CPBaseRunner.CPBaseRunner.addCustomArguments ( self)

Definition at line 55 of file CPBaseRunner.py.

55 def addCustomArguments(self):
56 pass
57

◆ args()

python.CPBaseRunner.CPBaseRunner.args ( self)

Definition at line 17 of file CPBaseRunner.py.

17 def args(self):
18 if self._args is None:
19 self._args = self.parser.parse_args()
20 return self._args
21

◆ findLocalPathYamlConfig()

python.CPBaseRunner.CPBaseRunner.findLocalPathYamlConfig ( textConfigPath)
static

Definition at line 138 of file CPBaseRunner.py.

138 def findLocalPathYamlConfig(textConfigPath):
139 configPath = os.path.normpath(os.path.expanduser(textConfigPath))
140 if os.path.isabs(configPath) and os.path.isfile(configPath):
141 return configPath
142 cwdPath = os.path.join(os.getcwd(), configPath)
143 if os.path.isfile(cwdPath):
144 return cwdPath
145 return None
146

◆ findRepoPathYamlConfig()

python.CPBaseRunner.CPBaseRunner.findRepoPathYamlConfig ( textConfigPath)
static
Search for the file up to two levels deep within the first DATAPATH entry.
First, check directly under the analysis repository (depth 0).
Then, check immediate subdirectories (depth 1), looking for the file inside each.
Returns a list of all matches found.

Definition at line 148 of file CPBaseRunner.py.

148 def findRepoPathYamlConfig(textConfigPath):
149 """
150 Search for the file up to two levels deep within the first DATAPATH entry.
151 First, check directly under the analysis repository (depth 0).
152 Then, check immediate subdirectories (depth 1), looking for the file inside each.
153 Returns a list of all matches found.
154 """
155 matches = []
156 analysisRepoPath = os.environ.get('DATAPATH', '').split(os.pathsep)[0]
157 # Depth 0: Directly under analysisRepoPath
158 searchPath = os.path.join(analysisRepoPath, textConfigPath)
159 if os.path.isfile(searchPath):
160 matches.append(searchPath)
161 # Depth 1: Inside immediate subdirectories
162 try:
163 for subdir in os.listdir(analysisRepoPath):
164 candidate = os.path.join(analysisRepoPath, subdir, textConfigPath)
165 if os.path.isfile(candidate):
166 matches.append(candidate)
167 except Exception:
168 pass
169 return matches
170
std::vector< std::string > split(const std::string &s, const std::string &t=":")
Definition hcg.cxx:177

◆ inputList()

python.CPBaseRunner.CPBaseRunner.inputList ( self)

Definition at line 23 of file CPBaseRunner.py.

23 def inputList(self):
24 if self._inputList is None:
25 if self.args.input_list.endswith('.txt'):
26 self._inputList = CPBaseRunner._parseInputFileList(self.args.input_list)
27 elif ".root" in self.args.input_list:
28 self._inputList = [self.args.input_list]
29 else:
30 raise FileNotFoundError(f'Input file list \"{self.args.input_list}\" is not supported!'
31 'Please provide a text file with a list of input files or a single root file.')
32 self.logger.info("Initialized input files: %s", self._inputList)
33 return self._inputList
34

◆ makeAlgSequence()

python.CPBaseRunner.CPBaseRunner.makeAlgSequence ( self)

Definition at line 59 of file CPBaseRunner.py.

59 def makeAlgSequence(self):
60 pass
61

◆ outputName()

python.CPBaseRunner.CPBaseRunner.outputName ( self)

Definition at line 36 of file CPBaseRunner.py.

36 def outputName(self):
37 if self.args.output_name.endswith('.root'):
38 return self.args.output_name[:-5]
39 else:
40 return self.args.output_name
41

◆ printAvailableArguments()

python.CPBaseRunner.CPBaseRunner.printAvailableArguments ( self)

Definition at line 196 of file CPBaseRunner.py.

196 def printAvailableArguments(self):
197 self.parser.description = 'CPRunScript available arguments'
198 self.parser.usage = argparse.SUPPRESS
199 self.parser.print_help()

◆ printFlags()

python.CPBaseRunner.CPBaseRunner.printFlags ( self)

Definition at line 42 of file CPBaseRunner.py.

42 def printFlags(self):
43 self.logger.info("="*73)
44 self.logger.info("="*20 + "FLAG CONFIGURATION" + "="*20)
45 self.logger.info("="*73)
46 self.logger.info(" Input files: %s", self.flags.Input.isMC)
47 self.logger.info(" RunNumber: %s", self.flags.Input.RunNumbers)
48 self.logger.info(" MCCampaign: %s", self.flags.Input.MCCampaign)
49 self.logger.info(" GeneratorInfo: %s", self.flags.Input.GeneratorsInfo)
50 self.logger.info(" MaxEvents: %s", self.flags.Exec.MaxEvents)
51 self.logger.info(" SkipEvents: %s", self.flags.Exec.SkipEvents)
52 self.logger.info("="*73)
53

◆ run()

python.CPBaseRunner.CPBaseRunner.run ( self)

Definition at line 63 of file CPBaseRunner.py.

63 def run(self):
64 pass
65
int run(int argc, char *argv[])

◆ setup()

python.CPBaseRunner.CPBaseRunner.setup ( self)

Definition at line 191 of file CPBaseRunner.py.

191 def setup(self):
192 self.parser.parse_args()
193 self.config = self._readYamlConfig()
194 self.flags = self._defaultFlagsInitialization()
195
bool setup(asg::AnaToolHandle< Interface > &tool, const std::string &type, const std::vector< std::string > &config, const std::string &progressFile="")
mostly useful for athena, which will otherwise re-use the previous tool

Member Data Documentation

◆ _args

python.CPBaseRunner.CPBaseRunner._args = None
protected

Definition at line 11 of file CPBaseRunner.py.

◆ _inputList

python.CPBaseRunner.CPBaseRunner._inputList = None
protected

Definition at line 12 of file CPBaseRunner.py.

◆ config

python.CPBaseRunner.CPBaseRunner.config = self._readYamlConfig()

Definition at line 193 of file CPBaseRunner.py.

◆ flags

python.CPBaseRunner.CPBaseRunner.flags = self._defaultFlagsInitialization()

Definition at line 194 of file CPBaseRunner.py.

◆ logger

python.CPBaseRunner.CPBaseRunner.logger = logging.getLogger("CPBaseRunner")

Definition at line 10 of file CPBaseRunner.py.

◆ parser

python.CPBaseRunner.CPBaseRunner.parser = self._defaultParseArguments()

Definition at line 13 of file CPBaseRunner.py.


The documentation for this class was generated from the following file: