affectanalyser.h 17.9 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1 2 3 4 5 6 7
#ifndef AFFECT_ANALYSER_H
#define AFFECT_ANALYSER_H

#include "kmerstore.h"
#include <set>
#include <vector>
#include <cassert>
8
#include <map>
Mikaël Salson's avatar
Mikaël Salson committed
9 10 11 12 13 14 15 16 17

// Define two constant affectations: ambiguous and unknown.

/* Declaration of types */

typedef enum affect_options_e {
  AO_NONE, AO_NO_CONSECUTIVE, AO_NO_MULTIPLICITY
} affect_options_t;

18 19

/* Stores results during .getMaximum() computation */
20 21 22 23 24 25 26 27 28 29 30
typedef struct affect_infos_s {
  int first_pos_max;            /* First position of maximum */
  int last_pos_max;             /* Last position of maximum */
  int max_value;                /* Maximal value */
  int nb_before_right;          /* Nb of “before” right of the maximum */
  int nb_after_right;           /* Same with “after” */
  int nb_before_left;           /* Nb of “before” left of the maximum */
  int nb_after_left;            /* Same with “after” */
  bool max_found;               /* We have found a maximum */
} affect_infos;

31 32
bool operator==(const affect_infos &ai1, const affect_infos &ai2);

Mikaël Salson's avatar
Mikaël Salson committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/**
 * Class that records for every k-mer of a given sequence
 * in which sequences this k-mer was also seen.
 * It can either record one affectation per kmer (the only sequence where it
 * occurs or ambiguous case if there are several possibilities, or 
 * unknown otherwise), or all the possible affectations (ie. there is no ambiguous
 * case, all the possibilities for one k-mer are stored).
 *
 * Input: Index that constitutes the k-mer sequence repertoire
 * Input: Sequence whose k-mers must be affected
 */
template<class T>
class AffectAnalyser {
 public:

48 49
  virtual ~AffectAnalyser() {}

Mikaël Salson's avatar
Mikaël Salson committed
50 51 52 53 54 55 56 57 58 59 60
  /* Queries */

  /**
   * @return the total number of affectations
   */
  virtual int count() const = 0;

  /**
   * @param affect: An affectation
   * @return the number of times this affectation has been given in the read.
   */
61
  virtual int count(const T &affect) const = 0;
Mikaël Salson's avatar
Mikaël Salson committed
62 63 64 65 66 67 68 69 70 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 106 107 108 109 110 111 112 113 114

  /**
   * @param i: the position to consider
   * @pre i >= 0 && i < count()
   * @return the affectation of the k-mer at position i.
   */
  virtual const T&getAffectation(int i)  const = 0;

  /**
   * @param options: options can either be AO_NONE or AO_NO_CONSECUTIVE 
   * @return all the affectations contained in the read from left to right.
   *         if AO_NO_CONSECUTIVE is given: two consecutive elements in the vector
   *                                     will be different (we remove consecutive
   *                                     duplicates)
   */
  virtual vector<T> getAllAffectations(affect_options_t options) const = 0;

  /**
   * @return the distinct affectations
   */
  virtual set<T> getDistinctAffectations() const = 0;

  /**
   * @return the sequence we are analysing
   */
  virtual const string &getSequence() const = 0;

  /**
   * @param affect: an affectation
   * @return the first occurrence of this affectation in the read
   *         or string::npos if the affectation was not found
   * @post getAffectation(first(affect)) == affect 
   * ==>  getAffectation(1...first(affect)-1) != affect
   */
  virtual int first(const T &affect) const  = 0;

  /**
   * @param affect: an affectation
   * @return the last occurrence of this affectation in the read
   *         or string::npos if the affectation was not found
   * @post getAffectation(last(affect)) == affect 
   * ==> getAffectation(last(affect)+1 ... count() -1) != affect
   */
  virtual int last(const T &affect) const  = 0;

  /**
   * @return a string representation of the object
   */
  virtual string toString() const  = 0;
};

template <class T>
class KmerAffectAnalyser: public AffectAnalyser<T> {
115
 protected:
Mikaël Salson's avatar
Mikaël Salson committed
116 117 118 119 120 121 122 123 124 125
  IKmerStore<T> &kms;
  const string &seq;
  vector<T> affectations;
 public:
  /**
   * @param kms: the index storing the affectation for the k-mers
   *             (parameter is not copied)
   * @param seq: the sequence to analyse (parameter is not copied)
   */
  KmerAffectAnalyser(IKmerStore<T> &kms, const string &seq);
126 127 128 129 130 131 132 133 134 135 136 137

  /**
   * This constructor must be seen as a “toy” constructor, used for 
   * testing.
   * It allows to directly provide the affectation and therefore avoids
   * the need to search a long time for good example that could be tested.
   * @param kms: mainly used for retrieving the seed or its size
   * @param seq: basically not used in the class
   * @param a: the affectation we must use.
   */
  KmerAffectAnalyser(IKmerStore<T> &kms, const string &seq, vector<T> a);

Mikaël Salson's avatar
Mikaël Salson committed
138 139 140 141 142 143 144 145 146 147 148 149
  ~KmerAffectAnalyser();

  int count() const;

  int count(const T &affect) const;

  const T&getAffectation(int i) const;

  vector<T> getAllAffectations(affect_options_t options) const;

  set<T> getDistinctAffectations() const;

150
  /**
151 152
   * @param maxOverlap: if greater than kms.getS(), it is automatically set
   *                    to that value.
153 154 155 156 157 158 159 160 161 162 163 164 165 166
   * @return A structure where the maximum is such that those positions
   *         maximise the number of affectations before, minus the number of
   *         affectations after the returned positions.
   *
   *         The maximum reached must be above max(0, total number of
   *         <before>) and such that the number of <before> after the
   *         rightmost max position is <ratioMin> times less than the number
   *         of <after> after that position. If no so much maximum is found,
   *         the boolean <max_found> is set to false in the structure.
   *
   * @complexity time: linear in count(), space: constant
   */
  affect_infos getMaximum(const T &before, const T &after, 
                          float ratioMin=2., 
167
                          int maxOverlap=1) const;
168

Mikaël Salson's avatar
Mikaël Salson committed
169 170 171 172 173 174 175 176 177
  const string &getSequence() const;

  int first(const T &affect) const;

  int last(const T &affect) const ;

  string toString() const;
};

178 179 180 181 182 183 184 185
/**
 * Class that allows to count in constant time the number of affectations
 * before or after a given point.
 */
template <class T>
class CountKmerAffectAnalyser: public KmerAffectAnalyser<T> {
 private:
  map<T, int* >counts;
186
  int overlap;
187 188 189 190 191
 public:

  CountKmerAffectAnalyser(IKmerStore<T> &kms, const string &seq);
  ~CountKmerAffectAnalyser();

192 193
  int count() const;

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  /**
   * @complexity constant time
   */
  int count(const T &affect) const;

  /**
   * Count the number of an affectation before (strictly) than a position
   * @complexity constant time
   */
  int countBefore(const T&affect, int pos) const;

  /**
   * Count the number of an affectation after (strictly) than a position)
   * @complexity constant time
   */
  int countAfter(const T&affect, int pos) const;

  /**
   * @return the first position pos in the sequence such that 
213
   *         countBefore(before, pos - s) 
214
             + countAfter(after, pos) is maximal
215
   *         and pos >= start, and the maximum is greater than min; 
216
   *         or -1 if such a position doesn't exist.
217
   *         Where s is kms.getS() - getAllowedOverlap() - 1.
218 219
   * @complexity linear in getSequence().size() 
   */
220
  int firstMax(const T&before, const T&after, int start=0, int min=-1) const;
221 222 223

  /**
   * @return the last position pos in the sequence such that
224
   *         countBefore(before, pos - s) 
225
   *         + countAfter(after, pos) is maximal
226 227
   *         and pos <= end (if end == -1 considers end of sequence), and the 
   *         maximum is greater than min; or -1 if such a position doesn't exist.
228
   *         Where s is kms.getS() - getAllowedOverlap() - 1.
229 230
   * @complexity linear in getSequence().size()
   */
231
  int lastMax(const T&before, const T&after, int end=-1, int min=-1) const;
232

233 234 235 236 237 238
  /**
   * @return the allowed overlap between two k-mers with distinct affectations
   * (default is 0)
   */
  int getAllowedOverlap();

239 240 241 242 243 244 245 246 247 248 249
  /**
   * @parameter forbidden: a set of forbidden affectations that must not 
   *                       be taken into account for the max computation.
   * @pre There must have at least one affectation that is not forbidden otherwise
   *      the returned value is the unknown affectation.
   * @return the affectation that is seen the most frequently in the sequence
   *         taken apart the forbidden ones.
   * @complexity Time: linear on the number of distinct affectations
   */
  T max(const set<T> forbidden = set<T>()) const;

250 251 252 253 254 255 256
  /**
   * Set the overlap allowed between two k-mers with two different affectations,
   * when looking for the maximum.
   * The overlap should not be greater than the span of the seed used.
   */
  void setAllowedOverlap(int overlap);

257 258 259 260 261 262 263 264
 private:
  /**
   * Build the counts map.
   */
  void buildCounts();

  /**
   * Search the maximum. Used by firstMax and lastMax.
265
   * @param iter: should be either 1 or -1
266 267
   */
  int searchMax(const T&before, const T &after,
268
                int start, int end, int iter, int min) const;
269
};
Mikaël Salson's avatar
Mikaël Salson committed
270 271 272 273 274 275 276 277 278

template <class T>
KmerAffectAnalyser<T>::KmerAffectAnalyser(IKmerStore<T> &kms, 
                                       const string &seq)
  :kms(kms), seq(seq) {
  assert(seq.length() >=  (size_t)kms.getS());
  affectations = kms.getResults(seq, true);
}

279 280 281 282 283 284
template <class T>
KmerAffectAnalyser<T>::KmerAffectAnalyser(IKmerStore<T> &kms,
                                          const string &seq,
                                          vector <T> a):
kms(kms), seq(seq), affectations(a){}

Mikaël Salson's avatar
Mikaël Salson committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
template <class T>
KmerAffectAnalyser<T>::~KmerAffectAnalyser(){}

template <class T>
int KmerAffectAnalyser<T>::count() const{
  return affectations.size();
}

template <class T>
int KmerAffectAnalyser<T>::count(const T &affect) const{
  int count = 0;
  for (typename vector<T>::const_iterator it = affectations.begin(); 
       it < affectations.end(); it++) {
    if (*it == affect)
      count++;
  }
  return count;
}

template <class T>
const T&KmerAffectAnalyser<T>::getAffectation(int i) const{
  assert(i >= 0 && i < count());
  return affectations[i];
}

template <class T>
vector<T> KmerAffectAnalyser<T>::getAllAffectations(affect_options_t options) const{
  if (options == AO_NONE)
    return affectations;
  vector<T> result;
  T previous = affectations[0];
  result.push_back(previous);
  for (size_t i = 1; i < affectations.size(); i++) {
318 319 320 321
    if (! (previous == affectations[i])) {
      result.push_back(affectations[i]);
      previous = affectations[i];
    }
Mikaël Salson's avatar
Mikaël Salson committed
322 323 324 325 326 327 328 329 330 331 332 333 334
  }
  return result;
}

template <class T>
set<T> KmerAffectAnalyser<T>::getDistinctAffectations() const{
  set<T> result;
  for (size_t i = 0; i < affectations.size(); i++) {    
    result.insert(affectations[i]);
  }
  return result;
}

335 336 337 338 339
template <class T>
affect_infos KmerAffectAnalyser<T>::getMaximum(const T &before, 
                                               const T &after, 
                                               float ratioMin,
                                               int maxOverlap) const {
340
  /* currentValue is the  { affectations[t] == before | t \in 1..i  } - | { affectations[i] == after | t \in 1..i }  */
341 342 343 344 345
  int currentValue;
  int span = kms.getS();
  int length = count();
  affect_infos results;

346 347
  if (maxOverlap > span)
    maxOverlap = span;
348

349
  /* Initialize results */
350 351 352 353 354 355
  results.max_found = false;
  results.max_value = 0;
  results.first_pos_max = results.last_pos_max = -1;
  results.nb_before_left = results.nb_before_right = results.nb_after_right = results.nb_after_left = 0;
  currentValue = 0;

356
  for (int i = 0; i < min(length,span - maxOverlap); i++) {
357 358 359 360 361 362 363 364
    if (affectations[i] == after) {
      currentValue--;
      results.nb_after_right++;
    }
  }

  for (int i = span - maxOverlap; i < length; i++) {
    /* i - span + maxOverlap, to avoir overlapping k-mers */
365 366 367 368 369


    /* Read the current affectations, and store them both in currentValue and at the right of the previous maximum.
       The affectation of 'before' is interpreted relatively to span and maxOverlap */

370 371 372 373 374 375 376 377
    if (affectations[i - span + maxOverlap] == before) {
      currentValue++;
      results.nb_before_right++;
    } 
    if (affectations[i] == after) {
      currentValue--;
      results.nb_after_right++;
    }
378 379 380 381

    /* Now currentValue = | { affectations[t - span + maxOverlap] == 'before' | t \in span-maxOverlap..i } | - | { affectations[i] == 'after' | t \in 0..i } | */

    /* If we raise above the max, or if we continue a previous maximum (even from a distant position), store in results */
382 383 384 385 386
    if (currentValue >= results.max_value) {
      if (currentValue > results.max_value)
        results.first_pos_max = i;
      results.max_value = currentValue;
      results.last_pos_max = i;
387 388

      /* What was at the right of the previous maximum is now at the left of the current maximum */
389 390 391 392 393 394
      results.nb_after_left += results.nb_after_right;
      results.nb_before_left += results.nb_before_right;
      results.nb_after_right = 0;
      results.nb_before_right = 0;
    }
  }
395
  for (int i = length - span + maxOverlap; i < length && i >= 0; i++) {
396 397 398 399
    if (affectations[i] == before)
      results.nb_before_right++;
  }

400 401 402 403 404 405
  /* Main test: 
     1) do we have enough affectations in good positions ('before' at the left and 'after' at the right) ?
     We tolerate some of them in bad positions, but there must be 'ratioMin' more in good positions
     2) there should be at least one 'before' and one 'after' (? CHECK ?)
  */

406 407 408 409 410 411 412 413 414 415
  if (results.nb_after_right >= results.nb_before_right*ratioMin
      && (results.nb_after_right > 0 || results.nb_before_right == 0)
      && currentValue < results.max_value
      && results.max_value > 0) {
    results.max_found = true;
    return results;
  }
  return results;
}

Mikaël Salson's avatar
Mikaël Salson committed
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
template <class T>
const string &KmerAffectAnalyser<T>::getSequence() const{
  return seq;
}

template <class T>
int KmerAffectAnalyser<T>::first(const T &affect) const{
  for (size_t i = 0; i < affectations.size(); i++) 
    if (affect == affectations[i])
      return i;
  return (int) string::npos;
}

template <class T>
int KmerAffectAnalyser<T>::last(const T &affect) const{
  for (size_t i = affectations.size(); i > 0;  i--) 
    if (affect == affectations[i-1])
      return i-1;
  return (int) string::npos;
}

template <class T>
string KmerAffectAnalyser<T>::toString() const{
  string kmer;
440 441 442 443 444 445
  for (size_t i = 0; i < affectations.size(); i++) {
    kmer += affectations[i].toString();
#ifdef DEBUG_KMERS
    kmer += ": "+spaced(seq.substr(i,kms.getS()), kms.getSeed())+"\n";
#endif
  }
Mikaël Salson's avatar
Mikaël Salson committed
446 447 448
  return kmer;
}

449 450 451 452 453
/* CountKmerAffectAnalyser */

template <class T>
CountKmerAffectAnalyser<T>::CountKmerAffectAnalyser(IKmerStore<T> &kms, const string &seq): KmerAffectAnalyser<T>(kms, seq) {
  buildCounts();
454
  overlap=0;
455 456 457 458 459 460 461 462 463 464 465 466 467
}

template <class T>
CountKmerAffectAnalyser<T>::~CountKmerAffectAnalyser() {
  set<T> affects = this->getDistinctAffectations();

  /* Initialize each key with a 0-integer array */
  for (typename set<T>::iterator it = affects.begin(); 
       it != affects.end(); it++) {
    delete [] counts[*it];
  }  
}

468 469 470 471 472
template <class T>
int CountKmerAffectAnalyser<T>::count() const {
  return KmerAffectAnalyser<T>::count();
}

473 474 475 476 477 478 479 480
template <class T>
int CountKmerAffectAnalyser<T>::count(const T &affect) const {
  if (counts.count(affect) == 0)
    return 0;

  return counts.find(affect)->second[KmerAffectAnalyser<T>::count() - 1];
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
template <class T>
T CountKmerAffectAnalyser<T>::max(const set<T> forbidden) const {
  typename map<T, int* >::const_iterator it = counts.begin();
  T max_affect = T::getUnknown();
  int max_count = -1;

  for (; it != counts.end(); it++) {
    if (forbidden.count(it->first) == 0) {
      int current_count = count(it->first);
      if (current_count > max_count) {
        max_affect = it->first;
        max_count = current_count;
      }
    }
  }

  return max_affect;
}

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
template <class T>
int CountKmerAffectAnalyser<T>::countBefore(const T&affect, int pos) const {
  if (pos == 0 || counts.count(affect) == 0)
    return 0;
  return counts.find(affect)->second[pos-1];
}

template <class T>
int CountKmerAffectAnalyser<T>::countAfter(const T&affect, int pos) const {
  if (counts.count(affect) == 0)
    return 0;
  int length = KmerAffectAnalyser<T>::count();
  typename map<T, int*>::const_iterator it = counts.find(affect);
  return it->second[length-1] - it->second[pos];
}  

template <class T>
int CountKmerAffectAnalyser<T>::firstMax(const T&before, const T&after, 
518 519
                                         int start, int min) const {
  return searchMax(before, after, start, KmerAffectAnalyser<T>::count()-1,1, min);
520 521 522 523
}

template <class T>
int CountKmerAffectAnalyser<T>::lastMax(const T&before, const T&after, 
524
                                        int end, int min) const {
525 526
  if (end == -1)
    end = KmerAffectAnalyser<T>::count()-1;
527
  return searchMax(before, after, end, 0, -1, min);
528 529
}

530 531 532 533 534 535 536 537 538 539
template <class T>
int CountKmerAffectAnalyser<T>::getAllowedOverlap() {
  return overlap;
}

template <class T>
void CountKmerAffectAnalyser<T>::setAllowedOverlap(int overlap) {
  this->overlap = overlap;
}

540 541
template <class T>
int CountKmerAffectAnalyser<T>::searchMax(const T&before, const T& after,
542
                                          int start, int end, int iter, int min) const {
543 544
  if (count(before) == 0 || count(after) == 0)
    return -1;
545
  int first_pos_max = -1;
546
  int max_value = min;
547
  int shift = KmerAffectAnalyser<T>::kms.getS() - overlap - 1;
548 549 550 551 552 553
  int shiftedStart = start, shiftedEnd = end;
  if (iter == 1)
    shiftedStart += shift;
  else
    shiftedEnd += shift;
  for (int i = shiftedStart; (i)*iter <= iter*shiftedEnd; i+=iter) {
554 555 556 557 558
    int valueBefore = countBefore(before, i - shift);
    int valueAfter = countAfter(after, i);
    if (valueAfter + valueBefore > max_value 
        && valueAfter > 0 && valueBefore > 0) {
      max_value = valueAfter + valueBefore;
559 560 561 562 563 564 565 566 567 568 569 570 571
      first_pos_max = i;
    }
  }
  return first_pos_max;
}

template <class T>
void CountKmerAffectAnalyser<T>::buildCounts() {
  int length = KmerAffectAnalyser<T>::count();
  set<T> affects = this->getDistinctAffectations();

  for (typename set<T>::iterator it = affects.begin(); 
       it != affects.end(); it++) {
572 573 574
    int *array = new int[length];
    /* Initialize each key with a 0-integer array */
    array[0] = (this->getAffectation(0) == *it) ? 1 : 0;
575

576 577 578
    /* Fill the array with actual values */
    for (int i = 1; i < length; i++) {
      T current = this->getAffectation(i);
579 580
      int value = (current == *it) ? 1 : 0;

581
      array[i] = array[i-1]+value;
582
    }
583
    counts[*it] = array;
584
  }
585

586 587
}

Mikaël Salson's avatar
Mikaël Salson committed
588
#endif