vidjil.cpp 52.7 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, 2012, 2013, 2014, 2015, 2016 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
43
#include "core/kmerstore.h"
#include "core/fasta.h"
#include "core/segment.h"
Mathieu Giraud's avatar
Mathieu Giraud committed
44
#include "core/windows.h"
Mikaël Salson's avatar
Mikaël Salson committed
45
46
47
48
49
50
51
#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
52
#include "core/list_utils.h"
Mathieu Giraud's avatar
Mathieu Giraud committed
53
#include "core/windowExtractor.h"
Mikaël Salson's avatar
Mikaël Salson committed
54

55
56
#include "lib/json.hpp"

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

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

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

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

71
72
#define DEFAULT_MULTI_GERMLINE_PATH "germline/"
#define DEFAULT_MULTI_GERMLINE_FILE "germlines.data"
Mikaël Salson's avatar
Mikaël Salson committed
73

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

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

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

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

// "tests/data/leukemia.fa" 

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

#define DEFAULT_DELTA_MIN  -10

#define DEFAULT_DELTA_MIN_D  0

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

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

#define DEFAULT_CLUSTER_COST  Cluster
#define DEFAULT_SEGMENT_COST   VDJ

122
#define DEFAULT_TRIM 100
Mikaël Salson's avatar
Mikaël Salson committed
123

124
125
#define MAX_CLONES_FOR_SIMILARITY 1000

126
// warn
127
#define WARN_MAX_CLONES 100
128
#define WARN_PERCENT_SEGMENTED 40
129

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

Mikaël Salson's avatar
Mikaël Salson committed
134
135

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

Mathieu Giraud's avatar
Mathieu Giraud committed
138
//$$ options: usage
Mikaël Salson's avatar
Mikaël Salson committed
139

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

extern int optind, optopt, opterr;

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

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

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

161
  cerr << "Germline databases (at least one -V/(-D)/-J, or -G, or -g option must be given for all commands except -c " << COMMAND_GERMLINES << ")" << endl
Mikaël Salson's avatar
Mikaël Salson committed
162
       << "  -V <file>     V germline multi-fasta file" << endl
163
       << "  -D <file>     D germline multi-fasta file (and resets -m and -w options), will segment into V(D)J components" << endl
Mikaël Salson's avatar
Mikaël Salson committed
164
       << "  -J <file>     J germline multi-fasta file" << endl
165
       << "  -G <prefix>   prefix for V (D) and J repertoires (shortcut for -V <prefix>V.fa -D <prefix>D.fa -J <prefix>J.fa) (basename gives germline code)" << endl
Mathieu Giraud's avatar
Mathieu Giraud committed
166
167
168
       << "  -g <path>     multiple locus/germlines. In the path <path>, takes 'germlines.data' to select locus and parameters" << endl
       << "                Selecting '-g germline' processes TRA, TRB, TRG, TRD, IGH, IGK and IGL locus, possibly with some incomplete/unusal recombinations" << endl
       << "                A different 'germlines.data' file can also be provided with -g <file>" << endl
169
170
171
       << endl

       << "Locus/recombinations" << endl
172
       << "  -d            try to detect several D (experimental)" << endl
173
174
       << "  -i            try to detect incomplete/unusual recombinations (locus with '+', must be used with -g)" << endl
       << "  -2            try to detect unexpected recombinations (must be used with -g)" << endl
175
       << endl ;
176

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

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

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

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

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

220
  if (advanced)
221
  cerr << "Fine segmentation options (second pass)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
222
       << "  -f <string>   use custom Cost for fine segmenter : format \"match, subst, indels, homo, del_end\" (default "<<VDJ<<" )"<< endl
223
       << "  -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
224
       << "  -E <float>    maximal e-value for determining if a D segment can be trusted (default: " << THRESHOLD_NB_EXPECTED_D << ")" << endl
225
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
226

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

  if (advanced)
  cerr << "Additional clustering (experimental)" << endl
233
       << "  -= <file>     manual clustering -- a file used to force some specific edges" << endl
234
235
236
237
238
       << "  -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
239
       << endl ;
240

Mathieu Giraud's avatar
Mathieu Giraud committed
241
  cerr << "Detailed output per read (generally not recommended, large files, but may be used for filtering, as in -uu -X 1000)" << endl
242
243
       << "  -U            output segmented reads (in " << SEGMENTED_FILENAME << " file)" << endl
       << "  -u            output unsegmented reads (in " << UNSEGMENTED_FILENAME << " file)" << endl
244
245
       << "  -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
246
       << "  -K            output detailed k-mer affectation on all reads (in " << AFFECTS_FILENAME << " file) (use only for debug, for example -KX 100)" << endl
247
248
       << endl
 
Mikaël Salson's avatar
Mikaël Salson committed
249
       << "Output" << endl
250
       << "  -o <dir>      output directory (default: " << DEFAULT_OUT_DIR << ")" <<  endl
251
       << "  -b <string>   output basename (by default basename of the input file)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
252
    
253
       << "  -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
254
255
256
       << "  -v            verbose mode" << endl
       << endl        

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

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

Mathieu Giraud's avatar
Mathieu Giraud committed
273
274
275

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

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

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
  //////////////////////////////////
  // 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
313
314
  //$$ options: defaults

315
  string germline_system = "" ;
316
317
318
319
  
  list <string> f_reps_V ;
  list <string> f_reps_D ;
  list <string> f_reps_J ;
320
  list <pair <string, string>> multi_germline_paths_and_files ;
321

322
  string read_header_separator = DEFAULT_READ_HEADER_SEPARATOR ;
Mikaël Salson's avatar
Mikaël Salson committed
323
324
  string f_reads = DEFAULT_READS ;
  string seed = DEFAULT_SEED ;
325
  string f_basename = "";
Mikaël Salson's avatar
Mikaël Salson committed
326

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

  int k = DEFAULT_K ;
332
  int w = DEFAULT_W ;
Mikaël Salson's avatar
Mikaël Salson committed
333

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

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

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

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

Mikaël Salson's avatar
Mikaël Salson committed
358
359
  // 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
360
  int trim_sequences = DEFAULT_TRIM;
Mikaël Salson's avatar
Mikaël Salson committed
361
362

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

370
371
  bool several_D = false;

372
  bool multi_germline = false;
373
  bool multi_germline_incomplete = false;
374
  bool multi_germline_mark = false;
375
  bool multi_germline_one_index_per_germline = true;
376
377
  bool multi_germline_unexpected_recombinations_12 = false;
  bool multi_germline_unexpected_recombinations_1U = false;
378

Mikaël Salson's avatar
Mikaël Salson committed
379
380
  string forced_edges = "" ;

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

  char c ;

387
388
  int options_s_k = 0 ;

389
  double expected_value = THRESHOLD_NB_EXPECTED;
390
  double expected_value_D = THRESHOLD_NB_EXPECTED_D;
391

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

Mathieu Giraud's avatar
Mathieu Giraud committed
396
397
  //$$ options: getopt

398

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

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

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

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

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

      // Germline

      case 'V':
432
	f_reps_V.push_back(optarg);
433
	germline_system = "custom" ;
Mikaël Salson's avatar
Mikaël Salson committed
434
435
436
	break;

      case 'D':
437
	f_reps_D.push_back(optarg);
438
	delta_min = DEFAULT_DELTA_MIN_D ;
Mikaël Salson's avatar
Mikaël Salson committed
439
440
441
	break;
        
      case 'J':
442
	f_reps_J.push_back(optarg);
443
	germline_system = "custom" ;
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
458
459
                }
              else
                {
460
                  multi_germline_paths_and_files.push_back(make_pair(extract_dirname(arg), extract_basename(arg, false)));
461
462
463
464
465
466
467
468
                }
            }
          else
             {
               cerr << ERROR_STRING << "A path or a file must be given with -g" << endl ;
               exit(1);
             }
        }
469
	germline_system = "multi" ;
470
	break;
471

472
473
474
475
      case 'd':
        several_D = true;
        break;

476
477
478
      case 'i':
	multi_germline_incomplete = true;
	break;
479
480
481
482

      case 'I':
        multi_germline_mark = true;
	break;
483
484
485
486

      case '1':
        multi_germline_one_index_per_germline = false ;
        break;
487
488

      case '2':
489
490
491
492
493
        multi_germline_unexpected_recombinations_12 = true ;
        break;

      case '4':
        multi_germline_unexpected_recombinations_1U = true ;
494
495
        break;

Mikaël Salson's avatar
Mikaël Salson committed
496
      case 'G':
Mikaël Salson's avatar
Mikaël Salson committed
497
	germline_system = string(optarg);
498
	f_reps_V.push_back((germline_system + "V.fa").c_str()) ;
499
500
501
502
503
        // Takes D only if it exists
        {
          struct stat buffer; 
          string putative_f_rep_D = germline_system + "D.fa" ;
          if (stat(putative_f_rep_D.c_str(), &buffer) == 0)
504
505
506
507
            {
              f_reps_D.push_back(putative_f_rep_D.c_str()) ;
              delta_min = DEFAULT_DELTA_MIN_D ;
            }
508
        }
509
	f_reps_J.push_back((germline_system + "J.fa").c_str()) ;
510
	germline_system = extract_basename(germline_system);
511

Mikaël Salson's avatar
Mikaël Salson committed
512
513
514
515
	break;

      // Algorithm

516
517
518
519
520
521
522
523
524
525
      case 's':
#ifndef NO_SPACED_SEEDS
	seed = string(optarg);
	k = seed_weight(seed);
	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
526
527
528
      case 'k':
	k = atoi(optarg);
	seed = seed_contiguous(k);
529
	options_s_k++ ;
Mikaël Salson's avatar
Mikaël Salson committed
530
531
532
533
534
535
536
537
538
539
        break;

      case 'w':
	w = atoi(optarg);
        break;

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

540
541
542
543
      case '!':
        keep_unsegmented_as_clone = true;
        break;

544
      case 'e':
545
        expected_value = atof_NO_LIMIT(optarg);
546
547
        break;

548
549
550
551
      case 'E':
        expected_value_D = atof_NO_LIMIT(optarg);
        break;

552
553
      // Output 

Mikaël Salson's avatar
Mikaël Salson committed
554
555
556
557
      case 'o':
        out_dir = optarg ;
        break;

558
559
      case 'b':
        f_basename = optarg;
Mikaël Salson's avatar
Mikaël Salson committed
560
561
        break;

562
563
564
565
      case 'a':
	output_sequences_by_cluster = true;
	break;

Mikaël Salson's avatar
Mikaël Salson committed
566
567
568
569
      case 't':
        trim_sequences = atoi(optarg);
        break;

570
571
572
573
      case 'v':
	verbose += 1 ;
	break;

574
575
      // Limits

Mikaël Salson's avatar
Mikaël Salson committed
576
577
578
579
      case '%':
	ratio_reads_clone = atof(optarg);
	break;

580
      case 'r':
Mikaël Salson's avatar
Mikaël Salson committed
581
582
583
	min_reads_clone = atoi(optarg);
        break;

584
      case 'y':
Mathieu Giraud's avatar
Mathieu Giraud committed
585
	max_representatives = atoi_NO_LIMIT(optarg);
586
587
        break;

Mikaël Salson's avatar
Mikaël Salson committed
588
      case 'z':
Mathieu Giraud's avatar
Mathieu Giraud committed
589
	max_clones = atoi_NO_LIMIT(optarg);
590
591
        if (max_representatives < max_clones)
          max_representatives = max_clones ;
Mikaël Salson's avatar
Mikaël Salson committed
592
        break;
593
594
595

      case 'A': // --all
	ratio_reads_clone = 0 ;
596
597
598
	min_reads_clone = 1 ;
	max_representatives = -1 ;
	max_clones = -1 ;
599
600
	break ;

601
      case 'X':
602
603
604
605
        max_reads_processed_sample = atoi_NO_LIMIT(optarg);
        break;

      case 'x':
Mathieu Giraud's avatar
Mathieu Giraud committed
606
        max_reads_processed = atoi_NO_LIMIT(optarg);
607
        break;
608

609
610
611
      // Labels

      case 'W':
Mathieu Giraud's avatar
Mathieu Giraud committed
612
        windows_labels[string(optarg)] = string("-W");
613
614
        break;

615
616
617
618
      case 'l':
	windows_labels_file = optarg; 
	break;

619
620
621
622
      case 'F':
        only_labeled_windows = true;
        break;

623
      // Clustering
624

625
      case '=':
626
627
	forced_edges = optarg;
	break;
Mikaël Salson's avatar
Mikaël Salson committed
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
	
      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;
	
649
      // Fine segmentation
650
651
652
653
      case '3':
        detect_CDR3 = true;
        break;
        
654
      case 'f':
Mikaël Salson's avatar
Mikaël Salson committed
655
656
	segment_cost=strToCost(optarg, VDJ);
        break;
Mathieu Giraud's avatar
Mathieu Giraud committed
657
658

      case 'u':
659
660
661
        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
662
        break;
663
664
665
      case 'U':
        output_segmented = true;
        break;
666
667
668
      case 'K':
        output_affects = true;
        break;
Mikaël Salson's avatar
Mikaël Salson committed
669
670
      }

671
672
673

  //$$ options: post-processing+display

674
675
676

  if (!germline_system.size() && (command != CMD_GERMLINES))
    {
677
      cerr << ERROR_STRING << "At least one germline must be given with -V/(-D)/-J, or -G, or -g." << endl ;
678
679
680
      exit(1);
    }

681
682
  if (options_s_k > 1)
    {
683
      cerr << ERROR_STRING << "Use at most one -s or -k option." << endl ;
684
685
686
      exit(1);
    }

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

Mikaël Salson's avatar
Mikaël Salson committed
689
690
691
692
693
694
695
696
697
698
699
700
701
  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
    {
702
      cerr << ERROR_STRING << "Wrong number of arguments." << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
703
704
      exit(1);
    }
Mathieu Giraud's avatar
Mathieu Giraud committed
705

706
  size_t min_cover_representative = (size_t) (min_reads_clone < (int) max_auditionned ? min_reads_clone : max_auditionned) ;
707

708
709
710
711
712
713
  // Default seeds

#ifndef NO_SPACED_SEEDS
  if (k == DEFAULT_K)
    {
      if (germline_system.find("TRA") != string::npos)
714
	seed = SEED_S13 ;
715
716
717

      else if ((germline_system.find("TRB") != string::npos)
	       || (germline_system.find("IGH") != string::npos))
718
	seed = SEED_S12 ;
719
      else // TRD, TRG, IGK, IGL, custom, multi
720
	seed = SEED_S10 ;
721
722
723
724
725

      k = seed_weight(seed);
    }
#else
  {
726
    cerr << ERROR_STRING << "Vidjil was compiled with NO_SPACED_SEEDS: please provide a -k option." << endl;
727
728
729
730
731
    exit(1) ;
  }
#endif
	  

Mathieu Giraud's avatar
Mathieu Giraud committed
732
733
734
735
#ifndef NO_SPACED_SEEDS
  // Check seed buffer  
  if (seed.size() >= MAX_SEED_SIZE)
    {
736
      cerr << ERROR_STRING << "Seed size is too large (MAX_SEED_SIZE)." << endl ;
Mathieu Giraud's avatar
Mathieu Giraud committed
737
738
739
740
      exit(1);
    }
#endif

741
742
743

  if (w < seed_weight(seed))
    {
744
      cerr << ERROR_STRING << "Too small -w. The window size should be at least equal to the seed size (" << seed_weight(seed) << ")." << endl;
745
746
747
      exit(1);
    }

Mikaël Salson's avatar
Mikaël Salson committed
748
749
750
751
  // 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) {
752
    cerr << ERROR_STRING << "Directory creation: " << out_dir << endl; perror("");
Mikaël Salson's avatar
Mikaël Salson committed
753
754
755
    exit(2);
  }

Mikaël Salson's avatar
Mikaël Salson committed
756
757
  const char *outseq_cstr = out_seqdir.c_str();
  if (mkpath(outseq_cstr, 0755) == -1) {
758
    cerr << ERROR_STRING << "Directory creation: " << out_seqdir << endl; perror("");
Mikaël Salson's avatar
Mikaël Salson committed
759
760
761
    exit(2);
  }

762
763
764
765
766
  // 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
767
768
769
  out_dir += "/" ;

  /// Load labels ;
770
  load_into_map(windows_labels, windows_labels_file);
Mikaël Salson's avatar
Mikaël Salson committed
771
772

  switch(command) {
Mathieu Giraud's avatar
Mathieu Giraud committed
773
  case CMD_WINDOWS: cout << "Extracting windows" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
774
    break;
775
  case CMD_CLONES: cout << "Analysing clones" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
776
777
778
    break;
  case CMD_SEGMENT: cout << "Segmenting V(D)J" << endl;
    break;
779
780
  case CMD_GERMLINES: cout << "Discovering germlines" << endl;
    break;
Mikaël Salson's avatar
Mikaël Salson committed
781
782
  }

Mathieu Giraud's avatar
Mathieu Giraud committed
783
  cout << "Command line: ";
Mikaël Salson's avatar
Mikaël Salson committed
784
  for (int i=0; i < argc; i++) {
Mathieu Giraud's avatar
Mathieu Giraud committed
785
    cout << argv[i] << " ";
Mikaël Salson's avatar
Mikaël Salson committed
786
  }
Mathieu Giraud's avatar
Mathieu Giraud committed
787
  cout << endl;
Mikaël Salson's avatar
Mikaël Salson committed
788
789
790
791
792
793
794
795
796
797
798
799

  //////////////////////////////////
  // 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
800
  cout << "# " << time_buffer << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
801
802


803
804
  //////////////////////////////////
  // Warning for non-optimal use
805

806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
  if (max_clones == -1 || max_clones > WARN_MAX_CLONES)
    {
      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 ;
    }
  
  if (max_clones == -1 || max_clones > WARN_MAX_CLONES || command == CMD_SEGMENT)
    {
      cout << "* Vidjil purpose is to extract very quickly windows overlapping the CDR3" << endl
	   << "* and to gather reads into clones (-c clones), and not to provide an accurate V(D)J segmentation." << endl
822
	   << "* The full V(D)J designations are slow to compute and are provided only for convenience." << endl
823
824
825
	   << "* More information is provided in the 'doc/algo.org' file." << endl 
	   << endl ;
    }
826

827
828
829
  /////////////////////////////////////////
  //            LOAD GERMLINES           //
  /////////////////////////////////////////
830

831
832
833
834
  if (command == CMD_GERMLINES)
    {
      multi_germline = true ;
      multi_germline_one_index_per_germline = false ;
835
836
837

      if (multi_germline_paths_and_files.size() == 0)
        multi_germline_paths_and_files.push_back(make_pair(DEFAULT_MULTI_GERMLINE_PATH, DEFAULT_MULTI_GERMLINE_FILE));
838
839
840
    }

  MultiGermline *multigermline = new MultiGermline(multi_germline_one_index_per_germline);
841

842
    {
843
      cout << "Load germlines and build Kmer indexes" << endl ;
844
845
846
    
      if (multi_germline)
	{
847
848
          for (pair <string, string> path_file: multi_germline_paths_and_files)
            multigermline->build_from_json(path_file.first, path_file.second, GERMLINES_REGULAR, trim_sequences);
849
850
851
852
853
854
	}
      else
	{
	  // Custom germline
	  Germline *germline;
	  germline = new Germline(germline_system, 'X',
855
                                  f_reps_V, f_reps_D, f_reps_J, 
856
                                  delta_min, trim_sequences);
857

858
          germline->new_index(seed);
859

860
861
862
	  multigermline->insert(germline);
	}
    }
863

864
    cout << endl ;
865

866
    if (!multi_germline_one_index_per_germline) {
867
      multigermline->build_with_one_index(seed, true);
868
    }
869

870
      if (multi_germline_unexpected_recombinations_12 || multi_germline_unexpected_recombinations_1U) {
871
872
873
        if (!multigermline->index) {
          multigermline->build_with_one_index(seed, false);
        }
874
      }
875

876
      if (multi_germline_unexpected_recombinations_12) {
877
878
        Germline *pseudo = new Germline("xxx", 'x', -10, trim_sequences);
        pseudo->seg_method = SEG_METHOD_MAX12 ;
879
880
        pseudo->index = multigermline->index ;
        multigermline->germlines.push_back(pseudo);
881
882
883
      }

      if (multi_germline_unexpected_recombinations_1U) {
884
        Germline *pseudo_u = new Germline("xxx", 'x', -10, trim_sequences);
885
        pseudo_u->seg_method = SEG_METHOD_MAX1U ;
886
887
888
        // TODO: there should be more up/downstream regions for the 'yyy' germline. And/or smaller seeds ?
        pseudo_u->index = multigermline->index ;
        multigermline->germlines.push_back(pseudo_u);
889
890
    }

891
892
893
      // Should come after the initialization of regular (and possibly pseudo) germlines
    if (multi_germline_incomplete) {
      multigermline->one_index_per_germline = true; // Starting from now, creates new indexes
894
895
896

      for (pair <string, string> path_file: multi_germline_paths_and_files)
        multigermline->build_from_json(path_file.first, path_file.second, GERMLINES_INCOMPLETE, trim_sequences);
897
898
    }

899
900
901
    if (multi_germline_mark)
      multigermline->mark_cross_germlines_as_ambiguous();
    
902
903
904
    cout << "Germlines loaded" << endl ;
    cout << *multigermline ;
    cout << endl ;
905
906

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

909
    
910
911
  //////////////////////////////////
  //$$ Read sequence files
912
913
914
915
916

    int only_nth_read = 1 ;
    if (max_reads_processed_sample != NO_LIMIT_VALUE)
      {
        only_nth_read = nb_sequences_in_fasta(f_reads) / max_reads_processed_sample;
917
918
919
        if (only_nth_read == 0)
          only_nth_read = 1 ;

920
        max_reads_processed = max_reads_processed_sample ;
921
922
923
924
925

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

928
929
930
  OnlineFasta *reads;

  try {
931
    reads = new OnlineFasta(f_reads, 1, read_header_separator, max_reads_processed, only_nth_read);
932
  } catch (const invalid_argument e) {
933
    cerr << ERROR_STRING << "Vidjil cannot open reads file " << f_reads << ": " << e.what() << endl;
934
935
936
937
938
939
    exit(1);
  }

  out_dir += "/";


940
941
942
943
944
  //////////////////////////////://////////
  //         DISCOVER GERMLINES          //
  /////////////////////////////////////////
  if (command == CMD_GERMLINES)
    {
945
      map <char, int> stats_kmer, stats_max;
946
      IKmerStore<KmerAffect> *index = multigermline->index ;
947
948

      // Initialize statistics, with two additional categories
949
950
      index->labels.push_back(make_pair(KmerAffect::getAmbiguous(), FASTA_AMBIGUOUS));
      index->labels.push_back(make_pair(KmerAffect::getUnknown(), FASTA_UNKNOWN));
951
      
952
      for (list< pair <KmerAffect, Fasta> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
953
	{
954
955
956
	  char key = affect_char(it->first.affect) ;
	  stats_kmer[key] = 0 ;
	  stats_max[key] = 0 ;
957
958
	}
      
959
      // init forbidden for .max()
960
961
962
      set<KmerAffect> forbidden;
      forbidden.insert(KmerAffect::getAmbiguous());
      forbidden.insert(KmerAffect::getUnknown());
963
      
964
965
966
      // Loop through all reads

      int nb_reads = 0 ;
967
968
969
      int total_length = 0 ;
      int s = index->getS();

970
971
972
973
974
      while (reads->hasNext())
	{
	  reads->next();
	  nb_reads++;
	  string seq = reads->getSequence().sequence;
975
	  total_length += seq.length() - s + 1;
Mathieu Giraud's avatar