Coverage for terrier/repeatmasker.py: 100.00%

128 statements  

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

1from pathlib import Path 

2from hierarchicalsoftmax import SoftmaxNode 

3from Bio import SeqIO 

4import toml 

5from corgi.seqtree import SeqTree 

6from collections import Counter, defaultdict 

7import gzip 

8import hashlib 

9import pandas as pd 

10from rich.console import Console 

11from rich.table import Table 

12 

13 

14def open_maybe_gz(file:Path): 

15 if file.name.endswith('.gz'): 

16 return gzip.open(file, "rt") 

17 else: 

18 return open(file, "r") 

19 

20 

21def get_verbatim_classification(path:Path, record) -> str: 

22 accession = record.id 

23 

24 description = record.description 

25 

26 if "#" in description: 

27 description = description[ description.find("#")+1 : ] 

28 

29 components = description.split("\t") 

30 if len(components) >= 2: 

31 return components[1] 

32 

33 if path.name == "simple.ref": 

34 return "Simple Repeat" 

35 elif accession.startswith("SINE_"): 

36 return "SINE" 

37 else: 

38 return description 

39 

40 

41def choose_classification(classifications:list[str]) -> str: 

42 """ 

43 Chooses the classification for an accession which has been given several labels. 

44 

45 A label is dropped if a more specific label of the same lineage is also present 

46 (e.g. 'DNA' is dropped in favour of 'DNA/hAT'). If labels from different lineages 

47 remain (e.g. 'DNA/hAT' and 'DNA/TcMar') then the most specific one is used, then the 

48 most common one, with ties broken alphabetically. This means that the result does not 

49 depend on the order of the files, and a generic label never outvotes a specific one. 

50 """ 

51 counts = Counter(classifications) 

52 remaining = [ 

53 label for label in counts 

54 if not any(other.startswith(f"{label}/") for other in counts) 

55 ] 

56 return min(remaining, key=lambda label: (-label.count("/"), -counts[label], label)) 

57 

58 

59def load_accession_rules(mapping:dict[str,str]) -> dict[str,str]: 

60 """ 

61 Loads the classifications for individual accessions from data/repbase-accession-rules.toml. 

62 

63 Every classification must be one which the label mapping can produce. 

64 """ 

65 with open(Path(__file__).parent/"data/repbase-accession-rules.toml", "r") as f: 

66 rules = toml.load(f) 

67 invalid = {accession: target for accession, target in rules.items() if target not in mapping.values()} 

68 if invalid: 

69 raise ValueError(f"Accession rules with classifications which are not in the mapping: {invalid}") 

70 return rules 

71 

72 

73def create_repeatmasker_seqtree( 

74 fasta_paths:list[Path], 

75 label_smoothing:float=0.0, 

76 gamma:float=0.0, 

77 partitions:int=5, 

78 seed:int=0, 

79 summary_csv:Path=None, 

80 classifications_csv:Path=None, 

81 retained_csv:Path=None, 

82 accession_rules:dict[str,str]=None, 

83) -> SeqTree: 

84 if partitions < 1: 

85 raise ValueError("partitions must be a positive integer") 

86 

87 with open(Path(__file__).parent/"data/repbase-to-repeatmasker.toml", "r") as f: 

88 mapping = toml.load(f) 

89 

90 if accession_rules is None: 

91 accession_rules = load_accession_rules(mapping) 

92 

93 classification_counts = Counter() 

94 retained_counts = Counter() 

95 total_bases = 0 

96 

97 # Create Tree From Text File 

98 classification_tree = SoftmaxNode(name="root", label_smoothing=label_smoothing, gamma=gamma) 

99 classification_nodes = {} 

100 

101 seqtree = SeqTree(classification_tree) 

102 

103 def get_node(classification:str) -> SoftmaxNode: 

104 if classification not in classification_nodes: 

105 components = classification.split("/") 

106 repeat_type = components[0] 

107 repeat_subtype = components[1] if len(components) > 1 else "" 

108 

109 if repeat_type not in classification_nodes: 

110 classification_nodes[repeat_type] = SoftmaxNode( 

111 repeat_type, 

112 parent=classification_tree, 

113 label_smoothing=label_smoothing, 

114 gamma=gamma, 

115 repeat_masker_name=repeat_type, 

116 ) 

117 repeat_type_node = classification_nodes[repeat_type] 

118 if repeat_subtype: 

119 classification_nodes[classification] = SoftmaxNode( 

120 repeat_subtype, 

121 parent=repeat_type_node, 

122 label_smoothing=label_smoothing, 

123 gamma=gamma, 

124 repeat_masker_name=classification, 

125 ) 

126 return classification_nodes[classification] 

127 

128 # Read files. The same accession can appear in several files with different labels, 

129 # so collect every labelled occurrence first and only then add each accession once. 

130 occurrences = defaultdict(list) # accession -> [(provided, status, classification, digest)] 

131 for file in fasta_paths: 

132 with open_maybe_gz(file) as f: 

133 for record in SeqIO.parse(f, "fasta"): 

134 accession = record.id 

135 

136 provided = get_verbatim_classification(file, record) 

137 classification = mapping.get(provided, provided) 

138 total_bases += len(record.seq) 

139 if accession in accession_rules: 

140 classification = accession_rules[accession] 

141 status = "rule" 

142 else: 

143 if classification == "Unknown": 

144 classification_counts[(provided, "unknown", classification)] += 1 

145 continue 

146 if classification not in mapping.values(): 

147 classification_counts[(provided, "unsupported", "")] += 1 

148 continue 

149 status = "mapped" if provided in mapping else "direct" 

150 

151 get_node(classification) # creates nodes in the order that labels first appear 

152 payload = f"{seed}:{str(record.seq).upper()}".encode("utf-8") 

153 digest = int.from_bytes(hashlib.sha256(payload).digest(), "big") 

154 occurrences[accession].append((provided, status, classification, digest)) 

155 

156 for accession, entries in occurrences.items(): 

157 classification = choose_classification([entry[2] for entry in entries]) 

158 node = classification_nodes[classification] 

159 # The partition comes from the sequence so that it does not depend on file order 

160 partition = min(digest for _, _, label, digest in entries if label == classification) % partitions 

161 seqtree.add(accession, node, partition) 

162 

163 for provided, status, label, _ in entries: 

164 if label == classification: 

165 retained_counts[label] += 1 

166 classification_counts[(provided, status, label)] += 1 

167 elif classification.startswith(f"{label}/"): 

168 # A more general label for an accession that also has a specific one 

169 classification_counts[(provided, "superseded", label)] += 1 

170 else: 

171 classification_counts[(provided, "add_failed", label)] += 1 

172 

173 

174 input_counts = Counter() 

175 for (provided, _, _), count in classification_counts.items(): 

176 input_counts[provided] += count 

177 rows = [] 

178 for provided, count in sorted(input_counts.items(), key=lambda item: (-item[1], item[0])): 

179 target = mapping.get(provided, provided) 

180 if target not in mapping.values() or target == "Unknown": 

181 target = "<UNSUPPORTED>" 

182 rows.append((provided, target, count)) 

183 classifications = pd.DataFrame(rows, columns=["provided", "repeat_masker", "count"]) 

184 total = sum(classification_counts.values()) 

185 accepted = sum(retained_counts.values()) 

186 statuses = Counter() 

187 for (_, status, _), count in classification_counts.items(): 

188 statuses[status] += count 

189 summary = pd.DataFrame([ 

190 ("Input files", len(fasta_paths)), 

191 ("Input sequences", total), 

192 ("Input bases", total_bases), 

193 ("Retained sequences", accepted), 

194 ("Accession rules applied", statuses["rule"]), 

195 ("Unsupported sequences", statuses["unsupported"]), 

196 ("Generic labels superseded", statuses["superseded"]), 

197 ("Unknown sequences", statuses["unknown"]), 

198 ("Conflicting labels dropped", statuses["add_failed"]), 

199 ("Retained classifications", len(retained_counts)), 

200 ], columns=["metric", "value"]) 

201 retained = pd.DataFrame([ 

202 (classification, count, round(100 * count / accepted, 2)) 

203 for classification, count in sorted(retained_counts.items(), key=lambda item: (-item[1], item[0])) 

204 ], columns=["repeat_masker", "count", "percent_retained"]) 

205 console = Console() 

206 for title, frame, output in [ 

207 ("Dataset summary", summary, summary_csv), 

208 ("Input classifications", classifications, classifications_csv), 

209 ("Retained classifications (direct assignments)", retained, retained_csv), 

210 ]: 

211 table = Table(title=title) 

212 for column in frame.columns: 

213 table.add_column(column, justify="right" if column in {"count", "value", "percent_retained"} else "left") 

214 for row in frame.itertuples(index=False, name=None): 

215 table.add_row(*(str(value) for value in row)) 

216 console.print(table) 

217 if output is not None: 

218 output = Path(output) 

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

220 frame.to_csv(output, index=False) 

221 console.print("<UNSUPPORTED> = no supported classification. SeqBank contains the input sequences.") 

222 return seqtree