vidjil.cpp 63.4 KB
Newer Older
Mikael Salson's avatar
Mikael Salson committed
1
/*
2
  This file is part of Vidjil-algo <http://www.vidjil.org>
3
  Copyright (C) 2011-2019 by VidjilNet consortium and Bonsai bioinformatics
4 5 6 7 8
  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>
Mikael Salson's avatar
Mikael Salson committed
9

10
  "Vidjil-algo" is free software: you can redistribute it and/or modify
Mikael Salson's avatar
Mikael Salson committed
11 12 13 14
  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.

15
  "Vidjil-algo" is distributed in the hope that it will be useful,
Mikael Salson's avatar
Mikael Salson committed
16 17 18 19 20
  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
21
  along with "Vidjil-algo". If not, see <http://www.gnu.org/licenses/>
Mikael Salson's avatar
Mikael Salson committed
22 23
*/

Mathieu Giraud's avatar
Mathieu Giraud committed
24
//$$ #include
Mikael Salson's avatar
Mikael Salson committed
25 26 27 28 29 30 31 32 33 34 35 36 37

#include<algorithm>
#include<utility>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

38
#include "core/check-compiler.h"
Mikael Salson's avatar
Mikael Salson committed
39
#include "core/tools.h"
40
#include "core/json.h"
41
#include "core/germline.h"
Mikael Salson's avatar
Mikael Salson committed
42 43
#include "core/kmerstore.h"
#include "core/fasta.h"
44
#include "core/bioreader.hpp"
Mikael Salson's avatar
Mikael Salson committed
45
#include "core/segment.h"
Mathieu Giraud's avatar
Mathieu Giraud committed
46
#include "core/windows.h"
Mikael Salson's avatar
Mikael Salson committed
47 48 49 50 51 52 53
#include "core/cluster-junctions.h"
#include "core/dynprog.h"
#include "core/read_score.h"
#include "core/read_chooser.h"
#include "core/compare-all.h"
#include "core/mkdir.h"
#include "core/labels.h"
Mikael Salson's avatar
Mikael Salson committed
54
#include "core/list_utils.h"
Mathieu Giraud's avatar
Mathieu Giraud committed
55
#include "core/windowExtractor.h"
56
#include "core/output.h"
Mikael Salson's avatar
Mikael Salson committed
57

58
#include "lib/CLI11.hpp"
59
#include "lib/json.hpp"
60
#include "lib/CLI11_json.hpp"
61

Mikael Salson's avatar
Mikael Salson committed
62 63 64 65 66 67 68
#include "vidjil.h"

// RELEASE_TAG may be defined in the "release.h" file.
// If RELEASE_TAG is undefined, the version will be the git hash.
// #define RELEASE_TAG  "2013.04"
#include "release.h"

69 70 71
// GIT_VERSION should be defined in "git-version.h", created by "create-git-version-h.sh", to be used outside of releases
#include "git-version.h"

72
#define PROGNAME "vidjil-algo"
73
#define VIDJIL_JSON_VERSION "2016b"
74
#define DOCUMENTATION "doc/vidjil-algo.md"
Mikael Salson's avatar
Mikael Salson committed
75

Mathieu Giraud's avatar
Mathieu Giraud committed
76 77
//$$ #define (mainly default options)

78
#define DEFAULT_MULTI_GERMLINE_PATH "germline/"
79
#define DEFAULT_MULTI_GERMLINE_FILE "homo-sapiens.g"
Mikael Salson's avatar
Mikael Salson committed
80

81
#define DEFAULT_READ_HEADER_SEPARATOR " "
82
#define DEFAULT_READS  "./demo/Stanford_S22.fasta"
83
#define DEFAULT_MIN_READS_CLONE 5
84
#define DEFAULT_MAX_REPRESENTATIVES 100
85
#define DEFAULT_MAX_CLONES 100
86
#define DEFAULT_RATIO_READS_CLONE 0.0
87
#define NO_LIMIT "all"
Mikael Salson's avatar
Mikael Salson committed
88

Mathieu Giraud's avatar
Mathieu Giraud committed
89
#define COMMAND_WINDOWS "windows"
90
#define COMMAND_CLONES "clones"
91
#define COMMAND_SEGMENT "designations"
92
#define COMMAND_GERMLINES "germlines"
Mikael Salson's avatar
Mikael Salson committed
93
 
94
enum { CMD_WINDOWS, CMD_CLONES, CMD_SEGMENT, CMD_GERMLINES } ;
Mikael Salson's avatar
Mikael Salson committed
95

96 97 98
#define DEFAULT_OUT_DIR "./out/" 

// Fixed filenames/suffixes
99
#define CLONES_FILENAME ".vdj.fa"
Mikael Salson's avatar
Mikael Salson committed
100
#define CLONE_FILENAME "clone.fa-"
101 102
#define WINDOWS_FILENAME ".windows.fa"
#define SEGMENTED_FILENAME ".segmented.vdj.fa"
103
#define UNSEGMENTED_FILENAME ".unsegmented.vdj.fa"
104
#define UNSEGMENTED_DETAIL_FILENAME ".fa"
105
#define AFFECTS_FILENAME ".affects"
106 107
#define EDGES_FILENAME ".edges"
#define COMP_FILENAME "comp.vidjil"
108
#define AIRR_SUFFIX ".tsv"
109
#define JSON_SUFFIX ".vidjil"
Mikael Salson's avatar
Mikael Salson committed
110

111
#define DEFAULT_K      0
112
#define DEFAULT_W      50
Mikael Salson's avatar
Mikael Salson committed
113

Mikael Salson's avatar
Mikael Salson committed
114
#define DEFAULT_MAX_AUDITIONED 2000
Mathieu Giraud's avatar
Mathieu Giraud committed
115
#define DEFAULT_RATIO_REPRESENTATIVE 0.5
116 117 118 119 120
#define DEFAULT_MIN_COVER_REPRESENTATIVE 3 // At least 3 reads to support a
                                           // representative (consisting of at
                                           // least
                                           // DEFAULT_RATIO_REPRESENTATIVE of
                                           // the clone's reads)
Mathieu Giraud's avatar
Mathieu Giraud committed
121

122
#define DEFAULT_KMER_THRESHOLD 1
Mathieu Giraud's avatar
Mathieu Giraud committed
123

Mikael Salson's avatar
Mikael Salson committed
124 125 126 127 128 129
#define DEFAULT_EPSILON  0
#define DEFAULT_MINPTS   10

#define DEFAULT_CLUSTER_COST  Cluster
#define DEFAULT_SEGMENT_COST   VDJ

130
#define DEFAULT_TRIM 0
Mikael Salson's avatar
Mikael Salson committed
131

132
#define MAX_CLONES_FOR_SIMILARITY 20
133

134
// warn
135
#define WARN_MAX_CLONES 5000
136
#define WARN_PERCENT_SEGMENTED 40
137
#define WARN_COVERAGE 0.6
138
#define WARN_NUM_CLONES_SIMILAR 10
139

Mikael Salson's avatar
Mikael Salson committed
140 141 142
// display
#define WIDTH_NB_READS 7
#define WIDTH_NB_CLONES 3
143
#define PAD_HELP "\n                              "
Mikael Salson's avatar
Mikael Salson committed
144 145

using namespace std ;
146
using json = nlohmann::json;
Mikael Salson's avatar
Mikael Salson committed
147

Mathieu Giraud's avatar
Mathieu Giraud committed
148
//$$ options: usage
Mikael Salson's avatar
Mikael Salson committed
149

Mathieu Giraud's avatar
Mathieu Giraud committed
150
extern char *optarg;
Mikael Salson's avatar
Mikael Salson committed
151 152 153

extern int optind, optopt, opterr;

154
string usage_examples(char *progname)
Mikael Salson's avatar
Mikael Salson committed
155
{
156 157
  stringstream ss;
  ss
158
       << "Examples (see " DOCUMENTATION ")" << endl
159
       << "  " << progname << " -c clones       -g germline/homo-sapiens.g   -2 -3 -r 1  demo/Demo-X5.fa           # (basic usage, detect the locus for each read," << endl
160 161
       << "                                                                                               #  cluster reads and report clones starting from the first read (-r 1)," << endl
       << "                                                                                               #  including unexpected recombinations (-2), assign V(D)J genes and try to detect the CDR3s (-3))" << endl
162 163 164 165 166
       << "  " << progname << " -c clones       -g germline/homo-sapiens.g:IGH    -3     demo/Stanford_S22.fasta   # (restrict to complete recombinations on the IGH locus)" << endl
       << "  " << progname << " -c clones       -g germline/homo-sapiens.g   -2 -3 -z 20 demo/LIL-L4.fastq.gz      # (basic usage, output detailed V(D)J analysis on the first 20 clones)" << endl
       << "  " << progname << " -c windows      -g germline/homo-sapiens.g   -y 0 -uu -U demo/LIL-L4.fastq.gz      # (splits all the reads into (large) files depending on the detection of V(D)J recombinations)" << endl
       << "  " << progname << " -c designations -g germline/homo-sapiens.g   -2 -3 -X 50 demo/Stanford_S22.fasta   # (full analysis of each read, here on 50 sampled reads)" << endl
       << "  " << progname << " -c germlines    -g germline/homo-sapiens.g               demo/Stanford_S22.fasta   # (statistics on the k-mers)" << endl
Mikael Salson's avatar
Mikael Salson committed
167
    ;
168 169

  return ss.str();
Mikael Salson's avatar
Mikael Salson committed
170 171
}

172 173 174 175
inline std::string failure_message_doc(const CLI::App *app, const CLI::Error &e) {
    std::string header = ERROR_STRING + std::string(e.what()) + "\n";
    header += "For more information, ";
    if(app->get_help_ptr() != nullptr)
176
        header += "run with " + app->get_help_ptr()->get_name() + " or ";
177 178 179
    header += "see " DOCUMENTATION ".\n";
    return header;
}
180

181
int atoi_NO_LIMIT(const char *optarg)
182
{
183 184
  return strcmp(NO_LIMIT, optarg) ? atoi(optarg) : NO_LIMIT_VALUE ;
}
185
double atof_NO_LIMIT(const char *optarg)
186 187
{
  return strcmp(NO_LIMIT, optarg) ? atof(optarg) : NO_LIMIT_VALUE ;
188 189
}

190 191 192 193 194 195 196 197 198 199
string string_NO_LIMIT(string s)
{
  if (!strcmp(NO_LIMIT, s.c_str()))
    return NO_LIMIT_VALUE_STRING ;

  return s;
}



Mikael Salson's avatar
Mikael Salson committed
200 201
int main (int argc, char **argv)
{
202
  cout << "# " << PROGNAME << " -- V(D)J recombinations analysis <http://www.vidjil.org/>" << endl
203
       << "# Copyright (C) 2011-2019 by the Vidjil team" << endl
204
       << "# Bonsai bioinformatics at CRIStAL (UMR CNRS 9189, Université Lille) and Inria Lille" << endl 
205
       << "# VidjilNet consortium" << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
206
       << endl
207
       << "# " << PROGNAME << " is free software, and you are welcome to redistribute it" << endl
Mathieu Giraud's avatar
Mathieu Giraud committed
208 209 210
       << "# under certain conditions -- see http://git.vidjil.org/blob/master/doc/LICENSE" << endl
       << "# No lymphocyte was harmed in the making of this software," << endl
       << "# however this software is for research use only and comes with no warranty." << endl
211
       << endl
212
       << "# Please cite http://biomedcentral.com/1471-2164/15/409 if you use " << PROGNAME << "." << endl
Mikael Salson's avatar
Mikael Salson committed
213 214
       << endl ;

215 216 217
  //////////////////////////////////
  // Display version information or git log

218 219
  string soft_version = PROGNAME ;
  soft_version += " " ;
220
#ifdef RELEASE_TAG
221
  cout << "# version: " PROGNAME << " " << RELEASE_TAG << endl ;
222 223 224 225 226 227 228 229 230 231
  soft_version.append(RELEASE_TAG);
#else
  cout << "# development version" << endl ;
#ifdef GIT_VERSION
  cout << "# git: " << GIT_VERSION << endl ;
  soft_version.append("dev ");
  soft_version.append(GIT_VERSION);
#endif
#endif

232
  CLI::App app{"# vidjil-algo -- V(D)J recombinations analysis", argv[0]};
233 234
  app.get_formatter()->label("REQUIRED", "");
  app.get_formatter()->label("Positionnals", "");
235
  app.failure_message(failure_message_doc);
236

Mathieu Giraud's avatar
Mathieu Giraud committed
237
  //$$ options: defaults
Mathieu Giraud's avatar
Mathieu Giraud committed
238
  float ratio_representative = DEFAULT_RATIO_REPRESENTATIVE;
Mikael Salson's avatar
Mikael Salson committed
239
  unsigned int max_auditionned = DEFAULT_MAX_AUDITIONED;
240
  // int average_deletion = 4;     // Average number of deletion in V or J
Mathieu Giraud's avatar
Mathieu Giraud committed
241

242
  //$$ options: definition with CLI11
243
  string group = "";
Mathieu Giraud's avatar
Mathieu Giraud committed
244

245
  // ----------------------------------------------------------------------------------------------------------------------
246
  string f_reads = DEFAULT_READS ;
247 248 249 250 251 252
  app.add_option("reads_file", f_reads, R"Z(reads file, in one of the following formats:
                                  - FASTA (.fa/.fasta, .fa.gz/.fasta.gz)
                                  - FASTQ (.fq/.fastq, .fq.gz/.fastq.gz)
                                  - BAM (.bam)
                              Paired-end reads should be merged before given as an input to vidjil-algo.
                 )Z")
253
    -> required() -> type_name("");
254

255

256
  // ----------------------------------------------------------------------------------------------------------------------
257
  group = "Command selection";
258

Mathieu Giraud's avatar
Mathieu Giraud committed
259 260 261 262
  string cmd = COMMAND_CLONES;
  app.add_option("-c", cmd, "command"
                 "\n  \t\t" COMMAND_CLONES    "  \t locus detection, window extraction, clone clustering (default command, most efficient, all outputs)"
                 "\n  \t\t" COMMAND_WINDOWS   "  \t locus detection, window extraction"
263
                 "\n  \t\t" COMMAND_SEGMENT   "  \t detailed V(D)J designation, without prior clustering (not as efficient)"
Mathieu Giraud's avatar
Mathieu Giraud committed
264
                 "\n  \t\t" COMMAND_GERMLINES "  \t statistics on k-mers in different germlines")
265
    -> group(group) -> type_name("COMMAND");
Mikael Salson's avatar
Mikael Salson committed
266

267
  // ----------------------------------------------------------------------------------------------------------------------
268
  group = "Input" ;
269 270

  string read_header_separator = DEFAULT_READ_HEADER_SEPARATOR ;
271
  app.add_option("--header-sep", read_header_separator, "separator for headers in the reads file", false)
272
    -> group(group) -> level() -> type_name("CHAR='" DEFAULT_READ_HEADER_SEPARATOR "'");
Mikael Salson's avatar
Mikael Salson committed
273

274 275 276 277 278 279 280 281 282 283 284
  int max_reads_processed = NO_LIMIT_VALUE;
  int max_reads_processed_sample = NO_LIMIT_VALUE;

  app.add_option("--first-reads,-x", max_reads_processed,
                 "maximal number of reads to process ('" NO_LIMIT "': no limit, default), only first reads")
    -> group(group) -> transform(string_NO_LIMIT);

  app.add_option("--sampled-reads,-X", max_reads_processed_sample,
                 "maximal number of reads to process ('" NO_LIMIT "': no limit, default), sampled reads")
    -> group(group) -> transform(string_NO_LIMIT);

285 286

  // ----------------------------------------------------------------------------------------------------------------------
287
  group = "Germline presets (at least one -g or -V/(-D)/-J option must be given)";
288

289
  vector <string> multi_germlines ;
290
  app.add_option("--germline,-g", multi_germlines, R"Z(
291
         -g <.g FILE>(:FILTER)
Mathieu Giraud's avatar
Mathieu Giraud committed
292 293 294
                    multiple locus/germlines, with tuned parameters.
                    Common values are '-g germline/homo-sapiens.g' or '-g germline/mus-musculus.g'
                    The list of locus/recombinations can be restricted, such as in '-g germline/homo-sapiens.g:IGH,IGK,IGL'
295 296
         -g PATH
                    multiple locus/germlines, shortcut for '-g PATH/)Z" DEFAULT_MULTI_GERMLINE_FILE R"Z(',
297
                    processes human TRA, TRB, TRG, TRD, IGH, IGK and IGL locus, possibly with incomplete/unusal recombinations)Z")
298
    -> group(group) -> type_name("GERMLINES");
299

300 301 302 303
  vector <string> v_reps_V ;
  vector <string> v_reps_D ;
  vector <string> v_reps_J ;
   
304 305
  app.add_option("-V", v_reps_V,
                 "custom V germline multi-fasta file(s)")
306
    -> group(group) -> type_name("FILE");
307

308

309
  app.add_option("-D", v_reps_D,
310
                 "custom D germline multi-fasta file(s), analyze into V(D)J components")
311
    -> group(group) -> type_name("FILE");
312

313 314
  app.add_option("-J", v_reps_J,
                 "custom V germline multi-fasta file(s)")
315
    -> group(group) -> type_name("FILE");
316

317

318
  bool multi_germline_unexpected_recombinations_12 = false;
319
  app.add_flag("-2", multi_germline_unexpected_recombinations_12, "try to detect unexpected recombinations") -> group(group);
320

321

322 323
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Recombination detection (\"window\" prediction, first pass)";
324 325 326
  group += "\n    (use either -s or -k option, but not both)";
  group += "\n    (using -k option is equivalent to set with -s a contiguous seed with only '#' characters)" ;
  group += "\n    (all these options, except -w, are overriden when using -g)";
327 328 329

  int options_s_k = 0 ;

330
  IndexTypes indexType = AC_AUTOMATON;
331
  app.add_flag_function("--plain-index",
332
                        [&](size_t n) { UNUSED(n); indexType = KMER_INDEX; },
333
                        "use a plain index (pre-2019 method) instead of the recommended Aho-Corasick-like automaton")
334
    -> group(group) -> level();
335

336 337
  string seed = DEFAULT_SEED ;
  bool seed_changed = false;
338
  app.add_option("--kmer,-k",
339 340 341 342 343 344 345 346 347 348
                 [&](CLI::results_t res) {
                   int kmer_size ;
                   bool worked = CLI::detail::lexical_cast(res[0], kmer_size);
                   if (worked) {
                     seed = seed_contiguous(kmer_size);
                     seed_changed = true;
                     options_s_k++ ;
                   }
                   return worked;
                 },
349
                 "k-mer size used for the V/J affectation (default: 10, 12, 13, depends on germline)")
350
    -> group(group) -> level() -> type_name("INT");
351

352
  int wmer_size = DEFAULT_W ;
353
  app.add_option("--window,-w", wmer_size,
354
                 "w-mer size used for the length of the extracted window ('" NO_LIMIT "': use all the read, no window clustering)")
355
    -> group(group) -> level() -> transform(string_NO_LIMIT);
356

357 358

  double expected_value = THRESHOLD_NB_EXPECTED;
359
  app.add_option("--e-value,-e", expected_value,
360
                 "maximal e-value for determining if a V-J segmentation can be trusted", true)
361
    -> group(group) -> level() -> transform(string_NO_LIMIT);
362

363 364
  int trim_sequences = DEFAULT_TRIM;
  bool trim_sequences_changed = false;
365
  app.add_option("--trim",
366
                 [&](CLI::results_t res) {
367
                   CLI::detail::lexical_cast(res[0], trim_sequences);
368 369 370 371
                   trim_sequences_changed = true;
                   return true;
                 },
                 // trim_sequences,
372
                 "trim V and J genes (resp. 5' and 3' regions) to keep at most <INT> nt  (0: no trim)")
373
    -> group(group) -> level() -> type_name("INT");
Mikael Salson's avatar
Mikael Salson committed
374

375
  app.add_option("--seed,-s",
376 377 378 379 380 381
                 [&](CLI::results_t res) {
                   seed = res[0] ;
                   options_s_k++ ;
                   seed_changed = true;
                   return true;
                 },
382
                 "seed, possibly spaced, used for the V/J affectation (default: depends on germline), given either explicitely or by an alias"
383
                 PAD_HELP + string_of_map(seedMap, " ")
384
                 )
385
    -> group(group) -> level() -> type_name("SEED=" DEFAULT_SEED);
386

Mikael Salson's avatar
Mikael Salson committed
387

388 389
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Recombination detection, experimental options (do not use)";
390

391 392 393 394
  bool multi_germline_mark = false;
  bool multi_germline_one_unique_index = false;
  bool multi_germline_unexpected_recombinations_1U = false;

395
  app.add_flag("-I", multi_germline_mark,
396
               "ignore k-mers common to different germline systems (experimental, do not use)")
397 398
    -> group(group) -> level();

399
  app.add_flag("-1", multi_germline_one_unique_index,
400
               "use a unique index for all germline systems (experimental, do not use)")
401 402 403
    -> group(group) -> level();

  app.add_flag("-4", multi_germline_unexpected_recombinations_1U,
404
               "try to detect unexpected recombinations with translocations (experimental, do not use)")
405 406
    -> group(group) -> level();

407
  bool keep_unsegmented_as_clone = false;
408 409
  app.add_flag("--not-analyzed-as-clones", keep_unsegmented_as_clone,
               "consider not analyzed reads as clones, taking for junction the complete sequence, to be used on very small datasets (for example --not-analyzed-as-clones -AX 20)")
410
    -> group(group) -> level();
411

412

413
  // ----------------------------------------------------------------------------------------------------------------------
414
  group = "Labeled sequences (windows related to these sequences will be kept even if -r/--ratio thresholds are not reached)";
415 416 417 418

  vector <string> windows_labels_explicit ;
  string windows_labels_file = "" ;

419 420
  app.add_option("--label", windows_labels_explicit, "label the given sequence(s)") -> group(group) -> level() -> type_name("SEQUENCE");
  app.add_option("--label-file", windows_labels_file, "label a set of sequences given in <file>") -> group(group) -> level() -> type_name("FILE");
421 422

  bool only_labeled_windows = false ;
423
  app.add_flag("--label-filter", only_labeled_windows, "filter -- keep only the windows related to the labeled sequences") -> group(group) -> level();
Mikael Salson's avatar
Mikael Salson committed
424 425


426
  // ----------------------------------------------------------------------------------------------------------------------
427
  group = "Limits to report and to analyze clones (second pass)";
428
  int max_clones_id = NO_LIMIT_VALUE ;
429 430 431
  int min_reads_clone = DEFAULT_MIN_READS_CLONE ;
  float ratio_reads_clone = DEFAULT_RATIO_READS_CLONE;

432 433
  app.add_option("--min-reads,-r", min_reads_clone, "minimal number of reads supporting a clone", true) -> group(group);
  app.add_option("--min-ratio", ratio_reads_clone, "minimal percentage of reads supporting a clone", true) -> group(group);
434
  app.add_option("--max-clones", max_clones_id, "maximal number of output clones ('" NO_LIMIT "': no maximum, default)", false) -> group(group);
435

436 437 438
  int max_clones = DEFAULT_MAX_CLONES ;
  int max_representatives = DEFAULT_MAX_REPRESENTATIVES ;

439
  app.add_option("--max-consensus,-y", max_representatives,
440 441
                 "maximal number of clones computed with a consensus sequence ('" NO_LIMIT "': no limit)", true)
    -> group(group) -> transform(string_NO_LIMIT);
442

443
  app.add_option("--max-designations,-z",
444 445 446 447 448 449 450
                 [&max_clones, &max_representatives](CLI::results_t res) {
                   max_clones = atoi_NO_LIMIT(res[0].c_str());
                   if ((max_representatives < max_clones) && (max_representatives != NO_LIMIT_VALUE))
                     max_representatives = max_clones ;
                   return true;
                   // TODO: return false on bad input
                 },
451
                 "maximal number of clones to be analyzed with a full V(D)J designation ('" NO_LIMIT "': no limit, do not use)")
452
    -> group(group) -> type_name("INT=" + string_of_int(max_clones));
453

454
  app.add_flag_function("--all", [&](size_t n) {
455
      UNUSED(n);
456 457 458 459 460
      ratio_reads_clone = 0 ;
      min_reads_clone = 1 ;
      max_representatives = NO_LIMIT_VALUE ;
      max_clones = NO_LIMIT_VALUE ;
    },
461
    "reports and analyzes all clones"
462 463
    PAD_HELP "(--min-reads 1 --min-ratio 0 --max-clones " NO_LIMIT" --max-consensus " NO_LIMIT " --max-designations " NO_LIMIT "),"
    PAD_HELP "to be used only on small datasets (for example --all -X 1000)")
464
    -> group(group);
465

466
  VirtualReadScore *readScorer = &DEFAULT_READ_SCORE;
467 468 469 470
  RandomScore randomScore;
  app.add_flag_function("--consensus-on-random-sample",
                        [&readScorer, &randomScore](size_t n) {
                          UNUSED(n);
471
                          readScorer = &randomScore;
472 473
                        }, "for large clones, use a random sample of reads to compute the consensus sequence (instead of a sample of the longest and highest quality reads)")
    ->group(group) -> level();
474 475 476

  // ----------------------------------------------------------------------------------------------------------------------
  group = "Clone analysis (second pass)";
477

478
  Cost segment_cost = DEFAULT_SEGMENT_COST ;
479
  app.add_option("--analysis-cost",
480 481 482 483
                 [&segment_cost](CLI::results_t res) {
                   segment_cost = strToCost(res[0].c_str(), VDJ); 
                   return true;
                 },
484
                 "use custom Cost for clone analysis: format \"match, subst, indels, del_end, homo\" (default " + string_of_cost(DEFAULT_SEGMENT_COST) + ")")
485
    -> group(group) -> level() -> type_name("COST");
Mathieu Giraud's avatar
Mathieu Giraud committed
486

487
  double expected_value_D = THRESHOLD_NB_EXPECTED_D;
488
  app.add_option("--analysis-e-value-D,-E", expected_value_D,
489 490
                 "maximal e-value for determining if a D segment can be trusted", true)
    -> group(group) -> level();
491

492
  int kmer_threshold = DEFAULT_KMER_THRESHOLD;
493 494
  app.add_option("--analysis-filter", kmer_threshold,
                 "typical number of V genes, filtered by k-mer comparison, to compare to the read ('" NO_LIMIT "': all genes)", true)
495
    -> group(group) -> transform(string_NO_LIMIT) -> level();
496

497 498 499
  bool several_D = false;
  app.add_flag("-d,--several-D", several_D, "try to detect several D (experimental)") -> group(group);

500
  bool detect_CDR3 = false;
501 502
  app.add_flag("-3,--cdr3", detect_CDR3, "CDR3/JUNCTION detection (requires gapped V/J germlines)")
    -> group(group);
503

504
  int alternative_genes = 0;
505
  app.add_option("--alternative-genes", alternative_genes, "number of alternative V(D)J genes to show beyond the most similar one", true)
506
    -> group(group) -> level();
507 508
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Additional clustering (third pass, experimental)" ;
509 510 511

  int epsilon = DEFAULT_EPSILON ;
  int minPts = DEFAULT_MINPTS ;
512 513
  app.add_option("--cluster-epsilon", epsilon, "minimum required neighbors for automatic clustering. No automatic clusterisation if =0.", true) -> group(group) -> level();
  app.add_option("--cluster-N", minPts, "minimum required neighbors for automatic clustering", true) -> group(group) -> level();
514 515 516

  bool save_comp = false;
  bool load_comp = false;
517 518
  app.add_flag("--cluster-save-matrix", save_comp, "generate and save comparative matrix for clustering") -> group(group) -> level();
  app.add_flag("--cluster-load-matrix", load_comp, "load comparative matrix for clustering") -> group(group) -> level();
519 520

  string forced_edges = "" ;
521
  app.add_option("--cluster-forced-edges", forced_edges, "manual clustering -- a file used to force some specific edges") -> group(group) -> level() -> type_name("FILE");
522

523
  Cost cluster_cost = DEFAULT_CLUSTER_COST ;
524
  app.add_option("--cluster-cost",
525 526 527 528
                 [&cluster_cost](CLI::results_t res) {
                   cluster_cost = strToCost(res[0].c_str(), Cluster);
                   return true;
                 },
529
                 "use custom Cost for automatic clustering : format \"match, subst, indels, del_end, homo\" (default " + string_of_cost(DEFAULT_CLUSTER_COST) + ")")
530
    -> group(group) -> level() -> type_name("COST");
531 532

  
533
  // ----------------------------------------------------------------------------------------------------------------------
534
  group = "Detailed output per read (generally not recommended, large files, but may be used for filtering, as in -uu -X 1000)";
535 536

  bool output_segmented = false;
537 538
  app.add_flag("--out-analyzed,-U", output_segmented,
               "output analyzed reads (in " SEGMENTED_FILENAME " file)")
539 540
    -> group(group);

541 542 543 544
  bool output_unsegmented = false;
  bool output_unsegmented_detail = false;
  bool output_unsegmented_detail_full = false;

545
  app.add_flag_function("--out-unanalyzed,-u", [&](size_t n) {
546 547 548
      output_unsegmented = (n >= 3);             // -uuu
      output_unsegmented_detail_full = (n >= 2); // -uu
      output_unsegmented_detail = (n >= 1);      // -u
Mathieu Giraud's avatar
Mathieu Giraud committed
549
    }, R"Z(
550 551 552
        -u          output unanalyzed reads, gathered by cause, except for very short and 'too few V/J' reads (in *)Z" UNSEGMENTED_DETAIL_FILENAME R"Z( files)
        -uu         output unanalyzed reads, gathered by cause, all reads (in *)Z" UNSEGMENTED_DETAIL_FILENAME R"Z( files) (use only for debug)
        -uuu        output unanalyzed reads, all reads, including a )Z" UNSEGMENTED_FILENAME R"Z( file (use only for debug))Z")
553
    -> group(group);
Mathieu Giraud's avatar
Mathieu Giraud committed
554

555 556 557
  bool output_sequences_by_cluster = false;
  app.add_flag("--out-reads", output_sequences_by_cluster, "output all reads by clones (" CLONE_FILENAME "*), to be used only on small datasets") -> group(group);

558
  bool output_affects = false;
559 560 561
  app.add_flag("--out-affects,-K", output_affects,
               "output detailed k-mer affectation for each read (in " AFFECTS_FILENAME " file) (use only for debug, for example -KX 100)")
    -> group(group) -> level();
562

563

564
  // ----------------------------------------------------------------------------------------------------------------------
565
  group = "Output";
566 567 568 569

  string out_dir = DEFAULT_OUT_DIR;
  string f_basename = "";

570 571
  app.add_option("--dir,-o", out_dir, "output directory", true) -> group(group) -> type_name("PATH");
  app.add_option("--base,-b", f_basename, "output basename (by default basename of the input file)") -> group(group) -> type_name("STRING");
572 573 574


  int verbose = 0 ;
575
  app.add_flag_function("--verbose,-v", [&](size_t n) { verbose += n ; }, "verbose mode") -> group(group);
576

577 578
  bool __only_on_exit__clean_memory; // Do not use except on exit, see #3729
  app.add_flag("--clean-memory", __only_on_exit__clean_memory, "clean memory on exit") -> group(group) -> level();
579

580 581 582 583 584 585 586 587 588 589 590 591
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Presets";

  app.add_option("--grep-reads",
    [&only_labeled_windows,&windows_labels_explicit,&output_sequences_by_cluster](CLI::results_t res) {
      only_labeled_windows = true;
      windows_labels_explicit.push_back(res[0].c_str());
      output_sequences_by_cluster = true;
      return true;
    },
    "output, by clone, reads related to the given window sequence, even when they are below the thresholds"
    PAD_HELP "(equivalent to --label SEQUENCE -label-filter --out-reads)")
592
    -> group(group) -> level() -> type_name("SEQUENCE");
593

594 595
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Help";
596
  app.set_help_flag("--help,-h", "help")
597 598
    -> group(group);

599
  app.add_flag_function("--help-advanced,-H", [&](size_t n) { UNUSED(n); throw CLI::CallForAdvancedHelp() ; },
600 601
                        "help, including advanced and experimental options"
                        "\n                              "
602
                        "The full help is available in " DOCUMENTATION ".")
603
    -> group(group);
Mikael Salson's avatar
Mikael Salson committed
604 605


606 607 608 609 610 611 612 613 614 615
  // Deprecated options
  bool deprecated = false;

#define DEPRECATED(options, text) app.add_flag_function((options), [&](size_t n) { UNUSED(n); deprecated = true ; return app.exit(CLI::ConstructionError((text), 1));}) -> level(3);

  DEPRECATED("-t", "'-t' is deprecated, please use '--trim'");
  DEPRECATED("-A", "'-A' is deprecated, please use '--all'");
  DEPRECATED("-a", "'-a' is deprecated, please use '--out-reads'");
  DEPRECATED("-l", "'-l' is deprecated, please use '--label'");

616
  // ----------------------------------------------------------------------------------------------------------------------
617
  app.footer(usage_examples(argv[0]));
618

619 620
  //$$ options: parsing
  CLI11_PARSE(app, argc, argv);
Mathieu Giraud's avatar
Mathieu Giraud committed
621

622
  //$$ options: post-processing+display
Mikael Salson's avatar
Mikael Salson committed
623

624
  int command = CMD_CLONES;
Mathieu Giraud's avatar
Mathieu Giraud committed
625 626 627 628 629 630 631 632
  if (cmd == COMMAND_CLONES)
    command = CMD_CLONES;
  else if (cmd == COMMAND_SEGMENT)
    command = CMD_SEGMENT;
  else if (cmd == COMMAND_WINDOWS)
    command = CMD_WINDOWS;
  else if (cmd == COMMAND_GERMLINES)
    command = CMD_GERMLINES;
633 634
  else if (cmd == "segment")
    return app.exit(CLI::ConstructionError("'-c segment' is deprecated, please use '-c designations'", 1));
Mathieu Giraud's avatar
Mathieu Giraud committed
635
  else {
636
    return app.exit(CLI::ConstructionError("Unknown command " + cmd, 1));
Mathieu Giraud's avatar
Mathieu Giraud committed
637
  }
638
  if (deprecated) return 1 ;
639

640 641 642
  list <string> f_reps_V(v_reps_V.begin(), v_reps_V.end());
  list <string> f_reps_D(v_reps_D.begin(), v_reps_D.end());
  list <string> f_reps_J(v_reps_J.begin(), v_reps_J.end());
643

644

645 646 647
  list <pair <string, string>> multi_germline_paths_and_files ;
  bool multi_germline = false;

Mathieu Giraud's avatar
Mathieu Giraud committed
648 649 650 651 652 653 654 655 656 657 658
  for (string arg: multi_germlines)
    {
      multi_germline = true;

      struct stat buffer;
      if (stat(arg.c_str(), &buffer) == 0)
        {
          if( buffer.st_mode & S_IFDIR )
            {
              // argument is a directory
              multi_germline_paths_and_files.push_back(make_pair(arg, DEFAULT_MULTI_GERMLINE_FILE)) ;
659 660
              continue ;
            }
Mathieu Giraud's avatar
Mathieu Giraud committed
661 662 663 664 665 666 667
        }

      // argument is not a directory (and basename can include ':' with a filter)
      multi_germline_paths_and_files.push_back(make_pair(extract_dirname(arg), extract_basename(arg, false)));
    }


668
  if (!multi_germline && (!f_reps_V.size() || !f_reps_J.size()))
669
    {
670
      return app.exit(CLI::ConstructionError("At least one germline must be given with -g or -V/(-D)/-J.", 1));
671 672
    }

673 674
  if (options_s_k > 1)
    {
675
      return app.exit(CLI::ConstructionError("Use at most one -s or -k option.", 1));
676 677
    }

678 679
  map <string, string> windows_labels ;

680
  for(string lab : windows_labels_explicit)
Mathieu Giraud's avatar
Mathieu Giraud committed
681
    windows_labels[lab] = string("--label");
682
  
Mikael Salson's avatar
Mikael Salson committed
683 684
  string out_seqdir = out_dir + "/seq/" ;

Mikael Salson's avatar
Mikael Salson committed
685 686 687
  if (verbose)
    cout << "# verbose " << verbose << endl ;

688
  if (f_reads == DEFAULT_READS)
Mikael Salson's avatar
Mikael Salson committed
689 690 691
    {
      cout << "# using default sequence file: " << f_reads << endl ;
    }
Mathieu Giraud's avatar
Mathieu Giraud committed
692

693
  size_t min_cover_representative = (size_t) min(min_reads_clone, DEFAULT_MIN_COVER_REPRESENTATIVE);
694

Mathieu Giraud's avatar
Mathieu Giraud committed
695 696 697
  // Check seed buffer  
  if (seed.size() >= MAX_SEED_SIZE)
    {
698
      return app.exit(CLI::ConstructionError("Seed size is too large (MAX_SEED_SIZE).", 1));
Mathieu Giraud's avatar
Mathieu Giraud committed
699
    }
700

Mathieu Giraud's avatar
Mathieu Giraud committed
701
  if ((wmer_size< 0) && (wmer_size!= NO_LIMIT_VALUE))
702
    {
703
      return app.exit(CLI::ConstructionError("Too small -w. The window size should be positive.", 1));
704 705
    }

Mikael Salson's avatar
Mikael Salson committed
706 707 708 709
  // Check that out_dir is an existing directory or creates it
  const char *out_cstr = out_dir.c_str();

  if (mkpath(out_cstr, 0755) == -1) {
710
    cerr << ERROR_STRING << "Directory creation: " << out_dir << endl; perror("");
711
    return 2;
Mikael Salson's avatar
Mikael Salson committed
712 713
  }

Mikael Salson's avatar
Mikael Salson committed
714 715
  const char *outseq_cstr = out_seqdir.c_str();
  if (mkpath(outseq_cstr, 0755) == -1) {
716
    cerr << ERROR_STRING << "Directory creation: " << out_seqdir << endl; perror("");
717
    return 2;
Mikael Salson's avatar
Mikael Salson committed
718 719
  }

720 721 722 723 724
  // Compute basename if not given as an option
  if (f_basename == "") {
    f_basename = extract_basename(f_reads);
  }

Mikael Salson's avatar
Mikael Salson committed
725 726 727
  out_dir += "/" ;

  /// Load labels ;
728
  load_into_map(windows_labels, windows_labels_file, "-l");
Mikael Salson's avatar
Mikael Salson committed
729 730

  switch(command) {
Mathieu Giraud's avatar
Mathieu Giraud committed
731
  case CMD_WINDOWS: cout << "Extracting windows" << endl; 
Mikael Salson's avatar
Mikael Salson committed
732
    break;
733
  case CMD_CLONES: cout << "Analysing clones" << endl; 
Mikael Salson's avatar
Mikael Salson committed
734 735 736
    break;
  case CMD_SEGMENT: cout << "Segmenting V(D)J" << endl;
    break;
737 738
  case CMD_GERMLINES: cout << "Discovering germlines" << endl;
    break;
Mikael Salson's avatar
Mikael Salson committed
739 740
  }

Mathieu Giraud's avatar
Mathieu Giraud committed
741
  cout << "Command line: ";
Mikael Salson's avatar
Mikael Salson committed
742
  for (int i=0; i < argc; i++) {
Mathieu Giraud's avatar
Mathieu Giraud committed
743
    cout << argv[i] << " ";
Mikael Salson's avatar
Mikael Salson committed
744
  }
Mathieu Giraud's avatar
Mathieu Giraud committed
745
  cout << endl;
Mikael Salson's avatar
Mikael Salson committed
746 747 748 749 750 751 752 753 754 755 756 757

  //////////////////////////////////
  // Display time and date
  time_t rawtime;
  struct tm *timeinfo;
  char time_buffer[80];

  time (&rawtime );
  timeinfo = localtime (&rawtime);

  strftime (time_buffer, 80,"%F %T", timeinfo);

Mathieu Giraud's avatar
Mathieu Giraud committed
758
  cout << "# " << time_buffer << endl ;
Mikael Salson's avatar
Mikael Salson committed
759 760


761 762
  //////////////////////////////////
  // Warning for non-optimal use
763

764
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES)
765 766
    {
      cout << endl
767
	   << "* WARNING: " << PROGNAME << " was run with '-A' option or with a large '-z' option" << endl ;
768 769 770 771 772
    }
  
  if (command == CMD_SEGMENT)
    {
      cout << endl
773
	   << "* WARNING: " << PROGNAME << " was run with '-c" COMMAND_SEGMENT "' option" << endl ;
774 775
    }
  
776
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES || command == CMD_SEGMENT)
777
    {
778
      cout << "* " << PROGNAME << " efficiently extracts windows overlapping the CDR3" << endl
779
           << "* to cluster reads into clones ('-c clones')." << endl
780 781
           << "* Computing accurate V(D)J designations for many sequences ('-c " COMMAND_SEGMENT "' or large '-z' values)" << endl
           << "* is not as efficient as the default '-c " COMMAND_CLONES "' command." << endl
782
	   << "* More information is provided in " DOCUMENTATION "." << endl
783 784
	   << endl ;
    }
785

786

787 788 789 790 791 792 793
  //

  //json which contains the Levenshtein distances
  json jsonLevenshtein;
  bool jsonLevenshteinComputed = false ;


794 795 796 797
  /////////////////////////////////////////
  //            JSON OUTPUT              //
  /////////////////////////////////////////

798
  string f_airr = out_dir + f_basename + AIRR_SUFFIX ;
799 800 801 802 803
  string f_json = out_dir + f_basename + JSON_SUFFIX ;

  ostringstream stream_cmdline;
  for (int i=0; i < argc; i++) stream_cmdline << argv[i] << " ";

804
  SampleOutput output({
805 806 807 808 809 810 811 812
    {"vidjil_json_version", VIDJIL_JSON_VERSION},
    {"samples", {
        {"number", 1},
        {"original_names", {f_reads}},
        {"run_timestamp", {time_buffer}},
        {"producer", {soft_version}},
        {"commandline", {stream_cmdline.str()}}
      }}
813
  });
814 815


816 817 818
  /////////////////////////////////////////
  //            LOAD GERMLINES           //
  /////////////////////////////////////////
819

820 821 822
  if (command == CMD_GERMLINES)
    {
      multi_germline = true ;
823
      multi_germline_one_unique_index = true ;
824 825
    }

826
  MultiGermline *multigermline = new MultiGermline(indexType, !multi_germline_one_unique_index);
827

828
    {
829
      cout << "Load germlines and build Kmer indexes" << endl ;
830 831 832
    
      if (multi_germline)
	{
833
          for (pair <string, string> path_file: multi_germline_paths_and_files)
834 835
            {
              try {
836
                multigermline->build_from_json(path_file.first, path_file.second, GERMLINES_REGULAR,
837
                                               FIRST_IF_UNCHANGED("", seed, seed_changed),
838
                                               FIRST_IF_UNCHANGED(0, trim_sequences, trim_sequences_changed), (kmer_threshold != NO_LIMIT_VALUE));
839
              } catch (std::exception& e) {
840
                cerr << ERROR_STRING << PROGNAME << " cannot properly read " << path_file.first << "/" << path_file.second << ": " << e.what() << endl;
841
                delete multigermline;
842
                return 1;
843 844
              }
            }
845 846 847 848 849
	}
      else
	{
	  // Custom germline
	  Germline *germline;
850
	  germline = new Germline("custom", 'X',
851 852
                                  f_reps_V, f_reps_D, f_reps_J,
                                  seed, trim_sequences, (kmer_threshold != NO_LIMIT_VALUE));
853

854
          germline->new_index(indexType);
855

856 857 858
	  multigermline->insert(germline);
	}
    }
859

860
    cout << endl ;
861

862
    if (multi_germline_one_unique_index) {
863
      multigermline->build_with_one_index(seed, true);
864
    }
865

866
      if (multi_germline_unexpected_recombinations_12 || multi_germline_unexpected_recombinations_1U) {
867 868 869
        if (!multigermline->index) {
          multigermline->build_with_one_index(seed, false);
        }
870
      }
871

872
      if (multi_germline_unexpected_recombinations_12) {
873
        Germline *pseudo = new Germline(PSEUDO_UNEXPECTED, PSEUDO_UNEXPECTED_CODE, "", trim_sequences, (kmer_threshold != NO_LIMIT_VALUE));
874
        pseudo->seg_method = SEG_METHOD_MAX12 ;
875
        pseudo->set_index(multigermline->index);
876
        multigermline->germlines.push_back(pseudo);
877 878 879
      }

      if (multi_germline_unexpected_recombinations_1U) {
880
        Germline *pseudo_u = new Germline(PSEUDO_UNEXPECTED, PSEUDO_UNEXPECTED_CODE, "", trim_sequences, (kmer_threshold != NO_LIMIT_VALUE));
881
        pseudo_u->seg_method = SEG_METHOD_MAX1U ;
882
        // TODO: there should be more up/downstream regions for the PSEUDO_UNEXPECTED germline. And/or smaller seeds ?
883
        pseudo_u->set_index(multigermline->index);
884
        multigermline->germlines.push_back(pseudo_u);
885 886
    }

887
      // Should come after the initialization of regular (and possibly pseudo) germlines
888
    {
889
      for (pair <string, string> path_file: multi_germline_paths_and_files)
890
        multigermline->build_from_json(path_file.first, path_file.second, GERMLINES_INCOMPLETE,
891
                                       FIRST_IF_UNCHANGED("", seed, seed_changed),
892
                                       FIRST_IF_UNCHANGED(0, trim_sequences, trim_sequences_changed), (kmer_threshold != NO_LIMIT_VALUE));
893
      if ((! multigermline->one_index_per_germline) && (command != CMD_GERMLINES)) {
894 895
        multigermline->insert_in_one_index(multigermline->index, true);
      }
896 897
    }

898 899
    if (multi_germline_mark)
      multigermline->mark_cross_germlines_as_ambiguous();
900 901

    multigermline->finish();
902
    cout << "Germlines loaded: " ;
903 904
    cout << *multigermline ;
    cout << endl ;
905 906

    // Number of reads for e-value computation
907
    unsigned long long nb_reads_for_evalue = (expected_value > NO_LIMIT_VALUE) ? nb_sequences_in_file(f_reads, true) : 1 ;
908

909
    
910 911
  //////////////////////////////////
  //$$ Read sequence files
912 913 914 915

    int only_nth_read = 1 ;
    if (max_reads_processed_sample != NO_LIMIT_VALUE)
      {
916
        only_nth_read = nb_sequences_in_file(f_reads) / max_reads_processed_sample;
917 918 919
        if (only_nth_read == 0)
          only_nth_read = 1 ;

920
        max_reads_processed = max_reads_processed_sample ;
921 922 923 924 925

        if (only_nth_read > 1)
          cout << "Processing every " << only_nth_read
               << (only_nth_read == 2 ? "nd" : (only_nth_read == 3 ? "rd" : "th"))
               << " read" << endl ;
926 927
      }

928
  OnlineBioReader *reads;
929 930

  try {
931
    reads = OnlineBioReaderFactory::create(f_reads, 1, read_header_separator, max_reads_processed, only_nth_read);
932
  } catch (const invalid_argument &e) {
933
    cerr << ERROR_STRING << PROGNAME << " cannot open reads file " << f_reads << ": " << e.what() << endl;
934
    return 1;
935 936 937 938 939
  }

  out_dir += "/";


940 941 942 943 944
  //////////////////////////////://////////
  //         DISCOVER GERMLINES          //
  /////////////////////////////////////////
  if (command == CMD_GERMLINES)
    {
945
      map <char, int> stats_kmer, stats_max;
946
      IKmerStore<KmerAffect> *index = multigermline->index ;
947 948

      // Initialize statistics, with two additional categories
949 950
      index->labels.push_back(make_pair(KmerAffect::getAmbiguous(), BIOREADER_AMBIGUOUS));
      index->labels.push_back(make_pair(KmerAffect::getUnknown(), BIOREADER_UNKNOWN));
951
      
952
      for (list< pair <KmerAffect, BioReader> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
953
	{
954 955 956
	  char key = affect_char(it->first.affect) ;
	  stats_kmer[key] = 0 ;
	  stats_max[key] = 0 ;
957 958
	}
      
959
      // init forbidden for .max()
960 961 962
      set<KmerAffect> forbidden;
      forbidden.insert(KmerAffect::getAmbiguous());
      forbidden.insert(KmerAffect::getUnknown());
963
      
964 965 966
      // Loop through all reads

      int nb_reads = 0 ;
967 968 969
      int total_length = 0 ;
      int s = index->getS();

970 971
      int kmer_size = seed_weight(seed);

972 973 974 975 976
      while (reads->hasNext())
	{
	  reads->next();
	  nb_reads++;
	  string seq = reads->getSequence().sequence;
977
	  total_length += seq.length() - s + 1;
978

979
	  KmerAffectAnalyser *kaa = new KmerAffectAnalyser(*index, seq);
980 981 982

	  for (int i = 0; i < kaa->count(); i++) 
	    { 
983 984
	      KmerAffect ksa = kaa->getAffectation(i);
	      stats_kmer[affect_char(ksa.affect)]++ ;
985
	    }
986

987
          delete kaa;
988

989
	  CountKmerAffectAnalyser ckaa(*index, seq);
990
	  ckaa.setAllowedOverlap(kmer_size-1);
991

992
	  stats_max[affect_char(ckaa.max(forbidden).affect)]++ ;
993

994 995
	}

996 997
      delete reads;

998 999
      // Display statistics

1000 1001 1002 1003
      cout << "  <== "
	   << nb_reads << " reads, "
	   << total_length << " kmers"
	   << endl ;
1004
      cout << "\t" << " max" << "\t\t" << "        kmers" << "\n" ;
1005

1006
      for (list< pair <KmerAffect, BioReader> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
1007
	{
1008 1009 1010
          if (it->first.getStrand() == -1)
            continue ;

1011 1012 1013 1014
	  char key = affect_char(it->first.affect) ;
	  
	  cout << setw(12) << stats_max[key] << " " ;
	  cout << setw(6) << fixed << setprecision(2) <<  (float) stats_max[key] / nb_reads * 100 << "%" ;
1015

1016
	  cout << "     " ;
1017

1018 1019
	  cout << setw(12) << stats_kmer[key] << " " ;
	  cout << setw(6) << fixed << setprecision(2) <<  (float) stats_kmer[key] / total_length * 100 << "%" ;
1020

1021
	  cout << "     " << key << " " << it->second.name << endl ;
1022
	}
1023
      
1024
      if (__only_on_exit__clean_memory) { delete multigermline; } return 0;