Coverage for corgi/refseq.py: 100.00%

142 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-28 00:24 +0000

1"""Tools for building a SeqTree from the RefSeq catalog and taxonomy.""" 

2 

3from multitax import NcbiTx 

4from hierarchicalsoftmax import SoftmaxNode 

5from pathlib import Path 

6import requests 

7from enum import Enum 

8from appdirs import user_cache_dir 

9from torchapp.download import cached_download 

10from rich.progress import track 

11from seqbank import SeqBank 

12import gzip 

13 

14 

15from .seqtree import SeqTree 

16 

17# https://academic.oup.com/nar/article/44/D1/D733/2502674 

18DNA_PREFIXES = {"NC", "AC", "NZ", "NT", "NW", "NG"} 

19 

20RANKS = ("superkingdom", "kingdom", "phylum", "class", "order") 

21 

22 

23class DNAType(Enum): 

24 """The types of DNA sequence that are classified.""" 

25 

26 NUCLEAR = "Nuclear" 

27 MITOCHONDRION = "Mitochondrion" 

28 PLASTID = "Plastid" 

29 PLASMID = "Plasmid" 

30 

31 def __str__(self): 

32 """Returns the name of the type.""" 

33 return str(self.value) 

34 

35 @classmethod 

36 def from_description(cls, description: str): 

37 """Convert a description to a DNAType.""" 

38 description = description.lower() 

39 if "mitochondrion" in description: 

40 return cls.MITOCHONDRION 

41 elif "plastid" in description: 

42 return cls.PLASTID 

43 elif "plasmid" in description: 

44 return cls.PLASMID 

45 else: 

46 return cls.NUCLEAR 

47 

48 

49def my_open(file): 

50 """Opens a text file for reading, or a gzipped file in binary mode.""" 

51 file = Path(file) 

52 if file.suffix.lower() == ".gz": 

53 return gzip.open(file, 'rb') 

54 return open(file, "r") 

55 

56 

57def line_count(file: Path): 

58 """Adapted from https://stackoverflow.com/a/9631635""" 

59 

60 def blocks(stream, size=65536): 

61 """Yields blocks of the stream until it is exhausted.""" 

62 while True: 

63 b = stream.read(size) 

64 if not b: 

65 break 

66 yield b 

67 

68 with my_open(file) as f: 

69 if isinstance(f, gzip.GzipFile): 

70 count = sum(bl.count(b"\n") for bl in track(blocks(f), description="Counting lines:")) 

71 else: 

72 count = sum(bl.count("\n") for bl in track(blocks(f), description="Counting lines:")) 

73 

74 return count 

75 

76 

77def get_refseq_release() -> int: 

78 """Returns the number of the current RefSeq release.""" 

79 url = "https://ftp.ncbi.nlm.nih.gov/refseq/release/RELEASE_NUMBER" 

80 response = requests.get(url) 

81 data = response.text.strip() 

82 return int(data) 

83 

84 

85def get_catalogue() -> Path: 

86 """Downloads (or reuses from the cache) the catalog for the current RefSeq release and returns its path.""" 

87 version = get_refseq_release() 

88 filename = f"RefSeq-release{version}.catalog.gz" 

89 url = f"https://ftp.ncbi.nlm.nih.gov/refseq/release/release-catalog/{filename}" 

90 

91 local_path = Path(user_cache_dir("torchapps")) / "Corgi" / filename 

92 cached_download(url, local_path=local_path) 

93 return local_path 

94 

95 

96def get_node_at_rank(taxon, taxonomy, taxon_to_node, current_node, rank): 

97 """Returns the node for the taxon's ancestor at a rank, creating it under `current_node` if needed. 

98 

99 If the taxon has no ancestor at the rank, then `current_node` is returned. 

100 

101 Args: 

102 taxon: The taxon ID. 

103 taxonomy: The taxonomy (e.g. multitax.NcbiTx). 

104 taxon_to_node (dict): The nodes already created, by taxon ID. 

105 current_node (SoftmaxNode): The parent node for any new node. 

106 rank (str): The taxonomic rank. 

107 """ 

108 current_id = taxonomy.parent_rank(taxon, rank) 

109 if not current_id: 

110 return current_node 

111 

112 if current_id in taxon_to_node: 

113 return taxon_to_node[current_id] 

114 

115 name = taxonomy.name(current_id) 

116 current_node = SoftmaxNode(name, parent=current_node, id=current_id, rank=rank, nseq=0) 

117 taxon_to_node[current_id] = current_node 

118 return current_node 

119 

120 

121def get_node(taxon, taxonomy, taxon_to_node, root, ranks): 

122 """Returns the node in the tree for a taxon, creating nodes for its ancestors at the given ranks as needed. 

123 

124 Args: 

125 taxon: The taxon ID. 

126 taxonomy: The taxonomy (e.g. multitax.NcbiTx). 

127 taxon_to_node (dict): The nodes already created, by taxon ID. 

128 root (SoftmaxNode): The node to start from. 

129 ranks (list[str]): The ranks to include, from the highest to the lowest. 

130 """ 

131 current_node = root 

132 for rank in ranks: 

133 current_node = get_node_at_rank(taxon, taxonomy, taxon_to_node, current_node, rank) 

134 

135 return current_node 

136 

137 

138def refseq_to_seqtree( 

139 output: Path, 

140 seqbank: Path, 

141 seqbank_output: Path | None = None, 

142 engine: str | None = "lmdb", 

143 render: Path | None = None, 

144 accessions: Path | None = None, 

145 partitions: int = 6, 

146 max_seqs: int = 100, 

147 catalog: Path | None = None, 

148 ranks: str = "superkingdom,kingdom,phylum,class,order", 

149 restrict_ranks: str = "class,order", 

150 mitochondrion_ranks: str = "", 

151 plastid_ranks: str = "", 

152 plasmid_ranks: str = "", 

153 nuclear_ranks: str = "", 

154 mitochondrion_restrict_ranks: str = "", 

155 plastid_restrict_ranks: str = "", 

156 plasmid_restrict_ranks: str = "", 

157 nuclear_restrict_ranks: str = "", 

158 print_tree: bool = False, 

159): 

160 """Builds a SeqTree from the RefSeq catalog for the accessions found in a SeqBank. 

161 

162 Each accession is placed in the taxonomic tree and assigned to a cross-validation partition. 

163 This is available on the command line as `corgi-tools refseq-to-seqtree`. 

164 

165 Args: 

166 output (Path): The path to save the SeqTree. 

167 seqbank (Path): The SeqBank with the sequences for the RefSeq accessions. 

168 seqbank_output (Path | None): Where to save a new SeqBank containing only the sequences selected for 

169 the SeqTree. 

170 engine (str | None): The storage engine for the output SeqBank: 'lmdb' (default), 'rocksdict' or 'speedict'. 

171 'rocksdict' requires the optional ``bio-corgi[rocksdict]`` extra and 'speedict' requires ``seqbank[speedict]``. 

172 If None, then seqbank chooses: RocksDict if it is installed, otherwise LMDB. 

173 render (Path | None): The path to render an image of the SeqTree. 

174 accessions (Path | None): The path to write a list of the accessions in the SeqTree. 

175 partitions (int): The number of cross-validation partitions. 

176 max_seqs (int): The maximum number of sequences for each leaf node. Use 0 for no limit. 

177 catalog (Path | None): The path to a RefSeq catalog. If not given, then the latest release is downloaded. 

178 ranks (str): The comma-separated taxonomic ranks to include in the tree. 

179 restrict_ranks (str): The comma-separated ranks of the nodes which sequences can be assigned to. 

180 mitochondrion_ranks (str): Overrides `ranks` for mitochondrion sequences. 

181 plastid_ranks (str): Overrides `ranks` for plastid sequences. 

182 plasmid_ranks (str): Overrides `ranks` for plasmid sequences. 

183 nuclear_ranks (str): Overrides `ranks` for nuclear sequences. 

184 mitochondrion_restrict_ranks (str): Overrides `restrict_ranks` for mitochondrion sequences. 

185 plastid_restrict_ranks (str): Overrides `restrict_ranks` for plastid sequences. 

186 plasmid_restrict_ranks (str): Overrides `restrict_ranks` for plasmid sequences. 

187 nuclear_restrict_ranks (str): Overrides `restrict_ranks` for nuclear sequences. 

188 print_tree (bool): Whether or not to print the tree to the screen. 

189 """ 

190 catalog = catalog or get_catalogue() 

191 print(f"Using catalog: {catalog}") 

192 count = line_count(catalog) 

193 print(f"{count} lines in catalog") 

194 

195 seqbank = SeqBank(seqbank) 

196 seqbank_accessions = seqbank.get_accessions() 

197 

198 if seqbank_output is not None: 

199 print(f"Saving seqbank with accessions corresponding to {seqbank_output}") 

200 seqbank_output = SeqBank(seqbank_output, write=True, engine=engine) 

201 

202 root = SoftmaxNode("root", rank="root", nseq=0) 

203 seqtree = SeqTree(root) 

204 

205 # Setup Nodes for each DNAType 

206 type_nodes = {} 

207 type_taxon_to_node = {} 

208 for type_obj in DNAType: 

209 type_str = str(type_obj) 

210 type_nodes[type_str] = SoftmaxNode(type_str, parent=root, rank="type", nseq=0) 

211 type_taxon_to_node[type_str] = {} 

212 

213 rank_strings = dict( 

214 mitochondrion=mitochondrion_ranks or ranks, 

215 plastid=plastid_ranks or ranks, 

216 plasmid=plasmid_ranks or ranks, 

217 nuclear=nuclear_ranks or ranks, 

218 ) 

219 

220 restrict_rank_strings = dict( 

221 mitochondrion=mitochondrion_restrict_ranks or restrict_ranks, 

222 plastid=plastid_restrict_ranks or restrict_ranks, 

223 plasmid=plasmid_restrict_ranks or restrict_ranks, 

224 nuclear=nuclear_restrict_ranks or restrict_ranks, 

225 ) 

226 

227 ranks_by_type = {k.title(): v.split(",") for k, v in rank_strings.items()} 

228 restrict_ranks_by_type = {k.title(): v.split(",") for k, v in restrict_rank_strings.items()} 

229 

230 print('Loading taxonomy...') 

231 taxonomy = NcbiTx() 

232 

233 with my_open(catalog) as f: 

234 for line in track(f, description="Processing RefSeq: ", total=count): 

235 if isinstance(line, bytes): 

236 line = line.decode() 

237 components = line.split("\t") 

238 accession = components[2] 

239 

240 if accession not in seqbank_accessions: 

241 continue 

242 

243 prefix = accession[:2] 

244 

245 # Exclude non-DNA sequences 

246 if prefix not in DNA_PREFIXES: 

247 continue 

248 

249 taxon = components[0] 

250 files = components[3] 

251 # status = components[4] 

252 

253 # Get the type of DNA by seeing what files it is in 

254 if "mitochondrion" in files: 

255 type_obj = DNAType.MITOCHONDRION 

256 elif "plastid" in files: 

257 type_obj = DNAType.PLASTID 

258 elif "plasmid" in files: 

259 type_obj = DNAType.PLASMID 

260 else: 

261 type_obj = DNAType.NUCLEAR 

262 type_str = str(type_obj) 

263 

264 # Get the node for this taxon 

265 node = get_node( 

266 taxon, taxonomy, type_taxon_to_node[type_str], type_nodes[type_str], ranks=ranks_by_type[type_str] 

267 ) 

268 

269 # Skip if not in one of the allowed ranks (e.g. class, order) 

270 if node.rank not in restrict_ranks_by_type[type_str]: 

271 continue 

272 

273 # Skip if we have too many sequences for this leaf node 

274 if max_seqs and node.nseq >= max_seqs: 

275 continue 

276 

277 if seqbank_output is not None: 

278 seqbank_output.add(seqbank[accession], accession) 

279 

280 partition = node.nseq % partitions 

281 

282 node.nseq += 1 

283 

284 seqtree.add(accession, node, partition) 

285 

286 print(f'Saving seqtree with {len(seqtree)} sequences to {output}') 

287 seqtree.save(output) 

288 

289 if render: 

290 print(f"Rendering seqtree to {render}") 

291 

292 for node in root.post_order_iter(): 

293 node.render_str = f"{node.name} ({node.nseq})" if node.nseq else node.name 

294 

295 seqtree.render(filepath=render, attr="render_str", print=print_tree) 

296 

297 if accessions: 

298 print(f"Writing accessions to file {accessions}") 

299 seqtree.accessions_to_file(accessions) 

300 

301 if seqbank_output is not None: 

302 seqbank_output.close() 

303 seqbank.close()