Debian Codegraph @

scripts/k3000/K3000_working_zone_no_redundant_edges.py

raw symbols SCIP
1 import sys
2 import K3000_common as kc
3
4 """
5 Given an input phased variants, select and output only "working zones"
6 A working zone is defined by
7 1/ Coverage XXX todo
8 2/ Topology: conserve only parts defined with X patterns.
9 A node is linked to at most two other nodes.
10 If a node n1 is linked to two nodes n2 and n3, then n2 and n3 have at most two sons, n4 and n5
11 """
12
13
14 def get_reverse_fact(x):
15 ''' reverse of a fact x. Example x = "4l_0;2h_3;-6h_21", reverse(x) = "6h_0;-2h_21;-4l_3"'''
16 res = ""
17 x = x.strip(";").split(";")
18 for i in range(len(x)):
19 original_id = x[-i-1]
20 if original_id[0] == "-":
21 reversed_id = original_id[1:]
22 else:
23 reversed_id = "-"+original_id
24 if i == 0:
25 value=kc.string_allele_value(reversed_id)+"_0" # With i=0, add '_0' to the value
26 else:
27 value=kc.string_allele_value(reversed_id)+"_"+kc.distance_string_value(x[-i]) # With i=1, add '_21' to the value
28 res+=value+";"
29 return res
30
31
32 def store_nodes(fact_file_name):
33 """
34 Store nodes with their min, max and mean coverages
35 """
36 nodes = {} # key= (int) node id, value variant_id
37 with open(fact_file_name) as fact_file:
38 for line in fact_file.readlines():
39 if not line: break
40 line=line.strip()
41 if line[0]=="#": continue
42 " -1145l_0;4780h_-60;-248h_-63;-7035l_-60;4077l_-59;-6265l_-60;-2978h_-69;4958h_-59;-4221h_-60;-1376l_-60;-4664l_-59;-2207h_-60;-6257l_-60;-5529l_-59;-5106h_-59;1310h_-59;-4514h_-59;3933h_-60;-5727h_-60;2325l_-60;-3976l_-59;-3363h_-60;-716l_-59;-3526h_-51;-5819h_-57;2927l_-59;-6146l_-60;-4374h_-53; => 1"
43 coverage = int(line.split()[-1])
44 for fact_id in range(len(line.split())-2): # In case of pairend facts, deal with the two facts (in this case len((line.split()) is 4
45 original_fact = line.split()[fact_id]
46 for fact in original_fact, get_reverse_fact(original_fact):
47 # print ("fact", fact)
48 for variant in fact.strip(";").split(";"):
49 # print(variant, fact)
50 signed_variant_id=variant.split("_")[0]
51 if signed_variant_id not in nodes: nodes[signed_variant_id] = 0
52 assert len(signed_variant_id)>0,line+"\n"+str(line.split()[fact_id])
53 nodes[signed_variant_id] += coverage
54 return nodes
55
56 def f(tuple, el):
57 return tuple[0]==el
58
59 def isin(list, el):
60 for tuple in list:
61 if f(tuple, el): return True
62 return False
63
64 def exists_edge(edges, node_id_1, node_id_2):
65
66 if node_id_1 in edges:
67 if isin(edges[node_id_1], node_id_2): return True
68 if node_id_2 in edges:
69 if isin(edges[node_id_2], node_id_1): return True
70 return False
71
72
73
74 def store_ordered_edges(fact_file_name, nodes):
75 """
76 Store edges
77 """
78 edges = {} # key = (signed int) node id, value = set of (signed int) target node ids with their distance (signed int). This distance may be negative as it reflects the position of the second variant wrt the end of the bubble sequence of the first.
79 # Hence a key is a couple (signed_int, signed int).
80 # rev_edges = {} # key = (signed int) node id, value = set of (signed int) target node ids (idem)
81 with open(fact_file_name) as fact_file:
82 for line in fact_file.readlines():
83 if not line: break
84 line=line.strip()
85 if line[0]=="#": continue
86 # print(line)
87 # print(len(line.split()))
88 for fact_id in range(len(line.split())-2): # In case of pairend facts, deal with the two facts (in this case len((line.split()) is 4
89 original_fact = line.split()[fact_id]
90 for used_fact in original_fact, get_reverse_fact(original_fact):
91 # sys.stderr.write(f"used fact {used_fact}\n")
92 comapped_variants = used_fact.strip(";").split(";")
93 # print(comapped_variants)
94 for i in range(len(comapped_variants)-1):
95 from_node_id = comapped_variants[i].split("_")[0]
96 to_node_id = comapped_variants[i+1].split("_")[0]
97 distance = int(comapped_variants[i+1].split("_")[1])
98
99 # add edge:
100 if from_node_id not in edges: edges[from_node_id] = set()
101 edges[from_node_id].add((to_node_id, distance))
102 # if to_node_id not in rev_edges: rev_edges[to_node_id] = set()
103 # rev_edges[to_node_id].add((from_node_id, distance))
104 # sys.stderr.write(f"{edges}\n")
105 ## Sort each list wrt distance:
106
107 for from_variant_id in edges:
108 edges[from_variant_id] = sorted(edges[from_variant_id], key=lambda x : x[1])
109
110
111 return edges
112
113
114 def remove_transitive_redundant(edges):
115 nb_removed = 0
116 nb_total = 0
117 nb_removed = 0
118 nb_total = 0
119 # new_edges = {}
120 for from_variant_id in edges:
121 # if an ordered list contains more than 2 children (A->B and A->C for instance), remove A->C if B->C exists somewhere else
122 updated_list = set()
123 updated_list.add(edges[from_variant_id][0]) # the first one stays, whatever.
124 for id_in_edges in range(len(edges[from_variant_id])-1):
125 nb_total+=1
126 cur_var = edges[from_variant_id][id_in_edges]
127 next_var = edges[from_variant_id][id_in_edges+1]
128 if cur_var[1]==next_var[1]: # same distance to start, we keep it
129 updated_list.add(edges[from_variant_id][id_in_edges+1])
130 continue
131 if not exists_edge(edges, cur_var[0], next_var[0]): # this is a not a transitive edge, we keep it
132 updated_list.add(edges[from_variant_id][id_in_edges+1])
133 else:
134 # sys.stderr.write(f"removed {from_variant_id} -> {edges[from_variant_id][id_in_edges+1]}\n")
135 nb_removed+=1
136 updated_list = sorted(updated_list, key=lambda x : x[1])
137 # sys.stderr.write(f"avant {from_variant_id} -> {edges[from_variant_id]}\n")
138 edges[from_variant_id]=updated_list
139 # sys.stderr.write(f"apres {from_variant_id} -> {new_edges[i][from_variant_id]}\n")
140 sys.stderr.write(f"Removed {nb_removed} transitive redundant edges among {nb_total}\n")
141 return nb_removed
142 # edges = new_edges
143
144 def keep_only_consecutive_edges(edges):
145 nb_total = 0
146 nb_removed = 0
147 for from_variant_id in edges:
148 # if an ordered list contains more than 2 children (A->B and A->C for instance), conserve the closest one
149 updated_list = set()
150 updated_list.add(edges[from_variant_id][0]) # the first one stays, whatever.
151 next_id = 0
152 while True: # add all soon with the same distance
153 next_id += 1
154 if next_id == len(edges[from_variant_id]): break
155 if edges[from_variant_id][next_id][1] == edges[from_variant_id][0][1]:
156 updated_list.add(edges[from_variant_id][next_id])
157 else: break
158 nb_total += len(edges[from_variant_id])
159 nb_removed += len(edges[from_variant_id])-next_id
160 updated_list = sorted(updated_list, key=lambda x : x[1])
161 # sys.stderr.write(f"avant {from_variant_id} -> {edges[from_variant_id]}\n")
162 edges[from_variant_id]=updated_list
163 # sys.stderr.write(f"apres {from_variant_id} -> {new_edges[i][from_variant_id]}\n")
164 sys.stderr.write(f"Removed {nb_removed} among {nb_total}\n")
165
166
167
168 def remove_distances(edges):
169 ## remove distances:
170 for from_variant_id in edges:
171 id_only_list = set()
172 for to_variant_id, distance in edges[from_variant_id]:
173 id_only_list.add(to_variant_id)
174 edges[from_variant_id] = id_only_list
175
176
177 def remove_tips(edges, nodes):
178 iodegree = {} # key = signed variant id, value = (At least one incoming edge, at least one ougoing edge)
179 ## Stores for all variants, if they have at least one incoming edge and at least one ougoing edge
180 for source_id, target_ids in edges.items():
181 if source_id not in nodes: continue # were removed
182 if source_id not in iodegree: iodegree[source_id] = [False,True]
183 else: iodegree[source_id][1] = True
184 for target_id in target_ids:
185 if target_id not in nodes: continue # were removed
186 if target_id not in iodegree: iodegree[target_id] = [True,False]
187 else: iodegree[target_id][0] = True
188
189 nb_tips_removed = 0
190 to_remove = set()
191 for node in nodes:
192 if node not in iodegree:
193 to_remove.add(node)
194 nb_tips_removed+=1
195 continue
196 if iodegree[node] != [True, True]:
197 to_remove.add(node)
198 nb_tips_removed+=1
199 continue
200 for node_to_remove in to_remove:
201 del nodes[node_to_remove]
202 sys.stderr.write(f"Removed {nb_tips_removed} tips\n")
203 return nb_tips_removed
204 # sys.exit()
205
206 def working_zones(edges, nodes):
207 """
208 if a node has 3 or more children or 3 or more ancestors, remove all of them
209 """
210 removed=0
211 for from_variant_id in edges:
212 if len(edges[from_variant_id]) > 2:
213 for to_variant_id in edges[from_variant_id]:
214 if to_variant_id in nodes:
215 removed+=1
216 del nodes[to_variant_id]
217 sys.stderr.write(f"Working zones, children removed {removed} non bi-allelic nodes\n")
218
219
220
221 ### ancestors. We first have to store them
222
223 input_edges = {} # key = son, value = list of ancestors
224 for source_id, target_ids in edges.items():
225 if source_id not in nodes : continue
226 for target_id in target_ids:
227 if target_id not in nodes: continue
228 if target_id not in input_edges: input_edges[target_id] = set()
229 input_edges[target_id].add(source_id)
230
231 removed=0
232 for from_variant_id in input_edges:
233 if len(input_edges[from_variant_id]) > 2:
234 for to_variant_id in input_edges[from_variant_id]:
235 if to_variant_id in nodes:
236 removed+=1
237 del nodes[to_variant_id]
238 sys.stderr.write(f"Working zones, ancestor removed {removed} non bi-allelic nodes\n")
239
240
241
242 def existing_fact(fact, nodes, edges):
243 """
244 Given a fact as:
245 -1145l_0;4780h_-60;-248h_-63;-7035l_-60;4077l_-59;-6265l_-60;-2978h_-69;4958h_-59;-4221h_-60;-1376l_-60;
246 returns True if
247 1/ all nodes exist in the gfa
248 2/ all edges exist in the gfa
249 else return False
250 """
251
252 s_fact = fact.strip(";").split(";")
253
254 ### Nodes
255 for shift_node in s_fact:
256 if shift_node.split('_')[0] not in nodes:
257 # sys.stderr.write(f"{shift_node.split('_')[0]} not in nodes\n")
258 return False
259 ### Edges
260 for i in range(len(s_fact)-1):
261 source = s_fact[i].split('_')[0]
262 target = s_fact[i+1].split('_')[0]
263 if source in edges and target in edges[source]: continue
264 if target in edges and source in edges[target]: continue
265 return False
266 return True
267
268 def print_as_facts(nodes, edges, fact_file_name):
269 """
270 Store nodes with their min, max and mean coverages
271 """
272 with open(fact_file_name) as fact_file:
273 for line in fact_file.readlines():
274 if not line: break
275 line=line.strip()
276 if line[0]=="#": continue
277 " -1145l_0;4780h_-60;-248h_-63;-7035l_-60;4077l_-59;-6265l_-60;-2978h_-69;4958h_-59;-4221h_-60;-1376l_-60;-4664l_-59;-2207h_-60;-6257l_-60;-5529l_-59;-5106h_-59;1310h_-59;-4514h_-59;3933h_-60;-5727h_-60;2325l_-60;-3976l_-59;-3363h_-60;-716l_-59;-3526h_-51;-5819h_-57;2927l_-59;-6146l_-60;-4374h_-53; => 1"
278 coverage = int(line.split()[-1])
279 printed_something = False
280 for fact_id in range(len(line.split())-2): # In case of pairend facts, deal with the two facts (in this case len((line.split()) is 4
281 original_fact = line.split()[fact_id]
282 if existing_fact(original_fact, nodes, edges):
283 print(original_fact, ' ', end='')
284 printed_something = True
285 if printed_something:
286 print ("=> ", line.split()[-1])
287
288
289
290 def print_as_gfa(nodes, edges):
291 # cov_threshold=10
292 # index nodes:
293 node_id_to_variant_id = {} # key = node_id (1,2, ..., n) value = variant_id (eg. -14h)
294 variant_id_to_node_id = {} # key = variant_id (eg. -14h) value = node_id (eg. 2)
295 node_id=1
296 for node in nodes:
297 node_id_to_variant_id[node_id] = node
298 variant_id_to_node_id[node] = node_id
299 node_id+=1
300
301
302 nb_nodes = 0
303 for node_id in node_id_to_variant_id:
304 nb_nodes+=1
305 # if nodes[node_id_to_variant_id[node_id]] < cov_threshold: continue
306 print("S\t"+str(node_id)+"\t"+str(node_id_to_variant_id[node_id])+"\tRC:i:"+str(nodes[node_id_to_variant_id[node_id]]))
307
308 nb_edges = 0
309 for from_variant_id in edges:
310 if from_variant_id not in nodes: continue # had been removed
311 # if nodes[from_variant_id] < cov_threshold: continue # too low cove
312 for to_variant_id in edges[from_variant_id]:
313 if to_variant_id not in nodes: continue # had been removed
314 # if nodes[to_variant_id] < cov_threshold: continue # too low cove
315 nb_edges+=1
316 print("L\t"+str(variant_id_to_node_id[from_variant_id])+"\t+\t"+str(variant_id_to_node_id[to_variant_id])+"\t+\t0M")
317
318 sys.stderr.write(f"Printed {nb_nodes} nodes and {nb_edges} edges\n")
319
320 def main():
321 outgfa = False
322 if len(sys.argv) > 2 and sys.argv[2]=="--gfa":
323 outgfa=True
324 sys.stderr.write(f"Output data as a gfa graph\n")
325 nodes = store_nodes(sys.argv[1])
326 edges = store_ordered_edges(sys.argv[1], nodes)
327 keep_only_consecutive_edges(edges)
328
329 remove_distances(edges)
330 # remove_tips(edges, nodes)
331 working_zones(edges, nodes)
332 # remove_tips(edges, nodes)
333 if outgfa:
334 print_as_gfa(nodes, edges)
335 else:
336 print_as_facts(nodes, edges, sys.argv[1])
337
338
339 if __name__ == '__main__':
340 main()