ATLAS Offline Software
Loading...
Searching...
No Matches
tool.py
Go to the documentation of this file.
1# Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
2#
3# @author Giordon Stark
4
5# High-level Tool wrapper around PythonToolHandle.
6# Automates buffer extraction, column setting, calling, and output
7# reconstruction using ColumnInfo metadata.
8
9import awkward as ak
10import numpy as np
11
12from ColumnarToolWrapperPython.buffers import (
13 _branch_name_for_column,
14 _is_key_index_column,
15 allocate_outputs,
16 classify_columns,
17 extract_buffers,
18 reconstruct_output,
19 resolve_optional_columns,
20)
21from ColumnarToolWrapperPython.python_tool_handle import PythonToolHandle
22
23
24class Tool:
25 """High-level wrapper around PythonToolHandle.
26
27 Handles the boilerplate of classifying columns, extracting awkward-array
28 buffers, allocating outputs, setting columns on the handle, calling the
29 tool, and reconstructing the output awkward array.
30
31 Parameters
32 ----------
33 type_and_name:
34 Tool type and instance name, e.g. "CP::MuonEfficiencyScaleFactors/myTool".
35 properties:
36 Optional dict of tool properties to set before initialization.
37 rename_containers:
38 Optional mapping from canonical container names (e.g. "Muons") to the
39 branch-name prefix used in the input arrays (e.g. "AnalysisMuonsAuxDyn").
40 This is passed to PythonToolHandle.rename_containers *after* initialize
41 so that ColumnInfo.name values match input array fields.
42 link_target_names:
43 Optional mapping from container names, after ``rename_containers`` is
44 applied, to the names used to calculate the keys of links pointing to
45 them, e.g.
46 ``{"AnalysisMuonsAuxDyn": "AnalysisMuons"}``. By default that is the
47 canonical name, independent of ``rename_containers``. The result is
48 reported in ``ColumnInfo.name_for_links``.
49 """
50
51 def __init__(self, type_and_name, properties=None, rename_containers=None, link_target_names=None):
52 self._handle = PythonToolHandle()
53 self._handle.set_type_and_name(type_and_name)
54 self._properties = dict(properties) if properties else {}
55
56 for key, value in self._properties.items():
57 self._handle.set_property(key, value)
58
59 self._handle.initialize()
60
61 if rename_containers:
62 self._handle.rename_containers(rename_containers)
63
64 if link_target_names:
65 self._handle.set_link_target_names(link_target_names)
66
67 # Cache classified column topology once after initialization
68 self._classified = classify_columns(self._handle.columns)
69
70 @property
71 def properties(self):
72 """Dict of properties set on this tool at construction time."""
73 return self._properties
74
75 @property
76 def columns(self):
77 """All ColumnInfo objects reported by the tool."""
78 return self._handle.columns
79
80 @property
81 def input_columns(self):
82 """Input (non-offset) ColumnInfo objects, including nested-vector data columns."""
83 cols = []
84 for info in self._classified.values():
85 cols.extend(info["inputs"])
86 for nested in info["nested_offsets"].values():
87 cols.extend(nested["inputs"])
88 return cols
89
90 @property
91 def output_columns(self):
92 """Output ColumnInfo objects, including nested-vector outputs (currently unsupported)."""
93 cols = []
94 for info in self._classified.values():
95 cols.extend(info["outputs"])
96 for nested in info["nested_offsets"].values():
97 cols.extend(nested["outputs"])
98 return cols
99
100 @property
102 """Deduplicated uproot branch names needed to fill non-optional inputs.
103
104 For nested-vector inputs, the trailing ``.data`` suffix is stripped so
105 the returned name matches the actual ROOT branch (e.g.
106 ``"Particles.NumTrkPt500"`` instead of ``"Particles.NumTrkPt500.data"``).
107 Key and index columns of links inside a vector map to the branch of
108 the link itself. For one link per object they keep their names, as
109 those are the actual ROOT branches: the branch of the link is a
110 grouping branch, which ``uproot.iterate`` can't read directly.
111 Optional inputs are excluded.
112 """
113 seen = []
114 seen_set = set()
115 for col in self.input_columns:
116 if col.is_optional:
117 continue
118 if _is_key_index_column(col) and "." not in col.offset_name:
119 branch = col.name
120 else:
121 branch = _branch_name_for_column(col.name)
122 if branch not in seen_set:
123 seen_set.add(branch)
124 seen.append(branch)
125 return seen
126
127 @property
129 """List of recommended systematic variation names."""
130 return self._handle.get_recommended_systematics()
131
132 def apply_systematic_variation(self, sys_name):
133 """Apply a systematic variation by name.
134
135 Parameters
136 ----------
137 sys_name:
138 Systematic variation name, e.g. ``"MUON_EFF_RECO_SYS__1up"``.
139 Pass ``""`` to reset to the nominal.
140 """
142
143 def __call__(self, events, systematic=None):
144 """Run the tool on events and return output columns as an ak.Array.
145
146 Parameters
147 ----------
148 events:
149 An ak.Array with fields matching the tool's input column names
150 (after any rename_containers mapping).
151 systematic:
152 Optional systematic variation name (e.g. "MUON_EFF_RECO_SYS__1up").
153 If provided, applied before running the tool and reset to nominal
154 after execution.
155
156 Returns
157 -------
158 ak.Array
159 Record array with one field per output column, each a
160 variable-length list over the per-particle values.
161 """
162 if systematic is not None:
163 self.apply_systematic_variation(systematic)
164
165 try:
166 num_events = int(ak.num(events, axis=0))
167
168 # Resolve optional columns against the actual fields present
169 effective = resolve_optional_columns(self._classified, events)
170
171 # Extract flat buffers from the awkward array
172 buffer_dict = extract_buffers(events, effective)
173
174 # Allocate zero-filled output arrays (added into buffer_dict in-place)
175 allocate_outputs(effective, buffer_dict)
176
177 # Set all columns on the handle
178 for container_name, info in effective.items():
179 # Container offset (always immutable)
180 self._handle[container_name] = np.asarray(buffer_dict[container_name])
181
182 # Nested-vector offsets and their data inputs/outputs
183 for nested_offset_name, nested in info["nested_offsets"].items():
184 self._handle[nested_offset_name] = np.asarray(
185 buffer_dict[nested_offset_name]
186 )
187 for col in nested["inputs"] + nested["event_indices"]:
188 self._handle[col.name] = np.asarray(buffer_dict[col.name])
189 for col in nested["outputs"]:
190 self._handle.set_column_void(col.name, buffer_dict[col.name], False)
191
192 # Flat input data columns and event indices (immutable)
193 for col in info["inputs"] + info["event_indices"]:
194 self._handle[col.name] = np.asarray(buffer_dict[col.name])
195
196 # Flat output data columns (mutable)
197 for col in info["outputs"]:
198 self._handle.set_column_void(col.name, buffer_dict[col.name], False)
199
200 self._handle.call()
201
202 return reconstruct_output(effective, buffer_dict, num_events)
203 finally:
204 # Reset to nominal if systematic was applied
205 if systematic is not None:
__init__(self, type_and_name, properties=None, rename_containers=None, link_target_names=None)
Definition tool.py:51
apply_systematic_variation(self, sys_name)
Definition tool.py:132
output_columns(self)
Definition tool.py:91
recommended_systematics(self)
Definition tool.py:128
required_input_branch_names(self)
Definition tool.py:101
properties(self)
Definition tool.py:71
columns(self)
Definition tool.py:76
__call__(self, events, systematic=None)
Definition tool.py:143
STL class.
void initialize()