forked from wtsi-npg/simtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
g2i.cpp
835 lines (727 loc) · 27.2 KB
/
g2i.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//
// g2i: Process one or more GTC files to produce a file suitable for being read
// by illuminus.
//
// Author: Jennifer Liddle (js10)
//
// $Id: g2i.cpp 1511 2013-01-21 15:37:42Z js10 $
//
// Author: Jennifer Liddle <[email protected], [email protected]>
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the Genome Research Ltd nor the names of its contributors
// may be used to endorse or promote products derived from software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. EVENT SHALL GENOME RESEARCH LTD. BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <time.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>
#include <hash_map>
#include "Gtc.h"
#include "Manifest.h"
#include "win2unix.h"
#include "Sim.h"
#include "json/json.h"
#define CACHESIZE 256
#define GCCACHESIZE 32
using namespace std;
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
hash_map<string,string> gtcHash; // <sample_name, filename>
Manifest *manifest = new Manifest();
vector<string> sampleArray;
hash_map<string,float*> cache;
hash_map<string,string> gcCache;
hash_map<string,int> exclusionList; // List of samples to exclude
typedef hash_map<string,fstream*> FileMap;
FileMap outFile;
FileMap::iterator pos;
vector<string> filenameArray;
vector<string> sampleNames;
typedef hash_map<string,ios::pos_type> PosMap;
PosMap filePos;
PosMap::iterator fp;
Gtc gtc;
// command line options
bool verbose=false;
bool binary=false;
bool genoSNP=false;
bool genoCalling = false;
bool simOutput = false;
bool excludeCnv=false;
bool includeCnv=false;
bool excludeExo=false;
bool normalise=true;
string outputFile;
string project;
string manifestDir;
string exclusionFile;
string chrSelect;
string tmpFile;
char * timestamp(void)
{
static char buffer[64];
time_t t = time(NULL);
strftime(buffer,64,"%F %T: ", localtime(&t));
return buffer;
}
void displayUsage(void)
{
cout << "g2i: convert Illumina GTC files into a format suitable for loading into illuminus or genoSNP, or export genotype calls"
<< endl << endl
<< "Usage:" << endl
<< "g2i -o <filename> [options] <gtcfile> <gtcfile> ..." << endl
<< "or" << endl
<< "g2i -o <filename> -i <filename> [options]" << endl << endl
<< "Where 'options' are one or more of:" << endl
<< "-o <prefix> specifies the output filename to create" << endl
<< "-t <prefix> Specify a temporary file location to use" << endl
<< "-v verbose mode" << endl
<< "-h displays this message" << endl
<< "-g produce genoSNP input rather than Illuminus" << endl
<< "-s produce genotype calling data rather than Illuminus" << endl
<< "-m produce SIM file rather than Illuminus" << endl
<< "-r <chromosome> select samples for this chromosome only" << endl
<< "-p <project> extract data for samples in this project ID from the Illumina LIMS" << endl
<< "-n do NOT perform normalisation on intensities" << endl
<< "-c exclude any SNPs beginning with cnv" << endl
<< "-k include any SNPs beginning with cnv" << endl
<< "-e exclude any samples beginning with 'Exo' or 'EXO'" << endl
<< "-x <filename> exclude any samples contained in <filename>" << endl
<< "-i <filename> specifies a file containing a list of GTC files to process" << endl
<< "-d <directory> specifies an alternative manifest file location" << endl
<< "<gtcfile>... is a list of GTC files to process" << endl << endl;
exit(0);
}
void loadExclusionFile(string fname)
{
ifstream f;
string s;
f.open(fname.c_str());
while (f >> s) {
exclusionList[s] = 1;
if (verbose) cout << timestamp() << "Excluding: " << s << endl;
}
f.close();
}
// Sort function to sort SNPs by position
bool SortByPosition(const snpClass &snp1, const snpClass &snp2)
{
if (snp1.chromosome.compare(snp2.chromosome))
return (snp1.chromosome.compare(snp2.chromosome) < 0);
if (snp1.position != snp2.position)
return (snp1.position < snp2.position);
return (snp1.name.compare(snp2.name) < 0);
}
void flushCache(int cacheIndex)
{
if (verbose) cout << timestamp() << "Flushing cache..." << endl;
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
// look up the file and position for this SNP
fstream *f = outFile[snp->chromosome];
f->seekp(filePos[snp->name]);
if (binary) {
f->write((char*)cache[snp->name], cacheIndex * sizeof(float));
filePos[snp->name] += cacheIndex * sizeof(float);
} else {
ostringstream os;
for (int i=0; i<cacheIndex; i++) {
if (cache[snp->name][i] < 0) cache[snp->name][i] = 0;
os << '\t' << setw(7) << std::fixed << setprecision(3) << cache[snp->name][i];
}
f->write(os.str().c_str(), os.str().size());
filePos[snp->name] += os.str().size();
}
}
}
void flushgcCache(int cacheIndex)
{
if (verbose) cout << timestamp() << "Flushing cache..." << endl;
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
// look up the file and position for this SNP
fstream *f = outFile[snp->chromosome];
f->seekp(filePos[snp->name]);
ostringstream os;
os << gcCache[snp->name];
f->write(os.str().c_str(), os.str().size());
filePos[snp->name] += os.str().size();
gcCache[snp->name] = "";
}
}
//
// We've read the Manifest and all the GTC files
// Now it's time to create the output files
//
void goForIt(string fname)
{
int recordLength = gtcHash.size() * 10 * 2;
if (binary) recordLength = gtcHash.size() * sizeof(float) * 2;
char *buffer = new char[recordLength];
if (binary) {
memset(buffer,0,recordLength);
} else {
memset(buffer,' ',recordLength);
buffer[recordLength-1] = '\n';
}
// Sort the SNPs into position order
sort(manifest->snps.begin(), manifest->snps.end(), SortByPosition);
// Create lockfile
string lockFileName = fname + ".lock";
FILE *lockfile = fopen(lockFileName.c_str(), "w");
if (!lockfile) {
cerr << "Can't create lock file " << lockFileName << endl;
cerr << strerror(errno) << endl;
exit(1);
}
fclose(lockfile);
//
// Create all of the output files - one for each chromosome
//
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
fstream *f = outFile[snp->chromosome];
if (!f) {
f = new fstream();
string fullFname = fname + "_intu_" + snp->chromosome + ".txt";
filenameArray.push_back("_intu_" + snp->chromosome + ".txt");
if (verbose) cout << timestamp() << "creating file " << fullFname << endl;
if (binary) f->open(fullFname.c_str(), ios::in | ios::out | ios::trunc | ios::binary);
else f->open(fullFname.c_str(), ios::in | ios::out | ios::trunc);
*f << "SNP\tCoor\tAlleles";
// write sample names from all the gtc files
for (hash_map<string,string>::iterator i = gtcHash.begin(); i != gtcHash.end(); i++) {
*f << "\t" << i->first << "A\t" << i->first << "B";
}
*f << endl;
// associate the file handle with the chromosome
outFile[snp->chromosome] = f;
}
f = outFile[snp->chromosome];
*f << snp->name << "\t" << snp->position << "\t" << snp->snp[0] << snp->snp[1];
filePos[snp->name] = f->tellp(); // store next position to write
f->write(buffer,recordLength); // fill with nulls (or spaces)
cache[snp->name] = new float[CACHESIZE];
}
//
// Process each GTC file in turn
//
int n=1;
int cacheIndex = 0;
for (hash_map<string,string>::iterator i = gtcHash.begin(); i != gtcHash.end(); i++) {
if (verbose) cout << timestamp() << "Processing GTC file " << n++ << " of " << gtcHash.size() << endl;
gtc.open(i->second,Gtc::XFORM | Gtc::INTENSITY); // reload GTC file to read XForm and Intensity arrays
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
int idx = snp->index - 1; // index is zero based in arrays, but starts from 1 in the map file
unsigned int norm = manifest->normIdMap[snp->normId];
XFormClass *XF = >c.XForm[norm];
double xn, yn;
if (normalise) {
// first do the normalisation calculation
double tempx = gtc.xRawIntensity[idx] - XF->xOffset;
double tempy = gtc.yRawIntensity[idx] - XF->yOffset;
double cos_theta = cos(XF->theta);
double sin_theta = sin(XF->theta);
double tempx2 = cos_theta * tempx + sin_theta * tempy;
double tempy2 = -sin_theta * tempx + cos_theta * tempy;
double tempx3 = tempx2 - XF->shear * tempy2;
double tempy3 = tempy2;
xn = tempx3 / XF->xScale;
yn = tempy3 / XF->yScale;
} else {
xn = gtc.xRawIntensity[idx];
yn = gtc.yRawIntensity[idx];
}
cache[snp->name][cacheIndex] = xn;
cache[snp->name][cacheIndex+1] = yn;
}
cacheIndex += 2;
if (cacheIndex == CACHESIZE) { flushCache(cacheIndex); cacheIndex=0; }
}
flushCache(cacheIndex);
// close all of the files
for (pos = outFile.begin(); pos != outFile.end(); pos++) {
pos->second->close();
}
// delete lockfile and create donefile
string doneFileName = lockFileName;
string::size_type dot = doneFileName.find(".lock");
doneFileName.replace(dot, 5, ".g2i");
rename(lockFileName.c_str(), doneFileName.c_str());
if (verbose) cout << timestamp() << "Renamed " << lockFileName << " to " << doneFileName << endl;
}
// Read the manifest
//
// manifestPath is the full pathname of the manifest directory, either
// calculated relative to the first GTC file (the default) or suppled
// on the command line. manifestName is the name of the manifest file
// as stored in the GTC file
//
void loadManifest(string manifestPath, string manifestName)
{
string mfile = manifestPath + '/' + manifestName + ".csv";
if (verbose) cout << timestamp() << "Reading manifest: " << mfile << endl;
try {
manifest->open(mfile);
}
catch (string s) {
cout << s << endl;
cerr << s << endl;
}
}
//
// Return a manifest file path relative to GTC file name gtcName
//
//
string relativeManifestPath(string gtcName)
{
string rpath = gtcName;
size_t i = rpath.find('/');
if (i == string::npos) {
rpath = '.';
}
else {
rpath = rpath.substr(0,rpath.find_last_of('/'));
}
rpath = rpath + "/..";
return rpath;
}
void getAutocallInfo(vector<string> &infiles, string project)
{
char buffer[1024];
// project may contain space chars ...
if (project.find("\\") == string::npos) {
// ... that haven't been escaped
size_t pos = project.find(" ");
while (pos != string::npos) {
// prepend with "\"
project.replace(pos,1,"\\ ");
// next search starts after current position
// (pos + 1), but we've also replace a 1-char
// string with a 2-char one, so check pos + 2
pos = project.find(" ", pos + 2);
}
}
string pname = "autocall_report.pl -t -p "+project;
if (verbose) cout << timestamp() << pname << endl;
FILE *f = popen(pname.c_str(), "r");
if (!f) {
cout << "Oops! " << strerror(errno) << endl;;
cerr << "Oops! " << strerror(errno) << endl;;
exit(1);
}
while (fgets(buffer,1024,f)) {
// Anorexia_670 WG0015336-DNA A02 144693_A02_CCC3_AN1208139 5065997151 R01C01 AutoCall Completed Pass 08/05/10 /nfs/illumina_geno04/call/20100508/5065997151_R01C01.gtc
char *p = strtok(buffer,"\t");
int n = 1;
while (p) {
if (n==10 && strlen(p) > 2) {
string filepath = p;
filepath = win2unix(filepath);
infiles.push_back(filepath);
if (verbose) cout << timestamp() << "Read " << p << " ==> " << filepath << endl;
}
n++;
p = strtok(NULL,"\t");
}
}
}
void createSimFile(string fname)
{
Sim *sim = new Sim();
hash_map<string,string>::iterator i = gtcHash.begin();
gtc.open(i->second, Gtc::INTENSITY);
sim->createFile(fname);
sim->writeHeader(gtcHash.size(), gtc.xRawIntensity.size());
//
//
// Process each GTC file in turn
//
unsigned int n=1;
for (hash_map<string,string>::iterator i = gtcHash.begin(); i != gtcHash.end(); i++) {
char *buffer;
if (verbose) cout << timestamp() << "Processing GTC file " << n << " of " << gtcHash.size() << endl;
//
// add sample name to each output file
// no family info as yet (todo?) - write sample ID twice
// fn << i->first << endl;
gtc.open(i->second,Gtc::XFORM | Gtc::INTENSITY); // reload GTC file to read XForm and Intensity arrays
buffer = new char[sim->sampleNameSize];
memset(buffer,0,sim->sampleNameSize);
// if we have a sample name from the json file, use it
if (sampleNames.size() > (n-1)) { strcpy(buffer, sampleNames[n-1].c_str()); }
else { strcpy(buffer,gtc.sampleName.c_str()); }
sim->write(buffer, sim->sampleNameSize);
for (unsigned int idx = 0; idx < gtc.xRawIntensity.size(); idx++) {
uint16_t v;
v = gtc.xRawIntensity[idx];
sim->write(&v,sizeof(v));
v = gtc.yRawIntensity[idx];
sim->write(&v,sizeof(v));
}
n++;
#if 0
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
int idx = snp->index - 1; // index is zero based in arrays, but starts from 1 in the map file
unsigned int norm = manifest->normIdMap[snp->normId];
XFormClass *XF = >c.XForm[norm];
// first do the normalisation calculation
double tempx = gtc.xRawIntensity[idx] - XF->xOffset;
double tempy = gtc.yRawIntensity[idx] - XF->yOffset;
double cos_theta = cos(XF->theta);
double sin_theta = sin(XF->theta);
double tempx2 = cos_theta * tempx + sin_theta * tempy;
double tempy2 = -sin_theta * tempx + cos_theta * tempy;
double tempx3 = tempx2 - XF->shear * tempy2;
double tempy3 = tempy2;
double xn = tempx3 / XF->xScale;
double yn = tempy3 / XF->yScale;
// add raw/norm x/y to .raw and .nor files
// fn << "\t" << std::fixed << setprecision(3) << xn << " " << yn;
}
#endif
}
sim->close();
}
void createGenoSNP(string fname)
{
// Sort the SNPs into position order
sort(manifest->snps.begin(), manifest->snps.end(), SortByPosition);
// Create lockfile
string lockFileName = fname + ".lock";
FILE *lockfile = fopen(lockFileName.c_str(), "w");
fclose(lockfile);
//
// Create all of the output files
//
string rawFname = fname + ".raw.txt";
string snpFname = fname + ".snp.txt";
string norFname = fname + ".nor.txt";
filenameArray.push_back(".raw.txt");
filenameArray.push_back(".snp.txt");
filenameArray.push_back(".nor.txt");
fstream fn;
fstream fs;
fstream fr;
fr.open(rawFname.c_str(), ios::in | ios::out | ios::trunc);
fn.open(norFname.c_str(), ios::in | ios::out | ios::trunc);
fs.open(snpFname.c_str(), ios::in | ios::out | ios::trunc);
if (verbose) cout << timestamp() << "creating file " << rawFname << ", " << norFname << " and " << snpFname << endl;
// Write SNP list to .snp
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
fs << snp->name << '\t'
<< (snp->normId % 100) + 1 << '\t'
<< snp->snp[0] << " " << snp->snp[1] << endl;
}
fs.close();
if (fs.bad())
cout << "Error closing snp file" << endl;
//
// Process each GTC file in turn
//
int n=1;
for (hash_map<string,string>::iterator i = gtcHash.begin(); i != gtcHash.end(); i++) {
if (verbose) cout << timestamp() << "Processing GTC file " << n++ << " of " << gtcHash.size() << endl;
//
// add sample name to each output file
// no family info as yet (todo?) - write sample ID twice
fn << i->first << "\t" << i->first;
fr << i->first << "\t" << i->first;
gtc.open(i->second,Gtc::XFORM | Gtc::INTENSITY); // reload GTC file to read XForm and Intensity arrays
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
int idx = snp->index - 1; // index is zero based in arrays, but starts from 1 in the map file
unsigned int norm = manifest->normIdMap[snp->normId];
XFormClass *XF = >c.XForm[norm];
// first do the normalisation calculation
double tempx = gtc.xRawIntensity[idx] - XF->xOffset;
double tempy = gtc.yRawIntensity[idx] - XF->yOffset;
double cos_theta = cos(XF->theta);
double sin_theta = sin(XF->theta);
double tempx2 = cos_theta * tempx + sin_theta * tempy;
double tempy2 = -sin_theta * tempx + cos_theta * tempy;
double tempx3 = tempx2 - XF->shear * tempy2;
double tempy3 = tempy2;
double xn = tempx3 / XF->xScale;
double yn = tempy3 / XF->yScale;
// add raw/norm x/y to .raw and .nor files
fr << "\t" << std::fixed << setprecision(3) << gtc.xRawIntensity[idx] << " " << gtc.yRawIntensity[idx];
fn << "\t" << std::fixed << setprecision(3) << xn << " " << yn;
}
fn << endl;
fr << endl;
}
fn.close();
if (fn.bad()) cout << "Error closing nor file" << endl;
fr.close();
if (fr.bad()) cout << "Error closing raw file" << endl;
// delete lockfile and create donefile
string doneFileName = lockFileName;
string::size_type dot = doneFileName.find(".lock");
doneFileName.replace(dot, 5, ".g2i");
rename(lockFileName.c_str(), doneFileName.c_str());
if (verbose) cout << timestamp() << "Renamed " << lockFileName << " to " << doneFileName << endl;
}
void createGenoCalling(string fname)
{
int recordLength = gtcHash.size() * 18;
char *buffer = new char[recordLength];
memset(buffer,' ',recordLength);
buffer[recordLength-1] = '\n';
// Sort the SNPs into position order
sort(manifest->snps.begin(), manifest->snps.end(), SortByPosition);
// Create lockfile
string lockFileName = fname + ".lock";
FILE *lockfile = fopen(lockFileName.c_str(), "w");
if (!lockfile) throw (strerror(errno));
fclose(lockfile);
//
// Create all of the output files - one for each chromosome
//
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
fstream *f = outFile[snp->chromosome];
if (!f) {
f = new fstream();
string fullFname = fname + "_gtu_" + snp->chromosome + ".txt";
filenameArray.push_back("_gtu_" + snp->chromosome + ".txt");
if (verbose) cout << timestamp() << "creating file " << fullFname << endl;
f->open(fullFname.c_str(), ios::in | ios::out | ios::trunc);
// write sample names from all the gtc files
for (hash_map<string,string>::iterator i = gtcHash.begin(); i != gtcHash.end(); i++) {
*f << "\t" << i->first;
}
*f << endl;
// associate the file handle with the chromosome
outFile[snp->chromosome] = f;
}
f = outFile[snp->chromosome];
*f << snp->name;
filePos[snp->name] = f->tellp(); // store next position to write
f->write(buffer,recordLength); // fill with nulls (or spaces)
gcCache[snp->name] = "";
}
//
// Process each GTC file in turn
//
int n=1;
int cacheIndex = 0;
for (hash_map<string,string>::iterator i = gtcHash.begin(); i != gtcHash.end(); i++) {
if (verbose) cout << timestamp() << "Processing GTC file " << n++ << " of " << gtcHash.size() << endl;
gtc.open(i->second,Gtc::GENOTYPES | Gtc::BASECALLS | Gtc::SCORES); // reload GTC file to read required arrays
for (vector<snpClass>::iterator snp = manifest->snps.begin(); snp != manifest->snps.end(); snp++) {
if (excludeCnv && snp->name.find("cnv") != string::npos) continue;
if (chrSelect.size() && chrSelect.compare(snp->chromosome)) continue;
int idx = snp->index - 1; // index is zero based in arrays, but starts from 1 in the map file
char buffer[128];
if (gtc.genotypes[idx] > 3)
cout << "Unknown genotype value: " << gtc.genotypes[idx] << endl;
if (gtc.genotypes[idx] == 0)
sprintf(buffer,"\tNN;%f", gtc.scores[idx]);
else
sprintf(buffer,"\t%c%c;%f", gtc.baseCalls[idx].a, gtc.baseCalls[idx].b, gtc.scores[idx]);
gcCache[snp->name] += buffer;
}
cacheIndex++;
if (cacheIndex == GCCACHESIZE) { flushgcCache(cacheIndex); cacheIndex=0; }
}
flushgcCache(cacheIndex);
// close all of the files
for (pos = outFile.begin(); pos != outFile.end(); pos++) {
pos->second->close();
}
// delete lockfile and create donefile
string doneFileName = lockFileName;
string::size_type dot = doneFileName.find(".lock");
doneFileName.replace(dot, 5, ".g2i");
rename(lockFileName.c_str(), doneFileName.c_str());
if (verbose) cout << timestamp() << "Renamed " << lockFileName << " to " << doneFileName << endl;
}
int main(int argc, char *argv[])
{
char c;
int nBadFiles = 0;
vector<string> infiles;
while ((c = getopt (argc, argv, "neckmsvbw?hgo:i:x:p:d:r:t:")) != -1) {
switch (c) {
case 'v': verbose=true; break;
case 'b': binary=true; break;
case 'c': excludeCnv=true; break;
case 'k': includeCnv=true; break;
case 'e': excludeExo=true; break;
case 'g': genoSNP=true; break;
case 's': genoCalling=true; break;
case 'm': simOutput=true; break;
case 'n': normalise=false; break;
case 'h':
case '?': displayUsage(); break;
case 'o': outputFile = optarg; break;
case 't': tmpFile = optarg; break;
case 'p': project = optarg; break;
case 'd': manifestDir = optarg; break;
case 'x': exclusionFile = optarg; break;
case 'r': chrSelect = optarg; break;
case 'i': ifstream f; string s;
f.open(optarg);
if (strcmp(optarg,".json")) {
bool parsingSuccessful = reader.parse( f, root );
if ( !parsingSuccessful ) {
std::cout << "Failed to parse json file\n" << reader.getFormatedErrorMessages() << endl;
return 0;
}
for ( unsigned int index = 0; index < root.size(); ++index ) { // Iterates over the sequence elements.
sampleNames.push_back(root[index]["uri"].asString());
infiles.push_back(root[index]["result"].asString());
}
} else {
while (f >> s) infiles.push_back(s);
}
f.close();
break;
}
}
if (outputFile.size() == 0) {
cout << "No output file specified" << endl;
displayUsage();
}
if (tmpFile.size() == 0) {
tmpFile = outputFile;
}
if (project.size()) {
getAutocallInfo(infiles,project);
}
if (exclusionFile.size() != 0) {
loadExclusionFile(exclusionFile);
}
// read the rest of the command line
for (int n = optind; n < argc; n++) {
infiles.push_back(argv[n]);
}
if (infiles.size() == 0) {
cout << "No input files specified" << endl;
displayUsage();
}
if (excludeCnv && includeCnv) {
cout << "You can't specify -c AND -k options together! That doesn't make sense!" << endl;
displayUsage();
}
if (!excludeCnv && !includeCnv) excludeCnv=true; // default to 'exclude' if nothing specified
// sanity check the GTC files
if (verbose) cout << timestamp() << "Sanity checking";
for (vector<string>::iterator f = infiles.begin(); f != infiles.end(); f++) {
bool badFile = false;
if (verbose) cout << '.';
try {
gtc.open(*f,0);
if (gtc.errorMsg.length()) throw gtc.errorMsg;
}
catch (string s) {
cout << s << endl;
badFile = true;
nBadFiles++;
}
if (excludeExo && ( (gtc.sampleName.find("Exo") == 0) ||
(gtc.sampleName.find("EXO") == 0))) {
badFile=true;
if (verbose) cout << "X";
}
if (exclusionList[gtc.sampleName]) {
badFile = true;
if (verbose) cout << "X";
}
if (!badFile) {
gtcHash[gtc.sampleName] = *f;
sampleArray.push_back(gtc.sampleName);
}
}
if (verbose) cout << endl;
// a little validation...
if (gtcHash.size() == 0) {
cout << "No gtc files specified\n";
exit(1);
}
string manifestName = "";
for (hash_map<string,string>::iterator i = gtcHash.begin(); i != gtcHash.end(); i++) {
gtc.open(i->second,0);
if (manifestName != "" && gtc.manifest != manifestName) {
cout << "GTC files do not all have the same manifest" << endl;
exit(1);
}
manifestName = gtc.manifest;
}
if (verbose) {
cout << timestamp() << "About to process " << gtcHash.size() << " GTC files" << endl;
if (nBadFiles) cout << "Cannot process " << nBadFiles << " GTC files" << endl;
}
if (!simOutput) {
if (verbose) cout << "Loading manifest " << manifestName << endl;
if (manifestDir.size()) {
loadManifest(manifestDir, manifestName);
} else {
loadManifest(relativeManifestPath(infiles[0]), manifestName);
}
}
try {
if (genoSNP) { createGenoSNP(tmpFile); }
else if (genoCalling) { createGenoCalling(tmpFile); }
else if (simOutput) { createSimFile(tmpFile); }
else { goForIt(tmpFile); }
}
catch (char *s) {
cerr << timestamp() << "Caught fatal error: " << s << endl;
return 1;
}
// Copy temporary files to final output files
if (tmpFile.compare(outputFile)) {
for (vector<string>::iterator i = filenameArray.begin(); i != filenameArray.end(); i++) {
string command = "cp " + tmpFile + *i + " " + outputFile + *i;
if (verbose) cout << timestamp() << "Sending command: '" << command << "'" << endl;
int ret = system(command.c_str());
if (ret) {
cerr << "system(" << command << ") returned value " << ret;
exit(1);
}
if (remove((tmpFile + *i).c_str()) != 0)
cerr << "error cleaning up temporary file" << endl;
}
}
return 0;
}