Representing library sequences and motifs as integers, so that scoring a motif is arithmetic
Why the scan is arithmetic
The scan in 00_core scores every motif of every pattern against every sequence, which is where its runtime goes. On strings — a Python set of motif strings per sequence — that costs roughly 10 s and 2 GB of RAM per pattern on a 30k-sequence library; on integers it is well under a second.
A motif of pattern (d1, spacer, d2) is pinned down entirely by its d1 + d2 defined bases — the spacer is N by construction — so it can be held as an integer in [0, 4**(d1+d2)). Every per-motif statistic then becomes an np.bincount over those integers, and the library is encoded once and reused for every pattern.
Nothing here decides anything biological: its only job is to give exactly the answer a readable string-based scan would, faster. The checks in this notebook hold the encoding to that, and tests/test_reference_scan.py holds the whole scan to it.
The base alphabet, and why it is ACGT in that order
A=0, C=1, G=2, T=3, and anything else — N, lowercase junk, the padding of a short sequence — is 4.
The order is not arbitrary. Complementary bases sit at opposite ends of it, so complementing a base is 3 - code: A↔︎T is 0↔︎3, C↔︎G is 1↔︎2. That is the whole reverse-complement implementation, and it is why encode_library can return the reverse strand for the price of one subtraction and one reversal.
Code 4 does double duty: it marks a base that is not ACGT and the padding that squares off a ragged library into a rectangular array. Both must be excluded from the scan, and because they share a marker, one test excludes both — there is no separate length bookkeeping to get wrong.
Both strands are left-aligned and padded on the right, so row i of rc is the reverse complement of sequence i occupying its first len(s) columns — not a reversal of the padded row, which would put the padding at the front.
From a window to an integer, and back
Write the d1 + d2 defined bases of a motif as the digits of a base-4 numeral:
_pattern_window_codes builds that numeral by Horner’s method — code = code*4 + next_digit, one pass over the defined positions in increasing order. The trick that makes it fast is that each step operates on a sliding view, encoded_seqs[:, j:j+n_windows]: position j of the window starting at w is absolute index w+j, so as w runs over all windows that column is exactly the slice above. Every window of every sequence is therefore built in parallel, with one vector operation per defined base rather than one per window.
Rejecting windows. A window containing a non-ACGT base anywhere — spacer included, to match the [ATGC] regex the reference implementation uses — is set to 4**(d1+d2), one past the largest real code. Which windows those are comes from a prefix sum over the == 4 mask: the number of bad bases in [w, w+width) is n_bad[w+width] - n_bad[w], so all windows are tested at once. Padding is code 4, so a window running off the end of a short sequence is rejected by the same test, with nothing extra written for it.
Decoding reverses the numeral. Base 4 is two bits, so digit i counted from the most significant is (code >> 2*(n-1-i)) & 3 — the same digits in the same order the encoder wrote them. _decode_motif_codes then drops N into the spacer positions.
With pattern (1, 2, 2), CAAGT has a single window whose defined bases are C, G, T, i.e. code 1*16 + 2*4 + 3 = 27. A window touching the N is rejected (code 4**3 = 64):
fwd, rc = encode_library(["CAAGT", "CAAGTN"])# A=0 C=1 G=2 T=3, so a motif's code is literally its defined bases as a base-4 numeral:# CNNGT of pattern (1,2,2) has defined bases C,G,T -> digits 1,2,3 -> int("123", 4).CNNGT =int("123", 4)REJECTED =4**3# the sentinel: one past the largest 3-digit base-4 numeralprint(f"CNNGT = {CNNGT}, REJECTED = {REJECTED}")print(_pattern_window_codes(fwd, (1, 2, 2)))_decode_motif_codes([CNNGT, int("000", 4)], (1, 2, 2))
CNNGT = 27, REJECTED = 64
[[27 64]
[27 64]]
['CNNGT', 'ANNAA']
What guarantees this is right?
The scan reports a motif string, but everything between the library and that string is integer arithmetic. Four properties have to hold, or the output is confidently wrong rather than obviously broken.
1. Distinct motifs get distinct codes. A base-4 numeral with a fixed number of digits is unique to its digit string — that is just positional notation — and the digit count is fixed at d1+d2 for a given pattern. Two different motifs of the same pattern therefore cannot collide.
2. Decoding is exactly the inverse of encoding. Both walk the same d1+d2 positions in the same order; the encoder multiplies up, the decoder shifts down. Cheap enough to check exhaustively rather than argue about, which this notebook’s tests do.
3. A rejected window can never be read as a motif. Real codes fill [0, 4**(d1+d2)) and the sentinel is 4**(d1+d2) exactly, so the single test code < 4**(d1+d2) separates them with no gap and no overlap. This is why the sentinel is that value and not, say, -1.
4. The arithmetic stays in range. Codes are int32, which holds 15 defined bases; the shipped patterns use at most 8. Beyond 15 the numeral would wrap and every count for that pattern would be quietly wrong, so _pattern_window_codes raises instead.
Properties 1–3 hold by construction and are verified exhaustively by this notebook’s tests. Whether the whole scan means the same thing as a readable implementation is a separate question: tests/test_reference_scan.py runs _get_pattern_scores against the string-based scan in tests/reference_scan.py and requires identical tables.
Encoding a motif back to its code
_encode_motif is the inverse of _decode_motif_codes: it turns a motif string back into the integer the scan counts under. It returns None for anything it cannot represent — an IUPAC-degenerate motif has no single code, and nor has a motif that does not fit the pattern — so a caller can expand a degenerate motif into its instances (_motif_instances in core) or fall back to a regex, rather than silently mis-assign sequences. tests/test_vectorized_presence.py checks the two paths agree element for element.
# the decode example above, inverted: CNNGT is digits 1,2,3; an IUPAC base has no single code_encode_motif("CNNGT", (1, 2, 2)), _encode_motif("YNNGT", (1, 2, 2))
(27, None)
The two strands of one site
An enzyme cuts a double-stranded site, so GAGACC and GGTCTC are one motif seen from two sides, and the scan must not count them as two. Where they can be folded together is decided by the pattern, because a motif of (d1, spacer, d2) reverse-complements into one of (d2, spacer, d1):
when that is the same shape — a contiguous motif (spacer == 0), or a balanced one (d1 == d2) — both spellings are codes in the same space, and one physical site is found twice, once per strand. These fold.
otherwise the rc spelling lives in another pattern’s space. Nothing to fold: scanning (3, 4, 4) on both strands already finds each site exactly once, because a (4, 4, 3) site is read on the reverse strand and spelled as (3, 4, 4). This is why find_restricted_motifs rewrites every pattern to its _canonical_pattern and drops duplicates — searching both shapes would re-find the same sites in mirror spelling, at twice the cost.
Folding an asymmetric pattern would merge two unrelated motifs, since reversing the digits of a (4, 4, 3) code reads the d2 bases where the d1 bases belong. _rc_code_table therefore refuses any pattern that is not self-rc.
The table itself is one observation: a code is the defined bases as a base-4 numeral, and the defined bases of the reverse complement are those digits reversed and complemented (A<->T, C<->G is 3 - digit). The spacer is undefined on both strands, so it plays no part. Because each base is two bits, both operations are bit arithmetic on the code: complementing every digit is a single XOR with 11 repeated k times, and reversing the digits is reversing the order of the 2-bit groups. _rc_code_table builds the table that way, and this notebook’s tests check it against revcomp on the motif strings over entire code spaces.
# GAGACC and GGTCTC are one site: the table maps each spelling's code to the other's_t = _rc_code_table((6, 0, 0))print(_decode_motif_codes([_t[_encode_motif("GAGACC", (6, 0, 0))]], (6, 0, 0)))# contiguous and balanced patterns fold; (3, 4, 4) does not, its rc motifs are (4, 4, 3)[_pattern_is_self_rc(p) for p in [(6, 0, 0), (4, 4, 4), (3, 4, 4)]]
['GGTCTC']
[True, True, False]
Scanning one pattern
A pattern is scored from two arrays: which motifs each sequence carries, and the totals of each motif over its carriers. The library below is twelve inserts of twelve bases with GAGACC (GGTCTC on the other strand) planted in four of them, and those four are the depleted ones, so a correct scan must report GAGACC on four plasmids, all depleted.
demo_lib = ["GAGACCTTAACG", "TTGAGACCGCAT", "ACGGTCTCAATG", "CCAAGAGACCTT","ACGTTGCAATGC", "TTACGCATTGCA", "GCATTACGGTTA", "ATGCCATTGCAA","CATGCAATTGCG", "TTGCAATGCCAT", "GCAATTGCATGC", "ATTGCCATGCAA"]demo_fc = np.array([-2.5, -3.0, -3.5, -3.0, 0.2, -0.1, 0.0, 0.3, -0.2, 0.1, 0.0, -0.3])pd.DataFrame({"insert": demo_lib, "log2FC": demo_fc,"carries the site": [("GAGACC"in s) or ("GGTCTC"in s) for s in demo_lib],"depleted (< -1)": demo_fc <-1})
insert
log2FC
carries the site
depleted (< -1)
0
GAGACCTTAACG
-2.5
True
True
1
TTGAGACCGCAT
-3.0
True
True
2
ACGGTCTCAATG
-3.5
True
True
3
CCAAGAGACCTT
-3.0
True
True
4
ACGTTGCAATGC
0.2
False
False
5
TTACGCATTGCA
-0.1
False
False
6
GCATTACGGTTA
0.0
False
False
7
ATGCCATTGCAA
0.3
False
False
8
CATGCAATTGCG
-0.2
False
False
9
TTGCAATGCCAT
0.1
False
False
10
GCAATTGCATGC
0.0
False
False
11
ATTGCCATGCAA
-0.3
False
False
Which motifs each sequence carries._motif_occurrences scans every window of both strands and reduces the result to one entry per sequence and motif: a motif occurring twice in an insert, or once on each strand, is one plasmid carrying it. For a self-rc pattern the two spellings of a site are folded onto the smaller code (_rc_code_table); for any other pattern the rc spelling is not in this code space, so there is nothing to fold. Either way each pattern emits one row per plasmid per site.
seq_idx, motif_codes = _motif_occurrences(encode_library(demo_lib), (6, 0, 0))occurrences = pd.DataFrame({"sequence": [demo_lib[i] for i in seq_idx],"motif": _decode_motif_codes(motif_codes, (6, 0, 0)),# the code IS the motif: A=0 C=1 G=2 T=3, read as a base-4 numeral"code (base 4)": [np.base_repr(c, 4).zfill(6) for c in motif_codes],"code": motif_codes})print(f"{len(occurrences)} (sequence, motif) pairs from {len(demo_lib)} sequences")occurrences.head(8)
82 (sequence, motif) pairs from 12 sequences
sequence
motif
code (base 4)
code
0
GAGACCTTAACG
AAGGTC
002231
173
1
GAGACCTTAACG
ACCTTA
011330
380
2
GAGACCTTAACG
AGACCT
020113
535
3
GAGACCTTAACG
CCTTAA
113300
1520
4
GAGACCTTAACG
CGTTAA
123300
1776
5
GAGACCTTAACG
CTTAAC
133001
1985
6
GAGACCTTAACG
GAGACC
202011
2181
7
TTGAGACCGCAT
ACCGCA
011210
356
Each row is one plasmid carrying one motif, and the base-4 column shows that a code is the motif: GAGACC is 202011. The planted site:
Four sequences, one row each: GGTCTC is the same site read on the other strand, folded onto GAGACC, the smaller numeral. Reporting re-spells it on the strand REBASE uses (canonical_motif).
A window containing a base other than ACGT is dropped, and so is one running past the end of a short sequence, since padding carries the same code as N:
edge = ["GAGACCTT", # clean"GAGACCTTNAAAAAA", # an N at position 8, then six more bases"GAGAC"] # shorter than the 6-base pattern_s, _c = _motif_occurrences(encode_library(edge), (6, 0, 0))pd.DataFrame({"sequence": [edge[i] for i in _s], "motif": _decode_motif_codes(_c, (6, 0, 0))})
sequence
motif
0
GAGACCTT
AAGGTC
1
GAGACCTT
AGACCT
2
GAGACCTT
GAGACC
3
GAGACCTTNAAAAAA
AAAAAA
4
GAGACCTTNAAAAAA
AAGGTC
5
GAGACCTTNAAAAAA
AGACCT
6
GAGACCTTNAAAAAA
GAGACC
The second insert keeps the windows that end before its N, loses the six that cover it, and picks up AAAAAA after it (TTTTTT on the other strand, folded). Every window of the third runs into the padding.
Totals per motif. Every statistic the scan reports is a sum over a motif’s carriers, so each is one np.bincount: carriers, depleted carriers, the sum of their log2FC, the sum of their background (each plasmid’s expected depletion rate, from plasmid_background; here one rate for all), and the first carrier, which makes the output order a function of the library rather than of hash order.
demo_bg = np.full(len(demo_lib), (demo_fc <-1).mean()) # one rate for all: 4 of 12n_seqs, n_depleted, fc_sum, bg_sum, first_seq = _motif_totals( seq_idx, motif_codes, demo_fc, demo_bg, -1, 4**6)present = np.flatnonzero(n_seqs) # the motifs this library actually containstotals = pd.DataFrame({"motif": _decode_motif_codes(present, (6, 0, 0)),"n_seqs": n_seqs[present], "n_depleted": n_depleted[present],"sum_log2fc": fc_sum[present], "sum_background": bg_sum[present],"first_seq": first_seq[present]})print(f"{len(totals)} motifs present out of {4**6} possible")totals.sort_values(["n_depleted", "n_seqs"], ascending=False).head(6)
53 motifs present out of 4096 possible
motif
n_seqs
n_depleted
sum_log2fc
sum_background
first_seq
43
GAGACC
4
4.0
-12.0
1.333333
0
2
AAGGTC
2
2.0
-5.5
0.666667
0
13
AGACCG
2
2.0
-6.5
0.666667
1
14
AGACCT
2
2.0
-5.5
0.666667
0
47
GTCTCA
2
2.0
-6.5
0.666667
1
50
TCTCAA
2
2.0
-6.5
0.666667
1
GAGACC tops the table with four carriers, all depleted. 05_fast turns these totals into the reported scores, and adds a compiled kernel that computes them in one pass.
Reading motif presence off the window codes
Scoring a pattern asks what motifs a sequence contains. The rest of the pipeline asks the reverse, of a handful of specific candidates: which sequences contain this motif, on either strand?
Done directly that is a regex per sequence per motif, and a noisy strain, which carries the most candidates, pays for it most. Instead presence is a lookup in the window codes, done once per pattern rather than once per motif: for 200 motifs of 4 patterns on the 150 nt example library (counts_panel.csv.gz, 30,108 inserts after the count filter), 0.3 s against 6 s for the regex, with identical answers.
_motif_presence_matrix returns (matrix, handled). A motif the fast path cannot encode — IUPAC-degenerate, or of an unknown pattern — is left as an all-False column and flagged in handled, so the caller does not read a blank column as “absent”: core reads a degenerate motif through its instances, each of which has a code, and a motif of unknown pattern by regex.
With insert (the lengths of the two flanks and of each insert) it also says which sequences carry the motif wholly inside the insert, from the same windows: this is how core tells a site from one the vector flank completes (Sites completed by the flank).
One row per sequence, one column per motif. GAGACC is found in the second sequence only on the other strand, where it is spelled GGTCTC: presence means “on either strand”.