Coverage for terrier/apps.py: 99.62%

264 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 09:18 +0000

1from typing import TYPE_CHECKING 

2from dataclasses import dataclass 

3from pathlib import Path 

4from urllib.parse import urlparse 

5import torchapp as ta 

6from corgi import Corgi 

7from corgi.apps import output_results_bar_chart 

8from seqbank import Engine 

9 

10from .defaults import DEFAULT_HEIGHT, DEFAULT_WIDTH 

11 

12from rich.console import Console 

13console = Console() 

14 

15 

16if TYPE_CHECKING: 

17 import pandas as pd 

18 from torchmetrics import Metric 

19 

20 

21@dataclass(frozen=True) 

22class CheckpointVersion: 

23 """ A released version of the Terrier model weights. """ 

24 version: str 

25 url: str 

26 description: str 

27 aliases: tuple[str, ...] = () 

28 

29 

30# Newest first. The first entry is used for 'latest'. 

31CHECKPOINT_VERSIONS = ( 

32 # TODO add version 0.5 when it is released 

33 CheckpointVersion( 

34 version="0.4", 

35 url="https://github.com/rbturnbull/terrier/releases/download/v0.4.0/terrier-0.4.ckpt", 

36 description="trained on RepBase31.04", 

37 ), 

38 CheckpointVersion( 

39 # The model weights did not change between versions 0.2 and 0.3 

40 version="0.2", 

41 url="https://github.com/rbturnbull/terrier/releases/download/v0.2.0/terrier-0.2.0.ckpt", 

42 description="trained on RepBase29.10. Used in the publication in Briefings in Bioinformatics (2025)", 

43 aliases=("0.3", "bib"), 

44 ), 

45) 

46LATEST_CHECKPOINT = "latest" 

47 

48 

49def checkpoint_names() -> list[str]: 

50 """ All the names that can be given to the --checkpoint option. """ 

51 names = [LATEST_CHECKPOINT] 

52 for version in CHECKPOINT_VERSIONS: 

53 names += [version.version, *version.aliases] 

54 return names 

55 

56 

57def resolve_checkpoint_version(name:str) -> CheckpointVersion|None: 

58 """ The checkpoint version for a version number or alias, or None if the name is not known. """ 

59 if name == LATEST_CHECKPOINT: 

60 return CHECKPOINT_VERSIONS[0] 

61 for version in CHECKPOINT_VERSIONS: 

62 if name == version.version or name in version.aliases: 

63 return version 

64 return None 

65 

66 

67def is_url(location:str) -> bool: 

68 return urlparse(str(location)).scheme in ("http", "https") 

69 

70 

71def checkpoint_help() -> str: 

72 versions = [f"'{LATEST_CHECKPOINT}' (v{CHECKPOINT_VERSIONS[0].version})"] 

73 for version in CHECKPOINT_VERSIONS: 

74 names = " / ".join(f"'{name}'" for name in (version.version, *version.aliases)) 

75 versions.append(f"{names}: {version.description}") 

76 return ( 

77 "The model weights to use. Give a released version, a path to a local checkpoint file or a URL. " 

78 "Released versions are " + "; ".join(versions) 

79 ) 

80 

81 

82CHECKPOINT_HELP = checkpoint_help() 

83 

84 

85def get_original_classification(original_id:str) -> str: 

86 """ The classification in a sequence ID of the form 'accession#classification'. """ 

87 if "#" in original_id: 

88 return original_id.split("#")[1] 

89 return "null" 

90 

91 

92class Terrier(Corgi): 

93 """ 

94 Transposable Element Repeat Result classifIER 

95 """ 

96 @ta.method("super") 

97 def data(self, **kwargs): 

98 data = super().data(**kwargs) 

99 return data 

100 

101 def get_bibtex_files(self) -> list[Path]: 

102 files = super().get_bibtex_files() 

103 files.append(Path(__file__).parent / "terrier.bib") 

104 return files 

105 

106 @ta.method 

107 def metrics(self) -> list[tuple[str,"Metric"]]: 

108 from hierarchicalsoftmax.metrics import RankAccuracyTorchMetric 

109 

110 rank_accuracy = RankAccuracyTorchMetric( 

111 root=self.classification_tree, 

112 ranks={1:"accuracy_repeatmasker_type", 2:"accuracy_repeatmasker_subtype"}, 

113 ) 

114 

115 return [('rank_accuracy', rank_accuracy)] 

116 

117 @ta.method 

118 def monitor(self): 

119 return "accuracy_repeatmasker_subtype" 

120 

121 def add_short_sequences(self, results_df:"pd.DataFrame") -> "pd.DataFrame": 

122 """ 

123 Adds a row to the results for each sequence that was skipped because it is shorter than the minimum length. 

124 

125 This means that the CSV files have a row for every sequence in the input, in the original order. 

126 The rows for the skipped sequences have an 'Unknown' prediction and no probabilities. 

127 """ 

128 import pandas as pd 

129 

130 min_length = getattr(self.dataloader, "min_length", 0) 

131 if not min_length: 

132 return results_df 

133 

134 def key(file, original_id, description): 

135 return (str(file), original_id, description) 

136 

137 positions = {} 

138 short_rows = [] 

139 position = 0 

140 for file in self.dataloader.files: 

141 for record in self.dataloader.parse(file): 

142 positions.setdefault(key(file, record.id, record.description), position) 

143 if len(record.seq) < min_length: 

144 short_rows.append(dict( 

145 file=file, 

146 accession=record.id.split("#")[0], 

147 prediction="Unknown", 

148 original_id=record.id, 

149 original_classification=get_original_classification(record.id), 

150 description=record.description, 

151 position=position, 

152 )) 

153 position += 1 

154 

155 if not short_rows: 

156 return results_df 

157 

158 columns = list(results_df.columns) 

159 results_df = results_df.copy() 

160 results_df["position"] = [ 

161 positions.get(key(file, original_id, description), float("inf")) 

162 for file, original_id, description in zip(results_df["file"], results_df["original_id"], results_df["description"]) 

163 ] 

164 combined = pd.concat([results_df, pd.DataFrame(short_rows)], ignore_index=True) 

165 combined = combined.sort_values(by="position", kind="stable") 

166 return combined[columns] 

167 

168 @ta.method 

169 def output_results( 

170 self, 

171 results, 

172 output_csv: Path = ta.Param(default=None, help="A path to output the results as a CSV."), 

173 output_tips_csv: Path = ta.Param(default=None, help="A path to output the results as a CSV which only stores the probabilities at the tips."), 

174 output_fasta: Path = ta.Param(default=None, help="A path to output the results in FASTA format."), 

175 unknown_only:bool = ta.Param(default=None, help="Whether or not to only rename the 'Unknown' sequences in the FASTA file."), 

176 image_dir: Path = ta.Param(default=None, help="A directory to output the results as images."), 

177 image_format:str = "png", 

178 image_threshold:float = 0.005, 

179 threshold:float = ta.Param(default=0.7, help="The threshold value for making hierarchical predictions."), 

180 **kwargs, 

181 ): 

182 import pandas as pd 

183 from hierarchicalsoftmax import inference 

184 import torch 

185 from Bio import SeqIO 

186 

187 def node_lineage_string(node) -> str: 

188 if node.is_root: 

189 return "Unknown" 

190 return "/".join([str(n) for n in node.ancestors[1:]] + [str(node)]) 

191 

192 classification_probabilities = inference.node_probabilities(results[0], root=self.classification_tree) 

193 if hasattr(self.classification_tree, "node_list_softmax"): 

194 category_names = [node_lineage_string(node) for node in self.classification_tree.node_list_softmax] 

195 else: 

196 # Backwards compatibility for older seqtree files which don't have the node_list_softmax attribute,  

197 # in which case we just use all non-root nodes as categories.  

198 # This is the case for Terrier 0.3 and earlier. 

199 category_names = [node_lineage_string(node) for node in self.classification_tree.node_list if not node.is_root] 

200 

201 chunk_details = pd.DataFrame(self.dataloader.chunk_details, columns=["file", "original_id", "description", "chunk"]) 

202 predictions_df = pd.DataFrame(classification_probabilities.numpy(), columns=category_names) 

203 

204 results_df = pd.concat( 

205 [chunk_details.drop(columns=['chunk']), predictions_df], 

206 axis=1, 

207 ) 

208 

209 # Average over chunks 

210 results_df["order"] = results_df.index 

211 results_df = results_df.groupby(["file", "original_id", "description"]).mean().reset_index() 

212 

213 # sort to get original order 

214 results_df = results_df.sort_values(by="order").drop(columns=["order"]) 

215 

216 # results_df['max_leaf_probability_prediction'] = results_df[leaf_names].idxmax(axis=1) 

217 

218 # Get new tensors now that we've averaged over chunks 

219 classification_probabilities = torch.as_tensor(results_df[category_names].to_numpy()) 

220 # get greedy predictions which can use the raw activation or the softmax probabilities 

221 greedy_predictions = inference.greedy_predictions( 

222 classification_probabilities, 

223 root=self.classification_tree, 

224 threshold=threshold, 

225 ) 

226 

227 results_df['prediction'] = [ 

228 node_lineage_string(node) 

229 for node in greedy_predictions 

230 ] 

231 

232 results_df['accession'] = results_df['original_id'].apply(lambda x: x.split("#")[0]) 

233 

234 def get_prediction_probability(row): 

235 prediction = row["prediction"] 

236 if prediction in row: 

237 return row[prediction] 

238 return 1.0 

239 

240 results_df['probability'] = results_df.apply(get_prediction_probability, axis=1) 

241 results_df['original_classification'] = results_df['original_id'].apply(get_original_classification) 

242 

243 # Reorder columns 

244 results_df = results_df[["file", "accession", "prediction", "probability", "original_id", "original_classification", "description" ] + category_names] 

245 

246 # Output images 

247 if image_dir: 

248 console.print(f"Writing inference probability renders to: {image_dir}") 

249 image_dir = Path(image_dir) 

250 image_paths = [] 

251 for _, row in results_df.iterrows(): 

252 filepath = row['file'] 

253 accession = row['accession'] 

254 image_path = image_dir / Path(filepath).name / f"{accession}.{image_format}" 

255 image_paths.append(image_path) 

256 

257 inference.render_probabilities( 

258 root=self.classification_tree, 

259 filepaths=image_paths, 

260 probabilities=classification_probabilities, 

261 predictions=greedy_predictions, 

262 threshold=image_threshold, 

263 ) 

264 

265 output_results_bar_chart(results_df["prediction"], top_k=10) 

266 

267 if not (image_dir or output_fasta or output_csv or output_tips_csv): 

268 print("No output files requested.") 

269 

270 if output_fasta: 

271 console.print(f"Writing results for {len(results_df)} repeats to: {output_fasta}") 

272 output_fasta = Path(output_fasta) 

273 output_fasta.parent.mkdir(exist_ok=True, parents=True) 

274 with open(output_fasta, "w") as fasta_out: 

275 for file in self.dataloader.files: 

276 for record in self.dataloader.parse(file): 

277 original_id = record.id 

278 row = results_df.loc[results_df.original_id == original_id] 

279 if len(row) == 0: 

280 SeqIO.write(record, fasta_out, "fasta") 

281 continue 

282 

283 accession = row['accession'].item() 

284 original_classification = row["original_classification"].item().strip() 

285 prediction = row["prediction"].item() 

286 

287 if not unknown_only or original_classification.lower() == "unknown": 

288 record.id = f"{accession}#{prediction}" 

289 

290 # Adapt description 

291 record.description = record.description.replace(original_id, "") 

292 last_bracket = record.description.rfind(")") 

293 if last_bracket == -1: 

294 record.description = f"{record.description} ( " 

295 else: 

296 record.description = record.description[:last_bracket].rstrip() + ", " 

297 

298 if prediction in row: 

299 new_probability = row[prediction].values[0] 

300 else: 

301 new_probability = 1.0 # i.e.root 

302 

303 new_description = f"{record.description} original classification = {original_classification}, " 

304 

305 if unknown_only: 

306 new_description += f"terrier classification = {prediction}, " 

307 

308 new_description += f"classification probability = {new_probability:.2f} )" 

309 

310 record.description = new_description 

311 

312 SeqIO.write(record, fasta_out, "fasta") 

313 

314 # The CSV files include the sequences that were too short to be classified 

315 csv_df = self.add_short_sequences(results_df) if (output_csv or output_tips_csv) else results_df 

316 

317 if output_tips_csv: 

318 output_tips_csv = Path(output_tips_csv) 

319 output_tips_csv.parent.mkdir(exist_ok=True, parents=True) 

320 non_tips = [node_lineage_string(node) for node in self.classification_tree.node_list if not node.is_leaf] 

321 tips_df = csv_df.drop(columns=non_tips) 

322 tips_df.to_csv(output_tips_csv, index=False) 

323 

324 if output_csv: 

325 output_csv = Path(output_csv) 

326 output_csv.parent.mkdir(exist_ok=True, parents=True) 

327 console.print(f"Writing results for {len(csv_df)} repeats to: {output_csv}") 

328 csv_df.to_csv(output_csv, index=False) 

329 

330 # if self.vector: 

331 # # x = results_df.to_xarray() 

332 # # breakpoint() 

333 # # embeddings = xr.DataArray(results[0][1], dims=("accession", "embedding")) 

334 # # embeddings.to_netcdf("embeddings.nc") 

335 # torch.save(results[0][1], "embeddings.pkl") 

336 

337 return results_df 

338 

339 @ta.method 

340 def checkpoint( 

341 self, 

342 checkpoint:str=ta.Param( 

343 default="latest", 

344 help=CHECKPOINT_HELP, 

345 metavar="VERSION|PATH|URL", 

346 ), 

347 ) -> str: 

348 """ Returns the location of the model checkpoint for a named version, a local path or a URL. """ 

349 version = resolve_checkpoint_version(str(checkpoint)) 

350 if version: 

351 console.print(f"Using Terrier checkpoint v{version.version}: {version.description}", style="dim", soft_wrap=True) 

352 return version.url 

353 

354 if is_url(checkpoint) or Path(checkpoint).exists(): 

355 console.print(f"Using Terrier checkpoint: {checkpoint}", style="dim", soft_wrap=True) 

356 return checkpoint 

357 

358 raise ValueError( 

359 f"Unknown checkpoint: '{checkpoint}'. " 

360 f"Use one of {', '.join(repr(name) for name in checkpoint_names())}, " 

361 "or give the path or URL of a checkpoint file." 

362 ) 

363 

364 @ta.tool 

365 def preprocess( 

366 self, 

367 input:list[str]=ta.Param(..., help="The path to a FASTA file, URL to a FASTA file, multiple FASTA files or a directory of FASTA files (e.g. the RepBase FASTA directory)"), 

368 seqbank:Path=ta.Param(None, help="The path to save the new SeqBank file."), 

369 engine:Engine=ta.Param(Engine.LMDB, help="The storage engine for the SeqBank. An existing SeqBank must already use this engine."), 

370 seqtree:Path=ta.Param(None, help="The path to save the new SeqTree file."), 

371 summary_csv:Path=ta.Param(None, help="Save dataset totals as CSV."), 

372 classifications_csv:Path=ta.Param(None, help="Save unique input names, resulting classifications, and counts as CSV."), 

373 retained_csv:Path=ta.Param(None, help="Save retained classification counts and percentages as CSV."), 

374 label_smoothing:float=0.0, 

375 gamma:float=0.0, 

376 partitions:int=5, 

377 seed:int=ta.Param(0, help="Seed for deterministic sequence-based partition assignments."), 

378 ): 

379 from seqbank import SeqBank 

380 from .repeatmasker import create_repeatmasker_seqtree 

381 

382 assert seqbank or seqtree or summary_csv or classifications_csv or retained_csv, "Provide a --seqbank, --seqtree, or summary CSV output path." 

383 

384 fasta_paths = self.find_fasta_paths(input) 

385 

386 # Filter out any empty FASTA files 

387 fasta_paths = [path for path in fasta_paths if path.stat().st_size > 0] 

388 if len(fasta_paths) == 0: 

389 raise ValueError("No valid FASTA files found in the input paths.") 

390 

391 # Create the seqbank from the FASTA files 

392 if seqbank: 

393 seqbank = SeqBank(path=seqbank, write=True, engine=engine) 

394 seqbank.add_files(fasta_paths, format="fasta") 

395 

396 # Create the seqtree 

397 if seqtree or summary_csv or classifications_csv or retained_csv: 

398 seqtree_path = Path(seqtree) if seqtree else None 

399 seqtree = create_repeatmasker_seqtree( 

400 fasta_paths=fasta_paths, 

401 label_smoothing=label_smoothing, 

402 gamma=gamma, 

403 partitions=partitions, 

404 seed=seed, 

405 summary_csv=summary_csv, 

406 classifications_csv=classifications_csv, 

407 retained_csv=retained_csv, 

408 ) 

409 if seqtree_path: 

410 seqtree.save(seqtree_path) 

411 seqtree.render(print=1, count=True) 

412 

413 @ta.tool 

414 def evaluate( 

415 self, 

416 csv:Path = ta.Param(..., help="The CSV file with the results."), 

417 superfamily:bool=ta.Param(default=True, help="Whether to use the superfamily level for the confusion matrix."), 

418 map:str="", 

419 ignore:str="Unknown", 

420 threshold:float=None, 

421 ) -> "pd.DataFrame": 

422 import pandas as pd 

423 from .evaluate import evaluate_results 

424 

425 df = pd.read_csv(csv) 

426 return evaluate_results(df, superfamily=superfamily, map=map, ignore=ignore, threshold=threshold) 

427 

428 @ta.tool 

429 def threshold_plot( 

430 self, 

431 csv:Path = ta.Param(..., help="The CSV file with the results."), 

432 output:Path=ta.Param(default=None, help="A path to write the confusion matrix, can be HTML or an image file."), 

433 superfamily:bool=ta.Param(default=True, help="Whether to use the superfamily level for the confusion matrix."), 

434 show:bool=ta.Param(default=True, help="Whether to show the confusion matrix."), 

435 width:int=DEFAULT_WIDTH, 

436 height:int=DEFAULT_HEIGHT, 

437 map:str="", 

438 ignore:str="Unknown", 

439 ) -> "pd.DataFrame": 

440 import pandas as pd 

441 from .evaluate import threshold_fig, show_fig 

442 

443 df = pd.read_csv(csv) 

444 

445 fig = threshold_fig(df, superfamily=superfamily, map=map, ignore=ignore, width=width, height=height) 

446 

447 if output: 

448 output = Path(output) 

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

450 print(f"Writing threshold figure to: {output}") 

451 match output.suffix.lower(): 

452 case ".html": 

453 fig.write_html(str(output)) 

454 case _: 

455 fig.write_image(str(output), engine="kaleido") 

456 

457 if show: 

458 show_fig(fig) 

459 

460 

461 @ta.tool 

462 def confusion_matrix( 

463 self, 

464 csv:Path = ta.Param(..., help="The CSV file with the results."), 

465 output:Path=ta.Param(default=None, help="A path to write the confusion matrix, can be CSV, HTML or an image file."), 

466 superfamily:bool=ta.Param(default=True, help="Whether to use the superfamily level for the confusion matrix."), 

467 show:bool=ta.Param(default=True, help="Whether to show the confusion matrix."), 

468 width:int=DEFAULT_WIDTH, 

469 height:int=DEFAULT_HEIGHT, 

470 map:str="", 

471 ignore:str="Unknown", 

472 threshold:float=None, 

473 ) -> "pd.DataFrame": 

474 import pandas as pd 

475 from .evaluate import build_confusion_matrix, confusion_matrix_fig, show_fig 

476 

477 df = pd.read_csv(csv) 

478 

479 cm = build_confusion_matrix(df, superfamily=superfamily, map=map, ignore=ignore, threshold=threshold) 

480 fig = confusion_matrix_fig(cm, width=width, height=height, title=f"{csv.name} Confusion Matrix") 

481 

482 if output: 

483 output = Path(output) 

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

485 print(f"Writing confusion matrix to: {output}") 

486 match output.suffix.lower(): 

487 case ".csv": 

488 cm.to_csv(output) 

489 case ".html": 

490 fig.write_html(str(output)) 

491 case _: 

492 fig.write_image(str(output), engine="kaleido") 

493 

494 if show: 

495 show_fig(fig) 

496 

497 return cm 

498 

499 

500 @ta.tool 

501 def comparison_plot( 

502 self, 

503 csv:list[Path] = ta.Param(..., help="The CSV file(s) with the results."), 

504 output:Path=ta.Param(default=None, help="A path to write the comparison plots, can be HTML or an image file."), 

505 superfamily:bool=ta.Param(default=True, help="Whether to use the superfamily level for the confusion matrix."), 

506 show:bool=ta.Param(default=True, help="Whether to show the confusion matrix."), 

507 threshold:float=None, 

508 ): 

509 """ Plot the comparison of Terrier results with the original annotations. """ 

510 from .evaluate import comparison_plot, show_fig 

511 

512 fig = comparison_plot(csv, superfamily=superfamily, threshold=threshold) 

513 

514 if output: 

515 output = Path(output) 

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

517 print(f"Writing comparison plot to: {output}") 

518 match output.suffix.lower(): 

519 case ".html": 

520 fig.write_html(str(output)) 

521 case _: 

522 fig.write_image(str(output), engine="kaleido") 

523 

524 if show: 

525 show_fig(fig) 

526 

527 return fig 

528 

529 def package_name(self) -> str: 

530 """ 

531 Returns the name of the package. 

532 """ 

533 return "bio-terrier"