Debian Codegraph @

python/pyabpoa.pyx

raw
1 import re, sys, os
2 from libc.stdlib cimport malloc, free
3 from libc.stdint cimport uint8_t
4 from collections import defaultdict as dd
5 cimport cython
6 from cabpoa cimport *
7 from libc.string cimport strcpy
8
9
10 cdef class msa_result:
11 cdef int n_seq
12 cdef int n_cons
13 cdef clu_n_seq, clu_read_ids, cons_len, cons_seq, cons_cov, cons_qv # _cons_len:[int], _cons_seq:['']
14 cdef int msa_len
15 cdef msa_seq # _msa_seq:['']
16
17 def __cinit__(self, n_seq, n_cons, clu_n_seq, clu_read_ids, cons_len, cons_seq, cons_cov, cons_qv, msa_len, msa_seq):
18 self.n_seq = n_seq
19 self.n_cons = n_cons
20 self.clu_n_seq = clu_n_seq
21 self.clu_read_ids = clu_read_ids
22 self.cons_len = cons_len
23 self.cons_seq = cons_seq
24 self.cons_cov = cons_cov
25 self.cons_qv = cons_qv
26 self.msa_len = msa_len
27 self.msa_seq = msa_seq
28
29 @property
30 def n_seq(self): return self.n_seq
31
32 @property
33 def n_cons(self): return self.n_cons
34
35 @property
36 def clu_n_seq(self): return self.clu_n_seq
37
38 @property
39 def clu_read_ids(self): return self.clu_read_ids
40
41 @property
42 def cons_len(self): return self.cons_len
43
44 @property
45 def cons_seq(self): return self.cons_seq
46
47 @property
48 def cons_cov(self): return self.cons_cov
49
50 @property
51 def cons_qv(self): return self.cons_qv
52
53 @property
54 def msa_len(self): return self.msa_len
55
56 @property
57 def msa_seq(self): return self.msa_seq
58
59 def print_msa(self):
60 if not self.msa_seq: return
61 for i, s in enumerate(self.msa_seq):
62 if i < self.n_seq:
63 print(f'>Seq_{i+1}')
64 else:
65 if self.n_cons > 1:
66 cons_id = f'_{i-self.n_seq+1} {",".join(list(map(str, self.clu_read_ids[i-self.n_seq])))}'
67 else:
68 cons_id = ''
69 print(f'>Consensus_sequence{cons_id}')
70 print(s)
71 return
72
73
74 def set_seq_int_dict(m):
75 if m == 5: # ACGTN ==> 01234, U ==> 4
76 seqs = 'ACGUTN'
77 ints = [0, 1, 2, 3, 3, 4]
78 elif m == 27: # ACGTN ==> 01234, BDEFH... ==> 56789...
79 seqs = 'ACGTNBDEFHIJKLMOPQRSUVWXYZ*'
80 ints = [0, 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]
81 else:
82 raise Exception(f'Unexpected m: {m}')
83
84 seq2int_dict = dd(lambda: m-1)
85 int2seq_dict = dd(lambda: '-')
86 for s, i in zip(seqs, ints):
87 seq2int_dict[s] = i
88 seq2int_dict[s.lower()] = i
89 int2seq_dict[i] = s
90 return seq2int_dict, int2seq_dict
91
92
93 cdef class msa_aligner:
94 cdef abpoa_t *ab
95 cdef abpoa_para_t abpt
96 cdef seq2int_dict, int2seq_dict
97 cdef char* _score_mat_fn
98 cdef bytes _score_mat_fn_b
99
100 def __cinit__(self, aln_mode='g', is_aa=False,
101 match=2, mismatch=4, score_matrix=b'', gap_open1=4, gap_open2=24, gap_ext1=2, gap_ext2=1,
102 extra_b=10, extra_f=0.01,
103 cons_algrm='HB'):
104 self.ab = abpoa_init()
105
106 if aln_mode == 'g':
107 self.abpt.align_mode = ABPOA_GLOBAL_MODE
108 elif aln_mode == 'l':
109 self.abpt.align_mode = ABPOA_LOCAL_MODE
110 elif aln_mode == 'e':
111 self.abpt.align_mode = ABPOA_EXTEND_MODE
112 else:
113 raise Exception(f'Unknown align mode: {aln_mode}')
114 if is_aa:
115 self.abpt.m = 27
116 self.abpt.mat = <int*>malloc(27 * 27 * cython.sizeof(int))
117 else:
118 self.abpt.m = 5
119 self.abpt.mat = <int*>malloc(25 * cython.sizeof(int))
120 self.abpt.match = match
121 self.abpt.mismatch = mismatch
122
123 if score_matrix:
124 self.abpt.use_score_matrix = 1
125 _score_mat_fn_b = score_matrix.encode('utf-8')
126 _score_mat_fn = <char*> malloc(len(_score_mat_fn_b) + 1)
127 strcpy(_score_mat_fn, _score_mat_fn_b)
128 self.abpt.mat_fn = _score_mat_fn
129
130 self.abpt.gap_open1 = gap_open1
131 self.abpt.gap_open2 = gap_open2
132 self.abpt.gap_ext1 = gap_ext1
133 self.abpt.gap_ext2 = gap_ext2
134 self.abpt.ret_cigar = 1
135
136 self.abpt.wb = extra_b
137 self.abpt.wf = extra_f
138 self.abpt.use_qv = 0
139 self.abpt.end_bonus = -1 # disable end_bonus/zdrop
140 self.abpt.zdrop = -1
141 self.abpt.disable_seeding = 1
142 self.abpt.progressive_poa = 0
143 if cons_algrm.upper() == 'MF':
144 self.abpt.cons_algrm = ABPOA_MF
145 elif cons_algrm.upper() == 'HB':
146 self.abpt.cons_algrm = ABPOA_HB
147 else:
148 raise Exception(f'Unknown conseneus calling mode: {cons_algrm}')
149
150 self.seq2int_dict, self.int2seq_dict = set_seq_int_dict(self.abpt.m)
151
152 def __dealloc__(self):
153 free(self.abpt.mat)
154 abpoa_free(self.ab)
155
156 def __bool__(self):
157 return self.ab != NULL
158
159 cdef int* _prepare_weights(self, seq, qscore):
160 cdef Py_ssize_t i, seq_l = len(seq)
161 cdef int *weights = NULL
162
163 weights = <int*>malloc(seq_l * cython.sizeof(int))
164 if weights == NULL:
165 raise MemoryError()
166
167 try:
168 if len(qscore) != seq_l:
169 raise ValueError('Each qscore array must have the same length as its sequence.')
170 for i in range(seq_l):
171 weights[i] = int(qscore[i])
172 if weights[i] < 0:
173 raise ValueError('Qscores must be non-negative integers.')
174 except:
175 free(weights)
176 raise
177 return weights
178
179 cdef void _add_sequences(self, seqs, qscores, int exist_n, int tot_n):
180 cdef uint8_t *bseq
181 cdef int *weights = NULL
182 cdef int seq_l
183 cdef Py_ssize_t i
184 cdef abpoa_res_t res
185
186 if qscores is not None and len(qscores) != len(seqs):
187 raise ValueError('qscores must contain one entry per input sequence.')
188
189 for read_i, seq in enumerate(seqs):
190 seq_l = len(seq)
191 bseq = <uint8_t*>malloc(seq_l * cython.sizeof(uint8_t))
192 if bseq == NULL:
193 raise MemoryError()
194 weights = NULL
195 res.n_cigar = 0
196 res.graph_cigar = NULL
197 try:
198 for i in range(seq_l):
199 bseq[i] = self.seq2int_dict[seq[i]]
200 if qscores is not None:
201 weights = self._prepare_weights(seq, qscores[read_i])
202 abpoa_align_sequence_to_graph(self.ab, &self.abpt, bseq, seq_l, &res)
203 abpoa_add_graph_alignment(self.ab, &self.abpt, bseq, weights, seq_l, NULL, res, exist_n+read_i, tot_n, 1)
204 finally:
205 free(bseq)
206 if weights != NULL:
207 free(weights)
208 if res.n_cigar:
209 free(res.graph_cigar)
210
211 def msa(self, seqs, out_cons, out_msa, max_n_cons=1, min_freq=0.25, out_pog=b'', incr_fn=b'', qscores=None):
212 cdef int seq_n = len(seqs)
213 cdef int exist_n = 0
214 cdef int tot_n = seq_n
215 cdef abpoa_cons_t abc
216
217 if out_cons: self.abpt.out_cons = 1
218 else: self.abpt.out_cons = 0
219 if out_msa: self.abpt.out_msa = 1
220 else: self.abpt.out_msa = 0
221 if max_n_cons < 1 or max_n_cons > 2:
222 raise Exception('Error: max number of consensus sequences should be 1 or 2.')
223 self.abpt.max_n_cons = max_n_cons
224 self.abpt.min_freq = min_freq
225 self.abpt.use_qv = 1 if qscores is not None else 0
226 if out_pog:
227 if isinstance(out_pog, str): out_pog = bytes(out_pog, 'utf-8')
228 self.abpt.out_pog = out_pog
229 else: self.abpt.out_pog = NULL
230
231 abpoa_post_set_para(&self.abpt)
232 abpoa_reset(self.ab, &self.abpt, len(seqs[0]))
233 if incr_fn:
234 if isinstance(incr_fn, str):
235 incr_fn = bytes(incr_fn, 'utf-8')
236 self.abpt.incr_fn = incr_fn
237 abpoa_restore_graph(self.ab, &self.abpt)
238 exist_n = self.ab[0].abs[0].n_seq
239 tot_n += exist_n
240 else:
241 self.abpt.incr_fn = NULL
242
243 self.ab[0].abs[0].n_seq += seq_n
244 self._add_sequences(seqs, qscores, exist_n, tot_n)
245
246 if self.abpt.out_msa:
247 abpoa_generate_rc_msa(self.ab, &self.abpt)
248 elif self.abpt.out_cons:
249 abpoa_generate_consensus(self.ab, &self.abpt)
250 abc = self.ab[0].abc[0]
251
252 n_cons, clu_n_seq, clu_read_ids, cons_len, cons_seq, cons_cov, cons_qv, msa_len, msa_seq = 0, [], [], [], [], [], [], 0, []
253 n_cons = abc.n_cons
254 for i in range(n_cons):
255 clu_n_seq.append(abc.clu_n_seq[i])
256 cons_len.append(abc.cons_len[i])
257 clu_read_ids1, cons_seq1, cons_cov1, cons_qv1 = [], '', [], ''
258 for j in range(abc.clu_n_seq[i]):
259 clu_read_ids1.append(abc.clu_read_ids[i][j])
260 clu_read_ids.append(clu_read_ids1)
261 for j in range(abc.cons_len[i]):
262 c = abc.cons_base[i][j]
263 if isinstance(c, bytes): c = ord(c)
264 cons_seq1 += self.int2seq_dict[c]
265 cons_cov1.append(abc.cons_cov[i][j])
266 if abc.cons_phred_score != NULL:
267 cons_qv1 += chr(abc.cons_phred_score[i][j])
268 cons_seq.append(cons_seq1)
269 cons_cov.append(cons_cov1)
270 cons_qv.append(cons_qv1)
271
272 msa_len = abc.msa_len
273 if msa_len > 0:
274 for i in range(abc.n_seq + n_cons):
275 msa_seq1 = ''
276 for c in abc.msa_base[i][:msa_len]:
277 if isinstance(c, bytes): c = ord(c)
278 msa_seq1 += self.int2seq_dict[c]
279 msa_seq.append(msa_seq1)
280
281 if self.abpt.out_pog:
282 abpoa_dump_pog(self.ab, &self.abpt)
283 return msa_result(tot_n, n_cons, clu_n_seq, clu_read_ids, cons_len, cons_seq, cons_cov, cons_qv, msa_len, msa_seq)
284
285 def msa_align(self, seqs, out_cons, out_msa, max_n_cons=1, min_freq=0.25, incr_fn=b'', qscores=None):
286 cdef int seq_n = len(seqs)
287 cdef int exist_n = 0
288 cdef int tot_n = seq_n
289
290 if out_cons: self.abpt.out_cons = 1
291 else: self.abpt.out_cons = 0
292 if out_msa: self.abpt.out_msa = 1
293 else: self.abpt.out_msa = 0
294 if max_n_cons < 1 or max_n_cons > 2:
295 raise Exception('Error: max number of consensus sequences should be 1 or 2.')
296 self.abpt.max_n_cons = max_n_cons
297 self.abpt.min_freq = min_freq
298 self.abpt.use_qv = 1 if qscores is not None else 0
299
300 abpoa_post_set_para(&self.abpt)
301 abpoa_reset(self.ab, &self.abpt, len(seqs[0]))
302 if incr_fn:
303 if isinstance(incr_fn, str):
304 incr_fn = bytes(incr_fn, 'utf-8')
305 self.abpt.incr_fn = incr_fn
306 abpoa_restore_graph(self.ab, &self.abpt)
307 exist_n = self.ab[0].abs[0].n_seq
308 tot_n += exist_n
309 else:
310 self.abpt.incr_fn = NULL
311
312 self.ab[0].abs[0].n_seq += seq_n
313 self._add_sequences(seqs, qscores, exist_n, tot_n)
314 return self
315
316 def msa_add(self, new_seqs, qscores=None):
317 if isinstance(new_seqs, str):
318 raise TypeError('Expected a list of strings. If you want to add a single sequence, pass it as a list: ["ACGT..."]')
319
320 cdef int exist_n = 0
321 exist_n = self.ab[0].abs[0].n_seq
322 if (exist_n == 0):
323 raise Exception('Error: no existing sequences in the graph. Please run msa() or msa_align() first.')
324 cdef int seq_n = len(new_seqs)
325 cdef int tot_n = seq_n
326
327 tot_n += exist_n
328 self.ab[0].abs[0].n_seq += seq_n
329 if qscores is not None:
330 self.abpt.use_qv = 1
331 self._add_sequences(new_seqs, qscores, exist_n, tot_n)
332 return self
333
334 def msa_output(self):
335 cdef abpoa_cons_t abc
336 if self.abpt.out_msa:
337 abpoa_generate_rc_msa(self.ab, &self.abpt)
338 elif self.abpt.out_cons:
339 abpoa_generate_consensus(self.ab, &self.abpt)
340 seq_n = self.ab[0].abs[0].n_seq
341 abc = self.ab[0].abc[0]
342
343 n_cons, clu_n_seq, clu_read_ids, cons_len, cons_seq, cons_cov, cons_qv, msa_len, msa_seq = 0, [], [], [], [], [], [], 0, []
344 n_cons = abc.n_cons
345 for i in range(n_cons):
346 clu_n_seq.append(abc.clu_n_seq[i])
347 cons_len.append(abc.cons_len[i])
348 clu_read_ids1, cons_seq1, cons_cov1, cons_qv1 = [], '', [], ''
349 for j in range(abc.clu_n_seq[i]):
350 clu_read_ids1.append(abc.clu_read_ids[i][j])
351 clu_read_ids.append(clu_read_ids1)
352 for j in range(abc.cons_len[i]):
353 c = abc.cons_base[i][j]
354 if isinstance(c, bytes): c = ord(c)
355 cons_seq1 += self.int2seq_dict[c]
356 cons_cov1.append(abc.cons_cov[i][j])
357 if abc.cons_phred_score != NULL:
358 cons_qv1 += chr(abc.cons_phred_score[i][j])
359 cons_seq.append(cons_seq1)
360 cons_cov.append(cons_cov1)
361 cons_qv.append(cons_qv1)
362
363 msa_len = abc.msa_len
364 if msa_len > 0:
365 for i in range(abc.n_seq + n_cons):
366 msa_seq1 = ''
367 for c in abc.msa_base[i][:msa_len]:
368 if isinstance(c, bytes): c = ord(c)
369 msa_seq1 += self.int2seq_dict[c]
370 msa_seq.append(msa_seq1)
371 return msa_result(seq_n, n_cons, clu_n_seq, clu_read_ids, cons_len, cons_seq, cons_cov, cons_qv, msa_len, msa_seq)