yallhap 0.4.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.
yallhap/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """
2
+ yallHap: Modern Y-chromosome haplogroup inference.
3
+
4
+ A pipeline-friendly tool for Y-chromosome haplogroup classification
5
+ supporting modern and ancient DNA with probabilistic confidence scoring.
6
+ """
7
+
8
+ __version__ = "0.4.0"
9
+
10
+ from yallhap.classifier import HaplogroupCall, classify
11
+ from yallhap.tree import Node, Tree
12
+
13
+ __all__ = ["Tree", "Node", "classify", "HaplogroupCall", "__version__"]
yallhap/ancient.py ADDED
@@ -0,0 +1,295 @@
1
+ """
2
+ Ancient DNA damage filtering for Y-chromosome haplogroup inference.
3
+
4
+ Implements filters for post-mortem DNA damage patterns commonly seen in
5
+ ancient DNA samples, including cytosine deamination (C>T and G>A transitions).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from enum import Enum
12
+ from typing import TYPE_CHECKING, Literal
13
+
14
+ if TYPE_CHECKING:
15
+ from yallhap.vcf import Variant
16
+
17
+
18
+ class MutationType(Enum):
19
+ """Classification of mutation types."""
20
+
21
+ TRANSITION = "transition" # Purine<->Purine or Pyrimidine<->Pyrimidine
22
+ TRANSVERSION = "transversion" # Purine<->Pyrimidine
23
+
24
+
25
+ # Transition pairs (within-class mutations)
26
+ TRANSITIONS = frozenset(
27
+ [
28
+ ("A", "G"),
29
+ ("G", "A"), # Purine <-> Purine
30
+ ("C", "T"),
31
+ ("T", "C"), # Pyrimidine <-> Pyrimidine
32
+ ]
33
+ )
34
+
35
+ # Transversion pairs (between-class mutations)
36
+ TRANSVERSIONS = frozenset(
37
+ [
38
+ ("A", "C"),
39
+ ("C", "A"),
40
+ ("A", "T"),
41
+ ("T", "A"),
42
+ ("G", "C"),
43
+ ("C", "G"),
44
+ ("G", "T"),
45
+ ("T", "G"),
46
+ ]
47
+ )
48
+
49
+
50
+ def get_mutation_type(ref: str, alt: str) -> MutationType | None:
51
+ """
52
+ Determine if a mutation is a transition or transversion.
53
+
54
+ Args:
55
+ ref: Reference allele (single nucleotide)
56
+ alt: Alternate allele (single nucleotide)
57
+
58
+ Returns:
59
+ MutationType.TRANSITION, MutationType.TRANSVERSION, or None if invalid
60
+ """
61
+ ref = ref.upper()
62
+ alt = alt.upper()
63
+
64
+ if (ref, alt) in TRANSITIONS:
65
+ return MutationType.TRANSITION
66
+ elif (ref, alt) in TRANSVERSIONS:
67
+ return MutationType.TRANSVERSION
68
+ return None
69
+
70
+
71
+ def is_transversion(ref: str, alt: str) -> bool:
72
+ """Check if mutation is a transversion (not affected by deamination damage)."""
73
+ return get_mutation_type(ref, alt) == MutationType.TRANSVERSION
74
+
75
+
76
+ def is_transition(ref: str, alt: str) -> bool:
77
+ """Check if mutation is a transition (potentially affected by deamination)."""
78
+ return get_mutation_type(ref, alt) == MutationType.TRANSITION
79
+
80
+
81
+ @dataclass
82
+ class DamagePattern:
83
+ """
84
+ A specific DNA damage pattern to filter.
85
+
86
+ Attributes:
87
+ ancestral: The ancestral (undamaged) allele
88
+ derived: The derived (damaged) allele that mimics a real mutation
89
+ description: Human-readable description of the damage
90
+ """
91
+
92
+ ancestral: str
93
+ derived: str
94
+ description: str
95
+
96
+ def matches(self, ref: str, alt: str) -> bool:
97
+ """Check if a mutation matches this damage pattern."""
98
+ return ref.upper() == self.ancestral and alt.upper() == self.derived
99
+
100
+
101
+ # Standard ancient DNA damage patterns
102
+ # C>T: Cytosine deamination on + strand
103
+ # G>A: Cytosine deamination on - strand (reverse complement)
104
+ DEAMINATION_DAMAGE = [
105
+ DamagePattern("C", "T", "C>T deamination (5' end bias)"),
106
+ DamagePattern("G", "A", "G>A deamination (3' end bias)"),
107
+ ]
108
+
109
+
110
+ class DamageFilter:
111
+ """
112
+ Filter for ancient DNA damage patterns.
113
+
114
+ Filters out variants that match known post-mortem damage signatures,
115
+ particularly cytosine deamination which causes C>T and G>A transitions.
116
+ """
117
+
118
+ def __init__(
119
+ self,
120
+ damage_patterns: list[DamagePattern] | None = None,
121
+ strict: bool = False,
122
+ ):
123
+ """
124
+ Initialize damage filter.
125
+
126
+ Args:
127
+ damage_patterns: List of damage patterns to filter.
128
+ Defaults to standard deamination patterns.
129
+ strict: If True, filter all transitions (not just deamination).
130
+ """
131
+ self.damage_patterns = damage_patterns or DEAMINATION_DAMAGE
132
+ self.strict = strict
133
+
134
+ def is_damage_like(
135
+ self,
136
+ ref: str,
137
+ alt: str,
138
+ ancestral: str | None = None,
139
+ derived: str | None = None,
140
+ ) -> bool:
141
+ """
142
+ Check if a variant looks like ancient DNA damage.
143
+
144
+ For haplogroup classification, we care about whether the called
145
+ derived allele could be damage rather than a real mutation.
146
+
147
+ Args:
148
+ ref: Reference allele
149
+ alt: Alternate allele (the called variant)
150
+ ancestral: Expected ancestral allele for the SNP (optional)
151
+ derived: Expected derived allele for the SNP (optional)
152
+
153
+ Returns:
154
+ True if the variant could be damage and should be filtered
155
+ """
156
+ # In strict mode, filter all transitions
157
+ if self.strict:
158
+ return is_transition(ref, alt)
159
+
160
+ # Check against known damage patterns
161
+ for pattern in self.damage_patterns:
162
+ # Check if the mutation matches a damage pattern
163
+ if pattern.matches(ref, alt):
164
+ return True
165
+
166
+ # If we know the SNP's expected alleles, check if damage
167
+ # could explain an apparent derived call
168
+ # Damage is when: ancestral allele gets damaged to look like derived
169
+ if (
170
+ ancestral
171
+ and derived
172
+ and pattern.ancestral == ancestral.upper()
173
+ and pattern.derived == derived.upper()
174
+ ):
175
+ return True
176
+
177
+ return False
178
+
179
+ def filter_variants(
180
+ self,
181
+ variants: dict[int, Variant], # Forward reference to avoid circular import
182
+ ) -> tuple[dict[int, Variant], int]:
183
+ """
184
+ Filter variants that look like damage.
185
+
186
+ Args:
187
+ variants: Dictionary of position -> Variant
188
+
189
+ Returns:
190
+ Tuple of (filtered variants dict, number filtered)
191
+ """
192
+ filtered: dict[int, Variant] = {}
193
+ count_filtered = 0
194
+
195
+ for pos, variant in variants.items():
196
+ if self.is_damage_like(variant.ref, variant.alt[0] if variant.alt else ""):
197
+ count_filtered += 1
198
+ else:
199
+ filtered[pos] = variant
200
+
201
+ return filtered, count_filtered
202
+
203
+
204
+ class TransversionOnlyFilter:
205
+ """
206
+ Filter that only allows transversion mutations.
207
+
208
+ Transversions are not affected by cytosine deamination and are thus
209
+ more reliable for ancient DNA haplogroup calling, though at the cost
210
+ of reduced resolution (fewer informative SNPs).
211
+ """
212
+
213
+ def is_allowed(self, ref: str, alt: str) -> bool:
214
+ """Check if mutation is a transversion (allowed)."""
215
+ return is_transversion(ref, alt)
216
+
217
+ def filter_variants(
218
+ self,
219
+ variants: dict[int, Variant],
220
+ ) -> tuple[dict[int, Variant], int]:
221
+ """
222
+ Filter variants to only keep transversions.
223
+
224
+ Args:
225
+ variants: Dictionary of position -> Variant
226
+
227
+ Returns:
228
+ Tuple of (filtered variants dict, number filtered)
229
+ """
230
+ filtered: dict[int, Variant] = {}
231
+ count_filtered = 0
232
+
233
+ for pos, variant in variants.items():
234
+ alt = variant.alt[0] if variant.alt else ""
235
+ if self.is_allowed(variant.ref, alt):
236
+ filtered[pos] = variant
237
+ else:
238
+ count_filtered += 1
239
+
240
+ return filtered, count_filtered
241
+
242
+
243
+ # Type alias for damage rescaling mode
244
+ DamageRescaleMode = Literal["none", "moderate", "aggressive"]
245
+
246
+
247
+ def apply_damage_rescale(
248
+ quality: float | int,
249
+ ref: str,
250
+ alt: str,
251
+ mode: DamageRescaleMode = "moderate",
252
+ ) -> float:
253
+ """
254
+ Rescale quality scores for potentially damaged variants.
255
+
256
+ Applies a penalty to quality scores for transitions that could be damage.
257
+ Transversions are not penalized.
258
+
259
+ Args:
260
+ quality: Original quality score
261
+ ref: Reference allele
262
+ alt: Alternate allele
263
+ mode: Rescaling aggressiveness
264
+ - "none": No rescaling
265
+ - "moderate": 50% penalty for C>T/G>A, 25% for other transitions
266
+ - "aggressive": 75% penalty for C>T/G>A, 50% for other transitions
267
+
268
+ Returns:
269
+ Rescaled quality score
270
+ """
271
+ if mode == "none":
272
+ return float(quality)
273
+
274
+ # Transversions are not affected by damage
275
+ if is_transversion(ref, alt):
276
+ return float(quality)
277
+
278
+ # Define penalties based on mode
279
+ if mode == "moderate":
280
+ ct_ga_penalty = 0.5 # C>T and G>A get 50% penalty
281
+ other_transition_penalty = 0.25
282
+ else: # aggressive
283
+ ct_ga_penalty = 0.75
284
+ other_transition_penalty = 0.5
285
+
286
+ # Apply appropriate penalty
287
+ ref = ref.upper()
288
+ alt = alt.upper()
289
+
290
+ if (ref == "C" and alt == "T") or (ref == "G" and alt == "A"):
291
+ return float(quality) * (1 - ct_ga_penalty)
292
+ elif is_transition(ref, alt):
293
+ return float(quality) * (1 - other_transition_penalty)
294
+
295
+ return float(quality)