/tools/indels/indel_table.py

https://bitbucket.org/cistrome/cistrome-harvard/ · Python · 113 lines · 83 code · 7 blank · 23 comment · 38 complexity · f5fec1086a2be335914db99eba98fffa MD5 · raw file

  1. #!/usr/bin/env python
  2. """
  3. Combines several interval files containing indels with counts. All input files need to have the same number of columns.
  4. usage: %prog [options] [input3 sum3[ input4 sum4[ input5 sum5[...]]]]
  5. -1, --input1=1: The first input file
  6. -s, --sum1=s: Whether or not to include the totals from first file in overall total
  7. -2, --input2=2: The second input file
  8. -S, --sum2=S: Whether or not to include the totals from second file in overall total
  9. -o, --output=o: The interval output file for the combined files
  10. """
  11. import re, sys
  12. from galaxy import eggs
  13. import pkg_resources; pkg_resources.require( "bx-python" )
  14. from bx.cookbook import doc_optparse
  15. def stop_err( msg ):
  16. sys.stderr.write( '%s\n' % msg )
  17. sys.exit()
  18. def numeric_sort( text1, text2 ):
  19. """
  20. For two items containing space-separated text, compares equivalent pieces
  21. numerically if both numeric or as text otherwise
  22. """
  23. pieces1 = text1.split()
  24. pieces2 = text2.split()
  25. if len( pieces1 ) == 0:
  26. return 1
  27. if len( pieces2 ) == 0:
  28. return -1
  29. for i, pc1 in enumerate( pieces1 ):
  30. if i == len( pieces2 ):
  31. return 1
  32. if not pieces2[i].isdigit():
  33. if pc1.isdigit():
  34. return -1
  35. else:
  36. if pc1 > pieces2[i]:
  37. return 1
  38. elif pc1 < pieces2[i]:
  39. return -1
  40. else:
  41. if not pc1.isdigit():
  42. return 1
  43. else:
  44. if int( pc1 ) > int( pieces2[i] ):
  45. return 1
  46. elif int( pc1 ) < int( pieces2[i] ):
  47. return -1
  48. if i < len( pieces2 ) - 1:
  49. return -1
  50. return 0
  51. def __main__():
  52. # Parse Command Line
  53. options, args = doc_optparse.parse( __doc__ )
  54. inputs = [ options.input1, options.input2 ]
  55. includes = [ options.sum1, options.sum2 ]
  56. inputs.extend( [ a for i, a in enumerate( args ) if i % 2 == 0 ] )
  57. includes.extend( [ a for i, a in enumerate( args ) if i % 2 == 1 ] )
  58. num_cols = 0
  59. counts = {}
  60. # read in data from all files and get total counts
  61. try:
  62. for i, input in enumerate( inputs ):
  63. for line in open( input, 'rb' ):
  64. sp_line = line.strip().split( '\t' )
  65. # set num_cols on first pass
  66. if num_cols == 0:
  67. if len( sp_line ) < 4:
  68. raise Exception, 'There need to be at least 4 columns in the file: Chrom, Start, End, and Count'
  69. num_cols = len( sp_line )
  70. # deal with differing number of columns
  71. elif len( sp_line ) != num_cols:
  72. raise Exception, 'All of the files need to have the same number of columns (current %s != %s of first line)' % ( len( sp_line ), num_cols )
  73. # get actual counts for each indel
  74. indel = '\t'.join( sp_line[:-1] )
  75. try:
  76. count = int( sp_line[-1] )
  77. except ValueError, e:
  78. raise Exception, 'The last column of each file must be numeric, with the count of the number of instances of that indel: %s' % str( e )
  79. # total across all included files
  80. if includes[i] == "true":
  81. try:
  82. counts[ indel ]['tot'] += count
  83. except ( IndexError, KeyError ):
  84. counts[ indel ] = { 'tot': count }
  85. # counts for ith file
  86. counts[ indel ][i] = count
  87. except Exception, e:
  88. stop_err( 'Failed to read all input files:\n%s' % str( e ) )
  89. # output combined results to table file
  90. try:
  91. output = open( options.output, 'wb' )
  92. count_keys = counts.keys()
  93. count_keys.sort( numeric_sort )
  94. for indel in count_keys:
  95. count_out = [ str( counts[ indel ][ 'tot' ] ) ]
  96. for i in range( len( inputs ) ):
  97. try:
  98. count_out.append( str( counts[ indel ][i] ) )
  99. except KeyError:
  100. count_out.append( '0' )
  101. output.write( '%s\t%s\n' % ( indel, '\t'.join( count_out ) ) )
  102. output.close()
  103. except Exception, e:
  104. stop_err( 'Failed to output data: %s' % str( e ) )
  105. if __name__=="__main__": __main__()