transition bar to visualise changed scale
[barcat.git] / graph
1 #!/usr/bin/env perl
2 use 5.014;
3 use warnings;
4 use utf8;
5 use List::Util qw( min max sum );
6 use open qw( :std :utf8 );
7
8 our $VERSION = '1.02';
9
10 use Getopt::Long '2.33', qw( :config gnu_getopt );
11 sub podexit { require Pod::Usage; Pod::Usage::pod2usage(-exitval => 0, @_) }
12 GetOptions(\my %opt,
13         'color|c!',
14         'follow|f:i',
15         'trim|length|l=i',
16         'markers|m=s',
17         'width|w=i',
18         'usage|h' => sub { podexit() },
19         'help'    => sub { podexit(-verbose => 2) },
20 ) or exit 64;  # EX_USAGE
21
22 $opt{width} ||= $ENV{COLUMNS} || 80;
23 $opt{color} //= -t *STDOUT;  # enable on tty
24
25 if (defined $opt{follow}) {
26         $opt{follow} ||= 1;
27         $SIG{ALRM} = sub {
28                 show_lines();
29                 alarm $opt{follow};
30         };
31         alarm $opt{follow};
32 }
33
34 $SIG{INT} = 'IGNORE';  # continue after assumed eof
35
36 my (@lines, @values);
37 while (readline) {
38         chomp;
39         push @values, s/^\h* ( -? [0-9]* (?:\.[0-9]+)? )//x && $1;
40         if (defined $opt{trim}) {
41                 my $trimpos = abs $opt{trim};
42                 if ($trimpos <= 1) {
43                         $_ = substr $_, 0, 1;
44                 }
45                 elsif (length > $trimpos) {
46                         substr($_, $trimpos - 1) = '…';
47                 }
48         }
49         push @lines, $_;
50 }
51 @lines or exit;
52
53 $SIG{INT} = 'DEFAULT';
54
55 sub show_lines {
56
57 state $nr = 0;
58
59 my @order  = sort { $b <=> $a } grep { length } @values;
60 my $maxval = $order[0];
61 my $minval = min $order[-1], 0;
62 my $lenval = max map { length } @order;
63 my $len    = defined $opt{trim} && $opt{trim} <= 0 ? -$opt{trim} + 1 :
64         1 + max map { length } @lines;  # left padding
65 my $size   = ($maxval - $minval) &&
66         ($opt{width} - $lenval - $len) / ($maxval - $minval);  # bar multiplication
67
68 my @barmark;
69 if ($opt{markers} // 1 and $size > 0) {
70         my sub orderpos { (($order[$_[0]] + $order[$_[0] + .5]) / 2 - $minval) * $size }
71         $barmark[ (sum(@order) / @order - $minval) * $size ] = '=';  # average
72         $barmark[ orderpos($#order * .31731) ] = '>';
73         $barmark[ orderpos($#order * .68269) ] = '<';
74         $barmark[ orderpos($#order / 2) ] = '+';  # mean
75         $barmark[ -$minval * $size ] = '|' if $minval < 0;  # zero
76         defined and $opt{color} and $_ = "\e[36m$_\e[0m" for @barmark;
77
78         state $lastmax = $maxval;
79         if ($maxval > $lastmax) {
80                 print ' ' x ($lenval + $len);
81                 printf "\e[90m" if $opt{color};
82                 printf '%-*s',
83                         ($lastmax - $minval) * $size + .5,
84                         '-' x (($values[$nr - 1] - $minval) * $size);
85                 print "\e[92m" if $opt{color};
86                 say '+' x (($maxval - $lastmax - $minval) * $size + .5);
87                 print "\e[0m" if $opt{color};
88                 $lastmax = $maxval;
89         }
90 }
91
92 while ($nr <= $#lines) {
93         my $val = $values[$nr];
94         if (length $val) {
95                 my $color = !$opt{color} ? 0 :
96                         $val == $order[0] ? 32 : # max
97                         $val == $order[-1] ? 31 : # min
98                         90;
99                 printf "\e[%sm", $color if $color;
100                 printf "%*s", $lenval, $val;
101                 print "\e[0m" if $color;
102         }
103         printf '%-*s', $len, $lines[$nr];
104         print $barmark[$_] // '-' for 1 .. $size && (($val || 0) - $minval) * $size;
105         say '';
106         $nr++;
107 }
108
109 }
110 show_lines();
111
112 __END__
113
114 =head1 NAME
115
116 graph - append bar chart to input numbers
117
118 =head1 SYNOPSIS
119
120 B<graph> [<options>] [<input>]
121
122 =head1 DESCRIPTION
123
124 Each line starting with a number is given a bar to visualise relative sizes.
125
126 =head1 OPTIONS
127
128 =over
129
130 =item -c, --[no-]color
131
132 Force colored output of values and bar markers.
133 Defaults on if output is a tty,
134 disabled otherwise such as when piped or redirected.
135
136 =item -f, --follow[=<seconds>]
137
138 Interval to output partial progress.
139
140 =item -l, --length=[-]<size>
141
142 Trim line contents (between number and bars)
143 to a maximum number of characters.
144 The exceeding part is replaced by an abbreviation sign,
145 unless C<--length=0>.
146
147 Prepend a dash (i.e. make negative) to enforce padding
148 regardless of encountered contents.
149
150 =item -m, --markers=
151
152 Statistical positions to indicate on bars.
153 Cannot be customized yet,
154 only disabled by providing an empty argument.
155
156 Any value enables all marker characters:
157
158 =over 2
159
160 =item B<=>
161
162 Average:
163 the sum of all values divided by the number of counted lines.
164
165 =item B<+>
166
167 Mean, median:
168 the middle value or average between middle values.
169
170 =item B<<>
171
172 Standard deviation left of the mean.
173 Only 16% of all values are lower.
174
175 =item B<< > >>
176
177 Standard deviation right of the mean.
178 The part between B<< <--> >> encompass all I<normal> results,
179 or 68% of all entries.
180
181 =back
182
183 =item -w, --width=<columns>
184
185 Override the maximum number of columns to use.
186 Appended graphics will extend to fill up the entire screen.
187
188 =back
189
190 =head1 EXAMPLES
191
192 Commonly used after counting, such as users on the current server:
193
194     users | sed 's/ /\n/g' | sort | uniq -c | graph
195
196 Letter frequencies in text files:
197
198     cat /usr/share/games/fortunes/*.u8 |
199     perl -CO -nE 'say for grep length, split /\PL*/, uc' |
200     sort | uniq -c | graph
201
202 Memory usage of user processes:
203
204     ps xo %mem,pid,cmd | graph -l40
205
206 Sizes (in megabytes) of all root files and directories:
207
208     du -d0 -m * | graph
209
210 Number of HTTP requests per day:
211
212     cat log/access.log | cut -d\  -f4 | cut -d: -f1 | uniq -c | graph
213
214 Any kind of database query with leading counts:
215
216     echo 'SELECT count(*),schemaname FROM pg_tables GROUP BY 2' |
217     psql -t | graph
218
219 Git statistics, such commit count by year:
220
221     git log --pretty=%ci | cut -b-4 | uniq -c | graph
222
223 Or the most frequent authors:
224
225     git shortlog -sn | graph | head -3
226
227 Latency history:
228
229     ping google.com |
230     perl -pe '$|=1; print s/ time=(.*)// ? "$1 for " : "> "' | graph -f
231
232 =head1 AUTHOR
233
234 Mischa POSLAWSKY <perl@shiar.org>
235
236 =head1 LICENSE
237
238 GPL3+.