2-bit DNA encoding — packing, Hamming, and barcodes
Day 13, lecture 2
Rust for bioinformaticians
What this lecture is
Lecture 1 gave you the bitwise toolkit [the primitive integer operations: AND, OR, XOR, NOT, shifts, count_ones] — now we use it on real data
Goal: store DNA compactly and compute on it fast using nothing but integers
We land on a working solution to a real industrial problem — single-cell barcode whitelist matching [identifying which “valid” cell barcode an observed read belongs to]
DNA has 4 letters — fits in 2 bits
DNA is a 4-letter alphabet: A, C, G, T. Four symbols means 2 bits per base (\(2^2 = 4\)).
Storage
Bits
Bases held
u8
8
4
u16
16
8
u32
32
16
u64
64
32
u128
128
64
A naive String uses 8 bits per base (one byte per ASCII character). The packed form is 4× smaller, and as a bonus we can do whole-sequence arithmetic on it in one CPU instruction.
The 2-bit code
The standard mapping used by samtools, bwa, jellyfish, and most modern tools:
Base
Bits
A
00
C
01
G
10
T
11
The four DNA bases and their 2-bit codes, with A=00, C=01, G=10, T=11 highlighted in a small mapping table.
Two nice properties fall out for free:
Complement = bitwise NOT.!00 = 11 (A → T) and !01 = 10 (C → G).
High bit distinguishes purines from pyrimidines [purines = A, G (two-ring); pyrimidines = C, T (one-ring); the second-most-common DNA classification].
Packing a sequence
Eight bases ACGTACGT → 16 bits → 2 bytes.
Eight-base sequence ACGTACGT packed into two bytes: each base mapped to its 2-bit code, then concatenated low-base-first into a 16-bit integer.
fn encode(b:u8) ->u64{match b {b'A'=>0,b'C'=>1,b'G'=>2,b'T'=>3, _ =>panic!() }}let seq =b"ACGTACGT";letmut packed:u64=0;for (i,&b) in seq.iter().enumerate() { packed |= encode(b) << (2* i);// place base i at bits 2i..2i+2}// packed == 0b1101_1000_1101_1000 (little-base-first layout)
A u64 holds 32 bases
The most useful packed sizes:
Container
Bases
Common name
u32
16
a 16-mer, a typical cell barcode
u64
32
a 32-mer, a typical k-mer in assembly
u128
64
a 64-mer, the BWA seed length
For sequences longer than 64 bases, use Vec<u64> with (n + 31) / 32 words — each word holds 32 bases, the final word is partially filled.
Extracting base 3 from a packed 16-bit value: shift right by 6 bits, then mask with 0b11 to keep just the two lowest bits.
Two CPU instructions: one shift, one AND. Constant time regardless of where i lies in the sequence.
Setting one base by index
To overwrite a base, clear its two bits, then OR the new value in:
fn set_base(packed:u64, i:usize, base:u8) ->u64{let shift =2* i;let cleared = packed &!(0b11<< shift);// zero the two bits cleared | ((base asu64) << shift) // OR new base in}
The clear step is essential — if we skipped it, the new bits would be ORed with the old, giving garbage.
Complement — one XOR for the whole sequence
To flip every base to its Watson-Crick complement:
let complemented = packed ^0xFFFF_FFFF_FFFF_FFFF;// flip all 64 bits// or equivalently:let complemented =!packed;
Each 2-bit base flips: 00↔︎11 (A↔︎T), 01↔︎10 (C↔︎G). XOR with all-1s is bitwise NOT.
Complementing a packed 8-base sequence with a single XOR against 0xFFFF: A↔︎T and C↔︎G shown for each base position.
One CPU operation regardless of sequence length. A 32-mer complements in one cycle; a 64-mer in two.
Reverse complement — reverse + complement
Reversing 2-bit packed data is not bit-by-bit reversal — that would scramble each base. It is a pair-wise reversal: swap whole 2-bit pairs end-to-end.
fn reverse_complement_32mer(packed:u64) ->u64{let reversed = reverse_pairs_u64(packed);// swap base 0 with 31, 1 with 30, ...!reversed // complement every base}
In practice we build reverse_pairs_u64 from u64::swap_bytes (reverses byte order — same as reversing 4-base chunks) plus a small in-byte pair swap [shuffle the 4 bases within each byte from order 0-1-2-3 to 3-2-1-0] using a couple of masks and shifts.
You will implement this in Exercise 4.
Hamming distance — XOR then popcount
For two unpacked strings, Hamming distance [the number of positions at which two equal-length sequences differ] is a loop with a counter. For two packed sequences, XOR finds the differing positions and popcount totals them — almost.
The catch with the A=00, C=01, G=10, T=11 code: a mismatched base flips either 1 or 2 bits, depending on which two bases were swapped. So we cannot just popcount the XOR — we have to first fold each 2-bit pair to a single “differs/same” bit.
fn hamming_packed(a:u64, b:u64) ->u32{let diff = a ^ b;// bits differ where bases differlet folded = (diff | (diff >>1)) &0x5555_5555_5555_5555;// 1 bit per base folded.count_ones() // popcount the folded bits}
Hamming distance via XOR and popcount: XOR two packed sequences, OR each pair with its shifted neighbour to fold to one bit per base, mask off the high bits, then popcount.
0x5555_5555_5555_5555 is the alternating mask …0101_0101 — one bit per base position. The whole function is four operations regardless of sequence length (up to 32 bases).
For billions of comparisons (one read alignment workload): the difference between minutes and weeks.
Real-world example — single-cell barcodes
Modern single-cell RNA-seq (10x Genomics Chromium, Drop-seq) works by droplet partitioning [each cell is captured in its own oil droplet alongside a barcoded bead]:
Each droplet contains one cell and one bead [a microscopic resin sphere coated in millions of identical capture oligos]
Every capture oligo on the bead carries the same cell barcode [a random 16-bp DNA tag that uniquely identifies the bead, and hence the cell]
All mRNAs from one cell pick up the same barcode → reads from the same cell can be pooled later
A single run produces hundreds of millions of reads, each labelled with a 16-bp barcode.
The whitelist problem
10x Genomics ships a whitelist [the list of oligonucleotides actually synthesised onto the beads] of ~6.7 million valid 16-bp barcodes. The rest of \(4^{16} \approx 4.3\) billion possible 16-mers were not synthesised.
For every read, we observe a barcode and ask: which whitelist entry does this correspond to?
Exact match — easy, look it up.
One sequencing error — match to the closest whitelist entry at Hamming distance 1.
Two or more errors — discard the read.
A query barcode coming off the sequencer, a small whitelist of valid barcodes, and the matching procedure: try exact match first, otherwise find the unique whitelist entry within Hamming distance 1.
When the exact lookup misses, generate all 48 possible 1-base substitutions of the query and test each:
fn hamming1_neighbors(query:u32) ->implIterator<Item =u32>{ (0..16).flat_map(move|i|{let original = (query >> (2* i)) &0b11; (0..4u32).filter(move|&b| b != original).map(move|b|{let cleared = query &!(0b11<< (2* i)); cleared | (b << (2* i))})})}// For each of 16 positions, 3 alternative bases = 48 neighbors.
For each of the 48 candidates, one HashSet::contains call. If exactly one hits the whitelist, that is the corrected barcode. Total: 48 hash lookups per read → microseconds.
This is one way to do Hamming-1 lookup — not necessarily the fastest. Production tools also use precomputed neighbour hash tables, locality-sensitive hashing, SIMD-vectorised distance scans, or trie / BK-tree indices. The 48-neighbour enumeration above wins on simplicity and is fast enough at single-cell-pipeline scale; profile before optimising further.