view cravat_annotate/cravat_annotate.py @ 18:dd9181024296 draft

Uploaded
author in_silico
date Tue, 12 Jun 2018 14:04:08 -0400
parents
children
line wrap: on
line source

"""
A galaxy wrapper for the /rest/service/query API endpoint on Cravat.
"""


import requests
import json
import sys
import re
import argparse


# The endpoint that CravatQuerys are submitted to
endpoint = 'http://cravat.us/CRAVAT/rest/service/query'


# The value delimiter used in the Cravat input file to delimit values
delimiter = "\t"


# Defualt indices for intepretting a cravat file's row of data in to a CravatQuery
cr_mapping = {
	'chromosome': 1,
	'position': 2,
	'strand': 3,
	'reference': 4,
	'alternate': 5
}


# The neccessary attributes neeeded to submit a query.
query_keys = [
	'chromosome', 'position', 'strand', 'reference', 'alternate'
]


# Expected response keys from server. Ordered in list so that galaxy output has uniform column ordering run-to-run.
# If cravat server returns additional keys, they are appended to and included in output.
response_keys = [
	"Chromosome", "Position", "Strand", "Reference base(s)", "Alternate base(s)",
	"HUGO symbol", "S.O. transcript", "Sequence ontology protein change", "Sequence ontology",
	"S.O. all transcripts", "gnomAD AF", "gnomAD AF (African)", "gnomAD AF (Amrican)",
	"gnomAD AF (Ashkenazi Jewish)", "gnomAD AF (East Asian)", "gnomAD AF (Finnish)",
	"gnomAD AF (Non-Finnish European)", "gnomAD AF (Other)", "gnomAD AF (South Asian)",
	"1000 Genomes AF", "ESP6500 AF (average)", "ESP6500 AF (European American)",
	"ESP6500 AF (African American)", "COSMIC transcript", "COSMIC protein change", 
	"COSMIC variant count [exact nucleotide change]", "cosmic_site_nt", "CGL driver class",
	"TARGET", "dbSNP", "cgc_role", "cgc_inheritance", "cgc_tumor_type_somatic",
	"cgc_tumor_type_germline", "ClinVar", "ClinVar disease identifier", "ClinVar XRef",
	"GWAS Phenotype (GRASP)", "GWAS PMID (GRASP)", "Protein 3D variant"
]


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input',
                            '-i',
                            required = True,
                            help='Input path to a VCF file for conversion',)
    parser.add_argument('--output',
                            '-o',
                            default = None,
                            help = 'Output path to write the cravat file to')
    return parser.parse_args()


def format_chromosome(chrom):
	""" : Ensure chromosome entry is propely formatted for use as querying attribute. """
	if chrom[0:3] == 'chr':
		return chrom
	return 'chr' + str(chrom)


def get_query_string(row):
	""" : From a row dict, return a query string for the Cravat server.
		: The row dict is cravat headeres associated to their values of that row.
	"""
	return '_'.join([ row['chromosome'], row['position'], row['strand'], row['reference'], row['alternate'] ])


def query(in_path, out_path):
	""" : From a Cravat the file at in_path, query each line on the Cravat server.
		: Write the response values to file at out_path.
	"""

	with open(in_path, 'r') as in_file, \
	open(out_path, 'w') as out_file:

		for line in in_file:
			line = line.strip().split('\t')
			# row is dict of cravat col headers assioted values in this line
			row = { header: line[index] for header, index in cr_mapping.items() }
			row['chromosome'] = format_chromosome(row['chromosome'])
			query_string = get_query_string(row)
			call = requests.get(endpoint, params={ 'mutation': query_string })
			if call.status_code != 200 or call.text == "":
				raise requests.RequestException("Bad Server Response. Respone code: '{}', Response Text: '{}'".format(call.status_code, call.text))
			json_response = json.loads(call.text)
			# See if server returned additional json key-val paris not expected in response_keys
			for key in json_response:
				if key not in response_keys:
					response_keys.append(key)
			# Write key in order of response_keys to standardize order of output columns
			wrote = False
			for key in response_keys:
				if key not in json_response:
					val = None
				val = json_response[key]
				# Format standardization for numerics
				try:
					val = float(val)
					val = format(val, ".4f")
				except:
					pass
				if wrote:
					out_file.write("\t")
				out_file.write(val)
				wrote = True
			out_file.write("\n")		


if __name__ == "__main__":
	cli_args = get_args()
	if cli_args.output == None:
		base, _ = os.path.split(cli_args.input)
		cli_args.output = os.path.join(base, "cravat_converted.txt") 
	query(cli_args.input, cli_args.output)