FairShip
Loading...
Searching...
No Matches
ShipGeoConfig.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 Collaboration
3
4from __future__ import annotations
5
6import json
7import os
8import pickle
9from typing import TYPE_CHECKING, Any
10
11
12class AttrDict(dict):
13 """
14 dict class that can address its keys as fields, e.g.
15 d['key'] = 1
16 assert d.key == 1
17 """
18
19 if TYPE_CHECKING:
20 # Attributes are populated dynamically from dict keys via
21 # `self.__dict__ = self`. Declare them as Any for the type checker
22 # so geometry-config field access (`ShipGeo.target.z` etc.) checks.
23 def __getattr__(self, name: str) -> Any: ...
24 def __setattr__(self, name: str, value: Any) -> None: ...
25
26 def __init__(self, *args, **kwargs) -> None:
27 super().__init__(*args, **kwargs)
28 self.__dict__ = self
29
30 def clone(self) -> AttrDict:
31 result = AttrDict()
32 for k, v in self.items():
33 if isinstance(v, AttrDict):
34 result[k] = v.clone()
35 else:
36 result[k] = v
37 return result
38
39
41 def __init__(self, *args, **kwargs) -> None:
42 super().__init__(*args, **kwargs)
43
44 def loads(self, buff: bytes):
45 rv = pickle.loads(buff)
46 self.clear()
47 self.update(rv)
48 return self
49
50 def loads_json(self, json_str: str):
51 """Deserialize config from JSON string"""
52
53 def dict_to_attrdict(d):
54 """Recursively convert dict to AttrDict"""
55 if isinstance(d, dict):
56 result = AttrDict()
57 for k, v in d.items():
58 result[k] = dict_to_attrdict(v)
59 return result
60 elif isinstance(d, list):
61 return [dict_to_attrdict(item) for item in d]
62 else:
63 return d
64
65 rv = json.loads(json_str)
66 self.clear()
67 # Convert nested dicts to AttrDict
68 for k, v in rv.items():
69 self[k] = dict_to_attrdict(v)
70 return self
71
72 def clone(self) -> Config:
73 result = Config()
74 for k, v in self.items():
75 if isinstance(v, AttrDict):
76 result[k] = v.clone()
77 else:
78 result[k] = v
79 return result
80
81 def dumps(self) -> bytes:
82 return pickle.dumps(self)
83
84 def dumps_json(self) -> str:
85 """Serialize config to JSON string"""
86 return json.dumps(self, indent=2, default=str)
87
88 def load(self, filename):
89 with open(os.path.expandvars(filename), "rb") as fh:
90 self.loads(fh.read())
91 return self
92
93 def dump(self, filename) -> int:
94 with open(os.path.expandvars(filename), "wb") as fh:
95 return fh.write(self.dumps())
96
97 def __str__(self) -> str:
98 return "ShipGeoConfig:\n " + "\n ".join(
99 [f"{k}: {self[k].__str__()}" for k in sorted(self.keys()) if not k.startswith("_")]
100 )
101
102
103def load_from_root_file(root_file, key: str = "ShipGeo") -> Config:
104 """
105 Load configuration from ROOT file.
106
107 Automatically detects and handles both formats:
108 - New format: JSON string (stored as std::string or TObjString)
109 - Old format: Pickled Python object
110
111 Args:
112 root_file: Either a ROOT.TFile object or a string path to ROOT file
113 key: The key name for the stored config (default: 'ShipGeo')
114
115 Returns:
116 Config object with the loaded configuration
117 """
118 import ROOT
119
120 own_file = False
121 if isinstance(root_file, str):
122 root_file = ROOT.TFile.Open(root_file)
123 own_file = True
124
125 try:
126 # Get the object (could be std::string or TObjString)
127 config_obj = root_file.Get(key)
128 if not config_obj:
129 raise ValueError(f"No object with key '{key}' found in ROOT file")
130
131 # Convert to Python string
132 content_str = str(config_obj)
133
134 # Auto-detect format by checking first character
135 if content_str.startswith("{"):
136 # JSON format - parse it
137 config = Config()
138 config.loads_json(content_str)
139 else:
140 # Assume pickle format - unpickle it
141 # Convert to bytes for pickle (using latin-1 encoding)
142 pickle_bytes = content_str.encode("latin-1")
143 config = pickle.loads(pickle_bytes)
144
145 # Ensure it's a Config object (might be if it was pickled as Config)
146 if not isinstance(config, Config):
147 # Wrap in Config if needed
148 c = Config()
149 c.update(config)
150 config = c
151
152 return config
153
154 finally:
155 if own_file:
156 root_file.Close()
None __init__(self, *args, **kwargs)
None __setattr__(self, str name, Any value)
Any __getattr__(self, str name)
loads_json(self, str json_str)
None __init__(self, *args, **kwargs)
load(self, filename)
loads(self, bytes buff)
int dump(self, filename)
Config load_from_root_file(root_file, str key="ShipGeo")