segment.cpp 33.6 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1
/*
2
  This file is part of Vidjil <http://www.vidjil.org>
3
  Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 by Bonsai bioinformatics
4 5 6 7 8
  at CRIStAL (UMR CNRS 9189, Université Lille) and Inria Lille
  Contributors: 
      Mathieu Giraud <mathieu.giraud@vidjil.org>
      Mikaël Salson <mikael.salson@vidjil.org>
      Marc Duez <marc.duez@vidjil.org>
Mikaël Salson's avatar
Mikaël Salson committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22

  "Vidjil" is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  "Vidjil" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with "Vidjil". If not, see <http://www.gnu.org/licenses/>
*/
Mikaël Salson's avatar
Mikaël Salson committed
23
#include <algorithm>    // std::sort
Mikaël Salson's avatar
Mikaël Salson committed
24 25 26 27
#include <cassert>
#include "segment.h"
#include "tools.h"
#include "affectanalyser.h"
Mikaël Salson's avatar
Mikaël Salson committed
28
#include <sstream>
29
#include <cstring>
Marc Duez's avatar
Marc Duez committed
30
#include <string>
Mikaël Salson's avatar
Mikaël Salson committed
31

32
#define NO_FORBIDDEN_ID (-1)
33

34
AlignBox::AlignBox(string _key, string _color) {
35
  key = _key;
36
  color = _color;
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51
  del_left = 0 ;
  start = 0 ;
  end = 0 ;
  del_right = 0 ;

  ref_nb = 0 ;
  ref = "";
  ref_label = "";
}

string AlignBox::getSequence(string sequence) {
  return sequence.substr(start, end-start+1);
}

52 53
void AlignBox::addToJson(json &seg) {

54
  json j;
55

56 57 58
  j["name"] = ref_label;

  if (key != "3") // no end information for J
59
    {
60 61
      j["end"] = end;
      j["delRight"] = del_right;
62
    }
63 64

  if (key != "5") // no start information for V
65
    {
66 67
      j["start"] = start;
      j["delLeft"] = del_left;
68
    }
69 70

  seg[key] = j ;
71
}
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

#define NO_COLOR "\033[0m"

int AlignBox::posInRef(int i) {
  // Works now only for V/J boxes

  if (del_left >= 0) // J
    return i - start + del_left + 1; // Why +1 ?

  if (del_right >= 0) // V
    return i + (ref.size() - del_right) - end ;

  return -99;
}

string AlignBox::refToString(int from, int to) {

  stringstream s;

  s << ref_label << "  \t" ;

  int j = posInRef(from);

  s << j << "\t" ;

  if (from > start)
    s << color;

  for (int i=from; i<=to; i++) {

    if (i == start)
      s << color;

106
    if (j > 0 && (size_t)j <= ref.size())
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
      s << ref[j-1] ;
    else
      s << ".";

    if (i == end)
      s << NO_COLOR;

    // Related position. To improve
    j++ ;
  }

  if (to < end)
    s << NO_COLOR;

  s << "\t" << j  ;

  return s.str();
}



128 129 130 131 132 133 134 135 136 137 138
ostream &operator<<(ostream &out, const AlignBox &box)
{
  out << "[/" << box.del_left << " " ;
  out << "@" << box.start << " " ;
  out << box.ref_label << "(" << box.ref_nb << ") " ;
  out << "@" << box.end << " " ;
  out << box.del_right << "/]" ;

  return out ;
}

139 140 141 142 143 144 145 146 147 148
string codeFromBoxes(vector <AlignBox*> boxes, string sequence)
{
  string code = "";

  int n = boxes.size();

  for (int i=0; i<n; i++) {

    if (i>0) {
      code += " " + string_of_int(boxes[i-1]->del_right) + "/"
Mathieu Giraud's avatar
Mathieu Giraud committed
149
        // From box_left->end + 1 to box_right->start - 1, both positions included
150 151 152 153 154 155 156 157 158
        + sequence.substr(boxes[i-1]->end + 1, boxes[i]->start - boxes[i-1]->end - 1)
        + "/" + string_of_int(boxes[i]->del_left) + " " ;
    }

    code += boxes[i]->ref_label ;
  }

  return code;
}
159

160

Mathieu Giraud's avatar
Mathieu Giraud committed
161
Segmenter::~Segmenter() {}
Mikaël Salson's avatar
Mikaël Salson committed
162

Mathieu Giraud's avatar
Mathieu Giraud committed
163
Sequence Segmenter::getSequence() const {
Mikaël Salson's avatar
Mikaël Salson committed
164 165
  Sequence s ;
  s.label_full = info ;
166 167 168 169 170 171
  if (segmented) {
    s.label = label + " " + (reversed ? "-" : "+");
    s.sequence = revcomp(sequence, reversed);
  } else {
    s.sequence = sequence;
  }
Mikaël Salson's avatar
Mikaël Salson committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

  return s ;
}

string Segmenter::getJunction(int l) const {
  assert(isSegmented());

  int start = (getLeft() + getRight())/2 - l/2;
  
  if (start < 0 or start + l > (int)sequence.size())  // TODO: +l ou +l-1 ?
    return "" ;

  return getSequence().sequence.substr(start, l);
}

int Segmenter::getLeft() const {
188
  return box_V->end;
Mikaël Salson's avatar
Mikaël Salson committed
189 190 191
}
  
int Segmenter::getRight() const {
192
  return box_J->start;
Mikaël Salson's avatar
Mikaël Salson committed
193 194 195
}

int Segmenter::getLeftD() const {
196
  return box_D->start;
Mikaël Salson's avatar
Mikaël Salson committed
197 198 199
}
  
int Segmenter::getRightD() const {
200
  return box_D->end;
Mikaël Salson's avatar
Mikaël Salson committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214
}

bool Segmenter::isReverse() const {
  return reversed;
}

bool Segmenter::isSegmented() const {
  return segmented;
}

bool Segmenter::isDSegmented() const {
  return dSegmented;
}

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

// E-values

void Segmenter::checkLeftRightEvaluesThreshold(double threshold, int strand)
{
  if (threshold == NO_LIMIT_VALUE)
    return ;

  if (evalue_left >= threshold && evalue_right >= threshold)
    because = UNSEG_TOO_FEW_ZERO ;
  else if ((strand == 1 ? evalue_left : evalue_right) >= threshold)
    because = UNSEG_TOO_FEW_V ;
  else if ((strand == 1 ? evalue_right : evalue_left) >= threshold)
    because = UNSEG_TOO_FEW_J ;
  else if (evalue >= threshold) // left and right are <= threshold, but their sum is > threshold
    because = UNSEG_TOO_FEW_ZERO ;
}


Mikaël Salson's avatar
Mikaël Salson committed
234 235 236 237 238 239 240 241
// Chevauchement

string Segmenter::removeChevauchement()
{
  assert(isSegmented());
  
  string chevauchement = "" ;

242
  if (box_V->end >= box_J->start)
Mikaël Salson's avatar
Mikaël Salson committed
243
    {
244 245 246 247
      int middle = (box_V->end + box_J->start) / 2 ;
      chevauchement = " !ov " + string_of_int (box_V->end - box_J->start + 1);
      box_V->end = middle ;
      box_J->start = middle+1 ;
Mikaël Salson's avatar
Mikaël Salson committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261
    }

  return chevauchement ;
}

// Prettyprint


bool Segmenter::finishSegmentation() 
{
  assert(isSegmented());
  
  string seq = getSequence().sequence;
    
262 263 264 265 266
  seg_V = seq.substr(0, box_V->end+1) ;
  seg_N = seq.substr(box_V->end+1, box_J->start-box_V->end-1) ;  // Twice computed for FineSegmenter, but only once in KmerSegmenter !
  seg_J = seq.substr(box_J->start) ;
  box_D->start=0;
  box_D->end=0;
Mikaël Salson's avatar
Mikaël Salson committed
267 268 269 270 271 272 273 274 275 276 277 278 279

  info = "VJ \t" + string_of_int(FIRST_POS) + " " + info + " " + string_of_int(seq.size() - 1 + FIRST_POS) ;
  info += "\t" + code ;

  info = (reversed ? "- " : "+ ") + info ;

  return true ;
}

bool Segmenter::finishSegmentationD() 
{
  string seq = getSequence().sequence;

280 281 282 283
  seg_V = seq.substr(0, box_V->end+1) ; // From pos. 0 to box_V->end
  seg_J = seq.substr(box_J->start) ;
  seg_N = seq.substr(box_V->end+1, box_J->start-box_V->end-1) ;  // Twice computed for FineSegmenter, but only once in KmerSegmenter !
  seg_D  = seq.substr(box_D->start, box_D->end-box_D->start+1) ; // From Dstart to Dend
Mikaël Salson's avatar
Mikaël Salson committed
284
  
285 286 287 288
  info = "VDJ \t0 " + string_of_int(box_V->end) +
                " " + string_of_int(box_D->start) +
		" " + string_of_int(box_D->end) +
		" " + string_of_int(box_J->start) +
Mikaël Salson's avatar
Mikaël Salson committed
289 290 291 292 293 294 295 296 297
		" " + string_of_int(seq.size()-1+FIRST_POS) ;
		
  info += "\t" + code ;
  
  info = (reversed ? "- " : "+ ") + info ;

  return true ;
}

298 299
string Segmenter::getInfoLine() const
{
300
  string s = "" ;
301 302 303 304 305

  s += (segmented ? "" : "! ") + info ;
  s += " " + info_extra ;
  s += " " + segmented_germline->code ;
  s += " " + string(segmented_mesg[because]) ;
306 307 308 309

  if (evalue > NO_LIMIT_VALUE)
    s += " " + scientific_string_of_double(evalue);

310 311 312 313 314
  if (evalue_left > NO_LIMIT_VALUE)
    s += " " + scientific_string_of_double(evalue_left);
  if (evalue_right > NO_LIMIT_VALUE)
    s += "/" + scientific_string_of_double(evalue_right);

315
  if (CDR3start > 0)
316 317
    s += " {" + string_of_int(JUNCTIONstart) + "(" + string_of_int(JUNCTIONend-JUNCTIONstart+1) + ")" + string_of_int(JUNCTIONend) + " "
      + "up"[JUNCTIONproductive] + " " + JUNCTIONaa + "}";
318

319 320 321
  return s ;
}

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
string KmerSegmenter::getInfoLineWithAffects() const
{
   stringstream ss;

   ss << "# "
      << right << setw(3) << score << " "
      << left << setw(30)
      << getInfoLine() ;

   if (getSegmentationStatus() != UNSEG_TOO_SHORT)
     ss << getKmerAffectAnalyser()->toString();

   return ss.str();
}


Mikaël Salson's avatar
Mikaël Salson committed
338 339
ostream &operator<<(ostream &out, const Segmenter &s)
{
340
  out << ">" << s.label << " " ;
341
  out << s.getInfoLine() << endl;
Mikaël Salson's avatar
Mikaël Salson committed
342 343 344 345 346 347 348 349 350

  if (s.segmented)
    {
      out << s.seg_V << endl ;
      out << s.seg_N << endl ;
      out << s.seg_J << endl ;
    }
  else
    {
351
      out << s.getSequence().sequence << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
352 353 354 355 356 357 358 359
    }

  return out ;
}


// KmerSegmenter (Cheap)

360 361
KmerSegmenter::KmerSegmenter() { kaa = 0 ; }

362
KmerSegmenter::KmerSegmenter(Sequence seq, Germline *germline, double threshold, int multiplier)
Mikaël Salson's avatar
Mikaël Salson committed
363
{
364 365 366 367
  box_V = new AlignBox();
  box_D = new AlignBox();
  box_J = new AlignBox();

368 369 370
  CDR3start = -1;
  CDR3end = -1;

371 372 373
  JUNCTIONstart = -1;
  JUNCTIONend = -1;

Mikaël Salson's avatar
Mikaël Salson committed
374 375 376
  label = seq.label ;
  sequence = seq.sequence ;
  info = "" ;
377
  info_extra = "seed";
Mikaël Salson's avatar
Mikaël Salson committed
378
  segmented = false;
379
  segmented_germline = germline ;
380
  system = germline->code; // useful ?
381
  reversed = false;
382
  because = NOT_PROCESSED ; // Cause of unsegmentation
383
  score = 0 ;
384
  evalue = NO_LIMIT_VALUE;
385 386
  evalue_left = NO_LIMIT_VALUE;
  evalue_right = NO_LIMIT_VALUE;
387

388
  int s = (size_t)germline->index->getS() ;
Mikaël Salson's avatar
Mikaël Salson committed
389
  int length = sequence.length() ;
Mikaël Salson's avatar
Mikaël Salson committed
390

391
  if (length < s) 
Mikaël Salson's avatar
Mikaël Salson committed
392
    {
Mathieu Giraud's avatar
Mathieu Giraud committed
393 394
      because = UNSEG_TOO_SHORT;
      kaa = NULL;
395
      return ;
Mikaël Salson's avatar
Mikaël Salson committed
396 397
    }
 
398
  kaa = new KmerAffectAnalyser(*(germline->index), sequence);
Mikaël Salson's avatar
Mikaël Salson committed
399 400
  
  // Check strand consistency among the affectations.
Mikaël Salson's avatar
Mikaël Salson committed
401 402 403 404 405 406 407 408 409
  int strand;
  int nb_strand[2] = {0,0};     // In cell 0 we'll put the number of negative
                                // strand, while in cell 1 we'll put the
                                // positives
  for (int i = 0; i < kaa->count(); i++) { 
    KmerAffect it = kaa->getAffectation(i);
    if (! it.isAmbiguous() && ! it.isUnknown()) {
      strand = affect_strand(it.affect);
      nb_strand[(strand + 1) / 2] ++; // (strand+1) / 2 → 0 if strand == -1; 1 if strand == 1
Mikaël Salson's avatar
Mikaël Salson committed
410 411 412
    }
  }

413 414
  score = nb_strand[0] + nb_strand[1] ; // Used only for non-segmented germlines

415 416
  reversed = (nb_strand[0] > nb_strand[1]) ;

417 418
  if ((germline->seg_method == SEG_METHOD_MAX12)
      || (germline->seg_method == SEG_METHOD_MAX1U))
419 420 421 422
    { // Pseudo-germline, MAX12 and MAX1U
      pair <KmerAffect, KmerAffect> max12 ;
      CountKmerAffectAnalyser ckaa(*(germline->index), sequence);

423 424 425 426 427

      set<KmerAffect> forbidden;
      forbidden.insert(KmerAffect::getAmbiguous());
      forbidden.insert(KmerAffect::getUnknown());

428
      if (germline->seg_method == SEG_METHOD_MAX12)
429 430 431
        // MAX12: two maximum k-mers (no unknown)
        {
          max12 = ckaa.max12(forbidden);
432

433 434 435 436 437 438
          if (max12.first.isUnknown() || max12.second.isUnknown())
            {
              because = UNSEG_TOO_FEW_ZERO ;
              return ;
            }
        }
439

440 441
      else
        // MAX1U: the maximum k-mers (no unknown) + unknown
442
        {
443 444 445 446 447 448 449 450 451
          CountKmerAffectAnalyser ckaa(*(germline->index), sequence);
          KmerAffect max = ckaa.max(forbidden);

          if (max.isUnknown())
            {
              because = UNSEG_TOO_FEW_ZERO ;
              return ;
            }
          max12 = make_pair(max, KmerAffect::getUnknown());
452 453
        }

454 455 456 457 458
      pair <KmerAffect, KmerAffect> before_after =  ckaa.sortLeftRight(max12);

      before = before_after.first ;
      after = before_after.second ;

459 460 461
      // This strand computation is only a heuristic, especially for chimera +/- reads
      // Anyway, it allows to gather such reads and their reverse complement into a unique window...
      // ... except when the read is quite different outside the window
462
      strand = reversed ? -1 : 1 ;
463 464 465 466 467
    }

  else
    { // Regular germline

468
  // Test on which strand we are, select the before and after KmerAffects
Mikaël Salson's avatar
Mikaël Salson committed
469
  if (nb_strand[0] == 0 && nb_strand[1] == 0) {
470
    because = UNSEG_TOO_FEW_ZERO ;
471
    return ;
Mikaël Salson's avatar
Mikaël Salson committed
472 473
  } else if (nb_strand[0] > RATIO_STRAND * nb_strand[1]) {
    strand = -1;
474 475
    before = KmerAffect(germline->affect_3, -1); 
    after = KmerAffect(germline->affect_5, -1);
Mikaël Salson's avatar
Mikaël Salson committed
476 477
  } else if (nb_strand[1] > RATIO_STRAND * nb_strand[0]) {
    strand = 1;
478 479
    before = KmerAffect(germline->affect_5, 1); 
    after = KmerAffect(germline->affect_3, 1);    
Mikaël Salson's avatar
Mikaël Salson committed
480 481
  } else {
    // Ambiguous information: we have positive and negative strands
482 483 484 485 486
    // and there is not enough difference to put them apart.
    if (nb_strand[0] + nb_strand[1] >= DETECT_THRESHOLD_STRAND)
      because = UNSEG_STRAND_NOT_CONSISTENT ;
    else
      because = UNSEG_TOO_FEW_ZERO ;
487
    return ;
Mikaël Salson's avatar
Mikaël Salson committed
488 489
  }

490
    } // endif Pseudo-germline
491
 
492
  computeSegmentation(strand, before, after, threshold, multiplier);
Mathieu Giraud's avatar
Mathieu Giraud committed
493
}
Mikaël Salson's avatar
Mikaël Salson committed
494

Mathieu Giraud's avatar
Mathieu Giraud committed
495
KmerSegmenter::~KmerSegmenter() {
496 497
  if (kaa)
    delete kaa;
498 499 500 501

  delete box_V;
  delete box_D;
  delete box_J;
502 503
}

504 505
KmerMultiSegmenter::KmerMultiSegmenter(Sequence seq, MultiGermline *multigermline, ostream *out_unsegmented,
                                       double threshold, int nb_reads_for_evalue)
506
{
507 508
  bool found_seg = false ; // Found a segmentation
  double best_evalue_seg = NO_LIMIT_VALUE ; // Best evalue, segmented sequences
509
  int best_score_unseg = 0 ; // Best score, unsegmented sequences
510
  the_kseg = NULL;
511
  multi_germline = multigermline;
512
  threshold_nb_expected = threshold;
513 514 515

  // E-value multiplier
  int multiplier = multi_germline->germlines.size() * nb_reads_for_evalue;
516
  
517 518 519 520 521
  // Iterate over the germlines
  for (list<Germline*>::const_iterator it = multigermline->germlines.begin(); it != multigermline->germlines.end(); ++it)
    {
      Germline *germline = *it ;

522
      KmerSegmenter *kseg = new KmerSegmenter(seq, germline, threshold, multiplier);
523
      bool keep_seg = false;
524

525 526 527
      if (out_unsegmented)
        {
          // Debug, display k-mer affectation and segmentation result for this germline
528
          *out_unsegmented << kseg->getInfoLineWithAffects() << endl ;
529 530
        }

531 532
      // Always remember the first kseg
      if (the_kseg == NULL)
533
        keep_seg = true;
534
      
535
      if (kseg->isSegmented())
536 537
        {
          // Yes, it is segmented
538
          // Should we keep the kseg ?
539
          if (!found_seg || (kseg->evalue < best_evalue_seg))
540
            {
541
              keep_seg = true;
542 543 544
              best_evalue_seg = kseg->evalue ;

              found_seg = true;
545
            }
546
        }
547 548 549 550 551 552 553
      else
        {
          // It is not segmented
          // Should we keep the kseg (with the unsegmentation cause) ?
            if (kseg->score > best_score_unseg)
            {              
              best_score_unseg = kseg->score ;
554
              if (!found_seg)
555 556 557 558
                keep_seg = true;
            }
        }
      
559
      if (keep_seg) {
560 561
        if (the_kseg)
          delete the_kseg;
562 563 564 565
        the_kseg = kseg;
      } else {
        delete kseg;
      }
566 567 568
    } // end for (Germlines)
}

569
KmerMultiSegmenter::~KmerMultiSegmenter() {
570 571
  if (the_kseg)
    delete the_kseg;
Mathieu Giraud's avatar
Mathieu Giraud committed
572 573
}

574 575
void KmerSegmenter::computeSegmentation(int strand, KmerAffect before, KmerAffect after,
                                        double threshold, int multiplier) {
576
  // Try to segment, computing 'box_V->end' and 'box_J->start'
577 578
  // If not segmented, put the cause of unsegmentation in 'because'

579
  affect_infos max;
580
  max = kaa->getMaximum(before, after);
Mikaël Salson's avatar
Mikaël Salson committed
581

582 583 584
  // We did not find a good segmentation point
  if (!max.max_found) {
    // We labeled it detected if there were both enough affect_5 and enough affect_3
585 586 587 588 589 590 591 592 593
    bool detected_before = (max.nb_before_left + max.nb_before_right >= DETECT_THRESHOLD);
    bool detected_after = (max.nb_after_left + max.nb_after_right >= DETECT_THRESHOLD);

    if (detected_before && detected_after)
      because = UNSEG_AMBIGUOUS ;
    else if ((strand == 1 && detected_before) || (strand == -1 && detected_after))
      because = UNSEG_TOO_FEW_J ;
    else if ((strand == 1 && detected_after) || (strand == -1 && detected_before))
      because = UNSEG_TOO_FEW_V ;
594
    else
595
      because = UNSEG_TOO_FEW_ZERO ;
596 597 598 599 600

    return ;
  }


601
  // E-values
602 603 604
  pair <double, double> pvalues = kaa->getLeftRightProbabilityAtLeastOrAbove();
  evalue_left = pvalues.first * multiplier ;
  evalue_right = pvalues.second * multiplier ;
605
  evalue = evalue_left + evalue_right ;
606

607
  checkLeftRightEvaluesThreshold(threshold, strand);
608

609
  if (because != NOT_PROCESSED)
610 611
    return ;

612 613
   // There was a good segmentation point

614 615
   box_V->end = max.first_pos_max;
   box_J->start = max.last_pos_max + 1;
616
   if (strand == -1) {
617 618 619
     int tmp = sequence.size() - box_V->end - 1;
     box_V->end = sequence.size() - box_J->start - 1;
     box_J->start = tmp;
620 621 622 623 624 625
   }

  // Yes, it is segmented
  segmented = true;
  because = reversed ? SEG_MINUS : SEG_PLUS ;

626
  info = string_of_int(box_V->end + FIRST_POS) + " " + string_of_int(box_J->start + FIRST_POS)  ;
627 628 629 630 631 632

  // removeChevauchement is called once info was already computed: it is only to output info_extra
  info_extra += removeChevauchement();
  finishSegmentation();

  return ;
Mathieu Giraud's avatar
Mathieu Giraud committed
633
}
Mikaël Salson's avatar
Mikaël Salson committed
634

635
KmerAffectAnalyser *KmerSegmenter::getKmerAffectAnalyser() const {
Mathieu Giraud's avatar
Mathieu Giraud committed
636 637
  return kaa;
}
Mikaël Salson's avatar
Mikaël Salson committed
638

639
int Segmenter::getSegmentationStatus() const {
Mathieu Giraud's avatar
Mathieu Giraud committed
640
  return because;
Mikaël Salson's avatar
Mikaël Salson committed
641 642
}

643 644 645 646 647
void Segmenter::setSegmentationStatus(int status) {
  because = status;
  segmented = (status == SEG_PLUS || status == SEG_MINUS);
}

Mikaël Salson's avatar
Mikaël Salson committed
648 649
// FineSegmenter

650

651
string check_and_resolve_overlap(string seq, int seq_begin, int seq_end,
652 653
                                 AlignBox *box_left, AlignBox *box_right,
                                 Cost segment_cost)
Mikaël Salson's avatar
Mikaël Salson committed
654
{
655
  // Overlap size
656
  int overlap = box_left->end - box_right->start + 1;
657 658 659

  if (overlap > 0)
    {
660 661
      string seq_left = seq.substr(seq_begin, box_left->end - seq_begin + 1);
      string seq_right = seq.substr(box_right->start, seq_end - box_right->start + 1);
662

Mikaël Salson's avatar
Mikaël Salson committed
663 664 665 666
      int score_r[overlap+1];
      int score_l[overlap+1];
      
      //LEFT
667
      DynProg dp_l = DynProg(seq_left, box_left->ref,
Mikaël Salson's avatar
Mikaël Salson committed
668
			   DynProg::Local, segment_cost);
669
      score_l[0] = dp_l.compute();
670

Mikaël Salson's avatar
Mikaël Salson committed
671 672
      
      //RIGHT
673
      // reverse right sequence
674
      string ref_right=string(box_right->ref.rbegin(), box_right->ref.rend());
675 676 677
      seq_right=string(seq_right.rbegin(), seq_right.rend());


678
      DynProg dp_r = DynProg(seq_right, ref_right,
Mikaël Salson's avatar
Mikaël Salson committed
679
			   DynProg::Local, segment_cost);
680
      score_r[0] = dp_r.compute();
681 682 683 684 685 686



      int trim_l[overlap+1];
      int trim_r[overlap+1];

687
      for(size_t i=0; i<=(size_t)overlap; i++) {
688 689
        score_l[i] = i < seq_left.size()  ? dp_l.best_score_on_i(seq_left.size()  - i, trim_l + i) : MINUS_INF ;
        score_r[i] = i < seq_right.size() ? dp_r.best_score_on_i(seq_right.size() - i, trim_r + i) : MINUS_INF ;
Mikaël Salson's avatar
Mikaël Salson committed
690
      }
691

692 693 694 695 696 697

// #define DEBUG_OVERLAP
#ifdef DEBUG_OVERLAP
      cout << dp_l ;
      cout << dp_r ;

698 699
      cout << "seq:" << seq_left << "\t\t" << seq_right << endl;
      cout << "ref:" << ref_left << "\t\t" << ref_right << endl;
700 701 702 703 704 705 706 707
      for(int i=0; i<=overlap; i++)
        cout << i << "  left: " << score_l[i] << "/" << trim_l[i] << "     right: " << score_r[i] << "/" << trim_r[i] << endl;
#endif

      int score = MINUS_INF;
      int best_i = 0 ;
      int best_j = 0 ;

Mikaël Salson's avatar
Mikaël Salson committed
708

709
      // Find (i, j), with i+j >= overlap,
710
      // maximizing score_l[j] + score_r[i]
Mikaël Salson's avatar
Mikaël Salson committed
711 712
      for (int i=0; i<=overlap; i++){
	for (int j=overlap-i; j<=overlap; j++){
713
          int score_ij = score_l[i] + score_r[j];
714

715 716 717
	  if (score_ij > score) {
            best_i = i ;
            best_j = j ;
718 719
            box_left->del_right = box_left->ref.size() - trim_l[i];
	    box_right->del_left = box_right->ref.size() - trim_r[j];
720
	    score = score_ij;
Mikaël Salson's avatar
Mikaël Salson committed
721 722 723
	  }
	}
      }
724

725 726
      box_left->end -= best_i ;
      box_right->start += best_j ;
727 728

#ifdef DEBUG_OVERLAP
729
      cout << "overlap: " << overlap << ", " << "best_overlap_split: " << score
730 731
           << "    left: " << best_i << "-" << box_left->del_right << " @" << box_left->end
           << "    right:" << best_j << "-" << box_right->del_left << " @" << box_right->start
732
           << endl;
733
#endif
734 735
    } // end if (overlap > 0)

736 737
  // From box_left->end + 1 to box_right->start - 1
  return seq.substr(box_left->end + 1, box_right->start - box_left->end - 1);
Mikaël Salson's avatar
Mikaël Salson committed
738 739
}

Mikaël Salson's avatar
Mikaël Salson committed
740 741 742 743 744
bool comp_pair (pair<int,int> i,pair<int,int> j)
{
  return ( i.first > j.first);
}

745 746 747 748 749

/**
 * Align a read against a collection of sequences, maximizing the alignment 'score'
 * @param read:         the read
 * @param rep:          a collection of reference sequences
750
 * @param reverse_ref:  if true, reverse the reference sequences (VkVk)
751
 * @param reverse_both: if true, reverse both the read and the reference sequences (J segment)
752
 * @param local:        if true, Local alignment (D segment), otherwise LocalEndWithSomeDeletions and onlyBottomTriangle (V and J segments)
753
 * @param box:          the AligBox to fill
754
 * @param segment_cost: the cost used by the dynamic programing
755
 * @post  box is filled
756 757
 */

758 759
void align_against_collection(string &read, Fasta &rep, int forbidden_rep_id,
                              bool reverse_ref, bool reverse_both, bool local,
760
                             AlignBox *box, Cost segment_cost)
Mikaël Salson's avatar
Mikaël Salson committed
761 762 763
{
  
  int best_score = MINUS_INF ;
764
  box->ref_nb = MINUS_INF ;
Mikaël Salson's avatar
Mikaël Salson committed
765 766 767 768
  int best_best_i = (int) string::npos ;
  int best_best_j = (int) string::npos ;
  int best_first_i = (int) string::npos ;
  int best_first_j = (int) string::npos ;
769

Mikaël Salson's avatar
Mikaël Salson committed
770
  vector<pair<int, int> > score_r;
Mikaël Salson's avatar
Mikaël Salson committed
771 772 773

  DynProg::DynProgMode dpMode = DynProg::LocalEndWithSomeDeletions;
  if (local==true) dpMode = DynProg::Local;
774 775 776

  // With reverse_ref, the read is reversed to prevent calling revcomp on each reference sequence
  string sequence_or_rc = revcomp(read, reverse_ref);
Mikaël Salson's avatar
Mikaël Salson committed
777 778 779
  
  for (int r = 0 ; r < rep.size() ; r++)
    {
780 781 782
      if (r == forbidden_rep_id)
        continue;

783
      DynProg dp = DynProg(sequence_or_rc, rep.sequence(r),
Mikaël Salson's avatar
Mikaël Salson committed
784 785
			   dpMode, // DynProg::SemiGlobalTrans, 
			   segment_cost, // DNA
786 787
			   reverse_both, reverse_both,
                          rep.read(r).marked_pos);
788 789 790

      bool onlyBottomTriangle = !local ;
      int score = dp.compute(onlyBottomTriangle, BOTTOM_TRIANGLE_SHIFT);
Mikaël Salson's avatar
Mikaël Salson committed
791
      
Mikaël Salson's avatar
Mikaël Salson committed
792 793 794 795 796 797 798 799 800 801 802
      if (local==true){ 
	dp.backtrack();
      }
      
      if (score > best_score)
	{
	  best_score = score ;
	  best_best_i = dp.best_i ;
	  best_best_j = dp.best_j ;
	  best_first_i = dp.first_i ;
	  best_first_j = dp.first_j ;
803 804
	  box->ref_nb = r ;
	  box->ref_label = rep.label(r) ;
805 806 807 808

          if (!local)
            dp.backtrack();
          box->marked_pos = dp.marked_pos_i ;
Mikaël Salson's avatar
Mikaël Salson committed
809
	}
Mikaël Salson's avatar
Mikaël Salson committed
810 811
	
	score_r.push_back(make_pair(score, r));
Mathieu Giraud's avatar
Mathieu Giraud committed
812 813 814 815 816 817

	// #define DEBUG_SEGMENT      

#ifdef DEBUG_SEGMENT	
	cout << rep.label(r) << " " << score << " " << dp.best_i << endl ;
#endif
Mikaël Salson's avatar
Mikaël Salson committed
818 819

    }
Mikaël Salson's avatar
Mikaël Salson committed
820
    sort(score_r.begin(),score_r.end(),comp_pair);
Mikaël Salson's avatar
Mikaël Salson committed
821

822 823 824 825
  box->ref = rep.sequence(box->ref_nb);
  box->del_right = reverse_both ? best_best_j : box->ref.size() - best_best_j - 1;
  box->del_left = best_first_j;
  box->start = best_first_i;
Mikaël Salson's avatar
Mikaël Salson committed
826
  
827
  box->score = score_r;
Mathieu Giraud's avatar
Mathieu Giraud committed
828 829

#ifdef DEBUG_SEGMENT	
830
  cout << "best: " << box->ref_label << " " << best_score ;
831
  cout << "del/del2/begin:" << (box->del_right) << "/" << (box->del_left) << "/" << (box->start) << endl;
Mathieu Giraud's avatar
Mathieu Giraud committed
832 833
  cout << endl;
#endif
834 835 836 837

  if (reverse_ref)
    // Why -1 here and +1 in dynprog.cpp /// best_i = m - best_i + 1 ;
    best_best_i = read.length() - best_best_i - 1 ;
838 839

  box->end = best_best_i ;
Mikaël Salson's avatar
Mikaël Salson committed
840 841 842 843 844 845 846
}

string format_del(int deletions)
{
  return deletions ? *"(" + string_of_int(deletions) + " del)" : "" ;
}

847
FineSegmenter::FineSegmenter(Sequence seq, Germline *germline, Cost segment_c,  double threshold, int multiplier)
Mikaël Salson's avatar
Mikaël Salson committed
848
{
849 850 851
  box_V = new AlignBox("5");
  box_D = new AlignBox("4");
  box_J = new AlignBox("3");
852

853 854
  segmented = false;
  dSegmented = false;
855
  because = NOT_PROCESSED ;
856
  segmented_germline = germline ;
857
  info_extra = "" ;
Mikaël Salson's avatar
Mikaël Salson committed
858 859 860
  label = seq.label ;
  sequence = seq.sequence ;
  segment_cost=segment_c;
861
  evalue = NO_LIMIT_VALUE;
862 863
  evalue_left = NO_LIMIT_VALUE;
  evalue_right = NO_LIMIT_VALUE;
864 865
  box_V->marked_pos = 0;
  box_J->marked_pos = 0;
Mikaël Salson's avatar
Mikaël Salson committed
866

867 868
  CDR3start = -1;
  CDR3end = -1;
869

870 871 872
  JUNCTIONstart = -1;
  JUNCTIONend = -1;

873 874 875
  bool reverse_V = false ;
  bool reverse_J = false ;

876
  if ((germline->seg_method == SEG_METHOD_MAX12) || (germline->seg_method == SEG_METHOD_MAX1U))
877
    {
878
      // We check whether this sequence is segmented with MAX12 or MAX1U (with default e-value parameters)
879
      KmerSegmenter *kseg = new KmerSegmenter(seq, germline, THRESHOLD_NB_EXPECTED, 1);
880
      if (kseg->isSegmented())
881
        {
882 883 884 885 886
          reversed = kseg->isReverse();

          KmerAffect left = reversed ? KmerAffect(kseg->after, true) : kseg->before ;
          KmerAffect right = reversed ? KmerAffect(kseg->before, true) : kseg->after ;

887 888
          delete kseg ;

889 890 891
          reverse_V = (left.getStrand() == -1);
          reverse_J = (right.getStrand() == -1);

892
          code = "Unexpected ";
893

894
          code += left.toStringSigns() + germline->index->getLabel(left).basename;
895
          code += "/";
896
          code += right.toStringSigns() + germline->index->getLabel(right).basename;
897
          info_extra += " " + left.toString() + "/" + right.toString() + " (" + code + ")";
898 899 900 901 902

          if (germline->seg_method == SEG_METHOD_MAX1U)
            return ;

          germline->override_rep5_rep3_from_labels(left, right);
903
        }
904
      else
905 906 907 908
        {
          delete kseg ;
          return ;
        }
909
    }
910

911 912 913 914 915 916 917
  // Strand determination, with KmerSegmenter (with default e-value parameters)
  // Note that we use only the 'strand' component
  // When the KmerSegmenter fails, continue with positive strand
  // TODO: flag to force a strand / to test both strands ?

  KmerSegmenter *kseg = new KmerSegmenter(seq, germline, THRESHOLD_NB_EXPECTED, 1);
  reversed = kseg->isReverse();
918
  delete kseg ;
Mikaël Salson's avatar
Mikaël Salson committed
919
  
920
  sequence_or_rc = revcomp(sequence, reversed); // sequence, possibly reversed
921

Mathieu Giraud's avatar
Mathieu Giraud committed
922 923

  /* Segmentation */
924
  align_against_collection(sequence_or_rc, germline->rep_5, NO_FORBIDDEN_ID, reverse_V, reverse_V, false,
925
                                        box_V, segment_cost);
926

927
  align_against_collection(sequence_or_rc, germline->rep_3, NO_FORBIDDEN_ID, reverse_J, !reverse_J, false,
928
                                          box_J, segment_cost);
929 930 931 932 933

  // J was run with '!reverseJ', we copy the box informations from right to left
  // Should this directly be handled in align_against_collection() ?
  box_J->start = box_J->end ;
  box_J->del_left = box_J->del_right;
934

935
  /* E-values */
936 937
  evalue_left  = multiplier * sequence.size() * germline->rep_5.totalSize() * segment_cost.toPValue(box_V->score[0].first);
  evalue_right = multiplier * sequence.size() * germline->rep_3.totalSize() * segment_cost.toPValue(box_J->score[0].first);
938
  evalue = evalue_left + evalue_right ;
939 940

  /* Unsegmentation causes */
941
  if (box_V->end == (int) string::npos)
942
    {
943
      evalue_left = BAD_EVALUE ;
944
    }
945
      
946
  if (box_J->start == (int) string::npos)
947
    {
948
      evalue_right = BAD_EVALUE ;
949 950
    }

951 952
  checkLeftRightEvaluesThreshold(threshold, reversed ? -1 : 1);

953 954 955
  if (because != NOT_PROCESSED)
    {
      segmented = false;
956
      info = " @" + string_of_int (box_V->end + FIRST_POS) + "  @" + string_of_int(box_J->start + FIRST_POS) ;
Mikaël Salson's avatar
Mikaël Salson committed
957 958
      return ;
    }
959 960 961 962

  /* The sequence is segmented */
  segmented = true ;
  because = reversed ? SEG_MINUS : SEG_PLUS ;
963

Mikaël Salson's avatar
Mikaël Salson committed
964
    //overlap VJ
965
  seg_N = check_and_resolve_overlap(sequence_or_rc, 0, sequence_or_rc.length(),
966
                                    box_V, box_J, segment_cost);
967

968
  // Why could this happen ?
969 970
      if (box_J->start>=(int) sequence.length())
	  box_J->start=sequence.length()-1;
Mikaël Salson's avatar
Mikaël Salson committed
971

972
  // seg_N will be recomputed in finishSegmentation()
Mikaël Salson's avatar
Mikaël Salson committed
973

974
  boxes.clear();
975 976
  boxes.push_back(box_V);
  boxes.push_back(box_J);