Exporter/Stat.pm

filter: Statementstmt 94.2% 131 / 139 Branchbran 86.9% 40 / 46 Conditioncond 63.6% 7 / 11 MC/DCmcdc 28.5% 2 / 7 Subroutinesub 100% 18 / 18 Podpod 0.0% 0 / 6 totaltotal 87.2% 198 / 227 CC 33 SCAR 21.0
CC
33
Cov
91%
inc_key_value
13.2
commit
12.0
entropy
9.3
CRAP 8.2
↑ Summary Stat.pm »
1 package Catmandu::Exporter::Stat;
2  
3 1 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Catmandu::Sane;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Catmandu::Util qw(:is);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Statistics::Descriptive;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use List::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Algorithm::HyperLogLog;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Statistics::TopK;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use POSIX qw(floor);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 1 with 'Catmandu::Exporter';
14  
15 1 has fields => (is => 'rw');
16 1 ▶has as => (is => 'ro', default => sub { 'Table'} );
Subroutine __ANON__: called CC=1 SCAR=0.0
17 1 has res => (is => 'ro');
18 2 ▶has topk => (is => 'ro', default => sub { 100 });
Subroutine __ANON__: called CC=1 SCAR=0.0
19 2 ▶has hll => (is => 'ro', default => sub { 14 });
Subroutine __ANON__: called CC=1 SCAR=0.0
20 1 has counter => (is => 'ro');
21  
22 1006 ▶sub add {
Subroutine add: called CC=3 SCAR=11.0
Pod undocumented
23 1006 my ($self, $data) = @_;
24  
25 1006 ▶ unless (defined $self->fields) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->fields) 1 1005 1006
26 1 $self->fields(join(",",sort keys %$data));
27 }
28  
29 1006 my @keys = split(/,/,$self->fields);
30  
31 1006 for my $key (@keys) {
32 4024 my $val = $data->{$key};
33 4024 $self->inc_key_value($key,$val);
34 }
35  
36 1006 $self->{counter} += 1;
37 }
38  
39 # Update a counter of unique values in a field , plus the number of
40 # values in a field.
41 4024 ▶sub inc_key_value {
Subroutine inc_key_value: called CC=12 SCAR=25.8
Pod undocumented
42 4024 my ($self,$key,$val) = @_;
43  
44 4024 my $prev = $self->{res}->{$key};
45 4024 my $count = 0;
46  
47 $prev->{hll} = Algorithm::HyperLogLog->new($self->hll)
48 4024 ▶ unless exists $prev->{hll};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $prev->{"hll"} 8 4016 4024
49 $prev->{top} = Statistics::TopK->new($self->topk)
50 4024 ▶ unless exists $prev->{top};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $prev->{"top"} 8 4016 4024
51  
52 $prev->{stat} = Statistics::Descriptive::Sparse->new()
53 4024 ▶ unless exists $prev->{stat};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $prev->{"stat"} 8 4016 4024
54  
55 4024 ▶ if (is_array_ref($val)) {
Branch: 2 branches
BranchTrueFalseTotal
if (is_array_ref($val)) { } 1000 3024 4024
elsif (is_hash_ref($val)) { } 0 3024 3024
56 1000 for (@$val) {
57 2000 ▶ if (!defined($_) || length($_) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $_ or length $_ == 0) { } 0 2000 2000
Condition33%1/3
not defined $_ or length $_ == 0
l!l&&r!l&&!r
002000
MC/DC0%0/2
not defined $_ or length $_ == 0
not defined $_ length $_ == 0
Truth table33%1/3
not(A) or B
A= not defined $_B= length $_ == 0
ABresult
1X1
011
000
58 0 $prev->{top}->add('<null>');
59 0 $prev->{hll}->add('<null>');
60 }
61 else {
62 2000 $prev->{top}->add($_);
63 2000 $prev->{hll}->add($_);
64 2000 $count++;
65 }
66 }
67 }
68 elsif (is_hash_ref($val)) {
69 # Nested fields are not supported for now. Treat them as unique
70 # values...
71 0 $prev->{top}->add("$val");
72 0 $prev->{hll}->add("$val");
73 0 $count++;
74 }
75 else {
76 3024 ▶ if (!defined($val) || length($val) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $val or length $val == 0) { } 1270 1754 3024
Condition66%2/3
not defined $val or length $val == 0
l!l&&r!l&&!r
127001754
MC/DC50%1/2
not defined $val or length $val == 0
not defined $val length $val == 0
Truth table66%2/3
not(A) or B
A= not defined $valB= length $val == 0
ABresult
1X1
011
000
77 1270 $prev->{top}->add('<null>');
78 1270 $prev->{hll}->add('<null>');
79 }
80 else {
81 1754 $prev->{top}->add($val);
82 1754 $prev->{hll}->add($val);
83 1754 $count++;
84 }
85 }
86  
87 4024 $prev->{count} += $count;
88 4024 ▶ $prev->{zero} += 1 if $count == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $count == 0 1270 2754 4024
89 4024 $prev->{stat}->add_data($count);
90  
91 4024 $self->{res}->{$key} = $prev;
92 }
93  
94 # Return the stats for a key
95 48 ▶sub get_stat {
Subroutine get_stat: called CC=1 SCAR=0.0
Pod undocumented
96 48 my ($self,$key) = @_;
97 48 return $self->{res}->{$key}->{stat};
98 }
99  
100 # Return the estimated number of unique values in a field
101 28 ▶sub get_key_uniq {
Subroutine get_key_uniq: called CC=1 SCAR=0.0
Pod undocumented
102 28 my ($self,$key) = @_;
103 28 return sprintf "%.3f" , $self->{res}->{$key}->{hll}->estimate();
104 }
105  
106 # Return the estimated entropy of a field
107 8 ▶sub entropy {
Subroutine entropy: called CC=9 SCAR=22.3
Pod undocumented
108 8 my ($self,$key) = @_;
109  
110 8 my %values = $self->{res}->{$key}->{top}->counts;
111 8 my $sample_count = keys %values;
112 8 my $sample_cardinality = floor($self->get_key_uniq($key));
113  
114 8 ▶ my $is_exact = $sample_count == $sample_cardinality ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$sample_count == $sample_cardinality ? : 5 3 8
115  
116 8 my $cnt = 0;
117 8 my $has_unit_values = 0;
118  
119 8 for my $k (keys %values) {
120 308 $cnt += $values{$k};
121 308 ▶ $has_unit_values = 1 if $values{$k} == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $values{$k} == 1 299 9 308
122 }
123  
124 8 my $missing_values = $sample_cardinality - $sample_count;
125  
126 8 ▶ if ($missing_values > 0 && ! $has_unit_values) {
Branch: 1 branch
BranchTrueFalseTotal
if ($missing_values > 0 and not $has_unit_values) 0 8 8
Condition66%2/3
$missing_values > 0 and not $has_unit_values
!ll&&!rl&&r
530
MC/DC0%0/2
$missing_values > 0 and not $has_unit_values
$missing_values > 0 not $has_unit_values
Truth table66%2/3
A and not(B)
A= $missing_values > 0B= not $has_unit_values
ABresult
0X0
100
111
127 0 print STDERR "Statistics::TopK bin not big enough to estimate the entropy\n";
128 0 print STDERR "Increate --topk to a value > " . $self->topk . "\n";
129 0 return 'n/a';
130 }
131  
132 8 $cnt += $missing_values;
133  
134 8 ▶ return 'n/a' unless $cnt > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $cnt > 0 0 8 8
135  
136 8 my $h = 0;
137 8 for my $k (keys %values) {
138 308 my $p = $values{$k}/$cnt;
139 308 $h += $p * log($p)/log(2);
140 }
141  
142 8 ▶ if ($has_unit_values) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_unit_values) 4 4 8
143 4 my $p = 1 / $cnt;
144 4 $h += $missing_values * $p * log($p)/log(2);
145 }
146  
147 8 return sprintf "%.1f/%.1f" , -1 * $h ,log($cnt)/log(2);
148 }
149  
150 2 ▶sub commit {
Subroutine commit: called CC=12 SCAR=24.9
Pod undocumented
151 2 my ($self) = shift;
152  
153 2 my @keys = split(/,/,$self->fields);
154  
155 2 my $fields = [qw(name count zeros zeros% min max mean variance stdev uniq~ uniq% entropy)];
156  
157 2 my $exporter = Catmandu->exporter(
158 $self->as,
159 fields => $fields,
160 file => $self->file
161 );
162  
163 2 $exporter->add(
164 { name => '#' , count => $self->counter }
165 );
166  
167 2 my $has_overflow = 0;
168  
169 2 for my $key (@keys) {
170 8 my $stats = {};
171 8 $stats->{name} = $key;
172 8 $stats->{count} = $self->{res}->{$key}->{count};
173 8 $stats->{min} = $self->get_stat($key)->min();
174 8 $stats->{max} = $self->get_stat($key)->max();
175 8 $stats->{mean} = $self->get_stat($key)->mean();
176 8 $stats->{variance} = sprintf "%.1f" , $self->get_stat($key)->variance();
177 8 $stats->{stdev} = sprintf "%.1f" , $self->get_stat($key)->standard_deviation();
178 8 my ($zeros,$zerosp,$occur_count,$values_count,$uniqs);
179 8 ▶ $zeros = $self->{res}->{$key}->{zero} // 0;
Condition100%2/2
$self->{"res"}{$key}{"zero"} // 0
l!l
62
MC/DC100%1/1
$self->{"res"}{$key}{"zero"} // 0
$self->{"res"}{$key}{"zero"}
Truth table100%2/2
A
A= $self->{"res"}{$key}{"zero"}
Aresult
11
00
180 8 $values_count = $self->{res}->{$key}->{count};
181 8 $occur_count = $self->get_stat($key)->count();
182 8 ▶ $zerosp = sprintf "%.1f" , $occur_count > 0 ? 100 * $zeros / $occur_count : 100;
Branch: 1 branch
BranchTrueFalseTotal
$occur_count > 0 ? : 8 0 8
183 8 ▶ $uniqs = sprintf "%.1f" , $values_count > 0 ? 100 * $self->get_key_uniq($key) / $values_count : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
$values_count > 0 ? : 6 2 8
184  
185 8 ▶ my $overflow = $values_count > 0 ? 100 * $self->get_key_uniq($key) / $values_count : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
$values_count > 0 ? : 6 2 8
186 8 ▶ $overflow = $overflow > 100 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$overflow > 100 ? : 2 6 8
187  
188 8 $stats->{zeros} = $zeros;
189 8 $stats->{'zeros%'} = $zerosp;
190 8 $stats->{'uniq~'} = floor($self->get_key_uniq($key));
191 8 $stats->{'uniq%'} = $uniqs;
192 8 ▶ $stats->{'uniq%'} .= " (!)" if $overflow;
Branch: 1 branch
BranchTrueFalseTotal
if $overflow 2 6 8
193 8 ▶ $stats->{'uniq~'} .= " (!)" if $overflow;
Branch: 1 branch
BranchTrueFalseTotal
if $overflow 2 6 8
194 8 $stats->{entropy} = $self->entropy($key);
195 8 ▶ $stats->{entropy} .= " (!)" if $overflow;
Branch: 1 branch
BranchTrueFalseTotal
if $overflow 2 6 8
196  
197 8 $exporter->add($stats);
198  
199 8 ▶ $has_overflow = 1 if $overflow;
Branch: 1 branch
BranchTrueFalseTotal
if $overflow 2 6 8
200 }
201  
202 2 $exporter->commit;
203  
204 2 ▶ if ($has_overflow) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_overflow) 2 0 2
205 2 print STDERR <<EOF;
206 Overflow warning - probably your dataset is too small for an accurate uniq~, uniq% and entropy count...
207 EOF
208 }
209 }
210  
211 1 1;
212  
213 =head1 NAME
214  
215 Catmandu::Exporter::Stat - a statistical export
216  
217 =head1 SYNOPSIS
218  
219 # Calculate statistics on the availabity of the ISBN fields in the dataset
220 cat data.json | catmandu convert -v JSON to Stat --fields isbn
221  
222 # Export the statistics as YAML
223 cat data.json | catmandu convert -v JSON to Stat --fields isbn --as YAML
224  
225 =head1 DESCRIPTION
226  
227 The L<Catmandu::Stat> package can be used to calculate statistics on the availablity of
228 fields in a data file. Use this exporter to count the availability of fields or count
229 the number of duplicate values. For each field the exporter calculates the following
230 statistics:
231  
232 * name : the name of a field
233 * count : the number of occurences of a field in all records
234 * zeros : the number of records without a field
235 * zeros% : the percentage of records without a field
236 * min : the minimum number of occurences of a field in any record
237 * max : the maximum number of occurences of a field in any record
238 * mean : the mean number of occurences of a field in all records
239 * variance : the variance of the field number
240 * stdev : the standard deviation of the field number
241 * uniq~ : the estimated number of unique records
242 * uniq% : the estimated percentage of uniq values
243 * entropy : the minimum and maximum entropy in the field values (estimated value)
244  
245 Details:
246  
247 * entropy is an indication in the variation of field values (are some values more unique than others)
248 * entropy values are displayed as : minimum/maximum entropy
249 * when the minimum entropy = 0, then all the field values are equal
250 * when the minimum and maximum entropy are equal, then all the field values are different
251 * the 'uniq%' and 'entropy' fields are estimated and are normally within 1% of the
252 correct value (this is done to keep the memory requirements of this module low)
253  
254 Each statistical report contains one row named hash '#' which contains the total
255 number of records.
256  
257 =head1 CONFIGURATION
258  
259 =over 4
260  
261 =item v
262  
263 Verbose output. Show the processing speed.
264  
265 =item fix FIX
266  
267 A fix or a fix file containing one or more fixes applied to the input data before
268 the statistics are calculated.
269  
270 =item fields KEY[,KEY,...]
271  
272 One or more fields in the data for which statistics need to be calculated. No deep nested
273 fields are allowed. The exporter will collect statistics on the availability of a field in
274 all records. For instance, the following record contains one 'title' field, zero 'isbn'
275 fields and 3 'author' fields
276  
277 ---
278 title: ABCDEF
279 author:
280 - Davis, Miles
281 - Parker, Charly
282 - Mingus, Charles
283 year: 1950
284  
285 Examples of operation:
286  
287 # Calculate statistics on the number of records that contain a 'title'
288 cat data.json | catmandu convert JSON to Stat --fields title
289  
290 # Calculate statistics on the number of records that contain a 'title', 'isbn' or 'subject' fields
291 cat data.json | catmandu convert JSON to Stat --fields title,isbn,subject
292  
293 # The next example will not work: no deeply nested fields allowed
294 cat data.json | catmandu convert JSON to Stat --fields foo.bar.x.y
295  
296 When no fields parameter is available, then all fields are read from the first input record.
297  
298 =item as Table | CSV | YAML | JSON | ...
299  
300 By default the statistics are exported in a Table format. The use 'as' option to change the
301 export format.
302  
303 =item topk NUMBER
304  
305 To calculate the entropy an estimate of the probability distribution of the
306 data set needs to be calculated. Topk is the expected lower bound on the
307 number of field values which have repeated entries. By default it is set to
308 100. If there are more fields values with doubles, then this number needs to
309 be increased.
310  
311 =item hll NUMBER
312  
313 This is the L<Algorithm::HyperLogLog> parameter calculating the estimation of
314 cardinality (uniqueness) of a data set. The HLL register parameter, which should
315 be between 4 and 16, gives an estimate on the precision of the calculation. The
316 bigger the number, the better precision but also more memory will be used. Default: 14.
317  
318 =back
319  
320 =head1 SEE ALSO
321  
322 L<Catmandu::Exporter> ,
323 L<Statistics::Descriptive> ,
324 L<Statistics::TopK> ,
325 L<Algorithm::HyperLogLog>
326  
327 =cut
328  
329 1 1;
↑ Summary Stat.pm »