Algorithmcore
Variant normalization
Also called left alignment of indels, indel normalization.
Write each variant in a unique form, parsimonious and left-aligned, so that the same indel in a repeat gets the same representation.
- Time
- O(k L (s + L)) worst · averageΘ(k L) best
- Space
- O(k L) extra
- Where
- L = the length of the longest allele; k = the number of alleles; s = the number of positions the variant moves left
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Adrian Tan, Goncalo R. Abecasis, Hyun Min Kang, 2015
Variant normalization rewrites a variant record into one standard form, so that two records that describe the same change to the genome look the same. The problem comes from repeats: deleting one copy of CA from CACACA gives the same sequence whichever copy is deleted, so a caller can write the deletion at any of several positions, and it can also add extra reference bases on either side. Tan, Abecasis and Kang (2015) defined the normalized form as the one that is parsimonious (no base is shared by all alleles at either end, beyond one padding base) and left-aligned (it cannot move further left), and showed that it is unique. Tools such as vt normalize and bcftools norm compute it before call sets are merged or compared.
In plain words
A change to a word can often be written in more than one way. If "banana" loses one "an", you cannot tell which "an" went, because all choices give "bana". You can also write the change with more letters around it than you need.
To make every writer agree, choose one rule. First cut off letters at the end that all versions share. If a version becomes empty, step one letter left and add the letter there to all versions. Repeat until nothing changes. Then cut off letters at the start that all versions share, but always keep at least one letter. The result is the shortest way to write the change, placed as far left as it can go.
The problem
Positions are 1-based, as in VCF; the code indexes strings from 0. A variant is a position and alleles , where is the reference allele, equal to the reference bases from position , and are the alternate alleles. All alleles are non-empty and pairwise different. Allele gives the haplotype , the reference with at replaced by .
Two variants are equivalent if they give the same haplotypes in the same order. A variant is
- left-aligned if no equivalent variant has a smaller position and alleles of the same lengths;
- parsimonious if no equivalent variant has shorter alleles, that is, the alleles do not all end with the same base, and they do not all start with the same base unless one of them has length 1.
Output. The unique equivalent variant that is both left-aligned and parsimonious.
The algorithm
NORMALIZE(R, p, x_0, ..., x_k)changed ← true- 1
while changed do - 2
changed ← false - 3
if all alleles end with the same base then remove it from each; changed ← true - 4
if some allele is empty then - 5
p ← p - 1; put R[p] in front of each allele; changed ← true - 6
while all alleles start with the same base and every allele has length at least 2 do - 7
remove the first base of each allele; p ← p + 1 - 8
return (p, x_0, ..., x_k)
Line L5 needs a base to the left. If the variant would have to move before position 1, the code stops with an error, where VCF would pad with the base after the event instead; the code leaves that case out. The first loop moves the event left one base at a time, rotating the alleles through the repeat; the second loop removes shared bases at the left end that the first loop could not see.
Example
Take the reference GTCACACAGT and a haplotype GTCACAGT that lacks one copy of CA. Among the records that describe it are (6, ACA, A), (4, ACA, A), (3, CAC, C), (5, CACAG, CAG) and (2, TCA, T); there are 34 in all with non-empty alleles. Start from (6, ACA, A):
| round | after L3 | after L5 |
|---|---|---|
| 1 | (6, AC, empty) |
(5, CAC, C) |
| 2 | (5, CA, empty) |
(4, ACA, A) |
| 3 | (4, AC, empty) |
(3, CAC, C) |
| 4 | (3, CA, empty) |
(2, TCA, T) |
| 5 | no change, since A and T differ |
no change |
The second loop does nothing, because T has length 1. The result is (2, TCA, T): the deletion of CA after the T at position 2. Every one of the 34 records normalizes to it.
An SNV written with extra bases, (3, CAC, CGC), loses the shared C at the end in line L3 and the shared C at the start in line L7, which gives (4, A, G).
Correctness
Every equivalent variant is fixed by how many bases of the common prefix of the haplotypes it leaves on the left and how many of the common suffix it leaves on the right. Each step of the first loop keeps the haplotypes the same and either trims a base of the common suffix into the right flank or shifts the event one base left. That loop ends when the alleles no longer share a last base and none is empty, which happens exactly when the whole common suffix is in the right flank. The second loop then moves as much of the common prefix into the left flank as it can while every allele keeps at least one base. Both counts are then determined by the haplotypes alone, so the result is the same for every equivalent input, and it is both parsimonious and left-aligned. The full proof is in proofs/correctness.md. It assumes that no haplotype is a suffix of all the others; otherwise the event would slide to position 1.
Proof: Normalization returns the unique left-aligned and parsimonious formfull
Strings are indexed from 0 in this proof, and the variant position is 1-based as in VCF, so the alleles start at index of the reference. Let be the reference and let a variant be with , the reference allele, and all alleles non-empty and pairwise different. Allele gives the haplotype
so . Two variants are equivalent when they give the same haplotypes in the same order.
Write for the length of the longest common prefix of , for the length of their longest common suffix, and . The haplotypes are pairwise different, since the alleles are.
Hypothesis. , that is, no haplotype is a suffix of all the others. If a haplotype is such a suffix, the event can slide to the start of the reference, and VCF then pads the alleles with the base after the event instead of the base before. The code raises an error in that case.
Representations as pairs of numbers
Lemma 1. The variants equivalent to a given one are in one-to-one correspondence with the pairs of integers such that
The pair stands for the variant at index with alleles . Its total allele length is .
Proof. Take an equivalent variant at index whose reference allele ends bases before the end of . Then each is , so is a common prefix and a common suffix of all the haplotypes, which gives and . Each is non-empty, so for every , that is . The alleles are fixed by and , since is what is left of after the prefix and the suffix.
Conversely, take a pair in the region. The prefix of length and the suffix of length are common to all the haplotypes, and since they do not overlap inside any . So the strings are non-empty, matches the reference at index , and replacing by gives . The are pairwise different, because would give . The length formula follows from .
The normalized form
Following Tan, Abecasis and Kang (2015), a variant is parsimonious when no equivalent variant has a smaller total allele length, and left-aligned when it cannot move one base to the left with all allele lengths kept the same. It is normalized when it is both.
Lemma 2. The normalized form is the unique pair with
Proof. By Lemma 1 a parsimonious variant maximizes over the region. The largest value is : it is an upper bound by the three constraints, and the pair reaches it. This pair is in the region because .
Moving one base to the left with the lengths kept is the move from to . On the line it is possible exactly when and . So a pair on that line is left-aligned exactly when or . If , then ; if also , then , which is impossible since . So in both cases and .
The algorithm reaches the normalized form
Phase 1 is the loop of lines L1 to L5, and phase 2 is the loop of lines L6 and L7. During phase 1 an allele may be empty for a moment. Extend the notation: the state is the index and the alleles , and we track , the number of reference bases after the reference allele.
Invariant. At the start of each round of phase 1, and after phase 1, every equals , with and .
Proof. It holds at the start, for the input variant, by the definition of and the argument of Lemma 1. Line L3 removes the last base of every allele when they all end with the same base. The haplotypes do not change, grows by 1, and the new suffix of length is common to all , so still holds. Line L5 moves the index one base left and puts in front of every allele. The haplotypes do not change, drops by 1, and stays the same.
At the start of each round every allele is non-empty: this holds for the input, and an allele that line L3 empties gets one base back from line L5 in the same round. So line L3 always has a last base to compare.
Termination of phase 1. Each round that changes something either raises by 1 or lowers by 1, so the number , which is at least 0 by the invariant, drops by at least 1 in each such round. So phase 1 stops after at most changes, where is the input index.
No error under the hypothesis. Line L5 raises an error only if an allele is empty while . Then is a common suffix of all the haplotypes, so , which the hypothesis excludes.
Lemma 3. When phase 1 stops, and every allele is non-empty.
Proof. Phase 1 stops when a full round changes nothing: no allele is empty, and the alleles do not all end with the same base. The last base of is . So the haplotypes have a common suffix of length but not of length , and .
Lemma 4. Phase 2 stops with and .
Proof. Phase 2 moves the index right by one while all alleles start with the same base and all have length at least 2. It does not change or the haplotypes. At the start of phase 2, by the invariant, and because every allele is non-empty, so starts at most at .
While , the step applies. The first base of is , and means these bases are all equal. The length of is since . After the step, is still at most .
When , the step does not apply. If , the bases exist since , and they are not all equal, by the definition of . If , some haplotype has , and its allele has length .
Theorem. If no haplotype is a suffix of all the others, normalize returns the normalized form of the variant, and this form depends only on the reference and the haplotypes. So all equivalent variants give the same output.
Proof. By Lemmas 3 and 4 the output is the pair , which is the normalized form by Lemma 2. Its values depend only on , and , which are functions of .
Cost
Let be the largest allele length during the run. Each change in phase 1 or phase 2 copies the alleles, in time. Phase 1 makes at most changes, and the alleles reach their final length plus the distance the variant moved, so with the number of bases the variant moves left, the time is . A version that keeps index pairs into the strings instead of copying them runs in time.
Complexity
- Time. Each round of the first loop does work on the ends of the alleles, plus the cost of the string updates. The number of rounds is at most , where is the shift to the left. The code builds new strings in each round, which costs per round and in total. With arrays and a moving window, each round costs and the total is .
- Space. for the alleles.
- In practice. The shift is at most the length of the repeat around the event, so normalizing a whole VCF is fast compared with reading it.
Properties
- Unique output. Equivalent inputs give the same output, which is the theorem of Tan et al. (2015).
- Idempotent. Normalizing a normalized variant changes nothing.
- Keeps the haplotypes. Every step keeps all the haplotypes the same.
- Needs the reference. Line L5 reads the reference base to the left, so the tool needs the reference sequence, not only the VCF.
Variants and improvements
- Right alignment. Some formats, such as the HGVS nomenclature for clinical variants, place an event as far to the 3' end as possible. The same algorithm with the two ends swapped gives that form.
- Multiallelic records. A record with several ALT alleles can be normalized as a whole, as here, or split into one record per ALT allele first, which can give each allele a different position. bcftools norm can do both.
- Complex variants. Two records that describe the same haplotype as a different set of events, such as an MNV against two SNVs, or an insertion plus a deletion against a substitution, are not made equal by normalization. Comparing them needs the haplotypes; tools that compare call sets for precision and recall do this by rebuilding the haplotypes.
- In callers. Aligners and callers can produce left-aligned indels directly, by breaking ties in the alignment to the left.
When to use it
Normalize every VCF before merging call sets, comparing them with a benchmark, or looking variants up in a database. Without it, a deletion in a repeat can be counted as a false positive in one set and a false negative in the other, although both sets have it.
Pitfalls
- A different reference. The result depends on the reference sequence. Normalizing against another build, or a reference that differs from the one used for calling, gives wrong results or a REF mismatch.
- Position 1. An event that reaches the start of a sequence cannot be padded on the left; VCF uses the base after the event there.
- Splitting first or not. Normalizing a multiallelic record as a whole and normalizing its split records can give different positions. Pick one order and use it for all call sets.
- Not a full comparison. Normalized records that differ can still give the same haplotypes when they are not equivalent one record at a time, as for complex variants.
- Repeats around the event. In a long tandem repeat, the left-aligned position can be far from where the caller put the event; this is correct, but it can move the event out of a region of interest.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variant-normalization/. The authors are listed in prov/YT7FC7.jsonl.
"""Normalization of a VCF-style variant (Tan, Abecasis and Kang 2015).
A variant is (pos, alleles): pos is the 1-based position of the first base
of the alleles on the reference, as in VCF, and alleles[0] is the reference
allele REF, equal to ref[pos - 1 : pos - 1 + len(REF)]. The other entries are
the ALT alleles. All alleles are non-empty strings over ACGT and pairwise
different.
normalize returns the unique left-aligned and parsimonious form. It needs
the reference base to the left of the variant whenever an allele becomes
empty; if the variant would have to move before position 1, it raises
ValueError (VCF then pads with the base after the event, which this code
leaves out).
"""
from __future__ import annotations
from typing import List, Sequence, Tuple
Variant = Tuple[int, Tuple[str, ...]]
def check(ref: str, pos: int, alleles: Sequence[str]) -> None:
"""Raise ValueError unless (pos, alleles) is a valid variant on ref."""
if len(alleles) < 2 or any(not a for a in alleles):
raise ValueError("need REF and at least one ALT, all non-empty")
if len(set(alleles)) != len(alleles):
raise ValueError("alleles must be pairwise different")
if pos < 1 or ref[pos - 1:pos - 1 + len(alleles[0])] != alleles[0]:
raise ValueError("REF does not match the reference at pos")
def normalize(ref: str, pos: int, alleles: Sequence[str]) -> Variant:
"""The normalized form of the variant (pos, alleles) on the reference ref."""
check(ref, pos, alleles)
al: List[str] = list(alleles)
changed = True
while changed: # @line L1
changed = False # @line L2
if len({a[-1] for a in al}) == 1: # @line L3
al = [a[:-1] for a in al]
changed = True
if any(a == "" for a in al): # @line L4
if pos == 1:
raise ValueError("the variant reaches position 1; pad on the right instead")
pos -= 1 # @line L5
al = [ref[pos - 1] + a for a in al]
changed = True
while len({a[0] for a in al}) == 1 and min(len(a) for a in al) >= 2: # @line L6
al = [a[1:] for a in al] # @line L7
pos += 1
return pos, tuple(al) # @line L8
def apply(ref: str, pos: int, ref_allele: str, alt: str) -> str:
"""The haplotype made by replacing ref_allele at pos (1-based) by alt."""
i = pos - 1
if ref[i:i + len(ref_allele)] != ref_allele:
raise ValueError("REF does not match the reference at pos")
return ref[:i] + alt + ref[i + len(ref_allele):]
def all_representations(ref: str, hap: str) -> List[Tuple[int, str, str]]:
"""Every (pos, REF, ALT) with non-empty alleles that turns ref into hap (brute force)."""
out = []
n = len(ref)
for i in range(n):
for j in range(i + 1, n + 1):
head, tail = ref[:i], ref[j:]
if len(head) + len(tail) >= len(hap) or not hap.startswith(head) or not hap.endswith(tail):
continue
alt = hap[len(head):len(hap) - len(tail)]
if alt and alt != ref[i:j]:
out.append((i + 1, ref[i:j], alt))
return out
test_variant_normalization.py 79 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/variant-normalization/. The authors are listed in prov/YT7FC7.jsonl.
import os
import random
import pytest
from variant_normalization import all_representations, apply, normalize
REF = "GTCACACAGT"
def lcp(a, b):
k = 0
while k < min(len(a), len(b)) and a[k] == b[k]:
k += 1
return k
def closed_form(ref, hap):
"""The normalized (pos, REF, ALT) from the proof: it depends only on ref and hap."""
s = lcp(ref[::-1], hap[::-1])
assert s < min(len(ref), len(hap))
a = min(lcp(ref, hap), min(len(ref), len(hap)) - s - 1)
return a + 1, ref[a:len(ref) - s], hap[a:len(hap) - s]
def test_page_example():
hap = "GTCACAGT"
reps = all_representations(REF, hap)
assert (2, "TCA", "T") in reps and (3, "CAC", "C") in reps and (6, "ACA", "A") in reps
for pos, r, a in reps:
assert normalize(REF, pos, (r, a)) == (2, ("TCA", "T"))
assert normalize(REF, 3, ("CACA", "CA", "CACACA")) == (2, ("TCA", "T", "TCACA"))
def test_snv_and_mnv_are_trimmed():
assert normalize(REF, 3, ("CAC", "CGC")) == (4, ("A", "G"))
assert normalize(REF, 1, ("GTCA", "GACA")) == (2, ("T", "A"))
assert normalize(REF, 3, ("CACA", "TACG")) == (3, ("CACA", "TACG"))
def test_all_equivalent_placements_give_one_form():
rng = random.Random(11)
for _ in range(300):
body = "".join(rng.choice("AC") for _ in range(rng.randint(3, 12)))
ref = "G" + body
i = rng.randint(1, len(ref) - 1)
if rng.random() < 0.5:
j = rng.randint(i + 1, min(len(ref), i + 3))
hap = ref[:i] + ref[j:]
else:
ins = "".join(rng.choice("AC") for _ in range(rng.randint(1, 3)))
hap = ref[:i] + ins + ref[i:]
if hap == ref:
continue
reps = all_representations(ref, hap)
expect = closed_form(ref, hap)
assert expect in reps
best = min(reps, key=lambda t: (len(t[1]), t[0]))
assert best == expect
for pos, r, a in reps:
got = normalize(ref, pos, (r, a))
assert got == (expect[0], (expect[1], expect[2]))
assert apply(ref, got[0], got[1][0], got[1][1]) == hap
def test_errors():
with pytest.raises(ValueError):
normalize(REF, 3, ("CA", "CA"))
with pytest.raises(ValueError):
normalize(REF, 3, ("GG", "G"))
with pytest.raises(ValueError):
normalize("AAAC", 2, ("AA", "A"))
if __name__ == "__main__":
raise SystemExit(pytest.main([os.path.abspath(__file__), "-q"]))
History
VCF asks for a padding base on indels, but it does not fix which of the equivalent positions to use. Tan, Abecasis and Kang (2015) gave the formal definitions of left-aligned and parsimonious, proved that the normalized form is unique, and gave the algorithm in their tool vt. bcftools norm implements the same normalization.
References
- Adrian Tan, Goncalo R. Abecasis and Hyun Min Kang, Unified representation of genetic variants, Bioinformatics 31(13), 2015, pp. 2202 to 2204 (the definitions of left-aligned and parsimonious, the uniqueness theorem and the normalization algorithm)
- The Variant Call Format Specification, VCFv4.3, hts-specs, Section 1.6.1, the REF and ALT fields (the padding base of indels and the base after the event at position 1)
- bcftools manual, the section on bcftools norm (left alignment and normalization of indels, and the splitting of multiallelic records)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YT7FC7 Edit this page History Report an error Markdown