Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

randomized svd draft #3008

Draft
wants to merge 32 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
1f45245
randomized svd draft
hanbin973 Oct 3, 2024
e408ab3
modified api remove scipy
hanbin973 Oct 4, 2024
a176132
remove scipy
hanbin973 Oct 7, 2024
8c662c8
correct docstring and comments
hanbin973 Oct 7, 2024
aa13613
space remove
hanbin973 Oct 7, 2024
5bf405a
rng to random seed
hanbin973 Oct 8, 2024
6e415e5
add windows feature
hanbin973 Oct 8, 2024
45ac61e
output shape change when windows=wholegnome
hanbin973 Oct 11, 2024
2cdb9dd
make centre work with nodes
hanbin973 Oct 11, 2024
1f194aa
remove redundant options from internal functions
hanbin973 Oct 11, 2024
fdc5842
start at testing
petrelharp Oct 13, 2024
c0a2854
change variable name to n_* to num_*
hanbin973 Oct 13, 2024
667d60f
return range sketch matrix Q
hanbin973 Oct 13, 2024
36c10e9
fix random sketch option to handle None
hanbin973 Oct 13, 2024
0ac88b8
random_sketch needs windows specified
hanbin973 Oct 13, 2024
a6fa8ab
input checking for range_sketch to align with windows
hanbin973 Oct 13, 2024
791c7da
docstring change to reflect range_sketch
hanbin973 Oct 13, 2024
2f4ce2b
linting has a bug; when converting lambda to ordinary function defini…
hanbin973 Oct 14, 2024
be2f736
now output is a dataclass
hanbin973 Oct 17, 2024
bcbbcf6
docstring change
hanbin973 Oct 17, 2024
1a8ff7a
change variable name of PCAResult class
hanbin973 Oct 18, 2024
af16340
move internal function of PCA out
hanbin973 Oct 18, 2024
e81db15
function rearrangement
hanbin973 Oct 22, 2024
277cfc2
terminology change loaindgs -> factor
hanbin973 Nov 15, 2024
be715de
time resolved feature
hanbin973 Nov 16, 2024
d3e6c89
Update python/tskit/trees.py
hanbin973 Nov 17, 2024
49fe716
Update python/tskit/trees.py
hanbin973 Nov 17, 2024
d217fc7
Update python/tskit/trees.py
hanbin973 Nov 17, 2024
89e3b27
Update python/tskit/trees.py
hanbin973 Nov 17, 2024
81cbecf
remove comments; eigen_values -> eigenvalues
hanbin973 Nov 18, 2024
7ca6452
support for subset of samples and individuals in a tree
hanbin973 Nov 20, 2024
587409b
add time assertion
hanbin973 Dec 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions python/tskit/trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from typing import NamedTuple

import numpy as np
import scipy.sparse

import _tskit
import tskit
Expand Down Expand Up @@ -8592,6 +8593,156 @@ def genetic_relatedness_vector(
)
return out

def pca(
self,
n_components: int = 10,
iterated_power: int = 3,
n_oversamples: int = 10,
indices: np.ndarray = None,
petrelharp marked this conversation as resolved.
Show resolved Hide resolved
centre: bool = True,
windows = None,
random_state: np.random.Generator = None,
petrelharp marked this conversation as resolved.
Show resolved Hide resolved
):
"""
Run randomized singular value decomposition (rSVD) to obtain principal components.
API partially adopted from `scikit-learn`:
https://scikit-learn.org/dev/modules/generated/sklearn.decomposition.PCA.html

:param int n_components: Number of principal components
:param int iterated_power: Number of power iteration of range finder
:param int n_oversamples: Number of additional test vectors
:param np.ndarray indices: Indcies of individuals to perform rSVD
:param bool centre: Centre the genetic relatedness matrix
:param windows: ???
:param np.random.Generator random_state: Random number generator
"""

def _rand_pow_range_finder(
operator: Callable,
operator_dim: int,
rank: int,
depth: int,
num_vectors: int,
rng: np.random.Generator,
) -> np.ndarray:
"""
Algorithm 9 in https://arxiv.org/pdf/2002.01387
"""
assert num_vectors >= rank > 0
test_vectors = rng.normal(size=(operator_dim, num_vectors))
Q = test_vectors
for i in range(depth):
Q = np.linalg.qr(Q).Q
Q = operator(Q)
Q = np.linalg.qr(Q).Q
return Q[:, :rank]

def _rand_svd(
operator: Callable,
operator_dim: int,
rank: int,
depth: int,
num_vectors: int,
rng: np.random.Generator,
) -> (np.ndarray, np.ndarray, np.ndarray):
"""
Algorithm 8 in https://arxiv.org/pdf/2002.01387
"""
assert num_vectors >= rank > 0
Q = _rand_pow_range_finder(
operator,
operator_dim,
num_vectors,
depth,
num_vectors,
rng
)
C = operator(Q).T
U_hat, D, V = np.linalg.svd(C, full_matrices=False)
U = Q @ U_hat
return U[:,:rank], D[:rank], V[:rank]

def _genetic_relatedness_vector(
ts: tskit.Treesequence,
arr: np.ndarray,
rows: np.ndarray,
cols: np.ndarray,
centre: bool = False,
windows = None,
) -> np.ndarray:
"""
Wrapper around `tskit.TreeSequence.genetic_relatedness_vector` to support centering in respect to individuals.
Multiplies an array to the genetic relatedness matrix of :class:`tskit.TreeSequence`.

:param tskit.TreeSequence ts: A tree sequence.
:param numpy.ndarray arr: The array to multiply. Either a vector or a matrix.
:param numpy.ndarray rows: Index of rows of the genetic relatedness matrix to be selected.
:param numpy.ndarray cols: Index of cols of the genetic relatedness matrix to be selected. The size should match the row length of `arr`.
:param bool centre: Centre the genetic relatedness matrix. Centering happens respect to the `rows` and `cols`.
:param windows: An increasing list of breakpoints between the windows to compute the genetic relatedness matrix in.
:return: An array that is the matrix-array product of the genetic relatedness matrix and the array.
:rtype: `np.ndarray`
"""

# maps samples to individuals
def sample_individual_sparray(ts: tskit.TreeSequence) -> scipy.sparse.sparray:
samples_individual = ts.nodes_individual[ts.samples()]
return scipy.sparse.csr_array(
(
np.ones(ts.num_samples),
(np.arange(ts.num_samples), samples_individual)
),
shape=(ts.num_samples, ts.num_individuals)
)

# maps values in idx to num_individuals
def individual_idx_sparray(n: int, idx: np.ndarray) -> scipy.sparse.sparray:
return scipy.sparse.csr_array(
(
np.ones(idx.size),
(idx, np.arange(idx.size))
),
shape=(n, idx.size)
)

assert cols.size == arr.shape[0], "Dimension mismatch"
# centering
x = arr - arr.mean(axis=0) if centre else arr # centering within index in rows
x = individual_idx_sparray(ts.num_individuals, cols).dot(x)
x = sample_individual_sparray(ts).dot(x)
x = ts.genetic_relatedness_vector(W=x, windows=windows, mode="branch", centre=False)
x = sample_individual_sparray(ts).T.dot(x)
x = individual_idx_sparray(ts.num_individuals, rows).T.dot(x)
petrelharp marked this conversation as resolved.
Show resolved Hide resolved
x = x - x.mean(axis=0) if centre else x # centering within index in cols

return x


if indices is None: indices = np.array([i.id for i in self.individuals()])
if random_state is None: random_state = np.random.default_rng()

def _G(x):
petrelharp marked this conversation as resolved.
Show resolved Hide resolved
return _genetic_relatedness_vector(
self.ts,
x,
indices,
indices,
centre,
windows
)

U, D, _ = _rand_svd(
petrelharp marked this conversation as resolved.
Show resolved Hide resolved
operator=_G,
operator_dim=indices.size,
rank=n_components,
depth=iterated_power,
num_vectors=n_components+n_oversamples,
rng=random_state
)

return U, D


def trait_covariance(self, W, windows=None, mode="site", span_normalise=True):
"""
Computes the mean squared covariances between each of the columns of ``W``
Expand Down Expand Up @@ -10171,3 +10322,4 @@ def write_ms(
)
else:
print(file=output)

Loading