-
Notifications
You must be signed in to change notification settings - Fork 24
/
gtc2vcf.c
3717 lines (3489 loc) · 169 KB
/
gtc2vcf.c
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* The MIT License
Copyright (c) 2018-2024 Giulio Genovese
Author: Giulio Genovese <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <getopt.h>
#include <errno.h>
#include <sys/resource.h>
#include <htslib/vcf.h>
#include <htslib/kseq.h>
#include <htslib/khash_str2int.h>
#include "bcftools.h"
#include "tsv2vcf.h"
#include "gtc2vcf.h"
#define GTC2VCF_VERSION "2024-09-27"
#define GT_NC 0
#define GT_AA 1
#define GT_AB 2
#define GT_BB 3
#define TAG_LIST_DFLT "GT,GQ,IGC,BAF,LRR,NORMX,NORMY,R,THETA,X,Y"
#define GC_WIN_DFLT "200"
#define CAPACITY_DFLT "32768"
#define GENOME_BUILD_DFLT "GRCh38"
#define VERBOSE (1 << 0)
#define BPM_LOADED (1 << 1)
#define CSV_LOADED (1 << 2)
#define EGT_LOADED (1 << 3)
#define LOAD_IDAT (1 << 4)
#define ADJUST_CLUSTERS (1 << 5)
#define GENOME_STUDIO (1 << 6)
#define NO_INFO_GC (1 << 7)
#define FORMAT_GT (1 << 8)
#define FORMAT_GQ (1 << 9)
#define FORMAT_IGC (1 << 10)
#define FORMAT_BAF (1 << 11)
#define FORMAT_LRR (1 << 12)
#define FORMAT_NORMX (1 << 13)
#define FORMAT_NORMY (1 << 14)
#define FORMAT_R (1 << 15)
#define FORMAT_THETA (1 << 16)
#define FORMAT_X (1 << 17)
#define FORMAT_Y (1 << 18)
/****************************************
* hFILE READING FUNCTIONS *
****************************************/
// read or skip a fixed length array
static void read_array(hFILE *hfile, void **arr, size_t *m_arr, size_t nmemb, size_t size, size_t term) {
if (arr) {
if (!m_arr) {
*arr = malloc((nmemb + term) * size);
if (!*arr) error("Failed to allocate memory for array\n");
} else if (*m_arr < nmemb + term) {
void *tmp = realloc(*arr, (nmemb + term) * size);
if (!tmp) error("Failed to allocate memory for array\n");
*arr = tmp;
*m_arr = nmemb + term;
}
if (hread(hfile, *arr, nmemb * size) < nmemb * size) {
error("Failed to read %ld bytes from stream\n", nmemb * size);
}
} else {
int i, c = 0;
for (i = 0; i < nmemb * size; i++) c = hgetc(hfile);
if (c == EOF) error("Failed to reposition stream forward %ld bytes\n", nmemb * size);
}
}
// read or skip a length-prefixed array
static void read_pfx_array(hFILE *hfile, void **arr, size_t *m_arr, size_t item_size) {
int32_t n;
if (hread(hfile, (void *)&n, 4) < 4) {
error("Failed to read 4 bytes from stream\n");
}
read_array(hfile, arr, m_arr, n, item_size, 0);
}
// read or skip a length-prefixed string
// http://en.wikipedia.org/wiki/LEB128#Decode_unsigned_integer
static void read_pfx_string(hFILE *hfile, char **str, size_t *m_str) {
uint8_t byte;
size_t n = 0, shift = 0;
while (1) {
if (hread(hfile, (void *)&byte, 1) < 1) {
error("Failed to read 1 byte from stream\n");
}
n |= (size_t)(byte & 0x7F) << shift;
if (!(byte & 0x80)) break;
shift += 7;
}
if (n || m_str) {
read_array(hfile, (void **)str, m_str, n, 1, 1);
if (str) (*str)[n] = '\0';
}
}
// check whether file is compressed with gzip
static int is_gzip(hFILE *hfile) {
uint8_t buffer[2];
if (hpeek(hfile, (void *)buffer, 2) < 2) error("Failed to read 2 bytes from stream\n");
return (buffer[0] == 0x1f && buffer[1] == 0x8b);
}
/****************************************
* BUFFER ARRAY IMPLEMENTATION *
****************************************/
typedef struct {
hFILE *hfile;
off_t offset;
int32_t item_num;
int32_t item_offset;
size_t item_capacity;
size_t item_size;
char *buffer;
} buffer_array_t;
static buffer_array_t *buffer_array_init(hFILE *hfile, size_t capacity, size_t item_size) {
buffer_array_t *arr = (buffer_array_t *)malloc(1 * sizeof(buffer_array_t));
arr->hfile = hfile;
read_bytes(hfile, (void *)&arr->item_num, sizeof(int32_t));
arr->offset = htell(arr->hfile);
arr->item_offset = 0;
arr->item_capacity = (capacity <= 0) ? (size_t)strtol(CAPACITY_DFLT, NULL, 0) : capacity;
arr->item_size = item_size;
arr->buffer = (char *)malloc(arr->item_capacity * item_size);
read_bytes(hfile, (void *)arr->buffer,
(arr->item_num < arr->item_capacity ? arr->item_num : arr->item_capacity) * item_size);
return arr;
}
static int get_element(buffer_array_t *arr, void *dst, size_t item_idx) {
if (!arr || item_idx >= arr->item_num) {
return -1;
} else if (item_idx - arr->item_offset < arr->item_capacity) {
memcpy(dst, (void *)(arr->buffer + (item_idx - arr->item_offset) * arr->item_size), arr->item_size);
return 0;
}
arr->item_offset = item_idx;
if (hseek(arr->hfile, arr->offset + item_idx * arr->item_size, SEEK_SET) < 0) {
error("Fail to seek to position %ld in file\n", arr->offset + item_idx * arr->item_size);
}
read_bytes(arr->hfile, (void *)arr->buffer,
((arr->item_num - arr->item_offset) < arr->item_capacity ? (arr->item_num - arr->item_offset)
: arr->item_capacity)
* arr->item_size);
memcpy(dst, (void *)arr->buffer, arr->item_size);
return 0;
}
static void buffer_array_destroy(buffer_array_t *arr) {
if (!arr) return;
free(arr->buffer);
free(arr);
}
/****************************************
* BPM FILE IMPLEMENTATION *
****************************************/
// http://github.com/snewhouse/glu-genetics/blob/master/glu/lib/illumina.py
// http://github.com/Illumina/BeadArrayFiles/blob/develop/module/BeadPoolManifest.py
typedef struct {
int32_t version;
uint8_t norm_id; // Normalization lookups from manifest. This indexes into list of
// normalization transforms read from GTC file
char *ilmn_id; // IlmnID (probe identifier) of locus
char *name; // Name (variant identifier) of locus
int32_t index;
char *ilmn_strand; // TOP BOT PLUS MINUS or Top Bot P M
char *snp; // SNP value for locus (e.g., [A/C])
char *chrom; // Chromosome for the locus (e.g., XY)
char *ploidy;
char *species;
char *map_info; // Mapping location of locus
char *customer_strand;
int32_t address_a; // AddressA ID of locus
char *allele_a_probe_seq; // CSV files or BPM files with version 4 data block
int32_t address_b; // AddressB ID of locus (0 if none)
char *allele_b_probe_seq; // CSV files or BPM files with version 4 data block (empty if
// none)
char *genome_build;
char *source;
char *source_version;
char *source_strand;
char *source_seq; // CSV files or BPM files with version 4 data block
char *top_genomic_seq; // CSV files or BPM files with version 4 data block
int32_t beadset_id; // CSV files
uint8_t exp_clusters;
uint8_t intensity_only;
uint8_t assay_type; // Identifies type of assay (0 - Infinium II, 1 - Infinium I (A/T),
// 2 - Infinium I (G/C)
uint8_t assay_type_csv;
float frac_a;
float frac_c;
float frac_g;
float frac_t;
char *ref_strand; // RefStrand annotation
} LocusEntry;
// retrieve assay type following (allele_a_probe_seq, source_seq) -> assay_type map
// (...W., ...W[./.]W...) -> 1
// (...S., ...S[./.]S...) -> 2
// (...S., ...S[./.]W...) -> 1
// (...S., ...W[./.]S...) -> 1
// (...W., ...S[./.]W...) -> 2
// (...W., ...W[./.]S...) -> 2
static uint8_t get_assay_type(const char *allele_a_probe_seq, const char *allele_b_probe_seq, const char *source_seq) {
if (!allele_a_probe_seq || !source_seq) return 0xFF;
if (!allele_b_probe_seq) return 0;
const char *left = strchr(source_seq, '[');
const char *right = strchr(source_seq, ']');
if (!left || !right) error("Source sequence is malformed: %s\n", source_seq);
char trail_left = toupper(*(left - 1));
char trail_right = toupper(*(right + 1));
if ((trail_left == 'A' || trail_left == 'T') && (trail_right == 'A' || trail_right == 'T')) return 1;
if ((trail_left == 'C' || trail_left == 'G') && (trail_right == 'C' || trail_right == 'G')) return 2;
int i = 2;
while (!(iupac2bitmask(allele_a_probe_seq[strlen(allele_a_probe_seq) - i])
& iupac2bitmask(allele_b_probe_seq[strlen(allele_b_probe_seq) - i])))
i++;
char trail_a_probe_seq = toupper(allele_a_probe_seq[strlen(allele_a_probe_seq) - i]);
if (trail_a_probe_seq == 'C' || trail_a_probe_seq == 'G' || trail_a_probe_seq == 'S') return 1;
if (trail_a_probe_seq == 'A' || trail_a_probe_seq == 'T' || trail_a_probe_seq == 'W') return 2;
// these weird rule were deduced from manifests for array GDA_PGx-8v1-0_20042614
if (trail_a_probe_seq == 'Y' && trail_right == 'G') return 1;
if (trail_a_probe_seq == 'Y' && trail_right == 'T') return 1;
if (trail_a_probe_seq == 'Y' && trail_right == 'A') return 2;
if (trail_a_probe_seq == 'K' && trail_right == 'C') return 1;
if (trail_a_probe_seq == 'K' && trail_right == 'A') return 2;
if (trail_a_probe_seq == 'M' && trail_right == 'G') return 1;
if (trail_a_probe_seq == 'M' && trail_right == 'T') return 2;
if (trail_a_probe_seq == 'R' && trail_right == 'C') return 1;
if (trail_a_probe_seq == 'R' && trail_right == 'T') return 2;
fprintf(stderr, "Warning: Unable to retrieve assay type: %s %s %s\n", allele_a_probe_seq, allele_b_probe_seq,
source_seq);
return 0xFF;
}
static void locusentry_read(LocusEntry *locus_entry, hFILE *hfile) {
locus_entry->norm_id = 0xFF;
read_bytes(hfile, (void *)&locus_entry->version, sizeof(int32_t));
if (locus_entry->version < 4 || locus_entry->version == 5 || locus_entry->version > 8)
error("Locus version %d in manifest file not supported\n", locus_entry->version);
read_pfx_string(hfile, &locus_entry->ilmn_id, NULL);
read_pfx_string(hfile, &locus_entry->name, NULL);
read_pfx_string(hfile, NULL, NULL); // ASOA
read_pfx_string(hfile, NULL, NULL); // ASOB
read_pfx_string(hfile, NULL, NULL); // LSO
read_bytes(hfile, (void *)&locus_entry->index, sizeof(int32_t));
read_pfx_string(hfile, NULL, NULL); // IllumicodeSeq
read_pfx_string(hfile, &locus_entry->ilmn_strand, NULL);
read_pfx_string(hfile, &locus_entry->snp, NULL);
read_pfx_string(hfile, &locus_entry->chrom, NULL);
read_pfx_string(hfile, &locus_entry->ploidy, NULL);
read_pfx_string(hfile, &locus_entry->species, NULL);
read_pfx_string(hfile, &locus_entry->map_info, NULL);
read_pfx_string(hfile, &locus_entry->top_genomic_seq, NULL); // only version 4
read_pfx_string(hfile, &locus_entry->customer_strand, NULL);
read_bytes(hfile, (void *)&locus_entry->address_a, sizeof(int32_t));
read_bytes(hfile, (void *)&locus_entry->address_b, sizeof(int32_t));
read_pfx_string(hfile, &locus_entry->allele_a_probe_seq, NULL); // only version 4
read_pfx_string(hfile, &locus_entry->allele_b_probe_seq, NULL); // only version 4
read_pfx_string(hfile, &locus_entry->genome_build, NULL);
read_pfx_string(hfile, &locus_entry->source, NULL);
read_pfx_string(hfile, &locus_entry->source_version, NULL);
read_pfx_string(hfile, &locus_entry->source_strand, NULL);
read_pfx_string(hfile, &locus_entry->source_seq, NULL); // only version 4
if (locus_entry->source_seq) {
char *ptr = strchr(locus_entry->source_seq, '-');
if (ptr && *(ptr - 1) == '/') {
*ptr = *(ptr - 2);
*(ptr - 2) = '-';
}
}
if (locus_entry->version >= 6) {
read_bytes(hfile, NULL, 1); // MarkerInCNVRegion
read_bytes(hfile, (void *)&locus_entry->exp_clusters, sizeof(int8_t));
read_bytes(hfile, (void *)&locus_entry->intensity_only, sizeof(int8_t));
read_bytes(hfile, (void *)&locus_entry->assay_type, sizeof(uint8_t));
if (locus_entry->assay_type < 0 || locus_entry->assay_type > 2)
error("Format error in reading assay type from locus entry\n");
if (locus_entry->address_b == 0 && locus_entry->assay_type != 0)
error("Manifest format error: Assay type is inconsistent with address B\n");
if (locus_entry->address_b != 0 && locus_entry->assay_type == 0)
error("Manifest format error: Assay type is inconsistent with address B\n");
} else {
locus_entry->assay_type =
get_assay_type(locus_entry->allele_a_probe_seq, locus_entry->allele_b_probe_seq, locus_entry->source_seq);
}
if (locus_entry->version >= 7) {
read_bytes(hfile, &locus_entry->frac_a, sizeof(float));
read_bytes(hfile, &locus_entry->frac_c, sizeof(float));
read_bytes(hfile, &locus_entry->frac_t, sizeof(float));
read_bytes(hfile, &locus_entry->frac_g, sizeof(float));
}
if (locus_entry->version >= 8) read_pfx_string(hfile, &locus_entry->ref_strand, NULL);
}
typedef struct {
char *fn;
hFILE *hfile; // bpm file
htsFile *fp; // csv file
int32_t version;
char *manifest_name; // Name of manifest
char *control_config; // Control description from manifest
int32_t num_loci; // Number of loci in manifest
int32_t *indexes;
char **names; // Names of loci from manifest
void *names2index;
uint8_t *norm_ids;
LocusEntry *locus_entries;
uint8_t *norm_lookups;
char **header;
size_t m_header;
} bpm_t;
static uint8_t *bpm_norm_lookups(bpm_t *bpm) {
int i;
uint8_t sorted_norm_ids[256];
for (i = 0; i < 256; i++) sorted_norm_ids[i] = 0xFF;
for (i = 0; i < bpm->num_loci; i++) {
int norm_id = bpm->locus_entries[i].norm_id;
sorted_norm_ids[norm_id] = norm_id;
}
int j = 0;
for (i = 0; i < 256; i++)
if (sorted_norm_ids[i] != 0xFF) sorted_norm_ids[j++] = sorted_norm_ids[i];
uint8_t *norm_lookups = (uint8_t *)malloc(256 * sizeof(uint8_t *));
memset((void *)norm_lookups, 0xFF, 256 * sizeof(uint8_t *));
for (i = 0; i < j; i++) norm_lookups[sorted_norm_ids[i]] = i;
return norm_lookups;
}
static bpm_t *bpm_init(const char *fn, int eof_check, int make_dict) {
bpm_t *bpm = (bpm_t *)calloc(1, sizeof(bpm_t));
bpm->fn = strdup(fn);
bpm->hfile = hopen(bpm->fn, "rb");
if (bpm->hfile == NULL) error("Could not open %s: %s\n", bpm->fn, strerror(errno));
if (is_gzip(bpm->hfile)) error("File %s is gzip compressed and currently cannot be sought\n", bpm->fn);
int i;
uint8_t buffer[4];
if (hread(bpm->hfile, (void *)buffer, 4) < 4) error("Failed to read magic number from %s file\n", bpm->fn);
if (memcmp(buffer, "BPM", 3) != 0) error("BPM file %s format identifier is bad\n", bpm->fn);
if (buffer[3] != 1) error("BPM file %s version is unknown\n", bpm->fn);
read_bytes(bpm->hfile, (void *)&bpm->version, sizeof(int32_t));
if (bpm->version & 0x1000) bpm->version ^= 0x1000;
if (bpm->version > 5 || bpm->version < 3) error("BPM file %s version %d is unsupported\n", bpm->fn, bpm->version);
read_pfx_string(bpm->hfile, &bpm->manifest_name, NULL);
if (bpm->version > 1) read_pfx_string(bpm->hfile, &bpm->control_config, NULL);
read_bytes(bpm->hfile, (void *)&bpm->num_loci, sizeof(int32_t));
read_array(bpm->hfile, (void **)&bpm->indexes, NULL, bpm->num_loci, sizeof(int32_t), 0);
bpm->names = (char **)malloc(bpm->num_loci * sizeof(char *));
for (i = 0; i < bpm->num_loci; i++) read_pfx_string(bpm->hfile, &bpm->names[i], NULL);
if (make_dict) {
bpm->names2index = khash_str2int_init();
for (i = 0; i < bpm->num_loci; i++) {
if (khash_str2int_has_key(bpm->names2index, bpm->names[i]))
error("Illumina probe %s present multiple times in file %s\n", bpm->names[i], fn);
khash_str2int_inc(bpm->names2index, bpm->names[i]);
}
}
read_array(bpm->hfile, (void **)&bpm->norm_ids, NULL, bpm->num_loci, sizeof(uint8_t), 0);
bpm->locus_entries = (LocusEntry *)malloc(bpm->num_loci * sizeof(LocusEntry));
LocusEntry locus_entry;
for (i = 0; i < bpm->num_loci; i++) {
memset(&locus_entry, 0, sizeof(LocusEntry));
locusentry_read(&locus_entry, bpm->hfile);
int idx = locus_entry.index - 1;
if (idx < 0 || idx >= bpm->num_loci) error("Locus entry index %d is out of boundaries\n", locus_entry.index);
if (bpm->norm_ids[idx] > 100)
error("Manifest format error: read invalid normalization ID %d\n", bpm->norm_ids[idx]);
// To mimic the flawed byte-wrapping behavior from GenomeStudio, AutoCall, and
// IAAP, this value is allowed to overflow beyond 255, which happens with some
// probes in the Omni5 arrays
bpm->norm_ids[idx] += 100 * locus_entry.assay_type;
locus_entry.norm_id = bpm->norm_ids[idx];
memcpy(&bpm->locus_entries[idx], &locus_entry, sizeof(LocusEntry));
}
bpm->norm_lookups = bpm_norm_lookups(bpm);
for (i = 0; i < bpm->num_loci; i++) {
if (i != bpm->locus_entries[i].index - 1)
error("Manifest format error: read invalid number of assay entries\n");
}
if (bpm->locus_entries[0].version < 8)
fprintf(stderr, "Warning: RefStrand annotation missing from manifest file %s\n", bpm->fn);
read_bytes(bpm->hfile, (void *)&bpm->m_header, sizeof(int32_t));
bpm->header = (char **)malloc(bpm->m_header * sizeof(char *));
for (i = 0; i < bpm->m_header; i++) read_pfx_string(bpm->hfile, &bpm->header[i], NULL);
if (eof_check && !heof(bpm->hfile))
error(
"BPM reader did not reach the end of file %s at position %ld\nUse --do-not-check-eof to suppress this "
"check\n",
bpm->fn, htell(bpm->hfile));
return bpm;
}
static void bpm_destroy(bpm_t *bpm) {
if (!bpm) return;
int i;
if (bpm->hfile && hclose(bpm->hfile) < 0) error("Error closing BPM file %s\n", bpm->fn);
free(bpm->fn);
if (bpm->fp && hts_close(bpm->fp) < 0) error("Error closing CSV file %s\n", bpm->fp->fn);
free(bpm->manifest_name);
free(bpm->control_config);
free(bpm->indexes);
if (bpm->names) {
for (i = 0; i < bpm->num_loci; i++) free(bpm->names[i]);
free(bpm->names);
}
khash_str2int_destroy(bpm->names2index);
free(bpm->norm_ids);
for (i = 0; i < bpm->num_loci; i++) {
LocusEntry *locus_entry = &bpm->locus_entries[i];
free(locus_entry->ilmn_id);
free(locus_entry->name);
free(locus_entry->ilmn_strand);
free(locus_entry->snp);
free(locus_entry->chrom);
free(locus_entry->ploidy);
free(locus_entry->species);
free(locus_entry->map_info);
free(locus_entry->customer_strand);
free(locus_entry->allele_a_probe_seq);
free(locus_entry->allele_b_probe_seq);
free(locus_entry->genome_build);
free(locus_entry->source);
free(locus_entry->source_version);
free(locus_entry->source_strand);
free(locus_entry->source_seq);
free(locus_entry->top_genomic_seq);
free(locus_entry->ref_strand);
}
free(bpm->locus_entries);
free(bpm->norm_lookups);
for (i = 0; i < bpm->m_header; i++) free(bpm->header[i]);
free(bpm->header);
free(bpm);
}
static void bpm_to_csv(const bpm_t *bpm, FILE *stream, int flags) {
int i;
for (i = 0; i < bpm->m_header; i++) fprintf(stream, "%s\n", bpm->header[i]);
if (flags & BPM_LOADED) {
fprintf(stream,
"Index,NormID,IlmnID,Name,IlmnStrand,SNP,AddressA_ID,AlleleA_ProbeSeq,AddressB_"
"ID,AlleleB_ProbeSeq,GenomeBuild,Chr,MapInfo,Ploidy,Species,Source,"
"SourceVersion,SourceStrand,SourceSeq,TopGenomicSeq,BeadSetID,Exp_Clusters,"
"Intensity_Only,Assay_Type,Frac A,Frac C,Frac G,Frac T,RefStrand");
if (flags & CSV_LOADED) fprintf(stream, ",Assay_Type_CSV");
fputc('\n', stream);
} else {
fprintf(stream,
"IlmnID,Name,IlmnStrand,SNP,AddressA_ID,AlleleA_ProbeSeq,AddressB_ID,AlleleB_"
"ProbeSeq,GenomeBuild,Chr,MapInfo,Ploidy,Species,Source,SourceVersion,"
"SourceStrand,SourceSeq,TopGenomicSeq,BeadSetID,Exp_Clusters,RefStrand\n");
}
if (flags & VERBOSE) {
kstring_t address_b = {0, 0, NULL};
if (flags & BPM_LOADED) {
for (i = 0; i < bpm->num_loci; i++) {
LocusEntry *locus_entry = &bpm->locus_entries[i];
address_b.l = 0;
ksprintf(&address_b, locus_entry->address_b ? "%010d" : "", locus_entry->address_b);
fprintf(stream,
"%d,%d,%s,%s,%s,%s,%010d,%-s,%s,%-s,%s,%s,%s,%s,%s,%s,%s,%s,%-s,%-s,%d,"
"%d,%d,%d,%f,%f,%f,%f,%s",
locus_entry->index, locus_entry->norm_id, locus_entry->ilmn_id, locus_entry->name,
locus_entry->ilmn_strand, locus_entry->snp, locus_entry->address_a,
locus_entry->allele_a_probe_seq ? locus_entry->allele_a_probe_seq : "", address_b.s,
locus_entry->allele_b_probe_seq ? locus_entry->allele_b_probe_seq : "",
locus_entry->genome_build, locus_entry->chrom, locus_entry->map_info, locus_entry->ploidy,
locus_entry->species, locus_entry->source, locus_entry->source_version,
locus_entry->source_strand, locus_entry->source_seq ? locus_entry->source_seq : "",
locus_entry->top_genomic_seq ? locus_entry->top_genomic_seq : "", locus_entry->beadset_id,
locus_entry->exp_clusters, locus_entry->intensity_only, locus_entry->assay_type,
locus_entry->frac_a, locus_entry->frac_c, locus_entry->frac_g, locus_entry->frac_t,
locus_entry->ref_strand ? locus_entry->ref_strand : "");
if (flags & CSV_LOADED) fprintf(stream, ",%d", locus_entry->assay_type_csv);
fputc('\n', stream);
}
} else {
for (i = 0; i < bpm->num_loci; i++) {
LocusEntry *locus_entry = &bpm->locus_entries[i];
address_b.l = 0;
ksprintf(&address_b, locus_entry->address_b ? "%010d" : "", locus_entry->address_b);
fprintf(stream, "%s,%s,%s,%s,%010d,%-s,%s,%-s,%s,%s,%s,%s,%s,%s,%s,%s,%-s,%-s,%d,%d,%s\n",
locus_entry->ilmn_id, locus_entry->name, locus_entry->ilmn_strand, locus_entry->snp,
locus_entry->address_a, locus_entry->allele_a_probe_seq, address_b.s,
locus_entry->allele_b_probe_seq ? locus_entry->allele_b_probe_seq : "",
locus_entry->genome_build, locus_entry->chrom, locus_entry->map_info, locus_entry->ploidy,
locus_entry->species, locus_entry->source, locus_entry->source_version,
locus_entry->source_strand, locus_entry->source_seq, locus_entry->top_genomic_seq,
locus_entry->beadset_id, locus_entry->exp_clusters,
locus_entry->ref_strand ? locus_entry->ref_strand : "");
}
}
free(address_b.s);
} else {
fprintf(stream, "... use --verbose to visualize Assay data ...\n");
}
fprintf(stream, "[Controls]\n");
fprintf(stream, "%s", bpm->control_config);
}
/****************************************
* CSV FILE IMPLEMENTATION *
****************************************/
static int tsv_read_uint8(tsv_t *tsv, bcf1_t *rec, void *usr) {
uint8_t *uint8 = (uint8_t *)usr;
char tmp = *tsv->se;
*tsv->se = 0;
char *endptr;
*uint8 = (uint8_t)strtol(tsv->ss, &endptr, 0);
*tsv->se = tmp;
return 0;
}
static int tsv_read_int32(tsv_t *tsv, bcf1_t *rec, void *usr) {
int32_t *int32 = (int32_t *)usr;
char tmp = *tsv->se;
*tsv->se = 0;
char *endptr;
*int32 = (int32_t)strtol(tsv->ss, &endptr, 10);
*tsv->se = tmp;
return 0;
}
static int tsv_read_float(tsv_t *tsv, bcf1_t *rec, void *usr) {
float *single = (float *)usr;
char tmp = *tsv->se;
*tsv->se = 0;
char *endptr;
*single = (float)strtof(tsv->ss, &endptr);
*tsv->se = tmp;
return 0;
}
static int tsv_read_string(tsv_t *tsv, bcf1_t *rec, void *usr) {
char **str = (char **)usr;
if (tsv->se == tsv->ss) {
*str = NULL;
} else {
char tmp = *tsv->se;
*tsv->se = 0;
*str = strdup(tsv->ss);
*tsv->se = tmp;
}
return 0;
}
// Petr Danecek's similar implementation in bcftools/tsv2vcf.c
static int csv_parse(tsv_t *tsv, bcf1_t *rec, char *str) {
int status = 0;
tsv->icol = 0;
tsv->ss = tsv->se = str;
while (*tsv->ss && tsv->icol < tsv->ncols) {
while (*tsv->se && *tsv->se != ',') tsv->se++;
if (tsv->cols[tsv->icol].setter) {
int ret = tsv->cols[tsv->icol].setter(tsv, rec, tsv->cols[tsv->icol].usr);
if (ret < 0) return -1;
status++;
}
if (*tsv->se) tsv->se++;
tsv->ss = tsv->se;
tsv->icol++;
}
return status ? 0 : -1;
}
static void locus_merge(LocusEntry *dest, LocusEntry *src) {
if (src->version) dest->version = src->version;
if (src->norm_id != 0xFF) dest->norm_id = src->norm_id;
if (strcmp(dest->ilmn_id, src->ilmn_id)) {
error("BPM and CSV manifests have conflicting IDs: %s and %s\n", dest->ilmn_id, src->ilmn_id);
} else {
free(dest->ilmn_id);
dest->ilmn_id = src->ilmn_id;
}
if (src->name) {
free(dest->name);
dest->name = src->name;
}
if (src->index != 0) dest->index = src->index;
if (src->ilmn_strand) {
free(dest->ilmn_strand);
dest->ilmn_strand = src->ilmn_strand;
}
if (src->snp) {
free(dest->snp);
dest->snp = src->snp;
}
if (src->chrom) {
free(dest->chrom);
dest->chrom = src->chrom;
}
if (src->ploidy) {
free(dest->ploidy);
dest->ploidy = src->ploidy;
}
if (src->species) {
free(dest->species);
dest->species = src->species;
}
if (src->map_info) {
free(dest->map_info);
dest->map_info = src->map_info;
}
if (src->customer_strand) {
free(dest->customer_strand);
dest->customer_strand = src->customer_strand;
}
if (src->address_a != 0) dest->address_a = src->address_a;
if (src->allele_a_probe_seq) {
free(dest->allele_a_probe_seq);
dest->allele_a_probe_seq = src->allele_a_probe_seq;
}
if (src->address_b != 0) dest->address_b = src->address_b;
if (src->allele_b_probe_seq) {
free(dest->allele_b_probe_seq);
dest->allele_b_probe_seq = src->allele_b_probe_seq;
}
if (src->genome_build) {
free(dest->genome_build);
dest->genome_build = src->genome_build;
}
if (src->source) {
free(dest->source);
dest->source = src->source;
}
if (src->source_version) {
free(dest->source_version);
dest->source_version = src->source_version;
}
if (src->source_strand) {
free(dest->source_strand);
dest->source_strand = src->source_strand;
}
if (src->source_seq) {
free(dest->source_seq);
dest->source_seq = src->source_seq;
}
if (src->top_genomic_seq) {
free(dest->top_genomic_seq);
dest->top_genomic_seq = src->top_genomic_seq;
}
if (src->beadset_id) dest->beadset_id = src->beadset_id;
if (src->exp_clusters) dest->exp_clusters = src->exp_clusters;
if (src->intensity_only) dest->intensity_only = src->intensity_only;
if (src->assay_type != 0xFF) dest->assay_type = src->assay_type;
if (src->assay_type_csv != 0xFF) dest->assay_type_csv = src->assay_type_csv;
if (src->frac_a) dest->frac_a = src->frac_a;
if (src->frac_c) dest->frac_c = src->frac_c;
if (src->frac_g) dest->frac_g = src->frac_g;
if (src->frac_t) dest->frac_t = src->frac_t;
if (src->ref_strand) {
free(dest->ref_strand);
dest->ref_strand = src->ref_strand;
}
}
// this line will read a CSV file and if a BPM object is provided it will fill it rather than
// create a new one
static bpm_t *bpm_csv_init(const char *fn, bpm_t *bpm, int make_dict) {
int bpm_available = bpm != NULL;
if (!bpm_available) bpm = (bpm_t *)calloc(1, sizeof(bpm_t));
int bpm_prev_num_loci = bpm->num_loci;
bpm->fp = hts_open(fn, "r");
if (bpm->fp == NULL) error("Could not open %s: %s\n", fn, strerror(errno));
kstring_t str = {0, 0, NULL};
kstring_t hdr = {0, 0, NULL};
if (hts_getline(bpm->fp, KS_SEP_LINE, &str) <= 0) error("Empty file: %s\n", fn);
if (strncmp(str.s, "Illumina", 8) && strncmp(str.s, "\"Illumina", 9))
error("Header of file %s is incorrect: %s\n", fn, str.s);
kputs(str.s, &hdr);
kputc('\n', &hdr);
char *tmp = NULL;
size_t prev = 0;
while (strncmp(str.s + prev, "[Assay]", 7)) {
if (strncmp(str.s + prev, "Descriptor File Name,", 21) == 0) {
free(bpm->manifest_name);
bpm->manifest_name = strdup(str.s + prev + 21);
char *ptr = strchr(bpm->manifest_name, ',');
if (ptr) *ptr = '\0';
} else if (strncmp(str.s + prev, "Loci Count ,", 12) == 0) {
bpm->num_loci = (int)strtol(str.s + prev + 12, &tmp, 0);
} else if (strncmp(str.s + prev, "Loci Count,", 11) == 0) {
bpm->num_loci = (int)strtol(str.s + prev + 11, &tmp, 0);
}
if (hts_getline(bpm->fp, KS_SEP_LINE, &str) <= 0) error("Error reading from file: %s\n", fn);
kputs(str.s, &hdr);
kputc('\n', &hdr);
}
if (bpm->num_loci == 0)
error("Could not understand number of loci from header of manifest file %s\n", fn);
else if (bpm_available && bpm_prev_num_loci != bpm->num_loci)
error("BPM manifest file has %d loci while CSV manifest file %s has %d loci\n", bpm_prev_num_loci, fn,
bpm->num_loci);
int i, moff = 0, *off = NULL;
for (i = 0; i < bpm->m_header; i++) free(bpm->header[i]);
bpm->m_header = ksplit_core(hdr.s, '\n', &moff, &off);
free(bpm->header);
bpm->header = (char **)malloc(bpm->m_header * sizeof(char *));
for (i = 0; i < bpm->m_header; i++) bpm->header[i] = strdup(&hdr.s[off[i]]);
free(off);
free(hdr.s);
if (hts_getline(bpm->fp, KS_SEP_LINE, &str) <= 0) error("Error reading from file: %s\n", fn);
LocusEntry locus_entry;
tsv_t *tsv = tsv_init(str.s);
tsv_register(tsv, "Index", tsv_read_int32, &locus_entry.index);
int norm_id = tsv_register(tsv, "NormID", tsv_read_uint8, &locus_entry.norm_id);
tsv_register(tsv, "IlmnID", tsv_read_string, &locus_entry.ilmn_id);
tsv_register(tsv, "Name", tsv_read_string, &locus_entry.name);
tsv_register(tsv, "IlmnStrand", tsv_read_string, &locus_entry.ilmn_strand);
tsv_register(tsv, "SNP", tsv_read_string, &locus_entry.snp);
tsv_register(tsv, "AddressA_ID", tsv_read_int32, &locus_entry.address_a);
tsv_register(tsv, "AlleleA_ProbeSeq", tsv_read_string, &locus_entry.allele_a_probe_seq);
tsv_register(tsv, "AddressB_ID", tsv_read_int32, &locus_entry.address_b);
tsv_register(tsv, "AlleleB_ProbeSeq", tsv_read_string, &locus_entry.allele_b_probe_seq);
tsv_register(tsv, "GenomeBuild", tsv_read_string, &locus_entry.genome_build);
tsv_register(tsv, "Chr", tsv_read_string, &locus_entry.chrom);
tsv_register(tsv, "MapInfo", tsv_read_string, &locus_entry.map_info);
tsv_register(tsv, "Ploidy", tsv_read_string, &locus_entry.ploidy);
tsv_register(tsv, "Species", tsv_read_string, &locus_entry.species);
tsv_register(tsv, "Source", tsv_read_string, &locus_entry.source);
tsv_register(tsv, "SourceVersion", tsv_read_string, &locus_entry.source_version);
tsv_register(tsv, "SourceStrand", tsv_read_string, &locus_entry.source_strand);
tsv_register(tsv, "SourceSeq", tsv_read_string, &locus_entry.source_seq);
tsv_register(tsv, "TopGenomicSeq", tsv_read_string, &locus_entry.top_genomic_seq);
int beadset_id = tsv_register(tsv, "BeadSetID", tsv_read_int32, &locus_entry.beadset_id);
tsv_register(tsv, "Exp_Clusters", tsv_read_uint8, &locus_entry.exp_clusters);
tsv_register(tsv, "Intensity_Only", tsv_read_uint8, &locus_entry.intensity_only);
tsv_register(tsv, "Frac A", tsv_read_float, &locus_entry.frac_a);
tsv_register(tsv, "Frac C", tsv_read_float, &locus_entry.frac_c);
tsv_register(tsv, "Frac G", tsv_read_float, &locus_entry.frac_g);
tsv_register(tsv, "Frac T", tsv_read_float, &locus_entry.frac_t);
int ref_strand = tsv_register(tsv, "RefStrand", tsv_read_string, &locus_entry.ref_strand);
if (ref_strand < 0) fprintf(stderr, "Warning: RefStrand annotation missing from manifest file %s\n", fn);
if (!bpm_available) bpm->locus_entries = (LocusEntry *)malloc(bpm->num_loci * sizeof(LocusEntry));
for (i = 0; i < bpm->num_loci; i++) {
memset(&locus_entry, 0, sizeof(LocusEntry));
locus_entry.norm_id = 0xFF;
locus_entry.assay_type = 0xFF;
locus_entry.assay_type_csv = 0xFF;
if (hts_getline(bpm->fp, KS_SEP_LINE, &str) <= 0) error("Error reading from file: %s\n", fn);
if (csv_parse(tsv, NULL, str.s) < 0) error("Could not parse the manifest file: %s\n", str.s);
if (beadset_id == 0 && locus_entry.beadset_id == 0)
error("BeadSetID value 0 for probe %s is not allowed\n", locus_entry.ilmn_id);
if (locus_entry.source_seq) {
char *ptr = strchr(locus_entry.source_seq, '-');
if (ptr && *(ptr - 1) == '/') {
*ptr = *(ptr - 2);
*(ptr - 2) = '-';
}
}
locus_entry.assay_type_csv =
get_assay_type(locus_entry.allele_a_probe_seq, locus_entry.allele_b_probe_seq, locus_entry.source_seq);
if (locus_entry.index == 0) locus_entry.index = i + 1;
int idx = locus_entry.index - 1;
if (idx < 0 || idx >= bpm->num_loci) error("Locus entry index %d is out of boundaries\n", idx);
if (!bpm_available) {
memcpy(&bpm->locus_entries[idx], &locus_entry, sizeof(LocusEntry));
} else {
locus_merge(&bpm->locus_entries[idx], &locus_entry);
if (bpm->locus_entries[idx].assay_type != 0xff
&& bpm->locus_entries[idx].assay_type != bpm->locus_entries[idx].assay_type_csv)
fprintf(stderr, "Warning: Failed to retrieve assay type %d: %s %s %s\n",
bpm->locus_entries[idx].assay_type, bpm->locus_entries[idx].allele_a_probe_seq,
bpm->locus_entries[idx].allele_b_probe_seq, bpm->locus_entries[idx].source_seq);
}
}
tsv_destroy(tsv);
if (hts_getline(bpm->fp, KS_SEP_LINE, &str) <= 0) error("Error reading from file: %s\n", fn);
if (strncmp(str.s, "[Controls]", 10) != 0)
error(
"Missing [Controls] section from manifest file: %s\n"
"Found the following line instead: %s\n",
fn, str.s);
while (hts_getline(bpm->fp, KS_SEP_LINE, &str) > 0) kputc('\n', &str);
free(bpm->control_config);
bpm->control_config = str.s;
if (make_dict && !bpm->names2index) {
bpm->names2index = khash_str2int_init();
for (i = 0; i < bpm->num_loci; i++) {
if (khash_str2int_has_key(bpm->names2index, bpm->locus_entries[i].name))
error("Illumina probe %s present multiple times in file %s\n", bpm->locus_entries[i].name, fn);
khash_str2int_inc(bpm->names2index, bpm->locus_entries[i].name);
}
}
if (norm_id == 0) {
free(bpm->norm_lookups);
bpm->norm_lookups = bpm_norm_lookups(bpm);
}
return bpm;
}
/****************************************
* EGT FILE IMPLEMENTATION *
****************************************/
// http://github.com/broadinstitute/picard/blob/master/src/main/java/picard/arrays/illumina/InfiniumEGTFile.java
// http://github.com/Illumina/BeadArrayFiles/blob/develop/module/ClusterFile.py
typedef struct {
int32_t N; // Number of samples assigned to cluster during training
float r_dev; // R (intensity) std deviation value
float r_mean; // R (intensity) mean value
float theta_dev; // Theta std devation value
float theta_mean; // Theta mean value
} ClusterStats;
typedef struct {
float cluster_separation; // A score measure the separation between genotype clusters
float total_score; // The GenTrain score
float original_score; // The original score before editing this cluster
uint8_t edited; // Whether this cluster has been manually manipulated
} ClusterScore;
typedef struct {
ClusterStats aa_cluster_stats; // Describes AA genotype cluster
ClusterStats ab_cluster_stats; // Describes AB genotype cluster
ClusterStats bb_cluster_stats; // Describes BB genotype cluster
float intensity_threshold; // Intensity threshold for no-call
ClusterScore cluster_score; // Various scores for cluster
int32_t address; // Bead type identifier for probe A
float r_mean; // precomputed clusters mean
} ClusterRecord;
typedef struct {
char *fn;
hFILE *hfile;
int32_t version;
char *gencall_version; // The GenCall version
char *cluster_version; // The clustering algorithm version
char *call_version; // The genotyping algorithm version
char *normalization_version; // The normalization algorithm version
char *date_created; // The date the cluster file was created (e.g., 3/9/2017 2:18:30 PM)
uint8_t is_wgt;
int32_t data_block_version;
char *opa;
char *manifest_name; // The manifest name used to build this cluster file
int32_t num_records;
ClusterRecord *cluster_records;
char **names; // Names of records from manifest
void *names2index;
} egt_t;
static void clusterscore_read(ClusterScore *clusterscore, hFILE *hfile) {
read_bytes(hfile, (void *)&clusterscore->cluster_separation, sizeof(float));
read_bytes(hfile, (void *)&clusterscore->total_score, sizeof(float));
read_bytes(hfile, (void *)&clusterscore->original_score, sizeof(float));
read_bytes(hfile, (void *)&clusterscore->edited, sizeof(uint8_t));
}
static void clusterrecord_read(ClusterRecord *clusterrecord, hFILE *hfile, int32_t data_block_version) {
read_bytes(hfile, (void *)&clusterrecord->aa_cluster_stats.N, sizeof(int32_t));
read_bytes(hfile, (void *)&clusterrecord->ab_cluster_stats.N, sizeof(int32_t));
read_bytes(hfile, (void *)&clusterrecord->bb_cluster_stats.N, sizeof(int32_t));
read_bytes(hfile, (void *)&clusterrecord->aa_cluster_stats.r_dev, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->ab_cluster_stats.r_dev, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->bb_cluster_stats.r_dev, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->aa_cluster_stats.r_mean, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->ab_cluster_stats.r_mean, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->bb_cluster_stats.r_mean, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->aa_cluster_stats.theta_dev, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->ab_cluster_stats.theta_dev, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->bb_cluster_stats.theta_dev, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->aa_cluster_stats.theta_mean, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->ab_cluster_stats.theta_mean, sizeof(float));
read_bytes(hfile, (void *)&clusterrecord->bb_cluster_stats.theta_mean, sizeof(float));
if (data_block_version >= 7) {
read_bytes(hfile, (void *)&clusterrecord->intensity_threshold, sizeof(float));
read_bytes(hfile, NULL, 14 * sizeof(float));
} else {
clusterrecord->intensity_threshold = NAN;
}
}
static egt_t *egt_init(const char *fn, int eof_check) {
int i;
egt_t *egt = (egt_t *)calloc(1, sizeof(egt_t));
egt->fn = strdup(fn);
egt->hfile = hopen(egt->fn, "rb");
if (egt->hfile == NULL) error("Could not open %s: %s\n", egt->fn, strerror(errno));
if (is_gzip(egt->hfile)) error("File %s is gzip compressed and currently cannot be sought\n", egt->fn);
read_bytes(egt->hfile, (void *)&egt->version, sizeof(int32_t));
if (egt->version != 3) error("EGT cluster file version %d not supported\n", egt->version);
read_pfx_string(egt->hfile, &egt->gencall_version, NULL);
read_pfx_string(egt->hfile, &egt->cluster_version, NULL);
read_pfx_string(egt->hfile, &egt->call_version, NULL);
read_pfx_string(egt->hfile, &egt->normalization_version, NULL);
read_pfx_string(egt->hfile, &egt->date_created, NULL);
read_bytes(egt->hfile, (void *)&egt->is_wgt, sizeof(uint8_t));
if (egt->is_wgt != 1) error("Only WGT cluster file version supported\n");
read_pfx_string(egt->hfile, &egt->manifest_name, NULL);
read_bytes(egt->hfile, (void *)&egt->data_block_version, sizeof(int32_t));
if (egt->data_block_version < 5 || egt->data_block_version == 6 || egt->data_block_version > 9)
error("Data block version %d in cluster file not supported\n", egt->data_block_version);
read_pfx_string(egt->hfile, &egt->opa, NULL);
read_bytes(egt->hfile, (void *)&egt->num_records, sizeof(int32_t));
egt->cluster_records = (ClusterRecord *)malloc(egt->num_records * sizeof(ClusterRecord));
for (i = 0; i < egt->num_records; i++)
clusterrecord_read(&egt->cluster_records[i], egt->hfile, egt->data_block_version);
for (i = 0; i < egt->num_records; i++) clusterscore_read(&egt->cluster_records[i].cluster_score, egt->hfile);
// toss useless strings such as aa_ab_bb/aa_ab/aa_bb/ab_bb
for (i = 0; i < egt->num_records; i++) read_pfx_string(egt->hfile, NULL, NULL);
egt->names = (char **)malloc(egt->num_records * sizeof(char *));
egt->names2index = khash_str2int_init();
for (i = 0; i < egt->num_records; i++) {
read_pfx_string(egt->hfile, &egt->names[i], NULL);
if (khash_str2int_has_key(egt->names2index, egt->names[i]))
error("Illumina probe %s present multiple times in file %s\n", egt->names[i], fn);
khash_str2int_inc(egt->names2index, egt->names[i]);
}
for (i = 0; i < egt->num_records; i++)
read_bytes(egt->hfile, (void *)&egt->cluster_records[i].address, sizeof(int32_t));
int32_t aa_n, ab_n, bb_n;
for (i = 0; i < egt->num_records; i++) {
read_bytes(egt->hfile, (void *)&aa_n, sizeof(int32_t));
read_bytes(egt->hfile, (void *)&ab_n, sizeof(int32_t));
read_bytes(egt->hfile, (void *)&bb_n, sizeof(int32_t));
if (egt->cluster_records[i].aa_cluster_stats.N != aa_n || egt->cluster_records[i].ab_cluster_stats.N != ab_n
|| egt->cluster_records[i].bb_cluster_stats.N != bb_n)
error("Cluster counts don't match with EGT cluster file %s\n", egt->fn);
}
if (egt->data_block_version == 9) read_bytes(egt->hfile, NULL, egt->num_records * sizeof(float));
if (eof_check && !heof(egt->hfile))
error(
"EGT reader did not reach the end of file %s at position %ld\nUse --do-not-check-eof to suppress this "
"check\n",
egt->fn, htell(egt->hfile));
for (i = 0; i < egt->num_records; i++) {
ClusterStats *aa = &egt->cluster_records[i].aa_cluster_stats;
ClusterStats *ab = &egt->cluster_records[i].ab_cluster_stats;
ClusterStats *bb = &egt->cluster_records[i].bb_cluster_stats;
egt->cluster_records[i].r_mean =
(aa->N * aa->r_mean + ab->N * ab->r_mean + bb->N * bb->r_mean) / (aa->N + ab->N + bb->N);
}
return egt;