-
Notifications
You must be signed in to change notification settings - Fork 1
/
rpyd2.py
executable file
·2063 lines (1641 loc) · 51.6 KB
/
rpyd2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
RpyD2
depends:
rpy2 <http://rpy.sourceforge.net/rpy2.html>
"""
from __future__ import division
from rpy2 import robjects as ro
r = ro.r
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')
rprint = ro.globalenv.get("print")
class InputNotRecognizedError(Exception):
pass
def load(fn,toprint=True):
import pickle
if toprint: print ">> loading:",fn,"...",
d,df=pickle.load(open(fn))
r=RpyD2([])
r.__dict__=d
for k,v in d.items():
setattr(r,k,v)
r.df=ro.DataFrame(df)
print "done."
return r
def from_csv(fn,sep='\t',lb='\n',header=True):
t=open(fn).read()
header=[]
ld=[]
for ln in t.split(lb):
if not header: header=ln.split(sep); continue
d={}
lndat=ln.split(sep)
if len(lndat)!=len(header): continue
for i,x in enumerate(lndat):
if x[0].isdigit():
if '.' in x:
x=float(x)
else:
x=int(x)
d[header[i]]=x
ld.append(d)
return RpyD2(ld)
def write(fn,data,toprint=False,join_line='\n',join_cell='\t'):
if type(data)==type([]):
o=""
for x in data:
if type(x)==type([]):
z=[]
for y in x:
if type(y)==type(u''):
y=y.encode('utf-8')
z+=[y]
x=z
line=join_cell.join(x)
else:
try:
line=str(x)
except UnicodeEncodeError:
line=x.encode('utf-8')
line=line.replace('\r','').replace('\n','')
o+=line+join_line
else:
o=str(data)
of = open(fn,'w')
of.write(o)
of.close()
if toprint:
print ">> saved: "+fn
def signcorr(samplesize):
import numpy as np
return 1.96/np.sqrt(samplesize-3)
#
#
# def mergeDL(dl1,dl2,rstyle=True):
# for k in dl2:
# kk=k
# if rstyle:
# if kk[0].isdigit(): kk='X'+kk
# kk=kk.replace("'",".")
# kk=kk.replace("-",".")
# kk=kk.replace(" ",".")
#
# try:
# dl1[kk].extend(dl2[k])
# except KeyError:
# print(">> error merging DLs: '"+kk+"' not found in original DL")
# continue
# return dl1
#
def rkey(kk):
if kk[0].isdigit(): kk='X'+kk
kk=kk.replace("'",".")
kk=kk.replace("-",".")
kk=kk.replace(" ",".")
kk=kk.replace(",",".")
return kk
def mergeDL(dl1,dl2,rstyle=True):
dl={}
for k in dl1:
dl[k]=[]
dl[k].extend(dl1[k])
for k in dl2:
kk=k
if rstyle:
kk=rkey(kk)
try:
dl[kk].extend(dl2[k])
except KeyError:
print(">> error merging DLs: '"+kk+"' not found in original DL")
continue
return dl
def printDL(dl):
for k in dl:
print k, len(dl[k]), dl[k][0], "..."
print
def ndian(numericValues,n=2):
theValues = sorted(numericValues)
if len(theValues) % n == 1:
return theValues[int((len(theValues)+1)/n)-1]
else:
lower = theValues[int(len(theValues)/n)-1]
upper = theValues[int(len(theValues)/n)]
return (float(lower + upper)) / n
def median(numericValues):
try:
import numpy as np
return np.median(numericValues)
except:
return ndian(numericValues,n=2)
def lowerq(numericValues):
return ndian(numericValues,n=4)
def upperq(numericValues):
return ndian(numericValues,n=(4/3))
def upperthird(numericValues):
return ndian(numericValues,n=(3/2))
def upperthirdfifth(numericValues):
return ndian(numericValues,n=(5/3))
def lowereighth(numericValues):
return ndian(numericValues,n=8)
def lowerfifth(numericValues):
return ndian(numericValues,n=5)
def lowertenth(numericValues):
return ndian(numericValues,n=10)
def mean(l):
return mean_stdev(l)[0]
def correlate(x,y):
from statlib.stats import pearsonr
return pearsonr(x,y)
def str_polyfunc(coefficients):
frmla=[]
import decimal
deg=len(coefficients)-1
for i in range(len(coefficients)):
term=str(decimal.Decimal(str(coefficients[i])))
power=deg-i
if power:
term+='*x^'+str(deg-i)
frmla+=[ term ]
frmla=' + '.join(frmla)
return frmla
def make_polyfunc(coefficients):
l=[(coefficients[i],(len(coefficients)-1-i)) for i in range(len(coefficients))]
return lambda x: sum([t[0]*(x**t[1]) for t in l])
class RpyD2():
def __init__(self,input,**kwargs):
"""
input is your data, which can be in the following forms:
1. LD (List of Dictionaries)
[ {'hair':'blonde','eyes':'blue'}, {'hair':'black','eyes':'green'}, ... ]
2. DL (Dictionary of Lists)
{ 'hair':['blonde','blue'], 'eyes':['blue','green] }
3. Rpy2 DataFrame
4. Another RpyD2
Keyword arguments will override the following default options:
self.cols=None # specify which columns to build from
self.rownamecol=None # specify a column name from which row names should be used
self.allcols=False # if False, columns limited to those shared among all rows;
if True, all columns are chosen;
if a positive integer N, columns limited to the 'top' N columns,
where columns are compared numerically by:
self.trimbyVariance=True # if trimbyVariance==True, sum of absolute value of Z-scores across column
otherwise, sum of scores across column
self.rank=True # if rank==True, append 'r'+ranknum to the top N columns
self.zero=0.0 # if allcols is True or an integer, what should empty cells be populated with?
self.z=False # if True, Z-score all quantitative columns
self.factor=True # if True, treat strings as factors
self.onlyQuant=False # if True, only build quantitative columns
self.onlyCat=False # if True, only build categorical (string) columns
self.toprint=True # if True, print R objects using R's summary() before returning them
self.colkey={}
self.rowcols=[] # these will be kept even if allcols is set to a number, trimming columns
"""
## set defaults
self.cols=None
self.rownamecol=None
self.allcols=False
self.trimbyVariance=True
self.rank=True
self.factor=True
self.z=False
self.zero=0.0
self.onlyQuant=False
self.onlyCat=False
self.rownames=[]
self.toprint=True
self.colkey={}
self.rowcols=[]
## override defaults with
for k,v in kwargs.items():
setattr(self,k,v)
## double override with non-keyword
#self.input=input
self.df=None
self.nrow=0
self.ncol=0
self._quantv=None
self._quantvz=None
self._tv=None
self._subv={'cols':{},'rows':{},'cols_rows':{}}
self._groupv={}
if not input: return
if not len(input): return
if type(input)==type([]) and type(input[0])==type({}):
self._gen_LD(input)
elif type(input)==type({}) and type(input.values()[0]==type([])):
self._gen_DL(input)
elif type(input)==type(self):
self._gen_self(input)
elif type(input)==type(ro.DataFrame({})):
self._gen_DF(input)
else:
raise InputNotRecognizedError("Cannot recognize input of type "+type(input))
def __str__(self):
return self.df.__str__()
def __repr__(self):
loc=object.__repr__(self)[:-1].split(" at ")[1]
return "<RpyD2 @ "+loc+" storing a "+str(self.nrow)+"x"+str(self.ncol)+" "+self.df.__repr__()[1:-1].replace(" - "," @ ")+">"
def col(self,colname):
"""Return column 'colname', where colname can be either a string name or an integer position (starting at 0)."""
try:
if type(colname)==type(unicode()): colname=colname.encode('utf-8')
if type(colname)==type(''):
colnum=self.cols.index(colname)
else:
colnum=colname
c=self.df[colnum]
if type(c)==type(ro.FactorVector([])):
return list([c.levels[c[item_i] - 1] for item_i in range(len(c))])
else:
return list(c)
except KeyError:
return
def row(self,rowname):
"""Return row 'rowname', where rowname can be either a string name or an integer position (starting at 0)."""
try:
if type(rowname)==type(''):
rownum=self.rows.index(rowname)
else:
rownum=rowname
l=[]
for colnum in range(self.ncol):
c=self.df[colnum]
if type(c)==type(ro.FactorVector([])):
l+=[c.levels[c[rownum] - 1]]
else:
l+=[c[rownum]]
return l
except:
return
def t(self):
if not self._tv:
self._tv=RpyD2(r['as.data.frame'](r['t'](self.df)))
self._tv.rownames=list(self._tv.df.rownames)
return self._tv
def toLD(self,rownamecol=False):
ld=[]
if rownamecol and type(rownamecol)!=type(''): rownamecol='xkey'
for row in self.rows:
d=dict(zip(self.cols, self.row(row)))
if rownamecol: d[rownamecol]=row
ld.append(d)
return ld
def toDL(self,cols=None,rows=None,rownamecol=False):
"""
Return a dictionary of lists representation of self:
{'col0':[row0val,row1val,...],
'col1':[row1val,row2val,...],
...}
If rows is a non-empty list, return only these rows.
If cols is a non-empty list, return only these cols.
If both are non-empty, return only these rows and only these cols.
"""
dl={}
if rownamecol and type(rownamecol)!=type(''):
rownamecol='rownamecol'
if not cols and not rows:
for i in range(self.ncol):
col=self.col(i)
colname=self.cols[i]
dl[colname]=col
if rownamecol:
dl[rownamecol]=list(self.df.rownames)
elif cols and not rows:
for col in cols:
dl[col]=self.col(col)
if rownamecol:
dl[rownamecol]=list(self.df.rownames)
elif cols and rows:
for col in cols:
dl[col]=[]
colnum=self.cols.index(col)
for row in rows:
rowdat=self.row(row)
dl[col].append(rowdat[colnum])
if rownamecol:
dl[rownamecol]=[]
for row in rows:
if type(row)==type(''):
dl[rownamecol].append(row)
else:
dl[rownamecol].append(self.rows[row])
elif rows and not cols:
for col in self.cols:
dl[col]=[]
colnum=self.cols.index(col)
for row in rows:
rowdat=self.row(row)
dl[col].append(rowdat[colnum])
if rownamecol:
dl[rownamecol]=[]
for row in rows:
if type(row)==type(''):
dl[rownamecol].append(row)
else:
dl[rownamecol].append(str(self.rows[row]))
return dl
def save(self,fn=None):
if not fn:
import time
fn=".".join( [ 'rpyd2', time.strftime('%Y%m%d.%H%M.%S', time.gmtime()) , 'pickle' ] )
import pickle
pickle.dump((self.__dict__,self.df),open(fn,'wb'))
print ">> saved:",fn
def get(self,col=None,row=None):
if col and row:
return self.col(col)[self.rows.index(row)]
elif col and not row:
return self.col(col)
elif row and not col:
return self.row(row)
elif not col and not row:
return self
def sub(self,cols=[],rows=[],removeCommon=True):
"""Return an RpyD2 from self, with only those rows and/or columns as specified."""
if cols and not rows:
if cols==self.cols:
return self
keytup=('cols',tuple(sorted(cols)))
elif cols and rows:
keytup=('cols',tuple( tuple(sorted(cols)), tuple(sorted(rows)) ))
elif rows and not cols:
keytup=('rows',tuple(sorted(rows)))
elif not cols and not rows:
return self
try:
return self._subv[keytup[0]][keytup[1]]
except KeyError:
dl=self.toDL(cols,rows,rownamecol=True)
dlkeys=[k for k in dl.keys() if k!='rownamecol' and k and not k.startswith('index_') and not k.startswith('row_')]
if len(dlkeys)>1:
dlkey=dlkeys[0]
from difflib import SequenceMatcher as SM
for dlkey2 in dlkeys[1:]:
s=SM(None,dlkey,dlkey2)
match=sorted(s.get_matching_blocks(),key=lambda m: -m.size)[0]
dlkey=dlkey2[match.b:match.b+match.size]
dl=dict(( (k.replace(dlkey,'') if k.replace(dlkey,'') else k),v) for k,v in dl.items())
m=RpyD2(dl,rownamecol='rownamecol')
self._subv[keytup[0]][keytup[1]]=m
return m
def q(self,z=False):
"""Return a version of self of only quantitative columns"""
if self.onlyQuant:
return self
if not z and self._quantv!=None:
return self._quantv
elif z and self._quantvz!=None:
return self._quantvz
r=RpyD2(self.toDL(),rownames=self.rownames,onlyQuant=True,z=z)
if z:
self._quantvz=r
else:
self._quantv=r
return r
def _is_quant_num(self,num):
try:
num+0
return True
except:
return False
def _is_quant(self,l,FalseAtNone=True):
if not FalseAtNone:
return self._is_quant_num(l[0])
else:
returnVal=True
for x in l:
if not self._is_quant_num(x):
returnVal=False
break
return returnVal
def _gen_DL(self,dl):
self.origin='dl'
if self.rownamecol:
self.rownames=dl[self.rownamecol]
del dl[self.rownamecol]
self._boot_DL(dl)
def _gen_LD(self,ld):
self.origin='ld'
dd={}
if not self.cols:
self.cols=getCols(ld,self.allcols,self.rownamecol)
if type(self.allcols)==type(2):
self.cols=trimCols(ld,self.cols,self.allcols,byVariance=self.trimbyVariance,rowcols=self.rowcols)
for i in range(len(self.cols)):
k=self.cols[i]
dd[k]=[]
if self.rownamecol: self.rownames=[]
for x in ld:
if self.rownamecol: self.rownames.append(x[self.rownamecol])
for k in self.cols:
try:
value=x[k]
except KeyError:
try:
value=x[".".join(k.split(".")[1:])]
except:
value=self.zero
dd[k].append(value)
self._boot_DL(dd)
def _gen_DF(self,df):
self._set_DF(df)
def _boot_DL(self,dl,rownames=None):
dd={}
import datetime
for k,v in dl.items():
if type(k)==type(unicode()):
k=str(k.encode('utf-8','replace'))
#print [type(vv) for vv in v]
#if type(v[0])==type(''):
if isinstance(v[0],basestring):
if self.onlyQuant: continue
if type(v[0])==type(unicode()): v = [vx.encode('utf-8','replace') for vx in v]
dd[k]=ro.StrVector(v)
if self.factor:
dd[k]=ro.FactorVector(dd[k])
elif isinstance(v[0],datetime.datetime):
import time
dd[k]=ro.vectors.POSIXlt( [ time.struct_time([vv.year,vv.month,vv.day,0,0,0,0,0,0]) for vv in v] )
else:
if self.z:
v=zfy(v)
try:
if not '.' in str(v[0]):
dd[k]=ro.IntVector(v)
else:
dd[k]=ro.FloatVector(v)
except:
continue
df=ro.DataFrame(dd)
self._set_DF(df)
def _set_DF(self,df):
if self.rownames:
df.rownames=ro.FactorVector(self.rownames)
#del self.rownames
self.df=df
self.nrow=self.df.nrow
self.ncol=self.df.ncol
self.cols=list(self.df.colnames)
self.rows=list(self.df.rownames)
def rankcols(self,byVariance=False,returnSums=False,rankfunc=None):
ranks={}
for colname in self.cols:
col=self.col(colname)
if byVariance:
rankcol=sum([abs(x) for x in zfy(col)])
else:
if not rankfunc:
rankcol=sum(col)
else:
rankcol=rankfunc(col)
ranks[colname]=rankcol
keys=sorted(ranks,key=lambda item: -ranks[item])
if not returnSums:
return keys
return (keys,[ranks[k] for k in keys])
def plots(self,x=None,y=None,n=1):
if not y: y=self.rankcols()
if not n or n==1:
if type(y)==type([]):
for ykey in y:
self.plot(x=x,y=y)
else:
self.plot(x=x,y=y)
return
# else, stepwise
a=None
lc=len(str(self.ncol))
#rg=self.group(x=x,ys=y)
for b in range(0,len(y),n):
if a==None:
a=b
continue
print a,b
sub=self.group(ys=y[a:b],x=x)
#sub=self.sub_where(rows={'y_type':y[a:b]})
abk=str(a).zfill(lc)+'-'+str(b).zfill(lc)
sub.plot(fn='plots.'+abk+'.'+self._get_fn(x,"+".join(y[a:b])) +'.png', x='row',y='y',col='y_type', group='y_type', smooth=False, line=True)
a=b
return
def _kwd(self,kwd,**kwarg):
for k,v in kwarg.items():
if not k in kwd:
kwd[k]=v
return kwd
def plot(self, fn=None, x=None, y=None, **opt):
opt=self._kwd(opt,col=None, group=None, w=1100, h=800, size=2, smooth=False, point=True, jitter=False, boxplot=False, boxplot2=False, title=False, flip=False, se=False, density=False, line=False, bar=False, xlab_size=14, ylab_size=14, position='identity', xlab_angle=0, logX=False, logY=False, area=False, text=False, text_size=3, text_angle=45, pdf=False, freqpoly=False)
if opt['jitter']: opt['position']='jitter'
#df=self.df
grdevices = importr('grDevices')
import rpy2.robjects.lib.ggplot2 as ggplot2
#print hasattr(self.df,'x')
if not x:
if self.df.rownames[0].isdigit():
self.df.x=ro.FloatVector([float(xx) for xx in list(self.df.rownames)])
else:
self.df.x=self.df.rownames
x='x'
#self.df.y = self.df[self.df.colnames.index(y)]
#print self.df.y
gp = ggplot2.ggplot(self.df)
pp = gp
if x and y:
if opt['col'] and opt['group']:
pp+=ggplot2.aes_string(x=x, y=y,col=opt['col'],group=opt['group'])
elif opt['col']:
pp+=ggplot2.aes_string(x=x, y=y,col=opt['col'])
elif opt['group']:
pp+=ggplot2.aes_string(x=x, y=y,group=opt['group'])
else:
pp+=ggplot2.aes_string(x=x, y=y)
else:
if not opt['density'] and not opt['bar'] and not opt['freqpoly']:
self._call_remaining('plot',fn=fn,x=x,y=y,**opt)
return
if type(fn)!=type(''): fn=''
if not fn.endswith('.png'):
fn+='plot.'+self._get_fn(x,y)+'.png'
if opt['text']:
if opt['col']:
pp+=ggplot2.geom_text(ggplot2.aes_string(label=opt['text'],colour=opt['col']),angle=opt['text_angle'],size=opt['text_size'])
else:
pp+=ggplot2.geom_text(ggplot2.aes_string(label=opt['text']),angle=opt['text_angle'],size=opt['text_size'])
if opt['boxplot']:
if opt['col']:
pp+=ggplot2.geom_boxplot(ggplot2.aes_string(fill=opt['col']),color='blue',position=opt['position'])
else:
pp+=ggplot2.geom_boxplot(color='blue')
if opt['point']:
if opt['col']:
pp+=ggplot2.geom_point(ggplot2.aes_string(fill=opt['col'],col=opt['col']),size=opt['size'],position=opt['position'])
else:
pp+=ggplot2.geom_point(size=opt['size'],position=opt['position'])
if opt['boxplot2']:
if opt['col']:
pp+=ggplot2.geom_boxplot(ggplot2.aes_string(fill=opt['col']),color='blue',outlier_colour="NA")
else:
pp+=ggplot2.geom_boxplot(color='blue')
if opt['smooth']:
if opt['smooth']=='lm':
if opt['col']:
pp+=ggplot2.stat_smooth(ggplot2.aes_string(col=opt['col']),size=1,method='lm',se=opt['se'])
else:
pp+=ggplot2.stat_smooth(col='blue',size=1,method='lm',se=opt['se'])
else:
if opt['col']:
pp+=ggplot2.stat_smooth(ggplot2.aes_string(col=opt['col']),size=1,se=opt['se'])
else:
pp+=ggplot2.stat_smooth(col='blue',size=1,se=opt['se'])
if opt['density']:
if opt['density']=='h':
if opt['col'] and opt['group']:
pp+=ggplot2.geom_histogram(ggplot2.aes_string(x=x,y='..count..',group=opt['group'],fill=opt['col'],col=opt['col'],alpha=0.2))
else:
pp+=ggplot2.geom_histogram(ggplot2.aes_string(x=x,y='..scaled..'))
else:
if opt['col']:
pp+=ggplot2.geom_density(ggplot2.aes_string(x=x,y='..scaled..',fill=opt['col'],col=opt['col'],alpha=0.2))
else:
pp+=ggplot2.geom_density(ggplot2.aes_string(x=x,y='..count..'))
if opt['line']:
pp+=ggplot2.geom_line(position=opt['position'])
if opt['area']:
pp+=ggplot2.geom_area(ggplot2.aes_string(x=x,y=y,fill=opt['col'],col=opt['col']))
if opt['bar']:
if y:
if opt['col']:
pp+=ggplot2.geom_bar(ggplot2.aes_string(x=x,y=y,fill=opt['col']),position='dodge',stat='identity')
else:
pp+=ggplot2.geom_bar(ggplot2.aes_string(x=x,y=y),position='dodge',stat='identity')
else:
if opt['col']:
pp+=ggplot2.geom_bar(ggplot2.aes_string(x=x,fill=opt['col']),position='dodge')
else:
pp+=ggplot2.geom_bar(ggplot2.aes_string(x=x),position='dodge')
if opt['freqpoly']:
if opt['col'] and opt['group']:
pp+=ggplot2.geom_freqpoly(ggplot2.aes_string(x=x,col=opt['col'],group=opt['group']),position=opt['position'])
else:
pp+=ggplot2.geom_bar(ggplot2.aes_string(x=x),position=opt['position'])
if opt['logX']:
pp+=ggplot2.scale_x_log10()
if opt['logY']:
pp+=ggplot2.scale_y_log10()
if not opt['title']:
opt['title']=fn.split("/")[-1]
pp+=ggplot2.opts(**{'title' : opt['title'], 'axis.text.x': ggplot2.theme_text(size=opt['xlab_size'],angle=opt['xlab_angle']), 'axis.text.y': ggplot2.theme_text(size=opt['ylab_size'],hjust=1)} )
#pp+=ggplot2.scale_colour_brewer(palette="Set1")
pp+=ggplot2.scale_colour_hue()
if opt['flip']:
pp+=ggplot2.coord_flip()
if opt['pdf']:
fn=fn.replace('.png','.pdf')
grdevices.pdf(file=fn, width=opt['w'], height=opt['h'])
else:
grdevices.png(file=fn, width=opt['w'], height=opt['h'])
pp.plot()
grdevices.dev_off()
print ">> saved: "+fn
def toVectors(self,xcol='x',ycol='y'):
vectors={}
ydat=self.col(ycol)
xdat=self.col(xcol)
for rownum in range(len(ydat)):
key=xdat[rownum]
if type(key)==type(''):
key=key.strip()
if not key: continue
val=ydat[rownum]
try:
vectors[key].append(val)
except KeyError:
vectors[key]=[]
vectors[key].append(val)
for k,v in vectors.items():
try:
vectors[k]=ro.FloatVector(v)
except:
vectors[k]=ro.StrVector(v)
if self.factor:
vectors[k]=ro.FactorVector(vectors[k])
return vectors
def _get_fn(self,x,y):
if y:
if type(y)==type([]):
y='+'.join(y)
elif type(y)!=type(''):
y=str(y)
if x and y:
return '-by-'.join([y,x])
elif x:
return x
elif y:
return y
else:
return "_x,y_"
def boxplot(self,fn=None,x=None,y=None,main=None,xlab=None,ylab=None,ggplot=False,w=1100,h=800):
if not (x and y):
self._call_remaining('boxplot',x=x,y=y)
return
if ggplot:
self.plot(fn=fn,x=x,y=y,w=w,h=h,title=main,point=False,smooth=False,boxplot2=True,col=x,group=x)
return
if fn==None: fn='boxplot.'+self._get_fn(x,y)+'.png'
if not main: main=fn
if not xlab: xlab=x
if not ylab: ylab=y
grdevices = importr('grDevices')
grdevices.png(file=fn, width=w, height=h)
frmla=ro.Formula(y+'~'+x)
r['boxplot'](frmla,data=self.df,main=main,xlab=xlab,ylab=ylab)
grdevices.dev_off()
print ">> saved: "+fn
def _call_remaining(self,function_name,x=None,y=None,fn=None,**opt):
function=getattr(self,function_name)
if y and not x:
for col in self.cols:
if col==y: continue
try:
function(x=col,y=y,fn=fn)
except:
pass
return
elif x and not y:
for col in self.cols:
if col==x: continue
try:
function(x=x,y=col,fn=fn,**opt)
except:
pass
return
elif not x and not y:
return
def vioplot(self,fn=None,x=None,y=None,w=1100,h=800):
"""API to the 'vioplot' R package: http://cran.r-project.org/web/packages/vioplot/index.html"""
if not (x and y):
self._call_remaining('vioplot',x=x,y=y)
return
if fn==None:
fn='vioplot.'+self._get_fn(x,y)+'.png'
vectors=self.toVectors(x,y)
importr('vioplot')
grdevices.png(file=fn, width=w, height=h)
vvals=vectors.values()
vkeys=vectors.keys()
r['vioplot'](*vvals,**{'names':vkeys,'col':'gold'})
r['title']( 'Violin (box+density) plot where y='+y+' and x='+x )
grdevices.dev_off()
print ">> saved: "+fn
def summary(self,obj=None):
if not obj:
obj=self.df
x=r['summary'](obj)
if self.toprint:
print x
return x
def xtabs(self,cols=[]):
frmla='~'+'+'.join(cols)
return r['xtabs'](frmla,data=self.df)
def ca(self,fn,cols=[]):
importr('ca')
fit=r['ca'](self.xtabs(cols))
if self.toprint:
print r['summary'](fit)
r_plot(fn,fit)
return fit
def pca(self,fn='pca.png',col=None,w=1200,h=1200,title=''):
stats = importr('stats')
graphics = importr('graphics')
df=self.q().df
pca = stats.princomp(df)
grdevices = importr('grDevices')
ofn=".".join(fn.split(".")[:-1]+["eigens"]+[fn.split(".")[-1]])
strfacts=str(df.nrow)+" items using "+str(df.ncol)+" features ["+ofn.split("/")[-1]+"]"
grdevices.png(file=ofn, width=w, height=h)
graphics.plot(pca, main = title+" [Eigenvalues for "+strfacts+"]")
# if col:
# graphics.hilight(pca,factors)
grdevices.dev_off()
print ">> saved: "+ofn
grdevices = importr('grDevices')
ofn=".".join(fn.split(".")[:-1]+["biplot"]+[fn.split(".")[-1]])
strfacts=str(df.nrow)+" items using "+str(df.ncol)+" features ["+ofn.split("/")[-1]+"]"
grdevices.png(file=ofn, width=w, height=h)
stats.biplot(pca, scale=1,main = title+" [biplot of "+strfacts+"]")
grdevices.dev_off()
print ">> saved: "+ofn
def chisq(self,cols=[]):
fit=r['chisq.test'](self.xtabs(cols))
if self.toprint:
print r['summary'](fit)
return fit
def _get_frmla(self,formula,joiner='+'):
if not '~' in formula:
ykey=formula.strip()
keys=set(self.df.colnames)
ykeys=set([ykey])
xkeys=keys.difference(ykeys)
return ro.Formula(ykey+" ~ "+joiner.join(xkeys))
else:
return ro.Formula(formula)
# def manova(self,ys=[],xs=[],xjoin='*'):
# Y=r['cbind'](ys)
# #frmla=self._get_frmla(Y+'~'+xjoin.join(xs),joiner='*')
# frmla=ro.Formula(Y+'~'+xjoin.join(xs))
#
# print frmla
# fit=r['manova'](frmla,data=self.df)
#
# if self.toprint:
# print r['summary'](fit)
#
# return fit
def aov(self, formula, tukey=False, plot=False, fn=None, w=1100, h=800):
frmla=self._get_frmla(formula,joiner='*')
fit=r['aov'](frmla,data=self.df)
if tukey:
tfit=r['TukeyHSD'](fit)
if self.toprint:
print r['summary'](fit)
if tukey:
print r['summary'](tfit)
if plot:
if not fn:
fn = 'aov.'+str(formula)+'.png'
grdevices.png(file=fn, width=w, height=h)
r('layout(matrix(c(1,2,3,4),2,2))') # optional layout
r['plot'](tfit) # diagnostic plots
grdevices.dev_off()
print ">> saved: "+fn
return fit
def polyplot(self,terms):
pass
def addRowCol(self,name='rowcol'):
self.addCol(name,self.rows)