/
_pyrodigal.pyx
4889 lines (4283 loc) · 184 KB
/
_pyrodigal.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
# cython: language_level=3, linetrace=True
"""Bindings to Prodigal, an ORF finder for genomes and metagenomes.
Example:
Pyrodigal can work on any DNA sequence stored in either a text or a
byte array. To load a sequence from one of the common sequence formats,
you can use an external dedicated library such as
`Biopython <https://github.com/biopython/biopython>`_::
>>> import gzip
>>> import Bio.SeqIO
>>> seq_path = "pyrodigal/tests/data/KK037166.fna.gz"
>>> with gzip.open(seq_path, "rt") as f:
... record = Bio.SeqIO.read(f, "fasta")
Then use Pyrodigal to find the genes in *metagenomic* mode (without
training first), for instance to build a map of codon frequencies
for each gene::
>>> from collections import Counter
>>> import pyrodigal
>>> p = pyrodigal.OrfFinder(meta=True)
>>> for gene in p.find_genes(record.seq.encode()):
... gene_seq = gene.sequence()
... codon_counter = Counter()
... for i in range(len(gene_seq), 3):
... codon_counter[gene_seq[i:i+3]] += 1
... codon_frequencies = {
... codon:count/(len(gene_seq)//3)
... for codon, count in codon_counter.items()
... }
Caution:
In Pyrodigal, sequences are assumed to contain only the usual
nucleotides (A/T/G/C) as lowercase or uppercase letters; any other
symbol will be treated as an unknown nucleotide. Be careful to remove
the gap characters if loading sequences from a multiple alignment file.
Note:
To cite Pyrodigal, please cite both the original method and the short
paper for the Python library itself, for instance as:
Pyrodigal (Larralde, 2022), a Python library binding to Prodigal
(Hyatt *et al.*, 2010).
References:
- Larralde, M.
*Pyrodigal: Python bindings and interface to Prodigal, an efficient
method for gene prediction in prokaryotes*. Journal of Open Source
Software 7, no. 72 (25 April 2022). :doi:`10.21105/joss.04296`.
- Hyatt D, Chen GL, Locascio PF, Land ML, Larimer FW, Hauser LJ.
*Prodigal: prokaryotic gene recognition and translation initiation
site identification*. BMC Bioinformatics 11, no. 1 (December 2010).
:doi:`10.1186/1471-2105-11-119`. :pmid:`20211023`. :pmc:`2848648`.
"""
# ----------------------------------------------------------------------------
from cpython cimport Py_buffer
from cpython.buffer cimport PyBUF_FORMAT, PyBUF_READ, PyBUF_WRITE
from cpython.bytes cimport PyBytes_FromStringAndSize, PyBytes_AsString
from cpython.exc cimport PyErr_CheckSignals
from cpython.list cimport PyList_New, PyList_SET_ITEM
from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free
from cpython.memoryview cimport PyMemoryView_FromMemory
from cpython.ref cimport Py_INCREF
from cpython.tuple cimport PyTuple_New, PyTuple_SET_ITEM
from libc.math cimport sqrt, log, pow, fmax, fmin
from libc.stdint cimport int8_t, uint8_t, uintptr_t
from libc.stdio cimport printf
from libc.stdlib cimport abs, malloc, calloc, free, qsort
from libc.string cimport memcpy, memchr, memset, strstr
from pyrodigal.prodigal cimport bitmap, dprog, gene, node, sequence
from pyrodigal.prodigal.metagenomic cimport NUM_META, _metagenomic_bin, initialize_metagenomic_bins
from pyrodigal.prodigal.node cimport _motif, _node, MIN_EDGE_GENE, MIN_GENE, MAX_SAM_OVLP, cross_mask, compare_nodes, stopcmp_nodes
from pyrodigal.prodigal.sequence cimport _mask, node_type, rcom_seq
from pyrodigal.prodigal.training cimport _training
from pyrodigal._unicode cimport *
from pyrodigal._sequence cimport (
nucleotide,
_is_a,
_is_g,
_is_gc,
_is_stop,
_is_start,
_is_atg,
_is_ttg,
_is_gtg,
_mer_ndx,
_letters,
_complement
)
from pyrodigal._connection cimport (
_intergenic_mod_same,
_intergenic_mod_diff,
_intergenic_mod,
_score_connection_forward_start,
_score_connection_forward_stop,
_score_connection_backward_start,
_score_connection_backward_stop,
_score_connections,
connection_function,
CONNECTION_FUNCTIONS,
)
from pyrodigal.impl.generic cimport skippable_generic
IF MMX_BUILD_SUPPORT:
from pyrodigal.impl.mmx cimport skippable_mmx
IF SSE2_BUILD_SUPPORT:
from pyrodigal.impl.sse cimport skippable_sse
IF AVX2_BUILD_SUPPORT:
from pyrodigal.impl.avx cimport skippable_avx
IF NEON_BUILD_SUPPORT:
from pyrodigal.impl.neon cimport skippable_neon
IF SYS_IMPLEMENTATION_NAME == "pypy":
cdef int MVIEW_READ = PyBUF_READ | PyBUF_WRITE
cdef int MVIEW_WRITE = PyBUF_READ | PyBUF_WRITE
ELSE:
cdef int MVIEW_READ = PyBUF_READ
cdef int MVIEW_WRITE = PyBUF_WRITE
# ----------------------------------------------------------------------------
import itertools
import textwrap
import threading
import warnings
include "_version.py"
# --- Module-level constants -------------------------------------------------
cdef int IDEAL_SINGLE_GENOME = 100000
cdef int MIN_SINGLE_GENOME = 20000
cdef int WINDOW = 120
cdef size_t MIN_MASKS_ALLOC = 8
cdef size_t MIN_GENES_ALLOC = 8
cdef size_t MIN_NODES_ALLOC = 8 * MIN_GENES_ALLOC
cdef set _TRANSLATION_TABLES = set(range(1, 7)) | set(range(9, 17)) | set(range(21, 26))
TRANSLATION_TABLES = frozenset(_TRANSLATION_TABLES)
cdef inline size_t new_capacity(size_t capacity) nogil:
return capacity + (capacity >> 3) + 6
# --- Sequence mask ----------------------------------------------------------
cdef class Mask:
"""The coordinates of a masked region.
"""
# --- Magic methods ------------------------------------------------------
def __init__(self, int begin, int end):
self.owner = None
self.mask = &self._data
self.mask.begin = begin
self.mask.end = end
def __repr__(self):
ty = type(self)
return "<{}.{} begin={!r} end={!r}>".format(
ty.__module__,
ty.__name__,
self.mask.begin,
self.mask.end,
)
def __eq__(self, other):
if isinstance(other, Mask):
return self.mask.begin == other.begin and self.mask.end == other.end
return False
# --- Properties ---------------------------------------------------------
@property
def begin(self):
return self.mask.begin
@property
def end(self):
return self.mask.end
# --- C interface -------------------------------------------------------
@staticmethod
cdef bint _intersects(_mask* mask, int begin, int end) nogil:
if mask == NULL:
return False
return mask.begin <= end and begin <= mask.end
# --- Python interface ---------------------------------------------------
cpdef bint intersects(self, int begin, int end):
return Mask._intersects(self.mask, begin, end)
cdef class Masks:
"""A list of masked regions within a `~pyrodigal.Sequence`.
"""
# --- Magic methods ------------------------------------------------------
def __cinit__(self):
self.masks = NULL
self.capacity = 0
self.length = 0
def __init__(self):
self._clear()
def __dealloc__(self):
PyMem_Free(self.masks)
def __copy__(self):
return self.copy()
def __len__(self):
return self.length
def __getitem__(self, ssize_t index):
cdef Mask mask
if index < 0:
index += <ssize_t> self.length
if index >= <ssize_t> self.length or index < 0:
raise IndexError("list index out of range")
mask = Mask.__new__(Mask)
mask.owner = self
mask.mask = &self.masks[index]
return mask
cpdef size_t __sizeof__(self):
return self.capacity * sizeof(_mask) + sizeof(self)
cpdef list __getstate__(self):
"""__getstate__(self)\n--
"""
cdef size_t i
return [
(self.masks[i].begin, self.masks[i].end)
for i in range(self.length)
]
cpdef object __setstate__(self, list state):
"""__setstate__(self, state)\n--
"""
cdef size_t i
cdef tuple mask
# realloc to the exact number of masks
self.length = self.capacity = len(state)
if self.capacity > 0:
self._allocate(self.capacity)
else:
PyMem_Free(self.masks)
self.masks = NULL
# copy data from the state list
for i, mask in enumerate(state):
self.masks[i].begin, self.masks[i].end = mask
# --- C interface -------------------------------------------------------
cdef int _allocate(self, size_t capacity) except 1:
# record new capacity
cdef size_t old_capacity = self.capacity
self.capacity = capacity
# allocate node array
self.masks = <_mask*> PyMem_Realloc(self.masks, self.capacity * sizeof(_mask))
if self.masks == NULL:
raise MemoryError("Failed to reallocate mask array")
# clean newly-allocated memory
if self.capacity > old_capacity:
memset(&self.masks[old_capacity], 0, (self.capacity - old_capacity) * sizeof(_mask))
return 0
cdef inline _mask* _add_mask(
self,
const int begin,
const int end,
) nogil except NULL:
"""Add a single node to the vector, and return a pointer to that node.
"""
cdef size_t old_capacity = self.capacity
cdef _mask* mask
if self.length >= self.capacity:
with gil:
self._allocate(MIN_MASKS_ALLOC if self.capacity == 0 else new_capacity(self.capacity))
self.length += 1
mask = &self.masks[self.length - 1]
mask.begin = begin
mask.end = end
return mask
cdef int _clear(self) nogil:
"""Remove all masks from the vector.
"""
cdef size_t old_length
old_length, self.length = self.length, 0
memset(self.masks, 0, old_length * sizeof(_mask))
# --- Python interface ---------------------------------------------------
cpdef void clear(self):
"""Remove all masks from the vector.
"""
with nogil:
self._clear()
cpdef Masks copy(self):
cdef Masks new = Masks.__new__(Masks)
new.capacity = self.capacity
new.length = self.length
new.masks = <_mask*> PyMem_Malloc(new.capacity * sizeof(_mask))
if new.masks == NULL:
raise MemoryError("Failed to allocate masks array")
memcpy(new.masks, self.masks, new.capacity * sizeof(_mask))
return new
# --- Input sequence ---------------------------------------------------------
cdef class Sequence:
"""A digitized input sequence.
Attributes:
gc (`float`): The GC content of the sequence, as a fraction.
masks (`~pyrodigal.Masks`): A list of masked regions within the
sequence.
"""
# --- Class methods ------------------------------------------------------
@staticmethod
cdef int _build(
const int kind,
const void* data,
const size_t length,
double* gc,
uint8_t* digits,
Masks masks,
) nogil except 1:
cdef size_t i
cdef Py_UCS4 letter
cdef int gc_count = 0
cdef int mask_begin = -1
for i in range(length):
letter = PyUnicode_READ(kind, data, i)
if letter == u'A' or letter == u'a':
digits[i] = nucleotide.A
elif letter == u'T' or letter == u't':
digits[i] = nucleotide.T
elif letter == u'G' or letter == u'g':
digits[i] = nucleotide.G
gc_count += 1
elif letter == u'C' or letter == u'c':
digits[i] = nucleotide.C
gc_count += 1
else:
digits[i] = nucleotide.N
if length > 0:
gc[0] = (<double> gc_count) / (<double> length)
if masks is not None:
for i in range(length):
if digits[i] == nucleotide.N:
if mask_begin == -1:
mask_begin = i
else:
if mask_begin != -1:
masks._add_mask(mask_begin, i-1)
mask_begin = -1
return 0
@classmethod
def from_bytes(cls, const unsigned char[:] sequence, bint mask = False):
"""from_bytes(cls, sequence)\n--
Create a new `Sequence` object from an ASCII-encoded sequence.
Arguments:
sequence (`bytes`): The ASCII-encoded sequence to use. Any
object implementing the *buffer protocol* is supported.
mask (`bool`): Enable region-masking for spans of unknown
characters, preventing genes from being built across them.
"""
cdef Sequence seq
cdef Masks masks
seq = Sequence.__new__(Sequence)
seq._allocate(sequence.shape[0])
seq.masks = Masks.__new__(Masks)
masks = seq.masks if mask else None
with nogil:
Sequence._build(
PyUnicode_1BYTE_KIND,
&sequence[0],
seq.slen,
&seq.gc,
seq.digits,
masks,
)
return seq
@classmethod
def from_string(cls, str sequence, bint mask = False):
"""from_string(cls, sequence)\n--
Create a new `Sequence` object from a Unicode sequence.
Arguments:
sequence (`str`): The Unicode sequence to use.
mask (`bool`): Enable region-masking for spans of unknown
characters, preventing genes from being built across them.
"""
cdef Sequence seq
cdef int kind
cdef void* data
cdef Masks masks
# make sure the unicode string is in canonical form,
# --> won't be needed anymore in Python 3.12
IF SYS_VERSION_INFO_MAJOR <= 3 and SYS_VERSION_INFO_MINOR < 12:
PyUnicode_READY(sequence)
seq = Sequence.__new__(Sequence)
seq._allocate(PyUnicode_GET_LENGTH(sequence))
seq.masks = Masks.__new__(Masks)
masks = seq.masks if mask else None
kind = PyUnicode_KIND(sequence)
data = PyUnicode_DATA(sequence)
with nogil:
Sequence._build(
kind,
data,
seq.slen,
&seq.gc,
seq.digits,
masks,
)
return seq
# --- Magic methods ------------------------------------------------------
def __cinit__(self):
self.slen = 0
self.gc = 0.0
self.digits = NULL
self.masks = None
def __dealloc__(self):
PyMem_Free(self.digits)
def __len__(self):
return self.slen
cpdef size_t __sizeof__(self):
return self.slen * sizeof(uint8_t) + sizeof(self)
def __str__(self):
cdef int i
cdef Py_UCS4 nuc
IF SYS_VERSION_INFO_MAJOR <= 3 and SYS_VERSION_INFO_MINOR < 7 and SYS_IMPLEMENTATION_NAME == "pypy":
cdef bytes dna
cdef void* data
# create an empty byte buffer that we can write to
dna = PyBytes_FromStringAndSize(NULL, self.slen)
data = <void*> PyBytes_AsString(dna)
ELSE:
cdef unicode dna
cdef int kind
cdef void* data
# create an empty string that we can write to
dna = PyUnicode_New(self.slen, 0x7F)
kind = PyUnicode_KIND(dna)
data = PyUnicode_DATA(dna)
with nogil:
for i in range(self.slen):
nuc = _letters[self.digits[i]]
IF SYS_VERSION_INFO_MAJOR <= 3 and SYS_VERSION_INFO_MINOR < 7 and SYS_IMPLEMENTATION_NAME == "pypy":
(<char*> data)[i] = nuc
ELSE:
PyUnicode_WRITE(kind, data, i, nuc)
IF SYS_VERSION_INFO_MAJOR <= 3 and SYS_VERSION_INFO_MINOR < 7 and SYS_IMPLEMENTATION_NAME == "pypy":
return dna.decode("ascii")
ELSE:
return dna
cpdef dict __getstate__(self):
"""__getstate__(self)\n--
"""
assert self.digits != NULL
# copy sequence digits
cdef bytearray digits = bytearray(self.slen)
cdef uint8_t[::1] view = digits
memcpy(&view[0], self.digits, self.slen * sizeof(uint8_t))
# build the state dict
return {
"slen": self.slen,
"gc": self.gc,
"masks": self.masks,
"digits": digits
}
cpdef object __setstate__(self, dict state):
"""__setstate__(self, state)\n--
"""
# get a view on the digits
cdef uint8_t[::1] view = state["digits"]
# copy attributes
self.masks = state["masks"]
self.gc = state["gc"]
# allocate sequence storage and copy bytes
self._allocate(state["slen"])
memcpy(self.digits, &view[0], self.slen * sizeof(uint8_t))
def __getbuffer__(self, Py_buffer* buffer, int flags):
assert self.digits != NULL
if flags & PyBUF_FORMAT:
buffer.format = b"B"
else:
buffer.format = NULL
buffer.buf = self.digits
buffer.internal = NULL
buffer.itemsize = sizeof(uint8_t)
buffer.len = self.slen * sizeof(uint8_t)
buffer.ndim = 1
buffer.obj = self
buffer.readonly = 0
buffer.shape = &self.slen
buffer.suboffsets = NULL
buffer.strides = NULL
# --- C interface -------------------------------------------------------
cdef int _allocate(self, int slen) except 1:
self.slen = slen
self.digits = <uint8_t*> PyMem_Malloc(slen * sizeof(uint8_t))
if self.digits == NULL:
raise MemoryError()
with nogil:
memset(self.digits, 0, slen * sizeof(uint8_t))
return 0
cdef char _amino(
self,
int i,
int tt,
int strand = 1,
bint is_init = False,
char unknown_residue = b"X"
) nogil:
cdef uint8_t x0
cdef uint8_t x1
cdef uint8_t x2
if _is_stop(self.digits, self.slen, i, tt, strand):
return b"*"
if _is_start(self.digits, self.slen, i, tt, strand) and is_init:
return b"M"
if strand == 1:
x0 = self.digits[i]
x1 = self.digits[i+1]
x2 = self.digits[i+2]
else:
x0 = _complement[self.digits[self.slen - 1 - i]]
x1 = _complement[self.digits[self.slen - 2 - i]]
x2 = _complement[self.digits[self.slen - 3 - i]]
if x0 == nucleotide.T and x1 == nucleotide.T and (x2 == nucleotide.T or x2 == nucleotide.C):
return b"F"
if x0 == nucleotide.T and x1 == nucleotide.T and (x2 == nucleotide.A or x2 == nucleotide.G):
return b"L"
if x0 == nucleotide.T and x1 == nucleotide.C and x2 != nucleotide.N:
return b"S"
if x0 == nucleotide.T and x1 == nucleotide.A and x2 == nucleotide.T:
return b"Y"
if x0 == nucleotide.T and x1 == nucleotide.A and x2 == nucleotide.C:
return b"Y"
if x0 == nucleotide.T and x1 == nucleotide.A and x2 == nucleotide.A:
if tt == 6:
return b"Q"
elif tt == 14:
return b"Y"
if x0 == nucleotide.T and x1 == nucleotide.A and x2 == nucleotide.G:
if tt == 6 or tt == 15:
return b"Q"
elif tt == 22:
return b"L"
if x0 == nucleotide.T and x1 == nucleotide.G and (x2 == nucleotide.T or x2 == nucleotide.C):
return b"C"
if x0 == nucleotide.T and x1 == nucleotide.G and x2 == nucleotide.A:
return b"G" if tt == 25 else b"W"
if x0 == nucleotide.T and x1 == nucleotide.G and x2 == nucleotide.G:
return b"W"
if x0 == nucleotide.C and x1 == nucleotide.T and (x2 == nucleotide.T or x2 == nucleotide.C or x2 == nucleotide.A):
return b"T" if tt == 3 else b"L"
if x0 == nucleotide.C and x1 == nucleotide.T and x2 == nucleotide.G:
return b"T" if tt == 3 else b"S" if tt == 12 else b"L"
if x0 == nucleotide.C and x1 == nucleotide.C and x2 != nucleotide.N:
return b"P"
if x0 == nucleotide.C and x1 == nucleotide.A and (x2 == nucleotide.T or x2 == nucleotide.C):
return b"H"
if x0 == nucleotide.C and x1 == nucleotide.A and (x2 == nucleotide.A or x2 == nucleotide.G):
return b"Q"
if x0 == nucleotide.C and x1 == nucleotide.G and x2 != nucleotide.N:
return b"R"
if x0 == nucleotide.A and x1 == nucleotide.T and (x2 == nucleotide.T or x2 == nucleotide.C):
return b"I"
if x0 == nucleotide.A and x1 == nucleotide.T and x2 == nucleotide.A:
return b"M" if tt == 2 or tt == 3 or tt == 5 or tt == 13 or tt == 22 else b"I"
if x0 == nucleotide.A and x1 == nucleotide.T and x2 == nucleotide.G:
return b"M"
if x0 == nucleotide.A and x1 == nucleotide.C and x2 != nucleotide.N:
return b"T"
if x0 == nucleotide.A and x1 == nucleotide.A and (x2 == nucleotide.T or x2 == nucleotide.C):
return b"N"
if x0 == nucleotide.A and x1 == nucleotide.A and x2 == nucleotide.A:
return b"N" if tt == 9 or tt == 14 or tt == 21 else b"K"
if x0 == nucleotide.A and x1 == nucleotide.A and x2 == nucleotide.G:
return b"K"
if x0 == nucleotide.A and x1 == nucleotide.G and (x2 == nucleotide.T or x2 == nucleotide.C):
return b"S"
if x0 == nucleotide.A and x1 == nucleotide.G and (x2 == nucleotide.A or x2 == nucleotide.G):
return b"G" if tt == 13 else b"S" if tt == 5 or tt == 9 or tt == 14 or tt == 21 else b"R"
if x0 == nucleotide.G and x1 == nucleotide.T and x2 != nucleotide.N:
return b"V"
if x0 == nucleotide.G and x1 == nucleotide.C and x2 != nucleotide.N:
return b"A"
if x0 == nucleotide.G and x1 == nucleotide.A and (x2 == nucleotide.T or x2 == nucleotide.C):
return b"D"
if x0 == nucleotide.G and x1 == nucleotide.A and (x2 == nucleotide.A or x2 == nucleotide.G):
return b"E"
if x0 == nucleotide.G and x1 == nucleotide.G and x2 != nucleotide.N:
return b"G"
return unknown_residue
cdef int _shine_dalgarno_exact(
self,
const int pos,
const int start,
const _training* tinf,
const int strand
) nogil except -1:
cdef int i
cdef int j
cdef int k
cdef int mism
cdef int rdis
cdef int limit
cdef int max_val
cdef int cmp_val
cdef int cur_val = 0
cdef int match[6]
cdef int cur_ctr
cdef int dis_flag
# reset the match array
match[0] = match[1] = match[2] = match[3] = match[4] = match[5] = -10
# compute distance to SD site
limit = min(6, start - 4 - pos)
# check boundaries
if pos < 0:
raise IndexError(f"Invalid read at index {pos} of sequence of length {self.slen} using limit {limit}")
elif pos + limit >= self.slen:
raise IndexError(f"Invalid read at index {pos+limit} of sequence of length {self.slen} using limit {limit}")
# Compare the 6-base region to AGGAGG
for i in range(limit):
if i%3 == 0:
if _is_a(self.digits, self.slen, pos+i, strand):
match[i] = 2
else:
if _is_g(self.digits, self.slen, pos+i, strand):
match[i] = 3
# Find the maximally scoring motif
max_val = 0
for i in range(limit, 2, -1):
for j in range(limit+1-i):
# count number of matching positions, skip if less than
# GAG matching (or if a mismatch occurs)
cur_ctr = -2
for k in range(j, j+i):
cur_ctr += match[k]
if cur_ctr < 6:
continue
# compute distance to the start codon
rdis = start - (pos + j + i)
if rdis < 5: # 3-4bp
dis_flag = 2 if i < 5 else 1
elif rdis < 11: # 5-10bp
dis_flag = 0
elif rdis < 13: # 11-12bp
dis_flag = 1 if i < 5 else 2
elif rdis < 16: # 13-15bp
dis_flag = 3
else:
continue
# match exact RBS Motifs
if cur_ctr == 6: # GGA
if dis_flag == 0: cur_val = 13
elif dis_flag == 1: cur_val = 6
elif dis_flag == 2: cur_val = 1
elif dis_flag == 3: cur_val = 2
elif cur_ctr == 8: # AGGA
if dis_flag == 0: cur_val = 15
elif dis_flag == 1: cur_val = 12
elif dis_flag == 2: cur_val = 11
elif dis_flag == 3: cur_val = 3
elif cur_ctr == 9: # GGAG
if dis_flag == 0: cur_val = 16
elif dis_flag == 1: cur_val = 12
elif dis_flag == 2: cur_val = 11
elif dis_flag == 3: cur_val = 3
elif cur_ctr == 11: # AGGAG
if dis_flag == 0: cur_val = 22
elif dis_flag == 1: cur_val = 21
elif dis_flag == 2: cur_val = 20
elif dis_flag == 3: cur_val = 10
elif cur_ctr == 12: # GGAGG
if dis_flag == 0: cur_val = 24
elif dis_flag == 1: cur_val = 23
elif dis_flag == 2: cur_val = 20
elif dis_flag == 3: cur_val = 10
elif cur_ctr == 14: # AGGAGG
if dis_flag == 0: cur_val = 27
elif dis_flag == 1: cur_val = 26
elif dis_flag == 2: cur_val = 25
elif dis_flag == 3: cur_val = 10
else:
cur_val = 0
# record the motif only if this is the maximal scoring motif so far
if tinf.rbs_wt[cur_val] < tinf.rbs_wt[max_val]:
continue
if tinf.rbs_wt[cur_val] == tinf.rbs_wt[max_val] and cur_val < max_val:
continue
max_val = cur_val
return max_val
cdef int _shine_dalgarno_mm(
self,
const int pos,
const int start,
const _training* tinf,
const int strand
) nogil except -1:
cdef int i
cdef int j
cdef int k
cdef int mism
cdef int rdis
cdef int limit
cdef int max_val
cdef int cmp_val
cdef int cur_val = 0
cdef int match[6]
cdef int cur_ctr
cdef int dis_flag
# reset the match array
match[0] = match[1] = match[2] = match[3] = match[4] = match[5] = -10
# compute distance to SD site
limit = min(6, start - 4 - pos)
# check boundaries
if pos < 0:
raise IndexError(f"Invalid read at index {pos} of sequence of length {self.slen} using limit {limit}")
elif pos + limit >= self.slen:
raise IndexError(f"Invalid read at index {pos+limit} of sequence of length {self.slen} using limit {limit}")
# Compare the 6-base region to AGGAGG
for i in range(limit):
if i%3 == 0:
match[i] = 2 if _is_a(self.digits, self.slen, pos+i, strand) else -3
else:
match[i] = 3 if _is_g(self.digits, self.slen, pos+i, strand) else -2
# Find the maximally scoring motif
max_val = 0
for i in range(limit, 4, -1):
for j in range(limit+1-i):
# count number of matching positions, skip if less than
# GAG matching (or if not exactly one mismatch occurs)
cur_ctr = -2
mism = 0;
for k in range(j, j+i):
cur_ctr += match[k]
if match[k] < 0.0:
mism += 1
if k <= j+1 or k >= j+i-2:
cur_ctr -= 10
if mism != 1 or cur_ctr < 6:
continue
# compute distance to the start codon
rdis = start - (pos + j + i)
if rdis < 5:
dis_flag = 1
elif rdis < 11:
dis_flag = 0
elif rdis < 13:
dis_flag = 2
elif rdis < 16:
dis_flag = 3
else:
continue
# match single-mismatch RBS Motifs
if cur_ctr == 6: # AGxAG
if dis_flag == 0: cur_val = 9
elif dis_flag == 1: cur_val = 5
elif dis_flag == 2: cur_val = 4
elif dis_flag == 3: cur_val = 2
elif cur_ctr == 7: # GGxGG
if dis_flag == 0: cur_val = 14
elif dis_flag == 1: cur_val = 8
elif dis_flag == 2: cur_val = 7
elif dis_flag == 3: cur_val = 2
elif cur_ctr == 9: # AGGxGG
if dis_flag == 0: cur_val = 19
elif dis_flag == 1: cur_val = 18
elif dis_flag == 2: cur_val = 17
elif dis_flag == 3: cur_val = 3
# record the motif only if this is the maximal scoring motif so far
if tinf.rbs_wt[cur_val] < tinf.rbs_wt[max_val]:
continue
if tinf.rbs_wt[cur_val] == tinf.rbs_wt[max_val] and cur_val < max_val:
continue
max_val = cur_val
return max_val
# --- Python interface ---------------------------------------------------
cpdef int shine_dalgarno(
self,
int pos,
int start,
TrainingInfo training_info,
int strand=1,
bint exact=True
) except -1:
"""shine_dalgarno(self, pos, start, training_info, strand=1, exact=True)\n--
Find the highest scoring Shine-Dalgarno motif upstream of ``start``.
Arguments:
pos (`int`): The position where to look for the Shine-Dalgarno
motif. Must be upstream of ``start`` (before or after,
depending on the strand).
start (`int`): The position of the start codon being considered.
training_info (`~pyrodigal.TrainingInfo`): The training info
containing the weights for the different ribosome weights.
Keyword Arguments:
strand (`int`): The strand to scan.
exact (`bool`): `True` to score Shine-Dalgarno motifs matching
exactly *AGGAGG*, `False` to allow one base mismatch.
Returns:
`int`: The index of the highest scoring Shine-Dalgarno motif.
Raises:
`ValueError`: On invalid `strand`, `pos` or `start` values.
"""
if strand != 1 and strand != -1:
raise ValueError(f"Invalid strand: {strand!r} (must be +1 or -1)")
if pos < 0:
raise ValueError(f"`pos` must be positive")
if start < 0:
raise ValueError(f"`start` must be positive")
if strand == 1 and pos > start - 5:
raise ValueError(f"`pos` is too close to `start` (must be at most `start` - 5)")
elif strand == -1 and pos < start + 6:
raise ValueError(f"`pos` is too close to `start` (must be at most `start` + 6)")
cdef int phase
with nogil:
if exact:
phase = self._shine_dalgarno_exact(pos, start, training_info.tinf, strand)
else:
phase = self._shine_dalgarno_mm(pos, start, training_info.tinf, strand)
return phase
# --- Connection Scorer ------------------------------------------------------
_TARGET_CPU = TARGET_CPU
_AVX2_RUNTIME_SUPPORT = False
_NEON_RUNTIME_SUPPORT = False
_SSE2_RUNTIME_SUPPORT = False
_MMX_RUNTIME_SUPPORT = False
_AVX2_BUILD_SUPPORT = False
_NEON_BUILD_SUPPORT = False
_SSE2_BUILD_SUPPORT = False
_MMX_BUILD_SUPPORT = False
IF TARGET_CPU == "x86" and TARGET_SYSTEM in ("freebsd", "linux_or_android", "macos", "windows"):
from pyrodigal.cpu_features.x86 cimport GetX86Info, X86Info
cdef X86Info cpu_info = GetX86Info()
_MMX_BUILD_SUPPORT = MMX_BUILD_SUPPORT
_SSE2_BUILD_SUPPORT = SSE2_BUILD_SUPPORT
_AVX2_BUILD_SUPPORT = AVX2_BUILD_SUPPORT
_MMX_RUNTIME_SUPPORT = cpu_info.features.mmx != 0
_SSE2_RUNTIME_SUPPORT = cpu_info.features.sse2 != 0
_AVX2_RUNTIME_SUPPORT = cpu_info.features.avx2 != 0
ELIF TARGET_CPU == "arm" and TARGET_SYSTEM == "linux_or_android":
from pyrodigal.cpu_features.arm cimport GetArmInfo, ArmInfo
cdef ArmInfo cpu_info = GetArmInfo()
_NEON_BUILD_SUPPORT = NEON_BUILD_SUPPORT
_NEON_RUNTIME_SUPPORT = cpu_info.features.neon != 0
ELIF TARGET_CPU == "aarch64":
_NEON_BUILD_SUPPORT = NEON_BUILD_SUPPORT
_NEON_RUNTIME_SUPPORT = NEON_BUILD_SUPPORT
cdef enum simd_backend:
NONE = 0
MMX = 1
SSE2 = 2
AVX2 = 3
NEON = 4
GENERIC = 5
cdef class ConnectionScorer:
"""A dedicated class for the fast scoring of nodes.
"""
# --- Magic methods ------------------------------------------------------
def __cinit__(self):
self.capacity = 0
self.skip_connection = self.skip_connection_raw = NULL
self.node_types = self.node_types_raw = NULL
self.node_strands = self.node_strands_raw = NULL
self.node_frames = self.node_frames_raw = NULL
def __init__(self, str backend="detect"):
"""__init__(self, backend="detect")\n--
Create a new connection score.
Arguments:
backend (`str`): The SIMD backend to use for the heuristic filter.
Use ``"detect"`` to use the best available one depending on
the CPU capabilities of the local machine. Other available
values are: ``"generic"``, ``"sse"``, ``"avx"``, ``neon``.
"""
IF TARGET_CPU == "x86":
if backend =="detect":
self.backend = simd_backend.NONE
IF MMX_BUILD_SUPPORT:
if _MMX_RUNTIME_SUPPORT:
self.backend = simd_backend.MMX
IF SSE2_BUILD_SUPPORT:
if _SSE2_RUNTIME_SUPPORT:
self.backend = simd_backend.SSE2
IF AVX2_BUILD_SUPPORT:
if _AVX2_RUNTIME_SUPPORT:
self.backend = simd_backend.AVX2
elif backend == "mmx":
IF not MMX_BUILD_SUPPORT:
raise RuntimeError("Extension was compiled without MMX support")
ELSE:
if not _MMX_RUNTIME_SUPPORT:
raise RuntimeError("Cannot run MMX instructions on this machine")
self.backend = simd_backend.MMX
elif backend == "sse":