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