0
|
1 import os,sys,math,pickle
|
|
2 import random as lrand
|
|
3 import rpy2.robjects as robjects
|
|
4 import argparse
|
|
5 import numpy
|
|
6 #import svmutil
|
|
7
|
|
8 def init():
|
|
9 lrand.seed(1982)
|
|
10 robjects.r('library(splines)')
|
|
11 robjects.r('library(stats4)')
|
|
12 robjects.r('library(survival)')
|
|
13 robjects.r('library(mvtnorm)')
|
|
14 robjects.r('library(modeltools)')
|
|
15 robjects.r('library(coin)')
|
|
16 robjects.r('library(MASS)')
|
|
17
|
|
18 def get_class_means(class_sl,feats):
|
|
19 means = {}
|
|
20 clk = class_sl.keys()
|
|
21 for fk,f in feats.items():
|
|
22 means[fk] = [numpy.mean((f[class_sl[k][0]:class_sl[k][1]])) for k in clk]
|
|
23 return clk,means
|
|
24
|
|
25 def save_res(res,filename):
|
|
26 with open(filename, 'w') as out:
|
|
27 for k,v in res['cls_means'].items():
|
|
28 out.write(k+"\t"+str(math.log(max(max(v),1.0),10.0))+"\t")
|
|
29 if k in res['lda_res_th']:
|
|
30 for i,vv in enumerate(v):
|
|
31 if vv == max(v):
|
|
32 out.write(str(res['cls_means_kord'][i])+"\t")
|
|
33 break
|
|
34 out.write(str(res['lda_res'][k]))
|
|
35 else: out.write("\t")
|
|
36 out.write( "\t" + res['wilcox_res'][k]+"\n")
|
|
37
|
|
38 def load_data(input_file, nnorm = False):
|
|
39
|
|
40 with open(input_file, 'rb') as inputf:
|
|
41 inp = pickle.load(inputf)
|
|
42 if nnorm: return inp['feats'],inp['cls'],inp['class_sl'],inp['subclass_sl'],inp['class_hierarchy'],inp['norm']
|
|
43 else: return inp['feats'],inp['cls'],inp['class_sl'],inp['subclass_sl'],inp['class_hierarchy']
|
|
44
|
|
45 def load_res(input_file):
|
|
46 with open(input_file, 'rb') as inputf:
|
|
47 inp = pickle.load(inputf)
|
|
48 return inp['res'],inp['params'],inp['class_sl'],inp['subclass_sl']
|
|
49
|
|
50
|
|
51 def test_kw_r(cls,feats,p,factors):
|
|
52 robjects.globalenv["y"] = robjects.FloatVector(feats)
|
|
53 for i,f in enumerate(factors):
|
|
54 robjects.globalenv['x'+str(i+1)] = robjects.FactorVector(robjects.StrVector(cls[f]))
|
|
55 fo = "y~x1"
|
|
56 for i,f in enumerate(factors[1:]):
|
|
57 if f == "subclass" and len(set(cls[f])) <= len(set(cls["class"])): continue
|
|
58 if len(set(cls[f])) == len(cls[f]): continue
|
|
59 fo += "+x"+str(i+2)
|
|
60 kw_res = robjects.r('kruskal.test('+fo+',)$p.value')
|
|
61 return float(tuple(kw_res)[0]) < p, float(tuple(kw_res)[0])
|
|
62
|
|
63 def test_rep_wilcoxon_r(sl,cl_hie,feats,th,multiclass_strat,mul_cor,fn,min_c,comp_only_same_subcl,curv=False):
|
|
64 comp_all_sub = not comp_only_same_subcl
|
|
65 tot_ok = 0
|
|
66 alpha_mtc = th
|
|
67 all_diff = []
|
|
68 for pair in [(x,y) for x in cl_hie.keys() for y in cl_hie.keys() if x < y]:
|
|
69 dir_cmp = "not_set" #
|
|
70 l_subcl1, l_subcl2 = (len(cl_hie[pair[0]]), len(cl_hie[pair[1]]))
|
|
71 if mul_cor != 0: alpha_mtc = th*l_subcl1*l_subcl2 if mul_cor == 2 else 1.0-math.pow(1.0-th,l_subcl1*l_subcl2)
|
|
72 ok = 0
|
|
73 curv_sign = 0
|
|
74 first = True
|
|
75 for i,k1 in enumerate(cl_hie[pair[0]]):
|
|
76 br = False
|
|
77 for j,k2 in enumerate(cl_hie[pair[1]]):
|
|
78 if not comp_all_sub and k1[len(pair[0]):] != k2[len(pair[1]):]:
|
|
79 ok += 1
|
|
80 continue
|
|
81 cl1 = feats[sl[k1][0]:sl[k1][1]]
|
|
82 cl2 = feats[sl[k2][0]:sl[k2][1]]
|
|
83 med_comp = False
|
|
84 if len(cl1) < min_c or len(cl2) < min_c:
|
|
85 med_comp = True
|
|
86 sx,sy = numpy.median(cl1),numpy.median(cl2)
|
|
87 if cl1[0] == cl2[0] and len(set(cl1)) == 1 and len(set(cl2)) == 1:
|
|
88 tres, first = False, False
|
|
89 elif not med_comp:
|
|
90 robjects.globalenv["x"] = robjects.FloatVector(cl1+cl2)
|
|
91 robjects.globalenv["y"] = robjects.FactorVector(robjects.StrVector(["a" for a in cl1]+["b" for b in cl2]))
|
|
92 pv = float(robjects.r('pvalue(wilcox_test(x~y,data=data.frame(x,y)))')[0])
|
|
93 tres = pv < alpha_mtc*2.0
|
|
94 if first:
|
|
95 first = False
|
|
96 if not curv and ( med_comp or tres ):
|
|
97 dir_cmp = sx < sy
|
|
98 if sx == sy: br = True
|
|
99 elif curv:
|
|
100 dir_cmp = None
|
|
101 if med_comp or tres:
|
|
102 curv_sign += 1
|
|
103 dir_cmp = sx < sy
|
|
104 else: br = True
|
|
105 elif not curv and med_comp:
|
|
106 if ((sx < sy) != dir_cmp or sx == sy): br = True
|
|
107 elif curv:
|
|
108 if tres and dir_cmp == None:
|
|
109 curv_sign += 1
|
|
110 dir_cmp = sx < sy
|
|
111 if tres and dir_cmp != (sx < sy):
|
|
112 br = True
|
|
113 curv_sign = -1
|
|
114 elif not tres or (sx < sy) != dir_cmp or sx == sy: br = True
|
|
115 if br: break
|
|
116 ok += 1
|
|
117 if br: break
|
|
118 if curv: diff = curv_sign > 0
|
|
119 else: diff = (ok == len(cl_hie[pair[1]])*len(cl_hie[pair[0]])) # or (not comp_all_sub and dir_cmp != "not_set")
|
|
120 if diff: tot_ok += 1
|
|
121 if not diff and multiclass_strat: return False
|
|
122 if diff and not multiclass_strat: all_diff.append(pair)
|
|
123 if not multiclass_strat:
|
|
124 tot_k = len(cl_hie.keys())
|
|
125 for k in cl_hie.keys():
|
|
126 nk = 0
|
|
127 for a in all_diff:
|
|
128 if k in a: nk += 1
|
|
129 if nk == tot_k-1: return True
|
|
130 return False
|
|
131 return True
|
|
132
|
|
133
|
|
134
|
|
135 def contast_within_classes_or_few_per_class(feats,inds,min_cl,ncl):
|
|
136 ff = zip(*[v for n,v in feats.items() if n != 'class'])
|
|
137 cols = [ff[i] for i in inds]
|
|
138 cls = [feats['class'][i] for i in inds]
|
|
139 if len(set(cls)) < ncl:
|
|
140 return True
|
|
141 for c in set(cls):
|
|
142 if cls.count(c) < min_cl:
|
|
143 return True
|
|
144 cols_cl = [x for i,x in enumerate(cols) if cls[i] == c]
|
|
145 for i,col in enumerate(zip(*cols_cl)):
|
|
146 if (len(set(col)) <= min_cl and min_cl > 1) or (min_cl == 1 and len(set(col)) <= 1):
|
|
147 return True
|
|
148 return False
|
|
149
|
|
150 def test_lda_r(cls,feats,cl_sl,boots,fract_sample,lda_th,tol_min,nlogs):
|
|
151 fk = feats.keys()
|
|
152 means = dict([(k,[]) for k in feats.keys()])
|
|
153 feats['class'] = list(cls['class'])
|
|
154 clss = list(set(feats['class']))
|
|
155 for uu,k in enumerate(fk):
|
|
156 if k == 'class': continue
|
|
157 ff = [(feats['class'][i],v) for i,v in enumerate(feats[k])]
|
|
158 for c in clss:
|
|
159 if len(set([float(v[1]) for v in ff if v[0] == c])) > max(float(feats['class'].count(c))*0.5,4): continue
|
|
160 for i,v in enumerate(feats[k]):
|
|
161 if feats['class'][i] == c:
|
|
162 feats[k][i] = math.fabs(feats[k][i] + lrand.normalvariate(0.0,max(feats[k][i]*0.05,0.01)))
|
|
163 rdict = {}
|
|
164 for a,b in feats.items():
|
|
165 if a == 'class' or a == 'subclass' or a == 'subject':
|
|
166 rdict[a] = robjects.StrVector(b)
|
|
167 else: rdict[a] = robjects.FloatVector(b)
|
|
168 robjects.globalenv["d"] = robjects.DataFrame(rdict)
|
|
169 lfk = len(feats[fk[0]])
|
|
170 rfk = int(float(len(feats[fk[0]]))*fract_sample)
|
|
171 f = "class ~ "+fk[0]
|
|
172 for k in fk[1:]: f += " + " + k.strip()
|
|
173 ncl = len(set(cls['class']))
|
|
174 min_cl = int(float(min([cls['class'].count(c) for c in set(cls['class'])]))*fract_sample*fract_sample*0.5)
|
|
175 min_cl = max(min_cl,1)
|
|
176 pairs = [(a,b) for a in set(cls['class']) for b in set(cls['class']) if a > b]
|
|
177
|
|
178 for k in fk:
|
|
179 for i in range(boots):
|
|
180 means[k].append([])
|
|
181 for i in range(boots):
|
|
182 for rtmp in range(1000):
|
|
183 rand_s = [lrand.randint(0,lfk-1) for v in range(rfk)]
|
|
184 if not contast_within_classes_or_few_per_class(feats,rand_s,min_cl,ncl): break
|
|
185 rand_s = [r+1 for r in rand_s]
|
|
186 means[k][i] = []
|
|
187 for p in pairs:
|
|
188 robjects.globalenv["rand_s"] = robjects.IntVector(rand_s)
|
|
189 robjects.globalenv["sub_d"] = robjects.r('d[rand_s,]')
|
|
190 z = robjects.r('z <- suppressWarnings(lda(as.formula('+f+'),data=sub_d,tol='+str(tol_min)+'))')
|
|
191 robjects.r('w <- z$scaling[,1]')
|
|
192 robjects.r('w.unit <- w/sqrt(sum(w^2))')
|
|
193 robjects.r('ss <- sub_d[,-match("class",colnames(sub_d))]')
|
|
194 if 'subclass' in feats:
|
|
195 robjects.r('ss <- ss[,-match("subclass",colnames(ss))]')
|
|
196 if 'subject' in feats:
|
|
197 robjects.r('ss <- ss[,-match("subject",colnames(ss))]')
|
|
198 robjects.r('xy.matrix <- as.matrix(ss)')
|
|
199 robjects.r('LD <- xy.matrix%*%w.unit')
|
|
200 robjects.r('effect.size <- abs(mean(LD[sub_d[,"class"]=="'+p[0]+'"]) - mean(LD[sub_d[,"class"]=="'+p[1]+'"]))')
|
|
201 scal = robjects.r('wfinal <- w.unit * effect.size')
|
|
202 rres = robjects.r('mm <- z$means')
|
|
203 rowns = list(rres.rownames)
|
|
204 lenc = len(list(rres.colnames))
|
|
205 coeff = [abs(float(v)) if not math.isnan(float(v)) else 0.0 for v in scal]
|
|
206 res = dict([(pp,[float(ff) for ff in rres.rx(pp,True)] if pp in rowns else [0.0]*lenc ) for pp in [p[0],p[1]]])
|
|
207 for j,k in enumerate(fk):
|
|
208 gm = abs(res[p[0]][j] - res[p[1]][j])
|
|
209 means[k][i].append((gm+coeff[j])*0.5)
|
|
210 res = {}
|
|
211 for k in fk:
|
|
212 m = max([numpy.mean([means[k][kk][p] for kk in range(boots)]) for p in range(len(pairs))])
|
|
213 res[k] = math.copysign(1.0,m)*math.log(1.0+math.fabs(m),10)
|
|
214 return res,dict([(k,x) for k,x in res.items() if math.fabs(x) > lda_th])
|
|
215
|
|
216
|
|
217 def test_svm(cls,feats,cl_sl,boots,fract_sample,lda_th,tol_min,nsvm):
|
|
218 return NULL
|
|
219 """
|
|
220 fk = feats.keys()
|
|
221 clss = list(set(cls['class']))
|
|
222 y = [clss.index(c)*2-1 for c in list(cls['class'])]
|
|
223 xx = [feats[f] for f in fk]
|
|
224 if nsvm:
|
|
225 maxs = [max(v) for v in xx]
|
|
226 mins = [min(v) for v in xx]
|
|
227 x = [ dict([(i+1,(v-mins[i])/(maxs[i]-mins[i])) for i,v in enumerate(f)]) for f in zip(*xx)]
|
|
228 else: x = [ dict([(i+1,v) for i,v in enumerate(f)]) for f in zip(*xx)]
|
|
229
|
|
230 lfk = len(feats[fk[0]])
|
|
231 rfk = int(float(len(feats[fk[0]]))*fract_sample)
|
|
232 mm = []
|
|
233
|
|
234 best_c = svmutil.svm_ms(y, x, [pow(2.0,i) for i in range(-5,10)],'-t 0 -q')
|
|
235 for i in range(boots):
|
|
236 rand_s = [lrand.randint(0,lfk-1) for v in range(rfk)]
|
|
237 r = svmutil.svm_w([y[yi] for yi in rand_s], [x[xi] for xi in rand_s], best_c,'-t 0 -q')
|
|
238 mm.append(r[:len(fk)])
|
|
239 m = [numpy.mean(v) for v in zip(*mm)]
|
|
240 res = dict([(v,m[i]) for i,v in enumerate(fk)])
|
|
241 return res,dict([(k,x) for k,x in res.items() if math.fabs(x) > lda_th])
|
|
242 """
|