separate project repository
[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.01';
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         'trim|length|l=i',
15         'markers|m=s',
16         'width|w=i',
17         'usage|h' => sub { podexit() },
18         'help'    => sub { podexit(-verbose => 2) },
19 ) or exit 64;  # EX_USAGE
20 $opt{width} ||= $ENV{COLUMNS} || 80;
21 $opt{color} //= 1;
22
23 my @lines = readline or exit;
24 chomp for @lines;
25 my @values = map { s/^\h* ( -? [0-9]* (?:\.[0-9]+)? )//x and $1 } @lines;
26 my @order  = sort { $b <=> $a } grep { length } @values;
27 if (defined $opt{trim}) {
28         my $trimpos = abs $opt{trim};
29         $trimpos <= 1 ? ($_ = substr($_, 0, 1)) :
30         (length > $trimpos and substr($_, $trimpos - 1) = '…') for @lines;
31 }
32
33 my $maxval = $order[0];
34 my $minval = min $order[-1], 0;
35 my $lenval = max map { length } @order;
36 my $len    = defined $opt{trim} && $opt{trim} <= 0 ? -$opt{trim} + 1 :
37         1 + max map { length } @lines;  # left padding
38 my $size   = ($maxval - $minval) &&
39         ($opt{width} - $lenval - $len) / ($maxval - $minval);  # bar multiplication
40
41 my @barmark;
42 if ($opt{markers} // 1 and $size > 0) {
43         sub orderpos { (($order[$_[0]] + $order[$_[0] + .5]) / 2 - $minval) * $size }
44         $barmark[ (sum(@order) / @order - $minval) * $size ] = '=';  # average
45         $barmark[ orderpos($#order * .31731) ] = '>';
46         $barmark[ orderpos($#order * .68269) ] = '<';
47         $barmark[ orderpos($#order / 2) ] = '+';  # mean
48         $barmark[ -$minval * $size ] = '|' if $minval < 0;  # zero
49         defined and $opt{color} and $_ = "\e[36m$_\e[0m" for @barmark;
50 }
51
52 for my $nr (0 .. $#lines) {
53         my $val = $values[$nr];
54         if (length $val) {
55                 my $color = !$opt{color} ? 0 :
56                         $val == $order[0] ? 32 : # max
57                         $val == $order[-1] ? 31 : # min
58                         90;
59                 printf "\e[%sm", $color if $color;
60                 printf "%*s", $lenval, $val;
61                 print "\e[0m" if $color;
62         }
63         printf '%-*s', $len, $lines[$nr];
64         print $barmark[$_] // '-' for 1 .. $size && (($val || 0) - $minval) * $size;
65         say '';
66 }
67
68 __END__
69
70 =head1 NAME
71
72 graph - append bar chart to input numbers
73
74 =head1 SYNOPSIS
75
76 B<graph> [<options>] [<input>]
77
78 =head1 DESCRIPTION
79
80 Each line starting with a number is given a bar to visualise relative sizes.
81
82 =head1 OPTIONS
83
84 =over
85
86 =item --no-color
87
88 Disable colored output of values and bar markers.
89
90 =item -l, --length=[-]<size>
91
92 Trim line contents (between number and bars)
93 to a maximum number of characters.
94 The exceeding part is replaced by an abbreviation sign,
95 unless C<--length=0>.
96
97 Prepend a dash (i.e. make negative) to enforce padding
98 regardless of encountered contents.
99
100 =item -m, --markers=
101
102 Statistical positions to indicate on bars.
103 Cannot be customized yet,
104 only disabled by providing an empty argument.
105
106 Any value enables all marker characters:
107
108 =over 2
109
110 =item B<=>
111
112 Average:
113 the sum of all values divided by the number of counted lines.
114
115 =item B<+>
116
117 Mean, median:
118 the middle value or average between middle values.
119
120 =item B<<>
121
122 Standard deviation left of the mean.
123 Only 16% of all values are lower.
124
125 =item B<< > >>
126
127 Standard deviation right of the mean.
128 The part between B<< <--> >> encompass all I<normal> results,
129 or 68% of all entries.
130
131 =back
132
133 =item -w, --width=<columns>
134
135 Override the maximum number of columns to use.
136 Appended graphics will extend to fill up the entire screen.
137
138 =back
139
140 =head1 EXAMPLES
141
142 Commonly used after counting, such as users on the current server:
143
144     users | sed 's/ /\n/g' | sort | uniq -c | graph
145
146 Letter frequencies in text files:
147
148     cat /usr/share/games/fortunes/*.u8 |
149     perl -CO -nE 'say for grep length, split /\PL*/, uc' |
150     sort | uniq -c | graph
151
152 Memory usage of user processes:
153
154     ps xo %mem,pid,cmd | graph -l40
155
156 Sizes (in megabytes) of all root files and directories:
157
158     du -d0 -m * | graph
159
160 Number of HTTP requests per day:
161
162     cat log/access.log | cut -d\  -f4 | cut -d: -f1 | uniq -c | graph
163
164 Any kind of database query with leading counts:
165
166     echo 'SELECT count(*),schemaname FROM pg_tables GROUP BY 2' |
167     psql -t | graph
168
169 Git statistics, such commit count by year:
170
171     git log --pretty=%ci | cut -b-4 | uniq -c | graph
172
173 Or the most frequent authors:
174
175     git shortlog -sn | graph | head -3
176
177 =head1 AUTHOR
178
179 Mischa POSLAWSKY <perl@shiar.org>
180
181 =head1 LICENSE
182
183 GPL3+.