-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstraw.cpp
More file actions
1263 lines (1130 loc) · 47.6 KB
/
Copy pathstraw.cpp
File metadata and controls
1263 lines (1130 loc) · 47.6 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
/*
The MIT License (MIT)
Copyright (c) 2011-2016 Broad Institute, Aiden Lab
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 <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <cmath>
#include <set>
#include <vector>
#include <streambuf>
#include <curl/curl.h>
#include "zlib.h"
#include "straw.h"
using namespace std;
/*
Straw: fast C++ implementation of dump. Not as fully featured as the
Java version. Reads the .hic file, finds the appropriate matrix and slice
of data, and outputs as text in sparse upper triangular format.
Currently only supporting matrices.
Usage: straw <NONE/VC/VC_SQRT/KR> <hicFile(s)> <chr1>[:x1:x2] <chr2>[:y1:y2] <BP/FRAG> <binsize>
*/
// this is for creating a stream from a byte array for ease of use
struct membuf : std::streambuf {
membuf(char *begin, char *end) {
this->setg(begin, begin, end);
}
};
// for holding data from URL call
struct MemoryStruct {
char *memory;
size_t size;
};
// callback for libcurl. data written to this buffer
static size_t
WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *) userp;
mem->memory = static_cast<char *>(realloc(mem->memory, mem->size + realsize + 1));
if (mem->memory == nullptr) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
std::memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
// get a buffer that can be used as an input stream from the URL
char *getData(CURL *curl, int64_t position, int64_t chunksize) {
std::ostringstream oss;
struct MemoryStruct chunk;
chunk.memory = static_cast<char *>(malloc(1));
chunk.size = 0; /* no data at this point */
oss << position << "-" << position + chunksize;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &chunk);
curl_easy_setopt(curl, CURLOPT_RANGE, oss.str().c_str());
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
// printf("%lu bytes retrieved\n", (int64_t)chunk.size);
return chunk.memory;
}
// returns whether or not this is valid HiC file
bool readMagicString(istream &fin) {
string str;
getline(fin, str, '\0');
return str[0] == 'H' && str[1] == 'I' && str[2] == 'C';
}
char readCharFromFile(istream &fin) {
char tempChar;
fin.read(&tempChar, sizeof(char));
return tempChar;
}
int16_t readInt16FromFile(istream &fin) {
int16_t tempInt16;
fin.read((char *) &tempInt16, sizeof(int16_t));
return tempInt16;
}
int32_t readInt32FromFile(istream &fin) {
int32_t tempInt32;
fin.read((char *) &tempInt32, sizeof(int32_t));
return tempInt32;
}
int64_t readInt64FromFile(istream &fin) {
int64_t tempInt64;
fin.read((char *) &tempInt64, sizeof(int64_t));
return tempInt64;
}
float readFloatFromFile(istream &fin) {
float tempFloat;
fin.read((char *) &tempFloat, sizeof(float));
return tempFloat;
}
double readDoubleFromFile(istream &fin) {
double tempDouble;
fin.read((char *) &tempDouble, sizeof(double));
return tempDouble;
}
// reads the header, storing the positions of the normalization vectors and returning the masterIndexPosition pointer
map<string, chromosome> readHeader(istream &fin, int64_t &masterIndexPosition, string &genomeID, int32_t &numChromosomes,
int32_t &version, int64_t &nviPosition, int64_t &nviLength) {
map<string, chromosome> chromosomeMap;
if (!readMagicString(fin)) {
cerr << "Hi-C magic string is missing, does not appear to be a hic file" << endl;
masterIndexPosition = -1;
return chromosomeMap;
}
version = readInt32FromFile(fin);
if (version < 6) {
cerr << "Version " << version << " no longer supported" << endl;
masterIndexPosition = -1;
return chromosomeMap;
}
masterIndexPosition = readInt64FromFile(fin);
getline(fin, genomeID, '\0');
if (version > 8) {
nviPosition = readInt64FromFile(fin);
nviLength = readInt64FromFile(fin);
}
int32_t nattributes = readInt32FromFile(fin);
// reading and ignoring attribute-value dictionary
for (int i = 0; i < nattributes; i++) {
string key, value;
getline(fin, key, '\0');
getline(fin, value, '\0');
}
numChromosomes = readInt32FromFile(fin);
// chromosome map for finding matrixType
for (int i = 0; i < numChromosomes; i++) {
string name;
int64_t length;
getline(fin, name, '\0');
if (version > 8) {
length = readInt64FromFile(fin);
} else {
length = (int64_t) readInt32FromFile(fin);
}
chromosome chr;
chr.index = i;
chr.name = name;
chr.length = length;
chromosomeMap[name] = chr;
}
return chromosomeMap;
}
// reads the footer from the master pointer location. takes in the chromosomes,
// norm, unit (BP or FRAG) and resolution or binsize, and sets the file
// position of the matrix and the normalization vectors for those chromosomes
// at the given normalization and resolution
bool readFooter(istream &fin, int64_t master, int32_t version, int32_t c1, int32_t c2, const string &matrixType, const string &norm,
const string &unit, int32_t resolution, int64_t &myFilePos, indexEntry &c1NormEntry, indexEntry &c2NormEntry,
vector<double> &expectedValues) {
if (version > 8) {
int64_t nBytes = readInt64FromFile(fin);
} else {
int32_t nBytes = readInt32FromFile(fin);
}
stringstream ss;
ss << c1 << "_" << c2;
string key = ss.str();
int32_t nEntries = readInt32FromFile(fin);
bool found = false;
for (int i = 0; i < nEntries; i++) {
string str;
getline(fin, str, '\0');
int64_t fpos = readInt64FromFile(fin);
int32_t sizeinbytes = readInt32FromFile(fin);
if (str == key) {
myFilePos = fpos;
found = true;
}
}
if (!found) {
cerr << "File doesn't have the given chr_chr map " << key << endl;
return false;
}
if ((matrixType == "observed" && norm == "NONE") || ((matrixType == "oe" || matrixType == "expected") && norm == "NONE" && c1 != c2))
return true; // no need to read norm vector index
// read in and ignore expected value maps; don't store; reading these to
// get to norm vector index
int32_t nExpectedValues = readInt32FromFile(fin);
for (int i = 0; i < nExpectedValues; i++) {
string unit0;
getline(fin, unit0, '\0'); //unit
int32_t binSize = readInt32FromFile(fin);
int64_t nValues;
if (version > 8) {
nValues = readInt64FromFile(fin);
} else {
nValues = (int64_t) readInt32FromFile(fin);
}
bool store = c1 == c2 && (matrixType == "oe" || matrixType == "expected") && norm == "NONE" && unit0 == unit && binSize == resolution;
if (version > 8) {
for (int j = 0; j < nValues; j++) {
double v = readFloatFromFile(fin);
if (store) {
expectedValues.push_back(v);
}
}
} else {
for (int j = 0; j < nValues; j++) {
double v = readDoubleFromFile(fin);
if (store) {
expectedValues.push_back(v);
}
}
}
int32_t nNormalizationFactors = readInt32FromFile(fin);
for (int j = 0; j < nNormalizationFactors; j++) {
int32_t chrIdx = readInt32FromFile(fin);
double v;
if (version > 8) {
v = readFloatFromFile(fin);
} else {
v = readDoubleFromFile(fin);
}
if (store && chrIdx == c1) {
for (double &expectedValue : expectedValues) {
expectedValue = expectedValue / v;
}
}
}
}
if (c1 == c2 && (matrixType == "oe" || matrixType == "expected") && norm == "NONE") {
if (expectedValues.empty()) {
cerr << "File did not contain expected values vectors at " << resolution << " " << unit << endl;
return false;
}
return true;
}
nExpectedValues = readInt32FromFile(fin);
for (int i = 0; i < nExpectedValues; i++) {
string type, unit0;
getline(fin, type, '\0'); //typeString
getline(fin, unit0, '\0'); //unit
int32_t binSize = readInt32FromFile(fin);
int64_t nValues;
if (version > 8) {
nValues = readInt64FromFile(fin);
} else {
nValues = (int64_t) readInt32FromFile(fin);
}
bool store = c1 == c2 && (matrixType == "oe" || matrixType == "expected") && type == norm && unit0 == unit && binSize == resolution;
if (version > 8) {
for (int j = 0; j < nValues; j++) {
double v = readFloatFromFile(fin);
if (store) {
expectedValues.push_back(v);
}
}
} else {
for (int j = 0; j < nValues; j++) {
double v = readDoubleFromFile(fin);
if (store) {
expectedValues.push_back(v);
}
}
}
int32_t nNormalizationFactors = readInt32FromFile(fin);
for (int j = 0; j < nNormalizationFactors; j++) {
int32_t chrIdx = readInt32FromFile(fin);
double v;
if (version > 8) {
v = (double) readFloatFromFile(fin);
} else {
v = readDoubleFromFile(fin);
}
if (store && chrIdx == c1) {
for (double &expectedValue : expectedValues) {
expectedValue = expectedValue / v;
}
}
}
}
if (c1 == c2 && (matrixType == "oe" || matrixType == "expected") && norm != "NONE") {
if (expectedValues.empty()) {
cerr << "File did not contain normalized expected values vectors at " << resolution << " " << unit << endl;
return false;
}
}
// Index of normalization vectors
nEntries = readInt32FromFile(fin);
bool found1 = false;
bool found2 = false;
for (int i = 0; i < nEntries; i++) {
string normtype;
getline(fin, normtype, '\0'); //normalization type
int32_t chrIdx = readInt32FromFile(fin);
string unit1;
getline(fin, unit1, '\0'); //unit
int32_t resolution1 = readInt32FromFile(fin);
int64_t filePosition = readInt64FromFile(fin);
int64_t sizeInBytes;
if (version > 8) {
sizeInBytes = readInt64FromFile(fin);
} else {
sizeInBytes = (int64_t) readInt32FromFile(fin);
}
if (chrIdx == c1 && normtype == norm && unit1 == unit && resolution1 == resolution) {
c1NormEntry.position = filePosition;
c1NormEntry.size = sizeInBytes;
found1 = true;
}
if (chrIdx == c2 && normtype == norm && unit1 == unit && resolution1 == resolution) {
c2NormEntry.position = filePosition;
c2NormEntry.size = sizeInBytes;
found2 = true;
}
}
if (!found1 || !found2) {
cerr << "File did not contain " << norm << " normalization vectors for one or both chromosomes at "
<< resolution << " " << unit << endl;
}
return true;
}
// reads the raw binned contact matrix at specified resolution, setting the block bin count and block column count
map<int32_t, indexEntry> readMatrixZoomData(istream &fin, const string &myunit, int32_t mybinsize, float &mySumCounts,
int32_t &myBlockBinCount, int32_t &myBlockColumnCount, bool &found) {
map<int32_t, indexEntry> blockMap;
string unit;
getline(fin, unit, '\0'); // unit
readInt32FromFile(fin); // Old "zoom" index -- not used
float sumCounts = readFloatFromFile(fin); // sumCounts
readFloatFromFile(fin); // occupiedCellCount
readFloatFromFile(fin); // stdDev
readFloatFromFile(fin); // percent95
int32_t binSize = readInt32FromFile(fin);
int32_t blockBinCount = readInt32FromFile(fin);
int32_t blockColumnCount = readInt32FromFile(fin);
found = false;
if (myunit == unit && mybinsize == binSize) {
mySumCounts = sumCounts;
myBlockBinCount = blockBinCount;
myBlockColumnCount = blockColumnCount;
found = true;
}
int32_t nBlocks = readInt32FromFile(fin);
for (int b = 0; b < nBlocks; b++) {
int32_t blockNumber = readInt32FromFile(fin);
int64_t filePosition = readInt64FromFile(fin);
int32_t blockSizeInBytes = readInt32FromFile(fin);
indexEntry entry = indexEntry();
entry.size = (int64_t) blockSizeInBytes;
entry.position = filePosition;
if (found) blockMap[blockNumber] = entry;
}
return blockMap;
}
// reads the raw binned contact matrix at specified resolution, setting the block bin count and block column count
map<int32_t, indexEntry> readMatrixZoomDataHttp(CURL *curl, int64_t &myFilePosition, const string &myunit, int32_t mybinsize,
float &mySumCounts, int32_t &myBlockBinCount, int32_t &myBlockColumnCount,
bool &found) {
map<int32_t, indexEntry> blockMap;
char *buffer;
int32_t header_size = 5 * sizeof(int32_t) + 4 * sizeof(float);
char *first;
first = getData(curl, myFilePosition, 1);
if (first[0] == 'B') {
header_size += 3;
} else if (first[0] == 'F') {
header_size += 5;
} else {
cerr << "Unit not understood" << endl;
return blockMap;
}
buffer = getData(curl, myFilePosition, header_size);
membuf sbuf(buffer, buffer + header_size);
istream fin(&sbuf);
string unit;
getline(fin, unit, '\0'); // unit
readInt32FromFile(fin); // Old "zoom" index -- not used
float sumCounts = readFloatFromFile(fin); // sumCounts
readFloatFromFile(fin); // occupiedCellCount
readFloatFromFile(fin); // stdDev
readFloatFromFile(fin); // percent95
int32_t binSize = readInt32FromFile(fin);
int32_t blockBinCount = readInt32FromFile(fin);
int32_t blockColumnCount = readInt32FromFile(fin);
found = false;
if (myunit == unit && mybinsize == binSize) {
mySumCounts = sumCounts;
myBlockBinCount = blockBinCount;
myBlockColumnCount = blockColumnCount;
found = true;
}
int32_t nBlocks = readInt32FromFile(fin);
if (found) {
int32_t chunkSize = nBlocks * (sizeof(int32_t) + sizeof(int64_t) + sizeof(int32_t));
buffer = getData(curl, myFilePosition + header_size, chunkSize);
membuf sbuf2(buffer, buffer + chunkSize);
istream fin2(&sbuf2);
for (int b = 0; b < nBlocks; b++) {
int32_t blockNumber = readInt32FromFile(fin2);
int64_t filePosition = readInt64FromFile(fin2);
int32_t blockSizeInBytes = readInt32FromFile(fin2);
indexEntry entry = indexEntry();
entry.size = (int64_t) blockSizeInBytes;
entry.position = filePosition;
blockMap[blockNumber] = entry;
}
} else {
myFilePosition = myFilePosition + header_size + (nBlocks * (sizeof(int32_t) + sizeof(int64_t) + sizeof(int32_t)));
}
delete buffer;
return blockMap;
}
// goes to the specified file pointer in http and finds the raw contact matrixType at specified resolution, calling readMatrixZoomData.
// sets blockbincount and blockcolumncount
map<int32_t, indexEntry> readMatrixHttp(CURL *curl, int64_t myFilePosition, const string &unit, int32_t resolution,
float &mySumCounts, int32_t &myBlockBinCount, int32_t &myBlockColumnCount) {
char *buffer;
int32_t size = sizeof(int32_t) * 3;
buffer = getData(curl, myFilePosition, size);
membuf sbuf(buffer, buffer + size);
istream bufin(&sbuf);
int32_t c1 = readInt32FromFile(bufin);
int32_t c2 = readInt32FromFile(bufin);
int32_t nRes = readInt32FromFile(bufin);
int32_t i = 0;
bool found = false;
myFilePosition = myFilePosition + size;
delete buffer;
map<int32_t, indexEntry> blockMap;
while (i < nRes && !found) {
// myFilePosition gets updated within call
blockMap = readMatrixZoomDataHttp(curl, myFilePosition, unit, resolution, mySumCounts, myBlockBinCount, myBlockColumnCount,
found);
i++;
}
if (!found) {
cerr << "Error finding block data" << endl;
}
return blockMap;
}
// goes to the specified file pointer and finds the raw contact matrixType at specified resolution, calling readMatrixZoomData.
// sets blockbincount and blockcolumncount
map<int32_t, indexEntry> readMatrix(istream &fin, int64_t myFilePosition, const string &unit, int32_t resolution,
float &mySumCounts, int32_t &myBlockBinCount, int32_t &myBlockColumnCount) {
map<int32_t, indexEntry> blockMap;
fin.seekg(myFilePosition, ios::beg);
int32_t c1 = readInt32FromFile(fin);
int32_t c2 = readInt32FromFile(fin);
int32_t nRes = readInt32FromFile(fin);
int32_t i = 0;
bool found = false;
while (i < nRes && !found) {
blockMap = readMatrixZoomData(fin, unit, resolution, mySumCounts, myBlockBinCount, myBlockColumnCount, found);
i++;
}
if (!found) {
cerr << "Error finding block data" << endl;
}
return blockMap;
}
// gets the blocks that need to be read for this slice of the data. needs blockbincount, blockcolumncount, and whether
// or not this is intrachromosomal.
set<int32_t> getBlockNumbersForRegionFromBinPosition(const int64_t *regionIndices, int32_t blockBinCount, int32_t blockColumnCount,
bool intra) {
int32_t col1 = static_cast<int32_t>(regionIndices[0] / blockBinCount);
int32_t col2 = static_cast<int32_t>((regionIndices[1] + 1) / blockBinCount);
int32_t row1 = static_cast<int32_t>(regionIndices[2] / blockBinCount);
int32_t row2 = static_cast<int32_t>((regionIndices[3] + 1) / blockBinCount);
set<int32_t> blocksSet;
// first check the upper triangular matrixType
for (int r = row1; r <= row2; r++) {
for (int c = col1; c <= col2; c++) {
int32_t blockNumber = r * blockColumnCount + c;
blocksSet.insert(blockNumber);
}
}
// check region part that overlaps with lower left triangle but only if intrachromosomal
if (intra) {
for (int r = col1; r <= col2; r++) {
for (int c = row1; c <= row2; c++) {
int32_t blockNumber = r * blockColumnCount + c;
blocksSet.insert(blockNumber);
}
}
}
return blocksSet;
}
set<int32_t> getBlockNumbersForRegionFromBinPositionV9Intra(int64_t *regionIndices, int32_t blockBinCount, int32_t blockColumnCount) {
// regionIndices is binX1 binX2 binY1 binY2
set<int32_t> blocksSet;
int32_t translatedLowerPAD = static_cast<int32_t>((regionIndices[0] + regionIndices[2]) / 2 / blockBinCount);
int32_t translatedHigherPAD = static_cast<int32_t>((regionIndices[1] + regionIndices[3]) / 2 / blockBinCount + 1);
int32_t translatedNearerDepth = static_cast<int32_t>(log2(
1 + abs(regionIndices[0] - regionIndices[3]) / sqrt(2) / blockBinCount));
int32_t translatedFurtherDepth = static_cast<int32_t>(log2(
1 + abs(regionIndices[1] - regionIndices[2]) / sqrt(2) / blockBinCount));
// because code above assume above diagonal; but we could be below diagonal
int32_t nearerDepth = min(translatedNearerDepth, translatedFurtherDepth);
if ((regionIndices[0] > regionIndices[3] && regionIndices[1] < regionIndices[2]) ||
(regionIndices[1] > regionIndices[2] && regionIndices[0] < regionIndices[3])) {
nearerDepth = 0;
}
int32_t furtherDepth = max(translatedNearerDepth, translatedFurtherDepth) + 1; // +1; integer divide rounds down
for (int depth = nearerDepth; depth <= furtherDepth; depth++) {
for (int pad = translatedLowerPAD; pad <= translatedHigherPAD; pad++) {
int32_t blockNumber = depth * blockColumnCount + pad;
blocksSet.insert(blockNumber);
}
}
return blocksSet;
}
void appendRecord(vector<contactRecord> &vector, int32_t index, int32_t binX, int32_t binY, float counts) {
contactRecord record = contactRecord();
record.binX = binX;
record.binY = binY;
record.counts = counts;
vector[index] = record;
}
// this is the meat of reading the data. takes in the block number and returns the set of contact records corresponding to
// that block. the block data is compressed and must be decompressed using the zlib library functions
vector<contactRecord> readBlock(istream &fin, CURL *curl, bool isHttp, indexEntry idx, int32_t version) {
if (idx.size <= 0) {
vector<contactRecord> v;
return v;
}
char *compressedBytes = new char[idx.size];
char *uncompressedBytes = new char[idx.size * 10]; //biggest seen so far is 3
if (isHttp) {
compressedBytes = getData(curl, idx.position, idx.size);
} else {
fin.seekg(idx.position, ios::beg);
fin.read(compressedBytes, idx.size);
}
// Decompress the block
// zlib struct
z_stream infstream;
infstream.zalloc = Z_NULL;
infstream.zfree = Z_NULL;
infstream.opaque = Z_NULL;
infstream.avail_in = static_cast<uInt>(idx.size); // size of input
infstream.next_in = (Bytef *) compressedBytes; // input char array
infstream.avail_out = static_cast<uInt>(idx.size * 10); // size of output
infstream.next_out = (Bytef *) uncompressedBytes; // output char array
// the actual decompression work.
inflateInit(&infstream);
inflate(&infstream, Z_NO_FLUSH);
inflateEnd(&infstream);
int32_t uncompressedSize = static_cast<int32_t>(infstream.total_out);
// create stream from buffer for ease of use
membuf sbuf(uncompressedBytes, uncompressedBytes + uncompressedSize);
istream bufferin(&sbuf);
uint64_t nRecords = static_cast<uint64_t>(readInt32FromFile(bufferin));
vector<contactRecord> v(nRecords);
// different versions have different specific formats
if (version < 7) {
for (int i = 0; i < nRecords; i++) {
int32_t binX = readInt32FromFile(bufferin);
int32_t binY = readInt32FromFile(bufferin);
float counts = readFloatFromFile(bufferin);
appendRecord(v, i, binX, binY, counts);
}
} else {
int32_t binXOffset = readInt32FromFile(bufferin);
int32_t binYOffset = readInt32FromFile(bufferin);
bool useShort = readCharFromFile(bufferin) == 0; // yes this is opposite of usual
bool useShortBinX = true;
bool useShortBinY = true;
if (version > 8) {
useShortBinX = readCharFromFile(bufferin) == 0;
useShortBinY = readCharFromFile(bufferin) == 0;
}
char type = readCharFromFile(bufferin);
int32_t index = 0;
if (type == 1) {
if (useShortBinX && useShortBinY) {
int16_t rowCount = readInt16FromFile(bufferin);
for (int i = 0; i < rowCount; i++) {
int32_t binY = binYOffset + readInt16FromFile(bufferin);
int16_t colCount = readInt16FromFile(bufferin);
for (int j = 0; j < colCount; j++) {
int32_t binX = binXOffset + readInt16FromFile(bufferin);
float counts;
if (useShort) {
counts = readInt16FromFile(bufferin);
} else {
counts = readFloatFromFile(bufferin);
}
appendRecord(v, index++, binX, binY, counts);
}
}
} else if (useShortBinX && !useShortBinY) {
int32_t rowCount = readInt32FromFile(bufferin);
for (int i = 0; i < rowCount; i++) {
int32_t binY = binYOffset + readInt32FromFile(bufferin);
int16_t colCount = readInt16FromFile(bufferin);
for (int j = 0; j < colCount; j++) {
int32_t binX = binXOffset + readInt16FromFile(bufferin);
float counts;
if (useShort) {
counts = readInt16FromFile(bufferin);
} else {
counts = readFloatFromFile(bufferin);
}
appendRecord(v, index++, binX, binY, counts);
}
}
} else if (!useShortBinX && useShortBinY) {
int16_t rowCount = readInt16FromFile(bufferin);
for (int i = 0; i < rowCount; i++) {
int32_t binY = binYOffset + readInt16FromFile(bufferin);
int32_t colCount = readInt32FromFile(bufferin);
for (int j = 0; j < colCount; j++) {
int32_t binX = binXOffset + readInt32FromFile(bufferin);
float counts;
if (useShort) {
counts = readInt16FromFile(bufferin);
} else {
counts = readFloatFromFile(bufferin);
}
appendRecord(v, index++, binX, binY, counts);
}
}
} else {
int32_t rowCount = readInt32FromFile(bufferin);
for (int i = 0; i < rowCount; i++) {
int32_t binY = binYOffset + readInt32FromFile(bufferin);
int32_t colCount = readInt32FromFile(bufferin);
for (int j = 0; j < colCount; j++) {
int32_t binX = binXOffset + readInt32FromFile(bufferin);
float counts;
if (useShort) {
counts = readInt16FromFile(bufferin);
} else {
counts = readFloatFromFile(bufferin);
}
appendRecord(v, index++, binX, binY, counts);
}
}
}
} else if (type == 2) {
int32_t nPts = readInt32FromFile(bufferin);
int16_t w = readInt16FromFile(bufferin);
for (int i = 0; i < nPts; i++) {
//int32_t idx = (p.y - binOffset2) * w + (p.x - binOffset1);
int32_t row = i / w;
int32_t col = i - row * w;
int32_t bin1 = binXOffset + col;
int32_t bin2 = binYOffset + row;
float counts;
if (useShort) {
int16_t c = readInt16FromFile(bufferin);
if (c != -32768) {
appendRecord(v, index++, bin1, bin2, c);
}
} else {
counts = readFloatFromFile(bufferin);
if (!isnan(counts)) {
appendRecord(v, index++, bin1, bin2, counts);
}
}
}
}
}
delete[] compressedBytes;
delete[] uncompressedBytes; // don't forget to delete your heap arrays in C++!
return v;
}
// reads the normalization vector from the file at the specified location
vector<double> readNormalizationVector(istream &bufferin, int32_t version) {
int64_t nValues;
if (version > 8) {
nValues = readInt64FromFile(bufferin);
} else {
nValues = (int64_t) readInt32FromFile(bufferin);
}
uint64_t numValues = static_cast<uint64_t>(nValues);
vector<double> values(numValues);
if (version > 8) {
for (int i = 0; i < nValues; i++) {
values[i] = (double) readFloatFromFile(bufferin);
}
} else {
for (int i = 0; i < nValues; i++) {
values[i] = readDoubleFromFile(bufferin);
}
}
return values;
}
class FileReader {
public:
string prefix = "http"; // HTTP code
ifstream fin;
CURL *curl;
bool isHttp = false;
static CURL *initCURL(const char *url) {
CURL *curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "straw");
}
return curl;
}
explicit FileReader(const string &fname) {
// read header into buffer; 100K should be sufficient
if (std::strncmp(fname.c_str(), prefix.c_str(), prefix.size()) == 0) {
isHttp = true;
curl = initCURL(fname.c_str());
if (!curl) {
cerr << "URL " << fname << " cannot be opened for reading" << endl;
exit(1);
}
} else {
fin.open(fname, fstream::in | fstream::binary);
if (!fin) {
cerr << "File " << fname << " cannot be opened for reading" << endl;
exit(2);
}
}
}
void close(){
if(isHttp){
curl_easy_cleanup(curl);
} else {
fin.close();
}
}
};
class HiCFile {
public:
string prefix = "http"; // HTTP code
bool isHttp = false;
ifstream fin;
CURL *curl;
int64_t master = 0LL;
map<string, chromosome> chromosomeMap;
string genomeID;
int32_t numChromosomes = 0;
int32_t version = 0;
int64_t nviPosition = 0LL;
int64_t nviLength = 0LL;
static int64_t totalFileSize;
static size_t hdf(char *b, size_t size, size_t nitems, void *userdata) {
size_t numbytes = size * nitems;
b[numbytes + 1] = '\0';
string s(b);
int32_t found = static_cast<int32_t>(s.find("Content-Range"));
if (found != string::npos) {
int32_t found2 = static_cast<int32_t>(s.find("/"));
//Content-Range: bytes 0-100000/891471462
if (found2 != string::npos) {
string total = s.substr(found2 + 1);
totalFileSize = stol(total);
}
}
return numbytes;
}
static CURL *initCURL(const char *url) {
CURL *curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, hdf);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "straw");
}
return curl;
}
explicit HiCFile(const string &fname) {
// read header into buffer; 100K should be sufficient
if (std::strncmp(fname.c_str(), prefix.c_str(), prefix.size()) == 0) {
isHttp = true;
char *buffer;
curl = initCURL(fname.c_str());
if (curl) {
buffer = getData(curl, 0, 100000);
} else {
cerr << "URL " << fname << " cannot be opened for reading" << endl;
exit(1);
}
membuf sbuf(buffer, buffer + 100000);
istream bufin(&sbuf);
chromosomeMap = readHeader(bufin, master, genomeID, numChromosomes,
version, nviPosition, nviLength);
delete buffer;
} else {
fin.open(fname, fstream::in | fstream::binary);
if (!fin) {
cerr << "File " << fname << " cannot be opened for reading" << endl;
exit(2);
}
chromosomeMap = readHeader(fin, master, genomeID, numChromosomes,
version, nviPosition, nviLength);
}
}
void close(){
if(isHttp){
curl_easy_cleanup(curl);
} else {
fin.close();
}
}
vector<double> readNormalizationVectorFromFooter(indexEntry cNormEntry) {
char *buffer;
if (isHttp) {
buffer = getData(curl, cNormEntry.position, cNormEntry.size);
} else {
buffer = new char[cNormEntry.size];
fin.seekg(cNormEntry.position, ios::beg);
fin.read(buffer, cNormEntry.size);
}
membuf sbuf3(buffer, buffer + cNormEntry.size);
istream bufferin(&sbuf3);
vector<double> cNorm = readNormalizationVector(bufferin, version);
delete buffer;
return cNorm;
}
};
int64_t HiCFile::totalFileSize = 0LL;
class MatrixZoomData {
public:
indexEntry c1NormEntry, c2NormEntry;
int64_t myFilePos = 0LL;
vector<double> expectedValues;
bool foundFooter = false;
vector<double> c1Norm;
vector<double> c2Norm;
int32_t c1 = 0;
int32_t c2 = 0;
string matrixType;
string norm;
string unit;
int32_t resolution = 0;
int32_t numBins1 = 0;
int32_t numBins2 = 0;
MatrixZoomData(HiCFile *hiCFile, const chromosome &chrom1, const chromosome &chrom2, const string &matrixType,
const string &norm, const string &unit, int32_t resolution) {
int32_t c01 = chrom1.index;
int32_t c02 = chrom2.index;
if (c01 <= c02) { // default is ok
this->c1 = c01;
this->c2 = c02;
this->numBins1 = static_cast<int32_t>(chrom1.length / resolution);
this->numBins2 = static_cast<int32_t>(chrom2.length / resolution);
} else { // flip
this->c1 = c02;
this->c2 = c01;
this->numBins1 = static_cast<int32_t>(chrom2.length / resolution);
this->numBins2 = static_cast<int32_t>(chrom1.length / resolution);
}
this->matrixType = matrixType;
this->norm = norm;
this->unit = unit;
this->resolution = resolution;
if (hiCFile->isHttp) {
char *buffer2;
int64_t bytes_to_read = hiCFile->totalFileSize - hiCFile->master;
buffer2 = getData(hiCFile->curl, hiCFile->master, bytes_to_read);
membuf sbuf2(buffer2, buffer2 + bytes_to_read);
istream bufin2(&sbuf2);
foundFooter = readFooter(bufin2, hiCFile->master, hiCFile->version, c1, c2, matrixType, norm, unit,
resolution,
myFilePos,
c1NormEntry, c2NormEntry, expectedValues);
delete buffer2;
} else {
hiCFile->fin.seekg(hiCFile->master, ios::beg);
foundFooter = readFooter(hiCFile->fin, hiCFile->master, hiCFile->version, c1, c2, matrixType, norm,
unit,
resolution, myFilePos,
c1NormEntry, c2NormEntry, expectedValues);
}
if (!foundFooter) {
return;
}
if (norm != "NONE") {
c1Norm = hiCFile->readNormalizationVectorFromFooter(c1NormEntry);
if (c1 == c2) {
c2Norm = c1Norm;
} else {
c2Norm = hiCFile->readNormalizationVectorFromFooter(c2NormEntry);
}