The helpers core is built from: fold changes, motif strings and strands, the search space,
Counts to log2 fold change
Each plasmid’s depletion is the log2 ratio of its share of the recipient sample to its share of the donor library, normalised so that the sample’s median plasmid sits at 0. Four details matter:
The pseudocount is added to raw counts, before normalisation: (n+1)/Σ(n+1) per sample, then the ratio. Normalised counts are far below 1, so adding 1 after normalising would flatten every ratio towards 1.
Shares are over the plasmids that pass the count filter, not over every molecule sequenced. That is a per-sample constant: it shifts all log2FC of a sample by the same amount, and the median normalisation below removes it.
Each sample is normalised to its median plasmid (normalize="median", the default): each column’s median log2FC is subtracted, so the median plasmid has log2FC 0, a fold change of 1. This is median-ratio normalisation, as in DESeq2; on the log2 scale, subtracting the median is the same as rescaling the counts by the median ratio. Shares alone are not enough: when a few plasmids take a large share of a sample’s reads, every other plasmid’s share shrinks and its log2FC falls below 0, by an amount that differs from strain to strain. Against the median plasmid, a depletion threshold of −0.5 means the same in every strain. normalize="total" stops at the shares.
The filter is reference count > count_threshold (default 20), in the one reference column.
count_threshold filters on donor abundance, not on depletion, so raising it costs power but does not choose which motifs are called. It does set how many plasmids carry each motif, so num_sequences is comparable between experiments only at the same threshold.
read counts, one row per insert, one column per sample; NaN counts as 0
reference_column
str
'MFDpir'
the input-library column every sample is compared with
count_threshold
int
20
an insert is kept when its reference count is strictly above this
pseudocount
float
1
added to the raw counts, before normalisation
normalize
str
'median'
“median”: each sample’s median insert at 0; “total”: shares only
returns
DataFrame
one column per sample, reference dropped; None without it, empty if none pass
# Four plasmids, a reference and one sample. 'd' sits exactly at the threshold and is dropped:# the filter is strict. By default the median plasmid, 'c', is at 0; "total" leaves the shares._toy = pd.DataFrame({'ref': [30, 90, 60, 20], 's': [0, 99, 40, 5]}, index=['a', 'b', 'c', 'd'])_fc = calculate_log2fc(_toy, reference_column='ref', count_threshold=20, pseudocount=1)_fc_total = calculate_log2fc(_toy, reference_column='ref', count_threshold=20, pseudocount=1, normalize="total")pd.DataFrame({"median": _fc['s'], "total": _fc_total['s']})
median
total
a
-4.381011
-4.588244
b
0.709247
0.502014
c
0.000000
-0.207233
# The smaller example library, against its MFDpir donor: the lowest log2FC in each strain.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.min(axis=0)
motif in upper-case IUPAC letters; anything else raises ValueError.
normalise_motif(motif)
Parameter
Type
Default
Description
motif
str
IUPAC letters and/or bracketed classes such as [AG], in any case
returns
str
upper-cased, each class written as its IUPAC letter: '[AG]TAC' -> 'RTAC'
normalise_motif rejects anything that is neither an IUPAC letter nor a class of A, C, G and T, so a misspelt motif fails loudly instead of matching nothing.
# Degenerate letters are complemented too: Y (C/T) pairs with R (A/G), so JJ1886's Type I site# read on the other strand is REBASE's RTACNNNNGTG. A bracketed class is written as its IUPAC letter.revcomp("CACNNNNGTAY"), normalise_motif("[ag]tacnnnngtg")
('RTACNNNNGTG', 'RTACNNNNGTG')
Choosing which strand to report a motif on
A recognition site and its reverse complement are the same site. The library is scanned on both strands, so a motif and its reverse complement always get identical statistics — same number of supporting sequences, same depletion score, same average log2FC. They are one answer, and which spelling to report is a tie that has to be broken the same way every time, or two result tables cannot be compared (GAGACC in one, GGTCTC in the other).
canonical_motif reports the strand REBASE uses, so results line up with the literature and with enzyme names (GGTCTC is BsaI/Eco31I). For motifs REBASE does not know, which includes most of what a discovery screen finds, it falls back to the alphabetically first strand: arbitrary, but the same on every run and machine. A motif REBASE lists on both strands takes the alphabetically first too.
The strand to report motif on: the one REBASE uses, else the alphabetically first.
canonical_motif(motif, rebase_motifs=None)
Parameter
Type
Default
Description
motif
str
an IUPAC motif, e.g. 'GAGACC'; bracketed classes are accepted
rebase_motifs
set | None
None
motifs to match; default the REBASE Gold Standard set shipped
returns
str
motif or its reverse complement, in IUPAC letters (normalise_motif)
# REBASE spells the BsaI / Eco31I site GGTCTC, so that is the strand we report; a motif unknown# to REBASE is reported on its alphabetically first strand.canonical_motif('GAGACC'), canonical_motif('AACNNNNCTTT'), canonical_motif('TGGCCGC', rebase_motifs=set())
A pattern (d1, spacer, d2) is the shape of a site: defined bases, undefined gap, defined bases. get_patterns returns the shapes the scan searches by default, each in the one form the scan uses.
The default is 43 patterns: contiguous sites of 5–7 bases, and gapped sites whose halves are 2–4 bases, with 5–8 defined bases in all and a gap of 1–8. It fits 837 of the 983 distinct motifs in the REBASE Gold Standard set shipped with the package. The arguments widen it: get_patterns(contiguous=(4, 8), halves=(2, 5), max_spacer=9) (68 patterns) fits 902, and adding max_defined=9 (77) fits 911, at about 8 times the motifs tested (3.6 million against 460,000 on the larger example library). That is not the default because, at the default thresholds, a wider search adds one-base-longer descriptions of weak or degenerate sites that steps 3 and 4 do not yet catch.
A site whose half has an undefined base inside it, such as CNGTANNNNNNTTC, has two gaps, and no pattern describes it: 47 of the 983 Gold Standard motifs are of this kind, almost all Type I. Each concrete variant of such a site has a one-gap shape, here (5, 6, 3), which can be passed in patterns to find the site. The variants are then reported as separate rows (CAGTANNNNNNTTC, CCGTANNNNNNTTC, …), because writing N inside a half would give a shape the scan does not search.
Presence and log2FC lookups for a hand-picked list of motifs, independent of find_restricted_motifs. A motif may use IUPAC codes (N, R, Y, …) and regex character classes ([AG]) interchangeably, and is searched on both strands of the insert with its context. An empty or non-string entry of the list gives a column of False; a misspelt motif raises ValueError (normalise_motif).
_seqs = pd.Series(1, index=["AAGGTCTCAA", "AAGAGACCAA", "TCTCAAAA", "TTTTTTTT"])# GGTCTC on the forward strand, on the reverse strand, and across the left junction# ("GG" + "TCTC...", once the flank is restored)._get_filter_for_motif(_seqs, "GGTCTC", "GG", "")
‘sequence’, ‘Motif_Category’ (a motif or ‘Other’), ‘sample’, ‘log2fc’
A plasmid carrying several motifs is labelled with the last of them in motif_list, as in plot_motif_depletion. With no insert to search the function prints an error and returns None.
Is a motif’s depletion more than the sample’s own noise?
The scan in 00_core tests a great many motifs (about 330,000 with the default 5 or more supporting plasmids on the smaller example library, 460,000 on the larger), so some will look perfect by luck alone. How many supporting plasmids a call needs before that stops being a plausible explanation depends on the sample, not on a constant.
Under the null, a motif’s depleted count is Binomial(n, p) where p is the rate at which its carriers would deplete in this sample if no site were involved: their background. A noisy sample has a higher p and therefore needs more evidence for the same claim, automatically. How p is estimated for each motif is the next section; first, the binomial form itself.
Shuffled data bear this out. With each sample’s log2FC shuffled across its plasmids, 20 times for each of six strains of the two example libraries, find_restricted_motifs at the defaults calls nothing, at any min_support from 2 to 6; the smallest q in any shuffle is 0.005, on a row the confidence bound rejects.
What this does not model. The binomial treats the plasmids carrying a motif as independent draws. They are not: motifs co-occur, which is the whole subject of step 4 of the core pipeline. So the p-value is a screen against chance, not a complete model of how a spurious call arises: a shadow of a real site is highly significant by this test and still needs explaining away.
# BH: p*n/rank is 0.04 for all four here, so all four q-values are 0.04._benjamini_hochberg([0.01, 0.02, 0.03, 0.04])
array([0.04, 0.04, 0.04, 0.04])
The background depends on the insert’s GC content
Within one sample, the chance that a plasmid looks depleted is not the same for every insert. On the 20 nt library, AT-rich inserts deplete far more often than GC-rich ones in some strains, for no reason a site could explain (possibly a fitness cost of such inserts; the cause is unknown). Fraction of plasmids below −0.5, on log2FC as calculate_log2fc returns them:
E1114 depletes 0.58 of the inserts with GC ≤ 25% and 0.07 of those above 65%; H120 0.46 against 0.02. JJ1886 hardly varies. Against one sample-wide rate, any motif made of A and T inherits the excess of the inserts that carry it and is called: 42 calls in E1114 and 39 in H120, almost all AT-rich.
The fix is the standard one in motif enrichment (HOMER’s GC-matched background): compare a motif’s carriers with plasmids of the same GC content. plasmid_background gives each plasmid the depletion rate of the plasmids in its insert-GC decile, and a motif’s null rate is the mean of its carriers’ backgrounds. GC is counted on the insert alone: the flanks are the same in every plasmid. The bins are deciles, fixed rather than a parameter: fine enough to follow the trend above, coarse enough that every rate rests on hundreds of plasmids. A 20 nt insert has only 21 possible GC contents, so deciles that would share an edge merge: the 20 nt library has 8 bins of 660–2,020 plasmids, the 150 nt panel library 10 of 1,805–3,858.
log2FC per insert, in the same order, median-normalised as calculate_log2fc does
log2fc_thr
float
-1
a plasmid is depleted below this
returns
ndarray
one rate per plasmid, strictly between 0 and 1
# E1114: the bins plasmid_background uses, and each one's background. An AT-rich insert's is# several times a GC-rich one's, as in the table above._bg = plasmid_background(_l2.index, _l2["E1114_T0"], -0.5)(pd.DataFrame({"insert GC": _gc.to_numpy(), "background": _bg}).groupby("background")["insert GC"] .agg(["min", "max", "size"]).sort_values("min").round(3))
min
max
size
background
0.363963
0.10
0.35
1393
0.199697
0.40
0.40
1317
0.148408
0.45
0.45
1853
0.124257
0.50
0.50
2020
0.096296
0.55
0.55
1890
0.065505
0.60
0.60
1435
0.057754
0.65
0.65
935
0.069697
0.70
0.90
660
# One rate per motif: the same 10/10 is far less surprising for AT-rich carriers whose background# is 0.5 (0.5**10) than for carriers whose background is 0.05 (0.05**10)._motif_pvalues([10, 10], [1.0, 1.0], [0.5, 0.05])
array([9.765625e-04, 9.765625e-14])
Helpers for analysis scripts
The pipeline does not use these; they serve analysis scripts that build pattern lists by hand or merge results across strains. get_patterns is the usual way to get the search space; generate_tuple_combinations builds patterns in bulk, and filter_symmetric_tuples keeps one of each mirror pair, the first met: (3, 4, 4) and (4, 4, 3) find the same sites, because the scan reads both strands.
Drop a tuple when its mirror (first and third elements swapped) came earlier in the list.
filter_symmetric_tuples(list_of_tuples)
Parameter
Type
Default
Description
list_of_tuples
list
(d1, spacer, d2) tuples
returns
list
the tuples kept, in input order
# The first of a mirror pair is kept, in input order; a self-mirror tuple stays.filter_symmetric_tuples([(4, 4, 3), (3, 4, 4), (4, 4, 4)])
[(4, 4, 3), (4, 4, 4)]
Merging motifs by spelling
find_iupac_equivalent_motifs groups same-length motifs that differ at ≤ max_mismatches positions (N positions skipped, reverse complements considered) and merges each group into one IUPAC motif, the union of bases at each position. It works on spelling alone, on any results table — across strains, say. Within one sample find_restricted_motifs already merges a degenerate site on the data, a variant joining only when its own carriers deplete like the site’s.
Groups are connected components: A~B and B~C merge all three, even when A and C are further apart. A motif that matched through its reverse complement is flipped before merging, and the merged motif is spelled on the strand of the group’s first row. Each row of the result, one per group with singletons included, gives merged_motif; original_motifs and original_motifs_oriented (as given, and on the merged strand); n_merged; max_pairwise_mismatches, over linked pairs; and rc_used, after sample_col when one is given. When df has them, num_sequences, avg_log2fc and fraction_depleted add total_sequences (their sum), avg_log2fc_weighted (weighted by num_sequences when present) and avg_fraction_depleted (unweighted mean).
motifs this many mismatches apart or fewer are linked; 1 or 2 advised
motif_col
str
'motif'
the column holding the motifs
sample_col
str | None
None
the sample column, each sample merged on its own; None: one sample
consider_rc
bool
True
also compare each motif with the other’s reverse complement
returns
DataFrame
one row per group of linked motifs, singletons included
Merging a results table with JJ1886’s motifs as the scan spells them (the statistics are illustrative): ATACNNNNGTG and CACNNNNGTAC are one mismatch apart once CACNNNNGTAC is flipped, and merge into REBASE’s RTACNNNNGTG: