kmerstore.h 7.92 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 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 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
#ifndef KMERSTORE_H
#define KMERSTORE_H

#include <map>
#include <string>
#include <list>
#include <stdexcept>
#include <stdint.h>
#include "fasta.h"
#include "tools.h"

using namespace std;

class Kmer {
public:
  unsigned int count;

  Kmer();
  Kmer(const string &kmer, const string &label="", int strand=1);
  Kmer &operator+=(const Kmer &);
  static bool hasRevcompSymetry();
} ;
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 ;

public:

  virtual ~IKmerStore();

  /**
   * @param input: A single FASTA file
   * @param label: label that must be associated to the given files
   * @post All the sequences in the FASTA files have been indexed.
   */
  void insert(Fasta& input, const string& label="");

  /**
   * @param input: A list of FASTA files
   * @param label: label that must be associated to the given files
   * @post All the sequences in the FASTA files have been indexed.
   */
  void insert(list<Fasta>& input, const string& label="");
  
  /**
   * @param input: A sequence to be cut in k-mers
   * @param label: label that must be associated to the given files
   * @post All the k-mers in the sequence have been indexed.
   */
  void insert(const string &sequence,
              const string &label);

  /**
   * @param word: a k-mer
   * @return the value for the kmer as stored in the structure (don't do revcomp)
   */ 
  virtual T& get(string &word) = 0;

  /**
   * @return the value of k
   */
  int getK() const;

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

  /**
   * @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.
   */
  vector<T> getResults(const string &seq, bool no_revcomp=false);

  /**
   * @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
   */
  virtual T& operator[](string& word) = 0;
};


template <class T> 
class MapKmerStore : public IKmerStore<T>
{
public:	
  map<string, T> store;

  /**
   * @param bool: if true, will also index revcomp
   * @param seed: the seed
   */
  MapKmerStore(string seed, bool=false);
  MapKmerStore(int k, bool=false);
  T& get(string &word);
  T& operator[](string& word);
};

template <class T> 
class ArrayKmerStore : public IKmerStore<T>
{
  T* store;
	
  int index(const string& word) const;
public:
  /**
   * @param bool: if true, will also index revcomp
   * @param seed: the seed
   */
  ArrayKmerStore(string seed, bool=false);
  ArrayKmerStore(int k, bool=false);
  ~ArrayKmerStore();
	
  T& get(string &word);
  T& operator[](string& word);
};


// IKmerStore

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

template<class T> 
void IKmerStore<T>::insert(list<Fasta>& input,
                           const string &label){
  for(list<Fasta>::iterator it = input.begin() ; it != input.end() ; it++){
    insert(*it, label);
  }
}

template<class T> 
void IKmerStore<T>::insert(Fasta& input,
                           const string &label){
  for (int r = 0; r < input.size(); r++) {
    insert(input.sequence(r), label);
  }
}

template<class T> 
void IKmerStore<T>::insert(const string &sequence,
                           const string &label){
  for(size_t i = 0 ; i + s < sequence.length() + 1 ; i++) {
    string kmer = spaced(sequence.substr(i, s), seed);
    int strand = 1;
    if (revcomp_indexed && T::hasRevcompSymetry()) {
      string rc_kmer = revcomp(kmer);
      if (rc_kmer.compare(kmer) < 0) {
        strand = -1;
        kmer = rc_kmer;
      }
    }
    this->get(kmer) += T(kmer, label, strand);
    if (revcomp_indexed && ! T::hasRevcompSymetry()) {
      string rc_kmer = revcomp(kmer);
      this->get(rc_kmer) += T(rc_kmer, label, -1);
    }
  }
}
  

template<class T>
int IKmerStore<T>::getK() const {
  return k;
}

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

template<class T>
vector<T> IKmerStore<T>::getResults(const string &seq, bool no_revcomp) {
  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++) {
    string kmer = spaced(seq.substr(i, s), seed);
    //    string kmer = seq.substr(i, s);
    // cout << kmer << endl << kmer0 << endl << endl ;
    if (revcomp_indexed && no_revcomp) {
      result[i] = get(kmer);
    } else {
      result[i] = (*this)[kmer];
    }
  }
  return result;
}


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;
}

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;
}

template <class T> 
T& MapKmerStore<T>::get(string& word){
  return store[word];
}

template <class T> 
T& MapKmerStore<T>::operator[](string& word){
  if (this->isRevcomp() && T::hasRevcompSymetry()) {
    string rc_kmer = revcomp(word);
    if (rc_kmer.compare(word) < 0)
      word = rc_kmer;
  }
  return store[word];
}

// ArrayKmerStore

template <class T> 
ArrayKmerStore<T>::ArrayKmerStore(int k, bool revcomp){
  this->seed = seed_contiguous(k);
  this->k = k;
  this->s = k;
  this->revcomp_indexed = revcomp;
  if ((size_t)(k << 1) >= sizeof(int) * 8)
    throw std::bad_alloc();
  store = new T[(unsigned int)1 << (k << 1)];
  if (! store)
    throw std::bad_alloc();
}


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;
  if ((size_t)(k << 1) >= sizeof(int) * 8)
    throw std::bad_alloc();
  store = new T[(unsigned int)1 << (k << 1)];
  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> 
int ArrayKmerStore<T>::index(const string& word) const{
	int index_word = 0;
	for(int i = 0 ; i < this->k ; i++){
		int B = 0;
		switch(word[i]){
			case 'A': B = 0; break;
			case 'C': B = 1; break;
			case 'G': B = 2; break;
			case 'T': B = 3; break;
		}
		index_word = (index_word << 2) | B;
	}
	return index_word;
}

template <class T> 
T& ArrayKmerStore<T>::get(string& word){
  return store[index(word)];
}

template <class T> 
T& ArrayKmerStore<T>::operator[](string& word){
  if (this->isRevcomp() && T::hasRevcompSymetry()) {
    string rc_kmer = revcomp(word);
    if (rc_kmer.compare(word) < 0)
      word = rc_kmer;
  }
  return store[index(word)];
}


/**
 * 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){
    index = new MapKmerStore<T>(seed, revcomp);
  }
  return index;
}

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

#endif