PageRenderTime 23ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/regVariation/best_regression_subsets.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 90 lines | 76 code | 13 blank | 1 comment | 17 complexity | 23a774896b797f177edb7b97479b92aa MD5 | raw file
  1. #!/usr/bin/env python
  2. from galaxy import eggs
  3. import sys, string
  4. from rpy import *
  5. import numpy
  6. def stop_err(msg):
  7. sys.stderr.write(msg)
  8. sys.exit()
  9. infile = sys.argv[1]
  10. y_col = int(sys.argv[2])-1
  11. x_cols = sys.argv[3].split(',')
  12. outfile = sys.argv[4]
  13. outfile2 = sys.argv[5]
  14. print "Predictor columns: %s; Response column: %d" %(x_cols,y_col+1)
  15. fout = open(outfile,'w')
  16. for i, line in enumerate( file ( infile )):
  17. line = line.rstrip('\r\n')
  18. if len( line )>0 and not line.startswith( '#' ):
  19. elems = line.split( '\t' )
  20. break
  21. if i == 30:
  22. break # Hopefully we'll never get here...
  23. if len( elems )<1:
  24. stop_err( "The data in your input dataset is either missing or not formatted properly." )
  25. y_vals = []
  26. x_vals = []
  27. for k,col in enumerate(x_cols):
  28. x_cols[k] = int(col)-1
  29. x_vals.append([])
  30. NA = 'NA'
  31. for ind,line in enumerate( file( infile )):
  32. if line and not line.startswith( '#' ):
  33. try:
  34. fields = line.split("\t")
  35. try:
  36. yval = float(fields[y_col])
  37. except Exception, ey:
  38. yval = r('NA')
  39. y_vals.append(yval)
  40. for k,col in enumerate(x_cols):
  41. try:
  42. xval = float(fields[col])
  43. except Exception, ex:
  44. xval = r('NA')
  45. x_vals[k].append(xval)
  46. except:
  47. pass
  48. response_term = ""
  49. x_vals1 = numpy.asarray(x_vals).transpose()
  50. dat= r.list(x=array(x_vals1), y=y_vals)
  51. r.library("leaps")
  52. set_default_mode(NO_CONVERSION)
  53. try:
  54. leaps = r.regsubsets(r("y ~ x"), data= r.na_exclude(dat))
  55. except RException, rex:
  56. stop_err("Error performing linear regression on the input data.\nEither the response column or one of the predictor columns contain no numeric values.")
  57. set_default_mode(BASIC_CONVERSION)
  58. summary = r.summary(leaps)
  59. tot = len(x_vals)
  60. pattern = "["
  61. for i in range(tot):
  62. pattern = pattern + 'c' + str(int(x_cols[int(i)]) + 1) + ' '
  63. pattern = pattern.strip() + ']'
  64. print >>fout, "#Vars\t%s\tR-sq\tAdj. R-sq\tC-p\tbic" %(pattern)
  65. for ind,item in enumerate(summary['outmat']):
  66. print >>fout, "%s\t%s\t%s\t%s\t%s\t%s" %(str(item).count('*'), item, summary['rsq'][ind], summary['adjr2'][ind], summary['cp'][ind], summary['bic'][ind])
  67. r.pdf( outfile2, 8, 8 )
  68. r.plot(leaps, scale="Cp", main="Best subsets using Cp Criterion")
  69. r.plot(leaps, scale="r2", main="Best subsets using R-sq Criterion")
  70. r.plot(leaps, scale="adjr2", main="Best subsets using Adjusted R-sq Criterion")
  71. r.plot(leaps, scale="bic", main="Best subsets using bic Criterion")
  72. r.dev_off()