vidjil.cpp 54.6 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1
/*
2
  This file is part of Vidjil <http://www.vidjil.org>
3
  Copyright (C) 2011-2017 by 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 11 12 13 14 15 16 17 18 19 20 21 22 23

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

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

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

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 38

#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>

#include "core/tools.h"
WebTogz's avatar
WebTogz committed
39
#include "core/json.h"
40
#include "core/germline.h"
Mikaël Salson's avatar
Mikaël Salson committed
41 42
#include "core/kmerstore.h"
#include "core/fasta.h"
43
#include "core/bioreader.hpp"
Mikaël Salson's avatar
Mikaël Salson committed
44
#include "core/segment.h"
Mathieu Giraud's avatar
Mathieu Giraud committed
45
#include "core/windows.h"
Mikaël Salson's avatar
Mikaël Salson committed
46 47 48 49 50 51 52
#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
53
#include "core/list_utils.h"
Mathieu Giraud's avatar
Mathieu Giraud committed
54
#include "core/windowExtractor.h"
Mikaël Salson's avatar
Mikaël Salson committed
55

56 57
#include "lib/json.hpp"

Mikaël Salson's avatar
Mikaël Salson committed
58 59 60 61 62 63 64
#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"

65 66 67
// 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"

68
#define VIDJIL_JSON_VERSION "2016b"
Mikaël Salson's avatar
Mikaël Salson committed
69

Mathieu Giraud's avatar
Mathieu Giraud committed
70 71
//$$ #define (mainly default options)

72
#define DEFAULT_MULTI_GERMLINE_PATH "germline/"
73
#define DEFAULT_MULTI_GERMLINE_FILE "homo-sapiens.g"
Mikaël Salson's avatar
Mikaël Salson committed
74

75
#define DEFAULT_READ_HEADER_SEPARATOR " "
Mathieu Giraud's avatar
Mathieu Giraud committed
76
#define DEFAULT_READS  "./data/Stanford_S22.fasta"
77
#define DEFAULT_MIN_READS_CLONE 5
78
#define DEFAULT_MAX_REPRESENTATIVES 100
79
#define DEFAULT_MAX_CLONES 100
80
#define DEFAULT_RATIO_READS_CLONE 0.0
81
#define NO_LIMIT "all"
Mikaël Salson's avatar
Mikaël Salson committed
82

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

90 91 92
#define DEFAULT_OUT_DIR "./out/" 

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

// "tests/data/leukemia.fa" 

106
#define DEFAULT_K      0
107
#define DEFAULT_W      50
108
#define DEFAULT_SEED   ""
Mikaël Salson's avatar
Mikaël Salson committed
109

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

Mikaël Salson's avatar
Mikaël Salson committed
113 114 115 116 117 118
#define DEFAULT_EPSILON  0
#define DEFAULT_MINPTS   10

#define DEFAULT_CLUSTER_COST  Cluster
#define DEFAULT_SEGMENT_COST   VDJ

119
#define DEFAULT_TRIM 0
Mikaël Salson's avatar
Mikaël Salson committed
120

121
#define MAX_CLONES_FOR_SIMILARITY 20
122

123
// warn
124
#define WARN_MAX_CLONES 100
125
#define WARN_PERCENT_SEGMENTED 40
126

Mikaël Salson's avatar
Mikaël Salson committed
127 128 129
// display
#define WIDTH_NB_READS 7
#define WIDTH_NB_CLONES 3
130

Mikaël Salson's avatar
Mikaël Salson committed
131 132

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

Mathieu Giraud's avatar
Mathieu Giraud committed
135
//$$ options: usage
Mikaël Salson's avatar
Mikaël Salson committed
136

Mathieu Giraud's avatar
Mathieu Giraud committed
137
extern char *optarg;
Mikaël Salson's avatar
Mikaël Salson committed
138 139 140

extern int optind, optopt, opterr;

141
void usage(char *progname, bool advanced)
Mikaël Salson's avatar
Mikaël Salson committed
142
{
143
  cerr << "Usage: " << progname << " [options] <reads.fa/.fq/.gz>" << endl << endl;
Mikaël Salson's avatar
Mikaël Salson committed
144 145

  cerr << "Command selection" << endl
146
       << "  -c <command>"
147
       << "\t"     << COMMAND_CLONES    << "  \t locus detection, window extraction, clone clustering (default command, most efficient, all outputs)" << endl
148
       << "  \t\t" << COMMAND_WINDOWS   << "  \t locus detection, window extraction" << endl
149
       << "  \t\t" << COMMAND_SEGMENT   << "  \t detailed V(D)J designation (not recommended)" << endl
150
       << "  \t\t" << COMMAND_GERMLINES << "  \t statistics on k-mers in different germlines" << endl
151
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
152

153 154 155 156 157
  if (advanced)
  cerr << "Input" << endl
       << "  -# <string>   separator for headers in the reads file (default: '" << DEFAULT_READ_HEADER_SEPARATOR << "')" << endl
       << endl ;

158
  cerr << "Germline presets (at least one -g or -V/(-D)/-J option must be given for all commands except -c " << COMMAND_GERMLINES << ")" << endl
159 160
       << "  -g <.g file>(:filter)" << endl
       << "                multiple locus/germlines, with tuned parameters." << endl
161
       << "                Common values are '-g germline/homo-sapiens.g' or '-g germline/mus-musculus.g'" << endl
162 163 164 165 166 167
       << "                The list of locus/recombinations can be restricted, such as in '-g germline/homo-sapiens.g:IGH,IGK,IGL'" << endl
       << "  -g <path>     multiple locus/germlines, shortcut for '-g <path>/" << DEFAULT_MULTI_GERMLINE_FILE << "'" << endl
       << "                processes human TRA, TRB, TRG, TRD, IGH, IGK and IGL locus, possibly with some incomplete/unusal recombinations" << endl
       << "  -V <file>     custom V germline multi-fasta file" << endl
       << "  -D <file>     custom D germline multi-fasta file (and resets -m and -w options), will segment into V(D)J components" << endl
       << "  -J <file>     custom J germline multi-fasta file" << endl
168 169 170
       << endl

       << "Locus/recombinations" << endl
171
       << "  -d            try to detect several D (experimental)" << endl
172
       << "  -2            try to detect unexpected recombinations (must be used with -g)" << endl
173
       << endl ;
174

175 176
  if (advanced)
  cerr << "Experimental options (do not use)" << endl
177
       << "  -I            ignore k-mers common to different germline systems (experimental, must be used with -g, do not use)" << endl
178
       << "  -1            use a unique index for all germline systems (experimental, must be used with -g, do not use)" << endl
179
       << "  -4            try to detect unexpected recombinations with translocations (experimental, must be used with -g, do not use)" << endl
180
       << "  -!            keep unsegmented reads as clones, taking for junction the complete sequence, to be used on very small datasets (for example -!AX 20)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
181 182
       << endl

Mathieu Giraud's avatar
Mathieu Giraud committed
183
       << "Window prediction" << endl
Mikaël Salson's avatar
Mikaël Salson committed
184
#ifndef NO_SPACED_SEEDS
185
       << "  (use either -s or -k option, but not both)" << endl
186
       << "  (all these options, except -w, are overriden when using -g)" << endl
187 188
       << "  -s <string>   spaced seed used for the V/J affectation" << endl
       << "                (default: #####-#####, ######-######, #######-#######, depends on germline)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
189
#endif
190
       << "  -k <int>      k-mer size used for the V/J affectation (default: 10, 12, 13, depends on germline)" << endl
191 192 193
#ifndef NO_SPACED_SEEDS
       << "                (using -k option is equivalent to set with -s a contiguous seed with only '#' characters)" << endl
#endif
Mathieu Giraud's avatar
Mathieu Giraud committed
194
       << "  -w <int>      w-mer size used for the length of the extracted window (default: " << DEFAULT_W << ") ('" << NO_LIMIT << "': use all the read, no window clustering)" << endl
195
       << "  -e <float>    maximal e-value for determining if a V-J segmentation can be trusted (default: " << THRESHOLD_NB_EXPECTED << ")" << endl
196
       << "  -t <int>      trim V and J genes (resp. 5' and 3' regions) to keep at most <int> nt (default: " << DEFAULT_TRIM << ") (0: no trim)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
197 198
       << endl

199 200 201 202
       << "Labeled sequences (windows related to these sequences will be kept even if -r/-% thresholds are not reached)" << endl
       << "  -W <sequence> label the given sequence" << endl
       << "  -l <file>     label a set of sequences given in <file>" << endl
       << "  -F            filter -- keep only the windows related to the labeled sequences" << endl
203
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
204

205
  cerr << "Limits to report a clone (or a window)" << endl
206 207
       << "  -r <nb>       minimal number of reads supporting a clone (default: " << DEFAULT_MIN_READS_CLONE << ")" << endl
       << "  -% <ratio>    minimal percentage of reads supporting a clone (default: " << DEFAULT_RATIO_READS_CLONE << ")" << endl
208 209
       << endl

210
       << "Limits to further analyze some clones" << endl
211
       << "  -y <nb>       maximal number of clones computed with a consensus sequence ('" << NO_LIMIT << "': no limit) (default: " << DEFAULT_MAX_REPRESENTATIVES << ")" << endl
212
       << "  -z <nb>       maximal number of clones to be analyzed with a full V(D)J designation ('" << NO_LIMIT << "': no limit, do not use) (default: " << DEFAULT_MAX_CLONES << ")" << endl
213
       << "  -A            reports and segments all clones (-r 0 -% 0 -y " << NO_LIMIT << " -z " << NO_LIMIT << "), to be used only on very small datasets (for example -AX 20)" << endl
214 215
       << "  -x <nb>       maximal number of reads to process ('" << NO_LIMIT << "': no limit, default), only first reads" << endl
       << "  -X <nb>       maximal number of reads to process ('" << NO_LIMIT << "': no limit, default), sampled reads" << endl
216
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
217

218
  if (advanced)
219
  cerr << "Fine segmentation options (second pass)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
220
       << "  -f <string>   use custom Cost for fine segmenter : format \"match, subst, indels, homo, del_end\" (default "<<VDJ<<" )"<< endl
221
       << "  -m <int>      minimal admissible delta between the end of the V and the start of the J (default: " << DEFAULT_DELTA_MIN << ") (default with -D: " << DEFAULT_DELTA_MIN_D << ")" << endl
222
       << "  -E <float>    maximal e-value for determining if a D segment can be trusted (default: " << THRESHOLD_NB_EXPECTED_D << ")" << endl
223
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
224

225 226 227 228 229 230
  cerr << "Clone analysis (second pass)" << endl
       << "  -3            CDR3/JUNCTION detection (requires gapped V/J germlines)" << endl
       << endl ;

  if (advanced)
  cerr << "Additional clustering (experimental)" << endl
231
       << "  -= <file>     manual clustering -- a file used to force some specific edges" << endl
232 233 234 235 236
       << "  -n <int>      maximum distance between neighbors for automatic clustering (default " << DEFAULT_EPSILON << "). No automatic clusterisation if =0." << endl
       << "  -N <int>      minimum required neighbors for automatic clustering (default " << DEFAULT_MINPTS << ")" << endl
       << "  -S            generate and save comparative matrix for clustering" << endl
       << "  -L            load comparative matrix for clustering" << endl
       << "  -C <string>   use custom Cost for automatic clustering : format \"match, subst, indels, homo, del_end\" (default "<<Cluster<<" )"<< endl
237
       << endl ;
238

Mathieu Giraud's avatar
Mathieu Giraud committed
239
  cerr << "Detailed output per read (generally not recommended, large files, but may be used for filtering, as in -uu -X 1000)" << endl
240 241
       << "  -U            output segmented reads (in " << SEGMENTED_FILENAME << " file)" << endl
       << "  -u            output unsegmented reads (in " << UNSEGMENTED_FILENAME << " file)" << endl
242 243
       << "  -uu           output unsegmented reads, gathered by unsegmentation cause, except for very short and 'too few V/J' reads (in *" << UNSEGMENTED_DETAIL_FILENAME << " files)" << endl
       << "  -uuu          output unsegmented reads, gathered by unsegmentation cause, all reads (in *" << UNSEGMENTED_DETAIL_FILENAME << " files) (use only for debug)" << endl
244
       << "  -K            output detailed k-mer affectation on all reads (in " << AFFECTS_FILENAME << " file) (use only for debug, for example -KX 100)" << endl
245 246
       << endl
 
Mikaël Salson's avatar
Mikaël Salson committed
247
       << "Output" << endl
248
       << "  -o <dir>      output directory (default: " << DEFAULT_OUT_DIR << ")" <<  endl
249
       << "  -b <string>   output basename (by default basename of the input file)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
250
    
251
       << "  -a            output all sequences by cluster (" << CLONE_FILENAME << "*), to be used only on small datasets" << endl
Mikaël Salson's avatar
Mikaël Salson committed
252 253 254
       << "  -v            verbose mode" << endl
       << endl        

255 256
       << "  -h            help" << endl
       << "  -H            help, including experimental and advanced options" << endl
257 258 259
       << "The full help is available in the doc/algo.org file."
       << endl

Mikaël Salson's avatar
Mikaël Salson committed
260
       << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
261
       << "Examples (see doc/algo.org)" << endl
262 263 264
       << "  " << progname << " -c clones   -g germline/homo-sapiens.g     -2 -3     data/Stanford_S22.fasta   # (basic usage, detect the locus for each read," << endl
       << "                                                                                          #  including unexpected recombinations, analyzes CDR3)" << endl
       << "  " << progname << " -c clones   -g germline/homo-sapiens.g:IGH    -3     data/Stanford_S22.fasta   # (restrict to complete recombinations on the IGH locus)" << endl
265 266
       << "  " << progname << " -c windows  -g germline/homo-sapiens.g     -2 -uu -U data/Stanford_S22.fasta   # (detect the locus, splits all the reads into large files)" << endl
       << "  " << progname << " -c segment  -g germline/homo-sapiens.g     -2 -3     data/Stanford_S22.fasta   # (full analysis of each read, only for debug/testing)" << endl
267
       << "  " << progname << " -c germlines -g germline/homo-sapiens.g              data/Stanford_S22.fasta   # (statistics on the k-mers)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
268 269 270 271
    ;
  exit(1);
}

Mathieu Giraud's avatar
Mathieu Giraud committed
272 273 274

int atoi_NO_LIMIT(char *optarg)
{
275 276
  return strcmp(NO_LIMIT, optarg) ? atoi(optarg) : NO_LIMIT_VALUE ;
}
277
double atof_NO_LIMIT(char *optarg)
278 279
{
  return strcmp(NO_LIMIT, optarg) ? atof(optarg) : NO_LIMIT_VALUE ;
Mathieu Giraud's avatar
Mathieu Giraud committed
280 281
}

Mikaël Salson's avatar
Mikaël Salson committed
282 283
int main (int argc, char **argv)
{
284
  cout << "# Vidjil -- V(D)J recombinations analysis <http://www.vidjil.org/>" << endl
285
       << "# Copyright (C) 2011-2017 by the Vidjil team" << endl
286
       << "# Bonsai bioinformatics at CRIStAL (UMR CNRS 9189, Université Lille) and Inria Lille" << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
287 288 289 290 291
       << endl
       << "# Vidjil is free software, and you are welcome to redistribute it" << endl
       << "# 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
292
       << endl
293
       << "# Please cite http://biomedcentral.com/1471-2164/15/409 if you use Vidjil." << endl
Mikaël Salson's avatar
Mikaël Salson committed
294 295
       << endl ;

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
  //////////////////////////////////
  // Display version information or git log

  string soft_version = "vidjil ";
#ifdef RELEASE_TAG
  cout << "# version: vidjil " << RELEASE_TAG << endl ;
  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

Mathieu Giraud's avatar
Mathieu Giraud committed
312 313
  //$$ options: defaults

314 315 316
  list <string> f_reps_V ;
  list <string> f_reps_D ;
  list <string> f_reps_J ;
317
  list <pair <string, string>> multi_germline_paths_and_files ;
318

319
  string read_header_separator = DEFAULT_READ_HEADER_SEPARATOR ;
Mikaël Salson's avatar
Mikaël Salson committed
320 321
  string f_reads = DEFAULT_READS ;
  string seed = DEFAULT_SEED ;
322
  string f_basename = "";
Mikaël Salson's avatar
Mikaël Salson committed
323

324
  string out_dir = DEFAULT_OUT_DIR;
Mikaël Salson's avatar
Mikaël Salson committed
325 326 327
  
  string comp_filename = COMP_FILENAME;

328 329
  int kmer_size = DEFAULT_K ;
  int wmer_size = DEFAULT_W ;
Mikaël Salson's avatar
Mikaël Salson committed
330

331
  IndexTypes indexType = KMER_INDEX;
332

Mikaël Salson's avatar
Mikaël Salson committed
333 334 335 336
  int epsilon = DEFAULT_EPSILON ;
  int minPts = DEFAULT_MINPTS ;
  Cost cluster_cost = DEFAULT_CLUSTER_COST ;
  Cost segment_cost = DEFAULT_SEGMENT_COST ;
337
  bool detect_CDR3 = false;
Mikaël Salson's avatar
Mikaël Salson committed
338 339 340 341 342
  
  int save_comp = 0;
  int load_comp = 0;
  
  int verbose = 0 ;
343
  int command = CMD_CLONES;
Mikaël Salson's avatar
Mikaël Salson committed
344

345
  int max_representatives = DEFAULT_MAX_REPRESENTATIVES ;
346 347 348
  int max_clones = DEFAULT_MAX_CLONES ;
  int min_reads_clone = DEFAULT_MIN_READS_CLONE ;
  float ratio_reads_clone = DEFAULT_RATIO_READS_CLONE;
Mikaël Salson's avatar
Mikaël Salson committed
349 350
  // int average_deletion = 4;     // Average number of deletion in V or J

351 352
  int max_reads_processed = NO_LIMIT_VALUE;
  int max_reads_processed_sample = NO_LIMIT_VALUE;
353

Mathieu Giraud's avatar
Mathieu Giraud committed
354
  float ratio_representative = DEFAULT_RATIO_REPRESENTATIVE;
Mikaël Salson's avatar
Mikaël Salson committed
355
  unsigned int max_auditionned = DEFAULT_MAX_AUDITIONED;
Mathieu Giraud's avatar
Mathieu Giraud committed
356

Mikaël Salson's avatar
Mikaël Salson committed
357 358
  // Admissible delta between left and right segmentation points
  int delta_min = DEFAULT_DELTA_MIN ; // Kmer+Fine
Mikaël Salson's avatar
Mikaël Salson committed
359
  int trim_sequences = DEFAULT_TRIM;
Mikaël Salson's avatar
Mikaël Salson committed
360 361

  bool output_sequences_by_cluster = false;
362
  bool output_segmented = false;
Mathieu Giraud's avatar
Mathieu Giraud committed
363
  bool output_unsegmented = false;
364
  bool output_unsegmented_detail = false;
365
  bool output_unsegmented_detail_full = false;
366
  bool output_affects = false;
367 368
  bool keep_unsegmented_as_clone = false;

369 370
  bool several_D = false;

371
  bool multi_germline = false;
372
  bool multi_germline_mark = false;
373
  bool multi_germline_one_index_per_germline = true;
374 375
  bool multi_germline_unexpected_recombinations_12 = false;
  bool multi_germline_unexpected_recombinations_1U = false;
376

Mikaël Salson's avatar
Mikaël Salson committed
377 378
  string forced_edges = "" ;

379
  map <string, string> windows_labels ;
Mathieu Giraud's avatar
Mathieu Giraud committed
380
  string windows_labels_file = "" ;
381
  bool only_labeled_windows = false ;
Mikaël Salson's avatar
Mikaël Salson committed
382 383 384

  char c ;

385 386
  int options_s_k = 0 ;

387
  double expected_value = THRESHOLD_NB_EXPECTED;
388
  double expected_value_D = THRESHOLD_NB_EXPECTED_D;
389

390 391
  //json which contains the Levenshtein distances
  json jsonLevenshtein;
392
  bool jsonLevenshteinComputed = false ;
WebTogz's avatar
WebTogz committed
393

Mathieu Giraud's avatar
Mathieu Giraud committed
394 395
  //$$ options: getopt

396

397
  while ((c = getopt(argc, argv, "A!x:X:hHadI124g:V:D:J:k:r:vw:e:E:C:f:W:l:Fc:m:N:s:b:Sn:o:L%:y:z:uUK3E:t:#:q")) != EOF)
Mikaël Salson's avatar
Mikaël Salson committed
398 399 400 401

    switch (c)
      {
      case 'h':
402 403 404 405
        usage(argv[0], false);

      case 'H':
        usage(argv[0], true);
406

Mikaël Salson's avatar
Mikaël Salson committed
407
      case 'c':
408 409
        if (!strcmp(COMMAND_CLONES,optarg))
          command = CMD_CLONES;
Mikaël Salson's avatar
Mikaël Salson committed
410 411
        else if (!strcmp(COMMAND_SEGMENT,optarg))
          command = CMD_SEGMENT;
Mathieu Giraud's avatar
Mathieu Giraud committed
412 413
        else if (!strcmp(COMMAND_WINDOWS,optarg))
          command = CMD_WINDOWS;
414 415
        else if (!strcmp(COMMAND_GERMLINES,optarg))
          command = CMD_GERMLINES;
Mikaël Salson's avatar
Mikaël Salson committed
416 417
        else {
          cerr << "Unknwown command " << optarg << endl;
418
	  usage(argv[0], false);
Mikaël Salson's avatar
Mikaël Salson committed
419 420
        }
        break;
421

422 423 424 425
      case 'q':
        indexType = AC_AUTOMATON;
        break;

426 427 428 429
      // Input
      case '#':
        read_header_separator = string(optarg);
        break;
Mikaël Salson's avatar
Mikaël Salson committed
430 431 432 433

      // Germline

      case 'V':
434
	f_reps_V.push_back(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
435 436 437
	break;

      case 'D':
438
	f_reps_D.push_back(optarg);
439
	delta_min = DEFAULT_DELTA_MIN_D ;
Mikaël Salson's avatar
Mikaël Salson committed
440 441 442
	break;
        
      case 'J':
443
	f_reps_J.push_back(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
444 445
	break;

446
      case 'g':
447
	multi_germline = true;
448 449 450 451 452 453 454 455
        {
          string arg = string(optarg);
          struct stat buffer;
          if (stat(arg.c_str(), &buffer) == 0)
            {
              if( buffer.st_mode & S_IFDIR )
                {
                  // argument is a directory
456
                  multi_germline_paths_and_files.push_back(make_pair(arg, DEFAULT_MULTI_GERMLINE_FILE)) ;
457
                  break ;
458 459
                }
            }
460 461 462 463

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

466 467 468 469
      case 'd':
        several_D = true;
        break;

470 471 472
      case 'I':
        multi_germline_mark = true;
	break;
473 474 475 476

      case '1':
        multi_germline_one_index_per_germline = false ;
        break;
477 478

      case '2':
479 480 481 482 483
        multi_germline_unexpected_recombinations_12 = true ;
        break;

      case '4':
        multi_germline_unexpected_recombinations_1U = true ;
484 485
        break;

Mikaël Salson's avatar
Mikaël Salson committed
486 487 488 489
	break;

      // Algorithm

490 491 492
      case 's':
#ifndef NO_SPACED_SEEDS
	seed = string(optarg);
493
	kmer_size = seed_weight(seed);
494 495 496 497 498 499
	options_s_k++ ;
#else
        cerr << "To enable the option -s, please compile without NO_SPACED_SEEDS" << endl;
#endif
        break;

Mikaël Salson's avatar
Mikaël Salson committed
500
      case 'k':
501 502
	kmer_size = atoi(optarg);
	seed = seed_contiguous(kmer_size);
503
	options_s_k++ ;
Mikaël Salson's avatar
Mikaël Salson committed
504 505 506
        break;

      case 'w':
Mathieu Giraud's avatar
Mathieu Giraud committed
507
	wmer_size = atoi_NO_LIMIT(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
508 509 510 511 512 513
        break;

      case 'm':
	delta_min = atoi(optarg);
        break;

514 515 516 517
      case '!':
        keep_unsegmented_as_clone = true;
        break;

518
      case 'e':
519
        expected_value = atof_NO_LIMIT(optarg);
520 521
        break;

522 523 524 525
      case 'E':
        expected_value_D = atof_NO_LIMIT(optarg);
        break;

526 527
      // Output 

Mikaël Salson's avatar
Mikaël Salson committed
528 529 530 531
      case 'o':
        out_dir = optarg ;
        break;

532 533
      case 'b':
        f_basename = optarg;
Mikaël Salson's avatar
Mikaël Salson committed
534 535
        break;

536 537 538 539
      case 'a':
	output_sequences_by_cluster = true;
	break;

Mikaël Salson's avatar
Mikaël Salson committed
540 541 542 543
      case 't':
        trim_sequences = atoi(optarg);
        break;

544 545 546 547
      case 'v':
	verbose += 1 ;
	break;

548 549
      // Limits

Mikaël Salson's avatar
Mikaël Salson committed
550 551 552 553
      case '%':
	ratio_reads_clone = atof(optarg);
	break;

554
      case 'r':
Mikaël Salson's avatar
Mikaël Salson committed
555 556 557
	min_reads_clone = atoi(optarg);
        break;

558
      case 'y':
Mathieu Giraud's avatar
Mathieu Giraud committed
559
	max_representatives = atoi_NO_LIMIT(optarg);
560 561
        break;

Mikaël Salson's avatar
Mikaël Salson committed
562
      case 'z':
Mathieu Giraud's avatar
Mathieu Giraud committed
563
	max_clones = atoi_NO_LIMIT(optarg);
564
        if ((max_representatives < max_clones) && (max_representatives != NO_LIMIT_VALUE))
565
          max_representatives = max_clones ;
Mikaël Salson's avatar
Mikaël Salson committed
566
        break;
567 568 569

      case 'A': // --all
	ratio_reads_clone = 0 ;
570
	min_reads_clone = 1 ;
571 572
	max_representatives = NO_LIMIT_VALUE ;
	max_clones = NO_LIMIT_VALUE ;
573 574
	break ;

575
      case 'X':
576 577 578 579
        max_reads_processed_sample = atoi_NO_LIMIT(optarg);
        break;

      case 'x':
Mathieu Giraud's avatar
Mathieu Giraud committed
580
        max_reads_processed = atoi_NO_LIMIT(optarg);
581
        break;
582

583 584 585
      // Labels

      case 'W':
Mathieu Giraud's avatar
Mathieu Giraud committed
586
        windows_labels[string(optarg)] = string("-W");
587 588
        break;

589 590 591 592
      case 'l':
	windows_labels_file = optarg; 
	break;

593 594 595 596
      case 'F':
        only_labeled_windows = true;
        break;

597
      // Clustering
598

599
      case '=':
600 601
	forced_edges = optarg;
	break;
Mikaël Salson's avatar
Mikaël Salson committed
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
	
      case 'n':
	epsilon = atoi(optarg);
        break;

      case 'N':
	minPts = atoi(optarg);
        break;
	
      case 'S':
	save_comp=1;
        break;

      case 'L':
	load_comp=1;
        break;
	
      case 'C':
	cluster_cost=strToCost(optarg, Cluster);
        break;
	
623
      // Fine segmentation
624 625 626 627
      case '3':
        detect_CDR3 = true;
        break;
        
628
      case 'f':
Mikaël Salson's avatar
Mikaël Salson committed
629 630
	segment_cost=strToCost(optarg, VDJ);
        break;
Mathieu Giraud's avatar
Mathieu Giraud committed
631 632

      case 'u':
633 634 635
        output_unsegmented_detail_full = output_unsegmented_detail; // -uuu
        output_unsegmented_detail = output_unsegmented;             // -uu
        output_unsegmented = true ;                                 // -u
Mathieu Giraud's avatar
Mathieu Giraud committed
636
        break;
637 638 639
      case 'U':
        output_segmented = true;
        break;
640 641 642
      case 'K':
        output_affects = true;
        break;
Mikaël Salson's avatar
Mikaël Salson committed
643 644
      }

645 646 647

  //$$ options: post-processing+display

648

649
  if (!multi_germline && (!f_reps_V.size() || !f_reps_J.size()))
650
    {
651
      cerr << ERROR_STRING << "At least one germline must be given with -g or -V/(-D)/-J." << endl ;
652 653 654
      exit(1);
    }

655 656
  if (options_s_k > 1)
    {
657
      cerr << ERROR_STRING << "Use at most one -s or -k option." << endl ;
658 659 660
      exit(1);
    }

Mikaël Salson's avatar
Mikaël Salson committed
661 662
  string out_seqdir = out_dir + "/seq/" ;

Mikaël Salson's avatar
Mikaël Salson committed
663 664 665 666 667 668 669 670 671 672 673 674 675
  if (verbose)
    cout << "# verbose " << verbose << endl ;

  if (optind == argc)
    {
      cout << "# using default sequence file: " << f_reads << endl ;
    }
  else if (optind+1 == argc)
    {
      f_reads = argv[optind] ; 
    }
  else
    {
676
      cerr << ERROR_STRING << "Wrong number of arguments." << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
677 678
      exit(1);
    }
Mathieu Giraud's avatar
Mathieu Giraud committed
679

680
  size_t min_cover_representative = (size_t) (min_reads_clone < (int) max_auditionned ? min_reads_clone : max_auditionned) ;
681

682 683 684
  // Default seeds

#ifndef NO_SPACED_SEEDS
685
  if (kmer_size == DEFAULT_K)
686
    {
687
      seed = SEED_S10 ;
688
      kmer_size = seed_weight(seed);
689 690 691
    }
#else
  {
692
    cerr << ERROR_STRING << "Vidjil was compiled with NO_SPACED_SEEDS: please provide a -k option." << endl;
693 694 695 696 697
    exit(1) ;
  }
#endif
	  

Mathieu Giraud's avatar
Mathieu Giraud committed
698 699 700 701
#ifndef NO_SPACED_SEEDS
  // Check seed buffer  
  if (seed.size() >= MAX_SEED_SIZE)
    {
702
      cerr << ERROR_STRING << "Seed size is too large (MAX_SEED_SIZE)." << endl ;
Mathieu Giraud's avatar
Mathieu Giraud committed
703 704 705 706
      exit(1);
    }
#endif

707

Mathieu Giraud's avatar
Mathieu Giraud committed
708
  if ((wmer_size< 0) && (wmer_size!= NO_LIMIT_VALUE))
709
    {
710
      cerr << ERROR_STRING << "Too small -w. The window size should be positive" << endl;
711 712 713
      exit(1);
    }

Mikaël Salson's avatar
Mikaël Salson committed
714 715 716 717
  // 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) {
718
    cerr << ERROR_STRING << "Directory creation: " << out_dir << endl; perror("");
Mikaël Salson's avatar
Mikaël Salson committed
719 720 721
    exit(2);
  }

Mikaël Salson's avatar
Mikaël Salson committed
722 723
  const char *outseq_cstr = out_seqdir.c_str();
  if (mkpath(outseq_cstr, 0755) == -1) {
724
    cerr << ERROR_STRING << "Directory creation: " << out_seqdir << endl; perror("");
Mikaël Salson's avatar
Mikaël Salson committed
725 726 727
    exit(2);
  }

728 729 730 731 732
  // 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
733 734 735
  out_dir += "/" ;

  /// Load labels ;
736
  load_into_map(windows_labels, windows_labels_file, "-l");
Mikaël Salson's avatar
Mikaël Salson committed
737 738

  switch(command) {
Mathieu Giraud's avatar
Mathieu Giraud committed
739
  case CMD_WINDOWS: cout << "Extracting windows" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
740
    break;
741
  case CMD_CLONES: cout << "Analysing clones" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
742 743 744
    break;
  case CMD_SEGMENT: cout << "Segmenting V(D)J" << endl;
    break;
745 746
  case CMD_GERMLINES: cout << "Discovering germlines" << endl;
    break;
Mikaël Salson's avatar
Mikaël Salson committed
747 748
  }

Mathieu Giraud's avatar
Mathieu Giraud committed
749
  cout << "Command line: ";
Mikaël Salson's avatar
Mikaël Salson committed
750
  for (int i=0; i < argc; i++) {
Mathieu Giraud's avatar
Mathieu Giraud committed
751
    cout << argv[i] << " ";
Mikaël Salson's avatar
Mikaël Salson committed
752
  }
Mathieu Giraud's avatar
Mathieu Giraud committed
753
  cout << endl;
Mikaël Salson's avatar
Mikaël Salson committed
754 755 756 757 758 759 760 761 762 763 764 765

  //////////////////////////////////
  // 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
766
  cout << "# " << time_buffer << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
767 768


769 770
  //////////////////////////////////
  // Warning for non-optimal use
771

772
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES)
773 774 775 776 777 778 779 780 781 782 783
    {
      cout << endl
	   << "* WARNING: vidjil was run with '-A' option or with a large '-z' option" << endl ;
    }
  
  if (command == CMD_SEGMENT)
    {
      cout << endl
	   << "* WARNING: vidjil was run with '-c segment' option" << endl ;
    }
  
784
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES || command == CMD_SEGMENT)
785
    {
786
      cout << "* Vidjil's purpose is to efficiently extract windows overlapping the CDR3" << endl
787
           << "* to cluster reads into clones ('-c clones')." << endl
788 789
           << "* 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
790 791 792
	   << "* More information is provided in the 'doc/algo.org' file." << endl 
	   << endl ;
    }
793

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815

  /////////////////////////////////////////
  //            JSON OUTPUT              //
  /////////////////////////////////////////

  string f_json = out_dir + f_basename + JSON_SUFFIX ;

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

  json j = {
    {"vidjil_json_version", VIDJIL_JSON_VERSION},
    {"samples", {
        {"number", 1},
        {"original_names", {f_reads}},
        {"run_timestamp", {time_buffer}},
        {"producer", {soft_version}},
        {"commandline", {stream_cmdline.str()}}
      }}
  };


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

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

826
  MultiGermline *multigermline = new MultiGermline(indexType, multi_germline_one_index_per_germline);
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 836 837 838 839 840 841
            {
              try {
                multigermline->build_from_json(path_file.first, path_file.second, GERMLINES_REGULAR, trim_sequences);
              } catch (std::exception& e) {
                cerr << ERROR_STRING << "Vidjil cannot properly read " << path_file.first << "/" << path_file.second << ": " << e.what() << endl;
                exit(1);
              }
            }
842 843 844 845