kmerstore.h 15.9 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1 2 3 4 5 6 7 8
#ifndef KMERSTORE_H
#define KMERSTORE_H

#include <map>
#include <string>
#include <list>
#include <stdexcept>
#include <stdint.h>
9
#include <math.h>
Mikaël Salson's avatar
Mikaël Salson committed
10 11 12 13 14 15 16 17 18 19
#include "fasta.h"
#include "tools.h"

using namespace std;

class Kmer {
public:
  unsigned int count;

  Kmer();
20 21 22 23

  /**
   * This constructor is used via a IKmerStore<Kmer> index (hence the argument list)       
   */
24
  Kmer(const string &label, int strand=1, size_t length=0);
25

Mikaël Salson's avatar
Mikaël Salson committed
26
  Kmer &operator+=(const Kmer &);
27

28 29 30 31 32
  /**
   * @return the length of the kmer (only there for compatibility with KmerAffect)
   */
  size_t getLength() const;

33 34 35 36
  /**
   * When indexing revcomp, should the value be the same or not?
   * In other words, does the information stored by the class is strand-dependent?
   */
Mikaël Salson's avatar
Mikaël Salson committed
37
  static bool hasRevcompSymetry();
38 39 40 41

  /**
   * @return true if the element is the same as when initialised with default constructor.
   */
42 43 44 45 46 47 48
  bool isNull() const;

  /**
   * @return true iff the kmer is unknown (which doesn't make sense here but
   * it only there for a reason of compatibility with KmerAffect)
   */
  bool isUnknown() const;
Mikaël Salson's avatar
Mikaël Salson committed
49 50
} ;
ostream &operator<<(ostream &os, const Kmer &kmer);
51 52 53 54 55 56 57
bool operator==(const Kmer &k1, const Kmer &k2);
bool operator<(const Kmer &k1, const Kmer &k2);
bool operator>(const Kmer &k1, const Kmer &k2);
bool operator<=(const Kmer &k1, const Kmer &k2);
bool operator>=(const Kmer &k1, const Kmer &k2);
bool operator!=(const Kmer &k1, const Kmer &k2);

Mikaël Salson's avatar
Mikaël Salson committed
58 59 60 61 62 63 64 65 66 67 68


/* K-mer indexing */

template <class T> class IKmerStore
{
protected:
  bool revcomp_indexed;
  int k; // weight of the seed
  int s; // span of the seed (s >= k)
  string seed ;
69
  size_t nb_kmers_inserted;
70
  size_t max_size_indexing;
71
  bool finished_building;
Mikaël Salson's avatar
Mikaël Salson committed
72 73 74 75 76

public:

  virtual ~IKmerStore();

77 78
  static int last_id;
  int id; // id of this index
79
  int refs; // number of germlines using this index
80

81
  list< pair <T, Fasta> > labels;
82

83 84
  IKmerStore();

Mikaël Salson's avatar
Mikaël Salson committed
85 86 87
  /**
   * @param input: A single FASTA file
   * @param label: label that must be associated to the given files
88
   * @param seed: the seed to use for indexing. By default it will be the seed of the index
89
   * @post All the sequences in the FASTA files have been indexed, and the label is stored in the list of labels
Mikaël Salson's avatar
Mikaël Salson committed
90
   */
91
  void insert(Fasta& input, const string& label="", int keep_only = 0, string seed = "");
Mikaël Salson's avatar
Mikaël Salson committed
92 93 94 95

  /**
   * @param input: A list of FASTA files
   * @param label: label that must be associated to the given files
96
   * @param seed: the seed to use for indexing. By default it will be the seed of the index
97
   * @post All the sequences in the FASTA files have been indexed, and the label is stored in the list of labels
Mikaël Salson's avatar
Mikaël Salson committed
98
   */
99
  void insert(list<Fasta>& input, const string& label="", int keep_only = 0, string seed = "");
Mikaël Salson's avatar
Mikaël Salson committed
100 101 102 103
  
  /**
   * @param input: A sequence to be cut in k-mers
   * @param label: label that must be associated to the given files
104 105 106 107
   * @param keep_only: if > 0 will keep at most the last keep_only nucleotides
   *                   of the sequence. if < 0 will keep at most the first
   *                   keep_only nucleotides of the sequence. if == 0,
   *                   will keep all the sequence.
108
   * @param seed: the seed to use for indexing. By default it will be the seed of the index
Mikaël Salson's avatar
Mikaël Salson committed
109 110
   * @post All the k-mers in the sequence have been indexed.
   */
111 112 113 114 115 116 117 118 119 120
  virtual void insert(const seqtype &sequence,
                      const string &label,
                      bool ignore_extended_nucleotides=true, int keep_only = 0,
                      string seed="");

  /**
   * Perform extra steps to finish the building of the index. After using
   * that function, we are not supposed to insert any other sequence.
   * No query function should be called before calling that function.
   */
121
  virtual void finish_building();
Mikaël Salson's avatar
Mikaël Salson committed
122 123 124 125 126

  /**
   * @param word: a k-mer
   * @return the value for the kmer as stored in the structure (don't do revcomp)
   */ 
127
  virtual T& get(seqtype &word) = 0;
Mikaël Salson's avatar
Mikaël Salson committed
128

129 130 131
  /**
   * @return the percentage of kmers that are set in the index
   */
132
  virtual float getIndexLoad(T kmer) const;
133

134 135 136 137 138 139
  /**
   * @return the given integer (size of a read),
   *         but limit this size to max_size_indexing if it was defined
   */
  int atMostMaxSizeIndexing(int n) const;

140 141 142
  /**
   * @return probability that the number of kmers is 'at_least' or more in a sequence of length 'length'
   */
143
  double getProbabilityAtLeastOrAbove(T kmer, int at_least, int length) const;
144

Mikaël Salson's avatar
Mikaël Salson committed
145 146 147 148 149 150 151 152 153 154
  /**
   * @return the value of k
   */
  int getK() const;

  /**
   * @return the value of s
   */
  int getS() const;

155 156 157 158 159
  /**
   * @return the seed used
   */
  string getSeed() const;

160 161 162 163
  /**
   * @param kmer: a kmer
   * @return one label associated with the kmer
   */
164
  Fasta getLabel(T kmer) const;
165

Mikaël Salson's avatar
Mikaël Salson committed
166 167 168 169
  /**
   * @param seq: a sequence
   * @param no_revcomp: force not to revcomp the sequence, even if
   *                    the index was built with revcomp.
170 171
   * @return a vector of length seq.length() - smallestAnalysableLength() + 1
   * containing for each position the corresponding value in the index.
Mikaël Salson's avatar
Mikaël Salson committed
172
   */
173
  virtual vector<T> getResults(const seqtype &seq, bool no_revcomp=false, string seed="") = 0;
Mikaël Salson's avatar
Mikaël Salson committed
174

175 176 177 178 179 180 181
  /**
   * @return the smallest analysable sequence length by the index. For an
   * index just storing k-mers it will obviously be getK(). But for more
   * sophisticated data structures it could be 1 for instance.
   */
  size_t smallestAnalysableLength() const;

Mikaël Salson's avatar
Mikaël Salson committed
182 183 184 185 186 187 188 189 190 191 192
  /**
   * @return true iff the revcomp is indexed
   */
  bool isRevcomp() const;

  /**
   * @param string: a k-mer
   * @return the value in the index associated to the given k-mer.
   *         isRevcomp() ==> the revcomp of the k-mer may be considered
   * @pre word.length() == this->k
   */
193
  virtual T& operator[](seqtype& word) = 0;
Mikaël Salson's avatar
Mikaël Salson committed
194 195
};

196 197 198
template<class T>
IKmerStore<T>::IKmerStore() {
  id = ++last_id;
Mikaël Salson's avatar
Mikaël Salson committed
199
  refs = 0;
200
  finished_building = false;
201 202
}

203
template<class T> int IKmerStore<T>::last_id = 0;
Mikaël Salson's avatar
Mikaël Salson committed
204 205 206 207 208

template <class T> 
class MapKmerStore : public IKmerStore<T>
{
public:	
209
  map<seqtype, T> store;
Mikaël Salson's avatar
Mikaël Salson committed
210 211 212 213 214 215 216

  /**
   * @param bool: if true, will also index revcomp
   * @param seed: the seed
   */
  MapKmerStore(string seed, bool=false);
  MapKmerStore(int k, bool=false);
217

218
  vector<T> getResults(const seqtype &seq, bool no_revcomp=false, string seed="");
219 220
  T& get(seqtype &word);
  T& operator[](seqtype & word);
221 222 223

 private:
  void init();
Mikaël Salson's avatar
Mikaël Salson committed
224 225 226 227 228 229 230
};

template <class T> 
class ArrayKmerStore : public IKmerStore<T>
{
  T* store;
	
231
  int index(const seqtype& word) const;
232 233 234 235 236 237 238 239

  /**
   * Allocates memory for store
   * @throws bad_alloc: when there is not enough memory or when the
   *                    the total number of kmers cannot be stored in an 
   *                    unsigned int
   */
  void init();
Mikaël Salson's avatar
Mikaël Salson committed
240 241 242 243 244 245 246 247
public:
  /**
   * @param bool: if true, will also index revcomp
   * @param seed: the seed
   */
  ArrayKmerStore(string seed, bool=false);
  ArrayKmerStore(int k, bool=false);
  ~ArrayKmerStore();
248

249
  vector<T> getResults(const seqtype &seq, bool no_revcomp=false, const string seed="");
250 251
  T& get(seqtype &word);
  T& operator[](seqtype & word);
252
  T& operator[](int word);
Mikaël Salson's avatar
Mikaël Salson committed
253 254 255 256 257 258 259 260 261 262
};


// IKmerStore

template<class T>
IKmerStore<T>::~IKmerStore(){}

template<class T> 
void IKmerStore<T>::insert(list<Fasta>& input,
263
                           const string &label,
264 265
                           int keep_only,
                           string seed){
Mikaël Salson's avatar
Mikaël Salson committed
266
  for(list<Fasta>::iterator it = input.begin() ; it != input.end() ; it++){
267
    insert(*it, label, keep_only, seed);
Mikaël Salson's avatar
Mikaël Salson committed
268 269 270 271 272
  }
}

template<class T> 
void IKmerStore<T>::insert(Fasta& input,
273
                           const string &label,
274 275
                           int keep_only,
                           string seed){
Mikaël Salson's avatar
Mikaël Salson committed
276
  for (int r = 0; r < input.size(); r++) {
277
    insert(input.sequence(r), label, true, keep_only, seed);
Mikaël Salson's avatar
Mikaël Salson committed
278
  }
279

280
  labels.push_back(make_pair(T(label, 1, seed_weight(seed)), input)) ;
281 282

  if (revcomp_indexed  && ! T::hasRevcompSymetry()) {
283
    labels.push_back(make_pair(T(label, -1, seed_weight(seed)), input)) ;
284
  }
Mikaël Salson's avatar
Mikaël Salson committed
285 286 287
}

template<class T> 
288
void IKmerStore<T>::insert(const seqtype &sequence,
289
                           const string &label,
290
                           bool ignore_extended_nucleotides,
291 292
                           int keep_only,
                           string seed){
293 294 295 296 297 298 299
  size_t start_indexing = 0;
  size_t end_indexing = sequence.length();
  if (keep_only > 0 && sequence.length() > (size_t)keep_only) {
    start_indexing = sequence.length() - keep_only;
  } else if (keep_only < 0 && sequence.length() > (size_t) -keep_only) {
    end_indexing = -keep_only;
  }
300

301 302 303 304
  if (seed.empty())
    seed = this->seed;

  size_t seed_span = seed.length();
305
  size_t seed_w = seed_weight(seed);
306 307 308 309 310
  size_t size_indexing = end_indexing - start_indexing;
  if (size_indexing > max_size_indexing) {
    max_size_indexing = size_indexing;
  }

311 312
  for(size_t i = start_indexing ; i + seed_span < end_indexing + 1 ; i++) {
    seqtype substr = sequence.substr(i, seed_span);
313
    seqtype kmer = spaced(substr, seed);
314

315
    if (ignore_extended_nucleotides && has_extended_nucleotides(kmer))
316 317
      continue;

Mikaël Salson's avatar
Mikaël Salson committed
318 319
    int strand = 1;
    if (revcomp_indexed && T::hasRevcompSymetry()) {
320
      seqtype rc_kmer = revcomp(kmer);
Mikaël Salson's avatar
Mikaël Salson committed
321 322 323 324 325
      if (rc_kmer.compare(kmer) < 0) {
        strand = -1;
        kmer = rc_kmer;
      }
    }
326 327 328 329
    T &this_kmer = this->get(kmer);
    if (this_kmer.isNull()) {
      nb_kmers_inserted++;
    }
330
    this_kmer += T(label, strand, seed_w);
Mikaël Salson's avatar
Mikaël Salson committed
331
    if (revcomp_indexed && ! T::hasRevcompSymetry()) {
332
      seqtype rc_kmer = spaced(revcomp(substr), seed);
333 334 335
      T &this_rc_kmer = this->get(rc_kmer);
      if (this_rc_kmer.isNull())
        nb_kmers_inserted++;
336
      this_rc_kmer += T(label, -1, seed_w);
Mikaël Salson's avatar
Mikaël Salson committed
337 338 339
    }
  }
}
340

341
template<class T>
342 343 344
void IKmerStore<T>::finish_building() {
  finished_building = true;
}
345

346 347
template<class T>
float IKmerStore<T>::getIndexLoad(const T kmer) const {
348 349
  float index_load = nb_kmers_inserted / pow(4.0, kmer.getLength());
  return (kmer.isUnknown()) ? 1 - index_load : index_load;
350
}
Mikaël Salson's avatar
Mikaël Salson committed
351

352 353 354 355 356 357 358
template<class T>
int IKmerStore<T>::atMostMaxSizeIndexing(int n) const {
  if (!max_size_indexing || n < max_size_indexing)
    return n ;

  return max_size_indexing ;
}
359 360

template<class T>
361
double IKmerStore<T>::getProbabilityAtLeastOrAbove(const T kmer, int at_least, int length) const {
362 363 364

  // n: number of kmers in the sequence
  int n = length - getS() + 1;
365
  float index_load = getIndexLoad(kmer) ;
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

  double proba = 0;
  double probability_having_system = pow(index_load, at_least);
  double probability_not_having_system = pow(1 - index_load, n - at_least);
  for (int i=at_least; i<=n; i++) {
    proba += nChoosek(n, i) * probability_having_system * probability_not_having_system;
    probability_having_system *= index_load;
    probability_not_having_system /= (1 - index_load);
  }

  return proba;
}



Mikaël Salson's avatar
Mikaël Salson committed
381 382 383 384 385 386 387 388 389 390
template<class T>
int IKmerStore<T>::getK() const {
  return k;
}

template<class T>
int IKmerStore<T>::getS() const {
  return s;
}

391 392 393 394 395
template<class T>
string IKmerStore<T>::getSeed() const {
  return seed;
}

396
template<class T>
397 398
Fasta IKmerStore<T>::getLabel(T kmer) const {
  for (typename list< pair<T, Fasta> >::const_iterator it = labels.begin(); it != labels.end(); ++it)
399 400
    if (it->first == kmer)
      return it->second ;
401
  return FASTA_AMBIGUOUS ;
402
}
403 404

// .getResults()
Mikaël Salson's avatar
Mikaël Salson committed
405
template<class T>
406
vector<T> MapKmerStore<T>::getResults(const seqtype &seq, bool no_revcomp, string seed) {
407

Mikaël Salson's avatar
Mikaël Salson committed
408
  string local_seed = seed;
409
  if (! seed.size())
Mikaël Salson's avatar
Mikaël Salson committed
410 411
    local_seed = IKmerStore<T>::seed;
  int s = local_seed.size();
412

Mikaël Salson's avatar
Mikaël Salson committed
413 414 415 416 417
  if ((int)seq.length() < s - 1) {
    return vector<T>(0);
  }
  vector<T> result(seq.length() - s + 1);
  for (size_t i=0; i + s < seq.length() + 1; i++) {
Mikaël Salson's avatar
Mikaël Salson committed
418
    seqtype kmer = spaced(seq.substr(i, s), local_seed);
419
    //    seqtype kmer = seq.substr(i, s);
Mikaël Salson's avatar
Mikaël Salson committed
420
    // cout << kmer << endl << kmer0 << endl << endl ;
421
    if (IKmerStore<T>::revcomp_indexed && no_revcomp) {
Mikaël Salson's avatar
Mikaël Salson committed
422 423 424 425 426 427 428 429
      result[i] = get(kmer);
    } else {
      result[i] = (*this)[kmer];
    }
  }
  return result;
}

430
template<class T>
431
vector<T> ArrayKmerStore<T>::getResults(const seqtype &seq, bool no_revcomp, string seed) {
Mikaël Salson's avatar
Mikaël Salson committed
432 433

  string local_seed = seed;
434
  if (! seed.size())
Mikaël Salson's avatar
Mikaël Salson committed
435 436
    local_seed = IKmerStore<T>::seed;
  int s = local_seed.size();
437 438 439 440 441 442 443 444 445 446 447 448

  int N = (int)seq.length();

  if (N < s - 1) {
    return vector<T>(0);
  }
  vector<T> result(N - s + 1);

  /* Read once the sequence, convert it to int* */
  int* intseq = new int[N];
  for (int i=0; i<N; i++)
    {
449
      intseq[i] = nuc_to_int(seq[i]);
450 451 452 453
    }

  /* Compute results */
  for (size_t i=0; (int) i+s < N+1; i++) {
Mikaël Salson's avatar
Mikaël Salson committed
454
    int kmer = spaced_int(intseq + i, local_seed);
455 456 457 458
    if (IKmerStore<T>::revcomp_indexed && no_revcomp) {
      result[i] = store[kmer]; // getfromint(kmer); // store[kmer];
      // cout << i << "/" << N << "  " << kmer << result[i] << endl ;
    } else {
459
      result[i] = (*this)[kmer]; // Deals with revcomp
460 461 462 463 464 465 466
    }
  }

  delete[] intseq ;
  return result;
}

Mikaël Salson's avatar
Mikaël Salson committed
467 468 469 470 471 472

template<class T>
bool IKmerStore<T>::isRevcomp() const {
  return revcomp_indexed;
}

473 474 475 476 477
template<class T>
size_t IKmerStore<T>::smallestAnalysableLength() const {
  return getK();
}

Mikaël Salson's avatar
Mikaël Salson committed
478 479 480
// MapKmerStore

template <class T>
481
MapKmerStore<T>::MapKmerStore(string seed, bool revcomp):IKmerStore<T>(){
Mikaël Salson's avatar
Mikaël Salson committed
482 483 484 485 486
  this->seed = seed;   
  int k = seed_weight(seed);
  this->k = k;
  this->s = seed.size();
  this->revcomp_indexed = revcomp;
487
  init();
Mikaël Salson's avatar
Mikaël Salson committed
488 489 490
}

template <class T>
491
MapKmerStore<T>::MapKmerStore(int k, bool revcomp):IKmerStore<T>(){
Mikaël Salson's avatar
Mikaël Salson committed
492 493 494 495
  this->seed = seed_contiguous(k);
  this->k = k;
  this->s = k;
  this->revcomp_indexed = revcomp;
496 497 498 499 500 501
  init();
}

template <class T>
void MapKmerStore<T>::init() {
  this->nb_kmers_inserted = 0;
502
  this->max_size_indexing = 0;
Mikaël Salson's avatar
Mikaël Salson committed
503 504 505
}

template <class T> 
506
T& MapKmerStore<T>::get(seqtype& word){
Mikaël Salson's avatar
Mikaël Salson committed
507 508 509 510
  return store[word];
}

template <class T> 
511
T& MapKmerStore<T>::operator[](seqtype& word){
Mikaël Salson's avatar
Mikaël Salson committed
512
  if (this->isRevcomp() && T::hasRevcompSymetry()) {
513
    seqtype rc_kmer = revcomp(word);
Mikaël Salson's avatar
Mikaël Salson committed
514 515 516 517 518 519 520 521 522
    if (rc_kmer.compare(word) < 0)
      word = rc_kmer;
  }
  return store[word];
}

// ArrayKmerStore

template <class T> 
523
ArrayKmerStore<T>::ArrayKmerStore(int k, bool revcomp):IKmerStore<T>() {
Mikaël Salson's avatar
Mikaël Salson committed
524 525 526 527
  this->seed = seed_contiguous(k);
  this->k = k;
  this->s = k;
  this->revcomp_indexed = revcomp;
528
  init();
Mikaël Salson's avatar
Mikaël Salson committed
529 530 531 532
}


template <class T> 
533
ArrayKmerStore<T>::ArrayKmerStore(string seed, bool revcomp):IKmerStore<T>(){
Mikaël Salson's avatar
Mikaël Salson committed
534 535 536 537 538
  this->seed = seed; 
  int k = seed_weight(seed);
  this->k = k;
  this->s = seed.size();
  this->revcomp_indexed = revcomp;
539 540 541 542 543
  init();
}

template <class T>
void ArrayKmerStore<T>::init() {
544
  this->nb_kmers_inserted = 0;
545
  this->max_size_indexing = 0;
546
  if ((size_t)(this->k << 1) >= sizeof(int) * 8)
Mikaël Salson's avatar
Mikaël Salson committed
547
    throw std::bad_alloc();
548
  store = new T[(unsigned int)1 << (this->k << 1)];
Mikaël Salson's avatar
Mikaël Salson committed
549 550 551 552 553 554 555 556 557 558 559 560 561 562
  if (! store)
    throw std::bad_alloc();
}

template <class T> 
ArrayKmerStore<T>::~ArrayKmerStore(){
  delete [] store;
}

/**	Returns index of word in an array of size 4^k
	Considering B(A) = 0, B(C) = 1, B(T) = 2, B(G) = 3
	index_word = \sum_{i=0}^{k-1}B(word[i])*4^(k-i-1)
**/
template <class T> 
563
int ArrayKmerStore<T>::index(const seqtype& word) const{
Mikaël Salson's avatar
Mikaël Salson committed
564
  return dna_to_int(word, this->k);
Mikaël Salson's avatar
Mikaël Salson committed
565 566 567
}

template <class T> 
568
T& ArrayKmerStore<T>::get(seqtype& word){
Mikaël Salson's avatar
Mikaël Salson committed
569 570 571 572
  return store[index(word)];
}

template <class T> 
573
T& ArrayKmerStore<T>::operator[](seqtype& word){
574 575 576 577 578
  return (*this)[index(word)];
}

template <class T> 
T& ArrayKmerStore<T>::operator[](int word){
Mikaël Salson's avatar
Mikaël Salson committed
579
  if (this->isRevcomp() && T::hasRevcompSymetry()) {
580 581
    int rc_kmer = revcomp_int(word, IKmerStore<T>::k);
    if (rc_kmer < word)
Mikaël Salson's avatar
Mikaël Salson committed
582 583
      word = rc_kmer;
  }
584
  return store[word];
Mikaël Salson's avatar
Mikaël Salson committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
}


/**
 * KmerStoreFactory is a factory that allows to create an index that best fits
 * your needs!
 */
class KmerStoreFactory {
 public:
  template<class T>
    static IKmerStore<T> *createIndex(string seed, bool revcomp=false);
  template<class T>
    static IKmerStore<T> *createIndex(int k, bool revcomp=false);
};

template<class T>
IKmerStore<T> *KmerStoreFactory::createIndex(string seed, bool revcomp) {
  IKmerStore<T> *index;
  try{
    index = new ArrayKmerStore<T>(seed, revcomp);
  }catch(exception e){
606
    cout << "  (using a MapKmer to fit into memory)" << endl;
Mikaël Salson's avatar
Mikaël Salson committed
607 608
    index = new MapKmerStore<T>(seed, revcomp);
  }
609

Mikaël Salson's avatar
Mikaël Salson committed
610 611 612 613 614 615 616 617 618
  return index;
}

template<class T>
IKmerStore<T> *KmerStoreFactory::createIndex(int k, bool revcomp) {
  return createIndex<T>(seed_contiguous(k), revcomp);
}

#endif