-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathGenrich.c
More file actions
5835 lines (5320 loc) · 171 KB
/
Copy pathGenrich.c
File metadata and controls
5835 lines (5320 loc) · 171 KB
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
/*
John M. Gaspar ([email protected])
June 2018
Finding sites of enrichment from genome-wide assays.
Version 0.6.1
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <getopt.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <zlib.h>
#include "Genrich.h"
/* void printVersion()
* Print version and copyright.
*/
void printVersion(void) {
fprintf(stderr, "Genrich, version %s\n", VERSION);
fprintf(stderr, "Copyright (C) 2018 John M. Gaspar ([email protected])\n");
exit(EXIT_FAILURE);
}
/* void usage()
* Prints usage information.
*/
void usage(void) {
fprintf(stderr, "Usage: ./Genrich -%c <file> -%c <file>", INFILE, OUTFILE);
fprintf(stderr, " [optional arguments]\n");
fprintf(stderr, "Required arguments:\n");
fprintf(stderr, " -%c <file> Input SAM/BAM file(s) for experimental sample(s)\n", INFILE);
fprintf(stderr, " -%c <file> Output peak file (in ENCODE narrowPeak format)\n", OUTFILE);
fprintf(stderr, "Optional I/O arguments:\n");
fprintf(stderr, " -%c <file> Input SAM/BAM file(s) for control sample(s)\n", CTRLFILE);
fprintf(stderr, " -%c <file> Output bedgraph-ish file for p/q values\n", LOGFILE);
fprintf(stderr, " -%c <file> Output bedgraph-ish file for pileups and p-values\n", PILEFILE);
fprintf(stderr, " -%c <file> Output BED file for reads/fragments/intervals\n", BEDFILE);
fprintf(stderr, " -%c <file> Output file for PCR duplicates (only with -%c)\n", DUPSFILE, DUPSOPT);
fprintf(stderr, "Filtering options:\n");
fprintf(stderr, " -%c Remove PCR duplicates\n", DUPSOPT);
fprintf(stderr, " -%c <arg> Comma-separated list of chromosomes to exclude\n", XCHROM);
fprintf(stderr, " -%c <file> Input BED file(s) of genomic regions to exclude\n", XFILE);
fprintf(stderr, " -%c <int> Minimum MAPQ to keep an alignment (def. 0)\n", MINMAPQ);
fprintf(stderr, " -%c <float> Keep sec alns with AS >= bestAS - <float> (def. 0)\n", ASDIFF);
fprintf(stderr, " -%c Keep unpaired alignments (def. false)\n", UNPAIROPT);
fprintf(stderr, " -%c <int> Keep unpaired alns, lengths changed to <int>\n", EXTENDOPT);
fprintf(stderr, " -%c Keep unpaired alns, lengths changed to paired avg\n", AVGEXTOPT);
fprintf(stderr, "Options for ATAC-seq:\n");
fprintf(stderr, " -%c Use ATAC-seq mode (def. false)\n", ATACOPT);
fprintf(stderr, " -%c <int> Expand cut sites to <int> bp (def. %d)\n", ATACLEN, DEFATAC);
fprintf(stderr, " -%c Skip Tn5 adjustments of cut sites (def. false)\n", DNASEOPT);
fprintf(stderr, "Options for peak-calling:\n");
fprintf(stderr, " -%c <float> Maximum p-value (def. %.2f)\n", PVALUE, DEFPVAL);
fprintf(stderr, " -%c <float> Maximum q-value (FDR-adjusted p-value; def. 1)\n", QVALUE);
fprintf(stderr, " -%c <float> Minimum AUC for a peak (def. %.1f)\n", MINAUC, DEFAUC);
fprintf(stderr, " -%c <int> Minimum length of a peak (def. %d)\n", MINLEN, DEFMINLEN);
fprintf(stderr, " -%c <int> Maximum distance between signif. sites (def. %d)\n", MAXGAP, DEFMAXGAP);
fprintf(stderr, "Other options:\n");
fprintf(stderr, " -%c Skip peak-calling\n", NOPEAKS);
fprintf(stderr, " -%c Call peaks directly from a log file (-%c)\n", PEAKSONLY, LOGFILE);
fprintf(stderr, " -%c Option to gzip-compress output(s)\n", GZOPT);
fprintf(stderr, " -%c Option to print status updates/counts to stderr\n", VERBOSE);
exit(EXIT_FAILURE);
}
/*** Utilites ***/
/* int error()
* Prints an error message.
*/
int error(const char* msg, enum errCode err) {
fprintf(stderr, "Error! %s%s\n", msg, errMsg[err]);
return EXIT_FAILURE;
}
/* void* memalloc()
* Allocates a heap block.
*/
void* memalloc(size_t size) {
void* ans = malloc(size);
if (ans == NULL)
exit(error("", ERRMEM));
return ans;
}
/* void* memrealloc()
* Changes the size of a heap block.
*/
void* memrealloc(void* ptr, size_t size) {
void* ans = realloc(ptr, size);
if (ans == NULL)
exit(error("", ERRMEM));
return ans;
}
/* float getFloat(char*)
* Converts the given char* to a float.
*/
float getFloat(char* in) {
char* endptr;
float ans = strtof(in, &endptr);
if (*endptr != '\0')
exit(error(in, ERRFLOAT));
return ans;
}
/* int getInt(char*)
* Converts the given char* to an int.
*/
int getInt(char* in) {
char* endptr;
int ans = (int) strtol(in, &endptr, 10);
if (*endptr != '\0')
exit(error(in, ERRINT));
return ans;
}
/* uint64_t getLong(char*)
* Converts the given char* to an uint64_t.
*/
uint64_t getLong(char* in) {
char* endptr;
uint64_t ans = (uint64_t) strtol(in, &endptr, 10);
if (*endptr != '\0')
exit(error(in, ERRINT));
return ans;
}
/* char* getLine()
* Reads the next line from a file.
*/
char* getLine(char* line, int size, File in, bool gz) {
if (gz)
return gzgets(in.gzf, line, size);
else
return fgets(line, size, in.f);
}
/*** Quicksort (of p-values, for q-value calculation) ***/
// adapted from https://www.geeksforgeeks.org/quick-sort/
/* void swapFloat(): Swap two float values (pileup->cov)
* void swapInt(): Swap two int values (pileup->end)
* int partition(): Place last elt into correct spot
* void quickSort(): Control quickSort process recursively
*/
void swapFloat(float* a, float* b) {
float t = *a;
*a = *b;
*b = t;
}
void swapInt(uint64_t* a, uint64_t* b) {
uint64_t t = *a;
*a = *b;
*b = t;
}
int64_t partition(float* pVal, uint64_t* pEnd,
int64_t low, int64_t high) {
float pivot = pVal[high]; // pivot value: last elt
int64_t idx = low - 1;
for (int64_t j = low; j < high; j++) {
if (pVal[j] < pivot) {
idx++;
swapFloat(pVal + idx, pVal + j);
swapInt(pEnd + idx, pEnd + j); // swap int values too
}
}
idx++;
swapFloat(pVal + idx, pVal + high);
swapInt(pEnd + idx, pEnd + high);
return idx;
}
void quickSort(float* pVal, uint64_t* pEnd,
int64_t low, int64_t high) {
if (low < high) {
int64_t idx = partition(pVal, pEnd, low, high);
quickSort(pVal, pEnd, low, idx - 1);
quickSort(pVal, pEnd, idx + 1, high);
}
}
/*** Calculate q-values ***/
/* float lookup()
* Return the pre-computed q-value for a given p-value,
* using parallel arrays (pVal and qVal).
*/
float lookup(float* pVal, uint64_t low, uint64_t high,
float* qVal, float p) {
if (low == high)
return qVal[low];
uint64_t idx = (low + high) / 2;
if (pVal[idx] == p)
return qVal[idx];
if (pVal[idx] > p)
return lookup(pVal, low, idx - 1, qVal, p);
return lookup(pVal, idx + 1, high, qVal, p);
}
/* void saveQval()
* Calculate and save q-values, given the pre-compiled
* arrays of p-values (pVal) and lengths (pEnd).
*/
void saveQval(Chrom* chrom, int chromLen, int n,
uint64_t genomeLen, float* pVal, uint64_t* pEnd,
int64_t pLen, bool verbose) {
// sort pileup by p-values
quickSort(pVal, pEnd, 0, pLen - 1);
// calculate q-values for each p-value: -log(q) = -log(p*N/k)
uint64_t k = 1; // 1 + number of bases with higher -log(p)
float logN = -log10f(genomeLen);
float* qVal = (float*) memalloc((pLen + 1) * sizeof(float));
qVal[pLen] = FLT_MAX;
for (int64_t i = pLen - 1; i > -1; i--) {
// ensure monotonicity
qVal[i] = MAX( MIN( pVal[i] + logN + log10f(k),
qVal[i + 1]), 0.0f);
k += pEnd[i];
}
// save pileups of q-values for each chrom
for (int i = 0; i < chromLen; i++) {
Chrom* chr = chrom + i;
if (chr->skip || chr->pval[n] == NULL)
continue;
for (uint32_t j = 0; j < chr->pvalLen[n]; j++)
if (chr->pval[n]->cov[j] == SKIP)
chr->qval->cov[j] = SKIP; // skipped region
else
chr->qval->cov[j] = lookup(pVal, 0, pLen,
qVal, chr->pval[n]->cov[j]);
}
// check if all q-values are 1
if (verbose && qVal[pLen-1] == 0.0f)
fprintf(stderr, "Warning! All q-values are 1\n");
// free memory
free(qVal);
}
/*** Save p-values in hashtable ***/
/* uint32_t jenkins_one_at_a_time_hash()
* Adapted from http://www.burtleburtle.net/bob/hash/doobs.html
* Modified to take a float (p-value) as input.
* Returns index into hashtable.
*/
uint32_t jenkins_one_at_a_time_hash(float f) {
uint32_t hash = 0;
unsigned char* p = (unsigned char*) &f;
for (int i = 0; i < sizeof(float); i++) {
hash += p[i];
hash += hash << 10;
hash ^= hash >> 6;
}
hash += hash << 3;
hash ^= hash >> 11;
hash += hash << 15;
return hash % HASH_SIZE;
}
/* int recordPval()
* Save length of given p-value into hashtable.
* Return 1 if new entry made, else 0.
*/
int recordPval(Hash** table, float p, uint32_t length) {
// check hashtable for matching p-value
uint32_t idx = jenkins_one_at_a_time_hash(p);
for (Hash* h = table[idx]; h != NULL; h = h->next)
if (p == h->val) {
// match: add length to bucket
h->len += length;
return 0;
}
// no match: add info into bucket
Hash* newVal = (Hash*) memalloc(sizeof(Hash));
newVal->val = p;
newVal->len = length;
newVal->next = table[idx];
table[idx] = newVal;
return 1;
}
/* Hash** hashPval()
* Collect p-values in a hashtable.
*/
Hash** hashPval(Chrom* chrom, int chromLen, int n,
int64_t* pLen) {
// create hashtable for conversion of p-values to q-values
Hash** table = (Hash**) memalloc(HASH_SIZE * sizeof(Hash*));
for (int i = 0; i < HASH_SIZE; i++)
table[i] = NULL;
// loop through chroms
for (int i = 0; i < chromLen; i++) {
Chrom* chr = chrom + i;
if (chr->skip || chr->pval[n] == NULL)
continue;
// populate hashtable
Pileup* p = chr->pval[n]; // use the last p-value array
uint32_t start = 0;
for (uint32_t m = 0; m < chr->pvalLen[n]; m++) {
// record p-value and length in hashtable
if (p->cov[m] != SKIP)
*pLen += recordPval(table, p->cov[m],
p->end[m] - start);
start = p->end[m];
}
}
return table;
}
/* float* collectPval()
* Collect arrays of p-values and genome lengths from
* hashtable (to be used in q-value calculations).
*/
float* collectPval(Hash** table, uint64_t** pEnd,
int64_t pLen, uint64_t* checkLen) {
float* pVal = (float*) memalloc(pLen * sizeof(float));
int64_t idx = 0;
for (int i = 0; i < HASH_SIZE; i++)
for (Hash* h = table[i]; h != NULL; h = h->next) {
pVal[idx] = h->val;
(*pEnd)[idx] = h->len;
*checkLen += h->len;
idx++;
}
if (idx != pLen)
exit(error(errMsg[ERRPVAL], ERRISSUE));
return pVal;
}
/* void computeQval()
* Control q-value calculations.
*/
void computeQval(Chrom* chrom, int chromLen,
uint64_t genomeLen, bool genomeOpt, int n,
bool verbose) {
// create "pileup" arrays for q-values
for (int i = 0; i < chromLen; i++) {
Chrom* chr = chrom + i;
if (chr->skip || chr->pval[n] == NULL)
continue;
uint32_t num = chr->pvalLen[n]; // use last p-value array length
chr->qval = (Pileup*) memalloc(sizeof(Pileup));
chr->qval->end = (uint32_t*) memalloc(num * sizeof(uint32_t));
chr->qval->cov = (float*) memalloc(num * sizeof(float));
}
// save all p-values (genome-wide) to hashtable
int64_t pLen = 0;
Hash** table = hashPval(chrom, chromLen, n, &pLen);
// collect p-values from hashtable
uint64_t* pEnd = memalloc(pLen * sizeof(uint64_t));
uint64_t checkLen = 0; // should match genomeLen
float* pVal = collectPval(table, &pEnd, pLen, &checkLen);
// check that collected p-value lengths match genomeLen
if (genomeOpt && checkLen != genomeLen) {
char msg[MAX_ALNS];
sprintf(msg, "Genome length (%ld) does not match p-value length (%ld)",
genomeLen, checkLen);
exit(error(msg, ERRISSUE));
}
// convert p-values to q-values
saveQval(chrom, chromLen, n, genomeLen, pVal, pEnd,
pLen, verbose);
// free memory
free(pEnd);
free(pVal);
for (int i = 0; i < HASH_SIZE; i++) {
Hash* tmp;
Hash* h = table[i];
while (h != NULL) {
tmp = h->next;
free(h);
h = tmp;
}
}
free(table);
}
/*** Calculate p-value for Chi-squared test ***/
// adapted from R-3.5.0 source code, as noted below
// from dpq.h in R-3.5.0:
#define R_Log1_Exp(x) ((x) > -M_LN2 ? log(-expm1(x)) : log1p(-exp(x)))
/* double bd0()
* Adapted from bd0.c in R-3.5.0.
*/
double bd0(double x, double np) {
double ej, s, s1, v;
if (fabs(x-np) < 0.1*(x+np)) {
v = (x-np)/(x+np);
s = (x-np)*v;
if (fabs(s) < DBL_MIN)
return s;
ej = 2*x*v;
v = v*v;
for (int j = 1; j < 1000; j++) {
ej *= v;
s1 = s+ej/((j<<1)+1);
if (s1 == s)
return s1;
s = s1;
}
}
return x * log(x / np) + np - x;
}
/* double stirlerr()
* Adapted from stirlerr.c in R-3.5.0.
* Argument 'n' is an integer in [1, 199].
*/
double stirlerr(double n) {
double S0 = 1.0 / 12;
double S1 = 1.0 / 360;
double S2 = 1.0 / 1260;
double S3 = 1.0 / 1680;
double S4 = 1.0 / 1188;
double sferr[16] = {
0.0,
0.0810614667953272582196702,
0.0413406959554092940938221,
0.02767792568499833914878929,
0.02079067210376509311152277,
0.01664469118982119216319487,
0.01387612882307074799874573,
0.01189670994589177009505572,
0.010411265261972096497478567,
0.009255462182712732917728637,
0.008330563433362871256469318,
0.007573675487951840794972024,
0.006942840107209529865664152,
0.006408994188004207068439631,
0.005951370112758847735624416,
0.005554733551962801371038690
};
double nn = n * n;
if (n > 80.0)
return (S0-(S1-S2/nn)/nn)/n;
if (n > 35.0)
return (S0-(S1-(S2-S3/nn)/nn)/nn)/n;
if (n > 15.0)
return (S0-(S1-(S2-(S3-S4/nn)/nn)/nn)/nn)/n;
return sferr[(int) n];
}
/* double dpois()
* Adapted from dpois.c in R-3.5.0 (cf. dpois_raw()).
*/
double dpois(double x, double lambda) {
return -0.5 * log(2.0 * M_PI * x) - stirlerr(x)
- bd0(x, lambda);
}
/* double pd_upper_series()
* Adapted from pgamma.c in R-3.5.0.
*/
double pd_upper_series(double x, double alph) {
double term = x / alph;
double sum = term;
do {
alph++;
term *= x / alph;
sum += term;
} while (term > sum * DBL_EPSILON);
return log(sum);
}
/* double pd_lower_series()
* Adapted from pgamma.c in R-3.5.0.
*/
double pd_lower_series(double lambda, double y) {
double term = 1, sum = 0;
while (y >= 1 && term > sum * DBL_EPSILON) {
term *= y / lambda;
sum += term;
y--;
}
return log1p(sum);
}
/* double pgamma_smallx()
* Adapted from pgamma.c in R-3.5.0.
*/
double pgamma_smallx(double x, double alph) {
double sum = 0.0;
double c = alph;
double n = 0.0;
double term;
do {
n++;
c *= -x / n;
term = c / (alph + n);
sum += term;
} while (fabs(term) > DBL_EPSILON * fabs(sum));
double lf2 = alph * log(x) - lgamma(alph + 1);
return R_Log1_Exp(log1p(sum) + lf2);
}
/* double pgamma()
* Adapted from pgamma.c in R-3.5.0 (cf. pgamma_raw()).
* Argument 'alph' is an integer in [2, 200].
*/
double pgamma(double x, double alph) {
if (x < 1)
// small values of x
return pgamma_smallx(x, alph);
else if (x <= alph - 1) {
// larger alph than x
double sum = pd_upper_series(x, alph);
double d = dpois(alph - 1, x);
return R_Log1_Exp(sum + d);
}
// x > alph - 1
double sum = pd_lower_series(x, alph - 1);
double d = dpois(alph - 1, x);
return sum + d;
}
/* double pchisq()
* Calculate a p-value for a chi-squared distribution
* with observation 'x' and 'df' degrees of freedom.
* 'df' must be an even integer in [4, 400].
* Adapted from pchisq.c and pgamma.c in R-3.5.0,
* with lower_tail=FALSE and log_p=TRUE.
* Return value is -log10(p).
*/
double pchisq(double x, int df) {
if (df < 4 || df > 400 || df / 2.0 != (int) (df / 2.0))
exit(error(errMsg[ERRDF], ERRISSUE));
return -pgamma(x / 2.0, df / 2.0) / M_LN10;
}
/*** Combine p-values from multiple replicates ***/
/* float multPval()
* Combine multiple p-values into a single net p-value
* using Fisher's method.
*/
float multPval(Pileup** pval, int n, uint32_t idx[]) {
double sum = 0.0;
int df = 0;
for (int j = 0; j < n; j++)
if (pval[j] != NULL && pval[j]->cov[idx[j]] != SKIP) {
sum += pval[j]->cov[idx[j]];
df += 2;
}
if (df == 0)
return SKIP;
if (df == 2 || ! sum)
return (float) sum;
// calculate p-value using chi-squared dist.
double p = pchisq(2.0 * sum / M_LOG10E, df);
return p > FLT_MAX ? FLT_MAX : (float) p;
}
/* uint32_t countIntervals2()
* Count the number of pileup intervals to create
* for the combined p-values.
*/
uint32_t countIntervals2(Chrom* c, int n) {
uint32_t num = 1;
uint32_t idx[n]; // indexes into each pval array
for (int j = 0; j < n; j++)
idx[j] = 0;
for (uint32_t k = 1; k < c->len; k++) {
bool add = false;
for (int j = 0; j < n; j++)
if (c->pval[j] != NULL
&& c->pval[j]->end[idx[j]] == k) {
if (! add) {
num++;
add = true;
}
idx[j]++;
}
}
return num;
}
/* void combinePval()
* Combine p-values for multiple replicates.
*/
void combinePval(Chrom* chrom, int chromLen, int n) {
// combine p-value "pileups" for each chrom
for (int i = 0; i < chromLen; i++) {
Chrom* chr = chrom + i;
if (chr->skip)
continue;
// make sure at least one pval array exists
int j;
for (j = 0; j < n; j++)
if (chr->pval[j] != NULL)
break;
if (j == n) {
// none exists: append another NULL
chr->pval = (Pileup**) memrealloc(chr->pval,
(n + 1) * sizeof(Pileup*));
chr->pval[n] = NULL;
continue;
}
// create additional 'pileup' array for combined p-values
uint32_t num = countIntervals2(chr, n);
chr->pval = (Pileup**) memrealloc(chr->pval,
(n + 1) * sizeof(Pileup*));
chr->pval[n] = (Pileup*) memalloc(sizeof(Pileup));
chr->pval[n]->end = (uint32_t*) memalloc(num * sizeof(uint32_t));
chr->pval[n]->cov = (float*) memalloc(num * sizeof(float));
chr->pvalLen = (uint32_t*) memrealloc(chr->pvalLen,
(n + 1) * sizeof(uint32_t));
chr->pvalLen[n] = num;
chr->sample++;
// save combined p-values
uint32_t idx[n + 1]; // indexes into each pval array
for (int j = 0; j <= n; j++)
idx[j] = 0;
for (uint32_t k = 1; k <= chr->len; k++) {
bool add = false;
for (int j = 0; j < n; j++)
if (chr->pval[j] != NULL
&& chr->pval[j]->end[idx[j]] == k) {
if (! add) {
chr->pval[n]->end[idx[n]] = k;
chr->pval[n]->cov[idx[n]]
= multPval(chr->pval, n, idx);
idx[n]++;
add = true;
}
idx[j]++;
}
}
}
}
/*** Log pileups and stats ***/
/* void printLogHeader()
* Print header of logfile.
*/
void printLogHeader(File log, bool gzOut, int n,
bool qvalOpt, bool sigOpt) {
if (n) {
// multiple samples: logfile has multiple p-values, no pileups
if (gzOut) {
gzprintf(log.gzf, "chr\tstart\tend");
for (int i = 0; i < n; i++)
gzprintf(log.gzf, "\t-log(p)_%d", i);
gzprintf(log.gzf, "\t-log(p)_comb");
if (qvalOpt)
gzprintf(log.gzf, "\t-log(q)");
if (sigOpt)
gzprintf(log.gzf, "\tsignif");
gzprintf(log.gzf, "\n");
} else {
fprintf(log.f, "chr\tstart\tend");
for (int i = 0; i < n; i++)
fprintf(log.f, "\t-log(p)_%d", i);
fprintf(log.f, "\t-log(p)_comb");
if (qvalOpt)
fprintf(log.f, "\t-log(q)");
if (sigOpt)
fprintf(log.f, "\tsignif");
fprintf(log.f, "\n");
}
} else {
// single sample: logfile has pileups and p-/q-values
if (gzOut) {
gzprintf(log.gzf, "chr\tstart\tend\texperimental\tcontrol\t-log(p)");
if (qvalOpt)
gzprintf(log.gzf, "\t-log(q)");
if (sigOpt)
gzprintf(log.gzf, "\tsignif");
gzprintf(log.gzf, "\n");
} else {
fprintf(log.f, "chr\tstart\tend\texperimental\tcontrol\t-log(p)");
if (qvalOpt)
fprintf(log.f, "\t-log(q)");
if (sigOpt)
fprintf(log.f, "\tsignif");
fprintf(log.f, "\n");
}
}
}
/* void printIntervalN()
* Print bedgraph(ish) interval for multiple replicates.
* Values: -log(p) for each replicate, combined -log(p),
* -log(q), and significance ('*') for each.
*/
void printIntervalN(File out, bool gzOut, char* name,
uint32_t start, uint32_t end, Pileup** p, int n,
uint32_t idx[], float pval, bool qvalOpt,
float qval, bool sig) {
if (gzOut) {
gzprintf(out.gzf, "%s\t%d\t%d", name, start, end);
for (int i = 0; i < n; i++)
if (p[i] == NULL || p[i]->cov[idx[i]] == SKIP)
gzprintf(out.gzf, "\t%s", NA);
else
gzprintf(out.gzf, "\t%f", p[i]->cov[idx[i]]);
if (pval == SKIP) {
gzprintf(out.gzf, "\t%s", NA);
if (qvalOpt)
gzprintf(out.gzf, "\t%s", NA);
} else {
gzprintf(out.gzf, "\t%f", pval);
if (qvalOpt)
gzprintf(out.gzf, "\t%f", qval);
}
gzprintf(out.gzf, "%s\n", sig ? "\t*" : "");
} else {
fprintf(out.f, "%s\t%d\t%d", name, start, end);
for (int i = 0; i < n; i++)
if (p[i] == NULL || p[i]->cov[idx[i]] == SKIP)
fprintf(out.f, "\t%s", NA);
else
fprintf(out.f, "\t%f", p[i]->cov[idx[i]]);
if (pval == SKIP) {
fprintf(out.f, "\t%s", NA);
if (qvalOpt)
fprintf(out.f, "\t%s", NA);
} else {
fprintf(out.f, "\t%f", pval);
if (qvalOpt)
fprintf(out.f, "\t%f", qval);
}
fprintf(out.f, "%s\n", sig ? "\t*" : "");
}
}
/* void printInterval()
* Print bedgraph(ish) interval for a single replicate.
* Values: pileups (experimental and control), -log(p),
* -log(q), and significance ('*') for each.
*/
void printInterval(File out, bool gzOut, char* name,
uint32_t start, uint32_t end, float exptVal,
float ctrlVal, float pval, bool qvalOpt, float qval,
bool sig) {
if (gzOut) {
if (ctrlVal == SKIP) {
gzprintf(out.gzf, "%s\t%d\t%d\t%f\t%f\t%s",
name, start, end, exptVal, 0.0f, NA);
if (qvalOpt)
gzprintf(out.gzf, "\t%s", NA);
gzprintf(out.gzf, "\n");
} else {
gzprintf(out.gzf, "%s\t%d\t%d\t%f\t%f\t%f",
name, start, end, exptVal, ctrlVal, pval);
if (qvalOpt)
gzprintf(out.gzf, "\t%f", qval);
gzprintf(out.gzf, "%s\n", sig ? "\t*" : "");
}
} else {
if (ctrlVal == SKIP) {
fprintf(out.f, "%s\t%d\t%d\t%f\t%f\t%s",
name, start, end, exptVal, 0.0f, NA);
if (qvalOpt)
fprintf(out.f, "\t%s", NA);
fprintf(out.f, "\n");
} else {
fprintf(out.f, "%s\t%d\t%d\t%f\t%f\t%f",
name, start, end, exptVal, ctrlVal, pval);
if (qvalOpt)
fprintf(out.f, "\t%f", qval);
fprintf(out.f, "%s\n", sig ? "\t*" : "");
}
}
}
/* void printLog()
* Control printing of stats for an interval.
*/
void printLog(File log, bool gzOut, Chrom* chr,
uint32_t start, int n, uint32_t m, uint32_t j,
uint32_t k, uint32_t idx[], bool qvalOpt,
bool sig) {
if (! n) {
// single replicate
printInterval(log, gzOut, chr->name,
start, chr->pval[n]->end[m],
chr->expt->cov[j], chr->ctrl->cov[k],
chr->pval[n]->cov[m], qvalOpt,
qvalOpt ? chr->qval->cov[m] : SKIP, sig);
} else {
// multiple replicates
printIntervalN(log, gzOut, chr->name,
start, chr->pval[n]->end[m], chr->pval, n, idx,
chr->pval[n]->cov[m], qvalOpt,
qvalOpt ? chr->qval->cov[m] : SKIP, sig);
// update indexes into pval arrays
for (int r = 0; r < n; r++)
if (chr->pval[r] != NULL
&& chr->pval[r]->end[idx[r]] == chr->pval[n]->end[m])
idx[r]++;
}
}
/* void logIntervals()
* Instead of calling peaks, just print log of pileups,
* and p- and q-values for each interval.
*/
void logIntervals(File log, bool gzOut, Chrom* chrom,
int chromLen, int n, bool qvalOpt) {
// print header
printLogHeader(log, gzOut, n, qvalOpt, false);
// loop through chroms
for (int i = 0; i < chromLen; i++) {
Chrom* chr = chrom + i;
if (chr->skip || (qvalOpt && chr->qval == NULL)
|| (! qvalOpt && chr->pval[n] == NULL) )
continue;
// create indexes into arrays (expt/ctrl pileup [if n == 0]
// and p-value arrays [if n > 0])
uint32_t j = 0, k = 0; // indexes into chr->expt, chr->ctrl
uint32_t idx[n]; // indexes into each pval array
for (int r = 0; r < n; r++)
idx[r] = 0;
// loop through intervals (defined by chr->pval[n])
uint32_t start = 0; // start of interval
for (uint32_t m = 0; m < chr->pvalLen[n]; m++) {
// print stats for interval
printLog(log, gzOut, chr, start, n, m, j, k,
idx, qvalOpt, false);
// update chr->expt and chr->ctrl indexes
if (! n) {
if (chr->ctrl->end[k] < chr->expt->end[j])
k++;
else {
if (chr->ctrl->end[k] == chr->expt->end[j])
k++;
j++;
}
}
start = chr->pval[n]->end[m];
}
}
}
/*** Call peaks ***/
/* void printPeak()
* Print peaks in ENCODE narrowPeak format.
*/
void printPeak(File out, bool gzOut, char* name,
int64_t start, int64_t end, int count, float signal,
float pval, float qval, uint32_t pos) {
if (gzOut) {
gzprintf(out.gzf, "%s\t%ld\t%ld\tpeak_%d\t%d\t.\t%f\t%f",
name, start, end, count,
MIN((unsigned int) (1000.0f * signal / (end - start)
+ 0.5f), 1000),
signal, pval);
if (qval == SKIP)
gzprintf(out.gzf, "\t-1\t%d\n", pos);
else
gzprintf(out.gzf, "\t%f\t%d\n", qval, pos);
} else {
fprintf(out.f, "%s\t%ld\t%ld\tpeak_%d\t%d\t.\t%f\t%f",
name, start, end, count,
MIN((unsigned int) (1000.0f * signal / (end - start)
+ 0.5f), 1000),
signal, pval);
if (qval == SKIP)
fprintf(out.f, "\t-1\t%d\n", pos);
else
fprintf(out.f, "\t%f\t%d\n", qval, pos);
}
}
/* void checkPeak()
* Check if potential peak is valid (coordinates,
* minAUC, and minLen parameters). If valid, print
* results via printPeak().
*/
void checkPeak(File out, bool gzOut, char* name,
int64_t start, int64_t end, int* count, float auc,
float pval, float qval, uint32_t pos, float minAUC,
int minLen, uint64_t* peakBP) {
if (start != -1 && auc >= minAUC
&& end - start >= minLen) {
printPeak(out, gzOut, name, start, end, *count,
auc, pval, qval, pos);
(*peakBP) += end - start;
(*count)++;
}
}
/* void resetVars()
* Reset peak variables to null values.
*/
void resetVars(int64_t* peakStart, float* summitVal,
uint32_t* summitLen, float* auc) {
*peakStart = -1;
*summitVal = -1.0f;
*summitLen = 0;
*auc = 0.0f;
}
/* void updatePeak()
* Update peak variables for current interval.
*/
void updatePeak(int64_t* peakStart, int64_t* peakEnd,
uint32_t start, uint32_t end, float* auc, float pqval,
float minPQval, float pval, float qval,
float* summitVal, float* summitPval, float* summitQval,
uint32_t* summitPos, uint32_t* summitLen) {
// update peak AUC, coordinates
uint32_t len = end - start;
*auc += len * (pqval - minPQval); // sum AUC
if (*peakStart == -1)
*peakStart = start; // start new potential peak
*peakEnd = end; // end of potential peak (for now)
// check if interval is summit for this peak
if (pqval > *summitVal) {
*summitVal = pqval;
*summitPval = pval;
*summitQval = qval;
*summitPos = (end + start)/2 - *peakStart; // midpoint of interval
*summitLen = len;
} else if (pqval == *summitVal) {
// update summitPos only if interval is longer
if (len > *summitLen) {
*summitPos = (end + start)/2 - *peakStart; // midpoint of interval
*summitLen = len;
// assume summitPval, summitQval remain the same
}
}
}
/* int callPeaks()
* Call peaks, using minAUC, maxGap, and minLen parameters.
* Produce output on the fly. Log pileups, p- and
* q-values for each interval. Return number of peaks.
*/
int callPeaks(File out, File log, bool logOpt, bool gzOut,
Chrom* chrom, int chromLen, int n, float minPQval,
bool qvalOpt, float minAUC, int minLen, int maxGap,
uint64_t* peakBP) {
if (logOpt)
printLogHeader(log, gzOut, n, qvalOpt, true);
// loop through chroms
int count = 0; // count of peaks
for (int i = 0; i < chromLen; i++) {
Chrom* chr = chrom + i;
if (chr->skip || (qvalOpt && chr->qval == NULL)
|| (! qvalOpt && chr->pval[n] == NULL) )
continue;
// create indexes into arrays for logging purposes
// (expt/ctrl pileup [if n == 0] and p-value arrays [if n > 0])
uint32_t j = 0, k = 0; // indexes into chr->expt, chr->ctrl
uint32_t idx[n]; // indexes into each pval array
for (int r = 0; r < n; r++)
idx[r] = 0;
// initialize peak variables