|
| 1 | +""" |
| 2 | +Contract / error-path tests. |
| 3 | +
|
| 4 | +Every public function in `scrise.factorization` and `scrise.rank_selection` |
| 5 | +documents required AnnData keys and value ranges in its docstring. These |
| 6 | +tests pin down what actually happens when a caller violates that contract |
| 7 | +(missing keys, wrong dtypes, out-of-range parameters) so a future change |
| 8 | +can't silently turn a clear error into a confusing downstream crash (or |
| 9 | +worse, a silently wrong result) without a test noticing. |
| 10 | +""" |
| 11 | + |
| 12 | +from collections.abc import Mapping, Sequence |
| 13 | +from typing import Any, cast |
| 14 | + |
| 15 | +import anndata |
| 16 | +import numpy as np |
| 17 | +import pandas as pd |
| 18 | +import pytest |
| 19 | + |
| 20 | +from ..factorization import ( |
| 21 | + correct_conditions, |
| 22 | + export_factors, |
| 23 | + order_components_by_energy, |
| 24 | + pf2, |
| 25 | +) |
| 26 | +from ..rank_selection import bicv |
| 27 | +from .conftest import make_synthetic_pf2_data |
| 28 | + |
| 29 | + |
| 30 | +def test_pf2_missing_condition_idxs_raises(): |
| 31 | + """pf2() requires X.obs['condition_unique_idxs']; without it the |
| 32 | + caller gets a clear KeyError rather than a cryptic failure deep inside |
| 33 | + the PARAFAC2 solver.""" |
| 34 | + X = anndata.AnnData(X=np.random.rand(10, 5).astype(np.float32)) |
| 35 | + with pytest.raises(KeyError, match="condition_unique_idxs"): |
| 36 | + pf2(X, rank=2, doEmbedding=False, compress=None) |
| 37 | + |
| 38 | + |
| 39 | +def test_correct_conditions_missing_condition_idxs_raises(): |
| 40 | + X = anndata.AnnData(X=np.random.rand(10, 5).astype(np.float32)) |
| 41 | + with pytest.raises(KeyError, match="condition_unique_idxs"): |
| 42 | + correct_conditions(X) |
| 43 | + |
| 44 | + |
| 45 | +def test_correct_conditions_none_X_raises_typeerror(): |
| 46 | + """correct_conditions has an explicit guard for X.X is None (e.g. a |
| 47 | + factors-only AnnData produced by export_factors) -- it should fail |
| 48 | + clearly rather than crash inside `.sum()`.""" |
| 49 | + obs = pd.DataFrame({"condition_unique_idxs": [0, 0, 1, 1]}) |
| 50 | + X = anndata.AnnData(X=None, obs=obs, shape=(4, 3)) |
| 51 | + X.uns["Pf2_A"] = np.ones((2, 2)) |
| 52 | + with pytest.raises(TypeError, match="X.X must not be None"): |
| 53 | + correct_conditions(X) |
| 54 | + |
| 55 | + |
| 56 | +@pytest.mark.parametrize("missing_key", ["Pf2_A", "Pf2_B", "Pf2_weights"]) |
| 57 | +def test_order_components_by_energy_missing_uns_key_raises(missing_key): |
| 58 | + keys = {"Pf2_A", "Pf2_B", "Pf2_weights"} |
| 59 | + rank, n_genes, n_conditions = 2, 5, 3 |
| 60 | + uns = { |
| 61 | + "Pf2_A": np.ones((n_conditions, rank)), |
| 62 | + "Pf2_B": np.ones((rank, rank)), |
| 63 | + "Pf2_weights": np.ones(rank), |
| 64 | + } |
| 65 | + del uns[missing_key] |
| 66 | + X = anndata.AnnData( |
| 67 | + X=np.zeros((6, n_genes), dtype=np.float32), |
| 68 | + uns=uns, |
| 69 | + varm=cast(Mapping[str, Sequence[Any]], {"Pf2_C": np.ones((n_genes, rank))}), |
| 70 | + ) |
| 71 | + with pytest.raises(KeyError, match=missing_key): |
| 72 | + order_components_by_energy(X) |
| 73 | + assert missing_key in keys # sanity: parametrization matches the real keys |
| 74 | + |
| 75 | + |
| 76 | +@pytest.mark.parametrize( |
| 77 | + "missing", |
| 78 | + ["uns:Pf2_A", "uns:Pf2_B", "uns:Pf2_weights", "varm:Pf2_C", "obsm:projections"], |
| 79 | +) |
| 80 | +def test_export_factors_missing_any_required_field_raises_keyerror(tmp_path, missing): |
| 81 | + n_cells, n_genes, rank = 10, 6, 2 |
| 82 | + fields = { |
| 83 | + "uns:Pf2_A": ("uns", "Pf2_A", np.ones((3, rank))), |
| 84 | + "uns:Pf2_B": ("uns", "Pf2_B", np.ones((rank, rank))), |
| 85 | + "uns:Pf2_weights": ("uns", "Pf2_weights", np.ones(rank)), |
| 86 | + "varm:Pf2_C": ("varm", "Pf2_C", np.ones((n_genes, rank))), |
| 87 | + "obsm:projections": ("obsm", "projections", np.ones((n_cells, rank))), |
| 88 | + } |
| 89 | + uns, varm, obsm = {}, {}, {} |
| 90 | + dest = {"uns": uns, "varm": varm, "obsm": obsm} |
| 91 | + for key, (section, name, value) in fields.items(): |
| 92 | + if key == missing: |
| 93 | + continue |
| 94 | + dest[section][name] = value |
| 95 | + |
| 96 | + X = anndata.AnnData( |
| 97 | + X=np.zeros((n_cells, n_genes), dtype=np.float32), uns=uns, varm=varm, obsm=obsm |
| 98 | + ) |
| 99 | + with pytest.raises(KeyError): |
| 100 | + export_factors(X, str(tmp_path / "out.h5ad")) |
| 101 | + |
| 102 | + |
| 103 | +@pytest.mark.parametrize( |
| 104 | + "kwargs", |
| 105 | + [ |
| 106 | + {"held_out_cell_frac": 0.0}, |
| 107 | + {"held_out_cell_frac": 1.0}, |
| 108 | + {"held_out_cell_frac": -0.1}, |
| 109 | + {"held_out_gene_frac": 0.0}, |
| 110 | + {"held_out_gene_frac": 1.5}, |
| 111 | + {"n_repeats": 0}, |
| 112 | + {"n_repeats": -1}, |
| 113 | + ], |
| 114 | +) |
| 115 | +def test_bicv_rejects_invalid_arguments(kwargs): |
| 116 | + X = make_synthetic_pf2_data(n_cond=4, n_genes=20, rank=2, seed=0) |
| 117 | + with pytest.raises(ValueError): |
| 118 | + bicv(X, [2], **kwargs) |
| 119 | + |
| 120 | + |
| 121 | +def test_bicv_rejects_rank_exceeding_max_feasible_rank(): |
| 122 | + X = make_synthetic_pf2_data(n_cond=3, n_genes=10, rank=2, seed=0) |
| 123 | + with pytest.raises(ValueError, match="exceeds the maximum feasible rank"): |
| 124 | + bicv(X, [10_000]) |
| 125 | + |
| 126 | + |
| 127 | +def test_export_factors_output_directory_is_created(tmp_path): |
| 128 | + """export_factors should create any missing parent directories for the |
| 129 | + output path rather than failing with FileNotFoundError.""" |
| 130 | + n_cells, n_genes, rank = 10, 6, 2 |
| 131 | + X = anndata.AnnData( |
| 132 | + X=np.zeros((n_cells, n_genes), dtype=np.float32), |
| 133 | + uns={ |
| 134 | + "Pf2_A": np.random.rand(3, rank), |
| 135 | + "Pf2_B": np.random.rand(rank, rank), |
| 136 | + "Pf2_weights": np.random.rand(rank), |
| 137 | + }, |
| 138 | + varm=cast( |
| 139 | + Mapping[str, Sequence[Any]], {"Pf2_C": np.random.rand(n_genes, rank)} |
| 140 | + ), |
| 141 | + obsm=cast( |
| 142 | + Mapping[str, Sequence[Any]], |
| 143 | + {"projections": np.random.rand(n_cells, rank).astype(np.float32)}, |
| 144 | + ), |
| 145 | + ) |
| 146 | + out_path = tmp_path / "nested" / "dir" / "out.h5ad" |
| 147 | + export_factors(X, str(out_path)) |
| 148 | + assert out_path.exists() |
0 commit comments