Skip to content
Open
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
24 changes: 24 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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**

Expand Down
6 changes: 6 additions & 0 deletions docs/app.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
73 changes: 73 additions & 0 deletions docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,79 @@ 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. 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 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 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

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)

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=("median_start", "count"),
group_size=("subject_id", "size"),
).reset_index()
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. 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

- **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:
Expand Down
2 changes: 1 addition & 1 deletion pixi.toml
Original file line number Diff line number Diff line change
@@ -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"]
Expand Down
4 changes: 3 additions & 1 deletion pycbas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__",
Expand Down Expand Up @@ -84,6 +85,7 @@
"criterion_trial",
"reached_criterion",
"subject_criteria",
"sequence_occurrences",
"estimate_resources",
"print_resource_estimate",
]
109 changes: 90 additions & 19 deletions pycbas/_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -2043,9 +2048,75 @@ 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

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",
label="Download sequence occurrences (CSV)"),
pn.widgets.FileDownload(callback=csv("subjects"),
filename="cbas_subject_windows.csv",
label="Download subject windows (CSV)"),
),
pn.pane.Markdown(
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."""
Expand Down
Loading
Loading