forked from Ensembl/ensembl-vep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStats.pm
1092 lines (853 loc) · 28.2 KB
/
Stats.pm
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
=head1 LICENSE
Copyright [2016-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy self the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sselftware
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
# EnsEMBL module for Bio::EnsEMBL::VEP::Stats
#
#
=head1 NAME
Bio::EnsEMBL::VEP::Stats - object for tracking VEP run stats
=head1 SYNOPSIS
my $stats = Bio::EnsEMBL::VEP::Haplo::Stats->new({
config => $config
});
my $start_time = $stats->start_time();
$stats->log_VariationFeature($vf);
my $end_time = $stats->end_time();
=head1 DESCRIPTION
The Stats class is used to track all runtime and data statistics
for a VEP run.
It also generates summary statistics output, by default in an HTML
report file containing tables and charts.
=head1 METHODS
=cut
use strict;
use warnings;
package Bio::EnsEMBL::VEP::Stats;
use base qw(Bio::EnsEMBL::VEP::BaseVEP);
use Bio::EnsEMBL::Variation::Utils::Constants;
use Bio::EnsEMBL::VEP::Constants;
use Bio::EnsEMBL::VEP::Utils qw(get_time);
=head2 new
Arg 1 : hashref $args
{
config => Bio::EnsEMBL::VEP::Config,
}
Example : $stats = Bio::EnsEMBL::VEP::Stats->new({config => $config});
Description: Create a new Bio::EnsEMBL::VEP::Stats object.
Returntype : Bio::EnsEMBL::VEP::Stats
Exceptions : none
Caller : BaseVEP
Status : Stable
=cut
sub new {
my $caller = shift;
my $class = ref($caller) || $caller;
my $self = $class->SUPER::new(@_);
# add shortcuts to these params
$self->add_shortcuts([qw(no_stats)]);
$self->{stats} = {counters => {}};
return $self;
}
=head2 info
Arg 1 : (optional) hashref $info
Example : $info = $stats->info();
Description: Get/set the info hashref. Used to store version and annotation
source data, as retrieved by get_output_header_info() in Runner.
Returntype : hashref
Exceptions : none
Caller : Runner::init()
Status : Stable
=cut
sub info {
my $self = shift;
$self->{info} = shift if @_;
return $self->{info} ||= {};
}
=head2 start_time
Example : $time = $stats->start_time();
Description: Get start timestamp of this VEP run. Set to current time the first
time this method is called.
Returntype : string
Exceptions : none
Caller : Runner::init()
Status : Stable
=cut
sub start_time {
my $self = shift;
$self->{stats}->{run_time_start} ||= time();
return $self->{stats}->{start_time} ||= get_time();
}
=head2 end_time
Example : $time = $stats->end_time();
Description: Get end timestamp of this VEP run. Set to current time the first
time this method is called.
Returntype : string
Exceptions : none
Caller : Runner::dump_stats()
Status : Stable
=cut
sub end_time {
return $_[0]->{stats}->{end_time} ||= get_time();
}
=head2 run_time
Example : $runtime = $stats->run_time();
Description: Get run time in seconds (current time - start time)
Returntype : int
Exceptions : none
Caller : generate_run_stats()
Status : Stable
=cut
sub run_time {
return time() - $_[0]->{stats}->{run_time_start};
}
=head2 log_lines_read
Arg 1 : int $num_lines
Example : $stats->log_lines_read($num_lines);
Description: Store the total number of lines read, used in stats output
Returntype : none
Exceptions : none
Caller : InputBuffer
Status : Stable
=cut
sub log_lines_read {
$_[0]->{stats}->{lines_read} = $_[1];
}
=head2 log_chromosomes
Arg 1 : hashref $chr_names_and_lengths
Example : $stats->log_chromosomes($lengths);
Description: Logs the chromosome names and lengths as retrieved from
core database or FASTA db
Returntype : none
Exceptions : none
Caller : BaseVEP
Status : Stable
=cut
sub log_chromosomes {
$_[0]->{stats}->{chr_lengths} ||= $_[1];
}
=head2 log_VariationFeature
Arg 1 : Bio::EnsEMBL::Variation::BaseVariationFeature $vf
Arg 2 : hashref $vf_hash
Example : $stats->log_VariationFeature($vf);
Description: Log statistics for a VariationFeature object
Returntype : none
Exceptions : none
Caller : OutputFactory
Status : Stable
=cut
sub log_VariationFeature {
my $self = shift;
my $vf = shift;
my $hash = shift;
return if $self->{no_stats};
my $stats = $self->{stats}->{counters};
# basic count
$stats->{var_count}++;
# position
$stats->{chr}->{$vf->{chr}}->{1e6 * int($vf->{start} / 1e6)}++;
# most severe consequence
$stats->{var_cons}->{$vf->display_consequence}++;
# known variants
$stats->{existing}++ if $vf->{existing};
# get stats
my $so_term = $vf->class_SO_term;
if(defined($so_term)) {
$stats->{classes}->{$so_term}++;
if($so_term eq 'SNV') {
my @alleles = split('/', $vf->allele_string);
my $ref_allele = shift @alleles;
$stats->{allele_changes}->{$ref_allele.'/'.$_}++ for @alleles;
}
}
}
=head2 log_VariationFeatureOverlapAllele
Arg 1 : Bio::EnsEMBL::Variation::VariationFeatureOverlapAllele $vfoa
Arg 2 : hashref $vf_hash
Example : $stats->log_VariationFeatureOverlapAllele($vfoa);
Description: Log statistics for a VariationFeatureOverlapAllele object
Returntype : none
Exceptions : none
Caller : OutputFactory
Status : Stable
=cut
sub log_VariationFeatureOverlapAllele {
my $self = shift;
my ($vfoa, $hash) = @_;
return if $self->{no_stats};
my $stats = $self->{stats}->{counters};
# consequence type(s)
$stats->{consequences}->{$_}++ for @{$hash->{Consequence}};
# feature types
$stats->{lc($hash->{Feature_type})}->{$hash->{Feature}}++ if $hash->{Feature};
# run sub-type method if available
my $method = 'log_'.(split('::', ref($vfoa)))[-1];
$self->$method(@_) if $self->can($method);
}
=head2 log_TranscriptVariationAllele
Arg 1 : Bio::EnsEMBL::Variation::TranscriptVariationAllele $tva
Arg 2 : hashref $vf_hash
Example : $stats->log_TranscriptVariationAllele($tva);
Description: Log statistics for a TranscriptVariationAllele object
Returntype : none
Exceptions : none
Caller : OutputFactory
Status : Stable
=cut
sub log_TranscriptVariationAllele {
my $self = shift;
$self->log_BaseTranscriptVariationAllele(@_);
}
=head2 log_TranscriptStructuralVariationAllele
Arg 1 : Bio::EnsEMBL::Variation::TranscriptStructuralVariationAllele $tsva
Arg 2 : hashref $vf_hash
Example : $stats->log_TranscriptStructuralVariationAllele($tsva);
Description: Log statistics for a TranscriptStructuralVariationAllele object
Returntype : none
Exceptions : none
Caller : OutputFactory
Status : Stable
=cut
sub log_TranscriptStructuralVariationAllele {
my $self = shift;
$self->log_BaseTranscriptVariationAllele(@_);
}
=head2 log_BaseTranscriptVariationAllele
Arg 1 : Bio::EnsEMBL::Variation::BaseTranscriptVariationAllele $btva
Arg 2 : hashref $vf_hash
Example : $stats->log_BaseTranscriptVariationAllele($btva);
Description: Log statistics for a BaseTranscriptVariationAllele object
Returntype : none
Exceptions : none
Caller : log_TranscriptVariationAllele()
log_TranscriptStructuralVariationAllele()
Status : Stable
=cut
sub log_BaseTranscriptVariationAllele {
my $self = shift;
my ($vfoa, $hash) = @_;
my $stats = $self->{stats}->{counters};
# protein pos
if($vfoa->_pre_consequence_predicates->{coding}) {
my $tr = $vfoa->feature;
my $protein_length =
$tr->{_variation_effect_feature_cache}->{peptide} ?
length($tr->{_variation_effect_feature_cache}->{peptide}) :
$tr->translation->length;
if(my $protein_pos = $vfoa->base_transcript_variation->translation_start) {
$stats->{protein_pos}->{int(10 * ($protein_pos / $protein_length))}++ if $protein_length;
}
}
# gene counts
$stats->{gene}->{$hash->{Gene}}++;
}
=head2 log_sift_polyphen
Arg 1 : string $tool_name
Arg 2 : string $prediction
Example : $stats->log_sift_polyphen('SIFT', 'deleterious');
Description: Log statistics for a SIFT or PolyPhen prediction
Returntype : none
Exceptions : none
Caller : OutputFactory
Status : Stable
=cut
sub log_sift_polyphen {
my ($self, $tool, $pred) = @_;
$self->{stats}->{counters}->{$tool}->{$pred}++;
}
=head2 increment_filtered_variants
Arg 1 : int $count
Example : $stats->increment_filtered_variants(3);
Description: Log a number of filtered variants
Returntype : none
Exceptions : none
Caller : AnnotationSource::Cache::BaseCacheVariation
Status : Stable
=cut
sub increment_filtered_variants {
my ($self, $count) = @_;
$self->{stats}->{counters}->{filtered_variants} += $count;
}
=head2 finished_stats
Example : $finished = $stats->finished_stats();
Description: Finalise and return finished stats hashref
Returntype : hashref
Exceptions : none
Caller : dump_text(), dump_html()
Status : Stable
=cut
sub finished_stats {
my $self = shift;
if(!exists($self->{finished_stats})) {
my $stats = $self->{stats};
# merge in counters data
my $counters = $stats->{counters};
$stats->{$_} = $counters->{$_} for keys %$counters;
# convert gene and transcript hashes to counts
for my $type(qw(gene transcript regulatoryfeature)) {
$stats->{$type} = scalar keys %{$stats->{$type}} if defined $stats->{$type};
}
# tot up chromosome counts
if($stats->{chr_lengths}) {
foreach my $chr(keys %{$stats->{chr}}) {
$stats->{chr_totals}->{$chr} += $stats->{chr}->{$chr}->{$_} for keys %{$stats->{chr}->{$chr}};
unless($stats->{chr_lengths}->{$chr}) {
delete $stats->{chr}->{$chr};
next;
}
my $start = 0;
my %tmp;
while($start <= $stats->{chr_lengths}->{$chr}) {
$tmp{$start / 1e6} = $stats->{chr}->{$chr}->{$start} || 0;
$start += 1e6;
}
$stats->{chr}->{$chr} = \%tmp;
}
}
# convert allele changes to Ts/Tv
my $ts_tv = \%Bio::EnsEMBL::VEP::Constants::TS_TV;
map {$stats->{ts_tv}->{$ts_tv->{$_}} += $stats->{allele_changes}->{$_}} grep {$ts_tv->{$_}} keys %{$stats->{allele_changes}} if $stats->{allele_changes};
# flesh out protein_pos
if(defined($stats->{protein_pos})) {
if(defined($stats->{protein_pos}->{10})) {
$stats->{protein_pos}->{9} += $stats->{protein_pos}->{10};
delete $stats->{protein_pos}->{10};
}
$stats->{protein_pos}->{$_} ||= 0 for (0..9);
my %tmp = map {$_.'0-'.($_+1).'0%' => $stats->{protein_pos}->{$_}} keys %{$stats->{protein_pos}};
$stats->{protein_pos} = \%tmp;
}
# coding cons
foreach my $con(
map {$_->SO_term}
grep {$_->{include} && $_->{include}->{coding}}
values %Bio::EnsEMBL::Variation::Utils::Constants::OVERLAP_CONSEQUENCES
) {
$stats->{coding}->{$con} = $stats->{consequences}->{$con} if $stats->{consequences}->{$con};
}
$self->{finished_stats} = {
charts => $self->generate_chart_data($stats),
run_stats => $self->generate_run_stats($stats),
general_stats => $self->generate_general_stats($stats),
}
}
return $self->{finished_stats};
}
=head2 generate_chart_data
Arg 1 : hashref $stats
Example : $chart_data = $stats->generate_chart_data($stats);
Description: Generates chart configurations and data based on available
stats.
Returntype : arrayref
Exceptions : none
Caller : finished_stats()
Status : Stable
=cut
sub generate_chart_data {
my $self = shift;
my $stats = shift;
# get some data from Constants
my $colour_keys = \%Bio::EnsEMBL::VEP::Constants::COLOUR_KEYS;
my %cons_ranks =
map { $_->{SO_term} => $_->{rank} }
values %Bio::EnsEMBL::Variation::Utils::Constants::OVERLAP_CONSEQUENCES;
# create pie chart hashes
my @charts = (
{
id => 'var_class',
title => 'Variant classes',
header => ['Variant class', 'Count'],
data => $stats->{classes},
type => 'pie',
sort => 'value',
height => 200,
},
{
id => 'var_cons',
title => 'Consequences (most severe)',
header => ['Consequence type', 'Count'],
data => $stats->{var_cons},
type => 'pie',
sort => \%cons_ranks,
colours => $colour_keys->{consequences},
},
{
id => 'consequences',
title => 'Consequences (all)',
header => ['Consequence type', 'Count'],
data => $stats->{consequences},
type => 'pie',
sort => \%cons_ranks,
colours => $colour_keys->{consequences},
},
{
id => 'coding',
title => 'Coding consequences',
header => ['Consequence type', 'Count'],
data => $stats->{coding},
type => 'pie',
sort => \%cons_ranks,
colours => $colour_keys->{consequences},
}
);
foreach my $tool(qw(SIFT PolyPhen)) {
my $lc_tool = lc($tool);
push @charts, {
id => $lc_tool,
title => $tool.' summary',
header => ['Prediction', 'Count'],
data => $stats->{$tool},
type => 'pie',
height => 200,
sort => 'value',
colours => $colour_keys->{$lc_tool},
} if $self->param($lc_tool);
}
push @charts, {
id => 'chr',
title => 'Variants by chromosome',
header => ['Chromosome','Count'],
data => $stats->{chr_totals},
sort => 'chr',
type => 'bar',
options => '{legend: {position: "none"}}',
} if $stats->{chr_totals};
foreach my $chr(sort {($a !~ /^\d+$/ || $b !~ /^\d+/) ? $a cmp $b : $a <=> $b} keys %{$stats->{chr}}) {
my $chr_id = $chr;
$chr_id =~ s/\./\_/g;
push @charts, {
id => 'chr_'.$chr_id,
title => 'Distribution of variants on chromosome '.$chr,
header => ['Position (mb)', 'Count'],
data => $stats->{chr}->{$chr},
sort => 'chr',
type => 'area',
options => '{hAxis: {title: "Position (mb)", textStyle: {fontSize: 8}}, legend: {position: "none"}}',
no_table => 1,
no_link => 1,
};
}
push @charts, {
id => 'protein',
title => 'Position in protein',
header => ['Position in protein (percentile)','Count'],
data => $stats->{protein_pos},
sort => 'chr',
type => 'bar',
no_table => 1,
options => '{hAxis: {title: "Position in protein (percentile)", textStyle: {fontSize: 10}}, legend: {position: "none"}}',
} if $stats->{protein_pos};
return \@charts;
}
=head2 generate_run_stats
Arg 1 : hashref $stats
Example : $run_stats = $stats->generate_run_stats($stats);
Description: Generates VEP run stats.
Returntype : arrayref
Exceptions : none
Caller : finished_stats()
Status : Stable
=cut
sub generate_run_stats {
my $self = shift;
my $stats = shift;
my $info = $self->{info};
# process command line opts
my %raw = %{$self->config->_raw_config};
my @opts;
foreach my $key(sort keys %raw) {
my $val = $raw{$key};
if(ref($val) eq 'ARRAY') {
next unless scalar @$val;
push @opts, '--'.$key, $_ for @$val;
}
else {
next if $val eq '0';
push @opts, '--'.$key;
push @opts, $val unless $val eq '1';
}
}
my @return = (
['Species', $self->species],
['Command line options', '<pre>'.join(" ", @opts).'</pre>'],
['Start time', $self->start_time],
['End time', $self->end_time],
['Run time', $self->run_time." seconds"],
['Input file', $self->param('input_file')],
[
'Output file',
$self->param('output_file')#.
# (defined($config->{html}) ? ' '.a({href => $config->{output_file}.'.html'}, '[HTML]') : '').
# ' '.a({href => $config->{output_file}}, '[text]')
],
);
my @cache_db_strings;
if($info->{cache_dir}) {
push @cache_db_strings, "Cache: ".$info->{cache_dir};
}
if($self->param('database') or ($self->param('cache') && !$self->param('offline'))) {
push @cache_db_strings, sprintf('%s on %s', $info->{db_name}, $info->{db_host});
}
foreach my $custom(@{$info->{custom_info} || []}) {
push @cache_db_strings, sprintf('Custom: %s (%s)', $custom->{file}, $custom->{type});
}
unshift @return, ['Annotation sources', join("; ", @cache_db_strings)];
unshift @return, ['VEP version (API)', sprintf(' %i (%i)', $info->{vep_version}, $info->{api_version})];
return \@return;
}
=head2 generate_general_stats
Arg 1 : hashref $stats
Example : $run_stats = $stats->generate_run_stats($stats);
Description: Generates general VEP stats, not run-related but not
suitable for charting e.g. no. overlapped genes.
Returntype : arrayref
Exceptions : none
Caller : finished_stats()
Status : Stable
=cut
sub generate_general_stats {
my $self = shift;
my $stats = shift;
return [
['Lines of input read', $stats->{lines_read}],
['Variants processed', $stats->{var_count}],
['Variants filtered out', $stats->{filtered_variants} || 0],
# ['Lines of output written', $stats->{out_count}],
[
'Novel / existing variants',
defined($stats->{existing}) ?
sprintf('%s (%.1f) / %s (%.1f)',
$stats->{var_count} - $stats->{existing},
100 * (($stats->{var_count} - $stats->{existing}) / $stats->{var_count}),
$stats->{existing},
100 * ($stats->{existing} / $stats->{var_count}),
)
: '-'
],
['Overlapped genes', $stats->{gene} || 0],
['Overlapped transcripts', $stats->{transcript} || 0],
['Overlapped regulatory features', $stats->{regulatoryfeature} || ($self->param('regulatory') ? 0 : '-')],
];
}
=head2 sort_keys
Arg 1 : hashref $data
Arg 2 : scalar $sort_type
Example : $run_stats = $stats->generate_run_stats($stats);
Description: Sorts the keys from a hashref of data according to various strategies
as set by $sort_type:
- string 'chr' : sort alphanumerically
- string 'value' : sort numerically by values in $data
- hashref : sort numerically by values of keys in $sort
Returntype : arrayref of strings
Exceptions : none
Caller : dump_text(), stats_html_head()
Status : Stable
=cut
sub sort_keys {
my $self = shift;
my $data = shift;
my $sort = shift;
my @keys;
# sort data
if(defined($sort)) {
if($sort eq 'chr') {
@keys = sort {($a !~ /^\d+$/ || $b !~ /^\d+/) ? $a cmp $b : $a <=> $b} keys %{$data};
}
elsif($sort eq 'value') {
@keys = sort {$data->{$a} <=> $data->{$b}} keys %{$data};
}
elsif(ref($sort) eq 'HASH') {
@keys = sort {$sort->{$a} <=> $sort->{$b}} keys %{$data};
}
}
else {
@keys = keys %{$data};
}
return \@keys;
}
=head2 dump_text
Arg 1 : (optional) filehandle $fh
Example : $stats->dump_text(*STDOUT);
Description: Dumps statistics as text to filehandle; STDERR is used if no
filehandle given.
Returntype : bool
Exceptions : none
Caller : Runner
Status : Stable
=cut
sub dump_text {
my $self = shift;
my $fh = shift || *STDERR;
my $finished_stats = $self->finished_stats;
print $fh "[VEP run statistics]\n";
print $fh join("\t", map {s/\<.+?\>//g; $_} @{$_})."\n" for @{$finished_stats->{run_stats}};
print $fh "\n[General statistics]\n";
print $fh join("\t", map {s/\<.+?\>//g; $_} grep {defined($_)} @{$_})."\n" for @{$finished_stats->{general_stats}};
foreach my $chart(@{$finished_stats->{charts}}) {
print $fh "\n[".$chart->{title}."]\n";
print $fh join("\t", ($_, $chart->{data}->{$_}))."\n" for @{$self->sort_keys($chart->{data}, $chart->{sort})};
}
return 1;
}
=head2 dump_html
Arg 1 : filehandle $fh
Example : $stats->dump_html($fh);
Description: Dumps statistics as HTML to filehandle
Returntype : bool
Exceptions : none
Caller : Runner
Status : Stable
=cut
sub dump_html {
my $self = shift;
my $fh = shift;
my $finished_stats = $self->finished_stats;
print $fh $self->stats_html_head($finished_stats->{charts});
# create menu
print $fh
'<div class="sidemenu">'.
'<div class="sidemenu_head">Links</div>'.
'<div class="sidemenu_body">'.
'<ul>'.
join('', map {sprintf('<li><a href="#%s">%s</a></li>', $_->[0], $_->[1])} (
['masthead', 'Top of page'],
['run_stats', 'VEP run statistics'],
['gen_stats', 'General statistics'],
map {
[$_->{id}, $_->{title}]
} grep { !$_->{no_link} } @{$finished_stats->{charts}},
)).
'</ul>'.
'</div>'.
'</div>';
print $fh "<div class='main_content'>";
print $fh
'<h3 id="run_stats">VEP run statistics</h3>'.
'<table class="stats_table">'.
join('', map {'<tr>'.join('', map {'<td>'.$_.'</td>'} @$_).'</tr>'} @{$finished_stats->{run_stats}}).
'</table>';
# vars in/out stats
print $fh
'<h3 id="gen_stats">General statistics</h3>'.
'<table class="stats_table">'.
join('', map {'<tr>'.join('', map {'<td>'.($_ || 0).'</td>'} @$_).'</tr>'} @{$finished_stats->{general_stats}}).
'</table>';
foreach my $chart(@{$finished_stats->{charts}}) {
my $height = $chart->{height} || ($chart->{type} eq 'pie' ? '400' : '200');
print $fh
'<hr/>'.
sprintf('<h3 id="%s">%s</h3>', $chart->{id}, $chart->{title}).
sprintf('<div id="%s" style="width: 800px; height: %ipx"> </div>', $chart->{id}."_".$chart->{type}, $height);
print $fh
sprintf('<div id="%s_table" style="width: 800px; height: 200px"> </div>', $chart->{id})
unless $chart->{no_table};
}
print $fh '</div>';
print $fh "\n</div></body>\n</html>\n";
return 1;
}
=head2 stats_html_head
Arg 1 : arrayref $chart_data
Example : $html = $stats->stats_html_head($chart_data);
Description: Generates the HTML header for HTML stats dump, includes
JavaScript necessary for rendering and interacting with
charts.
Returntype : string
Exceptions : none
Caller : dump_html()
Status : Stable
=cut
sub stats_html_head {
my $self = shift;
my $charts = shift;
my ($js);
foreach my $chart(@$charts) {
my @keys = @{$self->sort_keys($chart->{data}, $chart->{sort})};
my $type = ucfirst($chart->{type});
# add colour
if(defined($chart->{colours})) {
my $co = 'slices: ['.join(", ", map { $chart->{colours}->{$_} ? '{color: "'.$chart->{colours}->{$_}.'"}' : '{}' } @keys).']';
if(defined($chart->{options})) {
$chart->{options} =~ s/}$/, $co}/;
}
else {
$chart->{options} = "{$co}";
}
}
# code to draw chart
$js .= sprintf(
"var %s = draw$type('%s', '%s', google.visualization.arrayToDataTable([['%s','%s'],%s]), %s);\n",
$chart->{id}.'_'.$chart->{type},
$chart->{id}.'_'.$chart->{type},
$chart->{title},
$chart->{header}->[0], $chart->{header}->[1],
join(",", map {"['".$_."',".$chart->{data}->{$_}."]"} @keys),
$chart->{options} || 'null',
);
unless($chart->{no_table}) {
# code to draw table
$js .= sprintf(
"var %s = drawTable('%s', '%s', google.visualization.arrayToDataTable([['%s','%s'],%s]));\n",
$chart->{id}.'_table',
$chart->{id}.'_table',
$chart->{title},
$chart->{header}->[0], $chart->{header}->[1],
join(",", map {"['".$_."',".$chart->{data}->{$_}."]"} @keys)
);
# interaction between table/chart
$js .= sprintf(
qq{
google.visualization.events.addListener(%s, 'select', function() {
%s.setSelection(%s.getSelection());
});
google.visualization.events.addListener(%s, 'select', function() {
%s.setSelection(%s.getSelection());
});
},
$chart->{id}.'_'.$chart->{type},
$chart->{id}.'_table',
$chart->{id}.'_'.$chart->{type},
$chart->{id}.'_table',
$chart->{id}.'_'.$chart->{type},
$chart->{id}.'_table',
);
}
}
my $html =<<SHTML;
<html>
<head>
<title>VEP summary</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart','table']});
</script>
<script type="text/javascript">
function init() {
// charts
$js
}
function drawPie(id, title, data, options) {
var pie = new google.visualization.PieChart(document.getElementById(id));
pie.draw(data, options);
return pie;
}
function drawBar(id, title, data, options) {
var bar = new google.visualization.ColumnChart(document.getElementById(id));
bar.draw(data, options);
return bar;
}
function drawTable(id, title, data) {
var table = new google.visualization.Table(document.getElementById(id));
table.draw(data, null);
return table;
}
function drawLine(id, title, data, options) {
var line = new google.visualization.LineChart(document.getElementById(id));
line.draw(data, options);
return line;
}
function drawArea(id, title, data, options) {
var area = new google.visualization.AreaChart(document.getElementById(id));
area.draw(data, options);
return area;
}
google.setOnLoadCallback(init);
</script>
<style type="text/css">
body {
font-family: arial, sans-serif;
margin: 0px;
padding: 0px;
}
a {color: #36b;}
a.visited {color: #006;}