Skip to content

Commit a09b28d

Browse files
authored
Merge branch 'master' into add-As1
2 parents 97017b4 + 1da4a14 commit a09b28d

File tree

4 files changed

+120
-2
lines changed

4 files changed

+120
-2
lines changed

malariagen_data/anoph/fst.py

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import warnings
12
from typing import Tuple, Optional
23

34
import numpy as np
@@ -43,6 +44,8 @@ def _fst_gwss(
4344
inline_array,
4445
chunks,
4546
clip_min,
47+
min_snps_threshold,
48+
window_adjustment_factor,
4649
):
4750
# Compute allele counts.
4851
ac1 = self.snp_allele_counts(
@@ -81,6 +84,24 @@ def _fst_gwss(
8184
chunks=chunks,
8285
).compute()
8386

87+
n_snps = len(pos)
88+
if n_snps < min_snps_threshold:
89+
raise ValueError(
90+
f"Too few SNP sites ({n_snps}) available for Fst GWSS. "
91+
f"At least {min_snps_threshold} sites are required. "
92+
"Try a larger genomic region or different site selection criteria."
93+
)
94+
if window_size >= n_snps:
95+
adjusted_window_size = max(1, n_snps // window_adjustment_factor)
96+
warnings.warn(
97+
f"window_size ({window_size}) is >= the number of SNP sites "
98+
f"available ({n_snps}); automatically adjusting window_size to "
99+
f"{adjusted_window_size} (= {n_snps} // {window_adjustment_factor}).",
100+
UserWarning,
101+
stacklevel=2,
102+
)
103+
window_size = adjusted_window_size
104+
84105
with self._spinner(desc="Compute Fst"):
85106
with np.errstate(divide="ignore", invalid="ignore"):
86107
fst = allel.moving_hudson_fst(ac1, ac2, size=window_size)
@@ -96,8 +117,23 @@ def _fst_gwss(
96117
@doc(
97118
summary="""
98119
Run a Fst genome-wide scan to investigate genetic differentiation
99-
between two cohorts.
120+
between two cohorts. If window_size is >= the number of available
121+
SNP sites, a UserWarning is issued and window_size is automatically
122+
adjusted to number_of_snps // window_adjustment_factor. A ValueError
123+
is raised if the number of available SNP sites is below
124+
min_snps_threshold.
100125
""",
126+
parameters=dict(
127+
min_snps_threshold="""
128+
Minimum number of SNP sites required. If fewer sites are
129+
available a ValueError is raised.
130+
""",
131+
window_adjustment_factor="""
132+
If window_size is >= the number of available SNP sites,
133+
window_size is automatically set to
134+
number_of_snps // window_adjustment_factor.
135+
""",
136+
),
101137
returns=dict(
102138
x="An array containing the window centre point genomic positions",
103139
fst="An array with Fst statistic values for each window.",
@@ -123,6 +159,8 @@ def fst_gwss(
123159
inline_array: base_params.inline_array = base_params.inline_array_default,
124160
chunks: base_params.chunks = base_params.native_chunks,
125161
clip_min: fst_params.clip_min = 0.0,
162+
min_snps_threshold: fst_params.min_snps_threshold = 1000,
163+
window_adjustment_factor: fst_params.window_adjustment_factor = 10,
126164
) -> Tuple[np.ndarray, np.ndarray]:
127165
# Change this name if you ever change the behaviour of this function, to
128166
# invalidate any previously cached data.
@@ -147,7 +185,13 @@ def fst_gwss(
147185
results = self.results_cache_get(name=name, params=params)
148186

149187
except CacheMiss:
150-
results = self._fst_gwss(**params, inline_array=inline_array, chunks=chunks)
188+
results = self._fst_gwss(
189+
**params,
190+
inline_array=inline_array,
191+
chunks=chunks,
192+
min_snps_threshold=min_snps_threshold,
193+
window_adjustment_factor=window_adjustment_factor,
194+
)
151195
self.results_cache_set(name=name, params=params, results=results)
152196

153197
x = results["x"]

malariagen_data/anoph/fst_params.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,22 @@
3434
""",
3535
]
3636

37+
min_snps_threshold: TypeAlias = Annotated[
38+
int,
39+
"""
40+
Minimum number of SNP sites required for the Fst GWSS computation. If
41+
fewer sites are available, a ValueError is raised.
42+
""",
43+
]
44+
45+
window_adjustment_factor: TypeAlias = Annotated[
46+
int,
47+
"""
48+
If window_size is >= the number of available SNP sites, the window_size
49+
is automatically adjusted to number_of_snps // window_adjustment_factor.
50+
""",
51+
]
52+
3753
annotation: TypeAlias = Annotated[
3854
Optional[Literal["standard error", "Z score", "lower triangle"]],
3955
"""

malariagen_data/anopheles.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -970,6 +970,12 @@ def plot_ihs_gwss_track(
970970
inline_array=inline_array,
971971
)
972972

973+
if len(x) == 0:
974+
raise ValueError(
975+
"No iHS values remain after filtering. "
976+
"Try relaxing filter_min_maf or min_ehh parameters."
977+
)
978+
973979
# determine X axis range
974980
x_min = x[0]
975981
x_max = x[-1]
@@ -1494,6 +1500,12 @@ def plot_xpehh_gwss_track(
14941500
inline_array=inline_array,
14951501
)
14961502

1503+
if len(x) == 0:
1504+
raise ValueError(
1505+
"No XP-EHH values remain after filtering. "
1506+
"Try relaxing filter_min_maf or min_ehh parameters."
1507+
)
1508+
14971509
# determine X axis range
14981510
x_min = x[0]
14991511
x_max = x[-1]

tests/anoph/test_fst.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,52 @@ def test_fst_gwss(fixture, api: AnophelesFstAnalysis):
163163
assert isinstance(fig, bokeh.models.GridPlot)
164164

165165

166+
@parametrize_with_cases("fixture,api", cases=".")
167+
def test_fst_gwss_window_size_too_large(fixture, api: AnophelesFstAnalysis):
168+
# When window_size exceeds available SNPs, a UserWarning must be issued and
169+
# the function must still return a valid result using the adjusted window_size.
170+
all_sample_sets = api.sample_sets()["sample_set"].to_list()
171+
all_countries = api.sample_metadata()["country"].dropna().unique().tolist()
172+
countries = np.random.choice(all_countries, size=2, replace=False).tolist()
173+
cohort1_query = f"country == {countries[0]!r}"
174+
cohort2_query = f"country == {countries[1]!r}"
175+
with pytest.warns(UserWarning, match="window_size"):
176+
x, fst = api.fst_gwss(
177+
contig=str(np.random.choice(api.contigs)),
178+
sample_sets=all_sample_sets,
179+
cohort1_query=cohort1_query,
180+
cohort2_query=cohort2_query,
181+
site_mask=str(np.random.choice(api.site_mask_ids)),
182+
window_size=10_000_000, # far larger than any fixture SNP count
183+
min_cohort_size=1,
184+
)
185+
assert isinstance(x, np.ndarray)
186+
assert isinstance(fst, np.ndarray)
187+
assert len(x) > 0
188+
assert x.shape == fst.shape
189+
190+
191+
@parametrize_with_cases("fixture,api", cases=".")
192+
def test_fst_gwss_too_few_snps(fixture, api: AnophelesFstAnalysis):
193+
# When min_snps_threshold exceeds available SNPs, a ValueError must be raised.
194+
all_sample_sets = api.sample_sets()["sample_set"].to_list()
195+
all_countries = api.sample_metadata()["country"].dropna().unique().tolist()
196+
countries = np.random.choice(all_countries, size=2, replace=False).tolist()
197+
cohort1_query = f"country == {countries[0]!r}"
198+
cohort2_query = f"country == {countries[1]!r}"
199+
with pytest.raises(ValueError, match="Too few SNP sites"):
200+
api.fst_gwss(
201+
contig=str(np.random.choice(api.contigs)),
202+
sample_sets=all_sample_sets,
203+
cohort1_query=cohort1_query,
204+
cohort2_query=cohort2_query,
205+
site_mask=str(np.random.choice(api.site_mask_ids)),
206+
window_size=100,
207+
min_cohort_size=1,
208+
min_snps_threshold=10_000_000, # far larger than any fixture SNP count (~28k-70k)
209+
)
210+
211+
166212
@parametrize_with_cases("fixture,api", cases=".")
167213
def test_average_fst(fixture, api: AnophelesFstAnalysis):
168214
# Set up test parameters.

0 commit comments

Comments
 (0)