# coding


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Why the scan is arithmetic

The scan in `00_core` scores **every** motif of every pattern against
every sequence, which is where its runtime goes. On strings — a Python
set of motif strings per sequence — that costs roughly 10 s and 2 GB of
RAM per pattern on a 30k-sequence library; on integers it is well under
a second.

A motif of pattern `(d1, spacer, d2)` is pinned down entirely by its
`d1 + d2` defined bases — the spacer is `N` by construction — so it can
be held as an integer in `[0, 4**(d1+d2))`. Every per-motif statistic
then becomes an `np.bincount` over those integers, and the library is
encoded once and reused for every pattern.

Nothing here decides anything biological: its only job is to give
exactly the answer a readable string-based scan would, faster. The
checks in this notebook hold the encoding to that, and
`tests/test_reference_scan.py` holds the whole scan to it.

### The base alphabet, and why it is `ACGT` in that order

`A=0, C=1, G=2, T=3`, and anything else — `N`, lowercase junk, the
padding of a short sequence — is `4`.

The order is not arbitrary. Complementary bases sit at opposite ends of
it, so **complementing a base is `3 - code`**: A↔T is 0↔3, C↔G is 1↔2.
That is the whole reverse-complement implementation, and it is why
[`encode_library`](https://dbikard.github.io/randseq/coding.html#encode_library)
can return the reverse strand for the price of one subtraction and one
reversal.

Code `4` does double duty: it marks a base that is not ACGT *and* the
padding that squares off a ragged library into a rectangular array. Both
must be excluded from the scan, and because they share a marker, one
test excludes both — there is no separate length bookkeeping to get
wrong.

------------------------------------------------------------------------

<a
href="https://github.com/dbikard/randseq/blob/main/randseq/coding.py#L22"
target="_blank" style="float:right; font-size:smaller">source</a>

### encode_library

Encode DNA sequences as base codes, the form the scan reads
(`encoded_library`).

``` python
encode_library(sequences)
```

<table>
<colgroup>
<col style="width: 25%" />
<col style="width: 25%" />
<col style="width: 25%" />
<col style="width: 25%" />
</colgroup>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>sequences</code></td>
<td>list</td>
<td></td>
<td>DNA strings, e.g. inserts with their flanks; lengths may differ</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>tuple</td>
<td></td>
<td><code>(fwd, rc)</code>: uint8 base codes (n_sequences, max_length)
of each sequence and its rc</td>
</tr>
</tbody>
</table>

``` python
fwd, rc = encode_library(["ACGTT", "ggN"])
fwd, rc
```

    (array([[0, 1, 2, 3, 3],
            [2, 2, 4, 4, 4]], dtype=uint8),
     array([[0, 0, 1, 2, 3],
            [4, 1, 1, 4, 4]], dtype=uint8))

Both strands are left-aligned and padded on the right, so row `i` of
`rc` is the reverse complement of sequence `i` occupying its first
`len(s)` columns — not a reversal of the padded row, which would put the
padding at the front.

### From a window to an integer, and back

Write the `d1 + d2` defined bases of a motif as the digits of a **base-4
numeral**:

    CAC NNNN GTAT   ->  digits C,A,C,G,T,A,T  ->  1·4⁶ + 0·4⁵ + 1·4⁴ + 2·4³ + 3·4² + 0·4 + 3

[`_pattern_window_codes`](https://dbikard.github.io/randseq/coding.html#_pattern_window_codes)
builds that numeral by Horner’s method — `code = code*4 + next_digit`,
one pass over the defined positions in increasing order. The trick that
makes it fast is that each step operates on a **sliding view**,
`encoded_seqs[:, j:j+n_windows]`: position `j` of the window starting at
`w` is absolute index `w+j`, so as `w` runs over all windows that column
is exactly the slice above. Every window of every sequence is therefore
built in parallel, with one vector operation per defined base rather
than one per window.

**Rejecting windows.** A window containing a non-ACGT base anywhere —
spacer included, to match the `[ATGC]` regex the reference
implementation uses — is set to `4**(d1+d2)`, one past the largest real
code. Which windows those are comes from a prefix sum over the `== 4`
mask: the number of bad bases in `[w, w+width)` is
`n_bad[w+width] - n_bad[w]`, so all windows are tested at once. Padding
is code 4, so a window running off the end of a short sequence is
rejected by the same test, with nothing extra written for it.

**Decoding** reverses the numeral. Base 4 is two bits, so digit `i`
counted from the most significant is `(code >> 2*(n-1-i)) & 3` — the
same digits in the same order the encoder wrote them.
[`_decode_motif_codes`](https://dbikard.github.io/randseq/coding.html#_decode_motif_codes)
then drops `N` into the spacer positions.

With pattern `(1, 2, 2)`, `CAAGT` has a single window whose defined
bases are C, G, T, i.e. code `1*16 + 2*4 + 3 = 27`. A window touching
the `N` is rejected (code `4**3 = 64`):

``` python
fwd, rc = encode_library(["CAAGT", "CAAGTN"])

# A=0 C=1 G=2 T=3, so a motif's code is literally its defined bases as a base-4 numeral:
# CNNGT of pattern (1,2,2) has defined bases C,G,T -> digits 1,2,3 -> int("123", 4).
CNNGT = int("123", 4)
REJECTED = 4 ** 3            # the sentinel: one past the largest 3-digit base-4 numeral
print(f"CNNGT = {CNNGT}, REJECTED = {REJECTED}")
print(_pattern_window_codes(fwd, (1, 2, 2)))
_decode_motif_codes([CNNGT, int("000", 4)], (1, 2, 2))
```

    CNNGT = 27, REJECTED = 64
    [[27 64]
     [27 64]]

    ['CNNGT', 'ANNAA']

### What guarantees this is right?

The scan reports a motif string, but everything between the library and
that string is integer arithmetic. Four properties have to hold, or the
output is confidently wrong rather than obviously broken.

**1. Distinct motifs get distinct codes.** A base-4 numeral with a
*fixed* number of digits is unique to its digit string — that is just
positional notation — and the digit count is fixed at `d1+d2` for a
given pattern. Two different motifs of the same pattern therefore cannot
collide.

**2. Decoding is exactly the inverse of encoding.** Both walk the same
`d1+d2` positions in the same order; the encoder multiplies up, the
decoder shifts down. Cheap enough to check *exhaustively* rather than
argue about, which this notebook’s tests do.

**3. A rejected window can never be read as a motif.** Real codes fill
`[0, 4**(d1+d2))` and the sentinel is `4**(d1+d2)` exactly, so the
single test `code < 4**(d1+d2)` separates them with no gap and no
overlap. This is why the sentinel is that value and not, say, `-1`.

**4. The arithmetic stays in range.** Codes are `int32`, which holds 15
defined bases; the shipped patterns use at most 8. Beyond 15 the numeral
would wrap and every count for that pattern would be quietly wrong, so
[`_pattern_window_codes`](https://dbikard.github.io/randseq/coding.html#_pattern_window_codes)
raises instead.

Properties 1–3 hold by construction and are verified exhaustively by
this notebook’s tests. Whether the *whole scan* means the same thing as
a readable implementation is a separate question:
`tests/test_reference_scan.py` runs
[`_get_pattern_scores`](https://dbikard.github.io/randseq/fast.html#_get_pattern_scores)
against the string-based scan in `tests/reference_scan.py` and requires
identical tables.

### Encoding a motif back to its code

[`_encode_motif`](https://dbikard.github.io/randseq/coding.html#_encode_motif)
is the inverse of
[`_decode_motif_codes`](https://dbikard.github.io/randseq/coding.html#_decode_motif_codes):
it turns a motif string back into the integer the scan counts under. It
returns `None` for anything it cannot represent — an IUPAC-degenerate
motif has no single code, and nor has a motif that does not fit the
pattern — so a caller can expand a degenerate motif into its instances
([`_motif_instances`](https://dbikard.github.io/randseq/core.html#_motif_instances)
in `core`) or fall back to a regex, rather than silently mis-assign
sequences. `tests/test_vectorized_presence.py` checks the two paths
agree element for element.

``` python
# the decode example above, inverted: CNNGT is digits 1,2,3; an IUPAC base has no single code
_encode_motif("CNNGT", (1, 2, 2)), _encode_motif("YNNGT", (1, 2, 2))
```

    (27, None)

### The two strands of one site

An enzyme cuts a double-stranded site, so `GAGACC` and `GGTCTC` are one
motif seen from two sides, and the scan must not count them as two.
*Where* they can be folded together is decided by the pattern, because a
motif of `(d1, spacer, d2)` reverse-complements into one of
`(d2, spacer, d1)`:

- when that is the **same** shape — a contiguous motif (`spacer == 0`),
  or a balanced one (`d1 == d2`) — both spellings are codes in the
  *same* space, and one physical site is found twice, once per strand.
  These fold.
- otherwise the rc spelling lives in **another pattern’s** space.
  Nothing to fold: scanning `(3, 4, 4)` on both strands already finds
  each site exactly once, because a `(4, 4, 3)` site is read on the
  reverse strand and spelled as `(3, 4, 4)`. This is why
  [`find_restricted_motifs`](https://dbikard.github.io/randseq/core.html#find_restricted_motifs)
  rewrites every pattern to its
  [`_canonical_pattern`](https://dbikard.github.io/randseq/utils.html#_canonical_pattern)
  and drops duplicates — searching both shapes would re-find the same
  sites in mirror spelling, at twice the cost.

Folding an asymmetric pattern would merge two *unrelated* motifs, since
reversing the digits of a `(4, 4, 3)` code reads the `d2` bases where
the `d1` bases belong.
[`_rc_code_table`](https://dbikard.github.io/randseq/coding.html#_rc_code_table)
therefore refuses any pattern that is not self-rc.

The table itself is one observation: a code is the defined bases as a
base-4 numeral, and the defined bases of the reverse complement are
those digits **reversed and complemented** (`A<->T, C<->G` is
`3 - digit`). The spacer is undefined on both strands, so it plays no
part. Because each base is two bits, both operations are bit arithmetic
on the code: complementing every digit is a single XOR with `11`
repeated `k` times, and reversing the digits is reversing the order of
the 2-bit groups.
[`_rc_code_table`](https://dbikard.github.io/randseq/coding.html#_rc_code_table)
builds the table that way, and this notebook’s tests check it against
[`revcomp`](https://dbikard.github.io/randseq/utils.html#revcomp) on the
motif strings over entire code spaces.

``` python
# GAGACC and GGTCTC are one site: the table maps each spelling's code to the other's
_t = _rc_code_table((6, 0, 0))
print(_decode_motif_codes([_t[_encode_motif("GAGACC", (6, 0, 0))]], (6, 0, 0)))
# contiguous and balanced patterns fold; (3, 4, 4) does not, its rc motifs are (4, 4, 3)
[_pattern_is_self_rc(p) for p in [(6, 0, 0), (4, 4, 4), (3, 4, 4)]]
```

    ['GGTCTC']

    [True, True, False]

## Scanning one pattern

A pattern is scored from two arrays: which motifs each sequence carries,
and the totals of each motif over its carriers. The library below is
twelve inserts of twelve bases with `GAGACC` (`GGTCTC` on the other
strand) planted in four of them, and those four are the depleted ones,
so a correct scan must report `GAGACC` on four plasmids, all depleted.

``` python
demo_lib = ["GAGACCTTAACG", "TTGAGACCGCAT", "ACGGTCTCAATG", "CCAAGAGACCTT",
            "ACGTTGCAATGC", "TTACGCATTGCA", "GCATTACGGTTA", "ATGCCATTGCAA",
            "CATGCAATTGCG", "TTGCAATGCCAT", "GCAATTGCATGC", "ATTGCCATGCAA"]
demo_fc = np.array([-2.5, -3.0, -3.5, -3.0, 0.2, -0.1, 0.0, 0.3, -0.2, 0.1, 0.0, -0.3])

pd.DataFrame({"insert": demo_lib, "log2FC": demo_fc,
              "carries the site": [("GAGACC" in s) or ("GGTCTC" in s) for s in demo_lib],
              "depleted (< -1)": demo_fc < -1})
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">insert</th>
<th data-quarto-table-cell-role="th">log2FC</th>
<th data-quarto-table-cell-role="th">carries the site</th>
<th data-quarto-table-cell-role="th">depleted (&lt; -1)</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>GAGACCTTAACG</td>
<td>-2.5</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>TTGAGACCGCAT</td>
<td>-3.0</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>ACGGTCTCAATG</td>
<td>-3.5</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>CCAAGAGACCTT</td>
<td>-3.0</td>
<td>True</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>ACGTTGCAATGC</td>
<td>0.2</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>TTACGCATTGCA</td>
<td>-0.1</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>GCATTACGGTTA</td>
<td>0.0</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>ATGCCATTGCAA</td>
<td>0.3</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>CATGCAATTGCG</td>
<td>-0.2</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">9</td>
<td>TTGCAATGCCAT</td>
<td>0.1</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">10</td>
<td>GCAATTGCATGC</td>
<td>0.0</td>
<td>False</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">11</td>
<td>ATTGCCATGCAA</td>
<td>-0.3</td>
<td>False</td>
<td>False</td>
</tr>
</tbody>
</table>

</div>

**Which motifs each sequence carries.**
[`_motif_occurrences`](https://dbikard.github.io/randseq/coding.html#_motif_occurrences)
scans every window of both strands and reduces the result to one entry
per sequence and motif: a motif occurring twice in an insert, or once on
each strand, is one plasmid carrying it. For a self-rc pattern the two
spellings of a site are folded onto the smaller code
([`_rc_code_table`](https://dbikard.github.io/randseq/coding.html#_rc_code_table));
for any other pattern the rc spelling is not in this code space, so
there is nothing to fold. Either way each pattern emits one row per
plasmid per site.

``` python
seq_idx, motif_codes = _motif_occurrences(encode_library(demo_lib), (6, 0, 0))
occurrences = pd.DataFrame({
    "sequence": [demo_lib[i] for i in seq_idx],
    "motif": _decode_motif_codes(motif_codes, (6, 0, 0)),
    # the code IS the motif: A=0 C=1 G=2 T=3, read as a base-4 numeral
    "code (base 4)": [np.base_repr(c, 4).zfill(6) for c in motif_codes],
    "code": motif_codes})
print(f"{len(occurrences)} (sequence, motif) pairs from {len(demo_lib)} sequences")
occurrences.head(8)
```

    82 (sequence, motif) pairs from 12 sequences

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">sequence</th>
<th data-quarto-table-cell-role="th">motif</th>
<th data-quarto-table-cell-role="th">code (base 4)</th>
<th data-quarto-table-cell-role="th">code</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>GAGACCTTAACG</td>
<td>AAGGTC</td>
<td>002231</td>
<td>173</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>GAGACCTTAACG</td>
<td>ACCTTA</td>
<td>011330</td>
<td>380</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>GAGACCTTAACG</td>
<td>AGACCT</td>
<td>020113</td>
<td>535</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>GAGACCTTAACG</td>
<td>CCTTAA</td>
<td>113300</td>
<td>1520</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>GAGACCTTAACG</td>
<td>CGTTAA</td>
<td>123300</td>
<td>1776</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>GAGACCTTAACG</td>
<td>CTTAAC</td>
<td>133001</td>
<td>1985</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>GAGACCTTAACG</td>
<td>GAGACC</td>
<td>202011</td>
<td>2181</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>TTGAGACCGCAT</td>
<td>ACCGCA</td>
<td>011210</td>
<td>356</td>
</tr>
</tbody>
</table>

</div>

Each row is one plasmid carrying one motif, and the base-4 column shows
that a code **is** the motif: `GAGACC` is `202011`. The planted site:

``` python
occurrences[occurrences.motif.isin(["GAGACC", "GGTCTC"])]
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">sequence</th>
<th data-quarto-table-cell-role="th">motif</th>
<th data-quarto-table-cell-role="th">code (base 4)</th>
<th data-quarto-table-cell-role="th">code</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>GAGACCTTAACG</td>
<td>GAGACC</td>
<td>202011</td>
<td>2181</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">11</td>
<td>TTGAGACCGCAT</td>
<td>GAGACC</td>
<td>202011</td>
<td>2181</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">18</td>
<td>ACGGTCTCAATG</td>
<td>GAGACC</td>
<td>202011</td>
<td>2181</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">27</td>
<td>CCAAGAGACCTT</td>
<td>GAGACC</td>
<td>202011</td>
<td>2181</td>
</tr>
</tbody>
</table>

</div>

Four sequences, one row each: `GGTCTC` is the same site read on the
other strand, folded onto `GAGACC`, the smaller numeral. Reporting
re-spells it on the strand REBASE uses
([`canonical_motif`](https://dbikard.github.io/randseq/utils.html#canonical_motif)).

A window containing a base other than ACGT is dropped, and so is one
running past the end of a short sequence, since padding carries the same
code as `N`:

``` python
edge = ["GAGACCTT",           # clean
        "GAGACCTTNAAAAAA",    # an N at position 8, then six more bases
        "GAGAC"]              # shorter than the 6-base pattern
_s, _c = _motif_occurrences(encode_library(edge), (6, 0, 0))
pd.DataFrame({"sequence": [edge[i] for i in _s], "motif": _decode_motif_codes(_c, (6, 0, 0))})
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">sequence</th>
<th data-quarto-table-cell-role="th">motif</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>GAGACCTT</td>
<td>AAGGTC</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>GAGACCTT</td>
<td>AGACCT</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>GAGACCTT</td>
<td>GAGACC</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>GAGACCTTNAAAAAA</td>
<td>AAAAAA</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>GAGACCTTNAAAAAA</td>
<td>AAGGTC</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>GAGACCTTNAAAAAA</td>
<td>AGACCT</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>GAGACCTTNAAAAAA</td>
<td>GAGACC</td>
</tr>
</tbody>
</table>

</div>

The second insert keeps the windows that end before its `N`, loses the
six that cover it, and picks up `AAAAAA` after it (`TTTTTT` on the other
strand, folded). Every window of the third runs into the padding.

**Totals per motif.** Every statistic the scan reports is a sum over a
motif’s carriers, so each is one `np.bincount`: carriers, depleted
carriers, the sum of their log2FC, the sum of their background (each
plasmid’s expected depletion rate, from
[`plasmid_background`](https://dbikard.github.io/randseq/utils.html#plasmid_background);
here one rate for all), and the first carrier, which makes the output
order a function of the library rather than of hash order.

``` python
demo_bg = np.full(len(demo_lib), (demo_fc < -1).mean())      # one rate for all: 4 of 12
n_seqs, n_depleted, fc_sum, bg_sum, first_seq = _motif_totals(
    seq_idx, motif_codes, demo_fc, demo_bg, -1, 4 ** 6)

present = np.flatnonzero(n_seqs)                 # the motifs this library actually contains
totals = pd.DataFrame({"motif": _decode_motif_codes(present, (6, 0, 0)),
                       "n_seqs": n_seqs[present], "n_depleted": n_depleted[present],
                       "sum_log2fc": fc_sum[present], "sum_background": bg_sum[present],
                       "first_seq": first_seq[present]})
print(f"{len(totals)} motifs present out of {4 ** 6} possible")
totals.sort_values(["n_depleted", "n_seqs"], ascending=False).head(6)
```

    53 motifs present out of 4096 possible

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">motif</th>
<th data-quarto-table-cell-role="th">n_seqs</th>
<th data-quarto-table-cell-role="th">n_depleted</th>
<th data-quarto-table-cell-role="th">sum_log2fc</th>
<th data-quarto-table-cell-role="th">sum_background</th>
<th data-quarto-table-cell-role="th">first_seq</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">43</td>
<td>GAGACC</td>
<td>4</td>
<td>4.0</td>
<td>-12.0</td>
<td>1.333333</td>
<td>0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>AAGGTC</td>
<td>2</td>
<td>2.0</td>
<td>-5.5</td>
<td>0.666667</td>
<td>0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">13</td>
<td>AGACCG</td>
<td>2</td>
<td>2.0</td>
<td>-6.5</td>
<td>0.666667</td>
<td>1</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">14</td>
<td>AGACCT</td>
<td>2</td>
<td>2.0</td>
<td>-5.5</td>
<td>0.666667</td>
<td>0</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">47</td>
<td>GTCTCA</td>
<td>2</td>
<td>2.0</td>
<td>-6.5</td>
<td>0.666667</td>
<td>1</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">50</td>
<td>TCTCAA</td>
<td>2</td>
<td>2.0</td>
<td>-6.5</td>
<td>0.666667</td>
<td>1</td>
</tr>
</tbody>
</table>

</div>

`GAGACC` tops the table with four carriers, all depleted. `05_fast`
turns these totals into the reported scores, and adds a compiled kernel
that computes them in one pass.

## Reading motif presence off the window codes

Scoring a pattern asks what motifs a sequence contains. The rest of the
pipeline asks the reverse, of a handful of specific candidates: **which
sequences contain this motif, on either strand?**

Done directly that is a regex per sequence per motif, and a noisy
strain, which carries the most candidates, pays for it most. Instead
presence is a **lookup in the window codes**, done once per pattern
rather than once per motif: for 200 motifs of 4 patterns on the 150 nt
example library (`counts_panel.csv.gz`, 30,108 inserts after the count
filter), 0.3 s against 6 s for the regex, with identical answers.

[`_motif_presence_matrix`](https://dbikard.github.io/randseq/coding.html#_motif_presence_matrix)
returns `(matrix, handled)`. A motif the fast path cannot encode —
IUPAC-degenerate, or of an unknown pattern — is left as an all-`False`
column and flagged in `handled`, so the caller does not read a blank
column as “absent”: `core` reads a degenerate motif through its
instances, each of which has a code, and a motif of unknown pattern by
regex.

With `insert` (the lengths of the two flanks and of each insert) it also
says which sequences carry the motif wholly inside the insert, from the
same windows: this is how `core` tells a site from one the vector flank
completes (*Sites completed by the flank*).

``` python
_seqs = ["GAGACCTT", "AAGGTCTC", "TTTTTTTT", "GGGGGGGG"]
_m, _handled = _motif_presence_matrix(encode_library(_seqs), ["GAGACC", "TTTTTT"],
                                     [(6, 0, 0), (6, 0, 0)])
pd.DataFrame(_m, index=_seqs, columns=["GAGACC", "TTTTTT"])
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

<table class="dataframe" data-quarto-postprocess="true" data-border="1">
<thead>
<tr style="text-align: right;">
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th">GAGACC</th>
<th data-quarto-table-cell-role="th">TTTTTT</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">GAGACCTT</td>
<td>True</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">AAGGTCTC</td>
<td>True</td>
<td>False</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">TTTTTTTT</td>
<td>False</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">GGGGGGGG</td>
<td>False</td>
<td>False</td>
</tr>
</tbody>
</table>

</div>

One row per sequence, one column per motif. `GAGACC` is found in the
second sequence only on the other strand, where it is spelled `GGTCTC`:
presence means “on either strand”.
