Debian Codegraph @

tools/kissnp2/src/Bubble.cpp

raw
1 /*****************************************************************************
2 * discoSnp++: discovering polymorphism from raw unassembled NGS reads
3 * A tool from the GATB (Genome Assembly Tool Box)
4 * Copyright (C) 2014 INRIA
5 * Authors: P.Peterlongo, E.Drezen
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16 *
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *****************************************************************************/
20
21 #include <Bubble.hpp>
22 #include <Filter.hpp>
23
24 #include <string>
25 using namespace std;
26
27 #define DEBUG(a) // a
28 const char* BubbleFinder::STR_BFS_MAX_DEPTH = "-bfs-max-depth";
29 const char* BubbleFinder::STR_BFS_MAX_BREADTH = "-bfs-max-breadth";
30
31
32
33
34
35 /*********************************************************************
36 ** METHOD :
37 ** PURPOSE :
38 ** INPUT :
39 ** OUTPUT :
40 ** RETURN :
41 ** REMARKS :
42 *********************************************************************/
43 BubbleFinder::BubbleFinder (IProperties* props, const Graph& graph, Stats& stats)
44 : graph(graph), stats(stats), _terminator(0), _outputBank(0), _traversal(0), _synchronizer(0)
45 {
46 assert (props != 0);
47
48 /** We retrieve the kmer size. */
49 sizeKmer = graph.getKmerSize();
50
51 /** We set attributes according to user choice. */
52 accept_low = props->get (STR_DISCOSNP_LOW_COMPLEXITY) != 0;
53 authorised_branching = props->getInt (STR_DISCOSNP_AUTHORISED_BRANCHING);
54 max_indel_size = props->getInt (STR_MAX_INDEL_SIZE);
55 max_indel_ambiguity = props->getInt (STR_MAX_AMBIGOUS_INDELS);
56 max_polymorphism = props->getInt (STR_MAX_POLYMORPHISM);
57 max_sym_branches = props->getInt (STR_MAX_SYMMETRICAL_CROSSROADS);
58 accept_truncated_bubbles = props->get (STR_RADSEQ) != 0;
59 max_truncated_path_length_difference = props->getInt (STR_MAX_TRUNCATED_PATH_LENGTH_DIFFERENCE);
60
61 max_depth = props->getInt (STR_BFS_MAX_DEPTH);
62 max_recursion_depth=1000; // TODO: parameter?
63
64 max_breadth = props->getInt (STR_BFS_MAX_BREADTH);
65 /** We set the traversal kind. */
66 traversalKind = TRAVERSAL_NONE;
67 if (props->get(STR_DISCOSNP_TRAVERSAL_UNITIG) != 0) { traversalKind = TRAVERSAL_UNITIG; }
68 if (props->get(STR_DISCOSNP_TRAVERSAL_CONTIG) != 0) { traversalKind = TRAVERSAL_CONTIG; }
69
70 /** We set the name of the output file. */
71 stringstream ss;
72 ss << props->getStr(STR_URI_OUTPUT);// << "_k_" << sizeKmer << "_c_" << graph.getInfo().getInt("abundance");
73 // ss << "_D_"<<max_indel_size;
74 ss << ".fa";
75
76 /** We set the output file. So far, we force FASTA output usage, but we could make it configurable. */
77 setOutputBank (new BankFasta (ss.str()));
78
79 /** We need a synchronizer for dumping high/low sequences into the output bank in an atomic way
80 * (ie avoids potential issues with interleaved high/low sequences in multithread execution). */
81 setSynchronizer (System::thread().newSynchronizer());
82
83 /** We set a terminator here. Note that the construction will set up its inner map
84 * with the branching nodes as keys. Then, these keys can be shared with other instances
85 * of BranchingTerminator, which leads to less memory usage since this branching nodes keys
86 * is not supposed to changed. */
87 setTerminator (new BranchingTerminator(graph));
88 }
89
90 /*********************************************************************
91 ** METHOD :
92 ** PURPOSE :
93 ** INPUT :
94 ** OUTPUT :
95 ** RETURN :
96 ** REMARKS :
97 *********************************************************************/
98 BubbleFinder::BubbleFinder (const BubbleFinder& bf)
99 : graph(bf.graph), stats(bf.stats), _terminator(0), _outputBank(0), _traversal(0), _synchronizer(0)
100 {
101 sizeKmer = bf.sizeKmer;
102 accept_low = bf.accept_low;
103 authorised_branching = bf.authorised_branching;
104 max_indel_size = bf.max_indel_size;
105 max_indel_ambiguity = bf.max_indel_ambiguity;
106 max_polymorphism = bf.max_polymorphism;
107 max_sym_branches = bf.max_sym_branches;
108 max_depth = bf.max_depth;
109 max_recursion_depth = bf.max_recursion_depth;
110 max_breadth = bf.max_breadth;
111 traversalKind = bf.traversalKind;
112 breadth_first_queue = bf.breadth_first_queue;
113 accept_truncated_bubbles = bf.accept_truncated_bubbles;
114
115 /** Copy by reference (not by value). */
116 setOutputBank (bf._outputBank);
117 setSynchronizer (bf._synchronizer);
118
119 /** NOT A TRUE COPY: each instance created by this constructor will have its own
120 * Traversal/Terminator instances. */
121 setTerminator (new BranchingTerminator(*(bf._terminator)));
122 setTraversal (Traversal::create (traversalKind, graph, *_terminator, 0, bf.max_depth, bf.max_breadth));
123 }
124
125 /*********************************************************************
126 ** METHOD :
127 ** PURPOSE :
128 ** INPUT :
129 ** OUTPUT :
130 ** RETURN :
131 ** REMARKS :
132 *********************************************************************/
133 BubbleFinder::~BubbleFinder ()
134 {
135 setOutputBank (0);
136 setSynchronizer (0);
137 setTerminator (0);
138 setTraversal (0);
139 }
140
141
142 /*********************************************************************
143 ** METHOD :
144 ** PURPOSE :
145 ** INPUT :
146 ** OUTPUT :
147 ** RETURN : A unique successor of a node at depth d if exist. Else return nullptr
148 ** REMARKS : DEPRECATED
149 *********************************************************************/
150 Node get_successors (const Graph& graph, Node& node, const int depth){
151 GraphVector<Node> successors = graph.successors (node);
152 if(successors.size() != 1) return Node(~0); // depth 1
153 for (int d=2; d<depth; d++){
154 successors = graph.successors (successors[0]);
155 if(successors.size() != 1) return Node(~0);
156 }
157 return successors[0];
158 }
159
160
161 void BubbleFinder::start_snp_prediction(){
162 if (max_polymorphism<1) { // if the parameter P is set to 0, do not output any SNP
163 return;
164 }
165 bubble.polymorphism_type="SNP";
166 bubble.type=0;
167 bubble.extended_string[0]="";
168 bubble.extended_string[1]="";
169 Node notzero = Node(~0);
170 Node notzero2 = Node(~0);
171 expand (1,bubble.begin[0], bubble.begin[1], notzero, notzero2, "","", 0, 0);
172 }
173
174 /** Transform a nucleotide in ASCII form into an integer form as:
175 * - A=0
176 * - C=1
177 * - T=2
178 * - G=3
179 * \param[in] nt : the nucleotide in ASCII
180 * \return the translated nucleotide */
181 static int NT2int(char nt) { return (nt>>1)&3; }
182
183
184 void clear_queue_pair( std::queue<pair<Node, string> > &q )
185 {
186 std::queue<pair<Node, string> > empty;
187 std::swap( q, empty );
188 }
189
190 /*********************************************************************
191 ** METHOD :
192 ** PURPOSE :
193 ** INPUT :
194 ** OUTPUT :
195 ** RETURN :
196 ** REMARKS : breadth first search (queue already stored in the bubbleFinder class.
197 Then limit the queue size. Thus early possible bubbles are tested even if longer insers are too complex to be treated.
198 *********************************************************************/
199 void BubbleFinder::start_indel_prediction(){
200 if (max_indel_size==0)
201 return; // no need to try to find indels
202 bubble.type=1;
203 // Consider a deletion in the upper path (avance on the lower) and then try the opposite
204
205 Node current;
206 int found_del_size=max_indel_size+10; // No indel found for now (we could also use MAXINT)
207
208
209 for(int extended_path_id=0;extended_path_id<2;extended_path_id++){
210 // nb_snp_start++;
211 // cout<<"nb_snp_start "<<nb_snp_start<<endl;
212 current= bubble.begin[extended_path_id]; // 0 or 1
213 const char end_insertion=graph.toString(bubble.begin[(extended_path_id+1)%2])[sizeKmer-1];
214
215 DEBUG((cout<<"start indel finding with "<<end_insertion<<" extending path "<<extended_path_id<<endl));
216 string tried_extension;
217 breadth_first_queue.push(pair<Node, string>(current, string("")));
218 while(!breadth_first_queue.empty()){
219 // TODO maybe we could stop the whole breadth first search in case a bubble was found at a found_del_size and the current insert_size is <= found_del_size-2
220 DEBUG((cout<<"queue size "<<breadth_first_queue.size()<<" max_breadth "<<max_recursion_depth<<endl));
221 if(breadth_first_queue.size()>max_recursion_depth){
222 clear_queue_pair(breadth_first_queue);
223 break; // This bubble is too complex, we stop.
224 }
225 pair<Node,string> element=breadth_first_queue.front();
226 breadth_first_queue.pop();
227 DEBUG((cout<<"and now queue size "<<breadth_first_queue.size()<<endl));
228 current = element.first;
229 tried_extension=element.second;
230 int insert_size = tried_extension.length();
231 DEBUG((cout<<"insert size "<<insert_size<<endl));
232 /** if we already found an indel bubble: we need to check to other possible bubbles of the same size (indels of the same size) */
233 /** however, if we reach a node at depth lower than the succesfull bubble, as no other bubbles are stored in the queue with */
234 /** a higher length (property of the queue), then we can safelly stop the breadth first search */
235 if (insert_size == found_del_size-1){
236 clear_queue_pair(breadth_first_queue);
237 break; // ...and stop
238 }
239 /** checks if an indel was already found at a lower depth */
240 // TODO: maybe impossible, to check.
241 if (insert_size > found_del_size) {
242 continue;
243 }
244 if (end_insertion == graph.toString(current)[sizeKmer-1] ){
245 DEBUG((cout<<"start an INDEL detection "<<endl));
246 bubble.polymorphism_type="INDEL";//+(insert_size);
247
248 /** try to close the bubble from the two initial (with one extended) node */
249 Node notzero = Node(~0);
250 Node notzero2 = Node(~0);
251 if(extended_path_id==0?
252 expand (1, current, bubble.begin[1], notzero, notzero2,tried_extension,"", 0, 0)
253 :
254 expand (1, bubble.begin[0], current, notzero, notzero2, "",tried_extension, 0, 0)){
255 found_del_size=insert_size; // an extension was found. We'll check if other extensions with same size can be found.
256 continue; // we won't add stuffs in the queue, we can continue.
257 }
258 }
259
260 if(
261 insert_size == found_del_size || // no need to try longer extension than the one already found.
262 insert_size == max_indel_size // no need to try longer extension than the maximal length
263 ) continue;
264 GraphVector<Node> successors = graph.successors (current);
265
266
267 /** No branching authorized in the insertion mode. */
268 if (successors.size()>1 && authorised_branching==0) {
269 clear_queue_pair(breadth_first_queue);
270 break; // ...and stop
271 }
272
273 /** checks if a successor with the good starting letter (the one potentially closing the indel) exists */
274 bool exists;
275 Node successor = graph.successor(current,(Nucleotide)NT2int(end_insertion),exists);
276 if(exists)
277 breadth_first_queue.push(pair<Node, string>(successor,tried_extension+end_insertion));
278
279 /** then checks for the other possible extensions */
280 for (size_t successor_id=0; successor_id<successors.size() ; successor_id++) {
281 if(graph.toString(successors[successor_id])[sizeKmer-1] != end_insertion)
282 breadth_first_queue.push(pair<Node, string>(successors[successor_id], tried_extension+graph.toString(successors[successor_id])[sizeKmer-1]));
283 }
284
285
286 }
287 }
288 }
289
290
291 /*********************************************************************
292 ** METHOD :
293 ** PURPOSE :
294 ** INPUT :
295 ** OUTPUT :
296 ** RETURN :
297 ** REMARKS :
298 *********************************************************************/
299 template<>
300 void BubbleFinder::start (Bubble& bubble, const BranchingNode& node)
301 {
302 this->bubble=bubble;
303 DEBUG ((cout << "[BubbleSNPFinder::start] BRANCHING NODE " << graph.toString(node) << endl));
304 DEBUG ((cout << "[BubbleSNPFinder::start] bubble.isCanonical " << bubble.isCanonical << endl));
305 /** We compute the successors of the node. */
306 GraphVector<Node> successors = graph.successors((Node&)node);
307 DEBUG((cout << "successor size"<<successors.size()<<endl));
308 if(successors.size()<2) return; // false branching (no extention in one or the other direction).
309 for (size_t i=0; i<successors.size(); i++)
310 {
311 bubble.begin[0] = successors[i];
312
313 // In case two or more branching nodes lead to the same extensions : (b1 -> s1 and b1 -> s2 and b2 -> s1 and b2 -> s2), then
314 // we need to construct the bubble s1... s2... from only one of the two branching nodes b1 or b2.
315 // We chose the smallest from all the possible starting nodes to start a bubble.
316 GraphVector<Node> predecessors = graph.predecessors (successors[i]);
317
318
319 if (predecessors.size()>1)
320 {
321 for (size_t k=0; k<predecessors.size(); k++) { if (predecessors[k].kmer < node.kmer) { return; } }
322 }
323
324
325
326 for (size_t j=i+1; j<successors.size(); j++)
327 {
328 bubble.begin[1] = successors[j];
329 bubble.isCanonical =false;
330 bubble.closed_bubble=false;
331 bubble.truncated =false;
332 /*************************************************/
333 /** Try a SNP **/
334 /*************************************************/
335 DEBUG ((cout << " start SNP detection with " << graph.toString(bubble.begin[0]) <<" and "<< graph.toString(bubble.begin[1]) << endl));
336 start_snp_prediction();
337
338 /*************************************************/
339 /** Try an isolated insertion **/
340 /*************************************************/
341 bubble.isCanonical=false;
342 bubble.closed_bubble=false;
343 DEBUG ((cout << " start indel detection with " << graph.toString(bubble.begin[0]) <<" and "<< graph.toString(bubble.begin[1]) << endl));
344 start_indel_prediction();
345 }
346 }
347 }
348
349
350 /*********************************************************************
351 ** METHOD : Heart of the expand method. Factorisation of code, used twice in the expand method.
352 ** PURPOSE :
353 ** INPUT :
354 ** OUTPUT :
355 ** RETURN : True if expended, else return false
356 ** REMARKS :
357 *********************************************************************/
358 bool BubbleFinder::expand_heart(
359 const int nb_polymorphism,
360 Node& nextNode1,
361 Node& nextNode2,
362 Node& node1,
363 Node& node2,
364 Node& previousNode1,
365 Node& previousNode2,
366 string local_extended_string1,
367 string local_extended_string2,
368 int sym_branches,
369 int stack_size,
370 const int disymetrical_end_size=0){
371 /** We check whether the new nodes are different from previous ones. */
372 bool checkPrevious =
373 checkNodesDiff (previousNode1, node1, nextNode1) &&
374 checkNodesDiff (previousNode2, node2, nextNode2);
375
376 if (!checkPrevious){return false;}
377
378 bool dumped_bubble=false;
379
380
381 /************************************************************/
382 /** RECURSION FINISHED **/
383 /************************************************************/
384 if(nextNode1 == nextNode2)
385 {
386 bubble.closed_bubble=true;
387 DEBUG((cout<<"last node1.value "<<graph.toString(node1)<<" node2.value "<<graph.toString(node2)<<endl));
388 /** We check the branching properties of the next kmers. */
389
390
391 /** We finish the bubble with last distinct nodes. */
392 bubble.end[0] = node1;
393 bubble.end[1] = node2;
394
395 /** if the Bubble is truncated, it must be Canonical **/
396 if (graph.successors(node1).size()==0)
397 {
398 bubble.isCanonical = true ;
399 }
400 else
401 {
402 checkPath();
403 }
404
405 checkLowComplexity();
406 /** We check several conditions (the first path vs. its revcomp and low complexity). */
407 if (bubble.isCanonical && bubble.acceptable_complexity && checkRepeatSize(local_extended_string1, local_extended_string2))
408 {
409
410 /** We extend the bubble on the left and right (unitigs or contigs). */
411 extend ();
412 /** We got all the information about the bubble, we finish it. */
413 bubble.extended_string[0] = local_extended_string1;
414 bubble.extended_string[1] = local_extended_string2;
415 bubble.final_nb_polymorphism=nb_polymorphism;
416 finish (disymetrical_end_size);
417 dumped_bubble =true;
418 }
419 }
420
421 /************************************************************/
422 /** RECURSION CONTINUES **/
423 /************************************************************/
424 else
425 {
426
427 const Nucleotide added_nucleotide1 = graph.getNT(nextNode1,sizeKmer-1);
428 const Nucleotide added_nucleotide2 = graph.getNT(nextNode2,sizeKmer-1);
429 DEBUG((cout<<"continue with nextNode1.value "<<graph.toString(nextNode1)<<" nextNode2.value "<<graph.toString(nextNode2)<<endl));
430 /** We call recursively the method (recursion on 'pos'). */
431 dumped_bubble = expand (nb_polymorphism,
432 nextNode1,
433 nextNode2,
434 node1,
435 node2,
436 local_extended_string1+ascii(added_nucleotide1),
437 local_extended_string2+ascii(added_nucleotide2),
438 sym_branches,
439 stack_size+1);
440
441 // /** There's only one branch to expand if we keep non branching SNPs only, therefore we can safely stop the for loop */
442 // if ( authorised_branching==0 || authorised_branching==1 ) { break; }
443 }
444 return dumped_bubble;
445 }
446
447
448
449 /*********************************************************************
450 ** METHOD :
451 ** PURPOSE : Extension of a single single node. Extension is non branching and stops after max_depth path. Returns true if the created path if smaller or equal to max_depth.
452 ** INPUT :
453 ** OUTPUT :
454 ** RETURN : True if expended, else return false
455 ** REMARKS :
456 *********************************************************************/
457 bool BubbleFinder::expand_one_simple_path (
458 Node& node, // Node currently tested
459 string& local_extended_string, // add nucleotides to this string
460 const int max_depth, // maximal size of the path
461 int & size_extension // Obtained size of the extension
462 )
463 {
464 size_extension=0;
465 GraphVector < Node > successors;
466 for (int depth=0;depth<max_depth+1;depth++){
467 successors = graph.successors (node); // get next node
468 if (successors.size()>1) return false; // right branching, returns false
469 if (graph.indegree(node)>1) return false; // left branching, returns false.
470 if (successors.size()==0) return true; // path ends, return true
471 node = successors[0];
472 local_extended_string+=ascii(graph.getNT(successors[0],sizeKmer-1));
473 size_extension++;
474 }
475 // the loop stops one step latter, meaning that if we arrive here, the path if of length max_depth+1, longer than max_depth.
476 return false;
477 }
478
479
480
481
482 /*********************************************************************
483 ** METHOD :
484 ** PURPOSE :
485 ** INPUT :
486 ** OUTPUT :
487 ** RETURN : True if expended, else return false
488 ** REMARKS :
489 *********************************************************************/
490 bool BubbleFinder::expand (
491 const int nb_polymorphism,
492 Node node1, // Node currently tested
493 Node node2, // Node currently tested
494 Node previousNode1, // node before the one tested
495 Node previousNode2, // node before the one tested
496 string local_extended_string1,
497 string local_extended_string2,
498 int sym_branches, // number of symmetrically branchings traversed (used in b 2 mode)
499 int stack_size
500 )
501 {
502 DEBUG((cout<<" *"<<stack_size<<"+"<<endl));
503 DEBUG((cout<<"expand with node1.value "<<graph.toString(node1)<<" node2.value "<<graph.toString(node2)<<endl));
504 DEBUG((cout<<"expand with local_extended_string1 "<<local_extended_string1<<" local_extended_string2 "<<local_extended_string2<<endl));
505
506
507 /****************************************************************************/
508 /**************** OPTIMIZATION : AVOID RECURSIONS ***************************/
509 GraphVector < pair<Node,Node> > successors;
510 while (true){
511 if (checkBranching(node1,node2, sym_branches) == false) return false; // no possibility to continue
512 successors = graph.successors (node1, node2); // get next two nodes
513 if (successors.size() != 1) break; // no more iterative programming
514 if (successors[0].first == successors[0].second) {
515 break; // ended bubble
516 }
517
518 bool checkPrevious =
519 checkNodesDiff (previousNode1, node1, successors[0].first) &&
520 checkNodesDiff (previousNode2, node2, successors[0].second);
521 if (!checkPrevious){return false;}
522
523 local_extended_string1+=ascii(graph.getNT(successors[0].first,sizeKmer-1)); // extend upper sequence with new character
524 local_extended_string2+=ascii(graph.getNT(successors[0].second,sizeKmer-1));// extend lower sequence with new character
525 previousNode1 = node1; // change currents and previous nodes
526 previousNode2 = node2; // change currents and previous nodes
527 node1 = successors[0].first; // change currents and previous nodes
528 node2 = successors[0].second; // change currents and previous nodes
529 }
530
531 /**************** END OPTIMIZATION *****************************************/
532 /****************************************************************************/
533
534 /** We may have to stop the extension according to the branching mode. */
535 if (checkBranching(node1,node2, sym_branches) == false) {
536 return false;
537 }
538
539 bool dumped_bubble=false;
540
541
542 /*************************************************/
543 /** RADseq: We check if the bubble is truncated **/
544 /*************************************************/
545 int equal_zone_lenght=3; // TODO: make a parameter please.
546 const int suc1=graph.successors(node1).size();
547 const int suc2=graph.successors(node2).size();
548 if(accept_truncated_bubbles && (suc1==0 || suc2==0)) // If end of at least the two paths and if one asks for truncated bubbles.
549 {
550 //We check that the last 3 nt are similar on the two truncated paths
551 for (int i=0;i<equal_zone_lenght;i++)
552 if ( graph.getNT(node1, sizeKmer-i-1)!=graph.getNT(node2, sizeKmer-i-1)){
553 return false;
554 }
555 int disymetrical_end_size=0;
556 // First case: only upper path ends
557 if (suc2 == 1 && expand_one_simple_path (node2, local_extended_string2, max_truncated_path_length_difference, disymetrical_end_size)) {
558 disymetrical_end_size=-disymetrical_end_size;
559 bubble.truncated =true;
560 }
561
562 // second case: only lower path ends
563 if (suc1 == 1 && expand_one_simple_path (node1, local_extended_string1, max_truncated_path_length_difference, disymetrical_end_size)) {
564 bubble.truncated =true;
565 }
566
567 // third case: the both paths end, nothing additional to be checked.
568 if (suc1 == suc2) {
569 bubble.truncated =true;
570 }
571
572 if (bubble.truncated){
573 /** We call expand_heart with a false nextnode **/
574 Node notzero = Node(~0);
575 dumped_bubble = expand_heart(nb_polymorphism,notzero,notzero,node1,node2,previousNode1,previousNode2,local_extended_string1,local_extended_string2,sym_branches, stack_size,disymetrical_end_size);
576 }
577 }
578
579 /** We get the common successors of node1 and node2. */
580 /** Returns the successors of two nodes, ie with the same transition nucleotide from both nodes. */
581 // GraphVector < pair<Node,Node> > successors = graph.successors (node1, node2);
582 DEBUG((cout<<"successors size "<<successors.size()<<endl));
583
584
585 size_t i;
586
587 /***************************************************/
588 /** authorizng some symetrical croassroads **/
589 /** We loop over the successors of the two nodes. **/
590 /***************************************************/
591 for (i=0; i<successors.size(); i++)
592 {
593
594 /** extend the bubble with the couple of nodes */
595 dumped_bubble = expand_heart(nb_polymorphism,successors[i].first,successors[i].second,node1,node2,previousNode1,previousNode2,local_extended_string1,local_extended_string2,sym_branches,
596 stack_size);
597
598 /** B 2 special case: if two or more symmetrical branching close a bubble, the output is redundant. **/
599 /** Thus, if successors[i].first = successors[i].second and if the bubble is dumped, we stop **/
600 if (successors[i].first == successors[i].second && dumped_bubble) break;
601
602
603 // /** Stop as soon as a bubble is dumped */
604 // VERSION 2.2.5: commented this break line. Enable to explore all possible symmetrical paths, even in case of success on one of the paths.
605 if(dumped_bubble) break;
606 }
607
608 DEBUG((cout<<"stop try"<<endl));
609 if(dumped_bubble) {
610 return true;
611 }
612
613 /** NON DUMPED BUBBLE */
614 /** if the bubble was closed and was not dumped, it means that it was not canonical. It will be find latter thus we should not find close SNPs from this bubble. */
615 if(bubble.closed_bubble){
616 return true;
617 }
618
619 /** Maybe we can search for a close SNP */
620 if (nb_polymorphism < max_polymorphism && bubble.type==0) {
621 DEBUG((cout<<"try with a new polymorphism ("<<nb_polymorphism<<") with node1.value "<<graph.toString(node1)<<" node2.value "<<graph.toString(node2)<<endl));
622
623 GraphVector < Node > successors1 = graph.successors (node1);
624 GraphVector < Node > successors2 = graph.successors (node2);
625
626
627 /** We loop over the successors of the two nodes found with distinct extending nucleotides. */
628 for (size_t i1=0; i1<successors1.size(); i1++){
629 for (size_t i2=0; i2<successors2.size(); i2++){
630 if ( graph.getNT(successors1[i1],sizeKmer-1) == graph.getNT(successors2[i2],sizeKmer-1))
631 continue; // This has already been tested in previous loop
632 DEBUG((cout<<"TRYING"<<endl));
633 dumped_bubble |= expand_heart(nb_polymorphism+1,successors1[i1],successors2[i2],node1,node2,previousNode1,previousNode2,local_extended_string1,local_extended_string2,sym_branches ,
634 stack_size);
635 /******************************************************************************************* **/
636 /** Un-understood Sept 2015 (Pierre). Removed and replaced by the next "break" **/
637 /** if the bubble is finished with THIS couple of tested successors, we stop here.**/
638 /** if we don't check this, in b 2 mode we may close a bubble with several distinct couple of node and thus create redondant bubbles **/
639 /** if(dumped_bubble && successors1[i1]==successors2[i2]) break; **/
640 /******************************************************************************************* **/
641 if(dumped_bubble || bubble.closed_bubble) break;
642 }
643 if(dumped_bubble || bubble.closed_bubble) break;
644 }
645 }
646 return dumped_bubble || bubble.closed_bubble;
647 }
648
649
650
651 /*********************************************************************
652 ** METHOD :
653 ** PURPOSE :
654 ** INPUT :
655 ** OUTPUT :
656 ** RETURN :
657 ** REMARKS : In case of indel, the extended nodes are those from the full path of length 2k-1
658 *********************************************************************/
659 void BubbleFinder::extend ()
660 {
661 Nucleotide closureLeft = NUCL_UNKNOWN;
662 Nucleotide closureRight = NUCL_UNKNOWN;
663
664 /** We may have to extend the bubble according to the user choice. */
665 if (traversalKind != TRAVERSAL_NONE)
666 {
667 /** We ask for the predecessors of the first node and successors of the last node. */
668
669 GraphVector<Node> successors = graph.successors (bubble.end[0]);
670 GraphVector<Node> predecessors = graph.predecessors (bubble.begin[0]);
671
672 /** We need to reset branching nodes between extensions in case of overlapping extensions. */
673 _terminator->reset ();
674
675 /** If unique, we keep the left/right extensions. */
676 if (successors.size()==1)
677 {
678 /** We compute right extension of the node. */
679 closureRight = graph.getNT (successors [0], sizeKmer-1);
680 _traversal->traverse (successors[0], DIR_OUTCOMING, bubble.extensionRight);
681 bubble.divergenceRight = _traversal->getBubbles().empty() ? bubble.extensionRight.size() : _traversal->getBubbles()[0].first;
682 }
683
684 if (predecessors.size()==1)
685 {
686 /** We compute left extension of the node. */
687 closureLeft = graph.getNT (predecessors[0], 0);
688 Node rev_pred = graph.reverse(predecessors[0]);
689 _traversal->traverse (rev_pred, DIR_OUTCOMING, bubble.extensionLeft);
690 bubble.divergenceLeft = _traversal->getBubbles().empty() ? bubble.extensionLeft.size() : _traversal->getBubbles()[0].first;
691 }
692 }
693
694 /** We return a code value according to left/right extensions status. */
695 if (closureLeft==NUCL_UNKNOWN && closureRight==NUCL_UNKNOWN) { bubble.where_to_extend = 0; }
696 else if (closureLeft!=NUCL_UNKNOWN && closureRight==NUCL_UNKNOWN) { bubble.where_to_extend = 1; }
697 else if (closureLeft==NUCL_UNKNOWN && closureRight!=NUCL_UNKNOWN) { bubble.where_to_extend = 2; }
698 else if (closureLeft!=NUCL_UNKNOWN && closureRight!=NUCL_UNKNOWN) { bubble.where_to_extend = 3; }
699
700 bubble.closureLeft = closureLeft;
701 bubble.closureRight = closureRight;
702
703 }
704 /*********************************************************************
705 ** METHOD :
706 ** PURPOSE :
707 ** INPUT :
708 ** OUTPUT :
709 ** RETURN :
710 ** REMARKS :
711 *********************************************************************/
712 void BubbleFinder::finish (const int disymetrical_end_size)
713 {
714
715
716 /** We build two Sequence objects from the information of the bubble. */
717
718 /** We set the bubble index. NOTE: We have to make sure it is protected against concurrent
719 * accesses since we may be called here from different threads. */
720 if (bubble.type==0) __sync_add_and_fetch (&(stats.nb_bubbles_snp), 1);
721 if (bubble.type==1) __sync_add_and_fetch (&(stats.nb_bubbles_del), 1);
722 bubble.index = __sync_add_and_fetch (&(stats.nb_bubbles), 1);
723
724 /** compute the bubble paths */
725 string path_0 = graph.toString (bubble.begin[0])+bubble.extended_string[0];
726 string path_1 = graph.toString (bubble.begin[1])+bubble.extended_string[1];
727 stringstream comment;
728 if ( bubble.polymorphism_type=="SNP" ){
729 int polymorphism_id=1;
730 for (unsigned int i=0;i<min(path_0.length(), path_1.length());i++){ // In the rad seq context, path may be of inequal sizes
731 if (path_0[i]!=path_1[i]) {
732 if (polymorphism_id>1) {
733 comment << ",";
734 }
735 comment<<"P_" << polymorphism_id << ":" << i << "_" << path_0[i] << "/" << path_1[i];
736 polymorphism_id++;
737 }
738 }
739 }
740 if ( bubble.polymorphism_type=="INDEL" ){
741 // if disymetrical_end_size>0: path0 has been extended more than path1
742 // if disymetrical_end_size<0: path1 has been extended more than path0
743 int p0=path_0.length(),p1=path_1.length();
744 int bes0=bubble.extended_string[0].length(), bes1=bubble.extended_string[1].length();
745 if (disymetrical_end_size>0){
746 p0-=disymetrical_end_size;
747 bes0-=disymetrical_end_size;
748 }
749 if (disymetrical_end_size<0){
750 p1+=disymetrical_end_size;
751 bes1+=disymetrical_end_size;
752 }
753 const int insert_size = p0<p1?p1-p0:p0-p1;
754 const int size_repeat = sizeKmer-2-min(bes0,bes1); // SEE checkRepeatSize function for explanations
755 comment << "P_1:" << (sizeKmer-1) << "_" << (insert_size) << "_" << (size_repeat);
756 }
757
758
759 if (bubble.extended_string[0].length()<=bubble.extended_string[1].length()){
760 buildSequence ( 0, "higher", bubble.seq1, comment.str());
761 buildSequence ( 1, "lower", bubble.seq2, comment.str());
762 }
763 else{ // put the smaller overlap as the first sequence.
764 buildSequence ( 1, "higher", bubble.seq1, comment.str());
765 buildSequence ( 0, "lower", bubble.seq2, comment.str());
766 }
767
768 /** We have to protect the sequences dump wrt concurrent accesses. We use a {} block with
769 * a LocalSynchronizer instance with the shared ISynchonizer of the Kissnp2 class. */
770 {
771 LocalSynchronizer sync (_synchronizer);
772
773 /** We insert the two sequences into the output bank. */
774 _outputBank->insert (bubble.seq1);
775 _outputBank->insert (bubble.seq2);
776
777 /** Stats update (in concurrent access protection block). */
778
779 // stats.nb_bubbles++;
780 if (bubble.type==0){
781 stats.nb_where_to_extend_snp[bubble.where_to_extend] ++;
782 if (bubble.high_complexity) { stats.nb_bubbles_snp_high++; }
783 else { stats.nb_bubbles_snp_low++; }
784 if (bubble.truncated) { stats.nb_bubbles_snp_truncated++; }
785 }
786 if (bubble.type==1){
787 stats.nb_where_to_extend_del[bubble.where_to_extend] ++;
788 if (bubble.high_complexity) { stats.nb_bubbles_del_high++; }
789 else { stats.nb_bubbles_del_low++; }
790 }
791 }
792
793
794 }
795
796 /*********************************************************************
797 ** METHOD :
798 ** PURPOSE :
799 ** INPUT :
800 ** OUTPUT :
801 ** RETURN :
802 ** REMARKS :
803 *********************************************************************/
804 bool BubbleFinder::two_possible_extensions_on_one_path (Node& node) const
805 {
806 return graph.indegree(node)>1 || graph.outdegree(node)>1;
807 }
808
809 /*********************************************************************
810 ** METHOD :
811 ** PURPOSE :
812 ** INPUT :
813 ** OUTPUT :
814 ** RETURN :
815 ** REMARKS :
816 *********************************************************************/
817 bool BubbleFinder::two_possible_extensions (Node node1, Node node2) const
818 {
819 return
820 graph.successorsEdge (node1, node2).size() >= 2 ||
821 graph.successorsEdge (graph.reverse (node1),graph.reverse (node2)).size() >= 2;
822 }
823
824 /*********************************************************************
825 ** METHOD :
826 ** PURPOSE :
827 ** INPUT :
828 ** OUTPUT :
829 ** RETURN :
830 ** REMARKS :
831 *********************************************************************/
832 void BubbleFinder::buildSequence ( size_t pathIdx, const char* type, Sequence& seq, string polymorphism_comments)
833 {
834 stringstream commentStream;
835
836 /** We build the comment for the sequence. */
837 commentStream << bubble.polymorphism_type << "_" << type << "_path_" << bubble.index << "|" << polymorphism_comments << "|" << (bubble.high_complexity ? "high" : "low")<< "|nb_pol_" <<bubble.final_nb_polymorphism;
838
839
840
841 /** We may have extra information for the comment. */
842 if (traversalKind == TRAVERSAL_UNITIG)
843 {
844 commentStream << "|left_unitig_length_";
845 commentStream << (bubble.where_to_extend%2==1 ? (bubble.extensionLeft.size() +1) : 0);
846 commentStream << "|right_unitig_length_";
847 commentStream << (bubble.where_to_extend>1 ? (bubble.extensionRight.size()+1) : 0);
848 }
849 if (traversalKind == TRAVERSAL_CONTIG)
850 {
851 commentStream << "|left_unitig_length_";
852 commentStream << (bubble.where_to_extend%2==1 ? (bubble.divergenceLeft +1) : 0);
853 commentStream << "|right_unitig_length_";
854 commentStream << (bubble.where_to_extend>1 ? (bubble.divergenceRight+1) : 0);
855
856 commentStream << "|left_contig_length_";
857 commentStream << (bubble.where_to_extend%2==1 ? (bubble.extensionLeft.size() +1) : 0);
858 commentStream << "|right_contig_length_";
859 commentStream << (bubble.where_to_extend>1 ? (bubble.extensionRight.size()+1) : 0);
860 }
861
862 /** We assign the comment of the sequence. */
863 seq.setComment (commentStream.str());
864
865 size_t lenLeft = bubble.extensionLeft.size ();
866 size_t lenRight = bubble.extensionRight.size ();
867 size_t len = sizeKmer + bubble.extended_string[pathIdx].length();
868
869 if (bubble.closureLeft != NUCL_UNKNOWN) { len += 1 + lenLeft; }
870 if (bubble.closureRight != NUCL_UNKNOWN) { len += 1 + lenRight; }
871
872 /** We resize the sequence data if needed. Note: +1 for ending '\0'
873 * NOTE: we use resize if we need more space, setSize otherwise. */
874 if (seq.getData().size() < len+1) { seq.getData().resize (len+1); }
875 else { seq.getData().setSize (len+1); }
876
877 char* output = seq.getDataBuffer();
878
879 /** We add the left extension if any. Note that we use lower case for extensions. */
880 if (bubble.closureLeft != NUCL_UNKNOWN)
881 {
882 for (size_t i=0; i<lenLeft; i++) { *(output++) = tolower(ascii (reverse(bubble.extensionLeft [lenLeft-i-1]))); }
883 *(output++) = tolower(ascii(bubble.closureLeft));
884 }
885
886 /** We add the bubble path. */
887 string begin = graph.toString (bubble.begin[pathIdx]);
888
889 /** note that if path overlap > 0 central string is empty **/
890 for (size_t i=0; i<sizeKmer; i++) { *(output++) = begin[i]; }
891 for (size_t i=0; i<bubble.extended_string[pathIdx].length(); i++) { *(output++) = bubble.extended_string[pathIdx][i]; }
892
893 /** We add the right extension if any. Note that we use lower case for extensions. */
894 if (bubble.closureRight != NUCL_UNKNOWN)
895 {
896 *(output++) = tolower(ascii(bubble.closureRight));
897 for (size_t i=0; i<lenRight; i++) { *(output++) = tolower(ascii (bubble.extensionRight[i])); }
898 }
899
900 /** We add a null terminator for the strings. */
901 *(output++) = '\0';
902 }
903
904 /*********************************************************************
905 ** METHOD :
906 ** PURPOSE :
907 ** INPUT :
908 ** OUTPUT :
909 ** RETURN :
910 ** REMARKS :
911 *********************************************************************/
912 bool BubbleFinder::checkNodesDiff (Node& previous, Node& current, Node& next) const
913 {
914 return (next.kmer != current.kmer) && (next.kmer != previous.kmer); //CHARLOTTE:kmer ici sous forme d'int
915 }
916
917 /*********************************************************************
918 ** METHOD :
919 ** PURPOSE :
920 ** INPUT :
921 ** OUTPUT :
922 ** RETURN :
923 ** REMARKS : Trick: we test the reverse complement of the second $k$-mer. Thus the last nuc. of the first kmer and the first nuc. of the second kmer does not influence the
924 ** comparison. Thus the choice of the path used to make this comparison (higher or lower) does not change the results.
925 *********************************************************************/
926 void BubbleFinder::checkPath ()
927 {
928 /** We test whether the first kmer of the first path is smaller than
929 * the first kmer of the revcomp(first path), this should avoid repeated SNPs */
930 DEBUG((cout<<"check path "<<graph.toString (bubble.begin[0]) <<"<"<< graph.toString (graph.reverse(bubble.end[0]))<<endl));
931 if(graph.toString (bubble.begin[0]) < graph.toString (graph.reverse(bubble.end[0])))
932 bubble.isCanonical=true;
933 else
934 bubble.isCanonical=false;
935
936 return ;
937 }
938
939
940
941 /*********************************************************************
942 ** METHOD :
943 ** PURPOSE :
944 ** INPUT :
945 ** OUTPUT :
946 ** RETURN :
947 ** REMARKS :
948 *********************************************************************/
949 bool BubbleFinder::checkRepeatSize (string &extension1, string &extension2) const
950 {
951
952 if (extension1.length() == extension2.length()) return true; // This is a SNP
953 /** compute the bubble paths */
954 /** Expected size of a path = 2k-2 (without first and last kmer common to both alleles
955 * This can be smaller un case of repeat position ambiguity
956 * k-1-size_of_smallest_extension (without the first kmer thus provides the size of the ambiguity
957 * In this code we only compute the length of the extension, expected to be k-1 (see bellow)
958 * ACCTGGGA
959 * ACCTXXGGGA
960 * ACCT -> CCTG -> CTGG -> TGGG -> GGGA ---------------------> extended string is GGG (size k-1)
961 * ACCT -> CCTX -> CTXX -> TXXG -> XXGG -> XGGG -> GGGA ------> extended string is XXGGG (size k-1+size insert
962 *
963 * Extreme case:
964 * ACCTGGGA
965 * ACCT|GGGA|GGGA
966 *
967 * ACCT->CCTG->CTGG->TGGG->GGGA->GGAX ------------------------------> extended string is empty (size 0 = k-1-ambiguity => ambiguity=k-1)
968 * ACCT->CCTG->CTGG->TGGG->GGGA->GGAG->GAGG->AGGG->GGGA->GAAX ------> extended string is AGGG (size k = k-1-ambiguity+size_ins = k-1-(k-1)+k => insertion of length k
969 **/
970
971
972 const int size_repeat = sizeKmer-2-min(extension1.length(), extension2.length());
973 if (size_repeat>max_indel_ambiguity) {
974 return false;
975 }
976 return true;
977
978 }
979
980
981 /*********************************************************************
982 ** METHOD : BubbleFinder::checkBranching
983 ** PURPOSE : Checks the branching properties of a couple of nodes. If authorised_branching==0: no branching is authorized in any of the two nodes.
984 ** If authorised_branching==1: no symetrical branching authorized from the two nodes (ie. N1-->A and N1-->B and N2-->A and N2-->B not authorized)
985 ** INPUT :
986 ** OUTPUT :
987 ** RETURN :
988 ** REMARKS :
989 *********************************************************************/
990 bool BubbleFinder::checkBranching (Node& node1, Node& node2, int & sym_branches) const
991 {
992 // stop the extension if authorised_branching==0 (not branching in any path) and any of the two paths is branching
993 if (authorised_branching==0 && (two_possible_extensions_on_one_path(node1) || two_possible_extensions_on_one_path(node2)))
994 {
995 return false;
996 }
997
998 const bool two_extensions = two_possible_extensions (node1, node2);
999
1000 // stop the extension if authorised_branching==1 (not branching in both path) and both the two paths are branching
1001 if (authorised_branching==1 && two_extensions)
1002 {
1003 return false;
1004 }
1005
1006 // stop the extension if authorised_branching=2 and too much nrabching crossroads were traversed.
1007 if (authorised_branching==2 && two_extensions){
1008 if (sym_branches==max_sym_branches) {return false;} // We saw already too much symmetrically branching crossreads
1009 sym_branches++;
1010 }
1011 return true;
1012 }
1013
1014 /*********************************************************************
1015 ** METHOD :
1016 ** PURPOSE :
1017 ** INPUT :
1018 ** OUTPUT :
1019 ** RETURN :
1020 ** REMARKS :
1021 *********************************************************************/
1022 void BubbleFinder::checkLowComplexity ()
1023 {
1024 bubble.acceptable_complexity=true;
1025 string path1 = graph.toString (bubble.begin[0]).substr(0, sizeKmer-1) + graph.toString (bubble.end[0]);
1026 string path2 = graph.toString (bubble.begin[1]).substr(0, sizeKmer-1) + graph.toString (bubble.end[1]);
1027
1028 /** We compute the low complexity score of the two paths. */
1029 bubble.high_complexity = filterLowComplexity2Paths (path1, path2);
1030
1031 if (accept_low) return; // the complexity is acceptable for this bubble anyway.
1032
1033 bubble.acceptable_complexity=bubble.high_complexity;
1034 DEBUG((cout<<"check low "<<accept_low<<" "<<bubble.high_complexity<<endl));
1035 }
1036
1037 /*********************************************************************
1038 ** METHOD :
1039 ** PURPOSE :
1040 ** INPUT :
1041 ** OUTPUT :
1042 ** RETURN :
1043 ** REMARKS :
1044 *********************************************************************/
1045 IProperties* BubbleFinder::getConfig () const
1046 {
1047 IProperties* props = new Properties();
1048
1049 /** We aggregate information for user. */
1050 props->add (0, "config", "");
1051 props->add (1, "kmer_size", "%d", sizeKmer);
1052 props->add (1, "auth_branch", "%d", authorised_branching);
1053 props->add (1, "max_indel_size", "%d", max_indel_size);
1054 props->add (1, "max_polymorphism", "%d", max_polymorphism);
1055 props->add (1, "low", "%d", accept_low);
1056 props-> add (1, "rad", "%d", accept_truncated_bubbles);
1057 props->add (1, "traversal", "%s", toString (traversalKind).c_str());
1058 if (accept_truncated_bubbles){
1059 props->add(1, "radseq mode", "");
1060 props->add(2, "max_truncated_path_length_difference", "%d", accept_truncated_bubbles);
1061 }
1062
1063 return props;
1064 }
1065
1066
1067 /********************************************************************************/
1068 /******************************** SNPs ******************************************/
1069 /********************************************************************************/
1070
1071