pybcf 0.99.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.
@@ -0,0 +1,19 @@
1
+ Copyright 2024 Illumina Inc.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,8 @@
1
+ # pybcf code
2
+ include MANIFEST.in
3
+ include pyproject.toml
4
+ include src/bcf/*.cpp
5
+ include src/bcf/*.py
6
+ include src/bcf/*.pyx
7
+ include src/*.h
8
+ include src/*.cpp
pybcf-0.99.0/PKG-INFO ADDED
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.1
2
+ Name: pybcf
3
+ Version: 0.99.0
4
+ Summary: Package for loading data from bcf files
5
+ Home-page: https://github.com/jeremymcrae/pybcf
6
+ Author: Jeremy McRae
7
+ Author-email: jmcrae@illumina.com
8
+ License: MIT
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE.txt
13
+ Requires-Dist: numpy
14
+ Provides-Extra: test
15
+ Requires-Dist: pysam; extra == "test"
16
+
17
+
18
+ ### pybcf
19
+
20
+ This is a package for reading BCF files (binary call format). Similar to pysam/cyvcf2, but limited to reading from BCF files only, and oriented around getting genotype data into numpy arrays quickly.
21
+
22
+ '''py
23
+ from pybcf import BcfReader
24
+
25
+ bcf = BcfReader(bcf_path)
26
+
27
+ for var in bcf:
28
+ # the usual attributes are available e.g.
29
+ # var.chrom, var.pos, var.ref, var.alts, var.info['AF']
30
+
31
+ # get genotypes as numpy array
32
+ genotypes = var.samples['GT'] # as numpy array, missing=-1
33
+ '''
34
+
35
+ ### Limitations
36
+ - can't fetch variants from random regions yet
37
+ - not extensively tested yet
38
+ - extracting info fields is slow at the moment
pybcf-0.99.0/README.md ADDED
@@ -0,0 +1,22 @@
1
+
2
+ ### pybcf
3
+
4
+ This is a package for reading BCF files (binary call format). Similar to pysam/cyvcf2, but limited to reading from BCF files only, and oriented around getting genotype data into numpy arrays quickly.
5
+
6
+ '''py
7
+ from pybcf import BcfReader
8
+
9
+ bcf = BcfReader(bcf_path)
10
+
11
+ for var in bcf:
12
+ # the usual attributes are available e.g.
13
+ # var.chrom, var.pos, var.ref, var.alts, var.info['AF']
14
+
15
+ # get genotypes as numpy array
16
+ genotypes = var.samples['GT'] # as numpy array, missing=-1
17
+ '''
18
+
19
+ ### Limitations
20
+ - can't fetch variants from random regions yet
21
+ - not extensively tested yet
22
+ - extracting info fields is slow at the moment
@@ -0,0 +1,2 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 40.6.0", "cython", "wheel"]
pybcf-0.99.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
pybcf-0.99.0/setup.py ADDED
@@ -0,0 +1,125 @@
1
+
2
+ import glob
3
+ import io
4
+ from setuptools import setup
5
+ import sys
6
+ import os
7
+
8
+ from distutils.core import Extension
9
+ from distutils.ccompiler import new_compiler
10
+ from Cython.Build import cythonize
11
+
12
+ EXTRA_COMPILE_ARGS = ['-std=c++11', '-I/usr/include']
13
+ EXTRA_LINK_ARGS = []
14
+ if sys.platform == "darwin":
15
+ EXTRA_COMPILE_ARGS += [
16
+ "-stdlib=libc++",
17
+ "-I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1",
18
+ "-I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include",
19
+ ]
20
+ EXTRA_LINK_ARGS += [
21
+ "-L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib",
22
+ ]
23
+
24
+ def flatten(*lists):
25
+ return [str(x) for sublist in lists for x in sublist]
26
+
27
+ def build_zlib():
28
+ ''' compile zlib code to object files for linking with bgen on windows
29
+
30
+ Returns:
31
+ list of paths to compiled object code
32
+ '''
33
+ include_dirs = ['src/zlib/']
34
+ sources = list(glob.glob('src/zlib/*.c'))
35
+ extra_compile_args = ['/O2']
36
+
37
+ cc = new_compiler()
38
+ return cc.compile(sources, include_dirs=include_dirs,
39
+ extra_preargs=extra_compile_args)
40
+
41
+ def get_gzstream_path():
42
+ ''' workaround for building gzstream on windows
43
+
44
+ cython on windows didn't like the .C extension for gzstream. This just
45
+ renames the file (on windows only), and returns the relative path.
46
+ '''
47
+ gzstream_path = 'src/gzstream/gzstream.C'
48
+ if sys.platform == 'win32':
49
+ gzstream_win_path = 'src/gzstream/gzstream.cpp'
50
+ try:
51
+ os.rename(gzstream_path, gzstream_win_path)
52
+ except FileNotFoundError:
53
+ pass # avoid error on github actions
54
+ gzstream_path = gzstream_win_path
55
+ return gzstream_path
56
+
57
+ def scrub_gzstream():
58
+ ''' workaround for compilation error on macos
59
+
60
+ compiling gzstream requires the corresponding gzstream.h file, but if we
61
+ include the gzstream directory in the include dirs, then clang complains
62
+ about the version file in the gzstream folder. If we remove the gzstream
63
+ directory from the include dirs, then clang complains about the missing
64
+ gzstream.h. This is because gzstream.C identifies it's header file with
65
+ angle brackets. Replacing the angle brackets in that line seems to work.
66
+ '''
67
+ with open(get_gzstream_path(), 'rt') as handle:
68
+ lines = handle.readlines()
69
+
70
+ with open(get_gzstream_path(), 'wt') as handle:
71
+ for line in lines:
72
+ if line == '#include <gzstream.h>\n':
73
+ line = '#include "gzstream.h"\n'
74
+ handle.write(line)
75
+
76
+ if sys.platform == 'win32':
77
+ zlib, libs = build_zlib(), []
78
+ else:
79
+ zlib, libs = [], ['z']
80
+
81
+ scrub_gzstream()
82
+
83
+ ext = cythonize([
84
+ Extension('pybcf.reader',
85
+ extra_compile_args=EXTRA_COMPILE_ARGS,
86
+ extra_link_args=EXTRA_LINK_ARGS,
87
+ sources=['src/pybcf/reader.pyx',
88
+ get_gzstream_path(),
89
+ 'src/bcf.cpp',
90
+ 'src/header.cpp',
91
+ 'src/info.cpp',
92
+ 'src/sample_data.cpp',
93
+ 'src/variant.cpp'],
94
+ extra_objects=zlib,
95
+ include_dirs=['src', 'src/zlib'],
96
+ libraries=libs,
97
+ language='c++'),
98
+ ])
99
+
100
+ setup(name='pybcf',
101
+ description='Package for loading data from bcf files',
102
+ long_description=io.open('README.md', encoding='utf-8').read(),
103
+ long_description_content_type='text/markdown',
104
+ version='0.99.0',
105
+ author='Jeremy McRae',
106
+ author_email='jmcrae@illumina.com',
107
+ license="MIT",
108
+ url='https://github.com/jeremymcrae/pybcf',
109
+ packages=['pybcf'],
110
+ package_dir={'': 'src'},
111
+ install_requires=[
112
+ 'numpy',
113
+ ],
114
+ extras_require={
115
+ 'test': [
116
+ 'pysam',
117
+ ],
118
+ },
119
+ classifiers=[
120
+ 'Development Status :: 4 - Beta',
121
+ 'Topic :: Scientific/Engineering :: Bio-Informatics',
122
+ ],
123
+ ext_modules=ext,
124
+ test_loader='unittest:TestLoader',
125
+ )
@@ -0,0 +1,36 @@
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) {
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
+
31
+ Variant BCF::nextvar() {
32
+ return Variant(infile, header);
33
+ }
34
+
35
+
36
+ }
pybcf-0.99.0/src/bcf.h ADDED
@@ -0,0 +1,25 @@
1
+ #ifndef BCF_BCF_H
2
+ #define BCF_BCF_H
3
+
4
+ #include <cstdint>
5
+ #include <string>
6
+ #include <vector>
7
+
8
+ #include "gzstream/gzstream.h"
9
+
10
+ #include "header.h"
11
+ #include "variant.h"
12
+
13
+ namespace bcf {
14
+
15
+ class BCF {
16
+ igzstream infile;
17
+ public:
18
+ BCF(std::string path);
19
+ Variant nextvar();
20
+ Header header;
21
+ };
22
+
23
+ }
24
+
25
+ #endif
@@ -0,0 +1,165 @@
1
+ // ============================================================================
2
+ // gzstream, C++ iostream classes wrapping the zlib compression library.
3
+ // Copyright (C) 2001 Deepak Bandyopadhyay, Lutz Kettner
4
+ //
5
+ // This library is free software; you can redistribute it and/or
6
+ // modify it under the terms of the GNU Lesser General Public
7
+ // License as published by the Free Software Foundation; either
8
+ // version 2.1 of the License, or (at your option) any later version.
9
+ //
10
+ // This library is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
+ // Lesser General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Lesser General Public
16
+ // License along with this library; if not, write to the Free Software
17
+ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
+ // ============================================================================
19
+ //
20
+ // File : gzstream.C
21
+ // Revision : $Revision: 1.7 $
22
+ // Revision_date : $Date: 2003/01/08 14:41:27 $
23
+ // Author(s) : Deepak Bandyopadhyay, Lutz Kettner
24
+ //
25
+ // Standard streambuf implementation following Nicolai Josuttis, "The
26
+ // Standard C++ Library".
27
+ // ============================================================================
28
+
29
+ #include "gzstream.h"
30
+ #include <iostream>
31
+ #include <string.h> // for memcpy
32
+
33
+ #ifdef GZSTREAM_NAMESPACE
34
+ namespace GZSTREAM_NAMESPACE {
35
+ #endif
36
+
37
+ // ----------------------------------------------------------------------------
38
+ // Internal classes to implement gzstream. See header file for user classes.
39
+ // ----------------------------------------------------------------------------
40
+
41
+ // --------------------------------------
42
+ // class gzstreambuf:
43
+ // --------------------------------------
44
+
45
+ gzstreambuf* gzstreambuf::open( const char* name, int open_mode) {
46
+ if ( is_open())
47
+ return (gzstreambuf*)0;
48
+ mode = open_mode;
49
+ // no append nor read/write mode
50
+ if ((mode & std::ios::ate) || (mode & std::ios::app)
51
+ || ((mode & std::ios::in) && (mode & std::ios::out)))
52
+ 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);
62
+ if (file == 0)
63
+ return (gzstreambuf*)0;
64
+ opened = 1;
65
+ return this;
66
+ }
67
+
68
+ gzstreambuf * gzstreambuf::close() {
69
+ if ( is_open()) {
70
+ sync();
71
+ opened = 0;
72
+ if ( gzclose( file) == Z_OK)
73
+ return this;
74
+ }
75
+ return (gzstreambuf*)0;
76
+ }
77
+
78
+ int gzstreambuf::underflow() { // used for input buffer only
79
+ if ( gptr() && ( gptr() < egptr()))
80
+ return * reinterpret_cast<unsigned char *>( gptr());
81
+
82
+ if ( ! (mode & std::ios::in) || ! opened)
83
+ return EOF;
84
+ // Josuttis' implementation of inbuf
85
+ int n_putback = gptr() - eback();
86
+ if ( n_putback > 4)
87
+ n_putback = 4;
88
+ memcpy( buffer + (4 - n_putback), gptr() - n_putback, n_putback);
89
+
90
+ int num = gzread( file, buffer+4, bufferSize-4);
91
+ if (num <= 0) // ERROR or EOF
92
+ return EOF;
93
+
94
+ // reset buffer pointers
95
+ setg( buffer + (4 - n_putback), // beginning of putback area
96
+ buffer + 4, // read position
97
+ buffer + 4 + num); // end of buffer
98
+
99
+ // return next character
100
+ return * reinterpret_cast<unsigned char *>( gptr());
101
+ }
102
+
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
+ // --------------------------------------
137
+ // class gzstreambase:
138
+ // --------------------------------------
139
+
140
+ gzstreambase::gzstreambase( const char* name, int mode) {
141
+ init( &buf);
142
+ open( name, mode);
143
+ }
144
+
145
+ gzstreambase::~gzstreambase() {
146
+ buf.close();
147
+ }
148
+
149
+ void gzstreambase::open( const char* name, int open_mode) {
150
+ if ( ! buf.open( name, open_mode))
151
+ clear( rdstate() | std::ios::badbit);
152
+ }
153
+
154
+ void gzstreambase::close() {
155
+ if ( buf.is_open())
156
+ if ( ! buf.close())
157
+ clear( rdstate() | std::ios::badbit);
158
+ }
159
+
160
+ #ifdef GZSTREAM_NAMESPACE
161
+ } // namespace GZSTREAM_NAMESPACE
162
+ #endif
163
+
164
+ // ============================================================================
165
+ // EOF //
@@ -0,0 +1,121 @@
1
+ // ============================================================================
2
+ // gzstream, C++ iostream classes wrapping the zlib compression library.
3
+ // Copyright (C) 2001 Deepak Bandyopadhyay, Lutz Kettner
4
+ //
5
+ // This library is free software; you can redistribute it and/or
6
+ // modify it under the terms of the GNU Lesser General Public
7
+ // License as published by the Free Software Foundation; either
8
+ // version 2.1 of the License, or (at your option) any later version.
9
+ //
10
+ // This library is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
+ // Lesser General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Lesser General Public
16
+ // License along with this library; if not, write to the Free Software
17
+ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
+ // ============================================================================
19
+ //
20
+ // File : gzstream.h
21
+ // Revision : $Revision: 1.5 $
22
+ // Revision_date : $Date: 2002/04/26 23:30:15 $
23
+ // Author(s) : Deepak Bandyopadhyay, Lutz Kettner
24
+ //
25
+ // Standard streambuf implementation following Nicolai Josuttis, "The
26
+ // Standard C++ Library".
27
+ // ============================================================================
28
+
29
+ #ifndef GZSTREAM_H
30
+ #define GZSTREAM_H 1
31
+
32
+ // standard C++ with new header file names and std:: namespace
33
+ #include <iostream>
34
+ #include <fstream>
35
+ #include <zlib.h>
36
+
37
+ #ifdef GZSTREAM_NAMESPACE
38
+ namespace GZSTREAM_NAMESPACE {
39
+ #endif
40
+
41
+ // ----------------------------------------------------------------------------
42
+ // Internal classes to implement gzstream. See below for user classes.
43
+ // ----------------------------------------------------------------------------
44
+
45
+ class gzstreambuf : public std::streambuf {
46
+ private:
47
+ static const int bufferSize = 47+256; // size of data buff
48
+ // totals 512 bytes under g++ for igzstream at the end.
49
+
50
+ gzFile file; // file handle for compressed file
51
+ char buffer[bufferSize]; // data buffer
52
+ char opened; // open/close state of stream
53
+ int mode; // I/O mode
54
+
55
+ int flush_buffer();
56
+ public:
57
+ gzstreambuf() : opened(0) {
58
+ setp( buffer, buffer + (bufferSize-1));
59
+ setg( buffer + 4, // beginning of putback area
60
+ buffer + 4, // read position
61
+ buffer + 4); // end position
62
+ // ASSERT: both input & output capabilities will not be used together
63
+ }
64
+ int is_open() { return opened; }
65
+ gzstreambuf* open( const char* name, int open_mode);
66
+ gzstreambuf* close();
67
+ ~gzstreambuf() { close(); }
68
+
69
+ virtual int overflow( int c = EOF);
70
+ virtual int underflow();
71
+ virtual int sync();
72
+ };
73
+
74
+ class gzstreambase : virtual public std::ios {
75
+ protected:
76
+ gzstreambuf buf;
77
+ public:
78
+ gzstreambase() { init(&buf); }
79
+ gzstreambase( const char* name, int open_mode);
80
+ ~gzstreambase();
81
+ void open( const char* name, int open_mode);
82
+ void close();
83
+ gzstreambuf* rdbuf() { return &buf; }
84
+ };
85
+
86
+ // ----------------------------------------------------------------------------
87
+ // User classes. Use igzstream and ogzstream analogously to ifstream and
88
+ // ofstream respectively. They read and write files based on the gz*
89
+ // function interface of the zlib. Files are compatible with gzip compression.
90
+ // ----------------------------------------------------------------------------
91
+
92
+ class igzstream : public gzstreambase, public std::istream {
93
+ public:
94
+ igzstream() : std::istream( &buf) {}
95
+ igzstream( const char* name, int open_mode = std::ios::in)
96
+ : gzstreambase( name, open_mode), std::istream( &buf) {}
97
+ gzstreambuf* rdbuf() { return gzstreambase::rdbuf(); }
98
+ void open( const char* name, int open_mode = std::ios::in) {
99
+ gzstreambase::open( name, open_mode);
100
+ }
101
+ };
102
+
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
+ #ifdef GZSTREAM_NAMESPACE
115
+ } // namespace GZSTREAM_NAMESPACE
116
+ #endif
117
+
118
+ #endif // GZSTREAM_H
119
+ // ============================================================================
120
+ // EOF //
121
+
@@ -0,0 +1,119 @@
1
+
2
+
3
+ #include <sstream>
4
+
5
+ #include "header.h"
6
+
7
+ namespace bcf {
8
+
9
+ /// @brief strip specified characters form the ends of a string
10
+ /// @param s string to trim on either ends
11
+ /// @param vals characters to trim from the ends
12
+ static std::string trim(const std::string &s, const std::string &vals) {
13
+ size_t start = s.find_first_not_of(vals);
14
+ if (start == std::string::npos) {
15
+ return "";
16
+ }
17
+ size_t end = s.find_last_not_of(vals);
18
+ return s.substr(start, (end + 1) - start);
19
+ }
20
+
21
+ /// @brief split line into key, remainder, unless it is a single field
22
+ /// @param line string to split apart
23
+ /// @return vector with either one or two entries
24
+ static std::vector<std::string> split_line(std::string line) {
25
+ line = trim(line, "#");
26
+ size_t delim_pos = line.find('=');
27
+ std::vector<std::string> data;
28
+ if (delim_pos != std::string::npos) {
29
+ data.push_back(line.substr(0, delim_pos));
30
+ data.push_back(line.substr(delim_pos + 1, line.size() - delim_pos));
31
+ } else {
32
+ data.push_back(line);
33
+ }
34
+ return data;
35
+ }
36
+
37
+ /// @brief parse the comma-separated fields of an info/format/contig line
38
+ /// @param text
39
+ /// @return
40
+ static std::unordered_map<std::string, std::string> parse_delimited(std::string text) {
41
+ text = trim(text, "<>");
42
+ std::unordered_map<std::string, std::string> data;
43
+
44
+ size_t delim;
45
+ std::string item, key, value;
46
+ std::istringstream iss(text);
47
+
48
+ while (std::getline(iss, item, ',')) {
49
+ delim = item.find('=');
50
+ key = item.substr(0, delim);
51
+ value = item.substr(delim + 1, item.size() - delim);
52
+ data[key] = trim(value, "\"");
53
+ }
54
+ return data;
55
+ }
56
+
57
+ Header::Header(std::string & text) {
58
+ filters[idx] = {"PASS", "All filters passed"};
59
+
60
+ std::istringstream lines(text);
61
+ std::string line;
62
+ std::unordered_map<std::string, std::string> data;
63
+ while (std::getline(lines, line)) {
64
+ if (line[1] != '#') {
65
+ if (line.substr(0, 6).find("CHROM") != std::string::npos) {
66
+ if (samples.size() > 0) {
67
+ throw std::invalid_argument("BCF has two header lines starting with #CHROM!");
68
+ }
69
+ // parse the sample IDs
70
+ std::string item = "FORMAT\t";
71
+ size_t i = line.find(item);
72
+ if (i != std::string::npos) {
73
+ line = line.substr(i + item.size(), line.size());
74
+ std::istringstream iss(line);
75
+ while (std::getline(iss, item, '\t')) {
76
+ samples.push_back(item);
77
+ }
78
+ }
79
+ }
80
+ } else {
81
+ std::vector<std::string> parsed = split_line(line);
82
+ if (parsed.size() == 2) {
83
+ std::string id = parsed[0];
84
+ std::string remainder = parsed[1];
85
+
86
+ if (!(valid.count(id) > 0)) {
87
+ continue;
88
+ }
89
+
90
+ data = parse_delimited(remainder);
91
+
92
+ // use the IDX field for the map key, if IDX was included
93
+ if (has_idx_tag && data.count("IDX") == 0) {
94
+ throw std::invalid_argument("invalid BCF - missing IDX field in " + data["ID"]);
95
+ }
96
+ if (data.count("IDX") > 0) {
97
+ idx = std::stoi(data["IDX"]);
98
+ }
99
+
100
+ if (id == "contig") {
101
+ contigs[contig_idx] = {data["ID"]};
102
+ contig_idx += 1;
103
+ } else if (id == "INFO") {
104
+ info[idx] = {data["ID"], data["Number"], data["Type"],
105
+ data["Description"]};
106
+ } else if (id == "FORMAT") {
107
+ format[idx] = {data["ID"], data["Number"], data["Type"],
108
+ data["Description"]};
109
+ } else if ((id == "FILTER") && (data["ID"] != "PASS")) {
110
+ filters[idx] = {data["ID"], data["Description"]};
111
+ }
112
+ idx += (id != "contig");
113
+ }
114
+ }
115
+ }
116
+
117
+ }
118
+
119
+ }