0
|
1 #!/usr/bin/env python
|
|
2
|
|
3 """
|
|
4 Run kernel PCA using kpca() from R 'kernlab' package
|
|
5
|
|
6 usage: %prog [options]
|
|
7 -i, --input=i: Input file
|
|
8 -o, --output1=o: Summary output
|
|
9 -p, --output2=p: Figures output
|
|
10 -c, --var_cols=c: Variable columns
|
|
11 -k, --kernel=k: Kernel function
|
|
12 -f, --features=f: Number of principal components to return
|
|
13 -s, --sigma=s: sigma
|
|
14 -d, --degree=d: degree
|
|
15 -l, --scale=l: scale
|
|
16 -t, --offset=t: offset
|
|
17 -r, --order=r: order
|
|
18
|
|
19 usage: %prog input output1 output2 var_cols kernel features sigma(or_None) degree(or_None) scale(or_None) offset(or_None) order(or_None)
|
|
20 """
|
|
21
|
|
22 import sys, string
|
|
23 from rpy import *
|
|
24 import numpy
|
|
25 from bx.cookbook import doc_optparse
|
|
26
|
|
27
|
|
28 def stop_err(msg):
|
|
29 sys.stderr.write(msg)
|
|
30 sys.exit()
|
|
31
|
|
32 #Parse Command Line
|
|
33 options, args = doc_optparse.parse( __doc__ )
|
|
34 #{'options= kernel': 'rbfdot', 'var_cols': '1,2,3,4', 'degree': 'None', 'output2': '/afs/bx.psu.edu/home/gua110/workspace/galaxy_bitbucket/database/files/000/dataset_260.dat', 'output1': '/afs/bx.psu.edu/home/gua110/workspace/galaxy_bitbucket/database/files/000/dataset_259.dat', 'scale': 'None', 'offset': 'None', 'input': '/afs/bx.psu.edu/home/gua110/workspace/galaxy_bitbucket/database/files/000/dataset_256.dat', 'sigma': '1.0', 'order': 'None'}
|
|
35
|
|
36 infile = options.input
|
|
37 x_cols = options.var_cols.split(',')
|
|
38 kernel = options.kernel
|
|
39 outfile = options.output1
|
|
40 outfile2 = options.output2
|
|
41 ncomps = int(options.features)
|
|
42 fout = open(outfile,'w')
|
|
43
|
|
44 elems = []
|
|
45 for i, line in enumerate( file ( infile )):
|
|
46 line = line.rstrip('\r\n')
|
|
47 if len( line )>0 and not line.startswith( '#' ):
|
|
48 elems = line.split( '\t' )
|
|
49 break
|
|
50 if i == 30:
|
|
51 break # Hopefully we'll never get here...
|
|
52
|
|
53 if len( elems )<1:
|
|
54 stop_err( "The data in your input dataset is either missing or not formatted properly." )
|
|
55
|
|
56 x_vals = []
|
|
57
|
|
58 for k,col in enumerate(x_cols):
|
|
59 x_cols[k] = int(col)-1
|
|
60 x_vals.append([])
|
|
61
|
|
62 NA = 'NA'
|
|
63 skipped = 0
|
|
64 for ind,line in enumerate( file( infile )):
|
|
65 if line and not line.startswith( '#' ):
|
|
66 try:
|
|
67 fields = line.strip().split("\t")
|
|
68 for k,col in enumerate(x_cols):
|
|
69 try:
|
|
70 xval = float(fields[col])
|
|
71 except:
|
|
72 #xval = r('NA')
|
|
73 xval = NaN#
|
|
74 x_vals[k].append(xval)
|
|
75 except:
|
|
76 skipped += 1
|
|
77
|
|
78 x_vals1 = numpy.asarray(x_vals).transpose()
|
|
79 dat= r.list(array(x_vals1))
|
|
80
|
|
81 print r('library("kernlab")')
|
|
82
|
|
83 try:
|
|
84 r.suppressWarnings(r.library('kernlab'))
|
|
85 except:
|
|
86 stop_err('Missing R library kernlab')
|
|
87
|
|
88 set_default_mode(NO_CONVERSION)
|
|
89 if kernel=="rbfdot" or kernel=="anovadot":
|
|
90 pars = r.list(sigma=float(options.sigma))
|
|
91 elif kernel=="polydot":
|
|
92 pars = r.list(degree=float(options.degree),scale=float(options.scale),offset=float(options.offset))
|
|
93 elif kernel=="tanhdot":
|
|
94 pars = r.list(scale=float(options.scale),offset=float(options.offset))
|
|
95 elif kernel=="besseldot":
|
|
96 pars = r.list(degree=float(options.degree),sigma=float(options.sigma),order=float(options.order))
|
|
97 elif kernel=="anovadot":
|
|
98 pars = r.list(degree=float(options.degree),sigma=float(options.sigma))
|
|
99 else:
|
|
100 pars = r.list()
|
|
101
|
|
102 try:
|
|
103 kpc = r.kpca(x=r.na_exclude(dat), kernel=kernel, kpar=pars, features=ncomps)
|
|
104 except RException, rex:
|
|
105 stop_err("Encountered error while performing kPCA on the input data: %s" %(rex))
|
|
106 set_default_mode(BASIC_CONVERSION)
|
|
107
|
|
108 eig = r.eig(kpc)
|
|
109 pcv = r.pcv(kpc)
|
|
110 rotated = r.rotated(kpc)
|
|
111
|
|
112 comps = eig.keys()
|
|
113 eigv = eig.values()
|
|
114 for i in range(ncomps):
|
|
115 eigv[comps.index('Comp.%s' %(i+1))] = eig.values()[i]
|
|
116
|
|
117 print >>fout, "#Component\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)]))
|
|
118
|
|
119 print >>fout, "#Eigenvalue\t%s" %("\t".join(["%.4g" % el for el in eig.values()]))
|
|
120
|
|
121 print >>fout, "#Principal component vectors\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)]))
|
|
122 for obs,val in enumerate(pcv):
|
|
123 print >>fout, "%s\t%s" %(obs+1, "\t".join(["%.4g" % el for el in val]))
|
|
124
|
|
125 print >>fout, "#Rotated values\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)]))
|
|
126 for obs,val in enumerate(rotated):
|
|
127 print >>fout, "%s\t%s" %(obs+1, "\t".join(["%.4g" % el for el in val]))
|
|
128
|
|
129 r.pdf( outfile2, 8, 8 )
|
|
130 if ncomps != 1:
|
|
131 r.pairs(rotated,labels=r.list(range(1,ncomps+1)),main="Scatterplot of rotated values")
|
|
132 else:
|
|
133 r.plot(rotated, ylab='Comp.1', main="Scatterplot of rotated values")
|
|
134 r.dev_off() |