segment.cpp 29.2 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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

AlignBox::AlignBox() {
  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);
}


49 50 51 52 53 54 55 56 57 58 59 60
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 ;
}


61

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

Mathieu Giraud's avatar
Mathieu Giraud committed
64
Sequence Segmenter::getSequence() const {
Mikaël Salson's avatar
Mikaël Salson committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  Sequence s ;
  s.label_full = info ;
  s.label = label + " " + (reversed ? "-" : "+");
  s.sequence = revcomp(sequence, reversed);

  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 {
85
  return box_V->end;
Mikaël Salson's avatar
Mikaël Salson committed
86 87 88
}
  
int Segmenter::getRight() const {
89
  return box_J->start;
Mikaël Salson's avatar
Mikaël Salson committed
90 91 92
}

int Segmenter::getLeftD() const {
93
  return box_D->start;
Mikaël Salson's avatar
Mikaël Salson committed
94 95 96
}
  
int Segmenter::getRightD() const {
97
  return box_D->end;
Mikaël Salson's avatar
Mikaël Salson committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111
}

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

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

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

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

// 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
131 132 133 134 135 136 137 138
// Chevauchement

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

139
  if (box_V->end >= box_J->start)
Mikaël Salson's avatar
Mikaël Salson committed
140
    {
141 142 143 144
      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
145 146 147 148 149 150 151 152 153 154 155 156 157 158
    }

  return chevauchement ;
}

// Prettyprint


bool Segmenter::finishSegmentation() 
{
  assert(isSegmented());
  
  string seq = getSequence().sequence;
    
159 160 161 162 163
  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
164 165 166 167 168 169 170 171 172 173 174 175 176

  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;

177 178 179 180
  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
181
  
182 183 184 185
  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
186 187 188 189 190 191 192 193 194
		" " + string_of_int(seq.size()-1+FIRST_POS) ;
		
  info += "\t" + code ;
  
  info = (reversed ? "- " : "+ ") + info ;

  return true ;
}

195 196
string Segmenter::getInfoLine() const
{
197
  string s = "" ;
198 199 200 201 202

  s += (segmented ? "" : "! ") + info ;
  s += " " + info_extra ;
  s += " " + segmented_germline->code ;
  s += " " + string(segmented_mesg[because]) ;
203 204 205 206

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

207 208 209 210 211
  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);

212 213 214
  return s ;
}

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
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
231 232
ostream &operator<<(ostream &out, const Segmenter &s)
{
233
  out << ">" << s.label << " " ;
234
  out << s.getInfoLine() << endl;
Mikaël Salson's avatar
Mikaël Salson committed
235 236 237 238 239 240 241 242 243

  if (s.segmented)
    {
      out << s.seg_V << endl ;
      out << s.seg_N << endl ;
      out << s.seg_J << endl ;
    }
  else
    {
244
      out << s.getSequence().sequence << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
245 246 247 248 249 250 251 252
    }

  return out ;
}


// KmerSegmenter (Cheap)

253 254
KmerSegmenter::KmerSegmenter() { kaa = 0 ; }

255
KmerSegmenter::KmerSegmenter(Sequence seq, Germline *germline, double threshold, int multiplier)
Mikaël Salson's avatar
Mikaël Salson committed
256
{
257 258 259 260
  box_V = new AlignBox();
  box_D = new AlignBox();
  box_J = new AlignBox();

Mikaël Salson's avatar
Mikaël Salson committed
261 262 263
  label = seq.label ;
  sequence = seq.sequence ;
  info = "" ;
264
  info_extra = "seed";
Mikaël Salson's avatar
Mikaël Salson committed
265
  segmented = false;
266
  segmented_germline = germline ;
267
  system = germline->code; // useful ?
268
  reversed = false;
269
  because = NOT_PROCESSED ; // Cause of unsegmentation
270
  score = 0 ;
271
  evalue = NO_LIMIT_VALUE;
272 273
  evalue_left = NO_LIMIT_VALUE;
  evalue_right = NO_LIMIT_VALUE;
274

275
  int s = (size_t)germline->index->getS() ;
Mikaël Salson's avatar
Mikaël Salson committed
276
  int length = sequence.length() ;
Mikaël Salson's avatar
Mikaël Salson committed
277

278
  if (length < s) 
Mikaël Salson's avatar
Mikaël Salson committed
279
    {
Mathieu Giraud's avatar
Mathieu Giraud committed
280 281
      because = UNSEG_TOO_SHORT;
      kaa = NULL;
282
      return ;
Mikaël Salson's avatar
Mikaël Salson committed
283 284
    }
 
285
  kaa = new KmerAffectAnalyser(*(germline->index), sequence);
Mikaël Salson's avatar
Mikaël Salson committed
286 287
  
  // Check strand consistency among the affectations.
Mikaël Salson's avatar
Mikaël Salson committed
288 289 290 291 292 293 294 295 296
  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
297 298 299
    }
  }

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

302 303
  reversed = (nb_strand[0] > nb_strand[1]) ;

304 305
  if ((germline->seg_method == SEG_METHOD_MAX12)
      || (germline->seg_method == SEG_METHOD_MAX1U))
306 307 308 309
    { // Pseudo-germline, MAX12 and MAX1U
      pair <KmerAffect, KmerAffect> max12 ;
      CountKmerAffectAnalyser ckaa(*(germline->index), sequence);

310 311 312 313 314

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

315
      if (germline->seg_method == SEG_METHOD_MAX12)
316 317 318
        // MAX12: two maximum k-mers (no unknown)
        {
          max12 = ckaa.max12(forbidden);
319

320 321 322 323 324 325
          if (max12.first.isUnknown() || max12.second.isUnknown())
            {
              because = UNSEG_TOO_FEW_ZERO ;
              return ;
            }
        }
326

327 328
      else
        // MAX1U: the maximum k-mers (no unknown) + unknown
329
        {
330 331 332 333 334 335 336 337 338
          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());
339 340
        }

341 342 343 344 345
      pair <KmerAffect, KmerAffect> before_after =  ckaa.sortLeftRight(max12);

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

346 347 348
      // 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
349
      strand = reversed ? -1 : 1 ;
350 351 352 353 354
    }

  else
    { // Regular germline

355
  // Test on which strand we are, select the before and after KmerAffects
Mikaël Salson's avatar
Mikaël Salson committed
356
  if (nb_strand[0] == 0 && nb_strand[1] == 0) {
357
    because = UNSEG_TOO_FEW_ZERO ;
358
    return ;
Mikaël Salson's avatar
Mikaël Salson committed
359 360
  } else if (nb_strand[0] > RATIO_STRAND * nb_strand[1]) {
    strand = -1;
361 362
    before = KmerAffect(germline->affect_3, -1); 
    after = KmerAffect(germline->affect_5, -1);
Mikaël Salson's avatar
Mikaël Salson committed
363 364
  } else if (nb_strand[1] > RATIO_STRAND * nb_strand[0]) {
    strand = 1;
365 366
    before = KmerAffect(germline->affect_5, 1); 
    after = KmerAffect(germline->affect_3, 1);    
Mikaël Salson's avatar
Mikaël Salson committed
367 368
  } else {
    // Ambiguous information: we have positive and negative strands
369 370 371 372 373
    // 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 ;
374
    return ;
Mikaël Salson's avatar
Mikaël Salson committed
375 376
  }

377
    } // endif Pseudo-germline
378
 
379
  computeSegmentation(strand, before, after, threshold, multiplier);
Mathieu Giraud's avatar
Mathieu Giraud committed
380
}
Mikaël Salson's avatar
Mikaël Salson committed
381

Mathieu Giraud's avatar
Mathieu Giraud committed
382
KmerSegmenter::~KmerSegmenter() {
383 384
  if (kaa)
    delete kaa;
385 386
}

387 388
KmerMultiSegmenter::KmerMultiSegmenter(Sequence seq, MultiGermline *multigermline, ostream *out_unsegmented,
                                       double threshold, int nb_reads_for_evalue)
389
{
390 391
  bool found_seg = false ; // Found a segmentation
  double best_evalue_seg = NO_LIMIT_VALUE ; // Best evalue, segmented sequences
392
  int best_score_unseg = 0 ; // Best score, unsegmented sequences
393
  the_kseg = NULL;
394
  multi_germline = multigermline;
395
  threshold_nb_expected = threshold;
396 397 398

  // E-value multiplier
  int multiplier = multi_germline->germlines.size() * nb_reads_for_evalue;
399
  
400 401 402 403 404
  // Iterate over the germlines
  for (list<Germline*>::const_iterator it = multigermline->germlines.begin(); it != multigermline->germlines.end(); ++it)
    {
      Germline *germline = *it ;

405
      KmerSegmenter *kseg = new KmerSegmenter(seq, germline, threshold, multiplier);
406
      bool keep_seg = false;
407

408 409 410
      if (out_unsegmented)
        {
          // Debug, display k-mer affectation and segmentation result for this germline
411
          *out_unsegmented << kseg->getInfoLineWithAffects() << endl ;
412 413
        }

414 415
      // Always remember the first kseg
      if (the_kseg == NULL)
416
        keep_seg = true;
417
      
418
      if (kseg->isSegmented())
419 420
        {
          // Yes, it is segmented
421
          // Should we keep the kseg ?
422
          if (!found_seg || (kseg->evalue < best_evalue_seg))
423
            {
424
              keep_seg = true;
425 426 427
              best_evalue_seg = kseg->evalue ;

              found_seg = true;
428
            }
429
        }
430 431 432 433 434 435 436
      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 ;
437
              if (!found_seg)
438 439 440 441
                keep_seg = true;
            }
        }
      
442
      if (keep_seg) {
443 444
        if (the_kseg)
          delete the_kseg;
445 446 447 448
        the_kseg = kseg;
      } else {
        delete kseg;
      }
449 450 451
    } // end for (Germlines)
}

452
KmerMultiSegmenter::~KmerMultiSegmenter() {
453 454
  if (the_kseg)
    delete the_kseg;
Mathieu Giraud's avatar
Mathieu Giraud committed
455 456
}

457 458
void KmerSegmenter::computeSegmentation(int strand, KmerAffect before, KmerAffect after,
                                        double threshold, int multiplier) {
459
  // Try to segment, computing 'box_V->end' and 'box_J->start'
460 461
  // If not segmented, put the cause of unsegmentation in 'because'

462
  affect_infos max;
463
  max = kaa->getMaximum(before, after);
Mikaël Salson's avatar
Mikaël Salson committed
464

465 466 467
  // 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
468 469 470 471 472 473 474 475 476
    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 ;
477
    else
478
      because = UNSEG_TOO_FEW_ZERO ;
479 480 481 482 483

    return ;
  }


484
  // E-values
485 486 487
  pair <double, double> pvalues = kaa->getLeftRightProbabilityAtLeastOrAbove();
  evalue_left = pvalues.first * multiplier ;
  evalue_right = pvalues.second * multiplier ;
488
  evalue = evalue_left + evalue_right ;
489

490
  checkLeftRightEvaluesThreshold(threshold, strand);
491

492
  if (because != NOT_PROCESSED)
493 494
    return ;

495 496
   // There was a good segmentation point

497 498
   box_V->end = max.first_pos_max;
   box_J->start = max.last_pos_max + 1;
499
   if (strand == -1) {
500 501 502
     int tmp = sequence.size() - box_V->end - 1;
     box_V->end = sequence.size() - box_J->start - 1;
     box_J->start = tmp;
503 504 505 506 507 508
   }

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

509
  info = string_of_int(box_V->end + FIRST_POS) + " " + string_of_int(box_J->start + FIRST_POS)  ;
510 511 512 513 514 515

  // 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
516
}
Mikaël Salson's avatar
Mikaël Salson committed
517

518
KmerAffectAnalyser *KmerSegmenter::getKmerAffectAnalyser() const {
Mathieu Giraud's avatar
Mathieu Giraud committed
519 520
  return kaa;
}
Mikaël Salson's avatar
Mikaël Salson committed
521

522
int Segmenter::getSegmentationStatus() const {
Mathieu Giraud's avatar
Mathieu Giraud committed
523
  return because;
Mikaël Salson's avatar
Mikaël Salson committed
524 525
}

526 527 528 529 530
void Segmenter::setSegmentationStatus(int status) {
  because = status;
  segmented = (status == SEG_PLUS || status == SEG_MINUS);
}

Mikaël Salson's avatar
Mikaël Salson committed
531 532
// FineSegmenter

533

534
string check_and_resolve_overlap(string seq, int seq_begin, int seq_end,
535 536
                                 AlignBox *box_left, AlignBox *box_right,
                                 Cost segment_cost)
Mikaël Salson's avatar
Mikaël Salson committed
537
{
538
  // Overlap size
539
  int overlap = box_left->end - box_right->start + 1;
540 541 542

  if (overlap > 0)
    {
543 544
      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);
545

Mikaël Salson's avatar
Mikaël Salson committed
546 547 548 549
      int score_r[overlap+1];
      int score_l[overlap+1];
      
      //LEFT
550
      DynProg dp_l = DynProg(seq_left, box_left->ref,
Mikaël Salson's avatar
Mikaël Salson committed
551
			   DynProg::Local, segment_cost);
552
      score_l[0] = dp_l.compute();
553

Mikaël Salson's avatar
Mikaël Salson committed
554 555
      
      //RIGHT
556
      // reverse right sequence
557
      string ref_right=string(box_right->ref.rbegin(), box_right->ref.rend());
558 559 560
      seq_right=string(seq_right.rbegin(), seq_right.rend());


561
      DynProg dp_r = DynProg(seq_right, ref_right,
Mikaël Salson's avatar
Mikaël Salson committed
562
			   DynProg::Local, segment_cost);
563
      score_r[0] = dp_r.compute();
564 565 566 567 568 569 570 571 572



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

      for(int i=0; i<=overlap; i++) {
        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
573
      }
574

575 576 577 578 579 580

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

581 582
      cout << "seq:" << seq_left << "\t\t" << seq_right << endl;
      cout << "ref:" << ref_left << "\t\t" << ref_right << endl;
583 584 585 586 587 588 589 590
      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
591

592
      // Find (i, j), with i+j >= overlap,
593
      // maximizing score_l[j] + score_r[i]
Mikaël Salson's avatar
Mikaël Salson committed
594 595
      for (int i=0; i<=overlap; i++){
	for (int j=overlap-i; j<=overlap; j++){
596
          int score_ij = score_l[i] + score_r[j];
597

598 599 600
	  if (score_ij > score) {
            best_i = i ;
            best_j = j ;
601 602
            box_left->del_right = box_left->ref.size() - trim_l[i];
	    box_right->del_left = box_right->ref.size() - trim_r[j];
603
	    score = score_ij;
Mikaël Salson's avatar
Mikaël Salson committed
604 605 606
	  }
	}
      }
607

608 609
      box_left->end -= best_i ;
      box_right->start += best_j ;
610 611

#ifdef DEBUG_OVERLAP
612
      cout << "overlap: " << overlap << ", " << "best_overlap_split: " << score
613 614
           << "    left: " << best_i << "-" << box_left->del_right << " @" << box_left->end
           << "    right:" << best_j << "-" << box_right->del_left << " @" << box_right->start
615
           << endl;
616
#endif
617 618
    } // end if (overlap > 0)

619 620
  // 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
621 622
}

Mikaël Salson's avatar
Mikaël Salson committed
623 624 625 626 627
bool comp_pair (pair<int,int> i,pair<int,int> j)
{
  return ( i.first > j.first);
}

628 629 630 631 632

/**
 * Align a read against a collection of sequences, maximizing the alignment 'score'
 * @param read:         the read
 * @param rep:          a collection of reference sequences
633
 * @param reverse_ref:  if true, reverse the reference sequences (VkVk)
634
 * @param reverse_both: if true, reverse both the read and the reference sequences (J segment)
635
 * @param local:        if true, Local alignment (D segment), otherwise LocalEndWithSomeDeletions and onlyBottomTriangle (V and J segments)
636
 * @param box:          the AligBox to fill
637
 * @param segment_cost: the cost used by the dynamic programing
638
 * @post  box is filled
639 640
 */

641
void align_against_collection(string &read, Fasta &rep, bool reverse_ref, bool reverse_both, bool local,
642
                             AlignBox *box, Cost segment_cost)
Mikaël Salson's avatar
Mikaël Salson committed
643 644 645
{
  
  int best_score = MINUS_INF ;
646
  box->ref_nb = MINUS_INF ;
Mikaël Salson's avatar
Mikaël Salson committed
647 648 649 650
  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 ;
651

Mikaël Salson's avatar
Mikaël Salson committed
652
  vector<pair<int, int> > score_r;
Mikaël Salson's avatar
Mikaël Salson committed
653 654 655

  DynProg::DynProgMode dpMode = DynProg::LocalEndWithSomeDeletions;
  if (local==true) dpMode = DynProg::Local;
656 657 658

  // 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
659 660 661
  
  for (int r = 0 ; r < rep.size() ; r++)
    {
662
      DynProg dp = DynProg(sequence_or_rc, rep.sequence(r),
Mikaël Salson's avatar
Mikaël Salson committed
663 664 665
			   dpMode, // DynProg::SemiGlobalTrans, 
			   segment_cost, // DNA
			   reverse_both, reverse_both);
666 667 668

      bool onlyBottomTriangle = !local ;
      int score = dp.compute(onlyBottomTriangle, BOTTOM_TRIANGLE_SHIFT);
Mikaël Salson's avatar
Mikaël Salson committed
669
      
Mikaël Salson's avatar
Mikaël Salson committed
670 671 672 673 674 675 676 677 678 679 680
      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 ;
681 682
	  box->ref_nb = r ;
	  box->ref_label = rep.label(r) ;
Mikaël Salson's avatar
Mikaël Salson committed
683
	}
Mikaël Salson's avatar
Mikaël Salson committed
684 685
	
	score_r.push_back(make_pair(score, r));
Mathieu Giraud's avatar
Mathieu Giraud committed
686 687 688 689 690 691

	// #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
692 693

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

696 697 698 699
  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
700
  
701
  box->score = score_r;
Mathieu Giraud's avatar
Mathieu Giraud committed
702 703 704

#ifdef DEBUG_SEGMENT	
  cout << "best: " << best_labels << " " << best_score ;
705
  cout << "del/del2/begin:" << (box->del_right) << "/" << (box->del_left) << "/" << (box->start) << endl;
Mathieu Giraud's avatar
Mathieu Giraud committed
706 707
  cout << endl;
#endif
708 709 710 711

  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 ;
712 713

  box->end = best_best_i ;
Mikaël Salson's avatar
Mikaël Salson committed
714 715 716 717 718 719 720
}

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

721
FineSegmenter::FineSegmenter(Sequence seq, Germline *germline, Cost segment_c,  double threshold, int multiplier)
Mikaël Salson's avatar
Mikaël Salson committed
722
{
723 724 725 726
  box_V = new AlignBox();
  box_D = new AlignBox();
  box_J = new AlignBox();

727 728
  segmented = false;
  dSegmented = false;
729
  because = NOT_PROCESSED ;
730
  segmented_germline = germline ;
731
  info_extra = "" ;
Mikaël Salson's avatar
Mikaël Salson committed
732 733 734
  label = seq.label ;
  sequence = seq.sequence ;
  segment_cost=segment_c;
735
  evalue = NO_LIMIT_VALUE;
736 737
  evalue_left = NO_LIMIT_VALUE;
  evalue_right = NO_LIMIT_VALUE;
Mikaël Salson's avatar
Mikaël Salson committed
738

739 740
  CDR3start = -1;
  CDR3end = -1;
741

742 743 744
  bool reverse_V = false ;
  bool reverse_J = false ;

745
  if ((germline->seg_method == SEG_METHOD_MAX12) || (germline->seg_method == SEG_METHOD_MAX1U))
746
    {
747
      // We check whether this sequence is segmented with MAX12 or MAX1U (with default e-value parameters)
748
      KmerSegmenter *kseg = new KmerSegmenter(seq, germline, THRESHOLD_NB_EXPECTED, 1);
749
      if (kseg->isSegmented())
750
        {
751 752 753 754 755
          reversed = kseg->isReverse();

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

756 757
          delete kseg ;

758 759 760
          reverse_V = (left.getStrand() == -1);
          reverse_J = (right.getStrand() == -1);

761
          code = "Unexpected ";
762

763 764 765 766
          code += left.toStringSigns() + germline->index->getLabel(left).name;
          code += "/";
          code += right.toStringSigns() + germline->index->getLabel(right).name;
          info_extra += " " + left.toString() + "/" + right.toString() + " (" + code + ")";
767 768 769 770 771

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

          germline->override_rep5_rep3_from_labels(left, right);
772
        }
773
      else
774 775 776 777
        {
          delete kseg ;
          return ;
        }
778
    }
779

780 781 782 783 784 785 786
  // 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();
787
  delete kseg ;
Mikaël Salson's avatar
Mikaël Salson committed
788
  
789 790
  string sequence_or_rc = revcomp(sequence, reversed); // sequence, possibly reversed

Mathieu Giraud's avatar
Mathieu Giraud committed
791 792

  /* Segmentation */
793
  align_against_collection(sequence_or_rc, germline->rep_5, reverse_V, reverse_V, false,
794
                                        box_V, segment_cost);
795

796
  align_against_collection(sequence_or_rc, germline->rep_3, reverse_J, !reverse_J, false,
797
                                          box_J, segment_cost);
798 799 800 801 802

  // 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;
803

804
  /* E-values */
805 806
  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);
807
  evalue = evalue_left + evalue_right ;
808 809

  /* Unsegmentation causes */
810
  if (box_V->end == (int) string::npos)
811
    {
812
      evalue_left = BAD_EVALUE ;
813
    }
814
      
815
  if (box_J->start == (int) string::npos)
816
    {
817
      evalue_right = BAD_EVALUE ;
818 819
    }

820 821
  checkLeftRightEvaluesThreshold(threshold, reversed ? -1 : 1);

822 823 824
  if (because != NOT_PROCESSED)
    {
      segmented = false;
825
      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
826 827
      return ;
    }
828 829 830 831

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

Mikaël Salson's avatar
Mikaël Salson committed
833
    //overlap VJ
834
  seg_N = check_and_resolve_overlap(sequence_or_rc, 0, sequence_or_rc.length(),
835
                                    box_V, box_J, segment_cost);
836

837
  // Why could this happen ?
838 839
      if (box_J->start>=(int) sequence.length())
	  box_J->start=sequence.length()-1;
Mikaël Salson's avatar
Mikaël Salson committed
840

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

843 844
  code = box_V->ref_label +
    " "+ string_of_int(box_V->del_right) +
Mikaël Salson's avatar
Mikaël Salson committed
845 846
    "/" + seg_N + 
    // chevauchement +
847 848
    "/" + string_of_int(box_J->del_left) +
    " " + box_J->ref_label;
Mikaël Salson's avatar
Mikaël Salson committed
849

850
  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
851 852 853
  finishSegmentation();
}

854
bool FineSegmenter::FineSegmentD(Germline *germline,
855
                                 AlignBox *box_Y, AlignBox *box_DD, AlignBox *box_Z,
856
                                 double evalue_threshold, int multiplier){
857

Mikaël Salson's avatar
Mikaël Salson committed
858
    // Create a zone where to look for D, adding at most EXTEND_D_ZONE nucleotides at each side
859
    int l = box_Y->end - EXTEND_D_ZONE;
Mikaël Salson's avatar
Mikaël Salson committed
860 861 862
    if (l<0) 
      l=0 ;

863
    int r = box_Z->start + EXTEND_D_ZONE;
Mikaël Salson's avatar
Mikaël Salson committed
864

865 866 867 868
    string seq = getSequence().sequence; // segmented sequence, possibly rev-comped

    if (r > (int) seq.length())
      r = seq.length();
Mikaël Salson's avatar
Mikaël Salson committed
869
      
870
    string str = seq.substr(l, r-l);
Mikaël Salson's avatar
Mikaël Salson committed
871 872

    // Align
873
    align_against_collection(str, germline->rep_4, false, false, true,
874
                                           box_DD, segment_cost);
875

876 877 878 879
    box_DD->start += l ;
    box_DD->end += l ;

    float evalue_D = multiplier * (r-l) * germline->rep_4.totalSize() * segment_cost.toPValue(box_DD->score[0].first);
880

881
    if (evalue_D > evalue_threshold)
882
      return false;
Mikaël Salson's avatar
Mikaël Salson committed
883 884
    
    //overlap VD
885 886
    seg_N1 = check_and_resolve_overlap(seq, 0, box_DD->end,
                                       box_Y, box_DD, segment_cost);
Mikaël Salson's avatar
Mikaël Salson committed
887 888
    
    //overlap DJ
889 890
    seg_N2 = check_and_resolve_overlap(seq, box_DD->start, seq.length(),
                                       box_DD, box_Z, segment_cost);
891 892 893 894 895 896 897 898 899

    return true;
}

void FineSegmenter::FineSegmentD(Germline *germline, double evalue_threshold, int multiplier){

  if (segmented){

    dSegmented = FineSegmentD(germline,
900
                              box_V, box_D, box_J,
901 902 903 904
                              evalue_threshold, multiplier);

    if (!dSegmented)
      return ;
905

906 907
    code = box_V->ref_label +
    " "+ string_of_int(box_V->del_right) +
Mikaël Salson's avatar
Mikaël Salson committed
908 909
    "/" + seg_N1 + 
    
910 911 912
    "/" + string_of_int(box_D->del_left) +
    " " + box_D->ref_label +
    " " + string_of_int(box_D->del_right) +
Mikaël Salson's avatar
Mikaël Salson committed
913 914
    
    "/" + seg_N2 +
915 916
    "/" + string_of_int(box_J->del_left) +
    " " + box_J->ref_label;
Mikaël Salson's avatar
Mikaël Salson committed
917
    
Mikaël Salson's avatar
Mikaël Salson committed
918 919 920
    finishSegmentationD();
  }
}
Mikaël Salson's avatar
Mikaël Salson committed
921

Marc Duez's avatar
Marc Duez committed
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
void FineSegmenter::findCDR3(){
    string str = getSequence().sequence;
    
    list<string> codon_start;
    codon_start.push_back("TGT");
    codon_start.push_back("TGC");
    
    list<string> codon_end;
    codon_end.push_back("TTT");
    codon_end.push_back("TTC");
    codon_end.push_back("TGG");
    
    list<int> p_start;
    list<int> p_end;

    size_t loc;
    std::list<string>::const_iterator it;
    for (it = codon_start.begin(); it != codon_start.end(); ++it) {//filter 1 : start codon must be in V
        loc = 0;
941
        while ( loc != string::npos && loc < (size_t)box_V->end){
Marc Duez's avatar
Marc Duez committed
942
            loc = str.find(*it, loc+3);
943
            if (loc != string::npos && loc < (size_t)box_V->end) {
Marc Duez's avatar
Marc Duez committed
944 945 946 947 948 949
                p_start.push_front(loc);
            }
        }
    }

    for (it = codon_end.begin(); it != codon_end.end(); ++it) {//filter 2 : end codon must be in J
950
        loc = box_J->start;
Marc Duez's avatar
Marc Duez committed
951 952 953 954 955 956 957 958
        while ( loc != string::npos){
            loc = str.find(*it, loc+3);
            if (loc != string::npos) {
                p_end.push_back(loc);
            }
        }
    }

959 960
    CDR3start = -1;
    CDR3end = -1;
Marc Duez's avatar
Marc Duez committed
961 962 963 964 965 966 967 968 969 970