vidjil.cpp 54.8 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

#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 VIDJIL_JSON_VERSION "2016b"
Mikaël Salson's avatar
Mikaël Salson committed
70

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

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

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

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

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

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

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

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

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

#define DEFAULT_CLUSTER_COST  Cluster
#define DEFAULT_SEGMENT_COST   VDJ

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

120
#define MAX_CLONES_FOR_SIMILARITY 20
121

122
// warn
123
#define WARN_MAX_CLONES 100
124
#define WARN_PERCENT_SEGMENTED 40
125
#define WARN_COVERAGE 0.6
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
220
       << "  -f <string>   use custom Cost for fine segmenter : format \"match, subst, indels, homo, del_end\" (default "<< DEFAULT_SEGMENT_COST <<" )"<< endl
221
       << "  -E <float>    maximal e-value for determining if a D segment can be trusted (default: " << THRESHOLD_NB_EXPECTED_D << ")" << endl
222
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
223

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

  if (advanced)
  cerr << "Additional clustering (experimental)" << endl
230
       << "  -= <file>     manual clustering -- a file used to force some specific edges" << endl
231 232 233 234
       << "  -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
235
       << "  -C <string>   use custom Cost for automatic clustering : format \"match, subst, indels, homo, del_end\" (default "<< DEFAULT_CLUSTER_COST <<" )"<< endl
236
       << endl ;
237

Mathieu Giraud's avatar
Mathieu Giraud committed
238
  cerr << "Detailed output per read (generally not recommended, large files, but may be used for filtering, as in -uu -X 1000)" << endl
239
       << "  -U            output segmented reads (in " << SEGMENTED_FILENAME << " file)" << endl
240 241 242 243
       << "  -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

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
       << "  " << progname << " -c clones   -g germline/homo-sapiens.g     -2 -3     demo/Stanford_S22.fasta   # (basic usage, detect the locus for each read," << endl
263
       << "                                                                                          #  including unexpected recombinations, analyzes CDR3)" << endl
264 265 266 267
       << "  " << 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 windows  -g germline/homo-sapiens.g     -2 -uu -U demo/Stanford_S22.fasta   # (detect the locus, splits all the reads into large files)" << 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 first 50 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
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
  bool seed_changed = false;
323
  string f_basename = "";
Mikaël Salson's avatar
Mikaël Salson committed
324

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

329
  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
  int trim_sequences = DEFAULT_TRIM;
Mikaël Salson's avatar
Mikaël Salson committed
358

359 360
  bool trim_sequences_changed = false;
  
Mikaël Salson's avatar
Mikaël Salson committed
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: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);
Mikaël Salson's avatar
Mikaël Salson committed
439 440 441
	break;
        
      case 'J':
442
	f_reps_J.push_back(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
443 444
	break;

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

          // 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 ;
463
        }
464

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

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

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

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

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

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

      // Algorithm

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

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

512 513 514 515
      case '!':
        keep_unsegmented_as_clone = true;
        break;

516
      case 'e':
517
        expected_value = atof_NO_LIMIT(optarg);
518 519
        break;

520 521 522 523
      case 'E':
        expected_value_D = atof_NO_LIMIT(optarg);
        break;

524 525
      // Output 

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

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

534 535 536 537
      case 'a':
	output_sequences_by_cluster = true;
	break;

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

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

547 548
      // Limits

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

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

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

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

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

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

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

582 583 584
      // Labels

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

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

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

596
      // Clustering
597

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

      case 'u':
632 633 634
        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
635
        break;
636 637 638
      case 'U':
        output_segmented = true;
        break;
639 640 641
      case 'K':
        output_affects = true;
        break;
Mikaël Salson's avatar
Mikaël Salson committed
642 643
      }

644 645 646

  //$$ options: post-processing+display

647

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

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

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

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

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

681 682
  // Default seeds

683
#ifdef NO_SPACED_SEEDS
684
  if (! seed_changed)
685
    {
686
    cerr << ERROR_STRING << "Vidjil was compiled with NO_SPACED_SEEDS: please provide a -k option." << endl;
687 688 689 690 691
    exit(1) ;
  }
#endif
	  

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

701

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

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

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

722 723 724 725 726
  // 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
727 728 729
  out_dir += "/" ;

  /// Load labels ;
730
  load_into_map(windows_labels, windows_labels_file, "-l");
Mikaël Salson's avatar
Mikaël Salson committed
731 732

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

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

  //////////////////////////////////
  // 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
760
  cout << "# " << time_buffer << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
761 762


763 764
  //////////////////////////////////
  // Warning for non-optimal use
765

766
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES)
767 768 769 770 771 772 773 774 775 776 777
    {
      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 ;
    }
  
778
  if (max_clones == NO_LIMIT_VALUE || max_clones > WARN_MAX_CLONES || command == CMD_SEGMENT)
779
    {
780
      cout << "* Vidjil's purpose is to efficiently extract windows overlapping the CDR3" << endl
781
           << "* to cluster reads into clones ('-c clones')." << endl
782 783
           << "* 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
784 785 786
	   << "* More information is provided in the 'doc/algo.org' file." << endl 
	   << endl ;
    }
787

788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

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


810 811 812
  /////////////////////////////////////////
  //            LOAD GERMLINES           //
  /////////////////////////////////////////
813

814 815 816 817 818 819
  if (command == CMD_GERMLINES)
    {
      multi_germline = true ;
      multi_germline_one_index_per_germline = false ;
    }

820
  MultiGermline *multigermline = new MultiGermline(indexType, multi_germline_one_index_per_germline);
821

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

847
          germline->new_index(indexType);
848

849 850 851
	  multigermline->insert(germline);
	}
    }
852

853
    cout << endl ;
854

855
    if (!multi_germline_one_index_per_germline) {
856
      multigermline->build_with_one_index(seed, true);
857
    }
858

859
      if (multi_germline_unexpected_recombinations_12 || multi_germline_unexpected_recombinations_1U) {
860 861 862
        if (!multigermline->index) {
          multigermline->build_with_one_index(seed, false);
        }
863
      }
864

865
      if (multi_germline_unexpected_recombinations_12) {
866
        Germline *pseudo = new Germline(PSEUDO_UNEXPECTED, PSEUDO_UNEXPECTED_CODE, "", trim_sequences);
867
        pseudo->seg_method = SEG_METHOD_MAX12 ;
868 869
        pseudo->index = multigermline->index ;
        multigermline->germlines.push_back(pseudo);
870 871 872
      }

      if (multi_germline_unexpected_recombinations_1U) {
873
        Germline *pseudo_u = new Germline(PSEUDO_UNEXPECTED, PSEUDO_UNEXPECTED_CODE, "", trim_sequences);
874
        pseudo_u->seg_method = SEG_METHOD_MAX1U ;
875
        // TODO: there should be more up/downstream regions for the PSEUDO_UNEXPECTED germline. And/or smaller seeds ?
876 877
        pseudo_u->index = multigermline->index ;
        multigermline->germlines.push_back(pseudo_u);
878 879
    }