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

57 58
#include "lib/json.hpp"

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

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

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

Mathieu Giraud's avatar
Mathieu Giraud committed
72 73
//$$ #define (mainly default options)

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

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

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

92 93 94
#define DEFAULT_OUT_DIR "./out/" 

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

106
#define DEFAULT_K      0
107
#define DEFAULT_W      50
108
#define DEFAULT_SEED   DEFAULT_GERMLINE_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
#define WARN_COVERAGE 0.6
127

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

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

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

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

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

extern int optind, optopt, opterr;

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

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

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

159
  cerr << "Germline presets (at least one -g or -V/(-D)/-J option must be given for all commands except -c " << COMMAND_GERMLINES << ")" << endl
160 161
       << "  -g <.g file>(:filter)" << endl
       << "                multiple locus/germlines, with tuned parameters." << endl
162
       << "                Common values are '-g germline/homo-sapiens.g' or '-g germline/mus-musculus.g'" << endl
163 164 165 166 167 168
       << "                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
169 170 171
       << endl

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

176 177
  if (advanced)
  cerr << "Experimental options (do not use)" << endl
178
       << "  -I            ignore k-mers common to different germline systems (experimental, must be used with -g, do not use)" << endl
179
       << "  -1            use a unique index for all germline systems (experimental, must be used with -g, do not use)" << endl
180
       << "  -4            try to detect unexpected recombinations with translocations (experimental, must be used with -g, do not use)" << endl
181
       << "  -!            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
182 183
       << endl

Mathieu Giraud's avatar
Mathieu Giraud committed
184
       << "Window prediction" << endl
Mikaël Salson's avatar
Mikaël Salson committed
185
#ifndef NO_SPACED_SEEDS
186
       << "  (use either -s or -k option, but not both)" << endl
187
       << "  (all these options, except -w, are overriden when using -g)" << endl
188 189
       << "  -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
190
#endif
191
       << "  -k <int>      k-mer size used for the V/J affectation (default: 10, 12, 13, depends on germline)" << endl
192 193 194
#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
195
       << "  -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
196
       << "  -e <float>    maximal e-value for determining if a V-J segmentation can be trusted (default: " << THRESHOLD_NB_EXPECTED << ")" << endl
197
       << "  -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
198 199
       << endl

200 201 202 203
       << "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
204
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
205

206
  cerr << "Limits to report a clone (or a window)" << endl
207 208
       << "  -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
209 210
       << endl

211
       << "Limits to further analyze some clones" << endl
212
       << "  -y <nb>       maximal number of clones computed with a consensus sequence ('" << NO_LIMIT << "': no limit) (default: " << DEFAULT_MAX_REPRESENTATIVES << ")" << endl
213
       << "  -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
214
       << "  -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
215 216
       << "  -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
217
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
218

219
  if (advanced)
220
  cerr << "Fine segmentation options (second pass)" << endl
221
       << "  -f <string>   use custom Cost for fine segmenter : format \"match, subst, indels, del_end, homo\" (default "<< DEFAULT_SEGMENT_COST <<" )"<< 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
       << "  -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
236
       << "  -C <string>   use custom Cost for automatic clustering : format \"match, subst, indels, del_end, homo\" (default "<< DEFAULT_CLUSTER_COST <<" )"<< 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
       << "  -U            output segmented reads (in " << SEGMENTED_FILENAME << " file)" << endl
241 242 243 244
       << "  -u            output unsegmented reads, gathered by unsegmentation cause, except for very short and 'too few V/J' reads (in *" << UNSEGMENTED_DETAIL_FILENAME << " files)" << endl
       << "  -uu           output unsegmented reads, gathered by unsegmentation cause, all reads (in *" << UNSEGMENTED_DETAIL_FILENAME << " files) (use only for debug)" << endl
       << "  -uuu          output unsegmented reads, all reads, including a " << UNSEGMENTED_FILENAME << " file (use only for debug)" << endl

245
       << "  -K            output detailed k-mer affectation on all reads (in " << AFFECTS_FILENAME << " file) (use only for debug, for example -KX 100)" << endl
246 247
       << endl
 
Mikaël Salson's avatar
Mikaël Salson committed
248
       << "Output" << endl
249
       << "  -o <dir>      output directory (default: " << DEFAULT_OUT_DIR << ")" <<  endl
250
       << "  -b <string>   output basename (by default basename of the input file)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
251
    
252
       << "  -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
253 254 255
       << "  -v            verbose mode" << endl
       << endl        

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

Mikaël Salson's avatar
Mikaël Salson committed
261
       << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
262
       << "Examples (see doc/algo.org)" << endl
263 264 265
       << "  " << 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
266
       << "  " << progname << " -c clones   -g germline/homo-sapiens.g:IGH    -3     demo/Stanford_S22.fasta   # (restrict to complete recombinations on the IGH locus)" << endl
267 268 269
       << "  " << 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
270
       << "  " << 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
271
    ;
272
  return 1;
Mikaël Salson's avatar
Mikaël Salson committed
273 274
}

Mathieu Giraud's avatar
Mathieu Giraud committed
275 276 277

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

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

299 300 301
  //////////////////////////////////
  // Display version information or git log

302 303
  string soft_version = PROGNAME ;
  soft_version += " " ;
304
#ifdef RELEASE_TAG
305
  cout << "# version: " PROGNAME << " " << RELEASE_TAG << endl ;
306 307 308 309 310 311 312 313 314 315
  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
316 317
  //$$ options: defaults

318 319 320
  list <string> f_reps_V ;
  list <string> f_reps_D ;
  list <string> f_reps_J ;
321
  list <pair <string, string>> multi_germline_paths_and_files ;
322

323
  string read_header_separator = DEFAULT_READ_HEADER_SEPARATOR ;
Mikaël Salson's avatar
Mikaël Salson committed
324 325
  string f_reads = DEFAULT_READS ;
  string seed = DEFAULT_SEED ;
326
  bool seed_changed = false;
327
  string f_basename = "";
Mikaël Salson's avatar
Mikaël Salson committed
328

329
  string out_dir = DEFAULT_OUT_DIR;
Mikaël Salson's avatar
Mikaël Salson committed
330 331 332
  
  string comp_filename = COMP_FILENAME;

333
  int wmer_size = DEFAULT_W ;
Mikaël Salson's avatar
Mikaël Salson committed
334

335
  IndexTypes indexType = KMER_INDEX;
336

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

349
  int max_representatives = DEFAULT_MAX_REPRESENTATIVES ;
350 351 352
  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
353 354
  // int average_deletion = 4;     // Average number of deletion in V or J

355 356
  int max_reads_processed = NO_LIMIT_VALUE;
  int max_reads_processed_sample = NO_LIMIT_VALUE;
357

Mathieu Giraud's avatar
Mathieu Giraud committed
358
  float ratio_representative = DEFAULT_RATIO_REPRESENTATIVE;
Mikaël Salson's avatar
Mikaël Salson committed
359
  unsigned int max_auditionned = DEFAULT_MAX_AUDITIONED;
Mathieu Giraud's avatar
Mathieu Giraud committed
360

Mikaël Salson's avatar
Mikaël Salson committed
361
  int trim_sequences = DEFAULT_TRIM;
Mikaël Salson's avatar
Mikaël Salson committed
362

363 364
  bool trim_sequences_changed = false;
  
Mikaël Salson's avatar
Mikaël Salson committed
365
  bool output_sequences_by_cluster = false;
366
  bool output_segmented = false;
Mathieu Giraud's avatar
Mathieu Giraud committed
367
  bool output_unsegmented = false;
368
  bool output_unsegmented_detail = false;
369
  bool output_unsegmented_detail_full = false;
370
  bool output_affects = false;
371 372
  bool keep_unsegmented_as_clone = false;

373 374
  bool several_D = false;

375
  bool multi_germline = false;
376
  bool multi_germline_mark = false;
377
  bool multi_germline_one_index_per_germline = true;
378 379
  bool multi_germline_unexpected_recombinations_12 = false;
  bool multi_germline_unexpected_recombinations_1U = false;
380

Mikaël Salson's avatar
Mikaël Salson committed
381 382
  string forced_edges = "" ;

383
  map <string, string> windows_labels ;
Mathieu Giraud's avatar
Mathieu Giraud committed
384
  string windows_labels_file = "" ;
385
  bool only_labeled_windows = false ;
Mikaël Salson's avatar
Mikaël Salson committed
386 387 388

  char c ;

389 390
  int options_s_k = 0 ;

391
  double expected_value = THRESHOLD_NB_EXPECTED;
392
  double expected_value_D = THRESHOLD_NB_EXPECTED_D;
393

394 395
  //json which contains the Levenshtein distances
  json jsonLevenshtein;
396
  bool jsonLevenshteinComputed = false ;
WebTogz's avatar
WebTogz committed
397

Mathieu Giraud's avatar
Mathieu Giraud committed
398 399
  //$$ options: getopt

400

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

    switch (c)
      {
      case 'h':
406
        return usage(argv[0], false);
407 408

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

425 426 427 428
      case 'q':
        indexType = AC_AUTOMATON;
        break;

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

      // Germline

      case 'V':
437
	f_reps_V.push_back(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
438 439 440
	break;

      case 'D':
441
	f_reps_D.push_back(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
442 443 444
	break;
        
      case 'J':
445
	f_reps_J.push_back(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
446 447
	break;

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

          // 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 ;
466
        }
467

468 469 470 471
      case 'd':
        several_D = true;
        break;

472 473 474
      case 'I':
        multi_germline_mark = true;
	break;
475 476 477 478

      case '1':
        multi_germline_one_index_per_germline = false ;
        break;
479 480

      case '2':
481 482 483 484 485
        multi_germline_unexpected_recombinations_12 = true ;
        break;

      case '4':
        multi_germline_unexpected_recombinations_1U = true ;
486 487
        break;

Mikaël Salson's avatar
Mikaël Salson committed
488 489 490 491
	break;

      // Algorithm

492 493 494
      case 's':
#ifndef NO_SPACED_SEEDS
	seed = string(optarg);
495
        seed_changed = true;
496 497 498 499 500 501
	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
502
      case 'k':
503 504 505
        {
          int kmer_size = atoi(optarg);
          seed = seed_contiguous(kmer_size);
506
          seed_changed = true;
507
        }
508
	options_s_k++ ;
Mikaël Salson's avatar
Mikaël Salson committed
509 510 511
        break;

      case 'w':
Mathieu Giraud's avatar
Mathieu Giraud committed
512
	wmer_size = atoi_NO_LIMIT(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
513 514
        break;

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

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

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

527 528
      // Output 

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

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

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

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

546 547 548 549
      case 'v':
	verbose += 1 ;
	break;

550 551
      // Limits

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

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

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

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

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

577
      case 'X':
578 579 580 581
        max_reads_processed_sample = atoi_NO_LIMIT(optarg);
        break;

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

585 586 587
      // Labels

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

591 592 593 594
      case 'l':
	windows_labels_file = optarg; 
	break;

595 596 597 598
      case 'F':
        only_labeled_windows = true;
        break;

599
      // Clustering
600

601
      case '=':
602 603
	forced_edges = optarg;
	break;
Mikaël Salson's avatar
Mikaël Salson committed
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
	
      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;
	
625
      // Fine segmentation
626 627 628 629
      case '3':
        detect_CDR3 = true;
        break;
        
630
      case 'f':
Mikaël Salson's avatar
Mikaël Salson committed
631 632
	segment_cost=strToCost(optarg, VDJ);
        break;
Mathieu Giraud's avatar
Mathieu Giraud committed
633 634

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

647 648 649

  //$$ options: post-processing+display

650

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

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

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

Mikaël Salson's avatar
Mikaël Salson committed
665 666 667 668 669 670 671 672 673 674 675 676 677
  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
    {
678
      cerr << ERROR_STRING << "Wrong number of arguments." << endl ;
679
      return 1;
Mikaël Salson's avatar
Mikaël Salson committed
680
    }
Mathieu Giraud's avatar
Mathieu Giraud committed
681

682
  size_t min_cover_representative = (size_t) (min_reads_clone < (int) max_auditionned ? min_reads_clone : max_auditionned) ;
683

684 685
  // Default seeds

686
#ifdef NO_SPACED_SEEDS
687
  if (! seed_changed)
688
    {
689
      cerr << ERROR_STRING << PROGNAME << " was compiled with NO_SPACED_SEEDS: please provide a -k option." << endl;
690
      return 1;
691 692 693 694
  }
#endif
	  

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

704

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

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

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

725 726 727 728 729
  // 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
730 731 732
  out_dir += "/" ;

  /// Load labels ;
733
  load_into_map(windows_labels, windows_labels_file, "-l");
Mikaël Salson's avatar
Mikaël Salson committed
734 735

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

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

  //////////////////////////////////
  // 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
763
  cout << "# " << time_buffer << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
764 765


766 767
  //////////////////////////////////
  // Warning for non-optimal use
768

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

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812

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


813 814 815
  /////////////////////////////////////////
  //            LOAD GERMLINES           //
  /////////////////////////////////////////
816

817 818 819 820 821 822
  if (command == CMD_GERMLINES)
    {
      multi_germline = true ;
      multi_germline_one_index_per_germline = false ;
    }

823
  MultiGermline *multigermline = new MultiGermline(indexType, multi_germline_one_index_per_germline);
824

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

850
          germline->new_index(indexType);
851