Why Rust for bioinformatics?

Day 1, Lecture 1

Rust for bioinformaticians

About this lecture

  • Why Rust matters in modern bioinformatics
  • Where it lives in the toolbox already
  • What it costs
  • What this course will and will not teach

What Rust looks like — same code, three languages

Count the G + C bases in a short DNA string.

Python

count = 0
for base in "ACGTACGT":
    if base == 'G' or base == 'C':
        count += 1
print(count)

R

count <- 0
for (b in strsplit("ACGTACGT", "")[[1]]) {
  if (b == "G" || b == "C") {
    count <- count + 1
  }
}
print(count)

Rust

let mut count = 0;
for base in "ACGTACGT".chars() {
    if base == 'G' || base == 'C' {
        count += 1;
    }
}
println!("{}", count);

Same shape in all three. Rust adds let mut (variables are read-only by default) and ! after println (it’s a macro, not a function). Everything else reads the same.

Counting k-mers in three languages

Python

from collections import Counter

def count_kmers(seq, k):
    return Counter(
        seq[i:i+k]
        for i in range(len(seq)-k+1)
    )

R

count_kmers <- function(seq, k) {
  n <- nchar(seq) - k + 1
  table(substring(seq, 1:n, k:nchar(seq)))
}

Rust

use std::collections::HashMap;

fn count_kmers(seq: &[u8], k: usize)
    -> HashMap<Vec<u8>, usize>
{
    let mut counts = HashMap::new();
    for w in seq.windows(k) {
        *counts.entry(w.to_vec())
               .or_insert(0) += 1;
    }
    counts
}

Same algorithm. Rust adds type signatures (&[u8], usize, HashMap<...>) — that information is also present in Python and R, just inferred at runtime instead of checked at compile time.

Rust is faster, with almost the same code

Horizontal bar chart with a log-scale wall-clock axis from 0.1 s to 100 s. Four bars from top to bottom: CPython 3.12 at 44 seconds (grey), PyPy 3.10 at 7 seconds (grey), Rust release at 0.8 seconds (highlighted yellow with orange border), Rust plus rayon on 8 cores at 0.1 seconds (green).

Figure 1: Wall-clock for k-mer counting at k=21 on a 10 Mb genome, across four implementations.

Why this matters in bioinformatics

  • Reads per sample: \(10^8\)
  • Samples per project: \(10^2\) to \(10^5\)
  • Genome / transcriptome / pangenome sizes are growing faster than CPU clock speeds
  • Cloud bill scales linearly with wall-clock
  • Iteration speed scales inversely with wall-clock

The deployment story — Python

$ ./run_analysis.sh
ModuleNotFoundError: No module named 'pysam'

$ pip install pysam
ERROR: Building wheel for pysam failed (htslib not found)

$ apt install libhts-dev
E: Unable to locate package libhts-dev

$ # ...one hour later...

crates.io replaces a whole stack of tools

Python and R patch the dependency mess by layering container and environment managers on top:

  • Docker, Podman — container runtimes
  • Apptainer (formerly Singularity) — HPC-friendly containers
  • Conda, mamba — package + environment managers

A container ships your script + every library + a whole Linux — often 1-2 GB to run a 50-line analysis.

Rust binaries pull in nothing at run time. cargo build --release produces a single static executable; cargo install some-tool fetches the source and builds it. crates.io is the index — one tool, one ecosystem.

The tool is the artifact. No container needed.

Left: a stylised shipping container, labelled 'Docker / Apptainer / Conda', stacked from bottom to top with: 'Linux base image (Ubuntu, Alpine, ...)', 'system libraries (libc, libssl, ...)', 'language runtime (Python, R)', 'pip / conda packages', 'your script'. Total size labelled '~1-2 GB'. Right: a single small box labelled 'my_rust_tool (4 MB static binary)' with a tick mark, no container around it.

A container ships your code plus its libraries plus a whole Linux userspace — often 1-2 GB. A Rust binary is just the code, statically linked: a few megabytes.

Type safety — what Python and R skip

R — defend the function by hand

add <- function(a, b) {
  stopifnot(is.numeric(a),   # ← Rust
            is.numeric(b))   # ← doesn't
  a + b                      #   need
}                            #   these
add(3, "seven")
# Error: is.numeric(b) is not TRUE
#   (at runtime, not at write time)

Rust — the type signature is the check

fn add(a: i32, b: i32) -> i32 {
    a + b
}

add(3, "seven");
// error[E0308]: mismatched types
//   expected `i32`, found `&str`
//   (caught at compile, never ships)

The stopifnot(...) block on the left is the same check the Rust signature does on the right — except R does it at every call, at runtime, after the type information has already been written.

Safety — and why it matters

A segfault (segmentation fault — what happens when a program touches memory it doesn’t own) is the classic crash mode of C and C++: the operating system spots a bad memory access and kills the process. Python and Rust are designed so you almost never see one — Python checks at runtime, Rust at compile time.

let mut seq = vec![0u8; 100];
let r = &seq[0];           // borrow a reference into seq
seq.push(b'A');            // try to change seq while r still points in
println!("{}", r);
error[E0502]: cannot borrow `seq` as mutable because it is also
              borrowed as immutable
  --> src/main.rs:3:5
   |
 2 | let r = &seq[0];
   |          ------ immutable borrow occurs here
 3 | seq.push(b'A');
   | ^^^^^^^^^^^^^^^ mutable borrow occurs here
 4 | println!("{}", r);
   |                - immutable borrow later used here

Parallelism is easy — and unavoidable

CPU clock speeds stopped climbing around 2005. The cores kept multiplying — every modern laptop, desktop, and HPC node has at least 8 of them; a server typically has 64 to 256. To use any of that you have to write code that spreads work across cores.

In Rust this is usually a one-line change:

use rayon::prelude::*;

let total: HashMap<Vec<u8>, usize> = sequences
    .par_iter()                       // .iter() → .par_iter()
    .map(|seq| count_kmers(seq, 21))
    .reduce(HashMap::new, merge);

The compiler refuses to build any version that would race two threads against the same memory. No mutexes to acquire, no deadlocks to debug, no silently corrupted output. There is no equivalent in Python or R — Python’s GIL serialises threads, and R has no built-in story at all.

Rust in bioinformatics today

I/O and formats

  • noodles — pure-Rust HTSlib
  • rust-htslib — htslib FFI
  • needletail — FASTA/FASTQ

Variant calling

  • varlociraptor
  • longshot

Single-cell

  • alevin-fry

Long-read QC

  • chopper
  • nanoq

General

  • rust-bio
  • parts of mash, kraken2

Can easily integrate Rust code in Python if not ready to switch completely

use pyo3::prelude::*;

#[pyfunction]
fn count_kmers(seq: &[u8], k: usize)
    -> HashMap<Vec<u8>, usize>
{
    // ...same body as the Rust version above...
}
# In your Jupyter notebook:
import my_fast_lib
counts = my_fast_lib.count_kmers(seq, 21)

What this course teaches

Day Theme
1 Toolchain, scalars, control flow, functions
2 Ownership, borrowing, strings, slices
3 Structs, enums, iterators, recursion, error handling
4 I/O, crates, modules, plotting, zip
5 Tests, --release, parallelism, ecosystem
6 Yew & WebAssembly — pure-Rust web apps

Today specifically

By end of day 1 you will be able to:

  • Install Rust, scaffold and run a cargo project
  • Read and write Rust syntax for variables, control flow, functions
  • Use match expressions and panic!
  • Compute GC content, base counts, complement, Phred score, Hamming distance — five small programs, with tests