Spaces:
Sleeping
Sleeping
Commit ·
d198462
1
Parent(s): 081f924
Test the methods in mosaic_core; run full suite plus a Streamlit-free job in CI
Browse files- .github/workflows/tests.yml +38 -4
- tests/test_comparison.py +337 -0
- tests/test_metrics.py +113 -0
- tests/test_no_streamlit.py +30 -0
- tests/test_zeroshot.py +120 -0
- tests/tests.md +52 -21
.github/workflows/tests.yml
CHANGED
|
@@ -7,7 +7,9 @@ on:
|
|
| 7 |
branches: [main]
|
| 8 |
|
| 9 |
jobs:
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
runs-on: ubuntu-latest
|
| 12 |
env:
|
| 13 |
CI: "true"
|
|
@@ -21,10 +23,42 @@ jobs:
|
|
| 21 |
- name: Install dependencies
|
| 22 |
run: |
|
| 23 |
pip install --extra-index-url https://download.pytorch.org/whl/cpu -r requirements.txt
|
| 24 |
-
pip install -e .
|
| 25 |
|
| 26 |
- name: Download NLTK data
|
| 27 |
run: python -c "import nltk; nltk.download('punkt_tab', quiet=True)"
|
| 28 |
|
| 29 |
-
- name: Run
|
| 30 |
-
run: pytest tests/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
branches: [main]
|
| 8 |
|
| 9 |
jobs:
|
| 10 |
+
# Full environment used by the Streamlit app / Hugging Face Space.
|
| 11 |
+
# test_integration.py skips itself when CI=true (it downloads models and calls the HF API).
|
| 12 |
+
app-environment:
|
| 13 |
runs-on: ubuntu-latest
|
| 14 |
env:
|
| 15 |
CI: "true"
|
|
|
|
| 23 |
- name: Install dependencies
|
| 24 |
run: |
|
| 25 |
pip install --extra-index-url https://download.pytorch.org/whl/cpu -r requirements.txt
|
| 26 |
+
pip install -e ".[dev]"
|
| 27 |
|
| 28 |
- name: Download NLTK data
|
| 29 |
run: python -c "import nltk; nltk.download('punkt_tab', quiet=True)"
|
| 30 |
|
| 31 |
+
- name: Run tests
|
| 32 |
+
run: pytest tests/ -v
|
| 33 |
+
|
| 34 |
+
# The analysis library on its own: installs mosaic_core WITHOUT Streamlit
|
| 35 |
+
# and checks every method is importable and tested in that environment.
|
| 36 |
+
library-only:
|
| 37 |
+
runs-on: ubuntu-latest
|
| 38 |
+
strategy:
|
| 39 |
+
fail-fast: false
|
| 40 |
+
matrix:
|
| 41 |
+
python-version: ["3.10", "3.12"]
|
| 42 |
+
env:
|
| 43 |
+
CI: "true"
|
| 44 |
+
steps:
|
| 45 |
+
- uses: actions/checkout@v4
|
| 46 |
+
|
| 47 |
+
- uses: actions/setup-python@v5
|
| 48 |
+
with:
|
| 49 |
+
python-version: ${{ matrix.python-version }}
|
| 50 |
+
|
| 51 |
+
- name: Install library (no app extras)
|
| 52 |
+
run: pip install --extra-index-url https://download.pytorch.org/whl/cpu -e ".[dev]"
|
| 53 |
+
|
| 54 |
+
- name: Check Streamlit is not installed
|
| 55 |
+
run: |
|
| 56 |
+
if python -c "import streamlit" 2>/dev/null; then
|
| 57 |
+
echo "streamlit should not be a dependency of mosaic_core"; exit 1
|
| 58 |
+
fi
|
| 59 |
+
|
| 60 |
+
- name: Download NLTK data
|
| 61 |
+
run: python -c "import nltk; nltk.download('punkt_tab', quiet=True)"
|
| 62 |
+
|
| 63 |
+
- name: Run tests
|
| 64 |
+
run: pytest tests/ -v
|
tests/test_comparison.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for mosaic_core.comparison (centred cosine, MAD threshold, matching)."""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pytest
|
| 6 |
+
from scipy.stats import norm
|
| 7 |
+
|
| 8 |
+
from mosaic_core.comparison import (
|
| 9 |
+
MAD_TO_SD,
|
| 10 |
+
calibrate_match_threshold,
|
| 11 |
+
compute_condition_similarity,
|
| 12 |
+
describe_threshold,
|
| 13 |
+
greedy_match,
|
| 14 |
+
pair_zscores,
|
| 15 |
+
parse_condition_csv,
|
| 16 |
+
robust_loc_scale,
|
| 17 |
+
shared_theme_chi2,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _lookup_embedder(vectors: dict):
|
| 22 |
+
"""Deterministic stand-in for a sentence-transformer."""
|
| 23 |
+
return lambda sentences: np.array([vectors[s] for s in sentences], dtype=float)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _sim(values, rows=None, cols=None):
|
| 27 |
+
values = np.asarray(values, dtype=float)
|
| 28 |
+
rows = rows or [f"a{i}" for i in range(values.shape[0])]
|
| 29 |
+
cols = cols or [f"b{j}" for j in range(values.shape[1])]
|
| 30 |
+
return pd.DataFrame(values, index=rows, columns=cols)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestParseConditionCsv:
|
| 34 |
+
def test_row_per_topic_format(self):
|
| 35 |
+
df = pd.DataFrame({
|
| 36 |
+
"Topic": [-1, 0, 1, 2],
|
| 37 |
+
"topic_name": ["Noise", "Colours", "Unlabelled", "Calm"],
|
| 38 |
+
"texts": ["x | y", "red things | blue things", "z", "slow breath | | quiet"],
|
| 39 |
+
})
|
| 40 |
+
out = parse_condition_csv(df)
|
| 41 |
+
# topic -1 and "Unlabelled" are excluded, empty pieces are dropped
|
| 42 |
+
assert out == {"Colours": ["red things", "blue things"],
|
| 43 |
+
"Calm": ["slow breath", "quiet"]}
|
| 44 |
+
|
| 45 |
+
def test_long_format(self):
|
| 46 |
+
df = pd.DataFrame({"Topic Name": ["A", "A", "Outlier", "B"],
|
| 47 |
+
"Document": ["s1", "s2", "noise", " s3 "]})
|
| 48 |
+
assert parse_condition_csv(df) == {"A": ["s1", "s2"], "B": ["s3"]}
|
| 49 |
+
|
| 50 |
+
def test_unknown_format_returns_empty(self):
|
| 51 |
+
assert parse_condition_csv(pd.DataFrame({"foo": [1]})) == {}
|
| 52 |
+
|
| 53 |
+
def test_pipe_inside_sentence_is_not_a_separator(self):
|
| 54 |
+
# Only the literal " | " separator splits.
|
| 55 |
+
df = pd.DataFrame({"topic_name": ["A"], "texts": ["either|or | second"]})
|
| 56 |
+
assert parse_condition_csv(df) == {"A": ["either|or", "second"]}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class TestComputeConditionSimilarity:
|
| 60 |
+
def setup_method(self):
|
| 61 |
+
rng = np.random.default_rng(42)
|
| 62 |
+
self.vectors = {f"s{i}": rng.normal(size=12) for i in range(60)}
|
| 63 |
+
self.topics_a = {"A1": ["s0", "s1", "s2"], "A2": ["s3", "s4"], "A3": ["s5", "s6", "s7"]}
|
| 64 |
+
self.topics_b = {"B1": ["s10", "s11"], "B2": ["s12", "s13", "s14"],
|
| 65 |
+
"B3": ["s15"], "B4": ["s16", "s17"]}
|
| 66 |
+
|
| 67 |
+
def test_shapes_and_labels(self):
|
| 68 |
+
sim, raw, va, vb = compute_condition_similarity(
|
| 69 |
+
self.topics_a, self.topics_b, _lookup_embedder(self.vectors))
|
| 70 |
+
assert sim.shape == raw.shape == (3, 4)
|
| 71 |
+
assert list(sim.index) == ["A1", "A2", "A3"]
|
| 72 |
+
assert list(sim.columns) == ["B1", "B2", "B3", "B4"]
|
| 73 |
+
assert va.shape == (3, 12) and vb.shape == (4, 12)
|
| 74 |
+
assert np.all(sim.values <= 1 + 1e-12) and np.all(sim.values >= -1 - 1e-12)
|
| 75 |
+
|
| 76 |
+
def test_matches_manual_centred_cosine(self):
|
| 77 |
+
emb = _lookup_embedder(self.vectors)
|
| 78 |
+
sim, _, _, _ = compute_condition_similarity(self.topics_a, self.topics_b, emb)
|
| 79 |
+
|
| 80 |
+
def centred(topics):
|
| 81 |
+
all_vecs = np.vstack([self.vectors[s] for t in topics.values() for s in t])
|
| 82 |
+
c = all_vecs.mean(axis=0)
|
| 83 |
+
return {n: np.mean([self.vectors[s] for s in t], axis=0) - c for n, t in topics.items()}
|
| 84 |
+
|
| 85 |
+
ca, cb = centred(self.topics_a), centred(self.topics_b)
|
| 86 |
+
a, b = ca["A2"], cb["B4"]
|
| 87 |
+
expected = a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
|
| 88 |
+
assert sim.loc["A2", "B4"] == pytest.approx(expected)
|
| 89 |
+
|
| 90 |
+
def test_invariant_to_global_shift_of_one_condition(self):
|
| 91 |
+
"""Per-condition centring removes any content shift shared by a whole condition."""
|
| 92 |
+
shift = np.full(12, 5.0)
|
| 93 |
+
shifted = dict(self.vectors)
|
| 94 |
+
for t in self.topics_b.values():
|
| 95 |
+
for s in t:
|
| 96 |
+
shifted[s] = self.vectors[s] + shift
|
| 97 |
+
sim1, raw1, _, _ = compute_condition_similarity(
|
| 98 |
+
self.topics_a, self.topics_b, _lookup_embedder(self.vectors))
|
| 99 |
+
sim2, raw2, _, _ = compute_condition_similarity(
|
| 100 |
+
self.topics_a, self.topics_b, _lookup_embedder(shifted))
|
| 101 |
+
np.testing.assert_allclose(sim1.values, sim2.values, atol=1e-10)
|
| 102 |
+
# ...whereas the uncentred score is affected.
|
| 103 |
+
assert not np.allclose(raw1.values, raw2.values)
|
| 104 |
+
|
| 105 |
+
def test_independent_of_other_condition_size(self):
|
| 106 |
+
"""Adding sentences to B must not change A's topic vectors (no pooled centring)."""
|
| 107 |
+
emb = _lookup_embedder(self.vectors)
|
| 108 |
+
_, _, va1, _ = compute_condition_similarity(self.topics_a, self.topics_b, emb)
|
| 109 |
+
bigger_b = dict(self.topics_b, B5=[f"s{i}" for i in range(20, 60)])
|
| 110 |
+
_, _, va2, _ = compute_condition_similarity(self.topics_a, bigger_b, emb)
|
| 111 |
+
np.testing.assert_allclose(va1, va2)
|
| 112 |
+
|
| 113 |
+
def test_duplicate_sentences_are_embedded_once(self):
|
| 114 |
+
calls = []
|
| 115 |
+
|
| 116 |
+
def embed(sentences):
|
| 117 |
+
calls.append(list(sentences))
|
| 118 |
+
return np.array([self.vectors[s] for s in sentences])
|
| 119 |
+
|
| 120 |
+
compute_condition_similarity({"A": ["s0", "s1"]}, {"B": ["s1", "s2"], "C": ["s0"]}, embed)
|
| 121 |
+
assert len(calls) == 1
|
| 122 |
+
assert sorted(calls[0]) == ["s0", "s1", "s2"]
|
| 123 |
+
|
| 124 |
+
def test_empty_input(self):
|
| 125 |
+
sim, raw, _, _ = compute_condition_similarity({}, {}, _lookup_embedder({}))
|
| 126 |
+
assert sim.empty and raw.empty
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class TestRobustLocScale:
|
| 130 |
+
def test_median_and_mad(self):
|
| 131 |
+
v = np.array([1.0, 2.0, 3.0, 4.0, 100.0])
|
| 132 |
+
med, sd = robust_loc_scale(v)
|
| 133 |
+
assert med == 3.0
|
| 134 |
+
# |v - 3| = [2, 1, 0, 1, 97] -> MAD = 1
|
| 135 |
+
assert sd == pytest.approx(MAD_TO_SD * 1.0)
|
| 136 |
+
|
| 137 |
+
def test_matches_normal_sd_on_large_sample(self):
|
| 138 |
+
rng = np.random.default_rng(0)
|
| 139 |
+
med, sd = robust_loc_scale(rng.normal(loc=0.2, scale=0.1, size=200_000))
|
| 140 |
+
assert med == pytest.approx(0.2, abs=2e-3)
|
| 141 |
+
assert sd == pytest.approx(0.1, rel=0.02)
|
| 142 |
+
|
| 143 |
+
def test_resistant_to_outliers(self):
|
| 144 |
+
rng = np.random.default_rng(1)
|
| 145 |
+
clean = rng.normal(0, 0.1, size=1000)
|
| 146 |
+
dirty = np.concatenate([clean, np.full(20, 0.9)])
|
| 147 |
+
_, sd_clean = robust_loc_scale(clean)
|
| 148 |
+
_, sd_dirty = robust_loc_scale(dirty)
|
| 149 |
+
assert sd_dirty == pytest.approx(sd_clean, rel=0.1)
|
| 150 |
+
|
| 151 |
+
def test_ignores_non_finite(self):
|
| 152 |
+
assert robust_loc_scale([1.0, np.nan, 2.0, np.inf, 3.0]) == robust_loc_scale([1.0, 2.0, 3.0])
|
| 153 |
+
|
| 154 |
+
def test_zero_mad_falls_back_to_std(self):
|
| 155 |
+
v = np.array([1.0, 1.0, 1.0, 5.0])
|
| 156 |
+
med, sd = robust_loc_scale(v)
|
| 157 |
+
assert med == 1.0
|
| 158 |
+
assert sd == pytest.approx(np.std(v))
|
| 159 |
+
|
| 160 |
+
def test_constant_and_empty_fall_back_to_one(self):
|
| 161 |
+
assert robust_loc_scale(np.full(5, 0.3)) == (0.3, 1.0)
|
| 162 |
+
assert robust_loc_scale(np.array([])) == (0.0, 1.0)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class TestCalibrateMatchThreshold:
|
| 166 |
+
def test_threshold_is_median_plus_k_robust_sd(self):
|
| 167 |
+
rng = np.random.default_rng(3)
|
| 168 |
+
sim = _sim(rng.normal(0, 0.1, size=(20, 25)))
|
| 169 |
+
med, sd = robust_loc_scale(sim.values)
|
| 170 |
+
for k in (3.0, 3.5, 4.0):
|
| 171 |
+
calib = calibrate_match_threshold(sim, k)
|
| 172 |
+
assert calib["threshold"] == pytest.approx(med + k * sd)
|
| 173 |
+
assert calib["median"] == med and calib["robust_sd"] == sd
|
| 174 |
+
assert calib["tail"] == pytest.approx(norm.sf(k))
|
| 175 |
+
|
| 176 |
+
def test_diagnostics(self):
|
| 177 |
+
rng = np.random.default_rng(4)
|
| 178 |
+
sim = _sim(rng.normal(0, 0.1, size=(10, 30)))
|
| 179 |
+
calib = calibrate_match_threshold(sim, 3.5)
|
| 180 |
+
assert calib["n_pairs"] == 300
|
| 181 |
+
assert calib["max_possible"] == 10
|
| 182 |
+
expected = 10 * (1 - (1 - norm.sf(3.5)) ** 30)
|
| 183 |
+
assert calib["expected_chance"] == pytest.approx(expected)
|
| 184 |
+
assert calib["background_pct"] == pytest.approx(
|
| 185 |
+
100 * (sim.values < calib["threshold"]).mean())
|
| 186 |
+
|
| 187 |
+
def test_higher_k_is_stricter(self):
|
| 188 |
+
rng = np.random.default_rng(5)
|
| 189 |
+
sim = _sim(rng.normal(0, 0.1, size=(15, 15)))
|
| 190 |
+
t = [calibrate_match_threshold(sim, k)["threshold"] for k in (3.0, 3.5, 4.0)]
|
| 191 |
+
assert t[0] < t[1] < t[2]
|
| 192 |
+
|
| 193 |
+
def test_genuine_matches_clear_the_threshold(self):
|
| 194 |
+
rng = np.random.default_rng(6)
|
| 195 |
+
values = rng.normal(0, 0.1, size=(12, 12))
|
| 196 |
+
np.fill_diagonal(values[:5, :5], 0.9) # five true correspondences
|
| 197 |
+
calib = calibrate_match_threshold(_sim(values), 3.5)
|
| 198 |
+
assert np.all(np.diag(values)[:5] > calib["threshold"])
|
| 199 |
+
# the background itself (almost) never does
|
| 200 |
+
off = values[~np.eye(12, dtype=bool)]
|
| 201 |
+
assert (off > calib["threshold"]).mean() < 0.01
|
| 202 |
+
|
| 203 |
+
def test_empty_matrix(self):
|
| 204 |
+
calib = calibrate_match_threshold(pd.DataFrame(), 3.5)
|
| 205 |
+
assert calib["n_pairs"] == 0 and calib["expected_chance"] == 0.0
|
| 206 |
+
|
| 207 |
+
def test_describe_threshold_inverts_calibration(self):
|
| 208 |
+
rng = np.random.default_rng(7)
|
| 209 |
+
sim = _sim(rng.normal(0, 0.1, size=(8, 9)))
|
| 210 |
+
calib = calibrate_match_threshold(sim, 3.2)
|
| 211 |
+
described = describe_threshold(sim, calib["threshold"])
|
| 212 |
+
assert described["k"] == pytest.approx(3.2)
|
| 213 |
+
assert described["tail"] == pytest.approx(calib["tail"])
|
| 214 |
+
assert described["expected_chance"] == pytest.approx(calib["expected_chance"])
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class TestPairZscores:
|
| 218 |
+
def test_hub_topic_is_penalised(self):
|
| 219 |
+
# a0 scores high against every b ("hub"); a1 has one specific match with b1.
|
| 220 |
+
sim = _sim([[0.60, 0.62, 0.61, 0.60, 0.59],
|
| 221 |
+
[0.00, 0.60, 0.02, -0.01, 0.01],
|
| 222 |
+
[0.01, -0.02, 0.00, 0.02, -0.01],
|
| 223 |
+
[-0.01, 0.01, 0.02, 0.00, 0.00],
|
| 224 |
+
[0.02, 0.00, -0.01, 0.01, 0.02]])
|
| 225 |
+
z = pair_zscores(sim)
|
| 226 |
+
assert z.shape == sim.shape
|
| 227 |
+
# both pairs have a high raw score and stand out in column b1 ...
|
| 228 |
+
assert sim.loc["a0", "b1"] >= sim.loc["a1", "b1"]
|
| 229 |
+
# ... but only the specific pair also stands out in its own row
|
| 230 |
+
assert z.loc["a1", "b1"] > 2.0
|
| 231 |
+
assert z.loc["a0", "b1"] < 2.0
|
| 232 |
+
matches, _, _ = greedy_match(sim, threshold=0.5, z_df=z, min_z=2.0)
|
| 233 |
+
assert [(m["a"], m["b"]) for m in matches] == [("a1", "b1")]
|
| 234 |
+
|
| 235 |
+
def test_is_min_of_row_and_column_z(self):
|
| 236 |
+
rng = np.random.default_rng(8)
|
| 237 |
+
sim = _sim(rng.normal(size=(5, 6)))
|
| 238 |
+
z = pair_zscores(sim)
|
| 239 |
+
i, j = 2, 3
|
| 240 |
+
mr, sr = robust_loc_scale(sim.values[i, :])
|
| 241 |
+
mc, sc = robust_loc_scale(sim.values[:, j])
|
| 242 |
+
expected = min((sim.values[i, j] - mr) / sr, (sim.values[i, j] - mc) / sc)
|
| 243 |
+
assert z.iat[i, j] == pytest.approx(expected)
|
| 244 |
+
|
| 245 |
+
def test_empty(self):
|
| 246 |
+
assert pair_zscores(pd.DataFrame()).empty
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class TestGreedyMatch:
|
| 250 |
+
def test_one_to_one_in_descending_score_order(self):
|
| 251 |
+
sim = _sim([[0.9, 0.8, 0.1],
|
| 252 |
+
[0.85, 0.2, 0.1],
|
| 253 |
+
[0.1, 0.1, 0.7]])
|
| 254 |
+
matches, ua, ub = greedy_match(sim, threshold=0.5)
|
| 255 |
+
pairs = [(m["a"], m["b"]) for m in matches]
|
| 256 |
+
# a0-b0 is taken first, so a1 cannot also take b0 even though 0.85 > 0.8
|
| 257 |
+
assert pairs == [("a0", "b0"), ("a2", "b2")]
|
| 258 |
+
assert ua == ["a1"] and ub == ["b1"]
|
| 259 |
+
assert [m["score"] for m in matches] == sorted([m["score"] for m in matches], reverse=True)
|
| 260 |
+
|
| 261 |
+
def test_each_topic_used_at_most_once(self):
|
| 262 |
+
rng = np.random.default_rng(9)
|
| 263 |
+
sim = _sim(rng.uniform(0, 1, size=(7, 11)))
|
| 264 |
+
matches, ua, ub = greedy_match(sim, threshold=0.0)
|
| 265 |
+
a_used = [m["a"] for m in matches]
|
| 266 |
+
b_used = [m["b"] for m in matches]
|
| 267 |
+
assert len(set(a_used)) == len(a_used) and len(set(b_used)) == len(b_used)
|
| 268 |
+
assert len(matches) == 7 # min(shape) when everything clears the threshold
|
| 269 |
+
assert set(a_used) | set(ua) == set(sim.index)
|
| 270 |
+
assert set(b_used) | set(ub) == set(sim.columns)
|
| 271 |
+
|
| 272 |
+
def test_stops_at_threshold(self):
|
| 273 |
+
sim = _sim([[0.9, 0.1], [0.1, 0.49]])
|
| 274 |
+
matches, ua, ub = greedy_match(sim, threshold=0.5)
|
| 275 |
+
assert [(m["a"], m["b"]) for m in matches] == [("a0", "b0")]
|
| 276 |
+
assert ua == ["a1"] and ub == ["b1"]
|
| 277 |
+
|
| 278 |
+
def test_threshold_is_inclusive(self):
|
| 279 |
+
sim = _sim([[0.5]])
|
| 280 |
+
matches, _, _ = greedy_match(sim, threshold=0.5)
|
| 281 |
+
assert len(matches) == 1
|
| 282 |
+
|
| 283 |
+
def test_z_rejection_keeps_both_topics_available(self):
|
| 284 |
+
sim = _sim([[0.9, 0.8],
|
| 285 |
+
[0.7, 0.1]])
|
| 286 |
+
z = _sim([[0.5, 3.0], # a0-b0 has the top score but is not specific
|
| 287 |
+
[3.0, 3.0]])
|
| 288 |
+
matches, ua, ub = greedy_match(sim, threshold=0.5, z_df=z, min_z=2.0)
|
| 289 |
+
pairs = {(m["a"], m["b"]) for m in matches}
|
| 290 |
+
# a0 and b0 are both still matched, just not to each other
|
| 291 |
+
assert pairs == {("a0", "b1"), ("a1", "b0")}
|
| 292 |
+
assert ua == [] and ub == []
|
| 293 |
+
|
| 294 |
+
def test_reciprocal_best_flag(self):
|
| 295 |
+
sim = _sim([[0.9, 0.3],
|
| 296 |
+
[0.95, 0.6]])
|
| 297 |
+
matches, _, _ = greedy_match(sim, threshold=0.5)
|
| 298 |
+
by_pair = {(m["a"], m["b"]): m for m in matches}
|
| 299 |
+
# a1's best is b0 and b0's best is a1 -> reciprocal
|
| 300 |
+
assert by_pair[("a1", "b0")]["reciprocal_best"] is True
|
| 301 |
+
# a0's best is b0, but a0-b0 was taken; a0 never matched b1 (0.3 < 0.5)
|
| 302 |
+
assert ("a0", "b1") not in by_pair
|
| 303 |
+
m, _, _ = greedy_match(sim, threshold=0.0)
|
| 304 |
+
flags = {(x["a"], x["b"]): x["reciprocal_best"] for x in m}
|
| 305 |
+
assert flags[("a0", "b1")] is False
|
| 306 |
+
|
| 307 |
+
def test_non_finite_scores_are_never_matched(self):
|
| 308 |
+
sim = _sim([[np.nan, 0.6], [0.7, np.inf]])
|
| 309 |
+
matches, _, _ = greedy_match(sim, threshold=0.5)
|
| 310 |
+
assert {(m["a"], m["b"]) for m in matches} == {("a1", "b0"), ("a0", "b1")}
|
| 311 |
+
|
| 312 |
+
def test_empty(self):
|
| 313 |
+
assert greedy_match(pd.DataFrame(), 0.5) == ([], [], [])
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class TestSharedThemeChi2:
|
| 317 |
+
def test_matches_scipy_and_cramers_v(self):
|
| 318 |
+
table = np.array([[30, 10], [10, 30], [20, 20]])
|
| 319 |
+
res = shared_theme_chi2(table)
|
| 320 |
+
from scipy.stats import chi2_contingency
|
| 321 |
+
chi2, p, dof, _ = chi2_contingency(table)
|
| 322 |
+
assert res["chi2"] == pytest.approx(chi2) and res["p"] == pytest.approx(p)
|
| 323 |
+
assert res["dof"] == dof == 2
|
| 324 |
+
assert res["cramers_v"] == pytest.approx(np.sqrt(chi2 / (120 * 1)))
|
| 325 |
+
assert res["n"] == 120 and res["n_themes"] == 3
|
| 326 |
+
|
| 327 |
+
def test_identical_proportions_give_zero_effect(self):
|
| 328 |
+
res = shared_theme_chi2([[10, 20], [30, 60]])
|
| 329 |
+
assert res["cramers_v"] == pytest.approx(0.0, abs=1e-12)
|
| 330 |
+
|
| 331 |
+
def test_drops_empty_rows(self):
|
| 332 |
+
assert shared_theme_chi2([[10, 5], [0, 0], [5, 10]])["n_themes"] == 2
|
| 333 |
+
|
| 334 |
+
@pytest.mark.parametrize("table", [[[10, 5]], [[10, 0], [5, 0]], [[1, 2, 3]]])
|
| 335 |
+
def test_untestable_tables_raise(self, table):
|
| 336 |
+
with pytest.raises(ValueError):
|
| 337 |
+
shared_theme_chi2(table)
|
tests/test_metrics.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for mosaic_core.metrics (diversity ratio, C_embed, C_v)."""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from mosaic_core.metrics import embedding_coherence, topic_coherence_cv, topic_diversity
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TestTopicDiversity:
|
| 10 |
+
def test_ratio_is_one_when_every_sentence_has_its_own_report(self):
|
| 11 |
+
stats = topic_diversity([0, 0, 0], ["r1", "r2", "r3"])
|
| 12 |
+
row = stats.iloc[0]
|
| 13 |
+
assert row["Total_Sentences"] == 3 and row["Unique_Reports"] == 3
|
| 14 |
+
assert row["Diversity_Ratio"] == 1.0
|
| 15 |
+
|
| 16 |
+
def test_single_report_dominating_topic(self):
|
| 17 |
+
stats = topic_diversity([1, 1, 1, 1], ["r1", "r1", "r1", "r1"]).set_index("Topic")
|
| 18 |
+
assert stats.loc[1, "Diversity_Ratio"] == pytest.approx(0.25)
|
| 19 |
+
|
| 20 |
+
def test_mixed_topics(self):
|
| 21 |
+
topics = [0, 0, 0, 0, 1, 1, 2]
|
| 22 |
+
reports = ["a", "a", "b", "c", "a", "b", "z"]
|
| 23 |
+
stats = topic_diversity(topics, reports).set_index("Topic")
|
| 24 |
+
assert stats.loc[0, "Diversity_Ratio"] == pytest.approx(3 / 4)
|
| 25 |
+
assert stats.loc[1, "Diversity_Ratio"] == pytest.approx(1.0)
|
| 26 |
+
assert stats.loc[2, "Total_Sentences"] == 1
|
| 27 |
+
assert list(stats.columns) == ["Total_Sentences", "Unique_Reports", "Diversity_Ratio"]
|
| 28 |
+
|
| 29 |
+
def test_outliers_are_excluded(self):
|
| 30 |
+
stats = topic_diversity([-1, -1, 0], ["a", "b", "c"])
|
| 31 |
+
assert list(stats["Topic"]) == [0]
|
| 32 |
+
|
| 33 |
+
def test_ratio_bounds(self):
|
| 34 |
+
rng = np.random.default_rng(0)
|
| 35 |
+
topics = rng.integers(-1, 10, 1000)
|
| 36 |
+
reports = rng.integers(0, 50, 1000)
|
| 37 |
+
stats = topic_diversity(topics, reports)
|
| 38 |
+
assert (stats["Diversity_Ratio"] > 0).all() and (stats["Diversity_Ratio"] <= 1).all()
|
| 39 |
+
assert stats["Total_Sentences"].sum() == (topics != -1).sum()
|
| 40 |
+
|
| 41 |
+
def test_length_mismatch_raises(self):
|
| 42 |
+
with pytest.raises(ValueError):
|
| 43 |
+
topic_diversity([0, 1], ["a"])
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _brute_force_cembed(embeddings, topics):
|
| 47 |
+
embeddings = np.asarray(embeddings, dtype=float)
|
| 48 |
+
unit = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
|
| 49 |
+
per_topic = []
|
| 50 |
+
for t in sorted(set(topics) - {-1}):
|
| 51 |
+
u = unit[np.asarray(topics) == t]
|
| 52 |
+
if len(u) < 2:
|
| 53 |
+
continue
|
| 54 |
+
s = u @ u.T
|
| 55 |
+
per_topic.append(s[np.triu_indices(len(u), k=1)].mean())
|
| 56 |
+
return float(np.mean(per_topic)) if per_topic else 0.0
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class TestEmbeddingCoherence:
|
| 60 |
+
def test_matches_brute_force_pairwise_mean(self):
|
| 61 |
+
rng = np.random.default_rng(1)
|
| 62 |
+
emb = rng.normal(size=(120, 16))
|
| 63 |
+
topics = list(rng.integers(-1, 6, 120))
|
| 64 |
+
assert embedding_coherence(emb, topics) == pytest.approx(_brute_force_cembed(emb, topics))
|
| 65 |
+
|
| 66 |
+
def test_identical_sentences_score_one(self):
|
| 67 |
+
emb = np.tile([1.0, 2.0, 3.0], (4, 1))
|
| 68 |
+
assert embedding_coherence(emb, [0, 0, 0, 0]) == pytest.approx(1.0)
|
| 69 |
+
|
| 70 |
+
def test_scale_invariant(self):
|
| 71 |
+
rng = np.random.default_rng(2)
|
| 72 |
+
emb = rng.normal(size=(30, 5))
|
| 73 |
+
topics = [0] * 15 + [1] * 15
|
| 74 |
+
assert embedding_coherence(emb * 7.5, topics) == pytest.approx(embedding_coherence(emb, topics))
|
| 75 |
+
|
| 76 |
+
def test_singletons_and_outliers_ignored(self):
|
| 77 |
+
emb = np.array([[1.0, 0.0], [1.0, 0.0], [0.0, 1.0], [-1.0, 0.0]])
|
| 78 |
+
# topic 0 has two identical vectors (score 1); topic 1 is a singleton; -1 is ignored
|
| 79 |
+
assert embedding_coherence(emb, [0, 0, 1, -1]) == pytest.approx(1.0)
|
| 80 |
+
|
| 81 |
+
def test_no_qualifying_topic_returns_zero(self):
|
| 82 |
+
assert embedding_coherence(np.eye(3), [-1, 0, 1]) == 0.0
|
| 83 |
+
|
| 84 |
+
def test_length_mismatch_raises(self):
|
| 85 |
+
with pytest.raises(ValueError):
|
| 86 |
+
embedding_coherence(np.eye(3), [0, 0])
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class TestTopicCoherenceCv:
|
| 90 |
+
docs = [
|
| 91 |
+
"bright colours and geometric patterns",
|
| 92 |
+
"geometric patterns of bright light",
|
| 93 |
+
"colours shifting into patterns",
|
| 94 |
+
"calm slow breathing and relaxation",
|
| 95 |
+
"deep relaxation and calm breathing",
|
| 96 |
+
"breathing felt calm",
|
| 97 |
+
] * 5
|
| 98 |
+
|
| 99 |
+
def test_returns_score_in_unit_interval(self):
|
| 100 |
+
pytest.importorskip("gensim")
|
| 101 |
+
score = topic_coherence_cv(self.docs, [["colours", "patterns", "geometric"],
|
| 102 |
+
["calm", "breathing", "relaxation"]])
|
| 103 |
+
assert 0.0 <= score <= 1.0
|
| 104 |
+
|
| 105 |
+
def test_oov_and_ngrams_do_not_crash(self):
|
| 106 |
+
pytest.importorskip("gensim")
|
| 107 |
+
score = topic_coherence_cv(self.docs, [["bright light", "Patterns", "unseenword"],
|
| 108 |
+
["calm", "breathing"]])
|
| 109 |
+
assert np.isfinite(score)
|
| 110 |
+
|
| 111 |
+
def test_no_usable_topic_returns_zero(self):
|
| 112 |
+
pytest.importorskip("gensim")
|
| 113 |
+
assert topic_coherence_cv(self.docs, [["unseenword"], []]) == 0.0
|
tests/test_no_streamlit.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The analysis library must be importable without Streamlit."""
|
| 2 |
+
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
|
| 8 |
+
MODULES = ["mosaic_core", "mosaic_core.zeroshot", "mosaic_core.comparison", "mosaic_core.metrics"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@pytest.mark.parametrize("module", MODULES)
|
| 12 |
+
def test_import_does_not_load_streamlit(module):
|
| 13 |
+
code = (
|
| 14 |
+
"import sys\n"
|
| 15 |
+
"sys.modules['streamlit'] = None # any 'import streamlit' now raises ImportError\n"
|
| 16 |
+
f"import {module}\n"
|
| 17 |
+
"assert 'bertopic' not in sys.modules, 'light modules should not import BERTopic'\n"
|
| 18 |
+
)
|
| 19 |
+
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
|
| 20 |
+
assert result.returncode == 0, result.stderr
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_core_functions_do_not_import_streamlit():
|
| 24 |
+
code = (
|
| 25 |
+
"import sys\n"
|
| 26 |
+
"sys.modules['streamlit'] = None\n"
|
| 27 |
+
"import mosaic_core.core_functions\n"
|
| 28 |
+
)
|
| 29 |
+
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
|
| 30 |
+
assert result.returncode == 0, result.stderr
|
tests/test_zeroshot.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for mosaic_core.zeroshot."""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from mosaic_core.zeroshot import (
|
| 7 |
+
apply_zeroshot_threshold,
|
| 8 |
+
compute_zeroshot_similarities,
|
| 9 |
+
embeddings_fingerprint,
|
| 10 |
+
parse_categories,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestParseCategories:
|
| 15 |
+
def test_bare_labels(self):
|
| 16 |
+
labels, line_labels, line_texts = parse_categories("Anxiety\nJoy\n")
|
| 17 |
+
assert labels == ["Anxiety", "Joy"]
|
| 18 |
+
assert line_labels == ["Anxiety", "Joy"]
|
| 19 |
+
assert line_texts == ["Anxiety", "Joy"]
|
| 20 |
+
|
| 21 |
+
def test_description_is_embedded_with_label(self):
|
| 22 |
+
_, _, line_texts = parse_categories("Anxiety | feeling afraid")
|
| 23 |
+
assert line_texts == ["Anxiety: feeling afraid"]
|
| 24 |
+
|
| 25 |
+
def test_repeated_label_keeps_one_label_many_lines(self):
|
| 26 |
+
labels, line_labels, _ = parse_categories("A | one\nB\nA | two")
|
| 27 |
+
assert labels == ["A", "B"]
|
| 28 |
+
assert line_labels == ["A", "B", "A"]
|
| 29 |
+
|
| 30 |
+
def test_skips_blank_lines_and_empty_labels(self):
|
| 31 |
+
labels, line_labels, _ = parse_categories("\n \n | orphan description\nJoy")
|
| 32 |
+
assert labels == ["Joy"]
|
| 33 |
+
assert line_labels == ["Joy"]
|
| 34 |
+
|
| 35 |
+
def test_empty_description_falls_back_to_label(self):
|
| 36 |
+
_, _, line_texts = parse_categories("Joy | ")
|
| 37 |
+
assert line_texts == ["Joy"]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TestEmbeddingsFingerprint:
|
| 41 |
+
def test_stable_for_same_array(self):
|
| 42 |
+
e = np.arange(40, dtype=float).reshape(10, 4)
|
| 43 |
+
assert embeddings_fingerprint(e) == embeddings_fingerprint(e.copy())
|
| 44 |
+
|
| 45 |
+
def test_differs_for_different_content_same_shape(self):
|
| 46 |
+
e = np.zeros((10, 4))
|
| 47 |
+
f = np.ones((10, 4))
|
| 48 |
+
assert embeddings_fingerprint(e) != embeddings_fingerprint(f)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class TestComputeZeroshotSimilarities:
|
| 52 |
+
def test_cosine_against_encoded_lines(self):
|
| 53 |
+
docs = np.array([[1.0, 0.0], [0.0, 2.0], [1.0, 1.0]])
|
| 54 |
+
encode = lambda texts: np.array([[1.0, 0.0], [0.0, 1.0]])
|
| 55 |
+
sims = compute_zeroshot_similarities(docs, ["x", "y"], encode)
|
| 56 |
+
assert sims.shape == (3, 2)
|
| 57 |
+
np.testing.assert_allclose(sims[0], [1.0, 0.0])
|
| 58 |
+
np.testing.assert_allclose(sims[1], [0.0, 1.0])
|
| 59 |
+
np.testing.assert_allclose(sims[2], [np.sqrt(0.5), np.sqrt(0.5)])
|
| 60 |
+
|
| 61 |
+
def test_dimension_mismatch_raises(self):
|
| 62 |
+
docs = np.ones((3, 4))
|
| 63 |
+
encode = lambda texts: np.ones((len(texts), 8))
|
| 64 |
+
with pytest.raises(ValueError, match="mismatch"):
|
| 65 |
+
compute_zeroshot_similarities(docs, ["x"], encode, model_name="m")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class TestApplyZeroshotThreshold:
|
| 69 |
+
labels = ["A", "B", "C"]
|
| 70 |
+
line_labels = ["A", "B", "C"]
|
| 71 |
+
|
| 72 |
+
def test_assigns_best_label_above_threshold(self):
|
| 73 |
+
sims = np.array([[0.9, 0.1, 0.2],
|
| 74 |
+
[0.1, 0.8, 0.3]])
|
| 75 |
+
topics, info, per_doc = apply_zeroshot_threshold(sims, self.labels, self.line_labels, 0.5)
|
| 76 |
+
assert topics == [0, 1]
|
| 77 |
+
assert list(per_doc["best_category"]) == ["A", "B"]
|
| 78 |
+
assert list(per_doc["runner_up"]) == ["C", "C"]
|
| 79 |
+
|
| 80 |
+
def test_below_threshold_is_unclassified(self):
|
| 81 |
+
sims = np.array([[0.4, 0.1, 0.2]])
|
| 82 |
+
topics, info, per_doc = apply_zeroshot_threshold(sims, self.labels, self.line_labels, 0.5)
|
| 83 |
+
assert topics == [-1]
|
| 84 |
+
# best_category is reported regardless of the threshold
|
| 85 |
+
assert per_doc["best_category"].iloc[0] == "A"
|
| 86 |
+
assert info.set_index("Topic").loc[-1, "Count"] == 1
|
| 87 |
+
|
| 88 |
+
def test_margin_leaves_ambiguous_docs_unclassified(self):
|
| 89 |
+
sims = np.array([[0.80, 0.78, 0.1], # ambiguous: margin 0.02
|
| 90 |
+
[0.80, 0.50, 0.1]]) # clear: margin 0.30
|
| 91 |
+
topics, _, per_doc = apply_zeroshot_threshold(
|
| 92 |
+
sims, self.labels, self.line_labels, min_similarity=0.5, min_margin=0.1)
|
| 93 |
+
assert topics == [-1, 0]
|
| 94 |
+
np.testing.assert_allclose(per_doc["margin"], [0.02, 0.30])
|
| 95 |
+
|
| 96 |
+
def test_label_similarity_is_max_over_its_lines(self):
|
| 97 |
+
labels = ["A", "B"]
|
| 98 |
+
line_labels = ["A", "A", "B"]
|
| 99 |
+
sims = np.array([[0.2, 0.9, 0.5]])
|
| 100 |
+
topics, _, per_doc = apply_zeroshot_threshold(sims, labels, line_labels, 0.5)
|
| 101 |
+
assert topics == [0]
|
| 102 |
+
assert per_doc["confidence"].iloc[0] == pytest.approx(0.9)
|
| 103 |
+
|
| 104 |
+
def test_single_label_has_no_margin(self):
|
| 105 |
+
sims = np.array([[0.7], [0.2]])
|
| 106 |
+
topics, _, per_doc = apply_zeroshot_threshold(sims, ["A"], ["A"], 0.5, min_margin=0.3)
|
| 107 |
+
assert topics == [0, -1]
|
| 108 |
+
assert per_doc["margin"].isna().all()
|
| 109 |
+
assert list(per_doc["runner_up"]) == ["", ""]
|
| 110 |
+
|
| 111 |
+
def test_topic_info_counts_sum_to_n_docs(self):
|
| 112 |
+
rng = np.random.default_rng(0)
|
| 113 |
+
sims = rng.uniform(0, 1, size=(200, 3))
|
| 114 |
+
topics, info, _ = apply_zeroshot_threshold(sims, self.labels, self.line_labels, 0.6, 0.05)
|
| 115 |
+
assert info["Count"].sum() == 200
|
| 116 |
+
# only categories that received documents are listed, plus the -1 row
|
| 117 |
+
assert (info.loc[info["Topic"] != -1, "Count"] > 0).all()
|
| 118 |
+
assert info["Topic"].iloc[-1] == -1
|
| 119 |
+
for _, row in info.iterrows():
|
| 120 |
+
assert topics.count(row["Topic"]) == row["Count"]
|
tests/tests.md
CHANGED
|
@@ -1,32 +1,63 @@
|
|
| 1 |
# MOSAICapp Test Suite
|
| 2 |
|
| 3 |
-
This directory contains the automated tests for the
|
|
|
|
|
|
|
| 4 |
|
| 5 |
## File Structure
|
| 6 |
|
| 7 |
-
###
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
###
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
## How to Run
|
| 23 |
|
| 24 |
-
**Run everything:**
|
| 25 |
```bash
|
| 26 |
-
|
| 27 |
-
```
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
pytest tests/
|
| 32 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# MOSAICapp Test Suite
|
| 2 |
|
| 3 |
+
This directory contains the automated tests for the `mosaic_core` library. None of the
|
| 4 |
+
tests import Streamlit, and all of them except `test_integration.py` run offline with
|
| 5 |
+
small deterministic inputs (fake embeddings instead of real models).
|
| 6 |
|
| 7 |
## File Structure
|
| 8 |
|
| 9 |
+
### `conftest.py`
|
| 10 |
+
Shared **fixtures**, such as the path to `dummy_dataset.csv`.
|
| 11 |
+
|
| 12 |
+
### `test_core_functions.py` (fast)
|
| 13 |
+
Preprocessing and pipeline helpers: slugify, text-column detection, sentence splitting,
|
| 14 |
+
config hashing, label cleaning, LLM label caching, device resolution.
|
| 15 |
+
|
| 16 |
+
### `test_zeroshot.py` (fast)
|
| 17 |
+
Zero-shot classification: category parsing (`Label | description`, repeated labels),
|
| 18 |
+
the dimension-mismatch guard, and `apply_zeroshot_threshold` (similarity threshold,
|
| 19 |
+
margin rule for ambiguous documents, max-over-lines, single-category case, counts).
|
| 20 |
+
|
| 21 |
+
### `test_comparison.py` (fast)
|
| 22 |
+
Condition comparison:
|
| 23 |
+
- **Centred cosine:** agrees with a manual computation, is invariant to a global shift
|
| 24 |
+
of one condition, does not depend on the other condition's size, embeds each unique
|
| 25 |
+
sentence once.
|
| 26 |
+
- **MAD threshold:** `robust_loc_scale` (median, 1.4826 x MAD, outlier resistance,
|
| 27 |
+
degenerate fallbacks), `calibrate_match_threshold` (median + k x robust SD,
|
| 28 |
+
diagnostics, true matches clear it while background does not), `describe_threshold`.
|
| 29 |
+
- **Hub filtering:** `pair_zscores` penalises topics that score high against everything.
|
| 30 |
+
- **Matching:** `greedy_match` is one-to-one, stops at the threshold, keeps both topics
|
| 31 |
+
available after a z-score rejection, flags reciprocal best hits, ignores non-finite scores.
|
| 32 |
+
- **Frequency test:** `shared_theme_chi2` agrees with SciPy and computes Cramér's V.
|
| 33 |
+
- **CSV parsing:** both export formats and the `" | "` separator.
|
| 34 |
+
|
| 35 |
+
### `test_metrics.py` (fast)
|
| 36 |
+
Diversity ratio (bounds, outlier exclusion), embedding coherence C_embed (agrees with a
|
| 37 |
+
brute-force pairwise mean, scale invariance) and C_v coherence (requires gensim).
|
| 38 |
+
|
| 39 |
+
### `test_no_streamlit.py` (fast)
|
| 40 |
+
Checks that `mosaic_core` and its submodules import with Streamlit unavailable.
|
| 41 |
+
|
| 42 |
+
### `test_integration.py` (slow)
|
| 43 |
+
Runs the real ML pipeline: downloads a sentence-transformers model, fits BERTopic on
|
| 44 |
+
dummy data and, if `HF_TOKEN` is set, calls the Hugging Face Inference API. Skipped
|
| 45 |
+
automatically when `CI=true`.
|
| 46 |
|
| 47 |
## How to Run
|
| 48 |
|
|
|
|
| 49 |
```bash
|
| 50 |
+
pip install -e ".[dev]"
|
|
|
|
| 51 |
|
| 52 |
+
pytest tests/ -v # everything
|
| 53 |
+
CI=true pytest tests/ -v # everything except the slow integration tests
|
| 54 |
+
pytest tests/test_comparison.py -v # one file
|
| 55 |
```
|
| 56 |
+
|
| 57 |
+
## Continuous integration
|
| 58 |
+
|
| 59 |
+
`.github/workflows/tests.yml` runs two jobs on every push and pull request to `main`:
|
| 60 |
+
|
| 61 |
+
- **app-environment:** the full `requirements.txt` environment on Python 3.11.
|
| 62 |
+
- **library-only:** `pip install -e ".[dev]"` without Streamlit, on Python 3.10 and 3.12.
|
| 63 |
+
It fails if Streamlit is installed, to show the library does not depend on it.
|