assemblytrace 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- assemblytrace/__init__.py +1 -0
- assemblytrace/__main__.py +4 -0
- assemblytrace/annotation.py +307 -0
- assemblytrace/attribute.py +1388 -0
- assemblytrace/change.py +221 -0
- assemblytrace/claims.py +612 -0
- assemblytrace/cli.py +230 -0
- assemblytrace/core.py +100 -0
- assemblytrace/curation.py +155 -0
- assemblytrace/formats.py +957 -0
- assemblytrace/identity.py +74 -0
- assemblytrace/indels.py +95 -0
- assemblytrace/inventory.py +379 -0
- assemblytrace/io_safety.py +69 -0
- assemblytrace/lift.py +467 -0
- assemblytrace/localmatch.py +51 -0
- assemblytrace/project.py +494 -0
- assemblytrace/prov.py +277 -0
- assemblytrace/provenance.py +183 -0
- assemblytrace/py.typed +0 -0
- assemblytrace/release.py +432 -0
- assemblytrace/report.py +1046 -0
- assemblytrace/scan.py +538 -0
- assemblytrace/segments.py +348 -0
- assemblytrace/seqcol.py +161 -0
- assemblytrace/shellexp.py +229 -0
- assemblytrace/sparsediff.py +905 -0
- assemblytrace/summary.py +146 -0
- assemblytrace/variant_input.py +91 -0
- assemblytrace/versions.py +583 -0
- assemblytrace-1.1.0.dist-info/METADATA +198 -0
- assemblytrace-1.1.0.dist-info/RECORD +36 -0
- assemblytrace-1.1.0.dist-info/WHEEL +5 -0
- assemblytrace-1.1.0.dist-info/entry_points.txt +2 -0
- assemblytrace-1.1.0.dist-info/licenses/LICENSE +21 -0
- assemblytrace-1.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.1.0"
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""GFF3 coordinate/relationship audit and conservative CDS-to-protein checks."""
|
|
2
|
+
from collections import defaultdict
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from urllib.parse import unquote
|
|
5
|
+
from .core import _contigs, _TRANS, _open
|
|
6
|
+
from Bio.Seq import Seq
|
|
7
|
+
from Bio.Data import CodonTable
|
|
8
|
+
|
|
9
|
+
CODONS = dict(zip(
|
|
10
|
+
[a+b+c for a in 'TCAG' for b in 'TCAG' for c in 'TCAG'],
|
|
11
|
+
'FFLLSSSSYY**CC*W' 'LLLLPPPPHHQQRRRR' 'IIIMTTTTNNKKSSRR' 'VVVVAAAADDEEGGGG'))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse_gff(gff):
|
|
15
|
+
records=[]
|
|
16
|
+
with _open(gff) as fh:
|
|
17
|
+
for ln, raw in enumerate(fh,1):
|
|
18
|
+
s=raw.strip()
|
|
19
|
+
if not s or s.startswith('#'):
|
|
20
|
+
continue
|
|
21
|
+
if s.startswith('>'): # ##FASTA section follows
|
|
22
|
+
break
|
|
23
|
+
parts=s.split('\t')
|
|
24
|
+
if len(parts)!=9:
|
|
25
|
+
raise ValueError(f'GFF3 line {ln}: expected nine tab-separated fields')
|
|
26
|
+
try:
|
|
27
|
+
start,end=int(parts[3]),int(parts[4])
|
|
28
|
+
except ValueError as e:
|
|
29
|
+
raise ValueError(f'GFF3 line {ln}: invalid coordinates') from e
|
|
30
|
+
attrs={}
|
|
31
|
+
parents=[]
|
|
32
|
+
gtf=False
|
|
33
|
+
if parts[8] not in ('.', ''):
|
|
34
|
+
for field in parts[8].split(';'):
|
|
35
|
+
field=field.strip()
|
|
36
|
+
if not field:
|
|
37
|
+
continue # trailing or doubled ';'
|
|
38
|
+
head=field.split('=',1)[0]
|
|
39
|
+
if '=' in field and ' ' not in head.strip():
|
|
40
|
+
k,v=field.split('=',1)
|
|
41
|
+
key=unquote(k.strip())
|
|
42
|
+
if key=='Parent':
|
|
43
|
+
# GFF3 list commas are literal delimiters only BEFORE decoding.
|
|
44
|
+
# A percent-encoded comma (%2C) belongs to the identifier.
|
|
45
|
+
parents=[unquote(item) for item in v.split(',')]
|
|
46
|
+
attrs[key]=unquote(v)
|
|
47
|
+
elif ' ' in field: # GTF: key "value"
|
|
48
|
+
k,v=field.split(None,1)
|
|
49
|
+
attrs[k]=v.strip().strip('"')
|
|
50
|
+
gtf=True
|
|
51
|
+
else:
|
|
52
|
+
raise ValueError(f'GFF3 line {ln}: invalid attribute {field!r}')
|
|
53
|
+
if gtf:
|
|
54
|
+
tid=attrs.get('transcript_id')
|
|
55
|
+
if parts[2] in ('transcript','mRNA'):
|
|
56
|
+
attrs.setdefault('ID', tid or attrs.get('gene_id'))
|
|
57
|
+
if attrs.get('gene_id'): parents=[attrs['gene_id']]
|
|
58
|
+
elif parts[2]=='gene':
|
|
59
|
+
attrs.setdefault('ID', attrs.get('gene_id'))
|
|
60
|
+
elif tid:
|
|
61
|
+
parents=[tid]
|
|
62
|
+
records.append({'parents':parents,'line':ln,'seqid':unquote(parts[0]),'source':parts[1],'type':parts[2],
|
|
63
|
+
'start':start,'end':end,'strand':parts[6],
|
|
64
|
+
'phase':parts[7],'attributes':attrs,'gtf':gtf})
|
|
65
|
+
return records
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _proteins(path):
|
|
69
|
+
name=None; chunks=[]
|
|
70
|
+
with _open(path) as fh:
|
|
71
|
+
for line in fh:
|
|
72
|
+
s=line.strip()
|
|
73
|
+
if not s: continue
|
|
74
|
+
if s.startswith('>'):
|
|
75
|
+
if name is not None: yield name,''.join(chunks).upper()
|
|
76
|
+
name=s[1:].strip(); chunks=[]
|
|
77
|
+
if not name: raise ValueError('Empty protein FASTA header')
|
|
78
|
+
else:
|
|
79
|
+
if name is None: raise ValueError('Protein sequence before FASTA header')
|
|
80
|
+
s=s.replace('.','*') # gffread -y writes '.' for a stop codon
|
|
81
|
+
if not all(c.isalpha() or c=='*' for c in s): raise ValueError('Invalid protein sequence')
|
|
82
|
+
chunks.append(s)
|
|
83
|
+
if name is not None: yield name,''.join(chunks).upper()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _without_terminal_stop(sequence: str) -> str:
|
|
87
|
+
"""Ignore one conventional terminal marker, preserving additional stops."""
|
|
88
|
+
return sequence[:-1] if sequence.endswith('*') else sequence
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _translate(seq, table=1, expected=None):
|
|
92
|
+
"""Translate under NCBI code, including valid alternative start codons."""
|
|
93
|
+
if len(seq)%3:raise ValueError('CDS length is not a multiple of three')
|
|
94
|
+
translated=_without_terminal_stop(str(Seq(seq).translate(table=table)))
|
|
95
|
+
if expected and expected.startswith('M') and translated and translated[0]!='M':
|
|
96
|
+
start=seq[:3].upper()
|
|
97
|
+
if start in CodonTable.unambiguous_dna_by_id[table].start_codons:
|
|
98
|
+
translated='M'+translated[1:]
|
|
99
|
+
return translated
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def audit_annotation(fasta,gff,*,faa=None,cds=None):
|
|
104
|
+
reference={}
|
|
105
|
+
issues=[]
|
|
106
|
+
for name,seq in _contigs(fasta):
|
|
107
|
+
key=name.split()[0]
|
|
108
|
+
if key in reference:
|
|
109
|
+
issues.append({'severity':'error','code':'DUPLICATE_FASTA_ID','detail':key})
|
|
110
|
+
reference[key]=seq
|
|
111
|
+
records=parse_gff(gff)
|
|
112
|
+
ids=set()
|
|
113
|
+
parents_by_id=defaultdict(list)
|
|
114
|
+
for r in records:
|
|
115
|
+
seq=reference.get(r['seqid'])
|
|
116
|
+
if seq is None:
|
|
117
|
+
issues.append({'severity':'error','code':'UNKNOWN_CONTIG','line':r['line']})
|
|
118
|
+
if r['start']<1 or r['end']<r['start'] or (seq is not None and r['end']>len(seq)):
|
|
119
|
+
issues.append({'severity':'error','code':'INVALID_COORDINATES','line':r['line']})
|
|
120
|
+
if r['strand'] not in ('+','-','.','?'):
|
|
121
|
+
issues.append({'severity':'error','code':'INVALID_STRAND','line':r['line']})
|
|
122
|
+
if r['type']=='CDS' and r['phase'] not in ('0','1','2'):
|
|
123
|
+
issues.append({'severity':'error','code':'INVALID_CDS_PHASE','line':r['line']})
|
|
124
|
+
rid=r['attributes'].get('ID')
|
|
125
|
+
if rid:
|
|
126
|
+
ids.add(rid)
|
|
127
|
+
parents_by_id[rid].append(r)
|
|
128
|
+
for rid, group in parents_by_id.items():
|
|
129
|
+
if len(group)<2:
|
|
130
|
+
continue
|
|
131
|
+
# A repeated ID may describe one multipart CDS, never different features.
|
|
132
|
+
signatures={(r['type'],r['seqid'],r['strand'],tuple(sorted(r['parents'])),
|
|
133
|
+
r['attributes'].get('protein_id')) for r in group}
|
|
134
|
+
coordinates={(r['start'],r['end']) for r in group}
|
|
135
|
+
if (len(signatures)!=1 or group[0]['type']!='CDS'
|
|
136
|
+
or len(coordinates)!=len(group)):
|
|
137
|
+
for r in group:
|
|
138
|
+
issues.append({'severity':'error','code':'DUPLICATE_FEATURE_ID',
|
|
139
|
+
'line':r['line'],'detail':rid})
|
|
140
|
+
for r in records:
|
|
141
|
+
for parent in r['parents']:
|
|
142
|
+
if not parent:
|
|
143
|
+
continue
|
|
144
|
+
if parent not in ids:
|
|
145
|
+
issues.append({'severity':'error','code':'MISSING_PARENT','line':r['line'],'parent':parent})
|
|
146
|
+
continue
|
|
147
|
+
for pr in parents_by_id[parent]:
|
|
148
|
+
if pr['seqid'] != r['seqid']:
|
|
149
|
+
issues.append({'severity':'error','code':'PARENT_CONTIG_MISMATCH','line':r['line'],'parent':parent})
|
|
150
|
+
elif r['start'] < pr['start'] or r['end'] > pr['end']:
|
|
151
|
+
issues.append({'severity':'error','code':'CHILD_OUTSIDE_PARENT','line':r['line'],'parent':parent})
|
|
152
|
+
if pr['strand'] in ('+','-') and r['strand'] in ('+','-') and pr['strand'] != r['strand']:
|
|
153
|
+
issues.append({'severity':'error','code':'PARENT_STRAND_MISMATCH','line':r['line'],'parent':parent})
|
|
154
|
+
|
|
155
|
+
# Check GFF3 phase continuity across multipart CDS for each transcript.
|
|
156
|
+
cds_by_parent=defaultdict(list)
|
|
157
|
+
for r in records:
|
|
158
|
+
if r['type']=='CDS':
|
|
159
|
+
for parent in r['parents']:
|
|
160
|
+
if parent:cds_by_parent[parent].append(r)
|
|
161
|
+
for parent,segments in cds_by_parent.items():
|
|
162
|
+
if len(segments)<2 or len({r['seqid'] for r in segments})!=1 or len({r['strand'] for r in segments})!=1:
|
|
163
|
+
continue
|
|
164
|
+
strand=segments[0]['strand']
|
|
165
|
+
if strand not in ('+','-') or any(r['phase'] not in ('0','1','2') for r in segments):continue
|
|
166
|
+
ordered=sorted(segments,key=lambda r:r['start'],reverse=(strand=='-'))
|
|
167
|
+
translated_bases=(ordered[0]['end']-ordered[0]['start']+1)-int(ordered[0]['phase'])
|
|
168
|
+
for r in ordered[1:]:
|
|
169
|
+
expected=(3-(translated_bases%3))%3
|
|
170
|
+
if int(r['phase'])!=expected:
|
|
171
|
+
issues.append({'severity':'error','code':'INCONSISTENT_CDS_PHASE',
|
|
172
|
+
'line':r['line'],'parent':parent,'expected_phase':expected})
|
|
173
|
+
translated_bases+=r['end']-r['start']+1
|
|
174
|
+
|
|
175
|
+
invalid_lines={x['line'] for x in issues if x['severity']=='error' and 'line' in x}
|
|
176
|
+
proteins={'status':'not_evaluated','matched':0,'mismatched':0,'not_evaluable':0,'not_evaluable_reasons':{}}
|
|
177
|
+
if faa is not None:
|
|
178
|
+
proteins={'status':'evaluated','matched':0,'mismatched':0,'not_evaluable':0,'not_evaluable_reasons':{}}
|
|
179
|
+
reasons=defaultdict(int)
|
|
180
|
+
def skip(reason):
|
|
181
|
+
proteins['not_evaluable']+=1
|
|
182
|
+
reasons[reason]+=1
|
|
183
|
+
observed={}
|
|
184
|
+
for name,seq in _proteins(faa):
|
|
185
|
+
key=name.split()[0]
|
|
186
|
+
if key in observed:
|
|
187
|
+
raise ValueError(f'Duplicate protein FASTA identifier: {key}')
|
|
188
|
+
observed[key]=_without_terminal_stop(seq)
|
|
189
|
+
grouped=defaultdict(list)
|
|
190
|
+
unmapped_cds=set()
|
|
191
|
+
for r in records:
|
|
192
|
+
if r['type']=='CDS':
|
|
193
|
+
pid=r['attributes'].get('protein_id')
|
|
194
|
+
if pid:
|
|
195
|
+
grouped[pid].append(r)
|
|
196
|
+
else:
|
|
197
|
+
# Missing mappings are exclusions, not absent evidence. Count
|
|
198
|
+
# multipart features once by ID (or Parent when ID is absent).
|
|
199
|
+
rid=r['attributes'].get('ID')
|
|
200
|
+
if rid:
|
|
201
|
+
key=('id',rid)
|
|
202
|
+
elif r['parents']:
|
|
203
|
+
key=('parent',r['seqid'],r['strand'],tuple(sorted(r['parents'])))
|
|
204
|
+
else:
|
|
205
|
+
key=('line',r['line'])
|
|
206
|
+
unmapped_cds.add(key)
|
|
207
|
+
for _ in unmapped_cds:
|
|
208
|
+
skip('missing_protein_id')
|
|
209
|
+
proteins['unmatched_faa_ids']=sorted(set(observed)-set(grouped))
|
|
210
|
+
proteins['not_evaluable']+=len(proteins['unmatched_faa_ids'])
|
|
211
|
+
reasons['unmatched_faa_id']+=len(proteins['unmatched_faa_ids'])
|
|
212
|
+
if not grouped or proteins['unmatched_faa_ids']:
|
|
213
|
+
proteins['status']='not_evaluable' if not grouped else 'partially_evaluated'
|
|
214
|
+
for pid,segments in grouped.items():
|
|
215
|
+
if any(r['line'] in invalid_lines for r in segments):
|
|
216
|
+
skip('invalid_annotation');continue
|
|
217
|
+
if pid not in observed:
|
|
218
|
+
skip('missing_protein_in_faa');continue
|
|
219
|
+
if len({r['seqid'] for r in segments})!=1 or len({r['strand'] for r in segments})!=1:
|
|
220
|
+
skip('inconsistent_cds_segments');continue
|
|
221
|
+
strand=segments[0]['strand']
|
|
222
|
+
if strand not in ('+','-') or any(r['seqid'] not in reference or r['start']<1 or r['end']>len(reference[r['seqid']]) for r in segments):
|
|
223
|
+
skip('invalid_cds_coordinates');continue
|
|
224
|
+
ordered=sorted(segments,key=lambda r:r['start'],reverse=(strand=='-'))
|
|
225
|
+
attrs=[r['attributes'] for r in ordered]
|
|
226
|
+
if any('.' in a.get(k,'').split(',') for a in attrs for k in ('start_range','end_range')):
|
|
227
|
+
skip('partial_cds_range');continue
|
|
228
|
+
if any('pseudo' in a or 'transl_except' in a or 'exception' in a or a.get('partial')=='true' for a in attrs):
|
|
229
|
+
skip('translation_exception_or_pseudogene');continue
|
|
230
|
+
if ordered[0]['phase'] not in ('0','1','2'):
|
|
231
|
+
skip('invalid_phase');continue
|
|
232
|
+
if ordered[0]['phase']!='0':
|
|
233
|
+
skip('partial_initial_codon');continue
|
|
234
|
+
tables={a.get('transl_table','1') for a in attrs}
|
|
235
|
+
if len(tables)!=1:
|
|
236
|
+
skip('inconsistent_translation_table');continue
|
|
237
|
+
try:
|
|
238
|
+
table=int(next(iter(tables)))
|
|
239
|
+
CodonTable.unambiguous_dna_by_id[table]
|
|
240
|
+
except (KeyError,ValueError):
|
|
241
|
+
skip('unsupported_translation_table');continue
|
|
242
|
+
chunks=[]
|
|
243
|
+
for r in ordered:
|
|
244
|
+
fragment=reference[r['seqid']][r['start']-1:r['end']]
|
|
245
|
+
chunks.append(fragment if strand=='+' else fragment.translate(_TRANS)[::-1])
|
|
246
|
+
nt=''.join(chunks)[int(ordered[0]['phase']):].upper()
|
|
247
|
+
if len(nt)%3:
|
|
248
|
+
skip('partial_cds_frame');continue
|
|
249
|
+
if any(c not in 'ACGT' for c in nt):
|
|
250
|
+
skip('ambiguous_nucleotide');continue
|
|
251
|
+
try:
|
|
252
|
+
translated=_translate(nt,table=table,expected=observed[pid])
|
|
253
|
+
except (ValueError,KeyError):
|
|
254
|
+
skip('translation_failed');continue
|
|
255
|
+
if 'X' in translated or 'X' in observed[pid]:
|
|
256
|
+
skip('ambiguous_protein');continue
|
|
257
|
+
if translated==observed[pid]:
|
|
258
|
+
if '*' in translated:
|
|
259
|
+
skip('unexpected_internal_stop')
|
|
260
|
+
else:
|
|
261
|
+
proteins['matched']+=1
|
|
262
|
+
else:
|
|
263
|
+
proteins['mismatched']+=1
|
|
264
|
+
issues.append({'severity':'error','code':'PROTEIN_SEQUENCE_MISMATCH','protein_id':pid,
|
|
265
|
+
'translation_table':table})
|
|
266
|
+
proteins['not_evaluable_reasons']=dict(reasons)
|
|
267
|
+
if proteins['not_evaluable'] and proteins['status']=='evaluated':
|
|
268
|
+
proteins['status']='partially_evaluated'
|
|
269
|
+
cds_sequences={'status':'not_evaluated','matched':0,'mismatched':0,'not_evaluable':0}
|
|
270
|
+
if cds is not None:
|
|
271
|
+
cds_sequences={'status':'evaluated','matched':0,'mismatched':0,'not_evaluable':0}
|
|
272
|
+
given={}
|
|
273
|
+
for name,seq in _contigs(cds):
|
|
274
|
+
key=name.split()[0]
|
|
275
|
+
if key in given:
|
|
276
|
+
raise ValueError(f'Duplicate CDS FASTA identifier: {key}')
|
|
277
|
+
given[key]=seq
|
|
278
|
+
grouped_cds=defaultdict(list)
|
|
279
|
+
for r in records:
|
|
280
|
+
if r['type']=='CDS':
|
|
281
|
+
for parent in r['parents']:
|
|
282
|
+
if parent:grouped_cds[parent].append(r)
|
|
283
|
+
for transcript,segments in grouped_cds.items():
|
|
284
|
+
if any(r['line'] in invalid_lines for r in segments):
|
|
285
|
+
cds_sequences['not_evaluable']+=1;continue
|
|
286
|
+
if transcript not in given:
|
|
287
|
+
cds_sequences['not_evaluable']+=1;continue
|
|
288
|
+
if len({r['seqid'] for r in segments})!=1 or len({r['strand'] for r in segments})!=1:
|
|
289
|
+
cds_sequences['not_evaluable']+=1;continue
|
|
290
|
+
strand=segments[0]['strand']
|
|
291
|
+
if strand not in ('+','-') or any(r['seqid'] not in reference or r['start']<1 or r['end']>len(reference[r['seqid']]) for r in segments):
|
|
292
|
+
cds_sequences['not_evaluable']+=1;continue
|
|
293
|
+
ordered=sorted(segments,key=lambda r:r['start'],reverse=(strand=='-'))
|
|
294
|
+
pieces=[]
|
|
295
|
+
for r in ordered:
|
|
296
|
+
nt=reference[r['seqid']][r['start']-1:r['end']]
|
|
297
|
+
pieces.append(nt if strand=='+' else nt.translate(_TRANS)[::-1])
|
|
298
|
+
observed=''.join(pieces)
|
|
299
|
+
if observed==given[transcript]:
|
|
300
|
+
cds_sequences['matched']+=1
|
|
301
|
+
else:
|
|
302
|
+
cds_sequences['mismatched']+=1
|
|
303
|
+
issues.append({'severity':'error','code':'CDS_SEQUENCE_MISMATCH','transcript_id':transcript})
|
|
304
|
+
return {'features':len(records),'errors':sum(x['severity']=='error' for x in issues),
|
|
305
|
+
'warnings':sum(x['severity']=='warning' for x in issues),
|
|
306
|
+
'issues':issues,'proteins':proteins,'cds_sequences':cds_sequences,
|
|
307
|
+
'limitations':'FAA concordance requires protein_id mapping, supported NCBI transl_table and unambiguous complete CDS. Special translation exceptions, pseudo/partial CDS and uncertain models are explicitly not evaluated. Initiator methionine is accepted only for valid alternative starts. CDS FASTA concordance requires exact transcript Parent IDs.'}
|