|
| 1 | +"""runttest's Benjamini-Hochberg q-values, on a small table: right for the |
| 2 | +features with a p-value, and missing for a feature without one.""" |
| 3 | + |
| 4 | +from pathlib import Path |
| 5 | +from types import SimpleNamespace |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import pandas as pd |
| 9 | + |
| 10 | +import stats |
| 11 | + |
| 12 | +GROUPS = ('A', 'B') |
| 13 | +# Compound -> (mean, sd, n) per group; f_none is not measured in group B. |
| 14 | +FEATURES = { |
| 15 | + 'f1': ((100.0, 5.0, 3), (50.0, 5.0, 3)), |
| 16 | + 'f2': ((100.0, 10.0, 3), (90.0, 10.0, 3)), |
| 17 | + 'f3': ((100.0, 20.0, 3), (99.0, 20.0, 3)), |
| 18 | + 'f4': ((100.0, 3.0, 3), (80.0, 3.0, 3)), |
| 19 | + 'f_none': ((100.0, 5.0, 3), (np.nan, np.nan, np.nan)), |
| 20 | +} |
| 21 | + |
| 22 | + |
| 23 | +def write_inputs(out): |
| 24 | + index = pd.MultiIndex.from_tuples( |
| 25 | + [(c, 100.0 + i, 1.0) for i, c in enumerate(FEATURES)], |
| 26 | + names=['Compound', 'm/z', 'Retention time (min)']) |
| 27 | + columns, values = [], [] |
| 28 | + for kind, slot in (('average', 0), ('combASD', 1), ('neff', 2)): |
| 29 | + for g, group in enumerate(GROUPS): |
| 30 | + columns.append((kind, group)) |
| 31 | + values.append([FEATURES[c][g][slot] for c in FEATURES]) |
| 32 | + summary = pd.DataFrame(np.array(values).T, index=index, |
| 33 | + columns=pd.MultiIndex.from_tuples(columns)) |
| 34 | + summary.to_csv(out / 'x_summarydata.csv') |
| 35 | + pd.DataFrame({'m/z': [100.0 + i for i in range(len(FEATURES))]}, |
| 36 | + index=pd.Index(list(FEATURES), name='Compound')).to_csv(out / 'iondict.csv') |
| 37 | + rows = [['', '', ''], ['', '', ''], ['Compound', 'm/z', 'Retention time (min)']] |
| 38 | + rows += [[c, 100.0 + i, 1.0] for i, c in enumerate(FEATURES)] |
| 39 | + pd.DataFrame(rows).to_csv(out / 'x_filtered.csv', header=False, index=False) |
| 40 | + |
| 41 | + |
| 42 | +def test_a_feature_without_a_p_value_gets_no_q_value(tmp_path): |
| 43 | + write_inputs(tmp_path) |
| 44 | + params = SimpleNamespace(outputdir=tmp_path, filename=Path('x.csv'), querylist=['all']) |
| 45 | + stats.runttest(params, list(GROUPS), {'all': SimpleNamespace(ionlist=list(FEATURES))}) |
| 46 | + |
| 47 | + iondict = pd.read_csv(tmp_path / 'iondict.csv', index_col=0) |
| 48 | + assert np.isnan(iondict.loc['f_none', '-logp']) |
| 49 | + # It used to be given the smallest q-value of the others. |
| 50 | + assert np.isnan(iondict.loc['f_none', '-logq']) |
| 51 | + |
| 52 | + tested = iondict.drop('f_none') |
| 53 | + p = 10 ** -tested['-logp'].to_numpy() |
| 54 | + order = np.argsort(p) |
| 55 | + m = len(p) |
| 56 | + expected = np.minimum.accumulate((p[order] * m / np.arange(1, m + 1))[::-1])[::-1] |
| 57 | + q = np.empty(m) |
| 58 | + q[order] = expected |
| 59 | + np.testing.assert_allclose(10 ** -tested['-logq'].to_numpy(), q, rtol=1e-9) |
0 commit comments