-
Notifications
You must be signed in to change notification settings - Fork 0
/
soba_biggo.cgi
executable file
·1933 lines (1747 loc) · 114 KB
/
soba_biggo.cgi
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/perl
# partially cleaned up amigo.cgi from 12.204 to only produce SObA 2016 12 14
# /~raymond/cgi-bin/soba_biggo.cgi?action=annotSummaryCytoscape&autocompleteValue=F56F4.3%20(Caenorhabditis%20elegans,%20WB:WBGene00018980,%20-,%20-)&showControlsFlag=1
# on wormbase
# root/templates/classes/gene/phenotype_graph.tt2
# lib/WormBase/API/Object/Gene.pm
# root/js/wormbase.js
# anatomy, disease, go, lifestage, and phenotype
# Show "No observed ...", e.g.
# https://wormbase.org/species/c_elegans/gene/WBGene00002159#0b--10
# ZK512.8
use CGI;
use strict;
use HTML::Entities; # for untainting with encode_entities()
use LWP::Simple;
use LWP::UserAgent;
use JSON;
use Tie::IxHash; # allow hashes ordered by item added
use Net::Domain qw(hostname hostfqdn hostdomain);
use Storable qw(dclone); # copy hash of hashes
use Time::HiRes qw( time );
my $startTime = time; my $prevTime = time;
$startTime =~ s/(\....).*$/$1/;
$prevTime =~ s/(\....).*$/$1/;
my $hostname = hostname();
# my $top_datatype = 'phenotype';
my $json = JSON->new->allow_nonref;
my $query = new CGI;
# my $base_solr_url = "http://localhost:8080/solr/$top_datatype/"; # big geneontology golr server
my $base_solr_url = "http://localhost:8080/solr/"; # big geneontology golr server
my %paths; # finalpath => array of all (array of nodes of paths that end)
# childToParent -> child node -> parent node => relationship
# # parentToChild -> parent node -> child node => relationship
my %nodesAll; # for an annotated phenotype ID, all nodes in its topological map that have transitivity
my %edgesAll; # for an annotated phenotype ID, all edges in its topological map that have transitivity
my %ancestorNodes;
&process();
sub process {
my $action; # what user clicked
unless ($action = $query->param('action')) { $action = 'none'; }
if ($action eq 'annotSummaryCytoscape') { &annotSummaryCytoscape('all_roots'); }
elsif ($action eq 'annotSummaryGraph') { &annotSummaryGraph(); }
elsif ($action eq 'annotSummaryJson') { &annotSummaryJson(); } # temporarily keep this for the live www.wormbase going through the fake phenotype_graph_json widget
elsif ($action eq 'annotSummaryJsonp') { &annotSummaryJsonp(); } # new jsonp widget to get directly from .wormbase without fake widget
elsif ($action eq 'frontPage') { &frontPage(); } # autocomplete on gene names
elsif ($action eq 'autocompleteXHR') { &autocompleteXHR(); }
else { &frontPage(); } # no action, show dag by default
} # sub process
sub autocompleteXHR {
print "Content-type: text/html\n\n";
my ($var, $words) = &getHtmlVar($query, 'query');
unless ($words) { ($var, $words) = &getHtmlVar($query, 'query'); }
($var, my $field) = &getHtmlVar($query, 'field');
if ($field eq 'Gene') { &autocompleteGene($words); }
} # sub autocompleteXHR
sub autocompleteGene {
my ($words) = @_;
my ($var, $taxonFq) = &getHtmlVar($query, 'taxonFq');
my ($var, $datatype) = &getHtmlVar($query, 'datatype');
my $max_results = 20;
my $escapedWords = $words;
my $lcwords = lc($escapedWords);
my $ucwords = uc($escapedWords);
$escapedWords =~ s/ /%5C%20/g;
$escapedWords =~ s/:/\\:/g;
my %matches; my $t = tie %matches, "Tie::IxHash"; # sorted hash to filter results
my $datatype_solr_url = $base_solr_url . $datatype . '/';
# Exact match (case sensitive)
my $solr_gene_url = $datatype_solr_url . 'select?qt=standard&fl=score,id,bioentity_internal_id,synonym,bioentity_label,bioentity_name,taxon,taxon_label&version=2.2&wt=json&rows=' . $max_results . '&indent=on&q=*:*&fq=document_category:%22bioentity%22&fq=(bioentity_internal_id:' . $escapedWords . '+OR+bioentity_label:' . $escapedWords . '+OR+bioentity_name:' . $escapedWords . '+OR+synonym:' . $escapedWords . ')';
if ($taxonFq) { $solr_gene_url .= "&fq=($taxonFq)"; }
my ($matchesHashref) = &solrSearch( $solr_gene_url, \%matches, $max_results);
%matches = %$matchesHashref;
# String wildcard match (case sensitive)
my $matchesCount = scalar keys %matches;
if ($matchesCount < $max_results) {
my $extraMatchesCount = $max_results - $matchesCount;
$solr_gene_url = $datatype_solr_url . 'select?qt=standard&fl=score,id,bioentity_internal_id,synonym,bioentity_label,bioentity_name,taxon,taxon_label&version=2.2&wt=json&rows=' . $max_results . '&indent=on&q=*:*&fq=document_category:%22bioentity%22&fq=(bioentity_internal_id:' . $escapedWords . '*+OR+bioentity_label:' . $escapedWords . '*+OR+bioentity_name:' . $escapedWords . '*+OR+synonym:' . $escapedWords . '*)';
if ($taxonFq) { $solr_gene_url .= "&fq=($taxonFq)"; }
my ($matchesHashref) = &solrSearch( $solr_gene_url, \%matches, $max_results);
%matches = %$matchesHashref;
}
my @words; my $isPhrase = 0;
if ($words =~ m/[\s\-]/) {
$isPhrase++;
(@words) = split/[\s\-]/, $words; }
if ($isPhrase) {
my $lastWord = pop @words;
my $firstWord = join" ", @words;
my $extraMatchesCount = $max_results - $matchesCount;
$solr_gene_url = $datatype_solr_url . 'select?qt=standard&fl=score,id,bioentity_internal_id,synonym,bioentity_label,bioentity_name,taxon,taxon_label&version=2.2&wt=json&rows=' . $max_results . '&indent=on&q=*:*&fq=document_category:%22bioentity%22&fq=((bioentity_internal_id_searchable:"' . $firstWord . '"+AND+bioentity_internal_id_searchable:' . $lastWord . '*)+OR+(bioentity_name_searchable:"' . $firstWord . '"+AND+bioentity_name_searchable:' . $lastWord . '*)+OR+(bioentity_label_searchable:"' . $firstWord . '"+AND+bioentity_label_searchable:' . $lastWord . '*)+OR+(synonym_searchable:"' . $firstWord . '"+AND+synonym_searchable:' . $lastWord . '*))';
# :8080/solr/$datatype/select?qt=standard&fl=score,id,bioentity_internal_id,bioentity_label,bioentity_name,synonym,taxon,taxon_label&version=2.2&wt=json&rows=500&indent=on&q=*:*&fq=document_category:%22bioentity%22&fq=
if ($taxonFq) { $solr_gene_url .= "&fq=($taxonFq)"; }
my ($matchesHashref) = &solrSearch( $solr_gene_url, \%matches, $max_results);
%matches = %$matchesHashref;
} else { # not a phrase
# Exact match (case insensitive _searchable)
$matchesCount = scalar keys %matches;
if ($matchesCount < $max_results) {
my $extraMatchesCount = $max_results - $matchesCount;
$solr_gene_url = $datatype_solr_url . 'select?qt=standard&fl=score,id,bioentity_internal_id,synonym,bioentity_label,bioentity_name,taxon,taxon_label&version=2.2&wt=json&rows=' . $max_results . '&indent=on&q=*:*&fq=document_category:%22bioentity%22&fq=(bioentity_internal_id_searchable:' . $escapedWords . '+OR+bioentity_label_searchable:' . $escapedWords . '+OR+bioentity_name_searchable:' . $escapedWords . '+OR+synonym_searchable:' . $escapedWords . ')';
if ($taxonFq) { $solr_gene_url .= "&fq=($taxonFq)"; }
my ($matchesHashref) = &solrSearch( $solr_gene_url, \%matches, $max_results);
%matches = %$matchesHashref;
}
# Starting with word Wildcard match (case insensitive _searchable)
$matchesCount = scalar keys %matches;
if ($matchesCount < $max_results) {
my $extraMatchesCount = $max_results - $matchesCount;
$solr_gene_url = $datatype_solr_url . 'select?qt=standard&fl=score,id,bioentity_internal_id,synonym,bioentity_label,bioentity_name,taxon,taxon_label&version=2.2&wt=json&rows=' . $max_results . '&indent=on&q=*:*&fq=document_category:%22bioentity%22&fq=(bioentity_internal_id_searchable:' . $escapedWords . '*+OR+bioentity_label_searchable:' . $escapedWords . '*+OR+bioentity_name_searchable:' . $escapedWords . '*+OR+synonym_searchable:' . $escapedWords . '*)';
if ($taxonFq) { $solr_gene_url .= "&fq=($taxonFq)"; }
my ($matchesHashref) = &solrSearch( $solr_gene_url, \%matches, $max_results);
%matches = %$matchesHashref;
}
}
my $matches = join"\n", keys %matches;
print $matches;
} # sub autocompleteGene
sub solrSearch {
my ($solr_gene_url, $matchesHashref, $max_results) = @_;
my $matchesCount = scalar keys %$matchesHashref;
if ($matchesCount < $max_results) {
my $page_data = get $solr_gene_url;
unless ($page_data) { return $matchesHashref; }
my $perl_scalar = $json->decode( $page_data );
my %jsonHash = %$perl_scalar;
foreach my $geneHash (@{ $jsonHash{"response"}{"docs"} }) {
my %geneHash = %$geneHash;
my $id = $geneHash{id} || '-';
my $synonym = '-';
my $synonymRef = $geneHash{synonym} || '';
if ($synonymRef) {
my (@syns) = @$synonymRef;
$synonym = join ", ", @syns; }
my $taxon_label = $geneHash{taxon_label} || '-';
my $bioentity_label = $geneHash{bioentity_label} || '-';
my $bioentity_name = $geneHash{bioentity_name} || '-';
my $entry = qq($bioentity_label ($taxon_label, $id, $bioentity_name, $synonym));
unless ($$matchesHashref{$entry}) { $$matchesHashref{$entry}++; }
}
if (scalar (@{ $jsonHash{"response"}{"docs"} }) >= $max_results) { $$matchesHashref{"more results not shown; narrow your search"}++; }
} # if (scalar keys %matches < $max_results)
return $matchesHashref;
}
sub frontPage {
print "Content-type: text/html\n\n";
my $title = 'SObA pick a gene';
my $header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><HTML><HEAD>';
$header .= "<title>$title</title>\n";
$header .= '<link rel="stylesheet" href="http://tazendra.caltech.edu/~azurebrd/stylesheets/jex.css" />';
$header .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.7.0/build/autocomplete/assets/skins/sam/autocomplete.css\" />";
$header .= "<style type=\"text/css\">#forcedPersonAutoComplete { width:25em; padding-bottom:2em; } .div-autocomplete { padding-bottom:1.5em; }</style>";
$header .= qq(<style type="text/css">#forcedProcessAutoComplete { width:30em; padding-bottom:2em; } </style>);
$header .= <<"EndOfText";
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/autocomplete/assets/skins/sam/autocomplete.css" />
<link rel="stylesheet" type="text/css" href="http://tazendra.caltech.edu/~azurebrd/stylesheets/jex.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/fonts/fonts-min.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/connection/connection-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/datasource/datasource-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/autocomplete/autocomplete-min.js"></script>
<script type="text/javascript" src="../javascript/soba_biggo.js"></script>
EndOfText
$header .= "</head>";
$header .= '<body class="yui-skin-sam">';
print qq($header);
print << "EndOfText";
<B>Choose a gene <!--<span style="color: red;">*</span>--></B>
<font size="-2" color="#3B3B3B">Start typing in a gene and choose from the drop-down.</font>
<span id="containerForcedGeneAutoComplete">
<div id="forcedGeneAutoComplete">
<input size="50" name="gene" id="input_Gene" type="text" style="max-width: 444px; width: 99%; background-color: #E1F1FF;" value="">
<div id="forcedGeneContainer"></div>
</div></span><br/><br/>
<br/>
EndOfText
my $datatype = 'biggo'; # by defalt for front page
my $solr_taxon_url = $base_solr_url . $datatype . '/select?qt=standard&fl=id,taxon,taxon_label&version=2.2&wt=json&rows=0&indent=on&q=*:*&facet=true&facet.field=taxon_label&facet.mincount=1&fq=document_category:%22bioentity%22';
my $page_data = get $solr_taxon_url;
my $perl_scalar = $json->decode( $page_data );
my %jsonHash = %$perl_scalar;
print qq(Select a datatype to display.<br/>\n);
my @datatypes = qw( anatomy disease biggo go lifestage phenotype );
foreach my $datatype (@datatypes) {
my $checked = '';
if ($datatype eq 'phenotype') { $checked = qq(checked="checked"); }
print qq(<input type="radio" name="radio_datatype" id="radio_datatype" value="$datatype" $checked onclick="setAutocompleteListeners();" >$datatype</input><br/>\n); }
print qq(<br/>Prioritize search by selecting one or more species.<br/>\n);
my %taxons;
# print qq(<input type="checkbox" class="taxon_all" name="taxon_all" id="taxon_all" value="all" checked="checked">All Taxons</input><br/>\n);
my @priorityTaxons = ( 'Homo sapiens', 'Arabidopsis thaliana', 'Caenorhabditis elegans', 'Danio rerio', 'Drosophila melanogaster', 'Escherichia coli K-12', 'Mus musculus', 'Rattus norvegicus', 'Saccharomyces cerevisiae S288c' );
my %priorityTaxons;
foreach my $taxon (@priorityTaxons) {
$priorityTaxons{$taxon}++;
my $taxon_plus = $taxon; $taxon_plus =~ s/ /+/g;
print qq(<input type="checkbox" class="taxon" name="$taxon" id="$taxon" value="$taxon_plus" onclick="setAutocompleteListeners();">$taxon</input><br/>\n);
}
print qq(<br/>);
print qq(<br/>Additional species.<br/>);
while (scalar (@{ $jsonHash{"facet_counts"}{"facet_fields"}{"taxon_label"} }) > 0) {
my $taxon = shift @{ $jsonHash{"facet_counts"}{"facet_fields"}{"taxon_label"} };
my $someNumber = shift @{ $jsonHash{"facet_counts"}{"facet_fields"}{"taxon_label"} };
next if ($priorityTaxons{$taxon}); # already entered before
my $taxon_plus = $taxon; $taxon_plus =~ s/ /+/g;
$taxons{qq(<input type="checkbox" class="taxon" name="$taxon" id="$taxon" value="$taxon_plus" onclick="setAutocompleteListeners();">$taxon</input><br/>\n)}++;
}
foreach my $taxon (sort keys %taxons) {
print $taxon;
}
print qq(</body></html>);
} # sub frontPage
sub makeInputField {
my ($current_value, $table, $order, $colspan, $rowspan, $class, $td_width, $input_size) = @_;
unless ($current_value) { $current_value = ''; }
my $freeForced = 'free';
my $containerSpanId = "container${freeForced}${table}${order}AutoComplete";
my $divAutocompleteId = "${freeForced}${table}${order}AutoComplete";
my $inputId = "input_${table}_$order";
my $divContainerId = "${freeForced}${table}${order}Container";
my $data = "<td width=\"$td_width\" class=\"$class\" rowspan=\"$rowspan\" colspan=\"$colspan\">
<span id=\"$containerSpanId\">
<div id=\"$divAutocompleteId\" class=\"div-autocomplete\">
<input id=\"$inputId\" name=\"$inputId\" size=\"$input_size\" value=\"$current_value\">
<div id=\"$divContainerId\"></div></div></span>
</td>";
return $data;
} # sub makeInputField
sub getSolrUrl {
my ($focusTermId) = @_;
my ($identifierType) = $focusTermId =~ m/^(\w+):/;
my %idToSubdirectory;
$idToSubdirectory{"WBbt"} = "anatomy";
$idToSubdirectory{"DOID"} = "disease";
$idToSubdirectory{"GO"} = "go";
$idToSubdirectory{"WBls"} = "lifestage";
$idToSubdirectory{"WBPhenotype"} = "phenotype";
my $solr_url = $base_solr_url . '/';
} # sub getSolrUrl
sub getTopoHash {
my ($focusTermId) = @_;
my ($solr_url) = &getSolrUrl($focusTermId);
my $url = $solr_url . "select?qt=standard&fl=*&version=2.2&wt=json&indent=on&rows=1&q=id:%22" . $focusTermId . "%22&fq=document_category:%22ontology_class%22";
my $page_data = get $url;
my $perl_scalar = $json->decode( $page_data );
my %jsonHash = %$perl_scalar;
my $topoHashref = $json->decode( $jsonHash{"response"}{"docs"}[0]{"topology_graph_json"} );
my $transHashref = $json->decode( $jsonHash{"response"}{"docs"}[0]{"regulates_transitivity_graph_json"} ); # need this for inferred Tree View
return ($topoHashref, $transHashref);
} # sub getTopoHash
sub getTopoChildrenParents {
my ($focusTermId, $topoHref) = @_;
my %topo = %$topoHref;
my %children; # children of the wanted focusTermId, value is relationship type (predicate) ; are the corresponding nodes on an edge where the object is the focusTermId
my %parents; # direct parents of the wanted focusTermId, value is relationship type (predicate) ; are the corresponding nodes on an edge where the subject is the focusTermId
my %child; # for any term, each subkey is a child
my (@edges) = @{ $topo{"edges"} };
for my $index (0 .. @edges) {
my ($sub, $obj, $pred) = ('', '', '');
if ($edges[$index]{'sub'}) { $sub = $edges[$index]{'sub'}; }
if ($edges[$index]{'obj'}) { $obj = $edges[$index]{'obj'}; }
if ($edges[$index]{'pred'}) { $pred = $edges[$index]{'pred'}; }
if ($obj eq $focusTermId) { $children{$sub} = $pred; } # track children here
if ($sub eq $focusTermId) { $parents{$obj} = $pred; } # track parents here
}
return (\%children, \%parents);
} # sub getTopoChildrenParents
sub calcNodeWidth {
my ($nodeCount, $maxAnyCount) = @_;
unless ($maxAnyCount) { $maxAnyCount = 1; }
my $nodeWidth = 1; my $nodeScale = 1.5; my $nodeMinSize = 0.01; my $logScaler = .6;
$nodeWidth = ( sqrt($nodeCount)/sqrt($maxAnyCount) * $nodeScale ) + $nodeMinSize;
return $nodeWidth;
} # sub calcNodeWidth
sub getDiffTime {
my ($start, $prev, $message) = @_;
my $now = time;
$now =~ s/(\....).*$/$1/;
my $diffStart = $now - $startTime;
$diffStart =~ s/(\....).*$/$1/;
my $diffPrev = $now - $prevTime;
$diffPrev =~ s/(\....).*$/$1/;
$prevTime = $now;
$message = qq($diffStart seconds from start, $diffPrev seconds from previous check. Now $message);
return ($message);
} # sub getDiffTime
sub populateGeneNamesFromFlatfile {
my %geneNameToId; my %geneIdToName;
my $infile = '/home/azurebrd/cron/gin_names/gin_names.txt';
open (IN, "<$infile") or die "Cannot open $infile : $!";
while (my $line = <IN>) {
chomp $line;
my ($id, $name, $primary) = split/\t/, $line;
if ($primary eq 'primary') { $geneIdToName{$id} = $name; }
my ($lcname) = lc($name);
$geneNameToId{$lcname} = $id; }
close (IN) or die "Cannot close $infile : $!";
return (\%geneNameToId, \%geneIdToName);
} # sub populateGeneNamesFromFlatfile
sub calculateNodesAndEdgesAMIGO {
my ($focusTermId, $datatype) = @_;
unless ($datatype) { $datatype = 'phenotype'; } # later will need to change based on different datatypes
my $toReturn = '';
# my ($solr_url) = &getSolrUrl($focusTermId);
my $solr_url = $base_solr_url . 'phenotype/';
# link 1, from wbgene get wbphenotypes from "grouped":{ "annotation_class":{ "matches":12, "ngroups":4, "groups":[{ "groupValue":"WBPhenotype:0000674", # }]}}
my $rootId = 'WBPhenotype:0000886';
if ($datatype eq 'phenotype') { $rootId = 'WBPhenotype:0000886'; }
my %allLca; # all nodes that are LCA to any pair of annotated terms
my %nodes;
my %edgesPtc; # edges from parent to child
my $nodeWidth = 1;
my $weightedNodeWidth = 1;
my $unweightedNodeWidth = 1;
my %annotationCounts; # get annotation counts from evidence type
my %phenotypes; my @annotPhenotypes; # array of annotated terms to loop and do pairwise comparisons
my $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=bioentity:%22WB:' . $focusTermId . '%22';
my $page_data = get $annotation_count_solr_url; # get the URL
my $perl_scalar = $json->decode( $page_data ); # get the solr data
my %jsonHash = %$perl_scalar;
foreach my $doc (@{ $jsonHash{'response'}{'docs'} }) {
my $phenotype = $$doc{'annotation_class'};
$phenotypes{$phenotype}++;
my $id = $$doc{'id'};
my $varCount = 0; my $rnaiCount = 0;
if ($id =~ m/WB:WBVar\d+/) { my (@wbvar) = $id =~ m/(WB:WBVar\d+)/g; $varCount = scalar @wbvar; }
if ($id =~ m/WB:WBRNAi\d+/) { my (@wbrnai) = $id =~ m/(WB:WBRNAi\d+)/g; $rnaiCount = scalar @wbrnai; }
foreach my $phenotype (@{ $$doc{'regulates_closure'} }) {
if ($varCount) { for (1 .. $varCount) { $annotationCounts{$phenotype}{'any'}++; $annotationCounts{$phenotype}{'Allele'}++;
$nodes{$phenotype}{'counts'}{'any'}++; $nodes{$phenotype}{'counts'}{'Allele'}++; } }
if ($rnaiCount) { for (1 .. $rnaiCount) { $annotationCounts{$phenotype}{'any'}++; $annotationCounts{$phenotype}{'RNAi'}++;
$nodes{$phenotype}{'counts'}{'any'}++; $nodes{$phenotype}{'counts'}{'RNAi'}++; } }
}
}
foreach my $phenotypeId (sort keys %phenotypes) {
push @annotPhenotypes, $phenotypeId;
my $phenotype_solr_url = $solr_url . 'select?qt=standard&fl=regulates_transitivity_graph_json,topology_graph_json&version=2.2&wt=json&indent=on&rows=1&fq=-is_obsolete:true&fq=document_category:%22ontology_class%22&q=id:%22' . $phenotypeId . '%22';
my $page_data = get $phenotype_solr_url; # get the URL
my $perl_scalar = $json->decode( $page_data ); # get the solr data
my %jsonHash = %$perl_scalar;
my $gviz = GraphViz2->new(concentrate => 'concentrate'); # generate graphviz for main markup
my $transHashref = $json->decode( $jsonHash{"response"}{"docs"}[0]{"regulates_transitivity_graph_json"} );
my %transHash = %$transHashref;
my (@nodes) = @{ $transHash{"nodes"} };
my %transNodes; # track transitivity nodes as nodes to keep from topology data
for my $index (0 .. @nodes) { if ($nodes[$index]{'id'}) { my $id = $nodes[$index]{'id'}; $transNodes{$id}++; } }
my $topoHashref = $json->decode( $jsonHash{"response"}{"docs"}[0]{"topology_graph_json"} );
my %topoHash = %$topoHashref;
my (@edges) = @{ $topoHash{"edges"} };
for my $index (0 .. @edges) { # for each edge, add to graph
my ($sub, $obj, $pred) = ('', '', ''); # subject object predicate from topology_graph_json
if ($edges[$index]{'sub'}) { $sub = $edges[$index]{'sub'}; }
if ($edges[$index]{'obj'}) { $obj = $edges[$index]{'obj'}; }
next unless ( ($transNodes{$sub}) && ($transNodes{$obj}) );
if ($edges[$index]{'pred'}) { $pred = $edges[$index]{'pred'}; }
my $direction = 'back'; my $style = 'solid'; # graph arror direction and style
if ($sub && $obj && $pred) { # if subject + object + predicate
$edgesAll{$phenotypeId}{$sub}{$obj}++; # for an annotated term's edges, each child to its parents
$edgesPtc{$obj}{$sub}++; # any existing edge, parent to child
} # if ($sub && $obj && $pred)
} # for my $index (0 .. @edges)
my (@nodes) = @{ $topoHash{"nodes"} };
for my $index (0 .. @nodes) { # for each node, add to graph
my ($id, $lbl) = ('', ''); # id and label
if ($nodes[$index]{'id'}) { $id = $nodes[$index]{'id'}; }
if ($nodes[$index]{'lbl'}) { $lbl = $nodes[$index]{'lbl'}; }
next unless ($id);
$nodes{$id}{label} = $lbl;
next unless ($transNodes{$id});
# $lbl =~ s/ /<br\/>/g; # replace spaces with html linebreaks in graph for more-square boxes
my $label = "$lbl"; # node label should have full id, not stripped of :, which is required for edge title text
if ($annotationCounts{$id}) { # if there are annotation counts to variation and/or rnai, add them to the box
my @annotCounts;
foreach my $evidenceType (sort keys %{ $annotationCounts{$id} }) {
next if ($evidenceType eq 'any'); # skip 'any', only used for relative size to max value
push @annotCounts, qq($annotationCounts{$id}{$evidenceType} $evidenceType); }
my $annotCounts = join"; ", @annotCounts;
$label = qq(LINEBREAK<br\/>$label<br\/><font color="transparent">$annotCounts<\/font>); # add html line break and annotation counts to the label
}
if ($id && $lbl) {
$nodesAll{$phenotypeId}{$id} = $lbl;
}
}
} # foreach my $phenotype (sort keys %phenotypes)
while (@annotPhenotypes) {
my $ph1 = shift @annotPhenotypes; # compare each annotated term node to all other annotated term nodes
my $url = "http://www.wormbase.org/species/all/phenotype/$ph1"; # URL to link to wormbase page for object
my $xlabel = $ph1; # FIX
$nodes{$ph1}{annot}++;
foreach my $ph2 (@annotPhenotypes) { # compare each annotated term node to all other annotated term nodes
my $lcaHashref = &calculateLCA($ph1, $ph2);
my %lca = %$lcaHashref;
foreach my $lca (sort keys %lca) {
$url = "http://www.wormbase.org/species/all/phenotype/$lca"; # URL to link to wormbase page for object
$allLca{$lca}++;
unless ($phenotypes{$lca}) { # only add lca nodes that are not annotated terms
$xlabel = $lca; # FIX
$nodes{$lca}{lca}++;
}
} # foreach my $lca (sort keys %lca)
} # foreach my $ph2 (@annotPhenotypes) # compare each annotated term node to all other annotated term nodes
} # while (@annotPhenotypes)
my %edgesLca; # edges that exist in graph generated from annoated terms + lca terms + root
my @parentNodes = ($rootId); # nodes that are parents, at first root, later any nodes that should be in graph
while (@parentNodes) { # while there are parent nodes, go through them
my $parent = shift @parentNodes; # take a parent
my %edgesPtcCopy = %{ dclone(\%edgesPtc) }; # make a temp copy since edges will be getting deleted per parent
while (scalar keys %{ $edgesPtcCopy{$parent} } > 0) { # while parent has children
foreach my $child (sort keys %{ $edgesPtcCopy{$parent} }) { # each child of parent
if ($allLca{$child} || $phenotypes{$child}) { # good node, keep edge when child is an lca or annotated term
delete $edgesPtcCopy{$parent}{$child}; # remove from %edgesPtc, does not need to be checked further
push @parentNodes, $child; # child is a good node, add to parent list to check its children
$edgesLca{$parent}{$child}++; } # add parent-child edge to final graph
else { # bad node, remove and reconnect edges
delete $edgesPtcCopy{$parent}{$child}; # remove parent-child edge
foreach my $grandchild (sort keys %{ $edgesPtcCopy{$child} }) { # take each grandchild of child
delete $edgesPtcCopy{$child}{$grandchild}; # remove child-grandchild edge
$edgesPtcCopy{$parent}{$grandchild}++; } } # make replacement edge between parent and grandchild
} # foreach my $child (sort keys %{ $edgesPtcCopy{$parent} })
} # while (scalar keys %{ $edgesPtcCopy{$parent} } > 0)
} # while (@parentNodes)
foreach my $parent (sort keys %edgesLca) {
my $parent_placeholder = $parent;
$parent_placeholder =~ s/:/_placeholderColon_/g; # edges won't have proper title text if ids have : in them
foreach my $child (sort keys %{ $edgesLca{$parent} }) {
my $child_placeholder = $child;
$child_placeholder =~ s/:/_placeholderColon_/g; # edges won't have proper title text if ids have : in them
# $toReturn .= qq(EDGE $parent TO $child E<br/>\n);
# $gviz_lca_edges->add_edge(from => "$parent_placeholder", to => "$child_placeholder", dir => "$direction", color => "$edgecolor", fontcolor => "$edgecolor", style => "$style", arrowsize => ".3");
# $gviz_lca_unweighted->add_edge(from => "$parent_placeholder", to => "$child_placeholder", dir => "$direction", color => "$edgecolor", fontcolor => "$edgecolor", style => "$style", arrowsize => ".3");
# $gviz_homogeneous->add_edge(from => "$parent_placeholder", to => "$child_placeholder", dir => "$direction", color => "$edgecolor", fontcolor => "$edgecolor", style => "$style", arrowsize => ".3");
} # foreach my $child (sort keys %{ $edgesLca{$parent} })
} # foreach my $parent (sort keys %edgesLca)
# foreach my $node (sort keys %nodes) {
# if ($nodes{$node}{annot}) { $toReturn .= qq($node annot<br/>); }
# elsif ($nodes{$node}{lca}) { $toReturn .= qq($node lca<br/>); }
# }
return ($toReturn, \%nodes, \%edgesLca);
} # sub calculateNodesAndEdgesAMIGO
sub calculateNodesAndEdges {
my ($focusTermId, $datatype, $rootsChosen, $filterForLcaFlag, $maxDepth, $maxNodes) = @_;
my (@parentNodes) = split/,/, $rootsChosen;
unless ($datatype) { $datatype = 'phenotype'; } # later will need to change based on different datatypes
# if ($datatype eq 'phenotype') { # FIX should come from function call
# @parentNodes = ( 'WBPhenotype:0000886'); # TESTING , doesn't work 2019 03 01
# }
# # radio_etgo=radio_etgo_withiea&rootsChosen=&maxNodes=0&maxDepth=0&filterLongestFlag=0&filterForLcaFlag=1
# # radio_etgo=radio_etgo_withiea&rootsChosen= &showControlsFlag=1&fakeRootFlag=0&filterForLcaFlag=1&filterLongestFlag=0&maxNodes=0&maxDepth=0
# # radio_etgo= &rootsChosen=WBPhenotype:0000886&showControlsFlag=1 &filterForLcaFlag=0&filterLongestFlag=0&maxNodes=0&maxDepth=0
my ($var, $radio_etgo) = &getHtmlVar($query, 'radio_etgo');
my ($var, $radio_etp) = &getHtmlVar($query, 'radio_etp');
my ($var, $radio_etd) = &getHtmlVar($query, 'radio_etd');
my ($var, $radio_eta) = &getHtmlVar($query, 'radio_eta');
my $toReturn = '';
my $solr_url = $base_solr_url . $datatype . '/';
# link 1, from wbgene get wbphenotypes from "grouped":{ "annotation_class":{ "matches":12, "ngroups":4, "groups":[{ "groupValue":"WBPhenotype:0000674", # }]}}
my %allLca; # all nodes that are LCA to any pair of annotated terms
my %nodes;
my %edgesPtc; # edges from parent to child
my $nodeWidth = 1;
my $weightedNodeWidth = 1;
my $unweightedNodeWidth = 1;
# AMIGO
# my %annotationCounts; # get annotation counts from evidence type
# my %phenotypes; my @annotPhenotypes; # array of annotated terms to loop and do pairwise comparisons
# my $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=bioentity:%22' . $focusTermId . '%22';
# print qq( annotation_count_solr_url $annotation_count_solr_url\n); # get the URL
# my $page_data = get $annotation_count_solr_url; # get the URL
# my $perl_scalar = $json->decode( $page_data ); # get the solr data
# my %jsonHash = %$perl_scalar;
# foreach my $doc (@{ $jsonHash{'response'}{'docs'} }) {
# my $phenotype = $$doc{'annotation_class'};
# $phenotypes{$phenotype}++;
# my $id = $$doc{'id'};
# my $varCount = 0; my $rnaiCount = 0;
# if ($id =~ m/WB:WBVar\d+/) { my (@wbvar) = $id =~ m/(WB:WBVar\d+)/g; $varCount = scalar @wbvar; }
# if ($id =~ m/WB:WBRNAi\d+/) { my (@wbrnai) = $id =~ m/(WB:WBRNAi\d+)/g; $rnaiCount = scalar @wbrnai; }
# foreach my $phenotype (@{ $$doc{'regulates_closure'} }) {
# if ($varCount) { for (1 .. $varCount) { $annotationCounts{$phenotype}{'any'}++; $annotationCounts{$phenotype}{'Allele'}++;
# $nodes{$phenotype}{'counts'}{'any'}++; $nodes{$phenotype}{'counts'}{'Allele'}++; } }
# if ($rnaiCount) { for (1 .. $rnaiCount) { $annotationCounts{$phenotype}{'any'}++; $annotationCounts{$phenotype}{'RNAi'}++;
# $nodes{$phenotype}{'counts'}{'any'}++; $nodes{$phenotype}{'counts'}{'RNAi'}++; } }
# }
# }
# BIGGO
my %annotationCounts; # get annotation counts from evidence type
my %phenotypes; my @annotPhenotypes; # array of annotated terms to loop and do pairwise comparisons
my $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=bioentity:%22' . $focusTermId . '%22';
if ($radio_etgo) {
if ($radio_etgo eq 'radio_etgo_excludeiea') { $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=-evidence_type:IEA&fq=bioentity:%22' . $focusTermId . '%22'; }
elsif ($radio_etgo eq 'radio_etgo_onlyiea') { $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=bioentity,regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=evidence_type:(IDA+IEP+IGC+IGI+IMP+IPI)&fq=bioentity:%22' . $focusTermId . '%22'; } }
if ($radio_etp) {
if ($radio_etp eq 'radio_etp_onlyvariation') { $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=evidence_type:Variation&fq=bioentity:%22' . $focusTermId . '%22'; }
elsif ($radio_etp eq 'radio_etp_onlyrnai') { $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=evidence_type:RNAi&fq=bioentity:%22' . $focusTermId . '%22'; } }
if ($radio_etd) {
if ($radio_etd eq 'radio_etd_excludeiea') { $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=-evidence_type:IEA&fq=bioentity:%22' . $focusTermId . '%22'; } }
if ($radio_eta) {
if ($radio_eta eq 'radio_eta_onlyexprcluster') { $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=id:(*WB\:WBPaper*)&fq=bioentity:%22' . $focusTermId . '%22'; }
elsif ($radio_eta eq 'radio_eta_onlyexprpattern') { $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=id:(*WB\:Expr*+*WB\:Marker*)&fq=bioentity:%22' . $focusTermId . '%22'; } }
# Anatomy, Expr and Expression_cluster (ref.
# https://wormbase.org/tools/ontology_browser/show_genes?focusTermName=Anatomy&focusTermId=WBbt:0005766).
# There are three groups of objects WB:Expr***, WBMarker*** (these are Expression patterns), WB:WBPaper*** (these are Expression profiles).
# amigo.cgi query
# $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=bioentity:%22WB:' . $focusTermId . '%22';
my $page_data = get $annotation_count_solr_url; # get the URL
# print qq( annotation_count_solr_url $annotation_count_solr_url\n); # get the URL
# numFound == 0
my $perl_scalar = $json->decode( $page_data ); # get the solr data
my %jsonHash = %$perl_scalar;
if ($jsonHash{'response'}{'numFound'} == 0) { return ($toReturn, \%nodes, \%nodes); } # return nothing if there are no annotations found
foreach my $doc (@{ $jsonHash{'response'}{'docs'} }) {
my $phenotype = $$doc{'annotation_class'};
$phenotypes{$phenotype}++;
my $id = $$doc{'id'};
my (@idarray) = split/\t/, $id;
if ($datatype eq 'anatomy') {
my @entries = split/\|/, $idarray[7];
foreach my $entry (@entries) {
my $type = '';
if ($entry =~ m/^WB:Expr/) { $type = 'Expression Pattern'; }
elsif ($entry =~ m/^WBMarker/) { $type = 'Expression Pattern'; }
elsif ($entry =~ m/^WB:WBPaper/) { $type = 'Expression Cluster'; }
if ($type) {
foreach my $goid (@{ $$doc{'regulates_closure'} }) {
$annotationCounts{$goid}{'any'}++; $annotationCounts{$goid}{$type}++;
$nodes{$goid}{'counts'}{'any'}++; $nodes{$goid}{'counts'}{$type}++; } } } }
else {
my $type = $idarray[6];
if ($datatype eq 'lifestage') { if ($type eq 'IDA') { $type = 'Gene Expression'; } }
foreach my $goid (@{ $$doc{'regulates_closure'} }) {
$annotationCounts{$goid}{'any'}++; $annotationCounts{$goid}{$type}++;
$nodes{$goid}{'counts'}{'any'}++; $nodes{$goid}{'counts'}{$type}++; } }
}
# amigo.cgi
# my $annotation_count_solr_url = $solr_url . 'select?qt=standard&indent=on&wt=json&version=2.2&rows=100000&fl=regulates_closure,id,annotation_class&q=document_category:annotation&fq=-qualifier:%22not%22&fq=bioentity:%22WB:' . $focusTermId . '%22';
# my $phenotype_solr_url = $solr_url . 'select?qt=standard&fl=regulates_transitivity_graph_json,topology_graph_json&version=2.2&wt=json&indent=on&rows=1&fq=-is_obsolete:true&fq=document_category:%22ontology_class%22&q=id:%22' . $phenotypeId . '%22';
foreach my $phenotypeId (sort keys %phenotypes) {
push @annotPhenotypes, $phenotypeId;
my $phenotype_solr_url = $solr_url . 'select?qt=standard&fl=regulates_transitivity_graph_json,topology_graph_json&version=2.2&wt=json&indent=on&rows=1&fq=-is_obsolete:true&fq=document_category:%22ontology_class%22&q=id:%22' . $phenotypeId . '%22';
my $page_data = get $phenotype_solr_url; # get the URL
# print qq( phenotype_solr_url $phenotype_solr_url\n); # get the URL
my $perl_scalar = $json->decode( $page_data ); # get the solr data
my %jsonHash = %$perl_scalar;
next unless ($jsonHash{"response"}{"docs"}[0]{"regulates_transitivity_graph_json"} ); # term must have data to extra json from it
my $transHashref = $json->decode( $jsonHash{"response"}{"docs"}[0]{"regulates_transitivity_graph_json"} );
my %transHash = %$transHashref;
my (@nodes) = @{ $transHash{"nodes"} };
my %transNodes; # track transitivity nodes as nodes to keep from topology data
for my $index (0 .. @nodes) { if ($nodes[$index]{'id'}) { my $id = $nodes[$index]{'id'}; $transNodes{$id}++; } }
my $topoHashref = $json->decode( $jsonHash{"response"}{"docs"}[0]{"topology_graph_json"} );
my %topoHash = %$topoHashref;
my (@edges) = @{ $topoHash{"edges"} };
for my $index (0 .. @edges) { # for each edge, add to graph
my ($sub, $obj, $pred) = ('', '', ''); # subject object predicate from topology_graph_json
if ($edges[$index]{'sub'}) { $sub = $edges[$index]{'sub'}; }
if ($edges[$index]{'obj'}) { $obj = $edges[$index]{'obj'}; }
next unless ( ($transNodes{$sub}) && ($transNodes{$obj}) );
if ($edges[$index]{'pred'}) { $pred = $edges[$index]{'pred'}; }
my $direction = 'back'; my $style = 'solid'; # graph arror direction and style
if ($sub && $obj && $pred) { # if subject + object + predicate
$edgesAll{$phenotypeId}{$sub}{$obj}++; # for an annotated term's edges, each child to its parents
$edgesPtc{$obj}{$sub}++; # any existing edge, parent to child
} # if ($sub && $obj && $pred)
} # for my $index (0 .. @edges)
my (@nodes) = @{ $topoHash{"nodes"} };
for my $index (0 .. @nodes) { # for each node, add to graph
my ($id, $lbl) = ('', ''); # id and label
if ($nodes[$index]{'id'}) { $id = $nodes[$index]{'id'}; }
if ($nodes[$index]{'lbl'}) { $lbl = $nodes[$index]{'lbl'}; }
next unless ($id);
# UNDO THIS
# $lbl = "$id - $lbl"; # node label should have full id, not stripped of :, which is required for edge title text
$nodes{$id}{label} = $lbl;
next unless ($transNodes{$id});
# $lbl =~ s/ /<br\/>/g; # replace spaces with html linebreaks in graph for more-square boxes
my $label = "$lbl"; # node label should have full id, not stripped of :, which is required for edge title text
if ($annotationCounts{$id}) { # if there are annotation counts to variation and/or rnai, add them to the box
my @annotCounts;
foreach my $evidenceType (sort keys %{ $annotationCounts{$id} }) {
next if ($evidenceType eq 'any'); # skip 'any', only used for relative size to max value
push @annotCounts, qq($annotationCounts{$id}{$evidenceType} $evidenceType); }
my $annotCounts = join"; ", @annotCounts;
$label = qq(LINEBREAK<br\/>$label<br\/><font color="transparent">$annotCounts<\/font>); # add html line break and annotation counts to the label
}
if ($id && $lbl) {
$nodesAll{$phenotypeId}{$id} = $lbl;
}
}
} # foreach my $phenotypeId (sort keys %phenotypes)
if (!$filterForLcaFlag) {
foreach my $annotTerm (sort keys %nodesAll) {
$nodes{$annotTerm}{annot}++;
foreach my $phenotype (sort keys %{ $nodesAll{$annotTerm} }) {
# my $url = "http://www.wormbase.org/species/all/go_term/$phenotype"; # URL to link to wormbase page for object
$allLca{$phenotype}++;
unless ($phenotypes{$phenotype}) { # only add lca nodes that are not annotated terms
# print qq(NODES $phenotype LCA\n);
$nodes{$phenotype}{lca}++; } } } }
else {
while (@annotPhenotypes) {
my $ph1 = shift @annotPhenotypes; # compare each annotated term node to all other annotated term nodes
# my $url = "http://www.wormbase.org/species/all/go_term/$ph1"; # URL to link to wormbase page for object
my $xlabel = $ph1; # FIX
$nodes{$ph1}{annot}++;
foreach my $ph2 (@annotPhenotypes) { # compare each annotated term node to all other annotated term nodes
my $lcaHashref = &calculateLCA($ph1, $ph2);
my %lca = %$lcaHashref;
foreach my $lca (sort keys %lca) {
# $url = "http://www.wormbase.org/species/all/go_term/$lca"; # URL to link to wormbase page for object
$allLca{$lca}++;
unless ($phenotypes{$lca}) { # only add lca nodes that are not annotated terms
$xlabel = $lca; # FIX
$nodes{$lca}{lca}++;
}
} # foreach my $lca (sort keys %lca)
} # foreach my $ph2 (@annotPhenotypes) # compare each annotated term node to all other annotated term nodes
} # while (@annotPhenotypes)
}
my %edgesLca; # edges that exist in graph generated from annoated terms + lca terms + root
while (@parentNodes) { # while there are parent nodes, go through them
my $parent = shift @parentNodes; # take a parent
my %edgesPtcCopy = %{ dclone(\%edgesPtc) }; # make a temp copy since edges will be getting deleted per parent
while (scalar keys %{ $edgesPtcCopy{$parent} } > 0) { # while parent has children
foreach my $child (sort keys %{ $edgesPtcCopy{$parent} }) { # each child of parent
if ($allLca{$child} || $phenotypes{$child}) { # good node, keep edge when child is an lca or annotated term
delete $edgesPtcCopy{$parent}{$child}; # remove from %edgesPtc, does not need to be checked further
push @parentNodes, $child; # child is a good node, add to parent list to check its children
$edgesLca{$parent}{$child}++; } # add parent-child edge to final graph
else { # bad node, remove and reconnect edges
delete $edgesPtcCopy{$parent}{$child}; # remove parent-child edge
foreach my $grandchild (sort keys %{ $edgesPtcCopy{$child} }) { # take each grandchild of child
delete $edgesPtcCopy{$child}{$grandchild}; # remove child-grandchild edge
$edgesPtcCopy{$parent}{$grandchild}++; } } # make replacement edge between parent and grandchild
} # foreach my $child (sort keys %{ $edgesPtcCopy{$parent} })
} # while (scalar keys %{ $edgesPtcCopy{$parent} } > 0)
} # while (@parentNodes)
# don't think this does anything, did before for svg at some point
# foreach my $parent (sort keys %edgesLca) {
# my $parent_placeholder = $parent;
# $parent_placeholder =~ s/:/_placeholderColon_/g; # edges won't have proper title text if ids have : in them
# foreach my $child (sort keys %{ $edgesLca{$parent} }) {
# my $child_placeholder = $child;
# $child_placeholder =~ s/:/_placeholderColon_/g; # edges won't have proper title text if ids have : in them
# } # foreach my $child (sort keys %{ $edgesLca{$parent} })
# } # foreach my $parent (sort keys %edgesLca)
return ($toReturn, \%nodes, \%edgesLca);
} # sub calculateNodesAndEdges
sub annotSummaryJsonp {
my ($var, $datatype) = &getHtmlVar($query, 'datatype');
($var, my $callback) = &getHtmlVar($query, 'callback');
# /~azurebrd/cgi-bin/amigo.cgi?action=annotSummaryJsonp&focusTermId=WBGene00000899
# for cross domain access, needs to be jsonp with header below, content-type is different, json has a function wrapped around it.
print $query->header(
-type => 'application/javascript',
-access_control_allow_origin => '*',
);
if ($callback) { # Sibyl would like to assign the callback name as a parameter
print qq($callback\(\n); }
else {
my $ucfirstDatatype = ucfirst($datatype);
print qq(jsonCallback$ucfirstDatatype\(\n); } # need the datatype for separate widgets with different cytoscape graphs to tell which one they want back
&annotSummaryJsonCode();
print qq(\);\n);
} # sub annotSummaryJsonp
sub annotSummaryJson { # temporarily keep this for the live www.wormbase going through the fake phenotype_graph_json widget
# /~azurebrd/cgi-bin/amigo.cgi?action=annotSummaryJson&focusTermId=WBGene00000899
print qq(Content-type: application/json\n\n); # for json
&annotSummaryJsonCode();
} # sub annotSummaryJson
sub annotSummaryJsonCode {
my ($var, $focusTermId) = &getHtmlVar($query, 'focusTermId');
my ($var, $datatype) = &getHtmlVar($query, 'datatype');
my ($var, $fakeRootFlag) = &getHtmlVar($query, 'fakeRootFlag');
my ($var, $filterLongestFlag) = &getHtmlVar($query, 'filterLongestFlag');
my ($var, $filterForLcaFlag) = &getHtmlVar($query, 'filterForLcaFlag');
my ($var, $rootsChosen) = &getHtmlVar($query, 'rootsChosen');
my ($var, $maxNodes) = &getHtmlVar($query, 'maxNodes');
my ($var, $maxDepth) = &getHtmlVar($query, 'maxDepth');
($datatype) = lc($datatype);
unless ($maxNodes) { $maxNodes = 0; }
unless ($maxDepth) { $maxDepth = 0; }
unless ($rootsChosen) {
if ($datatype eq 'phenotype') { $rootsChosen = "WBPhenotype:0000886"; }
elsif ($datatype eq 'anatomy') { $rootsChosen = "WBbt:0000100"; }
elsif ($datatype eq 'disease') { $rootsChosen = "DOID:4"; }
elsif ($datatype eq 'lifestage') { $rootsChosen = "WBls:0000075"; }
}
my (@rootsChosen) = split/,/, $rootsChosen;
my ($return, $nodesHashref, $edgesLcaHashref) = &calculateNodesAndEdges($focusTermId, $datatype, $rootsChosen, $filterForLcaFlag, $maxDepth, $maxNodes);
if ($return) { print qq(RETURN $return ENDRETURN\n); }
my %nodes = %$nodesHashref;
my %edgesLca = %$edgesLcaHashref;
if ($fakeRootFlag) {
if ( ($datatype eq 'go') || ($datatype eq 'biggo') ) {
my $fakeRoot = 'GO:0000000';
$nodes{$fakeRoot}{label} = 'Gene Ontology';
$nodesAll{$fakeRoot}{label} = 'Gene Ontology';
foreach my $sub (@rootsChosen) {
if ($nodes{$sub}{'counts'}) { # root must have an annotation to be added
$edgesLca{$fakeRoot}{$sub}++; } # any existing edge, parent to child
} } }
my @nodes = ();
my %rootNodes;
my $rootNodeMaxAnnotationCount = 1; # max annotation count to calculate node size
foreach my $root (@rootsChosen) {
$rootNodes{$root}++; # add to roots hash
if ($nodes{$root}{'counts'}{'any'}) { # find maximum annotation count among roots
if ($nodes{$root}{'counts'}{'any'} > $rootNodeMaxAnnotationCount) {
$rootNodeMaxAnnotationCount = $nodes{$root}{'counts'}{'any'}; } } }
if ($fakeRootFlag) {
if ( ($datatype eq 'go') || ($datatype eq 'biggo') ) {
$rootNodes{'GO:0000000'}++; } }
my $diameterMultiplier = 60;
# Original Max Nodes way
# if ($maxNodes) { # only show up to maxNodes amount of nodes
# my $count = 0;
# my %tempNodes; my %tempEdges;
# my (@parentNodes) = split/,/, $rootsChosen;
# if ($fakeRootFlag) { @parentNodes = ( 'GO:0000000' ); $maxNodes++; }
#
# foreach my $node (@parentNodes) {
# $count++;
# foreach my $type (keys %{ $nodes{$node} }) {
# $tempNodes{$node}{$type} = $nodes{$node}{$type}; } }
# while ( (scalar @parentNodes > 0) && ($count < $maxNodes) ) { # while there are parent nodes, go through them
# my $parent = shift @parentNodes; # take a parent
# foreach my $child (sort keys %{ $edgesLca{$parent} }) { # each child of parent
# $count++;
# foreach my $type (keys %{ $nodes{$child} }) {
# $tempNodes{$child}{$type} = $nodes{$child}{$type}; }
# push @parentNodes, $child; # child is a good node, add to parent list to check its children
# $tempEdges{$parent}{$child}++; # add parent-child edge to final graph
# } # foreach my $child (sort keys %{ $edgesPtcCopy{$parent} })
# } # while (@parentNodes)
# %nodes = %{ dclone(\%tempNodes) };
# %edgesLca = %{ dclone(\%tempEdges) };
# } # if ($maxNodes)
# my %edgesLcaAllTrimmed = %{ dclone(\%edgesLca) }; # all edges after trimming, before lopping
my %edgesFromLongest; # find edges that belong to the longest path from all nodes to each of their children (to remove indirect nodes, like a grandchild directly to the grandparent, bypassing the parent)
foreach my $source (sort keys %nodes) { # for all nodes, calculate longest paths to each child and add to %edgesFromLongest
foreach my $target (sort keys %{ $edgesLca{$source } }) {
%paths = ();
foreach my $source (sort keys %edgesLca) {
foreach my $target (sort keys %{ $edgesLca{$source } }) {
$paths{"childToParent"}{$target}{$source}++; } }
my ($edgesFromFinalPathHashref) = &getLongestPathAndTransitivity($source, $target);
my %edgesFromFinalPath = %$edgesFromFinalPathHashref;
foreach my $source (sort keys %{ $edgesFromFinalPath{'longest'} }) {
foreach my $target (sort keys %{ $edgesFromFinalPath{'longest'}{$source} }) {
$edgesFromLongest{$source}{$target}++; } }
} # foreach my $target (sort keys %{ $edgesLca{$source } })
} # foreach my $source (sort keys %nodes)
if ($filterLongestFlag) { # remove edges of non-longest path, which are redundant
my %tempEdges;
foreach my $source (sort keys %edgesLca) {
foreach my $target (sort keys %{ $edgesLca{$source } }) {
if ($edgesFromLongest{$target}{$source}) { $tempEdges{$source}{$target} = $edgesLca{$source}{$target}; } } }
%edgesLca = %{ dclone(\%tempEdges) }; }
my %edgesAfterLongestBeforeLopping = %{ dclone(\%edgesLca) };
my %nodesAfterLongestBeforeLopping = %{ dclone(\%nodes) };
# Lopping top layers to less than maxNodes
if ($maxNodes) { # only show up to maxNodes amount of nodes
my $count = 0;
my %tempNodes; my %tempEdges;
my %lastGoodNodes; my %lastGoodEdges;
my (@parentNodes) = split/,/, $rootsChosen;
if ($fakeRootFlag) { @parentNodes = ( 'GO:0000000' ); $maxNodes++; }
foreach my $node (@parentNodes) {
# $count++;
# print qq(NODE $node COUNT $count\n);
foreach my $type (keys %{ $nodes{$node} }) {
$tempNodes{$node}{$type} = $nodes{$node}{$type}; } }
my @nextLayerParentNodes = ();
while ( (scalar @parentNodes > 0) && ($count < $maxNodes) ) { # while there are parent nodes, go through them
my $parent = shift @parentNodes; # take a parent
foreach my $child (sort keys %{ $edgesLca{$parent} }) { # each child of parent
$tempEdges{$parent}{$child}++; # add parent-child edge to final graph
next if (exists $tempNodes{$child}); # skip children already added through other parent
$count++;
if ($parent eq 'GO:0000000') { $count--; } # never count nodes attached to fake root
# print qq(NODE CHILD $child PARENT $parent COUNT $count\n);
foreach my $type (keys %{ $nodes{$child} }) {
$tempNodes{$child}{$type} = $nodes{$child}{$type}; }
push @nextLayerParentNodes, $child; # child is a good node, add to parent list to check its children
} # foreach my $child (sort keys %{ $edgesLca{$parent} })
if ( (scalar @parentNodes == 0) && ($count < $maxNodes) ) {
@parentNodes = @nextLayerParentNodes;
@nextLayerParentNodes = ();
# print qq(NODE COUNT $count\n);
%lastGoodNodes = %{ dclone(\%tempNodes) };
%lastGoodEdges = %{ dclone(\%tempEdges) };
}
} # while (@parentNodes)
# %nodes = %{ dclone(\%tempNodes) };
# %edgesLca = %{ dclone(\%tempEdges) };
%nodes = %{ dclone(\%lastGoodNodes) };
%edgesLca = %{ dclone(\%lastGoodEdges) };
} # if ($maxNodes)
# original max depth calculating to max depth and no further, not calculating full depth
# if ($maxDepth) {
# my $nodeDepth = 1;
# my %tempNodes; my %tempEdges;
# my %lastGoodNodes; my %lastGoodEdges;
# my (@parentNodes) = split/,/, $rootsChosen;
# if ($fakeRootFlag) { @parentNodes = ( 'GO:0000000' ); $nodeDepth = 0; }
#
# foreach my $node (@parentNodes) {
# foreach my $type (keys %{ $nodes{$node} }) {
# $tempNodes{$node}{$type} = $nodes{$node}{$type}; } }
# my @nextLayerParentNodes = ();
# while ( (scalar @parentNodes > 0) && ($nodeDepth < $maxDepth) ) { # while there are parent nodes, go through them
# # print qq(MAX DEPTH $maxDepth<BR>\n);
# # print qq(NODE DEPTH $nodeDepth<BR>\n);
# my $parent = shift @parentNodes; # take a parent
# foreach my $child (sort keys %{ $edgesLca{$parent} }) { # each child of parent
# $tempEdges{$parent}{$child}++; # add parent-child edge to final graph
# next if (exists $tempNodes{$child}); # skip children already added through other parent
# # $count++;
# # if ($parent eq 'GO:0000000') { $count--; } # never count nodes attached to fake root
# # print qq(NODE CHILD $child PARENT $parent COUNT $count\n);
# foreach my $type (keys %{ $nodes{$child} }) {
# $tempNodes{$child}{$type} = $nodes{$child}{$type}; }
# push @nextLayerParentNodes, $child; # child is a good node, add to parent list to check its children
# } # foreach my $child (sort keys %{ $edgesLca{$parent} })
# if ( (scalar @parentNodes == 0) && ($nodeDepth < $maxDepth) ) {
# $nodeDepth++;
# @parentNodes = @nextLayerParentNodes;
# @nextLayerParentNodes = ();
# # print qq(NODE COUNT $count\n);
# %lastGoodNodes = %{ dclone(\%tempNodes) };
# %lastGoodEdges = %{ dclone(\%tempEdges) };
# }
# } # while (@parentNodes)
# %nodes = %{ dclone(\%lastGoodNodes) };
# %edgesLca = %{ dclone(\%lastGoodEdges) };
# }
my $fullDepthFlag = 1; # calculate the full depth from the graph after lca and longest path
my $fullDepth = 10; # initialize to some large depth just in case
if ($fullDepthFlag) {
my $nodeDepth = 1;
my %tempNodes; my %tempEdges;
my %lastGoodNodes; my %lastGoodEdges;
my (@parentNodes) = split/,/, $rootsChosen;
if ($fakeRootFlag) {
if ( ($datatype eq 'go') || ($datatype eq 'biggo') ) {
@parentNodes = ( 'GO:0000000' ); $nodeDepth = 0; } }
foreach my $node (@parentNodes) {
# print qq(NODE $node PN @parentNodes\n);
foreach my $type (keys %{ $nodes{$node} }) {
$tempNodes{$node}{$type} = $nodes{$node}{$type}; } }
if ($maxDepth) { # if there's a max depth requested
if ($nodeDepth == $maxDepth) { # if requested depth is current depth, save the nodes and edges
%lastGoodNodes = %{ dclone(\%tempNodes) }; # doing this here in the case user wants max depth of 1
%lastGoodEdges = %{ dclone(\%tempEdges) }; } }
my @nextLayerParentNodes = ();
while ( (scalar @parentNodes > 0) ) { # while there are parent nodes, go through them
# print qq(MAX DEPTH $maxDepth<BR>\n);
# print qq(NODE DEPTH $nodeDepth<BR>\n);
my $parent = shift @parentNodes; # take a parent
# print qq(PARENT $parent PN @parentNodes\n);
foreach my $child (sort keys %{ $edgesLca{$parent} }) { # each child of parent
$tempEdges{$parent}{$child}++; # add parent-child edge to final graph
next if (exists $tempNodes{$child}); # skip children already added through other parent
# $count++;
# if ($parent eq 'GO:0000000') { $count--; } # never count nodes attached to fake root
# print qq(NODE CHILD $child PARENT $parent\n);
foreach my $type (keys %{ $nodes{$child} }) {
$tempNodes{$child}{$type} = $nodes{$child}{$type}; }
push @nextLayerParentNodes, $child; # child is a good node, add to parent list to check its children
# print qq(ADD $child to next layer\n);
} # foreach my $child (sort keys %{ $edgesLca{$parent} })
if ( (scalar @parentNodes == 0) ) { # if looked at all parent nodes
# print qq(DEPTH INCREASE\n);
$nodeDepth++; # increase depth
@parentNodes = @nextLayerParentNodes; # repopulate from the next layer of parent nodes
@nextLayerParentNodes = (); # clean up the next layer of parent nodes
# print qq(NODE DEPTH $nodeDepth\n);
if ($maxDepth) { # if there's a max depth requested
if ($nodeDepth == $maxDepth) { # if requested depth is current depth, save the nodes and edges
%lastGoodNodes = %{ dclone(\%tempNodes) };
%lastGoodEdges = %{ dclone(\%tempEdges) }; } } }
} # while (@parentNodes)
$fullDepth = $nodeDepth - 1; # node depth went one too many
if ($maxDepth > $fullDepth) { # if a depth higher than full depth is requested, show the whole graph
%lastGoodNodes = %{ dclone(\%tempNodes) };