pybcf 1.2.0__tar.gz → 1.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. {pybcf-1.2.0/src/pybcf.egg-info → pybcf-1.3.0}/PKG-INFO +6 -2
  2. {pybcf-1.2.0 → pybcf-1.3.0}/README.md +5 -1
  3. {pybcf-1.2.0 → pybcf-1.3.0}/setup.py +11 -9
  4. pybcf-1.3.0/src/bcf.cpp +73 -0
  5. pybcf-1.3.0/src/bcf.h +31 -0
  6. pybcf-1.2.0/src/gzstream/gzstream.C → pybcf-1.3.0/src/gzstream.cpp +53 -45
  7. {pybcf-1.2.0/src/gzstream → pybcf-1.3.0/src}/gzstream.h +11 -18
  8. {pybcf-1.2.0 → pybcf-1.3.0}/src/header.cpp +13 -0
  9. {pybcf-1.2.0 → pybcf-1.3.0}/src/header.h +1 -0
  10. pybcf-1.3.0/src/index.cpp +224 -0
  11. pybcf-1.3.0/src/index.h +49 -0
  12. {pybcf-1.2.0 → pybcf-1.3.0}/src/info.h +1 -1
  13. {pybcf-1.2.0 → pybcf-1.3.0}/src/pybcf/reader.cpp +2600 -1964
  14. {pybcf-1.2.0 → pybcf-1.3.0}/src/pybcf/reader.pyx +20 -9
  15. {pybcf-1.2.0 → pybcf-1.3.0/src/pybcf.egg-info}/PKG-INFO +6 -2
  16. {pybcf-1.2.0 → pybcf-1.3.0}/src/pybcf.egg-info/SOURCES.txt +3 -2
  17. {pybcf-1.2.0 → pybcf-1.3.0}/src/sample_data.h +1 -1
  18. {pybcf-1.2.0 → pybcf-1.3.0}/src/types.h +1 -1
  19. {pybcf-1.2.0 → pybcf-1.3.0}/src/variant.h +1 -2
  20. pybcf-1.3.0/test/test_indexed.py +151 -0
  21. pybcf-1.2.0/src/bcf.cpp +0 -36
  22. pybcf-1.2.0/src/bcf.h +0 -25
  23. pybcf-1.2.0/src/index.cpp +0 -92
  24. pybcf-1.2.0/src/index.h +0 -36
  25. {pybcf-1.2.0 → pybcf-1.3.0}/LICENSE.txt +0 -0
  26. {pybcf-1.2.0 → pybcf-1.3.0}/MANIFEST.in +0 -0
  27. {pybcf-1.2.0 → pybcf-1.3.0}/pyproject.toml +0 -0
  28. {pybcf-1.2.0 → pybcf-1.3.0}/setup.cfg +0 -0
  29. {pybcf-1.2.0 → pybcf-1.3.0}/src/info.cpp +0 -0
  30. {pybcf-1.2.0 → pybcf-1.3.0}/src/pybcf/__init__.py +0 -0
  31. {pybcf-1.2.0 → pybcf-1.3.0}/src/pybcf.egg-info/dependency_links.txt +0 -0
  32. {pybcf-1.2.0 → pybcf-1.3.0}/src/pybcf.egg-info/requires.txt +0 -0
  33. {pybcf-1.2.0 → pybcf-1.3.0}/src/pybcf.egg-info/top_level.txt +0 -0
  34. {pybcf-1.2.0 → pybcf-1.3.0}/src/sample_data.cpp +0 -0
  35. {pybcf-1.2.0 → pybcf-1.3.0}/src/variant.cpp +0 -0
  36. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/adler32.c +0 -0
  37. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/adler32_p.h +0 -0
  38. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/arch_functions.h +0 -0
  39. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/chunkset_tpl.h +0 -0
  40. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/compare256_rle.h +0 -0
  41. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/compress.c +0 -0
  42. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/cpu_features.c +0 -0
  43. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/cpu_features.h +0 -0
  44. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/crc32.c +0 -0
  45. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/crc32.h +0 -0
  46. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/crc32_braid_comb.c +0 -0
  47. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/crc32_braid_comb_p.h +0 -0
  48. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/crc32_braid_p.h +0 -0
  49. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/crc32_braid_tbl.h +0 -0
  50. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate.c +0 -0
  51. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate.h +0 -0
  52. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate_fast.c +0 -0
  53. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate_huff.c +0 -0
  54. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate_medium.c +0 -0
  55. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate_p.h +0 -0
  56. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate_quick.c +0 -0
  57. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate_rle.c +0 -0
  58. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate_slow.c +0 -0
  59. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/deflate_stored.c +0 -0
  60. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/fallback_builtins.h +0 -0
  61. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/functable.c +0 -0
  62. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/functable.h +0 -0
  63. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/gzguts.h +0 -0
  64. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/gzlib.c +0 -0
  65. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/gzwrite.c +0 -0
  66. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/infback.c +0 -0
  67. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/inffast_tpl.h +0 -0
  68. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/inffixed_tbl.h +0 -0
  69. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/inflate.c +0 -0
  70. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/inflate.h +0 -0
  71. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/inflate_p.h +0 -0
  72. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/inftrees.c +0 -0
  73. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/inftrees.h +0 -0
  74. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/insert_string.c +0 -0
  75. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/insert_string_roll.c +0 -0
  76. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/insert_string_tpl.h +0 -0
  77. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/match_tpl.h +0 -0
  78. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/trees.c +0 -0
  79. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/trees.h +0 -0
  80. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/trees_emit.h +0 -0
  81. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/trees_tbl.h +0 -0
  82. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/uncompr.c +0 -0
  83. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/zbuild.h +0 -0
  84. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/zendian.h +0 -0
  85. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/zutil.c +0 -0
  86. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/zutil.h +0 -0
  87. {pybcf-1.2.0 → pybcf-1.3.0}/src/zlib-ng/zutil_p.h +0 -0
  88. {pybcf-1.2.0 → pybcf-1.3.0}/test/test_pybcf.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pybcf
3
- Version: 1.2.0
3
+ Version: 1.3.0
4
4
  Summary: Package for loading data from bcf files
5
5
  Home-page: https://github.com/jeremymcrae/pybcf
6
6
  Author: Jeremy McRae
@@ -42,8 +42,12 @@ for var in bcf:
42
42
  # sample data is accessed as numpy arrays via the format keys
43
43
  keys = list(var.samples)
44
44
  genotypes = var.samples['GT'] # as n x 2 numpy array, missing=-1
45
+
46
+ # or fetch from random regions if bcf is indexed
47
+ for var in bcf.fetch('chr1', 10000, 200000):
48
+ print(var.chrom, var.pos)
45
49
  ```
46
50
 
47
51
  ### Limitations
48
- - can't fetch variants from random regions yet
52
+ - doesn't work with uncompressed BCFs
49
53
  - extracting info fields is a little slow
@@ -26,8 +26,12 @@ for var in bcf:
26
26
  # sample data is accessed as numpy arrays via the format keys
27
27
  keys = list(var.samples)
28
28
  genotypes = var.samples['GT'] # as n x 2 numpy array, missing=-1
29
+
30
+ # or fetch from random regions if bcf is indexed
31
+ for var in bcf.fetch('chr1', 10000, 200000):
32
+ print(var.chrom, var.pos)
29
33
  ```
30
34
 
31
35
  ### Limitations
32
- - can't fetch variants from random regions yet
36
+ - doesn't work with uncompressed BCFs
33
37
  - extracting info fields is a little slow
@@ -63,14 +63,15 @@ def get_gzstream_path():
63
63
  cython on windows didn't like the .C extension for gzstream. This just
64
64
  renames the file (on windows only), and returns the relative path.
65
65
  '''
66
- gzstream_path = 'src/gzstream/gzstream.C'
67
- if sys.platform == 'win32':
68
- gzstream_win_path = 'src/gzstream/gzstream.cpp'
69
- try:
70
- os.rename(gzstream_path, gzstream_win_path)
71
- except FileNotFoundError:
72
- pass # avoid error on github actions
73
- gzstream_path = gzstream_win_path
66
+ # gzstream_path = 'src/gzstream/gzstream.C'
67
+ gzstream_path = 'src/gzstream.cpp'
68
+ # if sys.platform == 'win32':
69
+ # gzstream_win_path = 'src/gzstream/gzstream.cpp'
70
+ # try:
71
+ # os.rename(gzstream_path, gzstream_win_path)
72
+ # except FileNotFoundError:
73
+ # pass # avoid error on github actions
74
+ # gzstream_path = gzstream_win_path
74
75
  return gzstream_path
75
76
 
76
77
  def scrub_gzstream():
@@ -116,6 +117,7 @@ ext = cythonize([
116
117
  sources=['src/pybcf/reader.pyx',
117
118
  get_gzstream_path(),
118
119
  'src/bcf.cpp',
120
+ 'src/index.cpp',
119
121
  'src/header.cpp',
120
122
  'src/info.cpp',
121
123
  'src/sample_data.cpp',
@@ -129,7 +131,7 @@ setup(name='pybcf',
129
131
  description='Package for loading data from bcf files',
130
132
  long_description=io.open('README.md', encoding='utf-8').read(),
131
133
  long_description_content_type='text/markdown',
132
- version='1.2.0',
134
+ version='1.3.0',
133
135
  author='Jeremy McRae',
134
136
  author_email='jmcrae@illumina.com',
135
137
  license="MIT",
@@ -0,0 +1,73 @@
1
+
2
+ #include <algorithm>
3
+ #include <iterator>
4
+ #include <stdexcept>
5
+
6
+ #include "bcf.h"
7
+
8
+ namespace bcf {
9
+
10
+
11
+ BCF::BCF(std::string path, std::string index_path) {
12
+ infile.open(path.c_str());
13
+ if (infile.fail()) {
14
+ throw std::invalid_argument("cannot open file at " + path);
15
+ }
16
+
17
+ // check the file header indicates this is a bcf file
18
+ char magic[5];
19
+ infile.read(&magic[0], 5);
20
+ if (magic[0] != 'B' || magic[1] != 'C' || magic[2] != 'F' || magic[3] != 2 || magic[4] != 2) {
21
+ throw std::invalid_argument("doesn't look like a BCF2.2 file");
22
+ }
23
+
24
+ std::uint32_t len;
25
+ infile.read(reinterpret_cast<char *>(&len), sizeof(len));
26
+ std::string text(len, ' ');
27
+ infile.read(reinterpret_cast<char *>(&text[0]), len);
28
+ header = Header(text);
29
+
30
+ // try opening the index file
31
+ if (index_path.size() == 0) {
32
+ index_path = path + ".csi";
33
+ }
34
+ try {
35
+ idxfile = IndexFile(index_path);
36
+ } catch (const std::invalid_argument& e) {}
37
+
38
+ }
39
+
40
+ Variant BCF::nextvar() {
41
+ Variant var = Variant(infile, header);
42
+ if ((query_chrom.size() != 0) && (var.chrom != query_chrom)) {
43
+ throw std::out_of_range("variant not on required chrom");
44
+ }
45
+
46
+ while (var.pos < query_start) {
47
+ var = Variant(infile, header);
48
+ if ((query_chrom.size() != 0) && (var.chrom != query_chrom)) {
49
+ throw std::out_of_range("variant not on required chrom");
50
+ }
51
+ }
52
+ if (var.pos > query_end) {
53
+ throw std::out_of_range("variant out of bounds");
54
+ }
55
+ return var;
56
+ }
57
+
58
+ void BCF::set_region(std::string chrom, std::uint32_t start, std::uint32_t end) {
59
+ if (!idxfile.has_index) {
60
+ throw std::invalid_argument("cannot fetch without an index file");
61
+ }
62
+
63
+ std::uint32_t contig_id = header.get_contig_id(chrom);
64
+
65
+ query_chrom = chrom;
66
+ query_start = start;
67
+ query_end = end;
68
+
69
+ Offsets offset = idxfile.query(contig_id, start, end);
70
+ infile.seek(offset);
71
+ }
72
+
73
+ }
pybcf-1.3.0/src/bcf.h ADDED
@@ -0,0 +1,31 @@
1
+ #ifndef BCF_BCF_H
2
+ #define BCF_BCF_H
3
+
4
+ #include <cstdint>
5
+ #include <string>
6
+ #include <vector>
7
+
8
+ #include "gzstream.h"
9
+
10
+ #include "header.h"
11
+ #include "variant.h"
12
+ #include "index.h"
13
+
14
+ namespace bcf {
15
+
16
+ class BCF {
17
+ igzstream infile;
18
+ IndexFile idxfile;
19
+ std::string query_chrom="";
20
+ std::uint32_t query_start=0;
21
+ std::uint32_t query_end=1 << 31;
22
+ public:
23
+ BCF(std::string path, std::string index_path="");
24
+ Variant nextvar();
25
+ void set_region(std::string chrom, std::uint32_t start=0, std::uint32_t end=1 << 31);
26
+ Header header;
27
+ };
28
+
29
+ }
30
+
31
+ #endif
@@ -29,6 +29,9 @@
29
29
  #include "gzstream.h"
30
30
  #include <iostream>
31
31
  #include <string.h> // for memcpy
32
+ #include <stdexcept>
33
+ #include <fcntl.h>
34
+ #include <unistd.h>
32
35
 
33
36
  #ifdef GZSTREAM_NAMESPACE
34
37
  namespace GZSTREAM_NAMESPACE {
@@ -42,6 +45,14 @@ namespace GZSTREAM_NAMESPACE {
42
45
  // class gzstreambuf:
43
46
  // --------------------------------------
44
47
 
48
+ void get_fmode( char* fmode, int open_mode) {
49
+ char* fmodeptr = fmode;
50
+ if (open_mode & std::ios::in)
51
+ *fmodeptr++ = 'r';
52
+ *fmodeptr++ = 'b';
53
+ *fmodeptr = '\0';
54
+ }
55
+
45
56
  gzstreambuf* gzstreambuf::open( const char* name, int open_mode) {
46
57
  if ( is_open())
47
58
  return (gzstreambuf*)0;
@@ -50,15 +61,10 @@ gzstreambuf* gzstreambuf::open( const char* name, int open_mode) {
50
61
  if ((mode & std::ios::ate) || (mode & std::ios::app)
51
62
  || ((mode & std::ios::in) && (mode & std::ios::out)))
52
63
  return (gzstreambuf*)0;
53
- char fmode[10];
54
- char* fmodeptr = fmode;
55
- if ( mode & std::ios::in)
56
- *fmodeptr++ = 'r';
57
- else if ( mode & std::ios::out)
58
- *fmodeptr++ = 'w';
59
- *fmodeptr++ = 'b';
60
- *fmodeptr = '\0';
61
- file = gzopen( name, fmode);
64
+ char fmode[10];
65
+ get_fmode(fmode, mode);
66
+ fd = ::open(name, open_mode);
67
+ file = gzdopen( fd, fmode);
62
68
  if (file == 0)
63
69
  return (gzstreambuf*)0;
64
70
  opened = 1;
@@ -75,6 +81,38 @@ gzstreambuf * gzstreambuf::close() {
75
81
  return (gzstreambuf*)0;
76
82
  }
77
83
 
84
+ void gzstreambuf::seek(bcf::Offsets offset) {
85
+ // reset the input buffer
86
+ setp( buffer, buffer + (bufferSize-1));
87
+ setg( buffer + 4, // beginning of putback area
88
+ buffer + 4, // read position
89
+ buffer + 4); // end position
90
+
91
+ // We must close the previous gzFile, otherwise we leak memory on each seek.
92
+ // But when we close the gzFile, this also closes the file descriptor, so we
93
+ // duplicate the file descriptor first.
94
+ int new_fd = dup(fd);
95
+
96
+ // seek using the file descriptor to an offset in the compressed file
97
+ ::lseek(new_fd, offset.c_offset, SEEK_SET);
98
+
99
+ // open a new gzfile object using the file descriptor (at new offset)
100
+ char fmode[10];
101
+ get_fmode(fmode, mode);
102
+ file = gzdopen(new_fd, fmode);
103
+ fd = new_fd;
104
+
105
+ if (file == 0) {
106
+ throw std::invalid_argument("cannot seek within this gzfile");
107
+ }
108
+
109
+ // read through to the correct offset in the uncompressed data. The
110
+ // uncompressed offset must be less than 2 ** 16, since that is the max
111
+ // BGZF chunk size (uncompressed or compressed).
112
+ char tmp[65536];
113
+ gzread(file, tmp, offset.u_offset);
114
+ }
115
+
78
116
  int gzstreambuf::underflow() { // used for input buffer only
79
117
  if ( gptr() && ( gptr() < egptr()))
80
118
  return * reinterpret_cast<unsigned char *>( gptr());
@@ -100,39 +138,6 @@ int gzstreambuf::underflow() { // used for input buffer only
100
138
  return * reinterpret_cast<unsigned char *>( gptr());
101
139
  }
102
140
 
103
- int gzstreambuf::flush_buffer() {
104
- // Separate the writing of the buffer from overflow() and
105
- // sync() operation.
106
- int w = pptr() - pbase();
107
- if ( gzwrite( file, pbase(), w) != w)
108
- return EOF;
109
- pbump( -w);
110
- return w;
111
- }
112
-
113
- int gzstreambuf::overflow( int c) { // used for output buffer only
114
- if ( ! ( mode & std::ios::out) || ! opened)
115
- return EOF;
116
- if (c != EOF) {
117
- *pptr() = c;
118
- pbump(1);
119
- }
120
- if ( flush_buffer() == EOF)
121
- return EOF;
122
- return c;
123
- }
124
-
125
- int gzstreambuf::sync() {
126
- // Changed to use flush_buffer() instead of overflow( EOF)
127
- // which caused improper behavior with std::endl and flush(),
128
- // bug reported by Vincent Ricard.
129
- if ( pptr() && pptr() > pbase()) {
130
- if ( flush_buffer() == EOF)
131
- return -1;
132
- }
133
- return 0;
134
- }
135
-
136
141
  // --------------------------------------
137
142
  // class gzstreambase:
138
143
  // --------------------------------------
@@ -147,14 +152,17 @@ gzstreambase::~gzstreambase() {
147
152
  }
148
153
 
149
154
  void gzstreambase::open( const char* name, int open_mode) {
150
- if ( ! buf.open( name, open_mode))
155
+ if ( ! buf.open( name, open_mode)) {
151
156
  clear( rdstate() | std::ios::badbit);
157
+ }
152
158
  }
153
159
 
154
160
  void gzstreambase::close() {
155
- if ( buf.is_open())
156
- if ( ! buf.close())
161
+ if ( buf.is_open()) {
162
+ if ( ! buf.close()) {
157
163
  clear( rdstate() | std::ios::badbit);
164
+ }
165
+ }
158
166
  }
159
167
 
160
168
  #ifdef GZSTREAM_NAMESPACE
@@ -31,9 +31,12 @@
31
31
 
32
32
  // standard C++ with new header file names and std:: namespace
33
33
  #include <iostream>
34
+ #include <string>
34
35
  #include <fstream>
35
36
  #include "zlib.h"
36
37
 
38
+ #include "index.h"
39
+
37
40
  #ifdef GZSTREAM_NAMESPACE
38
41
  namespace GZSTREAM_NAMESPACE {
39
42
  #endif
@@ -46,29 +49,26 @@ class gzstreambuf : public std::streambuf {
46
49
  private:
47
50
  static const int bufferSize = 47+256; // size of data buff
48
51
  // totals 512 bytes under g++ for igzstream at the end.
49
-
52
+
50
53
  gzFile file; // file handle for compressed file
51
54
  char buffer[bufferSize]; // data buffer
52
55
  char opened; // open/close state of stream
53
56
  int mode; // I/O mode
54
-
55
- int flush_buffer();
57
+ int fd=-1;
56
58
  public:
57
59
  gzstreambuf() : opened(0) {
58
60
  setp( buffer, buffer + (bufferSize-1));
59
61
  setg( buffer + 4, // beginning of putback area
60
62
  buffer + 4, // read position
61
- buffer + 4); // end position
62
- // ASSERT: both input & output capabilities will not be used together
63
+ buffer + 4); // end position
63
64
  }
64
65
  int is_open() { return opened; }
65
66
  gzstreambuf* open( const char* name, int open_mode);
66
67
  gzstreambuf* close();
68
+ void seek(bcf::Offsets offset);
67
69
  ~gzstreambuf() { close(); }
68
70
 
69
- virtual int overflow( int c = EOF);
70
71
  virtual int underflow();
71
- virtual int sync();
72
72
  };
73
73
 
74
74
  class gzstreambase : virtual public std::ios {
@@ -80,6 +80,10 @@ public:
80
80
  ~gzstreambase();
81
81
  void open( const char* name, int open_mode);
82
82
  void close();
83
+ void seek(bcf::Offsets offset) {
84
+ clear();
85
+ buf.seek(offset);
86
+ };
83
87
  gzstreambuf* rdbuf() { return &buf; }
84
88
  };
85
89
 
@@ -100,17 +104,6 @@ public:
100
104
  }
101
105
  };
102
106
 
103
- class ogzstream : public gzstreambase, public std::ostream {
104
- public:
105
- ogzstream() : std::ostream( &buf) {}
106
- ogzstream( const char* name, int mode = std::ios::out)
107
- : gzstreambase( name, mode), std::ostream( &buf) {}
108
- gzstreambuf* rdbuf() { return gzstreambase::rdbuf(); }
109
- void open( const char* name, int open_mode = std::ios::out) {
110
- gzstreambase::open( name, open_mode);
111
- }
112
- };
113
-
114
107
  #ifdef GZSTREAM_NAMESPACE
115
108
  } // namespace GZSTREAM_NAMESPACE
116
109
  #endif
@@ -181,4 +181,17 @@ std::vector<std::string> Header::get_formats() {
181
181
  return vals;
182
182
  }
183
183
 
184
+ /// @brief find the numeric contig ID for a chromosome/contig name
185
+ /// @param contig chromosome/contig name to find
186
+ /// @return
187
+ std::uint32_t Header::get_contig_id(std::string contig) {
188
+ for (auto & x : contigs) {
189
+ if (x.second.id == contig) {
190
+ return x.first;
191
+ }
192
+ }
193
+
194
+ throw std::invalid_argument(contig + " is not in this BCF");
195
+ }
196
+
184
197
  }
@@ -48,6 +48,7 @@ public:
48
48
  std::vector<std::string> get_info();
49
49
  std::vector<std::string> get_filters();
50
50
  std::vector<std::string> get_formats();
51
+ std::uint32_t get_contig_id(std::string contig);
51
52
  };
52
53
 
53
54
  }
@@ -0,0 +1,224 @@
1
+
2
+ #include <algorithm>
3
+ #include <fstream>
4
+ #include <stdexcept>
5
+ #include <unordered_map>
6
+
7
+ #include "gzstream.h"
8
+
9
+ #include "index.h"
10
+
11
+ namespace bcf {
12
+
13
+
14
+ Offsets parse_virtual_offset(std::uint64_t v_offset) {
15
+ std::uint64_t u_offset = v_offset & 0x000000000000ffff;
16
+ std::uint64_t c_offset = v_offset >> 16;
17
+ return { u_offset, c_offset};
18
+ }
19
+
20
+ /// @brief load file according to https://samtools.github.io/hts-specs/CSIv1.pdf
21
+ /// @param path path to CSI index file
22
+ IndexFile::IndexFile(std::string path) {
23
+ igzstream infile(path.c_str());
24
+ if (infile.fail()) {
25
+ throw std::invalid_argument("cannot open index file at " + path);
26
+ }
27
+
28
+ // check the file header indicates this is a bcf file
29
+ char magic[4];
30
+ infile.read(&magic[0], 4);
31
+ if (magic[0] != 'C' || magic[1] != 'S' || magic[2] != 'I' || magic[3] != 1) {
32
+ throw std::invalid_argument("doesn't look like a CSI file");
33
+ }
34
+
35
+ infile.read(reinterpret_cast<char *>(&min_shift), sizeof(min_shift));
36
+ infile.read(reinterpret_cast<char *>(&depth), sizeof(depth));
37
+ infile.read(reinterpret_cast<char *>(&l_aux), sizeof(l_aux));
38
+ infile.read(reinterpret_cast<char *>(&aux[0]), l_aux);
39
+ infile.read(reinterpret_cast<char *>(&n_ref), sizeof(n_ref));
40
+
41
+ std::uint32_t n_bins, bin_idx;
42
+ std::uint64_t v_offset;
43
+ std::int32_t n_chunks;
44
+ Offsets bin_offsets, chunk_begin, chunk_end;
45
+ for (std::uint32_t i=0; i< n_ref; i++) {
46
+ std::unordered_map<std::uint32_t, Bin> bins;
47
+ infile.read(reinterpret_cast<char *>(&n_bins), sizeof(n_bins));
48
+
49
+ for (std::uint32_t j=0; j<n_bins; j++) {
50
+ infile.read(reinterpret_cast<char *>(&bin_idx), sizeof(bin_idx));
51
+ infile.read(reinterpret_cast<char *>(&v_offset), sizeof(v_offset));
52
+ infile.read(reinterpret_cast<char *>(&n_chunks), sizeof(n_chunks));
53
+
54
+ bin_offsets = parse_virtual_offset(v_offset);
55
+ std::vector<Chunk> chunks;
56
+ for (std::uint32_t k=0; k<n_chunks; k++) {
57
+ infile.read(reinterpret_cast<char *>(&v_offset), sizeof(v_offset));
58
+ chunk_begin = parse_virtual_offset(v_offset);
59
+ infile.read(reinterpret_cast<char *>(&v_offset), sizeof(v_offset));
60
+ chunk_end = parse_virtual_offset(v_offset);
61
+ chunks.push_back({chunk_begin, chunk_end});
62
+ }
63
+ bins[bin_idx] = {bin_offsets, chunks};
64
+ }
65
+ indices.push_back(bins);
66
+ }
67
+ has_index = true;
68
+ }
69
+
70
+ /// calculate bin given an alignment covering [beg,end) (zero-based, half-close-half-open)
71
+ int IndexFile::reg2bin(std::int64_t beg, std::int64_t end) {
72
+ int l, s = min_shift, t = ((1 << depth * 3) - 1) / 7;
73
+ for (--end, l = depth; l > 0; --l, s += 3, t -= 1 << l * 3) {
74
+ if (beg >> s == end >> s) {
75
+ return t + (beg >> s);
76
+ }
77
+ }
78
+ return 0;
79
+ }
80
+
81
+ /// @brief calculate the list of bins that may overlap with region [beg,end) (zero-based).
82
+ ///
83
+ /// This code is from https://samtools.github.io/hts-specs/CSIv1.pdf, but adapted
84
+ /// for being inside a class.
85
+ ///
86
+ /// @param beg start position of region
87
+ /// @param end end position of region
88
+ /// @return currently integer, but this should be an iterator instead
89
+ std::vector<std::uint32_t> IndexFile::reg2bins(std::int64_t beg, std::int64_t end) {
90
+ int max_bins = bin_limit();
91
+
92
+ std::vector<std::uint32_t> bins;
93
+ int l, t, n, s = min_shift + depth * 3;
94
+ for (--end, l = n = t = 0; l <= depth; s -= 3, t += 1 << l * 3, ++l) {
95
+ int b = t + (beg >> s), e = t + (end >> s), i;
96
+ for (i = b; i <= e; ++i) {
97
+ // I should use the vector of bins for a contig (chromosome).
98
+ // Maybe an iterator of bins/chunks for the relevant region?
99
+ bins.push_back(i);
100
+ }
101
+ }
102
+ return bins;
103
+ }
104
+
105
+ /* calculate maximum bin number -- valid bin numbers range within [0,bin_limit) */
106
+ int IndexFile::bin_limit() {
107
+ return ((1 << (depth + 1) * 3) - 1) / 7;
108
+ }
109
+
110
+ /// @brief find the depth for a bin
111
+ ///
112
+ /// We need to know the depth of a bin in order to figure out how wide the bin
113
+ /// is, and its start and end. The width can be found via get_width().
114
+ ///
115
+ /// @param bin_idx bin index
116
+ /// @return depth of the bin
117
+ std::uint32_t IndexFile::get_bin_depth(std::uint32_t bin_idx) {
118
+ std::uint32_t factor = 8;
119
+ std::uint32_t start = 0;
120
+ std::uint32_t end = 0;
121
+
122
+ std::uint32_t bin_depth = depth;
123
+ while (bin_depth >= 0) {
124
+ if ((bin_idx >= start) && (bin_idx <= end)) {
125
+ return bin_depth;
126
+ }
127
+ bin_depth -= 1;
128
+ start = end + 1;
129
+ end = start * factor;
130
+ }
131
+
132
+ throw std::invalid_argument("couldn't get depth for bin: " + std::to_string(bin_idx));
133
+ }
134
+
135
+ /// @brief find the offset of a the bin relative to the first at the same depth
136
+ /// @param bin_idx bin index
137
+ /// @return
138
+ std::uint32_t IndexFile::get_bin_offset(std::uint32_t bin_idx) {
139
+ std::uint32_t factor = 8;
140
+ std::uint32_t start = 0;
141
+ std::uint32_t end = 0;
142
+
143
+ std::uint32_t bin_depth = depth;
144
+ while (bin_depth >= 0) {
145
+ if ((bin_idx >= start) && (bin_idx <= end)) {
146
+ return bin_idx - start;
147
+ }
148
+ bin_depth -= 1;
149
+ start = end + 1;
150
+ end = start * factor;
151
+ }
152
+
153
+ throw std::invalid_argument("couldn't get offset for bin: " + std::to_string(bin_idx));
154
+ }
155
+
156
+ /// @brief find the actual width of a bin
157
+ /// @param depth index depth for a bin
158
+ /// @param min_shift minimum bit shift (typically 14)
159
+ std::uint32_t get_width(std::int32_t depth, std::int32_t min_shift) {
160
+ return 1 << (min_shift + (depth * 3));
161
+ }
162
+
163
+ /// @brief find the file offsets for the first bin to overlap a given chrom region
164
+ /// @param contig_id integer for indexing into the indices vector
165
+ /// @param beg start position of region
166
+ /// @param end end position of region
167
+ /// @return file offsets for the bin as struct with u_offset and c_offset members.
168
+ Offsets IndexFile::query(std::uint32_t contig_id, std::int64_t beg, std::int64_t end) {
169
+ // find the bins which could overlap a position
170
+ auto bins = reg2bins(beg, end);
171
+
172
+ // cull bins which do not exist in the indexfile, and find the bin with the
173
+ // closest start to the position, preferrably immediately upstream of the begin
174
+ // position, but allow using the first downstream, if upstream bins do not exist
175
+ std::uint32_t bin_depth, bin_width, bin_start, delta;
176
+ std::uint32_t left_delta = 1 << (min_shift + 3 * depth);
177
+ std::uint32_t right_delta = 1 << (min_shift + 3 * depth);
178
+ std::int32_t left_bin = -1;
179
+ std::int32_t right_bin = -1;
180
+ for (auto & bin_idx: bins) {
181
+ if (indices[contig_id].count(bin_idx) == 0) {
182
+ continue;
183
+ }
184
+
185
+ bin_depth = get_bin_depth(bin_idx);
186
+ bin_width = get_width(bin_depth, min_shift);
187
+ bin_start = get_bin_offset(bin_idx) * bin_width;
188
+ delta = std::abs(bin_start - beg);
189
+
190
+ // find the bin that starts closest to the begin position
191
+ if (bin_start < beg) {
192
+ if (delta < left_delta) {
193
+ left_bin = bin_idx;
194
+ left_delta = delta;
195
+ };
196
+ } else {
197
+ if (delta < right_delta) {
198
+ right_bin = bin_idx;
199
+ right_delta = delta;
200
+ };
201
+ }
202
+ }
203
+
204
+ if ((left_bin < 0) && (right_bin < 0)) {
205
+ throw std::out_of_range("cannot find bin for: " + std::to_string(beg) + "-" + std::to_string(end));
206
+ }
207
+
208
+ if (left_bin >= 0) {
209
+ return indices[contig_id][left_bin].offset;
210
+ } else {
211
+ return indices[contig_id][right_bin].offset;
212
+ }
213
+ }
214
+
215
+ }
216
+
217
+ // int main() {
218
+ // bcf::IndexFile indexfile = bcf::IndexFile("/users/jmcrae/apps/pybcf/chr5.110000001-115000000.bcf.csi");
219
+ // std::cout << "bin: " << indexfile.reg2bin(111000000, 112000000) << std::endl;
220
+ // indexfile.query(4, 111000000);
221
+ // return 0;
222
+ // }
223
+
224
+ // g++ -stdlib=libc++ -std=c++11 -lz index.cpp gzstream.cpp; ./a.out