root/galaxy-central/tools/multivariate_stats/kpca.py

リビジョン 2, 4.4 KB (コミッタ: hatakeyama, 14 年 前)

import galaxy-central

行番号 
1#!/usr/bin/env python
2
3"""
4Run kernel PCA using kpca() from R 'kernlab' package
5
6usage: %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
19usage: %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
22from galaxy import eggs
23import sys, string
24from rpy import *
25import numpy
26import pkg_resources; pkg_resources.require( "bx-python" )
27from bx.cookbook import doc_optparse
28
29
30def stop_err(msg):
31    sys.stderr.write(msg)
32    sys.exit()
33
34#Parse Command Line
35options, args = doc_optparse.parse( __doc__ )
36#{'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'}
37
38infile = options.input
39x_cols = options.var_cols.split(',')
40kernel = options.kernel
41outfile = options.output1
42outfile2 = options.output2
43ncomps = int(options.features)
44fout = open(outfile,'w')
45
46elems = []
47for i, line in enumerate( file ( infile )):
48    line = line.rstrip('\r\n')
49    if len( line )>0 and not line.startswith( '#' ):
50        elems = line.split( '\t' )
51        break
52    if i == 30:
53        break # Hopefully we'll never get here...
54
55if len( elems )<1:
56    stop_err( "The data in your input dataset is either missing or not formatted properly." )
57
58x_vals = []
59
60for k,col in enumerate(x_cols):
61    x_cols[k] = int(col)-1
62    x_vals.append([])
63
64NA = 'NA'
65skipped = 0
66for ind,line in enumerate( file( infile )):
67    if line and not line.startswith( '#' ):
68        try:
69            fields = line.strip().split("\t")
70            for k,col in enumerate(x_cols):
71                try:
72                    xval = float(fields[col])
73                except:
74                    #xval = r('NA')
75                    xval = NaN#
76                x_vals[k].append(xval)
77        except:
78            skipped += 1
79
80x_vals1 = numpy.asarray(x_vals).transpose()
81dat= r.list(array(x_vals1))
82
83try:
84    r.suppressWarnings(r.library('kernlab'))
85except:
86    stop_err('Missing R library kernlab')
87           
88set_default_mode(NO_CONVERSION)
89if kernel=="rbfdot" or kernel=="anovadot":
90    pars = r.list(sigma=float(options.sigma))
91elif kernel=="polydot":
92    pars = r.list(degree=float(options.degree),scale=float(options.scale),offset=float(options.offset))
93elif kernel=="tanhdot":
94    pars = r.list(scale=float(options.scale),offset=float(options.offset))
95elif kernel=="besseldot":
96    pars = r.list(degree=float(options.degree),sigma=float(options.sigma),order=float(options.order))
97elif kernel=="anovadot":
98    pars = r.list(degree=float(options.degree),sigma=float(options.sigma))
99else:
100    pars = rlist()
101   
102try:
103    kpc = r.kpca(x=r.na_exclude(dat), kernel=kernel, kpar=pars, features=ncomps)
104except RException, rex:
105    stop_err("Encountered error while performing kPCA on the input data: %s" %(rex))
106set_default_mode(BASIC_CONVERSION)
107   
108eig = r.eig(kpc)
109pcv = r.pcv(kpc)
110rotated = r.rotated(kpc)
111
112comps = eig.keys()
113eigv = eig.values()
114for i in range(ncomps):
115    eigv[comps.index('Comp.%s' %(i+1))] = eig.values()[i]
116
117print >>fout, "#Component\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)]))
118
119print >>fout, "#Eigenvalue\t%s" %("\t".join(["%.4g" % el for el in eig.values()]))
120   
121print >>fout, "#Principal component vectors\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)]))
122for obs,val in enumerate(pcv):
123    print >>fout, "%s\t%s" %(obs+1, "\t".join(["%.4g" % el for el in val]))
124
125print >>fout, "#Rotated values\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)]))
126for obs,val in enumerate(rotated):
127    print >>fout, "%s\t%s" %(obs+1, "\t".join(["%.4g" % el for el in val]))
128
129r.pdf( outfile2, 8, 8 )
130if ncomps != 1:
131    r.pairs(rotated,labels=r.list(range(1,ncomps+1)),main="Scatterplot of rotated values")
132else:
133    r.plot(rotated, ylab='Comp.1', main="Scatterplot of rotated values")
134r.dev_off()
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。