4"""Convert pickled muon data to ROOT format (TTree or RNTuple).
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.
10 python eminem_importer.py input_file.pkl [options]
13 python eminem_importer.py muons_FullMC.pkl --output converted_data.root --format rntuple
21from pathlib
import Path
30 Parse command line arguments.
33 argparse.Namespace: Parsed command line arguments
35 parser = argparse.ArgumentParser(
36 description=
"Convert pickled muon data to ROOT format (TTree or RNTuple)",
37 formatter_class=argparse.RawDescriptionHelpFormatter,
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
49 help=
"Path to the input pickled data file (.pkl or .pkl.gz)",
54 default=
"converted_from_eminem.root",
55 help=
"Output ROOT file name (default: %(default)s)",
61 choices=[
"ttree",
"rntuple"],
63 help=
"Output format: ttree (default) or rntuple",
69 default=
"converted_ntuple",
70 help=
"Name of the output tree/ntuple (default: %(default)s)",
73 parser.add_argument(
"-v",
"--verbose", action=
"store_true", help=
"Enable verbose output")
75 parser.add_argument(
"--config", help=
"Path to custom column configuration file (JSON format)")
80 help=
"Print the default column configuration and exit",
83 return parser.parse_args()
88 Load pickled data from file, handling both compressed and uncompressed files.
91 input_file (str): Path to the input pickled file
92 verbose (bool): Enable verbose output
95 numpy.ndarray: Loaded data array
98 FileNotFoundError: If input file doesn't exist
99 Exception: If file cannot be loaded or has wrong format
101 input_path = Path(input_file)
103 if not input_path.exists():
104 raise FileNotFoundError(f
"Input file not found: {input_file}")
107 print(f
"Loading data from: {input_file}")
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
120 if isinstance(data, dict):
121 required = [
"px",
"py",
"pz",
"x",
"y",
"z",
"pdg_id",
"weight"]
123 missing = [k
for k
in required
if k
not in data]
125 raise ValueError(f
"Missing keys in dict: {missing}")
128 stacked = np.column_stack(
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"]),
142 print(f
"Loaded data shape: {stacked.shape}")
143 print(f
"Data type: {stacked.dtype}")
148 print(f
"Loaded data shape: {data.shape}")
149 print(f
"Data type: {data.dtype}")
152 if len(data.shape) != 2
or data.shape[1] != 8:
153 raise ValueError(f
"Expected data with shape (N, 8), got {data.shape}")
160 Load custom column configuration from JSON file.
163 config_path (str): Path to the configuration file
166 dict: Custom configuration dictionary
169 with open(config_path)
as f:
170 custom_config = json.load(f)
172 except Exception
as e:
173 raise RuntimeError(f
"Failed to load configuration file: {e}")
from e
178 Parse custom configuration and convert string unit representations to shipunit objects.
181 custom_config (dict): Custom configuration dictionary
184 dict: Configuration with parsed units
205 for col_name, col_config
in custom_config.items():
206 parsed_col_config = col_config.copy()
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]
214 print(f
"Warning: Unknown unit '{unit_str}' for column '{col_name}', ignoring unit")
215 parsed_col_config.pop(
"unit",
None)
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]
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)
225 parsed_config[col_name] = parsed_col_config
231 """Print the default configuration in JSON format."""
236 for col_name, col_config
in config.items():
238 for key, value
in col_config.items():
239 if key ==
"unit" or key ==
"offset_unit":
241 if value
is not None:
243 if hasattr(value,
"_name"):
244 json_col_config[key] = value._name
246 json_col_config[key] = str(value)
248 json_col_config[key] =
None
250 json_col_config[key] = value
251 json_config[col_name] = json_col_config
253 print(
"Default column configuration:")
254 print(json.dumps(json_config, indent=2))
259 Define column configuration with transformations and units.
262 custom_config_path (str, optional): Path to custom configuration file
265 dict: Column configuration dictionary
268 if custom_config_path:
273 except Exception
as e:
274 print(f
"Error: Could not load custom config: {e}")
283 "description":
"Momentum x-component",
289 "description":
"Momentum y-component",
295 "description":
"Momentum z-component",
301 "description":
"Position x-coordinate",
307 "description":
"Position y-coordinate",
315 "description":
"Position z-coordinate (with detector offset)",
320 "description":
"Particle ID",
325 "description":
"Weight",
335 Apply transformations to a data column based on its configuration.
338 data_column (numpy.ndarray): Raw data column
339 config (dict): Column configuration
342 numpy.ndarray or shipunit quantity: Transformed data column
344 result = data_column.copy()
347 if "scale_factor" in config:
348 result = result * config[
"scale_factor"]
351 if "offset" in config:
352 offset = config[
"offset"]
353 if config.get(
"offset_unit")
is not None:
355 if config.get(
"unit")
is not None:
357 result = result * config[
"unit"] + offset * config[
"offset_unit"]
360 result = result + offset * config[
"offset_unit"]
363 if config.get(
"unit")
is not None:
364 result = result * config[
"unit"] + offset
366 result = result + offset
369 if config.get(
"unit")
is not None and "offset" not in config:
370 result = result * config[
"unit"]
373 result = result.astype(config[
"type"])
380 Create ROOT RDataFrame from numpy data using configuration-driven approach.
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
388 ROOT.RDataFrame: ROOT dataframe with the converted data
391 print(
"Creating ROOT RDataFrame...")
399 for col_name, config
in column_config.items():
401 raw_data = data[:, config[
"index"]]
407 df_dict[col_name] = transformed_data
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']}")
419 df = ROOT.RDF.FromNumpy(df_dict)
422 print(f
"Created RDataFrame with {df.Count().GetValue()} entries")
429 Save ROOT dataframe to file in specified format.
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
439 print(f
"Saving to {output_file} in {output_format} format...")
442 opts = ROOT.RDF.RSnapshotOptions()
444 if output_format ==
"rntuple":
445 opts.fOutputFormat = ROOT.RDF.ESnapshotOutputFormat.kRNTuple
447 print(
"Using RNTuple format")
451 print(
"Using TTree format")
454 df.Snapshot(tree_name, output_file,
"", opts)
457 print(f
"Successfully saved data to {output_file}")
461 """Convert pickled muon data to ROOT format (TTree or RNTuple)."""
469 if not args.input_file:
470 print(
"Error: input_file is required unless --list-config is used", file=sys.stderr)
481 save_root_file(df, args.output, args.tree_name, args.format, args.verbose)
483 print(
"Conversion completed successfully!")
484 print(f
"Input: {args.input_file}")
485 print(f
"Output: {args.output} ({args.format} format)")
487 except Exception
as e:
488 print(f
"Error: {e}", file=sys.stderr)
492if __name__ ==
"__main__":
load_pickled_data(input_file, verbose=False)
save_root_file(df, output_file, tree_name, output_format, verbose=False)
load_custom_config(config_path)
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)