tools.cpp 11.7 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1
#include <algorithm>
2 3
#include <iostream>
#include <iomanip>
Mikaël Salson's avatar
Mikaël Salson committed
4
#include <algorithm>
Mikaël Salson's avatar
Mikaël Salson committed
5
#include "tools.h"
6
#include "../lib/json.hpp"
Mikaël Salson's avatar
Mikaël Salson committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

string seed_contiguous(int k)
{
  string seed = "" ;

  for (int i = 0; i < k; i++) 
    seed += SEED_YES;

  return seed ;
}

int seed_weight(const string &seed)
{
  return count(seed.begin(), seed.end(), SEED_YES);
}

23
map<string, string> seedMap = {
24 25
  {"7c", "#######"},
  {"8c", "########"},
26
  {"9c", "#########"},
27
  {"8s", "####-####"},
28 29 30 31 32
  {"10s", "#####-#####"},
  {"12s", "######-######"},
  {"13s", "#######-######"}
};

Mathieu Giraud's avatar
Mathieu Giraud committed
33
string expand_seed(const string &seed)
34 35
{
  if (seed.size() == 0)
Mathieu Giraud's avatar
Mathieu Giraud committed
36
    return expand_seed(DEFAULT_SEED);
37 38

  if (seed.find(SEED_YES) == std::string::npos)
39 40 41 42 43 44
    {
      if (seedMap.find(seed) == seedMap.end())
        throw invalid_argument("Unknown seed: " + seed);
      else
        return seedMap[seed];
    }
45 46 47 48 49

  return seed ;
}


Mathieu Giraud's avatar
Mathieu Giraud committed
50 51
char spaced_buf[MAX_SEED_SIZE+1];

Mikaël Salson's avatar
Mikaël Salson committed
52 53
string spaced(const string &input, const string &seed) {

Mathieu Giraud's avatar
Mathieu Giraud committed
54 55 56 57 58 59
// #ifdef STATIC_SPACED_SEED_FOURTEEN
//   return input.substr(0, 7) + input.substr(8, 7);
// #endif

  int j = 0 ;

Mikaël Salson's avatar
Mikaël Salson committed
60 61 62 63 64
  // cout << input << endl << seed << endl ;
  assert(input.length() == seed.length());

  for (size_t i = 0; i < input.length(); i++) 
    if (seed[i] == SEED_YES)
Mathieu Giraud's avatar
Mathieu Giraud committed
65
      spaced_buf[j++] = input[i] ;
Mikaël Salson's avatar
Mikaël Salson committed
66
  
Mathieu Giraud's avatar
Mathieu Giraud committed
67 68
  spaced_buf[j] = (char) 0;

Mikaël Salson's avatar
Mikaël Salson committed
69 70 71
#ifdef DEBUG_SPACED
  cout << input << " => |" << spaced_buf << "|" <<  endl ;
#endif
Mathieu Giraud's avatar
Mathieu Giraud committed
72 73

  return string(spaced_buf);
Mikaël Salson's avatar
Mikaël Salson committed
74 75 76
}


77
string string_of_int(int number, int w)
Mikaël Salson's avatar
Mikaël Salson committed
78 79
{
   stringstream ss;
80
   ss << setfill('0') << setw(w) << number ;
Mikaël Salson's avatar
Mikaël Salson committed
81 82 83
   return ss.str();
}

84 85 86 87 88 89 90
string fixed_string_of_float(float number, int precision)
{
   stringstream ss;
   ss << fixed << setprecision(precision) << number ;
   return ss.str();
}

91 92 93 94 95 96 97
string scientific_string_of_double(double number)
{
   stringstream ss;
   ss << scientific << number ;
   return ss.str();
}

Mathieu Giraud's avatar
Mathieu Giraud committed
98
string string_of_map(map <string, string> m, const string &before)
99 100 101 102 103 104 105
{
  stringstream ss;
  for (auto x: m)
    ss << before << x.first << ":" << x.second;
  return ss.str();
}

Mikaël Salson's avatar
Mikaël Salson committed
106

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
bool is_extended_nucleotide(char nuc) {
  switch(nuc) {
  case 'A': case 'a':
  case 'C': case 'c':
  case 'G': case 'g':
  case 'T': case 't':
    return false ;

  default:
    return true;
  }
}

bool has_extended_nucleotides(string s) {
  for (unsigned int i = 0; i<s.length(); i++)
    if (is_extended_nucleotide(s[i]))
      return true ;

  return false ;
}

Mikaël Salson's avatar
Mikaël Salson committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

char complement_nucleotide(char nuc) {
  switch(nuc) {
  case 'A': case 'a': return 'T';
  case 'C': case 'c': return 'G';
  case 'G': case 'g': return 'C';
  case 'T': case 't': return 'A';

  case 'Y': case 'y': return 'R'; // pyrimidine (CT)
  case 'R': case 'r': return 'Y'; // purine (AG)
  case 'W': case 'w': return 'W'; // weak (AT)
  case 'S': case 's': return 'S'; // strong (GC)
  case 'K': case 'k': return 'M'; // keto (TG)
  case 'M': case 'm': return 'K'; // amino (AC)

  case 'B': case 'b': return 'V'; // not A
  case 'D': case 'd': return 'H'; // not C
  case 'H': case 'h': return 'D'; // not G
  case 'V': case 'v': return 'B'; // not T

148 149
  case 'N': case 'n': return 'N';

Mikaël Salson's avatar
Mikaël Salson committed
150 151
  case ' ': return ' '; // ne devrait pas arriver...

152
  default: return '?';
Mikaël Salson's avatar
Mikaël Salson committed
153 154 155 156 157 158 159 160 161 162 163
  }
}

string complement(const string &dna) {
  string comp(dna);
  for (size_t i = 0; i < dna.length(); i++) {
    comp[i] = complement_nucleotide(dna[i]);
  }
  return comp;
}

Mikaël Salson's avatar
Mikaël Salson committed
164 165 166 167 168 169 170 171
int dna_to_int(const string &word, int size) {
  int index_word = 0;
  for(int i = 0 ; i < size ; i++){
    index_word = (index_word << 2) | nuc_to_int(word[i]);
  }
  return index_word;
}

172 173 174 175 176 177 178 179 180 181 182
uint64_t dna_to_hash(const string &word, int size) {
  // djb2-xor hash
  // no collision on 12-char strings on "ACGT" (nor on 8-char strings on "ACGTacgt")
  // min/max for 12-char strings on "AGCT" are "AAGAACCAACCC"/"TGAACCAACCAA"
  uint64_t hash = 5381;
  for(int i = 0 ; i < size ; i++){
    hash = ((hash << 5) + hash) ^ word[i];
  }
  return hash;
}

Mathieu Giraud's avatar
Mathieu Giraud committed
183 184 185
string nuc_to_aa(const string &word) {
  string aa;
  int index_word = 0;
186
  size_t i = 0;
Mathieu Giraud's avatar
Mathieu Giraud committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

  for (; i < word.length() ; i++) {
    index_word = (index_word << 2) | nuc_to_int(word[i]);

    if (i % 3 == 2) {
      aa += GENETIC_CODE[index_word];
      index_word = 0 ;
    }
  }

  if (i % 3)
    aa += GENETIC_CODE_OUT_OF_FRAME ;

  return aa;
}

Mathieu Giraud's avatar
Mathieu Giraud committed
203 204 205 206 207 208
Sequence create_sequence(string label_full, string label, string sequence, string quality) {
  Sequence seq;
  seq.label_full = label_full;
  seq.label = label;
  seq.sequence = sequence;
  seq.quality = quality;
209
  // ! TODO: seq.seq, factorize with fasta.cpp
Mathieu Giraud's avatar
Mathieu Giraud committed
210 211 212 213 214 215 216 217 218 219 220 221
  return seq;
}

bool operator==(const Sequence &s1, const Sequence &s2) {
  return s1.label_full == s2.label_full && s1.sequence == s2.sequence
    && s1.quality == s2.quality && s1.label == s2.label;
}

bool operator!=(const Sequence &s1, const Sequence &s2) {
  return !(s1 == s2);
}

Mikaël Salson's avatar
Mikaël Salson committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
string extract_from_label(string str, int field, string separator)
{
  if (!field)
    return str ;

  int found1 = -1;
  int i = 1;

  while (i++ < field)
    {
      found1 = str.find(separator, found1 + 1);
      if (found1 == (int) string::npos)
	return str ;
    }

  int found2 = str.find(separator, found1 + 1);

  if (found2 == (int) string::npos)
    return str ;
  
  return str.substr(found1+1, found2-found1-1);
}

245 246 247 248 249 250 251 252 253 254

string extract_dirname(string path) {
  size_t pos_lastdir = path.find_last_of('/');
  if (pos_lastdir != std::string::npos) {
    path = path.substr(0, pos_lastdir);
  }

  return path;
}

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
string extract_basename(string path, bool remove_ext) {
  size_t pos_lastdir = path.find_last_of('/');
  if (pos_lastdir != std::string::npos) {
    path = path.substr(pos_lastdir+1);
  }

  if (remove_ext) {
    size_t lastdot = path.find_last_of('.');
    if (lastdot != std::string::npos)
      path = path.substr(0, lastdot);
  }

  return path;
}

Mikaël Salson's avatar
Mikaël Salson committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
vector<string> generate_all_seeds(const string &str, const string &seed) {
  assert(str.length() == seed.length());
  static const string nucleotides = "ACGT";
  static const size_t nb_nucleotides = nucleotides.length();
  size_t nb_spaces = count(seed.begin(), seed.end(), '-');
  vector<string> sequences(1 << (nb_spaces * 2));
  if (nb_spaces == 0)
    sequences[0] = str;
  else {
    size_t first_pos = seed.find_first_of('-');
    string start_str = str.substr(0,first_pos);
    vector<string> end_sequences = generate_all_seeds(str.substr(first_pos+1), seed.substr(first_pos+1));
    size_t j = 0;
    for (string &end_str: end_sequences) {
      for (size_t i = 0; i < nb_nucleotides; i++) {
        sequences[j++] = start_str + nucleotides[i] + end_str;
      }
    }
  }

  return sequences;
}

Mikaël Salson's avatar
Mikaël Salson committed
293 294 295 296 297 298 299 300 301 302 303
int remove_trailing_whitespaces(string &str) {
  int count = 0;
  while (str.size() > 0 && (str[str.size() - 1] == '\r'
                            || str[str.size()-1] == ' '
                            || str[str.size()-1] == '\t')) {
    count++;
    str.resize(str.size() - 1);
  }
  return count;
}

304 305 306 307
string subsequence(const string &seq, int start, int end) {
  return seq.substr(start - 1, end - start + 1);
}

Mikaël Salson's avatar
Mikaël Salson committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
string revcomp(const string &dna, bool do_revcomp) {
  
  if (!do_revcomp)
    return dna;

  string rcomp(dna);
  for (size_t i = 0; i < dna.length(); i++) {
    rcomp[dna.length() - i - 1] = complement_nucleotide(dna[i]);
  }

  // cout << dna << " " << dna.length() << "  " << rcomp << " " << rcomp.length() << endl  ;

  return rcomp;
}

323 324 325 326 327 328 329 330 331 332 333
int revcomp_int(int word, int size) {
  int revcomp = 0;
  while (size) {
    revcomp <<= 2;
    revcomp |= (word & 3) ^ 3;
    word >>= 2;
    size--;
  }
  return revcomp;
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347
bool hasInFrameStopCodon(const string &sequence, int frame) {
  list<string> stop_codons {"TAG", "TAA", "TGA"};

  for (auto codon: stop_codons) {
    size_t pos_codon = sequence.find(codon);
    while (pos_codon != string::npos) {
      if (pos_codon % 3 == (size_t) frame)
        return true;
      pos_codon = sequence.find(codon, pos_codon+1);
    }
  }
  return false;
}

Mikaël Salson's avatar
Mikaël Salson committed
348 349 350
string reverse(const string &text) {
  return string(text.rbegin(), text.rend());
}
Mikaël Salson's avatar
Mikaël Salson committed
351

352
double nChoosek_stored[NB_N_CHOOSE_K_STORED][NB_N_CHOOSE_K_STORED] = {};
Mikaël Salson's avatar
Mikaël Salson committed
353 354 355 356 357 358
double nChoosek(unsigned n, unsigned k)
{
    if (k > n) return 0;
    if (k * 2 > n) k = n-k;
    if (k == 0) return 1;

359 360 361 362 363 364 365 366 367 368 369 370
    if (n >= NB_N_CHOOSE_K_STORED || nChoosek_stored[n][k] == 0) {
      double result = 1;
      unsigned i;
      for (i = 0; i < k && ((n-i) >= NB_N_CHOOSE_K_STORED || nChoosek_stored[n-i][k-i] == 0); i++ ) {
        result *= (n - i)*1./(k - i);
      }
      if (i < k) {
        result *= nChoosek_stored[n-i][k-i];
      }
      if (n < NB_N_CHOOSE_K_STORED)
        nChoosek_stored[n][k] = result;
      return result;
Mikaël Salson's avatar
Mikaël Salson committed
371
    }
372
    return nChoosek_stored[n][k];
Mikaël Salson's avatar
Mikaël Salson committed
373
}
374

375 376
void trimSequence(string &sequence, size_t &start_pos, size_t &length,
                  size_t required_start, size_t required_length) {
377 378 379 380 381 382 383 384 385 386 387
  float prefix_score = 0;
  float suffix_score = 0;
  size_t start_bad_suffix = 0;
  size_t start_prefix = start_pos;
  size_t max_factor_length = 0;
  size_t max_start_factor = 0;
  bool is_bad_suffix = false;
  size_t end_pos = start_prefix + length ; // first position outside our
                                           // substring of interest

  for (size_t i = start_prefix; i < end_pos; i++) {
388 389 390 391

    // prefix_score = PERCENT_TOO_MANY_N * |p| - 100 * (number of N in p),
    // where p = sequence[start_prefix..i]
    
392 393 394 395
    if (sequence[i] == 'N') {
      prefix_score -= 100;
      suffix_score -= 100;
    }
396 397 398
    
    prefix_score += PERCENT_TOO_MANY_N;
    suffix_score += PERCENT_TOO_MANY_N;
399

400 401 402 403 404 405 406
    if (suffix_score >= 0) {
      is_bad_suffix = false;
      suffix_score = 0;
    } else if (! is_bad_suffix) {
      is_bad_suffix = true;
      start_bad_suffix = i;
    }
407

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    // As soon as a prefix doesn't reach our criteria we must cut the factor
    // here, and then we will see if another one will meet the criteria again
    if (prefix_score < 0 || i == end_pos - 1) {
      size_t length_factor = i - start_prefix;
      if (i == end_pos - 1)
        length_factor++;
      if (is_bad_suffix) {
        length_factor = start_bad_suffix - start_prefix;
      }
      if (length_factor > max_factor_length) {
        max_factor_length = length_factor;
        max_start_factor = start_prefix;
      }
      // Restart for a new factor
      start_prefix = i+1;
      is_bad_suffix = false;
      suffix_score = 0;
      prefix_score = 0;
    }
427
  }
428

429
  start_pos = min(required_start, max_start_factor);
430 431 432
  length = max_factor_length;
  if (required_start != string::npos && start_pos + length < required_start + required_length)
    length = required_start + required_length - start_pos;
433 434 435
}


436
void output_label_average(ostream &out, string label, long long int nb, double average, int precision)
437 438 439 440 441 442 443 444 445
 {
  out << "  ";

  if (label.size())
    out << left << setw(18) << label << "->" ;

  out << right << setw(9) << nb ;
  out << "   " << setw(5) ;
  if (nb)
446
    out << fixed << setprecision(precision) << average ;
447 448 449
  else
    out << "-" ;
}
450 451


452
void json_add_warning(json &clone, string code, string msg, string level)
453 454 455 456
{
  if (!clone.count("warn"))
    clone["warn"] = {} ;

457
  clone["warn"] += { {"code", code}, {"level", level}, {"msg", msg} } ;
458
}
459

460 461 462 463 464 465 466 467 468 469 470 471 472 473
// Signal handling

bool global_interrupted;

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
void sigintHandler(int sig_num)
{
  signal(SIGINT, sigintHandler);
  global_interrupted = true;
}
#pragma GCC diagnostic pop


474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
/* 
	 Return the part of label before the star
	 For example:
	 IGHV5-51*01 -> IGHV5-51
	 If there is no star in the name, the whole label is returned.
	 IGHV10-40 -> IGHV10-40
*/
string extractGeneName(string label){
	string result;
	size_t star_pos;
	star_pos = label.rfind("*");
	if(star_pos != string::npos){
		result = label.substr(0, star_pos);
	}else{
		result = label;
	}
	return result;
}
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507


/*
   Opens a ostream, possibly gz-compressed
*/
std::ostream* new_ofgzstream(const char *f, bool gz)
{
  if (gz)
  {
    return new ogzstream(f);
  }
  else
  {
    return new ofstream(f);
  }
}