|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +""" |
| 4 | +This script extract population-specific annotations from a genome |
| 5 | +variation format (GVF) file. |
| 6 | +""" |
| 7 | + |
| 8 | +from argparse import ArgumentParser |
| 9 | +import numpy as np |
| 10 | +import pandas as pd |
| 11 | +import urllib.request, urllib.parse, urllib.error |
| 12 | + |
| 13 | + |
| 14 | +def parseGFFAttributes(attributeString): |
| 15 | + """Parse the GFF3 attribute column and return a dict""" |
| 16 | + if attributeString == ".": return {} |
| 17 | + ret = {} |
| 18 | + for attribute in attributeString.split(';'): |
| 19 | + key, value = attribute.split('=') |
| 20 | + ret[urllib.parse.unquote(key)] = urllib.parse.unquote(value) |
| 21 | + return ret |
| 22 | + |
| 23 | + |
| 24 | +def parseGVF(row): |
| 25 | + """ |
| 26 | + A simple GVF format parser, modified from a GFF3 format parser. |
| 27 | + Return a dictionary per row for our dataframe. |
| 28 | + """ |
| 29 | + |
| 30 | + populations = ['AFR', 'AMR', 'EAS', 'EUR', 'SAS'] |
| 31 | + |
| 32 | + record = {} |
| 33 | + |
| 34 | + parts = row.strip().split('\t') |
| 35 | + |
| 36 | + record['Chr'] = parts[0] |
| 37 | + record['Pos'] = parts[3] |
| 38 | + |
| 39 | + attr = parseGFFAttributes(parts[8]) |
| 40 | + record['ID'] = attr['ID'] |
| 41 | + dbSNP = attr['Dbxref'].split(':') |
| 42 | + record['rs'] = dbSNP[1] |
| 43 | + #maf = attr['global_minor_allele_frequency'] |
| 44 | + record['Ref'] = attr['Reference_seq'] |
| 45 | + record['Alt'] = attr['Variant_seq'] |
| 46 | + |
| 47 | + for pop in populations: |
| 48 | + if pop in attr.keys(): |
| 49 | + record[pop] = attr[pop] |
| 50 | + else: |
| 51 | + record[pop] = 0.0 |
| 52 | + |
| 53 | + return record |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + parser = ArgumentParser(description='Parse a file in GVF format and create a dataframe') |
| 58 | + parser.add_argument('-i', '--infile', help='Input a file in GVF format') |
| 59 | + parser.add_argument('-o', '--outfile', help='Outputfile name and path') |
| 60 | + args = parser.parse_args() |
| 61 | + |
| 62 | + fn = args.infile |
| 63 | + out = args.outfile |
| 64 | + |
| 65 | + rows_list = [] |
| 66 | + with open(fn) as infile: |
| 67 | + for row in infile: |
| 68 | + if row.startswith('#'): |
| 69 | + continue |
| 70 | + else: |
| 71 | + rows_list.append(parseGVF(row)) |
| 72 | + |
| 73 | + names = ['Chr', 'ID', 'rs', 'Pos', 'Ref', 'Alt', 'AFR', 'AMR', 'EAS', 'EUR', 'SAS'] |
| 74 | + df = pd.DataFrame(rows_list, columns=names) |
| 75 | + |
| 76 | + df.to_csv(out, sep='\t', index=False) |
| 77 | + |
| 78 | + |
0 commit comments