2 from __future__
import print_function
9 parser = argparse.ArgumentParser(description=
"Convert arbitrary ROOT file to SQLite database, mapping TTrees to tables and converting TObjects to JSON.")
11 parser.add_argument(
'inputfile', help=
'ROOT file to read')
12 parser.add_argument(
'-o',
'--output', help=
'SQLite file to write', default=
'root.sqlite')
13 args = parser.parse_args()
15 f = ROOT.TFile.Open(args.inputfile)
16 db = sqlite3.connect(args.output)
20 inf = re.compile(
"([- \[])inf([,}\]])")
21 nan = re.compile(
"([- \[])nan([,}\]])")
24 if isinstance(x, ROOT.string):
29 if isinstance(x, int):
31 if isinstance(x, float):
33 if isinstance(x, long):
37 rootobj =
unicode(ROOT.TBufferJSON.ConvertToJSON(x))
39 clean = nan.sub(
'\\g<1>0\\g<2>', inf.sub(
'\\g<1>1e38\\g<2>', rootobj))
40 obj = json.loads(clean)
41 jsonobj = json.dumps(obj, allow_nan=
False)
43 except Exception
as e:
44 return json.dumps({
"root2sqlite_error": e.__repr__(),
"root2sqlite_object": x.__repr__()})
49 if s.lower()
in SQLKWDs:
55 name = name.replace(
"/",
"_")
56 branches = [b.GetName()
for b
in ttree.GetListOfBranches()]
58 create =
"CREATE TABLE %s(%s);" % (name, colnames)
62 for i
in range(ttree.GetEntries()):
64 vals = tuple([
tosqlite(getattr(ttree, b))
for b
in branches])
66 insert =
"INSERT INTO %s(%s) VALUES (%s);" % (name, colnames,
",".
join([
"?"] * len(branches)))
68 db.executemany(insert, data)
71 xml_re = re.compile(
r"^<(.+)>(.+)=(.+)<\/\1>$")
72 def parse_directory(di):
73 directory = rootfile.GetDirectory(di)
74 for key
in directory.GetListOfKeys():
76 rtype = key.GetClassName()
77 fullpath =
"%s/%s" % (di, entry)
if di !=
"" else entry
78 if (rtype ==
"TDirectoryFile"):
79 for k, v, t
in parse_directory(fullpath):
82 obj = rootfile.Get(fullpath)
84 yield (fullpath, obj, rtype)
87 m = xml_re.search(entry)
92 fp =
"%s/%s" % (di, name)
93 yield (fp, value, rtype)
96 path_fix = re.compile(
r"^\/Run \d+")
97 for fullname, obj, rtype
in parse_directory(
""):
98 yield fullname, obj, rtype
101 name = name.replace(
"/",
"_")
102 create =
"CREATE TABLE %s(key, value);" % name
106 for k, v
in dictionary.iteritems():
109 insert =
"INSERT INTO %s(key, value) VALUES (?,?);" % name
111 db.executemany(insert, data)
119 basic_objects[name] = obj