kmerstore.h 14.1 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);
25

Mikaël Salson's avatar
Mikaël Salson committed
26 27
  Kmer &operator+=(const Kmer &);
  static bool hasRevcompSymetry();
28 29 30 31 32

  /**
   * @return true if the element is the same as when initialised with default constructor.
   */
  bool isNull();
Mikaël Salson's avatar
Mikaël Salson committed
33 34 35 36 37 38 39 40 41 42 43 44 45
} ;
ostream &operator<<(ostream &os, const Kmer &kmer);


/* 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 ;
46
  size_t nb_kmers_inserted;
47
  size_t max_size_indexing;
Mikaël Salson's avatar
Mikaël Salson committed
48 49 50 51 52

public:

  virtual ~IKmerStore();

53 54
  static int last_id;
  int id; // id of this index
55
  int refs; // number of germlines using this index
56

57
  list< pair <T, Fasta> > labels;
58

Mikaël Salson's avatar
Mikaël Salson committed
59 60 61
  /**
   * @param input: A single FASTA file
   * @param label: label that must be associated to the given files
62
   * @param seed: the seed to use for indexing. By default it will be the seed of the index
63
   * @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
64
   */
65
  void insert(Fasta& input, const string& label="", int keep_only = 0, string seed = "");
Mikaël Salson's avatar
Mikaël Salson committed
66 67 68 69

  /**
   * @param input: A list of FASTA files
   * @param label: label that must be associated to the given files
70
   * @param seed: the seed to use for indexing. By default it will be the seed of the index
71
   * @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
72
   */
73
  void insert(list<Fasta>& input, const string& label="", int keep_only = 0, string seed = "");
Mikaël Salson's avatar
Mikaël Salson committed
74 75 76 77
  
  /**
   * @param input: A sequence to be cut in k-mers
   * @param label: label that must be associated to the given files
78 79 80 81
   * @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.
82
   * @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
83 84
   * @post All the k-mers in the sequence have been indexed.
   */
85
  void insert(const seqtype &sequence,
86
              const string &label,
87 88
              bool ignore_extended_nucleotides=true, int keep_only = 0,
              string seed="");
Mikaël Salson's avatar
Mikaël Salson committed
89 90 91 92 93

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

96 97 98
  /**
   * @return the percentage of kmers that are set in the index
   */
99
  float getIndexLoad(T kmer) const;
100 101
  float getIndexLoad() const;

102 103 104 105 106 107
  /**
   * @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;

108 109 110
  /**
   * @return probability that the number of kmers is 'at_least' or more in a sequence of length 'length'
   */
111
  double getProbabilityAtLeastOrAbove(T kmer, int at_least, int length) const;
112

Mikaël Salson's avatar
Mikaël Salson committed
113 114 115 116 117 118 119 120 121 122
  /**
   * @return the value of k
   */
  int getK() const;

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

123 124 125 126 127
  /**
   * @return the seed used
   */
  string getSeed() const;

128 129 130 131
  /**
   * @param kmer: a kmer
   * @return one label associated with the kmer
   */
132
  Fasta getLabel(T kmer) const;
133

Mikaël Salson's avatar
Mikaël Salson committed
134 135 136 137 138 139 140
  /**
   * @param seq: a sequence
   * @param no_revcomp: force not to revcomp the sequence, even if
   *                    the index was built with revcomp.
   * @return a vector of length seq.length() - getK() + 1 containing
   * for each k-mer the corresponding value in the index.
   */
141
  virtual vector<T> getResults(const seqtype &seq, bool no_revcomp=false, string seed="") = 0;
Mikaël Salson's avatar
Mikaël Salson committed
142 143 144 145 146 147 148 149 150 151 152 153

  /**
   * @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
   */
154
  virtual T& operator[](seqtype& word) = 0;
Mikaël Salson's avatar
Mikaël Salson committed
155 156
};

157
template<class T> int IKmerStore<T>::last_id = 0;
Mikaël Salson's avatar
Mikaël Salson committed
158 159 160 161 162

template <class T> 
class MapKmerStore : public IKmerStore<T>
{
public:	
163
  map<seqtype, T> store;
Mikaël Salson's avatar
Mikaël Salson committed
164 165 166 167 168 169 170

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

172
  vector<T> getResults(const seqtype &seq, bool no_revcomp=false, string seed="");
173 174
  T& get(seqtype &word);
  T& operator[](seqtype & word);
175 176 177

 private:
  void init();
Mikaël Salson's avatar
Mikaël Salson committed
178 179 180 181 182 183 184
};

template <class T> 
class ArrayKmerStore : public IKmerStore<T>
{
  T* store;
	
185
  int index(const seqtype& word) const;
186 187 188 189 190 191 192 193

  /**
   * 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
194 195 196 197 198 199 200 201
public:
  /**
   * @param bool: if true, will also index revcomp
   * @param seed: the seed
   */
  ArrayKmerStore(string seed, bool=false);
  ArrayKmerStore(int k, bool=false);
  ~ArrayKmerStore();
202

203
  vector<T> getResults(const seqtype &seq, bool no_revcomp=false, const string seed="");
204 205
  T& get(seqtype &word);
  T& operator[](seqtype & word);
206
  T& operator[](int word);
Mikaël Salson's avatar
Mikaël Salson committed
207 208 209 210 211 212 213 214 215 216
};


// IKmerStore

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

template<class T> 
void IKmerStore<T>::insert(list<Fasta>& input,
217
                           const string &label,
218 219
                           int keep_only,
                           string seed){
Mikaël Salson's avatar
Mikaël Salson committed
220
  for(list<Fasta>::iterator it = input.begin() ; it != input.end() ; it++){
221
    insert(*it, label, keep_only, seed);
Mikaël Salson's avatar
Mikaël Salson committed
222 223 224 225 226
  }
}

template<class T> 
void IKmerStore<T>::insert(Fasta& input,
227
                           const string &label,
228 229
                           int keep_only,
                           string seed){
Mikaël Salson's avatar
Mikaël Salson committed
230
  for (int r = 0; r < input.size(); r++) {
231
    insert(input.sequence(r), label, true, keep_only, seed);
Mikaël Salson's avatar
Mikaël Salson committed
232
  }
233

234
  labels.push_back(make_pair(T(label, 1), input)) ;
235 236

  if (revcomp_indexed  && ! T::hasRevcompSymetry()) {
237
    labels.push_back(make_pair(T(label, -1), input)) ;
238
  }
Mikaël Salson's avatar
Mikaël Salson committed
239 240 241
}

template<class T> 
242
void IKmerStore<T>::insert(const seqtype &sequence,
243
                           const string &label,
244
                           bool ignore_extended_nucleotides,
245 246
                           int keep_only,
                           string seed){
247 248 249 250 251 252 253
  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;
  }
254

255 256 257 258
  if (seed.empty())
    seed = this->seed;

  size_t seed_span = seed.length();
259 260 261 262 263
  size_t size_indexing = end_indexing - start_indexing;
  if (size_indexing > max_size_indexing) {
    max_size_indexing = size_indexing;
  }

264 265
  for(size_t i = start_indexing ; i + seed_span < end_indexing + 1 ; i++) {
    seqtype substr = sequence.substr(i, seed_span);
266
    seqtype kmer = spaced(substr, seed);
267

268
    if (ignore_extended_nucleotides && has_extended_nucleotides(kmer))
269 270
      continue;

Mikaël Salson's avatar
Mikaël Salson committed
271 272
    int strand = 1;
    if (revcomp_indexed && T::hasRevcompSymetry()) {
273
      seqtype rc_kmer = revcomp(kmer);
Mikaël Salson's avatar
Mikaël Salson committed
274 275 276 277 278
      if (rc_kmer.compare(kmer) < 0) {
        strand = -1;
        kmer = rc_kmer;
      }
    }
279 280 281 282 283
    T &this_kmer = this->get(kmer);
    if (this_kmer.isNull()) {
      nb_kmers_inserted++;
    }
    this_kmer += T(label, strand);
Mikaël Salson's avatar
Mikaël Salson committed
284
    if (revcomp_indexed && ! T::hasRevcompSymetry()) {
285
      seqtype rc_kmer = spaced(revcomp(substr), seed);
286 287 288 289
      T &this_rc_kmer = this->get(rc_kmer);
      if (this_rc_kmer.isNull())
        nb_kmers_inserted++;
      this_rc_kmer += T(label, -1);
Mikaël Salson's avatar
Mikaël Salson committed
290 291 292
    }
  }
}
293

294 295
template<class T>
float IKmerStore<T>::getIndexLoad(const T kmer) const {
296
  return kmer.isUnknown() ? 1 - getIndexLoad() : getIndexLoad();
297
}
298 299
template<class T>
float IKmerStore<T>::getIndexLoad() const {
300
  return nb_kmers_inserted / pow(4.0, k);
301
}
Mikaël Salson's avatar
Mikaël Salson committed
302

303 304 305 306 307 308 309
template<class T>
int IKmerStore<T>::atMostMaxSizeIndexing(int n) const {
  if (!max_size_indexing || n < max_size_indexing)
    return n ;

  return max_size_indexing ;
}
310 311

template<class T>
312
double IKmerStore<T>::getProbabilityAtLeastOrAbove(const T kmer, int at_least, int length) const {
313 314 315

  // n: number of kmers in the sequence
  int n = length - getS() + 1;
316
  float index_load = getIndexLoad(kmer) ;
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

  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
332 333 334 335 336 337 338 339 340 341
template<class T>
int IKmerStore<T>::getK() const {
  return k;
}

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

342 343 344 345 346
template<class T>
string IKmerStore<T>::getSeed() const {
  return seed;
}

347
template<class T>
348 349
Fasta IKmerStore<T>::getLabel(T kmer) const {
  for (typename list< pair<T, Fasta> >::const_iterator it = labels.begin(); it != labels.end(); ++it)
350 351
    if (it->first == kmer)
      return it->second ;
352
  return FASTA_AMBIGUOUS ;
353
}
354 355

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

359 360 361
  if (! seed.size())
    seed = IKmerStore<T>::seed;
  int s = seed.size();
362

Mikaël Salson's avatar
Mikaël Salson committed
363 364 365 366 367
  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++) {
368
    seqtype kmer = spaced(seq.substr(i, s), seed);
369
    //    seqtype kmer = seq.substr(i, s);
Mikaël Salson's avatar
Mikaël Salson committed
370
    // cout << kmer << endl << kmer0 << endl << endl ;
371
    if (IKmerStore<T>::revcomp_indexed && no_revcomp) {
Mikaël Salson's avatar
Mikaël Salson committed
372 373 374 375 376 377 378 379
      result[i] = get(kmer);
    } else {
      result[i] = (*this)[kmer];
    }
  }
  return result;
}

380
template<class T>
381
vector<T> ArrayKmerStore<T>::getResults(const seqtype &seq, bool no_revcomp, string seed) {
382
  
383 384 385
  if (! seed.size())
    seed = IKmerStore<T>::seed;
  int s = seed.size();
386 387 388 389 390 391 392 393 394 395 396 397

  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++)
    {
398
      intseq[i] = nuc_to_int(seq[i]);
399 400 401 402
    }

  /* Compute results */
  for (size_t i=0; (int) i+s < N+1; i++) {
403
    int kmer = spaced_int(intseq + i, seed);
404 405 406 407
    if (IKmerStore<T>::revcomp_indexed && no_revcomp) {
      result[i] = store[kmer]; // getfromint(kmer); // store[kmer];
      // cout << i << "/" << N << "  " << kmer << result[i] << endl ;
    } else {
408
      result[i] = (*this)[kmer]; // Deals with revcomp
409 410 411 412 413 414 415
    }
  }

  delete[] intseq ;
  return result;
}

Mikaël Salson's avatar
Mikaël Salson committed
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430

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

// MapKmerStore

template <class T>
MapKmerStore<T>::MapKmerStore(string seed, bool revcomp){
  this->seed = seed;   
  int k = seed_weight(seed);
  this->k = k;
  this->s = seed.size();
  this->revcomp_indexed = revcomp;
431
  init();
Mikaël Salson's avatar
Mikaël Salson committed
432 433 434 435 436 437 438 439
}

template <class T>
MapKmerStore<T>::MapKmerStore(int k, bool revcomp){
  this->seed = seed_contiguous(k);
  this->k = k;
  this->s = k;
  this->revcomp_indexed = revcomp;
440 441 442 443 444 445
  init();
}

template <class T>
void MapKmerStore<T>::init() {
  this->nb_kmers_inserted = 0;
446
  this->max_size_indexing = 0;
Mikaël Salson's avatar
Mikaël Salson committed
447 448 449
}

template <class T> 
450
T& MapKmerStore<T>::get(seqtype& word){
Mikaël Salson's avatar
Mikaël Salson committed
451 452 453 454
  return store[word];
}

template <class T> 
455
T& MapKmerStore<T>::operator[](seqtype& word){
Mikaël Salson's avatar
Mikaël Salson committed
456
  if (this->isRevcomp() && T::hasRevcompSymetry()) {
457
    seqtype rc_kmer = revcomp(word);
Mikaël Salson's avatar
Mikaël Salson committed
458 459 460 461 462 463 464 465 466
    if (rc_kmer.compare(word) < 0)
      word = rc_kmer;
  }
  return store[word];
}

// ArrayKmerStore

template <class T> 
467
ArrayKmerStore<T>::ArrayKmerStore(int k, bool revcomp) {
Mikaël Salson's avatar
Mikaël Salson committed
468 469 470 471
  this->seed = seed_contiguous(k);
  this->k = k;
  this->s = k;
  this->revcomp_indexed = revcomp;
472
  init();
Mikaël Salson's avatar
Mikaël Salson committed
473 474 475 476 477 478 479 480 481 482
}


template <class T> 
ArrayKmerStore<T>::ArrayKmerStore(string seed, bool revcomp){
  this->seed = seed; 
  int k = seed_weight(seed);
  this->k = k;
  this->s = seed.size();
  this->revcomp_indexed = revcomp;
483 484 485 486 487
  init();
}

template <class T>
void ArrayKmerStore<T>::init() {
488
  this->nb_kmers_inserted = 0;
489
  this->max_size_indexing = 0;
490
  if ((size_t)(this->k << 1) >= sizeof(int) * 8)
Mikaël Salson's avatar
Mikaël Salson committed
491
    throw std::bad_alloc();
492
  store = new T[(unsigned int)1 << (this->k << 1)];
Mikaël Salson's avatar
Mikaël Salson committed
493 494 495 496 497 498 499 500 501 502 503 504 505 506
  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> 
507
int ArrayKmerStore<T>::index(const seqtype& word) const{
Mikaël Salson's avatar
Mikaël Salson committed
508
  return dna_to_int(word, this->k);
Mikaël Salson's avatar
Mikaël Salson committed
509 510 511
}

template <class T> 
512
T& ArrayKmerStore<T>::get(seqtype& word){
Mikaël Salson's avatar
Mikaël Salson committed
513 514 515 516
  return store[index(word)];
}

template <class T> 
517
T& ArrayKmerStore<T>::operator[](seqtype& word){
518 519 520 521 522
  return (*this)[index(word)];
}

template <class T> 
T& ArrayKmerStore<T>::operator[](int word){
Mikaël Salson's avatar
Mikaël Salson committed
523
  if (this->isRevcomp() && T::hasRevcompSymetry()) {
524 525
    int rc_kmer = revcomp_int(word, IKmerStore<T>::k);
    if (rc_kmer < word)
Mikaël Salson's avatar
Mikaël Salson committed
526 527
      word = rc_kmer;
  }
528
  return store[word];
Mikaël Salson's avatar
Mikaël Salson committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
}


/**
 * 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){
550
    cout << "  (using a MapKmer to fit into memory)" << endl;
Mikaël Salson's avatar
Mikaël Salson committed
551 552
    index = new MapKmerStore<T>(seed, revcomp);
  }
553 554 555

  index->id = ++IKmerStore<T>::last_id;

Mikaël Salson's avatar
Mikaël Salson committed
556 557 558 559 560 561 562 563 564
  return index;
}

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

#endif