Coverage for hierarchicalsoftmax/treedict.py: 100.00%

219 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 12:41 +0000

1import copy 

2import fnmatch 

3from pathlib import Path 

4from attrs import define, field 

5from collections import UserDict 

6import pickle 

7from collections import Counter 

8from rich.progress import track 

9import typer 

10 

11from .nodes import SoftmaxNode 

12 

13 

14@define 

15class NodeDetail: 

16 """ 

17 Stores metadata for a key in the TreeDict. 

18 

19 Attributes: 

20 partition (int): The partition ID this key belongs to. 

21 node (SoftmaxNode): The node in the classification tree associated with the key. 

22 node_id (int): The index of the node in the tree (used during pickling). 

23 """ 

24 partition:int 

25 node:SoftmaxNode = field(default=None, eq=False) 

26 node_id:int = None 

27 

28 def __getstate__(self): 

29 return (self.partition, self.node_id) 

30 

31 def __setstate__(self, state): 

32 self.partition, self.node_id = state 

33 self.node = None 

34 

35 

36class AlreadyExists(Exception): 

37 pass 

38 

39 

40class TreeDict(UserDict): 

41 def __init__(self, classification_tree:SoftmaxNode|None=None): 

42 """ 

43 Initialize a TreeDict. 

44 

45 Args: 

46 classification_tree (SoftmaxNode, optional): The root of the classification tree. 

47 If not provided, a new root node named "root" will be created. 

48 """ 

49 super().__init__() 

50 self.classification_tree = classification_tree or SoftmaxNode("root") 

51 

52 def add(self, key:str, node:SoftmaxNode, partition:int) -> NodeDetail: 

53 """ 

54 Associate a key with a node and a partition. 

55 

56 Args: 

57 key (str): The unique identifier for the item. 

58 node (SoftmaxNode): The node in the classification tree to associate with the key. 

59 partition (int): The partition index for the key. 

60 

61 Raises: 

62 AlreadyExists: If the key already exists with a different node. 

63 

64 Returns: 

65 NodeDetail: The metadata object for the added key. 

66 """ 

67 assert node.root == self.classification_tree 

68 if key in self: 

69 old_node = self.node(key) 

70 if not node == old_node: 

71 raise AlreadyExists(f"Accession {key} already exists in TreeDict at node {self.node(key)}. Cannot change to {node}") 

72 

73 detail = NodeDetail( 

74 partition=partition, 

75 node=node, 

76 ) 

77 self[key] = detail 

78 return detail 

79 

80 def set_indexes(self): 

81 """ 

82 Ensure the tree has assigned node indexes, and record the node_id for each key. 

83 """ 

84 self.classification_tree.set_indexes_if_unset() 

85 for detail in self.values(): 

86 if detail.node: 

87 detail.node_id = self.classification_tree.node_to_id[detail.node] 

88 

89 def save(self, path:Path): 

90 """ 

91 Save the TreeDict to a pickle file. 

92 

93 Args: 

94 path (Path): The file path to save the TreeDict. 

95 """ 

96 path = Path(path) 

97 path.parent.mkdir(exist_ok=True, parents=True) 

98 

99 self.set_indexes() 

100 with open(path, 'wb') as handle: 

101 pickle.dump(self, handle, protocol=pickle.HIGHEST_PROTOCOL) 

102 

103 @classmethod 

104 def load(self, path:Path): 

105 """ 

106 Load a TreeDict from a pickle file. 

107 

108 Args: 

109 path (Path): The path to the serialized TreeDict. 

110 

111 Returns: 

112 TreeDict: The loaded TreeDict instance. 

113 """ 

114 with open(path, 'rb') as handle: 

115 return pickle.load(handle) 

116 

117 def node(self, key:str): 

118 """ 

119 Retrieve the node associated with a key. 

120 

121 Args: 

122 key (str): The key for which to retrieve the node. 

123 

124 Returns: 

125 SoftmaxNode: The node corresponding to the key. 

126 """ 

127 detail = self[key] 

128 if detail.node is not None: 

129 return detail.node 

130 return self.classification_tree.node_list[detail.node_id] 

131 

132 def keys_in_partition(self, partition:int): 

133 """ 

134 Yield all keys that belong to a given partition. 

135 

136 Args: 

137 partition (int): The partition to filter by. 

138 

139 Yields: 

140 str: Keys in the specified partition. 

141 """ 

142 for key, detail in self.items(): 

143 if detail.partition == partition: 

144 yield key 

145 

146 def keys(self, partition:int|None = None): 

147 """ 

148 Return keys in the TreeDict, optionally filtering by partition. 

149 

150 Args: 

151 partition (int | None): The partition to filter keys by. If None, return all keys. 

152 

153 Returns: 

154 Iterator[str]: An iterator over the keys. 

155 """ 

156 return super().keys() if partition is None else self.keys_in_partition(partition) 

157 

158 def set_partition(self, pattern:str, partition:int) -> None: 

159 """ 

160 Assign a partition to every key matching a shell-style pattern. 

161 

162 Args: 

163 pattern (str): A pattern for keys, using the syntax of `fnmatch` (e.g. ``"NC_*"``). 

164 partition (int): The partition to assign to the matching keys. 

165 """ 

166 for key in super().keys(): 

167 if fnmatch.fnmatch(key, pattern): 

168 self[key].partition = partition 

169 

170 def merge(self, other:"TreeDict") -> None: 

171 """ 

172 Merge another TreeDict into this one in place. 

173 

174 Nodes with the same name under matching parents are shared and missing branches are added. 

175 The roots must have the same name. Where a key exists in both, the entry from `other` takes precedence, 

176 keeping its partition and with its node remapped into this tree. `other` is left unchanged. 

177 

178 Args: 

179 other (TreeDict): The TreeDict to merge into this one. 

180 

181 Raises: 

182 ValueError: If the roots of the two classification trees have different names. 

183 """ 

184 if self.classification_tree.name != other.classification_tree.name: 

185 raise ValueError("Cannot merge classification trees with different root names.") 

186 

187 # Resolve saved node IDs before changing the tree's indexes. 

188 existing_nodes = {key: self.node(key) for key in self} 

189 incoming = [(key, other.node(key), detail.partition) for key, detail in other.items()] 

190 source_nodes = list(other.classification_tree.pre_order_iter()) 

191 for node in self.classification_tree.pre_order_iter(): 

192 node.readonly = False 

193 node.softmax_start_index = None 

194 

195 node_map = {other.classification_tree: self.classification_tree} 

196 for node in source_nodes[1:]: 

197 parent = node_map[node.parent] 

198 match = next((child for child in parent.children if child.name == node.name), None) 

199 if match is None: 

200 match = SoftmaxNode( 

201 node.name, 

202 parent=parent, 

203 alpha=node.alpha, 

204 weight=node.weight, 

205 label_smoothing=node.label_smoothing, 

206 gamma=node.gamma, 

207 ) 

208 node_map[node] = match 

209 

210 for key, node in existing_nodes.items(): 

211 self[key].node = node 

212 for key, node, partition in incoming: 

213 self[key] = NodeDetail(partition=partition, node=node_map[node]) 

214 self.set_indexes() 

215 

216 def truncate(self, max_depth:int) -> "TreeDict": 

217 """ 

218 Truncate the classification tree to a specified maximum depth and return a new TreeDict. 

219 

220 Keys deeper than the depth limit will be reassigned to the ancestor node at that depth. 

221 

222 Args: 

223 max_depth (int): The maximum number of ancestor levels to keep. 

224 

225 Returns: 

226 TreeDict: A new truncated TreeDict of the same class as this one. 

227 """ 

228 self.classification_tree.set_indexes_if_unset() 

229 classification_tree = copy.deepcopy(self.classification_tree) 

230 new_treedict = type(self)(classification_tree) 

231 for key in track(self.keys()): 

232 original_node = self.node(key) 

233 node_id = self.classification_tree.node_to_id[original_node] 

234 node = classification_tree.node_list[node_id] 

235 

236 ancestors = node.ancestors 

237 if len(ancestors) >= max_depth: 

238 node = ancestors[max_depth-1] 

239 new_treedict.add(key, node, self[key].partition) 

240 

241 # Remove any nodes that beyond the max depth 

242 for node in new_treedict.classification_tree.pre_order_iter(): 

243 node.readonly = False 

244 node.softmax_start_index = None 

245 if len(node.ancestors) >= max_depth: 

246 node.parent = None 

247 

248 new_treedict.set_indexes() 

249 

250 return new_treedict 

251 

252 def add_counts(self): 

253 """ 

254 Count the number of keys assigned to each node, and store the count in each node. 

255 """ 

256 for node in self.classification_tree.post_order_iter(): 

257 node.count = 0 

258 

259 for key in self.keys(): 

260 node = self.node(key) 

261 node.count += 1 

262 

263 def add_partition_counts(self): 

264 """ 

265 Count the number of keys in each partition per node and store it in the node. 

266 """ 

267 for node in self.classification_tree.post_order_iter(): 

268 node.partition_counts = Counter() 

269 

270 for key, detail in self.items(): 

271 node = self.node(key) 

272 partition = detail.partition 

273 node.partition_counts[partition] += 1 

274 

275 def render(self, count:bool=False, partition_counts:bool=False, alphabetical:bool=False, **kwargs): 

276 """ 

277 Render the tree as text, optionally showing key counts or partition counts. 

278 

279 Args: 

280 count (bool): If True, show the number of keys at each node. 

281 partition_counts (bool): If True, show partition-wise key counts at each node. 

282 alphabetical (bool): If True, sort the children of each node by name. 

283 **kwargs: Additional arguments passed to the underlying tree render method. 

284 

285 Returns: 

286 anytree.RenderTree or str: The rendered tree. 

287 """ 

288 if alphabetical: 

289 kwargs.setdefault("childiter", lambda children: sorted(children, key=lambda child: child.name)) 

290 

291 if partition_counts: 

292 self.add_partition_counts() 

293 for node in self.classification_tree.post_order_iter(): 

294 partition_counts_str = "; ".join([f"{k}->{node.partition_counts[k]}" for k in sorted(node.partition_counts.keys())]) 

295 node.render_str = f"{node.name} {partition_counts_str}" 

296 kwargs['attr'] = "render_str" 

297 elif count: 

298 self.add_counts() 

299 for node in self.classification_tree.post_order_iter(): 

300 node.render_str = f"{node.name} ({node.count})" if getattr(node, "count", 0) else node.name 

301 

302 kwargs['attr'] = "render_str" 

303 

304 return self.classification_tree.render(**kwargs) 

305 

306 def sunburst(self, **kwargs) -> "go.Figure": 

307 """ 

308 Generate a Plotly sunburst plot based on the TreeDict. 

309 

310 Node values are based on the number of keys mapped to each node. 

311 

312 Args: 

313 **kwargs: Additional keyword arguments passed to Plotly layout. 

314 

315 Returns: 

316 plotly.graph_objects.Figure: A sunburst plot. 

317 """ 

318 import plotly.graph_objects as go 

319 

320 self.add_counts() 

321 labels = [] 

322 parents = [] 

323 values = [] 

324 

325 for node in self.classification_tree.pre_order_iter(): 

326 labels.append(node.name) 

327 parents.append(node.parent.name if node.parent else "") 

328 values.append(node.count) 

329 

330 fig = go.Figure(go.Sunburst( 

331 labels=labels, 

332 parents=parents, 

333 values=values, 

334 branchvalues="remainder", 

335 )) 

336 

337 fig.update_layout(margin=dict(t=10, l=10, r=10, b=10), **kwargs) 

338 return fig 

339 

340 def keys_to_file(self, file:Path) -> None: 

341 """ 

342 Write all keys to a text file, one per line. 

343 

344 Args: 

345 file (Path): Path to the output text file. 

346 """ 

347 with open(file, "w") as f: 

348 for key in self.keys(): 

349 print(key, file=f) 

350 

351 def csv(self, file:Path) -> None: 

352 """ 

353 Write all keys, node names and partitions to a CSV file. 

354 

355 Args: 

356 file (Path): Path to the output text file. 

357 """ 

358 with open(file, "w") as f: 

359 print("key,node,partition", file=f) 

360 for key in self.keys(): 

361 detail = self[key] 

362 node = self.node(key) 

363 print(f"{key},{node.name.strip()},{detail.partition}", file=f) 

364 

365 def pickle_tree(self, output:Path): 

366 """ 

367 Save only the classification tree (not the key-to-node mapping) to a pickle file. 

368 

369 Args: 

370 output (Path): Path to the output file. 

371 """ 

372 with open(output, 'wb') as pickle_file: 

373 pickle.dump(self.classification_tree, pickle_file) 

374 

375 

376app = typer.Typer() 

377 

378@app.command() 

379def keys( 

380 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

381 partition:int|None = typer.Option(None,help="The index of the partition to list."), 

382): 

383 """  

384 Prints a list of keys in a TreeDict.  

385  

386 If a partition is given, then only the keys for that partition are given. 

387 """ 

388 treedict = TreeDict.load(treedict) 

389 for key in treedict.keys(partition=partition): 

390 print(key) 

391 

392 

393@app.command() 

394def csv( 

395 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

396 csv:Path = typer.Argument(...,help="The path to the output CSV file."), 

397): 

398 """  

399 Writes a CSV file with the key, node name and partition.  

400 """ 

401 treedict = TreeDict.load(treedict) 

402 treedict.csv(csv) 

403 

404 

405@app.command() 

406def render( 

407 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

408 output:Path|None = typer.Option(None, help="The path to save the rendered tree."), 

409 print_tree:bool = typer.Option(True, help="Whether or not to print the tree to the screen."), 

410 count:bool = typer.Option(False, help="Whether or not to print the count of keys at each node."), 

411 partition_counts:bool = typer.Option(False, help="Whether or not to print the count of each partition at each node."), 

412 alphabetical:bool = typer.Option(False, help="Whether or not to sort the children of each node alphabetically."), 

413): 

414 """ 

415 Render the tree as text, optionally showing key counts or partition counts. 

416 """ 

417 treedict = TreeDict.load(treedict) 

418 treedict.render(filepath=output, print=print_tree, count=count, partition_counts=partition_counts, alphabetical=alphabetical) 

419 

420 

421@app.command() 

422def count( 

423 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

424): 

425 """ 

426 Prints the number of keys in the TreeDict. 

427 """ 

428 treedict = TreeDict.load(treedict) 

429 print(len(treedict)) 

430 

431 

432@app.command() 

433def sunburst( 

434 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

435 show:bool = typer.Option(False, help="Whether or not to show the plot."), 

436 output:Path = typer.Option(None, help="The path to save the rendered tree."), 

437 width:int = typer.Option(1000, help="The width of the plot."), 

438 height:int = typer.Option(0, help="The height of the plot. If 0 then it will be calculated based on the width."), 

439): 

440 """ 

441 Renders the TreeDict as a sunburst plot. 

442 """ 

443 treedict = TreeDict.load(treedict) 

444 height = height or width 

445 

446 fig = treedict.sunburst(width=width, height=height) 

447 if show: 

448 fig.show() 

449 

450 if output: 

451 output = Path(output) 

452 output.parent.mkdir(exist_ok=True, parents=True) 

453 

454 # if kaleido is installed, turn off mathjax 

455 # https://github.com/plotly/plotly.py/issues/3469 

456 try: 

457 import plotly.io as pio 

458 pio.kaleido.scope.mathjax = None 

459 except Exception as e: 

460 pass 

461 

462 output_func = fig.write_html if output.suffix.lower() == ".html" else fig.write_image 

463 output_func(output) 

464 

465 

466@app.command() 

467def truncate( 

468 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

469 max_depth:int = typer.Argument(...,help="The maximum depth to truncate the tree."), 

470 output:Path = typer.Argument(...,help="The path to the output file."), 

471): 

472 """ 

473 Truncates the tree to a maximum depth. 

474 """ 

475 treedict = TreeDict.load(treedict) 

476 new_tree = treedict.truncate(max_depth) 

477 new_tree.save(output) 

478 

479 

480@app.command() 

481def layer_size( 

482 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

483): 

484 """ 

485 Prints the size of the neural network layer to predict the classification tree. 

486 """ 

487 treedict = TreeDict.load(treedict) 

488 print(treedict.classification_tree.layer_size) 

489 

490 

491@app.command() 

492def pickle_tree( 

493 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

494 output:Path = typer.Argument(...,help="The path to the output pickle file."), 

495): 

496 """ 

497 Pickles the classification tree to a file. 

498 """ 

499 treedict = TreeDict.load(treedict) 

500 treedict.pickle_tree(output) 

501 

502 

503@app.command() 

504def set_partition( 

505 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

506 pattern:str = typer.Argument(...,help="A shell-style pattern to match keys (e.g. 'NC_*')."), 

507 partition:int = typer.Argument(...,help="The partition to set for matching keys."), 

508 output:Path = typer.Argument(...,help="The path to the output file."), 

509): 

510 """ 

511 Sets the partition for keys matching a shell-style pattern and saves the result. 

512 """ 

513 treedict = TreeDict.load(treedict) 

514 treedict.set_partition(pattern, partition) 

515 treedict.save(output) 

516 

517 

518@app.command() 

519def merge( 

520 treedict:Path = typer.Argument(...,help="The path to the TreeDict."), 

521 other:Path = typer.Argument(...,help="The path to the other TreeDict to merge in."), 

522 output:Path = typer.Argument(...,help="The path to the output file."), 

523): 

524 """ 

525 Merges another TreeDict into this one and saves the result. 

526 

527 Where a key exists in both, the entry from the other TreeDict takes precedence. 

528 """ 

529 treedict = TreeDict.load(treedict) 

530 other = TreeDict.load(other) 

531 treedict.merge(other) 

532 treedict.save(output)