vidjil.cpp 60.4 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1
/*
2
  This file is part of Vidjil-algo <http://www.vidjil.org>
3
  Copyright (C) 2011-2018 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>
Mikaël Salson's avatar
Mikaël Salson committed
9

10
  "Vidjil-algo" is free software: you can redistribute it and/or modify
Mikaël Salson's avatar
Mikaël 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,
Mikaël Salson's avatar
Mikaël 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/>
Mikaël Salson's avatar
Mikaël Salson committed
22 23
*/

Mathieu Giraud's avatar
Mathieu Giraud committed
24
//$$ #include
Mikaël Salson's avatar
Mikaël 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"
Mikaël Salson's avatar
Mikaël Salson committed
39
#include "core/tools.h"
40
#include "core/json.h"
41
#include "core/germline.h"
Mikaël Salson's avatar
Mikaël Salson committed
42 43
#include "core/kmerstore.h"
#include "core/fasta.h"
44
#include "core/bioreader.hpp"
Mikaël Salson's avatar
Mikaël Salson committed
45
#include "core/segment.h"
Mathieu Giraud's avatar
Mathieu Giraud committed
46
#include "core/windows.h"
Mikaël Salson's avatar
Mikaël 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"
Mikaël Salson's avatar
Mikaël 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"
Mikaël Salson's avatar
Mikaël Salson committed
57

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

Mikaël Salson's avatar
Mikaël Salson committed
61 62 63 64 65 66 67
#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"

68 69 70
// 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"

71
#define PROGNAME "vidjil-algo"
72
#define VIDJIL_JSON_VERSION "2016b"
Mikaël Salson's avatar
Mikaël Salson committed
73

Mathieu Giraud's avatar
Mathieu Giraud committed
74 75
//$$ #define (mainly default options)

76
#define DEFAULT_MULTI_GERMLINE_PATH "germline/"
77
#define DEFAULT_MULTI_GERMLINE_FILE "homo-sapiens.g"
Mikaël Salson's avatar
Mikaël Salson committed
78

79
#define DEFAULT_READ_HEADER_SEPARATOR " "
80
#define DEFAULT_READS  "./demo/Stanford_S22.fasta"
81
#define DEFAULT_MIN_READS_CLONE 5
82
#define DEFAULT_MAX_REPRESENTATIVES 100
83
#define DEFAULT_MAX_CLONES 100
84
#define DEFAULT_RATIO_READS_CLONE 0.0
85
#define NO_LIMIT "all"
Mikaël Salson's avatar
Mikaël Salson committed
86

Mathieu Giraud's avatar
Mathieu Giraud committed
87
#define COMMAND_WINDOWS "windows"
88
#define COMMAND_CLONES "clones"
Mikaël Salson's avatar
Mikaël Salson committed
89
#define COMMAND_SEGMENT "segment"
90
#define COMMAND_GERMLINES "germlines"
Mikaël Salson's avatar
Mikaël Salson committed
91
 
92
enum { CMD_WINDOWS, CMD_CLONES, CMD_SEGMENT, CMD_GERMLINES } ;
Mikaël Salson's avatar
Mikaël Salson committed
93

94 95 96
#define DEFAULT_OUT_DIR "./out/" 

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

109
#define DEFAULT_K      0
110
#define DEFAULT_W      50
Mikaël Salson's avatar
Mikaël Salson committed
111

Mikaël Salson's avatar
Mikaël Salson committed
112
#define DEFAULT_MAX_AUDITIONED 2000
Mathieu Giraud's avatar
Mathieu Giraud committed
113 114
#define DEFAULT_RATIO_REPRESENTATIVE 0.5

115
#define DEFAULT_KMER_THRESHOLD 1
Mathieu Giraud's avatar
Mathieu Giraud committed
116

Mikaël Salson's avatar
Mikaël Salson committed
117 118 119 120 121 122
#define DEFAULT_EPSILON  0
#define DEFAULT_MINPTS   10

#define DEFAULT_CLUSTER_COST  Cluster
#define DEFAULT_SEGMENT_COST   VDJ

123
#define DEFAULT_TRIM 0
Mikaël Salson's avatar
Mikaël Salson committed
124

125
#define MAX_CLONES_FOR_SIMILARITY 20
126

127
// warn
128
#define WARN_MAX_CLONES 5000
129
#define WARN_PERCENT_SEGMENTED 40
130
#define WARN_COVERAGE 0.6
131
#define WARN_NUM_CLONES_SIMILAR 10
132

Mikaël Salson's avatar
Mikaël Salson committed
133 134 135
// display
#define WIDTH_NB_READS 7
#define WIDTH_NB_CLONES 3
136

Mikaël Salson's avatar
Mikaël Salson committed
137 138

using namespace std ;
139
using json = nlohmann::json;
Mikaël Salson's avatar
Mikaël Salson committed
140

Mathieu Giraud's avatar
Mathieu Giraud committed
141
//$$ options: usage
Mikaël Salson's avatar
Mikaël Salson committed
142

Mathieu Giraud's avatar
Mathieu Giraud committed
143
extern char *optarg;
Mikaël Salson's avatar
Mikaël Salson committed
144 145 146

extern int optind, optopt, opterr;

147
string usage_examples(char *progname)
Mikaël Salson's avatar
Mikaël Salson committed
148
{
149 150
  stringstream ss;
  ss
151
       << "Examples (see doc/algo.org)" << endl
152 153 154
       << "  " << 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
       << "                                                                                               #  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
155
       << "  " << progname << " -c clones   -g germline/homo-sapiens.g:IGH    -3     demo/Stanford_S22.fasta   # (restrict to complete recombinations on the IGH locus)" << endl
156 157 158
       << "  " << 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 segment  -g germline/homo-sapiens.g   -2 -3 -X 50 demo/Stanford_S22.fasta   # (full analysis of each read, only for debug/testing, here on 50 sampled reads)" << endl
159
       << "  " << progname << " -c germlines -g germline/homo-sapiens.g              demo/Stanford_S22.fasta   # (statistics on the k-mers)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
160
    ;
161 162

  return ss.str();
Mikaël Salson's avatar
Mikaël Salson committed
163 164
}

165

166
int atoi_NO_LIMIT(const char *optarg)
167
{
168 169
  return strcmp(NO_LIMIT, optarg) ? atoi(optarg) : NO_LIMIT_VALUE ;
}
170
double atof_NO_LIMIT(const char *optarg)
171 172
{
  return strcmp(NO_LIMIT, optarg) ? atof(optarg) : NO_LIMIT_VALUE ;
173 174
}

175 176 177 178 179 180 181 182 183 184
string string_NO_LIMIT(string s)
{
  if (!strcmp(NO_LIMIT, s.c_str()))
    return NO_LIMIT_VALUE_STRING ;

  return s;
}



Mikaël Salson's avatar
Mikaël Salson committed
185 186
int main (int argc, char **argv)
{
187
  cout << "# " << PROGNAME << " -- V(D)J recombinations analysis <http://www.vidjil.org/>" << endl
188
       << "# Copyright (C) 2011-2018 by the Vidjil team" << endl
189
       << "# Bonsai bioinformatics at CRIStAL (UMR CNRS 9189, Université Lille) and Inria Lille" << endl 
190
       << "# VidjilNet consortium" << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
191
       << endl
192
       << "# " << PROGNAME << " is free software, and you are welcome to redistribute it" << endl
Mathieu Giraud's avatar
Mathieu Giraud committed
193 194 195
       << "# 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
196
       << endl
197
       << "# Please cite http://biomedcentral.com/1471-2164/15/409 if you use " << PROGNAME << "." << endl
Mikaël Salson's avatar
Mikaël Salson committed
198 199
       << endl ;

200 201 202
  //////////////////////////////////
  // Display version information or git log

203 204
  string soft_version = PROGNAME ;
  soft_version += " " ;
205
#ifdef RELEASE_TAG
206
  cout << "# version: " PROGNAME << " " << RELEASE_TAG << endl ;
207 208 209 210 211 212 213 214 215 216
  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

217
  CLI::App app{"# vidjil-algo -- V(D)J recombinations analysis", argv[0]};
218

Mathieu Giraud's avatar
Mathieu Giraud committed
219
  //$$ options: defaults
Mathieu Giraud's avatar
Mathieu Giraud committed
220
  float ratio_representative = DEFAULT_RATIO_REPRESENTATIVE;
Mikaël Salson's avatar
Mikaël Salson committed
221
  unsigned int max_auditionned = DEFAULT_MAX_AUDITIONED;
222
  // int average_deletion = 4;     // Average number of deletion in V or J
Mathieu Giraud's avatar
Mathieu Giraud committed
223

224
  //$$ options: definition with CLI11
225
  string group = "";
Mathieu Giraud's avatar
Mathieu Giraud committed
226

227
  // ----------------------------------------------------------------------------------------------------------------------
228
  string f_reads = DEFAULT_READS ;
229 230 231 232 233 234 235
  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")
    -> required() -> set_type_name("");
236

237

238
  // ----------------------------------------------------------------------------------------------------------------------
239
  group = "Command selection";
240

Mathieu Giraud's avatar
Mathieu Giraud committed
241 242 243 244 245 246 247
  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"
                 "\n  \t\t" COMMAND_SEGMENT   "  \t detailed V(D)J designation (not recommended)"
                 "\n  \t\t" COMMAND_GERMLINES "  \t statistics on k-mers in different germlines")
    -> group(group) -> set_type_name("COMMAND");
Mikaël Salson's avatar
Mikaël Salson committed
248

249
  // ----------------------------------------------------------------------------------------------------------------------
250
  group = "Input" ;
251 252

  string read_header_separator = DEFAULT_READ_HEADER_SEPARATOR ;
253 254
  app.add_option("--header-sep", read_header_separator, "separator for headers in the reads file", false)
    -> group(group) -> level() -> set_type_name("CHAR='" DEFAULT_READ_HEADER_SEPARATOR "'");
Mikaël Salson's avatar
Mikaël Salson committed
255

256 257

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

260
  vector <string> multi_germlines ;
Mathieu Giraud's avatar
Mathieu Giraud committed
261
  app.add_option("-g", multi_germlines, R"Z(
262
         -g <.g FILE>(:FILTER)
Mathieu Giraud's avatar
Mathieu Giraud committed
263 264 265
                    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'
266 267
         -g PATH
                    multiple locus/germlines, shortcut for '-g PATH/)Z" DEFAULT_MULTI_GERMLINE_FILE R"Z(',
268
                    processes human TRA, TRB, TRG, TRD, IGH, IGK and IGL locus, possibly with some incomplete/unusal recombinations)Z")
269 270
    -> group(group) -> set_type_name("GERMLINES");

271 272 273 274
  vector <string> v_reps_V ;
  vector <string> v_reps_D ;
  vector <string> v_reps_J ;
   
275 276 277 278
  app.add_option("-V", v_reps_V,
                 "custom V germline multi-fasta file(s)")
    -> group(group) -> set_type_name("FILE");

279

280
  app.add_option("-D", v_reps_D,
281
                 "custom D germline multi-fasta file(s), segment into V(D)J components")
282
    -> group(group) -> set_type_name("FILE");
283

284 285 286
  app.add_option("-J", v_reps_J,
                 "custom V germline multi-fasta file(s)")
    -> group(group) -> set_type_name("FILE");
287

288 289

  // ----------------------------------------------------------------------------------------------------------------------
290
  group = "Locus/recombinations";
291 292 293 294

  bool several_D = false;
  bool multi_germline_unexpected_recombinations_12 = false;

295
  app.add_flag("-d", several_D, "try to detect several D (experimental)") -> group(group);
296
  app.add_flag("-2", multi_germline_unexpected_recombinations_12, "try to detect unexpected recombinations (must be used with -g)") -> group(group);
297

298

299 300
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Recombination detection (\"window\" prediction, first pass)";
301 302 303
  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)";
304 305 306 307

  int options_s_k = 0 ;

  IndexTypes indexType = KMER_INDEX;
308
  app.add_flag_function("-q",
309
                        [&](size_t n) { UNUSED(n); indexType = AC_AUTOMATON; },
310 311
                        "use Aho-Corasick-like automaton (experimental)")
    -> group(group) -> level();
312

313 314
  string seed = DEFAULT_SEED ;
  bool seed_changed = false;
315 316 317 318 319 320 321 322 323 324 325
  app.add_option("-k",
                 [&](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;
                 },
326
                 "k-mer size used for the V/J affectation (default: 10, 12, 13, depends on germline)")
327
    -> group(group) -> level() -> set_type_name("INT");
328

329
  int wmer_size = DEFAULT_W ;
330
  app.add_option("-w", wmer_size,
331
                 "w-mer size used for the length of the extracted window ('" NO_LIMIT "': use all the read, no window clustering)")
332
    -> group(group) -> level() -> transform(string_NO_LIMIT);
333

334 335

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

340 341
  int trim_sequences = DEFAULT_TRIM;
  bool trim_sequences_changed = false;
342 343
  app.add_option("-t",
                 [&](CLI::results_t res) {
344
                   CLI::detail::lexical_cast(res[0], trim_sequences);
345 346 347 348
                   trim_sequences_changed = true;
                   return true;
                 },
                 // trim_sequences,
349
                 "trim V and J genes (resp. 5' and 3' regions) to keep at most <INT> nt  (0: no trim)")
350
    -> group(group) -> level() ->  set_type_name("INT");
Mikaël Salson's avatar
Mikaël Salson committed
351

352 353 354 355 356 357 358
  app.add_option("-s",
                 [&](CLI::results_t res) {
                   seed = res[0] ;
                   options_s_k++ ;
                   seed_changed = true;
                   return true;
                 },
359
                 "seed, possibly spaced, used for the V/J affectation (default: depends on germline), given either explicitely or by an alias"
360 361 362
                 "\n                             " + string_of_map(seedMap, " ")
                 )
    -> group(group) -> level() -> set_type_name("SEED=" DEFAULT_SEED);
363

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

365 366
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Recombination detection, experimental options (do not use)";
367

368 369 370 371
  bool multi_germline_mark = false;
  bool multi_germline_one_unique_index = false;
  bool multi_germline_unexpected_recombinations_1U = false;

372 373 374 375
  app.add_flag("-I", multi_germline_mark,
               "ignore k-mers common to different germline systems (experimental, must be used with -g, do not use)")
    -> group(group) -> level();

376
  app.add_flag("-1", multi_germline_one_unique_index,
377 378 379 380 381 382 383
               "use a unique index for all germline systems (experimental, must be used with -g, do not use)")
    -> group(group) -> level();

  app.add_flag("-4", multi_germline_unexpected_recombinations_1U,
               "try to detect unexpected recombinations with translocations (experimental, must be used with -g, do not use)")
    -> group(group) -> level();

384
  bool keep_unsegmented_as_clone = false;
385 386 387
  app.add_flag("--keep", keep_unsegmented_as_clone,
               "keep unsegmented reads as clones, taking for junction the complete sequence, to be used on very small datasets (for example --keep -AX 20)")
    -> group(group) -> level();
388

389

390
  // ----------------------------------------------------------------------------------------------------------------------
391
  group = "Labeled sequences (windows related to these sequences will be kept even if -r/--ratio thresholds are not reached)";
392 393 394 395

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

396 397
  app.add_option("-W", windows_labels_explicit, "label the given sequence(s)") -> group(group) -> level() -> set_type_name("SEQUENCE");
  app.add_option("-l", windows_labels_file, "label a set of sequences given in <file>") -> group(group) -> level() -> set_type_name("FILE");
398 399

  bool only_labeled_windows = false ;
400
  app.add_flag("-F", only_labeled_windows, "filter -- keep only the windows related to the labeled sequences") -> group(group) -> level();
Mikaël Salson's avatar
Mikaël Salson committed
401 402


403 404
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Limits to report a clone (or a window)";
405
  int max_clones_id = NO_LIMIT_VALUE ;
406 407 408
  int min_reads_clone = DEFAULT_MIN_READS_CLONE ;
  float ratio_reads_clone = DEFAULT_RATIO_READS_CLONE;

409
  app.add_option("--max-clones", max_clones_id, "maximal number of output clones ('" NO_LIMIT "': no maximum, default)", false) -> group(group);
410 411 412 413 414 415
  app.add_option("-r", min_reads_clone, "minimal number of reads supporting a clone", true) -> group(group);
  app.add_option("--ratio", ratio_reads_clone, "minimal percentage of reads supporting a clone", true) -> group(group);


  // ----------------------------------------------------------------------------------------------------------------------
  group = "Limits to further analyze some clones (second pass)";
416

417 418 419
  int max_clones = DEFAULT_MAX_CLONES ;
  int max_representatives = DEFAULT_MAX_REPRESENTATIVES ;

420
  app.add_option("-y", max_representatives,
421 422
                 "maximal number of clones computed with a consensus sequence ('" NO_LIMIT "': no limit)", true)
    -> group(group) -> transform(string_NO_LIMIT);
423 424 425 426 427 428 429 430 431

  app.add_option("-z",
                 [&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
                 },
432 433
                 "maximal number of clones to be analyzed with a full V(D)J designation ('" NO_LIMIT "': no limit, do not use)")
    -> group(group) -> set_type_name("INT=" + string_of_int(max_clones));
434 435

  app.add_flag_function("-A", [&](size_t n) {
436
      UNUSED(n);
437 438 439 440 441
      ratio_reads_clone = 0 ;
      min_reads_clone = 1 ;
      max_representatives = NO_LIMIT_VALUE ;
      max_clones = NO_LIMIT_VALUE ;
    },
442 443
    "reports and segments all clones (-r 0 --ratio 0 -y " NO_LIMIT " -z " NO_LIMIT "), to be used only on very small datasets (for example -AX 20)")
    -> group(group);
444

445 446 447
  int max_reads_processed = NO_LIMIT_VALUE;
  int max_reads_processed_sample = NO_LIMIT_VALUE;

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

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


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

460
  Cost segment_cost = DEFAULT_SEGMENT_COST ;
461 462 463 464 465
  app.add_option("-f",
                 [&segment_cost](CLI::results_t res) {
                   segment_cost = strToCost(res[0].c_str(), VDJ); 
                   return true;
                 },
466 467
                 "use custom Cost for fine segmenter : format \"match, subst, indels, del_end, homo\" (default " + string_of_cost(DEFAULT_SEGMENT_COST) + ")")
    -> group(group) -> level() -> set_type_name("COST");
Mathieu Giraud's avatar
Mathieu Giraud committed
468

469
  double expected_value_D = THRESHOLD_NB_EXPECTED_D;
470 471 472
  app.add_option("-E", expected_value_D,
                 "maximal e-value for determining if a D segment can be trusted", true)
    -> group(group) -> level();
473

474
  int kmer_threshold = DEFAULT_KMER_THRESHOLD;
475
  app.add_option("-Z", kmer_threshold,
476
                 "typical number of V genes, selected by k-mer comparison, to compare to the read ('" NO_LIMIT "': all genes)", true)
477
    -> group(group) -> transform(string_NO_LIMIT) -> level();
478

479
  bool detect_CDR3 = false;
480 481
  app.add_flag("-3,--cdr3", detect_CDR3, "CDR3/JUNCTION detection (requires gapped V/J germlines)")
    -> group(group);
482

483
  int alternative_genes = 0;
484
  app.add_option("--alternative-genes", alternative_genes, "number of alternative V(D)J genes to show beyond the most similar one", true)
485
    -> group(group) -> level();
486 487
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Additional clustering (third pass, experimental)" ;
488 489 490

  int epsilon = DEFAULT_EPSILON ;
  int minPts = DEFAULT_MINPTS ;
491
  app.add_option("-n", epsilon, "minimum required neighbors for automatic clustering. No automatic clusterisation if =0.", true) -> group(group) -> level();
492
  app.add_option("-N", minPts, "minimum required neighbors for automatic clustering", true) -> group(group) -> level();
493 494 495

  bool save_comp = false;
  bool load_comp = false;
496 497
  app.add_flag("-S", save_comp, "generate and save comparative matrix for clustering") -> group(group) -> level();
  app.add_flag("-L", load_comp, "load comparative matrix for clustering") -> group(group) -> level();
498 499

  string forced_edges = "" ;
500
  app.add_option("--forced-edges", forced_edges, "manual clustering -- a file used to force some specific edges") -> group(group) -> level() -> set_type_name("FILE");
501

502
  Cost cluster_cost = DEFAULT_CLUSTER_COST ;
503 504 505 506 507
  app.add_option("-C",
                 [&cluster_cost](CLI::results_t res) {
                   cluster_cost = strToCost(res[0].c_str(), Cluster);
                   return true;
                 },
508 509
                 "use custom Cost for automatic clustering : format \"match, subst, indels, del_end, homo\" (default " + string_of_cost(DEFAULT_CLUSTER_COST) + ")")
    -> group(group) -> level() -> set_type_name("COST");
510 511

  
512
  // ----------------------------------------------------------------------------------------------------------------------
513
  group = "Detailed output per read (generally not recommended, large files, but may be used for filtering, as in -uu -X 1000)";
514 515

  bool output_segmented = false;
516 517 518 519
  app.add_flag("-U", output_segmented,
               "output segmented reads (in " SEGMENTED_FILENAME " file)")
    -> group(group);

520 521 522 523
  bool output_unsegmented = false;
  bool output_unsegmented_detail = false;
  bool output_unsegmented_detail_full = false;

Mathieu Giraud's avatar
Mathieu Giraud committed
524
  app.add_flag_function("-u", [&](size_t n) {
525 526 527
      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
528 529 530
    }, R"Z(
        -u          output unsegmented reads, gathered by unsegmentation cause, except for very short and 'too few V/J' reads (in *)Z" UNSEGMENTED_DETAIL_FILENAME R"Z( files)
        -uu         output unsegmented reads, gathered by unsegmentation cause, all reads (in *)Z" UNSEGMENTED_DETAIL_FILENAME R"Z( files) (use only for debug)
531 532
        -uuu        output unsegmented reads, all reads, including a )Z" UNSEGMENTED_FILENAME R"Z( file (use only for debug))Z")
    -> group(group);
Mathieu Giraud's avatar
Mathieu Giraud committed
533

534
  bool output_affects = false;
535 536 537
  app.add_flag("-K", output_affects,
               "output detailed k-mer affectation on all reads (in " AFFECTS_FILENAME " file) (use only for debug, for example -KX 100)")
    -> group(group);
538

539

540
  // ----------------------------------------------------------------------------------------------------------------------
541
  group = "Output";
542 543 544 545

  string out_dir = DEFAULT_OUT_DIR;
  string f_basename = "";

546
  app.add_option("-o", out_dir, "output directory", true) -> group(group) -> set_type_name("PATH");
547
  app.add_option("-b", f_basename, "output basename (by default basename of the input file)") -> group(group) -> set_type_name("STRING");
548 549

  bool output_sequences_by_cluster = false;
550
  app.add_flag("-a", output_sequences_by_cluster, "output all sequences by cluster (" CLONE_FILENAME "*), to be used only on small datasets") -> group(group);
551 552

  int verbose = 0 ;
Mathieu Giraud's avatar
Mathieu Giraud committed
553
  app.add_flag_function("-v", [&](size_t n) { verbose += n ; }, "verbose mode") -> group(group);
554

555

556 557 558 559 560
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Help";
  app.set_help_flag("-h", "help")
    -> group(group);

561
  app.add_flag_function("-H", [&](size_t n) { UNUSED(n); throw CLI::CallForAdvancedHelp() ; },
562 563
                        "help, including advanced and experimental options"
                        "\n                              "
564 565
                        "The full help is available in the doc/algo.org file.")
    -> group(group);
Mikaël Salson's avatar
Mikaël Salson committed
566 567


568
  // ----------------------------------------------------------------------------------------------------------------------
569 570
  app.set_footer(usage_examples(argv[0]));

571 572
  //$$ options: parsing
  CLI11_PARSE(app, argc, argv);
Mathieu Giraud's avatar
Mathieu Giraud committed
573

574
  //$$ options: post-processing+display
Mikaël Salson's avatar
Mikaël Salson committed
575

576
  int command = CMD_CLONES;
Mathieu Giraud's avatar
Mathieu Giraud committed
577 578 579 580 581 582 583 584 585 586
  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;
  else {
    cerr << "Unknwown command " << optarg << endl;
587
    throw CLI::CallForHelp();
Mathieu Giraud's avatar
Mathieu Giraud committed
588
  }
589

590 591 592
  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());
593

594

595 596 597
  list <pair <string, string>> multi_germline_paths_and_files ;
  bool multi_germline = false;

Mathieu Giraud's avatar
Mathieu Giraud committed
598 599 600 601 602 603 604 605 606 607 608
  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)) ;
609 610
              continue ;
            }
Mathieu Giraud's avatar
Mathieu Giraud committed
611 612 613 614 615 616 617
        }

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


618
  if (!multi_germline && (!f_reps_V.size() || !f_reps_J.size()))
619
    {
620
      cerr << ERROR_STRING << "At least one germline must be given with -g or -V/(-D)/-J." << endl ;
621
      return 1;
622 623
    }

624 625
  if (options_s_k > 1)
    {
626
      cerr << ERROR_STRING << "Use at most one -s or -k option." << endl ;
627
      return 1;
628 629
    }

630 631
  map <string, string> windows_labels ;

632 633 634
  for(string lab : windows_labels_explicit)
    windows_labels[lab] = string("-W");
  
Mikaël Salson's avatar
Mikaël Salson committed
635 636
  string out_seqdir = out_dir + "/seq/" ;

Mikaël Salson's avatar
Mikaël Salson committed
637 638 639
  if (verbose)
    cout << "# verbose " << verbose << endl ;

640
  if (f_reads == DEFAULT_READS)
Mikaël Salson's avatar
Mikaël Salson committed
641 642 643
    {
      cout << "# using default sequence file: " << f_reads << endl ;
    }
Mathieu Giraud's avatar
Mathieu Giraud committed
644

645 646 647 648 649
  //  else
  //  {
  //    cerr << ERROR_STRING << "Wrong number of arguments." << endl ;
  //    return 1;
  //  }
Mathieu Giraud's avatar
Mathieu Giraud committed
650

651
  size_t min_cover_representative = (size_t) (min_reads_clone < (int) max_auditionned ? min_reads_clone : max_auditionned) ;
652

Mathieu Giraud's avatar
Mathieu Giraud committed
653 654 655
  // Check seed buffer  
  if (seed.size() >= MAX_SEED_SIZE)
    {
656
      cerr << ERROR_STRING << "Seed size is too large (MAX_SEED_SIZE)." << endl ;
657
      return 1;
Mathieu Giraud's avatar
Mathieu Giraud committed
658
    }
659

Mathieu Giraud's avatar
Mathieu Giraud committed
660
  if ((wmer_size< 0) && (wmer_size!= NO_LIMIT_VALUE))
661
    {
662
      cerr << ERROR_STRING << "Too small -w. The window size should be positive" << endl;
663
      return 1;
664 665
    }

Mikaël Salson's avatar
Mikaël Salson committed
666 667 668 669
  // 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) {
670
    cerr << ERROR_STRING << "Directory creation: " << out_dir << endl; perror("");
671
    return 2;
Mikaël Salson's avatar
Mikaël Salson committed
672 673
  }

Mikaël Salson's avatar
Mikaël Salson committed
674 675
  const char *outseq_cstr = out_seqdir.c_str();
  if (mkpath(outseq_cstr, 0755) == -1) {
676
    cerr << ERROR_STRING << "Directory creation: " << out_seqdir << endl; perror("");
677
    return 2;
Mikaël Salson's avatar
Mikaël Salson committed
678 679
  }

680 681 682 683 684
  // Compute basename if not given as an option
  if (f_basename == "") {
    f_basename = extract_basename(f_reads);
  }

Mikaël Salson's avatar
Mikaël Salson committed
685 686 687
  out_dir += "/" ;

  /// Load labels ;
688
  load_into_map(windows_labels, windows_labels_file, "-l");
Mikaël Salson's avatar
Mikaël Salson committed
689 690

  switch(command) {
Mathieu Giraud's avatar
Mathieu Giraud committed
691
  case CMD_WINDOWS: cout << "Extracting windows" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
692
    break;
693
  case CMD_CLONES: cout << "Analysing clones" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
694 695 696
    break;
  case CMD_SEGMENT: cout << "Segmenting V(D)J" << endl;
    break;
697 698
  case CMD_GERMLINES: cout << "Discovering germlines" << endl;
    break;
Mikaël Salson's avatar
Mikaël Salson committed
699 700
  }

Mathieu Giraud's avatar
Mathieu Giraud committed
701
  cout << "Command line: ";
Mikaël Salson's avatar
Mikaël Salson committed
702
  for (int i=0; i < argc; i++) {
Mathieu Giraud's avatar
Mathieu Giraud committed
703
    cout << argv[i] << " ";
Mikaël Salson's avatar
Mikaël Salson committed
704
  }
Mathieu Giraud's avatar
Mathieu Giraud committed
705
  cout << endl;
Mikaël Salson's avatar
Mikaël Salson committed
706 707 708 709 710 711 712 713 714 715 716 717

  //////////////////////////////////
  // 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
718
  cout << "# " << time_buffer << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
719 720


721 722
  //////////////////////////////////
  // Warning for non-optimal use
723

724
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES)
725 726
    {
      cout << endl
727
	   << "* WARNING: " << PROGNAME << " was run with '-A' option or with a large '-z' option" << endl ;
728 729 730 731 732
    }
  
  if (command == CMD_SEGMENT)
    {
      cout << endl
733
	   << "* WARNING: " << PROGNAME << " was run with '-c segment' option" << endl ;
734 735
    }
  
736
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES || command == CMD_SEGMENT)
737
    {
738
      cout << "* " << PROGNAME << " efficientl extracts windows overlapping the CDR3" << endl
739
           << "* to cluster reads into clones ('-c clones')." << endl
740 741
           << "* Computing accurate V(D)J designations for many sequences ('-c segment' or large '-z' values)" << endl
           << "* is slow and should be done only on small datasets or for testing purposes." << endl
742
	   << "* More information is provided in the 'doc/vidjil-algo.md' file." << endl 
743 744
	   << endl ;
    }
745

746

747 748 749 750 751 752 753
  //

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


754 755 756 757
  /////////////////////////////////////////
  //            JSON OUTPUT              //
  /////////////////////////////////////////

758
  string f_airr = out_dir + f_basename + AIRR_SUFFIX ;
759 760 761 762 763
  string f_json = out_dir + f_basename + JSON_SUFFIX ;

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

764
  SampleOutput output({
765 766 767 768 769 770 771 772
    {"vidjil_json_version", VIDJIL_JSON_VERSION},
    {"samples", {
        {"number", 1},
        {"original_names", {f_reads}},
        {"run_timestamp", {time_buffer}},
        {"producer", {soft_version}},
        {"commandline", {stream_cmdline.str()}}
      }}
773
  });
774 775


776 777 778
  /////////////////////////////////////////
  //            LOAD GERMLINES           //
  /////////////////////////////////////////
779

780 781 782
  if (command == CMD_GERMLINES)
    {
      multi_germline = true ;
783
      multi_germline_one_unique_index = true ;
784 785
    }

786
  MultiGermline *multigermline = new MultiGermline(indexType, !multi_germline_one_unique_index);
787

788
    {
789
      cout << "Load germlines and build Kmer indexes" << endl ;
790 791 792
    
      if (multi_germline)
	{
793
          for (pair <string, string> path_file: multi_germline_paths_and_files)
794 795
            {
              try {
796
                multigermline->build_from_json(path_file.first, path_file.second, GERMLINES_REGULAR,
797
                                               FIRST_IF_UNCHANGED("", seed, seed_changed),
798
                                               FIRST_IF_UNCHANGED(0, trim_sequences, trim_sequences_changed), (kmer_threshold != NO_LIMIT_VALUE));
799
              } catch (std::exception& e) {
800
                cerr << ERROR_STRING << PROGNAME << " cannot properly read " << path_file.first << "/" << path_file.second << ": " << e.what() << endl;
801
                delete multigermline;
802
                return 1;
803 804
              }
            }
805 806 807 808 809
	}
      else
	{
	  // Custom germline
	  Germline *germline;
810
	  germline = new Germline("custom", 'X',
811 812
                                  f_reps_V, f_reps_D, f_reps_J,
                                  seed, trim_sequences, (kmer_threshold != NO_LIMIT_VALUE));
813

814
          germline->new_index(indexType);
815

816 817 818
	  multigermline->insert(germline);
	}
    }
819

820
    cout << endl ;
821

822
    if (multi_germline_one_unique_index) {
823
      multigermline->build_with_one_index(seed, true);
824
    }
825

826
      if (multi_germline_unexpected_recombinations_12 || multi_germline_unexpected_recombinations_1U) {
827 828 829
        if (!multigermline->index) {
          multigermline->build_with_one_index(seed, false);
        }
830
      }
831

832
      if (multi_germline_unexpected_recombinations_12) {
833
        Germline *pseudo = new Germline(PSEUDO_UNEXPECTED, PSEUDO_UNEXPECTED_CODE, "", trim_sequences, (kmer_threshold != NO_LIMIT_VALUE));
834
        pseudo->seg_method = SEG_METHOD_MAX12 ;
835
        pseudo->set_index(multigermline->index);
836
        multigermline->germlines.push_back(pseudo);
837 838 839
      }

      if (multi_germline_unexpected_recombinations_1U) {
840
        Germline *pseudo_u = new Germline(PSEUDO_UNEXPECTED, PSEUDO_UNEXPECTED_CODE, "", trim_sequences, (kmer_threshold != NO_LIMIT_VALUE));
841
        pseudo_u->seg_method = SEG_METHOD_MAX1U ;
842
        // TODO: there should be more up/downstream regions for the PSEUDO_UNEXPECTED germline. And/or smaller seeds ?
843
        pseudo_u->set_index(multigermline->index);
844
        multigermline->germlines.push_back(pseudo_u);
845 846
    }

847
      // Should come after the initialization of regular (and possibly pseudo) germlines
848
    {
849
      for (pair <string, string> path_file: multi_germline_paths_and_files)
850
        multigermline->build_from_json(path_file.first, path_file.second, GERMLINES_INCOMPLETE,
851
                                       FIRST_IF_UNCHANGED("", seed, seed_changed),
852
                                       FIRST_IF_UNCHANGED(0, trim_sequences, trim_sequences_changed), (kmer_threshold != NO_LIMIT_VALUE));
853
      if ((! multigermline->one_index_per_germline) && (command != CMD_GERMLINES)) {
854 855
        multigermline->insert_in_one_index(multigermline->index, true);
      }
856 857
    }

858 859
    if (multi_germline_mark)
      multigermline->mark_cross_germlines_as_ambiguous();
860 861

    multigermline->finish();
862
    cout << "Germlines loaded: " ;
863 864
    cout << *multigermline ;
    cout << endl ;
865 866

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

869
    
870 871
  //////////////////////////////////
  //$$ Read sequence files
872 873 874 875

    int only_nth_read = 1 ;
    if (max_reads_processed_sample != NO_LIMIT_VALUE)
      {
876
        only_nth_read = nb_sequences_in_file(f_reads) / max_reads_processed_sample;
877 878 879
        if (only_nth_read == 0)
          only_nth_read = 1 ;

880
        max_reads_processed = max_reads_processed_sample ;
881 882 883 884 885

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

888
  OnlineBioReader *reads;
889 890

  try {
891
    reads = OnlineBioReaderFactory::create(f_reads, 1, read_header_separator, max_reads_processed, only_nth_read);
892
  } catch (const invalid_argument &e) {
893
    cerr << ERROR_STRING << PROGNAME << " cannot open reads file " << f_reads << ": " << e.what() << endl;
894
    return 1;
895 896 897 898 899
  }

  out_dir += "/";


900 901 902 903 904
  //////////////////////////////://////////
  //         DISCOVER GERMLINES          //
  /////////////////////////////////////////
  if (command == CMD_GERMLINES)
    {
905
      map <char, int> stats_kmer, stats_max;
906
      IKmerStore<KmerAffect> *index = multigermline->index ;
907 908

      // Initialize statistics, with two additional categories
909 910
      index->labels.push_back(make_pair(KmerAffect::getAmbiguous(), BIOREADER_AMBIGUOUS));
      index->labels.push_back(make_pair(KmerAffect::getUnknown(), BIOREADER_UNKNOWN));
911
      
912
      for (list< pair <KmerAffect, BioReader> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
913
	{
914 915 916
	  char key = affect_char(it->first.affect) ;
	  stats_kmer[key] = 0 ;
	  stats_max[key] = 0 ;
917 918
	}
      
919
      // init forbidden for .max()
920 921 922
      set<KmerAffect> forbidden;
      forbidden.insert(KmerAffect::getAmbiguous());
      forbidden.insert(KmerAffect::getUnknown());
923
      
924 925 926
      // Loop through all reads

      int nb_reads = 0 ;
927 928 929
      int total_length = 0 ;
      int s = index->getS();

930 931
      int kmer_size = seed_weight(seed);

932 933 934 935 936
      while (reads->hasNext())
	{
	  reads->next();
	  nb_reads++;
	  string seq = reads->getSequence().sequence;
937
	  total_length += seq.length() - s + 1;
938

939
	  KmerAffectAnalyser *kaa = new KmerAffectAnalyser(*index, seq);
940 941 942

	  for (int i = 0; i < kaa->count(); i++) 
	    { 
943 944
	      KmerAffect ksa = kaa->getAffectation(i);
	      stats_kmer[affect_char(ksa.affect)]++ ;
945
	    }
946

947
          delete kaa;
948

949
	  CountKmerAffectAnalyser ckaa(*index, seq);
950
	  ckaa.setAllowedOverlap(kmer_size-1);
951

952
	  stats_max[affect_char(ckaa.max(forbidden).affect)]++ ;
953

954 955
	}

956 957
      delete reads;

958 959
      // Display statistics

960 961 962 963
      cout << "  <== "
	   << nb_reads << " reads, "
	   << total_length << " kmers"
	   << endl ;
964
      cout << "\t" << " max" << "\t\t" << "        kmers" << "\n" ;
965

966
      for (list< pair <KmerAffect, BioReader> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
967
	{
968 969 970
          if (it->first.getStrand() == -1)
            continue ;

971 972 973 974
	  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 << "%" ;
975

976
	  cout << "     " ;
977

978 979
	  cout << setw(12) << stats_kmer[key] << " " ;
	  cout << setw(6) << fixed << setprecision(2) <<  (float) stats_kmer[key] / total_length * 100 << "%" ;
980

981
	  cout << "     " << key << " " << it->second.name << endl ;
982
	}
983
      
984
      delete multigermline;
985 986

      return 0;
987 988 989
    }


Mikaël Salson's avatar
Mikaël Salson committed
990 991 992
  ////////////////////////////////////////
  //           CLONE ANALYSIS           //
  ////////////////////////////////////////
993
  if (command == CMD_CLONES || command == CMD_WINDOWS) {
Mikaël Salson's avatar
Mikaël Salson committed
994 995

    //////////////////////////////////
Mathieu Giraud's avatar
Mathieu Giraud committed
996
    //$$ Kmer Segmentation
Mikaël Salson's avatar
Mikaël Salson committed
997

Mathieu Giraud's avatar
Mathieu Giraud committed
998
    cout << endl;
999 1000 1001 1002 1003 1004
    cout << "Loop through reads, ";

    if (wmer_size != NO_LIMIT_VALUE)
      cout << "looking for windows up to " << wmer_size << "bp" << endl;
    else
      cout << "considering all analyzed reads as windows" << endl;
Mikaël Salson's avatar
Mikaël Salson committed
1005

1006
    ofstream *out_segmented = NULL;
Mathieu Giraud's avatar
Mathieu Giraud committed
1007
    ofstream *out_unsegmented = NULL;
1008
    ofstream *out_unsegmented_detail[STATS_SIZE];
1009
    ofstream *out_affects = NULL;
Mikaël Salson's avatar
Mikaël Salson committed
1010
 
1011
    WindowExtractor we(multigermline);
1012 1013
    if (! output_sequences_by_cluster)
      we.setMaximalNbReadsPerWindow(max_auditionned);
1014 1015
 
    if (output_segmented) {
1016
      string f_segmented = out_dir + f_basename + SEGMENTED_FILENAME ;
1017 1018 1019 1020 1021
      cout << "  ==> " << f_segmented << endl ;
      out_segmented = new ofstream(f_segmented.c_str());
      we.setSegmentedOutput(out_segmented);
    }

Mathieu Giraud's avatar
Mathieu Giraud committed
1022
    if (output_unsegmented) {
1023
      string f_unsegmented = out_dir + f_basename + UNSEGMENTED_FILENAME ;
Mathieu Giraud's avatar
Mathieu Giraud committed
1024 1025 1026 1027
      cout << "  ==> " << f_unsegmented << endl ;
      out_unsegmented = new ofstream(f_unsegmented.c_str());
      we.setUnsegmentedOutput(out_unsegmented);
    }
1028

1029
    if (output_unsegmented_detail) {
1030
      for (int i=STATS_FIRST_UNSEG; i<STATS_SIZE; i++)
1031 1032 1033 1034 1035 1036 1037
        {
          // Sanitize segmented_mesg[i]
          string s = segmented_mesg[i] ;
          replace(s.begin(), s.end(), '?', '_');
          replace(s.begin(), s.end(), ' ', '_');
          replace(s.begin(), s.end(), '/', '_');
          replace(s.begin(), s.end(), '<', '_');
1038
          replace(s.begin(), s.end(), '\'', '_');
1039 1040 1041 1042 1043 1044

          string f_unsegmented_detail = out_dir + f_basename + "." + s + UNSEGMENTED_DETAIL_FILENAME ;
          cout << "  ==> " << f_unsegmented_detail << endl ;
          out_unsegmented_detail[i] = new ofstream(f_unsegmented_detail.c_str());
        }

1045
      we.setUnsegmentedDetailOutput(out_unsegmented_detail, output_unsegmented_detail_full);
1046 1047 1048
    }


1049 1050 1051 1052 1053 1054 1055
    if (output_affects) {
      string f_affects = out_dir + f_basename + AFFECTS_FILENAME ;
      cout << "  ==> " << f_affects << endl ;
      out_affects = new ofstream(f_affects.c_str());
      we.setAffectsOutput(out_affects);
    }

1056
    WindowsStorage *windowsStorage = we.extract(reads, wmer_size,
1057
                                                windows_labels, only_labeled_windows,
1058
                                                keep_unsegmented_as_clone,
1059
                                                expected_value, nb_reads_for_evalue);
1060
    windowsStorage->setIdToAll();
Mathieu Giraud's avatar
Mathieu Giraud committed
1061
    size_t nb_total_reads = we.getNbReads();
Mikaël Salson's avatar
Mikaël Salson committed
1062 1063


Mathieu Giraud's avatar
Mathieu Giraud committed
1064
    //$$ Display statistics on segmentation causes
Mikaël Salson's avatar
Mikaël Salson committed
1065