# fast


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

## Why a second implementation of the scan

Without numba, one pattern is totalled by the numpy steps of `04_coding`
— window codes for every position of both strands, a sort per row to
collapse repeats, and `bincount`s over what is left. Each step is a full
pass over an intermediate array of `n_sequences x 2 x insert length`,
and on a 30k-sequence library that is about 0.2 s per pattern. No single
step dominates, so no numpy rewrite of one step buys much.

The kernel here fuses all of it into one compiled pass over the
sequences. For each window it computes the code directly from the 2-bit
bases, folds a self-reverse-complementary code onto `min(code, rc)` with
the digit formula, and skips the window if this sequence has already
counted that code — a *stamp* array recording the last sequence seen per
code, which replaces the sort. What it accumulates is exactly what
`_motif_totals(*_motif_occurrences(...))` returns, so
[`_scan_pattern`](https://dbikard.github.io/randseq/fast.html#_scan_pattern)
can take either path and nothing downstream can tell which ran.

Measured on the 150 nt example library (`counts_panel.csv.gz`, 30,108
inserts after the count filter) over the 43 shipped patterns: numpy 8.7
s, this kernel 3.0 s on one core and 0.5 s on eight. The first call in a
process also pays a one-off compile of about 4 s, cached on disk
afterwards where the package directory is writable.

### It is optional

numba is not a hard dependency. Install it with the `fast` extra:

``` sh
pip install "randseq[fast] @ git+https://github.com/dbikard/randseq.git"
```

Without it, `HAVE_NUMBA` is `False` and the scan runs the numpy path,
which is the readable statement of the algorithm and the reference this
kernel is tested against. Setting the environment variable
`RANDSEQ_NO_NUMBA=1` before importing `randseq` forces the numpy path
even when numba is installed.

``` python
from randseq.coding import encode_library, _encode_motif
```

``` python
if HAVE_NUMBA:
    # the second sequence is the reverse complement of the first
    _enc = encode_library(["GAGACCTT", "AAGGTCTC", "TTTTTTTT"])
    n, n_dep, fc_sum, bg_sum, first = _pattern_totals(_enc, (6, 0, 0), [-3.0, -2.0, 0.5],
                                                     [0.25, 0.5, 0.125], log2FC_thr=-1)
    # (6, 0, 0) is self-rc, so GAGACC and GGTCTC fold onto the smaller code: both of the first two
    # sequences carry it, both are depleted, their backgrounds add, and the first carrier is 0
    _g = _encode_motif("GAGACC", (6, 0, 0))
    print("GAGACC: carriers", n[_g], " depleted", n_dep[_g], " log2FC sum", fc_sum[_g],
          " background sum", bg_sum[_g], " first carrier", first[_g])
```

    GAGACC: carriers 2  depleted 2.0  log2FC sum -5.0  background sum 0.75  first carrier 0

### What guarantees this is the same scan?

The kernel re-implements every rule the numpy path applies — rejecting a
window with a non-ACGT base or padding, folding the strands of a self-rc
pattern, counting a motif once per sequence — so this notebook’s tests
check each against
[`_motif_occurrences`](https://dbikard.github.io/randseq/coding.html#_motif_occurrences) +
[`_motif_totals`](https://dbikard.github.io/randseq/coding.html#_motif_totals):
on the example library for contiguous, balanced and asymmetric patterns,
and on random ragged libraries containing `N`. `tests/test_fast_scan.py`
repeats the comparison over all 43 shipped patterns, and runs the whole
[`_get_pattern_scores`](https://dbikard.github.io/randseq/fast.html#_get_pattern_scores)
both ways. Counts and background sums must agree exactly —
[`plasmid_background`](https://dbikard.github.io/randseq/utils.html#plasmid_background)
returns multiples of 2⁻²⁰, which add exactly in any order — and the
log2FC sums to 1e-9, since the threads add them in a different order.

## One pattern’s scores

[`_scan_pattern`](https://dbikard.github.io/randseq/fast.html#_scan_pattern)
returns a pattern’s totals from the kernel when numba is installed and
from the numpy steps of `04_coding` otherwise, so every count the
pipeline makes of “the plasmids carrying a motif” comes from one place.
[`_get_pattern_scores`](https://dbikard.github.io/randseq/fast.html#_get_pattern_scores)
turns the totals into the reported table: `fraction_depleted` is
depleted carriers over carriers, `avg_log2fc` their mean log2FC, and
`p_value` the binomial test of the depleted count against the carriers’
mean background (`01_utils`).

``` python
# The twelve inserts of `04_coding`: GAGACC planted in the four depleted ones
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])
scores = _get_pattern_scores(encode_library(demo_lib), demo_fc, (6, 0, 0))
scores.sort_values(["fraction_depleted", "num_sequences"], ascending=False).head(6)
```

<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">fraction_depleted</th>
<th data-quarto-table-cell-role="th">num_sequences</th>
<th data-quarto-table-cell-role="th">avg_log2fc</th>
<th data-quarto-table-cell-role="th">p_value</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>GAGACC</td>
<td>1.0</td>
<td>4</td>
<td>-3.00</td>
<td>0.012346</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>AAGGTC</td>
<td>1.0</td>
<td>2</td>
<td>-2.75</td>
<td>0.111111</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>AGACCT</td>
<td>1.0</td>
<td>2</td>
<td>-2.75</td>
<td>0.111111</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>AGACCG</td>
<td>1.0</td>
<td>2</td>
<td>-3.25</td>
<td>0.111111</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">11</td>
<td>GTCTCA</td>
<td>1.0</td>
<td>2</td>
<td>-3.25</td>
<td>0.111111</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">12</td>
<td>TCTCAA</td>
<td>1.0</td>
<td>2</td>
<td>-3.25</td>
<td>0.111111</td>
</tr>
</tbody>
</table>

</div>

The planted site comes out at `fraction_depleted` 1.0 on four plasmids,
with a mean log2FC of −3.0. The motifs below it are 6-mers overlapping
the planted site, on two plasmids each: too few to judge, which is what
`min_support` exists to discard.
