Finding the DNA motifs a strain restricts, from a table of plasmid counts before and after delivery.
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:
counts → log2FC per plasmid
score every motif of every requested pattern — the scan
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
drop a candidate whose score was borrowed from a stronger one
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 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.
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
K12_T0
HS_T0
E1114_T0
E1167_T0
H120_T0
TA054_T0
TA447_T0
E101_T0
41-1Ti9_T0
TA280_T0
M114_T0
TA249_T0
ROAR8_T0
JJ1886_T0
CFT073_T0
APECO1_T0
UTI89_T0
S88_T0
MG1655_T0
seq
CGGAGGTACTGGGTACATTT
0.053839
0.052486
0.198139
-0.298920
0.248968
0.064302
0.173654
0.091857
0.037475
0.105217
-0.332624
-0.063143
0.153653
0.035279
0.199444
0.216417
-0.420177
0.208060
0.129389
TGGCGATAATGCCGGCTATC
0.055484
0.140062
0.447659
0.116408
0.148431
0.073310
0.050872
-0.015937
-0.000986
-0.027312
0.000043
0.123943
-0.158044
-0.031221
0.028689
0.003235
-0.170595
0.086728
0.140558
TTCCAGTTCACTGGTCTTCG
-0.039673
0.052838
-0.094876
-0.058226
-0.071222
-0.059618
0.389411
0.086398
0.215640
0.125599
0.201220
-0.066652
-0.003432
0.236186
-0.180337
0.256712
0.218989
0.452512
0.167261
AATTTCAGTGCCGTTCAGAT
-0.241936
-0.419289
-0.214320
-0.055334
-0.193911
-0.180443
-0.233472
-0.144541
-0.269051
-0.206790
0.055304
-0.024940
-0.019646
-0.091950
-0.108537
-0.267889
0.497149
-0.189453
-0.142007
CTGCGGTAATAATTCCCGCC
-0.168407
-0.151090
0.591358
0.405361
0.057666
-0.297286
-0.213485
-0.293529
-0.465928
-0.300698
-0.225458
-0.020998
0.095261
-0.328740
-0.219906
-0.110738
-0.311057
-0.194322
-0.147295
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
GCTTGATGTAGCCTTCGAAC
-0.090498
-0.077031
0.037574
-0.264828
-0.327042
-0.034614
-0.085175
-0.247852
-0.242389
-0.144174
-0.095388
0.034867
0.270337
-0.224290
0.265613
-0.219473
-0.282711
-0.061401
-0.094254
TAATGGCAAATTGACACTCC
0.268225
0.106618
0.438321
-0.102874
0.258529
0.063001
0.227910
0.131522
0.203018
0.094437
0.478815
-0.129064
0.000404
0.175361
-0.003251
0.204180
0.490384
0.196397
0.425986
GCTGCGCGCGGAGTTGTTCC
-0.619835
-0.378119
-0.421264
-0.324669
-0.451031
-0.246031
-0.455210
-0.359524
-0.364741
-0.361490
-0.585051
0.214125
-0.975015
-0.323065
-0.503433
-0.135453
-0.525759
-0.503168
-0.920714
GCAACACGCCAGTAAGGTGT
0.703437
0.490088
0.754857
-0.051391
0.485527
0.597611
0.149697
0.386591
0.741034
0.278790
0.164374
0.645063
0.409897
0.002233
0.408861
0.085801
0.331181
0.058894
0.415349
GATAGCCGGATAGCTTAAGG
-0.235664
-0.128696
-0.418972
-0.210574
-0.260554
-0.158647
-0.028420
-0.356935
-0.228562
-0.094755
-0.302651
-0.243483
-0.124763
-0.128952
-0.224737
-0.164897
-0.117829
-0.406399
0.179141
11503 rows × 19 columns
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() 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.
_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 motifvals = [f for f, c inzip(_fc, carries) if c]print(f"plasmids carrying GAGACC : {[s for s, c inzip(_seqs, carries) if c]}")print(f"their log2FC : {vals}")print(f"score, fraction below -1 : {np.mean(np.array(vals) <-1)}")
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), 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 in 01_utils explains why). _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, 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.
left, right ="GTCCTAGGTATAATACTAGT", "GTTTTAGAGCTAGAAATAGC"lib = get_lib_seq_context(log2fc_df.index, left, right)fcs = log2fc_df["JJ1886_T0"].valuesbg = plasmid_background(log2fc_df.index, fcs, -1)print(f"{len(lib)} sequences, each {len(lib[0])} nt with the flanks added")lib[0][:60]
(candidates, p-values of every motif tested, the pattern's totals)
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 themprint(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
motif
fraction_depleted
num_sequences
avg_log2fc
p_value
pattern
1
ATANNNNTGTG
0.964467
197
-4.638428
4.479256e-244
(3, 4, 4)
2
CACNNNNGTAT
1.000000
192
-4.805313
2.601024e-258
(3, 4, 4)
4
TACNNNNGTGA
0.849315
73
-4.059755
4.842427e-72
(3, 4, 4)
6
TACNNNNGTGG
0.907692
65
-4.409352
1.440987e-72
(3, 4, 4)
0
AACNNNNCTTT
1.000000
63
-5.209253
1.372226e-86
(3, 4, 4)
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 scores a set of related motifs — typically the four bases at one position — from the counts step 2 made (_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.
the scan’s totals by canonical pattern, shared; filled in place
returns
list
(motif, n_plasmids, score, carriers' mean background) per motif, in the order given
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}")
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.
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). 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.
Each undefined position worth testing on a candidate.
_undefined_positions(motif, pattern)
Parameter
Type
Default
Description
motif
str
the candidate
pattern
tuple
its (d1, spacer, d2) shape
returns
list
(four variants, their pattern) for each position
# 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]}")
_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:
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 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.
Source: _is_extension (notebook only)
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) +1and _find_broad_in_specific(specific, general)
CACNNNNGTAC passes rule 1. At the first position of its spacer, the four bases score alike:
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:
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) 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 classifies the bases at one position; _classify_positions does it at each position asked, profiling a motif of A, C, G and T from the scan’s counts (_variant_profile) and one with an IUPAC letter on the carriers of its instances (_union_profile).
True when, at one of _relax_positions, every other base is site-like
CCACNNNAGTA, a shadow of the strain’s Type I site that rules 1 and 2 let through, against CACNNNNGTAC, a real site:
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 elsef"={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 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:
each motif’s (d1, spacer, d2), or None where unknown
log2fc_series
Series
log2FC indexed by insert, read by the regex fallback
left_context
str
vector sequence 5’ of the insert
right_context
str
vector sequence 3’ of the insert
inside
bool
False
also return the carriers with a site wholly inside the insert
returns
ndarray
boolean, (n_sequences, n_motifs); with inside, (carriers, internal carriers)
_carriers reads which plasmids carry each motif from the window codes of its instances (_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). With inside=True it also returns the carriers with a site wholly inside the insert (Sites completed by the flank).
df without the redundant rows, in the original row order
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 inzip(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 notin mixtures]after2 = [r for r in surv ifnotany(_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
motif
pattern
fraction_depleted
num_sequences
14
CACNNNNGTAT
(3, 4, 4)
1.000000
192
51
AATANNNNTGTG
(4, 4, 4)
0.989474
190
12
AACNNNNCTTT
(3, 4, 4)
1.000000
63
17
CACNNNNGTAC
(3, 4, 4)
1.000000
20
1
GAGACC
(6, 0, 0)
1.000000
9
38
TGGCNNNCACA
(4, 3, 4)
0.714286
7
35
AAGTNNNGTTA
(4, 3, 4)
0.833333
6
25
GAAGNNNACAC
(4, 3, 4)
0.800000
5
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.
_carriers(..., inside=True) of df’s motifs, if the caller has them
returns
tuple
(kept, set_aside), rows of df; set_aside adds _junction_support and listed
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:
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:
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, 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 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:
One other base is site-like and two are not, so the position is degenerate and becomes R. _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.
the merged motif, or motif itself when no position is degenerate
# 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 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.
carriers of CCTNAGG, CCTHAGG, CCTSAGG, CCTWAGG: [595 595 240 355]
Reading the result table
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): 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) 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 row of the result table with every column (all_motifs=True)
q_threshold
float
0.05
a call needs q below this
score_thr
float
0.5
and the lower bound on the depleted fraction at this or above
min_support
int
5
a motif that needs the flanks needs this many internal carriers
returns
str
“called”, or each failed test with its numbers; a bimodal call adds a note
# 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())
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 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.
how many candidates step 3 left; kept as .n_candidates
max_candidates
int
the limit they exceed; kept as .max_candidates
log2fc_thr
float
the run’s thresholds, quoted in the message
score_thr
float
quoted in the message
min_support
int
quoted in the message
candidates
DataFrame
step 3’s candidate table; kept as .candidates
find_restricted_motifs expects log2FC as 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. 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 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).
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.
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})
sample
motif
num_sequences
sample_rate
background
fraction_depleted
fraction_depleted_lower
avg_log2fc
q_value
called
0
JJ1886_R1
AAAGNNNNGTT
913
0.131
0.132
0.997809
0.993
-3.425663
0.000000e+00
True
1
JJ1886_R1
RTACNNNNGTG
963
0.131
0.131
1.0
0.997
-3.285517
0.000000e+00
True
2
JJ1886_R1
GGTCTC
55
0.131
0.130
0.981818
0.917
-2.851532
2.999895e-43
True
3
CFT073_R1
GAGNNNNNNNGTCA
301
0.167
0.141
0.837209
0.798
-1.037914
3.873944e-156
True
4
HS_R1
GGTAAG
1879
0.115
0.116
0.637573
0.619
-0.654037
0.000000e+00
True
5
LMR_503_R1
AAAGNNNNGTT
913
0.191
0.194
0.995619
0.990
-3.09052
0.000000e+00
True
6
LMR_503_R1
RTACNNNNGTG
963
0.191
0.191
1.0
0.997
-3.186244
0.000000e+00
True
7
LMR_503_R1
ACGNNNNNGTTG
414
0.191
0.189
0.917874
0.892
-1.551262
7.910596e-224
True
8
LMR_503_R1
GGTCTC
55
0.191
0.187
0.963636
0.890
-2.595199
1.262662e-32
True
9
B156_R1
CCAYNNNNNTGT
926
0.140
0.140
0.988121
0.980
-2.609215
0.000000e+00
True
10
B156_R1
GACNNNNGTTY
1174
0.140
0.140
0.99063
0.985
-2.535198
0.000000e+00
True
11
381A_R1
CCTNAGG
595
0.304
0.295
0.736134
0.705
-1.369679
4.131717e-103
True
12
EDL933_R1
CACNNNNNNNCTGG
277
0.108
0.089
0.906137
0.872
-1.15585
7.219223e-223
True
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).