Debian Codegraph @

scripts/k3000/K3000_common.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 '''
5 Compaction of facts. Non ambiguous paths from a set of facts are compacted
6 @author (except for the 'unique' function) pierre peterlongo [email protected]
7 '''
8
9 __author__ = "Pierre Peterlongo"
10 __email__ = "[email protected]"
11
12
13 import sys
14 import sorted_list
15 import os
16
17
18
19 # update_progress() : Displays or updates a console progress bar
20 ## Accepts a float between 0 and 1. Any int will be converted to a float.
21 ## A value under 0 represents a 'halt'.
22 ## A value at 1 or bigger represents 100%
23 #https://stackoverflow.com/questions/3160699/python-progress-bar
24 def update_progress(progress):
25 barLength = 50 # Modify this to change the length of the progress bar
26 status = ""
27 # if isinstance(progress, int):
28 # progress = float(progress)
29 # if not isinstance(progress, float):
30 # progress = 0
31 # status = "error: progress var must be float\r\n"
32 if progress < 0:
33 progress = 0
34 status = "Halt...\r\n"
35 if progress >= 1:
36 progress = 1
37 status = "Done...\r\n"
38 block = int(round(barLength*progress))
39 text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), round(progress*100,2), status)
40 sys.stderr.write(text)
41 sys.stderr.flush()
42
43 def file_size(f):
44 old_file_position = f.tell()
45 f.seek(0, os.SEEK_END)
46 size = f.tell()
47 f.seek(old_file_position, os.SEEK_SET)
48 return size
49
50 def hamming_near_perfect (s1, s2, max=0):
51 """ returns True is the hamming distance between {s1} and {s2} at most equal to {max}
52 jocker N are authorized.
53 s1 and s2 are compared as upper case sequences (eg a==A)
54 """
55 res=0
56
57 if len(s1) != len(s2): return False
58 for i in range(len(s1)):
59 if s1[i].upper() == 'N' or s2[i].upper()=='N': continue
60 if s1[i].upper()!=s2[i].upper():
61 res+=1
62 if res>max: return False
63 return True
64
65
66
67
68 def get_complement(char):
69 complement = {"A" : "T", "T" : "A", "G" : "C", "C" : "G", "a" : "t", "t" : "a", "g" : "c" , "c" : "g", "N":"N"}
70 return complement[char]
71
72
73 def get_reverse_complement(seq):
74 s = ""
75 for i in range(len(seq)):
76 s = get_complement(seq[i]) + s
77 return s
78
79 string_allele_value = lambda x: x.split('_')[0]
80 allele_value = lambda x: int(x.split('_')[0])
81 allele_values = lambda list_: [allele_value(x) for x in list_]
82 distance_string_value = lambda x: x.split('_')[1]
83
84 def generate_header(raw_int_facts):
85 # from 204_0;201_-23;336_-85; to 102h;100l;168h;
86 res=""
87 for raw_int_fact in raw_int_facts.strip(";").split(';'):
88 res+=unitig_id2snp_id(allele_value(raw_int_fact))+";"
89 return res
90
91 def d_list_equal(a_d,b_d):
92 a=[allele_value(x) for x in a_d]
93 b=[allele_value(x) for x in b_d]
94 return a==b
95
96 def d_list_sup(a_d,b_d):
97 a=[allele_value(x) for x in a_d]
98 b=[allele_value(x) for x in b_d]
99 return a>=b
100
101
102 def d_list_order(a_d,b_d):
103 a=[allele_value(x) for x in a_d]
104 b=[allele_value(x) for x in b_d]
105 if a<b: return -1
106 if a==b: return 0
107 return 1
108
109
110 def get_reverse_fact(x):
111 ''' reverse of a fact x. Example is fact x = ["4_0","2_3","-6_21"], reverse(x) = ["6_0","-2_21","-4_3"] '''
112 res =[]
113 for i in range (len(x)):
114 value = -allele_value(x[-i-1]) # With i=0, '-6_21' is transformed into 6
115 if i==0:
116 value=str(value)+"_0" # With i=0, add '_0' to the value
117 else:
118 value=str(value)+"_"+distance_string_value(x[-i]) # With i=1, add '_21' to the value
119 res.append(value)
120 return res
121
122
123 def is_palindromic(x):
124 ''' return true is a fact x is palindromic, eg [1_0,2_12,-2_13,-1_12]'''
125 if len(x)%2 == 1: return False
126 for i in range(0,int(len(x)/2)):
127 if allele_value(x[i]) != -allele_value(x[-i-1]): return False
128 return True
129 #
130 #
131 # print(get_reverse_sr(["4_0","2_3","-6_21"]))
132 # print(is_palindromic(["4_0","4_21"]))
133
134 def f(variant):
135 '''
136 sVp
137 * s='-' or nothing
138 * V=int value
139 * p='h' or 'l' (path)
140
141 f(sVp)=s2V+g(p) with g(p)=0 if p='h' and 1 if p='l'
142 '''
143 s=''
144 if variant[0]=='-':
145 s='-'
146 V=int(variant[1:-1])
147 else:
148 V=int(variant[:-1])
149 p=variant[-1]
150 odd=0
151 if p=='l':
152 odd=1
153
154 res=(V*2)+odd
155 return s+str(res)
156
157
158 def valid_fact(rawfact):
159 """
160 Checks if a fact is valid.
161 A fact containing twice or more the same variant id is not valid.
162 eg: 9h_0;35100h_34;-42157l_33; ok
163 eg: 10081h_0;10081l_13; ko
164 eg: 10081h_0;10081h_13; ko
165 eg: -10081h_0;10081l_13; ko
166 """
167 id_variants = set()
168 for variant in rawfact.rstrip(';').split(';'):
169 id_variant = variant.lstrip("-").split("_")[0][:-1] # from -10081h_0 to 10081
170 if id_variant in id_variants: return False
171 id_variants.add(id_variant)
172 return True
173
174 def generate_facts_from_disco_pashing(file_name):
175 mfile = open(file_name)
176 sl = sorted_list.sorted_list()
177 nb_non_valid = 0
178 for line in mfile:
179 #9h_0;35100h_34;-42157l_33; -16792l_0;-41270h_70; => 1
180 # or
181 #-2586h_0;19690h_40; => 2
182 if line[0]=='#':
183 # print(line,end='')
184 continue
185 line=line.strip().split("=>")[0]
186 line=line.strip().split()
187 for fact in line:
188 if not valid_fact(fact):
189 nb_non_valid+=1
190 continue
191 facttab=[]
192 for variant in fact.split(';')[:-1]:
193 facttab.append(f(variant.split('_')[0])+"_"+variant.split('_')[1])
194
195
196 facttab = get_canonical(facttab) # store the canonical version of the fact. Btw, afterwards we add all reverse complements.
197 sl.add(facttab)
198
199 sl.unique() # Remove redundancies
200 return sl, nb_non_valid
201
202 def generate_facts(file_name):
203 ''' Given an input file storing facts, store them in the fact array'''
204 # -10021_0;68561_21;-86758_3;27414_12;
205 sr_file = open(file_name, 'r')
206 sl = sorted_list.sorted_list()
207 for line in sr_file:
208 if line[0]==">": continue # compatible with fasta-file format
209 line = line.split()[0].rstrip()[:-1].split(';')
210 sr=[]
211 for allele_id in line:
212 # sr_val=int(unitig_id)
213 sr=sr+[allele_id]
214 sl.add(sr)
215 # print(sr)#DEBUG
216 return sl
217
218 def detect_input_output_edges(facts):
219 '''
220 Given all stored facts and ther reverse complements, stores variants that have at least one input edge (in has_input_edge)
221 and those that have at least one output edge (in has_output_edge)
222
223 if a fact is ["4_0","2_3","-6_21"],
224 has_input_edge = {2,-6}
225 has_output_edge = {4,2}
226
227
228 this means that ["6_0","-2_21","-4_3"] is also stored, hence:
229 has_input_edge = {2, -6, -2, -4}
230 has_output_edge = {4, 2, 6, -2}
231
232
233
234 Returns:
235 has_input_edge, has_output_edge
236 '''
237 has_input_edge= set()
238 has_output_edge = set()
239
240
241 for fact in facts.traverse():
242 previous_variant_id = ""
243 # print(fact)
244 for variant_id in allele_values(fact):
245 if previous_variant_id == "": # first value, just store it:
246 previous_variant_id = variant_id
247 continue
248 has_output_edge.add(previous_variant_id)
249 has_input_edge.add(variant_id)
250 previous_variant_id = variant_id
251 # print(f'output {has_output_edge}')
252 # print(f'inputput {has_input_edge}')
253 # sys.exit()
254 return has_input_edge,has_output_edge
255
256 def add_reverse_facts(facts):
257 ''' For all facts, we add their reverse in the same structure
258 This double the fact size, unless there are palindromes ([1_0,-1_21] for instance). Those are not added.
259 We don't check that this does not create any duplicates'''
260 facts_ = sorted_list.sorted_list()
261 for fact in facts.traverse():
262 if not is_palindromic(fact):
263 facts_.add(get_reverse_fact(fact))
264 for fact in facts_.traverse():
265 facts.add(fact)
266 return facts
267
268
269
270 def colinear(x,X,starting_positions):
271 ''' Check that all sr in X are colinear with x
272 For each sr in X, one knows its starting position on x, with table starting_positions'''
273 for i in range(len(X)):
274 other = X[i]
275 starting_position = starting_positions[i]
276 pos=0
277 while True:
278 if pos>=len(other) or pos+starting_position>=len(x) : break
279 if allele_value(other[pos]) != allele_value(x[pos+starting_position]): # "non colinear"
280 return False
281 pos+=1
282 return True
283
284
285 def is_canonical(sr):
286 ''' return True if the canonical representation of sr is itself'''
287 if d_list_sup(sr, get_reverse_fact(sr)):
288 return True
289 else:
290 return False
291
292 def get_canonical(fact):
293 ''' return the canonical representation of sr'''
294 fact_=get_reverse_fact(fact)
295 if d_list_sup(fact, fact_):
296 return fact
297 else:
298 return fact_
299
300 def print_maximal_facts(facts):
301
302 '''print all maximal facts as a flat format'''
303 for sr in facts.traverse():
304 if is_canonical(sr) or is_palindromic(sr):
305 if len(sr)==1:
306 print (str(allele_value(sr[0]))+";")
307 else:
308 for unitig_id in sr:
309 print (str(unitig_id)+";", end="")
310 print ()
311
312
313
314 def determine_k(fa_file_name):
315 """ given the output disco file, ie discoRes_k_31_c_2_D_0_P_3_b_2_coherent.fa return the k value (ie 31).
316 """
317 return int(fa_file_name.split("_k_")[1].split("_")[0])
318
319 def unitig_id2snp_id(unitig_id):
320 sign=1
321 if unitig_id<0: sign=-1
322 unitig_id=abs(unitig_id)
323 res=str(sign*(unitig_id//2))
324 if unitig_id%2==0:
325 res+="h"
326 else:
327 res+="l"
328 return res
329
330
331 def get_fact_id(fact):
332 ''' returns the id of a fact
333 WARNING: here fact contains as last value its unique id.
334 '''
335 return int(fact[-1].split("_")[1])
336
337 def get_reverse_fact_id(fact,facts):
338 ''' returns the id of the reverse complement of fact
339 1/ find the sequence of the fact_ in facts
340 2/ grab its id
341 WARNING: here fact contains as last value its unique id.
342 '''
343 #1/
344 # print("reverse fact id of",fact)
345 without_id_reverse_fact = get_reverse_fact(fact[:-1]) # get the fact reverse complement
346 # print("rc is", without_id_reverse_fact)
347 Y=facts.get_lists_starting_with_given_prefix(without_id_reverse_fact) # find the reverse complement in the list.
348 # print("Y is", Y)
349 for y in Y: # should be of size >= 1. One of them is exactly 'without_id_reverse_fact' plus its id.
350 if len(y) == len(without_id_reverse_fact)+1: # 'y' is 'without_id_reverse_fact' with its node id
351 return get_fact_id(y) # 2/
352 return None # Should not happend
353
354 # facts=generate_facts("test.txt")
355 # facts.unique()
356 # facts=add_reverse_facts(facts)
357 # facts.unique()
358 # for sr in facts.traverse():
359 # print (sr)
360
361 def get_snp_positions(comment_line):
362 """
363 from a comment line, eg:
364 >SNP_higher_path_99|P_1:20_C/T,P_2:25_T/C|high|nb_pol_2|left_unitig_length_21|right_unitig_length_14|C1_262|Q1_73|G1_0/1:5710,65,3395|rank_0
365 returns the snp positions, eg
366 [20, 25]
367 """
368 positions = []
369 for variants_localization in comment_line.split("|")[1].split(','):
370 positions.append(int(variants_localization.split(":")[1].split("_")[0]))
371 return positions
372
373
374 def index_sequences(fa_file_name, sequences={}):
375 mfile = open(fa_file_name)
376 while True:
377 line1 = mfile.readline()
378 if not line1: break
379 line1 = line1.strip()
380 line2 = mfile.readline().strip()
381 mfile.readline() # USELESS
382 line4 = mfile.readline().strip()
383
384 if not line1.startswith(">SNP"): continue
385
386 #line1:
387 #>SNP_higher_path_9|P_1:30_A/C|high|nb_pol_1|left_unitig_length_152|right_unitig_length_3|C1_25|Q1_63|G1_0/1:399,14,359|rank_0
388 # key is 9h
389 # one need to store the left unitig length. Here 152
390 # one need to store the right unitig length. Here 3
391 # note that the position of the left_unitig_length field is always the same with or without multiple snps.
392 snp_positions = get_snp_positions(line1)
393 line1 = line1.split('|')
394 snp_id = line1[0].split('_')[-1] # from SNP_higher_path_9 to 9
395
396 left_unitig_len = int(line1[4].split('_')[-1])
397 right_unitig_len = int(line1[5].split('_')[-1])
398
399 sequences[snp_id] = [left_unitig_len, right_unitig_len, line2, line4, snp_positions] #sequences[snp_id] = [left_unitig_len, right_unitig_len, upperseq, lowerseq, snp_positions]
400
401 mfile.close()
402 return sequences
403
404 def seq_to_lower_case_except_SNPs(seq, snp_positions):
405 """ given a sequence in ACGTN, put everything in lower case, except the variant positions on the upper case bubble"""
406 res=""
407 position_on_bubble=-1
408 for letter in seq:
409 if letter.isupper():
410 position_on_bubble+=1
411 if position_on_bubble!=-1 and position_on_bubble in snp_positions: res+=letter.upper()
412 else: res+=letter.lower()
413 return res
414
415 def update_SNP_positions(seq1, seq2):
416 """
417 Given a sequence `seq1` with upper case letters showing SNP positions, eg
418 acggcgagTg
419 update SNPs positions given a a sequence `seq2` of the same length, eg:
420 aGggTgaggg
421 final results is
422 aGggTgagTg
423 In case of equality of lower case letter, seq1 is abitrary showen
424 raises an error if two distinct upper case letters occur at the same position
425 """
426 new_seq = ""
427 # print(f'Try concatenate \n{seq1} with \n{seq2}')
428
429 for i, letter in enumerate(seq1):
430 if seq2[i].isupper():
431 # detects errors
432 if letter.isupper() and letter != seq2[i]: raise ValueError (f'Cannot concatenate \n{seq1} with \n{seq2}, no solution for position {i} of suffix')
433 # no error conserve the previous value as it was upper case
434 new_seq+=seq2[i]
435 # here either letter is upper, we keep it, or letter is lower, we also keept it.
436 else: new_seq+=letter
437 return new_seq
438
439
440
441 def test_update_SNP_positions():
442 seq1 = "atggcgagTg"
443 seq2 = "aGggTgtggg"
444 res = update_SNP_positions(seq1,seq2)
445 assert res == "aGggTgagTg"
446
447 # test_update_SNP_positions()
448
449 def line2seq(line, sequences, int_facts_format, hamming_max=3):
450 '''
451 Parses a (non paired) fact, represented by ints or not
452 Returns a bench of information relative to the line to be printed or not to be printed
453 '''
454 header = line.strip()+ " SP:" # add latter the starting and ending positions of each allele on the global sequence (SP = Sequence positions). Enables to recover the good overlap length in the final GFA file
455 bubble_facts_position_start_stops = "BP:" # to the header is also added the Bubble positions. For each allele in the fact we store the distance between the bubble start (upper case letter and the end of the previous bubble (also upper case letter). We add the length of the bubble (upper case letter).
456 # EG:
457 # ------XXXXXXXXXXXXXXXXXX------ 0_18
458 # ------------XXXXXXXXXXXXXX----------- 3:14
459 # ----------XXXXXXXXXXXXXXXX---------- -7:16 (distance is negative is bubbles overlap
460
461 line=line.strip(';').split(';')
462 previous_bubble_ru=0
463 full_seq = ""
464 toprint = True
465 for i,int_snp_id_d in enumerate(line):
466
467 # print("#################@ i #######################@",i)
468
469 ## _________--------X---------______________________________ previous snp (or full sequence we dont care)
470 ## <---- previous_bubble_ru ---->
471 ## <------ right_unitig_len ----> previous snp -> previous_bubble_ru = k-1+right_unitig_len of the previous snp
472 ## __--------X---------_________________________________ new SNP
473 ## <----> shift between snps <-------------------------> to be written
474 ## <---upper_case---><----------------ru------------->
475
476
477 ## shift + uppercase + ru = to_be_written + previous_bubble_ru
478 ## ->
479 ## to_be_written = shift + uppercase + ru - previous_bubble_ru
480 ## If a SNP is reversed, we reverse complement the sequence and change "right“ unitig for "left" unitig
481 if int_facts_format:
482 allele_id = unitig_id2snp_id(allele_value(int_snp_id_d))
483 else:
484 allele_id = int_snp_id_d.split("_")[0]
485
486 # print(f"\n\n *****{int_snp_id_d}, {allele_id} ********")
487 snp_id = allele_id[:-1]
488
489 higher=True
490 if allele_id[-1] == 'l':
491 higher=False
492
493 forward=True
494 if allele_id[0] == '-':
495 forward=False
496 snp_id = snp_id[1:]
497 try:
498
499 if higher: seq = sequences[snp_id][2]
500 else: seq = sequences[snp_id][3]
501 if forward:
502 lu = sequences[snp_id][0]
503 ru = sequences[snp_id][1]
504 len_bubble = len(seq)-lu-ru # len sequence - len left unitig - len right unitig
505 snp_positions = sequences[snp_id][4]
506 else:
507 seq=get_reverse_complement(seq)
508 lu = sequences[snp_id][1]
509 ru = sequences[snp_id][0]
510 len_bubble = len(seq)-lu-ru # len sequence - len left unitig - len right unitig
511 snp_positions = [len_bubble-x-1 for x in sequences[snp_id][4]] # reverse snp positions
512 snp_positions.sort() # and sort them in increasing order
513
514
515 #conserves only SNP positions in upper case:
516 seq = seq_to_lower_case_except_SNPs(seq, snp_positions)
517
518 #treat first snp apart
519 if i==0:
520 full_seq+=seq
521 previous_bubble_ru = ru
522 header+="0_"+str(len(full_seq))+";" # SP==Sequence Positions
523 bubble_facts_position_start_stops+="0_"+str(len_bubble)+";"
524 # print("full_seq =",full_seq)
525
526 else:
527 to_be_written = len_bubble + ru + int(distance_string_value(int_snp_id_d)) - previous_bubble_ru
528 bubble_facts_position_start_stops+=distance_string_value(int_snp_id_d)+"_"+str(len_bubble)+";"
529 # #DEBUG
530 # print("to_be_written =",to_be_written)
531 # print("len seq =",len(seq))
532 # print("previous_bubble_ru =",previous_bubble_ru)
533 # print("len_bubble =", len_bubble)
534 # print("start_to_end =", len_bubble+ru)
535 # print("shift =", int(distance_string_value(int_snp_id_d)))
536
537 # print("full_seq =",full_seq)
538 # print("seq =",seq)
539 # if to_be_written>0: print("add ", seq[-to_be_written:])
540 # else: print("add nothing")
541
542 if to_be_written>0: # an overlap exists
543 if to_be_written<=len(seq): # the to_be_written part is smaller or equal to the length of the new sequence, we concatenate the to_be_written part.
544 # check that the overlap is correct. Fake read happen with reads containing indels. We could try to retreive the good overlap, but it'd be time consuming and useless as other reads should find the good shift.
545 p=len(seq)-to_be_written # maximal size of the overlap.
546 if p > len(full_seq):
547 # if the previous sequence is included into the new one, the start on the new seq is shifted
548 # ------------------ full_seq
549 # ------------------------- seq
550 # <---> = len(seq)-len(full_seq)-to_be_written
551 start_on_seq=len(seq)-len(full_seq)-to_be_written
552 stop_on_seq=start_on_seq+min(p,len(full_seq))
553 else:
554 start_on_seq=0
555 stop_on_seq=start_on_seq+p
556
557 if not hamming_near_perfect(full_seq[-p:], seq[start_on_seq:stop_on_seq], hamming_max): #Fake read (happens with reads containing indels). We could try to retreive the good sequence, but it'd be time consuming and useless as other reads should find the good shift.
558 toprint = False
559 break
560 header+=str(len(full_seq)-len(seq)+to_be_written) # starting position of the new sequence on the full seq that overlaps the full seq by len(seq)-to_be_written
561 try:
562 overlap = update_SNP_positions(full_seq[-p:], seq[start_on_seq:stop_on_seq])
563 except ValueError as err:
564 toprint = False
565 # sys.stderr.write(f"{format(err)} \n")
566 break
567
568 full_seq = full_seq[:-p]+overlap+seq[-to_be_written:]
569
570 header+="_"+str(len(full_seq))+";" # ending position of the new sequence on the full seq.
571 else: # the to_be_written part is bigger than the length of the new sequence, we fill with Ns and add the full new seq
572 for i in range(to_be_written-len(seq)):
573 full_seq+='N'
574 header+=str(len(full_seq)) # starting position of the new sequence on the full seq (possibly overlapping the full seq)
575 full_seq+=seq
576 header+="_"+str(len(full_seq))+";" # ending position of the new sequence on the full seq.
577 previous_bubble_ru = ru
578
579 else: # the new seq finishes before the already created full_seq. In this case we need to update the previous ru wrt
580 ### ----------XXXXXXXX--------------------------
581 ### <-- pbru -->
582 ### -------------------XXXXX-------
583 ### <shift > < tbw > (negative)
584 ### <---npbru ---> (next previous_bubble_ru)
585 ### pbru = shift +len(upper) + npbru -->
586 ### npbru = pbru - shift - len(upper)
587 ### TODO BUG ? (I_ here is alway followed by a negative value in the experiments I made (june 2020))
588 previous_bubble_ru = previous_bubble_ru-int(distance_string_value(int_snp_id_d))-len_bubble
589
590 overlap_start = len(full_seq)+to_be_written-len(seq) #(included)
591 overlap_stop = len(full_seq)+to_be_written #(excluded)
592
593 header += "I_"+str(overlap_start)+"_"+str(overlap_stop)+";" # this allele is useless we do not store its start and stop positions
594
595 if not hamming_near_perfect(full_seq[overlap_start:overlap_stop], seq, hamming_max):
596 # print(f"Too far:\n{full_seq[overlap_start:overlap_stop]}\n{seq}\n")
597 toprint=False
598 # print(full_seq[overlap_start:overlap_stop]+"\n"+seq+"\n")
599 try:
600 overlap = update_SNP_positions(full_seq[overlap_start:overlap_stop], seq)
601 except ValueError as err:
602 toprint = False
603 # sys.stderr.write(f"{format(err)} \n")
604 break
605 full_seq = full_seq[:overlap_start] + overlap + full_seq[overlap_stop:]
606
607
608 except KeyError: # in case a variant is in the phasing file but absent from the disco file. This is due to uncoherent prediction
609 sys.stderr.write(f"{snp_id} not in sequences\n")
610 toprint=False
611 break
612 return toprint, header, bubble_facts_position_start_stops, full_seq