Coverage for src/python/ensembl/vep/corpus/exporter/formats/file/gff3.py: 97%

86 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-18 14:41 +0000

1# See the NOTICE file distributed with this work for additional information 

2# regarding copyright ownership. 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14"""GFF3 rendering for corpora.""" 

15 

16from __future__ import annotations 

17 

18from collections.abc import Iterator, Sequence 

19from urllib.parse import quote 

20 

21from ensembl.vep.common import Strand 

22from ensembl.vep.corpus.base import Corpus 

23from ensembl.vep.models.genic import Gene, Transcript 

24 

25__all__ = ["GFF3_NAME", "escape_attribute_value", "gff3_lines"] 

26 

27GFF3_NAME = "corpus.gff3" 

28 

29_SOURCE = "ensembl_vep_synthetic" 

30_ATTRIBUTE_SAFE_CHARACTERS = ".:^*$@!+_?-|" 

31 

32 

33def escape_attribute_value(value: str) -> str: 

34 """Percent-encode one scalar GFF3 attribute value.""" 

35 return quote(value, safe=_ATTRIBUTE_SAFE_CHARACTERS) 

36 

37 

38def _typed_id(kind: str, stable_id: str) -> str: 

39 """Return a GFF3 identifier without duplicating an existing type prefix.""" 

40 prefix = f"{kind}:" 

41 return stable_id if stable_id.startswith(prefix) else f"{prefix}{stable_id}" 

42 

43 

44def _display_name(kind: str, stable_id: str) -> str: 

45 """Return the untyped portion of a conventionally prefixed GFF3 identifier.""" 

46 prefix = f"{kind}:" 

47 return stable_id.removeprefix(prefix) 

48 

49 

50def _translation_id(transcript: Transcript) -> str: 

51 """Return a stable, non-empty GFF3 identifier for a transcript's translation.""" 

52 translation = transcript.translation 

53 assert translation is not None 

54 stable_id = translation.stable_id or f"{_display_name('transcript', transcript.stable_id)}_translation" 

55 return _typed_id("CDS", stable_id) 

56 

57 

58def _strand_symbol(strand: Strand) -> str: 

59 """Return the GFF3 strand column for a strand.""" 

60 return "+" if strand == Strand.FORWARD else "-" 

61 

62 

63def _row( 

64 seq_region_name: str, 

65 feature_type: str, 

66 start: int, 

67 end: int, 

68 strand: Strand, 

69 attributes: dict[str, str], 

70 phase: int | None = None, 

71) -> str: 

72 """Return one nine-column GFF3 line.""" 

73 attribute_text = ";".join(f"{key}={escape_attribute_value(value)}" for key, value in attributes.items()) 

74 phase_text = "." if phase is None else str(phase) 

75 return "\t".join( 

76 ( 

77 seq_region_name, 

78 _SOURCE, 

79 feature_type, 

80 str(start), 

81 str(end), 

82 ".", 

83 _strand_symbol(strand), 

84 phase_text, 

85 attribute_text, 

86 ) 

87 ) 

88 

89 

90def _cds_rows(transcript: Transcript, seq_region_name: str) -> list[tuple[int, str]]: 

91 """Return the CDS rows, each keyed by start, with the phase each block begins in.""" 

92 spans = transcript.cds_genomic_spans 

93 translation = transcript.translation 

94 if not spans or translation is None: 

95 return [] 

96 rows = [] 

97 coding_bases_before = 0 

98 for block_start, block_end in spans: 

99 phase = (3 - coding_bases_before % 3) % 3 

100 rows.append( 

101 ( 

102 block_start, 

103 _row( 

104 seq_region_name, 

105 "CDS", 

106 block_start, 

107 block_end, 

108 transcript.strand, 

109 { 

110 "ID": _translation_id(transcript), 

111 "Parent": _typed_id("transcript", transcript.stable_id), 

112 "protein_id": _translation_id(transcript), 

113 }, 

114 phase=phase, 

115 ), 

116 ) 

117 ) 

118 coding_bases_before += block_end - block_start + 1 

119 return rows 

120 

121 

122def _utr_rows(transcript: Transcript, seq_region_name: str) -> list[tuple[int, str]]: 

123 """Return the UTR rows, each keyed by start.""" 

124 rows = [] 

125 for feature_type, spans in ( 

126 ("five_prime_UTR", transcript.five_prime_utr_genomic_spans), 

127 ("three_prime_UTR", transcript.three_prime_utr_genomic_spans), 

128 ): 

129 for block_start, block_end in spans or []: 

130 rows.append( 

131 ( 

132 block_start, 

133 _row( 

134 seq_region_name, 

135 feature_type, 

136 block_start, 

137 block_end, 

138 transcript.strand, 

139 {"Parent": _typed_id("transcript", transcript.stable_id)}, 

140 ), 

141 ) 

142 ) 

143 return rows 

144 

145 

146def _transcript_rows(transcript: Transcript, seq_region_name: str) -> list[str]: 

147 """Return a transcript's row followed by its exon, CDS and UTR rows in genomic order.""" 

148 attributes = { 

149 "ID": _typed_id("transcript", transcript.stable_id), 

150 "Name": _display_name("transcript", transcript.stable_id), 

151 } 

152 if transcript.gene is not None: 

153 attributes["Parent"] = _typed_id("gene", transcript.gene.stable_id) 

154 biotype = transcript.biotype 

155 if biotype is None and transcript.gene is not None: 

156 biotype = transcript.gene.biotype 

157 if biotype is not None: 

158 attributes["biotype"] = biotype 

159 rows = [ 

160 _row(seq_region_name, "transcript", transcript.start, transcript.end, transcript.strand, attributes) 

161 ] 

162 

163 children: list[tuple[int, str]] = [] 

164 for exon in transcript.spliced_exons: 

165 children.append( 

166 ( 

167 exon.start, 

168 _row( 

169 seq_region_name, 

170 "exon", 

171 exon.start, 

172 exon.end, 

173 exon.strand, 

174 { 

175 "ID": _typed_id("exon", exon.stable_id), 

176 "Parent": _typed_id("transcript", transcript.stable_id), 

177 }, 

178 ), 

179 ) 

180 ) 

181 children.extend(_cds_rows(transcript, seq_region_name)) 

182 children.extend(_utr_rows(transcript, seq_region_name)) 

183 children.sort(key=lambda entry: entry[0]) 

184 rows.extend(row for _start, row in children) 

185 return rows 

186 

187 

188def _gene_row(gene: Gene, seq_region_name: str) -> str: 

189 """Return a gene's row.""" 

190 attributes = {"ID": _typed_id("gene", gene.stable_id), "Name": _display_name("gene", gene.stable_id)} 

191 if gene.biotype is not None: 191 ↛ 193line 191 didn't jump to line 193 because the condition on line 191 was always true

192 attributes["biotype"] = gene.biotype 

193 return _row(seq_region_name, "gene", gene.start, gene.end, gene.strand, attributes) 

194 

195 

196def gff3_lines(corpora: Sequence[Corpus]) -> Iterator[str]: 

197 """Yield the GFF3 records for corpora.""" 

198 yield "##gff-version 3" 

199 for corpus in corpora: 

200 for sequence_region in corpus.sequence_regions: 

201 yield f"##sequence-region {sequence_region.seq_region_name} 1 {sequence_region.end}" 

202 for corpus in corpora: 

203 written_genes: set[str] = set() 

204 for transcript in corpus.transcripts: 

205 if transcript.slice is None: 205 ↛ 206line 205 didn't jump to line 206 because the condition on line 205 was never true

206 continue 

207 seq_region_name = transcript.slice.seq_region_name 

208 gene = transcript.gene 

209 if gene is not None and gene.stable_id not in written_genes: 

210 written_genes.add(gene.stable_id) 

211 yield _gene_row(gene, seq_region_name) 

212 yield from _transcript_rows(transcript, seq_region_name)