fast

Scoring one pattern: its totals from an optional compiled kernel or from the numpy path, and the

Why a second implementation of the scan

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

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

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

It is optional

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

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

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

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

What guarantees this is the same scan?

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

One pattern’s scores

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

# The twelve inserts of `04_coding`: GAGACC planted in the four depleted ones
demo_lib = ["GAGACCTTAACG", "TTGAGACCGCAT", "ACGGTCTCAATG", "CCAAGAGACCTT",
            "ACGTTGCAATGC", "TTACGCATTGCA", "GCATTACGGTTA", "ATGCCATTGCAA",
            "CATGCAATTGCG", "TTGCAATGCCAT", "GCAATTGCATGC", "ATTGCCATGCAA"]
demo_fc = np.array([-2.5, -3.0, -3.5, -3.0, 0.2, -0.1, 0.0, 0.3, -0.2, 0.1, 0.0, -0.3])
scores = _get_pattern_scores(encode_library(demo_lib), demo_fc, (6, 0, 0))
scores.sort_values(["fraction_depleted", "num_sequences"], ascending=False).head(6)
motif fraction_depleted num_sequences avg_log2fc p_value
6 GAGACC 1.0 4 -3.00 0.012346
0 AAGGTC 1.0 2 -2.75 0.111111
2 AGACCT 1.0 2 -2.75 0.111111
8 AGACCG 1.0 2 -3.25 0.111111
11 GTCTCA 1.0 2 -3.25 0.111111
12 TCTCAA 1.0 2 -3.25 0.111111

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