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.
@@ -0,0 +1,221 @@
1
+ """Conservative polishing change identification, with explicit alignment requirements."""
2
+ from collections import defaultdict
3
+ import hashlib
4
+ import re
5
+ from .core import _contigs, _open, _TRANS
6
+ from .annotation import parse_gff
7
+
8
+ _CS = re.compile(r':\d+|=[A-Za-z]+|\*[A-Za-z][A-Za-z]|\+[A-Za-z]+|-[A-Za-z]+|~[A-Za-z]{2}\d+[A-Za-z]{2}')
9
+
10
+
11
+ def _unique_records(path):
12
+ result={}
13
+ for name,seq in _contigs(path):
14
+ key=name.split()[0]
15
+ if key in result:
16
+ raise ValueError(f'Duplicate FASTA identifier {key!r}: coordinate-based comparisons are ambiguous')
17
+ result[key]=seq
18
+ if not result:
19
+ raise ValueError(f'No FASTA records: {path}')
20
+ return result
21
+
22
+
23
+ def _fingerprint(seq):
24
+ seq=seq.upper()
25
+ rc=seq.translate(_TRANS)[::-1]
26
+ return min(hashlib.sha256(seq.encode()).hexdigest(),hashlib.sha256(rc.encode()).hexdigest())
27
+
28
+
29
+ def compare_changes(before,after,*,max_variants=1000000,assume_collinear=False):
30
+ """Reconcile exact content globally before interpreting coordinate differences."""
31
+ a,b=_unique_records(before),_unique_records(after)
32
+ groups_a=defaultdict(list);groups_b=defaultdict(list)
33
+ for name,seq in a.items():groups_a[_fingerprint(seq)].append(name)
34
+ for name,seq in b.items():groups_b[_fingerprint(seq)].append(name)
35
+ matched_a=set();matched_b=set();pairs=[];ambiguous=[];unchanged=0
36
+ for fp in sorted(groups_a.keys() & groups_b.keys()):
37
+ aa=sorted(groups_a[fp]);bb=sorted(groups_b[fp]);unchanged+=min(len(aa),len(bb))
38
+ if len(aa)==len(bb)==1:
39
+ old,new=aa[0],bb[0];matched_a.add(old);matched_b.add(new)
40
+ rc=a[old].translate(_TRANS)[::-1]
41
+ orientation=('ambiguous_palindrome' if a[old]==b[new]==rc else
42
+ '+' if a[old]==b[new] else '-' if rc==b[new] else 'unknown')
43
+ pairs.append({'before':old,'after':new,'orientation':orientation,'length':len(a[old]),'renamed':old!=new})
44
+ else:
45
+ ambiguous.append({'before':aa,'after':bb,'matched_count':min(len(aa),len(bb)),
46
+ 'reason':'duplicate_or_imbalanced_exact_sequences'})
47
+ count=min(len(aa),len(bb))
48
+ matched_a.update(aa[:count]);matched_b.update(bb[:count])
49
+ # No unique identifier crosswalk is reported for ambiguous duplicates.
50
+ variants=[];unresolved=[]
51
+ shared=(set(a)-matched_a)&(set(b)-matched_b)
52
+ for name in sorted(shared):
53
+ old,new=a[name],b[name]
54
+ if old==new or new==old.translate(_TRANS)[::-1]:
55
+ unresolved.append({'contig':name,'reason':'ambiguous_duplicate_content'});continue
56
+ if len(old)!=len(new):
57
+ unresolved.append({'contig':name,'reason':'requires_alignment','length_before':len(old),'length_after':len(new)});continue
58
+ mismatch_count=sum(x!=y for x,y in zip(old,new))
59
+ if mismatch_count>1 and not assume_collinear:
60
+ unresolved.append({'contig':name,'reason':'requires_alignment_for_multiple_differences',
61
+ 'positional_mismatches':mismatch_count});continue
62
+ if mismatch_count>max_variants-len(variants):raise ValueError('Maximum variant limit exceeded')
63
+ for i,(x,y) in enumerate(zip(old,new),1):
64
+ if x!=y:
65
+ variants.append({'contig':name,'ref_pos':i,'ref':x,'alt':y,'type':'SNV',
66
+ 'source':'same_length_same_name_direct_comparison',
67
+ 'coordinate_assumption':('collinearity_assumed_by_user' if assume_collinear else 'single_positional_difference')})
68
+ for pair in pairs:
69
+ if pair['before']==pair['after'] and pair['orientation']=='-':
70
+ unresolved.append({'contig':pair['before'],'reason':'orientation_changed'})
71
+ ua=sorted(set(a)-matched_a-shared);ub=sorted(set(b)-matched_b-shared)
72
+ unresolved.extend({'contig':x,'reason':'unmatched_before_requires_alignment'} for x in ua)
73
+ unresolved.extend({'contig':x,'reason':'unmatched_after_requires_alignment'} for x in ub)
74
+ return {'variants':variants,'unresolved':unresolved,'unchanged_contigs':unchanged,
75
+ 'exact_sequence_pairs':pairs,'ambiguous_exact_groups':ambiguous,
76
+ 'renamed_exact_pairs':sum(x['renamed'] for x in pairs),
77
+ 'unmatched_before_count':len(ua),'unmatched_after_count':len(ub),
78
+ 'limitations':'Exact-content mapping is orientation-invariant and duplicate-aware. '
79
+ 'Unmatched contigs require alignment; direct positional calls do not prove mechanism. '
80
+ 'Assume-collinear may be misleading when compensating indels occur.'}
81
+
82
+
83
+ def parse_cs_paf(path,*,min_mapq=20,max_variants=1000000,before=None,after=None):
84
+ """Parse minimap2 PAF cs tag. Target is the reference (before assembly)."""
85
+ if (before is None)!=(after is None):
86
+ raise ValueError('Both before and after FASTA are required for cs verification')
87
+ reference=_unique_records(before) if before is not None else None
88
+ queries=_unique_records(after) if after is not None else None
89
+ variants=[]; unresolved=[]; hits=defaultdict(list)
90
+ with _open(path) as fh:
91
+ for line_no,line in enumerate(fh,1):
92
+ if not line.strip() or line.startswith('#'): continue
93
+ p=line.rstrip('\n').split('\t')
94
+ if len(p)<12: raise ValueError(f'PAF line {line_no}: fewer than 12 columns')
95
+ try:
96
+ qname=p[0]; strand=p[4]; target=p[5]; tstart=int(p[7]); tend=int(p[8]); mapq=int(p[11]); tlen=int(p[6]); qlen=int(p[1]); qstart=int(p[2]); qend=int(p[3])
97
+ except (ValueError,IndexError) as e:
98
+ raise ValueError(f'PAF line {line_no}: invalid coordinates') from e
99
+ if strand not in ('+','-') or not (0<=tstart<=tend<=tlen) or not (0<=qstart<=qend<=qlen):
100
+ raise ValueError(f'PAF line {line_no}: invalid alignment interval')
101
+ tags={x[:2]:x[5:] for x in p[12:] if len(x)>=5 and x[2]==':' and x[4]==':'}
102
+ if tags.get('tp')=='S' or mapq<min_mapq or mapq==255:
103
+ unresolved.append({'line':line_no,'reason':'secondary_or_low_mapq'});continue
104
+ cs=tags.get('cs')
105
+ if not cs:
106
+ unresolved.append({'line':line_no,'reason':'missing_cs_tag'});continue
107
+ hits[qname].append((line_no,target,tstart,tend,cs,strand,qstart,qend,qlen,tlen))
108
+ for query,alignments in hits.items():
109
+ if len(alignments)!=1:
110
+ unresolved.append({'query':query,'reason':'ambiguous_multiple_alignments','count':len(alignments)})
111
+ continue
112
+ line_no,target,tstart,tend,cs,strand,qstart,qend,qlen,tlen=alignments[0]
113
+ tokens=_CS.findall(cs)
114
+ if ''.join(tokens)!=cs:
115
+ unresolved.append({'line':line_no,'reason':'unsupported_cs_syntax'})
116
+ continue
117
+ if reference is not None:
118
+ if target not in reference or query not in queries:
119
+ unresolved.append({'line':line_no,'reason':'reference_or_query_contig_missing'});continue
120
+ if len(reference[target])!=tlen or len(queries[query])!=qlen:
121
+ unresolved.append({'line':line_no,'reason':'paf_contig_length_mismatch'});continue
122
+ target_seq=reference[target][tstart:tend].upper()
123
+ query_seq=queries[query][qstart:qend].upper()
124
+ if strand=='-':query_seq=query_seq.translate(_TRANS)[::-1]
125
+ ti=qi=0;valid=True
126
+ for tok in tokens:
127
+ op=tok[0]
128
+ if op==':':
129
+ n=int(tok[1:]);t=target_seq[ti:ti+n];q=query_seq[qi:qi+n]
130
+ if len(t)!=n or t!=q:valid=False;break
131
+ ti+=n;qi+=n
132
+ elif op=='=':
133
+ n=len(tok)-1;val=tok[1:].upper()
134
+ if target_seq[ti:ti+n]!=val or query_seq[qi:qi+n]!=val:valid=False;break
135
+ ti+=n;qi+=n
136
+ elif op=='*':
137
+ if target_seq[ti:ti+1]!=tok[1].upper() or query_seq[qi:qi+1]!=tok[2].upper():valid=False;break
138
+ ti+=1;qi+=1
139
+ elif op=='+':
140
+ n=len(tok)-1
141
+ if query_seq[qi:qi+n]!=tok[1:].upper():valid=False;break
142
+ qi+=n
143
+ elif op=='-':
144
+ n=len(tok)-1
145
+ if target_seq[ti:ti+n]!=tok[1:].upper():valid=False;break
146
+ ti+=n
147
+ else:valid=False;break
148
+ if not valid or ti!=len(target_seq) or qi!=len(query_seq):
149
+ unresolved.append({'line':line_no,'reason':'cs_sequence_mismatch'});continue
150
+ pos=tstart+1
151
+ query_consumed=0
152
+ for token in tokens:
153
+ op=token[0]
154
+ if op==':': pos+=int(token[1:]);query_consumed+=int(token[1:])
155
+ elif op=='=': pos+=len(token)-1;query_consumed+=len(token)-1
156
+ elif op=='*':
157
+ variants.append({'contig':target,'ref_pos':pos,'ref':token[1].upper(),
158
+ 'alt':token[2].upper(),'type':'SNV','source':'paf_cs','query':query,'orientation':strand,
159
+ 'sequence_verification':'both_fastas' if reference is not None else 'not_evaluated'})
160
+ pos+=1;query_consumed+=1
161
+ elif op=='+':
162
+ query_consumed+=len(token)-1
163
+ variants.append({'contig':target,'ref_pos':pos-1,'ref':'','alt':token[1:].upper(),
164
+ 'type':'INS','source':'paf_cs','query':query,
165
+ 'coordinate_convention':'insertion_after_ref_pos; 0 denotes before first base',
166
+ 'orientation':strand,'sequence_verification':'both_fastas' if reference is not None else 'not_evaluated'})
167
+ elif op=='-':
168
+ variants.append({'contig':target,'ref_pos':pos,'ref':token[1:].upper(),
169
+ 'alt':'','type':'DEL','source':'paf_cs','query':query,'orientation':strand,
170
+ 'sequence_verification':'both_fastas' if reference is not None else 'not_evaluated'})
171
+ pos+=len(token)-1
172
+ else:
173
+ unresolved.append({'line':line_no,'reason':'intron_cs_not_supported'})
174
+ break
175
+ if len(variants)>max_variants: raise ValueError('Maximum variant limit exceeded')
176
+ if pos-1!=tend or query_consumed!=qend-qstart:
177
+ if pos-1!=tend:
178
+ unresolved.append({'line':line_no,'reason':'cs_target_span_mismatch','parsed_end':pos-1,'paf_end':tend})
179
+ if query_consumed!=qend-qstart:
180
+ unresolved.append({'line':line_no,'reason':'cs_query_span_mismatch',
181
+ 'parsed_query_bases':query_consumed,'paf_query_bases':qend-qstart})
182
+ variants=[v for v in variants if not (v.get('source')=='paf_cs' and v.get('query')==query)]
183
+ # Indel placement in tandem repeats/homopolymers is often non-unique.
184
+ # This local single-base shift screen does NOT establish global uniqueness.
185
+ for v in variants:
186
+ if v['type'] not in ('INS','DEL'):
187
+ continue
188
+ v['placement_ambiguity']='not_assessed_without_reference'
189
+ if reference is None or v['contig'] not in reference:
190
+ continue
191
+ seq=reference[v['contig']].upper()
192
+ p=v['ref_pos']
193
+ if v['type']=='INS':
194
+ inserted=v['alt']
195
+ shift_left=(p>0 and seq[p-1]==inserted[-1])
196
+ shift_right=(p<len(seq) and seq[p]==inserted[0])
197
+ else:
198
+ deleted=v['ref'];start=p-1;end=start+len(deleted)
199
+ shift_left=(start>0 and seq[start-1]==deleted[-1])
200
+ shift_right=(end<len(seq) and seq[end]==deleted[0])
201
+ v['placement_ambiguity']='repeat_context' if shift_left or shift_right else 'no_single_base_shift_detected'
202
+ return {'variants':variants,'unresolved':unresolved,
203
+ 'sequence_validation':'both_fastas' if reference is not None else 'not_evaluated',
204
+ 'limitations':'Single primary, sufficient-MAPQ alignments only; when FASTAs are supplied, cs spans are checked against both sequences. Indel placement_ambiguity is a local shift screen, not a proof of uniqueness or biological correctness.'}
205
+
206
+
207
+ def annotate_change_impact(variants,gff):
208
+ cds=defaultdict(list)
209
+ for r in parse_gff(gff):
210
+ if r['type']=='CDS': cds[r['seqid']].append(r)
211
+ out=[]
212
+ for v in variants:
213
+ pos=v['ref_pos']; end=pos+len(v['ref'])-1 if v['type']=='DEL' else pos
214
+ overlap=[r for r in cds[v['contig']] if r['start']<=end and r['end']>=pos]
215
+ if not overlap: effect='no_CDS_overlap_detected'
216
+ elif v['type']=='SNV': effect='CDS_overlap_SNV_effect_unknown'
217
+ elif v['type'] in ('INS','DEL'):
218
+ effect='possible_frameshift' if (len(v['alt'])-len(v['ref']))%3 else 'possible_inframe_indel'
219
+ else: effect='not_evaluated'
220
+ out.append({**v,'coding_context':effect,'overlapping_CDS':len(overlap)})
221
+ return {'variants':out,'limitations':'Coordinates refer to the before/reference assembly; CDS overlap is not a validated transcript-specific functional consequence.'}