Repository 'cravat_annotate_mutations'
hg clone https://toolshed.g2.bx.psu.edu/repos/in_silico/cravat_annotate_mutations

Changeset 17:a9cb0192d52d (2018-06-12)
Previous changeset 16:efb15a586f5e (2018-06-12) Next changeset 18:dd9181024296 (2018-06-12)
Commit message:
Uploaded
added:
cravat_convert/base_converter.py
cravat_convert/cravat_convert.py
cravat_convert/cravat_convert.xml
cravat_convert/vcf_converter.py
removed:
cravat_annotate/cravat_annotate.py
cravat_annotate/cravat_annotate.xml
b
diff -r efb15a586f5e -r a9cb0192d52d cravat_annotate/cravat_annotate.py
--- a/cravat_annotate/cravat_annotate.py Tue Jun 12 12:05:48 2018 -0400
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
[
b'@@ -1,246 +0,0 @@\n-"""\n-A galaxy wrapper for the /rest/service/query API endpoint on Cravat.\n-\n-\n-Notes on Mapping:\n------------------\n-The CravatQuery class uses static method \'from_array\' to interpret an array of values\n-into a query string for the /rest/service/query API service on the cravat server.\n-This involves using a mapping dictionary to know how to associate the array\'s index positions\n-in to query-ing attributes, such as the chromosome, position, etc. The CravatQuery\n-class contains a default value (\'default_mapping\'); however, this could also be\n-offered as a user-configurable option.\n-"""\n-\n-\n-import requests\n-import json\n-import sys\n-import re\n-\n-\n-class CravatQueryException(Exception):\n-\n-\tdef __init__(self, message, errors=None):\t \n-\t\tsuper(CravatQueryException, self).__init__(message)\n-\t\t# Support for custom error codes\n-\t\tself.errors = errors\n-\n-\n-class CravatQuery(object):\n-\t"""\n-\t: A class for handling Cravat query strings.\n-\t: Args (all required):\n-\t:\tchr - Chromosome\n-\t:\tpos - Position\n-\t:\tstrand - Strand\n-\t:\tref - Reference Base\n-\t:\talt - Alternate Base\n-\t"""\n-\n-\t# The endpoint that CravatQuerys are submitted to\n-\tendpoint = \'http://cravat.us/CRAVAT/rest/service/query\'\n-\n-\t# The value delimiter used in the Cravat input file to delimit values\n-\tdelimiter = "\\t"\n-\n-\t# Defualt indices for intepretting a cravat file\'s row of data in to a CravatQuery\n-\tdefault_mapping = {\n-\t\t\'chromosome\': 1,\n-\t\t\'position\': 2,\n-\t\t\'strand\': 3,\n-\t\t\'reference\': 4,\n-\t\t\'alternate\': 5\n-\t}\n-\n-\t# Defualt values. Used as backup for CravatQuery to resolve query with incomplete information\n-\tdefault_values = {\n-\t\t\'strand\': \'+\'\n-\t}\n-\n-\t# The neccessary attributes neeeded to submit a query.\n-\tquery_keys = [\n-\t\t\'chromosome\', \'position\', \'strand\', \'reference\', \'alternate\'\n-\t]\n-\n-\t# Expected response keys from server. Ordered in list so that galaxy output has uniform column ordering run-to-run.\n-\t# If cravat server returns additional keys, they are appended to and included in output.\n-\tresponse_keys = [\n-\t\t"Chromosome", "Position", "Strand", "Reference base(s)", "Alternate base(s)",\n-\t \t"HUGO symbol", "S.O. transcript", "Sequence ontology protein change", "Sequence ontology",\n-\t\t"S.O. all transcripts", "gnomAD AF", "gnomAD AF (African)", "gnomAD AF (Amrican)",\n-\t\t"gnomAD AF (Ashkenazi Jewish)", "gnomAD AF (East Asian)", "gnomAD AF (Finnish)",\n-\t\t"gnomAD AF (Non-Finnish European)", "gnomAD AF (Other)", "gnomAD AF (South Asian)",\n-\t\t"1000 Genomes AF", "ESP6500 AF (average)", "ESP6500 AF (European American)",\n-\t\t"ESP6500 AF (African American)", "COSMIC transcript", "COSMIC protein change", \n-\t\t"COSMIC variant count [exact nucleotide change]", "cosmic_site_nt", "CGL driver class",\n-\t\t"TARGET", "dbSNP", "cgc_role", "cgc_inheritance", "cgc_tumor_type_somatic",\n-\t\t"cgc_tumor_type_germline", "ClinVar", "ClinVar disease identifier", "ClinVar XRef",\n-\t\t"GWAS Phenotype (GRASP)", "GWAS PMID (GRASP)", "Protein 3D variant"\n-\t]\n-\n-\n-\tdef __init__(self, _chr, pos, strand, ref, alt):\n-\t\t# \'_chr\' used to avoid naming confliction with python built-in \'chr\'\n-\t\tself.chromosome = CravatQuery.format_chromosome(_chr)\n-\t\tself.position = pos\n-\t\tself.strand = strand\n-\t\tself.reference = ref\n-\t\tself.alternate = alt\n-\t\tself.values = [self.chromosome, self.position, self.strand, self.reference, self.alternate]\n-\n-\n-\tdef __str__(self):\n-\t\t""" : Represent the CravatQuery as a valid query string for call to Cravat server """\n-\t\treturn "_".join(map(lambda x: str(x), self.values))\n-\n-\t\n-\tdef as_query_string(self):\n-\t\treturn str(self)\n-\n-\t\n-\t@staticmethod\n-\tdef from_dictionary(d):\n-\t\t"""\n-\t\t: Instantiate a CravatQuery from a dictionary representation.\n-\t\t: Args:\n-\t\t\t: d <dictionary>: A dictionary representing a CravatQuery, containing keys: [{}] \n-\t\t""".format(CravatQuery.query_keys)\n-\n-\t\tfor key in CravatQuery.query_keys:\n-\t\t\tif key not in d:\n-\t\t\t\traise CravatQueryException("CravatQuery.from_dictionary requires keys: [{}], however key: \'{}\' was not provided "\n-\t\t\t\t\t\t\t\t\t\t\t.for'..b' associated to \'fmt\'\n-\t\tif mapping == None:\n-\t\t\tmapping = CravatQuery.default_mapping\n-\t\t\t\n-\t\t# Build a dict of cravat querying keys to values.\n-\t\td = {}\n-\t\tfor key in CravatQuery.query_keys:\n-\t\t\t# Try to get index position from mapping by the key, and value from array by the index\n-\t\t\tif key in mapping:\n-\t\t\t\tindex = mapping[key]\n-\t\t\t\td[key] = array[index]\n-\t\t\t# If index not provided in mapping, check if there is a defualt value\n-\t\t\telif key in CravatQuery.default_values:\n-\t\t\t\td[key] = CravatQuery.default_values[key]\n-\t\t\t# Unable to get value for querying key, meaning can\'t construct the minimum requirements for query\n-\t\t\telse:\n-\t\t\t\traise CravatQueryException("CravatQuery.from_array requires a mapping index for key: \'{}\', however value was not provided".format(key))\n-\t\treturn CravatQuery.from_dictionary(d)\n-\n-\n-\n-\t@staticmethod\n-\tdef format_chromosome(_chr):\n-\t\t"""\n-\t\t: Format a chromosome for use as query parameter. \'_chr\' name used to avoid python built-in name confliction.\n-\t\t: Args:\n-\t\t\t: _chr - Either an interger [1,23], or \'x\'/\'X\', or \'y\'/\'Y\', or a string of the form\n-\t\t\t: \t\t\'chr<z>\' where \'<z>\' is one of the previously described values \n-\t\t"""\n-\t\tinRange = lambda x: 1 <= x and x <= 23\n-\t\t_chr = _chr.lower()\n-\t\t_chr = _chr.strip(\'chr\')\n-\t\t# Handler interger chromosomes 1 to 23\n-\t\ttry:\n-\t\t\t_chr = int(_chr)\n-\t\t\tif inRange(_chr):\n-\t\t\t\treturn \'chr\' + str(_chr)\n-\t\t\telse:\n-\t\t\t\traise CravatQueryException("Chromsomme of \'{}\' was out of range [1,23]".format(_chr))\n-\t\texcept:\n-\t\t\tpass\n-\t\t# Handle chromosomes chromosomes x and y\n-\t\tif _chr == \'x\' or _chr == \'y\':\n-\t\t\treturn \'chr\' + _chr\n-\t\traise CravatQueryException("Unable to resolve input: \'{}\' into a valid chromosome representation".format(_chr))\n-\n-\n-\t@staticmethod\n-\tdef jump_header(in_file, out_file, headerlines=0):\n-\t\t"""\n-\t\t: Jumps over a header space of line number \'headerlines\'. Sets up in_file so that\n-\t\t: the next execution of in_file.readline() will return the first non-header line.\n-\t\t"""\n-\t\tin_file.seek(0)\n-\t\tfor line in range(headerlines):\n-\t\t\tin_file.readline()\n-\n-\n-def main(in_path, out_path, pre_callback=None, user_mapping=None):\n-\t"""\n-\t: Read the file line by line and use data to query cravat server.\n-\t: Args:\n-\t\t: fmt <str>: \'cr\' or \'vcf\'. The input format\n-\t\t: in_path <str>: Path to input file\n-\t\t: in_path <str>: Path to output file\n-\t\t: header_callback <function>: A function to handle the header space. Executed\n-\t\t\tbefore main loop. Recieves in_file, out_file, and fmt as argumnets\n-\t"""\n-\n-\twith open(in_path, \'r\') as in_file, \\\n-\topen(out_path, \'w\') as out_file:\n-\n-\t\t# Perform any pre-processing steps, such as jumping a header space\n-\t\tif pre_callback:\n-\t\t\tpre_callback(in_file, out_file, fmt)\n-\n-\t\t# main loop\n-\t\tfor line in in_file:\n-\n-\t\t\t# Create query from line of input data\n-\t\t\tline = line.strip().split(\'\\t\')\n-\t\t\tquery = CravatQuery.from_array(line, user_mapping)\n-\t\t\t# Make request, and write respone data\n-\t\t\tcall = requests.get(CravatQuery.endpoint, params={ \'mutation\': query.as_query_string })\n-\t\t\ttry:\n-\t\t\t\tif call.status_code != 200 or call.text == "":\n-\t\t\t\t\traise CravatQueryException("Bad Server Response. Respone code: \'{}\', Response Text: \'{}\'".format(call.status_code, call.text))\n-\t\t\t\tjson_response = json.loads(call.text)\n-\t\t\t\twrote = False\n-\t\t\t\tfor key, val in json_response.items():\n-\t\t\t\t\t# Set numeric values to uniform format\n-\t\t\t\t\ttry:\n-\t\t\t\t\t\tval = float(val)\n-\t\t\t\t\t\tval = format(val, ".4f")\n-\t\t\t\t\texcept:\n-\t\t\t\t\t\tpass\n-\t\t\t\t\tif wrote:\n-\t\t\t\t\t\tout_file.write("\\t")\n-\t\t\t\t\tout_file.write(val)\n-\t\t\t\t\twrote = True\n-\t\t\t\tout_file.write("\\n")\n-\t\t\texcept CravatQueryException as e:\n-\t\t\t\tprint(e)\n-\t\t\t\t\n-\t\t\n-\n-\n-if __name__ == "__main__":\n-\n-\t# Input and output file paths, obtained form command line\n-\tin_path = sys.argv[1]\n-\tout_path = sys.argv[2]\n-\n-\t# Possibly allow user mapping configuration thourgh here. Not fully implemented\n-\tif len(sys.argv) > 2:\n-\t\tuser_mapping = sys.argv[3]\n-\n-\t# Run the main operation\n-\tmain(in_path, out_path)\n\\ No newline at end of file\n'
b
diff -r efb15a586f5e -r a9cb0192d52d cravat_annotate/cravat_annotate.xml
--- a/cravat_annotate/cravat_annotate.xml Tue Jun 12 12:05:48 2018 -0400
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
[
@@ -1,25 +0,0 @@
-<tool id="cravat_query" name="CRAVAT Query" version="1.0.0">
-    <description>Queries CRAVAT for cancer annotation</description>
-  <command interpreter="python">cravat_annotate.py $input $output</command>
-  
-  <inputs>
-    <param format="tabular" name="input" type="data" label="Source file"/>
-  </inputs>
-  
-  <outputs>
-    <data format="tabular" name="output" />
-  </outputs>
-
-  <tests>
-    <test>
-      <param name="input" value="input_call.txt"/>
-      <output name="output" file="Galaxy23-[CRAVAT_Query_on_data_22].tabular"/>
-    </test>
-  </tests>
-
-  <help>
-    This tool queries CRAVAT for cancer annotation.
-  </help>
-
-</tool>
-
b
diff -r efb15a586f5e -r a9cb0192d52d cravat_convert/base_converter.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/cravat_convert/base_converter.py Tue Jun 12 14:03:57 2018 -0400
b
@@ -0,0 +1,22 @@
+class BaseConverter(object):
+    def __init__(self):
+        self.format_name = None
+    def check_format(self,*args,**kwargs):
+        err_msg = 'Converter for %s format has no method check_format' %\
+            self.format_name
+        raise NotImplementedError(err_msg)
+    def setup(self,*args,**kwargs):
+        err_msg = 'Converter for %s format has no method setup' %\
+            self.format_name
+        raise NotImplementedError(err_msg)
+    def convert_line(self,*args,**kwargs):
+        err_msg = 'Converter for %s format has no method convert_line' %\
+            self.format_name
+        raise NotImplementedError(err_msg)
+
+
+class BadFormatError(Exception):
+    def __init__(self, message, errors=None):
+        super(BadFormatError, self).__init__(message)
+        # Support for custom error codes, if added later
+        self.errors = errors
\ No newline at end of file
b
diff -r efb15a586f5e -r a9cb0192d52d cravat_convert/cravat_convert.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/cravat_convert/cravat_convert.py Tue Jun 12 14:03:57 2018 -0400
[
@@ -0,0 +1,77 @@
+'''
+Convert a VCF format file to Cravat format file
+'''
+
+import os
+import argparse
+from vcf_converter import CravatConverter
+
+# File read/write configuration variables
+vcf_sep = '\t'
+cr_sep = '\t'
+cr_newline = '\n'
+
+# VCF Headers mapped to their index position in a row of VCF values
+vcf_mapping = {
+    'CHROM': 0,
+    'POS': 1,
+    'ID': 2,
+    'REF': 3,
+    'ALT': 4,
+    'QUAL': 5,
+    'FILTER': 6,
+    'INFO': 7,
+    'FORMAT': 8,
+    'NA00001': 9,
+    'NA00002': 10,
+    'NA00003': 11
+}
+
+
+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 = os.path.join(os.getcwd(), "cravat_converted.txt"),
+                            help = 'Output path to write the cravat file to')
+    return parser.parse_args()
+
+
+def convert(in_path, out_path=None):
+    if not out_path:
+        base, _ = os.path.split(in_path)
+        out_path = os.path.join(base, "cravat_converted.txt")
+    
+    with open(in_path, 'r') as in_file, \
+    open(out_path, 'w') as out_file:
+
+        # cr_count will be used to generate the 'TR' field of the cravat rows (first header)
+        cr_count = 0
+        # VCF lines are always assumed to be '+' strand, as VCF doesn't specify that attribute
+        strand = '+'
+        # VCF converter. Adjusts position, reference, and alternate for Cravat formatting.
+        converter = CravatConverter()
+
+        for line in in_file:
+            if line.startswith("#"):
+                continue
+            line = line.strip().split(vcf_sep)
+            # row is dict of VCF headers mapped to corresponding values of this line
+            row = { header: line[index] for header, index in vcf_mapping.items() }
+            for alt in row["ALT"].split(","):
+                new_pos, new_ref, new_alt = converter.extract_vcf_variant(strand, row["POS"], row["REF"], alt)
+                new_pos, new_ref, new_alt = str(new_pos), str(new_ref), str(new_alt)
+                cr_line = cr_sep.join([
+                    'TR' + str(cr_count), row['CHROM'], new_pos, strand, new_ref, new_alt, row['ID']
+                ])
+                out_file.write(cr_line + cr_newline)
+                cr_count += 1
+
+
+if __name__ == "__main__":
+    cli_args = get_args()
+    convert(cli_args.input, cli_args.output)
b
diff -r efb15a586f5e -r a9cb0192d52d cravat_convert/cravat_convert.xml
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/cravat_convert/cravat_convert.xml Tue Jun 12 14:03:57 2018 -0400
b
@@ -0,0 +1,20 @@
+<tool id="cravat_convert" name="CRAVAT Convert" version="1.0.0">
+    <description>Converts a VCF format file to a Cravat format file</description>
+    <command interpreter="python">cravat_convert.py -i $input -o $output</command>
+  
+    <inputs>
+        <param format="tabular" name="input" type="data" label="Source file"/>
+    </inputs>
+  
+    <outputs>
+        <data format="tabular" name="output" />
+    </outputs>
+
+    <!-- <tests></tests> -->
+
+    <help>
+        Converts a VCF format file to a Cravat format file
+    </help>
+
+</tool>
+
b
diff -r efb15a586f5e -r a9cb0192d52d cravat_convert/vcf_converter.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/cravat_convert/vcf_converter.py Tue Jun 12 14:03:57 2018 -0400
[
b'@@ -0,0 +1,243 @@\n+"""\r\n+A module originally obtained from the cravat package. Modified to use in the vcf\r\n+converter galaxy tool.\r\n+\r\n+\r\n+Register of changes made (Chris Jacoby):\r\n+    1) Changed imports as galaxy tool won\'t have access to complete cravat python package\r\n+    2) Defined BadFormatError in BaseConverted file, as I didn\'t have the BadFormatError module\r\n+"""\r\n+\r\n+from base_converter import BaseConverter, BadFormatError\r\n+import re\r\n+\r\n+class CravatConverter(BaseConverter):\r\n+    \r\n+    def __init__(self):\r\n+        self.format_name = \'vcf\'\r\n+        self.samples = []\r\n+        self.var_counter = 0\r\n+        self.addl_cols = [{\'name\':\'phred\',\r\n+                           \'title\':\'Phred\',\r\n+                           \'type\':\'string\'},\r\n+                          {\'name\':\'filter\',\r\n+                           \'title\':\'VCF filter\',\r\n+                           \'type\':\'string\'},\r\n+                          {\'name\':\'zygosity\',\r\n+                           \'title\':\'Zygosity\',\r\n+                           \'type\':\'string\'},\r\n+                          {\'name\':\'alt_reads\',\r\n+                           \'title\':\'Alternate reads\',\r\n+                           \'type\':\'int\'},\r\n+                          {\'name\':\'tot_reads\',\r\n+                           \'title\':\'Total reads\',\r\n+                           \'type\':\'int\'},\r\n+                          {\'name\':\'af\',\r\n+                           \'title\':\'Variant allele frequency\',\r\n+                           \'type\':\'float\'}]\r\n+    \r\n+    def check_format(self, f): \r\n+        return f.readline().startswith(\'##fileformat=VCF\')\r\n+    \r\n+    def setup(self, f):\r\n+        \r\n+        vcf_line_no = 0\r\n+        for line in f:\r\n+            vcf_line_no += 1\r\n+            if len(line) < 6:\r\n+                continue\r\n+            if line[:6] == \'#CHROM\':\r\n+                toks = re.split(\'\\s+\', line.rstrip())\r\n+                if len(toks) > 8:\r\n+                    self.samples = toks[9:]\r\n+                break\r\n+    \r\n+    def convert_line(self, l):\r\n+        if l.startswith(\'#\'): return None\r\n+        self.var_counter += 1\r\n+        toks = l.strip(\'\\r\\n\').split(\'\\t\')\r\n+        all_wdicts = []\r\n+        if len(toks) < 8:\r\n+            raise BadFormatError(\'Wrong VCF format\')\r\n+        [chrom, pos, tag, ref, alts, qual, filter, info] = toks[:8]\r\n+        if tag == \'\':\r\n+            raise BadFormatError(\'ID column is blank\')\r\n+        elif tag == \'.\':\r\n+            tag = \'VAR\' + str(self.var_counter)\r\n+        if chrom[:3] != \'chr\':\r\n+            chrom = \'chr\' + chrom\r\n+        alts = alts.split(\',\')\r\n+        len_alts = len(alts)\r\n+        if len(toks) == 8:\r\n+            for altno in range(len_alts):\r\n+                wdict = None\r\n+                alt = alts[altno]\r\n+                newpos, newref, newalt = self.extract_vcf_variant(\'+\', pos, ref, alt)\r\n+                wdict = {\'tags\':tag,\r\n+                         \'chrom\':chrom,\r\n+                         \'pos\':newpos,\r\n+                         \'ref_base\':newref,\r\n+                         \'alt_base\':newalt,\r\n+                         \'sample_id\':\'no_sample\',\r\n+                         \'phred\': qual,\r\n+                         \'filter\': filter}\r\n+                all_wdicts.append(wdict)\r\n+        elif len(toks) > 8:\r\n+            sample_datas = toks[9:]\r\n+            genotype_fields = {}\r\n+            genotype_field_no = 0\r\n+            for genotype_field in toks[8].split(\':\'):\r\n+                genotype_fields[genotype_field] = genotype_field_no\r\n+                genotype_field_no += 1\r\n+            if not (\'GT\' in genotype_fields):\r\n+                raise BadFormatError(\'No GT Field\')\r\n+            gt_field_no = genotype_fields[\'GT\']\r\n+            for sample_no in range(len(sample_datas)):\r\n+                sample = self.samples[sample_no]\r\n+                sample_data = sample_datas[sample_no].split(\':\')\r\n+                gts = {}\r\n+                for gt in sample_data[gt_field_no].replace(\'/\', \'|\').split(\'|\'):\r\n+                  '..b'\r\n+                ref_reads = sample_data[genotype_fields[\'AD\']].split(\',\')[0]\r\n+                alt_reads = sample_data[genotype_fields[\'AD\']].split(\',\')[1]\r\n+            elif gt == max(gts.keys()):    \r\n+                #if geontype has multiple alt bases, then AD will have #alt1 reads, #alt2 reads\r\n+                alt_reads = sample_data[genotype_fields[\'AD\']].split(\',\')[1]\r\n+            else:\r\n+                alt_reads = sample_data[genotype_fields[\'AD\']].split(\',\')[0]                            \r\n+                             \r\n+        if \'DP\' in genotype_fields and genotype_fields[\'DP\'] <= len(sample_data): \r\n+            depth = sample_data[genotype_fields[\'DP\']] \r\n+        elif alt_reads != \'\' and ref_reads != \'\':\r\n+            #if DP is not present but we have alt and ref reads count, dp = ref+alt\r\n+            depth = int(alt_reads) + int(ref_reads)   \r\n+\r\n+        if \'AF\' in genotype_fields and genotype_fields[\'AF\'] <= len(sample_data):\r\n+            af = float(sample_data[genotype_fields[\'AF\']] )\r\n+        elif depth != \'\' and alt_reads != \'\':\r\n+            #if AF not specified, calc it from alt and ref reads\r\n+            af = float(alt_reads) / float(depth)\r\n+ \r\n+        return depth, alt_reads, af\r\n+            \r\n+    def extract_vcf_variant (self, strand, pos, ref, alt):\r\n+\r\n+        reflen = len(ref)\r\n+        altlen = len(alt)\r\n+        \r\n+        # Returns without change if same single nucleotide for ref and alt. \r\n+        if reflen == 1 and altlen == 1 and ref == alt:\r\n+            return pos, ref, alt\r\n+        \r\n+        # Trimming from the start and then the end of the sequence \r\n+        # where the sequences overlap with the same nucleotides\r\n+        new_ref2, new_alt2, new_pos = \\\r\n+            self.trimming_vcf_input(ref, alt, pos, strand)\r\n+                \r\n+        if new_ref2 == \'\':\r\n+            new_ref2 = \'-\'\r\n+        if new_alt2 == \'\':\r\n+            new_alt2 = \'-\'\r\n+        \r\n+        return new_pos, new_ref2, new_alt2\r\n+    \r\n+    # This function looks at the ref and alt sequences and removes \r\n+    # where the overlapping sequences contain the same nucleotide.\r\n+    # This trims from the end first but does not remove the first nucleotide \r\n+    # because based on the format of VCF input the \r\n+    # first nucleotide of the ref and alt sequence occur \r\n+    # at the position specified.\r\n+    #     End removed first, not the first nucleotide\r\n+    #     Front removed and position changed\r\n+    def trimming_vcf_input(self, ref, alt, pos, strand):\r\n+        pos = int(pos)\r\n+        reflen = len(ref)\r\n+        altlen = len(alt)\r\n+        minlen = min(reflen, altlen)\r\n+        new_ref = ref\r\n+        new_alt = alt\r\n+        new_pos = pos\r\n+        # Trims from the end. Except don\'t remove the first nucleotide. \r\n+        # 1:6530968 CTCA -> GTCTCA becomes C -> GTC.\r\n+        for nt_pos in range(0, minlen - 1): \r\n+            if ref[reflen - nt_pos - 1] == alt[altlen - nt_pos - 1]:\r\n+                new_ref = ref[:reflen - nt_pos - 1]\r\n+                new_alt = alt[:altlen - nt_pos - 1]\r\n+            else:\r\n+                break    \r\n+        new_ref_len = len(new_ref)\r\n+        new_alt_len = len(new_alt)\r\n+        minlen = min(new_ref_len, new_alt_len)\r\n+        new_ref2 = new_ref\r\n+        new_alt2 = new_alt\r\n+        # Trims from the start. 1:6530968 G -> GT becomes 1:6530969 - -> T.\r\n+        for nt_pos in range(0, minlen):\r\n+            if new_ref[nt_pos] == new_alt[nt_pos]:\r\n+                if strand == \'+\':\r\n+                    new_pos += 1\r\n+                elif strand == \'-\':\r\n+                    new_pos -= 1\r\n+                new_ref2 = new_ref[nt_pos + 1:]\r\n+                new_alt2 = new_alt[nt_pos + 1:]\r\n+            else:\r\n+                new_ref2 = new_ref[nt_pos:]\r\n+                new_alt2 = new_alt[nt_pos:]\r\n+                break  \r\n+        return new_ref2, new_alt2, new_pos\r\n+\r\n+\r\n+if __name__ == "__main__":\r\n+    c = CravatConverter()\n\\ No newline at end of file\n'