Debian Codegraph @

ncls/src/ncls.pyx

raw
1 # import numpy as cnp
2 import sys
3
4 cimport cython
5 from libc.stdint cimport int64_t
6 from libc.stdlib cimport malloc
7
8 cimport ncls.src.cncls as cn
9
10 import numpy as np
11
12
13 cdef inline int int_max(int a, int b): return a if a >= b else b
14 cdef inline int int_min(int a, int b): return a if a <= b else b
15 # import ctypes as c
16
17 try:
18 dummy = profile
19 except:
20 profile = lambda x: x
21
22 cdef class NCLS64:
23
24 cdef cn.SublistHeader *subheader
25 cdef cn.IntervalMap *im
26 cdef int n, ntop
27 cdef int nlists
28
29 # build NCLS from array of starts, ends, values
30 @cython.boundscheck(False)
31 @cython.wraparound(False)
32 @cython.initializedcheck(False)
33 def __cinit__(self, const int64_t [::1] starts=None, const int64_t [::1] ends=None, const int64_t [::1] ids=None):
34
35 if None in (starts, ends, ids):
36 return
37
38 if len(starts) == 0 or len(ends) == 0 or len(ids) == 0:
39 return
40
41 cdef int i
42 cdef length = len(starts)
43 self.close() # DUMP OUR EXISTING MEMORY
44 self.n = len(starts)
45 self.im = cn.interval_map_alloc(self.n)
46 if self.im == NULL:
47 raise MemoryError('unable to allocate IntervalMap[%d]' % self.n)
48 i = 0
49 for i in range(length):
50 self.im[i].start = starts[i]
51 self.im[i].end = ends[i]
52 self.im[i].target_id = <long> ids[i]
53 self.im[i].sublist = -1
54
55 self.subheader = cn.build_nested_list(self.im, self.n, &(self.ntop), &(self.nlists))
56
57 def intervals(self, take=None):
58 intervals = []
59
60 cdef int i = 0
61 cdef int _take = int(take) if not take is None else len(self)
62 if not self.im: # if empty
63 return []
64
65 for i in range(_take):
66 intervals.append((self.im[i].start, self.im[i].end, self.im[i].target_id))
67
68 return intervals
69
70
71 @cython.boundscheck(False)
72 @cython.wraparound(False)
73 @cython.initializedcheck(False)
74 cpdef all_overlaps_both(self,
75 const int64_t [::1] starts,
76 const int64_t [::1] ends,
77 const int64_t [::1] indexes):
78
79 cdef int i = 0
80 cdef int nhit = 0
81 cdef int length = len(starts)
82 cdef int loop_counter = 0
83 cdef int nfound = 0
84 cdef int spent = 0
85
86 output_arr = np.zeros(length, dtype=np.int64)
87 output_arr_other = np.zeros(length, dtype=np.int64)
88 cdef int64_t [::1] output
89 cdef int64_t [::1] output_other
90
91 output = output_arr
92 output_other = output_arr_other
93
94 cdef cn.IntervalIterator *it
95 cdef cn.IntervalIterator *it_alloc
96
97 cdef cn.IntervalMap im_buf[1024]
98 if not self.im: # if empty
99 return [], []
100
101 it_alloc = cn.interval_iterator_alloc()
102 it = it_alloc
103 for loop_counter in range(length):
104
105 spent = 0
106 while not spent:
107 i = 0
108 cn.find_intervals(it, starts[loop_counter], ends[loop_counter], self.im, self.ntop,
109 self.subheader, self.nlists, im_buf, 1024,
110 &(nhit), &(it)) # GET NEXT BUFFER CHUNK
111
112 if nfound + nhit >= length:
113
114 length = (length + nhit) * 2
115 output_arr = np.resize(output_arr, length)
116 output_arr_other = np.resize(output_arr_other, length)
117 output = output_arr
118 output_other = output_arr_other
119
120 while i < nhit:
121 output[nfound] = indexes[loop_counter]
122 output_other[nfound] = im_buf[i].target_id
123
124 # print(" output[nfound]", output[nfound])
125 # print(" output_other[nfound]", output_other[nfound])
126
127 nfound += 1
128 i += 1
129
130 if nhit < 1024:
131 spent = 1
132
133 cn.reset_interval_iterator(it_alloc)
134 it = it_alloc
135
136 cn.free_interval_iterator(it_alloc)
137
138 return output_arr[:nfound], output_arr_other[:nfound]
139
140
141 @cython.boundscheck(False)
142 @cython.wraparound(False)
143 @cython.initializedcheck(False)
144 cpdef last_overlap_both(self, const int64_t [::1] starts, const int64_t [::1] ends, const int64_t [::1] indexes):
145
146 cdef int i = 0
147 cdef int nhit = 0
148 cdef int length = len(starts)
149 cdef int loop_counter = 0
150 cdef int nfound = 0
151 cdef int max_end = -1
152 cdef int spent = 0
153
154 output_arr = np.zeros(length, dtype=np.int64)
155 output_arr_other = np.zeros(length, dtype=np.int64)
156 cdef int64_t [::1] output
157 cdef int64_t [::1] output_other
158
159 output = output_arr
160 output_other = output_arr_other
161
162 cdef cn.IntervalIterator *it
163 cdef cn.IntervalIterator *it_alloc
164
165 cdef cn.IntervalMap im_buf[1024]
166 if not self.im: # if empty
167 return [], []
168
169 it_alloc = cn.interval_iterator_alloc()
170 it = it_alloc
171 for loop_counter in range(length):
172 max_end = -1
173 spent = 0
174 while not spent:
175 i = 0
176 cn.find_intervals(it, starts[loop_counter], ends[loop_counter], self.im, self.ntop,
177 self.subheader, self.nlists, im_buf, 1024,
178 &(nhit), &(it)) # GET NEXT BUFFER CHUNK
179 if nhit:
180 while i < nhit:
181 if im_buf[i].end >= max_end:
182 # print("max_end", im_buf[i].end)
183 output[nfound] = indexes[loop_counter]
184 output_other[nfound] = im_buf[i].target_id
185 max_end = im_buf[i].end
186
187 i += 1
188
189 nfound += 1
190
191 if nhit < 1024:
192 spent = 1
193
194 cn.reset_interval_iterator(it_alloc)
195 it = it_alloc
196
197 cn.free_interval_iterator(it_alloc)
198
199 return output_arr[:nfound], output_arr_other[:nfound]
200
201
202 @cython.boundscheck(False)
203 @cython.wraparound(False)
204 @cython.initializedcheck(False)
205 cpdef k_overlaps_both(self, const int64_t [::1] starts, const int64_t [::1] ends, const int64_t [::1] indexes, int k):
206
207 cdef int i = 0
208 cdef int nhit = 0
209 cdef int length = len(starts)
210 cdef int loop_counter = 0
211 cdef int nfound = 0
212 cdef int spent = 0
213
214 output_arr = np.zeros(length, dtype=np.int64)
215 output_arr_other = np.zeros(length, dtype=np.int64)
216 cdef int64_t [::1] output
217 cdef int64_t [::1] output_other
218
219 output = output_arr
220 output_other = output_arr_other
221
222 cdef cn.IntervalIterator *it
223 cdef cn.IntervalIterator *it_alloc
224
225 cdef cn.IntervalMap im_buf[1024]
226 if not self.im: # if empty
227 return [], []
228
229 it_alloc = cn.interval_iterator_alloc()
230 it = it_alloc
231 for loop_counter in range(length):
232
233 # remember first pointer for dealloc
234 spent = 0
235 while not spent:
236 i = 0
237 cn.find_intervals(it, starts[loop_counter], ends[loop_counter], self.im, self.ntop,
238 self.subheader, self.nlists, im_buf, 1024,
239 &(nhit), &(it)) # GET NEXT BUFFER CHUNK
240
241 if nfound + nhit >= length:
242
243 length = (length + nhit) * 2
244 output_arr = np.resize(output_arr, length)
245 output_arr_other = np.resize(output_arr_other, length)
246 output = output_arr
247 output_other = output_arr_other
248
249 if k < nhit:
250 nhit = k
251
252 while i < nhit:
253
254 output[nfound] = indexes[loop_counter]
255 output_other[nfound] = im_buf[i].target_id
256
257 nfound += 1
258 i += 1
259
260 if nhit < 1024:
261 spent = 1
262
263 cn.reset_interval_iterator(it_alloc)
264 it = it_alloc
265
266 cn.free_interval_iterator(it_alloc)
267
268 return output_arr[:nfound], output_arr_other[:nfound]
269
270 @cython.boundscheck(False)
271 @cython.wraparound(False)
272 @cython.initializedcheck(False)
273 cpdef all_overlaps_self(self, const int64_t [::1] starts, const int64_t [::1] ends, const int64_t [::1] indexes):
274
275 cdef int i
276 cdef int nhit = 0
277 cdef int length = len(starts)
278 cdef int loop_counter = 0
279 cdef int nfound = 0
280 cdef int spent = 0
281
282 output_arr = np.zeros(length, dtype=np.int64)
283 cdef int64_t [::1] output
284
285 output = output_arr
286
287 cdef cn.IntervalIterator *it
288 cdef cn.IntervalIterator *it_alloc
289
290 cdef cn.IntervalMap im_buf[1024]
291 if not self.im: # if empty
292 return [], []
293
294 it_alloc = cn.interval_iterator_alloc()
295 it = it_alloc
296 for loop_counter in range(length):
297
298 # remember first pointer for dealloc
299
300 spent = 0
301 while not spent:
302 i = 0
303 cn.find_intervals(it, starts[loop_counter], ends[loop_counter], self.im, self.ntop,
304 self.subheader, self.nlists, im_buf, 1024,
305 &(nhit), &(it)) # GET NEXT BUFFER CHUNK
306
307 if nfound + nhit >= length:
308
309 length = (length + nhit) * 2
310 output_arr = np.resize(output_arr, length)
311 output = output_arr
312
313 for i in range(nhit):
314
315 output[nfound] = indexes[loop_counter]
316
317 nfound += 1
318
319 if nhit < 1024:
320 spent = 1
321
322 cn.reset_interval_iterator(it_alloc)
323 it = it_alloc
324
325 cn.free_interval_iterator(it_alloc)
326
327 return output_arr[:nfound]
328
329
330 @cython.boundscheck(False)
331 @cython.wraparound(False)
332 @cython.initializedcheck(False)
333 cpdef coverage(self, const int64_t [::1] starts, const int64_t [::1] ends, const int64_t [::1] indexes):
334
335 # assumes the ncls to not contain any overlapping intervals
336
337 cdef int i = 0
338 cdef int64_t start = 0
339 cdef int64_t end = 0
340 cdef int other_start = 0
341 cdef int other_end = 0
342 cdef int nhit = 0
343 cdef int length = len(starts)
344 cdef int loop_counter = 0
345 cdef int nfound = 0
346 cdef int spent = 0
347
348 output_arr_length = np.zeros(length, dtype=np.int64)
349 cdef int64_t [::1] output_length
350
351 output_length = output_arr_length
352
353 cdef cn.IntervalIterator *it
354 cdef cn.IntervalIterator *it_alloc
355
356 cdef cn.IntervalMap im_buf[1024]
357 if not self.im: # if empty
358 return [], []
359
360 it_alloc = cn.interval_iterator_alloc()
361 it = it_alloc
362 for loop_counter in range(length):
363
364 start = starts[loop_counter]
365 end = ends[loop_counter]
366 # remember first pointer for dealloc
367 spent = 0
368 while not spent:
369 i = 0
370 cn.find_intervals(it, starts[loop_counter], ends[loop_counter], self.im, self.ntop,
371 self.subheader, self.nlists, im_buf, 1024,
372 &(nhit), &(it)) # GET NEXT BUFFER CHUNK
373
374 while i < nhit:
375 output_length[loop_counter] += int_min(im_buf[i].end, end) - int_max(im_buf[i].start, start)
376 i += 1
377
378 if nhit < 1024:
379 spent = 1
380
381 cn.reset_interval_iterator(it_alloc)
382 it = it_alloc
383
384 cn.free_interval_iterator(it_alloc)
385
386 return output_arr_length
387
388 def __len__(self):
389 return self.n
390
391 def __str__(self):
392
393 contents = ["Number intervals:", self.n, "Number of intervals in main list:", self.ntop, "Number of intervals with subintervals:", self.nlists, "Percentage in top-level interval", self.ntop/float(self.n)]
394 return "NCLS64\n------\n" + "\n".join(str(c) for c in contents)
395
396 def __dealloc__(self):
397 'remember: dealloc cannot call other methods!'
398 if self.subheader:
399 cn.free(self.subheader)
400 if self.im:
401 cn.free(self.im)
402
403 def close(self):
404 if self.subheader:
405 cn.free(self.subheader)
406 if self.im:
407 cn.free(self.im)
408 self.subheader = NULL
409 self.im = NULL
410
411 return None
412
413 def find_overlap(self, int64_t start, int64_t end):
414 if not self.im: # RAISE EXCEPTION IF NO DATA
415 return []
416
417 return NCLSIterator(start, end, self)
418
419
420 cpdef has_overlap(self, int64_t start, int64_t end):
421 cdef int nhit = 0
422
423 cdef cn.IntervalIterator *it
424 cdef cn.IntervalMap im_buf[1024]
425 if not self.im: # if empty
426 return 0
427
428 it = cn.interval_iterator_alloc()
429
430 while it:
431 cn.find_intervals(it, start, end, self.im, self.ntop,
432 self.subheader, self.nlists, im_buf, 1024,
433 &(nhit), &(it)) # GET NEXT BUFFER CHUNK
434
435 if nhit > 0:
436 cn.free_interval_iterator(it)
437 return True
438
439 cn.free_interval_iterator(it)
440
441 return False
442
443
444
445 @cython.boundscheck(False)
446 @cython.wraparound(False)
447 @cython.initializedcheck(False)
448 cpdef set_difference_helper(self, const int64_t [::1] starts, const int64_t [::1] ends, const int64_t [::1] indexes,
449 const int64_t [::1] nhits):
450
451 cdef int i
452 cdef int nhit = 0
453 cdef int nfound = 0
454 cdef int64_t nstart = 0
455 cdef int64_t nend = 0
456 cdef int length = len(starts)
457 cdef int loop_counter = 0
458 cdef int overlap_type_nb = 0
459 cdef int na = -1
460 cdef int spent = 0
461
462
463 output_arr = np.zeros(length, dtype=np.int64)
464 output_arr_start = np.zeros(length, dtype=np.int64)
465 output_arr_end = np.zeros(length, dtype=np.int64)
466 cdef int64_t [::1] output
467 cdef int64_t [::1] output_start
468 cdef int64_t [::1] output_end
469
470 output = output_arr
471 output_start = output_arr_start
472 output_end = output_arr_end
473
474 cdef cn.IntervalIterator *it
475 cdef cn.IntervalIterator *it_alloc
476 cdef cn.IntervalMap im_buf[1024]
477 if not self.im: # if empty
478 return [], [], []
479
480 it_alloc = cn.interval_iterator_alloc()
481 it = it_alloc
482 for loop_counter in range(length):
483
484 nhit = nhits[loop_counter]
485 nstart = starts[loop_counter]
486 nend = ends[loop_counter]
487
488 while nhit > 0:
489 i = 0
490 cn.find_intervals(it, starts[loop_counter], ends[loop_counter], self.im, self.ntop,
491 self.subheader, self.nlists, im_buf, 1024,
492 &(na), &(it)) # GET NEXT BUFFER CHUNK
493
494 if nfound + nhit >= length:
495 length = (length + nhit) * 2
496 output_arr = np.resize(output_arr, length)
497 output_arr_start = np.resize(output_arr_start, length)
498 output = output_arr
499 output_start = output_arr_start
500 output_arr_end = np.resize(output_arr_end, length)
501 output_end = output_arr_end
502
503 # B covers whole of A; ignore
504 if nhit == 1 and starts[loop_counter] > im_buf[i].start and ends[loop_counter] < im_buf[i].end:
505 # print("ignore me!")
506 output_start[nfound] = -1
507 output_end[nfound] = -1
508 output[nfound] = indexes[loop_counter]
509 i = nhit
510 nfound += 1
511 break
512
513 max_i = 1024 if nhit > 1024 else nhit
514
515 while i < max_i:
516 # in case the start contributes nothing
517 if nstart < im_buf[i].start:
518 output[nfound] = indexes[loop_counter]
519 output_start[nfound] = nstart
520 output_end[nfound] = im_buf[i].start
521 nfound += 1
522 nstart = im_buf[i].end
523
524 i += 1
525
526 nhit = nhit - 1024
527
528 if nhit <= 0:
529 i = i - 1
530 if im_buf[i].start <= nstart and im_buf[i].end >= ends[loop_counter]:
531 # print("im_buf[i].start <= nstart and im_buf[i].end >= ends[loop_counter]")
532 #print("we are here " * 10)
533
534 output_start[nfound] = -1
535 output_end[nfound] = -1
536 output[nfound] = <long> indexes[loop_counter]
537 nfound += 1
538 else:
539 if im_buf[i].start > nstart:
540 output[nfound] = indexes[loop_counter]
541 output_start[nfound] = nstart
542 output_end[nfound] = im_buf[i].start
543 nfound += 1
544
545 if im_buf[i].end < ends[loop_counter]:
546 output[nfound] = indexes[loop_counter]
547 output_start[nfound] = im_buf[i].end
548 output_end[nfound] = ends[loop_counter]
549 nfound += 1
550
551 cn.reset_interval_iterator(it_alloc)
552 it = it_alloc
553
554 cn.free_interval_iterator(it_alloc)
555
556 return output_arr[:nfound], output_arr_start[:nfound], output_arr_end[:nfound]
557
558
559 # this one is actually slower!!!!
560 @cython.boundscheck(False)
561 @cython.wraparound(False)
562 @cython.initializedcheck(False)
563 cpdef first_overlap_both(self, const int64_t [::1] starts, const int64_t [::1] ends, const int64_t [::1] indexes):
564
565 cdef int ix = 0
566 cdef int length = len(starts)
567 cdef int loop_counter = 0
568 cdef int nfound = 0
569
570 output_arr = np.zeros(length, dtype=np.int64)
571 output_arr_other = np.zeros(length, dtype=np.int64)
572 cdef int64_t [::1] output
573 cdef int64_t [::1] output_other
574
575 output = output_arr
576 output_other = output_arr_other
577
578 cdef cn.IntervalIterator *it
579 cdef cn.IntervalIterator *it_alloc
580
581 cdef cn.IntervalMap im_buf[1024]
582 if not self.im: # if empty
583 return [], []
584
585
586 for loop_counter in range(length):
587
588 # remember first pointer for dealloc
589 ix = cn.find_overlap_start(starts[loop_counter], ends[loop_counter], self.im, self.ntop)
590
591 if ix != -1:
592 output[nfound] = indexes[loop_counter]
593 output_other[nfound] = self.im[ix].target_id
594
595 nfound += 1
596
597 return output_arr[:nfound], output_arr_other[:nfound]
598
599
600 @cython.boundscheck(False)
601 @cython.wraparound(False)
602 @cython.initializedcheck(False)
603 cpdef all_containments_both(self, const int64_t [::1] starts, const int64_t [::1] ends, const int64_t [::1] indexes):
604
605 cdef int i
606 cdef int nhit = 0
607 cdef int length = len(starts)
608 cdef int loop_counter = 0
609 cdef int nfound = 0
610 cdef int64_t start, end
611 cdef int spent = 0
612
613 output_arr = np.zeros(length, dtype=np.int64)
614 output_arr_other = np.zeros(length, dtype=np.int64)
615 cdef int64_t [::1] output
616 cdef int64_t [::1] output_other
617
618 output = output_arr
619 output_other = output_arr_other
620
621 cdef cn.IntervalIterator *it
622 cdef cn.IntervalIterator *it_alloc
623
624
625 cdef cn.IntervalMap im_buf[1024]
626 if not self.im: # if empty
627 return [], []
628
629
630 it_alloc = cn.interval_iterator_alloc()
631 it = it_alloc
632
633 for loop_counter in range(length):
634
635 start = starts[loop_counter]
636 end = ends[loop_counter]
637 spent = 0
638 while not spent:
639 i = 0
640 cn.find_intervals(it, start, end, self.im, self.ntop,
641 self.subheader, self.nlists, im_buf, 1024,
642 &(nhit), &(it)) # GET NEXT BUFFER CHUNK
643
644 while i < nhit:
645
646 if im_buf[i].start <= start and im_buf[i].end >= end:
647
648 if nfound >= length:
649
650 length = nfound * 2
651 output_arr = np.resize(output_arr, length)
652 output_arr_other = np.resize(output_arr_other, length)
653 output = output_arr
654 output_other = output_arr_other
655
656 output[nfound] = indexes[loop_counter]
657 output_other[nfound] = im_buf[i].target_id
658
659 nfound += 1
660 i += 1
661
662 if nhit < 1024:
663 spent = 1
664
665 cn.reset_interval_iterator(it_alloc)
666 it = it_alloc
667
668 cn.free_interval_iterator(it_alloc)
669
670 return output_arr[:nfound], output_arr_other[:nfound]
671
672
673
674
675 @cython.boundscheck(False)
676 @cython.wraparound(False)
677 @cython.initializedcheck(False)
678 cpdef has_overlaps(self, const int64_t [::1] starts, const int64_t [::1] ends, const int64_t [::1] indexes):
679
680 cdef int i = 0
681 cdef int ix = 0
682 cdef int length = len(starts)
683 cdef int nfound = 0
684
685 if not self.im: # if empty
686 return []
687
688 output_arr = np.zeros(length, dtype=np.int64)
689 cdef int64_t [::1] output
690 output = output_arr
691
692 for i in range(length):
693
694 ix = cn.find_overlap_start(starts[i], ends[i], self.im, self.ntop)
695
696 if ix != -1:
697 output[nfound] = indexes[i]
698 nfound += 1
699
700 i += 1
701
702 return output_arr[:nfound]
703
704
705
706 cdef class NCLSIterator:
707
708 cdef cn.IntervalIterator *it
709 cdef cn.IntervalIterator *it_alloc
710 cdef cn.IntervalMap im_buf[1024]
711 cdef int nhit, ihit
712 cdef int64_t start, end
713 cdef NCLS64 db
714
715 def __cinit__(self, int64_t start, int64_t end, NCLS64 db not None):
716 self.it = cn.interval_iterator_alloc()
717 self.it_alloc = self.it
718 self.start = start
719 self.end = end
720 self.db = db
721 self.nhit = 0
722 self.ihit = 0
723
724
725 def __iter__(self):
726 return self
727
728
729 cdef int cnext(self): # c VERSION OF ITERATOR next METHOD RETURNS INDEX
730 cdef int64_t i
731 if self.ihit >= self.nhit: # TRY TO GET ONE MORE BUFFER CHUNK OF HITS
732 if self.it == NULL: # ITERATOR IS EXHAUSTED
733 return -1
734 cn.find_intervals(self.it, self.start, self.end, self.db.im, self.db.ntop,
735 self.db.subheader, self.db.nlists, self.im_buf, 1024,
736 &(self.nhit), &(self.it)) # GET NEXT BUFFER CHUNK
737 self.ihit = 0 # START ITERATING FROM START OF BUFFER
738
739 if self.ihit < self.nhit: # RETURN NEXT ITEM FROM BUFFER
740 i = self.ihit
741 self.ihit = self.ihit + 1 # ADVANCE THE BUFFER COUNTER
742 return i
743 else: # BUFFER WAS EMPTY, NO HITS TO ITERATE OVER...
744 return -1
745
746
747 # PYTHON VERSION OF next RETURNS HIT AS A TUPLE
748 def __next__(self): # PYREX USES THIS NON-STANDARD NAME INSTEAD OF next()!!!
749 cdef int i
750 i = self.cnext()
751 if i >= 0:
752 return (self.im_buf[i].start, self.im_buf[i].end, self.im_buf[i].target_id)
753 else:
754 raise StopIteration
755
756 def __dealloc__(self):
757 'remember: dealloc cannot call other methods!'
758 cn.free_interval_iterator(self.it_alloc)
759
760
761 def find_overlap(self, int64_t start, int64_t end):
762 if not self.im:
763 return []
764
765 return NCLSIterator(start, end, self)