vidjil.cpp 62.9 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-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>
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"
WebTogz's avatar
WebTogz committed
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

Mathieu Giraud's avatar
Mathieu Giraud committed
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"
73
#define DOCUMENTATION "doc/vidjil-algo.md"
Mikaël Salson's avatar
Mikaël Salson committed
74

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

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

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

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

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

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

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

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

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

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

#define DEFAULT_CLUSTER_COST  Cluster
#define DEFAULT_SEGMENT_COST   VDJ

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

126
#define MAX_CLONES_FOR_SIMILARITY 20
127

128
// warn
Mathieu Giraud's avatar
Mathieu Giraud committed
129
#define WARN_MAX_CLONES 5000
130
#define WARN_PERCENT_SEGMENTED 40
131
#define WARN_COVERAGE 0.6
132
#define WARN_NUM_CLONES_SIMILAR 10
133

Mikaël Salson's avatar
Mikaël Salson committed
134 135 136
// display
#define WIDTH_NB_READS 7
#define WIDTH_NB_CLONES 3
137
#define PAD_HELP "\n                              "
Mikaël Salson's avatar
Mikaël Salson committed
138 139

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

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

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

extern int optind, optopt, opterr;

148
string usage_examples(char *progname)
Mikaël Salson's avatar
Mikaël Salson committed
149
{
150 151
  stringstream ss;
  ss
152
       << "Examples (see " DOCUMENTATION ")" << endl
153
       << "  " << 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
154 155
       << "                                                                                               #  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
156 157 158 159 160
       << "  " << 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
Mikaël Salson's avatar
Mikaël Salson committed
161
    ;
162 163

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

166 167 168 169
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)
170
        header += "run with " + app->get_help_ptr()->get_name() + " or ";
171 172 173
    header += "see " DOCUMENTATION ".\n";
    return header;
}
Mathieu Giraud's avatar
Mathieu Giraud committed
174

175
int atoi_NO_LIMIT(const char *optarg)
Mathieu Giraud's avatar
Mathieu Giraud committed
176
{
177 178
  return strcmp(NO_LIMIT, optarg) ? atoi(optarg) : NO_LIMIT_VALUE ;
}
179
double atof_NO_LIMIT(const char *optarg)
180 181
{
  return strcmp(NO_LIMIT, optarg) ? atof(optarg) : NO_LIMIT_VALUE ;
Mathieu Giraud's avatar
Mathieu Giraud committed
182 183
}

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

209 210 211
  //////////////////////////////////
  // Display version information or git log

212 213
  string soft_version = PROGNAME ;
  soft_version += " " ;
214
#ifdef RELEASE_TAG
215
  cout << "# version: " PROGNAME << " " << RELEASE_TAG << endl ;
216 217 218 219 220 221 222 223 224 225
  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

226
  CLI::App app{"# vidjil-algo -- V(D)J recombinations analysis", argv[0]};
227
  app.failure_message(failure_message_doc);
Mathieu Giraud's avatar
Mathieu Giraud committed
228

Mathieu Giraud's avatar
Mathieu Giraud committed
229
  //$$ options: defaults
Mathieu Giraud's avatar
Mathieu Giraud committed
230
  float ratio_representative = DEFAULT_RATIO_REPRESENTATIVE;
Mikaël Salson's avatar
Mikaël Salson committed
231
  unsigned int max_auditionned = DEFAULT_MAX_AUDITIONED;
232
  // int average_deletion = 4;     // Average number of deletion in V or J
Mathieu Giraud's avatar
Mathieu Giraud committed
233

234
  //$$ options: definition with CLI11
Mathieu Giraud's avatar
Mathieu Giraud committed
235
  string group = "";
Mathieu Giraud's avatar
Mathieu Giraud committed
236

237
  // ----------------------------------------------------------------------------------------------------------------------
238
  string f_reads = DEFAULT_READS ;
239 240 241 242 243 244
  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")
245
    -> required() -> type_name("");
246

247

248
  // ----------------------------------------------------------------------------------------------------------------------
Mathieu Giraud's avatar
Mathieu Giraud committed
249
  group = "Command selection";
250

Mathieu Giraud's avatar
Mathieu Giraud committed
251 252 253 254
  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"
255
                 "\n  \t\t" COMMAND_SEGMENT   "  \t detailed V(D)J designation, without prior clustering (not as efficient)"
Mathieu Giraud's avatar
Mathieu Giraud committed
256
                 "\n  \t\t" COMMAND_GERMLINES "  \t statistics on k-mers in different germlines")
257
    -> group(group) -> type_name("COMMAND");
Mikaël Salson's avatar
Mikaël Salson committed
258

259
  // ----------------------------------------------------------------------------------------------------------------------
Mathieu Giraud's avatar
Mathieu Giraud committed
260
  group = "Input" ;
261 262

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

266 267 268 269 270 271 272 273 274 275 276
  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);

277 278

  // ----------------------------------------------------------------------------------------------------------------------
Mathieu Giraud's avatar
Mathieu Giraud committed
279
  group = "Germline presets (at least one -g or -V/(-D)/-J option must be given)";
280

281
  vector <string> multi_germlines ;
282
  app.add_option("--germline,-g", multi_germlines, R"Z(
283
         -g <.g FILE>(:FILTER)
Mathieu Giraud's avatar
Mathieu Giraud committed
284 285 286
                    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'
287 288
         -g PATH
                    multiple locus/germlines, shortcut for '-g PATH/)Z" DEFAULT_MULTI_GERMLINE_FILE R"Z(',
289
                    processes human TRA, TRB, TRG, TRD, IGH, IGK and IGL locus, possibly with incomplete/unusal recombinations)Z")
290
    -> group(group) -> type_name("GERMLINES");
291

292 293 294 295
  vector <string> v_reps_V ;
  vector <string> v_reps_D ;
  vector <string> v_reps_J ;
   
296 297
  app.add_option("-V", v_reps_V,
                 "custom V germline multi-fasta file(s)")
298
    -> group(group) -> type_name("FILE");
299

300

301
  app.add_option("-D", v_reps_D,
302
                 "custom D germline multi-fasta file(s), analyze into V(D)J components")
303
    -> group(group) -> type_name("FILE");
304

305 306
  app.add_option("-J", v_reps_J,
                 "custom V germline multi-fasta file(s)")
307
    -> group(group) -> type_name("FILE");
308

309

310
  bool multi_germline_unexpected_recombinations_12 = false;
311
  app.add_flag("-2", multi_germline_unexpected_recombinations_12, "try to detect unexpected recombinations") -> group(group);
312

313

314 315
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Recombination detection (\"window\" prediction, first pass)";
316 317 318
  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)";
319 320 321

  int options_s_k = 0 ;

322
  IndexTypes indexType = AC_AUTOMATON;
323
  app.add_flag_function("--plain-index",
324
                        [&](size_t n) { UNUSED(n); indexType = KMER_INDEX; },
325
                        "use a plain index (pre-2019 method) instead of the recommended Aho-Corasick-like automaton")
326
    -> group(group) -> level();
327

328 329
  string seed = DEFAULT_SEED ;
  bool seed_changed = false;
330
  app.add_option("--kmer,-k",
331 332 333 334 335 336 337 338 339 340
                 [&](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;
                 },
341
                 "k-mer size used for the V/J affectation (default: 10, 12, 13, depends on germline)")
342
    -> group(group) -> level() -> type_name("INT");
343

344
  int wmer_size = DEFAULT_W ;
345
  app.add_option("--window,-w", wmer_size,
346
                 "w-mer size used for the length of the extracted window ('" NO_LIMIT "': use all the read, no window clustering)")
347
    -> group(group) -> level() -> transform(string_NO_LIMIT);
348

349 350

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

355 356
  int trim_sequences = DEFAULT_TRIM;
  bool trim_sequences_changed = false;
357
  app.add_option("--trim",
358
                 [&](CLI::results_t res) {
Mikaël Salson's avatar
Mikaël Salson committed
359
                   CLI::detail::lexical_cast(res[0], trim_sequences);
360 361 362 363
                   trim_sequences_changed = true;
                   return true;
                 },
                 // trim_sequences,
364
                 "trim V and J genes (resp. 5' and 3' regions) to keep at most <INT> nt  (0: no trim)")
365
    -> group(group) -> level() -> type_name("INT");
Mikaël Salson's avatar
Mikaël Salson committed
366

367
  app.add_option("--seed,-s",
368 369 370 371 372 373
                 [&](CLI::results_t res) {
                   seed = res[0] ;
                   options_s_k++ ;
                   seed_changed = true;
                   return true;
                 },
Mathieu Giraud's avatar
Mathieu Giraud committed
374
                 "seed, possibly spaced, used for the V/J affectation (default: depends on germline), given either explicitely or by an alias"
375
                 PAD_HELP + string_of_map(seedMap, " ")
376
                 )
377
    -> group(group) -> level() -> type_name("SEED=" DEFAULT_SEED);
378

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

380 381
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Recombination detection, experimental options (do not use)";
382

383 384 385 386
  bool multi_germline_mark = false;
  bool multi_germline_one_unique_index = false;
  bool multi_germline_unexpected_recombinations_1U = false;

387
  app.add_flag("-I", multi_germline_mark,
388
               "ignore k-mers common to different germline systems (experimental, do not use)")
389 390
    -> group(group) -> level();

391
  app.add_flag("-1", multi_germline_one_unique_index,
392
               "use a unique index for all germline systems (experimental, do not use)")
393 394 395
    -> group(group) -> level();

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

399
  bool keep_unsegmented_as_clone = false;
400 401
  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)")
402
    -> group(group) -> level();
403

404

405
  // ----------------------------------------------------------------------------------------------------------------------
406
  group = "Labeled sequences (windows related to these sequences will be kept even if -r/--ratio thresholds are not reached)";
407 408 409 410

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

411 412
  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");
413 414

  bool only_labeled_windows = false ;
415
  app.add_flag("--label-filter", 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
416 417


418
  // ----------------------------------------------------------------------------------------------------------------------
419
  group = "Limits to report and to analyze clones (second pass)";
420
  int max_clones_id = NO_LIMIT_VALUE ;
421 422 423
  int min_reads_clone = DEFAULT_MIN_READS_CLONE ;
  float ratio_reads_clone = DEFAULT_RATIO_READS_CLONE;

424 425
  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);
426
  app.add_option("--max-clones", max_clones_id, "maximal number of output clones ('" NO_LIMIT "': no maximum, default)", false) -> group(group);
427

428 429 430
  int max_clones = DEFAULT_MAX_CLONES ;
  int max_representatives = DEFAULT_MAX_REPRESENTATIVES ;

431
  app.add_option("--max-consensus,-y", max_representatives,
432 433
                 "maximal number of clones computed with a consensus sequence ('" NO_LIMIT "': no limit)", true)
    -> group(group) -> transform(string_NO_LIMIT);
434

435
  app.add_option("--max-designations,-z",
436 437 438 439 440 441 442
                 [&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
                 },
443
                 "maximal number of clones to be analyzed with a full V(D)J designation ('" NO_LIMIT "': no limit, do not use)")
444
    -> group(group) -> type_name("INT=" + string_of_int(max_clones));
445

446
  app.add_flag_function("--all", [&](size_t n) {
447
      UNUSED(n);
448 449 450 451 452
      ratio_reads_clone = 0 ;
      min_reads_clone = 1 ;
      max_representatives = NO_LIMIT_VALUE ;
      max_clones = NO_LIMIT_VALUE ;
    },
453
    "reports and analyzes all clones"
454 455
    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)")
456
    -> group(group);
457

458
  VirtualReadScore *readScorer = &DEFAULT_READ_SCORE;
459 460 461 462
  RandomScore randomScore;
  app.add_flag_function("--consensus-on-random-sample",
                        [&readScorer, &randomScore](size_t n) {
                          UNUSED(n);
463
                          readScorer = &randomScore;
464 465
                        }, "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();
466 467 468

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

470
  Cost segment_cost = DEFAULT_SEGMENT_COST ;
471
  app.add_option("--analysis-cost",
472 473 474 475
                 [&segment_cost](CLI::results_t res) {
                   segment_cost = strToCost(res[0].c_str(), VDJ); 
                   return true;
                 },
476
                 "use custom Cost for clone analysis: format \"match, subst, indels, del_end, homo\" (default " + string_of_cost(DEFAULT_SEGMENT_COST) + ")")
477
    -> group(group) -> level() -> type_name("COST");
Mathieu Giraud's avatar
Mathieu Giraud committed
478

479
  double expected_value_D = THRESHOLD_NB_EXPECTED_D;
480
  app.add_option("--analysis-e-value-D,-E", expected_value_D,
481 482
                 "maximal e-value for determining if a D segment can be trusted", true)
    -> group(group) -> level();
483

484
  int kmer_threshold = DEFAULT_KMER_THRESHOLD;
485 486
  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)
487
    -> group(group) -> transform(string_NO_LIMIT) -> level();
488

489 490 491
  bool several_D = false;
  app.add_flag("-d,--several-D", several_D, "try to detect several D (experimental)") -> group(group);

492
  bool detect_CDR3 = false;
493 494
  app.add_flag("-3,--cdr3", detect_CDR3, "CDR3/JUNCTION detection (requires gapped V/J germlines)")
    -> group(group);
495

496
  int alternative_genes = 0;
497
  app.add_option("--alternative-genes", alternative_genes, "number of alternative V(D)J genes to show beyond the most similar one", true)
498
    -> group(group) -> level();
499 500
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Additional clustering (third pass, experimental)" ;
501 502 503

  int epsilon = DEFAULT_EPSILON ;
  int minPts = DEFAULT_MINPTS ;
504 505
  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();
506 507 508

  bool save_comp = false;
  bool load_comp = false;
509 510
  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();
511 512

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

515
  Cost cluster_cost = DEFAULT_CLUSTER_COST ;
516
  app.add_option("--cluster-cost",
517 518 519 520
                 [&cluster_cost](CLI::results_t res) {
                   cluster_cost = strToCost(res[0].c_str(), Cluster);
                   return true;
                 },
521
                 "use custom Cost for automatic clustering : format \"match, subst, indels, del_end, homo\" (default " + string_of_cost(DEFAULT_CLUSTER_COST) + ")")
522
    -> group(group) -> level() -> type_name("COST");
Mathieu Giraud's avatar
Mathieu Giraud committed
523 524

  
525
  // ----------------------------------------------------------------------------------------------------------------------
Mathieu Giraud's avatar
Mathieu Giraud committed
526
  group = "Detailed output per read (generally not recommended, large files, but may be used for filtering, as in -uu -X 1000)";
527 528

  bool output_segmented = false;
529 530
  app.add_flag("--out-analyzed,-U", output_segmented,
               "output analyzed reads (in " SEGMENTED_FILENAME " file)")
531 532
    -> group(group);

533 534 535 536
  bool output_unsegmented = false;
  bool output_unsegmented_detail = false;
  bool output_unsegmented_detail_full = false;

537
  app.add_flag_function("--out-unanalyzed,-u", [&](size_t n) {
538 539 540
      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
541
    }, R"Z(
542 543 544
        -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")
545
    -> group(group);
Mathieu Giraud's avatar
Mathieu Giraud committed
546

547 548 549
  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);

550
  bool output_affects = false;
551 552 553
  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();
554

555

556
  // ----------------------------------------------------------------------------------------------------------------------
Mathieu Giraud's avatar
Mathieu Giraud committed
557
  group = "Output";
558 559 560 561

  string out_dir = DEFAULT_OUT_DIR;
  string f_basename = "";

562 563
  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");
564 565 566


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

Mathieu Giraud's avatar
Mathieu Giraud committed
569 570
  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();
571

572 573 574 575 576 577 578 579 580 581 582 583
  // ----------------------------------------------------------------------------------------------------------------------
  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)")
584
    -> group(group) -> level() -> type_name("SEQUENCE");
585

586 587
  // ----------------------------------------------------------------------------------------------------------------------
  group = "Help";
588
  app.set_help_flag("--help,-h", "help")
589 590
    -> group(group);

591
  app.add_flag_function("--help-advanced,-H", [&](size_t n) { UNUSED(n); throw CLI::CallForAdvancedHelp() ; },
592 593
                        "help, including advanced and experimental options"
                        "\n                              "
594
                        "The full help is available in " DOCUMENTATION ".")
595
    -> group(group);
Mikaël Salson's avatar
Mikaël Salson committed
596 597


598 599 600 601 602 603 604 605 606 607
  // 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'");

608
  // ----------------------------------------------------------------------------------------------------------------------
609
  app.footer(usage_examples(argv[0]));
610

Mathieu Giraud's avatar
Mathieu Giraud committed
611 612
  //$$ options: parsing
  CLI11_PARSE(app, argc, argv);
Mathieu Giraud's avatar
Mathieu Giraud committed
613

Mathieu Giraud's avatar
Mathieu Giraud committed
614
  //$$ options: post-processing+display
Mikaël Salson's avatar
Mikaël Salson committed
615

616
  int command = CMD_CLONES;
Mathieu Giraud's avatar
Mathieu Giraud committed
617 618 619 620 621 622 623 624
  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;
625 626
  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
627
  else {
628
    return app.exit(CLI::ConstructionError("Unknown command " + cmd, 1));
Mathieu Giraud's avatar
Mathieu Giraud committed
629
  }
630
  if (deprecated) return 1 ;
631

Mathieu Giraud's avatar
Mathieu Giraud committed
632 633 634
  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());
635

636

637 638 639
  list <pair <string, string>> multi_germline_paths_and_files ;
  bool multi_germline = false;

Mathieu Giraud's avatar
Mathieu Giraud committed
640 641 642 643 644 645 646 647 648 649 650
  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)) ;
651 652
              continue ;
            }
Mathieu Giraud's avatar
Mathieu Giraud committed
653 654 655 656 657 658 659
        }

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


660
  if (!multi_germline && (!f_reps_V.size() || !f_reps_J.size()))
661
    {
662
      return app.exit(CLI::ConstructionError("At least one germline must be given with -g or -V/(-D)/-J.", 1));
663 664
    }

665 666
  if (options_s_k > 1)
    {
667
      return app.exit(CLI::ConstructionError("Use at most one -s or -k option.", 1));
668 669
    }

670 671
  map <string, string> windows_labels ;

672
  for(string lab : windows_labels_explicit)
Mathieu Giraud's avatar
Mathieu Giraud committed
673
    windows_labels[lab] = string("--label");
674
  
Mikaël Salson's avatar
Mikaël Salson committed
675 676
  string out_seqdir = out_dir + "/seq/" ;

Mikaël Salson's avatar
Mikaël Salson committed
677 678 679
  if (verbose)
    cout << "# verbose " << verbose << endl ;

680
  if (f_reads == DEFAULT_READS)
Mikaël Salson's avatar
Mikaël Salson committed
681 682 683
    {
      cout << "# using default sequence file: " << f_reads << endl ;
    }
Mathieu Giraud's avatar
Mathieu Giraud committed
684

685
  size_t min_cover_representative = (size_t) (min_reads_clone < (int) max_auditionned ? min_reads_clone : max_auditionned) ;
686

Mathieu Giraud's avatar
Mathieu Giraud committed
687 688 689
  // Check seed buffer  
  if (seed.size() >= MAX_SEED_SIZE)
    {
690
      return app.exit(CLI::ConstructionError("Seed size is too large (MAX_SEED_SIZE).", 1));
Mathieu Giraud's avatar
Mathieu Giraud committed
691
    }
692

Mathieu Giraud's avatar
Mathieu Giraud committed
693
  if ((wmer_size< 0) && (wmer_size!= NO_LIMIT_VALUE))
694
    {
695
      return app.exit(CLI::ConstructionError("Too small -w. The window size should be positive.", 1));
696 697
    }

Mikaël Salson's avatar
Mikaël Salson committed
698 699 700 701
  // 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) {
702
    cerr << ERROR_STRING << "Directory creation: " << out_dir << endl; perror("");
703
    return 2;
Mikaël Salson's avatar
Mikaël Salson committed
704 705
  }

Mikaël Salson's avatar
Mikaël Salson committed
706 707
  const char *outseq_cstr = out_seqdir.c_str();
  if (mkpath(outseq_cstr, 0755) == -1) {
708
    cerr << ERROR_STRING << "Directory creation: " << out_seqdir << endl; perror("");
709
    return 2;
Mikaël Salson's avatar
Mikaël Salson committed
710 711
  }

712 713 714 715 716
  // 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
717 718 719
  out_dir += "/" ;

  /// Load labels ;
720
  load_into_map(windows_labels, windows_labels_file, "-l");
Mikaël Salson's avatar
Mikaël Salson committed
721 722

  switch(command) {
Mathieu Giraud's avatar
Mathieu Giraud committed
723
  case CMD_WINDOWS: cout << "Extracting windows" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
724
    break;
725
  case CMD_CLONES: cout << "Analysing clones" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
726 727 728
    break;
  case CMD_SEGMENT: cout << "Segmenting V(D)J" << endl;
    break;
729 730
  case CMD_GERMLINES: cout << "Discovering germlines" << endl;
    break;
Mikaël Salson's avatar
Mikaël Salson committed
731 732
  }

Mathieu Giraud's avatar
Mathieu Giraud committed
733
  cout << "Command line: ";
Mikaël Salson's avatar
Mikaël Salson committed
734
  for (int i=0; i < argc; i++) {
Mathieu Giraud's avatar
Mathieu Giraud committed
735
    cout << argv[i] << " ";
Mikaël Salson's avatar
Mikaël Salson committed
736
  }
Mathieu Giraud's avatar
Mathieu Giraud committed
737
  cout << endl;
Mikaël Salson's avatar
Mikaël Salson committed
738 739 740 741 742 743 744 745 746 747 748 749

  //////////////////////////////////
  // 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
750
  cout << "# " << time_buffer << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
751 752


753 754
  //////////////////////////////////
  // Warning for non-optimal use
755

756
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES)
757 758
    {
      cout << endl
759
	   << "* WARNING: " << PROGNAME << " was run with '-A' option or with a large '-z' option" << endl ;
760 761 762 763 764
    }
  
  if (command == CMD_SEGMENT)
    {
      cout << endl
765
	   << "* WARNING: " << PROGNAME << " was run with '-c" COMMAND_SEGMENT "' option" << endl ;
766 767
    }
  
768
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES || command == CMD_SEGMENT)
769
    {
770
      cout << "* " << PROGNAME << " efficiently extracts windows overlapping the CDR3" << endl
771
           << "* to cluster reads into clones ('-c clones')." << endl
772 773
           << "* 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
774
	   << "* More information is provided in " DOCUMENTATION "." << endl
775 776
	   << endl ;
    }
777

778

779 780 781 782 783 784 785
  //

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


786 787 788 789
  /////////////////////////////////////////
  //            JSON OUTPUT              //
  /////////////////////////////////////////

790
  string f_airr = out_dir + f_basename + AIRR_SUFFIX ;
791 792 793 794 795
  string f_json = out_dir + f_basename + JSON_SUFFIX ;

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

796
  SampleOutput output({
797 798 799 800 801 802 803 804
    {"vidjil_json_version", VIDJIL_JSON_VERSION},
    {"samples", {
        {"number", 1},
        {"original_names", {f_reads}},
        {"run_timestamp", {time_buffer}},
        {"producer", {soft_version}},
        {"commandline", {stream_cmdline.str()}}
      }}
805
  });
806 807


808 809 810