Repository 'allele_counts'
hg clone https://toolshed.g2.bx.psu.edu/repos/nick/allele_counts

Changeset 1:49bb46c3a1af (2013-05-24)
Previous changeset 0:28c40f4b7d2b (2013-05-24) Next changeset 2:318fdf77aa54 (2013-05-31)
Commit message:
Uploaded script
added:
allele-counts.py
b
diff -r 28c40f4b7d2b -r 49bb46c3a1af allele-counts.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/allele-counts.py Fri May 24 10:33:35 2013 -0400
[
b'@@ -0,0 +1,377 @@\n+#!/usr/bin/python\n+# This parses the output of Dan\'s "Naive Variant Detector" (previously,\n+# "BAM Coverage"). It was forked from the code of "bam-coverage.py".\n+#\n+# New in this version: default to stdin and stdout, override by using -i and -o\n+#   to specify filenames\n+#\n+# TODO:\n+# - test handling of -c 0 (and -f 0?)\n+# - should it technically handle data lines that start with a \'#\'?\n+import os\n+import sys\n+from optparse import OptionParser\n+\n+COLUMNS = [\'sample\', \'chr\', \'pos\', \'A\', \'C\', \'G\', \'T\', \'coverage\', \'alleles\',\n+  \'major\', \'minor\', \'freq\'] #, \'bias\']\n+CANONICAL_VARIANTS = [\'A\', \'C\', \'G\', \'T\']\n+USAGE = """Usage: cat variants.vcf | %prog [options] > alleles.csv\n+       %prog [options] -i variants.vcf -o alleles.csv"""\n+OPT_DEFAULTS = {\'infile\':\'-\', \'outfile\':\'-\', \'freq_thres\':1.0, \'covg_thres\':100,\n+  \'print_header\':False, \'stdin\':False}\n+DESCRIPTION = """This will parse the VCF output of Dan\'s "Naive Variant Caller" (aka "BAM Coverage") Galaxy tool. For each position reported, it counts the number of reads of each base, determines the major allele, minor allele (second most frequent variant), and number of alleles above a threshold. So currently it only considers SNVs (ACGT), including in the coverage figure. By default it reads from stdin and prints to stdout."""\n+EPILOG = """Requirements:\n+The input VCF must report the variants for each strand.\n+The variants should be case-sensitive (e.g. all capital base letters).\n+Strand bias: Both strands must show the same bases passing the frequency threshold (but not necessarily in the same order). If the site fails this test, the number of alleles is reported as 0."""\n+\n+\n+def get_options(defaults, usage, description=\'\', epilog=\'\'):\n+  """Get options, print usage text."""\n+\n+  parser = OptionParser(usage=usage, description=description, epilog=epilog)\n+\n+  parser.add_option(\'-i\', \'--infile\', dest=\'infile\',\n+    default=defaults.get(\'infile\'),\n+    help=\'Read input VCF data from this file instead of stdin.\')\n+  parser.add_option(\'-o\', \'--outfile\', dest=\'outfile\',\n+    default=defaults.get(\'outfile\'),\n+    help=\'Print output data to this file instead of stdout.\')\n+  parser.add_option(\'-f\', \'--freq-thres\', dest=\'freq_thres\', type=\'float\',\n+    default=defaults.get(\'freq_thres\'),\n+    help=\'Frequency threshold for counting alleles, given in percentage: -f 1 = 1% frequency. Default is %default%.\')\n+  parser.add_option(\'-c\', \'--covg-thres\', dest=\'covg_thres\', type=\'int\',\n+    default=defaults.get(\'covg_thres\'),\n+    help=\'Coverage threshold. Each site must be supported by at least this many reads on each strand. Otherwise the site will not be printed in the output. The default is %default reads per strand.\')\n+  parser.add_option(\'-H\', \'--header\', dest=\'print_header\', action=\'store_const\',\n+    const=not(defaults.get(\'print_header\')), default=defaults.get(\'print_header\'),\n+    help=\'Print header line. This is a #-commented line with the column labels. Off by default.\')\n+  parser.add_option(\'-d\', \'--debug\', dest=\'debug\', action=\'store_true\',\n+    default=False,\n+    help=\'Turn on debug mode. You must also specify a single site to process in a final argument using UCSC coordinate format.\')\n+\n+  (options, args) = parser.parse_args()\n+\n+  # read in positional arguments\n+  arguments = {}\n+  if options.debug:\n+    if len(args) >= 1:\n+      arguments[\'print_loc\'] = args[0]\n+      args.remove(args[0])\n+\n+  return (options, arguments)\n+\n+\n+def main():\n+\n+  (options, args) = get_options(OPT_DEFAULTS, USAGE, DESCRIPTION, EPILOG)\n+\n+  infile = options.infile\n+  outfile = options.outfile\n+  print_header = options.print_header\n+  freq_thres = options.freq_thres / 100.0\n+  covg_thres = options.covg_thres\n+  debug = options.debug\n+\n+  if debug:\n+    print_loc = args.get(\'print_loc\')\n+    if print_loc:\n+      if \':\' in print_loc:\n+        (print_chr, print_pos) = print_loc.split(\':\')\n+      else:\n+        print_pos = print_loc\n+    else:\n+      sys.stderr.write("Warning: No site'..b'age\'] = coverage\n+    try:\n+      sample[\'major\']  = ranked_bases[0][0]\n+    except IndexError, e:\n+      sample[\'major\']  = \'.\'\n+    try:\n+      sample[\'minor\']  = ranked_bases[1][0]\n+      sample[\'freq\']   = ranked_bases[1][1] / float(coverage)\n+    except IndexError, e:\n+      sample[\'minor\']  = \'.\'\n+      sample[\'freq\']   = 0.0\n+\n+    site_summary.append(sample)\n+\n+  return site_summary\n+\n+\n+def print_site(filehandle, site, columns):\n+  """Print the output lines for one site (one per sample).\n+  filehandle must be open."""\n+  for sample in site:\n+    if sample[\'print\']:\n+      fields = [str(sample.get(column)) for column in columns]\n+      filehandle.write(\'\\t\'.join(fields)+"\\n")\n+\n+\n+def get_read_counts(variant_counts, freq_thres, strands=\'+-\', debug=False):\n+  """Count the number of reads for each base, and create a ranked list of\n+  alleles passing the frequency threshold.\n+      Arguments:\n+  variant_counts: Dict of the stranded variants (keys) and their read counts (values).\n+  freq_thres: The frequency threshold each allele needs to pass to be included.\n+  strands: Which strand(s) to count. Can be \'+\', \'-\', or \'+-\' for both (default).\n+  variants: A list of the variants of interest. Other types of variants will not\n+    be included in the returned list. If no list is given, all variants found in\n+    the variant_counts will be used.\n+      Return value:\n+  ranked_bases: A list of the alleles and their read counts. The elements are\n+    tuples (base, read count). The alleles are listed in descending order of\n+    frequency, and only those passing the threshold are included."""\n+\n+  # Get list of all variants from variant_counts list\n+  variants = [variant[1:] for variant in variant_counts]\n+  # deduplicate via a dict\n+  variant_dict = dict((variant, 1) for variant in variants)\n+  variants = variant_dict.keys()\n+\n+  ranked_bases = []\n+  for variant in variants:\n+    reads = 0\n+    for strand in strands:\n+      reads += variant_counts.get(strand+variant, 0)\n+    ranked_bases.append((variant, reads))\n+\n+  # get coverage for the specified strands\n+  coverage = 0\n+  for variant in variant_counts:\n+    if variant[0] in strands:\n+      coverage += variant_counts.get(variant, 0)\n+  # if debug: print "strands: "+strands+\', covg: \'+str(coverage)\n+\n+  if coverage < 1:\n+    return []\n+\n+  # sort the list of alleles by read count\n+  ranked_bases.sort(reverse=True, key=lambda base: base[1])\n+\n+  if debug:\n+    print strands+\' coverage: \'+str(coverage)+\', freq_thres: \'+str(freq_thres)\n+    for base in ranked_bases:\n+      print (base[0]+\': \'+str(base[1])+\'/\'+str(float(coverage))+\' = \'+\n+        str(base[1]/float(coverage)))\n+\n+  # remove bases below the frequency threshold\n+  ranked_bases = [base for base in ranked_bases\n+    if base[1]/float(coverage) >= freq_thres]\n+\n+  return ranked_bases\n+\n+\n+def count_alleles(variant_counts, freq_thres, debug=False):\n+  """Determine how many alleles to report, based on filtering rules.\n+  The current rule determines which bases pass the frequency threshold on each\n+  strand individually, then compares the two sets of bases. If they are the same\n+  (regardless of order), the allele count is the number of bases. Otherwise it\n+  is zero."""\n+  allele_count = 0\n+\n+  alleles_plus  = get_read_counts(variant_counts, freq_thres, debug=debug,\n+    strands=\'+\')\n+  alleles_minus = get_read_counts(variant_counts, freq_thres, debug=debug,\n+    strands=\'-\')\n+\n+  if debug:\n+    print \'+ \'+str(alleles_plus)\n+    print \'- \'+str(alleles_minus)\n+\n+  # check if each strand reports the same set of alleles\n+  alleles_plus_sorted  = sorted([base[0] for base in alleles_plus if base[1]])\n+  alleles_minus_sorted = sorted([base[0] for base in alleles_minus if base[1]])\n+  if alleles_plus_sorted == alleles_minus_sorted:\n+    allele_count = len(alleles_plus)\n+\n+  return allele_count\n+\n+\n+def fail(message):\n+  sys.stderr.write(message+\'\\n\')\n+  sys.exit(1)\n+\n+if __name__ == "__main__":\n+  main()\n\\ No newline at end of file\n'