Skip to content

Add sequence_occurrences: where each counted sequence occurred - #2

Open
droumis wants to merge 11 commits into
mainfrom
feat/sequence-occurrences
Open

droumis wants to merge 11 commits into
mainfrom
feat/sequence-occurrences

Conversation

@droumis

@droumis droumis commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Summary

Adds sequence_occurrences, which returns the start of every counted window of the given sequences, per subject, so timing summaries such as a group's median trial can be computed from exactly the windows the analysis counted.

  • Occurrence table: one row per counted window (subject_id, block, sequence, start, row, session). For every subject and sequence the number of rows equals that cell of the count matrix.
  • Subject table: one row per subject and contingency, including subjects that never used the sequences, with n_trials, reached and cutoff.
  • No summaries in the library. Medians and normalisation are analytic choices left to the caller; the guide gives a recipe for per-group medians.
  • CBASResult.counts_digest: a SHA-256 of the count matrix a result came from. sequence_occurrences recounts and raises if the counts differ, so mismatched settings or a filtered cohort cannot produce positions for data the analysis did not test. Defaults to None; no numbers change.
  • App: the Export tab offers both tables as CSV for the significant sequences, built from the cohort and settings the run used.

The counting code is unchanged. The window scan is separate from enumerate_sequences and is checked against the count matrix on every call.

Version is 0.3.0.dev0 on this branch, so an install from it is distinguishable from the 0.2.0 release.

Testing

  • pixi run python -m pytest tests/ -q: 288 passed.
  • Positions are checked against a plain-loop reference across criterion orders, block-aware counting, multi-contingency data, unreached criteria and irregular session layouts.
  • The guide's median recipe is executed as written by a test, on a cohort where one group never uses a sequence.
  • The app's downloads were exercised in a browser in comparative, correlative and multi-contingency modes.

To try it:

pip install "git+https://github.com/droumis/pycbas@feat/sequence-occurrences"

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.
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.
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.
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.
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.
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.
So an install from the branch reports a version distinct from the 0.2.0 release.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Count verification accepts altered trial data with identical counts, allowing occurrence exports to return timings from inputs that do not match the analysis.

4 open issues
What changed in this PR

Adds occurrence-level timing data to pycbas so callers can summarize when counted sequences appear, while leaving counting behavior unchanged and summaries to callers.

Changes:

  • Adds sequence_occurrences, returning window positions and per-subject counting cutoffs.
  • Records count-matrix digests in pipeline results for recount verification.
  • Adds app CSV exports from captured run inputs, with tests, documentation, and a development-version bump.
File Description
tests/​test_occurrences.py Tests positions, table structure, verification, and the median recipe.
tests/​test_multicontingency.py Checks digest recording for multi-contingency results.
tests/​test_cbas.py Tests result digests and their sensitivity to matrix changes.
tests/​test_app.py Tests occurrence downloads and captured-cohort behavior.
pycbas/​pipeline.py Records count digests across analysis pipelines.
pycbas/​params.py Adds the result digest field and hashing helper.
pycbas/​occurrences.py Implements occurrence scanning, tables, and recount checks.
pycbas/​_app.py Captures run inputs and adds occurrence CSV downloads.
pycbas/​__init__.py Exports the API and updates the development version.
pixi.toml Updates the workspace version to 0.3.0.dev0.
docs/​guide.md Explains positions, group medians, and timing caveats.
docs/​app.md Describes the new occurrence exports.
docs/​api.md Documents the occurrence API and result digest.
CHANGELOG.md Records the new API, digest, and app exports.

Review effort: Max

Comment thread pycbas/occurrences.py Resolved
Comment thread pycbas/occurrences.py Resolved
Comment thread pycbas/occurrences.py Resolved
Comment thread pycbas/occurrences.py Resolved
…nces

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.
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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Subject ID hashing can collide for different identity lists, allowing verification to accept mismatched subjects, and multi-contingency window endpoints are calculated incorrectly.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Encode subject IDs unambiguously in result digest

pycbas/​params.py:61

Joining IDs with an unescaped separator does not uniquely encode the ordered ID list. For example, ['a', 'b\x1fc'] and ['a\x1fb', 'c'] produce identical digests when counts and sequences are unchanged. Subject permits these string IDs, so verification against a CBASResult can accept different subject identities. Encode the list unambiguously, such as with its escaped representation, instead of joining its elements.

Low severity Use symbol count to calculate multi-contingency window endpoint

pycbas/​occurrences.py:81

For multi-contingency results, sequence is a (block, symbols) pair, so len(sequence) is always 2 and gives the wrong endpoint for windows of other lengths. Use len(split_sequence_entry(sequence)[1]) to calculate the endpoint for both entry formats. Same issue in docs/guide.md:467.

4 resolved since last review

Review effort: Balanced (adaptive)

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.
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.
@droumis

droumis commented Nov 27, 2026

Copy link
Copy Markdown
Owner Author

Both issues from the second Copilot review are fixed: subject ids are now hashed as a JSON array in counts_digest (fa27e1c), and the window end is given by its symbol count, len(split_sequence_entry(sequence)[1]), in the docstring and the guide (617ebd6).

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported, and the supplied evidence identifies comprehensive coverage of the new API, digest integration, validation, and application exports.

No open issues 🎉

Review effort: Lite

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants