Coverage for corgi/apps.py: 99.06%
213 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-28 00:24 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-28 00:24 +0000
1"""The Corgi application: training, prediction and tools built with torchapp."""
3from typing import TYPE_CHECKING
4from pathlib import Path
5import typer
6import torchapp as ta
7from rich.console import Console
9if TYPE_CHECKING:
10 from torch import nn
11 import pandas as pd
12 from hierarchicalsoftmax.nodes import SoftmaxNode
13 from torchmetrics import Metric
14 from .data import CorgiDataModule
16console = Console()
19def limit_torch_threads(num_threads: int | None) -> None:
20 """Limits the number of CPU threads that PyTorch uses.
22 Args:
23 num_threads (int | None): The maximum number of threads. If None, then the PyTorch default is left unchanged.
25 Raises:
26 typer.BadParameter: If `num_threads` is less than 1.
27 """
28 if num_threads is None:
29 return
31 if num_threads < 1:
32 raise typer.BadParameter("num_threads must be at least 1.")
34 import torch
36 torch.set_num_threads(num_threads)
39def output_results_bar_chart(predictions: "pd.Series", top_k: int = 10, bar_size: int = 80):
40 """Prints a table with a bar chart of the proportion of each prediction.
42 Args:
43 predictions (pd.Series): The prediction for each sequence.
44 top_k (int): The number of most common predictions to show. The rest are summed into 'Other Categories'.
45 If zero, then all predictions are shown.
46 bar_size (int): The number of characters in a bar which represents 100%.
47 """
48 from rich.table import Table
49 from rich.box import SIMPLE
51 value_counts = predictions.value_counts()
52 total_categories = len(value_counts)
53 if top_k:
54 original_value_counts = value_counts
55 value_counts = value_counts.iloc[:top_k]
56 table = Table(box=SIMPLE)
57 table.add_column("Prediction", justify="left", style="bold")
58 table.add_column("Proportion", justify="left", style="blue")
59 table.add_column("Count", justify="right")
60 for prediction, count in value_counts.items():
61 proportion = count / len(predictions)
62 bar = "█" * int(proportion * bar_size)
63 table.add_row(prediction, f"{bar} {proportion:.1%}", f"{count}")
64 if total_categories > top_k:
65 count = sum(original_value_counts.iloc[top_k:])
66 proportion = count / len(predictions)
67 bar = "█" * int(proportion * bar_size)
68 table.add_row("Other Categories", f"{bar} {proportion:.1%}", f"{count}")
69 # Add line
70 table.add_row('────────────────────', '─' * bar_size, '─' * 10, style="red")
71 table.add_row("Total", "", f"{len(predictions)}")
73 console.print(table)
76def set_alphas_with_phi(tree, phi=1.0):
77 """Sets the `alpha` (loss weight) of each node in the tree to `phi` raised to the power of the node's depth.
79 Args:
80 tree (SoftmaxNode): The root of the classification tree.
81 phi (float): The multiplication factor for the loss at each level of the tree.
82 """
83 import numpy as np
85 for node in tree.pre_order_iter():
86 node.alpha = np.power(phi, len(node.ancestors))
89class Corgi(ta.TorchApp):
90 """
91 corgi - Classifier for ORganelle Genomes (Inter alia)
92 """
94 @ta.method
95 def data(
96 self,
97 seqtree: Path = ta.Param(..., help="The seqtree which has the sequences to use."),
98 seqbank: Path = ta.Param(..., help="The seqbank file with the sequences."),
99 validation_partition: int = ta.Param(default=0, help="The partition to use for validation."),
100 batch_size: int = ta.Param(default=32, help="The batch size."),
101 validation_length: int = ta.Param(
102 default=1_000, help="The standard length of sequences to use for validation."
103 ),
104 phi: float = ta.Param(
105 default=1.0,
106 tune=True,
107 tune_min=0.8,
108 tune_max=1.2,
109 help="A multiplication factor for the loss at each level of the tree.",
110 ),
111 test_partition: int = ta.Param(
112 default=-1, help="The partition to retain for testing (by default, -1 so that it is not used)."
113 ),
114 minimum_length: int = ta.Param(
115 default=150, help="The minimum length to truncate sequences in a training batch."
116 ),
117 maximum_length: int = ta.Param(
118 default=3_000, help="The maximum length to truncate sequences in a training batch."
119 ),
120 skewness: float = ta.Param(default=5, help="The skewness of the distribution of sequence lengths in a batch."),
121 loc: float = ta.Param(
122 default=600, help="A parameter to shift the centre of the distribution of sequence lengths."
123 ),
124 scale: float = ta.Param(default=1000, help="A parameter to scale the distribution of sequence lengths."),
125 # tips_mode:bool = False,
126 max_items: int = ta.Param(
127 default=0, help="The maximum number of items to use for training. If zero then all items are used."
128 ),
129 train_all: bool = ta.Param(default=False, help="Whether or not to use the validation partition for training."),
130 ) -> "CorgiDataModule":
131 """
132 Creates a Pytorch Lightning object which Corgi uses in training and prediction.
133 """
134 from seqbank import SeqBank
135 from polytorch import HierarchicalData
136 from .data import CorgiDataModule
137 from .seqtree import SeqTree
139 assert seqtree is not None, "No seqtree given"
140 assert seqbank is not None, "No seqbank given"
142 seqtree = Path(seqtree)
143 seqbank = Path(seqbank)
145 print(f"Loading seqtree {seqtree}")
146 seqtree = SeqTree.load(seqtree)
147 self.classification_tree = seqtree.classification_tree
149 print(f"Loading seqbank {seqbank}")
150 seqbank = SeqBank(seqbank)
152 self.classification_tree = seqtree.classification_tree
154 set_alphas_with_phi(self.classification_tree, phi=phi)
156 self.output_types = [
157 HierarchicalData(root=self.classification_tree),
158 ]
160 print(f"Creating dataloaders with batch_size {batch_size} and validation partition {validation_partition}.")
161 data = CorgiDataModule(
162 seqtree=seqtree,
163 seqbank=seqbank,
164 batch_size=batch_size,
165 validation_partition=validation_partition,
166 max_items=max_items,
167 minimum_length=minimum_length,
168 maximum_length=maximum_length,
169 validation_length=validation_length,
170 test_partition=test_partition,
171 train_all=train_all,
172 skewness=skewness,
173 loc=loc,
174 scale=scale,
175 )
177 return data
179 @ta.method
180 def module_class(self, **kwargs) -> 'CorgiLightningModule':
181 """Returns the class of the Lightning module, which adds support for saving embeddings during prediction."""
182 from .modules import CorgiLightningModule
184 return CorgiLightningModule
186 @ta.method("module_class", "checkpoint")
187 def model(
188 self,
189 pretrained: Path = ta.Param(None, help="A pretrained model to finetune."),
190 embedding_dim: int = ta.Param(
191 default=8,
192 help="The size of the embeddings for the nucleotides (N, A, G, C, T).",
193 tune=True,
194 tune_min=4,
195 tune_max=32,
196 log=True,
197 ),
198 cnn_layers: int = ta.Param(
199 default=6,
200 help="The number of 1D convolution layers.",
201 tune=True,
202 tune_min=2,
203 tune_max=6,
204 ),
205 kernel_size_maxpool: int = ta.Param(
206 default=2,
207 help="The size of the pooling before going to the LSTM.",
208 ),
209 dropout: float = ta.Param(
210 default=0.2,
211 help="The amount of dropout to use. (not currently enabled)",
212 tune=True,
213 tune_min=0.0,
214 tune_max=0.3,
215 ),
216 final_bias: bool = ta.Param(
217 default=True,
218 help="Whether or not to use bias in the final layer.",
219 tune=True,
220 ),
221 kernel_size: int = ta.Param(
222 default=3, help="The size of the kernels for CNN only classifier.", tune=True, tune_choices=[3, 5, 7, 9]
223 ),
224 cnn_dims_start: int = ta.Param(
225 default=None,
226 help="The size of the number of filters in the first CNN layer. If not set then it is derived from the MACC",
227 ),
228 factor: float = ta.Param(
229 default=2.0,
230 help="The factor to multiply the number of filters in the CNN layers each time it is downscaled.",
231 tune=True,
232 log=True,
233 tune_min=0.5,
234 tune_max=2.5,
235 ),
236 penultimate_dims: int = ta.Param(
237 default=1024,
238 help="The factor to multiply the number of filters in the CNN layers each time it is downscaled.",
239 tune=True,
240 log=True,
241 tune_min=512,
242 tune_max=2048,
243 ),
244 include_length: bool = True,
245 transformer_heads: int = ta.Param(8, help="The number of heads in the transformer."),
246 transformer_layers: int = ta.Param(
247 0, help="The number of layers in the transformer. If zero then no transformer is used."
248 ),
249 macc: int = ta.Param(
250 default=10_000_000,
251 help="The approximate number of multiply or accumulate operations in the model. Used to set cnn_dims_start if not provided explicitly.",
252 ),
253 reload: bool = ta.Param(default=False, help="Whether or not to reload the pretrained model before using it."),
254 **kwargs,
255 ) -> 'nn.Module':
256 """
257 Creates a deep learning model for the Corgi to use.
259 Returns:
260 nn.Module: The created model.
261 """
262 from polytorch import total_size
263 from .models import calc_cnn_dims_start, ConvClassifier
265 assert self.classification_tree
267 num_classes = total_size(self.output_types)
269 if pretrained:
270 if str(pretrained) == "default":
271 pretrained = self.checkpoint(**kwargs)
273 pretrained = self.process_location(pretrained, reload=reload)
275 if not pretrained or not pretrained.is_file():
276 raise FileNotFoundError(f"Cannot find pretrained model at '{pretrained}'")
278 module_class = self.module_class(**kwargs)
279 module = module_class.load_from_checkpoint(str(pretrained), weights_only=False)
280 model = module.model
281 if model.output_types_match(self.output_types):
282 console.print(
283 f"[green]The output types of the pretrained model match the classification tree "
284 f"({num_classes} outputs). Keeping its final layer."
285 )
286 model.output_types = self.output_types
287 else:
288 old_outputs = model.final.out_features
289 console.print(
290 f"[yellow]The output types of the pretrained model ({old_outputs} outputs) are different from "
291 f"the classification tree ({num_classes} outputs). Replacing its final layer with a new, "
292 f"randomly initialised one."
293 )
294 model.replace_output_types(self.output_types, final_bias=final_bias)
295 return model
297 # if cnn_dims_start not given then calculate it from the MACC
298 if not cnn_dims_start:
299 assert macc
301 cnn_dims_start = calc_cnn_dims_start(
302 macc=macc,
303 seq_len=1024, # arbitary number
304 embedding_dim=embedding_dim,
305 cnn_layers=cnn_layers,
306 kernel_size=kernel_size,
307 factor=factor,
308 penultimate_dims=penultimate_dims,
309 num_classes=num_classes,
310 )
312 return ConvClassifier(
313 num_embeddings=5, # i.e. the size of the vocab which is N, A, C, G, T
314 kernel_size=kernel_size,
315 factor=factor,
316 cnn_layers=cnn_layers,
317 output_types=self.output_types,
318 kernel_size_maxpool=kernel_size_maxpool,
319 final_bias=final_bias,
320 dropout=dropout,
321 cnn_dims_start=cnn_dims_start,
322 penultimate_dims=penultimate_dims,
323 include_length=include_length,
324 transformer_layers=transformer_layers,
325 transformer_heads=transformer_heads,
326 )
328 @ta.method
329 def metrics(self) -> list[tuple[str, 'Metric']]:
330 """Returns the metrics to track during validation, which are the accuracy at each rank of the taxonomic tree."""
331 from hierarchicalsoftmax.metrics import RankAccuracyTorchMetric
333 rank_accuracy = RankAccuracyTorchMetric(
334 root=self.classification_tree,
335 ranks={
336 1: "type_accuracy",
337 2: "superkingdom_accuracy",
338 3: "kingdom_accuracy",
339 4: "phylum_accuracy",
340 5: "class_accuracy",
341 6: "order_accuracy",
342 },
343 )
345 return [('rank_accuracy', rank_accuracy)]
347 @ta.method
348 def monitor(self):
349 """Returns the name of the metric to monitor when selecting the best checkpoint."""
350 return "superkingdom_accuracy"
352 @ta.method
353 def loss_function(self):
354 """Returns the loss function, which combines the losses for the hierarchical output of the model."""
355 from polytorch import PolyLoss
357 assert self.output_types
358 return PolyLoss(data_types=self.output_types, feature_axis=1)
360 def package_name(self) -> str:
361 """
362 Returns the name of the package.
363 """
364 return "bio-corgi"
366 def find_input_paths(self, files: list[str], base_extensions: set[str] | None = None) -> list[Path]:
367 """Finds the sequence files to classify.
369 Directories are searched recursively for files with a recognised sequence file extension (optionally gzipped).
371 Args:
372 files (list[str]): Paths or URLs of files or directories.
373 base_extensions (set[str] | None): The file extensions to accept. If not given, then the extensions for
374 FASTA, GenBank, tabular and FASTQ files are used.
376 Returns:
377 list[Path]: The paths of the matching files.
378 """
379 base_extensions = base_extensions or {
380 ".fa",
381 ".fasta",
382 ".fna",
383 ".fas",
384 ".frn",
385 ".ref", # FASTA
386 ".genbank",
387 ".gb",
388 ".gbk", # Genbank
389 ".tab",
390 ".tsv", # Tabular
391 ".fastq",
392 ".fq", # Fastq
393 }
395 # Function to check if a file matches allowed extensions (including .gz)
396 def matches_extensions(file: Path):
397 """Returns whether the file has one of the allowed extensions, with or without a '.gz' suffix."""
398 return file.suffix in base_extensions or (
399 file.suffix == ".gz" and any(file.stem.endswith(ext) for ext in base_extensions)
400 )
402 # Expand the list
403 fasta_paths = []
405 # If 'files' is a string or Path, convert it to a list
406 if isinstance(files, (str, Path)):
407 files = [files]
409 for path in files:
410 path = self.process_location(path)
411 if path.is_dir():
412 # If it's a directory, find all files with the specified extensions
413 fasta_paths.extend([file for file in path.rglob("*") if matches_extensions(file)])
414 else:
415 # If it's not a directory, add the file to the list
416 if matches_extensions(path):
417 fasta_paths.append(path)
419 return fasta_paths
421 def find_fasta_paths(self, files: list[str]) -> list[Path]:
422 """Finds the FASTA files to classify.
424 Args:
425 files (list[str]): Paths or URLs of files or directories.
427 Returns:
428 list[Path]: The paths of the FASTA files.
429 """
430 return self.find_input_paths(files, base_extensions={".fa", ".fasta", ".fna", ".fas", ".frn", ".ref"})
432 @ta.method
433 def prediction_dataloader(
434 self,
435 module,
436 input: list[str] = ta.Param(None, help="A FASTA file with sequences to be classified."),
437 file: list[Path] = ta.Param(
438 None, help="A FASTA file with sequences to be classified (DEPRECATED. Use `input`)."
439 ),
440 seqtree: Path = ta.Param(None, help="The seqtree with the classification tree to use. DEPRECATED."),
441 embeddings: Path = ta.Param(None, help="A path to save the embeddings from the model output."),
442 max_seqs: int = None,
443 batch_size: int = 1,
444 max_length: int = 5_000,
445 min_length: int = 128,
446 num_threads: int = ta.Param(
447 default=None,
448 help="The maximum number of PyTorch CPU threads to use during prediction. If not set, PyTorch uses its default.",
449 ),
450 **kwargs,
451 ):
452 """Creates the dataloader for the sequences to be classified.
454 Long sequences are split into overlapping chunks. The details of the chunks are recorded as the dataloader is
455 iterated so that the predictions can be combined for each sequence.
457 Raises:
458 typer.BadParameter: If no sequence files are found in the input.
459 """
460 from .data import SeqIODataloader
461 from .seqtree import SeqTree
463 limit_torch_threads(num_threads)
465 files = []
466 if input:
467 files += self.find_input_paths(input)
469 if file:
470 files += self.find_input_paths(file)
472 if not files:
473 raise typer.BadParameter("No files given to classify.")
475 if seqtree and Path(seqtree).exists():
476 seqtree = SeqTree.load(seqtree)
477 self.classification_tree = seqtree.classification_tree
478 else:
479 self.classification_tree = module.hparams['classification_tree']
480 self.dataloader = SeqIODataloader(
481 files=files, batch_size=batch_size, max_length=max_length, max_seqs=max_seqs, min_length=min_length
482 )
484 if embeddings:
485 module.set_embedding_path(
486 embeddings_path=embeddings,
487 dataloader=self.dataloader,
488 )
489 return self.dataloader
491 def node_to_str(self, node: 'SoftmaxNode') -> str:
492 """
493 Converts the node to a string
494 """
495 from .seqtree import node_to_str
497 return node_to_str(node)
499 @ta.method
500 def output_results(
501 self,
502 results,
503 output_csv: Path = ta.Param(default=None, help="A path to output the results as a CSV."),
504 output_tips_csv: Path = ta.Param(
505 default=None, help="A path to output the results as a CSV which only stores the probabilities at the tips."
506 ),
507 # output_fasta: Path = ta.Param(default=None, help="A path to output the results in FASTA format."),
508 image_dir: Path = ta.Param(default=None, help="A directory to output the results as images."),
509 image_format: str = "svg",
510 image_threshold: float = 0.005,
511 prediction_threshold: float = ta.Param(
512 default=0.5, help="The threshold value for making hierarchical predictions."
513 ),
514 **kwargs,
515 ):
516 """Processes the model output into predictions and writes the requested outputs.
518 The probabilities for the chunks of each sequence are averaged, a greedy hierarchical prediction is made, and a
519 summary bar chart is printed. Optionally the results are written to CSV files and images of the probabilities
520 are rendered for each sequence.
521 """
522 import torch
523 import pandas as pd
524 from hierarchicalsoftmax.inference import node_probabilities, greedy_predictions, render_probabilities
526 assert self.classification_tree # This should be saved on the checkpoint
528 classification_probabilities = node_probabilities(results[0], root=self.classification_tree)
530 if hasattr(self.classification_tree, "node_list_softmax"):
531 category_names = [self.node_to_str(node) for node in self.classification_tree.node_list_softmax]
532 else:
533 # Backwards compatibility for older seqtree files which don't have the node_list_softmax attribute,
534 # in which case we just use all non-root nodes as categories.
535 category_names = [self.node_to_str(node) for node in self.classification_tree.node_list if not node.is_root]
537 chunk_details = pd.DataFrame(
538 self.dataloader.chunk_details, columns=["file", "original_id", "description", "chunk"]
539 )
540 predictions_df = pd.DataFrame(classification_probabilities.numpy(), columns=category_names)
542 results_df = pd.concat(
543 [chunk_details.drop(columns=['chunk']), predictions_df],
544 axis=1,
545 )
547 # Average over chunks
548 results_df["chunk_index"] = results_df.index
549 results_df = results_df.groupby(["file", "original_id", "description"]).mean().reset_index()
551 # sort to get original order
552 results_df = results_df.sort_values(by="chunk_index").drop(columns=["chunk_index"])
554 # Get new tensors now that we've averaged over chunks
555 classification_probabilities = torch.as_tensor(results_df[category_names].to_numpy())
557 # get greedy predictions which can use the raw activation or the softmax probabilities
558 predictions = greedy_predictions(
559 classification_probabilities,
560 root=self.classification_tree,
561 threshold=prediction_threshold,
562 )
564 results_df['prediction'] = [self.node_to_str(node) for node in predictions]
566 results_df['accession'] = results_df['original_id'].apply(lambda x: x.split("#")[0])
568 def get_prediction_probability(row):
569 """Returns the probability of the predicted node in a row of results, or 1.0 if it is the root."""
570 prediction = row["prediction"]
571 if prediction in row:
572 return row[prediction]
573 return 1.0
575 results_df['probability'] = results_df.apply(get_prediction_probability, axis=1)
577 # Reorder columns
578 results_df = results_df[
579 ["file", "accession", "prediction", "probability", "original_id", "description"] + category_names
580 ]
582 # Output images
583 if image_dir:
584 console.print(f"Writing inference probability renders to: {image_dir}")
585 image_dir = Path(image_dir)
586 image_paths = []
587 for _, row in results_df.iterrows():
588 filepath = row['file']
589 accession = row['accession']
590 image_path = image_dir / Path(filepath).name / f"{accession}.{image_format}"
591 image_paths.append(image_path)
593 render_probabilities(
594 root=self.classification_tree,
595 filepaths=image_paths,
596 probabilities=classification_probabilities,
597 predictions=predictions,
598 threshold=image_threshold,
599 )
601 # Output Bar Chart
602 output_results_bar_chart(results_df["prediction"], top_k=10)
604 if not (image_dir or output_csv or output_tips_csv):
605 print("No output files requested.")
607 # if output_fasta:
608 # console.print(f"Writing results for {len(results_df)} repeats to: {output_fasta}")
609 # with open(output_fasta, "w") as fasta_out:
610 # for file in self.dataloader.files:
611 # for record in SeqIO.parse(file, "fasta"):
612 # original_id = record.id
613 # row = results_df.loc[results_df.original_id == original_id]
614 # if len(row) == 0:
615 # SeqIO.write(record, fasta_out, "fasta")
616 # continue
618 # accession = row['accession'].item()
619 # prediction = row["prediction"].item()
621 # new_id = f"{accession}#{prediction}"
622 # record.id = new_id
624 # # Adapt description
625 # record.description = record.description.replace(original_id, "")
626 # last_bracket = record.description.rfind(")")
627 # if last_bracket == -1:
628 # record.description = f"{record.description} ( "
629 # else:
630 # record.description = record.description[:last_bracket].rstrip() + ", "
632 # if prediction in row:
633 # new_probability = row[prediction].values[0]
634 # else:
635 # new_probability = 1.0 # i.e.root
636 # record.description = f"{record.description} classification probability = {new_probability:.2f} )"
638 # SeqIO.write(record, fasta_out, "fasta")
640 if output_tips_csv:
641 output_tips_csv = Path(output_tips_csv)
642 output_tips_csv.parent.mkdir(exist_ok=True, parents=True)
643 non_tips = [self.node_to_str(node) for node in self.classification_tree.node_list if not node.is_leaf]
644 tips_df = results_df.drop(columns=non_tips)
645 tips_df.to_csv(output_tips_csv, index=False)
647 if output_csv:
648 output_csv = Path(output_csv)
649 output_csv.parent.mkdir(exist_ok=True, parents=True)
650 console.print(f"Writing results for {len(results_df)} sequences to: {output_csv}")
651 results_df.to_csv(output_csv, index=False)
653 # if self.vector:
654 # # x = results_df.to_xarray()
655 # # breakpoint()
656 # # embeddings = xr.DataArray(results[0][1], dims=("accession", "embedding"))
657 # # embeddings.to_netcdf("embeddings.nc")
658 # torch.save(results[0][1], "embeddings.pkl")
660 return results_df
662 @ta.method
663 def extra_hyperparameters(self) -> dict:
664 """Extra hyperparameters to save with the module."""
665 return dict(
666 classification_tree=self.classification_tree,
667 )
669 @ta.method
670 def checkpoint(
671 self,
672 checkpoint: Path = ta.Param(
673 default=None, help="A path to a checkpoint to load. If not given then a default checkpoint is used."
674 ),
675 large: bool = ta.Param(
676 default=False, help="Whether or not to use a large checkpoint (overridden by `checkpoint` parameter)."
677 ),
678 ) -> str:
679 """Returns the location of the checkpoint to use: the given path, or a default (small or large) pretrained model."""
680 if checkpoint:
681 return checkpoint
682 if large:
683 # return "https://figshare.unimelb.edu.au/ndownloader/files/55166705"
684 return "https://ndownloader.figshare.com/files/55166705"
685 raise NotImplementedError("Large checkpoint not yet available.")
687 # return "https://figshare.unimelb.edu.au/ndownloader/files/55166714"
688 return "https://ndownloader.figshare.com/files/55166714"
690 @ta.tool
691 def refseq_to_seqtree(
692 self,
693 output: Path = ta.Param(..., help="The path to save the SeqTree."),
694 seqbank: Path = ta.Param(..., help="The SeqBank with the sequences for the RefSeq accessions."),
695 seqbank_output: Path = ta.Param(
696 default=None, help="Where to save a new SeqBank containing only the sequences selected for the SeqTree."
697 ),
698 engine: str = ta.Param(
699 default="lmdb",
700 help="The storage engine for the output SeqBank: 'lmdb', 'rocksdict' or 'speedict'. "
701 "'rocksdict' requires installing bio-corgi[rocksdict] and 'speedict' requires seqbank[speedict].",
702 ),
703 render: Path = ta.Param(default=None, help="The path to render an image of the SeqTree."),
704 accessions: Path = ta.Param(default=None, help="The path to write a list of the accessions in the SeqTree."),
705 partitions: int = ta.Param(default=6, help="The number of cross-validation partitions."),
706 max_seqs: int = ta.Param(
707 default=100, help="The maximum number of sequences for each leaf node. Use 0 for no limit."
708 ),
709 catalog: Path = ta.Param(
710 default=None, help="The path to a RefSeq catalog. If not given, then the latest release is downloaded."
711 ),
712 ranks: str = ta.Param(
713 default="superkingdom,kingdom,phylum,class,order",
714 help="The comma-separated taxonomic ranks to include in the tree.",
715 ),
716 restrict_ranks: str = ta.Param(
717 default="class,order", help="The comma-separated ranks of the nodes which sequences can be assigned to."
718 ),
719 mitochondrion_ranks: str = ta.Param(default="", help="Overrides `ranks` for mitochondrion sequences."),
720 plastid_ranks: str = ta.Param(default="", help="Overrides `ranks` for plastid sequences."),
721 plasmid_ranks: str = ta.Param(default="", help="Overrides `ranks` for plasmid sequences."),
722 nuclear_ranks: str = ta.Param(default="", help="Overrides `ranks` for nuclear sequences."),
723 mitochondrion_restrict_ranks: str = ta.Param(
724 default="", help="Overrides `restrict_ranks` for mitochondrion sequences."
725 ),
726 plastid_restrict_ranks: str = ta.Param(default="", help="Overrides `restrict_ranks` for plastid sequences."),
727 plasmid_restrict_ranks: str = ta.Param(default="", help="Overrides `restrict_ranks` for plasmid sequences."),
728 nuclear_restrict_ranks: str = ta.Param(default="", help="Overrides `restrict_ranks` for nuclear sequences."),
729 print_tree: bool = ta.Param(default=False, help="Whether or not to print the tree to the screen."),
730 ):
731 """
732 Builds a SeqTree from the RefSeq catalog for the accessions found in a SeqBank.
734 Each accession is placed in the taxonomic tree and assigned to a cross-validation partition.
735 """
736 from .refseq import refseq_to_seqtree
738 return refseq_to_seqtree(
739 output=output,
740 seqbank=seqbank,
741 seqbank_output=seqbank_output,
742 engine=engine,
743 render=render,
744 accessions=accessions,
745 partitions=partitions,
746 max_seqs=max_seqs,
747 catalog=catalog,
748 ranks=ranks,
749 restrict_ranks=restrict_ranks,
750 mitochondrion_ranks=mitochondrion_ranks,
751 plastid_ranks=plastid_ranks,
752 plasmid_ranks=plasmid_ranks,
753 nuclear_ranks=nuclear_ranks,
754 mitochondrion_restrict_ranks=mitochondrion_restrict_ranks,
755 plastid_restrict_ranks=plastid_restrict_ranks,
756 plasmid_restrict_ranks=plasmid_restrict_ranks,
757 nuclear_restrict_ranks=nuclear_restrict_ranks,
758 print_tree=print_tree,
759 )