Coverage for corgi/seqtree.py: 99.25%
133 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"""SeqTree: a mapping from sequence accessions to partitions and nodes in a classification tree."""
3from typing import TYPE_CHECKING, List, Optional
4from pathlib import Path
5import hashlib
6import typer
7from rich.progress import track
8from hierarchicalsoftmax.treedict import TreeDict, NodeDetail, AlreadyExists # noqa: F401 AlreadyExists is re-exported
10if TYPE_CHECKING:
11 from hierarchicalsoftmax import SoftmaxNode
12 from seqbank import SeqBank
15def str_to_int_hash(s: str) -> int:
16 """Return a deterministic 32-bit integer seed from the string's MD5 hash."""
17 hash_object = hashlib.md5(s.encode())
18 hash_digest = hash_object.digest()
20 # Convert the hash to an integer
21 seed_number = int.from_bytes(hash_digest, 'big')
22 seed_number = seed_number % (2**32) # The maximum value is 2**32-1 for a numpy seed
24 return seed_number
27def node_to_str(node: "SoftmaxNode") -> str:
28 """
29 Converts the node to a string
30 """
31 # return "/".join([str(n) for n in node.ancestors[1:]] + [str(node)])
32 result = str(node)
33 ancestors = node.ancestors[1:]
34 if ancestors:
35 result = f"{ancestors[0]}/{result}"
36 return result
39# Alias, not a subclass: pickles saved before SeqTree subclassed TreeDict reference
40# `corgi.seqtree.SeqDetail`, and `NodeDetail` has the same `(partition, node_id)` state.
41SeqDetail = NodeDetail
44class SeqTree(TreeDict):
45 """A TreeDict from sequence accessions to their partition and node in a classification tree.
47 Keeps corgi's accession-based method names and adds SeqBank-specific methods.
48 """
50 def accessions(self, partition: int | None = None):
51 """Return all accession keys or an iterator over the requested partition."""
52 return self.keys(partition)
54 def accessions_in_partition(self, partition: int):
55 """Yield accessions assigned to the given partition."""
56 return self.keys_in_partition(partition)
58 def accessions_to_file(self, file: Path) -> None:
59 """Writes all the accessions of this SeqTree to a file."""
60 return self.keys_to_file(file)
62 def prune(self, max_depth: int) -> "SeqTree":
63 """
64 Returns a new SeqTree with the classification tree truncated to a maximum depth.
66 The original SeqTree is not modified, although its tree is indexed (and so becomes read-only).
67 """
68 return self.truncate(max_depth)
70 def export(
71 self,
72 seqbank: "SeqBank",
73 output: Path | str,
74 length: int = 0,
75 format: str = "",
76 seed: int = 0,
77 partition: int | None = None,
78 ):
79 """
80 Outputs sequences from a seqbank into a file.
82 If the partition is given then only the accessions in the partition are exported.
83 The format of the exported file. If not given, then it will be inferred from the file extension of the output.
85 The slice is taken from a random position in the sequence that is at least `length` long.
87 Random seed can be set with `seed`.
88 """
89 import numpy as np
90 from Bio.Seq import Seq
91 from Bio import SeqIO
92 from Bio.SeqRecord import SeqRecord
93 from seqbank.transform import bytes_to_str
94 from seqbank.io import get_file_format
96 format = format or get_file_format(output)
97 with open(output, "w") as f:
98 for accession, detail in track(self.items()):
99 if partition is not None and detail.partition != partition:
100 continue
102 data = seqbank[accession]
103 node = self.node(accession)
104 # If the sequence is long enough, take a random slice
105 if length and len(data) > length:
106 start_max = len(data) - length
107 my_seed = seed + str_to_int_hash(accession)
108 np.random.seed(my_seed % 2**32)
109 start = np.random.randint(0, start_max + 1)
110 data = data[start : start + length]
112 seq_string = bytes_to_str(data)
113 node_str = node_to_str(node)
114 record = SeqRecord(
115 Seq(seq_string),
116 id=f"{accession}#{node_str}",
117 description="",
118 )
120 SeqIO.write(record, f, format)
122 def intersection_seqbank(self, seqbank: "SeqBank") -> List[str]:
123 """
124 Removes any accession that is not found in a SeqBank.
126 Returns a list of missing accessions.
127 """
128 my_accessions = self.keys()
129 missing = seqbank.missing(my_accessions)
130 for accession in missing:
131 del self[accession]
132 return missing
135app = typer.Typer()
138@app.command()
139def intersection_seqbank(
140 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
141 seqbank: Path = typer.Argument(..., help="The path to the SeqBank."),
142 output: Path = typer.Argument(..., help="The path to the SeqBank."),
143):
144 """
145 Takes a SeqTree and removes any accession that is not found in a SeqBank.
147 Saves the output SeqTree to `output`.
148 """
149 from seqbank import SeqBank
151 seqtree = SeqTree.load(seqtree)
152 seqbank = SeqBank(seqbank)
153 try:
154 seqtree.intersection_seqbank(seqbank)
155 finally:
156 seqbank.close()
157 seqtree.save(output)
160@app.command()
161def accessions(
162 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
163 partition: Optional[int] = typer.Option(None, help="The index of the partition to list."),
164):
165 """
166 Prints a list of accessions in a SeqTree.
168 If a partition is given, then only the accessions for that partition are given.
169 """
170 seqtree = SeqTree.load(seqtree)
171 for accession in seqtree.accessions(partition=partition):
172 print(accession)
175@app.command()
176def export(
177 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
178 seqbank: Path = typer.Argument(..., help="The path to the SeqBank."),
179 output: Path = typer.Argument(..., help="The path to the output file."),
180 length: int = typer.Option(None, help="If used then a subsequence this maximum length is selected."),
181 seed: int = typer.Option(42, help="The random seed to use when slicing the length."),
182 partition: Optional[int] = typer.Option(
183 None,
184 help="The index of the partition to include in the export. If not given then all accesions will be exported.",
185 ),
186 format: str = typer.Option(
187 "",
188 help="The format of the exported file. If not given, then it will be inferred from the file extension of the output.",
189 ),
190):
191 """Export sequences with accession and classification labels from a SeqBank.
193 Optionally select a partition and pass length and seed options to the
194 exporter. Infer the sequence format from the output path if omitted.
195 """
196 from seqbank import SeqBank
198 seqtree = SeqTree.load(seqtree)
199 seqbank = SeqBank(seqbank)
200 try:
201 seqtree.export(seqbank, output, format=format, length=length, seed=seed, partition=partition)
202 finally:
203 seqbank.close()
206@app.command()
207def render(
208 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
209 output: Optional[Path] = typer.Option(None, help="The path to save the rendered tree."),
210 print: bool = typer.Option(True, help="Whether or not to print the tree to the screen."),
211 count: bool = typer.Option(False, help="Whether or not to print the count of accessions at each node."),
212 partition_counts: bool = typer.Option(
213 False, help="Whether or not to print the count of each partition at each node."
214 ),
215 alphabetical: bool = typer.Option(False, help="Whether or not to sort the children of each node alphabetically."),
216):
217 """Render a saved SeqTree, optionally displaying or saving accession counts."""
218 seqtree = SeqTree.load(seqtree)
219 seqtree.render(
220 filepath=output, print=print, count=count, partition_counts=partition_counts, alphabetical=alphabetical
221 )
224@app.command()
225def count(
226 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
227):
228 """Print the number of accessions in a saved SeqTree."""
229 seqtree = SeqTree.load(seqtree)
230 print(len(seqtree))
233@app.command()
234def sunburst(
235 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
236 show: bool = typer.Option(False, help="Whether or not to show the plot."),
237 output: Path = typer.Option(None, help="The path to save the rendered tree."),
238 width: int = typer.Option(1000, help="The width of the plot."),
239 height: int = typer.Option(0, help="The height of the plot. If 0 then it will be calculated based on the width."),
240):
241 """Plot accession counts as a sunburst and optionally display or save it.
243 Save HTML for an .html output path and an image otherwise. Default the
244 plot height to its width when height is zero.
245 """
246 seqtree = SeqTree.load(seqtree)
247 height = height or width
249 fig = seqtree.sunburst(width=width, height=height)
250 if show:
251 fig.show()
253 if output:
254 output = Path(output)
255 output.parent.mkdir(exist_ok=True, parents=True)
257 if output.suffix.lower() == ".html":
258 fig.write_html(output)
259 else:
260 # https://github.com/plotly/plotly.py/issues/3469
261 import plotly.io as pio
263 try: # Kaleido 0.x only
264 pio.kaleido.scope.mathjax = None
265 except AttributeError:
266 pass
267 fig.write_image(output)
270@app.command()
271def prune(
272 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
273 max_depth: int = typer.Argument(..., help="The maximum depth to prune the tree."),
274 output: Path = typer.Argument(..., help="The path to the output file."),
275):
276 """
277 Prunes the tree to a maximum depth.
278 """
279 seqtree = SeqTree.load(seqtree)
280 new_tree = seqtree.prune(max_depth)
281 new_tree.save(output)
284@app.command()
285def layer_size(
286 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
287):
288 """
289 Prints the size of the neural network layer to predict the classification tree.
290 """
291 seqtree = SeqTree.load(seqtree)
292 print(seqtree.classification_tree.layer_size)
295@app.command()
296def pickle_tree(
297 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
298 output: Path = typer.Argument(..., help="The path to the output pickle file."),
299):
300 """Extract the classification tree from a saved SeqTree into a pickle file."""
301 seqtree = SeqTree.load(seqtree)
302 seqtree.pickle_tree(output)
305@app.command()
306def set_partition(
307 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
308 pattern: str = typer.Argument(..., help="The pattern to match accessions."),
309 partition: int = typer.Argument(..., help="The partition to set for matching accessions."),
310 output: Path = typer.Argument(..., help="The path to the output file."),
311):
312 """Set the partition for accessions matching a shell-style pattern and save."""
313 seqtree = SeqTree.load(seqtree)
314 seqtree.set_partition(pattern, partition)
315 seqtree.save(output)
318@app.command()
319def merge(
320 seqtree: Path = typer.Argument(..., help="The path to the SeqTree."),
321 other: Path = typer.Argument(..., help="The path to the other SeqTree."),
322 output: Path = typer.Argument(..., help="The path to the output file."),
323):
324 """Merge another SeqTree into this one and save."""
325 seqtree = SeqTree.load(seqtree)
326 other = SeqTree.load(other)
327 seqtree.merge(other)
328 seqtree.save(output)
331if __name__ == "__main__":
332 app()