Debian Codegraph @

scripts/k3000/K3000_enhance_gfa.py

raw symbols SCIP
1 import sys
2
3 def get_left_clean_snp(snp):
4 return snp.lstrip().lstrip('-')
5
6
7 def set_indexes_from_gfa(gfa_file_name):
8 mfile = open(gfa_file_name)
9 snp_to_fact_id={} # each SNP id (without order nor h or l) is linked to some compacted facts id
10 # eg: '1015': {8, 5, 6, 7}
11 facts={} # each compacted fact is accessible by a unique id. We store only the set of SNPs ids (not their orientering or their intra distance)
12 # eg: 5: {' 5: {'1015h', '827h'}', '827h'}
13 for line in mfile:
14
15 # S 0 -5001_l;-8805_h;-12869_h;-25834_l;-47306_l;38133_l;
16 if line[0]!="S": continue # not a compacted fact
17 line=line.strip().split()
18 compactedfact_id = line[1]
19 facts[compactedfact_id]=[] # stored as a set to conserve the variants order, needed for computing AC.
20 for value in line[2].strip().split(';')[:-1]:
21 facts[compactedfact_id].append(value)
22 snp_id=get_left_clean_snp(value) # from ' -587h' to '587h'
23 if snp_id[:-1] not in snp_to_fact_id:
24 snp_to_fact_id[snp_id[:-1]]=set()
25 snp_to_fact_id[snp_id[:-1]].add(compactedfact_id)
26 mfile.close()
27 return facts, snp_to_fact_id
28
29
30 query_sign = lambda s : "-" if s[0]=="-" else "+"
31
32 def compatibles(raw_fact,compacted_fact):
33 """"given a raw fact, detects if it is totaly included into the compacted_fact[i]
34 we already know that the 2 facts share at least a snp
35 This methods detects if there exists or not a snp, with distinct alleles in the two facts (eg 1000h in one fact, 1000l in the other).
36 Returns false in this case, True else.
37 When True is returned, a second boolean value is returned.
38 It is set to True of the raw fact and the compacted_fact are in the same orientation, else it is set to false
39 """
40
41 ## index query facts:
42 query_fact_to_hl = {}
43 query_fact_to_pm = {}
44 for variant in raw_fact:
45 id_only = variant.lstrip('-')[:-1]
46 query_fact_to_pm[id_only] = query_sign(variant)
47 query_fact_to_hl[id_only] = variant[-1]
48
49 ## checks that all variants from the raw fact are included in the compacted_fact:
50 for variant in raw_fact:
51 if variant not in compacted_fact and variant.lstrip('-') not in compacted_fact and '-'+variant not in compacted_fact :
52 return False, None
53
54 ## check compacted fact vs query fact
55 same_direction = False
56 direction_set = False
57 for variant in compacted_fact:
58 id_only = variant.lstrip('-')[:-1]
59 if id_only not in query_fact_to_hl: continue
60 sign = query_sign(variant)
61 if variant[-1] != query_fact_to_hl[id_only]: return False, None
62 # check sign
63 if not direction_set:
64 direction_set = True
65 same_direction = (sign == query_fact_to_pm[id_only])
66 else:
67 if same_direction and sign != query_fact_to_pm[id_only]: return False, None
68 if not same_direction and sign == query_fact_to_pm[id_only]: return False, None
69 assert (direction_set)
70 return True, same_direction
71
72
73 def get_compatible_facts(text_raw_fact, compacted_facts, snp_to_fact_id):
74 """
75 given the text of a raw fact, returns all compacted_facts ids in which this raw fact occurs
76 add the sign of each of the compacted_facts id in which this raw fact occurs. Negative if it is not the same orientation as the text_raw_fact, else positive
77 Example:
78 * text_raw_fact: -10000l_0;92837_h;
79 * compacted_facts: ... '29731': {'31938l', '499h'} ... (factid -> list of non oriented alleles)
80 * snp_to_fact_id: ... '31938': {'29731'} ... (snp id non oriented -> list of fact ids in which the snp occurs)
81 """
82 subcompacedfacts=set() # Stores all facts potentially compatible with any of the snp of the text_raw_fact
83 raw_fact_snps = set() # Stores the oriented alleles of the text_raw_fact.
84 result = set() # Stores the id of the compacted facts that are compatible with the input text_raw_fact
85 text_raw_fact=text_raw_fact.rstrip(';') #Avoids an empty value when splitting with ';'
86 for oriented_allele in text_raw_fact.split(";"):
87 snp_id_only=get_left_clean_snp(oriented_allele).split("_")[0][:-1] # get the snp id non oriented
88 if snp_id_only in snp_to_fact_id: # the snp may be absent in case it was removed by the sequence concatenation process.
89 subcompacedfacts=subcompacedfacts.union(snp_to_fact_id[snp_id_only]) # fill the subcompacedfacts with all facts in which the snp id non oriented occurs.
90 raw_fact_snps.add(oriented_allele.split("_")[0])
91 for j in subcompacedfacts:
92 cmpt,same_orientation = compatibles(raw_fact_snps, compacted_facts[j])
93 if cmpt:
94 if same_orientation: result.add(int(j))
95 else: result.add(-int(j))
96
97 return result
98
99
100 get_allele_id = lambda x: x.split("_")[-1]+x.split("_")[1][0] #>SNP_higher_path_9 to "9h"
101 get_coverage = lambda x: int(x.split("_")[-1]) #C1_31 to int(31)
102 def index_allele_coverage(raw_disco_fa_file_name, read_set_id, alleles_coverage = {}):
103 """
104 For each allele name (eg 21112l) provides its coverage in the considered read set)
105 Returns a dictionary: allele_id -> coverage
106 Used only by "detects_allele_coverage"
107 """
108 mfile = open(raw_disco_fa_file_name)
109 # first variant rteated appart to recover the position of the coverage in which we are interested
110 coverage_field=-1
111 while True:
112 comment = mfile.readline()
113 if not comment: break
114 if not comment.startswith(">SNP"): continue # do not deal with indels for now
115 s_comment = comment.strip().split("|")
116 mfile.readline() # sequence we don't care
117 for i,field_content in enumerate(s_comment):
118 if field_content.startswith("C"+str(read_set_id)+"_"):
119 coverage_field=i
120 break
121 assert coverage_field != -1, "Read set id "+str(read_set_id)+" not in "+comment
122 allele_id = get_allele_id(s_comment[0])
123 coverage = get_coverage(s_comment[coverage_field])
124 alleles_coverage[allele_id]=coverage
125
126
127
128 # other variants
129 while True:
130 # >SNP_higher_path_9|P_1:30_C/T,P_2:35_T/G|high|nb_pol_2|left_unitig_length_31|right_unitig_length_66|C1_31|Q1_63|G1_0/1:398,14,458|rank_0
131 # ggtgcagacaacccggcaggtgttgatgataAAGATCTGGTTAAATACGCCGATATTGGCGCGACTTACTATTTCAATAAAAACATGTCCACCTACGttgactataaaatcaacctgttggatgaagatgacagcttctacgctgccaatggcatctctaccg
132 # >SNP_lower_path_9|P_1:30_C/T,P_2:35_T/G|high|nb_pol_2|left_unitig_length_31|right_unitig_length_66|C1_28|Q1_63|G1_0/1:398,14,458|rank_0
133 # ggtgcagacaacccggcaggtgttgatgataAAGATCTGGTTAAATACGCCGATATTGGCGTGACTGACTATTTCAATAAAAACATGTCCACCTACGttgactataaaatcaacctgttggatgaagatgacagcttctacgctgccaatggcatctctaccg
134 comment = mfile.readline()
135 if not comment: break
136 if not comment.startswith(">SNP"): continue # do not deal with indels for now
137 comment = comment.strip().split("|")
138 mfile.readline() # sequence we don't care
139 allele_id = get_allele_id(comment[0])
140 coverage = get_coverage(comment[coverage_field])
141 alleles_coverage[allele_id]=coverage
142
143 mfile.close()
144 return alleles_coverage
145
146 def detects_allele_coverage(compacted_facts, raw_disco_co_file_name, raw_disco_unco_file_name, read_set_id):
147 """
148 Given the compacted facts indexed and the raw disco output:
149 for each compacted fact, find all allele that belong to it and store its coverage
150 Returns a dictionary: compacted_fact_id -> allele_weight
151 """
152 alleles_coverage = index_allele_coverage(raw_disco_co_file_name, read_set_id)
153 alleles_coverage = index_allele_coverage(raw_disco_unco_file_name, read_set_id, alleles_coverage)
154 compacted_fact_allele_weight = {} # For each compacted fact id, stores its weight
155 for fact_id, fact_value in compacted_facts.items():
156 compacted_fact_allele_weight[fact_id] = []
157
158 for allele_id in fact_value: #{'10540l', '4734l', '29633h'}
159 allele_coverage = alleles_coverage[get_left_clean_snp(allele_id)]
160 compacted_fact_allele_weight[fact_id].append(allele_coverage)
161 return compacted_fact_allele_weight
162
163 def detects_facts_coverage(compacted_facts, snp_to_fact_id, raw_facts_file_name):
164 """
165 Given the compacted facts indexed and the raw phasing information: for each compacted fact, find all facts that belong to it and compute its estimated coverage
166 Returns a dictionary: compacted_fact_id -> weight
167 """
168 compacted_fact_weight = {} # For each compacted fact id (int), stores its weight
169 mfile = open(raw_facts_file_name)
170 for line in mfile.readlines():
171 if line[0]=="#" : continue # comment
172 coverage = int(line.strip().split("=>")[-1]) # -10011l_0;13979l_-57;21112l_-22;19270l_-14; => 4
173 line=line.strip().split("=>")[0].split() # remove coverage and split into two facts if needed
174 for rawfact in line:
175 if len(rawfact)==0: continue
176 # detects all compacted_facts in which the rawfact occurs:
177 matching_compacted_fact_ids = get_compatible_facts(rawfact, compacted_facts, snp_to_fact_id)
178 for matching_compacted_fact_id in matching_compacted_fact_ids:
179 matching_compacted_fact_id = abs(matching_compacted_fact_id) # remove the useless sign here
180 if matching_compacted_fact_id not in compacted_fact_weight:
181 compacted_fact_weight[matching_compacted_fact_id]=0
182 compacted_fact_weight[matching_compacted_fact_id]+=coverage
183 mfile.close()
184 return compacted_fact_weight
185
186 def print_facts(phasing_file,compacted_fact_weight, compacted_fact_allele_weight):
187 cpt=0
188 mfile=open(phasing_file)
189 for line in mfile:
190 if line[0] != "S" : continue
191 #S 0 -5001l;-8805h;-12869h;-25834l;-47306l;38133l;
192 line=line.strip()
193 compacted_fact_id=int(line.split()[1])
194 fact_weight=0
195 # assert (compacted_fact_id in compacted_fact_weight)
196 fact_weight = compacted_fact_weight[compacted_fact_id]
197
198 # assert(str(compacted_fact_id) in compacted_fact_allele_weight)
199
200 alleles_weight = compacted_fact_allele_weight[str(compacted_fact_id)]
201
202
203
204
205 print(f"{str(line)}\tFC:i:{str(fact_weight)}\tmin:{min(alleles_weight)}\tmax:{max(alleles_weight)}\tmean:{sum(alleles_weight)/len(alleles_weight)}\tAC:{';'.join(str(e) for e in alleles_weight)};")
206 # print(line+"\tFC:i:"+str(fact_weight)+"\tRC:i:"+str(alleles_weight[1])+"\tmin:i:"+str(alleles_weight[0])+"\tmax:i:"+str(alleles_weight[1])+"\tmean:i:"+str(alleles_weight[2])) ## RC is max ([1]) as we take the max (17/02/2020)
207 cpt+=1
208 sys.stderr.write(str(cpt)+" facts written\n")
209 mfile.close()
210
211 def add_pair_edge (pair_edges, left, right, abundance):
212 """
213 Add a new pair to all stored pairs. Creates cells and dictionary if needed
214 Stores a canonical representation of pairs (smallest id left)
215 """
216 if left > right: left, right = right, left # swap values if left > right, in order to avoid a -> b and -b -> -a
217 if left not in pair_edges: pair_edges[left]={}
218 if right not in pair_edges[left]: pair_edges[left][right]=0
219 pair_edges[left][right]+=abundance
220
221
222 def detects_pairs_of_linked_compacted_paths(compacted_facts, snp_to_fact_id, raw_facts_file_name, fact_overlaps):
223 """
224 given the compacted facts indexed and the raw phasing information, detects pairs of facts that are co-mapped by at least one pair of paired non compacted facts
225 returns a dictionary compacted_fact_id -> {compacted_fact_id} such that the key is smaller than all values.
226 """
227 pair_edges = {} # For each "left" (arbitrary) compacted fact (key) link to a dictionnary right compacted fact -> number of occurrences
228 mfile = open(raw_facts_file_name)
229 for line in mfile.readlines():
230 if line[0]=="#" : continue # comment
231 abundance = int(line.strip().split("=>")[1])
232 line=line.strip().split("=>")[0] # remove coverage
233 line=line.strip().split() # two pairs
234 if len(line)<2: continue # we consider only pairs of facts
235 # for the first fact, detects all compacted_facts in which it occurs:
236 left_compacted_facts = get_compatible_facts(line[0], compacted_facts, snp_to_fact_id)
237 # for the second fact, detects all compacted_facts in which it occurs:
238 right_compacted_facts = get_compatible_facts(line[1], compacted_facts, snp_to_fact_id)
239 ### if compacted facts matched, make all pairs
240 if len(left_compacted_facts)>0 and len(right_compacted_facts)>0:
241 for left_compacted_fact_id in left_compacted_facts:
242 for right_compacted_fact_id in right_compacted_facts:
243 if left_compacted_fact_id in fact_overlaps and right_compacted_fact_id in fact_overlaps[left_compacted_fact_id]:
244 continue # this pair only retreives two facts that overlap
245 if right_compacted_fact_id in fact_overlaps and left_compacted_fact_id in fact_overlaps[right_compacted_fact_id]:
246 continue # this pair only retreives two facts that overlap
247
248 add_pair_edge(pair_edges, left_compacted_fact_id, right_compacted_fact_id, abundance)
249
250 mfile.close()
251 return pair_edges
252
253 def print_pair_edges_gfa_style(pair_edges, occurrence_min=1):
254 cpt=0
255 for left_fact_id in pair_edges:
256 left_sign = ''
257 if left_fact_id<0: left_sign = '-'
258 else: left_sign = '+'
259 abs_left_fact_id = abs(left_fact_id)
260 for right_fact_id in pair_edges[left_fact_id]:
261 # the right sign is reversed as pairend reads map --> <--. Hence if right is forward on a fact we have to reverse this fact
262 right_sign = ''
263 if right_fact_id<0: right_sign = '+'
264 else: right_sign = '-'
265 abs_right_fact_id = abs(right_fact_id)
266
267
268
269 if pair_edges[left_fact_id][right_fact_id]>=occurrence_min:
270 cpt+=1
271 print ("L\t"+str(abs_left_fact_id)+"\t"+left_sign+"\t"+str(abs_right_fact_id)+"\t"+right_sign+"\t0M\tFC:i:"+str(pair_edges[left_fact_id][right_fact_id]))
272 sys.stderr.write(str(cpt)+" paired fact written\n")
273
274 def print_facts_overlaps(phasing_file):
275 fact_overlaps={}
276 mfile=open(phasing_file)
277 cpt=0
278 for line in mfile:
279 if line[0] != "L" : continue
280 cpt+=1
281 #L 17012 - 23084 + 2M
282 line=line.strip()
283 print(line)
284 # store pairs:
285 source = int(line.split()[1])
286 target = int(line.split()[3])
287 if source > target:
288 tmp = source
289 source = target
290 target = tmp
291 if source not in fact_overlaps:
292 fact_overlaps[source]=set()
293 fact_overlaps[source].add(target)
294
295 sys.stderr.write(str(cpt)+" facts overlaps written\n")
296 return fact_overlaps
297
298
299
300
301
302
303 def detects_pairs_of_edges_sharing_snp(compacted_facts, snp_to_fact_id):
304 """
305 detects which facts share at least a snp id with incompatible h/l
306 returns a dictionary fact_id -> set(fact_ids) (key is lower than any fact in the value)
307 """
308 facts_shared_snps = {}
309 for key,values in compacted_facts.items():
310 for oriented_allele in values:
311 snp_id_only=get_left_clean_snp(oriented_allele).split("_")[0][:-1] # get the snp id non oriented
312 horl = get_left_clean_snp(oriented_allele).split("_")[0][-1] # get the path 'h' or 'l' of the SNP
313 # print("snp_id_only",snp_id_only)
314 if snp_id_only in snp_to_fact_id: # the snp may be absent in case it was removed by the sequence concatenation process.
315 for fact_id in snp_to_fact_id[snp_id_only]:
316 if int(fact_id)<=int(key):
317 continue
318 fact = compacted_facts[fact_id]
319 for snp_id in fact:
320 ### checks that h or l values are disctincts between the two facts
321 if get_left_clean_snp(snp_id).split("_")[0][:-1] == snp_id_only and get_left_clean_snp(snp_id).split("_")[0][-1]!=horl: # TO VALIDATE 9/9/2019
322 if key not in facts_shared_snps: facts_shared_snps[key] = set()
323 facts_shared_snps[key].add(fact_id)
324 # for key, value in facts_shared_snps.items():
325 # print(key,value)
326 return facts_shared_snps
327
328 def print_pairs_of_edges_sharing_snp(facts_shared_snps):
329 cpt=0
330 for key, values in facts_shared_snps.items():
331 for value in values:
332 print("L\t"+key+"\t+\t"+value+"\t+\t-2M")
333 cpt+=1
334 sys.stderr.write(str(cpt)+" pairs of facts sharing at least one snp written\n")
335
336
337 def main (phasing_file,raw_facts_file_name, raw_disco_co_file_name, raw_disco_unco_file_name, read_set_id):
338 sys.stderr.write("#INDEX FACTS\n")
339 compacted_facts, snp_to_fact_id = set_indexes_from_gfa(phasing_file)
340
341 sys.stderr.write("#COMPUTE THE COMPACTED FACT COVERAGES\n")
342 compacted_fact_weight = detects_facts_coverage(compacted_facts, snp_to_fact_id, raw_facts_file_name)
343
344 sys.stderr.write("#COMPUTE THE COMPACTED FACT ALLELE COVERAGES\n")
345 compacted_fact_allele_weight=detects_allele_coverage(compacted_facts, raw_disco_co_file_name, raw_disco_unco_file_name, read_set_id)
346
347 sys.stderr.write("#PRINT COMPACTED FACTS \n")
348 print_facts(phasing_file,compacted_fact_weight, compacted_fact_allele_weight)
349
350 sys.stderr.write("#PRINT COMPACTED FACT OVERLAPS \n")
351 fact_overlaps=print_facts_overlaps(phasing_file)
352
353 sys.stderr.write("#COMPUTE PAIRS OF COMPACTED FACT GRAPH\n")
354 pair_edges=detects_pairs_of_linked_compacted_paths(compacted_facts, snp_to_fact_id, raw_facts_file_name,fact_overlaps)
355
356 sys.stderr.write("#PRINT EDGES OF COMPACTED FACT GRAPH\n")
357 print_pair_edges_gfa_style(pair_edges)
358
359 sys.stderr.write("#COMPUTE THE FACTS SHARING AT LEAST ONE SNP\n")
360 facts_shared_snps = detects_pairs_of_edges_sharing_snp(compacted_facts, snp_to_fact_id)
361 print_pairs_of_edges_sharing_snp(facts_shared_snps)
362
363
364 if __name__ == "__main__":
365 main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) # compacted_facts.gfa phased_alleles_read_set_id_1.txt discoRes_k_31_c_2_D_0_P_3_b_2_coherent.fa discoRes_k_31_c_2_D_0_P_3_b_2_uncoherent.fa 1
366
367
368