# core


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

## What RandSeq measures

A library of plasmids carrying random inserts is conjugated into a
recipient strain. A plasmid whose insert contains a site recognised by
an active restriction system is destroyed on entry, so it is
**depleted** relative to the input library. This module works back from
each plasmid’s depletion to the motifs responsible.

### The method in four sentences

Every plasmid gets a **log2FC**: how much rarer it became after
delivery. Every motif gets the plasmids that contain it, and so a set of
log2FC values. A motif’s **score** is the fraction of those values below
a threshold — what fraction of the plasmids carrying this motif were
destroyed. Everything after that is deciding **which of the many motifs
that score well is the actual site**.

In steps:

1.  counts → log2FC per plasmid
2.  score every motif of every requested pattern — **the scan**
3.  keep one description per site, discarding the same site written more
    or less specifically; set aside a candidate the vector flanks
    complete unless its sites inside the insert support it
4.  drop a candidate whose score was borrowed from a stronger one
5.  report each motif on its canonical strand, tested against the
    depletion of plasmids of the same GC content, with a degenerate site
    written as one IUPAC motif

Steps 3 and 4 are two halves of one problem: **one real site makes many
motifs score well.** Step 3 compares motif *strings*; step 4 compares
the *plasmids* motifs are found in, which relates descriptions too
different for a string rule.

### The example data

- `countsTable.csv.gz` — 19 recipient strains, with the donor `MFDpir`
  as the input library; 11,629 inserts of 20 nt
- `counts_panel.csv.gz` — 8 recipient strains and two donor replicates
  (`Control_R1`, `Control_R2`), each strain picked to exercise one
  behaviour of the pipeline (`example_data/counts_panel_key.csv` says
  which); 34,217 inserts, mostly 150 nt

*E. coli* JJ1886 is in both, so two measurements of one strain must
agree on which motifs they call and on which strand they name them.

## Step 1: counts → log2FC per plasmid

The input is a table of read counts, one row per insert sequence and one
column per sample, one of which is the input library.
[`calculate_log2fc`](https://dbikard.github.io/randseq/utils.html#calculate_log2fc)
turns it into a log2 fold change per insert against that column: inserts
too rare in the input are dropped, a pseudocount is added, each sample
is converted to shares and normalised so that its median plasmid sits at
0. `01_utils` explains each choice (*Counts to log2 fold change*).
Everything downstream works on one column: a Series indexed by insert
sequence.

``` python
counts_file="countsTable.csv.gz"
file_path=os.path.join(data_path,counts_file)
counts=pd.read_csv(file_path, index_col=0)
counts = counts[[col for col in counts.columns if ("_T0" in col) or ("MFDpir" in col)]]
log2fc_df = calculate_log2fc(counts, reference_column='MFDpir', count_threshold=20, pseudocount=1)
log2fc_df
```

<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">K12_T0</th>
<th data-quarto-table-cell-role="th">HS_T0</th>
<th data-quarto-table-cell-role="th">E1114_T0</th>
<th data-quarto-table-cell-role="th">E1167_T0</th>
<th data-quarto-table-cell-role="th">H120_T0</th>
<th data-quarto-table-cell-role="th">TA054_T0</th>
<th data-quarto-table-cell-role="th">TA447_T0</th>
<th data-quarto-table-cell-role="th">E101_T0</th>
<th data-quarto-table-cell-role="th">41-1Ti9_T0</th>
<th data-quarto-table-cell-role="th">TA280_T0</th>
<th data-quarto-table-cell-role="th">M114_T0</th>
<th data-quarto-table-cell-role="th">TA249_T0</th>
<th data-quarto-table-cell-role="th">ROAR8_T0</th>
<th data-quarto-table-cell-role="th">JJ1886_T0</th>
<th data-quarto-table-cell-role="th">CFT073_T0</th>
<th data-quarto-table-cell-role="th">APECO1_T0</th>
<th data-quarto-table-cell-role="th">UTI89_T0</th>
<th data-quarto-table-cell-role="th">S88_T0</th>
<th data-quarto-table-cell-role="th">MG1655_T0</th>
</tr>
<tr>
<th data-quarto-table-cell-role="th">seq</th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
<th data-quarto-table-cell-role="th"></th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">CGGAGGTACTGGGTACATTT</td>
<td>0.053839</td>
<td>0.052486</td>
<td>0.198139</td>
<td>-0.298920</td>
<td>0.248968</td>
<td>0.064302</td>
<td>0.173654</td>
<td>0.091857</td>
<td>0.037475</td>
<td>0.105217</td>
<td>-0.332624</td>
<td>-0.063143</td>
<td>0.153653</td>
<td>0.035279</td>
<td>0.199444</td>
<td>0.216417</td>
<td>-0.420177</td>
<td>0.208060</td>
<td>0.129389</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">TGGCGATAATGCCGGCTATC</td>
<td>0.055484</td>
<td>0.140062</td>
<td>0.447659</td>
<td>0.116408</td>
<td>0.148431</td>
<td>0.073310</td>
<td>0.050872</td>
<td>-0.015937</td>
<td>-0.000986</td>
<td>-0.027312</td>
<td>0.000043</td>
<td>0.123943</td>
<td>-0.158044</td>
<td>-0.031221</td>
<td>0.028689</td>
<td>0.003235</td>
<td>-0.170595</td>
<td>0.086728</td>
<td>0.140558</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">TTCCAGTTCACTGGTCTTCG</td>
<td>-0.039673</td>
<td>0.052838</td>
<td>-0.094876</td>
<td>-0.058226</td>
<td>-0.071222</td>
<td>-0.059618</td>
<td>0.389411</td>
<td>0.086398</td>
<td>0.215640</td>
<td>0.125599</td>
<td>0.201220</td>
<td>-0.066652</td>
<td>-0.003432</td>
<td>0.236186</td>
<td>-0.180337</td>
<td>0.256712</td>
<td>0.218989</td>
<td>0.452512</td>
<td>0.167261</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">AATTTCAGTGCCGTTCAGAT</td>
<td>-0.241936</td>
<td>-0.419289</td>
<td>-0.214320</td>
<td>-0.055334</td>
<td>-0.193911</td>
<td>-0.180443</td>
<td>-0.233472</td>
<td>-0.144541</td>
<td>-0.269051</td>
<td>-0.206790</td>
<td>0.055304</td>
<td>-0.024940</td>
<td>-0.019646</td>
<td>-0.091950</td>
<td>-0.108537</td>
<td>-0.267889</td>
<td>0.497149</td>
<td>-0.189453</td>
<td>-0.142007</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">CTGCGGTAATAATTCCCGCC</td>
<td>-0.168407</td>
<td>-0.151090</td>
<td>0.591358</td>
<td>0.405361</td>
<td>0.057666</td>
<td>-0.297286</td>
<td>-0.213485</td>
<td>-0.293529</td>
<td>-0.465928</td>
<td>-0.300698</td>
<td>-0.225458</td>
<td>-0.020998</td>
<td>0.095261</td>
<td>-0.328740</td>
<td>-0.219906</td>
<td>-0.110738</td>
<td>-0.311057</td>
<td>-0.194322</td>
<td>-0.147295</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">GCTTGATGTAGCCTTCGAAC</td>
<td>-0.090498</td>
<td>-0.077031</td>
<td>0.037574</td>
<td>-0.264828</td>
<td>-0.327042</td>
<td>-0.034614</td>
<td>-0.085175</td>
<td>-0.247852</td>
<td>-0.242389</td>
<td>-0.144174</td>
<td>-0.095388</td>
<td>0.034867</td>
<td>0.270337</td>
<td>-0.224290</td>
<td>0.265613</td>
<td>-0.219473</td>
<td>-0.282711</td>
<td>-0.061401</td>
<td>-0.094254</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">TAATGGCAAATTGACACTCC</td>
<td>0.268225</td>
<td>0.106618</td>
<td>0.438321</td>
<td>-0.102874</td>
<td>0.258529</td>
<td>0.063001</td>
<td>0.227910</td>
<td>0.131522</td>
<td>0.203018</td>
<td>0.094437</td>
<td>0.478815</td>
<td>-0.129064</td>
<td>0.000404</td>
<td>0.175361</td>
<td>-0.003251</td>
<td>0.204180</td>
<td>0.490384</td>
<td>0.196397</td>
<td>0.425986</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">GCTGCGCGCGGAGTTGTTCC</td>
<td>-0.619835</td>
<td>-0.378119</td>
<td>-0.421264</td>
<td>-0.324669</td>
<td>-0.451031</td>
<td>-0.246031</td>
<td>-0.455210</td>
<td>-0.359524</td>
<td>-0.364741</td>
<td>-0.361490</td>
<td>-0.585051</td>
<td>0.214125</td>
<td>-0.975015</td>
<td>-0.323065</td>
<td>-0.503433</td>
<td>-0.135453</td>
<td>-0.525759</td>
<td>-0.503168</td>
<td>-0.920714</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">GCAACACGCCAGTAAGGTGT</td>
<td>0.703437</td>
<td>0.490088</td>
<td>0.754857</td>
<td>-0.051391</td>
<td>0.485527</td>
<td>0.597611</td>
<td>0.149697</td>
<td>0.386591</td>
<td>0.741034</td>
<td>0.278790</td>
<td>0.164374</td>
<td>0.645063</td>
<td>0.409897</td>
<td>0.002233</td>
<td>0.408861</td>
<td>0.085801</td>
<td>0.331181</td>
<td>0.058894</td>
<td>0.415349</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">GATAGCCGGATAGCTTAAGG</td>
<td>-0.235664</td>
<td>-0.128696</td>
<td>-0.418972</td>
<td>-0.210574</td>
<td>-0.260554</td>
<td>-0.158647</td>
<td>-0.028420</td>
<td>-0.356935</td>
<td>-0.228562</td>
<td>-0.094755</td>
<td>-0.302651</td>
<td>-0.243483</td>
<td>-0.124763</td>
<td>-0.128952</td>
<td>-0.224737</td>
<td>-0.164897</td>
<td>-0.117829</td>
<td>-0.406399</td>
<td>0.179141</td>
</tr>
</tbody>
</table>

<p>11503 rows × 19 columns</p>
</div>

## Step 2: score every motif

Every motif of every **pattern** is scored over
`left_flank + insert + right_flank`, on both strands. A pattern is the
shape of a site, `(d1, spacer, d2)`: defined bases, undefined gap,
defined bases. `(6, 0, 0)` is a contiguous site like `GGTCTC`;
`(3, 4, 4)` a bipartite site like `CACNNNNGTAT`.
[`get_patterns()`](https://dbikard.github.io/randseq/utils.html#get_patterns)
returns the shapes REBASE records for Type I, II and III systems; a site
whose shape is not searched cannot be found.

The flanks are scanned because a site can **straddle the junction**
between insert and vector. In the 150 nt panel library the left flank
ends in `AAAC`, so every insert that starts `NNNNGTC` completes B156’s
site `AAACNNNNGTC`: 382 of the 894 plasmids that carry the site in B156
carry it across the junction.

A motif is counted **once per plasmid**, however often it occurs there,
and a motif and its **reverse complement are one motif**. Thresholds
keep one convention throughout the package: a log2FC threshold is strict
(`log2FC < thr`), a score or support threshold inclusive (`>= thr`, so
`min_support=3` means three supporting plasmids, not four).

Step 2 for one motif, by hand: `GAGACC` is in the first two sequences,
in the second read on the other strand as `GGTCTC`.

``` python
_seqs = ["GAGACCTT", "AAGAGACC", "TTTTTTTT"]
_fc = [-2.0, 0.5, -3.0]

carries = [("GAGACC" in s) or ("GGTCTC" in s) for s in _seqs]   # either strand, one motif
vals = [f for f, c in zip(_fc, carries) if c]
print(f"plasmids carrying GAGACC : {[s for s, c in zip(_seqs, carries) if c]}")
print(f"their log2FC             : {vals}")
print(f"score, fraction below -1 : {np.mean(np.array(vals) < -1)}")
```

    plasmids carrying GAGACC : ['GAGACCTT', 'AAGAGACC']
    their log2FC             : [-2.0, 0.5]
    score, fraction below -1 : 0.5

The scan does this for every motif of every pattern at once, on integer
codes rather than strings: `04_coding` shows how, and `05_fast` adds an
optional compiled kernel. Both are tested to give exactly the table of a
readable string-based scan (`tests/reference_scan.py`).

### On the example library

From here on the examples use JJ1886 in the 20 nt library: the inserts
with their flanks
([`get_lib_seq_context`](https://dbikard.github.io/randseq/utils.html#get_lib_seq_context)),
their log2FC, and each plasmid’s background — the depletion rate of
plasmids of similar insert GC content, which every test is taken against
([`plasmid_background`](https://dbikard.github.io/randseq/utils.html#plasmid_background)
in `01_utils` explains why).
[`_scan_candidates`](https://dbikard.github.io/randseq/core.html#_scan_candidates)
scans one pattern and keeps the motifs that pass the support and score
thresholds. It returns three things: the candidates, with `motif`,
`fraction_depleted`, `num_sequences`, `avg_log2fc`, `p_value` and
`pattern` (as a string); the p-value of every motif with enough support
to be a test, survivor or not; and the pattern’s totals from
[`_scan_pattern`](https://dbikard.github.io/randseq/fast.html#_scan_pattern),
so that later steps look motifs of this pattern up rather than scan it
again. The p-values are returned because the Benjamini-Hochberg
correction needs the full set of tests, and only this step sees it: a
motif that fails the score threshold was still tested.

``` python
left, right = "GTCCTAGGTATAATACTAGT", "GTTTTAGAGCTAGAAATAGC"
lib = get_lib_seq_context(log2fc_df.index, left, right)
fcs = log2fc_df["JJ1886_T0"].values
bg = plasmid_background(log2fc_df.index, fcs, -1)
print(f"{len(lib)} sequences, each {len(lib[0])} nt with the flanks added")
lib[0][:60]
```

    11503 sequences, each 60 nt with the flanks added

    'GTCCTAGGTATAATACTAGTCGGAGGTACTGGGTACATTTGTTTTAGAGCTAGAAATAGC'

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

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

### \_scan_candidates

Score every motif of one pattern; keep those reaching `score_thr` on
`min_support` plasmids.

``` python
_scan_candidates(pattern, encoded_library, fc_values, background, log2fc_thr,
                 score_thr, min_support, parallel=True)
```

<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>pattern</code></td>
<td>tuple</td>
<td></td>
<td>the <code>(d1, spacer, d2)</code> shape to scan</td>
</tr>
<tr>
<td><code>encoded_library</code></td>
<td>tuple</td>
<td></td>
<td><code>(fwd, rc)</code> from <a
href="https://dbikard.github.io/randseq/coding.html#encode_library"><code>encode_library</code></a>,
of the sequences with their flanks</td>
</tr>
<tr>
<td><code>fc_values</code></td>
<td></td>
<td></td>
<td>log2FC of each sequence, in library order</td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray</td>
<td></td>
<td>each sequence’s expected depletion rate (<a
href="https://dbikard.github.io/randseq/utils.html#plasmid_background"><code>plasmid_background</code></a>)</td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td></td>
<td>a sequence is depleted below this</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td></td>
<td>lowest <code>fraction_depleted</code> a candidate keeps
(<code>&gt;=</code>)</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td></td>
<td>fewest carriers a motif is tested on (<code>&gt;=</code>)</td>
</tr>
<tr>
<td><code>parallel</code></td>
<td>bool</td>
<td><code>True</code></td>
<td>passed to <a
href="https://dbikard.github.io/randseq/fast.html#_scan_pattern"><code>_scan_pattern</code></a>;
False inside a pool worker</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>tuple</td>
<td></td>
<td><code>(candidates, p-values of every motif tested, the pattern's totals)</code></td>
</tr>
</tbody>
</table>

``` python
candidates, tested, _ = _scan_candidates((3, 4, 4), encode_library(lib), fcs, bg, -1, 0.7, 3)
# far more motifs were tested than survived -- the correction has to account for all of them
print(f"{len(candidates)} candidates kept out of {len(tested)} tested")
candidates.sort_values('num_sequences', ascending=False).head()
```

    8 candidates kept out of 16296 tested

<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>
<th data-quarto-table-cell-role="th">pattern</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>ATANNNNTGTG</td>
<td>0.964467</td>
<td>197</td>
<td>-4.638428</td>
<td>4.479256e-244</td>
<td>(3, 4, 4)</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>CACNNNNGTAT</td>
<td>1.000000</td>
<td>192</td>
<td>-4.805313</td>
<td>2.601024e-258</td>
<td>(3, 4, 4)</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>TACNNNNGTGA</td>
<td>0.849315</td>
<td>73</td>
<td>-4.059755</td>
<td>4.842427e-72</td>
<td>(3, 4, 4)</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>TACNNNNGTGG</td>
<td>0.907692</td>
<td>65</td>
<td>-4.409352</td>
<td>1.440987e-72</td>
<td>(3, 4, 4)</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>AACNNNNCTTT</td>
<td>1.000000</td>
<td>63</td>
<td>-5.209253</td>
<td>1.372226e-86</td>
<td>(3, 4, 4)</td>
</tr>
</tbody>
</table>

</div>

## Step 3: one description per site

The scan returns one site described several ways. In this library the
Type I site `CACNNNNGTAT` also comes back as `CACNNNNGTA`, one base
shorter, and `CACNNNNGTAC` comes back once for each base pinned at the
first position of its spacer (`CACANNNGTAC`, `CACCNNNGTAC`, …). Step 3
keeps one description per site, with one tool and three rules applied in
this order:

- **the variant profile**: pin one position next to a motif to each of
  A, C, G and T, and score the four motifs
- **rule 1, a mixture is not a site**: drop a motif when some position
  next to it splits its four variants into depleting and not
- **rule 2, a one-base extension of a site is redundant**: drop a motif
  that is a rule-1 survivor plus one defined base
- **rule 3, a motif with an uninformative base is not the site**: drop a
  motif when putting N back at one of its defined bases gives four bases
  that all behave like the site

### The variant profile

[`_variant_profile`](https://dbikard.github.io/randseq/core.html#_variant_profile)
scores a set of related motifs — typically the four bases at one
position — from the counts step 2 made
([`_scan_pattern`](https://dbikard.github.io/randseq/fast.html#_scan_pattern)),
so a variant is scored exactly as the scan scored it, and a pattern is
scanned at most once however many motifs need it. The counts are kept in
`totals`, a dict by canonical pattern that holds for one library,
log2FC, background and threshold; the pipeline shares it across calls,
so a pattern step 2 scanned is never scanned again. A motif that has no
code — an IUPAC letter, or a defined base in the spacer — gets `n = 0`
and `nan` for its score and background.

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

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

### \_variant_profile

Support, depletion score and background of each of a set of related
motifs.

``` python
_variant_profile(motifs, pattern, encoded, fc, background, log2fc_thr,
                 totals=None)
```

<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>motifs</code></td>
<td>list</td>
<td></td>
<td>motif strings, all of the same <code>pattern</code></td>
</tr>
<tr>
<td><code>pattern</code></td>
<td>tuple</td>
<td></td>
<td>the <code>(d1, spacer, d2)</code> shape they share</td>
</tr>
<tr>
<td><code>encoded</code></td>
<td>tuple</td>
<td></td>
<td><code>(fwd, rc)</code> from <a
href="https://dbikard.github.io/randseq/coding.html#encode_library"><code>encode_library</code></a></td>
</tr>
<tr>
<td><code>fc</code></td>
<td>ndarray</td>
<td></td>
<td>log2FC per library sequence, in the same order</td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray</td>
<td></td>
<td>each sequence’s expected depletion rate (<a
href="https://dbikard.github.io/randseq/utils.html#plasmid_background"><code>plasmid_background</code></a>)</td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td></td>
<td>a plasmid is depleted below this</td>
</tr>
<tr>
<td><code>totals</code></td>
<td>dict | None</td>
<td><code>None</code></td>
<td>the scan’s totals by canonical pattern, shared; filled in place</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>list</td>
<td></td>
<td><code>(motif, n_plasmids, score, carriers' mean background)</code>
per motif, in the order given</td>
</tr>
</tbody>
</table>

``` python
enc = encode_library(lib)

# CACNNNNGTA leaves the eleventh position undefined. What do the four bases score there?
for motif, n, s, b in _variant_profile(["CACNNNNGTAA", "CACNNNNGTAC", "CACNNNNGTAG", "CACNNNNGTAT"],
                                      (3, 4, 4), enc, fcs, bg, -1):
    print(f"  {motif}  n={n:>4}  score={s:.3f}  background={b:.3f}")
```

      CACNNNNGTAA  n=  15  score=0.067  background=0.045
      CACNNNNGTAC  n=  20  score=1.000  background=0.044
      CACNNNNGTAG  n=  11  score=0.000  background=0.042
      CACNNNNGTAT  n= 192  score=1.000  background=0.046

Two of the four are dead and two are perfect. Whatever `CACNNNNGTA`
scores as a whole, it is an average over two populations, not one.

A profile is a **mixture** when its variants *split*: some fail the
score threshold the candidate had to pass, **and** the variants spread
by at least that threshold. Both halves are needed: a failing variant
alone would condemn a weak real site with one variant just below the
line, and a spread alone a strong site whose variants merely differ.
Variants on fewer than `min_support` plasmids are not judged, and fewer
than two judgeable variants is `unknown`.

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

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

### \_verdict

Call a variant profile ‘mixture’, ‘genuine’ or ‘unknown’.

``` python
_verdict(profile, score_thr, min_support)
```

<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>profile</code></td>
<td>list</td>
<td></td>
<td><code>(motif, n, score, ...)</code> from <a
href="https://dbikard.github.io/randseq/core.html#_variant_profile"><code>_variant_profile</code></a>;
only <code>n</code> and <code>score</code> are read</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td></td>
<td>the depletion score a candidate had to reach to be here</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td></td>
<td>a variant on fewer plasmids than this is not judged</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>tuple</td>
<td></td>
<td>the verdict, and the spread of the judged variants (None when fewer
than two)</td>
</tr>
</tbody>
</table>

``` python
# Four real profiles, one per case the rule has to get right.
mixture = [("a", 15, 0.07), ("c", 20, 1.00), ("g", 11, 0.00), ("t", 192, 1.00)]
weak    = [("a", 77, 0.506), ("c", 53, 0.679), ("g", 62, 0.468), ("t", 110, 0.564)]
strong  = [("a", 555, 0.654), ("c", 409, 0.677), ("g", 526, 0.755), ("t", 667, 0.705)]
thin    = [("a", 4, 1.0), ("c", 1, 1.0), ("g", 3, 1.0), ("t", 1, 1.0)]
for name, p in [("mixture", mixture), ("weak", weak), ("strong", strong), ("thin", thin)]:
    v, spread = _verdict(p, 0.5, 5)
    print(f"  {name:8s} {v:8s} spread={'  —' if spread is None else f'{spread:.3f}'}")
```

      mixture  mixture  spread=1.000
      weak     genuine  spread=0.211
      strong   genuine  spread=0.101
      thin     unknown  spread=  —

`weak` decides the design: one variant scores 0.468, below the 0.5
threshold, but all four sit within 0.21 of each other, so no population
of non-sites hides inside it. `thin` is `unknown`, which matters to rule
2.

A motif is tested where one more defined base could go: one base beyond
each end, and the spacer position next to each half
([`_undefined_positions`](https://dbikard.github.io/randseq/core.html#_undefined_positions)).
A position in the middle of a long spacer is skipped: fixing it would
leave two gaps, a shape `(d1, spacer, d2)` cannot write. These are also
the only positions a one-base extension can add its base at, which ties
rules 1 and 2 together.

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

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

### \_undefined_positions

Each undefined position worth testing on a candidate.

``` python
_undefined_positions(motif, pattern)
```

<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>motif</code></td>
<td>str</td>
<td></td>
<td>the candidate</td>
</tr>
<tr>
<td><code>pattern</code></td>
<td>tuple</td>
<td></td>
<td>its <code>(d1, spacer, d2)</code> shape</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>list</td>
<td></td>
<td><code>(four variants, their pattern)</code> for each position</td>
</tr>
</tbody>
</table>

``` python
# NATACNNNNGTGN: four positions to test, each giving a different pattern.
for variants, vpat in _undefined_positions("ATACNNNNGTG", (4, 4, 3)):
    print(f"  {vpat}  {variants[0]}")

# A contiguous motif has no spacer, so only the two ends are testable.
print()
for variants, vpat in _undefined_positions("GGTCTC", (6, 0, 0)):
    print(f"  {vpat}  {variants[0]}")
```

      (5, 4, 3)  AATACNNNNGTG
      (4, 4, 4)  ATACNNNNGTGA
      (5, 3, 3)  ATACANNNGTG
      (4, 3, 4)  ATACNNNAGTG

      (7, 0, 0)  AGGTCTC
      (7, 0, 0)  GGTCTCA

### Rule 1: a mixture is not a site

[`_is_mixture`](https://dbikard.github.io/randseq/core.html#_is_mixture)
reads the profile at each position next to a motif; one split is enough.
The scan finds this strain’s Type I site as `CACNNNNGTAT` (reported on
its canonical strand as `ATACNNNNGTG`, pattern `(4, 4, 3)`), and also
`ATANNNNTGTG`: the same stretch of DNA with its gap one base to the
left. Neither string contains the other, so rule 2 cannot relate them,
although both describe mostly the same 190 plasmids. Rule 1 separates
them:

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

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

### \_is_mixture

Does fixing one position next to this motif split its carriers into
sites and non-sites?

``` python
_is_mixture(motif, pattern, encoded_library, fc_values, background,
            log2fc_thr=-1, score_thr=0.5, min_support=5, totals=None)
```

<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>motif</code></td>
<td>str</td>
<td></td>
<td>the candidate</td>
</tr>
<tr>
<td><code>pattern</code></td>
<td>tuple</td>
<td></td>
<td>its <code>(d1, spacer, d2)</code> shape</td>
</tr>
<tr>
<td><code>encoded_library</code></td>
<td>tuple</td>
<td></td>
<td><code>(fwd, rc)</code> from <a
href="https://dbikard.github.io/randseq/coding.html#encode_library"><code>encode_library</code></a></td>
</tr>
<tr>
<td><code>fc_values</code></td>
<td>ndarray</td>
<td></td>
<td>log2FC per library sequence</td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray</td>
<td></td>
<td>expected depletion per sequence: unread by the verdict, kept in
totals</td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td><code>-1</code></td>
<td>a plasmid is depleted below this</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td><code>0.5</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_verdict"><code>_verdict</code></a></td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>5</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_verdict"><code>_verdict</code></a></td>
</tr>
<tr>
<td><code>totals</code></td>
<td>dict | None</td>
<td><code>None</code></td>
<td>shared pattern totals, as for <a
href="https://dbikard.github.io/randseq/core.html#_variant_profile"><code>_variant_profile</code></a></td>
</tr>
<tr>
<td><em>returns</em></td>
<td>bool</td>
<td></td>
<td>True when the four bases at some position split</td>
</tr>
</tbody>
</table>

``` python
for motif, pat in [("ATANNNNTGTG", (3, 4, 4)), ("ATACNNNNGTG", (4, 4, 3))]:
    print(f"{motif}  {pat}   _is_mixture = {_is_mixture(motif, pat, enc, fcs, bg, -1, 0.7, 3)}")
    for variants, vpat in _undefined_positions(motif, pat):
        prof = _variant_profile(variants, vpat, enc, fcs, bg, -1)
        v, spread = _verdict(prof, 0.7, 3)
        cells = "  ".join(f"{s:.2f}({n})" if n else "  -- (0)" for _, n, s, _ in prof)
        print(f"   {str(vpat):10s} {v:8s} "
              f"spread={'   —' if spread is None else f'{spread:.2f}'}   {cells}")
    print()
```

    ATANNNNTGTG  (3, 4, 4)   _is_mixture = True
       (4, 4, 4)  mixture  spread=0.74   0.99(190)  0.33(3)  0.25(4)    -- (0)
       (3, 4, 5)  genuine  spread=0.07   1.00(53)  0.93(45)  0.95(56)  0.98(43)
       (4, 3, 4)  mixture  spread=1.00   0.20(5)  1.00(189)  0.00(3)    -- (0)
       (3, 3, 5)  genuine  spread=0.49   0.00(2)    -- (0)  0.99(189)  0.50(6)

    ATACNNNNGTG  (4, 4, 3)   _is_mixture = False
       (5, 4, 3)  unknown  spread=   —   1.00(189)  1.00(1)  1.00(1)  1.00(1)
       (4, 4, 4)  genuine  spread=0.00   1.00(54)  1.00(44)  1.00(53)  1.00(41)
       (5, 3, 3)  unknown  spread=   —     -- (0)  1.00(1)  1.00(2)  1.00(189)
       (4, 3, 4)  unknown  spread=   —     -- (0)  1.00(1)  1.00(2)  1.00(189)

Pinning the base next to `ATANNNNTGTG`’s left half splits its carriers:
190 at 0.99 against a handful at 0.33 and 0.25. The real site has
nothing to split: every base at its one judgeable position scores 1.00;
its other three positions have too few plasmids to judge.

### Rule 2: a one-base extension of a site is redundant

A rule-1 survivor has nothing to split at any position next to it, so a
candidate that is that motif plus one defined base adds nothing: rule 1
scored all four bases at that position and found no difference. The
filter does not compare every pair:
[`_parent_motifs`](https://dbikard.github.io/randseq/core.html#_parent_motifs)
lists the motifs a candidate could extend, and the filter looks them up
among the survivors, on either strand (`_is_extension` is the pairwise
definition it is tested against). When the four bases are too thin to
judge, rule 1 keeps the shorter motif and rule 2 drops the extension:
with no evidence that the extra base matters, the simpler description is
kept.

<details class="code-fold">
<summary>Source: \_is_extension (notebook only)</summary>

``` python
def _is_extension(specific, general):
    """Is `specific` the motif `general` with one more defined base, on either strand?

    The extra base sits one past an end of `general` or at an edge of its spacer -- the
    positions `_undefined_positions` tests. Both strands are checked because every pattern is
    searched in one canonical form, so adding a base to a motif's longer side can turn its shape
    into the mirror form, which the scan writes on the other strand: `TACNNNNGTGA` is
    `CACNNNNGTA` with a base added on the left.
    """
    defined = lambda m: len(m) - m.count("N")
    return defined(specific) == defined(general) + 1 and _find_broad_in_specific(specific, general)
```

</details>

`CACNNNNGTAC` passes rule 1. At the first position of its spacer, the
four bases score alike:

``` python
print("CACNNNNGTAC is a mixture:", _is_mixture("CACNNNNGTAC", (3, 4, 4), enc, fcs, bg, -1, 0.7, 3))
for motif, n, s, _ in _variant_profile([f"CAC{b}NNNGTAC" for b in "ACGT"], (4, 3, 4), enc, fcs, bg, -1):
    print(f"  {motif}  n={n:>3}  score={s:.2f}   extension of CACNNNNGTAC: "
          f"{_is_extension(motif, 'CACNNNNGTAC')}")
```

    CACNNNNGTAC is a mixture: False
      CACANNNGTAC  n=  4  score=1.00   extension of CACNNNNGTAC: True
      CACCNNNGTAC  n=  9  score=1.00   extension of CACNNNNGTAC: True
      CACGNNNGTAC  n=  4  score=1.00   extension of CACNNNNGTAC: True
      CACTNNNGTAC  n=  3  score=1.00   extension of CACNNNNGTAC: True

Every base scores 1.00, so the four are `CACNNNNGTAC` plus a base that
says nothing, and rule 2 drops them.

**Why rule 1 comes first.** `CACNNNNGTA` is a mixture, and both real
sites, `CACNNNNGTAC` and `CACNNNNGTAT`, are extensions of it:

``` python
print("CACNNNNGTA is a mixture:", _is_mixture("CACNNNNGTA", (3, 4, 3), enc, fcs, bg, -1, 0.7, 3))
for site in ["CACNNNNGTAC", "CACNNNNGTAT"]:
    print(f"  {site} is an extension of CACNNNNGTA: {_is_extension(site, 'CACNNNNGTA')}")
```

    CACNNNNGTA is a mixture: True
      CACNNNNGTAC is an extension of CACNNNNGTA: True
      CACNNNNGTAT is an extension of CACNNNNGTA: True

Rule 1 removes `CACNNNNGTA`, so the two sites have no surviving motif to
extend, and they stay. Run rule 2 first and both go as extensions of
`CACNNNNGTA`, which rule 1 then removes too: the strain’s Type I site
disappears. Within each rule the order of the candidates does not
matter, so neither does the result.

### Rule 3: a motif with an uninformative base is not the site

Rule 2 needs the shorter motif to be a candidate. When it fell short of
the thresholds, a longer motif can still clear them because its extra
base happens to pick out the most depleted of the shorter one’s
carriers. Rule 3 asks from the other side: put N back at one of a
candidate’s defined bases and classify the other three bases there. If
every one behaves like the site, the candidate’s base carries no
information.

A base is classified by comparing two models of its carriers — depleted
at the site’s rate, or at their own background — by their log-likelihood
ratio, which grows with the number of plasmids and so is also the
confidence: a base is classified when one model fits ten times better.
Simpler criteria fail: a fixed cut-off between the two rates misplaces
the boundary, which depends on both, and a test against background calls
site-like a base depleted at four times background but a quarter of the
site’s rate. The site’s rate is the candidate’s own, re-estimated once
from the candidate pooled with the bases first found site-like, because
a candidate selected for scoring high overstates it.

Rule 3 drops a motif when, at one position, *every* other base is
site-like. When only some are, the position is degenerate, and reporting
writes it as an IUPAC letter (below).

The positions tested
([`_relax_positions`](https://dbikard.github.io/randseq/core.html#_relax_positions))
are those rule 1 tests from the other side: every base of a contiguous
motif, an interior one becoming a one-base spacer, and for a gapped
motif the outer and the spacer-side base of each half, as long as the
half keeps a defined base.
[`_classify_bases`](https://dbikard.github.io/randseq/core.html#_classify_bases)
classifies the bases at one position;
[`_classify_positions`](https://dbikard.github.io/randseq/core.html#_classify_positions)
does it at each position asked, profiling a motif of A, C, G and T from
the scan’s counts
([`_variant_profile`](https://dbikard.github.io/randseq/core.html#_variant_profile))
and one with an IUPAC letter on the carriers of its instances
([`_union_profile`](https://dbikard.github.io/randseq/core.html#_union_profile)).

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

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

### \_relax_positions

The defined bases of `motif` that can be put back to N, leaving a valid
pattern.

``` python
_relax_positions(motif, pattern)
```

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>motif</code></td>
<td>str</td>
<td></td>
<td>the candidate</td>
</tr>
<tr>
<td><code>pattern</code></td>
<td>tuple</td>
<td></td>
<td>its <code>(d1, spacer, d2)</code> shape</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>list</td>
<td></td>
<td>positions in <code>motif</code></td>
</tr>
</tbody>
</table>

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

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

### \_classify_bases

‘site’, ‘non-site’ or ‘unknown’ for each base other than `motif`’s at
one position.

``` python
_classify_bases(profile, motif, min_support)
```

<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>profile</code></td>
<td>list</td>
<td></td>
<td><code>(motif, n, score, background)</code> for the four bases, from
<a
href="https://dbikard.github.io/randseq/core.html#_variant_profile"><code>_variant_profile</code></a></td>
</tr>
<tr>
<td><code>motif</code></td>
<td>str</td>
<td></td>
<td>the candidate, one of the four</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td></td>
<td>a base carried by fewer plasmids is not classified</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>dict | None</td>
<td></td>
<td>other motif -&gt; class, if carried <code>min_support</code> times;
None if <code>motif</code> is not</td>
</tr>
</tbody>
</table>

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

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

### \_classify_positions

For each position, the class and carriers of every base `motif` does not
allow there.

``` python
_classify_positions(motif, positions, pattern, encoded_library, fc_values,
                    background, log2fc_thr=-1, min_support=5, totals=None)
```

<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>motif</code></td>
<td>str</td>
<td></td>
<td>the candidate; IUPAC letters allowed at its defined positions</td>
</tr>
<tr>
<td><code>positions</code></td>
<td>list</td>
<td></td>
<td>defined positions of <code>motif</code> to classify</td>
</tr>
<tr>
<td><code>pattern</code></td>
<td>tuple</td>
<td></td>
<td>its <code>(d1, spacer, d2)</code> shape</td>
</tr>
<tr>
<td><code>encoded_library</code></td>
<td>tuple</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>fc_values</code></td>
<td>ndarray</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td><code>-1</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>5</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>totals</code></td>
<td>dict | None</td>
<td><code>None</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><em>returns</em></td>
<td>dict</td>
<td></td>
<td>position -&gt; {base: (class, carriers)}; empty at each when
<code>motif</code> has too few carriers</td>
</tr>
</tbody>
</table>

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

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

### \_is_over_specified

Does `motif` have a defined base at which every other base behaves like
the site?

``` python
_is_over_specified(motif, pattern, encoded_library, fc_values, background,
                   log2fc_thr=-1, min_support=5, totals=None)
```

<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>motif</code></td>
<td>str</td>
<td></td>
<td>the candidate</td>
</tr>
<tr>
<td><code>pattern</code></td>
<td>tuple</td>
<td></td>
<td>its <code>(d1, spacer, d2)</code> shape</td>
</tr>
<tr>
<td><code>encoded_library</code></td>
<td>tuple</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>fc_values</code></td>
<td>ndarray</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td><code>-1</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>5</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>totals</code></td>
<td>dict | None</td>
<td><code>None</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><em>returns</em></td>
<td>bool</td>
<td></td>
<td>True when, at one of <a
href="https://dbikard.github.io/randseq/core.html#_relax_positions"><code>_relax_positions</code></a>,
every other base is site-like</td>
</tr>
</tbody>
</table>

`CCACNNNAGTA`, a shadow of the strain’s Type I site that rules 1 and 2
let through, against `CACNNNNGTAC`, a real site:

``` python
for motif, pat in [("CCACNNNAGTA", (4, 3, 4)), ("CACNNNNGTAC", (3, 4, 4))]:
    print(f"{motif}  over-specified: {_is_over_specified(motif, pat, enc, fcs, bg, -1, 3)}")
    for i in _relax_positions(motif, pat):
        prof = _variant_profile([motif[:i] + b + motif[i + 1:] for b in "ACGT"], pat, enc, fcs, bg, -1)
        cls = _classify_bases(prof, motif, 3) or {}
        cells = "  ".join(f"{m[i]}:{s:.2f}({n})" + ("" if m == motif else f"={cls.get(m, '-')[:4]}")
                          for m, n, s, _ in prof)
        print(f"   position {i:>2}  {cells}")
```

    CCACNNNAGTA  over-specified: True
       position  0  A:0.95(42)=site  C:1.00(55)  G:1.00(45)=site  T:0.92(60)=site
       position  3  A:0.00(27)=non-  C:1.00(55)  G:0.01(70)=non-  T:0.00(40)=non-
       position  7  A:1.00(55)  C:0.50(2)=-  G:0.00(5)=non-  T:1.00(3)=site
       position 10  A:1.00(55)  C:0.00(1)=-  G:0.00(5)=non-  T:0.00(5)=non-
    CACNNNNGTAC  over-specified: False
       position  0  A:0.08(60)=non-  C:1.00(20)  G:0.00(17)=non-  T:0.06(54)=non-
       position  2  A:0.04(23)=non-  C:1.00(20)  G:0.00(24)=non-  T:0.05(21)=non-
       position  7  A:0.03(29)=non-  C:0.08(13)=non-  G:1.00(20)  T:0.10(29)=non-
       position 10  A:0.07(15)=non-  C:1.00(20)  G:0.00(11)=non-  T:1.00(192)=site

At `CCACNNNAGTA`’s first base all four bases deplete almost completely,
so its `C` carries nothing and the motif goes. At every position of
`CACNNNNGTAC` the other bases deplete at background, except at its last:
there `T` depletes like `C`, and `A` and `G` do not. That is a
degenerate position — `CACNNNNGTAC` and `CACNNNNGTAT` behave as one
site, `CACNNNNGTAY` — and the reason rule 3 requires *every* other base
to be site-like.

### The filter

[`_filter_redundant_patterns`](https://dbikard.github.io/randseq/core.html#_filter_redundant_patterns)
applies the three rules in order. Rule 2 is a handful of lookups per
candidate and rule 3 reads patterns the scan already counted, so the
filter stays linear in the number of candidates. A candidate whose
pattern is unknown cannot be tested by rules 1 and 3, and stays. Six
patterns over the example library:

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

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

### \_carriers

Which plasmids carry each motif, on either strand.

``` python
_carriers(encoded, motifs, patterns, log2fc_series, left_context, right_context,
          inside=False)
```

<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>encoded</code></td>
<td>tuple</td>
<td></td>
<td><code>(fwd, rc)</code> from <a
href="https://dbikard.github.io/randseq/coding.html#encode_library"><code>encode_library</code></a></td>
</tr>
<tr>
<td><code>motifs</code></td>
<td>list</td>
<td></td>
<td>motif strings, IUPAC letters allowed</td>
</tr>
<tr>
<td><code>patterns</code></td>
<td>list</td>
<td></td>
<td>each motif’s <code>(d1, spacer, d2)</code>, or None where
unknown</td>
</tr>
<tr>
<td><code>log2fc_series</code></td>
<td>Series</td>
<td></td>
<td>log2FC indexed by insert, read by the regex fallback</td>
</tr>
<tr>
<td><code>left_context</code></td>
<td>str</td>
<td></td>
<td>vector sequence 5’ of the insert</td>
</tr>
<tr>
<td><code>right_context</code></td>
<td>str</td>
<td></td>
<td>vector sequence 3’ of the insert</td>
</tr>
<tr>
<td><code>inside</code></td>
<td>bool</td>
<td><code>False</code></td>
<td>also return the carriers with a site wholly inside the insert</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>ndarray</td>
<td></td>
<td>boolean, (n_sequences, n_motifs); with <code>inside</code>,
<code>(carriers, internal carriers)</code></td>
</tr>
</tbody>
</table>

[`_carriers`](https://dbikard.github.io/randseq/core.html#_carriers)
reads which plasmids carry each motif from the window codes of its
instances
([`_instance_presence`](https://dbikard.github.io/randseq/core.html#_instance_presence)):
a motif with IUPAC letters is carried where one of its instances is. A
motif whose pattern is unknown falls back to a regex over the sequences
with their flanks
([`_get_filter_for_motif`](https://dbikard.github.io/randseq/utils.html#_get_filter_for_motif)).
With `inside=True` it also returns the carriers with a site wholly
inside the insert (*Sites completed by the flank*).

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

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

### \_filter_redundant_patterns

Keep one description per site, by rules 1 to 3.

``` python
_filter_redundant_patterns(df, log2fc_series, left_context, right_context,
                           log2fc_thr=-1, score_thr=0.5, min_support=5,
                           encoded=None, totals=None, background=None)
```

<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>df</code></td>
<td>DataFrame</td>
<td></td>
<td>candidates, with ‘motif’ and ‘pattern’</td>
</tr>
<tr>
<td><code>log2fc_series</code></td>
<td>Series</td>
<td></td>
<td>log2FC indexed by insert</td>
</tr>
<tr>
<td><code>left_context</code></td>
<td>str</td>
<td></td>
<td>vector sequence 5’ of the insert</td>
</tr>
<tr>
<td><code>right_context</code></td>
<td>str</td>
<td></td>
<td>vector sequence 3’ of the insert</td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td><code>-1</code></td>
<td>a plasmid is depleted below this</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td><code>0.5</code></td>
<td>the candidates’ bar, reused for a variant’s and a mixture’s
spread</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>5</code></td>
<td>a variant on fewer plasmids than this is not judged</td>
</tr>
<tr>
<td><code>encoded</code></td>
<td>tuple | None</td>
<td><code>None</code></td>
<td>the library from <a
href="https://dbikard.github.io/randseq/coding.html#encode_library"><code>encode_library</code></a>,
if the caller has it</td>
</tr>
<tr>
<td><code>totals</code></td>
<td>dict | None</td>
<td><code>None</code></td>
<td>shared pattern totals, as for <a
href="https://dbikard.github.io/randseq/core.html#_variant_profile"><code>_variant_profile</code></a></td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray | None</td>
<td><code>None</code></td>
<td>expected depletion per plasmid; default <a
href="https://dbikard.github.io/randseq/utils.html#plasmid_background"><code>plasmid_background</code></a></td>
</tr>
<tr>
<td><em>returns</em></td>
<td>DataFrame</td>
<td></td>
<td><code>df</code> without the redundant rows, in the original row
order</td>
</tr>
</tbody>
</table>

``` python
pats = [(6, 0, 0), (7, 0, 0), (3, 4, 3), (3, 4, 4), (4, 3, 4), (4, 4, 4)]
enc = encode_library(lib)
candidates_demo = pd.concat([_scan_candidates(p, enc, fcs, bg, -1, 0.7, 3)[0] for p in pats],
                            ignore_index=True)
_pat = lambda s: tuple(int(x) for x in s.strip("()").split(","))
mixtures = [m for m, p in zip(candidates_demo.motif, candidates_demo.pattern)
            if _is_mixture(m, _pat(p), enc, fcs, bg, -1, 0.7, 3)]
rows = list(candidates_demo.itertuples())
surv = [r for r in rows if r.motif not in mixtures]
after2 = [r for r in surv if not any(_is_extension(r.motif, o.motif) for o in surv)]
kept = _filter_redundant_patterns(candidates_demo, log2fc_df["JJ1886_T0"], left, right,
                                 log2fc_thr=-1, score_thr=0.7, min_support=3)
print(f"{len(candidates_demo)} candidates: rule 1 drops {len(mixtures)} mixtures, rule 2 drops "
      f"{len(surv) - len(after2)} extensions, rule 3 drops {len(after2) - len(kept)} "
      f"over-specified motifs, {len(kept)} go on to step 4")
kept.sort_values("num_sequences", ascending=False)[["motif", "pattern", "fraction_depleted",
                                                    "num_sequences"]].head(8)
```

    75 candidates: rule 1 drops 12 mixtures, rule 2 drops 24 extensions, rule 3 drops 6 over-specified motifs, 33 go on to step 4

<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">pattern</th>
<th data-quarto-table-cell-role="th">fraction_depleted</th>
<th data-quarto-table-cell-role="th">num_sequences</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">14</td>
<td>CACNNNNGTAT</td>
<td>(3, 4, 4)</td>
<td>1.000000</td>
<td>192</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">51</td>
<td>AATANNNNTGTG</td>
<td>(4, 4, 4)</td>
<td>0.989474</td>
<td>190</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">12</td>
<td>AACNNNNCTTT</td>
<td>(3, 4, 4)</td>
<td>1.000000</td>
<td>63</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">17</td>
<td>CACNNNNGTAC</td>
<td>(3, 4, 4)</td>
<td>1.000000</td>
<td>20</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>GAGACC</td>
<td>(6, 0, 0)</td>
<td>1.000000</td>
<td>9</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">38</td>
<td>TGGCNNNCACA</td>
<td>(4, 3, 4)</td>
<td>0.714286</td>
<td>7</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">35</td>
<td>AAGTNNNGTTA</td>
<td>(4, 3, 4)</td>
<td>0.833333</td>
<td>6</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">25</td>
<td>GAAGNNNACAC</td>
<td>(4, 3, 4)</td>
<td>0.800000</td>
<td>5</td>
</tr>
</tbody>
</table>

</div>

The survivors include the strain’s sites, on whichever strand the scan
read them: `CACNNNNGTAT` (reported as `ATACNNNNGTG`), `AACNNNNCTTT`
(`AAAGNNNNGTT`), `CACNNNNGTAC` and `GAGACC`. Beside them sits
`AATANNNNTGTG`, 0.99 depleted on 190 plasmids, because nearly every
plasmid that carries it also carries `ATACNNNNGTG`; the other 28
survivors are on seven plasmids or fewer. None of them is a site plus
one base, so no string rule relates them to a site: that is step 4’s
question.

### Sites completed by the flank

Reading the flanks with each insert has a cost. The flank is the same in
every plasmid, so where a motif uses flank bases it is a shorter motif
of the insert at one fixed position, and whatever depletes those inserts
scores for the motif too. Without this check, TA249 and ROAR8 in the 20
nt library are called for `DCAANNNNNNTAGA`, on 159 carriers; 157 of them
read its `TAGA` in the right flank (`GTTTTAGAGC…`), so on them the motif
is `DCAA` at insert positions 15–18. A real site completed by the flank
also restricts where it lies wholly inside the insert: JJ1886’s
`RTACNNNNGTG` needs the flank on 199 of its 212 carriers, and its 13
internal carriers are all depleted.

So a candidate that needs the flank on more than half its carriers
(`junction_share` \> 0.5) must stand on its **internal carriers**, those
with a site wholly inside the insert, by the tests a call passes: at
least `min_support` of them, the lower bound on their depleted fraction
at `score_thr`, and their depleted count significant against their
background (p \< `q_threshold`). At 0.5 or below the internal carriers
are at least half the support and the call already rests on them, so the
trigger is fixed. The check runs between steps 3 and 4: step 4 lets a
stronger candidate claim a weaker one’s plasmids, and a candidate the
flank completes would claim them as readily as a site.
`_carriers(..., inside=True)` reads the internal carriers off the
windows that find the carriers: a window is inside the insert when it
starts after one flank and ends before the other.

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

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

### \_junction_support

How much each motif relies on the flanks, and how its internal carriers
fare on their own.

``` python
_junction_support(presence, inside, fc, background, log2fc_thr, q_threshold)
```

<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>presence</code></td>
<td>ndarray</td>
<td></td>
<td>carriers of each motif, read with the flanks (<a
href="https://dbikard.github.io/randseq/core.html#_carriers"><code>_carriers</code></a>)</td>
</tr>
<tr>
<td><code>inside</code></td>
<td>ndarray</td>
<td></td>
<td>carriers with a site wholly inside the insert (<a
href="https://dbikard.github.io/randseq/core.html#_carriers"><code>_carriers</code></a>,
<code>inside=True</code>)</td>
</tr>
<tr>
<td><code>fc</code></td>
<td>ndarray</td>
<td></td>
<td>log2FC per plasmid</td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray</td>
<td></td>
<td>expected depletion per plasmid (<a
href="https://dbikard.github.io/randseq/utils.html#plasmid_background"><code>plasmid_background</code></a>)</td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td></td>
<td>a plasmid is depleted below this</td>
</tr>
<tr>
<td><code>q_threshold</code></td>
<td>float</td>
<td></td>
<td>level of the one-sided bound, as for
<code>fraction_depleted_lower</code></td>
</tr>
<tr>
<td><em>returns</em></td>
<td>DataFrame</td>
<td></td>
<td><code>junction_share</code>, <code>internal_n</code>,
<code>internal_fraction_lower</code>, <code>internal_p_value</code></td>
</tr>
</tbody>
</table>

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

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

### \_junction_dependent

Does a motif rely on the flanks without its internal carriers reaching
the bar?

``` python
_junction_dependent(stats, score_thr, min_support, q_threshold)
```

<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>stats</code></td>
<td></td>
<td></td>
<td>a table or a row with the columns of <a
href="https://dbikard.github.io/randseq/core.html#_junction_support"><code>_junction_support</code></a></td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td></td>
<td>the internal carriers’ lower bound must reach this</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td></td>
<td>there must be at least this many of them</td>
</tr>
<tr>
<td><code>q_threshold</code></td>
<td>float</td>
<td></td>
<td>and their p-value must be below this</td>
</tr>
</tbody>
</table>

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

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

### \_filter_junction_dependent

Set aside the candidates that need the flanks and whose internal
carriers miss the bar.

``` python
_filter_junction_dependent(df, log2fc_series, left_context, right_context,
                           log2fc_thr=-1, score_thr=0.5, min_support=5,
                           q_threshold=0.05, p_threshold=0.05, encoded=None,
                           background=None, carriers=None)
```

<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>df</code></td>
<td>DataFrame</td>
<td></td>
<td>candidates, with ‘motif’, ‘pattern’, ‘num_sequences’,
‘fraction_depleted’</td>
</tr>
<tr>
<td><code>log2fc_series</code></td>
<td>Series</td>
<td></td>
<td>log2FC indexed by insert</td>
</tr>
<tr>
<td><code>left_context</code></td>
<td>str</td>
<td></td>
<td>vector sequence 5’ of the insert</td>
</tr>
<tr>
<td><code>right_context</code></td>
<td>str</td>
<td></td>
<td>vector sequence 3’ of the insert</td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td><code>-1</code></td>
<td>a plasmid is depleted below this</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td><code>0.5</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_junction_dependent"><code>_junction_dependent</code></a>,
and for <code>listed</code></td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>5</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_junction_dependent"><code>_junction_dependent</code></a></td>
</tr>
<tr>
<td><code>q_threshold</code></td>
<td>float</td>
<td><code>0.05</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_junction_dependent"><code>_junction_dependent</code></a>,
and the level of the bound for <code>listed</code></td>
</tr>
<tr>
<td><code>p_threshold</code></td>
<td>float</td>
<td><code>0.05</code></td>
<td><code>listed</code> needs p at or below this: the scan’s cutoff</td>
</tr>
<tr>
<td><code>encoded</code></td>
<td>tuple | None</td>
<td><code>None</code></td>
<td>the library from <a
href="https://dbikard.github.io/randseq/coding.html#encode_library"><code>encode_library</code></a>,
if the caller has it</td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray | None</td>
<td><code>None</code></td>
<td>expected depletion per plasmid; default <a
href="https://dbikard.github.io/randseq/utils.html#plasmid_background"><code>plasmid_background</code></a></td>
</tr>
<tr>
<td><code>carriers</code></td>
<td>tuple | None</td>
<td><code>None</code></td>
<td><code>_carriers(..., inside=True)</code> of <code>df</code>’s
motifs, if the caller has them</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>tuple</td>
<td></td>
<td><code>(kept, set_aside)</code>, rows of <code>df</code>;
<code>set_aside</code> adds <a
href="https://dbikard.github.io/randseq/core.html#_junction_support"><code>_junction_support</code></a>
and <code>listed</code></td>
</tr>
</tbody>
</table>

``` python
for sample, motif, pat in [("TA249_T0", "DCAANNNNNNTAGA", (4, 6, 4)), ("JJ1886_T0", "RTACNNNNGTG", (4, 4, 3))]:
    x = log2fc_df[sample]
    f = x.to_numpy()
    b = plasmid_background(x.index, f, -0.5)
    has, inside = _carriers(enc, [motif], [pat], x, left, right, inside=True)
    s = _junction_support(has, inside, f, b, -0.5, 0.05).iloc[0]
    flank = has[:, 0] & ~inside[:, 0]
    print(f"{sample} {motif}: {has.sum()} carriers, junction_share {s.junction_share:.2f}, "
          f"{'set aside' if _junction_dependent(s, 0.5, 5, 0.05) else 'stands'}")
    print(f"   need the flank {flank.sum():>4}   depleted {(f[flank] < -0.5).mean():.2f}   "
          f"background {b[flank].mean():.2f}")
    print(f"   internal       {int(s.internal_n):>4}   depleted {(f[inside[:, 0]] < -0.5).mean():.2f}   "
          f"lower bound {s.internal_fraction_lower:.2f}, p = {s.internal_p_value:.2g}")
```

    TA249_T0 DCAANNNNNNTAGA: 159 carriers, junction_share 0.99, set aside
       need the flank  157   depleted 0.61   background 0.09
       internal          2   depleted 0.50   lower bound 0.03, p = 0.17
    JJ1886_T0 RTACNNNNGTG: 212 carriers, junction_share 0.94, stands
       need the flank  199   depleted 1.00   background 0.07
       internal         13   depleted 1.00   lower bound 0.79, p = 6e-16

TA249’s carriers that need the flank are 61% depleted against a
background of 0.09; one of its two internal carriers is depleted, which
places no site inside the insert. JJ1886’s 13 internal carriers bound
their depleted fraction at 0.79.

Step 3 hands over motifs of A, C, G and T, so the check first sees a
degenerate site’s variants. In JJ1886, `ATACNNNNGTG` has four internal
carriers, one short of `min_support`, and is set aside; `CACNNNNGTAC`
has nine and goes on to step 4. The merge then reports `RTACNNNNGTG`,
which passes the check on its own carriers (*A degenerate site is one
motif*).

A candidate set aside is reported, not called, with the reason (*Reading
the result table*), when it would otherwise be called: q \<
`q_threshold` and the lower bound at `score_thr`, on all its carriers.
These are the calls the check removes, such as TA249’s `GCAANNNNNNTAGA`.
Both tests rest on the candidate’s own carriers and the scan’s p-values,
so they are decided here, before step 4; a listed candidate may be one
that step 4 would also have removed. The others, 149 of TA249’s 155, are
dropped as step 4’s are: the log counts them and `verbose=True` lists
them.

## Step 4: drop candidates whose score was borrowed

Two descriptions of one site in different shapes — `ATACNNNNGTG` of
pattern `(4, 4, 3)` and `CACANNAGTA` of `(4, 2, 4)` — sit on mostly the
same plasmids, but neither is the other with a position left undefined.
What separates them is what each has that the other does not:

``` python
_pair = ["ATACNNNNGTG", "CACANNAGTA"]
_has = _carriers(enc, _pair, [(4, 4, 3), (4, 2, 4)], log2fc_df["JJ1886_T0"], left, right)
_dep = fcs < -1
print(f"shared: {(_has[:, 0] & _has[:, 1]).sum()} plasmids")
for j, other in [(0, 1), (1, 0)]:
    alone = _has[:, j] & ~_has[:, other]
    print(f"{_pair[j]:<12} n={_has[:, j].sum()}  score {_dep[_has[:, j]].mean():.3f}   "
          f"without {_pair[other]}'s plasmids: n={alone.sum()}  score {_dep[alone].mean():.3f}")
```

    shared: 188 plasmids
    ATACNNNNGTG  n=192  score 1.000   without CACANNAGTA's plasmids: n=4  score 1.000
    CACANNAGTA   n=192  score 0.990   without ATACNNNNGTG's plasmids: n=4  score 0.500

Without the plasmids carrying `ATACNNNNGTG`, `CACANNAGTA` falls from
0.99 to 0.50: its score was **borrowed**. Without those carrying
`CACANNAGTA`, `ATACNNNNGTG` holds at 1.00. A candidate is dropped when,
restricted to the plasmids that carry it but no stronger candidate, it
no longer reaches `score_thr`. The test is on the collapse, not on what
is left: both leftovers here are four plasmids.

Candidates are tested strongest first — highest fraction depleted, then
most plasmids — each against the union of the survivors ranked above it.
Every survivor is then tested again against all the others, weakest
first, because a shadow can rank above the site it shadows. A leftover
must also be depleted beyond its own background at the scan’s cutoff:
the largest p-value that clears `q_threshold` after Benjamini-Hochberg
over every motif the scan tested, the pool every candidate was selected
from. On the six-pattern search of step 3:

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

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

### \_filter_explained_candidates

Drop candidates whose depletion is fully accounted for by stronger
candidates.

``` python
_filter_explained_candidates(candidates_df, log2fc_series, left_context,
                             right_context, log2fc_thr=-1, score_thr=0.7,
                             min_support=3, encoded=None, p_threshold=0.05,
                             background=None, presence=None)
```

<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>candidates_df</code></td>
<td>DataFrame</td>
<td></td>
<td>candidates, with ‘motif’ and optionally ‘pattern’</td>
</tr>
<tr>
<td><code>log2fc_series</code></td>
<td>Series</td>
<td></td>
<td>log2FC indexed by insert</td>
</tr>
<tr>
<td><code>left_context</code></td>
<td>str</td>
<td></td>
<td>vector sequence 5’ of the insert</td>
</tr>
<tr>
<td><code>right_context</code></td>
<td>str</td>
<td></td>
<td>vector sequence 3’ of the insert</td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td><code>-1</code></td>
<td>a plasmid is depleted below this</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td><code>0.7</code></td>
<td>share of a candidate’s leftover plasmids that must still be
depleted</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>3</code></td>
<td>not used; accepted so the step takes the pipeline’s thresholds</td>
</tr>
<tr>
<td><code>encoded</code></td>
<td>tuple | None</td>
<td><code>None</code></td>
<td>the library from <a
href="https://dbikard.github.io/randseq/coding.html#encode_library"><code>encode_library</code></a>,
if the caller has it</td>
</tr>
<tr>
<td><code>p_threshold</code></td>
<td>float</td>
<td><code>0.05</code></td>
<td>the leftover must beat its carriers’ mean background at this p</td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray | None</td>
<td><code>None</code></td>
<td>expected depletion per plasmid; default <a
href="https://dbikard.github.io/randseq/utils.html#plasmid_background"><code>plasmid_background</code></a></td>
</tr>
<tr>
<td><code>presence</code></td>
<td>ndarray | None</td>
<td><code>None</code></td>
<td>each candidate’s carriers (<a
href="https://dbikard.github.io/randseq/core.html#_carriers"><code>_carriers</code></a>),
if the caller has them</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>tuple</td>
<td></td>
<td><code>(kept, explanations)</code>: dropped motif -&gt; (explained
by, plasmids left, their score)</td>
</tr>
</tbody>
</table>

``` python
_scan = [_scan_candidates(p, enc, fcs, bg, -1, 0.7, 3)[1] for p in pats]
_pv = np.concatenate(_scan)
_cut = _pv[_benjamini_hochberg(_pv) < 0.05].max()          # the scan's BH cutoff at q < 0.05
after4, why = _filter_explained_candidates(kept, log2fc_df["JJ1886_T0"], left, right,
                                          log2fc_thr=-1, score_thr=0.7, encoded=enc,
                                          p_threshold=_cut)
print(f"scan cutoff p <= {_cut:.1e}; {len(kept)} candidates -> {len(after4)}")
for m, (by, n, s) in sorted(why.items(), key=lambda kv: -kv[1][1]):
    print(f"  {m:<14} <- {by:<28} {n:>3} plasmids left, score {s:.2f}")
after4[["motif", "pattern", "fraction_depleted", "num_sequences"]]
```

    scan cutoff p <= 1.4e-04; 33 candidates -> 5
      AAGTNNNNTTAA   <- AACNNNNCTTT                    3 plasmids left, score 0.67
      CACGNNNNTACC   <- CACNNNNGTAT + 1 more           3 plasmids left, score 0.67
      GTGTNNNNCGGA   <- CACNNNNGTAT                    3 plasmids left, score 0.67
      CTCTNNNNTCTC   <- CACNNNNGTAT                    3 plasmids left, score 0.67
      GAACNNNNGCCC   <- CACNNNNGTAC                    2 plasmids left, score 1.00
      AATANNNNTGTG   <- CACNNNNGTAT + 1 more           2 plasmids left, score 0.00
      GAAGNNNACAC    <- CACNNNNGTAT                    2 plasmids left, score 0.50
      AAGGNNNGTTC    <- AACNNNNCTTT                    2 plasmids left, score 0.50
      CCTGAGA        <- GAGACC                         2 plasmids left, score 0.50
      TGGCNNNCACA    <- CACNNNNGTAT                    2 plasmids left, score 0.00
      GACCNNNNCCTC   <- GAGACC                         1 plasmids left, score 1.00
      AGAGNNNNCACG   <- CACNNNNGTAT + 1 more           1 plasmids left, score 1.00
      CCACNNNTGTA    <- CACNNNNGTAC                    1 plasmids left, score 1.00
      AAGTNNNGTTA    <- AACNNNNCTTT + 1 more           1 plasmids left, score 0.00
      CTGGNNNNCACA   <- CACNNNNGTAT                    1 plasmids left, score 0.00
      GTGTNNNNATAA   <- CACNNNNGTAT                    1 plasmids left, score 0.00
      TGTGNNNATAA    <- CACNNNNGTAT                    1 plasmids left, score 0.00
      AAGTNNNGTTC    <- AACNNNNCTTT + 1 more           1 plasmids left, score 0.00
      CAGANNNCTCA    <- GAGACC                         1 plasmids left, score 0.00
      CCTGNNNCCTC    <- GAGACC + 1 more                1 plasmids left, score 0.00
      CGCCNNNNCACA   <- CACNNNNGTAT                    1 plasmids left, score 0.00
      GACTNNNACAC    <- CACNNNNGTAT                    1 plasmids left, score 0.00
      TGCTNNNCACA    <- CACNNNNGTAT                    1 plasmids left, score 0.00
      GCGGNNNNCACA   <- CACNNNNGTAT + 1 more           0 plasmids left, score 0.00
      CCTTNNNACAC    <- CACNNNNGTAT                    0 plasmids left, score 0.00
      GCAGNNNNCTCA   <- GAGACC                         0 plasmids left, score 0.00
      GGCANNNNCACA   <- CACNNNNGTAT                    0 plasmids left, score 0.00
      TGTGNNNNTAAA   <- CACNNNNGTAT                    0 plasmids left, score 0.00

<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">pattern</th>
<th data-quarto-table-cell-role="th">fraction_depleted</th>
<th data-quarto-table-cell-role="th">num_sequences</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>GAGACC</td>
<td>(6, 0, 0)</td>
<td>1.0</td>
<td>9</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">12</td>
<td>AACNNNNCTTT</td>
<td>(3, 4, 4)</td>
<td>1.0</td>
<td>63</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">14</td>
<td>CACNNNNGTAT</td>
<td>(3, 4, 4)</td>
<td>1.0</td>
<td>192</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">17</td>
<td>CACNNNNGTAC</td>
<td>(3, 4, 4)</td>
<td>1.0</td>
<td>20</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">34</td>
<td>AGGTNNNGGTC</td>
<td>(4, 3, 4)</td>
<td>1.0</td>
<td>3</td>
</tr>
</tbody>
</table>

</div>

Five candidates stand: the strain’s four sites and `AGGTNNNGGTC`, which
rests on three depleted plasmids that no stronger candidate accounts for
(this search uses `min_support=3`; the default of 5 would not have
admitted it). `AATANNNNTGTG` keeps two of its 190 plasmids, neither
depleted. `GAAGNNNACAC` shows why a leftover must also beat background:
one of its two leftover plasmids is depleted, 50%, but against their
background of 0.050 that is p = 0.10, far above the cutoff.

## Reporting

A motif and its reverse complement carry identical statistics, so each
reported motif is put on its canonical strand
([`canonical_motif`](https://dbikard.github.io/randseq/utils.html#canonical_motif),
`01_utils`), its pattern mirrored to follow it: a site comes back as
`GGTCTC`, never `GAGACC`, in every run and every dataset of the same
strain.

### Is the depletion one population or two?

A real site shifts its carriers as one population. A shadow of another
site is a **mixture**: the carriers that also carry the real site are
destroyed, the rest untouched. Sarle’s **bimodality coefficient**
exceeds 5/9, its value for a uniform distribution, when a distribution
has two modes — but also when the carriers fall into two *depleted*
groups: `CACNNNNGTAC` on the 20 nt JJ1886 library has 19 carriers
between −6.6 and −4.4 and one at −8.6, a coefficient of 0.654. So
`bimodal` also requires that, split in two where they separate best, the
upper group is not depleted (its median at or above `log2fc_thr`);
`bimodality` keeps the raw coefficient. A shadow is significant and
bimodal, a weak real site significant and unimodal, so both are
reported; bimodality does not block a call.

[`_annotate_significance`](https://dbikard.github.io/randseq/core.html#_annotate_significance)
adds these two columns to the result table, with the p- and q-values and
the bound on the depleted fraction (*Reading the result table*, below).

### A degenerate site is one motif

The scan reports motifs of A, C, G and T, so a site that accepts two
bases at a position comes back as two motifs. B156 in the example panel
recognises `GACNNNNGTTY`; steps 2–4 call `GAACNNNNGTC` and `AAACNNNNGTC`
— the site read on the other strand, split at its first base — and keep
both, because each depletes plasmids the other does not carry. Rule 3’s
classification reads the position:

``` python
counts_panel = pd.read_csv(os.path.join(data_path, "counts_panel.csv.gz"), index_col=0)
left_panel, right_panel = "GTCTAGGGCGGCGGTAAAAC", "ACTAGAGCACCAGAAGTCTA"
log2fc_panel = calculate_log2fc(counts_panel, reference_column="Control_R1", count_threshold=20)
b156 = log2fc_panel["B156_R1"]
enc_panel = encode_library(get_lib_seq_context(b156.index.tolist(), left_panel, right_panel))
fc_b156 = b156.to_numpy()
bg_b156 = plasmid_background(b156.index, fc_b156, -0.5)

_cls = _classify_positions("GAACNNNNGTC", [0], (4, 4, 3), enc_panel, fc_b156, bg_b156, -0.5)[0]
for m, n, s, b in _variant_profile([x + "AACNNNNGTC" for x in "ACGT"], (4, 4, 3), enc_panel,
                                  fc_b156, bg_b156, -0.5):
    print(f"  {m}  n={n:>4}  score={s:.3f}  background={b:.3f}  {_cls.get(m[0], ('(the call)',))[0]}")
```

      AAACNNNNGTC  n= 894  score=0.992  background=0.140  site
      CAACNNNNGTC  n= 386  score=0.140  background=0.139  non-site
      GAACNNNNGTC  n= 291  score=0.986  background=0.139  (the call)
      TAACNNNNGTC  n= 461  score=0.141  background=0.140  non-site

One other base is site-like and two are not, so the position is
degenerate and becomes `R`.
[`_generalise_motif`](https://dbikard.github.io/randseq/core.html#_generalise_motif)
applies this to every defined position of a call, one position at a time
— the one whose site-like bases have the most carriers, the first on a
tie — and classifies the merged motif again on its own carriers until
nothing changes. A merged motif’s carriers are the plasmids carrying any
of its instances, counted from the presence matrix, since one plasmid
can carry two.

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

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

### \_generalise_motif

`motif` with each degenerate position written as the IUPAC letter of its
site-like bases.

``` python
_generalise_motif(motif, pattern, encoded_library, fc_values, background,
                  log2fc_thr=-1, min_support=5, totals=None)
```

<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>motif</code></td>
<td>str</td>
<td></td>
<td>a called motif</td>
</tr>
<tr>
<td><code>pattern</code></td>
<td>tuple</td>
<td></td>
<td>its <code>(d1, spacer, d2)</code> shape</td>
</tr>
<tr>
<td><code>encoded_library</code></td>
<td>tuple</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>fc_values</code></td>
<td>ndarray</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>background</code></td>
<td>ndarray</td>
<td></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td><code>-1</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>5</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><code>totals</code></td>
<td>dict | None</td>
<td><code>None</code></td>
<td>as for <a
href="https://dbikard.github.io/randseq/core.html#_is_mixture"><code>_is_mixture</code></a></td>
</tr>
<tr>
<td><em>returns</em></td>
<td>str</td>
<td></td>
<td>the merged motif, or <code>motif</code> itself when no position is
degenerate</td>
</tr>
</tbody>
</table>

``` python
# B156's two sites, each from one of its called variants.
for seed, pat in [("GAACNNNNGTC", (4, 4, 3)), ("ACANNNNNATGG", (3, 5, 4))]:
    merged = _generalise_motif(seed, pat, enc_panel, fc_b156, bg_b156, -0.5)
    print(f"  {seed} -> {merged} (reported as {canonical_motif(merged)})")
```

      GAACNNNNGTC -> RAACNNNNGTC (reported as GACNNNNGTTY)
      ACANNNNNATGG -> ACANNNNNRTGG (reported as CCAYNNNNNTGT)

[`_merge_degenerate_calls`](https://dbikard.github.io/randseq/core.html#_merge_degenerate_calls)
scores each merged motif on its own carriers, against the scan’s
p-values; when it is called, it replaces the called rows that are its
instances on either strand, and `merged_from` names them. It starts from
the calls, after step 4 has removed the shadows the rule would otherwise
fire on. A merged motif also replaces an instance set aside for want of
internal sites (*Sites completed by the flank*), since it passed that
check on carriers that include the variant’s: on the 20 nt JJ1886
library, `RTACNNNNGTG` replaces `ATACNNNNGTG` this way. B156’s result,
below, shows both its sites merged.

A palindromic site has a limit of its own. In `CCTNAGG` (381A) the
central N pairs C with G and A with T, so `CCTHAGG` (not G, hence not C
on the other strand) is carried by exactly the plasmids carrying
`CCTNAGG`: the data can only set C/G against A/T. In both 381A
replicates A/T is site-like beside C/G, so `CCTNAGG` is what the data
support.

``` python
_cct = _carriers(enc_panel, ["CCTNAGG", "CCTHAGG", "CCTSAGG", "CCTWAGG"],
                 [(3, 1, 3), (7, 0, 0), (7, 0, 0), (7, 0, 0)], b156, left_panel, right_panel)
print("carriers of CCTNAGG, CCTHAGG, CCTSAGG, CCTWAGG:", _cct.sum(axis=0))
```

    carriers of CCTNAGG, CCTHAGG, CCTSAGG, CCTWAGG: [595 595 240 355]

### Reading the result table

[`find_restricted_motifs`](https://dbikard.github.io/randseq/core.html#find_restricted_motifs)
returns the called motifs in five columns: `motif`, `num_sequences`,
`fraction_depleted`, `avg_log2fc` and `q_value`. With `all_motifs=True`
it returns every motif that reached scoring, called or not, with all the
columns below.

- **How strong is the effect?** `fraction_depleted` is the share of
  carriers depleted, and `avg_log2fc` says how far they fall. Compare
  `fraction_depleted` with `background`, the rate at which plasmids like
  the carriers deplete anyway
  ([`plasmid_background`](https://dbikard.github.io/randseq/utils.html#plasmid_background)):
  381A’s `CCTNAGG` depletes 0.74 of its carriers against a background of
  0.30 (*The example panel at a glance*, below), EDL933’s
  `CACNNNNNNNCTGG` 0.91 against 0.09.
- **How sure are we?** `p_value` is the binomial probability of at least
  this many depleted carriers at their `background` rate, and `q_value`
  adjusts it over every motif the scan tested in the sample (`01_utils`,
  *Is a motif’s depletion more than the sample’s own noise?*). A call
  needs q \< `q_threshold`.
- **Are most carriers depleted?** `fraction_depleted_lower` is a 95%
  lower bound on the depleted fraction, and a call needs it at
  `score_thr` too. On the 20 nt JJ1886 library `CTTNCACA` has 10 of 20
  carriers depleted (q = 7·10⁻⁵) but bounds the fraction only at 0.30;
  `GGTCTC`, 9 of 9, bounds it at 0.72.
- **Does it need the flank?** `junction_share` is the share of carriers
  with no site wholly inside the insert. Above 0.5 a call also needs its
  `internal_n` internal carriers to pass on their own:
  `internal_fraction_lower` at `score_thr`, `internal_p_value` below
  `q_threshold` (*Sites completed by the flank*). A candidate that fails
  this is listed only when it would otherwise be called.
- **Is it one population?** `bimodal` marks carriers that mix destroyed
  and untouched plasmids; `bimodality` is the raw coefficient.
- **Is it a degenerate site?** `merged_from` lists the variants an IUPAC
  motif replaced, and is empty for every other row.
- **Why called or not?** `called` is the verdict, and `reason`
  ([`call_reason`](https://dbikard.github.io/randseq/core.html#call_reason))
  says it in words: `called`, or each test that failed with its numbers.
  A called row whose carriers are bimodal says so, since that is worth a
  look before trusting the call.

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

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

### call_reason

Why a row of the result table is called or not, in a few words.

``` python
call_reason(row, q_threshold=0.05, score_thr=0.5, min_support=5)
```

<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>row</code></td>
<td>Series</td>
<td></td>
<td>a row of the result table with every column
(<code>all_motifs=True</code>)</td>
</tr>
<tr>
<td><code>q_threshold</code></td>
<td>float</td>
<td><code>0.05</code></td>
<td>a call needs q below this</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td><code>0.5</code></td>
<td>and the lower bound on the depleted fraction at this or above</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>5</code></td>
<td>a motif that needs the flanks needs this many internal carriers</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>str</td>
<td></td>
<td>“called”, or each failed test with its numbers; a bimodal call adds
a note</td>
</tr>
</tbody>
</table>

``` python
# A row with the numbers of GTCGNNNNNNNCGGA on the 20 nt JJ1886 run, its flank columns aside:
# significant, but 7 of 12 carriers depleted bounds the depleted fraction at 0.32, so most carriers
# are not shown depleted.
_row = lambda **kw: pd.Series({"num_sequences": 12, "fraction_depleted": 7 / 12, "q_value": 1e-3,
                               "fraction_depleted_lower": 0.32, "bimodal": True,
                               "junction_share": 0.0, "internal_n": 12, "internal_fraction_lower": 0.32,
                               "internal_p_value": 1e-3, **kw})
call_reason(_row())
```

    'most carriers not shown depleted (7/12; lower bound 0.32 < 0.5)'

## Running the pipeline

Steps 2 to 4 and reporting, on one sample. Thresholds too loose for a
sample can leave step 3 with tens of thousands of candidates, which step
4 would compare for minutes; past `max_candidates` the pipeline raises
[`TooManyCandidatesError`](https://dbikard.github.io/randseq/core.html#toomanycandidateserror)
instead of returning a table. A count that large usually means the
thresholds are too loose for the sample, not that the strain has
thousands of sites.

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

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

### TooManyCandidatesError

Raised when step 3 leaves more candidates than step 4 will compare.

``` python
TooManyCandidatesError(n_candidates, max_candidates, log2fc_thr, score_thr,
                       min_support, candidates)
```

<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>n_candidates</code></td>
<td>int</td>
<td></td>
<td>how many candidates step 3 left; kept as
<code>.n_candidates</code></td>
</tr>
<tr>
<td><code>max_candidates</code></td>
<td>int</td>
<td></td>
<td>the limit they exceed; kept as <code>.max_candidates</code></td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td></td>
<td>the run’s thresholds, quoted in the message</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td></td>
<td>quoted in the message</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td></td>
<td>quoted in the message</td>
</tr>
<tr>
<td><code>candidates</code></td>
<td>DataFrame</td>
<td></td>
<td>step 3’s candidate table; kept as <code>.candidates</code></td>
</tr>
</tbody>
</table>

[`find_restricted_motifs`](https://dbikard.github.io/randseq/core.html#find_restricted_motifs)
expects log2FC as
[`calculate_log2fc`](https://dbikard.github.io/randseq/utils.html#calculate_log2fc)
returns them, median-normalised, and uses them as given: normalise
values computed elsewhere the same way. Every test is against the
GC-matched background of
[`plasmid_background`](https://dbikard.github.io/randseq/utils.html#plasmid_background).
On the arguments:

- `log2fc_thr`, −0.5 by default, is relative to the sample’s median
  plasmid: low enough to see weakly restricting systems such as BREX,
  which −1 misses.
- `min_support`: with every carrier depleted, the lower bound on the
  depleted fraction is 0.22, 0.37, 0.47 and 0.55 for 2 to 5 carriers, so
  5 is the smallest support that can be called at `score_thr=0.5` (4 at
  0.45, 7 at 0.65). Lower only adds candidates and runtime: E1114 on the
  20 nt library exceeds `max_candidates` at 2 to 4.
- `score_thr`: a candidate needs this share of its carriers depleted,
  and a call needs the lower bound `fraction_depleted_lower` to reach
  it.
- `q_threshold`: the q-value is Benjamini-Hochberg over every motif the
  scan tested, each against its carriers’ background.
- `max_candidates`: step 4’s cost grows faster than the number of
  candidates. The default, 5000, is above the 3,258 that the busiest
  strain of the example data (E1114, 20 nt library) brings at the
  defaults. A caller screening many strains should catch
  [`TooManyCandidatesError`](https://dbikard.github.io/randseq/core.html#toomanycandidateserror)
  and record that strain as “no confident call”.
- `patterns`: a pattern and its mirror find the same sites, so each is
  searched once, in one form: `(4, 4, 3)` is searched as `(3, 4, 4)`.
- `n_jobs`: a pattern takes about a second on a 30k-sequence library, so
  more processes are rarely worth their startup cost.
- `verbose`: by default the log counts what each step keeps, and how
  many of the candidates set aside for the flank would otherwise be
  called. `verbose=True` also lists each candidate set aside, marking
  those, and each candidate step 4 removes, with the stronger motif that
  explains its plasmids (most of these appear in no table), and each
  motif scored.
- `encoded_library`:
  `encode_library(get_lib_seq_context(log2fc_series.index, left, right))`.
  Strains screened with the same library and flanks share it, so a panel
  encodes it once; it must describe exactly `log2fc_series.index`, in
  order.

The default table holds the called motifs, sorted by q then motif; with
`all_motifs=True`, every scored motif, called rows first (*Reading the
result table*).

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

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

### find_restricted_motifs

The motifs one sample restricts: steps 2 to 4 and reporting, on a log2FC
series.

``` python
find_restricted_motifs(log2fc_series, left_context_str, right_context_str,
                       n_jobs=1, patterns=None, log2fc_thr=-0.5, min_support=5,
                       score_thr=0.5, max_candidates=5000, q_threshold=0.05,
                       encoded_library=None, all_motifs=False, verbose=False)
```

<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>log2fc_series</code></td>
<td>Series</td>
<td></td>
<td>log2FC indexed by insert, median-normalised (<a
href="https://dbikard.github.io/randseq/utils.html#calculate_log2fc"><code>calculate_log2fc</code></a>)</td>
</tr>
<tr>
<td><code>left_context_str</code></td>
<td>str</td>
<td></td>
<td>vector sequence 5’ of the insert</td>
</tr>
<tr>
<td><code>right_context_str</code></td>
<td>str</td>
<td></td>
<td>vector sequence 3’ of the insert</td>
</tr>
<tr>
<td><code>n_jobs</code></td>
<td>int</td>
<td><code>1</code></td>
<td>processes scanning the patterns; 1 scans in this process</td>
</tr>
<tr>
<td><code>patterns</code></td>
<td>list | None</td>
<td><code>None</code></td>
<td><code>(d1, spacer, d2)</code> shapes to search, or one; default <a
href="https://dbikard.github.io/randseq/utils.html#get_patterns"><code>get_patterns()</code></a></td>
</tr>
<tr>
<td><code>log2fc_thr</code></td>
<td>float</td>
<td><code>-0.5</code></td>
<td>a plasmid counts as depleted below this</td>
</tr>
<tr>
<td><code>min_support</code></td>
<td>int</td>
<td><code>5</code></td>
<td>fewest carriers a motif is scored on</td>
</tr>
<tr>
<td><code>score_thr</code></td>
<td>float</td>
<td><code>0.5</code></td>
<td>share of carriers a candidate needs depleted, and a call its lower
bound</td>
</tr>
<tr>
<td><code>max_candidates</code></td>
<td>int</td>
<td><code>5000</code></td>
<td>most candidates step 3 may hand to step 4; past it, raise</td>
</tr>
<tr>
<td><code>q_threshold</code></td>
<td>float</td>
<td><code>0.05</code></td>
<td>a motif is called when its q-value is below this</td>
</tr>
<tr>
<td><code>encoded_library</code></td>
<td>tuple | None</td>
<td><code>None</code></td>
<td>the library from <a
href="https://dbikard.github.io/randseq/coding.html#encode_library"><code>encode_library</code></a>,
if already encoded</td>
</tr>
<tr>
<td><code>all_motifs</code></td>
<td>bool</td>
<td><code>False</code></td>
<td>return every scored motif with every column, not only the calls</td>
</tr>
<tr>
<td><code>verbose</code></td>
<td>bool</td>
<td><code>False</code></td>
<td>also print each candidate set aside or removed, and each motif
scored</td>
</tr>
<tr>
<td><em>returns</em></td>
<td>DataFrame</td>
<td></td>
<td>the called motifs, one row each (<em>Reading the result
table</em>)</td>
</tr>
</tbody>
</table>

## Putting it to work

JJ1886 in the panel, at the defaults — every pattern of
[`get_patterns()`](https://dbikard.github.io/randseq/utils.html#get_patterns),
a plasmid depleted below −0.5, score 0.5:

``` python
motifs_jj1886 = find_restricted_motifs(log2fc_panel["JJ1886_R1"], left_panel, right_panel)
motifs_jj1886
```

    85 candidate(s) across all patterns; 4 remain after step 3.
    4 motif(s) scored.
    1 degenerate site(s) reported as one motif:
      RTACNNNNGTG <- ATACNNNNGTG + CACNNNNGTAC
    3 motif(s) called.

    Scanning patterns:   0%|          | 0/43 [00:00<?, ?it/s]
    Scanning patterns:  21%|##        | 9/43 [00:00<00:00, 83.23it/s]
    Scanning patterns:  42%|####1     | 18/43 [00:00<00:00, 83.29it/s]
    Scanning patterns:  63%|######2   | 27/43 [00:00<00:00, 76.11it/s]
    Scanning patterns:  81%|########1 | 35/43 [00:00<00:00, 67.24it/s]
    Scanning patterns:  98%|#########7| 42/43 [00:00<00:00, 45.60it/s]
    Scanning patterns: 100%|##########| 43/43 [00:00<00:00, 54.40it/s]

<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">num_sequences</th>
<th data-quarto-table-cell-role="th">fraction_depleted</th>
<th data-quarto-table-cell-role="th">avg_log2fc</th>
<th data-quarto-table-cell-role="th">q_value</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>AAAGNNNNGTT</td>
<td>913</td>
<td>0.997809</td>
<td>-3.425663</td>
<td>0.000000e+00</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>RTACNNNNGTG</td>
<td>963</td>
<td>1.000000</td>
<td>-3.285517</td>
<td>0.000000e+00</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>GGTCTC</td>
<td>55</td>
<td>0.981818</td>
<td>-2.851532</td>
<td>2.999895e-43</td>
</tr>
</tbody>
</table>

</div>

``` python
import io, contextlib
```

B156’s two degenerate sites, each reported as one motif;
`all_motifs=True` shows the variants each replaced:

``` python
motifs_b156 = find_restricted_motifs(log2fc_panel["B156_R1"], left_panel, right_panel,
                                     all_motifs=True)
motifs_b156[["motif", "num_sequences", "q_value", "merged_from", "reason"]]
```

    160 candidate(s) across all patterns; 4 remain after step 3.
    4 motif(s) scored.
    2 degenerate site(s) reported as one motif:
      GACNNNNGTTY <- AAACNNNNGTC + GAACNNNNGTC
      CCAYNNNNNTGT <- ACANNNNNATGG + ACANNNNNGTGG
    2 motif(s) called.

    Scanning patterns:   0%|          | 0/43 [00:00<?, ?it/s]
    Scanning patterns:  21%|##        | 9/43 [00:00<00:00, 85.41it/s]
    Scanning patterns:  42%|####1     | 18/43 [00:00<00:00, 83.54it/s]
    Scanning patterns:  63%|######2   | 27/43 [00:00<00:00, 76.76it/s]
    Scanning patterns:  81%|########1 | 35/43 [00:00<00:00, 68.07it/s]
    Scanning patterns:  98%|#########7| 42/43 [00:00<00:00, 46.13it/s]
    Scanning patterns: 100%|##########| 43/43 [00:00<00:00, 54.97it/s]

<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">num_sequences</th>
<th data-quarto-table-cell-role="th">q_value</th>
<th data-quarto-table-cell-role="th">merged_from</th>
<th data-quarto-table-cell-role="th">reason</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>CCAYNNNNNTGT</td>
<td>926</td>
<td>0.0</td>
<td>ACANNNNNATGG+ACANNNNNGTGG</td>
<td>called</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>GACNNNNGTTY</td>
<td>1174</td>
<td>0.0</td>
<td>AAACNNNNGTC+GAACNNNNGTC</td>
<td>called</td>
</tr>
</tbody>
</table>

</div>

### The example panel at a glance

Every strain of the example panel at the defaults, replicate R1.
`sample_rate` is the share of all the sample’s plasmids depleted, the
rate a motif would be tested against without a GC-matched background.

``` python
panel_calls = []
for s in [c for c in log2fc_panel.columns if c.endswith("_R1")]:
    x = log2fc_panel[s]
    with contextlib.redirect_stdout(io.StringIO()), _quiet():
        t = find_restricted_motifs(x, left_panel, right_panel, encoded_library=enc_panel, all_motifs=True)
    panel_calls.append(t.assign(sample=s, sample_rate=(x < -0.5).mean()))
panel_calls = pd.concat(panel_calls, ignore_index=True)
panel_calls[["sample", "motif", "num_sequences", "sample_rate", "background", "fraction_depleted",
             "fraction_depleted_lower", "avg_log2fc", "q_value", "called"]].round(
    {"sample_rate": 3, "background": 3, "fraction_depleted": 3, "fraction_depleted_lower": 3, "avg_log2fc": 2})
```

<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">sample</th>
<th data-quarto-table-cell-role="th">motif</th>
<th data-quarto-table-cell-role="th">num_sequences</th>
<th data-quarto-table-cell-role="th">sample_rate</th>
<th data-quarto-table-cell-role="th">background</th>
<th data-quarto-table-cell-role="th">fraction_depleted</th>
<th data-quarto-table-cell-role="th">fraction_depleted_lower</th>
<th data-quarto-table-cell-role="th">avg_log2fc</th>
<th data-quarto-table-cell-role="th">q_value</th>
<th data-quarto-table-cell-role="th">called</th>
</tr>
</thead>
<tbody>
<tr>
<td data-quarto-table-cell-role="th">0</td>
<td>JJ1886_R1</td>
<td>AAAGNNNNGTT</td>
<td>913</td>
<td>0.131</td>
<td>0.132</td>
<td>0.997809</td>
<td>0.993</td>
<td>-3.425663</td>
<td>0.000000e+00</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">1</td>
<td>JJ1886_R1</td>
<td>RTACNNNNGTG</td>
<td>963</td>
<td>0.131</td>
<td>0.131</td>
<td>1.0</td>
<td>0.997</td>
<td>-3.285517</td>
<td>0.000000e+00</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">2</td>
<td>JJ1886_R1</td>
<td>GGTCTC</td>
<td>55</td>
<td>0.131</td>
<td>0.130</td>
<td>0.981818</td>
<td>0.917</td>
<td>-2.851532</td>
<td>2.999895e-43</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">3</td>
<td>CFT073_R1</td>
<td>GAGNNNNNNNGTCA</td>
<td>301</td>
<td>0.167</td>
<td>0.141</td>
<td>0.837209</td>
<td>0.798</td>
<td>-1.037914</td>
<td>3.873944e-156</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">4</td>
<td>HS_R1</td>
<td>GGTAAG</td>
<td>1879</td>
<td>0.115</td>
<td>0.116</td>
<td>0.637573</td>
<td>0.619</td>
<td>-0.654037</td>
<td>0.000000e+00</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">5</td>
<td>LMR_503_R1</td>
<td>AAAGNNNNGTT</td>
<td>913</td>
<td>0.191</td>
<td>0.194</td>
<td>0.995619</td>
<td>0.990</td>
<td>-3.09052</td>
<td>0.000000e+00</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">6</td>
<td>LMR_503_R1</td>
<td>RTACNNNNGTG</td>
<td>963</td>
<td>0.191</td>
<td>0.191</td>
<td>1.0</td>
<td>0.997</td>
<td>-3.186244</td>
<td>0.000000e+00</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">7</td>
<td>LMR_503_R1</td>
<td>ACGNNNNNGTTG</td>
<td>414</td>
<td>0.191</td>
<td>0.189</td>
<td>0.917874</td>
<td>0.892</td>
<td>-1.551262</td>
<td>7.910596e-224</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">8</td>
<td>LMR_503_R1</td>
<td>GGTCTC</td>
<td>55</td>
<td>0.191</td>
<td>0.187</td>
<td>0.963636</td>
<td>0.890</td>
<td>-2.595199</td>
<td>1.262662e-32</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">9</td>
<td>B156_R1</td>
<td>CCAYNNNNNTGT</td>
<td>926</td>
<td>0.140</td>
<td>0.140</td>
<td>0.988121</td>
<td>0.980</td>
<td>-2.609215</td>
<td>0.000000e+00</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">10</td>
<td>B156_R1</td>
<td>GACNNNNGTTY</td>
<td>1174</td>
<td>0.140</td>
<td>0.140</td>
<td>0.99063</td>
<td>0.985</td>
<td>-2.535198</td>
<td>0.000000e+00</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">11</td>
<td>381A_R1</td>
<td>CCTNAGG</td>
<td>595</td>
<td>0.304</td>
<td>0.295</td>
<td>0.736134</td>
<td>0.705</td>
<td>-1.369679</td>
<td>4.131717e-103</td>
<td>True</td>
</tr>
<tr>
<td data-quarto-table-cell-role="th">12</td>
<td>EDL933_R1</td>
<td>CACNNNNNNNCTGG</td>
<td>277</td>
<td>0.108</td>
<td>0.089</td>
<td>0.906137</td>
<td>0.872</td>
<td>-1.15585</td>
<td>7.219223e-223</td>
<td>True</td>
</tr>
</tbody>
</table>

</div>

The RM sites of JJ1886, LMR_503, B156, CFT073 and EDL933 deplete 84% to
100% of their carriers, against backgrounds of 0.09 to 0.19. HS’s BREX
site `GGTAAG` is a weaker system: 64% of its carriers depleted, by 0.65
log2 on average, yet on 1,879 carriers it is as significant as the
strongest RM site. 381A is a noisy sample, with 30% of all its plasmids
depleted; `CCTNAGG` is called at 74% against that. EDL933_dRM_R1 calls
nothing.

Every scored row is a call. On these calls the GC-matched background
stays within 0.02 of the sample’s rate, except for CFT073’s
`GAGNNNNNNNGTCA` (0.14 against 0.17).
