public
Created

pyvcf proposal to use funcparserlib to clarify parsing

  • Download Gist
funcparserlib_vcf.py
Python
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
import sys
import os
import re
import logging
import collections
import pprint
 
from funcparserlib.lexer import make_tokenizer, Spec
from funcparserlib.parser import (maybe, many, eof, skip, fwd, name_parser_vars, SyntaxError)
from funcparserlib.contrib.common import const, n, op, op_, sometok
 
 
# Object specification
# --------------------
 
class _HeaderEntry(object):
""" Base class for header entries """
 
expected = []
 
def __init__(self, values=None, strict=True, name=None):
self._name = name
self.values = values
if strict and hasattr(values, 'keys'):
missing = set(self.expected) - set(values.keys())
extra = set(values.keys()) - set(self.expected)
if missing:
logging.warning('missing definitions of %s for a %s header entry', missing, self.name)
if extra:
logging.warning('extra definitions %s for a %s header entry', extra, self.name)
 
@property
def name(self):
if self._name is not None:
return self._name
return self.__class__.__name__
 
def __repr__(self):
return "HeaderEntry(type=%s, values=%s)" % (self.name, self.values)
 
def __getattr__(self, name):
try:
return self.values[name]
except KeyError:
raise AttributeError
 
 
class _HeaderFormatSpec(_HeaderEntry):
""" Base class for header entries used to cast values later on in the file """
 
expected = ['ID', 'Number', 'Type', 'Description']
 
def cast(self, string):
if string == '.':
return None
try:
return self.Type(string)
except ValueError:
if type == int:
try:
value = float(string)
logging.warning('int type is actually a float')
return value
except:
pass
logging.warning('unable to parse value %s as type %s for %s', string, self.Type, self.name)
 
 
 
class Header(list):
""" A collection of header entries """
 
class FORMAT(_HeaderFormatSpec):
pass
 
class INFO(_HeaderFormatSpec):
pass
 
class FILTER(_HeaderEntry):
expected = ['ID', 'Description']
 
class contig(_HeaderEntry):
expected = ['assembly', 'taxonomy', 'species', 'length', 'ID', 'md5']
 
 
_classes = {
'INFO': INFO,
'FORMAT': FORMAT,
'FILTER': FILTER,
'contig': contig
}
 
def __init__(self, *entries):
list.__init__(self, *entries)
self.version = None
self.infos = {}
self.filters = {}
self.formats = {}
self.contigs = {}
 
self._check_version()
self._create_lookups()
 
def _check_version(self):
if len(self) > 0 and self[0].name == 'fileformat':
self.version = self[0].values
else:
logging.warning('header is missing fileformat specification')
 
def _create_lookups(self):
dicts = {
'INFO': self.infos,
'FILTER': self.filters,
'FORMAT': self.formats,
'contig': self.contigs
}
for entry in self:
dict_ = dicts.get(entry.name)
if dict_ is not None:
dict_[entry.ID] = entry
 
@classmethod
def _make_entry(cls, a):
""" Look up the class for a header line """
key, vals = a[0], a[1]
try:
return cls._classes[key](vals)
except KeyError:
return _HeaderEntry(name=key, values=vals)
 
@classmethod
def _make_value(cls, (k, v)):
""" handle typing of key, value pairs """
if k == 'Type':
if v == 'Integer': v = int
if v == 'String': v = str
if v == 'Float': v = float
return (k,v)
 
if k in ['Number', 'length'] :
try:
return k, int(v)
except ValueError:
return k, v
 
return k, v
 
@classmethod
def _make_ordered_dict(cls, el):
""" flatten a (head, list) pair into a list """
l = [el[0]]
if len(el) > 1:
l = l + el[1]
return collections.OrderedDict(l)
 
 
 
# Lexer specification
# -------------------
 
specs = [
Spec('description', r'"([^"]*)"'),
Spec('op', r'[#<>=,\n]'),
Spec('number', r'(\d+)'),
Spec('name', r'[A-Za-z_0-9\.:\/-]+'),
]
def tokenize(s):
return list(make_tokenizer(specs)(s))
 
 
# Grammar specification
# ---------------------
 
# a header value can be a name, a number or a quoted string
value = (sometok('name') | sometok('number') | sometok('description'))
 
# key value pairs are separated with '='
kv = sometok('name') + op_('=') + value >> Header._make_value
 
# a list of kvs are comma separated
kvlist = kv + many(op_(',') + kv) >> Header._make_ordered_dict
 
# header lines are name = (value | <kvlist>)
header_line = op_('#') + op_('#') + sometok('name') + op_('=') + (value | op_('<') + kvlist + op_('>')) >> Header._make_entry
 
header = many(header_line + op_('\n')) >> Header
 
 
 
exf = """##fileformat=VCFv4.1
##fileDate=20090805
##source=myImputationProgramV3.1
##reference=file:///seq/references/1000GenomesPilot-NCBI36.fasta
##contig=<ID=20,length=62435964,assembly=B36,md5=f126cdf8a6e0c7f379d618ff66beb2da,species="Homo sapiens",taxonomy=x>
##phasing=partial
##INFO=<ID=NS,Number=1,Type=Integer,Description="Number of Samples With Data">
##INFO=<ID=DP,Number=1,Type=Integer,Description="Total Depth">
##INFO=<ID=AF,Number=A,Type=Float,Description="Allele Frequency">
##INFO=<ID=AA,Number=1,Type=String,Description="Ancestral Allele">
##INFO=<ID=DB,Number=0,Type=Flag,Description="dbSNP membership, build 129">
##INFO=<ID=H2,Number=0,Type=Flag,Description="HapMap2 membership">
##FILTER=<ID=q10,Description="Quality below 10">
##FILTER=<ID=s50,Description="Less than 50% of samples have data">
##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">
##FORMAT=<ID=GQ,Number=1,Type=Integer,Description="Genotype Quality">
##FORMAT=<ID=DP,Number=1,Type=Integer,Description="Read Depth">
##FORMAT=<ID=HQ,Number=2,Type=Integer,Description="Haplotype Quality">"""
 
if __name__ == '__main__':
pprint.pprint(header.parse(tokenize(exf)))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.