Repository navigation
Description
Biopython's motif search is very slow for long sequences. For example, running it for a "random" 500 kbp sequence for the mouse genome with a CTCF motif takes ~2.5 minutes.
Here is a realistic example of a code to annotate motifs that I ran for a 500 kbp sequence:
%%prun
sites = []
bg = {'A':seq.count('A')/l, 'T':seq.count('T')/l, 'G':seq.count('G')/l, 'C':seq.count('C')/l}
pssm = pfm.pwm.log_odds(bg)
print('Got PSSM')
sl = len(pfm)
i = 0
t = time.time()
for pos, score in pssm.search(seq, threshold=7):
if abs(pos) >= i:
print(i, len(sites), time.time()-t)
i += 10000
if pos < 0:
strand = '-'
start = l+pos-sl
else:
strand = '+'
start = pos
sites.append([chrom, start, start+sl, strand, score])
sites = pd.DataFrame.from_records(sites, columns=['Chromosome', 'Start', 'End', 'Strand', 'Score'])Got PSSM
0 0 2.0478174686431885
10000 2 4.058326721191406
20000 3 4.646576166152954
30000 4 4.920068979263306
40000 5 5.375012636184692
50000 6 5.443111896514893
60000 8 6.0875067710876465
70000 13 11.027215480804443
80000 15 11.987048625946045
90000 19 17.511669397354126
100000 21 18.390772104263306
110000 25 19.8211829662323
120000 27 20.215988636016846
130000 28 20.231982707977295
140000 29 21.383938550949097
150000 31 22.255633115768433
160000 32 23.772958755493164
170000 33 23.932071447372437
180000 34 25.212602138519287
190000 35 25.851369857788086
200000 36 27.52578067779541
210000 40 29.91758108139038
220000 41 32.79414367675781
230000 42 33.60089659690857
240000 44 34.95528721809387
250000 46 35.159255504608154
260000 47 35.528780937194824
270000 48 36.44404315948486
280000 49 36.45104694366455
290000 50 37.153515577316284
300000 55 39.4925754070282
310000 58 40.15520477294922
320000 59 40.58962845802307
330000 60 40.729615926742554
340000 62 42.952834129333496
350000 65 44.504544734954834
360000 160 114.50919079780579
370000 167 118.49372220039368
380000 169 121.2152419090271
390000 175 124.65023851394653
400000 179 127.58756136894226
410000 185 131.23024106025696
420000 190 136.9982407093048
430000 191 137.73300671577454
440000 196 140.6570725440979
450000 204 151.1570451259613
460000 206 152.5533037185669
470000 207 154.19884824752808
480000 210 157.08620762825012
490000 211 157.83301162719727
Here are the top few lines of prun output:
637986800 function calls (637986785 primitive calls) in 152.975 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
75997576 69.802 0.000 110.334 0.000 matrix.py:93(__getitem__)
380988464 30.814 0.000 30.814 0.000 {built-in method builtins.isinstance}
18999316 21.019 0.000 131.352 0.000 matrix.py:34(<listcomp>)
999986 8.175 0.000 8.175 0.000 {built-in method numpy.array}
75997576 5.105 0.000 5.105 0.000 {function GenericPositionMatrix.__getitem__ at 0x7f69edae3b70}
77997651/77997636 4.955 0.000 4.955 0.000 {built-in method builtins.len}
216 4.300 0.020 159.012 0.736 matrix.py:408(search)
999964 2.453 0.000 150.575 0.000 matrix.py:28(_calculate)
999964 2.279 0.000 153.734 0.000 matrix.py:380(calculate)
999970 1.228 0.000 1.228 0.000 {built-in method numpy.empty}
999964 1.222 0.000 1.222 0.000 {built-in method Bio.motifs._pwm.calculate}
As one might notice, the first line in the profiler output is matrix.py:93(__getitem__), and it takes almost 2 minutes of cumtime. I think, this is coming from
biopython/Bio/motifs/matrix.py
Line 34 in 7844bca
| logodds = numpy.array([[score_dict[letter][i] for letter in "ACGT"] |
I am very inexperienced with OOP, so my attempts at creating a PR failed, however I assumer it would be trivial.
Another issue, and why I added timings and number of motifs found every 10 kbp, is that clearly when there is a lot of hits with the minimum score, for some reason it slows down the code a lot, e.g. look at the jump at 360000! I am not sure why this is happening though. And I have repeated the run with all additional code for adding found motifs to a list etc commented out, and it doesn't make a difference.
Activity
peterjc commentedon Nov 27, 2019
Do you have a complete example? You are missing
import timeand the definition ofpfmDoes replacing this:
with:
help a little? Probably only a tiny bit.
Beyond that perhaps @mdehoon can comment. I wondered if maybe the C code could take a scores dictionary rather than an array... or if the
GenericPositionMatrixclass could have an.as_array()method?Phlya commentedon Nov 27, 2019
Sorry, I can make a complete example, but would need to share a long fasta file and the pfm then - this was just meant as a demonstration.
Your suggestion would still lead to the same number of getitem calls, I think? That seems to be main culprit.
I would just do something like this somewhere at initialisation:
self.array = numpy.vstack([self[nt] for nt in 'AGCT']).TAnd then use
self.array- or.as_array()would work as well if it just returns the stored array.The problem is the code path for systems without numpy...
Phlya commentedon Nov 27, 2019
Here is a complete example:
test_seq.txt
CTCF_human.txt
peterjc commentedon Nov 27, 2019
Can you clarify what platform you are on - CPython, PyPy, other; has the C code in your Biopython been compiled and installed; and if you have numpy installed or not.
I suspect that with the current state of PyPy support for C code we can now remove the pure-python fall back as it is no longer needed (numpy would be required).
Phlya commentedon Nov 27, 2019
Sorry - it's CPython on Ubuntu 18.04, and I installed biopython from PyPI - so I guess I have the C code installed? Numpy is installed.
peterjc commentedon Nov 27, 2019
What does this do on your system?
I'm trying to confirm which of the two
_calculatefunctions is being called, the first one (requires our C code and numpy), or the second slower pure python one:https://github.com/biopython/biopython/blob/biopython-175/Bio/motifs/matrix.py#L28
https://github.com/biopython/biopython/blob/biopython-175/Bio/motifs/matrix.py#L46
This might answer more directly:
I get this screen - press Q to get out - showing the C code is available:
Phlya commentedon Nov 27, 2019
I'm getting the same screen as you with the second command.
Phlya commentedon Nov 27, 2019
I tried simply doing this to test performance improvement:
But I get an error, that I don't understand:
mdehoon commentedon Nov 27, 2019
I would suggest to rewrite the
searchfunction such that it callsself.calculateonly once:and then iterate over the scores. That should be much faster (but it will also use more memory).
peterjc commentedon Nov 27, 2019
Current code as in Biopython 1.75,
With my tiny suggestion:
Single run only, ~5s is a slight improvement - might be worth benching marking properly but doesn't seem to help much:
Phlya commentedon Nov 27, 2019
If
calculatewas a generator that would remove the memory issue! I don't know anything about C, would that be possible?peterjc commentedon Nov 27, 2019
The following looks more promising,
Using your test script ending as follows BTW,
New:
Old:
Confirming no change in the output:
Not bad, about a fifth of the run time.
Note: I have not checked the pure Python version actually still works.
Do you like this approach @mdehoon? This has the advantage of not changing the public API at all.
peterjc commentedon Nov 27, 2019
I don't know this code well enough to comment on the generator idea without a lot more work - my change is very targeted, avoiding the hot-spot of the matrix class
__getitem__@phyla identifier by benchmarking. Essentially that is a big if/else statement to decide how to handle various index arguments - since in this context we know the exact arguments in advance, and can do the appropriate look up directly.Phlya commentedon Nov 27, 2019
That looks really good! This still creates a new array for each position, is it possible to calculate it just once and store? I'd expect it to be even faster then, although not sure this would still be the bottleneck after your change.
peterjc commentedon Nov 27, 2019
With a slight refactoring I think yes, the
.search()call could define the array once for the duration of the search, do the alphabet check and call._calculate()directly (bypassing.calculate()which can remain as a public API).Update: I'm not currently clear enough on how the reverse-complement is being handled in the search to try that...
3 remaining items
peterjc commentedon Nov 28, 2019
Perhaps the motifs code should raise a
TypeErrorwhen given aSeqRecord, or do the expected thing and use the.seqattribute automatically?Phlya commentedon Nov 28, 2019
Ah of course, thank you! I would have expected this to raise an error?..
Phlya commentedon Nov 28, 2019
And it does work super quickly!
Phlya commentedon Nov 28, 2019
But indeed, simply applying
.calculate()to a whole chromosome leads toMemoryErroron my machine.mdehoon commentedon Nov 28, 2019
@Phlya
Then you could modify the
searchfunction such that the sequence is divided into segments, and search each separately. If the segments are long enough (maybe 100,000 bp or so), the code will still be fast while memory usage will stay low.Phlya commentedon Nov 28, 2019
Exactly what I am writing now
Phlya commentedon Nov 28, 2019
Here is the function that works for me. It uses pandas, which I think is not a biopython dependency? I am however happy for it to be adapted to replace the
.search()method.mdehoon commentedon Nov 29, 2019
@Phlya Indeed, pandas is not a biopython dependency.
Would you be able to create a pull request with the code to replace the
.search()method in Biopython?Phlya commentedon Nov 30, 2019
Ok, this implementation, actually, will miss motifs on the edges of chunks, I'll have to modify it a little. Otherwise, yes, I can create a PR, perhaps, on Monday.
mdehoon commentedon Nov 30, 2019
@Phlya Great, thanks!
Phlya commentedon Dec 5, 2019
Sorry, I've been sick for a few days and accumulated some relatively urgent things I need to do at work, but I remember about this.
Phlya commentedon Dec 6, 2019
#2386 here is the PR, let me know what you think. It relies heavily on numpy, but assume that is OK
mdehoon commentedon Dec 22, 2019
As #2386 has been accepted, can we close this issue?
peterjc commentedon Dec 23, 2019
Probably this can be closed, yes.
Is there any need to merge #2361 as well, or can that be closed too?