-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtree.py
214 lines (169 loc) · 5.49 KB
/
tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""
Display tools for TTrees.
"""
from __future__ import annotations
import dataclasses
import functools
from pathlib import Path
from typing import Any, TypedDict
import uproot
import uproot.reading
from rich.console import Console
from rich.markup import escape
from rich.text import Text
from rich.tree import Tree
console = Console()
__all__ = (
"MetaDict",
"UprootEntry",
"console",
"make_tree",
"print_tree",
"process_item",
)
def __dir__() -> tuple[str, ...]:
return __all__
class MetaDictRequired(TypedDict, total=True):
label_text: Text
label_icon: str
class MetaDict(MetaDictRequired, total=False):
guide_style: str
@dataclasses.dataclass
class UprootEntry:
path: str
item: Any
@property
def is_dir(self) -> bool:
if isinstance(self.item, uproot.reading.ReadOnlyDirectory):
return True
if isinstance(self.item, uproot.behaviors.TBranch.HasBranches):
return len(self.item.branches) > 0
return False
def meta(self) -> MetaDict:
return process_item(self.item)
def label(self) -> Text:
meta = self.meta()
return Text.assemble(meta["label_icon"], meta["label_text"])
def tree_args(self) -> dict[str, Any]:
d: dict[str, Text | str] = {"label": self.label()}
if "guide_style" in self.meta():
d["guide_style"] = self.meta()["guide_style"]
return d
@property
def children(self) -> list[UprootEntry]:
if not self.is_dir:
return []
if isinstance(self.item, uproot.reading.ReadOnlyDirectory):
items = {
key.split(";")[0]
for key in self.item.keys() # noqa: SIM118
if "/" not in key
}
elif isinstance(self.item, uproot.behaviors.TBranch.HasBranches):
items = {item.name for item in self.item.branches}
else:
items = {obj.name.split(";")[0] for obj in self.item.branches}
return [
UprootEntry(f"{self.path}/{key}", self.item[key]) for key in sorted(items)
]
def make_tree(node: UprootEntry, *, tree: Tree | None = None) -> Tree:
"""
Given an object, build a rich.tree.Tree output.
"""
tree = Tree(**node.tree_args()) if tree is None else tree.add(**node.tree_args())
for child in node.children:
make_tree(child, tree=tree)
return tree
@functools.singledispatch
def process_item(uproot_object: Any) -> MetaDict:
"""
Given an unknown object, return a rich.tree.Tree output. Specialize for known objects.
"""
name = getattr(uproot_object, "name", "<unnamed>")
classname = getattr(uproot_object, "classname", uproot_object.__class__.__name__)
label_text = Text.assemble(
(f"{name} ", "bold"),
(classname, "italic"),
)
return MetaDict(label_icon="❓ ", label_text=label_text)
@process_item.register
def _process_item_tfile(
uproot_object: uproot.reading.ReadOnlyDirectory,
) -> MetaDict:
"""
Given an TFile, return a rich.tree.Tree output.
"""
path = Path(uproot_object.file_path)
if uproot_object.path:
# path is to a TDirectory on tree
path_name = escape(uproot_object.path[0])
link_text = f"file://{path}:/{path_name}"
else:
# path is the top of the tree: the file
path_name = escape(path.name)
link_text = f"file://{path}"
label_text = Text.from_markup(f"[link {link_text}]{path_name}")
return MetaDict(
label_icon="📁 ",
label_text=label_text,
guide_style="bold bright_blue",
)
@process_item.register
def _process_item_ttree(uproot_object: uproot.TTree) -> MetaDict:
"""
Given an tree, return a rich.tree.Tree output.
"""
label_text = Text.assemble(
(f"{uproot_object.name} ", "bold"),
f"({uproot_object.num_entries:g})",
)
return MetaDict(
label_icon="🌴 ",
label_text=label_text,
guide_style="bold bright_green",
)
@process_item.register
def _process_item_tbranch(uproot_object: uproot.TBranch) -> MetaDict:
"""
Given an branch, return a rich.tree.Tree output.
"""
jagged = isinstance(
uproot_object.interpretation, uproot.interpretation.jagged.AsJagged
)
icon = "🍃 " if jagged else "🍁 "
if len(uproot_object.branches):
icon = "🌿 "
label_text = Text.assemble(
(f"{uproot_object.name} ", "bold"),
(f"{uproot_object.typename}", "italic"),
)
return MetaDict(
label_icon=icon,
label_text=label_text,
guide_style="bold bright_green",
)
@process_item.register
def _process_item_th(uproot_object: uproot.behaviors.TH1.Histogram) -> MetaDict:
"""
Given an histogram, return a rich.tree.Tree output.
"""
icon = "📊 " if uproot_object.kind == "COUNT" else "📈 "
sizes = " × ".join(f"{len(ax)}" for ax in uproot_object.axes)
label_text = Text.assemble(
(f"{uproot_object.name} ", "bold"),
(f"{uproot_object.classname} ", "italic"),
f"({sizes})",
)
return MetaDict(
label_icon=icon,
label_text=label_text,
)
# pylint: disable-next=redefined-outer-name
def print_tree(entry: str, *, console: Console = console) -> None:
"""
Prints a tree given a specification string. Currently, that must be a
single filename. Colons are not allowed currently in the filename.
"""
upfile = uproot.open(entry)
tree = make_tree(UprootEntry("/", upfile))
console.print(tree)