Day 10, lecture 1
A[i][j] = 1 if there is an edge from i to j20 × 20 substitution-score matrixThree common bioinformatics matrices: a single-cell expression matrix (genes × cells, mostly zero), a k-mer count table (samples × k-mers), and a small adjacency matrix for a phylogenetic graph.
The central operation is multiplication — matrix-times-vector (A·x, the workhorse) or matrix-times-matrix (A·B, less common in inner loops).
Matrix A (2×3), vector x (length 3), and the resulting vector y (length 2), with each entry of y spelled out as a dot product of one row of A against x.
Computer memory is a long flat run of bytes — there is no two-dimensional shelf. So an Array2<f64> of shape (rows, cols) is stored as one contiguous buffer of rows * cols floats, plus the two integers rows and cols.
There are two conventions for how to lay the entries out:
ndarray — offset(i, j) = i · cols + jnalgebra — offset(i, j) = j · rows + iThe same 3×4 matrix shown in two memory layouts: row-major colours each row separately and lays the rows end-to-end in memory; column-major colours each column separately and lays the columns end-to-end. The offset formulas appear under each layout.
// Row-major matrix: iterating row-by-row touches consecutive memory.
for i in 0..rows {
for j in 0..cols {
sum += a[[i, j]]; // FAST: each step reads the next byte
}
}
// Same matrix, swap the loops: now we stride through cache.
for j in 0..cols {
for i in 0..rows {
sum += a[[i, j]]; // SLOW: each step jumps rows*8 bytes
}
}The CPU loads memory in 64-byte chunks called cache lines [a contiguous block the CPU fetches from RAM in one go; reusing it is essentially free, fetching a new one costs ~100 cycles]. The first loop reuses each cache line; the second discards it on every iteration.
Where each read lands in linear memory for a 4×4 matrix: reading a row in row-major touches 4 contiguous cells (one cache line); reading a column touches 4 cells spread far apart (4 cache lines). Mirror behaviour for column-major.
The slowdown is often 5-20×. Same code, same numbers, different access pattern.
ndarrayndarray is the standard crate for dense N-dimensional arrays.
use ndarray::{Array1, Array2, array};
let a: Array2<f64> = Array2::zeros((3, 3)); // 3x3 of zeros
let b: Array2<f64> = Array2::eye(3); // 3x3 identity
let m = array![[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]]; // literal
let x: Array1<f64> = array![1.0, 2.0, 3.0];
let y = m.dot(&x); // matrix-vector multiply
let mt = m.t(); // transpose, no copyIf you know NumPy, you know 90% of ndarray. See the ndarray-for-NumPy-users guide.
The equivalent in R:
R stores matrices in column-major order — same data, opposite layout from ndarray.
A typical 10x Genomics single-cell experiment:
| Dimension | Size |
|---|---|
| Genes (rows) | ~ 10 000 |
| Cells (columns) | ~ 100 000 |
| Total entries | 10⁹ |
| Non-zero fraction | 1-5% |
As a dense f64 matrix: 10⁹ × 8 bytes = 8 GB. As a sparse matrix: 80-400 MB, a 20-100× saving — and most matrix operations get faster too, because zero times anything is zero and we skip it.
Three parallel arrays: row, col, value. Entry k lives at (row[k], col[k]) = value[k].
A = [ 0 0 5 0 ]
[ 0 8 0 0 ]
[ 2 0 0 0 ]
[ 0 0 0 7 ]
row = [0, 1, 2, 3]
col = [2, 1, 0, 3]
value = [5, 8, 2, 7]
COO format: each non-zero is a (row, col, value) triplet, stored in three parallel arrays.
Use COO for: loading data (e.g., from a TSV), building a matrix incrementally. Avoid COO for matrix-vector multiplication — there is no row or column order, so the multiply algorithm cannot stream cleanly.
Three flat arrays: values, col_indices, row_pointers of length rows + 1.
A = [ 0 0 5 0 ]
[ 0 8 0 0 ]
[ 2 0 0 0 ]
[ 0 0 0 7 ]
values = [5, 8, 2, 7]
col_idx = [2, 1, 0, 3]
row_ptr = [0, 1, 2, 3, 4] // row i lives at values[row_ptr[i] .. row_ptr[i+1]]
CSR format: a single flat array of values, a parallel array of column indices, and a row_pointers array giving the start index for each row.
Fast row access. Fast matrix-vector multiplication — for each row you walk a contiguous slice of values and col_idx. This is the workhorse format for numerical sparse code.
The mirror image of CSR — column-oriented.
A = [ 0 0 5 0 ]
[ 0 8 0 0 ]
[ 2 0 0 0 ]
[ 0 0 0 7 ]
values = [2, 8, 5, 7]
row_idx = [2, 1, 0, 3]
col_ptr = [0, 1, 2, 3, 4] // column j lives at values[col_ptr[j] .. col_ptr[j+1]]
CSC format: same idea as CSR but oriented around columns; values, row_indices, and col_pointers.
Fast column access; slow row access. Use CSC when you frequently pull out single columns — e.g., a single-cell pipeline processing one cell (column) at a time.
| Use case | Best format |
|---|---|
| Loading from disk, building incrementally | COO |
| Matrix-vector multiplication, iterative solvers | CSR |
| Slicing or extracting single columns | CSC |
| Whole matrix is dense (or near-dense), small | dense Array2 |
Typical workflow: read a TSV into COO → convert to CSR for math.
sprssprs is the standard sparse-matrix crate. The main type is CsMat<f64> — compressed sparse, CSR or CSC.
use sprs::{TriMat, CsMat};
let mut triplets = TriMat::new((3, 3)); // (rows, cols)
triplets.add_triplet(0, 2, 5.0);
triplets.add_triplet(1, 1, 8.0);
let csr: CsMat<f64> = triplets.to_csr(); // build COO, convert to CSR
let nnz = csr.nnz(); // 2 non-zeros
let x = vec![1.0, 2.0, 3.0];
let y = &csr * &x; // sparse mat-vec multiplyConversion COO → CSR is one method call. Matrix-vector multiply uses the standard * operator.
Sparse matrix-vector multiplication with sprs: a 4×4 matrix with 4 non-zero entries multiplied by a length-4 vector of ones produces a length-4 result vector whose entries are exactly the non-zero values, picked up one per row.
For an n × n matrix and a length-n vector:
| Format | Operations | Notes |
|---|---|---|
| Dense | n² multiply-adds |
Cache-friendly, vectorisable |
| Sparse (CSR) | nnz multiply-adds |
Only non-zeros visited |
For n = 100 000 and density 0.5% (nnz = 5 × 10⁷):
10¹⁰ operations (~10 s)5 × 10⁷ operations (~0.05 s)That is a ~200× speedup before counting the memory saved.
A·x = b — two approachesA huge chunk of numerical bioinformatics is “find x such that A·x = b”:
A (LU, Cholesky), back-substitute. Exact to floating-point. O(n³) time, O(n²) memory. Fine for n ≤ a few thousand.O(nnz × iterations). Scales to n = 10⁶+.For large sparse problems you choose iterative.
Start with a guess \(\mathbf{x}\) (zeros are fine). Sweep through the rows. For each row \(i\), isolate \(x_i\) in the equation \(\mathbf{A}\mathbf{x} = \mathbf{b}\):
\[x_i^{\,k+1} \;=\; \dfrac{1}{A_{ii}} \left( b_i \;-\; \sum_{j \ne i} A_{ij}\, x_j \right)\]
The right-hand side uses the latest available value of each \(x_j\) — newly updated \(x_0, \dots, x_{i-1}\) from the current sweep, and old \(x_{i+1}, \dots, x_{n-1}\) from the previous one. Writing \(x_i\) back in place is what makes it Gauss-Seidel rather than Jacobi.
For the matrix A = [[4, -1, 0], [-1, 4, -1], [0, -1, 4]] and b = [2, 6, 2], the first sweep gives x = [0.5, 1.625, 0.906]; a few more sweeps bring it within 1e-6 of the true solution.
Two common sufficient conditions:
For matrices outside these classes Gauss-Seidel may diverge — the successive x vectors blow up instead of homing in.
In practice: most matrices that arise from physical or biological modelling problems are SPD or close to it, and Gauss-Seidel just works.
Successive iterates of Gauss-Seidel narrowing on the true solution; the rate depends on the condition number of A.
Each iteration moves the current x closer to the true solution. The rate of convergence depends on the condition number [a single number summarising how “stretched” the matrix is; close to 1 is great, very large is slow or unstable] of A. Well-conditioned: handful of iterations. Ill-conditioned: thousands, or never.
64 × 64 matrix of codon-to-codon transitionsWhenever you have “what comes next depends only on what is now”, a Markov chain is the standard model.
A 3-state Markov chain shown as a directed graph with weighted edges, the equivalent 3x3 transition matrix P, and the matrix-vector multiplication P^T times p_t producing p_{t+1}.
Three pieces: states (the nodes), transition probabilities (the edge weights — each row of P sums to 1), and a current distribution p_t that evolves one step at a time.
Starting from the all-mass-on-A distribution p_0 = [1, 0, 0], multiplying by P^T once gives p_1 = [0.7, 0.2, 0.1], twice gives p_2 = [0.56, 0.25, 0.19], and many more steps converge to the stationary distribution π ≈ [0.296, 0.185, 0.519].
Start with any distribution p_0. Multiply by Pᵀ over and over. The sequence converges to the stationary distribution π:
Convergence is guaranteed when the chain is ergodic [every state reachable from every other, and the chain is not stuck in a cycle].
Alternatively, solve directly for the eigenvector with eigenvalue 1:
\[\pi = \pi \cdot P \qquad \Longleftrightarrow \qquad (P^T - I)\,\pi = 0,\ \ \sum_i \pi_i = 1\]
In words: \(\pi\) is the distribution that doesn’t change when we apply \(P\) — the state we arrive at after one transition is the same as the state we started from.
For small dense P this is fast and exact. For large sparse P power iteration is more practical — the steady-state solve would densify the factorisation.
Google’s original ranking algorithm is a Markov chain. Each web page is a state; each hyperlink is a transition; the imaginary “random surfer” walks the graph by following random outgoing links. The probability of being on page i after many steps is page i’s rank — and the algorithm to compute it is power iteration on a giant sparse transition matrix.
A 5-page web graph with directed hyperlinks; a random-surfer pictogram traversing it; the resulting sparse transition matrix P; and the steady-state distribution π shown as a bar chart of the page ranks. Pages with many incoming links have high rank.
Bioinformatics borrowed the trick: Personalized PageRank on protein-interaction graphs to score “how related is gene X to my list of seed genes”; random walks on co-expression networks; HotNet-style algorithms that find mutated subnetworks in cancer.
| Power iteration | Direct eigenvector | |
|---|---|---|
| Works for | any sparse P |
small dense P |
| Cost | O(nnz × iters) |
O(n³) |
| Output | full trajectory p_0, p_1, ..., π |
just π |
| Convergence | needs ergodicity | always (when valid) |
| Typical use | network analysis, PageRank | small biological models |
Power iteration is the default for anything large or sparse.
O(nnz × iters) instead of O(n³).Four exercises, in order:
ndarray::Array2, slicing, mat-vec multiplysprs::CsMat, triplet → CSR, memory comparison