FairShip
Loading...
Searching...
No Matches
eminem_importer.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP
3# Collaboration
4"""Convert pickled muon data to ROOT format (TTree or RNTuple).
5
6This script converts pickled muon data to ROOT format, supporting both TTree and RNTuple output formats.
7The input data should be a NumPy array with columns: px, py, pz, x, y, z, id, w.
8
9Usage:
10 python eminem_importer.py input_file.pkl [options]
11
12Example:
13 python eminem_importer.py muons_FullMC.pkl --output converted_data.root --format rntuple
14"""
15
16import argparse
17import gzip
18import json
19import pickle
20import sys
21from pathlib import Path
22
23import numpy as np
24import ROOT
25import shipunit as u
26
27
29 """
30 Parse command line arguments.
31
32 Returns:
33 argparse.Namespace: Parsed command line arguments
34 """
35 parser = argparse.ArgumentParser(
36 description="Convert pickled muon data to ROOT format (TTree or RNTuple)",
37 formatter_class=argparse.RawDescriptionHelpFormatter,
38 epilog="""
39Examples:
40 %(prog)s muons_FullMC.pkl
41 %(prog)s muons_FullMC.pkl --output my_data.root
42 %(prog)s muons_FullMC.pkl --format rntuple --output my_data.root
43 """,
44 )
45
46 parser.add_argument(
47 "input_file",
48 nargs="?",
49 help="Path to the input pickled data file (.pkl or .pkl.gz)",
50 )
51 parser.add_argument(
52 "-o",
53 "--output",
54 default="converted_from_eminem.root",
55 help="Output ROOT file name (default: %(default)s)",
56 )
57
58 parser.add_argument(
59 "-f",
60 "--format",
61 choices=["ttree", "rntuple"],
62 default="ttree",
63 help="Output format: ttree (default) or rntuple",
64 )
65
66 parser.add_argument(
67 "-t",
68 "--tree-name",
69 default="converted_ntuple",
70 help="Name of the output tree/ntuple (default: %(default)s)",
71 )
72
73 parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
74
75 parser.add_argument("--config", help="Path to custom column configuration file (JSON format)")
76
77 parser.add_argument(
78 "--list-config",
79 action="store_true",
80 help="Print the default column configuration and exit",
81 )
82
83 return parser.parse_args()
84
85
86def load_pickled_data(input_file, verbose=False):
87 """
88 Load pickled data from file, handling both compressed and uncompressed files.
89
90 Args:
91 input_file (str): Path to the input pickled file
92 verbose (bool): Enable verbose output
93
94 Returns:
95 numpy.ndarray: Loaded data array
96
97 Raises:
98 FileNotFoundError: If input file doesn't exist
99 Exception: If file cannot be loaded or has wrong format
100 """
101 input_path = Path(input_file)
102
103 if not input_path.exists():
104 raise FileNotFoundError(f"Input file not found: {input_file}")
105
106 if verbose:
107 print(f"Loading data from: {input_file}")
108
109 try:
110 # Try gzip first (files may be gzipped regardless of extension)
111 try:
112 with gzip.GzipFile(input_file, "rb") as f:
113 data = pickle.load(f)
114 except gzip.BadGzipFile:
115 with open(input_file, "rb") as f:
116 data = pickle.load(f)
117 except Exception as e:
118 raise RuntimeError(f"Failed to load pickled data: {e}") from e
119
120 if isinstance(data, dict):
121 required = ["px", "py", "pz", "x", "y", "z", "pdg_id", "weight"]
122
123 missing = [k for k in required if k not in data]
124 if missing:
125 raise ValueError(f"Missing keys in dict: {missing}")
126
127 # convert to column stack (ONLY here, once)
128 stacked = np.column_stack(
129 [
130 np.asarray(data["px"]),
131 np.asarray(data["py"]),
132 np.asarray(data["pz"]),
133 np.asarray(data["x"]),
134 np.asarray(data["y"]),
135 np.asarray(data["z"]),
136 np.asarray(data["pdg_id"]),
137 np.asarray(data["weight"]),
138 ]
139 )
140
141 if verbose:
142 print(f"Loaded data shape: {stacked.shape}")
143 print(f"Data type: {stacked.dtype}")
144
145 return stacked
146
147 if verbose:
148 print(f"Loaded data shape: {data.shape}")
149 print(f"Data type: {data.dtype}")
150
151 # Validate data format
152 if len(data.shape) != 2 or data.shape[1] != 8:
153 raise ValueError(f"Expected data with shape (N, 8), got {data.shape}")
154
155 return data
156
157
158def load_custom_config(config_path):
159 """
160 Load custom column configuration from JSON file.
161
162 Args:
163 config_path (str): Path to the configuration file
164
165 Returns:
166 dict: Custom configuration dictionary
167 """
168 try:
169 with open(config_path) as f:
170 custom_config = json.load(f)
171 return custom_config
172 except Exception as e:
173 raise RuntimeError(f"Failed to load configuration file: {e}") from e
174
175
176def parse_custom_config_units(custom_config):
177 """
178 Parse custom configuration and convert string unit representations to shipunit objects.
179
180 Args:
181 custom_config (dict): Custom configuration dictionary
182
183 Returns:
184 dict: Configuration with parsed units
185 """
186 # Common unit mappings for shipunit
187 unit_map = {
188 "m": u.m,
189 "cm": u.cm,
190 "mm": u.mm,
191 "km": u.km,
192 "GeV": u.GeV,
193 "MeV": u.MeV,
194 "keV": u.keV,
195 "eV": u.eV,
196 "s": u.s,
197 "ms": u.ms,
198 "ns": u.ns,
199 "kg": u.kg,
200 "g": u.g,
201 # Add more mappings as needed
202 }
203
204 parsed_config = {}
205 for col_name, col_config in custom_config.items():
206 parsed_col_config = col_config.copy()
207
208 # Parse unit strings to shipunit objects
209 if "unit" in col_config and isinstance(col_config["unit"], str):
210 unit_str = col_config["unit"]
211 if unit_str in unit_map:
212 parsed_col_config["unit"] = unit_map[unit_str]
213 else:
214 print(f"Warning: Unknown unit '{unit_str}' for column '{col_name}', ignoring unit")
215 parsed_col_config.pop("unit", None)
216
217 if "offset_unit" in col_config and isinstance(col_config["offset_unit"], str):
218 offset_unit_str = col_config["offset_unit"]
219 if offset_unit_str in unit_map:
220 parsed_col_config["offset_unit"] = unit_map[offset_unit_str]
221 else:
222 print(f"Warning: Unknown offset unit '{offset_unit_str}' for column '{col_name}', ignoring offset unit")
223 parsed_col_config.pop("offset_unit", None)
224
225 parsed_config[col_name] = parsed_col_config
226
227 return parsed_config
228
229
231 """Print the default configuration in JSON format."""
232 config = get_column_config()
233
234 # Convert to JSON-serializable format
235 json_config = {}
236 for col_name, col_config in config.items():
237 json_col_config = {}
238 for key, value in col_config.items():
239 if key == "unit" or key == "offset_unit":
240 # Convert units to string representation
241 if value is not None:
242 # Try to get a reasonable string representation
243 if hasattr(value, "_name"):
244 json_col_config[key] = value._name
245 else:
246 json_col_config[key] = str(value)
247 else:
248 json_col_config[key] = None
249 else:
250 json_col_config[key] = value
251 json_config[col_name] = json_col_config
252
253 print("Default column configuration:")
254 print(json.dumps(json_config, indent=2))
255
256
257def get_column_config(custom_config_path=None):
258 """
259 Define column configuration with transformations and units.
260
261 Args:
262 custom_config_path (str, optional): Path to custom configuration file
263
264 Returns:
265 dict: Column configuration dictionary
266 """
267 # Load custom configuration if provided
268 if custom_config_path:
269 try:
270 custom_config = load_custom_config(custom_config_path)
271 # Parse string unit representations back to shipunit objects
272 return parse_custom_config_units(custom_config)
273 except Exception as e:
274 print(f"Error: Could not load custom config: {e}")
275 sys.exit(1)
276
277 # Default configuration for each column
278 # Each column can have: index, unit, offset, scale_factor, description
279 config = {
280 "px": {
281 "index": 0,
282 "unit": u.GeV, # Momentum in GeV
283 "description": "Momentum x-component",
284 "type": "float64",
285 },
286 "py": {
287 "index": 1,
288 "unit": u.GeV, # Momentum in GeV
289 "description": "Momentum y-component",
290 "type": "float64",
291 },
292 "pz": {
293 "index": 2,
294 "unit": u.GeV, # Momentum in GeV
295 "description": "Momentum z-component",
296 "type": "float64",
297 },
298 "x": {
299 "index": 3,
300 "unit": u.m, # Position in meters
301 "description": "Position x-coordinate",
302 "type": "float64",
303 },
304 "y": {
305 "index": 4,
306 "unit": u.m, # Position in meters
307 "description": "Position y-coordinate",
308 "type": "float64",
309 },
310 "z": {
311 "index": 5,
312 "unit": u.m, # Position in meters
313 "offset": -68.500, # Apply z-offset
314 "offset_unit": u.m,
315 "description": "Position z-coordinate (with detector offset)",
316 "type": "float64",
317 },
318 "id": {
319 "index": 6,
320 "description": "Particle ID",
321 "type": "int32",
322 },
323 "w": {
324 "index": 7,
325 "description": "Weight",
326 "type": "float64",
327 },
328 }
329
330 return config
331
332
333def apply_column_transformation(data_column, config):
334 """
335 Apply transformations to a data column based on its configuration.
336
337 Args:
338 data_column (numpy.ndarray): Raw data column
339 config (dict): Column configuration
340
341 Returns:
342 numpy.ndarray or shipunit quantity: Transformed data column
343 """
344 result = data_column.copy()
345
346 # Apply scale factor if specified
347 if "scale_factor" in config:
348 result = result * config["scale_factor"]
349
350 # Apply offset (before units if both are present)
351 if "offset" in config:
352 offset = config["offset"]
353 if config.get("offset_unit") is not None:
354 # If we have units, we need to handle the offset carefully
355 if config.get("unit") is not None:
356 # Both result and offset will have units
357 result = result * config["unit"] + offset * config["offset_unit"]
358 else:
359 # Only offset has units
360 result = result + offset * config["offset_unit"]
361 else:
362 # No units for offset; still apply the column unit if one is set
363 if config.get("unit") is not None:
364 result = result * config["unit"] + offset
365 else:
366 result = result + offset
367
368 # Apply units (if not already applied above)
369 if config.get("unit") is not None and "offset" not in config:
370 result = result * config["unit"]
371
372 if "type" in config:
373 result = result.astype(config["type"])
374
375 return result
376
377
378def create_root_dataframe(data, verbose=False, custom_config_path=None):
379 """
380 Create ROOT RDataFrame from numpy data using configuration-driven approach.
381
382 Args:
383 data (numpy.ndarray): Input data array with columns [px, py, pz, x, y, z, id, w]
384 verbose (bool): Enable verbose output
385 custom_config_path (str, optional): Path to custom configuration file
386
387 Returns:
388 ROOT.RDataFrame: ROOT dataframe with the converted data
389 """
390 if verbose:
391 print("Creating ROOT RDataFrame...")
392
393 # Get column configuration
394 column_config = get_column_config(custom_config_path)
395
396 # Create dataframe dictionary using configuration
397 df_dict = {}
398
399 for col_name, config in column_config.items():
400 # Extract raw data column
401 raw_data = data[:, config["index"]]
402
403 # Apply transformations
404 transformed_data = apply_column_transformation(raw_data, config)
405
406 # Store in dictionary
407 df_dict[col_name] = transformed_data
408
409 if verbose:
410 print(f" {col_name}: {config.get('description', 'No description')}")
411 if config.get("unit"):
412 print(f" Unit: {config['unit']}")
413 if config.get("offset"):
414 offset_unit = config.get("offset_unit", "")
415 print(f" Offset: {config['offset']} {offset_unit}")
416 if config.get("scale_factor"):
417 print(f" Scale factor: {config['scale_factor']}")
418
419 df = ROOT.RDF.FromNumpy(df_dict)
420
421 if verbose:
422 print(f"Created RDataFrame with {df.Count().GetValue()} entries")
423
424 return df
425
426
427def save_root_file(df, output_file, tree_name, output_format, verbose=False):
428 """
429 Save ROOT dataframe to file in specified format.
430
431 Args:
432 df (ROOT.RDataFrame): Input dataframe
433 output_file (str): Output file path
434 tree_name (str): Name of the tree/ntuple
435 output_format (str): Output format ('ttree' or 'rntuple')
436 verbose (bool): Enable verbose output
437 """
438 if verbose:
439 print(f"Saving to {output_file} in {output_format} format...")
440
441 # Set up snapshot options
442 opts = ROOT.RDF.RSnapshotOptions()
443
444 if output_format == "rntuple":
445 opts.fOutputFormat = ROOT.RDF.ESnapshotOutputFormat.kRNTuple
446 if verbose:
447 print("Using RNTuple format")
448 else:
449 # TTree is the default format
450 if verbose:
451 print("Using TTree format")
452
453 # Save the data
454 df.Snapshot(tree_name, output_file, "", opts)
455
456 if verbose:
457 print(f"Successfully saved data to {output_file}")
458
459
460def main():
461 """Convert pickled muon data to ROOT format (TTree or RNTuple)."""
462 args = parse_arguments()
463
464 # Handle special options
465 if args.list_config:
467 return
468
469 if not args.input_file:
470 print("Error: input_file is required unless --list-config is used", file=sys.stderr)
471 sys.exit(2)
472
473 try:
474 # Load the pickled data
475 data = load_pickled_data(args.input_file, args.verbose)
476
477 # Create ROOT dataframe
478 df = create_root_dataframe(data, args.verbose, args.config)
479
480 # Save to ROOT file
481 save_root_file(df, args.output, args.tree_name, args.format, args.verbose)
482
483 print("Conversion completed successfully!")
484 print(f"Input: {args.input_file}")
485 print(f"Output: {args.output} ({args.format} format)")
486
487 except Exception as e:
488 print(f"Error: {e}", file=sys.stderr)
489 sys.exit(1)
490
491
492if __name__ == "__main__":
493 main()
load_pickled_data(input_file, verbose=False)
save_root_file(df, output_file, tree_name, output_format, verbose=False)
create_root_dataframe(data, verbose=False, custom_config_path=None)
apply_column_transformation(data_column, config)
get_column_config(custom_config_path=None)
parse_custom_config_units(custom_config)