4from __future__
import annotations
13 dict class that can address its keys as fields, e.g.
24 for k, v
in self.items():
25 if isinstance(v, AttrDict):
37 rv = pickle.loads(buff)
43 """Deserialize config from JSON string"""
45 def dict_to_attrdict(d):
46 """Recursively convert dict to AttrDict"""
47 if isinstance(d, dict):
49 for k, v
in d.items():
50 result[k] = dict_to_attrdict(v)
52 elif isinstance(d, list):
53 return [dict_to_attrdict(item)
for item
in d]
57 rv = json.loads(json_str)
60 for k, v
in rv.items():
61 self[k] = dict_to_attrdict(v)
66 for k, v
in self.items():
67 if isinstance(v, AttrDict):
74 return pickle.dumps(self)
77 """Serialize config to JSON string"""
78 return json.dumps(self, indent=2, default=str)
81 with open(os.path.expandvars(filename),
"rb")
as fh:
85 def dump(self, filename) -> int:
86 with open(os.path.expandvars(filename),
"wb")
as fh:
87 return fh.write(self.
dumps())
90 return "ShipGeoConfig:\n " +
"\n ".join(
91 [f
"{k}: {self[k].__str__()}" for k
in sorted(self.keys())
if not k.startswith(
"_")]
95def load_from_root_file(root_file, key: str =
"ShipGeo") -> Config:
97 Load configuration from ROOT file.
99 Automatically detects
and handles both formats:
100 - New format: JSON string (stored
as std::string
or TObjString)
101 - Old format: Pickled Python object
104 root_file: Either a ROOT.TFile object
or a string path to ROOT file
105 key: The key name
for the stored config (default:
'ShipGeo')
108 Config object
with the loaded configuration
113 if isinstance(root_file, str):
114 root_file = ROOT.TFile.Open(root_file)
119 config_obj = root_file.Get(key)
121 raise ValueError(f
"No object with key '{key}' found in ROOT file")
124 content_str = str(config_obj)
127 if content_str.startswith(
"{"):
130 config.loads_json(content_str)
134 pickle_bytes = content_str.encode(
"latin-1")
135 config = pickle.loads(pickle_bytes)
138 if not isinstance(config, Config):
None __init__(self, *args, **kwargs)
None __init__(self, *args, **kwargs)
def loads_json(self, str json_str)
def loads(self, bytes buff)
int open(const char *, int)
Opens a file descriptor.