diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d64710..9354941 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 tutorial page keeps the published vignette's image on R's side, and the PBMC 3k comparison's numbers do not change. +- **`composition_test(sample_col=)` tests per-sample proportions (#144).** The Fisher + test counts every cell as a replicate, so with thousands of cells nearly every + difference is significant, including one that is only donor-to-donor variation. In a + simulation with no condition effect (12 donors, 6 against 6, each with its own + cell-type proportions) at least one cell type came out BH-significant in 35 of 40 + runs. The unit that replicates is the donor. + - `sample_col` names the sample each cell came from. Each group's proportion in each + sample is compared between the two levels with a two-sided Mann-Whitney test, BH + adjusted across groups, as before. In the same simulation it reports a significant + type in 1 of 40 runs, and it still finds a type that is three times as common in + one condition in 10 of 10. + - `prop_` is then the mean of the per-sample proportions. `odds_ratio` and + `chisq_p` are cell-level quantities and are not reported, and `df.attrs` carries + `method`, `sample_col` and `n_samples`. + - A sample in both levels is an error, and so is a level none of whose cells has a + sample. A cell with no sample is left out. A design too small to reach significance, + such as three samples against three, whose smallest possible p is 0.1, warns. + - Without `sample_col` nothing changes except the docstring, which now says what the + p-values assume, and `df.attrs['method']`. + ### Removed - **Sixteen names from `truecell.generics`, none of which ever did anything (#142).** diff --git a/skills/truecell-spatial/SKILL.md b/skills/truecell-spatial/SKILL.md index 9a86b5c..6203bed 100644 --- a/skills/truecell-spatial/SKILL.md +++ b/skills/truecell-spatial/SKILL.md @@ -97,11 +97,20 @@ d = truecell.nearest_neighbor_distance(obj, group_by="cell_type", reference="Ast n = truecell.local_neighborhood(obj, group_by="cell_type", k=10) # Is a type over- or under-represented between conditions? -c = truecell.composition_test(obj, group_by="cell_type", split_by="condition") +c = truecell.composition_test(obj, group_by="cell_type", split_by="condition", + sample_col="donor") ``` All three return DataFrames and leave the object alone. +`composition_test`'s p-values need `sample_col` whenever a condition has more than one +donor. Without it every cell is a replicate, so with thousands of cells nearly every +type comes out significant, including a difference that is only donor-to-donor +variation: in a simulation with no condition effect and six donors a side, at least one +type was called significant in 35 of 40 runs. With it the test compares per-sample +proportions. Each sample must sit inside one condition, and with three donors a side no +type can reach p < 0.05, which the function warns about. + ## Niches ```python diff --git a/skills/truecell/reference/api-map.md b/skills/truecell/reference/api-map.md index bf7c07e..4aa4f7f 100644 --- a/skills/truecell/reference/api-map.md +++ b/skills/truecell/reference/api-map.md @@ -284,7 +284,7 @@ build_niche_assay(seurat, group_by, image=None, k=20, niches=4, assay_name="nich find_spatially_variable_features(seurat, features=None, method="moransi", k=10, weights="inverse_square", assay=None, layer="scale.data", image=None, r_metric=5.0, bandwidth=1.0) -> pd.DataFrame -composition_test(seurat, group_by, split_by, reference=None) -> pd.DataFrame +composition_test(seurat, group_by, split_by, reference=None, sample_col=None) -> pd.DataFrame ``` The loaders' `fov` names the one image they build, as Seurat's `fov` argument does diff --git a/tests/test_composition_samples.py b/tests/test_composition_samples.py new file mode 100644 index 0000000..e496b9b --- /dev/null +++ b/tests/test_composition_samples.py @@ -0,0 +1,167 @@ +"""``composition_test`` and its unit of replication. + +The Fisher test per group counts every cell as an independent observation. With +thousands of cells nearly every difference is significant, including one that is +only donor-to-donor variation: in a simulation with no condition effect at all +(12 donors, 6 against 6, each with its own cell-type proportions) the default +reported a significant cell type in 35 of 40 runs. ``sample_col`` gives the test one +observation per sample, which is what replicates. + +The function reads only ``meta_data``, so the simulations use a stand-in for the +object and run in a fraction of a second. +""" +import warnings +from math import comb +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest +from scipy.stats import mannwhitneyu + +from truecell import composition_test + + +def _simulate(seed, n_types=6, per_donor=600, n_donors=12, effect=None): + """Donors with their own cell-type proportions around uniform; half in each condition.""" + rng = np.random.default_rng(seed) + rows = [] + for d in range(n_donors): + p = rng.dirichlet(np.full(n_types, 15.0)) + if effect is not None and d >= n_donors // 2: + p = p * effect + p = p / p.sum() + rows += [(f"d{d}", "A" if d < n_donors // 2 else "B", f"T{t}") + for t in rng.choice(n_types, per_donor, p=p)] + md = pd.DataFrame(rows, columns=["donor", "cond", "ct"], + index=[f"c{i}" for i in range(len(rows))]) + return SimpleNamespace(meta_data=md) + + +def test_cells_as_replicates_find_differences_that_are_only_donor_variation(): + """The premise: with no condition effect, the default reports one almost every time, + and `sample_col` about as often as its nominal 5%.""" + cell = sample = 0 + for seed in range(30): + obj = _simulate(seed) + cell += bool((composition_test(obj, "ct", "cond")["padj"] < 0.05).any()) + sample += bool((composition_test(obj, "ct", "cond", sample_col="donor")["padj"] < 0.05).any()) + # The simulation has to be able to show the problem, or the second assertion is empty. + assert cell >= 20, cell + assert sample <= 4, sample + + +def test_a_real_difference_between_donors_is_still_found(): + """Not merely conservative: a cell type three times as common in one condition.""" + found = 0 + for seed in range(10): + obj = _simulate(100 + seed, effect=np.array([3, 1, 1, 1, 1, 1])) + res = composition_test(obj, "ct", "cond", sample_col="donor").set_index("group") + found += bool(res.loc["T0", "padj"] < 0.05) and res.loc["T0", "enriched_in"] == "B" + assert found >= 9, found + + +def test_the_sample_level_table_is_the_mann_whitney_of_per_sample_proportions(): + rng = np.random.default_rng(3) + rows = [] + # 4 donors a side; group "x" is rarer in B, "y" commoner, "z" the same + for d in range(8): + cond = "A" if d < 4 else "B" + w = {"x": 0.5 if cond == "A" else 0.2, "y": 0.2 if cond == "A" else 0.5, "z": 0.3} + rows += [(f"d{d}", cond, g) for g in rng.choice(list(w), 80 + 10 * d, p=list(w.values()))] + md = pd.DataFrame(rows, columns=["donor", "cond", "ct"]) + res = composition_test(SimpleNamespace(meta_data=md), "ct", "cond", sample_col="donor", + reference="A").set_index("group") + + props = pd.crosstab(md["donor"], md["ct"], normalize="index") + a, b = props.loc[[f"d{i}" for i in range(4)]], props.loc[[f"d{i}" for i in range(4, 8)]] + for group in "xyz": + want = mannwhitneyu(b[group], a[group], alternative="two-sided").pvalue + assert res.loc[group, "p"] == pytest.approx(want, rel=1e-12) + assert res.loc[group, "prop_A"] == pytest.approx(a[group].mean()) # mean of the samples, + assert res.loc[group, "prop_B"] == pytest.approx(b[group].mean()) # not the pooled cells + assert res.loc[group, "log2_ratio"] == pytest.approx(np.log2(b[group].mean() / a[group].mean())) + cells = md[md["ct"] == group] + assert res.loc[group, "n_A"] == (cells["cond"] == "A").sum() + assert res.loc[group, "n_B"] == (cells["cond"] == "B").sum() + assert res.loc["x", "enriched_in"] == "A" and res.loc["y", "enriched_in"] == "B" + assert (res["padj"] >= res["p"] - 1e-12).all() + assert list(res["log2_ratio"]) == sorted(res["log2_ratio"], reverse=True) + + +def test_the_sample_level_table_leaves_out_what_only_cells_can_give(): + res = composition_test(_simulate(0), "ct", "cond", sample_col="donor") + assert "odds_ratio" not in res.columns + assert "chisq_p" not in res.attrs + assert res.attrs["method"] == "mannwhitneyu" and res.attrs["sample_col"] == "donor" + assert res.attrs["n_samples"] == {"A": 6, "B": 6} + assert {"group", "log2_ratio", "p", "padj", "sig", "enriched_in"} <= set(res.columns) + + +def test_the_default_is_the_same_cell_level_test_as_before(): + res = composition_test(_simulate(0), "ct", "cond") + assert "odds_ratio" in res.columns and "chisq_p" in res.attrs + assert res.attrs["method"] == "fisher_exact" and "sample_col" not in res.attrs + + +def test_a_sample_in_both_levels_is_an_error(): + obj = _simulate(0) + obj.meta_data.loc[obj.meta_data["donor"] == "d0", "cond"] = ["A", "B"] * 300 + with pytest.raises(ValueError, match=r"must sit inside one level.*\['d0'\]"): + composition_test(obj, "ct", "cond", sample_col="donor") + + +def test_a_cell_with_no_sample_is_left_out_whatever_the_pandas_version(): + """Left to `astype(str)` it is a sample called "nan" on pandas 2 and vanishes on pandas 3, + and either way its cell would still be counted in `n_`.""" + whole = _simulate(2) + with_gaps = SimpleNamespace(meta_data=whole.meta_data.copy()) + gaps = with_gaps.meta_data.index[::7] # every seventh cell has no sample + with_gaps.meta_data.loc[gaps, "donor"] = np.nan + left_in = SimpleNamespace(meta_data=whole.meta_data.drop(index=gaps)) + got = composition_test(with_gaps, "ct", "cond", sample_col="donor") + want = composition_test(left_in, "ct", "cond", sample_col="donor") + pd.testing.assert_frame_equal(got, want) + assert got.attrs["n_samples"] == {"A": 6, "B": 6} + assert got[["n_A", "n_B"]].to_numpy().sum() == len(left_in.meta_data) + + +def test_a_level_whose_cells_have_no_sample_is_an_error_not_a_scipy_one(): + obj = _simulate(0) + obj.meta_data["donor"] = obj.meta_data["donor"].where(obj.meta_data["cond"] == "A") # B has none + with pytest.raises(ValueError, match="No sample in split_by level 'B'"): + composition_test(obj, "ct", "cond", sample_col="donor") + + +def test_an_unknown_sample_column_is_a_keyerror(): + with pytest.raises(KeyError, match="'nope' not in meta_data"): + composition_test(_simulate(0), "ct", "cond", sample_col="nope") + + +@pytest.mark.parametrize("n_donors,warns", [(6, True), (7, True), (8, False), (12, False)]) +def test_too_few_samples_to_reach_significance_warns(n_donors, warns): + """Three against three cannot give a p below 0.1; four against four can give 0.029.""" + assert (2 / comb(n_donors, n_donors // 2) >= 0.05) == warns # the premise, from the formula + obj = _simulate(0, n_donors=n_donors, per_donor=100) + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + composition_test(obj, "ct", "cond", sample_col="donor") + few = [w for w in seen if "smallest p-value a Mann-Whitney test" in str(w.message)] + assert bool(few) == warns + + +def test_a_group_the_same_in_every_sample_gets_p_one_and_does_not_poison_the_rest(): + """scipy returns NaN when every value is identical, and one NaN makes every + adjusted p-value NaN.""" + rng = np.random.default_rng(5) + rows = [] + for d in range(8): + cond = "A" if d < 4 else "B" + rows += [(f"d{d}", cond, "same")] * 20 # exactly 20% of every sample + rows += [(f"d{d}", cond, g) for g in rng.choice(["x", "y"], 80)] + md = pd.DataFrame(rows, columns=["donor", "cond", "ct"]) + assert pd.crosstab(md["donor"], md["ct"], normalize="index")["same"].nunique() == 1 # the premise + res = composition_test(SimpleNamespace(meta_data=md), "ct", "cond", + sample_col="donor").set_index("group") + assert res.loc["same", "p"] == 1.0 + assert not res["p"].isna().any() and not res["padj"].isna().any() diff --git a/truecell/composition.py b/truecell/composition.py index 95f7e2b..c487ee9 100644 --- a/truecell/composition.py +++ b/truecell/composition.py @@ -5,11 +5,17 @@ *directional* log2 proportion ratio (unambiguous), a per-group Fisher exact test (group vs rest), BH-adjusted q-values, and the overall chi-square. +The Fisher test counts every cell as a replicate, which is only right for a single +sample per condition. With several donors per condition, pass ``sample_col`` and +the test compares per-sample proportions instead. + Depends only on scipy (a core dependency); BH is computed inline so no statsmodels requirement. """ from __future__ import annotations +import warnings +from math import comb from typing import Optional import numpy as np @@ -31,11 +37,88 @@ def _bh(pvals: np.ndarray) -> np.ndarray: return out +def _finish(df: pd.DataFrame, ref: str, test: str) -> pd.DataFrame: + """BH-adjust, label, direction and order a table of per-group tests.""" + df["padj"] = _bh(df["p"].to_numpy()) + bins = [-np.inf, 0.001, 0.01, 0.05, np.inf] + df["sig"] = pd.cut(df["padj"], bins, labels=["***", "**", "*", "ns"]) + df["enriched_in"] = np.where(df["log2_ratio"] > 0, test, ref) + return df.sort_values("log2_ratio", ascending=False).reset_index(drop=True) + + +def _across_samples(md, group_by, split_by, sample_col, ref, test) -> pd.DataFrame: + """The per-sample version: one observation per sample, not one per cell. + + Each group's proportion in each sample is compared between the two levels with a + two-sided Mann-Whitney U test. A cell with no sample is left out, up front: left to + ``astype(str)`` it would become a sample called "nan" on pandas 2 and vanish on + pandas 3. + """ + keep = md[sample_col].notna() + cond = md.loc[keep, split_by].astype(str) + sample = md.loc[keep, sample_col].astype(str) + group = md.loc[keep, group_by].astype(str) + # A sample is one donor, so it sits in one condition; if it does not, the + # comparison is not between samples at all. + spans = cond.groupby(sample).nunique() + spans = spans[spans > 1].index.tolist() + if spans: + raise ValueError( + f"sample_col='{sample_col}' must sit inside one level of split_by='{split_by}', " + f"but {spans[:5]} have cells in both." + ) + counts = pd.crosstab(sample, group) + cells = pd.crosstab(group, cond) # the cells used, group x level + props = counts.div(counts.sum(axis=1), axis=0) + level = cond.groupby(sample).first().reindex(props.index) + in_ref, in_test = (level == ref).to_numpy(), (level == test).to_numpy() + n_ref, n_test = int(in_ref.sum()), int(in_test.sum()) + if not (n_ref and n_test): + empty = ref if not n_ref else test + raise ValueError( + f"No sample in split_by level '{empty}': sample_col='{sample_col}' is missing " + f"for every one of its cells." + ) + + # The smallest p an exact two-sided test can give, with every sample of one level + # above every sample of the other: 2 / C(n1 + n2, n1). Past 0.05 nothing can come + # out significant, however large the difference. + p_min = 2 / comb(n_ref + n_test, n_ref) + if p_min >= 0.05: + warnings.warn( + f"{n_test} samples against {n_ref}: the smallest p-value a Mann-Whitney test " + f"can give is {p_min:.3g}, so no group can come out significant. The log2 " + f"ratios are still a ranking.", + stacklevel=3, + ) + + rows = [] + for grp in counts.columns: + x_test, x_ref = props.loc[in_test, grp].to_numpy(), props.loc[in_ref, grp].to_numpy() + p = float(stats.mannwhitneyu(x_test, x_ref, alternative="two-sided").pvalue) + # Identical in every sample: scipy returns NaN, and one NaN would turn every + # adjusted p-value into NaN. There is nothing to tell the levels apart by. + p = 1.0 if np.isnan(p) else p + prop_test, prop_ref = x_test.mean(), x_ref.mean() + with np.errstate(divide="ignore"): + log2 = np.log2(prop_test / prop_ref) if prop_ref else np.nan + rows.append({ + "group": grp, f"n_{ref}": cells.loc[grp, ref], f"n_{test}": cells.loc[grp, test], + f"prop_{ref}": prop_ref, f"prop_{test}": prop_test, + "log2_ratio": log2, "p": p, + }) + df = _finish(pd.DataFrame(rows), ref, test) + df.attrs.update(reference=ref, test=test, method="mannwhitneyu", sample_col=sample_col, + n_samples={ref: n_ref, test: n_test}) + return df + + def composition_test( seurat, group_by: str, split_by: str, reference: Optional[str] = None, + sample_col: str | None = None, ) -> pd.DataFrame: """Directional abundance test of ``group_by`` categories across ``split_by``. @@ -45,12 +128,31 @@ def composition_test( all others). p-values are BH-adjusted. The overall chi-square p is stored in ``df.attrs['chisq_p']``. + **Cells are not replicates.** Without ``sample_col`` the Fisher test counts every + cell as an independent observation. With thousands of cells nearly every + difference is then significant, including one that is only donor-to-donor + variation, because the unit that replicates is the donor, not the cell. In a + simulation with no condition effect at all (12 donors, 6 against 6, each with its + own cell-type proportions) at least one cell type came out significant in 35 of 40 + runs. Read the p-values as a ranking, or as a test for one sample per condition. + For several donors per condition pass ``sample_col``. + Parameters ---------- - group_by : categorical metadata column tested for enrichment (rows). - split_by : metadata column with exactly two levels (the conditions). - reference : which ``split_by`` level is the denominator (default: the first - sorted level). log2 > 0 ⇒ enriched in the *other* level. + group_by : categorical metadata column tested for enrichment (rows). + split_by : metadata column with exactly two levels (the conditions). + reference : which ``split_by`` level is the denominator (default: the first + sorted level). log2 > 0 ⇒ enriched in the *other* level. + sample_col : metadata column naming the sample (donor) each cell came from. The + test then has one observation per sample: each group's proportion + in each sample is compared between the two levels with a two-sided + Mann-Whitney U test, BH-adjusted across groups. Every sample must sit + in one level of ``split_by``, and a cell with no sample is left out. + ``prop_`` is then the mean of the per-sample proportions, + ``odds_ratio`` and ``chisq_p`` are not reported (they are cell-level), + and ``df.attrs['n_samples']`` counts the samples per level. With few + samples the test cannot reach significance whatever the data: three + against three cannot give a p-value below 0.1, and a warning says so. Returns ------- @@ -59,7 +161,7 @@ def composition_test( ``odds_ratio``, ``p``, ``padj``, ``sig`` and ``enriched_in``. """ md = seurat.meta_data - for col in (group_by, split_by): + for col in (group_by, split_by) + ((sample_col,) if sample_col is not None else ()): if col not in md.columns: raise KeyError(f"'{col}' not in meta_data.") tab = pd.crosstab(md[group_by].astype(str), md[split_by].astype(str)) @@ -72,6 +174,8 @@ def composition_test( if ref not in conds: raise ValueError(f"reference '{ref}' not a level of {split_by}: {conds}.") test = [c for c in conds if c != ref][0] + if sample_col is not None: + return _across_samples(md, group_by, split_by, sample_col, ref, test) n_ref, n_test = tab[ref].sum(), tab[test].sum() rows = [] @@ -88,13 +192,9 @@ def composition_test( f"prop_{ref}": prop_ref, f"prop_{test}": prop_test, "log2_ratio": log2, "odds_ratio": odds, "p": p, }) - df = pd.DataFrame(rows) - df["padj"] = _bh(df["p"].to_numpy()) - bins = [-np.inf, 0.001, 0.01, 0.05, np.inf] - df["sig"] = pd.cut(df["padj"], bins, labels=["***", "**", "*", "ns"]) - df["enriched_in"] = np.where(df["log2_ratio"] > 0, test, ref) - df = df.sort_values("log2_ratio", ascending=False).reset_index(drop=True) + df = _finish(pd.DataFrame(rows), ref, test) df.attrs["chisq_p"] = float(stats.chi2_contingency(tab.to_numpy())[1]) df.attrs["reference"] = ref df.attrs["test"] = test + df.attrs["method"] = "fisher_exact" return df