|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | +import pytest |
| 4 | +import xarray as xr |
| 5 | +from hypothesis import given, settings |
| 6 | +from hypothesis.extra.numpy import arrays |
| 7 | +from sklearn.decomposition import PCA |
| 8 | + |
| 9 | +from sgkit.stats.pc_relate import ( |
| 10 | + _collapse_ploidy, |
| 11 | + _impute_genotype_call_with_variant_mean, |
| 12 | + gramian, |
| 13 | + pc_relate, |
| 14 | +) |
| 15 | +from sgkit.testing import simulate_genotype_call_dataset |
| 16 | + |
| 17 | + |
| 18 | +def test_pc_relate__genotype_inputs_checks() -> None: |
| 19 | + g_wrong_ploidy = simulate_genotype_call_dataset(100, 10, n_ploidy=3) |
| 20 | + with pytest.raises(ValueError, match="PC Relate only works for diploid genotypes"): |
| 21 | + pc_relate(g_wrong_ploidy) |
| 22 | + |
| 23 | + g_non_biallelic = simulate_genotype_call_dataset(100, 10, n_allele=3) |
| 24 | + with pytest.raises( |
| 25 | + ValueError, match="PC Relate only works for biallelic genotypes" |
| 26 | + ): |
| 27 | + pc_relate(g_non_biallelic) |
| 28 | + |
| 29 | + g_no_pcs = simulate_genotype_call_dataset(100, 10) |
| 30 | + with pytest.raises( |
| 31 | + ValueError, match="Input dataset must contain sample_pcs variable" |
| 32 | + ): |
| 33 | + pc_relate(g_no_pcs) |
| 34 | + |
| 35 | + with pytest.raises(ValueError, match="Input dataset must contain call_genotype"): |
| 36 | + pc_relate(g_no_pcs.drop_vars("call_genotype")) |
| 37 | + |
| 38 | + with pytest.raises( |
| 39 | + ValueError, match="Input dataset must contain call_genotype_mask" |
| 40 | + ): |
| 41 | + pc_relate(g_no_pcs.drop_vars("call_genotype_mask")) |
| 42 | + |
| 43 | + |
| 44 | +def test_pc_relate__maf_inputs_checks() -> None: |
| 45 | + g = simulate_genotype_call_dataset(100, 10) |
| 46 | + with pytest.raises(ValueError, match=r"MAF must be between \(0.0, 1.0\)"): |
| 47 | + pc_relate(g, maf=-1) |
| 48 | + with pytest.raises(ValueError, match=r"MAF must be between \(0.0, 1.0\)"): |
| 49 | + pc_relate(g, maf=1.0) |
| 50 | + with pytest.raises(ValueError, match=r"MAF must be between \(0.0, 1.0\)"): |
| 51 | + pc_relate(g, maf=0.0) |
| 52 | + |
| 53 | + |
| 54 | +@given(arrays(np.int8, (3, 5))) |
| 55 | +@settings(max_examples=10) |
| 56 | +def test_gramian_is_symmetric(a: np.ndarray) -> None: |
| 57 | + b = gramian(a) |
| 58 | + assert np.allclose(b, b.T) |
| 59 | + |
| 60 | + |
| 61 | +def test_collapse_ploidy() -> None: |
| 62 | + g = simulate_genotype_call_dataset(1000, 10, missing_pct=0.1) |
| 63 | + assert g.call_genotype.shape == (1000, 10, 2) |
| 64 | + assert g.call_genotype_mask.shape == (1000, 10, 2) |
| 65 | + |
| 66 | + # Test individual cases: |
| 67 | + g.call_genotype.loc[dict(variants=1, samples=1, ploidy=0)] = 1 |
| 68 | + g.call_genotype.loc[dict(variants=1, samples=1, ploidy=1)] = 1 |
| 69 | + g.call_genotype_mask.loc[dict(variants=1, samples=1, ploidy=0)] = 0 |
| 70 | + g.call_genotype_mask.loc[dict(variants=1, samples=1, ploidy=1)] = 0 |
| 71 | + |
| 72 | + g.call_genotype.loc[dict(variants=2, samples=2, ploidy=0)] = 0 |
| 73 | + g.call_genotype.loc[dict(variants=2, samples=2, ploidy=1)] = 1 |
| 74 | + g.call_genotype_mask.loc[dict(variants=2, samples=2, ploidy=0)] = 0 |
| 75 | + g.call_genotype_mask.loc[dict(variants=2, samples=2, ploidy=1)] = 0 |
| 76 | + |
| 77 | + g.call_genotype.loc[dict(variants=3, samples=3, ploidy=0)] = -1 |
| 78 | + g.call_genotype.loc[dict(variants=3, samples=3, ploidy=1)] = 1 |
| 79 | + g.call_genotype_mask.loc[dict(variants=3, samples=3, ploidy=0)] = 1 |
| 80 | + g.call_genotype_mask.loc[dict(variants=3, samples=3, ploidy=1)] = 0 |
| 81 | + |
| 82 | + call_g, call_g_mask = _collapse_ploidy(g) |
| 83 | + assert call_g.shape == (1000, 10) |
| 84 | + assert call_g_mask.shape == (1000, 10) |
| 85 | + assert call_g.isel(variants=1, samples=1) == 2 |
| 86 | + assert call_g.isel(variants=2, samples=2) == 1 |
| 87 | + assert call_g.isel(variants=3, samples=3) == -1 |
| 88 | + assert call_g_mask.isel(variants=1, samples=1) == 0 |
| 89 | + assert call_g_mask.isel(variants=3, samples=3) == 1 |
| 90 | + |
| 91 | + |
| 92 | +def test_impute_genotype_call_with_variant_mean() -> None: |
| 93 | + g = simulate_genotype_call_dataset(1000, 10, missing_pct=0.1) |
| 94 | + call_g, call_g_mask = _collapse_ploidy(g) |
| 95 | + # Test individual cases: |
| 96 | + call_g.loc[dict(variants=2)] = 1 |
| 97 | + call_g.loc[dict(variants=2, samples=1)] = 2 |
| 98 | + call_g_mask.loc[dict(variants=2)] = False |
| 99 | + call_g_mask.loc[dict(variants=2, samples=[0, 9])] = True |
| 100 | + imputed_call_g = _impute_genotype_call_with_variant_mean(call_g, call_g_mask) |
| 101 | + assert imputed_call_g.isel(variants=2, samples=1) == 2 |
| 102 | + assert (imputed_call_g.isel(variants=2, samples=slice(2, 9)) == 1).all() |
| 103 | + assert (imputed_call_g.isel(variants=2, samples=[0, 9]) == (7 + 2) / 8).all() |
| 104 | + |
| 105 | + |
| 106 | +def test_pc_relate__values_within_range() -> None: |
| 107 | + n_samples = 100 |
| 108 | + g = simulate_genotype_call_dataset(1000, n_samples) |
| 109 | + call_g, _ = _collapse_ploidy(g) |
| 110 | + pcs = PCA(n_components=2, svd_solver="full").fit_transform(call_g.T) |
| 111 | + g["sample_pcs"] = (("components", "samples"), pcs.T) |
| 112 | + phi = pc_relate(g) |
| 113 | + assert phi.pc_relate_phi.shape == (n_samples, n_samples) |
| 114 | + data_np = phi.pc_relate_phi.data.compute() # to be able to use fancy indexing below |
| 115 | + upper_phi = data_np[np.triu_indices_from(data_np, 1)] |
| 116 | + assert (upper_phi > -0.5).all() and (upper_phi < 0.5).all() |
| 117 | + |
| 118 | + |
| 119 | +def test_pc_relate__identical_sample_should_be_05() -> None: |
| 120 | + n_samples = 100 |
| 121 | + g = simulate_genotype_call_dataset(1000, n_samples, missing_pct=0.1) |
| 122 | + call_g, _ = _collapse_ploidy(g) |
| 123 | + pcs = PCA(n_components=2, svd_solver="full").fit_transform(call_g.T) |
| 124 | + g["sample_pcs"] = (("components", "samples"), pcs.T) |
| 125 | + # Add identical sample |
| 126 | + g.call_genotype.loc[dict(samples=8)] = g.call_genotype.isel(samples=0) |
| 127 | + phi = pc_relate(g) |
| 128 | + assert phi.pc_relate_phi.shape == (n_samples, n_samples) |
| 129 | + assert np.allclose(phi.pc_relate_phi.isel(sample_x=8, sample_y=0), 0.5, atol=0.1) |
| 130 | + |
| 131 | + |
| 132 | +def test_pc_relate__parent_child_relationship() -> None: |
| 133 | + # Eric's source: https://github.com/pystatgen/sgkit/pull/228#discussion_r487436876 |
| 134 | + |
| 135 | + # Create a dataset that is 2/3 founders and 1/3 progeny |
| 136 | + seed = 1 |
| 137 | + rs = np.random.RandomState(seed) |
| 138 | + ds = simulate_genotype_call_dataset(1000, 300, seed=seed) |
| 139 | + ds["sample_type"] = xr.DataArray( |
| 140 | + np.repeat(["mother", "father", "child"], 100), dims="samples" |
| 141 | + ) |
| 142 | + sample_groups = ds.groupby("sample_type").groups |
| 143 | + |
| 144 | + def simulate_new_generation(ds: xr.Dataset) -> xr.Dataset: |
| 145 | + # Generate progeny genotypes as a combination of randomly |
| 146 | + # selected haplotypes from each parents |
| 147 | + idx = sample_groups["mother"] + sample_groups["father"] |
| 148 | + gt = ds.call_genotype.isel(samples=idx).values |
| 149 | + idx = rs.randint(0, 2, size=gt.shape[:2]) |
| 150 | + # Collapse to haplotype across ploidy dim using indexer |
| 151 | + # * shape = (samples, variants) |
| 152 | + ht = gt[np.ix_(*map(range, gt.shape[:2])) + (idx,)].T |
| 153 | + gt_child = np.stack([ht[sample_groups[t]] for t in ["mother", "father"]]).T |
| 154 | + ds["call_genotype"].values = np.concatenate((gt, gt_child), axis=1) |
| 155 | + return ds |
| 156 | + |
| 157 | + # Redefine the progeny genotypes |
| 158 | + ds = simulate_new_generation(ds) |
| 159 | + |
| 160 | + # Infer kinship |
| 161 | + call_g, _ = _collapse_ploidy(ds) |
| 162 | + pcs = PCA(n_components=2, svd_solver="full").fit_transform(call_g.T) |
| 163 | + ds["sample_pcs"] = (("components", "samples"), pcs.T) |
| 164 | + ds["pc_relate_phi"] = pc_relate(ds)["pc_relate_phi"].compute() |
| 165 | + |
| 166 | + # Check that all coefficients are in expected ranges |
| 167 | + cts = ( |
| 168 | + ds["pc_relate_phi"] |
| 169 | + .to_series() |
| 170 | + .reset_index() |
| 171 | + .pipe(lambda df: df.loc[df.sample_x >= df.sample_y]["pc_relate_phi"]) |
| 172 | + .pipe( |
| 173 | + pd.cut, |
| 174 | + bins=[p for phi in [0, 0.25, 0.5] for p in [phi - 0.1, phi + 0.1]], |
| 175 | + labels=[ |
| 176 | + "unrelated", |
| 177 | + "unclassified", |
| 178 | + "parent/child", |
| 179 | + "unclassified", |
| 180 | + "self", |
| 181 | + ], |
| 182 | + ordered=False, |
| 183 | + ) |
| 184 | + .value_counts() |
| 185 | + ) |
| 186 | + assert cts["parent/child"] == len(sample_groups["child"]) * 2 |
| 187 | + assert cts["self"] == ds.dims["samples"] |
| 188 | + assert cts["unclassified"] == 0 |
0 commit comments