gnuplot hide works for multiple checked columns
[MojoFacets.git] / lib / MojoFacets / Gnuplot.pm
1 package MojoFacets::Gnuplot;
2
3 use warnings;
4 use strict;
5
6 use base 'Mojolicious::Controller';
7
8 use Data::Dump qw(dump);
9 use Digest::MD5 qw(md5_hex);
10 use Text::Unaccent::PurePerl;
11 use MojoFacets::Data;
12
13 sub index {
14         my $self = shift;
15
16         my $columns = $self->session('columns') || return $self->redirect_to('/data/columns');
17         my $path    = $self->session('path')    || return $self->redirect_to('/data/load');
18         my $with    = $self->param('with') || 'points';
19
20         my $gnuplot_hide = $self->every_param('gnuplot_hide');
21         warn "## gnuplot_hide=",dump( $gnuplot_hide );
22         my $hide_columns;
23         $hide_columns->{$_}++ foreach @$gnuplot_hide;
24         warn "## hide_columns ", dump $hide_columns;
25
26 #       my $name = join('.', 'items', map { my $n = unac_string($_); $n =~ s/\W+/_/g; $n } @$columns );
27         my $name = MojoFacets::Data::__export_path_name( $path, 'items', @$columns );
28
29         warn "# name $name\n";
30
31         my $url = "/export/$path/$name";
32         my $dir = $self->app->home->rel_file('public');
33
34         if ( -e "$dir/$url" ) {
35
36                 my $timefmt = $self->param('timefmt');
37
38                 my $spaces = $timefmt;
39                 $spaces =~ s/\S//g;
40                 $spaces = length( $spaces );
41
42                 my @plot;
43                 foreach ( 1 .. $#$columns ) {
44                         my $title = $columns->[$_];
45                         next if $hide_columns->{$title};
46                         $title =~ s/_/ /g;
47                         my $n = $_ + 1 + $spaces;
48                         push @plot, qq|"$dir/$url" using 1:$n title "$title" with $with| unless $hide_columns->{ $title };
49                 }
50
51                 my $g = qq|
52
53 set terminal png
54 set output '$dir/$url.png'
55
56                 |;
57
58                 if ( $timefmt ) {
59                         $g .= qq|
60
61 set xdata time
62 set timefmt "$timefmt"
63 set format x "$timefmt"
64
65                         |;
66                 }
67
68 #set xrange [ "2009-01-01":"2010-01-01" ]
69 #set yrange [ 0 : ]
70
71                 $g .= "\n\nplot " . join(',', @plot) . "\n";
72                 $g =~ s/\n\n+/\n/sg;
73
74 #warn "gnuplot $g";
75
76                 open(my $gnuplot, '|-', 'gnuplot') || die "gnuplot $!";
77                 print $gnuplot $g;
78                 close $gnuplot;
79
80                 if ( -e "$dir/$url.png" ) {
81                         warn "redirect $url.png";
82                         return $self->redirect_to( "$url.png" );
83                 } else {
84                         $self->render_text( "no $dir/$url.png" );
85                 }
86         } else {
87                 $self->render_text("no graph for $url");
88         }
89 }
90
91 1;