-
Notifications
You must be signed in to change notification settings - Fork 30
/
R_interface.py
executable file
·1214 lines (1120 loc) · 53.9 KB
/
R_interface.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
import sys, string
import export
import math
import random
import copy
import os
import os.path
import unique
import traceback
R_present=True
try:
### If file is present use this location
loc = unique.filepath('Config/R_location.txt')
s = open(loc,'r')
useStaticLocation=s.read()
#print useStaticLocation
#print 'Using the Config designated location
for p in os.environ['PATH'].split(':'): ### For Unix cluster environments
if os.path.exists(p + '/R'):
#path = p + '/R'
useStaticLocation = False
except Exception:
#print 'NOT using the Config designated location'
useStaticLocation = False
try:
forceError ### This doesn't currently work with the compiled version of AltAnalyze
import rpy2.robjects as robjects
r = robjects.r
print "\n---------Using RPY2---------\n"
except Exception:
from pyper import *
#print "\n---------Using PypeR---------\n"
### Running the wrong one once is fine, but multiple times causes it to stall in a single session
try:
try:
if 'Xdarwin' in sys.platform: ### Xdarwin is indicated since this if statement is invalid without a stand-alone Mac R package (ideal)
#print 'Using AltAnalyze local version of R'
#print 'A'
path = unique.filepath("AltDatabase/tools/R/Mac/R")
r = R(RCMD=path,use_numpy=True)
elif os.name == 'nt':
path = unique.filepath("AltDatabase/tools/R/PC/bin/x64/R.exe")
r = R(RCMD=path,use_numpy=True)
else:
#print 'B'
if useStaticLocation == False or useStaticLocation=='no':
print 'NOT using static location'
r = R(use_numpy=True)
else:
print 'Using static location'
path = '/usr/local/bin/R'
if os.path.exists(path): pass
else:
path = '/usr/bin/R'
if os.path.exists(path):
print 'Using the R path:',path
r = R(RCMD=path,use_numpy=True)
else:
r = None
R_present=False
print 'R does not appear to be installed... Please install first.'
except Exception:
#print 'C'
r = R(use_numpy=True)
except Exception:
print traceback.format_exc()
r = None
R_present=False
pass
LegacyMode = True
### Create a Directory for R packages in the AltAnalyze program directory (in non-existant)
r_package_path = string.replace(os.getcwd()+'/Config/R','\\','/') ### R doesn't link \\
r_package_path = unique.filepath(r_package_path) ### Remove the AltAnalyze.app location
try: os.mkdir(r_package_path)
except Exception: None
if R_present:
### Set an R-package installation path
command = '.libPaths("'+r_package_path+'")'; r(command) ### doesn't work with %s for some reason
#print_out = r('.libPaths()');print print_out; sys.exit()
def remoteMonocle(input_file,expPercent,pval,numGroups):
#input_file="Altanalyze"
setWorkingDirectory(findParentDir(input_file)[:-1])
try: os.mkdir(findParentDir(input_file)[:-1])
except Exception: None
z = RScripts(input_file)
setWorkingDirectory(input_file)
z.Monocle(input_file,expPercent,pval,numGroups)
def remoteHopach(input_file,cluster_method,metric_gene,metric_array,force_array='',force_gene=''):
""" Run Hopach via a call from an external clustering and visualizaiton module """
#input_file = input_file[1:] #not sure why, but the '\' needs to be there while reading initally but not while accessing the file late
row_order = []
column_order = []
if 'ICGS-SubCluster' in input_file:
force_array=2
input_file = checkForDuplicateIDs(input_file) ### Duplicate IDs will cause R to exit when creating the data matrix
z = RScripts(input_file)
setWorkingDirectory(input_file)
z.Hopach(cluster_method,metric_gene,force_gene,metric_array,force_array)
if cluster_method == 'both' or cluster_method == 'gene':
filename = findParentDir(input_file)+'/hopach/rows.'+findFileName(input_file)
row_order = importHopachOutput(filename)
if cluster_method == 'both' or cluster_method == 'array':
filename = findParentDir(input_file)+'/hopach/columns.'+findFileName(input_file)
column_order = importHopachOutput(filename)
#print row_order; sys.exit()
return input_file, row_order, column_order
def remoteAffyNormalization(input_file,normalization_method,probe_level,batch_effects):
### Input file is the path of the expression output from normalization
setWorkingDirectory(findParentDir(input_file)[:-1])
try: os.mkdir(findParentDir(input_file)[:-1])
except Exception: None #Already exists
z = RScripts(input_file)
z.AffyNormalization(normalization_method,probe_level,batch_effects)
def checkForDuplicateIDs(input_file, useOrderedDict=True):
if 'SamplePrediction' in input_file or '-Guide' in input_file:
### OrderedDict is prefered but will alter prior ICGS results
useOrderedDict = False
first_row = True
import collections
if useOrderedDict:
try: key_db = collections.OrderedDict()
except Exception:
try:
import ordereddict
key_db = ordereddict.OrderedDict()
except Exception:
key_db={}
else:
key_db={}
key_list=[]
fn=filepath(input_file)
offset=0
nonNumericsPresent=False
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
if first_row == True:
if ('row_clusters-flat' in t and 'row_clusters-flat' not in t[0]):
headers = string.join(['uid']+t[2:],'\t')+'\n'
offset = 1
elif '-filtered.txt' in fn and ".R2." in t[1] and LegacyMode:
headers = string.join(['uid']+t[2:],'\t')+'\n'
offset = 1
else:
headers = line
first_row = False
else:
key = t[0]
try:
k1,k2string.split(key,' ')
print [k1, k2],
if k1==k2: key = k1
print key
except Exception: pass
if key!='column_clusters-flat':
key_list.append(key)
try: s = map(float,t[offset+1:])
except Exception:
nonNumericsPresent=True
key_db[key]=t
if nonNumericsPresent:
import numpy
for key in key_db:
t = key_db[key]
s=[key]
if offset ==1: s.append('')
temp=[]
for value in t[offset+1:]:
try: temp.append(float(value))
except Exception: pass
avg=numpy.mean(temp)
for value in t[offset+1:]:
try: s.append(str(float(value)-avg))
except Exception: s.append('0.000101')
key_db[key]=s
if len(key_db) != len(key_list) or offset>0 or nonNumericsPresent:
print 'Writing a cleaned-up version of the input file:'
### Duplicate IDs present
input_file = input_file[:-4]+'-clean.txt'
export_text = export.ExportFile(input_file) ### create a new input file
export_text.write(headers) ### Header is the same for each file
for key in key_db:
t = key_db[key]
if offset > 0:
t = [t[0]]+t[1+offset:]
export_text.write(string.join(t,'\t')+'\n') ### Write z-score values and row names
export_text.close()
print 'File written...'
return input_file
def importHopachOutput(filename):
#print filename
""" Import the ID order information """
db={} ### Used to store the cluster data
hopach_clusters=[]
cluster_level=[]
cluster_level2=[]
cluster_level3=[]
hopach_db={}
cluster_db={}
level2_level1={}
firstLine = True
fn=filepath(filename)
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
if firstLine: firstLine = False
else:
t = string.split(data,'\t')
final_level_order = int(t[-1])
index, uid, cluster_number, cluster_label, cluster_level_order, final_label, final_level_order = string.split(data,'\t')
try: l2 = str(int(round(float(cluster_label),0)))[:2]
except Exception: l2 = int(cluster_label[0])
try: l3 = str(int(round(float(cluster_label),0)))[:3]
except Exception: l3 = int(cluster_label[0])
hopach_clusters.append((int(final_level_order),int(index)-1)) ### Need to order according to the original index, sorted by the clustered order
cluster_level.append(int(cluster_label[0])) ### This is the root cluster number
cluster_level2.append(l2) ### Additional cluster levels
cluster_level3.append(l3)
hopach_db[uid] = cluster_label
level2_level1[l2] = int(cluster_label[0])
level2_level1[l3] = int(cluster_label[0])
try: cluster_db[int(float(cluster_label[0]))].append(uid)
except Exception: cluster_db[int(cluster_label[0])] = [uid]
try: cluster_db[l2].append(uid)
except Exception: cluster_db[l2] = [uid]
try: cluster_db[l3].append(uid)
except Exception: cluster_db[l3] = [uid]
split_cluster=[]
if 'column' in fn:
cluster_limit = 50 ### typically less columns than rows
else:
cluster_limit = 75
for cluster in cluster_db:
#print cluster,len(cluster_db[cluster]),(float(len(cluster_db[cluster]))/len(hopach_db))
if len(cluster_db[cluster])>cluster_limit and (float(len(cluster_db[cluster]))/len(hopach_db))>0.2:
#print cluster
if cluster<10:
split_cluster.append(cluster)
import unique
levels1 = unique.unique(cluster_level)
already_split={}
updated_indexes={}
if len(split_cluster)>0:
print 'Splitting large hopach clusters:',split_cluster
i=0
for l2 in cluster_level2:
l1 = level2_level1[l2]
if l1 in split_cluster:
cluster_level[i] = l2
try:
l2_db = already_split[l1]
l2_db[l2]=[]
except Exception: already_split[l1] = {l2:[]}
i+=1
### Check and see if the l1 was split or not (might need 3 levels)
i=0
for l3 in cluster_level3:
l1 = level2_level1[l3]
if l1 in already_split:
#l1_members = len(cluster_db[l1])
l2_members = len(already_split[l1])
#print l1, l3, l1_members, l2_members
if l2_members == 1: ### Thus, not split
cluster_level[i] = l3
#print l1, l3, 'split'
i+=1
else:
if len(cluster_level) > 50: ### Decide to use different hopach levels
if len(levels1)<3:
cluster_level = cluster_level2
if len(cluster_level) > 200:
if len(levels1)<4:
cluster_level = cluster_level2
hopach_clusters.sort()
hopach_clusters = map(lambda x: x[1], hopach_clusters) ### Store the original file indexes in order based the cluster final order
### Change the cluster_levels from non-integers to integers for ICGS comparison group simplicity and better coloring of the color bar
cluster_level2 = []
### Rename the sorted cluster IDs as integers
cluster_level_sort = []
for i in cluster_level:
if str(i) not in cluster_level_sort:
cluster_level_sort.append(str(i))
cluster_level2.append(str(i))
cluster_level_sort.sort()
cluster_level = cluster_level2
cluster_level2=[]
i=1; cluster_conversion={}
for c in cluster_level_sort:
cluster_conversion[str(c)] = str(i)
i+=1
for c in cluster_level:
cluster_level2.append(cluster_conversion[c])
#print string.join(map(str,cluster_level2),'\t');sys.exit()
db['leaves'] = hopach_clusters ### This mimics Scipy's cluster output data structure
db['level'] = cluster_level2
return db
class RScripts:
def __init__(self,file):
self._file = file
def format_value_for_R(self,value):
value = '"'+value+'"'
return value
def File(self):
filename = self._file
filename_list = string.split(filename,'/')
filename = filename_list[-1]
filename = self.format_value_for_R(filename)
#root_dir = string.join(filename_list[:-1],'/')
return filename
def Monocle(self,samplelogfile,expPercent,p_val,numGroups):
#samplelogfile='C:/Users/venz6v/Documents/Altanalyze R/data.txt'
#grp_list="C:/Users/venz6v/Documents/Altanalyze R/grous.txt"
#gene_list="C:/Users/venz6v/Documents/Altanalyze R/gene.txt"
filename=self.File()
samplelogfile=findParentDir(filename)+'Monocle/expressionFile.txt"'
grp_list=findParentDir(filename)+'Monocle/sampleGroups.txt"'
gene_list=findParentDir(filename)+'Monocle/geneAnnotations.txt"'
pseudo_tree=findParentDir(filename)+'Monocle/monoclePseudotime.pdf"'
pseudo_txt=findParentDir(filename)+'Monocle/monoclePseudotime.txt"'
#try: os.mkdir(findParentDir(samplelogfile)) ### create "hopach" dir if not present
#except Exception: None
#try: os.mkdir(findParentDir(grp_list)) ### create "hopach" dir if not present
#except Exception: None
#try: os.mkdir(findParentDir(gene_list)) ### create "hopach" dir if not present
#except Exception: None
#self._file = samplelogfile
#samplelogfile = self.File()
#self._file = grp_list
#grp_list = self.File()
#self._file = gene_list
#gene_list = self.File()
print 'Loading monocle package in R'
print_out = r('library("monocle")')
if "Error" in print_out:
print 'Installing the R package "monocle" in Config/R'
print_out = r('source("http://bioconductor.org/biocLite.R"); biocLite("monocle")')
print print_out
print_out = r('library("monocle")')
if "Error" in print_out: print 'unable to download the package "monocle"';
print_out = r('library("monocle")')
print "Reading Monocle data..."
data_import = 'fpkm_matrix<-read.delim(%s,row.names=1,check.names=FALSE)' % samplelogfile
#print [data_import]
print_out = r(data_import);
print print_out
data_import = 'sample_sheet<-read.delim(%s,row.names=1,check.names=FALSE)' % grp_list
#print [data_import]
print_out = r(data_import);
print print_out
data_import = 'gene_ann<-read.delim(%s,row.names=1,check.names=FALSE)' % gene_list
#print [data_import]
print_out = r(data_import);
print print_out
print_out= r('pd <- new("AnnotatedDataFrame",data=sample_sheet)');
print_out=r('fd <- new("AnnotatedDataFrame",data=gene_ann)');
print_out=r('URMM <- newCellDataSet(as.matrix(fpkm_matrix),phenoData = pd,featureData =fd)');
print print_out
#colname(a) == colname(b)
print_out=r('URMM<- detectGenes(URMM, min_expr = 0)')
gene_exp='expressed_genes <- row.names(subset(fData(URMM), num_cells_expressed >=%s ))'% expPercent
#print [gene_exp]
try:print_out = r(gene_exp)
except Exception:
print "expression genes"
print_out=r('length(expressed_genes)')
print print_out
# specify the grouping column for finding differential genes
import multiprocessing
cores = multiprocessing.cpu_count()
print 'using', cores, 'cores'
k = 'diff_test_res <- differentialGeneTest(URMM[expressed_genes, ], fullModelFormulaStr = "expression~Group",cores=%s)' % cores
print [k]
print_out=r(k)
print print_out
gene_ord='ordering_genes <- row.names(subset(diff_test_res, pval < %s))' %p_val
print_out=r(gene_ord); print print_out
print_out=r('write.table(ordering_genes,file="ordering_genes.txt")') ### Writing out the informative genes used
print print_out
print_out=r('length(ordering_genes)'); print 'number or ordering genes',print_out
print_out=r('ordering_genes <- intersect(ordering_genes, expressed_genes)'); print print_out
print_out=r('URMM <- setOrderingFilter(URMM, ordering_genes)'); print print_out
print_out=r('URMM <- reduceDimension(URMM, use_irlba = F)'); print print_out
for i in range(numGroups,1,-1):
span='URMM <- orderCells(URMM, num_paths = %s, reverse = F)'% i;
print_out=r(span);
print print_out
if "Error" in print_out:
continue
else:
print_out=r(span);print i
print print_out
break
print_out=r('png("Monocle/monoclePseudotime.png")');
print print_out
print_out=r('plot_spanning_tree(URMM)'); print print_out
print_out=r('dev.off()')
print_out=r('pdf("Monocle/monoclePseudotime.pdf")');
print print_out
print_out=r('plot_spanning_tree(URMM)'); print print_out
print_out=r('dev.off()')
"""
print_out=r('pdf("Monocle/monoclePseudotimeOriginalGroups.pdf")');
print print_out
print_out=r('plot_spanning_tree(URMM), color_by = "originalGroups"'); print print_out
print_out=r('dev.off()')
"""
print_out=r('write.table(pData(URMM),file="Monocle/monoclePseudotime.txt")')
print " completed"
def AffyNormalization(self,normalization_method,probe_level,batch_effects):
print 'Loading affy package in R'
print_out = r('library("affy")')
if "Error" in print_out:
#print_out = r('install.packages("ggplot2", repos="http://cran.us.r-project.org")')
print 'Installing the R package "affy" in Config/R'
print_out = r('source("http://bioconductor.org/biocLite.R"); biocLite("affy")')
if "Error" in print_out: print 'unable to download the package "affy"'; forceError
print_out = r('library("affy")')
if 'gcrma' in normalization_method:
print 'Loading gcrma package in R'
print_out = r('library("gcrma")')
if "Error" in print_out:
print 'Installing the R package "gcrma" in Config/R'
print_out = r('source("http://bioconductor.org/biocLite.R"); biocLite("gcrma")')
if "Error" in print_out: print 'unable to download the package "gcrma"'; forceError
print_out = r('library("gcrma")')
if batch_effects == 'remove':
### Import or download support for SVA/Combat
print 'Loading sva package in R'
print_out = r('library("sva")')
if "Error" in print_out:
print 'Installing the R package "sva" in Config/R'
print_out = r('source("http://bioconductor.org/biocLite.R"); biocLite("sva")')
if "Error" in print_out: print 'unable to download the package "sva"'; forceError
print_out = r('library("sva")')
print "Reading Affy files..."
print_out = r('rawdata<-ReadAffy()')
print print_out
r('setwd("ExpressionInput")')
if probe_level: ### normalize at the level of probes rahter than probeset (e.g., alt.exon analysis of 3' array)
print_out = r('PM<-probes(rawdata,which="pm")'); print print_out
print_out = r('AffyInfo<-dimnames(PM)[[1]]'); print print_out
print_out = r('cutpos<-regexpr("\\d+$",AffyInfo,perl=T)'); print print_out
print_out = r('AffyID<-substr(AffyInfo,1,cutpos-1)'); print print_out
print_out = r('probe<-as.numeric(substr(AffyInfo,cutpos,nchar(AffyInfo)))'); print print_out
print_out = r('data.bgc<-bg.correct(rawdata,method="rma")'); print print_out
print_out = r('data.bgc.q<-normalize.AffyBatch.quantiles(data.bgc,type="pmonly")'); print print_out
print_out = r('pm.bgc.q<-probes(data.bgc.q,which="pm")'); print print_out
print_out = r('normalized<-cbind(AffyID,probe,pm.bgc.q)'); print print_out
command = 'write.table(normalized,file='+self.File()+',sep="\t",row.names=FALSE, quote=FALSE)'
print_out = r(command)
print print_out
print 'probe-level normalization complete'
else:
print "Begining %s normalization (will install array annotations if needed)... be patient" % normalization_method
print_out = r('normalized<-%s(rawdata)') % normalization_method
print print_out
command = 'write.exprs(normalized,'+self.File()+')'; print_out = r(command)
print print_out
print self.File(), 'written...'
if batch_effects == 'remove':
### Import data
command = 'mod = model.matrix(~as.factor(cancer) + age, data=pheno)'
print_out = r(command)
command = 'cdata = ComBat(dat=normalized, batch=as.factor(pheno$batch), mod=mod, numCov=match("age", colnames(mod)))'
print_out = r(command)
command = 'write.table(cdata,file='+self.File()+',sep="\t",row.names=FALSE, quote=FALSE)'
print_out = r(command)
output_file = string.replace(self.File(),'exp.','stats.')
print_out = r('calls<-mas5calls(rawdata)')
#print_out = r('pvals<-se.exprs(calls)') ### outdated?
print_out = r('pvals<-assayData(calls)[["se.exprs"]]')
command = 'write.table(pvals,'+output_file+',sep = "\t", col.names = NA)'; print_out = r(command)
print output_file, 'written...'
def Limma(self,test_type):
r('library("limma")')
filename = self.File()
try: output_file = string.replace(filename,'input','output-'+test_type)
except ValueError: output_file = filename[0:-4]+'-output.txt'
print "Begining to process",filename
data_import = 'data<-read.table(%s,sep="\t",header=T,row.names=1,as.is=T)' % filename
print_out = r(data_import)
design_matrix_file = string.replace(filename,'input','design')
design_import = 'design<-read.table(%s,sep="\t",header=T,row.names=1,as.is=T)' % design_matrix_file
design_matrix = r(design_import)
print_out = r('fit<-lmFit(data,design)')
fit_data = r['fit']
print_out = r('fit<-eBayes(fit)')
fit_data = r['fit']
contrast_matrix_file = string.replace(filename,'input','contrast')
contrast_import = 'contrast<-read.table(%s,sep="\t",header=T,row.names=1,as.is=T)' % contrast_matrix_file
print_out = r(contrast_import)
contrast_matrix = r['contrast']
r('contrast<-as.matrix(contrast)')
r('fit.contrast<-contrasts.fit(fit,contrast)')
r('fit.contrast<-eBayes(fit.contrast)')
r('nonadj<-fit.contrast$F.p.value')
if test_type == 'fdr':
print_out = r('results<-p.adjust(fit.contrast$F.p.value,method="fdr")')
else:
print_out = r('results<-nonadj')
result = r['results']
print 'test_type=',test_type
print_out = r('sum(results<0.05)')
summary = r['sum']
print "Number of probeset with a p<0.05",summary,"using",test_type
r('output<-cbind(data,results)')
output = 'write.table(output,%s,sep="\t")' % output_file
print_out = r(output)
print output_file, 'written...'
def Multtest(self,test_type):
r('library("multtest")')
filename = self.File()
try: output_file = string.replace(filename,'input','output')
except ValueError: output_file = filename[0:-4]+'-output.txt'
print "Begining to process",filename
parse_line = 'job<-read.table(%s,sep="\t", row.names=1, as.is=T)' % filename
print_out = r(parse_line)
print_out = r('matrix_size<-dim(job)')
print_out = r('label<-job[1,2:matrix_size[2]]')
print_out = r('jobdata<-job[2:matrix_size[1],2:matrix_size[2]]')
if test_type == "f":
print_out = r('ttest<-mt.maxT(jobdata,label, test="f", B=50000)')
if test_type == "t":
print_out = r('ttest<-mt.maxT(jobdata,label)')
print_out = r('ttest2<-ttest[order(ttest[,1]),]')
write_file = 'write.table(ttest2,%s,sep="\t")' % output_file
print_out = r(write_file)
print "Results written to:",output_file
def check_hopach_file_type(self):
if 'hopach.input' in self.File():
return 'continue'
else: return 'break'
def check_multtest_file_type(self):
if 'output' not in self.File():
return 'continue'
else: return 'break'
def check_limma_file_type(self):
if 'input' in self.File():
return 'continue'
else: return 'break'
def Hopach(self,cluster_method,metric_gene,force_gene,metric_array,force_array):
if R_present==False:
rNotPresent
print_out = r('library("Biobase")')
if "Error" in print_out:
print 'Installing the R package "Biobase" in Config/R'
print_out = r('source("http://bioconductor.org/biocLite.R"); biocLite("Biobase")')
if "Error" in print_out: print 'unable to download the package "Biobase"'; forceError
print_out = r('library("Biobase")')
print_out = r('library("hopach")')
if "Error" in print_out:
print 'Installing the R package "hopach" in Config/R'
print_out = r('source("http://bioconductor.org/biocLite.R"); biocLite("hopach")')
if "Error" in print_out: print 'unable to download the package "hopach"'; forceError
print_out = r('library("hopach")')
filename = self.File()
#r('memory.limit(2000)')
print "Begining to process",filename,"using HOPACH"
metric_g = self.format_value_for_R(metric_gene)
metric_a = self.format_value_for_R(metric_array)
parse_line = 'data<-read.table(%s,sep="\t",as.is=T,row.names=1,header=T)' % filename
checklinelengths(self._file)
print_out = r(parse_line)
dat = r['data']
print_out = r(parse_line)
#print "Number of columns in input file:",len(dat)
print_out = r('data<-as.matrix(data)')
dat = r['data']
#print "Number of columns in matrix:",len(dat)
force1=''; force2=''; hopg='NULL'; hopa='NULL'; distmatg='NULL'; distmata = 'NULL' ### defaults for tree export
if force_gene != '' and force_gene != 0: force1=',kmax='+str(force_gene)+', khigh='+str(force_gene)+', K='+str(force_array)
if force_array != '' and force_array != 0: force2=',kmax='+str(force_array)+', khigh='+str(force_array)+', K='+str(force_array)
if cluster_method == 'both' or cluster_method == 'gene':
distance_matrix_line = 'distmatg<-distancematrix(data,d=%s)' % metric_g
#print distance_matrix_line
if len(dat) > 1:
print_out1 = r(distance_matrix_line)
print_out2 = r('hopg<-hopach(data,dmat=distmatg,ord="own"'+force1+')')
#print 'hopg<-hopach(data,dmat=distmatg,ord="own"'+force1+')'
try: hopach_run = r['hopg']
except Exception:
print print_out1
print print_out2
hopg = 'hopg'
distmatg = 'distmatg'
gene_output = self.HopachGeneOutputFilename(metric_gene,str(force_gene))
output = 'out<-makeoutput(data,hopg,file=%s)' % gene_output
#print output
print_out = r(output)
#print print_out
output_file = r['out']
status = 'stop'
if 'clustering' in hopach_run:
if 'order' in hopach_run['clustering']:
try:
if len(hopach_run['clustering']['order']) > 10: status = 'continue'
except TypeError:
error = 'file: '+filename+": Hopach returned the array of cluster orders as blank while clustering GENES... can not process cluster... continuing with other files"
print error; errors.append(error)
if status == 'continue':
r(output_file); print 'hopach output written'
else:
error = 'file: '+filename+" Hopach returned data-matrix length zero...ARRAY clusters can not be generated"
print error; errors.append(error)
if cluster_method == 'both' or cluster_method == 'array':
distance_matrix_line = 'distmata<-distancematrix(t(data),d=%s)' % metric_a
if len(dat) > 1:
dist = r(distance_matrix_line)
#print distance_matrix_line
print_out = r('hopa<-hopach(t(data),dmat=distmata,ord="own"'+force1+')') #,coll="all"
#print ['hopa<-hopach(t(data),dmat=distmata,ord="own",'+force2+')']
#print 'hopa<-hopach(t(data),dmat=distmata,ord="own"'+force2+')'
hopach_run = r['hopa']
hopa = 'hopa'
distmata = 'distmata'
array_output = self.HopachArrayOutputFilename(metric_array,str(force_array))
output = 'out<-makeoutput(t(data),hopa,file=%s)' % array_output
print_out = r(output)
output_file = r['out']
status = 'stop'
if 'clustering' in hopach_run:
if 'order' in hopach_run['clustering']:
try:
if len(hopach_run['clustering']['order']) > 10: status = 'continue'
except TypeError:
error = 'file: '+filename+": Hopach returned the array of cluster orders as blank while clustering ARRAYS... can not process cluster"
print error; errors.append(error)
if status == 'continue':
r(output_file); print 'hopach output written'
else:
error = 'file: '+filename+"data-matrix length zero...ARRAY clusters can not be generated...continuing analysis"
print error; errors.append(error)
if len(metric_g)==0: metric_g = 'NULL'
if len(metric_a)==0: metric_a = 'NULL'
try:
output_filename = string.replace(gene_output,'rows.','')
cdt_output_line = 'hopach2tree(data, file = %s, hopach.genes = %s, hopach.arrays = %s, dist.genes = %s, dist.arrays = %s, d.genes = %s, d.arrays = %s, gene.wts = NULL, array.wts = NULL, gene.names = NULL)' % (output_filename,hopg,hopa,distmatg,distmata,metric_g,metric_a) ###7 values
except Exception: None
make_tree_line = 'makeTree(labels, ord, medoids, dist, side = "GENE")' ### Used internally by HOPACH
#print cdt_output_line
try: print_out = r(cdt_output_line)
except Exception: None
#print print_out
def HopachGeneOutputFilename(self,value,force):
filename = self.File() ### Relative to the set working directory
if 'hopach.input' in filename: ### When running this module on it's own (requires nown filetypes)
new_filename = string.replace(filename,'hopach.input','hopach.output')
if len(value)>1: new_filename = string.replace(new_filename,'.txt','-'+value+'.txt')
if len(force)>0: new_filename = string.replace(new_filename,'.txt','-'+'force_'+str(force)+'c.txt')
else: ### When called from an external heatmap visualization module
filename = self._file ### full path
new_filename = findParentDir(filename)+'/hopach/rows.'+findFileName(filename)
try: os.mkdir(findParentDir(new_filename)) ### create "hopach" dir if not present
except Exception: None
new_filename = '"'+new_filename+'"'
return new_filename
def HopachArrayOutputFilename(self,value,force):
filename = self.File()
if 'hopach.input' in filename: ### When running this module on it's own (requires nown filetypes)
new_filename = string.replace(filename,'hopach.input','arrays.output')
if len(value)>1: new_filename = string.replace(new_filename,'.txt','-'+value+'.txt')
if len(force)>0: new_filename = string.replace(new_filename,'.txt','-'+'force_'+str(force)+'c.txt')
else:
filename = self._file ### full path
filename = self._file ### full path
new_filename = findParentDir(filename)+'/hopach/columns.'+findFileName(filename)
try: os.mkdir(findParentDir(new_filename)) ### create "hopach" dir if not present
except Exception: None
new_filename = '"'+new_filename+'"'
return new_filename
def display(self):
print self.data
class FormatData:
def setdata(self,value):
self.data = value
def transform(self):
self.data = checktype(self.data)
def display(self):
print self.data
def returndata(self):
return self.data
def checktype(object):
###Checks to see if item is a list or dictionary. If dictionary, convert to list
import types
if type(object) is types.DictType:
object = converttolist(object)
elif type(object) is types.ListType:
object = object
elif type(object) is types.TupleType:
object = list(object)
elif type(object) is types.StringType:
object = importtable(object)
return object
def cleanUpLine(line):
line = string.replace(line,'\n','')
line = string.replace(line,'\c','')
data = string.replace(line,'\r','')
data = string.replace(data,'"','')
return data
def checklinelengths(filename):
fn=filepath(filename); first_row='yes'; line_number=0
for line in open(fn,'rU').xreadlines():
try: data = cleanUpLine(line)
except Exception: print 'error parsing the line:',[line], line_number
t = string.split(data,'\t')
if first_row == 'yes':
elements = len(t)
first_row = 'no'
else:
if len(t) != elements:
print "Line number", line_number, "contains",len(t),"elements, when",elements,"expected...kill program"
print filename; kill
line_number+=1
def converttolist(dictionary):
###Converts dictionary to list by appending the dictionary key as the first item in the list
converted_lists=[]
for key in dictionary:
dictionary_list = dictionary[key]
dictionary_list.reverse(); dictionary_list.append(key); dictionary_list.reverse()
converted_lists.append(dictionary_list)
return converted_lists
############ IMPORT FILES BEGIN ############
def importtable(filename):
fn=filepath(filename); tab_db = []
for line in open(fn,'rU').readlines():
data,null = string.split(line,'\n')
t = string.split(data,'\t')
tab_db.append(t)
return tab_db
def filepath(filename):
dir=os.path.dirname(__file__) #directory file is input as a variable
status = verifyFile(filename)
if status:
fn = filename
else:
fn=os.path.join(dir,filename)
return fn
def verifyFile(filename):
status = False
try:
fn=filepath(filename)
for line in open(fn,'rU').xreadlines(): status = True;break
except Exception: status = False
return status
def findFileName(filename):
filename = string.replace(filename,'\\','/')
dataset_name = string.split(filename,'/')[-1]
return dataset_name
def findParentDir(filename):
filename = string.replace(filename,'//','/')
filename = string.replace(filename,'\\','/')
x = string.find(filename[::-1],'/')*-1
return filename[:x]
def setWorkingDirectory(filename):
### Set R's working directory when calling this module remotely
working_dir = findParentDir(filename)
setwd = 'setwd("%s")' % working_dir
try: r(setwd)
except Exception:
print [filename]
print [working_dir]
print traceback.format_exc()
kill
def read_directory(sub_dir):
dir=os.path.dirname(__file__)
#print "Working Directory:", r('getwd()')
working_dir = dir+'/'+sub_dir[1:]
setwd = 'setwd("%s")' % working_dir
r(setwd)
#print "Working Directory:", r('getwd()')
dir_list = os.listdir(dir +'/'+ sub_dir[1:]); dir_list2 = []
for entry in dir_list: #add in code to prevent folder names from being included
if entry[-4:] == ".txt" or entry[-4:] == ".csv": dir_list2.append(entry)
return dir_list2
def CreateFilesMonocle(filename,rawExpressionFile,species='Hs'):
first_row = True
key_db={}
key_list=[]
fn=filepath(filename)
offset=0
nonNumericsPresent=False
try:
import gene_associations
gene_to_symbol = gene_associations.getGeneToUid(species,('hide','Ensembl-Symbol'))
except Exception:
print "gene_symbols present"
gene_to_symbol={}
setWorkingDirectory(findParentDir(filename)[:-1])
try: os.mkdir(findParentDir(filename)+'/Monocle')
except Exception: None
#filename=self.File()
x = 0
data_name=findParentDir(filename)+'/Monocle/expressionFile.txt'
gene_name=findParentDir(filename)+'/Monocle/geneAnnotations.txt'
sample_name=findParentDir(filename)+'/Monocle/sampleGroups.txt'
gene_names = [];
gene_list=[];
dat=[];
export_cdt = open(sample_name,'w')
export_gene=open(gene_name,'w')
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
if first_row == True:
if 'row_clusters-flat' in t and 'row_clusters-flat' not in t[0]:
headers = string.join(t[2:],'\t')+'\n'
offset = 1
else:
headers = string.join(t[1:],'\t')+'\n'
first_row = False
else:
key = t[0]
if key!='column_clusters-flat':
key_list.append(key)
try: s = map(float,t[offset+1:])
except Exception:
nonNumericsPresent=True
key_db[key]=t
else:
clusters = map(str,t[offset+1:])
for key in key_list:
t = key_db[key]
s=[key]
if offset ==1: s.append('')
temp=[]
for value in t[offset+1:]:
try: temp.append(float(value))
except Exception: pass
min1=min(temp)
for value in t[offset+1:]:
try: s.append(str(float(value)-min1))
except Exception: s.append('0.000101')
key_db[key]=s
export_object = open(data_name,'w')
export_object.write(''+'\t'+headers) ### Header is the same for each file
for key in key_list:
t = key_db[key]
if offset > 0:
t = [t[0]]+t[1+offset:]
export_object.write(string.join(t,'\t')+'\n') ### Write z-score values and row names
export_object.close()
print 'File written...'
#return input_file
array_names = []; array_linker_db = {}; d = 0; i = 0
for entry in headers.split('\t'):
entry=cleanUpLine(entry)
if '::' in entry:
a = (entry.split("::"))
elif ':' in entry:
a = (entry.split(":"))
else:
a = (clusters[i],entry)
#entry=string.join(a,'.')
ent=entry+'\t'+a[0];
#if(ent[0].isdigit()):
# ent='X'+ent[0:]
#if '-' in ent:
# ent=string.replace(ent,'-','.')
#if '+' in ent:
# ent=string.replace(ent,'+','.')
#print j
array_names.append(ent);
i+=1
i=0
eheader = string.join(['']+['Group'],'\t')+'\n' ### format column-flat-clusters for export
export_cdt.write(eheader)
for row in array_names:
export_cdt.write(row+'\n')
i+=1
export_cdt.close()
gheader = string.join(['']+ ['gene_short_name'],'\t')+'\n' ### format column-flat-clusters for export
export_gene.write(gheader)
for key in key_list:
proceed=False
### The commented out code just introduces errors and is not needed - re-evaluate in the future if needed
"""
if key in gene_to_symbol:
symbol = gene_to_symbol[key][0]
if symbol in gene_list:
nid = symbol
proceed = True
if proceed:
k=gene_list.index(nid)
export_object.write(line)
export_gene.write(key+'\n')
else:
export_gene.write(key+'\t'+key+'\n')"""
export_gene.write(key+'\t'+key+'\n')
export_object.close()
export_gene.close()
def reformatHeatmapFile(input_file):
import unique
export_file=string.replace(input_file,'Clustering-','Input-')
eo = export.ExportFile(export_file)
first_row = True
fn=filepath(input_file)
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
if first_row == True:
if 'column_clusters-flat' not in t:
array_names = []
for i in t[2:]:
array_names.append(string.replace(i,':','-'))
#print array_names;sys.exit()
#array_names.append(i)
elif 'column_clusters-flat' in t:
array_clusters = t[2:]
unique_clusters = unique.unique(array_clusters)
ind=0; headers=[]
for c in array_clusters:
headers.append(c+'::'+array_names[ind])
ind+=1
headers = string.join(['uid']+headers,'\t')+'\n'
eo.write(headers)
first_row = False
else:
values = string.join([t[0]]+t[2:],'\t')+'\n'
eo.write(values)
return export_file, len(unique_clusters)
def run_JTKcycle(expFile,annotFile,Time_range1, Time_range2,No_of_Timepoints,No_of_replicates,timepoint_difference):
print 'Loading JTK-Cycle package in R'
path='"'+r_package_path+'/JTK_CYCLE.R"'
#print [path]
line = 'source(%s)' % path
print_out = r(line)
"""
if "Error" in print_out:
print 'Installing the R package "JTK_CYCLE.R" in Config/R'
print_out = r('install.packages("devtools")')
print print_out
print_out = r('library(devtools)')
print print_out
print_out = r('install_github("mfcovington/jtk-cycle")')
#print_out = r('source("http://bioconductor.org/biocLite.R"); biocLite("jtk-cycle")')
print print_out
print_out = r('library("JTK_CYCLE.R")')
sys,exit()