view find_in_reference.py @ 0:fe0327a3ba81

Uploaded
author jjohnson
date Sat, 04 Jan 2014 09:03:57 -0500
parents
children 856033fb26e8
line wrap: on
line source

#!/usr/bin/env python
"""
#
#------------------------------------------------------------------------------
#                         University of Minnesota
#         Copyright 2013, Regents of the University of Minnesota
#------------------------------------------------------------------------------
# Author:
#
#  James E Johnson
#
#------------------------------------------------------------------------------
"""

"""
Takes 2 tabular files as input:  
  1. The file to be filtered 
  2. The reference file 

The string value of selected column of the input file is searched for 
in the string values of the selected column of the reference file.

The intended purpose is to filter a peptide fasta file in tabular format 
by whether those peptide sequences are found in a reference fasta file.

"""
import sys,re,os.path
import tempfile
import optparse
from optparse import OptionParser
import logging


def __main__():
  #Parse Command Line
  parser = optparse.OptionParser()
  parser.add_option( '-i', '--input', dest='input', help='The input file to filter. (Otherwise read from stdin)' )
  parser.add_option( '-r', '--reference', dest='reference', help='The reference file to filter against' )
  parser.add_option( '-o', '--output', dest='output', help='The output file for input lines filtered by reference')
  parser.add_option( '-f', '--filtered', dest='filtered', help='The output file for input lines not in the output')
  parser.add_option('-c','--input_column', dest='input_column', default=None, help='The column for the value in the input file. (first column = 1, default to last column)')
  parser.add_option('-C','--reference_column', dest='reference_column', default=None, help='The column for the value in the reference file. (first column = 1, default to last column)')
  parser.add_option( '-k', '--keep', dest='keep', action="store_true", default=False, help='' )
  parser.add_option( '-d', '--debug', dest='debug', action='store_true', default=False, help='Turn on wrapper debugging to stdout'  )
  (options, args) = parser.parse_args()
  # Input files
  if options.input != None:
    try:
      inputPath = os.path.abspath(options.input)
      inputFile = open(inputPath, 'r')
    except Exception, e:
      print >> sys.stderr, "failed: %s" % e
      exit(2)
  else:
    inputFile = sys.stdin
  # Reference
  if options.reference == None:
      print >> sys.stderr, "failed: reference file is required" 
      exit(2)
  # Output files
  outFile = None
  filteredFile = None
  if options.filtered == None and options.output == None:
    #write to stdout
    outFile = sys.stdout
  else:
    if options.output != None:
      try:
        outPath = os.path.abspath(options.output)
        outFile = open(outPath, 'w')
      except Exception, e:
        print >> sys.stderr, "failed: %s" % e
        exit(3)
    if options.filtered != None:
      try:
        filteredPath = os.path.abspath(options.filtered)
        filteredFile = open(filteredPath, 'w')
      except Exception, e:
        print >> sys.stderr, "failed: %s" % e
        exit(3)
  incol = -1
  if options.input_column and options.input_column > 0:
    incol = int(options.input_column)-1
  refcol = -1
  if options.reference_column and options.reference_column > 0:
    refcol = int(options.reference_column)-1
  refFile = None
  for ln,line in enumerate(inputFile):
    try:
      found = False
      search_string = line.split('\t')[incol].rstrip('\r\n')
      if options.debug: 
        print >> sys.stderr, "search: %s" % (search_string)
      refFile = open(options.reference,'r')
      for tn,fline in enumerate(refFile):
        target_string = fline.split('\t')[refcol]
        if options.debug: 
          print >> sys.stderr, "in: %s %s %s" % (search_string,search_string in target_string,target_string)
        if search_string in target_string:
          found = True
          break
      if found:
        if options.keep == True:
          if outFile:
              outFile.write(line)
        else:
          if filteredFile:
            filteredFile.write(line)
      else:
        if options.keep == True:
          if filteredFile:
            filteredFile.write(line)
        else:
          if outFile:
            outFile.write(line)
    except Exception, e:
      print >> sys.stderr, "failed: Error reading %s - %s" % (options.reference,e)
    finally:
      if refFile:
        refFile.close()

if __name__ == "__main__" : __main__()