Mercurial > repos > iuc > rpy_statistics_collection
comparison pca.py @ 0:ffcdde989859 draft
Uploaded
author | iuc |
---|---|
date | Tue, 29 Jul 2014 06:30:45 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:ffcdde989859 |
---|---|
1 #!/usr/bin/env python | |
2 | |
3 import sys, string | |
4 #from rpy import * | |
5 import rpy2.robjects as robjects | |
6 import rpy2.rlike.container as rlc | |
7 from rpy2.robjects.packages import importr | |
8 r = robjects.r | |
9 grdevices = importr('grDevices') | |
10 import numpy | |
11 | |
12 def stop_err(msg): | |
13 sys.stderr.write(msg) | |
14 sys.exit() | |
15 | |
16 infile = sys.argv[1] | |
17 x_cols = sys.argv[2].split(',') | |
18 method = sys.argv[3] | |
19 outfile = sys.argv[4] | |
20 outfile2 = sys.argv[5] | |
21 | |
22 if method == 'svd': | |
23 scale = center = "FALSE" | |
24 if sys.argv[6] == 'both': | |
25 scale = center = "TRUE" | |
26 elif sys.argv[6] == 'center': | |
27 center = "TRUE" | |
28 elif sys.argv[6] == 'scale': | |
29 scale = "TRUE" | |
30 | |
31 fout = open(outfile,'w') | |
32 elems = [] | |
33 for i, line in enumerate( file ( infile )): | |
34 line = line.rstrip('\r\n') | |
35 if len( line )>0 and not line.startswith( '#' ): | |
36 elems = line.split( '\t' ) | |
37 break | |
38 if i == 30: | |
39 break # Hopefully we'll never get here... | |
40 | |
41 if len( elems )<1: | |
42 stop_err( "The data in your input dataset is either missing or not formatted properly." ) | |
43 | |
44 x_vals = [] | |
45 | |
46 for k,col in enumerate(x_cols): | |
47 x_cols[k] = int(col)-1 | |
48 # x_vals.append([]) | |
49 | |
50 NA = 'NA' | |
51 skipped = 0 | |
52 for ind,line in enumerate( file( infile )): | |
53 if line and not line.startswith( '#' ): | |
54 try: | |
55 fields = line.strip().split("\t") | |
56 valid_line = True | |
57 for k,col in enumerate(x_cols): | |
58 try: | |
59 xval = float(fields[col]) | |
60 except: | |
61 skipped += 1 | |
62 valid_line = False | |
63 break | |
64 if valid_line: | |
65 for k,col in enumerate(x_cols): | |
66 xval = float(fields[col]) | |
67 #x_vals[k].append(xval) | |
68 x_vals.append(xval) | |
69 except: | |
70 skipped += 1 | |
71 | |
72 #x_vals1 = numpy.asarray(x_vals).transpose() | |
73 #dat= r.list(array(x_vals1)) | |
74 dat = r['matrix'](robjects.FloatVector(x_vals),ncol=len(x_cols),byrow=True) | |
75 | |
76 #set_default_mode(NO_CONVERSION) | |
77 try: | |
78 if method == "cor": | |
79 #pc = r.princomp(r.na_exclude(dat), cor = r("TRUE")) | |
80 pc = r.princomp(r['na.exclude'](dat), cor = r("TRUE")) | |
81 elif method == "cov": | |
82 #pc = r.princomp(r.na_exclude(dat), cor = r("FALSE")) | |
83 pc = r.princomp(r['na.exclude'](dat), cor = r("FALSE")) | |
84 elif method=="svd": | |
85 #pc = r.prcomp(r.na_exclude(dat), center = r(center), scale = r(scale)) | |
86 pc = r.prcomp(r['na.exclude'](dat), center = r(center), scale = r(scale)) | |
87 #except RException, rex: | |
88 except Exception, rex: # need to find rpy2 RException | |
89 stop_err("Encountered error while performing PCA on the input data: %s" %(rex)) | |
90 | |
91 #set_default_mode(BASIC_CONVERSION) | |
92 summary = r.summary(pc, loadings="TRUE") | |
93 #ncomps = len(summary['sdev']) | |
94 ncomps = len(summary.rx2('sdev')) | |
95 | |
96 #if type(summary['sdev']) == type({}): | |
97 # comps_unsorted = summary['sdev'].keys() | |
98 # comps=[] | |
99 # sd = summary['sdev'].values() | |
100 # for i in range(ncomps): | |
101 # sd[i] = summary['sdev'].values()[comps_unsorted.index('Comp.%s' %(i+1))] | |
102 # comps.append('Comp.%s' %(i+1)) | |
103 #elif type(summary['sdev']) == type([]): | |
104 # comps=[] | |
105 # for i in range(ncomps): | |
106 # comps.append('Comp.%s' %(i+1)) | |
107 # sd = summary['sdev'] | |
108 | |
109 comps=[] | |
110 for i in range(ncomps): | |
111 comps.append('Comp.%s' %(i+1)) | |
112 sd = summary.rx2('sdev') | |
113 | |
114 print >>fout, "#Component\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)])) | |
115 #print >>fout, "#Std. deviation\t%s" %("\t".join(["%.4g" % el for el in sd])) | |
116 print >>fout, "#Std. deviation\t%s" %("\t".join(["%.4g" % el for el in sd])) | |
117 total_var = 0 | |
118 vars = [] | |
119 for s in sd: | |
120 var = s*s | |
121 total_var += var | |
122 vars.append(var) | |
123 for i,var in enumerate(vars): | |
124 vars[i] = vars[i]/total_var | |
125 | |
126 print >>fout, "#Proportion of variance explained\t%s" %("\t".join(["%.4g" % el for el in vars])) | |
127 | |
128 print >>fout, "#Loadings\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)])) | |
129 xcolnames = ["c%d" %(el+1) for el in x_cols] | |
130 #if 'loadings' in summary: #in case of princomp | |
131 if 'loadings' in summary.names: #in case of princomp | |
132 loadings = 'loadings' | |
133 #elif 'rotation' in summary: #in case of prcomp | |
134 elif 'rotation' in summary.names: #in case of prcomp | |
135 loadings = 'rotation' | |
136 #for i,val in enumerate(summary[loadings]): | |
137 # print >>fout, "%s\t%s" %(xcolnames[i], "\t".join(["%.4g" % el for el in val])) | |
138 vm = summary.rx2(loadings) | |
139 for i in range(vm.nrow): | |
140 vals = [] | |
141 for j in range(vm.ncol): | |
142 vals.append("%.4g" % vm.rx2(i+1,j+1)[0]) | |
143 print >>fout, "%s\t%s" %(xcolnames[i], "\t".join(vals)) | |
144 | |
145 print >>fout, "#Scores\t%s" %("\t".join(["%s" % el for el in range(1,ncomps+1)])) | |
146 #if 'scores' in summary: #in case of princomp | |
147 if 'scores' in summary.names: #in case of princomp | |
148 scores = 'scores' | |
149 #elif 'x' in summary: #in case of prcomp | |
150 elif 'x' in summary.names: #in case of prcomp | |
151 scores = 'x' | |
152 #for obs,sc in enumerate(summary[scores]): | |
153 # print >>fout, "%s\t%s" %(obs+1, "\t".join(["%.4g" % el for el in sc])) | |
154 vm = summary.rx2(scores) | |
155 for i in range(vm.nrow): | |
156 vals = [] | |
157 for j in range(vm.ncol): | |
158 vals.append("%.4g" % vm.rx2(i+1,j+1)[0]) | |
159 print >>fout, "%s\t%s" %(i+1, "\t".join(vals)) | |
160 r.pdf( outfile2, 8, 8 ) | |
161 r.biplot(pc) | |
162 #r.dev_off() | |
163 grdevices.dev_off() | |
164 |