Skip to content

Commit 79b6fe3

Browse files
authored
Add PCA tutorial for genetic datasets
Added tutorial on comparing branch and SNP-based PCA using msprime and tskit, including code examples for simulating ARGs and performing PCA.
1 parent da1f625 commit 79b6fe3

1 file changed

Lines changed: 236 additions & 0 deletions

File tree

PCA.md

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
---
2+
jupyter:
3+
jupytext:
4+
formats: ipynb,md
5+
text_representation:
6+
extension: .md
7+
format_name: markdown
8+
format_version: '1.3'
9+
jupytext_version: 1.19.1
10+
kernelspec:
11+
display_name: msprime
12+
language: python
13+
name: myenv
14+
---
15+
16+
# Comparing branch and SNP-based PCA
17+
18+
19+
Principal Component Analysis (PCA) is commonly used for exploring population structure in genetic datasets, where it is usually computed from SNP genotyped data. In the context of ARGs, it is also possible to perform branch PCA as implemented in `tskit`. This does not use variant data. (Of course, it may indirectly rely on variant data if the ARG was inferred from data.)
20+
21+
In this tutorial, we demonstrate both approaches. We will apply these to haplotypes and diploid genotype data.
22+
23+
The documentation of `tskit.TreeSequence.pca` can be found [here](https://tskit.dev/tskit/docs/stable/python-api.html#tskit.TreeSequence.pca).
24+
25+
26+
:::{note}
27+
Usually, PCA is carried out on a diploid genotype matrix (individuals in rows, loci in columns) with values 0, 1, and 2. PCA can then be achieved through singular value decomposition (SVD) of the column-centred genotype matrix. This results in a matrix of principal component (PC) scores, which are linear combinations of the genotype columns. The PC scores are ordered, decreasingly, by the amount of variation from the original data they account for.
28+
:::
29+
30+
31+
First, we'll simulate an ARG with population structure:
32+
33+
```python
34+
# load required libraries
35+
import msprime as msp
36+
import tskit
37+
import numpy as np
38+
import matplotlib.pyplot as plt
39+
from scipy.stats import linregress
40+
```
41+
42+
```python
43+
# set a mutation rate
44+
mu = 1e-8
45+
# number of sub-populations/'islands'
46+
nPop = 5
47+
# number of diploids sampled from each sub-population
48+
nSamp = 10
49+
# number of haplotypes sampled
50+
nHap = 2* nSamp
51+
# per-island effective population size
52+
nn = 1e4
53+
# migration rate (per individual and island pair)
54+
migRate = 1e-5
55+
```
56+
57+
Simulate an ARG using an island model demography. There are five islands, each with a population size of 10,000. Pairwise migration rates are $10^{-5}$.
58+
59+
```python
60+
# Island model demography, 5 islands connected by low gene flow
61+
dmg = msp.Demography.island_model([nn] * nPop, migration_rate=migRate)
62+
```
63+
64+
```python
65+
# Simulate ARG
66+
ts = msp.sim_ancestry(samples={i: nSamp for i in range(nPop)},
67+
demography=dmg,
68+
random_seed=1234,
69+
sequence_length=1e6,
70+
recombination_rate=1e-9)
71+
ts
72+
```
73+
74+
The same ARG, but with mutations added.
75+
76+
```python
77+
# Add mutations
78+
tsm = msp.sim_mutations(ts, rate=mu, random_seed=1234)
79+
tsm
80+
```
81+
82+
The migration rates between the islands are quite low. This should lead to considerable genetic differentiation. Let us compute pairwise $F_{ST}$:
83+
84+
```python
85+
# Considerable pairwise Fst between the 'islands'
86+
fstmat = np.zeros([nPop,nPop])
87+
for i in range(nPop-1):
88+
for j in range(i+1,nPop):
89+
fstmat[i,j] = tsm.Fst([range(i*nHap,(i+1)*nHap), range((i+1)*nHap,(i+2)*nHap)])
90+
fstmat
91+
```
92+
93+
## PCA 'by hand'
94+
To compute a SNP PCA, we start by extracting the haploid 'genotypes' from the ARG. We then make use of the `TreeSequence` object's `individuals_nodes` property (an array) to select each individual's two haplotypes and to add them to create individual diploid genotypes.
95+
96+
```python
97+
# obtain a haplotype matrix and print its shape
98+
# 100 haplotypes (= 10 individual samples * 5 islands * 2 haplotypes per individual)
99+
# 13683 variant sites
100+
htMat=tsm.genotype_matrix().transpose()
101+
htMat.shape
102+
```
103+
104+
```python
105+
# Add each individual's two haplotypes to generate individual genotypes
106+
sample_ids_to_mat_index = np.full_like(tsm.samples(), tskit.NULL, shape=tsm.num_nodes)
107+
sample_ids_to_mat_index[tsm.samples()] = np.arange(len(tsm.samples()))
108+
gtMat = htMat[sample_ids_to_mat_index[ts.individuals_nodes]].sum(axis=1)
109+
```
110+
111+
```python
112+
# Haplotype SVD (column-centred)
113+
htSvd = np.linalg.svd(htMat - htMat.mean(axis=0), full_matrices=False)
114+
```
115+
116+
```python
117+
# Genotype SVD (column-centred)
118+
gtSvd = np.linalg.svd(gtMat - gtMat.mean(axis=0), full_matrices=False)
119+
```
120+
121+
## Branch PCA (tskit)
122+
To demstrate that branch PCA works without variant data, we run it on the ARG without mutations, `ts`.
123+
124+
125+
```python
126+
# haplotypes, each sample haplotype is ues by default
127+
hapBranchPca=ts.pca(num_components=10)
128+
```
129+
130+
```python
131+
# genotypes, all individuals are specified
132+
dipBranchPca=ts.pca(num_components=10, individuals=range(5*nSamp))
133+
```
134+
135+
Plot for comparison
136+
137+
```python
138+
fig, axs = plt.subplots(2, 2)
139+
plt.tight_layout()
140+
axs[0, 0].scatter(htSvd.U[:,0],
141+
htSvd.U[:,1],
142+
c=np.repeat([1,2,3,4,5], [nHap] * nPop))
143+
axs[0, 0].set_title('Haplotypes (sites)')
144+
145+
axs[0,0].set_ylabel("PC2")
146+
axs[0,1].scatter(gtSvd.U[:,0],
147+
gtSvd.U[:,1]*-1,
148+
c=np.repeat([1,2,3,4,5], [nSamp] * nPop))
149+
axs[0,1].set_title("Individuals (sites)")
150+
151+
# flipping the axes to make similarity clearer:
152+
axs[1,0].scatter(hapBranchPca.factors[:,0]*-1,
153+
hapBranchPca.factors[:,1]*-1,
154+
c=np.repeat([1,2,3,4,5], [nHap] * nPop))
155+
axs[1,0].set_title("Haplotypes (branches)")
156+
axs[1,0].set_ylabel("PC2")
157+
axs[1,0].set_xlabel("PC1")
158+
159+
axs[1,1].scatter(dipBranchPca.factors[:,0]*-1,
160+
dipBranchPca.factors[:,1],
161+
c=np.repeat([1,2,3,4,5], [nSamp] * nPop))
162+
axs[1,1].set_title("Individuals (branches)")
163+
axs[1,1].set_xlabel("PC1")
164+
165+
plt.show()
166+
```
167+
168+
The plots on the left show one dot per haplotype. These have twice as many dots as the plots on the right, which show individuals. The colours indicate from which of the five islands a haplotype or individual was sampled. As expected with low geneflow, there is some grouping by island. Feel free to re-run with higher or lower values of `migRate` to see how the separations between the island samples changes.
169+
170+
171+
## Comparing variance components between branch and SNP PCA
172+
Both `numpy.linalg.svd` and `tskit.TreeSequence.pca` return information about the amount of variation accounted for by each PC. These information are stored in the slots `S` (standard variation for SVD) and `eigenvalues` (variance for branch PCA). To make the two match, we need to multiply the eigenvalues by the mutation rate before taking the square root.
173+
174+
```python
175+
# square root of (branch eigenvalues multiplied by the mutation rate)
176+
xx=np.sqrt(hapBranchPca.eigenvalues * mu)
177+
# SVD S values
178+
yy=htSvd.S[:10]
179+
```
180+
181+
We now fit a least-squares regression model to demonstrate the match between SVD standard variation and transformed eigenvalues.
182+
183+
```python
184+
res = linregress(xx, yy)
185+
print(f"Intercept: {res.intercept:.4f}\n Slope: {res.slope:.4f}\n r^2: {res.rvalue**2:.4f}")
186+
187+
```
188+
189+
$r^2$ is close to 1. Let us visualise this. Each dot below shows a standard deviation value associate with one PC. The fact that they are well correlated suggests that both SNP and branch PCA yielded very similar results.
190+
191+
```python
192+
plt.scatter(xx, yy)
193+
plt.xlabel("sqrt(Branch eigenvals)")
194+
plt.ylabel("GT svd.S")
195+
plt.plot(xx, res.intercept + res.slope*xx, 'r', label='fitted line')
196+
plt.xlabel(r"Branches: $\sqrt{eigenvals * \mu}$") # use raw string to avoid error message about \s
197+
plt.ylabel("SNPs: $S$")
198+
plt.title("Variance components of SNP and branch PCA")
199+
plt.grid()
200+
plt.show()
201+
```
202+
203+
## Time windows
204+
Above we showed how variant and branch-based PCA are equivalent. But the ARG is a much richer data type than the genotype matrix. ARGs contain information about the historic relationships between the samples (possibly blurred by a inference step). Branch PCA allows one to specify a time window over which the PCA is to be computed, something that cannot be done for SNP PCA. Next, we compute PCA in time slices with breaks 0, 10, 100, 1000, 10,000, 100,000, 100,0000, 1,000,000, and 10,000,000. The results are stored in a list.
205+
206+
```python
207+
pctime=[tsm.pca(num_components=10, time_windows=[10**i, 10**(i+1)]) for i in range(8)]
208+
```
209+
210+
Being of class `PCAResult`, the elements of the list have a `factors` property. This has a shape of (100,10). I.e., 10 PCs for 100 haplotypes.
211+
212+
```python
213+
pctime[0].factors.shape
214+
```
215+
216+
```python
217+
for i in range(8):
218+
evecs = pctime[i].factors[:,:10]
219+
220+
plt.scatter(evecs[:,0],
221+
evecs[:,1],
222+
c=np.repeat(range(5), 20))
223+
plt.title(f"Branch PCA, (window: {10**i} - {10**(i+1)} gens)")
224+
plt.show()
225+
```
226+
227+
When selecting a very old window, each individual contributes to its own PC, causing most to be plotted at the origin (0,0). We can see this when inspecting the oldest window's PC scores, which are an identityt matrix. All haplotypes below the first two have 0 entries for the first two PC scores (the two left-most columns).
228+
229+
```python
230+
pctime[7].factors[:20,:10]
231+
```
232+
233+
## Empirical data
234+
Here, we demonstrated using simulated data how SNPs and ARG branches lead to equivalent PCA results. For empirical data, the ancestral states of variant sites are not known a priori, which will in practice often lead to polarisation differences. That may affect the outcome of PCA.
235+
236+
**TODO:** Extend Tutorial to empirical data.

0 commit comments

Comments
 (0)