vidjil.cpp 47.7 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1
/*
2
3
4
5
6
7
8
  This file is part of Vidjil <http://www.vidjil.org>
  Copyright (C) 2011, 2012, 2013, 2014, 2015 by Bonsai bioinformatics 
  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
57
58
59
60
61

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

62
63
64
// 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"

65
#define VIDJIL_JSON_VERSION "2014.10"
Mikaël Salson's avatar
Mikaël Salson committed
66

Mathieu Giraud's avatar
Mathieu Giraud committed
67
68
//$$ #define (mainly default options)

69
#define DEFAULT_MULTIGERMLINE "germline"
Mikaël Salson's avatar
Mikaël Salson committed
70

Mathieu Giraud's avatar
Mathieu Giraud committed
71
#define DEFAULT_READS  "./data/Stanford_S22.fasta"
72
#define DEFAULT_MIN_READS_CLONE 5
73
#define DEFAULT_MAX_REPRESENTATIVES 100
74
75
#define DEFAULT_MAX_CLONES 20
#define DEFAULT_RATIO_READS_CLONE 0.0
76
#define NO_LIMIT "all"
Mikaël Salson's avatar
Mikaël Salson committed
77

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

85
86
87
#define DEFAULT_OUT_DIR "./out/" 

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

// "tests/data/leukemia.fa" 

100
#define DEFAULT_K      0
101
#define DEFAULT_W      50
102
#define DEFAULT_SEED   ""
Mikaël Salson's avatar
Mikaël Salson committed
103
104

#define DEFAULT_DELTA_MIN  -10
Mathieu Giraud's avatar
Mathieu Giraud committed
105
#define DEFAULT_DELTA_MAX   20
Mikaël Salson's avatar
Mikaël Salson committed
106
107

#define DEFAULT_DELTA_MIN_D  0
108
#define DEFAULT_DELTA_MAX_D  80
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
120
121
// error
#define ERROR_STRING "[error] "

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

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

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

using namespace std ;

Mathieu Giraud's avatar
Mathieu Giraud committed
133
//$$ options: usage
Mikaël Salson's avatar
Mikaël Salson committed
134

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

extern int optind, optopt, opterr;

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

  cerr << "Command selection" << endl
144
145
146
147
148
       << "  -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
       << "  \t\t" << COMMAND_SEGMENT   << "  \t detailed V(D)J segmentation (not recommended)" << endl
       << "  \t\t" << COMMAND_GERMLINES << "  \t statistics on k-mers in different germlines" << endl
Mikaël Salson's avatar
Mikaël Salson committed
149
150
       << endl       

151
       << "Germline databases (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
152
       << "  -V <file>     V germline multi-fasta file" << endl
153
       << "  -D <file>     D germline multi-fasta file (and resets -m, -M and -w options), will segment into V(D)J components" << endl
Mikaël Salson's avatar
Mikaël Salson committed
154
       << "  -J <file>     J germline multi-fasta file" << endl
155
       << "  -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
156
       << "  -g <path>     multiple germlines (in the path <path>, takes TRA, TRB, TRG, TRD, IGH, IGK and IGL and sets window prediction parameters)" << endl
157
       << "  -i            multiple germlines, also incomplete rearrangements (must be used with -g)" << endl
158
       << endl ;
159

160
161
  if (advanced)
  cerr << "Experimental options (do not use)" << endl
162
       << "  -I            ignore k-mers common to different germline systems (experimental, must be used with -g, do not use)" << endl
163
       << "  -1            use a unique index for all germline systems (experimental, must be used with -g, do not use)" << endl
164
       << "  -2            try to detect unexpected recombinations (experimental, must be used with -g, do not use)" << endl
165
       << "  -!            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
166
167
       << endl

Mathieu Giraud's avatar
Mathieu Giraud committed
168
       << "Window prediction" << endl
Mikaël Salson's avatar
Mikaël Salson committed
169
#ifndef NO_SPACED_SEEDS
170
       << "  (use either -s or -k option, but not both)" << endl
171
       << "  (all these options, except -w, are overriden when using -g)" << endl
172
173
       << "  -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
174
#endif
175
       << "  -k <int>      k-mer size used for the V/J affectation (default: 10, 12, 13, depends on germline)" << endl
176
177
178
#ifndef NO_SPACED_SEEDS
       << "                (using -k option is equivalent to set with -s a contiguous seed with only '#' characters)" << endl
#endif
179
180
       << "  -m <int>      minimal admissible delta between last V and first J k-mer (default: " << DEFAULT_DELTA_MIN << ") (default with -D: " << DEFAULT_DELTA_MIN_D << ")" << endl
       << "  -M <int>      maximal admissible delta between last V and first J k-mer (default: " << DEFAULT_DELTA_MAX << ") (default with -D: " << DEFAULT_DELTA_MAX_D << ")" << endl
181
       << "  -w <int>      w-mer size used for the length of the extracted window (default: " << DEFAULT_W << ")" << endl
182
       << "  -e <float>    maximal e-value for determining if a segmentation can be trusted (default: " << THRESHOLD_NB_EXPECTED << ")" << endl
Mikaël Salson's avatar
Mikaël Salson committed
183
184
       << endl

Mathieu Giraud's avatar
Mathieu Giraud committed
185
       << "Window annotations" << endl
186
       << "  -l <file>     labels for some windows -- these windows will be kept even if -r/-% thresholds are not reached" << endl
187
       << "  -F            filter -- keep only the labeled windows" << endl
188
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
189

190
  cerr << "Limits to report a clone (or a window)" << endl
191
192
       << "  -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
193
194
       << endl

195
       << "Limits to further analyze some clones" << endl
196
       << "  -y <nb>       maximal number of clones computed with a representative ('" << NO_LIMIT << "': no limit) (default: " << DEFAULT_MAX_REPRESENTATIVES << ")" << endl
197
       << "  -z <nb>       maximal number of clones to be segmented ('" << NO_LIMIT << "': no limit, do not use) (default: " << DEFAULT_MAX_CLONES << ")" << endl
198
       << "  -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
199
200
       << "  -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
201
       << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
202

203
204
  if (advanced)
  cerr << "Fine segmentation options (second pass, see warning in doc/algo.org)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
205
       << "  -f <string>   use custom Cost for fine segmenter : format \"match, subst, indels, homo, del_end\" (default "<<VDJ<<" )"<< endl
206
       << "  -3            CDR3 detection (experimental)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
207
208
       << endl

209
       << "Additional clustering (experimental)" << endl
210
       << "  -E <file>     manual clustering -- a file used to force some specific edges" << endl
211
212
213
214
215
       << "  -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
216
       << endl ;
217

218
  cerr << "Detailed output per read (not recommended, large files)" << endl
219
220
       << "  -U            output segmented reads (in " << SEGMENTED_FILENAME << " file)" << endl
       << "  -u            output unsegmented reads (in " << UNSEGMENTED_FILENAME << " file)" << endl
221
       << "  -K            output detailed k-mer affectation on all reads (in " << AFFECTS_FILENAME << " file) (use only for debug, for example -KX 100)" << endl
222
223
       << endl
 
Mikaël Salson's avatar
Mikaël Salson committed
224
       << "Output" << endl
225
       << "  -o <dir>      output directory (default: " << DEFAULT_OUT_DIR << ")" <<  endl
226
       << "  -b <string>   output basename (by default basename of the input file)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
227
    
228
       << "  -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
229
230
231
       << "  -v            verbose mode" << endl
       << endl        

232
233
       << "  -h            help" << endl
       << "  -H            help, including experimental and advanced options" << endl
234
235
236
       << "The full help is available in the doc/algo.org file."
       << endl

Mikaël Salson's avatar
Mikaël Salson committed
237
       << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
238
       << "Examples (see doc/algo.org)" << endl
Mathieu Giraud's avatar
Mathieu Giraud committed
239
       << "  " << progname << " -c clones   -G germline/IGH  -r 5          data/Stanford_S22.fasta" << endl
240
241
       << "  " << progname << " -c clones   -g germline      -r 5          data/Stanford_S22.fasta   # (detect the locus for each read)" << endl
       << "  " << progname << " -c windows  -g germline      -u -U         data/Stanford_S22.fasta   # (detect the locus, splits the reads into two (large) files)" << endl
Mathieu Giraud's avatar
Mathieu Giraud committed
242
       << "  " << progname << " -c segment  -G germline/IGH                data/Stanford_S22.fasta   # (only for testing)" << endl
243
       << "  " << progname << " -c germlines                               data/Stanford_S22.fasta" << endl
Mikaël Salson's avatar
Mikaël Salson committed
244
245
246
247
    ;
  exit(1);
}

Mathieu Giraud's avatar
Mathieu Giraud committed
248
249
250

int atoi_NO_LIMIT(char *optarg)
{
251
252
  return strcmp(NO_LIMIT, optarg) ? atoi(optarg) : NO_LIMIT_VALUE ;
}
253
double atof_NO_LIMIT(char *optarg)
254
255
{
  return strcmp(NO_LIMIT, optarg) ? atof(optarg) : NO_LIMIT_VALUE ;
Mathieu Giraud's avatar
Mathieu Giraud committed
256
257
}

Mikaël Salson's avatar
Mikaël Salson committed
258
259
int main (int argc, char **argv)
{
260
  cout << "# Vidjil -- V(D)J recombinations analysis <http://www.vidjil.org/>" << endl
261
262
       << "# Copyright (C) 2011, 2012, 2013, 2014, 2015 by the Vidjil team" << endl
       << "# Bonsai bioinformatics at CRIStAL (UMR CNRS 9189, Université Lille) and Inria Lille" << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
263
264
265
266
267
       << 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
268
269
       << endl
       << "# Please cite http://biomedcentral.com/1471-2164/15/409 if you use Vidjil." 
Mikaël Salson's avatar
Mikaël Salson committed
270
271
       << endl ;

Mathieu Giraud's avatar
Mathieu Giraud committed
272
273
  //$$ options: defaults

274
  string germline_system = "" ;
275
276
277
278
279
  
  list <string> f_reps_V ;
  list <string> f_reps_D ;
  list <string> f_reps_J ;

Mikaël Salson's avatar
Mikaël Salson committed
280
281
  string f_reads = DEFAULT_READS ;
  string seed = DEFAULT_SEED ;
282
  string f_basename = "";
Mikaël Salson's avatar
Mikaël Salson committed
283

284
  string out_dir = DEFAULT_OUT_DIR;
Mikaël Salson's avatar
Mikaël Salson committed
285
286
287
288
  
  string comp_filename = COMP_FILENAME;

  int k = DEFAULT_K ;
289
  int w = DEFAULT_W ;
Mikaël Salson's avatar
Mikaël Salson committed
290

Mikaël Salson's avatar
Mikaël Salson committed
291
292
293
294
  int epsilon = DEFAULT_EPSILON ;
  int minPts = DEFAULT_MINPTS ;
  Cost cluster_cost = DEFAULT_CLUSTER_COST ;
  Cost segment_cost = DEFAULT_SEGMENT_COST ;
295
  bool detect_CDR3 = false;
Mikaël Salson's avatar
Mikaël Salson committed
296
297
298
299
300
  
  int save_comp = 0;
  int load_comp = 0;
  
  int verbose = 0 ;
301
  int command = CMD_CLONES;
Mikaël Salson's avatar
Mikaël Salson committed
302

303
  int max_representatives = DEFAULT_MAX_REPRESENTATIVES ;
304
305
306
  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
307
308
  // int average_deletion = 4;     // Average number of deletion in V or J

309
  int max_reads_processed = -1;
310
  int max_reads_processed_sample = -1;
311

Mathieu Giraud's avatar
Mathieu Giraud committed
312
  float ratio_representative = DEFAULT_RATIO_REPRESENTATIVE;
Mikaël Salson's avatar
Mikaël Salson committed
313
  unsigned int max_auditionned = DEFAULT_MAX_AUDITIONED;
Mathieu Giraud's avatar
Mathieu Giraud committed
314

Mikaël Salson's avatar
Mikaël Salson committed
315
316
317
318
319
  // Admissible delta between left and right segmentation points
  int delta_min = DEFAULT_DELTA_MIN ; // Kmer+Fine
  int delta_max = DEFAULT_DELTA_MAX ; // Fine

  bool output_sequences_by_cluster = false;
320
  bool output_segmented = false;
Mathieu Giraud's avatar
Mathieu Giraud committed
321
  bool output_unsegmented = false;
322
  bool output_affects = false;
323
324
  bool keep_unsegmented_as_clone = false;

325
  bool multi_germline = false;
326
  bool multi_germline_incomplete = false;
327
  bool multi_germline_mark = false;
328
  bool multi_germline_one_index_per_germline = true;
329
  bool multi_germline_unexpected_recombinations = false;
330
  string multi_germline_file = DEFAULT_MULTIGERMLINE;
Mikaël Salson's avatar
Mikaël Salson committed
331
332
333

  string forced_edges = "" ;

334
  map <string, string> windows_labels ;
Mathieu Giraud's avatar
Mathieu Giraud committed
335
  string windows_labels_file = "" ;
336
  bool only_labeled_windows = false ;
Mikaël Salson's avatar
Mikaël Salson committed
337
338
339

  char c ;

340
341
  int options_s_k = 0 ;

342
343
  double expected_value = THRESHOLD_NB_EXPECTED;

WebTogz's avatar
WebTogz committed
344
345
346
  //JsonArray which contains the Levenshtein distances
  JsonArray jsonLevenshtein;

Mathieu Giraud's avatar
Mathieu Giraud committed
347
348
  //$$ options: getopt

349

350
  while ((c = getopt(argc, argv, "A!x:X:hHaiI12g:G:V:D:J:k:r:vw:e:C:f:l:Fc:m:M:N:s:b:Sn:o:L%:y:z:uUK3E:")) != EOF)
Mikaël Salson's avatar
Mikaël Salson committed
351
352
353
354

    switch (c)
      {
      case 'h':
355
356
357
358
        usage(argv[0], false);

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

Mikaël Salson's avatar
Mikaël Salson committed
360
      case 'c':
361
362
        if (!strcmp(COMMAND_CLONES,optarg))
          command = CMD_CLONES;
Mikaël Salson's avatar
Mikaël Salson committed
363
364
        else if (!strcmp(COMMAND_SEGMENT,optarg))
          command = CMD_SEGMENT;
Mathieu Giraud's avatar
Mathieu Giraud committed
365
366
        else if (!strcmp(COMMAND_WINDOWS,optarg))
          command = CMD_WINDOWS;
367
368
        else if (!strcmp(COMMAND_GERMLINES,optarg))
          command = CMD_GERMLINES;
Mikaël Salson's avatar
Mikaël Salson committed
369
370
        else {
          cerr << "Unknwown command " << optarg << endl;
371
	  usage(argv[0], false);
Mikaël Salson's avatar
Mikaël Salson committed
372
373
        }
        break;
374

Mikaël Salson's avatar
Mikaël Salson committed
375
376
377
378

      // Germline

      case 'V':
379
	f_reps_V.push_back(optarg);
380
	germline_system = "custom" ;
Mikaël Salson's avatar
Mikaël Salson committed
381
382
383
	break;

      case 'D':
384
	f_reps_D.push_back(optarg);
385
386
	delta_min = DEFAULT_DELTA_MIN_D ;
	delta_max = DEFAULT_DELTA_MAX_D ;
Mikaël Salson's avatar
Mikaël Salson committed
387
388
389
	break;
        
      case 'J':
390
	f_reps_J.push_back(optarg);
391
	germline_system = "custom" ;
Mikaël Salson's avatar
Mikaël Salson committed
392
393
	break;

394
      case 'g':
395
396
	multi_germline = true;
	multi_germline_file = string(optarg);
397
	germline_system = "multi" ;
398
	break;
399
400
401
402

      case 'i':
	multi_germline_incomplete = true;
	break;
403
404
405
406

      case 'I':
        multi_germline_mark = true;
	break;
407
408
409
410

      case '1':
        multi_germline_one_index_per_germline = false ;
        break;
411
412
413
414
415

      case '2':
        multi_germline_unexpected_recombinations = true ;
        break;

Mikaël Salson's avatar
Mikaël Salson committed
416
      case 'G':
Mikaël Salson's avatar
Mikaël Salson committed
417
	germline_system = string(optarg);
418
	f_reps_V.push_back((germline_system + "V.fa").c_str()) ;
419
420
421
422
423
        // 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)
424
425
426
427
428
            {
              f_reps_D.push_back(putative_f_rep_D.c_str()) ;
              delta_min = DEFAULT_DELTA_MIN_D ;
              delta_max = DEFAULT_DELTA_MAX_D ;
            }
429
        }
430
	f_reps_J.push_back((germline_system + "J.fa").c_str()) ;
431
	germline_system = extract_basename(germline_system);
432

Mikaël Salson's avatar
Mikaël Salson committed
433
434
435
436
	break;

      // Algorithm

437
438
439
440
441
442
443
444
445
446
      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
447
448
449
      case 'k':
	k = atoi(optarg);
	seed = seed_contiguous(k);
450
	options_s_k++ ;
Mikaël Salson's avatar
Mikaël Salson committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
        break;

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

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

      case 'M':
	delta_max = atoi(optarg);
        break;

465
466
467
468
      case '!':
        keep_unsegmented_as_clone = true;
        break;

469
      case 'e':
470
        expected_value = atof_NO_LIMIT(optarg);
471
472
        break;

473
474
      // Output 

Mikaël Salson's avatar
Mikaël Salson committed
475
476
477
478
      case 'o':
        out_dir = optarg ;
        break;

479
480
      case 'b':
        f_basename = optarg;
Mikaël Salson's avatar
Mikaël Salson committed
481
482
        break;

483
484
485
486
487
488
489
490
      case 'a':
	output_sequences_by_cluster = true;
	break;

      case 'v':
	verbose += 1 ;
	break;

491
492
      // Limits

Mikaël Salson's avatar
Mikaël Salson committed
493
494
495
496
      case '%':
	ratio_reads_clone = atof(optarg);
	break;

497
      case 'r':
Mikaël Salson's avatar
Mikaël Salson committed
498
499
500
	min_reads_clone = atoi(optarg);
        break;

501
      case 'y':
Mathieu Giraud's avatar
Mathieu Giraud committed
502
	max_representatives = atoi_NO_LIMIT(optarg);
503
504
        break;

Mikaël Salson's avatar
Mikaël Salson committed
505
      case 'z':
Mathieu Giraud's avatar
Mathieu Giraud committed
506
	max_clones = atoi_NO_LIMIT(optarg);
Mikaël Salson's avatar
Mikaël Salson committed
507
        break;
508
509
510

      case 'A': // --all
	ratio_reads_clone = 0 ;
511
512
513
	min_reads_clone = 1 ;
	max_representatives = -1 ;
	max_clones = -1 ;
514
515
	break ;

516
      case 'X':
517
518
519
520
        max_reads_processed_sample = atoi_NO_LIMIT(optarg);
        break;

      case 'x':
Mathieu Giraud's avatar
Mathieu Giraud committed
521
        max_reads_processed = atoi_NO_LIMIT(optarg);
522
        break;
523

524
525
526
527
      case 'l':
	windows_labels_file = optarg; 
	break;

528
529
530
531
      case 'F':
        only_labeled_windows = true;
        break;

532
      // Clustering
533

534
      case 'E':
535
536
	forced_edges = optarg;
	break;
Mikaël Salson's avatar
Mikaël Salson committed
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
	
      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;
	
558
      // Fine segmentation
559
560
561
562
      case '3':
        detect_CDR3 = true;
        break;
        
563
      case 'f':
Mikaël Salson's avatar
Mikaël Salson committed
564
565
	segment_cost=strToCost(optarg, VDJ);
        break;
Mathieu Giraud's avatar
Mathieu Giraud committed
566
567
568
569

      case 'u':
        output_unsegmented = true;
        break;
570
571
572
      case 'U':
        output_segmented = true;
        break;
573
574
575
      case 'K':
        output_affects = true;
        break;
Mikaël Salson's avatar
Mikaël Salson committed
576
577
      }

578
579
580

  //$$ options: post-processing+display

581
582
583

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

588
589
  if (options_s_k > 1)
    {
590
      cerr << ERROR_STRING << "Use at most one -s or -k option." << endl ;
591
592
593
      exit(1);
    }

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

Mikaël Salson's avatar
Mikaël Salson committed
596
597
598
599
600
601
602
603
604
605
606
607
608
  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
    {
609
      cerr << ERROR_STRING << "Wrong number of arguments." << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
610
611
      exit(1);
    }
Mathieu Giraud's avatar
Mathieu Giraud committed
612

613
  size_t min_cover_representative = (size_t) (min_reads_clone < (int) max_auditionned ? min_reads_clone : max_auditionned) ;
614

615
616
617
618
619
620
  // Default seeds

#ifndef NO_SPACED_SEEDS
  if (k == DEFAULT_K)
    {
      if (germline_system.find("TRA") != string::npos)
621
	seed = SEED_S13 ;
622
623
624

      else if ((germline_system.find("TRB") != string::npos)
	       || (germline_system.find("IGH") != string::npos))
625
	seed = SEED_S12 ;
626
      else // TRD, TRG, IGK, IGL, custom, multi
627
	seed = SEED_S10 ;
628
629
630
631
632

      k = seed_weight(seed);
    }
#else
  {
633
    cerr << ERROR_STRING << "Vidjil was compiled with NO_SPACED_SEEDS: please provide a -k option." << endl;
634
635
636
637
638
    exit(1) ;
  }
#endif
	  

Mathieu Giraud's avatar
Mathieu Giraud committed
639
640
641
642
#ifndef NO_SPACED_SEEDS
  // Check seed buffer  
  if (seed.size() >= MAX_SEED_SIZE)
    {
643
      cerr << ERROR_STRING << "Seed size is too large (MAX_SEED_SIZE)." << endl ;
Mathieu Giraud's avatar
Mathieu Giraud committed
644
645
646
647
      exit(1);
    }
#endif

648
649
650

  if (w < seed_weight(seed))
    {
651
      cerr << ERROR_STRING << "Too small -w. The window size should be at least equal to the seed size (" << seed_weight(seed) << ")." << endl;
652
653
654
      exit(1);
    }

Mikaël Salson's avatar
Mikaël Salson committed
655
656
657
658
  // 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) {
659
    cerr << ERROR_STRING << "Directory creation: " << out_dir << endl; perror("");
Mikaël Salson's avatar
Mikaël Salson committed
660
661
662
    exit(2);
  }

Mikaël Salson's avatar
Mikaël Salson committed
663
664
  const char *outseq_cstr = out_seqdir.c_str();
  if (mkpath(outseq_cstr, 0755) == -1) {
665
    cerr << ERROR_STRING << "Directory creation: " << out_seqdir << endl; perror("");
Mikaël Salson's avatar
Mikaël Salson committed
666
667
668
    exit(2);
  }

669
670
671
672
673
  // 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
674
675
676
  out_dir += "/" ;

  /// Load labels ;
677
  load_into_map(windows_labels, windows_labels_file);
Mikaël Salson's avatar
Mikaël Salson committed
678
679

  switch(command) {
Mathieu Giraud's avatar
Mathieu Giraud committed
680
  case CMD_WINDOWS: cout << "Extracting windows" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
681
    break;
682
  case CMD_CLONES: cout << "Analysing clones" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
683
684
685
    break;
  case CMD_SEGMENT: cout << "Segmenting V(D)J" << endl;
    break;
686
687
  case CMD_GERMLINES: cout << "Discovering germlines" << endl;
    break;
Mikaël Salson's avatar
Mikaël Salson committed
688
689
  }

Mathieu Giraud's avatar
Mathieu Giraud committed
690
  cout << "Command line: ";
Mikaël Salson's avatar
Mikaël Salson committed
691
  for (int i=0; i < argc; i++) {
Mathieu Giraud's avatar
Mathieu Giraud committed
692
    cout << argv[i] << " ";
Mikaël Salson's avatar
Mikaël Salson committed
693
  }
Mathieu Giraud's avatar
Mathieu Giraud committed
694
  cout << endl;
Mikaël Salson's avatar
Mikaël Salson committed
695
696
697
698
699
700
701
702
703
704
705
706

  //////////////////////////////////
  // 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
707
  cout << "# " << time_buffer << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
708
709
710
711
712


  //////////////////////////////////
  // Display version information or git log

713
  string soft_version = "vidjil ";
Mikaël Salson's avatar
Mikaël Salson committed
714
#ifdef RELEASE_TAG
Mathieu Giraud's avatar
Mathieu Giraud committed
715
  cout << "# version: vidjil " << RELEASE_TAG << endl ;
716
  soft_version.append(RELEASE_TAG);
Mikaël Salson's avatar
Mikaël Salson committed
717
#else
718
719
720
  cout << "# development version" << endl ;
#ifdef GIT_VERSION
  cout << "# git: " << GIT_VERSION << endl ;
721
  soft_version.append("dev ");
722
  soft_version.append(GIT_VERSION);
723
#endif
724
#endif
725

726
727
  //////////////////////////////////
  // Warning for non-optimal use
728

729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
  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
	   << "* The following segmentations are slow to compute and are provided only for convenience." << endl
	   << "* They should be checked with other softwares such as IgBlast, iHHMune-align or IMGT/V-QUEST." << endl 
	   << "* More information is provided in the 'doc/algo.org' file." << endl 
	   << endl ;
    }
750

751
752
753
  /////////////////////////////////////////
  //            LOAD GERMLINES           //
  /////////////////////////////////////////
754

755
756
757
758
759
760
761
  if (command == CMD_GERMLINES)
    {
      multi_germline = true ;
      multi_germline_one_index_per_germline = false ;
    }

  MultiGermline *multigermline = new MultiGermline(multi_germline_one_index_per_germline);
762

763
    {
764
      cout << "Load germlines and build Kmer indexes" << endl ;
765
766
767
768
769
770
771
772
773
774
    
      if (multi_germline)
	{
	  multigermline->build_default_set(multi_germline_file);
	}
      else
	{
	  // Custom germline
	  Germline *germline;
	  germline = new Germline(germline_system, 'X',
775
776
777
                                  f_reps_V, f_reps_D, f_reps_J, 
                                  delta_min, delta_max);

778
          germline->new_index(seed);
779

780
781
782
	  multigermline->insert(germline);
	}
    }
783

784
    cout << endl ;
785

786
    if (!multi_germline_one_index_per_germline) {
787
      multigermline->build_with_one_index(seed, true);
788
    }
789

790
      if (multi_germline_unexpected_recombinations) {
791
792
793
794
        if (!multigermline->index) {
          multigermline->build_with_one_index(seed, false);
        }

795
796
797
798
799
        Germline *pseudo = new Germline(PSEUDO_GERMLINE_MAX12, 'x', -10, 80);
        pseudo->index = multigermline->index ;
        multigermline->germlines.push_back(pseudo);
    }

800
801
802
803
804
805
      // 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
      multigermline->build_incomplete_set(multi_germline_file);
    }

806
807
808
    if (multi_germline_mark)
      multigermline->mark_cross_germlines_as_ambiguous();
    
809
810
811
    cout << "Germlines loaded" << endl ;
    cout << *multigermline ;
    cout << endl ;
812
813
814
815

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

816
    
817
818
819
820
821
822
823
  //////////////////////////////////
  //$$ Read sequence files
 
  OnlineFasta *reads;

  try {
    reads = new OnlineFasta(f_reads, 1, " ");
824
  } catch (const invalid_argument e) {
825
    cerr << ERROR_STRING << "Vidjil cannot open reads file " << f_reads << ": " << e.what() << endl;
826
827
828
829
830
831
    exit(1);
  }

  out_dir += "/";


832
833
834
835
836
  //////////////////////////////://////////
  //         DISCOVER GERMLINES          //
  /////////////////////////////////////////
  if (command == CMD_GERMLINES)
    {
837
      map <char, int> stats_kmer, stats_max;
838
      IKmerStore<KmerAffect> *index = multigermline->index ;
839
840

      // Initialize statistics, with two additional categories
841
842
      index->labels.push_back(make_pair(KmerAffect::getAmbiguous(), AFFECT_AMBIGUOUS_SYMBOL));
      index->labels.push_back(make_pair(KmerAffect::getUnknown(), AFFECT_UNKNOWN_SYMBOL));
843
844
      
      for (list< pair <KmerAffect, string> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
845
	{
846
847
848
	  char key = affect_char(it->first.affect) ;
	  stats_kmer[key] = 0 ;
	  stats_max[key] = 0 ;
849
850
	}
      
851
      // init forbidden for .max()
852
853
854
      set<KmerAffect> forbidden;
      forbidden.insert(KmerAffect::getAmbiguous());
      forbidden.insert(KmerAffect::getUnknown());
855
      
856
857
858
      // Loop through all reads

      int nb_reads = 0 ;
859
860
861
      int total_length = 0 ;
      int s = index->getS();

862
863
864
865
866
      while (reads->hasNext())
	{
	  reads->next();
	  nb_reads++;
	  string seq = reads->getSequence().sequence;
867
	  total_length += seq.length() - s + 1;
868

869
	  KmerAffectAnalyser *kaa = new KmerAffectAnalyser(*index, seq);
870
871
872

	  for (int i = 0; i < kaa->count(); i++) 
	    { 
873
874
	      KmerAffect ksa = kaa->getAffectation(i);
	      stats_kmer[affect_char(ksa.affect)]++ ;
875
	    }
876

877
          delete kaa;
878

879
	  CountKmerAffectAnalyser ckaa(*index, seq);
880
881
	  ckaa.setAllowedOverlap(k-1);

882
	  stats_max[affect_char(ckaa.max(forbidden).affect)]++ ;
883

884
885
	}

886
887
      delete reads;

888
889
      // Display statistics

890
891
892
893
      cout << "  <== "
	   << nb_reads << " reads, "
	   << total_length << " kmers"
	   << endl ;
894
      cout << "\t" << " max" << "\t\t" << "        kmers" << "\n" ;
895
896

      for (list< pair <KmerAffect, string> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
897
	{
898
899
900
901
	  char key = affect_char(it->first.affect) ;
	  
	  cout << setw(12) << stats_max[key] << " " ;
	  cout << setw(6) << fixed << setprecision(2) <<  (float) stats_max[key] / nb_reads * 100 << "%" ;
902

903
	  cout << "     " ;
904

905
906
	  cout << setw(12) << stats_kmer[key] << " " ;
	  cout << setw(6) << fixed << setprecision(2) <<  (float) stats_kmer[key] / total_length * 100 << "%" ;
907

908
	  cout << "     " << key << " " << it->second << endl ;
909
	}
910
911
      
      delete index;
912
913
914
915
      exit(0);
    }


Mikaël Salson's avatar
Mikaël Salson committed
916
917
918
  ////////////////////////////////////////
  //           CLONE ANALYSIS           //
  ////////////////////////////////////////
919
  if (command == CMD_CLONES || command == CMD_WINDOWS) {
Mikaël Salson's avatar
Mikaël Salson committed
920
921

    //////////////////////////////////
Mathieu Giraud's avatar
Mathieu Giraud committed
922
    //$$ Kmer Segmentation
Mikaël Salson's avatar
Mikaël Salson committed
923

924
925
926
927
928
929
930
931
    int only_nth_read = 1 ;
    if (max_reads_processed_sample > 0)
      {
        only_nth_read = nb_sequences_in_fasta(f_reads) / max_reads_processed_sample;
        max_reads_processed = max_reads_processed_sample ;
        cout << "Processing every " << only_nth_read << "th read" << endl ;
      }

Mathieu Giraud's avatar
Mathieu Giraud committed
932
933
    cout << endl;
    cout << "Loop through reads, looking for windows" << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
934

935
    ofstream *out_segmented = NULL;
Mathieu Giraud's avatar
Mathieu Giraud committed
936
    ofstream *out_unsegmented = NULL;
937
    ofstream *out_affects = NULL;
Mikaël Salson's avatar
Mikaël Salson committed
938
 
Mathieu Giraud's avatar
Mathieu Giraud committed
939
    WindowExtractor we;
940
941
    if (! output_sequences_by_cluster)
      we.setMaximalNbReadsPerWindow(max_auditionned);
942
943
 
    if (output_segmented) {
944
      string f_segmented = out_dir + f_basename + SEGMENTED_FILENAME ;
945
946
947
948
949
      cout << "  ==> " << f_segmented << endl ;
      out_segmented = new ofstream(f_segmented.c_str());
      we.setSegmentedOutput(out_segmented);
    }

Mathieu Giraud's avatar
Mathieu Giraud committed
950
    if (output_unsegmented) {
951
      string f_unsegmented = out_dir + f_basename + UNSEGMENTED_FILENAME ;
Mathieu Giraud's avatar
Mathieu Giraud committed
952
953
954
955
      cout << "  ==> " << f_unsegmented << endl ;
      out_unsegmented = new ofstream(f_unsegmented.c_str());
      we.setUnsegmentedOutput(out_unsegmented);
    }
956

957
958
959
960
961
962
963
    if (output_affects) {
      string f_affects = out_dir + f_basename + AFFECTS_FILENAME ;
      cout << "  ==> " << f_affects << endl ;
      out_affects = new ofstream(f_affects.c_str());
      we.setAffectsOutput(out_affects);
    }

964
965
966
    WindowsStorage *windowsStorage = we.extract(reads, multigermline, w,
                                                windows_labels, only_labeled_windows,
                                                max_reads_processed, only_nth_read, keep_unsegmented_as_clone,
Mathieu Giraud's avatar