vidjil.cpp 41.5 KB
Newer Older
Mikaël Salson's avatar
Mikaël Salson committed
1
2
/*
  This file is part of "Vidjil" <http://bioinfo.lifl.fr/vidjil>
Mathieu Giraud's avatar
Mathieu Giraud committed
3
4
  Copyright (C) 2011, 2012, 2013, 2014 by Bonsai bioinformatics at LIFL (UMR CNRS 8022, Université Lille) and Inria Lille
  Contributors: Mathieu Giraud <mathieu.giraud@lifl.fr>, Mikaël Salson <mikael.salson@lifl.fr>, Marc Duez <marc.duez@lifl.fr>
Mikaël Salson's avatar
Mikaël Salson committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

  "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
20
//$$ #include
Mikaël Salson's avatar
Mikaël Salson committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34

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

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

58
59
60
// 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"

61
#define VIDJIL_JSON_VERSION "2014.10"
Mikaël Salson's avatar
Mikaël Salson committed
62

Mathieu Giraud's avatar
Mathieu Giraud committed
63
64
//$$ #define (mainly default options)

65
#define DEFAULT_MULTIGERMLINE "germline"
Mikaël Salson's avatar
Mikaël Salson committed
66

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

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

81
82
83
#define DEFAULT_OUT_DIR "./out/" 

// Fixed filenames/suffixes
84
#define CLONES_FILENAME ".vdj.fa"
Mikaël Salson's avatar
Mikaël Salson committed
85
#define CLONE_FILENAME "clone.fa-"
86
87
88
89
90
91
#define WINDOWS_FILENAME ".windows.fa"
#define SEGMENTED_FILENAME ".segmented.vdj.fa"
#define UNSEGMENTED_FILENAME ".unsegmented.fa"
#define EDGES_FILENAME ".edges"
#define COMP_FILENAME "comp.vidjil"
#define JSON_SUFFIX ".vidjil"
Mikaël Salson's avatar
Mikaël Salson committed
92
93
94

// "tests/data/leukemia.fa" 

95
#define DEFAULT_K      0
Mikaël Salson's avatar
Mikaël Salson committed
96
#define DEFAULT_W      40
Mikaël Salson's avatar
Mikaël Salson committed
97
#define DEFAULT_W_D    60
98
#define DEFAULT_SEED   ""
Mikaël Salson's avatar
Mikaël Salson committed
99
100

#define DEFAULT_DELTA_MIN  -10
Mathieu Giraud's avatar
Mathieu Giraud committed
101
#define DEFAULT_DELTA_MAX   20
Mikaël Salson's avatar
Mikaël Salson committed
102
103

#define DEFAULT_DELTA_MIN_D  0
104
#define DEFAULT_DELTA_MAX_D  80
Mikaël Salson's avatar
Mikaël Salson committed
105

Mikaël Salson's avatar
Mikaël Salson committed
106
#define DEFAULT_MAX_AUDITIONED 2000
Mathieu Giraud's avatar
Mathieu Giraud committed
107
108
#define DEFAULT_RATIO_REPRESENTATIVE 0.5

Mikaël Salson's avatar
Mikaël Salson committed
109
110
111
112
113
114
#define DEFAULT_EPSILON  0
#define DEFAULT_MINPTS   10

#define DEFAULT_CLUSTER_COST  Cluster
#define DEFAULT_SEGMENT_COST   VDJ

115
116
117
// error
#define ERROR_STRING "[error] "

118
// warn
119
#define WARN_MAX_CLONES 100
120
#define WARN_PERCENT_SEGMENTED 40
121

Mikaël Salson's avatar
Mikaël Salson committed
122
123
124
// display
#define WIDTH_NB_READS 7
#define WIDTH_NB_CLONES 3
125

Mikaël Salson's avatar
Mikaël Salson committed
126
127
128

using namespace std ;

Mathieu Giraud's avatar
Mathieu Giraud committed
129
//$$ options: usage
Mikaël Salson's avatar
Mikaël Salson committed
130

Mathieu Giraud's avatar
Mathieu Giraud committed
131
extern char *optarg;
Mikaël Salson's avatar
Mikaël Salson committed
132
133
134
135
136

extern int optind, optopt, opterr;

void usage(char *progname)
{
137
  cerr << "Usage: " << progname << " [options] <reads.fa/.fq/.gz>" << endl << endl;
Mikaël Salson's avatar
Mikaël Salson committed
138
139

  cerr << "Command selection" << endl
140
141
       << "  -c <command> \t" << COMMAND_WINDOWS << "  \t window extracting" << endl 
       << "  \t\t" << COMMAND_CLONES  << "  \t clone gathering (default)" << endl 
142
       << "  \t\t" << COMMAND_SEGMENT   << "  \t V(D)J segmentation (not recommended)" << endl
143
       << "  \t\t" << COMMAND_GERMLINES << "  \t discover all germlines" << endl
Mikaël Salson's avatar
Mikaël Salson committed
144
145
       << endl       

146
       << "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
147
       << "  -V <file>     V germline multi-fasta file" << endl
148
       << "  -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
149
       << "  -J <file>     J germline multi-fasta file" << endl
150
       << "  -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
151
       << "  -g <path>     multiple germlines (in the path <path>, takes TRA, TRB, TRG, TRD, IGH and IGL and sets window prediction parameters)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
152
153
       << endl

Mathieu Giraud's avatar
Mathieu Giraud committed
154
       << "Window prediction" << endl
Mikaël Salson's avatar
Mikaël Salson committed
155
#ifndef NO_SPACED_SEEDS
156
       << "  (use either -s or -k option, but not both)" << endl
157
158
       << "  -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
159
#endif
160
       << "  -k <int>      k-mer size used for the V/J affectation (default: 10, 12, 13, depends on germline)" << endl
161
162
163
#ifndef NO_SPACED_SEEDS
       << "                (using -k option is equivalent to set with -s a contiguous seed with only '#' characters)" << endl
#endif
164
165
166
       << "  -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
       << "  -w <int>      w-mer size used for the length of the extracted window (default: " << DEFAULT_W << ") (default with -D: " << DEFAULT_W_D << ")" << endl
Mikaël Salson's avatar
Mikaël Salson committed
167
168
       << endl

Mathieu Giraud's avatar
Mathieu Giraud committed
169
170
       << "Window annotations" << endl
       << "  -l <file>     labels for some windows -- these windows will be kept even if some limits are not reached" << endl
Mikaël Salson's avatar
Mikaël Salson committed
171
172
       << endl

173
       << "Limits to report a clone (or a window)" << endl
174
175
       << "  -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
176
177
       << endl

178
       << "Limits to further analyze some clones" << endl
179
       << "  -y <nb>       maximal number of clones computed with a representative ('" << NO_LIMIT << "': no limit) (default: " << DEFAULT_MAX_REPRESENTATIVES << ")" << endl
180
       << "  -z <nb>       maximal number of clones to be segmented ('" << NO_LIMIT << "': no limit, do not use) (default: " << DEFAULT_MAX_CLONES << ")" << endl
181
       << "  -A            reports and segments all clones (-r 0 -% 0 -y " << NO_LIMIT << " -z " << NO_LIMIT << "), to be used only on very small datasets" << endl
Mikaël Salson's avatar
Mikaël Salson committed
182
183
       << endl

Mathieu Giraud's avatar
Mathieu Giraud committed
184
       << "Fine segmentation options (second pass, see warning in doc/algo.org)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
185
186
187
       << "  -f <string>   use custom Cost for fine segmenter : format \"match, subst, indels, homo, del_end\" (default "<<VDJ<<" )"<< endl
       << endl

188
189
190
191
192
193
194
195
196
       << "Additional clustering" << endl
       << "  -e <file>     manual clustering -- a file used to force some specific edges" << endl
       << "  -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
       << endl

197
       << "Debug" << endl
198
199
       << "  -U            output segmented (in " << SEGMENTED_FILENAME << " file) sequences" << endl
       << "  -u            output unsegmented (in " << UNSEGMENTED_FILENAME << " file) sequences" << endl
200
       << "                and display detailed k-mer affectation both on segmented and on unsegmented sequences" << endl
Mikaël Salson's avatar
Mikaël Salson committed
201
       << "Output" << endl
202
       << "  -o <dir>      output directory (default: " << DEFAULT_OUT_DIR << ")" <<  endl
203
       << "  -b <string>   output basename (by default basename of the input file)" << endl
Mikaël Salson's avatar
Mikaël Salson committed
204
    
205
       << "  -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
206
207
208
       << "  -v            verbose mode" << endl
       << endl        

209
210
211
       << "The full help is available in the doc/algo.org file."
       << endl

Mikaël Salson's avatar
Mikaël Salson committed
212
       << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
213
       << "Examples (see doc/algo.org)" << endl
Mathieu Giraud's avatar
Mathieu Giraud committed
214
215
       << "  " << progname << " -c clones   -G germline/IGH  -r 5          data/Stanford_S22.fasta" << endl
       << "  " << progname << " -c segment  -G germline/IGH                data/Stanford_S22.fasta   # (only for testing)" << endl
216
       << "  " << progname << " -c germlines                               data/Stanford_S22.fasta" << endl
Mikaël Salson's avatar
Mikaël Salson committed
217
218
219
220
221
222
    ;
  exit(1);
}

int main (int argc, char **argv)
{
223
  cout << "# Vidjil -- V(D)J recombinations analysis <http://www.vidjil.org/>" << endl
Mathieu Giraud's avatar
Mathieu Giraud committed
224
225
       << "# Copyright (C) 2011, 2012, 2013, 2014 by the Vidjil team" << endl
       << "# Bonsai bioinformatics at LIFL (UMR CNRS 8022, Université Lille) and Inria Lille" << endl 
Mathieu Giraud's avatar
Mathieu Giraud committed
226
227
228
229
230
       << 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
Mikaël Salson's avatar
Mikaël Salson committed
231
232
       << endl ;

Mathieu Giraud's avatar
Mathieu Giraud committed
233
234
  //$$ options: defaults

235
  string germline_system = "" ;
236
237
238
239
240
  
  list <string> f_reps_V ;
  list <string> f_reps_D ;
  list <string> f_reps_J ;

Mikaël Salson's avatar
Mikaël Salson committed
241
242
  string f_reads = DEFAULT_READS ;
  string seed = DEFAULT_SEED ;
243
  string f_basename = "";
Mikaël Salson's avatar
Mikaël Salson committed
244

245
  string out_dir = DEFAULT_OUT_DIR;
Mikaël Salson's avatar
Mikaël Salson committed
246
247
248
249
  
  string comp_filename = COMP_FILENAME;

  int k = DEFAULT_K ;
Mikaël Salson's avatar
Mikaël Salson committed
250
251
252
  int w = 0 ;
  int default_w = DEFAULT_W ;

Mikaël Salson's avatar
Mikaël Salson committed
253
254
255
256
257
258
259
260
261
262
  int epsilon = DEFAULT_EPSILON ;
  int minPts = DEFAULT_MINPTS ;
  Cost cluster_cost = DEFAULT_CLUSTER_COST ;
  Cost segment_cost = DEFAULT_SEGMENT_COST ;
  
  
  int save_comp = 0;
  int load_comp = 0;
  
  int verbose = 0 ;
263
  int command = CMD_CLONES;
Mikaël Salson's avatar
Mikaël Salson committed
264

265
  int max_representatives = DEFAULT_MAX_REPRESENTATIVES ;
266
267
268
  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
269
270
  // int average_deletion = 4;     // Average number of deletion in V or J

Mathieu Giraud's avatar
Mathieu Giraud committed
271
  float ratio_representative = DEFAULT_RATIO_REPRESENTATIVE;
Mikaël Salson's avatar
Mikaël Salson committed
272
  unsigned int max_auditionned = DEFAULT_MAX_AUDITIONED;
Mathieu Giraud's avatar
Mathieu Giraud committed
273

Mikaël Salson's avatar
Mikaël Salson committed
274
275
276
277
278
  // 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;
279
  bool output_segmented = false;
Mathieu Giraud's avatar
Mathieu Giraud committed
280
  bool output_unsegmented = false;
281
  bool multi_germline = false;
282
  string multi_germline_file = DEFAULT_MULTIGERMLINE;
Mikaël Salson's avatar
Mikaël Salson committed
283
284
285

  string forced_edges = "" ;

Mathieu Giraud's avatar
Mathieu Giraud committed
286
  string windows_labels_file = "" ;
Mikaël Salson's avatar
Mikaël Salson committed
287
288
289

  char c ;

290
291
  int options_s_k = 0 ;

WebTogz's avatar
WebTogz committed
292
293
294
  //JsonArray which contains the Levenshtein distances
  JsonArray jsonLevenshtein;

Mathieu Giraud's avatar
Mathieu Giraud committed
295
296
  //$$ options: getopt

297
  while ((c = getopt(argc, argv, "Ahag:G:V:D:J:k:r:vw:e:C:f:l:c:m:M:N:s:b:Sn:o:L%:y:z:uU")) != EOF)
Mikaël Salson's avatar
Mikaël Salson committed
298
299
300
301
302

    switch (c)
      {
      case 'h':
        usage(argv[0]);
303

Mikaël Salson's avatar
Mikaël Salson committed
304
      case 'c':
305
306
        if (!strcmp(COMMAND_CLONES,optarg))
          command = CMD_CLONES;
Mikaël Salson's avatar
Mikaël Salson committed
307
308
        else if (!strcmp(COMMAND_SEGMENT,optarg))
          command = CMD_SEGMENT;
Mathieu Giraud's avatar
Mathieu Giraud committed
309
310
        else if (!strcmp(COMMAND_WINDOWS,optarg))
          command = CMD_WINDOWS;
311
312
        else if (!strcmp(COMMAND_GERMLINES,optarg))
          command = CMD_GERMLINES;
Mikaël Salson's avatar
Mikaël Salson committed
313
314
315
316
317
        else {
          cerr << "Unknwown command " << optarg << endl;
	  usage(argv[0]);
        }
        break;
318

Mikaël Salson's avatar
Mikaël Salson committed
319
320
321
322

      // Germline

      case 'V':
323
	f_reps_V.push_back(optarg);
324
	germline_system = "custom" ;
Mikaël Salson's avatar
Mikaël Salson committed
325
326
327
	break;

      case 'D':
328
	f_reps_D.push_back(optarg);
329
330
331
	delta_min = DEFAULT_DELTA_MIN_D ;
	delta_max = DEFAULT_DELTA_MAX_D ;
	default_w = DEFAULT_W_D ;
Mikaël Salson's avatar
Mikaël Salson committed
332
333
334
	break;
        
      case 'J':
335
	f_reps_J.push_back(optarg);
336
	germline_system = "custom" ;
Mikaël Salson's avatar
Mikaël Salson committed
337
338
	break;

339
      case 'g':
340
341
	multi_germline = true;
	multi_germline_file = string(optarg);
342
	germline_system = "multi" ;
343
344
	break;
	
Mikaël Salson's avatar
Mikaël Salson committed
345
      case 'G':
Mikaël Salson's avatar
Mikaël Salson committed
346
	germline_system = string(optarg);
347
	f_reps_V.push_back((germline_system + "V.fa").c_str()) ;
348
349
350
351
352
353
354
355
356
357
358
        // 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)
            f_reps_D.push_back(putative_f_rep_D.c_str()) ;

          delta_min = DEFAULT_DELTA_MIN_D ;
          delta_max = DEFAULT_DELTA_MAX_D ;
          default_w = DEFAULT_W_D ;
        }
359
	f_reps_J.push_back((germline_system + "J.fa").c_str()) ;
360
	germline_system = extract_basename(germline_system);
361

Mikaël Salson's avatar
Mikaël Salson committed
362
363
364
365
	break;

      // Algorithm

366
367
368
369
370
371
372
373
374
375
      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
376
377
378
      case 'k':
	k = atoi(optarg);
	seed = seed_contiguous(k);
379
	options_s_k++ ;
Mikaël Salson's avatar
Mikaël Salson committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
        break;

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

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

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

394
395
      // Output 

Mikaël Salson's avatar
Mikaël Salson committed
396
397
398
399
      case 'o':
        out_dir = optarg ;
        break;

400
401
      case 'b':
        f_basename = optarg;
Mikaël Salson's avatar
Mikaël Salson committed
402
403
        break;

404
405
406
407
408
409
410
411
      case 'a':
	output_sequences_by_cluster = true;
	break;

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

412
413
      // Limits

Mikaël Salson's avatar
Mikaël Salson committed
414
415
416
417
      case '%':
	ratio_reads_clone = atof(optarg);
	break;

418
      case 'r':
Mikaël Salson's avatar
Mikaël Salson committed
419
420
421
	min_reads_clone = atoi(optarg);
        break;

422
      case 'y':
423
424
425
426
427
	if (!strcmp(NO_LIMIT, optarg))
	  {
	    max_representatives = -1;
	    break;
	  }
428
429
430
	max_representatives = atoi(optarg);
        break;

Mikaël Salson's avatar
Mikaël Salson committed
431
      case 'z':
432
433
434
435
436
	if (!strcmp(NO_LIMIT, optarg))
	  {
	    max_clones = -1;
	    break;
	  }
Mikaël Salson's avatar
Mikaël Salson committed
437
438
	max_clones = atoi(optarg);
        break;
439
440
441

      case 'A': // --all
	ratio_reads_clone = 0 ;
442
443
444
	min_reads_clone = 1 ;
	max_representatives = -1 ;
	max_clones = -1 ;
445
446
	break ;

447
448
449
450
      case 'l':
	windows_labels_file = optarg; 
	break;

451
      // Clustering
452
453
454
455

      case 'e':
	forced_edges = optarg;
	break;
Mikaël Salson's avatar
Mikaël Salson committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
	
      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;
	
477
478
      // Fine segmentation

479
      case 'f':
Mikaël Salson's avatar
Mikaël Salson committed
480
481
	segment_cost=strToCost(optarg, VDJ);
        break;
Mathieu Giraud's avatar
Mathieu Giraud committed
482
483
484
485

      case 'u':
        output_unsegmented = true;
        break;
486
487
488
      case 'U':
        output_segmented = true;
        break;
Mikaël Salson's avatar
Mikaël Salson committed
489
490
      }

491
492
493

  //$$ options: post-processing+display

494
495
496
497
498
499
500

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

Mikaël Salson's avatar
Mikaël Salson committed
501
502
503
504
505
  // If there was no -w option, then w is either DEFAULT_W or DEFAULT_W_D
  if (w == 0)
    w = default_w ;

  
506
507
  if (options_s_k > 1)
    {
508
      cout << ERROR_STRING << "Use at most one -s or -k option." << endl ;
509
510
511
      exit(1);
    }

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

Mikaël Salson's avatar
Mikaël Salson committed
514
515
516
517
518
519
520
521
522
523
524
525
526
  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
    {
527
      cout << ERROR_STRING << "Wrong number of arguments." << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
528
529
      exit(1);
    }
Mathieu Giraud's avatar
Mathieu Giraud committed
530

531
  size_t min_cover_representative = (size_t) (min_reads_clone < (int) max_auditionned ? min_reads_clone : max_auditionned) ;
532

533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
  // Default seeds

#ifndef NO_SPACED_SEEDS
  if (k == DEFAULT_K)
    {
      if (germline_system.find("TRA") != string::npos)
	seed = "#######-######" ;

      else if ((germline_system.find("TRB") != string::npos)
	       || (germline_system.find("IGH") != string::npos))
	seed = "######-######" ; 
      else // TRD, TRG, IGK, IGL
	seed = "#####-#####" ; 

      k = seed_weight(seed);
    }
#else
  {
551
    cout << ERROR_STRING << "Vidjil was compiled with NO_SPACED_SEEDS: please provide a -k option." << endl;
552
553
554
555
556
    exit(1) ;
  }
#endif
	  

Mathieu Giraud's avatar
Mathieu Giraud committed
557
558
559
560
#ifndef NO_SPACED_SEEDS
  // Check seed buffer  
  if (seed.size() >= MAX_SEED_SIZE)
    {
561
      cout << ERROR_STRING << "Seed size is too large (MAX_SEED_SIZE)." << endl ;
Mathieu Giraud's avatar
Mathieu Giraud committed
562
563
564
565
      exit(1);
    }
#endif

566
567
568

  if (w < seed_weight(seed))
    {
569
      cout << ERROR_STRING << "Too small -w. The window size should be at least equal to the seed size (" << seed_weight(seed) << ")." << endl;
570
571
572
      exit(1);
    }

Mikaël Salson's avatar
Mikaël Salson committed
573
574
575
576
  // 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) {
577
    cout << ERROR_STRING << "Directory creation: " << out_dir << endl; perror("");
Mikaël Salson's avatar
Mikaël Salson committed
578
579
580
    exit(2);
  }

Mikaël Salson's avatar
Mikaël Salson committed
581
582
  const char *outseq_cstr = out_seqdir.c_str();
  if (mkpath(outseq_cstr, 0755) == -1) {
583
    cout << ERROR_STRING << "Directory creation: " << out_seqdir << endl; perror("");
Mikaël Salson's avatar
Mikaël Salson committed
584
585
586
    exit(2);
  }

587
588
589
590
591
  // 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
592
593
594
  out_dir += "/" ;

  /// Load labels ;
Mathieu Giraud's avatar
Mathieu Giraud committed
595
  map <string, string> windows_labels = load_map(windows_labels_file);
Mikaël Salson's avatar
Mikaël Salson committed
596
597

  switch(command) {
Mathieu Giraud's avatar
Mathieu Giraud committed
598
  case CMD_WINDOWS: cout << "Extracting windows" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
599
    break;
600
  case CMD_CLONES: cout << "Analysing clones" << endl; 
Mikaël Salson's avatar
Mikaël Salson committed
601
602
603
    break;
  case CMD_SEGMENT: cout << "Segmenting V(D)J" << endl;
    break;
604
605
  case CMD_GERMLINES: cout << "Discovering germlines" << endl;
    break;
Mikaël Salson's avatar
Mikaël Salson committed
606
607
  }

Mathieu Giraud's avatar
Mathieu Giraud committed
608
  cout << "Command line: ";
Mikaël Salson's avatar
Mikaël Salson committed
609
  for (int i=0; i < argc; i++) {
Mathieu Giraud's avatar
Mathieu Giraud committed
610
    cout << argv[i] << " ";
Mikaël Salson's avatar
Mikaël Salson committed
611
  }
Mathieu Giraud's avatar
Mathieu Giraud committed
612
  cout << endl;
Mikaël Salson's avatar
Mikaël Salson committed
613
614
615
616
617
618
619
620
621
622
623
624

  //////////////////////////////////
  // 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
625
  cout << "# " << time_buffer << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
626
627
628
629
630
631


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

#ifdef RELEASE_TAG
Mathieu Giraud's avatar
Mathieu Giraud committed
632
  cout << "# version: vidjil " << RELEASE_TAG << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
633
#else
634
  cout << "# development version" << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
635
636
#endif

637
638
639
#ifdef GIT_VERSION
  cout << "# git: " << GIT_VERSION << endl ;
#endif
640

641

642
643
  //////////////////////////////////
  // Warning for non-optimal use
644

645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
  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 ;
    }
666

667
668
669
  /////////////////////////////////////////
  //            LOAD GERMLINES           //
  /////////////////////////////////////////
670

671
  MultiGermline *multigermline = new MultiGermline();
672

673
674
675
676
677
678
679
680
    {
      cout << "Build Kmer indexes" << endl ;
    
      if (multi_germline)
	{
	  multigermline->build_default_set(multi_germline_file);
	}
      else if (command == CMD_GERMLINES)
681
	{
682
683
	  multigermline->load_standard_set(multi_germline_file);
	  multigermline->build_with_one_index(seed);
684
	}
685
686
687
688
689
      else
	{
	  // Custom germline
	  Germline *germline;
	  germline = new Germline(germline_system, 'X',
690
691
692
                                  f_reps_V, f_reps_D, f_reps_J, 
                                  delta_min, delta_max);

693
694
695

	  if (command == CMD_WINDOWS || command == CMD_CLONES)
	    germline->new_index(seed);
696

697
698
699
	  multigermline->insert(germline);
	}
    }
700

701
702
703
704
705
706
707
708

  //////////////////////////////////
  //$$ Read sequence files
 
  OnlineFasta *reads;

  try {
    reads = new OnlineFasta(f_reads, 1, " ");
709
  } catch (const invalid_argument e) {
710
    cout << ERROR_STRING << "Vidjil cannot open reads file " << f_reads << ": " << e.what() << endl;
711
712
713
714
715
716
    exit(1);
  }

  out_dir += "/";


717
718
719
720
721
  //////////////////////////////://////////
  //         DISCOVER GERMLINES          //
  /////////////////////////////////////////
  if (command == CMD_GERMLINES)
    {
722
      map <char, int> stats_kmer, stats_max;
723
      IKmerStore<KmerAffect> *index = multigermline->index ;
724
725

      // Initialize statistics, with two additional categories
726
727
      index->labels.push_back(make_pair(KmerAffect::getAmbiguous(), AFFECT_AMBIGUOUS_SYMBOL));
      index->labels.push_back(make_pair(KmerAffect::getUnknown(), AFFECT_UNKNOWN_SYMBOL));
728
729
      
      for (list< pair <KmerAffect, string> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
730
	{
731
732
733
	  char key = affect_char(it->first.affect) ;
	  stats_kmer[key] = 0 ;
	  stats_max[key] = 0 ;
734
735
	}
      
736
      // init forbidden for .max()
737
738
739
      set<KmerAffect> forbidden;
      forbidden.insert(KmerAffect::getAmbiguous());
      forbidden.insert(KmerAffect::getUnknown());
740
      
741
742
743
      // Loop through all reads

      int nb_reads = 0 ;
744
745
746
      int total_length = 0 ;
      int s = index->getS();

747
748
749
750
751
      while (reads->hasNext())
	{
	  reads->next();
	  nb_reads++;
	  string seq = reads->getSequence().sequence;
752
	  total_length += seq.length() - s + 1;
753

754
	  KmerAffectAnalyser *kaa = new KmerAffectAnalyser(*index, seq);
755
756
757

	  for (int i = 0; i < kaa->count(); i++) 
	    { 
758
759
	      KmerAffect ksa = kaa->getAffectation(i);
	      stats_kmer[affect_char(ksa.affect)]++ ;
760
	    }
761

762
          delete kaa;
763

764
	  CountKmerAffectAnalyser ckaa(*index, seq);
765
766
	  ckaa.setAllowedOverlap(k-1);

767
	  stats_max[affect_char(ckaa.max(forbidden).affect)]++ ;
768

769
770
	}

771
772
      delete reads;

773
774
      // Display statistics

775
776
777
778
      cout << "  <== "
	   << nb_reads << " reads, "
	   << total_length << " kmers"
	   << endl ;
779
      cout << "\t" << " max" << "\t\t" << "        kmers" << "\n" ;
780
781

      for (list< pair <KmerAffect, string> >::const_iterator it = index->labels.begin(); it != index->labels.end(); ++it)
782
	{
783
784
785
786
	  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 << "%" ;
787

788
	  cout << "     " ;
789

790
791
	  cout << setw(12) << stats_kmer[key] << " " ;
	  cout << setw(6) << fixed << setprecision(2) <<  (float) stats_kmer[key] / total_length * 100 << "%" ;
792

793
	  cout << "     " << key << " " << it->second << endl ;
794
	}
795
796
      
      delete index;
797
798
799
800
      exit(0);
    }


Mikaël Salson's avatar
Mikaël Salson committed
801
802
803
  ////////////////////////////////////////
  //           CLONE ANALYSIS           //
  ////////////////////////////////////////
804
  if (command == CMD_CLONES || command == CMD_WINDOWS) {
Mikaël Salson's avatar
Mikaël Salson committed
805
806

    //////////////////////////////////
Mathieu Giraud's avatar
Mathieu Giraud committed
807
808
809
810
811
812
    cout << "# seed = " << seed << "," ;
    cout << " weight = " << seed_weight(seed) << "," ;
    cout << " span = " << seed.size() << endl ;
    cout << "# k = " << k << "," ;
    cout << " w = " << w << "," ;
    cout << " delta = [" << delta_min << "," << delta_max << "]" << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
813
814
815


    //////////////////////////////////
Mathieu Giraud's avatar
Mathieu Giraud committed
816
    //$$ Kmer Segmentation
Mikaël Salson's avatar
Mikaël Salson committed
817

Mathieu Giraud's avatar
Mathieu Giraud committed
818
819
    cout << endl;
    cout << "Loop through reads, looking for windows" << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
820

821
    ofstream *out_segmented = NULL;
Mathieu Giraud's avatar
Mathieu Giraud committed
822
    ofstream *out_unsegmented = NULL;
Mikaël Salson's avatar
Mikaël Salson committed
823
 
Mathieu Giraud's avatar
Mathieu Giraud committed
824
    WindowExtractor we;
825
826
 
    if (output_segmented) {
827
      string f_segmented = out_dir + f_basename + SEGMENTED_FILENAME ;
828
829
830
831
832
      cout << "  ==> " << f_segmented << endl ;
      out_segmented = new ofstream(f_segmented.c_str());
      we.setSegmentedOutput(out_segmented);
    }

Mathieu Giraud's avatar
Mathieu Giraud committed
833
    if (output_unsegmented) {
834
      string f_unsegmented = out_dir + f_basename +  UNSEGMENTED_FILENAME ;
Mathieu Giraud's avatar
Mathieu Giraud committed
835
836
837
838
      cout << "  ==> " << f_unsegmented << endl ;
      out_unsegmented = new ofstream(f_unsegmented.c_str());
      we.setUnsegmentedOutput(out_unsegmented);
    }
839

840
841

    WindowsStorage *windowsStorage = we.extract(reads, multigermline, w, windows_labels);
WebTogz's avatar
WebTogz committed
842
    windowsStorage->setIdToAll();
Mathieu Giraud's avatar
Mathieu Giraud committed
843
    size_t nb_total_reads = we.getNbReads();
Mikaël Salson's avatar
Mikaël Salson committed
844
845


Mathieu Giraud's avatar
Mathieu Giraud committed
846
    //$$ Display statistics on segmentation causes
Mikaël Salson's avatar
Mikaël Salson committed
847

848
849
        
    ostringstream stream_segmentation_info;
Mikaël Salson's avatar
Mikaël Salson committed
850

Mathieu Giraud's avatar
Mathieu Giraud committed
851
852
    int nb_segmented_including_too_short = we.getNbSegmented(TOTAL_SEG_AND_WINDOW) 
      + we.getNbSegmented(TOTAL_SEG_BUT_TOO_SHORT_FOR_THE_WINDOW);
Mikaël Salson's avatar
Mikaël Salson committed
853

854
    stream_segmentation_info << "  ==> segmented " << nb_segmented_including_too_short << " reads"
Mikaël Salson's avatar
Mikaël Salson committed
855
	<< " (" << setprecision(3) << 100 * (float) nb_segmented_including_too_short / nb_total_reads << "%)" 
Mathieu Giraud's avatar
Mathieu Giraud committed
856
857
	<< endl ;

858
    // nb_segmented is the main denominator for the following
Mathieu Giraud's avatar
Mathieu Giraud committed
859
    int nb_segmented = we.getNbSegmented(TOTAL_SEG_AND_WINDOW);
860
    float ratio_segmented = 100 * (float) nb_segmented / nb_total_reads ;
Mikaël Salson's avatar
Mikaël Salson committed
861

862
    stream_segmentation_info << "  ==> found " << windowsStorage->size() << " " << w << "-windows"
Mikaël Salson's avatar
Mikaël Salson committed
863
	<< " in " << nb_segmented << " segments"
864
	<< " (" << setprecision(3) << ratio_segmented << "%)"
Mikaël Salson's avatar
Mikaël Salson committed
865
866
	<< " inside " << nb_total_reads << " sequences" << endl ;
  
867
    // warn if there are too few segmented sequences
868
    if (ratio_segmented < WARN_PERCENT_SEGMENTED)
869
      {
870
871
        stream_segmentation_info << "  ! There are not so many CDR3 windows found in this set of reads." << endl ;
        stream_segmentation_info << "  ! If this is unexpected, check the germline (-G) and try to change seed parameters (-k)." << endl ;
872
873
      }

874
    stream_segmentation_info << "                                  #      av. length" << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
875

876
    multigermline->out_stats(stream_segmentation_info);
877
878
    stream_segmentation_info << endl;
    we.out_stats(stream_segmentation_info);
Mikaël Salson's avatar
Mikaël Salson committed
879
    
880
    cout << stream_segmentation_info.str();
Mathieu Giraud's avatar
Mathieu Giraud committed
881
      map <junction, JsonList> json_data_segment ;
Mikaël Salson's avatar
Mikaël Salson committed
882
    
Mikaël Salson's avatar
Mikaël Salson committed
883
884

	//////////////////////////////////
Mathieu Giraud's avatar
Mathieu Giraud committed
885
	//$$ Sort windows
Mikaël Salson's avatar
Mikaël Salson committed
886
	
Mathieu Giraud's avatar
Mathieu Giraud committed
887
888
        cout << "Sort windows by number of occurrences" << endl;
        windowsStorage->sort();
Mikaël Salson's avatar
Mikaël Salson committed
889
890

	//////////////////////////////////
Mathieu Giraud's avatar
Mathieu Giraud committed
891
	//$$ Output windows
Mikaël Salson's avatar
Mikaël Salson committed
892
893
	//////////////////////////////////

894
	string f_all_windows = out_dir + f_basename + WINDOWS_FILENAME;
Mathieu Giraud's avatar
Mathieu Giraud committed
895
	cout << "  ==> " << f_all_windows << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
896

Mathieu Giraud's avatar
Mathieu Giraud committed
897
	ofstream out_all_windows(f_all_windows.c_str());
Mathieu Giraud's avatar
Mathieu Giraud committed
898
        windowsStorage->printSortedWindows(out_all_windows);
Mikaël Salson's avatar
Mikaël Salson committed
899
900
901


    //////////////////////////////////
902
903
904
905
906
907
908
    //$$ min_reads_clone (ou label)

    int min_reads_clone_ratio = (int) (ratio_reads_clone * nb_segmented / 100.0);
    cout << "Considering only labeled windows and windows with >= " << min_reads_clone << " reads"
	 << " and with a ratio >= " << ratio_reads_clone << " (" << min_reads_clone_ratio << ")" << endl ;

    int min_reads_clone_final = max(min_reads_clone, min_reads_clone_ratio);
Mathieu Giraud's avatar
Mathieu Giraud committed
909

910
    pair<int, int> info_remove = windowsStorage->keepInterestingWindows((size_t) min_reads_clone_final);
Mikaël Salson's avatar
Mikaël Salson committed
911
	 
Mathieu Giraud's avatar
Mathieu Giraud committed
912
913
    cout << "  ==> keep " <<  windowsStorage->size() << " windows in " << info_remove.second << " reads" ;
    cout << " (" << setprecision(3) << 100 * (float) info_remove.second / nb_total_reads << "%)  " << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
914

915
916
917
918
    if (windowsStorage->size() == 0)
      {
	cout << "  ! No windows with current parameters." << endl;
      }
919

920
921
922
923
924
925
    //////////////////////////////////
    //$$ Clustering
    windowsStorage->sort();
    list<pair <junction, int> > sort_clones = windowsStorage->getSortedList();
    cout << "  ==> " << sort_clones.size() << " clones" << endl ;
    
926
    list <list <junction> > clones_windows;
927
    comp_matrix comp=comp_matrix(sort_clones);
928
      
929
    if (command == CMD_CLONES) {
Mikaël Salson's avatar
Mikaël Salson committed
930
931
932

    if (epsilon || forced_edges.size())
      {
Mathieu Giraud's avatar
Mathieu Giraud committed
933
	cout << "Cluster similar windows" << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
934
935
936

	if (load_comp==1) 
	  {
937
	    comp.load((out_dir+f_basename + "." + comp_filename).c_str());
Mikaël Salson's avatar
Mikaël Salson committed
938
939
940
	  }
	else
	  {
Mathieu Giraud's avatar
Mathieu Giraud committed
941
	    comp.compare( cout, cluster_cost);
Mikaël Salson's avatar
Mikaël Salson committed
942
943
944
945
	  }
	
	if (save_comp==1)
	  {
946
	    comp.save(( out_dir+f_basename + "." + comp_filename).c_str());
Mikaël Salson's avatar
Mikaël Salson committed
947
948
	  }
       
Mathieu Giraud's avatar
Mathieu Giraud committed
949
	clones_windows  = comp.cluster(forced_edges, w, cout, epsilon, minPts) ;
950
	comp.stat_cluster(clones_windows, cout );
Mikaël Salson's avatar
Mikaël Salson committed
951
	comp.del();
952
	cout << "  ==> " << clones_windows.size() << " clusters" << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
953
954
      } 
    else
955
956
      { 
	cout << "No clustering" << endl ; 
Mikaël Salson's avatar
Mikaël Salson committed
957
958
      }

959
960
961
962
963
964
965
966
967

    // TODO: output clones_windows (.data, other places ?)

    // TODO: Are these constraints checked somewhere ? keepInterestingWindows ?
    // if (labeled 
    //     || ((clone_nb_reads >= min_reads_clone) 
    //		  && (clone_nb_reads * 100.0 / nb_segmented >= ratio_reads_clone)))

    if (sort_clones.size() == 0)
968
969
      {
	cout << "  ! No clones with current parameters." << endl;
970
	cout << "  ! See the 'Limits to report a clone' options (-r, -%, -z, -A)." << endl;
971
      }
972
    else
Mikaël Salson's avatar
Mikaël Salson committed
973
974
      {

975
976
    cout << endl;

Mikaël Salson's avatar
Mikaël Salson committed
977
    //////////////////////////////////
Mathieu Giraud's avatar
Mathieu Giraud committed
978
    //$$ Output clones
979

980
    if (max_clones > 0)
981
      cout << "Detailed analysis of at most " << max_clones<< " clones" ;
982
    else
983
984
      cout << "Detailed analysis of all clones" ;
    cout << endl ;
Mikaël Salson's avatar
Mikaël Salson committed
985
986

    map <string, int> clones_codes ;
Mathieu Giraud's avatar
Mathieu Giraud committed
987
    map <string, string> clones_map_windows ;
Mikaël Salson's avatar
Mikaël Salson committed
988
989
990
991

    list <Sequence> representatives ;
    list <string> representatives_labels ;

992
    // VirtualReadScore *scorer = new KmerAffectReadScore(*(germline->index));
993
    int last_num_clone_on_stdout = 0 ;
Mikaël Salson's avatar
Mikaël Salson committed
994
995
    int num_clone = 0 ;