-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGO_Optimizer_OLD
executable file
·1862 lines (1522 loc) · 70.4 KB
/
GO_Optimizer_OLD
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
#!/usr/bin/env perl
my ($noK, $noF, $noP) = (0,0,0); # testing purposes only -- leave all 0
my $HS_uniprot_trim = 1; # trim "-\d" suffixes from Uniprot IDs for human xref entries?
#$Id$
# Copyright © 2009, Stowers Institute for Medical Research. All rights reserved.
# c.f. attached LICENSE
=pod
=head1 SYNOPSIS
Briefly, GO_Optimizer takes a gene expression matrix, k-means clusters it for a range of k, identifies significant GO terms per cluster,
and reports which value of k maximizes the number of significant GO terms (also returns GO and cluster stability analyses for each k).
Alternatively, if a cluster mapping already exists, GO_Optimizer can skip the clustering and proceed directly to GO analysis.
=head1 OPTIONS
=item S<MANDATORY PARAMETERS>
=over
=item B<-f --file>
The input file
=item B<-x --taxon>
The ncbi taxa id for the desired organism (use --showtaxa for a listing of the most common model organisms).
=item B<-d --db>
The GO database to use (use --showdbs to get a listing of all canonically-named GO databases on the given mysql host).
=back
=item S<OPTIONAL PARAMETERS>
=over
=item B<-m --mode>
Run mode. Use "k" to start from the beginning (default; do k-means clustering) or "F" to start with the Fisher's exact testing.
NOTE: The input files are different for each mode. Mode "k" takes a gene expression matrix (columns are measurements),
while mode "F" takes a clustering matrix (columns are cluster assignments; one column per k). Mode 'F' also works perfectly well for
'flagged' lists, where column 1 is the gene identifier(s) and column 2 is a single integer indicating group membership.
=item B<-h --host>
The mysql host where the GO database lives (default: mysql-dev).
=item B<-b --bkg>
Background type for each cluster being analyzed. Use "complement" for all other clusters, "genome" for the rest of the genome, or "opposite" for opposing
list pairs ("opposite" is only available for mode = F, see below). If using "opposite", cluster values in each mapping column of the cluster matrix must
comprise a set of signed pairs, e.g. 1/-1, 2/-2, 3/-3, where the unsigned value is the set number and the signs indicate the opposing pair. This indicates
which gene sets are "opposites" to be compared. Thus, all genes in cluster 1 will be compared to all genes in cluster -1, likewise for 2 and -2, etc.
=item B<-l --levels>
The GO 'tree' levels to search for significant terms in (FatiGO-style), given as 'min-max'; default 3-9.
=item B<-n --slim>
Use a slim list (-n slimfile) instead of searching all terms and levels. The slim list must consist only of GO accessions.
=item B<-a --alpha>
Fisher's Exact Test parameter: post-adjustment significance cutoff value; default is 0.05.
=item B<-t --Ftails>
Fisher's Exact Test parameter: number of tails for the test; default is 2. Informs R parameter "alternative" for function "fisher.test". Choices:
=over
=item B<2 = two-tailed test>
=item B<1 = 1-tailed; cluster > background>
=item B<-1 = 1-tailed; cluster < background>
=back
=item B<-v --Fclev>
Fisher's Exact Test parameter: confidence interval for test; default 0.95. Becomes R parameter "conf.level" for function "fisher.test".
=item B<-j --padj>
Fisher's Exact Test parameter: method for p-value adjustment; default is "BH". Informs R parameter "method" for function "p.adjust". Choices:
=over
=item B<BF = Bonferroni>
=item B<BH = Benjamini-Hochberg>
=item B<BY = Benjamini-Young>
=item B<F = FDR>
=item B<H = Holm>
=item B<HB = Hochberg>
=item B<HM = Hommel>
=item B<NA = none>
=back
=item S<MANDATORY PARAMETERS IF MODE = K>
=over
=item B<-r --krange>
K-Means parameter: range of k values to evaluate, given as 'min-max', e.g. 3-10. Informs R parameter "centers" for function "kmeans".
=back
=item S<OPTIONAL PARAMETERS IF MODE = K>
=over
=item B<-i --kiter>
K-Means parameter: number of iterations for each k-means execution; default is 200. Becomes R parameter "iter.max" for function "kmeans".
=item B<-p --kreps>
K-Means parameter: number of times to re-cluster each k (for cluster stability testing); default is 10.
=item B<-s --kstart>
K-Means parameter: initial cluster number; default is 1. Becomes R parameter "nstart" for function "kmeans".
=item B<-g --kalg>
K-Means parameter: algorithm specification; default is "HW". Informs R parameter "algorithm" for function "kmeans". Choices:
=over
=item B<HW = Hartigan-Wong>
=item B<L = Lloyd>
=item B<F = Forgy>
=item B<M = MacQueen>
=back
=item B<-p --kreps>
K-Means parameter: number of reinitializations to use in testing cluster stability (since kmeans algorithms are randomly initialized), default 10.
=back
=item S<OTHER FLAGS>
=over
=item B<--showdbs>
Show a list of canonically-named GO databases (go_yyyymm) on the specified host (be sure to specify -h if not using mysql-dev).
=item B<--showtaxa>
Show a list of the NCBI taxa ids for the most common model organisms.
=item B<--help>
Display command line usage with options.
=item B<--man>
Display complete manual page and exit.
=item B<--version>
Display the scripts version number and exit.
=back
=back
=head1 RUNNING
=head1 OUTPUTS
=over
=item B<GO_Optimizer_Final_Report_<krange>.txt>
=item B<GO_Optimizer_kmeans.Rout>
R session output, k-means script
=item B<GO_Optimizer_kmeans_cluster_map_<krange>.txt>
=item B<GO_Optimizer_Consensus_Cluster_Profiles_k<k>.png>
=item B<GO_Optimizer_kmeans_<krange>_Cluster_Stats.png>
=item B<GO_Optimizer_kmeans_<krange>_log_R.txt>
=item B<GO_Optimizer_Fisher's.Rout>
R session output, Fisher's exact test script
=item B<GO_Optimizer_Fisher's_GO_Report_k<k>.png>
=item B<>
=back
=head1 EXAMPLES
=over
=item C< GO_Optimizer --man >
print a manpage.
=item C< GO_Optimizer --showtaxa >
show the NCBI taxa numbers for the most common model organisms.
=item C< GO_Optimizer --getGOstats Bacillus.subtilis -d go_201001>
show all NCBI taxa numbers associated with Bacillus subtilis* from database 'go_201001', and their associated DB statistics.
=item C< GO_Optimizer --showdbs -h rho >
show any GO databases (with name format go_yyyymm) on host rho.
=item C< GO_Optimizer -m k -f expmatrix.txt -x 9606 -b complement -d go_201001 -r 3-10 -i 200 -p 30 -t 1 -a 0.01 >
Run GO_Optimizer on file expmatrix.txt (thus, mode=k), species = human, bkg = other clusters, GO db = go_201001 (on mysql-dev), k range from 3 to 10, 200 iterations, repeat 30 times, and use a 1-sided Fisher's test (for over-enrichment in cluster) with alpha = 0.01.
=item C< GO_Optimizer -m F -f clustmatrix.txt -x 9606 -b complement -d go_201001 -t 1 -a 0.01 >
The same call as above, but starting at the Fisher's test (thus, mode=F, kmeans is skipped, and input file is a cluster matrix equivalent to GO_Optimizer_kmeans_cluster_map_<krange>.txt).
=back
=head1 VERSION
$Revision: 1.0$
=head1 AUTHOR
Ariel Paulson ([email protected])
=head1 DEPENDENCIES
perl
=head1 AVAILABILITY
Download at will.
=cut
use DBI;
use Cwd;
use Storable (qw/ nstore retrieve /);
use File::Path;
use Data::Dumper;
use Getopt::Long;
use Pod::Usage;
use FindBin;
use strict;
#use vars qw($VERSION $VC_DATE);
#BEGIN {
our $VERSION = qw$Revision: 1.0 $[-1];
our $VC_DATE = qw$Date: $[-2];
#}
###################################################################### ACTUAL CODE ######################################################################
###################################################################### ACTUAL CODE ######################################################################
###################################################################### ACTUAL CODE ######################################################################
###################################################################### ACTUAL CODE ######################################################################
###################################################################### ACTUAL CODE ######################################################################
### Setup
my %taxon_ids = (
3702 => 'Arabidopsis thaliana',
6500 => 'Aplysia californica',
7739 => 'Branchistoma floridae',
6239 => 'Caenorhabditis elegans',
7955 => 'Danio rerio',
7227 => 'Drosophila melanogaster',
9031 => 'Gallus gallus',
9606 => 'Homo sapiens',
10090 => 'Mus musculus',
45351 => 'Nematostella vectensis',
46514 => 'Patiria (Asterina) miniata',
10116 => 'Rattus norvegicus',
4932 => 'Saccharomyces cerevisiae',
4896 => 'Schizosaccharomyces pombe',
10228 => 'Trichoplax adherens',
8355 => 'Xenopus laevis'
);
my %valid = (
'TF' => {'T',1, 'F',1},
'mode' => {'K',1, 'F',1},
'bkg' => {'genome',1, 'complement',1, 'opposite',1},
'kalg' => {'HW' => 'Hartigan-Wong', 'L' => 'Lloyd', 'F' => 'Forgy', 'M' => 'MacQueen'},
'Ftails' => {1 => ['greater','OVER'], 2 => ['two.sided','BOTH'], -1 => ['lesser','UNDER']},
'padj' => {'H' => 'holm', 'HB' => 'hochberg', 'HM' => 'hommel', 'BF' => 'bonferroni', 'BH' => 'BH', 'BY' => 'BY', 'F' => 'fdr', 'NA' => 'none'}
);
my %tailuse = ('OVER' => {'OVER',1}, 'UNDER' => {'UNDER',1}, 'BOTH' => {'OVER',1, 'UNDER',1});
# script parameters
my ($file, $taxon, $showdbs, $showtaxa, $slimtree, $getGOstats, $getdbids, $help, $man, $ver, $GOdb, $wdir, $slim);
my $bkg = 'complement';
my $mode = 'K';
my $dbhost = 'mysql-dev';
my @log;
# algorithm parameters for R
my ($krange, $kmin, $kmax, $levmin, $levmax);
my ($levels, $kiter, $kreps, $kstart, $kalg, $Ftails, $Fclev, $alpha, $padj) = ('3-9', 200, 10, 1, 'HW', 2, 0.95, 0.05, 'BH');
GetOptions(
"m=s" => \$mode,
"f=s" => \$file,
"x=s" => \$taxon,
"b=s" => \$bkg,
"d=s" => \$GOdb,
"h=s" => \$dbhost,
"w=s" => \$wdir,
"n=s" => \$slim,
"mode=s" => \$mode,
"file=s" => \$file,
"taxon=s" => \$taxon,
"bkg=s" => \$bkg,
"db=s" => \$GOdb,
"host=s" => \$dbhost,
"wdir=s" => \$wdir,
"slim=s" => \$slim,
"l=s" => \$levels,
"r=s" => \$krange,
"i=i" => \$kiter,
"s=i" => \$kstart,
"g=s" => \$kalg,
"p=i" => \$kreps,
"t=i" => \$Ftails,
"v=f" => \$Fclev,
"j=s" => \$padj,
"a=f" => \$alpha,
"levels=s" => \$levels,
"krange=s" => \$krange,
"kiter=i" => \$kiter,
"kstart=i" => \$kstart,
"kalg=s" => \$kalg,
"kreps=i" => \$kreps,
"Ftails=i" => \$Ftails,
"Fclev=f" => \$Fclev,
"padj=s" => \$padj,
"alpha=f" => \$alpha,
"showdbs" => \$showdbs,
"showtaxa" => \$showtaxa,
"slimtree=s" => \$slimtree,
"getdbids" => \$getdbids,
"getGOstats=s" => \$getGOstats,
"help|?" => \$help,
"man!" => \$man,
"version!" => \$ver
) or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;
if ($ver) {print "$FindBin::Script: $VERSION\n"; exit(0)};
# declare HERE
my (%four_names, %slimterms, %slimfound, %ignore, %termlevels, %idtable, %allterms);
my (%accdata, %obsoletes, %levelmap, %relations, %idcounts, %idtrack, %termgenes1);
my ($dbh, $maxlevel);
my $cache = "/home/apa/local/bin/GO_Optimizer_DBcache"; # DB cache directory
if ($showtaxa) {
my $commontaxa = join "\n", map { sprintf("%5d = %s", $_, $taxon_ids{$_}) } (sort {$taxon_ids{$a} cmp $taxon_ids{$b}} keys %taxon_ids);
print "\n\nSome taxa and their numbers:\n$commontaxa\n\n\n";
exit;
} elsif ($showdbs) {
my $dbh = DBI->connect("DBI:mysql:host=$dbhost",'anonymous','guy#fawkes',{RaiseError=>1}) or die "Cannot connect to $dbhost: $DBI::err() $DBI::errstr()\n";
my $dbquery = $dbh->prepare("SHOW DATABASES");
$dbquery->execute();
my $ref = $dbquery->fetchall_arrayref();
$dbquery->finish();
print "\n\nGO databases on host $dbhost:\n";
foreach (@$ref) {
print "$$_[0]\n" if $$_[0] =~ /^go_\d{6}$/;
}
$dbh->disconnect();
print "\n\n";
exit;
} elsif ($slimtree) {
die "\n--slimtree flag MUST be accompanied by a taxon id, using the -x or --taxon switch!\n" unless $taxon;
die "\n--slimtree flag MUST be accompanied by a database name, using the -d or --db switch!\n" unless $GOdb;
&GO_queries($taxon);
&get_level_mappings;
my ($tid, %kids1, @kids, %levels, @tree, @gpids);
if ($accdata{$slimtree}) {
$tid = $accdata{$slimtree}->[2];
} elsif ($obsoletes{A2T}{$slimtree}) {
$tid = $obsoletes{A2T}{$slimtree};
} else {
die "GO accession $slimtree not found for taxon $taxon!\n";
}
foreach my $level (keys %{ $levelmap{L} }) {
push @kids, (keys %{ $levelmap{L}{$level}{$tid} });
# $levels{$_}{$level} = 1 foreach @kids;
}
my %kids1 = map {($_=>1)} @kids;
delete $kids1{$tid};
@kids = ($tid, (sort keys %kids1)); # make sure query accession is first!
foreach my $tid (@kids) {
my $acc = $allterms{I2A}{$tid};
my $lev = join ',', (sort {$a <=> $b} keys %{ $levels{$tid} });
foreach my $gpid (keys %{ $allterms{I2G}{$taxon}{$tid} }) {
my %idtemp;
$idtemp{ $idtable{1}{$taxon}{$gpid}{$_} }{$_} = 1 foreach (keys %{ $idtable{1}{$taxon}{$gpid} });
my $symbs = join '; ', (sort keys %{ $idtemp{S} });
my $names = join '; ', (sort keys %{ $idtemp{N} });
my $xrefs = join '; ', (sort keys %{ $idtemp{X} });
# push @gpids, "$acc\t$accdata{$acc}->[1]\t$lev\t$xrefs\t$symbs\t$names\n";
push @gpids, "$acc\t$accdata{$acc}->[1]\t$lev\t$xrefs\t$symbs\t$names\n";
}
}
# open TREE, "> GO_Tree_${GOdb}_$taxon.txt";
# print TREE ;
# close TREE;
my $outname = "All_GO_Mappings_${slimtree}_${GOdb}_$taxon.txt";
print "Outputting $outname\n";
open GPIDS, "> $outname";
# print GPIDS "Accession\tTerm\tLevels\tXrefs\tSymbols\tNames\n";
print GPIDS "Accession\tTerm\tXrefs\tSymbols\tNames\n";
print GPIDS @gpids;
close GPIDS;
exit;
} elsif ($getdbids) {
die "\n--getdbids flag MUST be accompanied by a database name, using the -d or --db switch!\n" unless $GOdb;
&GO_queries($taxon);
my (%realias, @dbids);
my %origins = ('S' => 'SYMBOLS', 'N' => 'NAMES', 'X' => 'XREFS');
foreach my $gpid (sort keys %{ $idtable{1}{$taxon} }) {
foreach my $alias (keys %{ $idtable{1}{$taxon}{$gpid} }) {
$realias{$gpid}{ $idtable{1}{$taxon}{$gpid}{$alias} }{$alias} = 1; # re-key by alias origin (name, symbol, xref)
}
foreach my $origin (qw/ S N X /) {
my $string = join ';', (sort keys %{ $realias{$gpid}{$origin} });
push @dbids, "$gpid\t$origins{$origin}\t$string";
}
}
my $msg = join "\n", @dbids;
print "Gene_Product_ID\tType\tIDs\n$msg";
exit;
} elsif ($getGOstats) {
($GOdb)? (print "\nChecking entries in database $GOdb...\n") : (die "\n--getGOstats flag MUST be accompanied by a database name, using the -d or --db switch!\n");
my (%taxtable, %ml, $ids);
my ($genus, $species) = split /\./, $getGOstats;
my $dbhq = DBI->connect("DBI:mysql:database=$GOdb:host=$dbhost",'anonymous','guy#fawkes',{RaiseError=>1}) or die "Cannot connect to $GOdb on $dbhost: $DBI::err() $DBI::errstr()\n";
my $qgenus = $dbhq->quote($genus);
my ($qspecies, $taxidquery);
if ($species eq '*') {
$taxidquery = $dbhq->prepare("SELECT ncbi_taxa_id, species FROM species WHERE genus = $qgenus");
} else {
$qspecies = $dbhq->quote("$species%");
$taxidquery = $dbhq->prepare("SELECT ncbi_taxa_id, species FROM species WHERE genus = $qgenus AND species like $qspecies");
}
$taxidquery->execute();
while ( my ($taxon, $spec) = $taxidquery->fetchrow_array() ) {
$taxtable{$taxon} = [$spec, $taxon, "$genus $spec", 0, 0, 0]; # last 3 fields will be: gene product count, gpid label count, term count from GO database
}
$taxidquery->finish();
if (scalar (keys %taxtable) == 0) {
if ($species eq '') {
print "No entries of genus \"$genus\" were found for any species!\n\n";
} else {
print "No entries of genus \"$genus\" were found for any species \"$species*\"!\n\n";
}
exit;
}
(scalar (keys %taxtable) == 1) ? ($ids = 'id') : ($ids = 'ids');
print scalar (keys %taxtable)," related taxon $ids found.\nQuerying term/identifier prevalence per taxon...\n";
foreach my $taxon (keys %taxtable) {
&GO_queries($taxon);
my (%labels, %terms);
$taxtable{$taxon}->[3] = scalar (keys %{ $idcounts{GPID}{$taxon} });
foreach my $labeltype (qw/ SYMB NAME XREF /) {
$labels{$_} = 1 foreach (keys %{ $idcounts{$labeltype}{$taxon} });
}
$taxtable{$taxon}->[4] = scalar (keys %labels);
foreach my $gpid (keys %{ $idcounts{GPID}{$taxon} }) {
$terms{$_} = 1 foreach (keys %{ $allterms{G2I}{$taxon}{$gpid} });
}
$taxtable{$taxon}->[5] = scalar (keys %terms);
}
$dbhq->disconnect; # disconnect HERE after all &GO_queries are complete
$dbh->disconnect; # disconnect HERE after all &GO_queries are complete
my @header = ('Taxon ID', 'Scientific Name', 'Genes', 'Labels', 'Terms');
foreach my $i (1..5) {
$ml{$i} = length($header[$i-1]) if length($header[$i-1]) > $ml{$i}; # max length for sprintf
foreach my $taxon (keys %taxtable) {
$ml{$i} = length($taxtable{$taxon}->[$i]) if length($taxtable{$taxon}->[$i]) > $ml{$i}; # ditto
}
}
my $msg = sprintf("%-$ml{1}s %-$ml{2}s %-$ml{3}s %-$ml{4}s %-$ml{5}s\n", @header);
$msg .= sprintf("%$ml{1}d %-$ml{2}s %$ml{3}d %$ml{4}d %$ml{5}d\n", @{ $taxtable{$_} }[1..5]) foreach (sort { $taxtable{$a}->[0] cmp $taxtable{$b}->[0] } keys %taxtable);
print "\n\n$msg\n\n";
exit;
} else {
## Test script parameters
die "File '$file' not accessible!\n" unless -e $file;
die "Taxon number '$taxon' must be a positive integer!\n" if $taxon =~ /\D/;
die "Background type '$bkg' must be 'genome' or 'complement'!\n" unless $valid{bkg}{$bkg};
die "Mode type '$mode' must be 'K' or 'F'!\n" unless $valid{mode}{$mode};
if ($wdir) {
$wdir = cwd()."/$wdir" unless ($wdir =~ /^\//); # don't change if rooted
if (-d $wdir) {
(rmtree $wdir) ? (print "Old working directory '$wdir' successfully removed.\n") : (warn "Could not remove old working directory '$wdir': $!\n");
}
(mkdir $wdir) ? (print "Working directory '$wdir' successfully created.\n") : (warn "Could not create working directory '$wdir': $!\n");
} else {
$wdir = cwd(); # don't refresh this directory...
}
print "Working directory = $wdir\n";
## Test R parameters
if ($mode eq 'K') {
($kmin, $kmax) = ($1, $2) if $krange =~ /^(\d+)-(\d+)$/;
die "Invalid format for k range '$krange'! Must specify as min-max, e.g. 3-10, even if single value\n" unless ($kmin =~ /^\d+$/ && $kmax =~ /^\d+$/);
die "k-means iteration value '$kiter' must be a positive integer!\n" if $kiter =~ /\D/;
die "k-means repeat number '$kreps' must be a positive integer!\n" if $kreps =~ /\D/;
die "k-means nstart value '$kstart' must be a positive integer!\n" if $kstart =~ /\D/;
die "k-means algorithm choice '$kalg' invalid!\n" unless $valid{kalg}{$kalg};
if ($bkg eq 'opposite') {
print "Background mode 'opposite' not allowed for mode=K! Changing to 'complement'\n";
$bkg = 'complement';
}
}
($levmin, $levmax) = ($1, $2) if $levels =~ /^(\d+)-(\d+)$/;
die "Invalid format for GO level range '$levels'! Must specify as min-max, e.g. 4-9, even if single value\n" unless ($levmin =~ /^\d+$/ && $levmax =~ /^\d+$/);
die "Fisher's test tails value '$Ftails' must be 1, 2, or -1!\n" unless $valid{Ftails}{$Ftails};
die "Fisher's test confidence level value '$Fclev' must be a positive real number!\n" if $Fclev =~ /[^\d\.]/;
die "Alpha value '$alpha' must be a positive real number!\n" if $alpha =~ /[^\d\.]/;
die "p-value adjustment method '$padj' invalid!\n" unless $valid{padj}{$padj};
}
chomp(my $date = `date`);
my $tailname = $valid{Ftails}{$Ftails}->[1];
my $term_mappings = "$wdir/GO_Optimizer_term_mappings.txt";
my $term_table = "$wdir/GO_Optimizer_term_table.txt";
my $R_script_K = "$wdir/GO_Optimizer_kmeans.R";
my $R_session_K = $R_script_K."out";
my $R_data_K = "$wdir/GO_Optimizer_kmeans_input.txt";
my $R_results_K = "$wdir/GO_Optimizer_kmeans_cluster_map_$krange.txt";
my $R_image_K = "$wdir/GO_Optimizer_kmeans_$krange.RData";
my $R_plot_K = "$wdir/GO_Optimizer_kmeans_${krange}_Cluster_Stats.png";
my $R_log_K = "$wdir/GO_Optimizer_kmeans_${krange}_log_R.txt";
my $R_script_F = "$wdir/GO_Optimizer_Fishers.R";
my $R_session_F = $R_script_F."out";
my $R_data_F = "$wdir/GO_Optimizer_Fishers_input.txt";
my $R_results_F = "$wdir/GO_Optimizer_Fishers_${tailname}_output.txt";
my $R_sigterms_F = "$wdir/GO_Optimizer_Fishers_${tailname}_significant_terms.txt";
my $R_sigrows_F = "$wdir/GO_Optimizer_Fishers_${tailname}_significant_genelist.txt";
my $R_script_P = "$wdir/GO_Optimizer_Summary_Plot.R";
my $R_session_P = $R_script_P."out";
my $R_data1_P = "$wdir/GO_Optimizer_kmeans_${krange}_${tailname}_Sig_Term_Matrix.txt";
my $R_data2_P = "$wdir/GO_Optimizer_kmeans_${krange}_${tailname}_Plot_Table.txt";
my $R_plot_P = "$wdir/GO_Optimizer_kmeans_${krange}_${tailname}_GO_Stats.png";
my ($script_text_K, $script_text_F, $script_text_P);
my $logfile = "$wdir/GO_Optimizer_Log.txt";
open LOG, "> $logfile" or warn "Cannot create logfile '$logfile': $!\n"; # overwrite existing
close LOG;
my ($kdir, $Fdir, @allk);
if ($mode eq 'K') {
@allk = ($kmin..$kmax);
$kdir = "$wdir/K_${krange}_cluster_graphs"; # for final results files that have been broken out by K
$Fdir = "$wdir/K_${krange}_${tailname}_result_breakouts"; # for final results files that have been broken out by K
} elsif ($mode eq 'F') {
$kdir = "$wdir/${file}_cluster_graphs"; # for final results files that have been broken out by K
$Fdir = "$wdir/${file}_${tailname}_result_breakouts"; # for final results files that have been broken out by K
}
my $BTfile = "$Fdir/GO_Optimizer_Fishers_significant_terms"; # these DO NOT HAVE .txt endings!
my $BGfile = "$Fdir/GO_Optimizer_Fishers_significant_genelist"; # these DO NOT HAVE .txt endings!
unless ($noK || $mode eq 'F') { # if skipping k-means, $kdir files will not be regenerated (so don't refresh directory)
if (-d $kdir) {
(rmtree $kdir) ? (print "Old breakout directory '$kdir' successfully removed.\n") : (warn "Could not remove old breakout directory '$kdir': $!\n");
}
(mkdir $kdir) ? (print "Breakout directory '$kdir' successfully created.\n") : (warn "Could not create breakout directory '$kdir': $!\n");
}
unless ($noF) { # if skipping Fisher's, $Fdir files will not be regenerated (so don't refresh directory)
if (-d $Fdir) {
(rmtree $Fdir) ? (print "Old breakout directory '$Fdir' successfully removed.\n") : (warn "Could not remove old breakout directory '$Fdir': $!\n");
}
(mkdir $Fdir) ? (print "Breakout directory '$Fdir' successfully created.\n") : (warn "Could not create breakout directory '$Fdir': $!\n");
}
## Get slim list, if specified
my $slimnum;
if ($slim) {
if (open SLIM, $slim) {
my ($slimlines, $slimcount, $slimwarn);
while (<SLIM>) {
$_ =~ s/[\n\r\"]//g;
$slimlines++;
if ($_ =~ /^GO:\d{7}/) {
$slimterms{1}{$_} = 1;
$slimcount++;
} else {
$slimterms{0}{$_} = 1;
$slimwarn++;
}
}
close SLIM;
print "SLIM TERMS: $slimlines lines read | $slimcount accessions | ", scalar (keys %{ $slimterms{1} }), " unique.\n";
print " There were also ", scalar (keys %{ $slimterms{0} }), " unique non-accession entries in $slimwarn instances.\n" if $slimwarn;
$slimnum = scalar (keys %{ $slimterms{1} });
} else {
print "Slim list '$slim' does not exist! Slim analysis will not be performed.\n";
$slim = undef;
}
}
############################## QUERIES ##############################
############################## QUERIES ##############################
############################## QUERIES ##############################
############################## QUERIES ##############################
############################## QUERIES ##############################
### Find all identifiers associated with GO terms
&GO_queries($taxon);
## Get all IDs and their levels (from root); also get immediate children & parents
my $childquery = $dbh->prepare("SELECT DISTINCT term2_id, distance FROM graph_path WHERE term1_id = ?");
my $parentquery = $dbh->prepare("SELECT DISTINCT term1_id, distance FROM graph_path WHERE term2_id = ?");
########## have a query to investigate gene_product_count table somewhere....
print "Mapping GO terms to levels...\n";
$childquery->bind_param(1, $four_names{all}->[0]);
$childquery->execute();
while ( my ($tid, $level) = $childquery->fetchrow_array() ) {
if ($allterms{I2A}{$tid}) { # no relationships or obsoletes
$termlevels{T2L}{$tid}{$level} = 1;
$termlevels{L2T}{$level}{$tid} = 1;
$maxlevel = $level if $level > $maxlevel;
}
}
warn "Error retrieving data: $childquery->errstr()\n" if $childquery->err();
$childquery->finish();
if ($levmax > $maxlevel) {
print "\nWARNING: given range for GO level analysis was $levmin-$levmax, but the tree only extends to level $maxlevel.\n Range is now $levmin-$maxlevel.\n\n";
$levmax = $maxlevel;
}
&get_level_mappings;
unless (%relations && %levelmap) {
print "Mapping downstream GO terms to upper levels...\n";
foreach my $level (0..$maxlevel) {
my $thislevel = scalar (keys %{ $termlevels{L2T}{$level} });
my %downstreams;
foreach my $tid (keys %{ $termlevels{L2T}{$level} }) { # all terms at level $level
$childquery->bind_param(1, $tid);
$childquery->execute();
while ( my ($tid2, $dist) = $childquery->fetchrow_array() ) {
if ($allterms{I2A}{$tid2}) { # no relationships or obsoletes
$levelmap{L}{$level}{$tid}{$tid2} = 1 if $dist > 0; # for each $tid at level $level, what are its downstream $tids? (no self-references)
$levelmap{T}{$tid2}{$level}{$tid} = 1; # for each $tid2, what are its level-$level parental mappings? (need self-references)
# print "$tid child = $tid2 @ $dist\n" if $tid == 19;
$relations{P2C}{$tid}{$tid2} = 1 if $dist == 1;
$downstreams{$tid2} = 1;
}
}
warn "Error retrieving data: $childquery->errstr()\n" if $childquery->err();
$childquery->finish();
$parentquery->bind_param(1, $tid);
$parentquery->execute();
while ( my ($tid2, $dist) = $parentquery->fetchrow_array() ) {
if ($allterms{I2A}{$tid2} && $tid2 != $tid) { # no relationships, obsoletes, or self-references
# print "$tid parent = $tid2 @ $dist\n" if $tid == 19;
$relations{C2P}{$tid}{$tid2} = 1 if $dist == 1;
}
}
warn "Error retrieving data: $parentquery->errstr()\n" if $parentquery->err();
$parentquery->finish();
}
my $msg = sprintf("Level %2d: %5d terms absorbed %5d downstream terms.", $level, $thislevel, scalar (keys %downstreams));
&logreport($msg);
}
&logreport("Storing '$cache/${GOdb}_relations_dump.dat' for next time...");
nstore(\%relations,"$cache/${GOdb}_relations_dump.dat") or warn "Cannot store \%relations in file '$cache/${GOdb}_relations_dump.dat': $!";
&logreport("Storing '$cache/${GOdb}_levelmap_dump.dat' for next time...");
nstore(\%levelmap,"$cache/${GOdb}_levelmap_dump.dat") or warn "Cannot store \%levelmap in file '$cache/${GOdb}_levelmap_dump.dat': $!";
}
$dbh->disconnect();
#open PCR, "> $wdir/pc_relations_dump.txt" or warn "Cannot create file '$wdir/pc_relations_dump.txt': $!\n";
#print PCR Dumper(\%relations),"\n";
#close PCR;
open TAB, "> $term_table" or warn "Cannot create file '$term_table': $!\n";
print TAB "Term ID\tGO Accession\tObsolete Accs\tTerm Type\tTerm Name\tTree Level\tParents\tChildren\tDownstream IDs\tGenes\tDownstream Genes\n";
#foreach my $tid (sort {$allterms{I2A}{$a} cmp $allterms{I2A}{$b}} keys %{ $allterms{I2A} }) {
foreach my $tid (keys %{ $allterms{I2A} }) {
my $gpids = scalar (keys %{ $allterms{I2G}{$taxon}{$tid} });
my $obsolete = join ',', (sort keys %{ $obsoletes{T2A}{$tid} });
my $acc = $allterms{I2A}{$tid};
if ($slimterms{1}{$acc}) {
$slimfound{$acc} = $acc;
} else {
foreach my $obs (keys %{ $obsoletes{T2A}{$tid} }) {
$slimfound{$obs} = $acc if $slimterms{1}{$obs};
}
}
my $typename = join "\t", @{ $accdata{$acc} }[0,1];
my $alevels = join ',', (sort {$a <=> $b} keys %{ $termlevels{T2L}{$tid} });
my $parents = scalar (keys %{ $relations{C2P}{$tid} });
my $children = scalar (keys %{ $relations{P2C}{$tid} });
my %downstream;
foreach my $level (0..$maxlevel) {
if ($levelmap{L}{$level}{$tid}) {
foreach my $tid2 (keys %{ $levelmap{L}{$level}{$tid} }) {
$downstream{I}{$tid2} = 1;
$downstream{G}{$_} = 1 foreach (keys %{ $allterms{I2G}{$taxon}{$tid2} });
}
}
}
my $dsI = scalar (keys %{ $downstream{I} });
my $dsG = scalar (keys %{ $downstream{G} });
print TAB "$tid\t$acc\t$obsolete\t$typename\t$alevels\t$parents\t$children\t$dsI\t$gpids\t$dsG\n" if ($gpids || $dsG); # must have associated products!
}
close TAB;
my $slimmap = scalar keys %slimfound;
my $slimlost = $slimnum - $slimmap;
print "WARNING: $slimlost/$slimnum slim terms do not exist or are not associated with taxon $taxon in this database!\n" if $slimlost;
my $msg = scalar (keys %{ $idcounts{SYMB}{$taxon} })." Symbols, ".
scalar (keys %{ $idcounts{NAME}{$taxon} })." Names, and ".
scalar (keys %{ $idcounts{XREF}{$taxon} })." External IDs for ".
scalar (keys %{ $idcounts{GPID}{$taxon} })." GP IDs.\n".
scalar (keys %accdata)." GO accessions = ".
scalar (keys %{ $relations{C2P} })." children assigned to ".
scalar (keys %{ $relations{P2C} })." parents.\n";
&logreport($msg);
############################## K-MEANS ##############################
############################## K-MEANS ##############################
############################## K-MEANS ##############################
############################## K-MEANS ##############################
############################## K-MEANS ##############################
my (%originals, %allgenes, %equivalents, %matched);
if ($mode eq 'F') {
$R_results_K = $file;
} else {
### Process expression matrix
my ($colcount, $lines, $row, $tcount, @tocluster, $orgwarn);
open IN, $file or die "Cannot open expression matrix file '$file': $!\n";
while (<IN>) {
$_ =~ s/[\n\r\"]//g;
my ($id, $data) = split /\t/, $_, 2;
$lines++;
next if $lines == 1; # MANDATORY HEADER
$row++; # counting data rows only
push @tocluster, "$row\t$data\n";
$originals{$row} = $id;
my @genes = split /\;/, $id;
$tcount += scalar @genes;
&matchup(\@genes, $row);
}
close IN;
my $matches = scalar (keys %matched);
my $matchpct = sprintf("%0.0f", 100*($matches/$row));
my $matchmsg = "$matches/$row rows ($matchpct%) were assigned a GO identifier.";
($matchpct <= 50) ? ($orgwarn = "Only $matchmsg Did you pick the right organism?\n") : ($orgwarn = $matchmsg);
my $msg = "$row rows\n$tcount total IDs\n".scalar (keys %allgenes)." unique IDs\n$orgwarn";
&logreport($msg);
open OUT, "> $R_data_K" or warn "Cannot create file '$R_data_K': $!\n";
print OUT @tocluster;
close OUT;
### Run k-means battery in R
&generate_kmeans_script;
open OUT, "> $R_script_K" or warn "Cannot create file '$R_script_K': $!\n";
print OUT $script_text_K;
close OUT;
if ($noK) {
print "Skipping k-means clustering in R.\n";
} else {
print "Running k-means clustering in R:\nCalling: nohup R --vanilla < $R_script_K > $R_session_K\n";
system "nohup R --vanilla < $R_script_K > $R_session_K";
}
}
### Process resulting cluster matrix
my (%ksets, @kvalues, $kcount, $lines, $row2, $tcount2, $orgwarn, $flagged);
print "Reading clustering matrix...\n";
open IN, $R_results_K or die "Cannot open cluster matrix file '$R_results_K': $!\n";
while (<IN>) {
$_ =~ s/[\n\r\"]//g;
my ($id, @data) = split /\t/, $_;
$lines++;
if ($lines == 1) { # first line = header
@allk = @data;
$_ =~ s/\D//g foreach @allk; # header may have non-integer components
$kcount = scalar @allk;
my $ktest;
foreach (@allk) {
$ktest = 1 if $_; # does colname still exist?
}
unless ($ktest) { # colnames were digit-free
@allk = (1..$kcount); # replace with "virtual k" values = col nums
}
next;
}
if ($mode eq 'F') { # if input is user-supplied cluster matrix, it will have genes as row identifiers. Must convert to row ID sets.
$row2++;
my @genes = split /\;/, $id;
$tcount2 += scalar @genes;
&matchup(\@genes, $row2);
$originals{$row2} = $id;
} else {
$row2 = $id;
}
foreach my $ki (1..$kcount) {
my $k = $allk[$ki-1];
# print "Row $row2: ki $ki = k $k: clust $data[$ki-1]\n";
$ksets{$k}{ $data[$ki-1] }{$row2} = 1; # kset X, kcluster Y contains gene Z; automatic removal of duplicates within kclusters
}
}
close IN;
$flagged = 1 if ($kcount == 1 && $mode eq 'F'); # flagged list, apparently
#open KT, "> $wdir/Ktest.txt" or warn "Cannot create file '$wdir/Ktest.txt': $!\n";
#print KT Dumper(\%ksets),"\n";
#close KT;
my $allclust;
foreach my $k (@allk) {
my %kctemp;
foreach my $clust (keys %{ $ksets{$k} }) {
(my $set = $clust) =~ s/^-//; # if exists
$allclust++;
if ($bkg eq 'opposite') { # gather sets by column
$kctemp{$set}{$clust} = 1;
}
}
if ($bkg eq 'opposite') { # test to ensure set/antiset completion
foreach my $set (keys %kctemp) {
print "Incomplete clustering map for k $k: set $set not paired.\n" if (scalar (keys %{ $kctemp{$set} }) < 2);
}
}
}
if ($mode eq 'F') {
($kmin, $kmax) = (sort {$a <=> $b} keys %ksets)[0,-1];
$krange = "$kmin-$kmax"; # starting with cluster matrix; $kmin, $kmax, $krange were not previously defined
print "Flagged list with $allclust sets detected.\n" if $flagged;
my $matches = scalar (keys %matched);
my $matchpct = sprintf( "%0.0f", 100*($matches/$row2) );
my $matchmsg = "$matches/$row2 rows ($matchpct%) were assigned a GO identifier.";
($matchpct <= 50) ? ($orgwarn = "Only $matchmsg Did you pick the right organism?\n") : ($orgwarn = $matchmsg);
my $msg = "$row2 rows\n$tcount2 total IDs\n".scalar (keys %allgenes)." unique IDs\n$orgwarn";
&logreport($msg);
}
my $noun;
(scalar @allk > 1) ? ($noun = 'values') : ($noun = 'value');
my $msg = "$row2 IDs / ".scalar (keys %originals)." unique IDs in $allclust total clusters across ".(scalar @allk)." $noun of k.\n";
&logreport($msg);
### For each cluster: pool/unique IDs, create background, then get GO terms for cluster and background, then map terms to desired levels
my (%GOtable, %termout, %siginco, %mappings, %termrows, %levelterms, %rowmapped, %termgenes2, %slimhits, %outterms1);
my ($all_lost, $allout, @preFish);
print "Processing gene lists by k...\n";
foreach my $k (@allk) { # k value
foreach my $clust (sort {$a <=> $b} keys %{ $ksets{$k} }) { # cluster for this gene, for given k: 1 <= cluster <= k
next if $clust < 0 && $bkg eq 'opposite'; # only need to compare set-antiset one way; drop reverse comparison
my (%clustergpids, $bkgcount);
my $rowcount = scalar (keys %{ $ksets{$k}{$clust} }); # total rows in cluster
$siginco{$k}{$clust}{A} = $siginco{$k}{$clust}{S} = 0; # ensure printable values for later
# print " k $k cluster $clust: $rowcount rows\n";
## find GO identifiers for row identifiers
foreach my $row (sort {$a <=> $b} keys %{ $ksets{$k}{$clust} }) { # incoming row identifiers from clustering matrix
my (%termhits, %rowhits);
foreach my $gene (keys %{ $equivalents{R2G}{$row} }) { # 1 or more equivalent identifiers for the pending row
if (exists $idtable{2}{$taxon}{$gene}) { # identifier found in DB
my $gpid = $idtable{2}{$taxon}{$gene};
$termhits{GENE}{$gene} = 1;
$termhits{GPID}{$gpid} = 1;
$clustergpids{$gpid} = 1;
foreach my $tid (keys %{ $allterms{G2I}{$taxon}{$gpid} }) {
# print "$k | $clust | $row | $tid\n";
$termrows{$k}{$clust}{$tid}{C}{$row} = 1;
$rowhits{$tid} = 1;
}
} else {
# $ksetlost{$k}{$clust}{$row}{$gene} = 1;
$all_lost++;
}
}
if (%termhits) {
my $hitgenes = join ',', (sort keys %{ $termhits{GENE} });
my $hitaccs = join ',', map { $allterms{I2A}{$_} } (keys %rowhits);
$mappings{$row} = "$row\t$originals{$row}\t$hitgenes\t$hitaccs\n";
} else {
# $rowlost{$k}{$clust}{$row} = 1; # none of the row identifiers were found in DB
$mappings{$row} = "$row\t$originals{$row}\t\n";
}
}
## pool GO identifiers for the background
if ($bkg eq "genome") {
my %termlist;
foreach my $gpid (keys %{ $idtable{1}{$taxon} }) {
unless (exists $clustergpids{$gpid}) {
$termlist{$gpid} = 1;
$termrows{$k}{$clust}{$_}{B}{$gpid} = 1 foreach (keys %{ $allterms{G2I}{$taxon}{$gpid} }); # here, $gpid subs for $row
}