/
vcfgl.cpp
1750 lines (1355 loc) · 59.8 KB
/
vcfgl.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
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
/*
* vcfgl: gl simulator for vcf/bcf files
*
* isinaltinkaya
*
*/
#include <htslib/thread_pool.h> // htsThreadPool
#include <time.h> // clock
#include "shared.h"
#include "io.h"
#include "random_generator.h"
#include "bcf_utils.h"
#include "gl_methods.h"
argStruct* args;
const char* nonref_str;
/// qs_bins[nRanges]
/// qs_bins[i][0] = start of i-th range
/// qs_bins[i][1] = end of i-th range
/// qs_bins[i][2] = qs value to assign for i-th range
static int apply_qs_bins(const int in_qs) {
for (size_t i = 0; i < args->n_qs_bins; ++i) {
if (in_qs >= args->qs_bins[i][0] && in_qs <= args->qs_bins[i][1]) {
return (args->qs_bins[i][2]);
}
}
ERROR("Could not find a range for qs value %d", in_qs);
}
int rec_alleles[5] = { -1, -1, -1, -1, -1 };
int* true_gts_acgt_int = NULL;
int* true_gts_alleles_idx = NULL;
int* n_sim_reads_arr = NULL;
// return value < 0 skip the site
// returns negative value only if program will skip the position given arg values
// skip position reasons:
// -1 all input true genotypes at position are homozygous ref (iff PROGRAM_WILL_SKIP_INPUT_HOMOREFGT_SITES)
// -2 all input true genotypes at position are homozygous alt (iff PROGRAM_WILL_SKIP_INPUT_HOMOALTGT_SITES)
/// @note skips the site in truth VCF as well
inline int check_rec_alleles(simRecord* sim) {
// -------------------------------------------- //
// read genotypes
int32_t ngt_arr = 0;
int ngt = 0;
ngt = bcf_get_genotypes(sim->hdr, sim->rec, &sim->gt_arr, &ngt_arr);
if (ngt <= 0) {
ERROR("Could not find GT tag at position %ld.", sim->rec->pos + 1);
}
const int n_alleles = sim->rec->n_allele;
if (n_alleles > 5) {
ERROR("Multiallelic sites with more than 4 alleles are not supported. If this is a feature you need, please contact the developers or create a feature request on the GitHub page.");
}
const int nSamples = sim->nSamples;
// -> clear
// rec_alleles[0] = -1;
// rec_alleles[1] = -1;
// rec_alleles[2] = -1;
// rec_alleles[3] = -1;
// rec_alleles[4] = -1;
char* allele = NULL;
int x;
for (int i = 0;i < n_alleles;++i) {
allele = sim->rec->d.allele[i];
if (allele[0] == '<') {
ERROR("Allele '%s' at position %ld is not a valid base.", allele, sim->rec->pos + 1);
}
if (allele[1] != '\0') {
ERROR("Allele '%s' at position %ld is not a single base. If this is on purpose and this is a feature you want to use, please contact the developers or create a feature request on the GitHub page.", allele, sim->rec->pos + 1);
}
if (PROGRAM_WILL_USE_ACGT_GTSOURCE) {
if (-1 == (rec_alleles[i] = ACGT_CHAR2INT(allele[0]))) {
ERROR("Allele '%s' at position %ld is not a valid base.", allele, sim->rec->pos + 1);
}
} else if (PROGRAM_WILL_USE_BINARY_GTSOURCE) {
// assume: input vcf always have REF=0 ALT=1
// #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT ind
// chr 1 . 0 1 . PASS . GT 0|1
// then set REF to A and ALT to C:
// chr 1 . A C . PASS . GT 0|1
// make sure REF and ALT are binary
x = allele[0] - '0';
if (x != 0 && x != 1) {
ERROR("[--source %d] Found allele '%s' at position %ld. Only 0 and 1 are allowed when using binary GT source. Please change the source or check your input file.", args->gtSource, allele, sim->rec->pos + 1);
}
rec_alleles[i] = x;
}
}
if (PROGRAM_WILL_USE_BINARY_GTSOURCE) {
if (n_alleles > 2) {
ERROR("Multiallelic sites are not supported when using binary GT source. If this is a feature you need, please contact the developers or create a feature request on the GitHub page.");
}
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, "A,C")));
}
int allelesum = 0;
int a;
for (int i = 0;i < nSamples * SIM_PLOIDY;++i) {
true_gts_acgt_int[i] = -1; // clear
a = bcf_gt_allele(sim->gt_arr[i]);
true_gts_alleles_idx[i] = a;
allelesum += a;
true_gts_acgt_int[i] = ACGT_CHAR2INT(sim->rec->d.allele[a][0]);
}
if (PROGRAM_WILL_SKIP_INPUT_HOMOREFGT_SITES && (0 == allelesum)) {
return(-1);
}
// for each alt, check if all inds are homozygous alt
if (PROGRAM_WILL_SKIP_INPUT_HOMOALTGT_SITES) {
for (a = 1; a < n_alleles; ++a) {
if ((a * nSamples * SIM_PLOIDY) == allelesum) {
return(-2);
}
}
}
#if 0
for (int i = 0;i < n_alleles;++i) {
fprintf(stderr, "Found %s allele: %s with int value %d\n", i == 0 ? "REF" : (i == 1 ? "ALT_1" : (i == 2 ? "ALT_2" : (i == 3 ? "ALT_3" : "ALT_4"))), sim->rec->d.allele[i], rec_alleles[i]);
}
#endif
return(0);
}
inline void write_record_values(htsFile* out_fp, simRecord* sim) {
int ret;
if (NULL == sim->rec) {
// last flush at the program end
ret = prepare_gvcf_block(sim, sim->gvcfd);
DEVASSERT(GVCF_WRITE_SIMREC != ret);
if (GVCF_FLUSH_BLOCK == ret) {
ASSERT(0 == bcf_write(out_fp, sim->hdr, sim->gvcfd->grec));
}
return;
}
if (NULL == sim->gvcfd) {
ASSERT(0 == bcf_write(out_fp, sim->hdr, sim->rec));
return;
} else {
// for flushing gvcf blocks (if any)
// e.g. we have a gvcf block in the buffer but the next record is variant
// so we need to flush the block then write the variant record
ret = prepare_gvcf_block(sim, sim->gvcfd);
if (GVCF_FLUSH_BLOCK == ret) {
// flush block
ASSERT(0 == bcf_write(out_fp, sim->hdr, sim->gvcfd->grec));
// now try again with current record
ret = prepare_gvcf_block(sim, sim->gvcfd);
}
ASSERT(ret != GVCF_FLUSH_BLOCK); // cannot be asking to flush twice
if (GVCF_WRITE_SIMREC == ret) {
ASSERT(0 == bcf_write(out_fp, sim->hdr, sim->rec));
}
if (GVCF_NO_WRITE == ret) {
// write nothing; current block is still growing
return;
}
return;
}
}
// rng1_seeder: seed for poisson distribution
// used if error_qs != 0 so that error_qs 0 gives the same output as angsd
// isolates poisson distribution RNG from other RNGs
// to be able to sample depths from poisson the same way given the same seed
// regardless of --error-qs beta sampling being on or off
unsigned short int rng1_seeder[3] = SEEDER_INIT;
unsigned short int rng1_seeder_save[3] = SEEDER_INIT;
// rng2_seeder: seed for beta distribution
unsigned short int rng2_seeder[3] = SEEDER_INIT;
unsigned short int rng2_seeder_save[3] = SEEDER_INIT;
void(*calculate_gls)(simRecord* sim);
/// @brief simulate a position with no reads for any of the individuals
/// @param sim
/// @return
inline int simulate_site_with_no_reads(simRecord* sim) {
if (args->printPileup) {
ksprintf(sim->pileup, "%s\t%ld\t%c", sim->hdr->id[BCF_DT_CTG][sim->rec->rid].key, sim->rec->pos + 1, sim->rec->d.allele[0][0]);
for (int s = 0; s < sim->nSamples; s++) {
ksprintf(sim->pileup, "\t0\t*\t*");
}
kputc('\n', sim->pileup);
}
// remove genotypes from main output file
bcf_update_genotypes(sim->hdr, sim->rec, NULL, 0);
// -- gVCF --
if (args->doGVCF) {
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, "<NON_REF>")));
sim->add_tags();
return (0);
}
// -- VCF --
if (args->doUnobserved == ARG_DOUNOBSERVED_TRIM) {
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, "."))); //DRAGON missing allele
sim->nAlleles = 1;
sim->nGenotypes = 1;
sim->nAllelesObserved = 0; //DRAGON
} else if (args->doUnobserved == ARG_DOUNOBSERVED_STAR) {
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, "<*>")));
sim->nAlleles = 1;
sim->nGenotypes = 1;
sim->nAllelesObserved = 0; //DRAGON
} else if (args->doUnobserved == ARG_DOUNOBSERVED_NONREF) {
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, "<NON_REF>")));
sim->nAlleles = 1;
sim->nGenotypes = 1;
sim->nAllelesObserved = 0; //DRAGON
} else if (args->doUnobserved == ARG_DOUNOBSERVED_EXPLODE_ACGT) {
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, "A,C,G,T")));
sim->nAlleles = 4;
sim->nAllelesObserved = 4;
sim->nGenotypes = 10;
} else if (args->doUnobserved == ARG_DOUNOBSERVED_EXPLODE_ACGT_STAR) {
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, "A,C,G,T,<*>")));
sim->nAlleles = 5;
sim->nAllelesObserved = 4;
sim->nGenotypes = 15;
} else if (args->doUnobserved == ARG_DOUNOBSERVED_EXPLODE_ACGT_NONREF) {
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, "A,C,G,T,<NON_REF>")));
sim->nAlleles = 5;
sim->nAllelesObserved = 4;
sim->nGenotypes = 15;
}
sim->current_size_bcf_tag_number[FMT_NUMBER_G] = sim->nSamples * sim->nGenotypes;
sim->current_size_bcf_tag_number[FMT_NUMBER_R] = sim->nSamples * sim->nAllelesObserved;
sim->current_size_bcf_tag_number[FMT_NUMBER_R_WITH_NONREF] = sim->nSamples * sim->nAlleles;
sim->current_size_bcf_tag_number[INFO_NUMBER_G] = sim->nGenotypes;
sim->current_size_bcf_tag_number[INFO_NUMBER_R] = sim->nAllelesObserved;
sim->current_size_bcf_tag_number[INFO_NUMBER_R_WITH_NONREF] = sim->nAlleles;
DEVASSERT(sim->current_size_bcf_tag_number[FMT_NUMBER_G] <= sim->max_size_bcf_tag_number[FMT_NUMBER_G]);
DEVASSERT(sim->current_size_bcf_tag_number[FMT_NUMBER_R] <= sim->max_size_bcf_tag_number[FMT_NUMBER_R]);
DEVASSERT(sim->current_size_bcf_tag_number[FMT_NUMBER_R_WITH_NONREF] <= sim->max_size_bcf_tag_number[FMT_NUMBER_R_WITH_NONREF]);
DEVASSERT(sim->current_size_bcf_tag_number[INFO_NUMBER_G] <= sim->max_size_bcf_tag_number[INFO_NUMBER_G]);
DEVASSERT(sim->current_size_bcf_tag_number[INFO_NUMBER_R] <= sim->max_size_bcf_tag_number[INFO_NUMBER_R]);
DEVASSERT(sim->current_size_bcf_tag_number[INFO_NUMBER_R_WITH_NONREF] <= sim->max_size_bcf_tag_number[INFO_NUMBER_R_WITH_NONREF]);
for (int i = 0;i < sim->max_size_bcf_tag_number[bcf_tags[GL].n];++i) {
if (NULL != sim->pl_arr) {
sim->pl_arr[i] = bcf_int32_missing;
}
if (NULL != sim->gp_arr) {
sim->gp_arr[i] = bcf_float_missing_union_f;
}
sim->gl_arr[i] = bcf_float_missing_union_f;
}
// no need to set the rest of the tags to missing since the initialized values (and vals we reset them to during record reset) are 0
sim->add_tags();
if (args->printPileup) {
FLUSH_BGZF_KSTRING_BUFFER(args->out_pileup_fp, sim->pileup);
}
return (0);
}
// return value < 0 skip the site
// returns negative value only if program will skip the position given arg values
// skip position reasons:
// -3 observed only 1 simulated allele at position (iff PROGRAM_WILL_SKIP_SIM_INVAR_SITES)
// -4 no alleles were observed at position (iff 1==args->rmEmptySites)
int simulate_record_values(simRecord* sim) {
bcf1_t* rec = sim->rec;
if (0 == rec->n_allele) {
ERROR("No alleles found at position %ld.", rec->pos + 1);
}
if (PROGRAM_WILL_SKIP_INPUT_HOMOGT_SITES) {
if (1 == rec->n_allele) {
return(-1);
}
}
const int nSamples = sim->nSamples;
int n_sim_reads = 0;
// -- for error-qs 2
double error_prob_forQs_i = -1.0;
int qScore_i = -1;
int adjqScore_i = -1;
// --
// -------------------------------------------- //
// reset reused objects for the current rec
sim->reset_rec_objects();
// -------------------------------------------- //
int s = -1; // sample index
int b = -1; // base index in ACGT
int a = -1; // allele index
// -------------------------------------------- //
// simulate read depths
if (args->mps_depths != NULL) {
poissonSampler_sample_depths_perSample_means(args->poissonSampler, n_sim_reads_arr, nSamples);
} else {
poissonSampler_sample_depths_same_mean(args->poissonSampler[0], n_sim_reads_arr, nSamples);
}
for (s = 0; s < nSamples; s++) {
n_sim_reads = n_sim_reads_arr[s];
sim->fmt_dp_arr[s] = n_sim_reads;
sim->info_dp_arr[0] += n_sim_reads;
if (n_sim_reads > sim->_nBasesPerSample) {
sim->expand_arrays(n_sim_reads);
}
}
// end simulate read depths
// -------------------------------------------- //
// -------------------------------------------------------------------- //
// INFO/DP == 0 //
// no reads were simulated for any of the individuals //
if (0 == sim->info_dp_arr[0]) {
// [FILTER] --rm-empty-sites
VWARN("No alleles were observed at position %ld.", sim->rec->pos + 1);
if (1 == args->rmEmptySites) {
return (-4);
}
return(simulate_site_with_no_reads(sim));
}
// -------------------------------------------------------------------- //
// INFO/DP >0 //
int which_strand = -1;
int true_base = -1; // true base (no error)
int r_base = -1; // simulated base (observed base after error)
int tail_dist = -1;
if (args->printPileup) {
ksprintf(sim->pileup, "%s\t%ld\t%c", sim->hdr->id[BCF_DT_CTG][rec->rid].key, rec->pos + 1, rec->d.allele[0][0]);
}
int32_t* sample_acgt_fmt_ad_arr = NULL;
int32_t* sample_acgt_fmt_adf_arr = NULL;
int32_t* sample_acgt_fmt_adr_arr = NULL;
int32_t* sample_acgt_fmt_qsum_arr = NULL;
int32_t* sample_acgt_fmt_qsum_sq_arr = NULL;
double base_pick_error_prob = args->base_pick_error_prob;
if (1 == args->error_qs) {
// if error_qs 1, args->base_pick_error_prob initted to -1.0
base_pick_error_prob = args->betaSampler->sample();
if (args->printBasePickError) {
// TSV: type, sample_id, contig, site, read_index, base_pick_error_prob
for (s = 0; s < nSamples; s++) {
fprintf(stdout, "base_pick_error_prob\t%s\t%s\t%ld\tNA\t%f\n", sim->hdr->samples[s], sim->hdr->id[BCF_DT_CTG][rec->rid].key, rec->pos + 1, base_pick_error_prob);
}
}
}
int* sample_true_gts = NULL;
for (s = 0; s < nSamples; s++) {
n_sim_reads = sim->fmt_dp_arr[s];
if (0 == n_sim_reads) {
if (args->printPileup) {
ksprintf(sim->pileup, "\t0\t*\t*");
}
} else {
sample_true_gts = true_gts_acgt_int + (s * SIM_PLOIDY);
sample_acgt_fmt_ad_arr = sim->acgt_fmt_ad_arr + (s * 4);
if (1 == args->addFormatADF || 1 == args->addInfoADF) {
sample_acgt_fmt_adf_arr = sim->acgt_fmt_adf_arr + (s * 4);
}
if (1 == args->addFormatADR || 1 == args->addInfoADR) {
sample_acgt_fmt_adr_arr = sim->acgt_fmt_adr_arr + (s * 4);
}
sample_acgt_fmt_qsum_arr = sim->acgt_fmt_qsum_arr + (s * 4);
sample_acgt_fmt_qsum_sq_arr = sim->acgt_fmt_qsum_sq_arr + (s * 4);
for (int read_i = 0; read_i < n_sim_reads; read_i++) {
// -------------------------------------------- //
// ----> pick a haplotype
(sample_uniform_rng1() < 0.5) ? true_base = sample_true_gts[0] : true_base = sample_true_gts[1];
// -------------------------------------------- //
// ----> base picking
// use an indepentent rng for the error base choosing sample_uniform function
// sample_uniform() in error_base choosing is called for x times where x depends on base_pick_error_prob
// to be able to sample the same values from haplotype picking and if (sample_uniform() < base_pick_error_prob) statement
// isolate the base_pick_error_prob dependent part of the RNG from the rest of the RNGs
// so that we sample the same depths and haplotypes given the same seed when we use error-qs 0, 1 and 2
// for use with error-qs 1
r_base = true_base;
if (sample_uniform_rng0() < base_pick_error_prob) {
while ((r_base = (floor(4 * sample_uniform_rng0()))) == true_base);
}
// -------------------------------------------- //
// ----> get qScores
if (2 == args->error_qs) {
error_prob_forQs_i = args->betaSampler->sample();
qScore_i = -1;
adjqScore_i = -1;
if (0.0 == error_prob_forQs_i) {
qScore_i = CAP_BASEQ;
} else if (1.0 == error_prob_forQs_i) {
qScore_i = 0;
} else if ((0.0 < error_prob_forQs_i) && (error_prob_forQs_i < 1.0)) {
double tmp = -10.0 * log10(error_prob_forQs_i);
qScore_i = (int)(tmp);
adjqScore_i = (PROGRAM_WILL_ADJUST_QS) ? (int)(tmp + args->adjustBy) : adjqScore_i;
} else {
ERROR("Bad error probability value: %f", error_prob_forQs_i);
}
if (args->n_qs_bins != 0) {
qScore_i = apply_qs_bins(qScore_i);
if (PROGRAM_WILL_ADJUST_QS) {
adjqScore_i = apply_qs_bins(adjqScore_i);
}
} else {
qScore_i = (qScore_i > CAP_BASEQ) ? CAP_BASEQ : qScore_i;
if (PROGRAM_WILL_ADJUST_QS) {
adjqScore_i = (adjqScore_i > CAP_BASEQ) ? CAP_BASEQ : adjqScore_i;
}
}
sim->base_qScores[s][read_i] = qScore_i;
if (PROGRAM_WILL_ADJUST_QS) {
DEVASSERT(sim->adj_base_qScores != NULL);
sim->adj_base_qScores[s][read_i] = adjqScore_i;
}
if (args->printQsError) {
// TSV: type, sample_id, contig, site, read_index, error_prob
fprintf(stdout, "qs_error_prob\t%s\t%s\t%ld\t%d\t%f\n", sim->hdr->samples[s], sim->hdr->id[BCF_DT_CTG][rec->rid].key, rec->pos + 1, read_i, error_prob_forQs_i);
}
if (args->printQScores) {
// TSV: type, sample_id, contig, site, read_index, qScore
fprintf(stdout, "qs\t%s\t%s\t%ld\t%d\t%d\n", sim->hdr->samples[s], sim->hdr->id[BCF_DT_CTG][rec->rid].key, rec->pos + 1, read_i, ((PROGRAM_WILL_ADJUST_QS_FOR_PRINTQSCORES) ? adjqScore_i : qScore_i));
}
if (args->usePreciseGlError) {
sim->base_error_probs[s][read_i] = error_prob_forQs_i;
if (args->printGlError) {
// TSV: type, sample_id, contig, site, read_index, error_prob
fprintf(stdout, "gl_error_prob\t%s\t%s\t%ld\t%d\t%f\n", sim->hdr->samples[s], sim->hdr->id[BCF_DT_CTG][rec->rid].key, rec->pos + 1, read_i, error_prob_forQs_i);
}
} else {
if (args->printGlError) {
// TSV: type, sample_id, contig, site, read_index, error_prob
fprintf(stdout, "gl_error_prob\t%s\t%s\t%ld\t%d\t%f\n", sim->hdr->samples[s], sim->hdr->id[BCF_DT_CTG][rec->rid].key, rec->pos + 1, read_i, ((PROGRAM_WILL_ADJUST_QS_FOR_PRINTGLERROR) ? (QS_TO_ERRPROB(adjqScore_i)) : (QS_TO_ERRPROB(qScore_i))));
}
}
if (PROGRAM_WILL_ADJUST_QS_FOR_QSUM) {
ASSERT(adjqScore_i != -1);
sample_acgt_fmt_qsum_arr[r_base] += adjqScore_i;
sample_acgt_fmt_qsum_sq_arr[r_base] += QS_TO_QSSQ(adjqScore_i);
} else {
sample_acgt_fmt_qsum_arr[r_base] += qScore_i;
sample_acgt_fmt_qsum_sq_arr[r_base] += QS_TO_QSSQ(qScore_i);
}
} else {
// will use precalculated values at args->preCalc->qScore and args->preCalc->error_prob_forGl instead
if (PROGRAM_WILL_ADJUST_QS_FOR_QSUM) {
ASSERT(args->preCalc->adj_qScore != -1);
sample_acgt_fmt_qsum_arr[r_base] += args->preCalc->adj_qScore;
sample_acgt_fmt_qsum_sq_arr[r_base] += QS_TO_QSSQ(args->preCalc->adj_qScore);
} else {
sample_acgt_fmt_qsum_arr[r_base] += args->preCalc->qScore;
sample_acgt_fmt_qsum_sq_arr[r_base] += QS_TO_QSSQ(args->preCalc->qScore);
}
}
sample_acgt_fmt_ad_arr[r_base]++;
if (PROGRAM_WILL_SAMPLE_STRAND) {
if (sample_uniform_rng0() < 0.5) {
which_strand = SIM_FORWARD_STRAND;
} else {
which_strand = SIM_REVERSE_STRAND;
}
if (SIM_FORWARD_STRAND == which_strand) {
if (sample_acgt_fmt_adf_arr != NULL) {
sample_acgt_fmt_adf_arr[r_base]++;
}
} else if (SIM_REVERSE_STRAND == which_strand) {
if (sample_acgt_fmt_adr_arr != NULL) {
sample_acgt_fmt_adr_arr[r_base]++;
}
} else {
NEVER;
}
} else {
which_strand = SIM_FORWARD_STRAND;
if (sample_acgt_fmt_adf_arr != NULL) {
sample_acgt_fmt_adf_arr[r_base]++;
}
}
sim->acgt_n_bases_forI16[(2 * r_base) + which_strand]++;
sim->bases[s][read_i] = r_base;
} // read loop
if (args->printPileup) {
ksprintf(sim->pileup, "\t%d", n_sim_reads);
kputc('\t', sim->pileup);
for (int read_i = 0; read_i < n_sim_reads; read_i++) {
kputc("ACGT"[sim->bases[s][read_i]], sim->pileup);
}
kputc('\t', sim->pileup);
if (NULL != sim->base_qScores) {
for (int read_i = 0; read_i < n_sim_reads; read_i++) {
kputc((PROGRAM_WILL_ADJUST_QS_FOR_PILEUP ? sim->adj_base_qScores[s][read_i] : sim->base_qScores[s][read_i]) + QSCORE_PHRED_ENCODING_OFFSET, sim->pileup);
}
} else {
for (int read_i = 0; read_i < n_sim_reads; read_i++) {
kputc((PROGRAM_WILL_ADJUST_QS_FOR_PILEUP ? args->preCalc->adj_qScore : args->preCalc->qScore) + QSCORE_PHRED_ENCODING_OFFSET, sim->pileup);
}
}
}
for (b = 0; b < 4;++b) {
sim->acgt_info_ad_arr[b] += sample_acgt_fmt_ad_arr[b];
}
}
} // samples loop
if (args->printPileup) {
kputc('\n', sim->pileup);
}
if (args->addI16) {
for (s = 0;s < nSamples;s++) {
n_sim_reads = sim->fmt_dp_arr[s];
if (0 != n_sim_reads) {
for (int read_i = 0; read_i < n_sim_reads; read_i++) {
tail_dist = sample_from_range_rng_rand(1, 50);
if (tail_dist > CAP_TAIL_DIST) {
tail_dist = CAP_TAIL_DIST;
}
sim->acgt_sum_taildist[r_base] += tail_dist;
sim->acgt_sum_taildist_sq[r_base] += (tail_dist * tail_dist);
}
}
}
}
int nObservedBases = 0;
for (b = 0; b < 4; ++b)
{
DEVASSERT(sim->acgt_info_ad_arr != NULL);
if (sim->acgt_info_ad_arr[b] > 0)
{
nObservedBases++;
}
}
if (PROGRAM_WILL_SKIP_SIM_INVAR_SITES) {
if (1 == nObservedBases) {
return(-3);
} else if (0 == nObservedBases) {
NEVER;
}
}
// -------------------------------------------- //
// -> Reorder alleles: sort by INFO/AD (descending order)
// use:
// acgt_info_ad_arr: contains per-base read depths summed across samples
//
// set: simRecord values:
// acgt2alleles
// alleles2acgt
// nAlleles
// nGenotypes
// allele_unobserved
// alleles
// step 1) sorting
// assumption: MAX_NALLELES == 5
// alelles[4] is reserved for NON_REF
DEVASSERT(5 == MAX_NALLELES);
int sorted_indices[4] = { 0,1,2,3 };
int tmp = -1;
int n_exploded_bases = 0;
// insertion sort (descending order)
for (int i = 1; i < 4; i++) {
for (int j = i; j > 0 && sim->acgt_info_ad_arr[sorted_indices[j]] > sim->acgt_info_ad_arr[sorted_indices[j - 1]]; j--) {
tmp = sorted_indices[j];
sorted_indices[j] = sorted_indices[j - 1];
sorted_indices[j - 1] = tmp;
}
}
for (a = 0;a < 4;++a) {
b = sorted_indices[a];
sim->alleles2acgt[a] = b;
sim->acgt2alleles[b] = a;
}
// step 2) handle unobserved alleles
int n_observed_bases = 0;
for (b = 0;b < 4;++b) {
if (sim->acgt_info_ad_arr[b] > 0) {
n_observed_bases++;
} else {
if (PROGRAM_WILL_EXPLODE_ACGT) {
// explode A,C,G,T
++n_exploded_bases;
} else {
sim->alleles2acgt[sim->acgt2alleles[b]] = -1;
sim->acgt2alleles[b] = -1;
}
}
}
sim->allele_unobserved = -1;
int n_alleles = 0;
for (a = 0; a < 5; ++a) {
if (-1 == sim->alleles2acgt[a]) {
if (PROGRAM_WILL_ADD_UNOBSERVED) {
sim->allele_unobserved = a;
}
break;
}
ASSERT(a != 4);
++n_alleles;
kputc("ACGT"[sim->alleles2acgt[a]], &sim->alleles);
if (a != 3 && sim->alleles2acgt[a + 1] != -1) {
kputc(',', &sim->alleles);
}
}
int n_unobserved = 0;
if (PROGRAM_WILL_ADD_UNOBSERVED) {
kputc(',', &sim->alleles);
kputs(nonref_str, &sim->alleles);
sim->alleles2acgt[sim->allele_unobserved] = BASE_NONREF;
sim->acgt2alleles[BASE_NONREF] = sim->allele_unobserved;
++n_unobserved;
}
sim->nAllelesObserved = n_alleles;
sim->nAlleles = n_alleles + n_unobserved;
sim->nGenotypes = NALLELES_TO_NGTS(sim->nAlleles);
sim->current_size_bcf_tag_number[FMT_NUMBER_G] = sim->nSamples * sim->nGenotypes;
sim->current_size_bcf_tag_number[FMT_NUMBER_R] = sim->nSamples * sim->nAllelesObserved;
sim->current_size_bcf_tag_number[FMT_NUMBER_R_WITH_NONREF] = sim->nSamples * sim->nAlleles;
sim->current_size_bcf_tag_number[INFO_NUMBER_G] = sim->nGenotypes;
sim->current_size_bcf_tag_number[INFO_NUMBER_R] = sim->nAllelesObserved;
sim->current_size_bcf_tag_number[INFO_NUMBER_R_WITH_NONREF] = sim->nAlleles;
DEVASSERT(sim->current_size_bcf_tag_number[FMT_NUMBER_G] <= sim->max_size_bcf_tag_number[FMT_NUMBER_G]);
DEVASSERT(sim->current_size_bcf_tag_number[FMT_NUMBER_R] <= sim->max_size_bcf_tag_number[FMT_NUMBER_R]);
DEVASSERT(sim->current_size_bcf_tag_number[FMT_NUMBER_R_WITH_NONREF] <= sim->max_size_bcf_tag_number[FMT_NUMBER_R_WITH_NONREF]);
DEVASSERT(sim->current_size_bcf_tag_number[INFO_NUMBER_G] <= sim->max_size_bcf_tag_number[INFO_NUMBER_G]);
DEVASSERT(sim->current_size_bcf_tag_number[INFO_NUMBER_R] <= sim->max_size_bcf_tag_number[INFO_NUMBER_R]);
DEVASSERT(sim->current_size_bcf_tag_number[INFO_NUMBER_R_WITH_NONREF] <= sim->max_size_bcf_tag_number[INFO_NUMBER_R_WITH_NONREF]);
ASSERT(0 == (bcf_update_alleles_str(sim->hdr, sim->rec, sim->alleles.s)));
DEVASSERT(sim->nAlleles == sim->rec->n_allele);
// -------------------------------------------- //
calculate_gls(sim);
// -------------------------------------------- //
// remove genotypes from main output file
bcf_update_genotypes(sim->hdr, sim->rec, NULL, 0);
// -------------------------------------------- //
// -> set sorted values for *_NUMBER_R_WITH_NONREF tags
sample_acgt_fmt_ad_arr = NULL;
sample_acgt_fmt_adf_arr = NULL;
sample_acgt_fmt_adr_arr = NULL;
int32_t* sample_fmt_ad_arr = NULL;
int32_t* sample_fmt_adf_arr = NULL;
int32_t* sample_fmt_adr_arr = NULL;
for (s = 0; s < sim->nSamples; ++s) {
for (a = 0; a < sim->nAlleles; ++a) {
b = sim->alleles2acgt[a];
if (BASE_NONREF == b) {
continue;
}
sample_fmt_ad_arr = sim->fmt_ad_arr + (s * sim->nAlleles);
sample_fmt_adf_arr = sim->fmt_adf_arr + (s * sim->nAlleles);
sample_fmt_adr_arr = sim->fmt_adr_arr + (s * sim->nAlleles);
sample_acgt_fmt_ad_arr = sim->acgt_fmt_ad_arr + (s * 4);
sample_acgt_fmt_adf_arr = sim->acgt_fmt_adf_arr + (s * 4);
sample_acgt_fmt_adr_arr = sim->acgt_fmt_adr_arr + (s * 4);
if (NULL != sim->fmt_ad_arr) {
sample_fmt_ad_arr[a] = sample_acgt_fmt_ad_arr[b];
}
if (NULL != sim->fmt_adf_arr) {
sample_fmt_adf_arr[a] = sample_acgt_fmt_adf_arr[b];
}
if (NULL != sim->fmt_adr_arr) {
sample_fmt_adr_arr[a] = sample_acgt_fmt_adr_arr[b];
}
if (NULL != sim->info_ad_arr) {
sim->info_ad_arr[a] += sample_acgt_fmt_ad_arr[b];
}
if (NULL != sim->info_adf_arr) {
sim->info_adf_arr[a] += sample_acgt_fmt_adf_arr[b];
}
if (NULL != sim->info_adr_arr) {
sim->info_adr_arr[a] += sample_acgt_fmt_adr_arr[b];
}
}
}
if (1 == args->addQS) {
// example: at position 0
// sample 1:
// sampled base,qual
// C,4
// T,4
// A,1
// T,6
//
// sample 2:
// sampled base,qual
// G,7
//
// sample 1 sum of quals = 15
// normalized qsum for A,C,G,T
// sample1: 1/15,4/15,0,10/15
// sample2: 0,0,7/7,0
// qsum: 1/15,4/15,7/7,10/15
a = -1;
b = -1;
float sum = 0.0;
sample_acgt_fmt_qsum_arr = NULL;
sample_acgt_fmt_qsum_sq_arr = NULL;
// -- calculation of the qsum -- //
// sum the normalized qsum across all samples
// to account for differences in coverage
// modified from: bcftools/bam2bcf.c
for (s = 0; s < nSamples; ++s) {
sum = 0.0;
sample_acgt_fmt_qsum_arr = sim->acgt_fmt_qsum_arr + (s * 4);
sample_acgt_fmt_qsum_sq_arr = sim->acgt_fmt_qsum_sq_arr + (s * 4);
for (b = 0; b < 4; ++b) {
sum += sample_acgt_fmt_qsum_arr[b];
}
if (0.0 != sum) {
for (b = 0; b < 4; ++b) {
a = sim->acgt2alleles[b];
if (-1 == a) {
continue;
}
// per-sample normalization
// save as ordered (base b --> allele index a)
sim->qs_arr[a] += (float)((float)(sample_acgt_fmt_qsum_arr[b]) / sum);
}
}
}
}
// -------------------------------------------- //
// -> set sorted values for FMT_NUMBER_G tags
// //GL
// GP
// PL
if (args->addPL) {
int x;
for (int i = 0; i < sim->current_size_bcf_tag_number[bcf_tags[PL].n];++i) {
if (bcf_float_is_missing(sim->gl_arr[i])) {
sim->pl_arr[i] = bcf_int32_missing;
} else if (bcf_float_is_vector_end(sim->gl_arr[i])) {
NEVER;
} else {
#if 0
if (sim->gl_arr[i] == std::numeric_limits<float>::infinity()) {
NEVER;
}
#endif
if (sim->gl_arr[i] == NEG_INF) {
sim->pl_arr[i] = MAXPL;
continue;
}
// when max threshold disabled, vcfgl gives same results as bcftools
// +tag2tag -- --GL-to-PL
x = lroundf(-10.0 * sim->gl_arr[i]);
if (x > MAXPL) {
x = MAXPL;
}
sim->pl_arr[i] = x;
}
}
}
if (args->addGP) {
for (int i = 0; i < sim->current_size_bcf_tag_number[bcf_tags[PL].n];++i) {
if (bcf_float_is_missing(sim->gl_arr[i])) {
sim->gp_arr[i] = bcf_float_missing_union_f;
} else if (bcf_float_is_vector_end(sim->gl_arr[i])) {
NEVER;
} else {
sim->gp_arr[i] = pow(10, sim->gl_arr[i]);
}
}
}
// -------------------------------------------- //
// prepare I16 tag
// requires:
// acgt_n_bases_forI16
// acgt_fmt_qsum_arr
// acgt_fmt_qsum_sq_arr
// acgt_sum_taildist
// acgt_sum_taildist_sq
if (1 == args->addI16) {
// ------------------------------------------------------- //
// I16 REF fields
// ------------------------------------------------------- //
int refb = sim->alleles2acgt[0];
// 1 #reference Q13 bases on the forward strand
sim->i16_arr[0] = sim->acgt_n_bases_forI16[(refb * 2) + SIM_FORWARD_STRAND];
// 2 #reference Q13 bases on the reverse strand
sim->i16_arr[1] = sim->acgt_n_bases_forI16[(refb * 2) + SIM_REVERSE_STRAND];
sample_fmt_ad_arr = NULL;
for (s = 0; s < nSamples; ++s) {
// 5 sum of reference base qualities
sim->i16_arr[4] += sim->acgt_fmt_qsum_arr[s * 4 + refb];
// 6 sum of squares of reference base qualities
sim->i16_arr[5] += sim->acgt_fmt_qsum_sq_arr[s * 4 + refb];
sample_fmt_ad_arr = sim->fmt_ad_arr + (s * sim->nAlleles);
for (a = 0; a < sim->nAlleles; ++a) {
if (sim->nAllelesObserved == a) {
// exclude NONREF allele since that cannot have a mapq
continue;
}
for (int i = 0; i < sample_fmt_ad_arr[a]; ++i) {
if (0 == a) {
// 9 sum of ref mapping qualities
sim->i16_arr[8] += args->i16_mapq;
// 10 sum of squares of ref mapping qualities
sim->i16_arr[9] += args->i16_mapq * args->i16_mapq;
} else {
// 11 sum of non-ref mapping qualities
sim->i16_arr[10] += args->i16_mapq;
// 12 sum of squares of non-ref mapping qualities
sim->i16_arr[11] += args->i16_mapq * args->i16_mapq;
}
}
}
}
// 13 sum of tail distance for ref bases
sim->i16_arr[12] = sim->acgt_sum_taildist[refb];
// 14 sum of squares of tail distance for ref bases
sim->i16_arr[13] = sim->acgt_sum_taildist_sq[refb];
// ------------------------------------------------------- //
// I16 NON-REF fields
// ------------------------------------------------------- //
// start from 1 to exclude the reference allele
ASSERT(sim->nAlleles > 1);
for (a = 1; a < sim->nAlleles; ++a) {
if (sim->nAllelesObserved == a) {
continue;
}