fasta.cpp 10.2 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1
/*
2 3 4 5 6 7 8
  This file is part of Vidjil <http://www.vidjil.org>
  Copyright (C) 2011, 2012, 2013, 2014, 2015 by Bonsai bioinformatics 
  at CRIStAL (UMR CNRS 9189, Université Lille) and Inria Lille
  Contributors: 
      Mathieu Giraud <mathieu.giraud@vidjil.org>
      Mikaël Salson <mikael.salson@vidjil.org>
      Marc Duez <marc.duez@vidjil.org>
Mikaël Salson's avatar
Mikaël Salson committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

  "Vidjil" is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  "Vidjil" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with "Vidjil". If not, see <http://www.gnu.org/licenses/>
*/

#include <fstream>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cctype>
#include <stdexcept>
#include "fasta.h"

32
#include "../lib/gzstream.h"
33

34 35 36 37 38 39 40 41

// http://stackoverflow.com/a/5840160/4475279
unsigned long long filesize(const char* filename)
{
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg();
}

42 43 44 45 46
void Fasta::init(int extract_field, string extract_separator)
{
  this -> extract_field = extract_field ;
  this -> extract_separator = extract_separator ; 
  total_size = 0;
47
  name = "";
48
  basename = "";
49 50 51 52 53 54
}

Fasta::Fasta(bool virtualfasta, string name)
{
  init(0, "");
  this -> name = name;
55
  basename = extract_basename(name);
56 57 58 59 60
}

Fasta::Fasta(int extract_field, string extract_separator)
{
  init(extract_field, extract_separator);
Mikaël Salson's avatar
Mikaël Salson committed
61 62 63
}

Fasta::Fasta(const string &input, 
64 65
	     int extract_field, string extract_separator,
             bool verbose) 
Mikaël Salson's avatar
Mikaël Salson committed
66
{
67 68
  init(extract_field, extract_separator);

69
  if (!input.size()) // Do not open empty filenames (D germline if not segmentD)
Mikaël Salson's avatar
Mikaël Salson committed
70 71
    return ;

72
  add(input, verbose);  
73 74
}

75
void Fasta::add(istream &in, bool verbose) {
76
  in >> *this;
77

78
  if (verbose)
79
  cout << "\t" << setw(6) << total_size << " bp in " << setw(3) << size() << " sequences" << endl ;
80 81
}

82
void Fasta::add(const string &filename, bool verbose) {
83
  igzstream is(filename.c_str());
Mikaël Salson's avatar
Mikaël Salson committed
84 85
  if (is.fail())
    {
86
      throw invalid_argument(" !! Error in opening file: "+ filename);
Mikaël Salson's avatar
Mikaël Salson committed
87
    }
88

89 90 91 92 93 94 95 96
  if (name.size())
    name += " ";

  if (basename.size())
    basename += " ";

  name += filename;
  basename += extract_basename(filename);
97

98
  if (verbose)
99
  cout << " <== " << filename ;
100
  add(is, verbose);
Mikaël Salson's avatar
Mikaël Salson committed
101 102 103
  is.close();
}

104 105 106 107 108
void Fasta::add(Sequence seq) {
  reads.push_back(seq);
  total_size += seq.sequence.size();
}

Mikaël Salson's avatar
Mikaël Salson committed
109
int Fasta::size() const{ return (int)reads.size(); }
110 111
int Fasta::totalSize() const { return total_size ; }

Mathieu Giraud's avatar
Mathieu Giraud committed
112 113 114 115 116 117 118 119 120
list<Sequence> Fasta::getAll() const {
  list<Sequence> reads;

  for (int i=0; i < size(); i++) {
    reads.push_back(read(i));
  }

  return reads;
}
Mikaël Salson's avatar
Mikaël Salson committed
121 122 123 124 125 126 127
const string& Fasta::label(int index) const{ return reads[index].label; }
const string& Fasta::label_full(int index) const{ return reads[index].label_full; }
const Sequence& Fasta::read(int index) const {return reads[index];}
const string& Fasta::sequence(int index) const{ return reads[index].sequence; }

// OnlineFasta

128 129 130 131 132
OnlineFasta::OnlineFasta(int extract_field, string extract_separator,
                         int nb_sequences_max, int only_nth_sequence):
  input(NULL),
  extract_field(extract_field), extract_separator(extract_separator),
  nb_sequences_max(nb_sequences_max), only_nth_sequence(only_nth_sequence){}
Mikaël Salson's avatar
Mikaël Salson committed
133 134

OnlineFasta::OnlineFasta(const string &input, 
135 136
                         int extract_field, string extract_separator,
                         int nb_sequences_max, int only_nth_sequence)
137
  :input(new igzstream(input.c_str())),
Mikaël Salson's avatar
Mikaël Salson committed
138
  extract_field(extract_field), 
139 140
   extract_separator(extract_separator),
   nb_sequences_max(nb_sequences_max), only_nth_sequence(only_nth_sequence)
Mikaël Salson's avatar
Mikaël Salson committed
141 142
{
  if (this->input->fail()) {
143
    delete this->input;
144
    throw invalid_argument("!! Error in opening file "+input);
Mikaël Salson's avatar
Mikaël Salson committed
145
  }
Mathieu Giraud's avatar
Mathieu Giraud committed
146 147

  cout << "  <== " << input << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
148 149 150 151 152
  input_allocated = true;
  init();
}

OnlineFasta::OnlineFasta(istream &input, 
153 154
                         int extract_field, string extract_separator,
                         int nb_sequences_max, int only_nth_sequence)
155
  :input(&input), extract_field(extract_field),
156 157
   extract_separator(extract_separator),
   nb_sequences_max(nb_sequences_max), only_nth_sequence(only_nth_sequence)
Mikaël Salson's avatar
Mikaël Salson committed
158 159 160 161 162 163 164 165
{
  input_allocated = false;
  init();
}

OnlineFasta::~OnlineFasta() {
  if (input_allocated)
    delete input;
166 167
  if (current.seq)
    delete [] current.seq;
Mikaël Salson's avatar
Mikaël Salson committed
168 169 170
}

void OnlineFasta::init() {
171
  nb_sequences_parsed = 0;
172
  nb_sequences_returned = 0;
173
  char_nb = 0;
Mikaël Salson's avatar
Mikaël Salson committed
174 175
  line_nb = 0;
  line = getInterestingLine();
176
  current.seq = NULL;
177
  current_gaps = 0;
Mikaël Salson's avatar
Mikaël Salson committed
178 179
}

180 181 182 183
unsigned long long OnlineFasta::getPos() {
  return char_nb;
}

Mikaël Salson's avatar
Mikaël Salson committed
184 185 186 187 188 189 190 191
size_t OnlineFasta::getLineNb() {
  return line_nb;
}

Sequence OnlineFasta::getSequence() {
  return current;
}

192 193 194 195 196

bool OnlineFasta::hasNextData() {
  return ((!input->eof()) || line.length() > 0);
}

Mikaël Salson's avatar
Mikaël Salson committed
197
bool OnlineFasta::hasNext() {
198
  return hasNextData()
199
    && ((nb_sequences_max == NO_LIMIT_VALUE) || (nb_sequences_returned < nb_sequences_max));
Mikaël Salson's avatar
Mikaël Salson committed
200 201
}

202 203
void OnlineFasta::skipToNthSequence() {
  // Possibly skip some reads, when only_nth_sequence > 1
204
  while (hasNextData())
205 206 207 208 209 210 211 212 213 214
    if (nb_sequences_parsed % only_nth_sequence)
      {
        nb_sequences_returned--;
        next();
        continue ;
      }
    else
      return  ;
}

215 216
void OnlineFasta::addLineToCurrentSequence(string line)
{
217 218 219 220 221 222 223 224 225 226 227 228
  for (char& c : line)
    {
      if (c == ' ')
        continue ;

      if (c == '.') {
        current_gaps++;
        continue ;
      }

      current.sequence += c;
    }
229
}
230

Mikaël Salson's avatar
Mikaël Salson committed
231 232 233 234 235 236 237 238
void OnlineFasta::next() {
  fasta_state state = FASTX_UNINIT;

  // Reinit the Sequence object
  current.label_full.erase();
  current.label.erase();
  current.sequence.erase();
  current.quality.erase();
239
  if (current.seq) {
240
    delete [] current.seq;
241
    current.seq = NULL;
242
    current_gaps = 0;
243
  }
Mikaël Salson's avatar
Mikaël Salson committed
244

245
  if  (hasNextData()) {
Mikaël Salson's avatar
Mikaël Salson committed
246 247 248 249
    switch(line[0]) {
    case '>': state=FASTX_FASTA; break;
    case '@': state=FASTX_FASTQ_ID; break;
    default: 
250
      throw invalid_argument("The file seems to be malformed!");
Mikaël Salson's avatar
Mikaël Salson committed
251 252 253
    }
    
    // Identifier line
254
    nb_sequences_parsed++;
255
    nb_sequences_returned++;
Mikaël Salson's avatar
Mikaël Salson committed
256 257 258 259
    current.label_full = line.substr(1);
    current.label = extract_from_label(current.label_full, extract_field, extract_separator);

    line = getInterestingLine();
260
    while (hasNextData() && ((state != FASTX_FASTA || line[0] != '>')
Mikaël Salson's avatar
Mikaël Salson committed
261 262
                         && (state != FASTX_FASTQ_QUAL || line[0] != '@'))) {

263
      if (hasNextData()) {
Mikaël Salson's avatar
Mikaël Salson committed
264 265 266
        switch(state) {
        case FASTX_FASTA: case FASTX_FASTQ_ID:
          // Sequence
267
          addLineToCurrentSequence(line);
Mikaël Salson's avatar
Mikaël Salson committed
268 269 270
          break;
        case FASTX_FASTQ_SEQ:
          // FASTQ separator between sequence and quality
271 272
          if (line[0] != '+')
            throw invalid_argument("Expected line starting with + in FASTQ file");
Mikaël Salson's avatar
Mikaël Salson committed
273 274 275 276
          break;
        case FASTX_FASTQ_SEP:
          // Reading quality
          current.quality = line;
277 278
          if (current.quality.length() != current.sequence.length())
            throw invalid_argument("Quality and sequence don't have the same length ");
Mikaël Salson's avatar
Mikaël Salson committed
279 280
          break;
        default:
281
          throw invalid_argument("Unexpected state after reading identifiers line");
Mikaël Salson's avatar
Mikaël Salson committed
282 283 284 285 286 287
        }
        if (state >= FASTX_FASTQ_ID && state <= FASTX_FASTQ_SEP)
          state = (fasta_state)(((int)state) + 1);
      } else {
        unexpectedEOF();
      }
288
      line = getInterestingLine(state);
Mikaël Salson's avatar
Mikaël Salson committed
289 290 291 292 293 294 295
    }

    if (state >= FASTX_FASTQ_ID && state < FASTX_FASTQ_QUAL) 
      unexpectedEOF();

    // Sequence in uppercase
    transform(current.sequence.begin(), current.sequence.end(), current.sequence.begin(), (int (*)(int))toupper);
296 297 298

    // Compute seq
    current.seq = new int[current.sequence.length()];
299
    for (unsigned int i=0; i< current.sequence.length(); i++)
300
      {
301
	current.seq[i] = nuc_to_int(current.sequence[i]) ;
302 303
      }

Mikaël Salson's avatar
Mikaël Salson committed
304 305
  } else
    unexpectedEOF();
306 307

  skipToNthSequence();
Mikaël Salson's avatar
Mikaël Salson committed
308 309
}

310
string OnlineFasta::getInterestingLine(int state) {
Mikaël Salson's avatar
Mikaël Salson committed
311
  string line;
312
  while (line.length() == 0 && hasNextData() && getline(*input, line)) {
Mikaël Salson's avatar
Mikaël Salson committed
313
    line_nb++;
314
    char_nb += line.length() + 1;
Mikaël Salson's avatar
Mikaël Salson committed
315
    remove_trailing_whitespaces(line);
316 317 318

    if (line.length() && line[0] == '#' && state != FASTX_FASTQ_SEP)
      line = "" ;
Mikaël Salson's avatar
Mikaël Salson committed
319 320 321 322 323
  }
  return line;
}

void OnlineFasta::unexpectedEOF() {
324
  throw invalid_argument("Unexpected EOF while reading FASTA/FASTQ file");
Mikaël Salson's avatar
Mikaël Salson committed
325 326 327 328 329 330 331 332 333 334 335
}

// Operators

istream& operator>>(istream& in, Fasta& fasta){
	string line;
	Sequence read;
        OnlineFasta of(in, fasta.extract_field, fasta.extract_separator);

        while (of.hasNext()) {
          of.next();
336
          fasta.add(of.getSequence());
Mikaël Salson's avatar
Mikaël Salson committed
337 338 339 340 341 342
        }
	return in;
}

ostream& operator<<(ostream& out, Fasta& fasta){
	for(int i = 0 ; i < fasta.size() ; i++){
343
          out << fasta.read(i);
Mikaël Salson's avatar
Mikaël Salson committed
344 345 346 347 348
	}
	return out;
}

ostream &operator<<(ostream &out, const Sequence &seq) {
349 350 351 352 353 354 355
  bool is_fastq=false;
  if (seq.quality.length() > 0) {
    is_fastq = true;
    out << "@";
  } else
    out << ">";
  out << seq.label << endl;
Mikaël Salson's avatar
Mikaël Salson committed
356
  out << seq.sequence << endl;
357 358 359
  if (is_fastq) {
    out << "+" << endl << seq.quality << endl;
  }
Mikaël Salson's avatar
Mikaël Salson committed
360 361
  return out;
}
362

363
int nb_sequences_in_fasta(string f, bool approx)
364
{
365 366 367
  if (approx)
    return approx_nb_sequences_in_fasta(f);

368 369 370 371 372 373 374 375 376 377
  OnlineFasta *sequences = new OnlineFasta(f, 1, " ");
  int nb_sequences = 0 ;

  while (sequences->hasNext())
    {
      sequences->next();
      nb_sequences++ ;
    }

  cout << "  ==> " << nb_sequences << " sequences" << endl;
378 379

  delete sequences ;
380 381
  return nb_sequences ;
}
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407


#define SAMPLE_APPROX_NB_SEQUENCES 200

int approx_nb_sequences_in_fasta(string f)
{
  OnlineFasta *sequences = new OnlineFasta(f, 1, " ");
  int nb_sequences = 0 ;

  while (nb_sequences < SAMPLE_APPROX_NB_SEQUENCES && sequences->hasNext())
    {
      sequences->next();
      nb_sequences++ ;
    }

  cout << "  ==> " ;

  if (sequences->hasNext())
    {
      cout << "approx. " ;
      float ratio = (float) filesize(f.c_str()) / (float) sequences->getPos();
      nb_sequences = (int) (ratio * nb_sequences);
    }

  cout << nb_sequences << " sequences" << endl;

408
  delete sequences ;
409 410
  return nb_sequences ;
}