forked from deeptools/pyBigWig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyBigWig.c
1909 lines (1709 loc) · 55.5 KB
/
pyBigWig.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
#include <Python.h>
#include <inttypes.h>
#include "pyBigWig.h"
#ifdef WITHNUMPY
#include <float.h>
#include "numpy/npy_common.h"
#include "numpy/halffloat.h"
#include "numpy/ndarrayobject.h"
#include "numpy/arrayscalars.h"
int lsize = NPY_SIZEOF_LONG;
//Raises an exception on error, which should be checked
uint32_t getNumpyU32(PyArrayObject *obj, Py_ssize_t i) {
int dtype;
char *p;
uint32_t o = 0;
npy_intp stride;
//Get the dtype
dtype = PyArray_TYPE(obj);
//Get the stride
stride = PyArray_STRIDE(obj, 0);
p = PyArray_BYTES(obj) + i*stride;
switch(dtype) {
case NPY_INT8:
if(((int8_t *) p)[0] < 0) {
PyErr_SetString(PyExc_RuntimeError, "Received an integer < 0!\n");
goto error;
}
o += ((int8_t *) p)[0];
break;
case NPY_INT16:
if(((int16_t *) p)[0] < 0) {
PyErr_SetString(PyExc_RuntimeError, "Received an integer < 0!\n");
goto error;
}
o += ((int16_t *) p)[0];
break;
case NPY_INT32:
if(((int32_t *) p)[0] < 0) {
PyErr_SetString(PyExc_RuntimeError, "Received an integer < 0!\n");
goto error;
}
o += ((int32_t *) p)[0];
break;
case NPY_INT64:
if(((int64_t *) p)[0] < 0) {
PyErr_SetString(PyExc_RuntimeError, "Received an integer < 0!\n");
goto error;
}
o += ((int64_t *) p)[0];
break;
case NPY_UINT8:
o += ((uint8_t *) p)[0];
break;
case NPY_UINT16:
o += ((uint16_t *) p)[0];
break;
case NPY_UINT32:
o += ((uint32_t *) p)[0];
break;
case NPY_UINT64:
if(((uint64_t *) p)[0] > (uint32_t) -1) {
PyErr_SetString(PyExc_RuntimeError, "Received an integer larger than possible for a 32bit unsigned integer!\n");
goto error;
}
o += ((uint64_t *) p)[0];
break;
default:
PyErr_SetString(PyExc_RuntimeError, "Received unknown data type for conversion to uint32_t!\n");
goto error;
break;
}
return o;
error:
return 0;
};
long getNumpyL(PyObject *obj) {
short s;
int i;
long l;
long long ll;
unsigned short us;
unsigned int ui;
unsigned long ul;
unsigned long long ull;
if(!PyArray_IsIntegerScalar(obj)) {
PyErr_SetString(PyExc_RuntimeError, "Received non-Integer scalar type for conversion to long!\n");
return 0;
}
if(PyArray_IsScalar(obj, Short)) {
s = ((PyShortScalarObject *)obj)->obval;
l = s;
} else if(PyArray_IsScalar(obj, Int)) {
i = ((PyLongScalarObject *)obj)->obval;
l = i;
} else if(PyArray_IsScalar(obj, Long)) {
l = ((PyLongScalarObject *)obj)->obval;
} else if(PyArray_IsScalar(obj, LongLong)) {
ll = ((PyLongScalarObject *)obj)->obval;
l = ll;
} else if(PyArray_IsScalar(obj, UShort)) {
us = ((PyLongScalarObject *)obj)->obval;
l = us;
} else if(PyArray_IsScalar(obj, UInt)) {
ui = ((PyLongScalarObject *)obj)->obval;
l = ui;
} else if(PyArray_IsScalar(obj, ULong)) {
ul = ((PyLongScalarObject *)obj)->obval;
l = ul;
} else if(PyArray_IsScalar(obj, ULongLong)) {
ull = ((PyLongScalarObject *)obj)->obval;
l = ull;
} else {
PyErr_SetString(PyExc_RuntimeError, "Received unknown scalar type for conversion to long!\n");
return 0;
}
return l;
}
//Raises an exception on error, which should be checked
float getNumpyF(PyArrayObject *obj, Py_ssize_t i) {
int dtype;
char *p;
float o = 0.0;
npy_intp stride;
//Get the dtype
dtype = PyArray_TYPE(obj);
//Get the stride
stride = PyArray_STRIDE(obj, 0);
p = PyArray_BYTES(obj) + i*stride;
switch(dtype) {
case NPY_FLOAT16:
return npy_half_to_float(((npy_half*)p)[0]);
case NPY_FLOAT32:
return ((float*)p)[0];
case NPY_FLOAT64:
if(((double*)p)[0] > FLT_MAX) {
PyErr_SetString(PyExc_RuntimeError, "Received a floating point value greater than possible for a 32-bit float!\n");
goto error;
}
if(((double*)p)[0] < -FLT_MAX) {
PyErr_SetString(PyExc_RuntimeError, "Received a floating point value less than possible for a 32-bit float!\n");
goto error;
}
o += ((double*)p)[0];
return o;
default:
PyErr_SetString(PyExc_RuntimeError, "Received unknown data type for conversion to float!\n");
goto error;
break;
}
return o;
error:
return 0;
}
//The calling function needs to free the result
char *getNumpyStr(PyArrayObject *obj, Py_ssize_t i) {
char *p , *o = NULL;
npy_intp stride, j;
int dtype;
//Get the dtype
dtype = PyArray_TYPE(obj);
//Get the stride
stride = PyArray_STRIDE(obj, 0);
p = PyArray_BYTES(obj) + i*stride;
switch(dtype) {
case NPY_STRING:
o = calloc(1, stride + 1);
strncpy(o, p, stride);
return o;
case NPY_UNICODE:
o = calloc(1, stride/4 + 1);
for(j=0; j<stride/4; j++) o[j] = (char) ((uint32_t*)p)[j];
return o;
default:
PyErr_SetString(PyExc_RuntimeError, "Received unknown data type!\n");
break;
}
return NULL;
}
#endif
//Return 1 if there are any entries at all
int hasEntries(bigWigFile_t *bw) {
if(bw->hdr->nBasesCovered > 0) return 1;
return 0;
}
PyObject* pyBwEnter(pyBigWigFile_t*self, PyObject *args) {
bigWigFile_t *bw = self->bw;
if(!bw) {
PyErr_SetString(PyExc_RuntimeError, "The bigWig file handle is not opened!");
return NULL;
}
Py_INCREF(self);
return (PyObject*) self;
}
PyObject* pyBwOpen(PyObject *self, PyObject *pyFname) {
char *fname = NULL;
char *mode = "r";
pyBigWigFile_t *pybw;
bigWigFile_t *bw = NULL;
if(!PyArg_ParseTuple(pyFname, "s|s", &fname, &mode)) goto error;
//Open the local/remote file
if(strchr(mode, 'w') != NULL || bwIsBigWig(fname, NULL)) {
bw = bwOpen(fname, NULL, mode);
} else {
bw = bbOpen(fname, NULL);
}
if(!bw) {
fprintf(stderr, "[pyBwOpen] bw is NULL!\n");
goto error;
}
if(!mode || !strchr(mode, 'w')) {
if(!bw->cl) goto error;
}
pybw = PyObject_New(pyBigWigFile_t, &bigWigFile);
if(!pybw) {
fprintf(stderr, "[pyBwOpen] PyObject_New() returned NULL (out of memory?)!\n");
goto error;
}
pybw->bw = bw;
pybw->lastTid = -1;
pybw->lastType = -1;
pybw->lastSpan = (uint32_t) -1;
pybw->lastStep = (uint32_t) -1;
pybw->lastStart = (uint32_t) -1;
return (PyObject*) pybw;
error:
if(bw) bwClose(bw);
PyErr_SetString(PyExc_RuntimeError, "Received an error during file opening!");
return NULL;
}
static void pyBwDealloc(pyBigWigFile_t *self) {
if(self->bw) bwClose(self->bw);
PyObject_DEL(self);
}
static PyObject *pyBwClose(pyBigWigFile_t *self, PyObject *args) {
bwClose(self->bw);
self->bw = NULL;
Py_INCREF(Py_None);
return Py_None;
}
//Accessor for the header (version, nLevels, nBasesCovered, minVal, maxVal, sumData, sumSquared
static PyObject *pyBwGetHeader(pyBigWigFile_t *self, PyObject *args) {
bigWigFile_t *bw = self->bw;
PyObject *ret, *val;
if(!bw) {
PyErr_SetString(PyExc_RuntimeError, "The bigWig file handle is not opened!");
return NULL;
}
ret = PyDict_New();
val = PyLong_FromUnsignedLong(bw->hdr->version);
if(PyDict_SetItemString(ret, "version", val) == -1) goto error;
Py_DECREF(val);
val = PyLong_FromUnsignedLong(bw->hdr->nLevels);
if(PyDict_SetItemString(ret, "nLevels", val) == -1) goto error;
Py_DECREF(val);
val = PyLong_FromUnsignedLongLong(bw->hdr->nBasesCovered);
if(PyDict_SetItemString(ret, "nBasesCovered", val) == -1) goto error;
Py_DECREF(val);
val = PyLong_FromDouble(bw->hdr->minVal);
if(PyDict_SetItemString(ret, "minVal", val) == -1) goto error;
Py_DECREF(val);
val = PyLong_FromDouble(bw->hdr->maxVal);
if(PyDict_SetItemString(ret, "maxVal", val) == -1) goto error;
Py_DECREF(val);
val = PyLong_FromDouble(bw->hdr->sumData);
if(PyDict_SetItemString(ret, "sumData", val) == -1) goto error;
Py_DECREF(val);
val = PyLong_FromDouble(bw->hdr->sumSquared);
if(PyDict_SetItemString(ret, "sumSquared", val) == -1) goto error;
Py_DECREF(val);
return ret;
error :
Py_XDECREF(val);
Py_XDECREF(ret);
PyErr_SetString(PyExc_RuntimeError, "Received an error while getting the bigWig header!");
return NULL;
}
//Accessor for the chroms, args is optional
static PyObject *pyBwGetChroms(pyBigWigFile_t *self, PyObject *args) {
PyObject *ret = NULL, *val;
bigWigFile_t *bw = self->bw;
char *chrom = NULL;
uint32_t i;
if(!bw) {
PyErr_SetString(PyExc_RuntimeError, "The bigWig file handle is not opened!");
return NULL;
}
if(!(PyArg_ParseTuple(args, "|s", &chrom)) || !chrom) {
ret = PyDict_New();
for(i=0; i<bw->cl->nKeys; i++) {
val = PyLong_FromUnsignedLong(bw->cl->len[i]);
if(PyDict_SetItemString(ret, bw->cl->chrom[i], val) == -1) goto error;
Py_DECREF(val);
}
} else {
for(i=0; i<bw->cl->nKeys; i++) {
if(strcmp(bw->cl->chrom[i],chrom) == 0) {
ret = PyLong_FromUnsignedLong(bw->cl->len[i]);
break;
}
}
}
if(!ret) {
Py_INCREF(Py_None);
ret = Py_None;
}
return ret;
error :
Py_XDECREF(val);
Py_XDECREF(ret);
PyErr_SetString(PyExc_RuntimeError, "Received an error while adding an item to the output dictionary!");
return NULL;
}
enum bwStatsType char2enum(char *s) {
if(strcmp(s, "mean") == 0) return mean;
if(strcmp(s, "std") == 0) return stdev;
if(strcmp(s, "dev") == 0) return dev;
if(strcmp(s, "max") == 0) return max;
if(strcmp(s, "min") == 0) return min;
if(strcmp(s, "cov") == 0) return cov;
if(strcmp(s, "coverage") == 0) return cov;
if(strcmp(s, "sum") == 0) return sum;
return -1;
};
//Fetch summary statistics, default is the mean of the entire chromosome.
static PyObject *pyBwGetStats(pyBigWigFile_t *self, PyObject *args, PyObject *kwds) {
bigWigFile_t *bw = self->bw;
double *val;
uint32_t start, end = -1, tid;
unsigned long startl = 0, endl = -1;
static char *kwd_list[] = {"chrom", "start", "end", "type", "nBins", "exact", NULL};
char *chrom, *type = "mean";
PyObject *ret, *exact = Py_False, *starto = NULL, *endo = NULL;
int i, nBins = 1;
errno = 0; //In the off-chance that something elsewhere got an error and didn't clear it...
if(!bw) {
PyErr_SetString(PyExc_RuntimeError, "The bigWig file handle is not open!");
return NULL;
}
if(bw->type == 1) {
PyErr_SetString(PyExc_RuntimeError, "bigBed files have no statistics!");
return NULL;
}
if(!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOsiO", kwd_list, &chrom, &starto, &endo, &type, &nBins, &exact)) {
PyErr_SetString(PyExc_RuntimeError, "You must supply at least a chromosome!");
return NULL;
}
//Check inputs, reset to defaults if nothing was input
if(!nBins) nBins = 1; //For some reason, not specifying this overrides the default!
if(!type) type = "mean";
tid = bwGetTid(bw, chrom);
if(starto) {
#ifdef WITHNUMPY
if(PyArray_IsScalar(starto, Integer)) {
startl = (long) getNumpyL(starto);
} else
#endif
if(PyLong_Check(starto)) {
startl = PyLong_AsLong(starto);
#if PY_MAJOR_VERSION < 3
} else if(PyInt_Check(starto)) {
startl = PyInt_AsLong(starto);
#endif
} else {
PyErr_SetString(PyExc_RuntimeError, "The start coordinate must be a number!");
return NULL;
}
}
if(endo) {
#ifdef WITHNUMPY
if(PyArray_IsScalar(endo, Integer)) {
endl = (long) getNumpyL(endo);
} else
#endif
if(PyLong_Check(endo)) {
endl = PyLong_AsLong(endo);
#if PY_MAJOR_VERSION < 3
} else if(PyInt_Check(endo)) {
endl = PyInt_AsLong(endo);
#endif
} else {
PyErr_SetString(PyExc_RuntimeError, "The end coordinate must be a number!");
return NULL;
}
}
if(endl == (unsigned long) -1 && tid != (uint32_t) -1) endl = bw->cl->len[tid];
if(tid == (uint32_t) -1 || startl > end || endl > end) {
PyErr_SetString(PyExc_RuntimeError, "Invalid interval bounds!");
return NULL;
}
start = (uint32_t) startl;
end = (uint32_t) endl;
if(end <= start || end > bw->cl->len[tid] || start >= end) {
PyErr_SetString(PyExc_RuntimeError, "Invalid interval bounds!");
return NULL;
}
if(char2enum(type) == doesNotExist) {
PyErr_SetString(PyExc_RuntimeError, "Invalid type!");
return NULL;
}
//Return a list of None if there are no entries at all
if(!hasEntries(bw)) {
ret = PyList_New(nBins);
for(i=0; i<nBins; i++) {
Py_INCREF(Py_None);
PyList_SetItem(ret, i, Py_None);
}
return ret;
}
//Get the actual statistics
if(exact == Py_True) {
val = bwStatsFromFull(bw, chrom, start, end, nBins, char2enum(type));
} else {
val = bwStats(bw, chrom, start, end, nBins, char2enum(type));
}
if(!val) {
PyErr_SetString(PyExc_RuntimeError, "An error was encountered while fetching statistics.");
return NULL;
}
ret = PyList_New(nBins);
for(i=0; i<nBins; i++) {
if(isnan(val[i])) {
Py_INCREF(Py_None);
PyList_SetItem(ret, i, Py_None);
} else {
PyList_SetItem(ret, i, PyFloat_FromDouble(val[i]));
}
}
free(val);
return ret;
}
//Fetch a list of individual values
//For bases with no coverage, the value should be None
#ifdef WITHNUMPY
static PyObject *pyBwGetValues(pyBigWigFile_t *self, PyObject *args, PyObject *kwds) {
#else
static PyObject *pyBwGetValues(pyBigWigFile_t *self, PyObject *args) {
#endif
bigWigFile_t *bw = self->bw;
int i;
uint32_t start, end = -1, tid;
unsigned long startl, endl;
char *chrom;
PyObject *ret, *starto = NULL, *endo = NULL;
bwOverlappingIntervals_t *o;
if(!bw) {
PyErr_SetString(PyExc_RuntimeError, "The bigWig file handle is not open!");
return NULL;
}
if(bw->type == 1) {
PyErr_SetString(PyExc_RuntimeError, "bigBed files have no values! Use 'entries' instead.");
return NULL;
}
#ifdef WITHNUMPY
static char *kwd_list[] = {"chrom", "start", "end", "numpy", NULL};
PyObject *outputNumpy = Py_False;
if(!PyArg_ParseTupleAndKeywords(args, kwds, "sOO|O", kwd_list, &chrom, &starto, &endo, &outputNumpy)) {
#else
if(!PyArg_ParseTuple(args, "sOO", &chrom, &starto, &endo)) {
#endif
PyErr_SetString(PyExc_RuntimeError, "You must supply a chromosome, start and end position.\n");
return NULL;
}
tid = bwGetTid(bw, chrom);
#ifdef WITHNUMPY
if(PyArray_IsScalar(starto, Integer)) {
startl = (long) getNumpyL(starto);
} else
#endif
if(PyLong_Check(starto)) {
startl = PyLong_AsLong(starto);
#if PY_MAJOR_VERSION < 3
} else if(PyInt_Check(starto)) {
startl = PyInt_AsLong(starto);
#endif
} else {
PyErr_SetString(PyExc_RuntimeError, "The start coordinate must be a number!");
return NULL;
}
#ifdef WITHNUMPY
if(PyArray_IsScalar(endo, Integer)) {
endl = (long) getNumpyL(endo);
} else
#endif
if(PyLong_Check(endo)) {
endl = PyLong_AsLong(endo);
#if PY_MAJOR_VERSION < 3
} else if(PyInt_Check(endo)) {
endl = PyInt_AsLong(endo);
#endif
} else {
PyErr_SetString(PyExc_RuntimeError, "The end coordinate must be a number!");
return NULL;
}
if(endl == (unsigned long) -1 && tid != (uint32_t) -1) endl = bw->cl->len[tid];
if(tid == (uint32_t) -1 || startl > end || endl > end) {
PyErr_SetString(PyExc_RuntimeError, "Invalid interval bounds!");
return NULL;
}
start = (uint32_t) startl;
end = (uint32_t) endl;
if(end <= start || end > bw->cl->len[tid] || start >= end) {
PyErr_SetString(PyExc_RuntimeError, "Invalid interval bounds!");
return NULL;
}
if(!hasEntries(self->bw)) {
#ifdef WITHNUMPY
if(outputNumpy == Py_True) {
return PyArray_SimpleNew(0, NULL, NPY_FLOAT);
} else {
#endif
return PyList_New(0);
#ifdef WITHNUMPY
}
#endif
}
o = bwGetValues(self->bw, chrom, start, end, 1);
if(!o) {
PyErr_SetString(PyExc_RuntimeError, "An error occurred while fetching values!");
return NULL;
}
#ifdef WITHNUMPY
if(outputNumpy == Py_True) {
npy_intp len = end - start;
ret = PyArray_SimpleNewFromData(1, &len, NPY_FLOAT, (void *) o->value);
//This will break if numpy ever stops using malloc!
PyArray_ENABLEFLAGS((PyArrayObject*) ret, NPY_ARRAY_OWNDATA);
free(o->start);
free(o->end);
free(o);
} else {
#endif
ret = PyList_New(end-start);
for(i=0; i<(int) o->l; i++) PyList_SetItem(ret, i, PyFloat_FromDouble(o->value[i]));
bwDestroyOverlappingIntervals(o);
#ifdef WITHNUMPY
}
#endif
return ret;
}
static PyObject *pyBwGetIntervals(pyBigWigFile_t *self, PyObject *args, PyObject *kwds) {
bigWigFile_t *bw = self->bw;
uint32_t start, end = -1, tid, i;
unsigned long startl = 0, endl = -1;
static char *kwd_list[] = {"chrom", "start", "end", NULL};
bwOverlappingIntervals_t *intervals = NULL;
char *chrom;
PyObject *ret, *starto = NULL, *endo = NULL;
if(!bw) {
PyErr_SetString(PyExc_RuntimeError, "The bigWig file handle is not opened!");
return NULL;
}
if(bw->type == 1) {
PyErr_SetString(PyExc_RuntimeError, "bigBed files have no intervals! Use 'entries()' instead.");
return NULL;
}
if(!PyArg_ParseTupleAndKeywords(args, kwds, "s|OO", kwd_list, &chrom, &starto, &endo)) {
PyErr_SetString(PyExc_RuntimeError, "You must supply at least a chromosome.\n");
return NULL;
}
//Sanity check
tid = bwGetTid(bw, chrom);
if(endl == (unsigned long) -1 && tid != (uint32_t) -1) endl = bw->cl->len[tid];
if(tid == (uint32_t) -1 || startl > end || endl > end) {
PyErr_SetString(PyExc_RuntimeError, "Invalid interval bounds!");
return NULL;
}
if(starto) {
#ifdef WITHNUMPY
if(PyArray_IsScalar(starto, Integer)) {
startl = (long) getNumpyL(starto);
} else
#endif
if(PyLong_Check(starto)) {
startl = PyLong_AsLong(starto);
#if PY_MAJOR_VERSION < 3
} else if(PyInt_Check(starto)) {
startl = PyInt_AsLong(starto);
#endif
} else {
PyErr_SetString(PyExc_RuntimeError, "The start coordinate must be a number!");
return NULL;
}
}
if(endo) {
#ifdef WITHNUMPY
if(PyArray_IsScalar(endo, Integer)) {
endl = (long) getNumpyL(endo);
} else
#endif
if(PyLong_Check(endo)) {
endl = PyLong_AsLong(endo);
#if PY_MAJOR_VERSION < 3
} else if(PyInt_Check(endo)) {
endl = PyInt_AsLong(endo);
#endif
} else {
PyErr_SetString(PyExc_RuntimeError, "The end coordinate must be a number!");
return NULL;
}
}
start = (uint32_t) startl;
end = (uint32_t) endl;
if(end <= start || end > bw->cl->len[tid] || start >= end) {
PyErr_SetString(PyExc_RuntimeError, "Invalid interval bounds!");
return NULL;
}
//Check for empty files
if(!hasEntries(bw)) {
Py_INCREF(Py_None);
return Py_None;
}
//Get the intervals
intervals = bwGetOverlappingIntervals(bw, chrom, start, end);
if(!intervals) {
PyErr_SetString(PyExc_RuntimeError, "An error occurred while fetching the overlapping intervals!");
return NULL;
}
if(!intervals->l) {
Py_INCREF(Py_None);
return Py_None;
}
ret = PyTuple_New(intervals->l);
for(i=0; i<intervals->l; i++) {
if(PyTuple_SetItem(ret, i, Py_BuildValue("(iif)", intervals->start[i], intervals->end[i], intervals->value[i]))) {
Py_DECREF(ret);
bwDestroyOverlappingIntervals(intervals);
PyErr_SetString(PyExc_RuntimeError, "An error occurred while constructing the output tuple!");
return NULL;
}
}
bwDestroyOverlappingIntervals(intervals);
return ret;
}
#if PY_MAJOR_VERSION >= 3
//Return 1 iff obj is a ready unicode type
int PyString_Check(PyObject *obj) {
if(PyUnicode_Check(obj)) {
return PyUnicode_READY(obj)+1;
}
return 0;
}
//I don't know what happens if PyBytes_AsString(NULL) is used...
char *PyString_AsString(PyObject *obj) {
return PyBytes_AsString(PyUnicode_AsASCIIString(obj));
}
#endif
//Will return 1 for long or int types currently
int isNumeric(PyObject *obj) {
#ifdef WITHNUMPY
if(PyArray_IsScalar(obj, Integer)) return 1;
#endif
#if PY_MAJOR_VERSION < 3
if(PyInt_Check(obj)) return 1;
#endif
return PyLong_Check(obj);
}
//On error, throws a runtime error, so use PyErr_Occurred() after this
uint32_t Numeric2Uint(PyObject *obj) {
long l;
#if PY_MAJOR_VERSION < 3
if(PyInt_Check(obj)) {
return (uint32_t) PyInt_AsLong(obj);
}
#endif
l = PyLong_AsLong(obj);
//Check bounds
if(l > 0xFFFFFFFF) {
PyErr_SetString(PyExc_RuntimeError, "Length out of bounds for a bigWig file!");
return (uint32_t) -1;
}
return (uint32_t) l;
}
//This runs bwCreateHdr, bwCreateChromList, and bwWriteHdr
PyObject *pyBwAddHeader(pyBigWigFile_t *self, PyObject *args, PyObject *kwds) {
bigWigFile_t *bw = self->bw;
char **chroms = NULL;
int64_t n;
uint32_t *lengths = NULL, len;
int32_t maxZooms = 10;
long zoomTmp = 10;
static char *kwd_list[] = {"cl", "maxZooms", NULL};
PyObject *InputTuple = NULL, *tmpObject, *tmpObject2;
Py_ssize_t i, pyLen;
if(!bw) {
PyErr_SetString(PyExc_RuntimeError, "The bigWig file handle is not open!");
return NULL;
}
if(!PyArg_ParseTupleAndKeywords(args, kwds, "O|k", kwd_list, &InputTuple, &zoomTmp)) {
PyErr_SetString(PyExc_RuntimeError, "Illegal arguments");
return NULL;
}
maxZooms = zoomTmp;
//Ensure that we received a list
if(!PyList_Check(InputTuple)) {
PyErr_SetString(PyExc_RuntimeError, "You MUST input a list of tuples (e.g., [('chr1', 1000), ('chr2', 2000)]!");
goto error;
}
pyLen = PyList_Size(InputTuple);
if(pyLen < 1) {
PyErr_SetString(PyExc_RuntimeError, "You input an empty list!");
goto error;
}
n = pyLen;
lengths = calloc(n, sizeof(uint32_t));
chroms = calloc(n, sizeof(char*));
if(!lengths || !chroms) {
PyErr_SetString(PyExc_RuntimeError, "Couldn't allocate lengths or chroms!");
goto error;
}
//Convert the tuple into something more useful in C
for(i=0; i<pyLen; i++) {
tmpObject = PyList_GetItem(InputTuple, i);
if(!tmpObject) {
PyErr_SetString(PyExc_RuntimeError, "Couldn't get a tuple!");
goto error;
}
if(!PyTuple_Check(tmpObject)) {
PyErr_SetString(PyExc_RuntimeError, "The input list is not made up of tuples!");
goto error;
}
if(PyTuple_Size(tmpObject) != 2) {
PyErr_SetString(PyExc_RuntimeError, "One tuple does not contain exactly 2 members!");
goto error;
}
//Chromosome
tmpObject2 = PyTuple_GetItem(tmpObject, 0); //This returns NULL in python3?!?
if(!PyString_Check(tmpObject2)) {
PyErr_SetString(PyExc_RuntimeError, "The first element of each tuple MUST be a string!");
goto error;
}
chroms[i] = PyString_AsString(tmpObject2);
if(!chroms[i]) {
PyErr_SetString(PyExc_RuntimeError, "Received something other than a string for a chromosome name!");
goto error;
}
//Length
tmpObject2 = PyTuple_GetItem(tmpObject, 1);
if(!isNumeric(tmpObject2)) {
PyErr_SetString(PyExc_RuntimeError, "The second element of each tuple MUST be an integer!");
goto error;
}
len = Numeric2Uint(tmpObject2);
if(PyErr_Occurred()) goto error;
if(zoomTmp > 0xFFFFFFFF) {
PyErr_SetString(PyExc_RuntimeError, "A requested length is longer than what can be stored in a bigWig file!");
goto error;
}
lengths[i] = len;
}
//Create the header
if(bwCreateHdr(bw, maxZooms)) {
PyErr_SetString(PyExc_RuntimeError, "Received an error in bwCreateHdr");
goto error;
}
//Create the chromosome list
bw->cl = bwCreateChromList(chroms, lengths, n);
if(!bw->cl) {
PyErr_SetString(PyExc_RuntimeError, "Received an error in bwCreateChromList");
goto error;
}
//Write the header
if(bwWriteHdr(bw)) {
PyErr_SetString(PyExc_RuntimeError, "Received an error while writing the bigWig header");
goto error;
}
if(lengths) free(lengths);
if(chroms) free(chroms);
Py_INCREF(Py_None);
return Py_None;
error:
if(lengths) free(lengths);
if(chroms) free(chroms);
return NULL;
}
//1 on true, 0 on false
int isType0(PyObject *chroms, PyObject *starts, PyObject *ends, PyObject *values) {
int rv = 0;
Py_ssize_t i, sz = 0;
PyObject *tmp;
if(!PyList_Check(chroms)
#ifdef WITHNUMPY
&& !PyArray_Check(chroms)
#endif
) return rv;
if(!PyList_Check(starts)
#ifdef WITHNUMPY
&& !PyArray_Check(starts)
#endif
) return rv;
if(!PyList_Check(ends)
#ifdef WITHNUMPY
&& !PyArray_Check(ends)
#endif
) return rv;
if(!PyList_Check(values)
#ifdef WITHNUMPY
&& !PyArray_Check(values)
#endif
) return rv;
if(PyList_Check(chroms)) sz = PyList_Size(chroms);
#ifdef WITHNUMPY
if(PyArray_Check(chroms)) sz += PyArray_Size(chroms);
#endif
if(PyList_Check(starts)) {
if(sz != PyList_Size(starts)) return rv;
#ifdef WITHNUMPY
} else {
if(sz != PyArray_Size(starts)) return rv;
#endif
}
if(PyList_Check(ends)) {
if(sz != PyList_Size(ends)) return rv;
#ifdef WITHNUMPY
} else {
if(sz != PyArray_Size(ends)) return rv;
#endif
}
if(PyList_Check(values)) {
if(sz != PyList_Size(values)) return rv;
#ifdef WITHNUMPY
} else {
if(sz != PyArray_Size(values)) return rv;
#endif
}
//Ensure chroms contains strings, etc.
if(PyList_Check(chroms)) {
for(i=0; i<sz; i++) {
tmp = PyList_GetItem(chroms, i);
if(!PyString_Check(tmp)) return rv;
}
#ifdef WITHNUMPY
} else {
if(!PyArray_ISSTRING( (PyArrayObject*) chroms)) return rv;
#endif
}
if(PyList_Check(starts)) {
for(i=0; i<sz; i++) {
tmp = PyList_GetItem(starts, i);
if(!isNumeric(tmp)) return rv;
}
#ifdef WITHNUMPY
} else {
if(!PyArray_ISINTEGER( (PyArrayObject*) starts)) return rv;
#endif
}
if(PyList_Check(ends)) {
for(i=0; i<sz; i++) {
tmp = PyList_GetItem(ends, i);
if(!isNumeric(tmp)) return rv;
}
#ifdef WITHNUMPY
} else {
if(!PyArray_ISINTEGER( (PyArrayObject*) ends)) return rv;
#endif
}
if(PyList_Check(values)) {
for(i=0; i<sz; i++) {
tmp = PyList_GetItem(values, i);
if(!PyFloat_Check(tmp)) return rv;
}
#ifdef WITHNUMPY
} else {
if(!PyArray_ISFLOAT((PyArrayObject*) values)) return rv;
#endif
}
return 1;
}
//single chrom, multiple starts, single span
int isType1(PyObject *chroms, PyObject *starts, PyObject *values, PyObject *span) {
int rv = 0;
Py_ssize_t i, sz = 0;
PyObject *tmp;
if(!PyString_Check(chroms)) return rv;
if(!PyList_Check(starts)
#ifdef WITHNUMPY
&& !PyArray_Check(starts)
#endif
) return rv;
if(!PyList_Check(values)
#ifdef WITHNUMPY
&& !PyArray_Check(values)
#endif
) return rv;
if(!isNumeric(span)) return rv;
if(PyList_Check(starts)) sz = PyList_Size(starts);
#ifdef WITHNUMPY
if(PyArray_Check(starts)) sz += PyArray_Size(starts);
#endif
if(PyList_Check(values)) if(sz != PyList_Size(values)) return rv;
#ifdef WITHNUMPY
if(PyArray_Check(values)) if(sz != PyArray_Size(values)) return rv;
#endif