From bce4a9ce90839daf563beb50dee2d1e4bdefe914 Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Wed, 25 Nov 2026 15:22:30 -0800 Subject: [PATCH 01/11] Record a digest of the count matrix on CBASResult A result did not say which counts it was computed from, so a later step that recounts the cohort could not tell whether it used the same data and settings. Comparing the sequence list is not enough. With two arms and short sequences it often survives a changed criterion or a dropped subject. counts_digest is a SHA-256 of the counts, row ids and column labels, set by the three pipelines. It defaults to None, so results built by hand are unaffected. No numbers change. --- pycbas/params.py | 31 +++++++++++++++++++ pycbas/pipeline.py | 13 ++++---- tests/test_cbas.py | 56 ++++++++++++++++++++++++++++++++++ tests/test_multicontingency.py | 11 +++++++ 4 files changed, 105 insertions(+), 6 deletions(-) diff --git a/pycbas/params.py b/pycbas/params.py index 85a21a7..4afd736 100644 --- a/pycbas/params.py +++ b/pycbas/params.py @@ -1,5 +1,7 @@ """CBAS parameter and result dataclasses.""" +import hashlib + import numpy as np from dataclasses import dataclass @@ -29,13 +31,42 @@ class CBASParams: @dataclass class CBASResult: + """Outcome of a CBAS run. + + `counts_digest` identifies the count matrix the result was computed from, by its + counts, row ids and column labels. It lets a later step that recounts the same + cohort, such as `sequence_occurrences`, confirm it counted exactly what the + analysis counted. None for results built by hand. + """ + sequences: list[tuple] test_stats: np.ndarray g_values: np.ndarray k_final: int significant_mask: np.ndarray k_history: list = None + counts_digest: str | None = None @property def n_significant(self): return int(self.significant_mask.sum()) + + +def _counts_digest(counts, subject_ids, sequences): + """SHA-256 of a count matrix together with its row and column labels.""" + counts = np.ascontiguousarray(counts, dtype=" Date: Wed, 25 Nov 2026 15:26:49 -0800 Subject: [PATCH 02/11] Add sequence_occurrences Returns the start of every counted window of the given sequences, per subject, so timing summaries such as a group median trial can be computed by the caller. The rows for a subject and sequence are the windows the count matrix counted, so their number equals that cell. A second table gives each subject's stream length, whether it reached the criterion, and its cutoff, including subjects that never used the sequences. The function recounts with the given settings and raises if the result's counts_digest, or a given CountMatrix, does not match. The window scan is separate from enumerate_sequences and is checked against the count matrix on every call. The counting code is unchanged. --- pycbas/__init__.py | 2 + pycbas/occurrences.py | 326 ++++++++++++++++++++++++++++++++++++++ tests/test_occurrences.py | 324 +++++++++++++++++++++++++++++++++++++ 3 files changed, 652 insertions(+) create mode 100644 pycbas/occurrences.py create mode 100644 tests/test_occurrences.py diff --git a/pycbas/__init__.py b/pycbas/__init__.py index 49e8f0d..19172c4 100644 --- a/pycbas/__init__.py +++ b/pycbas/__init__.py @@ -42,6 +42,7 @@ contingency_criteria) from .criterion import criterion_trial, reached_criterion from .core import subject_criteria, NonIntegerCountWarning +from .occurrences import sequence_occurrences __all__ = [ "__version__", @@ -84,6 +85,7 @@ "criterion_trial", "reached_criterion", "subject_criteria", + "sequence_occurrences", "estimate_resources", "print_resource_estimate", ] diff --git a/pycbas/occurrences.py b/pycbas/occurrences.py new file mode 100644 index 0000000..636b3f7 --- /dev/null +++ b/pycbas/occurrences.py @@ -0,0 +1,326 @@ +"""Where each counted sequence occurred, subject by subject. + +The count matrix says how often each subject used a sequence. This module says +where. Every row of the occurrence table is one window the count matrix counted, so +for any subject and sequence the number of rows equals that cell of the matrix. +Nothing is added to the analysis and nothing is summarised. Medians, normalisation +and how to treat subjects that rarely or never use a sequence are analytic choices, +and they are left to the caller. + +Positions are reported in the coordinate the criterion uses. That is a 0-based index +into the subject's counted stream, which holds only the trials of the selected +contingency, counted across sessions. In multi-contingency data it restarts in each +contingency. `row` maps a position back to `Subject.trials`. + +The windows are found by a scan written separately from `enumerate_sequences`, and +every call checks the two against each other through the count matrix. A +disagreement raises rather than returning positions that do not match the analysis. +""" + +import warnings + +import numpy as np +from numpy.lib.stride_tricks import sliding_window_view + +from .cohort import CHOICE, CONDITION, REWARD, SESSION, CountMatrix, as_cohort +from .contingency import build_multicontingency_count_matrix, shared_contingency_blocks +from .core import build_count_matrix, reward_blocks +from .criterion import as_enumeration_cutoff, criterion_trial +from .io import extract_choice_stream, extract_choice_streams_by_block +from .params import CBASResult, _counts_digest + +__all__ = ["sequence_occurrences"] + +_MISMATCH = ( + "the recount does not match {what}. The cohort, the parameters or the counting " + "settings differ from the ones the analysis used. Check encode_reward, " + "block_aware, contingency or blocks, criterion and criterion_order, and whether " + "the cohort was filtered or reordered since.") + + +def sequence_occurrences(cohort, params, sequences, *, contingency=2, + block_aware=False, encode_reward=True, blocks=None, + counted=None): + """Start positions of every counted occurrence of the given sequences. + + Pass the same cohort, parameters and counting settings as the analysis, and pass + its result as `counted` so the recount can be checked against it. + + Args: + cohort: Cohort the analysis ran on. + params: CBASParams the analysis used. + sequences: entries in the form of `result.sequences`, bare tuples for a + single-contingency analysis or `(block, tuple)` pairs for a + multi-contingency one. For the significant sequences of a result, + `[s for s, m in zip(result.sequences, result.significant_mask) if m]`. + contingency: condition value the analysis filtered on, or None for all + trials. Single-contingency only. + block_aware: whether the analysis kept sequences within sessions. + Single-contingency only. Multi-contingency counting always does. + encode_reward: whether the analysis folded reward into the symbols. + blocks: contingency blocks the analysis included. Multi-contingency only, + default all shared by every subject. + counted: the analysis's CBASResult, or a CountMatrix. The recount must match + it exactly. A result is matched by its `counts_digest`. A result without + one, from an older version, is matched by its sequence list, which is + not exact, and a warning says so. + + Returns: + `(occurrences, subjects)`, two dicts of equal-length numpy arrays, so + `pandas.DataFrame(occurrences)` gives a table. + + `occurrences` has one row per counted window, ordered by subject, then by + the order of `sequences`, then by position. + + - `subject_id` + - `block`, the contingency block, or the `contingency` value for a + single-contingency analysis + - `sequence`, the entry as passed + - `start`, the 0-based position of the window's first trial in the counted + stream. Its last trial is `start + len(sequence) - 1`, and without + `block_aware` a window can span two sessions. + - `row`, the index of that first trial in `Subject.trials` + - `session`, the session of that first trial + + `subjects` has one row per subject and block, including subjects that never + used any of the sequences. + + - `subject_id`, `block` + - `n_trials`, the length of the counted stream + - `reached`, whether the subject reached the criterion + - `cutoff`, the last position at which a window may start. It is the + criterion trial when reached and `n_trials` otherwise, so positions are + bounded by how quickly each subject reached the criterion. + + Raises: + ValueError: if the recount does not match `counted`, or a sequence is + malformed, repeated, longer than `params.seq_len_max`, or was never + counted under these settings. + """ + cohort = as_cohort(cohort) + entries, multi = _normalise(sequences) + if not multi and blocks is not None: + raise ValueError("blocks applies to multi-contingency sequences, which are " + "(block, sequence) pairs") + for entry in entries: + length = len(entry[1] if multi else entry) + if not 1 <= length <= params.seq_len_max: + raise ValueError(f"sequence {entry!r} has length {length}, outside 1 to " + f"seq_len_max={params.seq_len_max}") + + if multi: + matrix = build_multicontingency_count_matrix( + cohort, params, blocks=blocks, encode_reward=encode_reward) + used_blocks = sorted(blocks) if blocks is not None else \ + shared_contingency_blocks(cohort) + else: + matrix = build_count_matrix(cohort, params, contingency=contingency, + encode_reward=encode_reward, + block_aware=block_aware) + used_blocks = [contingency] + _verify(counted, matrix) + + column = {entry: j for j, entry in enumerate(matrix.sequences)} + missing = [entry for entry in entries if entry not in column] + if missing: + raise ValueError( + f"{len(missing)} sequence(s) were never counted under these settings, " + f"e.g. {missing[:3]!r}. A wrong encode_reward or num_arms is the usual " + f"cause.") + + targets = {} + for entry in entries: + block, seq = entry if multi else (contingency, entry) + targets.setdefault(block, []).append(seq) + + occ = {"subject_id": [], "block": [], "sequence": [], "start": [], "row": [], + "session": []} + subj = {"subject_id": [], "block": [], "n_trials": [], "reached": [], + "cutoff": []} + order = getattr(params, "criterion_order", 0) + matrix_row = {sid: i for i, sid in enumerate(matrix.subject_ids)} + + for subject in cohort: + found = {} + for block in used_blocks: + if multi: + symbols, rows, rewards = _block_segments( + subject, block, params.num_arms, encode_reward) + else: + symbols, rows, rewards = _single_segments( + subject, contingency, block_aware, params.num_arms, encode_reward) + _check_rows(subject, symbols, rows, params.num_arms, encode_reward) + + n_trials = sum(len(s) for s in symbols) + criterion = criterion_trial(rewards, order, params.criterion) + cutoff = as_enumeration_cutoff(criterion, n_trials) + subj["subject_id"].append(subject.id) + subj["block"].append(block) + subj["n_trials"].append(n_trials) + subj["reached"].append(bool(np.isfinite(criterion))) + subj["cutoff"].append(cutoff) + + for seq, hits in _scan(symbols, rows, targets.get(block, []), + cutoff).items(): + found[(block, seq) if multi else seq] = hits + + counts = matrix.counts[matrix_row[subject.id]] + for entry in entries: + starts, hit_rows = found[entry] + if len(starts) != counts[column[entry]]: + raise RuntimeError( + f"found {len(starts)} occurrences of {entry!r} for subject " + f"{subject.id!r} where the count matrix has " + f"{counts[column[entry]]:g}. This is a bug in pycbas.") + n = len(starts) + occ["subject_id"].extend([subject.id] * n) + occ["block"].extend([entry[0] if multi else contingency] * n) + occ["sequence"].extend([entry] * n) + occ["start"].append(starts) + occ["row"].append(hit_rows) + occ["session"].append(subject.trials[hit_rows, SESSION]) + + return _columns(occ, ("start", "row", "session")), \ + _columns(subj, ("n_trials", "cutoff"), bools=("reached",)) + + +def _normalise(sequences): + """Entries as hashable tuples of builtin ints, and whether they are paired.""" + entries, kinds = [], set() + for entry in sequences: + paired = len(entry) == 2 and isinstance(entry[1], (tuple, list, np.ndarray)) + kinds.add(paired) + if paired: + entries.append((int(entry[0]), tuple(int(s) for s in entry[1]))) + else: + entries.append(tuple(int(s) for s in entry)) + if not entries: + raise ValueError("sequences is empty") + if len(kinds) > 1: + raise ValueError("sequences mixes bare sequences with (block, sequence) pairs") + if len(set(entries)) != len(entries): + raise ValueError("sequences contains repeated entries") + return entries, kinds.pop() + + +def _verify(counted, matrix): + if counted is None: + return + if isinstance(counted, CountMatrix): + same = (list(counted.subject_ids) == list(matrix.subject_ids) + and list(counted.sequences) == list(matrix.sequences) + and np.array_equal(counted.counts, matrix.counts)) + what = "the given CountMatrix" + elif isinstance(counted, CBASResult): + if counted.counts_digest is not None: + same = counted.counts_digest == _counts_digest( + matrix.counts, matrix.subject_ids, matrix.sequences) + else: + warnings.warn( + "this CBASResult has no counts_digest, so the recount is checked " + "against its sequence list only. That check can pass when the " + "settings differ, especially with few arms and short sequences. " + "Re-run the analysis with this version for an exact check.", + UserWarning, stacklevel=3) + same = list(counted.sequences) == list(matrix.sequences) + what = "the given CBASResult" + else: + raise TypeError(f"counted must be a CBASResult or a CountMatrix, got " + f"{type(counted).__name__}") + if not same: + raise ValueError(_MISMATCH.format(what=what)) + + +def _single_segments(subject, contingency, block_aware, num_arms, encode_reward): + """Symbol and row segments as `build_count_matrix` sees them, with rewards.""" + trials = subject.trials + if contingency is None: + mask = np.ones(len(trials), dtype=bool) + else: + mask = trials[:, CONDITION] == contingency + if block_aware: + symbols = extract_choice_streams_by_block(trials, contingency, num_arms, + encode_reward=encode_reward) + rows = _rows_by_session(trials, mask) + else: + symbols = [extract_choice_stream(trials, contingency, num_arms, + encode_reward=encode_reward)] + rows = [np.flatnonzero(mask)] + return symbols, rows, reward_blocks(trials, contingency, block_aware) + + +def _block_segments(subject, block, num_arms, encode_reward): + """Segments as `build_multicontingency_count_matrix` sees one block.""" + mask = subject.trials[:, CONDITION] == block + return (subject.symbol_blocks_for(block, num_arms, encode_reward), + _rows_by_session(subject.trials, mask), + subject.reward_blocks_for(block)) + + +def _rows_by_session(trials, mask): + """Row indices per session, in the order `np.unique` gives the counting code.""" + sessions = trials[:, SESSION] + return [np.flatnonzero(mask & (sessions == s)) for s in np.unique(sessions[mask])] + + +def _check_rows(subject, symbols, rows, num_arms, encode_reward): + """The row map must reproduce the stream the counting code used.""" + trials = subject.trials + for sym, idx in zip(symbols, rows, strict=True): + rebuilt = trials[idx, CHOICE] + if encode_reward: + rebuilt = rebuilt + trials[idx, REWARD] * num_arms + if not np.array_equal(rebuilt, sym): + raise RuntimeError(f"row map for subject {subject.id!r} does not match " + f"its counted stream. This is a bug in pycbas.") + + +def _scan(symbols, rows, targets, cutoff): + """Counted start positions and rows of each target, by the enumeration rules. + + A window starting at global position p is counted when p <= cutoff and the + window lies inside one segment. Global positions run across segments, and every + segment adds its full length, including segments too short for the window. + """ + by_length = {} + for seq in targets: + by_length.setdefault(len(seq), []).append(seq) + starts = {seq: [] for seq in targets} + hit_rows = {seq: [] for seq in targets} + offset = 0 + for sym, idx in zip(symbols, rows): + if offset > cutoff: + break + for length, seqs in by_length.items(): + if len(sym) < length: + continue + windows = sliding_window_view(np.asarray(sym), length) + for seq in seqs: + hits = np.flatnonzero((windows == np.asarray(seq)).all(axis=1)) + hits = hits[offset + hits <= cutoff] + starts[seq].append(offset + hits) + hit_rows[seq].append(idx[hits]) + offset += len(sym) + return {seq: (_concat(starts[seq]), _concat(hit_rows[seq])) for seq in targets} + + +def _concat(parts): + return np.concatenate(parts).astype(np.int64) if parts else \ + np.empty(0, dtype=np.int64) + + +def _columns(table, int_arrays, bools=()): + """Lists of values, or of int arrays for `int_arrays`, as numpy columns.""" + out = {} + for key, values in table.items(): + if key in int_arrays and values and isinstance(values[0], np.ndarray): + out[key] = _concat(values) + elif key in int_arrays: + out[key] = np.asarray(values, dtype=np.int64) + elif key in bools: + out[key] = np.asarray(values, dtype=bool) + else: + column = np.empty(len(values), dtype=object) + column[:] = values + out[key] = column + return out diff --git a/tests/test_occurrences.py b/tests/test_occurrences.py new file mode 100644 index 0000000..4b829ca --- /dev/null +++ b/tests/test_occurrences.py @@ -0,0 +1,324 @@ +"""Tests for `sequence_occurrences`, all on synthetic cohorts. + +The central property is that the occurrence table is the count matrix unrolled. For +every subject and sequence the number of rows equals the count, and the positions +are exactly the windows the enumeration counted. A reference written here as plain +loops checks the positions, and the function's own check against the count matrix +checks the totals. +""" + +from dataclasses import replace + +import numpy as np +import pytest + +from pycbas import (CBASParams, Cohort, Subject, build_count_matrix, + run_cbas_comparative, run_cbas_multicontingency, + sequence_occurrences) +from pycbas.contingency import build_multicontingency_count_matrix +from pycbas.core import reward_blocks +from pycbas.criterion import as_enumeration_cutoff, criterion_trial +from pycbas.io import extract_choice_stream, extract_choice_streams_by_block + +from test_multicontingency import two_block_record + + +def subject(choices, rewards=None, sessions=None, conditions=None, id="s"): + n = len(choices) + return Subject(id=id, trials=np.column_stack([ + np.ones(n, dtype=int) if sessions is None else sessions, + choices, + np.zeros(n, dtype=int) if rewards is None else rewards, + np.full(n, 2) if conditions is None else conditions, + ])) + + +def irregular_cohort(seed=0, num_arms=3): + """Subjects with the session layouts most likely to break a position map. + + Sessions of length one, session labels out of order and recurring after a gap, + trials of another condition interleaved, and one subject too short for any + sequence longer than two. + """ + rng = np.random.default_rng(seed) + layouts = [ + [5, 3, 1, 4] * 3 + [2] * 10, + [1, 1, 1, 2, 2, 3, 3, 3, 3] * 6, + [7] * 30 + [2] * 25 + [7] * 5, + list(np.repeat([1, 2, 3, 4], 18)), + [1, 1], + ] + subjects = [] + for i, sessions in enumerate(layouts): + n = len(sessions) + conditions = np.where(rng.random(n) < 0.15, 0, 2) + subjects.append(subject(rng.integers(0, num_arms, n), + rng.integers(0, 2, n), np.asarray(sessions), + conditions, id=f"s{i}")) + return Cohort(subjects) + + +def reference_starts(segments, length, cutoff): + """Counted start positions per sequence, by the enumeration rules, as loops.""" + out, offset = {}, 0 + for seg in segments: + for i in range(len(seg) - length + 1): + if offset + i <= cutoff: + out.setdefault(tuple(seg[i:i + length].tolist()), []).append(offset + i) + offset += len(seg) + return out + + +def as_table(occ): + """{(subject_id, sequence): starts} from an occurrence table.""" + table = {} + for sid, seq, start in zip(occ["subject_id"], occ["sequence"], occ["start"]): + table.setdefault((sid, seq), []).append(int(start)) + return table + + +class TestKnownPositions: + params = CBASParams(num_arms=3, seq_len_max=3, criterion=100) + + def cohort(self): + return Cohort([subject([0, 0, 0, 0, 1, 0, 0, 1])]) + + def test_overlapping_windows_each_count(self): + occ, _ = sequence_occurrences(self.cohort(), self.params, + [(0, 0, 0), (0, 0), (0, 1)], + encode_reward=False) + table = as_table(occ) + assert table[("s", (0, 0, 0))] == [0, 1] + assert table[("s", (0, 0))] == [0, 1, 2, 5] + assert table[("s", (0, 1))] == [3, 6] + + def test_the_cutoff_bounds_the_start_inclusively(self): + params = replace(self.params, criterion=5) + occ, subjects = sequence_occurrences(self.cohort(), params, [(0, 0), (0, 1)], + encode_reward=False) + table = as_table(occ) + assert table[("s", (0, 0))] == [0, 1, 2, 5] + assert table[("s", (0, 1))] == [3] + assert subjects["cutoff"].tolist() == [5] + assert subjects["reached"].tolist() == [True] + + def test_an_unreached_criterion_counts_every_window(self): + _, subjects = sequence_occurrences(self.cohort(), self.params, [(0,)], + encode_reward=False) + assert subjects["reached"].tolist() == [False] + assert subjects["cutoff"].tolist() == [8] + assert subjects["n_trials"].tolist() == [8] + + def test_a_cutoff_shorter_than_the_sequence(self): + params = replace(self.params, criterion=1) + occ, _ = sequence_occurrences(self.cohort(), params, [(0, 0, 0)], + encode_reward=False) + assert as_table(occ)[("s", (0, 0, 0))] == [0, 1] + + +@pytest.mark.parametrize("order,count", [(0, 40), (1, 8), (2, 3)]) +@pytest.mark.parametrize("block_aware", [False, True]) +@pytest.mark.parametrize("encode_reward", [False, True]) +@pytest.mark.parametrize("contingency", [2, None]) +def test_positions_are_exactly_the_counted_windows(order, count, block_aware, + encode_reward, contingency): + cohort = irregular_cohort() + params = CBASParams(num_arms=3, seq_len_max=3, criterion=count, + criterion_order=order) + settings = dict(contingency=contingency, block_aware=block_aware, + encode_reward=encode_reward) + matrix = build_count_matrix(cohort, params, **settings) + occ, subjects = sequence_occurrences(cohort, params, matrix.sequences, + counted=matrix, **settings) + table = as_table(occ) + + for i, subj in enumerate(cohort): + if block_aware: + segments = extract_choice_streams_by_block(subj.trials, contingency, 3, + encode_reward) + else: + segments = [extract_choice_stream(subj.trials, contingency, 3, + encode_reward)] + n = sum(len(s) for s in segments) + cutoff = as_enumeration_cutoff(criterion_trial( + reward_blocks(subj.trials, contingency, block_aware), order, count), n) + expected = {} + for length in range(1, 4): + expected.update(reference_starts(segments, length, cutoff)) + got = {seq: starts for (sid, seq), starts in table.items() if sid == subj.id} + assert got == expected, subj.id + assert subjects["cutoff"][i] == cutoff + for j, seq in enumerate(matrix.sequences): + assert len(got.get(seq, [])) == matrix.counts[i, j] + + # `row` points at the first trial of each window, in the raw trials. + for sid, seq, row, session in zip(occ["subject_id"], occ["sequence"], + occ["row"], occ["session"]): + trials = cohort.by_id(sid).trials + symbol = trials[row, 1] + (trials[row, 2] * 3 if encode_reward else 0) + assert symbol == seq[0] + assert session == trials[row, 0] + if contingency is not None: + assert trials[row, 3] == contingency + + +class TestMultiContingency: + params = CBASParams(num_arms=3, seq_len_max=2, criterion=6, criterion_order=1, + resample_number=20) + + def cohort(self): + return Cohort([two_block_record(seed, n=40) for seed in range(6)]) + + def test_positions_are_local_to_each_contingency(self): + cohort = self.cohort() + matrix = build_multicontingency_count_matrix(cohort, self.params) + occ, subjects = sequence_occurrences(cohort, self.params, matrix.sequences, + counted=matrix) + assert len(subjects["subject_id"]) == len(cohort) * 2 + assert set(subjects["block"]) == {1, 2} + + cutoff = {(s, b): c for s, b, c in zip(subjects["subject_id"], + subjects["block"], + subjects["cutoff"])} + for sid, block, start, row in zip(occ["subject_id"], occ["block"], + occ["start"], occ["row"]): + assert start <= cutoff[(sid, block)] + assert cohort.by_id(sid).trials[row, 3] == block + assert occ["start"].min() == 0 + assert occ["start"].max() < 40 + + def test_blocks_restrict_the_tables(self): + cohort = self.cohort() + matrix = build_multicontingency_count_matrix(cohort, self.params, blocks=[1]) + occ, subjects = sequence_occurrences(cohort, self.params, matrix.sequences, + blocks=[1], counted=matrix) + assert set(occ["block"]) == {1} + assert set(subjects["block"]) == {1} + + def test_checked_against_a_pipeline_result(self): + cohort = self.cohort() + result = run_cbas_multicontingency(cohort, [0, 1] * 3, self.params) + occ, _ = sequence_occurrences(cohort, self.params, result.sequences[:5], + counted=result) + assert len(occ["start"]) > 0 + + +class TestTables: + params = CBASParams(num_arms=3, seq_len_max=3, criterion=40) + + def test_non_users_are_in_subjects_but_not_occurrences(self): + cohort = Cohort([subject([0, 1, 0, 1], id="a"), subject([2, 2, 2, 2], id="b")]) + occ, subjects = sequence_occurrences(cohort, self.params, [(0, 1)], + encode_reward=False) + assert set(occ["subject_id"]) == {"a"} + assert subjects["subject_id"].tolist() == ["a", "b"] + + def test_columns_have_equal_lengths_and_documented_dtypes(self): + cohort = irregular_cohort() + matrix = build_count_matrix(cohort, self.params) + occ, subjects = sequence_occurrences(cohort, self.params, matrix.sequences[:10]) + for table in (occ, subjects): + assert len({len(column) for column in table.values()}) == 1 + for key in ("start", "row", "session", ): + assert occ[key].dtype == np.int64 + for key in ("subject_id", "block", "sequence"): + assert occ[key].dtype == object + assert subjects["reached"].dtype == bool + assert subjects["cutoff"].dtype == np.int64 + + def test_reordering_the_cohort_changes_no_subject_rows(self): + cohort = irregular_cohort() + seqs = build_count_matrix(cohort, self.params).sequences[:20] + before = as_table(sequence_occurrences(cohort, self.params, seqs)[0]) + after = as_table(sequence_occurrences(cohort.reorder([3, 0, 4, 2, 1]), + self.params, seqs)[0]) + assert before == after + + def test_numpy_entries_are_accepted(self): + cohort = irregular_cohort() + seqs = build_count_matrix(cohort, self.params).sequences[:3] + as_numpy = [np.asarray(s) for s in seqs] + a = sequence_occurrences(cohort, self.params, seqs)[0] + b = sequence_occurrences(cohort, self.params, as_numpy)[0] + assert a["sequence"].tolist() == b["sequence"].tolist() + + +class TestVerification: + """Mismatches are refused, on a hypothesis space small enough that the sequence + list alone would often fail to notice them.""" + + params = CBASParams(num_arms=2, seq_len_max=2, criterion=40, resample_number=20) + + def cohort(self): + rng = np.random.default_rng(1) + return Cohort([subject(rng.integers(0, 2, 60), rng.integers(0, 2, 60), + np.repeat([1, 2, 3], 20), + np.where(rng.random(60) < 0.2, 0, 2), id=f"s{i}") + for i in range(6)]) + + def run(self, cohort): + return run_cbas_comparative(cohort, [0, 0, 0, 1, 1, 1], self.params, + encode_reward=False) + + def test_the_matching_result_passes_silently(self, recwarn): + cohort = self.cohort() + result = self.run(cohort) + sequence_occurrences(cohort, self.params, result.sequences, + encode_reward=False, counted=result) + assert not [w for w in recwarn if issubclass(w.category, UserWarning)] + + @pytest.mark.parametrize("change", [ + dict(params=dict(criterion=39)), + dict(params=dict(criterion_order=1, criterion=10)), + dict(settings=dict(block_aware=True)), + dict(settings=dict(contingency=None)), + ]) + def test_different_settings_are_refused(self, change): + cohort = self.cohort() + result = self.run(cohort) + params = replace(self.params, **change.get("params", {})) + settings = dict(encode_reward=False, **change.get("settings", {})) + matrix = build_count_matrix(cohort, self.params, encode_reward=False) + for counted in (result, matrix): + with pytest.raises(ValueError, match="does not match"): + sequence_occurrences(cohort, params, result.sequences[:2], + counted=counted, **settings) + + def test_a_filtered_cohort_is_refused(self): + cohort = self.cohort() + result = self.run(cohort) + matrix = build_count_matrix(cohort, self.params, encode_reward=False) + fewer = Cohort(list(cohort)[1:]) + for counted in (result, matrix): + with pytest.raises(ValueError, match="does not match"): + sequence_occurrences(fewer, self.params, result.sequences[:2], + encode_reward=False, counted=counted) + + def test_a_result_without_a_digest_warns_and_falls_back(self): + cohort = self.cohort() + result = replace(self.run(cohort), counts_digest=None) + with pytest.warns(UserWarning, match="no counts_digest"): + sequence_occurrences(cohort, self.params, result.sequences[:2], + encode_reward=False, counted=result) + + def test_counted_must_be_a_result_or_a_matrix(self): + with pytest.raises(TypeError, match="CBASResult or a CountMatrix"): + sequence_occurrences(self.cohort(), self.params, [(0,)], + encode_reward=False, counted=object()) + + @pytest.mark.parametrize("sequences,match", [ + ([], "empty"), + ([(0,), (0,)], "repeated"), + ([(0,), (1, (0,))], "mixes"), + ([(0, 1, 0)], "seq_len_max"), + ([(3,)], "never counted"), + ]) + def test_malformed_sequences_are_refused(self, sequences, match): + with pytest.raises(ValueError, match=match): + sequence_occurrences(self.cohort(), self.params, sequences, + encode_reward=False) + + def test_blocks_need_paired_entries(self): + with pytest.raises(ValueError, match="blocks applies"): + sequence_occurrences(self.cohort(), self.params, [(0,)], + encode_reward=False, blocks=[1]) From 934c9a267fca2aec01fcfa0c3771f82ec58c6747 Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Wed, 25 Nov 2026 15:31:54 -0800 Subject: [PATCH 03/11] Add occurrence downloads to the GUI export tab The occurrences CSV has one row per counted occurrence of each significant sequence. The subject windows CSV gives each subject's stream length, criterion status and cutoff, with its group or score. run_analysis now reads the cohort and counting settings once and keeps them with the result. The loaders and the subject filter replace the live cohort without clearing the result, so the export recounts from what the run analysed, and the digest check refuses anything else. --- pycbas/_app.py | 100 +++++++++++++++++++++++++++++++++++++--------- tests/test_app.py | 40 +++++++++++++++++++ 2 files changed, 121 insertions(+), 19 deletions(-) diff --git a/pycbas/_app.py b/pycbas/_app.py index 25e86f8..7495a8c 100644 --- a/pycbas/_app.py +++ b/pycbas/_app.py @@ -99,6 +99,10 @@ class CBASApp(param.Parameterized): progress_value = param.Integer(default=0) status_text = param.String(default="") result = param.Parameter(default=None) + # What the run behind `result` analysed, captured when it started. The loaders and + # the subject filter replace `cohort` without touching `result`, so anything that + # recounts for a result must use these rather than the live state. + _run_inputs = param.Parameter(default=None, doc="Cohort, labels and settings of the last run") @property def has_blocks(self): @@ -180,32 +184,33 @@ def run_analysis(self): criterion_order=self.criterion_order, resample_number=self.resample_number, ) + # Read the cohort and settings once. The run can take minutes on a thread, and + # the same values are kept with the result for anything that recounts later. + cohort = self.cohort # The label is read off each subject by name, so the run cannot pair a # subject with another's group however the cohort was filtered or ordered. - if self.has_blocks: + key = SCORE_KEY if self.mode == "Correlative" and not cohort.has_blocks \ + else GROUP_KEY + labels = {s.id: s.meta.get(key) for s in cohort} + if cohort.has_blocks: # Each contingency is its own hypothesis set, corrected jointly, so # `blocks` changes the size of the hypothesis space rather than # subsetting a result. chunked is left at its default for that reason. from pycbas.pipeline import run_cbas_multicontingency - self.result = run_cbas_multicontingency( - self.cohort, GROUP_KEY, params, - blocks=list(self.selected_blocks) or None, - encode_reward=self.encode_reward, - ) - elif self.mode == "Comparative": - self.result = run_cbas_comparative( - self.cohort, GROUP_KEY, params, - contingency=self.contingency, - encode_reward=self.encode_reward, - block_aware=self.block_aware, - ) + counting = dict(blocks=list(self.selected_blocks) or None, + encode_reward=self.encode_reward) + result = run_cbas_multicontingency(cohort, key, params, **counting) else: - self.result = run_cbas_correlative( - self.cohort, SCORE_KEY, params, - contingency=self.contingency, - encode_reward=self.encode_reward, - block_aware=self.block_aware, - ) + counting = dict(contingency=self.contingency, + encode_reward=self.encode_reward, + block_aware=self.block_aware) + run = run_cbas_comparative if key == GROUP_KEY else run_cbas_correlative + result = run(cohort, key, params, **counting) + self._run_inputs = dict( + cohort=cohort, params=params, counting=counting, + label_name="group" if key == GROUP_KEY else "score", labels=labels, + ) + self.result = result _observed_cache_key = param.Parameter(default=None) #: None when the count could not be determined, so the estimate falls back @@ -2043,9 +2048,66 @@ def make_download_section(result): "The CSV contains all sequences with their test statistics, " "g-values (adjusted p-values), and significance status." ), + *_occurrence_downloads(result), ) +def _occurrence_frames(result, inputs, sequences): + """Occurrence and subject tables for `sequences`, as the export writes them. + + Recounts from the inputs captured when the run started, and is checked against + the result's digest, so a cohort loaded or filtered since cannot leak in. + """ + from pycbas import sequence_occurrences + occ, subjects = sequence_occurrences(inputs["cohort"], inputs["params"], sequences, + counted=result, **inputs["counting"]) + occ, subjects = pd.DataFrame(occ), pd.DataFrame(subjects) + # The same label as the results CSV, so the files join on `sequence`. + occ["sequence"] = occ["sequence"].map(_seq_label) + for frame in (occ, subjects): + frame.insert(1, inputs["label_name"], + frame["subject_id"].map(inputs["labels"])) + return occ, subjects + + +def _occurrence_downloads(result): + """Download buttons for where each significant sequence occurred.""" + inputs = app_state._run_inputs + if inputs is None or result.n_significant == 0: + return [] + significant = [s for s, m in zip(result.sequences, result.significant_mask) if m] + frames = {} + + def csv(which): + def callback(): + if not frames: + frames["occ"], frames["subjects"] = _occurrence_frames( + result, inputs, significant) + return io.StringIO(frames[which].to_csv(index=False)) + return callback + + return [ + pn.Row( + pn.widgets.FileDownload(callback=csv("occ"), + filename="cbas_occurrences.csv", + label="Download sequence occurrences (CSV)"), + pn.widgets.FileDownload(callback=csv("subjects"), + filename="cbas_subject_windows.csv", + label="Download subject windows (CSV)"), + ), + pn.pane.Markdown( + "The occurrences CSV has one row per counted occurrence of each significant " + "sequence. `start` is the 0-based trial of its first choice within the " + "counted trials, which restart in each contingency, and `row` is its 0-based " + "index in the subject's loaded trials. The subject windows CSV lists every " + "subject, including those that never used a sequence, with `cutoff`, the " + "last trial at which a counted sequence may start. Positions are bounded " + "by each subject's cutoff, so compare cutoffs across groups before " + "comparing timing. See the guide, \"When does a sequence occur?\"." + ), + ] + + # --- Demo data generator --- def generate_demo_data(event): """Generate synthetic data for testing.""" diff --git a/tests/test_app.py b/tests/test_app.py index ab9dc6f..4c6546a 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -357,6 +357,46 @@ def test_result_panes_build(self, result): assert app.make_sig_table(result) is not None assert app.build_results_tabs() is not None + def test_occurrence_downloads_follow_the_significant_sequences(self, result): + from dataclasses import replace + mask = np.zeros(len(result.sequences), dtype=bool) + mask[:4] = True + section = app.make_download_section(replace(result, significant_mask=mask)) + downloads = {d.filename: d for d in section.select(app.pn.widgets.FileDownload)} + + occ = pd.read_csv(downloads["cbas_occurrences.csv"].callback()) + subjects = pd.read_csv(downloads["cbas_subject_windows.csv"].callback()) + assert list(occ.columns) == ["subject_id", "group", "block", "sequence", + "start", "row", "session"] + assert list(subjects.columns) == ["subject_id", "group", "block", "n_trials", + "reached", "cutoff"] + assert set(occ["sequence"]) <= {app._seq_label(s) for s in result.sequences[:4]} + assert set(occ["group"]) <= {0, 1} + n_subjects = len(app.app_state._run_inputs["cohort"]) + assert len(subjects) == n_subjects * 3 + + def test_no_occurrence_downloads_without_significant_sequences(self, result): + from dataclasses import replace + none = replace(result, significant_mask=np.zeros(len(result.sequences), bool)) + names = {d.filename for d in app.make_download_section(none).select( + app.pn.widgets.FileDownload)} + assert "cbas_occurrences.csv" not in names + + def test_occurrences_use_the_cohort_the_run_analysed(self, result): + """The subject filter replaces the live cohort and leaves the result alone.""" + inputs = app.app_state._run_inputs + dropped = app.app_state.cohort.ids[0] + app.app_state.cohort = app.app_state.cohort.filter(lambda s: s.id != dropped) + assert app.app_state._run_inputs is inputs + + _, subjects = app._occurrence_frames(result, inputs, result.sequences[:3]) + assert dropped in set(subjects["subject_id"]) + + # and the live cohort, had it been used, is refused rather than exported + live = dict(inputs, cohort=app.app_state.cohort) + with pytest.raises(ValueError, match="does not match"): + app._occurrence_frames(result, live, result.sequences[:3]) + class TestManhattanPlot: """The figure in README.md, so its faults are the first thing anyone sees.""" From 159c9f753fc3d9e6124bf2f1c5d0fcaca1231229 Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Wed, 25 Nov 2026 15:36:31 -0800 Subject: [PATCH 04/11] Document sequence_occurrences A guide section explains what the two tables hold and what start counts. It gives a recipe for group medians that keeps subjects who never used a sequence in the group size, and lists what to check before reading timing differences, chiefly that positions are bounded by each subject's cutoff. Adds the API entry, the app's new downloads and an Unreleased changelog section. --- CHANGELOG.md | 16 ++++++++++++ docs/api.md | 24 +++++++++++++++++ docs/app.md | 6 +++++ docs/guide.md | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 117 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d839fa..97b5258 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## Unreleased + +### Added + +- **`sequence_occurrences`.** The start of every counted window of the given sequences, + per subject, with each subject's counting cutoff, so timing summaries such as a + group's median trial can be computed from the windows the analysis counted. It + recounts with the given settings and raises if the counts differ from the result's. + +- **`CBASResult.counts_digest`.** A SHA-256 of the count matrix a result was computed + from, which `sequence_occurrences` checks against. It defaults to None, and no numbers + change. + +- **Occurrence downloads in the app.** The Export tab writes both tables for the + significant sequences, built from the cohort and settings the run used. + ## 0.2.0 Subjects now carry their own identity, which changes the shape of the public API: diff --git a/docs/api.md b/docs/api.md index 1b83b4c..32aae66 100644 --- a/docs/api.md +++ b/docs/api.md @@ -327,6 +327,29 @@ enumeration. Only interesting when `params.criterion_order` is nonzero; see --- +### `sequence_occurrences` + +```python +sequence_occurrences(cohort, params, sequences, *, contingency=2, block_aware=False, + encode_reward=True, blocks=None, counted=None) +``` + +Start positions of every counted occurrence of `sequences`, given in the form of +`result.sequences`. Pass the settings the analysis used, and its `CBASResult` or a +`CountMatrix` as `counted`. The function recounts and raises `ValueError` if the counts +differ. A result is matched by its `counts_digest`. A result without one is matched by +its sequence list, which is not exact, and a warning says so. + +Returns `(occurrences, subjects)`, two dicts of equal-length numpy arrays. +`occurrences` has one row per counted window, with `subject_id`, `block`, `sequence`, +`start`, `row` and `session`. `subjects` has one row per subject and contingency, with +`n_trials`, `reached` and `cutoff`, including subjects that never used the sequences. +`start` is 0-based and counts only the trials the analysis counted. See +[when does a sequence occur](guide.md#when-does-a-sequence-occur) for the columns, a +recipe for group medians, and what to check before comparing groups. + +--- + ### `CBASResult` Returned by the pipeline functions. @@ -338,6 +361,7 @@ Returned by the pipeline functions. - `g_values` (ndarray, shape 2S) - Adjusted p-values from the converged step-down. Same layout as test_stats. - `k_final` (int) - Converged k value from k-FWER iteration. - `significant_mask` (ndarray of bool, shape S) - True for sequences significant in either direction. +- `counts_digest` (str or None) - SHA-256 of the count matrix the result was computed from, with its row ids and column labels. `sequence_occurrences` checks its recount against it. None for a result built by hand. **Properties** diff --git a/docs/app.md b/docs/app.md index 62e2d04..918e833 100644 --- a/docs/app.md +++ b/docs/app.md @@ -176,6 +176,12 @@ Results are presented across several tabs: **Export** — download full results or significant-only as CSV. +When some sequences are significant, the Export tab also offers two tables of where they +occurred. The occurrences CSV has one row per counted occurrence, and the subject windows +CSV gives each subject's counting cutoff. Both are built from the cohort and settings the +run used, so loading or filtering data afterwards does not change them. Read +[when does a sequence occur](guide.md#when-does-a-sequence-occur) before comparing groups. + For multi-contingency runs every sequence label carries the contingency block it belongs to, as `c3: 2-4-2`, in the plots, the tables and the CSV. The same arm sequence appearing under two contingencies is two rows, because it is two hypotheses. diff --git a/docs/guide.md b/docs/guide.md index ccf5c54..c4ebd87 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -432,6 +432,77 @@ matrix.select_block(1).shape # just that contingency's columns `select_block` raises on a single-contingency matrix rather than selecting nothing, since an empty result there reads as a contingency with no sequences. Use `split_sequence_entry` to get a sequence's length from an entry: `len(entry)` is 2 for every pair, whatever the sequence length. +## When does a sequence occur? + +The count matrix says how often each subject used a sequence. `sequence_occurrences` says where. It returns two tables. In the first, each row is one window the count matrix counted, so the rows for a subject and a sequence add up to that cell of the matrix. The second has a row for every subject, including subjects that never used the sequences, with what is needed to interpret the first. + +Pass the same cohort, parameters and counting settings as the analysis, and the result as `counted`. The function recounts and raises if its counts differ from the ones the result was computed from, so a changed setting or a filtered cohort cannot produce positions for data the analysis did not test. + +```python +import pandas as pd +from pycbas import sequence_occurrences + +significant = [s for s, m in zip(result.sequences, result.significant_mask) if m] +occ, subjects = sequence_occurrences(cohort, params, significant, + contingency=2, counted=result) +occ, subjects = pd.DataFrame(occ), pd.DataFrame(subjects) +``` + +| `occ` column | Meaning | +|---|---| +| `subject_id` | The subject | +| `block` | The contingency block, or the `contingency` value for a single-contingency run | +| `sequence` | The entry as passed | +| `start` | 0-based position of the window's first trial among the subject's counted trials | +| `row` | Index of that trial in `Subject.trials` | +| `session` | Session of that trial | + +| `subjects` column | Meaning | +|---|---| +| `subject_id`, `block` | One row per subject and contingency | +| `n_trials` | Number of counted trials, after the contingency filter | +| `reached` | Whether the subject reached the criterion | +| `cutoff` | Last position at which a counted window may start | + +**What `start` counts.** Positions are in the coordinate the criterion uses. Only trials of the selected contingency are counted, across sessions, and in multi-contingency data the count restarts in each contingency. Exploration trials and rows the loader dropped are not counted either. Use `row` to get back to the raw data. A window's last trial is `start + len(sequence) - 1`, and without `block_aware` a window can span two sessions. + +### A median per group + +The library does not summarise the positions, because every summary involves choices that belong to the analysis. This recipe takes one median per subject, then the median across the subjects in each group, so a subject that uses a sequence often counts no more than one that uses it rarely. + +```python +from pycbas import decode_sequence + +group = dict(zip(cohort.ids, cohort.labels_from("lesion"))) +subjects["group"] = subjects["subject_id"].map(group) + +per_subject = (occ.groupby(["block", "sequence", "subject_id"])["start"].median() + .rename("median_start").reset_index() + .merge(subjects, on=["subject_id", "block"])) +per_subject["fraction"] = per_subject["median_start"] / per_subject["cutoff"] + +summary = per_subject.groupby(["sequence", "group"]).agg( + median_start=("median_start", "median"), + median_fraction=("fraction", "median"), + users=("subject_id", "nunique"), +).reset_index() +summary["group_size"] = summary["group"].map( + subjects.drop_duplicates("subject_id").groupby("group").size()) +summary["label"] = summary["sequence"].map( + lambda s: decode_sequence(s, num_arms=params.num_arms)) +``` + +`users` counts the subjects in the group that used the sequence at all, and `group_size` counts all of them. Subjects that never used a sequence have no median and are left out, so compare `users` with `group_size` before comparing groups. + +### Before reading timing differences + +- **Positions are bounded by each subject's cutoff.** With a performance criterion, a subject that takes longer to reach it has more trials in which any sequence can start, so its median start is later for every sequence, whatever it did. A sequence used evenly has a median near half the cutoff, which is why the recipe also reports `fraction`. Compare `cutoff` across groups, and look separately at subjects that did not reach the criterion, since they contribute their whole stream. +- **The criterion trial is not trials to criterion.** For orders 1 and above, `cutoff` is the trial where the subject's `criterion`-th qualifying run starts, not where it ends. For order 0, reaching the criterion only means the subject had at least that many trials. +- **Overlapping windows each count.** Five consecutive choices of the same arm hold three windows of that arm repeated three times, so repeated runs weigh more in a median than a single use. +- **Timing of significant sequences is descriptive.** Those sequences were selected because their counts differ, so testing their timing on the same data counts the evidence twice. + +The app's Export tab writes both tables as CSV for the significant sequences, with the group or score added. + ## Using individual pipeline stages For custom workflows, you can call each stage separately: From 6606019a6eeb7e5fb7822e7344e10e8f33c2c9a1 Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Wed, 25 Nov 2026 16:15:55 -0800 Subject: [PATCH 05/11] Fit the occurrence export note to the run it describes The note under the occurrence downloads said positions restart in each contingency and told users to compare groups, even for single-contingency and correlative runs. It now says each only where it applies, sits under its own heading, and links to the guide section. --- pycbas/_app.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/pycbas/_app.py b/pycbas/_app.py index 7495a8c..9ca1c0f 100644 --- a/pycbas/_app.py +++ b/pycbas/_app.py @@ -2086,7 +2086,13 @@ def callback(): return io.StringIO(frames[which].to_csv(index=False)) return callback + restart = ", which restart in each contingency," if "blocks" in inputs["counting"] \ + else "" + compare = ("compare cutoffs across groups before comparing timing between them" + if inputs["label_name"] == "group" else + "check whether cutoffs track the score before relating timing to it") return [ + pn.pane.Markdown("#### Where the significant sequences occurred"), pn.Row( pn.widgets.FileDownload(callback=csv("occ"), filename="cbas_occurrences.csv", @@ -2096,18 +2102,21 @@ def callback(): label="Download subject windows (CSV)"), ), pn.pane.Markdown( - "The occurrences CSV has one row per counted occurrence of each significant " - "sequence. `start` is the 0-based trial of its first choice within the " - "counted trials, which restart in each contingency, and `row` is its 0-based " - "index in the subject's loaded trials. The subject windows CSV lists every " - "subject, including those that never used a sequence, with `cutoff`, the " - "last trial at which a counted sequence may start. Positions are bounded " - "by each subject's cutoff, so compare cutoffs across groups before " - "comparing timing. See the guide, \"When does a sequence occur?\"." + f"The occurrences CSV has one row per counted occurrence of each significant " + f"sequence. `start` is the 0-based trial of its first choice within the " + f"counted trials{restart} and `row` is its 0-based index in the subject's " + f"loaded trials. The subject windows CSV lists every subject, including " + f"those that never used a sequence, with `cutoff`, the last trial at which a " + f"counted sequence may start. Positions are bounded by each subject's " + f"cutoff, so {compare}. See [When does a sequence occur?]({_GUIDE_URL}) in " + f"the user guide." ), ] +_GUIDE_URL = "https://droumis.github.io/pycbas/guide/#when-does-a-sequence-occur" + + # --- Demo data generator --- def generate_demo_data(event): """Generate synthetic data for testing.""" From 38153f8e19a9bfc696a9083ed687ebb59bec0d3d Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Fri, 27 Nov 2026 11:50:54 -0800 Subject: [PATCH 06/11] Keep groups that never used a sequence in the median recipe The guide's group-median recipe started from the occurrence rows, so a group in which no subject used a sequence had no row, rather than a row showing none did. It now starts from every subject for every sequence. A test runs the guide's code as written on a cohort where one group never uses a sequence. --- docs/guide.md | 16 +++++---- tests/test_occurrences.py | 76 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 7 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index c4ebd87..a874753 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -476,23 +476,25 @@ from pycbas import decode_sequence group = dict(zip(cohort.ids, cohort.labels_from("lesion"))) subjects["group"] = subjects["subject_id"].map(group) -per_subject = (occ.groupby(["block", "sequence", "subject_id"])["start"].median() - .rename("median_start").reset_index() - .merge(subjects, on=["subject_id", "block"])) +medians = (occ.groupby(["sequence", "subject_id"])["start"].median() + .rename("median_start").reset_index()) +# Every subject for every sequence, so subjects that never used one stay in, as NaN. +per_subject = (occ[["block", "sequence"]].drop_duplicates() + .merge(subjects, on="block") + .merge(medians, on=["sequence", "subject_id"], how="left")) per_subject["fraction"] = per_subject["median_start"] / per_subject["cutoff"] summary = per_subject.groupby(["sequence", "group"]).agg( median_start=("median_start", "median"), median_fraction=("fraction", "median"), - users=("subject_id", "nunique"), + users=("median_start", "count"), + group_size=("subject_id", "size"), ).reset_index() -summary["group_size"] = summary["group"].map( - subjects.drop_duplicates("subject_id").groupby("group").size()) summary["label"] = summary["sequence"].map( lambda s: decode_sequence(s, num_arms=params.num_arms)) ``` -`users` counts the subjects in the group that used the sequence at all, and `group_size` counts all of them. Subjects that never used a sequence have no median and are left out, so compare `users` with `group_size` before comparing groups. +`users` counts the subjects in the group that used the sequence at all, and `group_size` counts all of them. Every group gets a row for every sequence: one that no subject in the group used has `users` of 0 and no median. The medians are over users only, so compare `users` with `group_size` before comparing groups. ### Before reading timing differences diff --git a/tests/test_occurrences.py b/tests/test_occurrences.py index 4b829ca..341707b 100644 --- a/tests/test_occurrences.py +++ b/tests/test_occurrences.py @@ -7,7 +7,9 @@ checks the totals. """ +import re from dataclasses import replace +from pathlib import Path import numpy as np import pytest @@ -243,6 +245,80 @@ def test_numpy_entries_are_accepted(self): assert a["sequence"].tolist() == b["sequence"].tolist() +GUIDE = Path(__file__).resolve().parents[1] / "docs" / "guide.md" + + +def guide_section_code(heading): + """The Python blocks of one `##` section of the guide, in order.""" + text = GUIDE.read_text() + start = text.index(f"\n## {heading}\n") + end = text.find("\n## ", start + 1) + section = text[start:end if end != -1 else None] + return re.findall(r"```python\n(.*?)```", section, flags=re.DOTALL) + + +class TestGuideRecipe: + """The guide's group-median recipe, run as written. + + It is the documented way to get the number the feature exists for, so it is + tested like code. The cohort has a sequence that one group never uses, which is + the case a recipe built only from the occurrence rows silently drops. + """ + + params = CBASParams(num_arms=3, seq_len_max=2, criterion=40, resample_number=50) + + def cohort(self): + rng = np.random.default_rng(7) + subjects = [] + for i in range(8): + group = i % 2 + n = 60 + # group 1 never chooses arm 2, so no sequence containing it is theirs + arms = 3 if group == 0 else 2 + trials = np.column_stack([np.ones(n, dtype=int), rng.integers(0, arms, n), + rng.integers(0, 2, n), np.full(n, 2)]) + subjects.append(Subject(id=f"s{i}", trials=trials, meta={"lesion": group})) + return Cohort(subjects) + + def test_every_group_has_a_row_for_every_sequence(self): + pytest.importorskip("pandas") + blocks = guide_section_code("When does a sequence occur?") + assert len(blocks) == 2, "update this test to the guide's code blocks" + + cohort = self.cohort() + matrix = build_count_matrix(cohort, self.params) + result = run_cbas_comparative(cohort, "lesion", self.params) + # Pin the selection rather than depend on what reaches significance: one + # sequence only group 0 uses, and one both groups use. + users = matrix.counts > 0 + groups = cohort.labels_from("lesion") + only_0 = next(j for j in range(users.shape[1]) + if users[groups == 0, j].any() and not users[groups == 1, j].any()) + both = next(j for j in range(users.shape[1]) + if users[groups == 0, j].any() and users[groups == 1, j].any()) + mask = np.zeros(len(result.sequences), dtype=bool) + mask[[only_0, both]] = True + result = replace(result, significant_mask=mask) + + namespace = dict(cohort=cohort, params=self.params, result=result) + for code in blocks: + exec(code, namespace) + summary = namespace["summary"] + + assert len(summary) == 2 * 2 + assert not summary.duplicated(["sequence", "group"]).any() + for _, row in summary.iterrows(): + j = matrix.sequences.index(row["sequence"]) + in_group = groups == row["group"] + assert row["users"] == users[in_group, j].sum() + assert row["group_size"] == in_group.sum() + assert np.isnan(row["median_start"]) == (row["users"] == 0) + + missing = summary[(summary["sequence"] == matrix.sequences[only_0]) + & (summary["group"] == 1)] + assert len(missing) == 1 and missing["users"].item() == 0 + + class TestVerification: """Mismatches are refused, on a hypothesis space small enough that the sequence list alone would often fail to notice them.""" From 571c0c338e686500bbd86035217553e1bed7e9ac Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Fri, 27 Nov 2026 11:50:54 -0800 Subject: [PATCH 07/11] Mark the branch as 0.3.0.dev0 So an install from the branch reports a version distinct from the 0.2.0 release. --- pixi.toml | 2 +- pycbas/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pixi.toml b/pixi.toml index 31c2b9d..5fa323a 100644 --- a/pixi.toml +++ b/pixi.toml @@ -1,6 +1,6 @@ [workspace] name = "pycbas" -version = "0.2.0" +version = "0.3.0.dev0" description = "Choice-Wide Behavioral Association Study" channels = ["conda-forge"] platforms = ["osx-arm64"] diff --git a/pycbas/__init__.py b/pycbas/__init__.py index 19172c4..5fb1cea 100644 --- a/pycbas/__init__.py +++ b/pycbas/__init__.py @@ -14,7 +14,7 @@ #: hatch. Worth being able to check from Python: 0.2.0 changes numerical output at #: ties, so "which version produced this result" is a question users will need to #: answer. -__version__ = "0.2.0" +__version__ = "0.3.0.dev0" from .params import CBASParams, CBASResult From 1d3cbfa7a30e4e936a358503cf21354db90cd1a5 Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Fri, 27 Nov 2026 12:20:36 -0800 Subject: [PATCH 08/11] Scan each length once and refuse ambiguous inputs in sequence_occurrences The scan compared every requested sequence with every window, once per subject, so exporting many sequences from a large cohort took tens of seconds. Windows are now read as integer codes and matched in one pass per length, and work is spent only on sequences a subject used: about seven times faster on a synthetic cohort of 1,500 subjects and 1,600 sequences. Whole-window comparison remains for codes that could overflow, and a test checks both paths against the reference. blocks is now made one sorted list of unique blocks first. An iterator was used up by the recount and left nothing to scan, and a repeated block repeated subject rows. Symbols and blocks that int() would change, such as 0.9 or "1", are refused rather than truncated to another sequence. --- pycbas/occurrences.py | 149 ++++++++++++++++++++++++++++++-------- tests/test_occurrences.py | 61 ++++++++++++++++ 2 files changed, 179 insertions(+), 31 deletions(-) diff --git a/pycbas/occurrences.py b/pycbas/occurrences.py index 636b3f7..10c071d 100644 --- a/pycbas/occurrences.py +++ b/pycbas/occurrences.py @@ -102,6 +102,10 @@ def sequence_occurrences(cohort, params, sequences, *, contingency=2, if not multi and blocks is not None: raise ValueError("blocks applies to multi-contingency sequences, which are " "(block, sequence) pairs") + if blocks is not None: + # One list for both the recount and the scan: an iterator would be used up + # by the first, and a repeated block would repeat subject rows in the second. + blocks = sorted(set(blocks)) for entry in entries: length = len(entry[1] if multi else entry) if not 1 <= length <= params.seq_len_max: @@ -111,7 +115,7 @@ def sequence_occurrences(cohort, params, sequences, *, contingency=2, if multi: matrix = build_multicontingency_count_matrix( cohort, params, blocks=blocks, encode_reward=encode_reward) - used_blocks = sorted(blocks) if blocks is not None else \ + used_blocks = blocks if blocks is not None else \ shared_contingency_blocks(cohort) else: matrix = build_count_matrix(cohort, params, contingency=contingency, @@ -132,6 +136,7 @@ def sequence_occurrences(cohort, params, sequences, *, contingency=2, for entry in entries: block, seq = entry if multi else (contingency, entry) targets.setdefault(block, []).append(seq) + plans = {block: _plan(seqs) for block, seqs in targets.items()} occ = {"subject_id": [], "block": [], "sequence": [], "start": [], "row": [], "session": []} @@ -139,6 +144,8 @@ def sequence_occurrences(cohort, params, sequences, *, contingency=2, "cutoff": []} order = getattr(params, "criterion_order", 0) matrix_row = {sid: i for i, sid in enumerate(matrix.subject_ids)} + entry_columns = np.array([column[entry] for entry in entries], dtype=np.int64) + empty = np.empty(0, dtype=np.int64) for subject in cohort: found = {} @@ -160,18 +167,18 @@ def sequence_occurrences(cohort, params, sequences, *, contingency=2, subj["reached"].append(bool(np.isfinite(criterion))) subj["cutoff"].append(cutoff) - for seq, hits in _scan(symbols, rows, targets.get(block, []), - cutoff).items(): - found[(block, seq) if multi else seq] = hits - - counts = matrix.counts[matrix_row[subject.id]] - for entry in entries: - starts, hit_rows = found[entry] - if len(starts) != counts[column[entry]]: - raise RuntimeError( - f"found {len(starts)} occurrences of {entry!r} for subject " - f"{subject.id!r} where the count matrix has " - f"{counts[column[entry]]:g}. This is a bug in pycbas.") + if block in plans: + for seq, hits in _scan(symbols, rows, plans[block], cutoff).items(): + found[(block, seq) if multi else seq] = hits + + # Only the entries this subject used, in the order given. Anything left in + # `found` afterwards was found where the count matrix has none. + expected = matrix.counts[matrix_row[subject.id], entry_columns] + for i in np.flatnonzero(expected): + entry = entries[i] + starts, hit_rows = found.pop(entry, (empty, empty)) + if len(starts) != expected[i]: + _count_bug(entry, subject, len(starts), expected[i]) n = len(starts) occ["subject_id"].extend([subject.id] * n) occ["block"].extend([entry[0] if multi else contingency] * n) @@ -179,11 +186,19 @@ def sequence_occurrences(cohort, params, sequences, *, contingency=2, occ["start"].append(starts) occ["row"].append(hit_rows) occ["session"].append(subject.trials[hit_rows, SESSION]) + for entry, (starts, _) in found.items(): + _count_bug(entry, subject, len(starts), 0) return _columns(occ, ("start", "row", "session")), \ _columns(subj, ("n_trials", "cutoff"), bools=("reached",)) +def _count_bug(entry, subject, found, counted): + raise RuntimeError( + f"found {found} occurrences of {entry!r} for subject {subject.id!r} where " + f"the count matrix has {counted:g}. This is a bug in pycbas.") + + def _normalise(sequences): """Entries as hashable tuples of builtin ints, and whether they are paired.""" entries, kinds = [], set() @@ -191,9 +206,10 @@ def _normalise(sequences): paired = len(entry) == 2 and isinstance(entry[1], (tuple, list, np.ndarray)) kinds.add(paired) if paired: - entries.append((int(entry[0]), tuple(int(s) for s in entry[1]))) + entries.append((_as_int(entry[0], entry), + tuple(_as_int(s, entry) for s in entry[1]))) else: - entries.append(tuple(int(s) for s in entry)) + entries.append(tuple(_as_int(s, entry) for s in entry)) if not entries: raise ValueError("sequences is empty") if len(kinds) > 1: @@ -203,6 +219,23 @@ def _normalise(sequences): return entries, kinds.pop() +def _as_int(value, entry): + """`value` as a builtin int, refusing anything the conversion would change. + + `int` truncates 0.9 to 0 and parses "1", either of which would return the + occurrences of a sequence other than the one asked for. + """ + try: + converted = int(value) + except (TypeError, ValueError): + converted = None + if converted is None or isinstance(value, (bool, np.bool_, str, bytes)) \ + or converted != value: + raise ValueError(f"sequence {entry!r} holds {value!r}, which is not an " + f"integer symbol or block") + return converted + + def _verify(counted, matrix): if counted is None: return @@ -275,33 +308,87 @@ def _check_rows(subject, symbols, rows, num_arms, encode_reward): f"its counted stream. This is a bug in pycbas.") -def _scan(symbols, rows, targets, cutoff): - """Counted start positions and rows of each target, by the enumeration rules. +def _plan(seqs): + """How to find `seqs`, grouped by length, worked out once for every subject. + + Each window is read as one base-`base` integer, so a segment is scanned once + per length however many sequences are requested. Symbols no target uses are + all read as `base - 1`, so any window holding one matches nothing. A length + whose codes could overflow, or targets with negative symbols, fall back to + comparing whole windows. + """ + by_length = {} + for seq in seqs: + by_length.setdefault(len(seq), []).append(seq) + plan = {} + for length, group in by_length.items(): + base = max(max(seq) for seq in group) + 2 + if min(min(seq) for seq in group) < 0 or base ** length >= 2 ** 63: + plan[length] = (group, None, None, None) + continue + wanted = {} + for seq in group: + code = 0 + for s in seq: + code = code * base + s + wanted[code] = seq + keys = np.fromiter(wanted, dtype=np.int64, count=len(wanted)) + plan[length] = (group, base, wanted, keys) + return plan + + +def _scan(symbols, rows, plan, cutoff): + """Counted start positions and rows of the planned sequences, by the + enumeration rules. Only sequences found at least once are returned. A window starting at global position p is counted when p <= cutoff and the window lies inside one segment. Global positions run across segments, and every segment adds its full length, including segments too short for the window. """ - by_length = {} - for seq in targets: - by_length.setdefault(len(seq), []).append(seq) - starts = {seq: [] for seq in targets} - hit_rows = {seq: [] for seq in targets} + starts, hit_rows = {}, {} offset = 0 for sym, idx in zip(symbols, rows): if offset > cutoff: break - for length, seqs in by_length.items(): - if len(sym) < length: + sym = np.asarray(sym, dtype=np.int64) + for length, step in plan.items(): + # Only windows that start at or before the cutoff and end in the segment. + n_windows = min(len(sym) - length + 1, cutoff - offset + 1) + if n_windows <= 0: continue - windows = sliding_window_view(np.asarray(sym), length) - for seq in seqs: - hits = np.flatnonzero((windows == np.asarray(seq)).all(axis=1)) - hits = hits[offset + hits <= cutoff] - starts[seq].append(offset + hits) - hit_rows[seq].append(idx[hits]) + for seq, hits in _match(sym, length, n_windows, *step): + starts.setdefault(seq, []).append(offset + hits) + hit_rows.setdefault(seq, []).append(idx[hits]) offset += len(sym) - return {seq: (_concat(starts[seq]), _concat(hit_rows[seq])) for seq in targets} + return {seq: (_concat(starts[seq]), _concat(hit_rows[seq])) for seq in starts} + + +def _match(sym, length, n_windows, seqs, base, wanted, keys): + """`(seq, starts)` for each of `seqs` found among the first `n_windows` windows.""" + if base is None: + windows = sliding_window_view(sym, length)[:n_windows] + for seq in seqs: + hits = np.flatnonzero((windows == np.asarray(seq)).all(axis=1)) + if len(hits): + yield seq, hits + return + + other = base - 1 + sym = np.where((sym >= 0) & (sym < other), sym, other) + codes = np.zeros(n_windows, dtype=np.int64) + for k in range(length): + codes = codes * base + sym[k:k + n_windows] + + hits = np.flatnonzero(np.isin(codes, keys)) + if not len(hits): + return + # A stable sort keeps each sequence's starts in increasing order. + found = codes[hits] + order = np.argsort(found, kind="stable") + hits, found = hits[order], found[order] + present, first = np.unique(found, return_index=True) + for code, positions in zip(present.tolist(), np.split(hits, first[1:])): + yield wanted[code], positions def _concat(parts): diff --git a/tests/test_occurrences.py b/tests/test_occurrences.py index 341707b..9e81756 100644 --- a/tests/test_occurrences.py +++ b/tests/test_occurrences.py @@ -197,6 +197,20 @@ def test_blocks_restrict_the_tables(self): assert set(occ["block"]) == {1} assert set(subjects["block"]) == {1} + @pytest.mark.parametrize("blocks", [lambda: iter([1]), lambda: [1, 1], + lambda: (1,)]) + def test_blocks_in_any_iterable_form_match_a_list(self, blocks): + cohort = self.cohort() + matrix = build_multicontingency_count_matrix(cohort, self.params, blocks=[1]) + expected = sequence_occurrences(cohort, self.params, matrix.sequences, + blocks=[1], counted=matrix) + got = sequence_occurrences(cohort, self.params, matrix.sequences, + blocks=blocks(), counted=matrix) + for want, have in zip(expected, got): + assert want.keys() == have.keys() + for key in want: + assert want[key].tolist() == have[key].tolist(), key + def test_checked_against_a_pipeline_result(self): cohort = self.cohort() result = run_cbas_multicontingency(cohort, [0, 1] * 3, self.params) @@ -244,6 +258,49 @@ def test_numpy_entries_are_accepted(self): b = sequence_occurrences(cohort, self.params, as_numpy)[0] assert a["sequence"].tolist() == b["sequence"].tolist() + def test_integral_floats_are_the_integers_they_hold(self): + cohort = irregular_cohort() + seqs = build_count_matrix(cohort, self.params).sequences[:3] + as_float = [tuple(float(s) for s in seq) for seq in seqs] + a = sequence_occurrences(cohort, self.params, seqs)[0] + b = sequence_occurrences(cohort, self.params, as_float)[0] + assert a["start"].tolist() == b["start"].tolist() + assert a["sequence"].tolist() == b["sequence"].tolist() + + +@pytest.mark.parametrize("seed", range(5)) +def test_both_scan_paths_find_the_same_windows(seed): + """Integer window codes, and the whole-window comparison used when codes could + overflow, agree with each other and with the reference. The streams include + symbols no target uses, negative ones among them.""" + from pycbas.occurrences import _plan, _scan + + rng = np.random.default_rng(seed) + segments = [rng.integers(-1, 6, n) for n in rng.integers(0, 30, 4)] + rows = [] + start = 0 + for segment in segments: + rows.append(np.arange(start, start + len(segment))) + start += len(segment) + targets = sorted({tuple(int(s) for s in rng.integers(0, 4, length)) + for length in (1, 2, 3, 3, 4) for _ in range(6)}) + cutoff = int(rng.integers(0, start + 1)) + + plan = _plan(targets) + fallback = {length: (step[0], None, None, None) for length, step in plan.items()} + coded, compared = _scan(segments, rows, plan, cutoff), \ + _scan(segments, rows, fallback, cutoff) + + expected = {} + for length in (1, 2, 3, 4): + expected.update({seq: starts for seq, starts in + reference_starts(segments, length, cutoff).items() + if seq in targets and starts}) + for found in (coded, compared): + assert {seq: starts.tolist() for seq, (starts, _) in found.items()} == expected + for starts, hit_rows in found.values(): + assert hit_rows.tolist() == starts.tolist() # rows here are positions + GUIDE = Path(__file__).resolve().parents[1] / "docs" / "guide.md" @@ -388,6 +445,10 @@ def test_counted_must_be_a_result_or_a_matrix(self): ([(0,), (1, (0,))], "mixes"), ([(0, 1, 0)], "seq_len_max"), ([(3,)], "never counted"), + ([(0.9,)], "not an integer"), + ([("1",)], "not an integer"), + ([(True,)], "not an integer"), + ([(1.5, (0,))], "not an integer"), ]) def test_malformed_sequences_are_refused(self, sequences, match): with pytest.raises(ValueError, match=match): From a5447a72b94eaaf805afbf73be399daeea58a535 Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Fri, 27 Nov 2026 12:20:36 -0800 Subject: [PATCH 09/11] Say what the recount check guarantees It compares counts, not trials, so the guide no longer claims a mismatched cohort cannot produce positions. Rearranged trials with identical counts would pass, which is rare unless seq_len_max is very small. --- docs/guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide.md b/docs/guide.md index a874753..1cf031b 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -436,7 +436,7 @@ matrix.select_block(1).shape # just that contingency's columns The count matrix says how often each subject used a sequence. `sequence_occurrences` says where. It returns two tables. In the first, each row is one window the count matrix counted, so the rows for a subject and a sequence add up to that cell of the matrix. The second has a row for every subject, including subjects that never used the sequences, with what is needed to interpret the first. -Pass the same cohort, parameters and counting settings as the analysis, and the result as `counted`. The function recounts and raises if its counts differ from the ones the result was computed from, so a changed setting or a filtered cohort cannot produce positions for data the analysis did not test. +Pass the same cohort, parameters and counting settings as the analysis, and the result as `counted`. The function recounts and raises if its counts differ from the ones the result was computed from. That catches a changed setting, a filtered or reordered cohort, and edited trials, since almost any edit changes some count. It compares counts, not the trials themselves, so trials rearranged without changing any count would pass. That is rare unless `seq_len_max` is very small, but pass the cohort exactly as the analysis loaded it. ```python import pandas as pd From fa27e1c0bcd51c590f5f15048c4ce50b50f8f8cf Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Fri, 27 Nov 2026 12:37:53 -0800 Subject: [PATCH 10/11] Encode subject ids unambiguously in counts_digest The ids were joined with an unescaped separator, so two different id lists holding that character could hash the same. They are now hashed as a JSON array, which escapes every character and marks its own end. Digest values change; no analysis output does. --- pycbas/params.py | 10 ++++++++-- tests/test_cbas.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/pycbas/params.py b/pycbas/params.py index 4afd736..0e59907 100644 --- a/pycbas/params.py +++ b/pycbas/params.py @@ -1,6 +1,7 @@ """CBAS parameter and result dataclasses.""" import hashlib +import json import numpy as np from dataclasses import dataclass @@ -53,12 +54,17 @@ def n_significant(self): def _counts_digest(counts, subject_ids, sequences): - """SHA-256 of a count matrix together with its row and column labels.""" + """SHA-256 of a count matrix together with its row and column labels. + + Each part must mark its own end, or two different inputs could run together + into the same bytes. The shape fixes the length of the counts, and the ids are + a JSON array, which escapes any character an id holds and ends at its `]`. + """ counts = np.ascontiguousarray(counts, dtype=" 1] + assert collided == [[["1", "2"], [1, 2]]] + def test_numpy_integers_in_labels_do_not_change_it(self): counts = np.ones((1, 2)) plain = _counts_digest(counts, ["a"], [(1, (0, 1)), (2, (1,))]) From 617ebd61faf6cf9fbfc8851a7fb28d791f1a9a14 Mon Sep 17 00:00:00 2001 From: Demetris Roumis Date: Fri, 27 Nov 2026 12:37:53 -0800 Subject: [PATCH 11/11] Give the end of a window by its symbol count The docs gave a window's last trial as start + len(sequence) - 1, but a multi-contingency entry is a (block, symbols) pair, whose len is always 2. They now use the number of symbols, and note that the end's raw row is not row + n - 1 when trials of another condition fall inside the window. --- docs/guide.md | 2 +- pycbas/occurrences.py | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index 1cf031b..90058e0 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -464,7 +464,7 @@ occ, subjects = pd.DataFrame(occ), pd.DataFrame(subjects) | `reached` | Whether the subject reached the criterion | | `cutoff` | Last position at which a counted window may start | -**What `start` counts.** Positions are in the coordinate the criterion uses. Only trials of the selected contingency are counted, across sessions, and in multi-contingency data the count restarts in each contingency. Exploration trials and rows the loader dropped are not counted either. Use `row` to get back to the raw data. A window's last trial is `start + len(sequence) - 1`, and without `block_aware` a window can span two sessions. +**What `start` counts.** Positions are in the coordinate the criterion uses. Only trials of the selected contingency are counted, across sessions, and in multi-contingency data the count restarts in each contingency. Exploration trials and rows the loader dropped are not counted either. Use `row` to get back to the raw data. A window of `n` symbols ends at `start + n - 1`, with `n = len(split_sequence_entry(sequence)[1])`, because `len` of a multi-contingency entry is always 2. That end is in counted trials: its row is not `row + n - 1` when trials of another condition fall inside the window. Without `block_aware` a window can span two sessions. ### A median per group diff --git a/pycbas/occurrences.py b/pycbas/occurrences.py index 10c071d..67be035 100644 --- a/pycbas/occurrences.py +++ b/pycbas/occurrences.py @@ -77,9 +77,13 @@ def sequence_occurrences(cohort, params, sequences, *, contingency=2, single-contingency analysis - `sequence`, the entry as passed - `start`, the 0-based position of the window's first trial in the counted - stream. Its last trial is `start + len(sequence) - 1`, and without - `block_aware` a window can span two sessions. - - `row`, the index of that first trial in `Subject.trials` + stream. Its last trial is `start + n - 1` for a sequence of `n` symbols, + `n = len(split_sequence_entry(sequence)[1])`, since `len` of a + multi-contingency pair is always 2. Without `block_aware` a window can + span two sessions. + - `row`, the index of that first trial in `Subject.trials`. The last + trial's row is not `row + n - 1` when trials of another condition fall + between them, since `start` counts only the counted trials. - `session`, the session of that first trial `subjects` has one row per subject and block, including subjects that never