blib/lib/Hailo/Engine/Scored.pm

filter: Statementstmt 13.6% 19 / 139 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 17 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 29.4% 5 / 17 Podpod 0.0% 0 / 1 totaltotal 10.0% 24 / 239 CC 39 SCAR 45.7
CC
39
Cov
9%
reply
240.0
_evaluate_reply
132.0
_get_pivot_probabilites
20.0
CRAP 96.7
↑ Summary blib/lib/Hailo/Engine/Default.pm »
1 package Hailo::Engine::Scored;
2 1 our $AUTHORITY = 'cpan:AVAR';
3 1 $Hailo::Engine::Scored::VERSION = '0.74';
4 1 ▶use v5.28.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use List::Util qw<sum>;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use List::MoreUtils qw<any>;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Time::HiRes qw<gettimeofday tv_interval>;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 extends 'Hailo::Engine::Default';
11  
12 after BUILD => sub {
13 0 ▶ my ($self) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
14 0 my %args = $self->arguments;
15  
16 0 ▶ if (defined $args{iterations} && defined $args{interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"iterations"} and defined $args{"interval"}) 0 0 0
Condition0%0/3
defined $args{"iterations"} and defined $args{"interval"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args{"iterations"} and defined $args{"interval"}
defined $args{"iterations"} defined $args{"interval"}
Truth table0%0/3
A and B
A= defined $args{"iterations"}B= defined $args{"interval"}
ABresult
0X0
100
111
17 0 die __PACKAGE__.": You can only specify one of 'iterations' and 'interval'\n";
18 }
19 0 return;
20 1 };
21  
22 sub reply {
23 0 ▶ my $self = shift;
Subroutine reply: not called CC=15 SCAR=54.8
Pod undocumented
24 0 ▶ my $tokens = shift // [];
Condition0%0/2
shift() // []
l!l
00
MC/DC0%0/1
shift() // []
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
25  
26 # see if we recognize any of the input tokens
27 0 my $token_cache = $self->_resolve_input_tokens($tokens);
28 0 my @input_token_ids = keys %$token_cache;
29 0 my @token_counts;
30  
31 # let's select potential pivot tokens from the input
32 0 ▶ if (keys %$token_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$token_cache) 0 0 0
33 # we only want the ones with normal spacing (usually normal words)
34 @token_counts = map {
35 0 ▶ $token_cache->{$_}[0] == 0 ? [$_, $token_cache->{$_}[2]] : ()
Branch: 1 branch
BranchTrueFalseTotal
$token_cache->{$_}[0] == 0 ? : 0 0 0
36 } keys %$token_cache;
37 }
38  
39 0 my $token_probs = $self->_get_pivot_probabilites(\@token_counts);
40 0 my @started = gettimeofday();
41 0 my $iterations = 0;
42  
43 0 my $done;
44 0 my %args = $self->arguments;
45 0 ▶ if (!defined $args{iterations} && !defined $args{interval}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args{"iterations"} or defined $args{"interval"}) 0 0 0
Condition0%0/3
defined $args{"iterations"} or defined $args{"interval"}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $args{"iterations"} or defined $args{"interval"}
defined $args{"iterations"} defined $args{"interval"}
Truth table0%0/3
A or B
A= defined $args{"iterations"}B= defined $args{"interval"}
ABresult
1X1
011
000
46 # construct replies for half a second by default
47 0 $args{interval} = 0.5;
48 }
49  
50 0 ▶ if (defined $args{iterations}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{'iterations'}) { } 0 0 0
51 $done = sub {
52 0 ▶ return 1 if $iterations == $args{iterations};
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $iterations == $args{"iterations"} 0 0 0
53 0 };
54 }
55 else {
56 $done = sub {
57 0 ▶ my $elapsed = tv_interval(\@started, [gettimeofday]);
Subroutine __ANON__: not called CC=2 SCAR=17.9
58 0 ▶ return 1 if $elapsed >= $args{interval};
Branch: 1 branch
BranchTrueFalseTotal
if $elapsed >= $args{"interval"} 0 0 0
59 0 };
60 }
61  
62 0 my (%link_cache, %expr_cache, $best_score, $best_reply);
63 0 while (1) {
64 0 $iterations++;
65 0 my $reply = $self->_generate_reply($token_probs, \%expr_cache);
66 0 ▶ return if !defined $reply; # we don't know any expressions yet
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reply 0 0 0
67  
68 0 my $score = $self->_evaluate_reply(\@input_token_ids, $reply, \%link_cache);
69  
70 0 ▶ if (defined $best_reply && $self->_too_similar(\@input_token_ids, $reply)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $best_reply and $self->_too_similar(\@input_token_ids, $reply)) 0 0 0
Condition0%0/3
defined $best_reply and $self->_too_similar(\@input_token_ids, $reply)
!ll&&!rl&&r
000
MC/DC0%0/2
defined $best_reply and $self->_too_similar(\@input_token_ids, $reply)
defined $best_reply $self->_too_similar(\@input_token_ids, $reply)
Truth table0%0/3
A and B
A= defined $best_replyB= $self->_too_similar(\@input_token_ids, $reply)
ABresult
0X0
100
111
71 0 ▶ last if $done->();
Branch: 1 branch
BranchTrueFalseTotal
if &$done() 0 0 0
72 0 next;
73 }
74  
75 0 ▶ if (!defined $best_score || $score > $best_score) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $best_score or $score > $best_score) 0 0 0
Condition0%0/3
not defined $best_score or $score > $best_score
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $best_score or $score > $best_score
not defined $best_score $score > $best_score
Truth table0%0/3
not(A) or B
A= not defined $best_scoreB= $score > $best_score
ABresult
1X1
011
000
76 0 $best_score = $score;
77 0 $best_reply = $reply;
78 }
79  
80 0 ▶ last if $done->();
Branch: 1 branch
BranchTrueFalseTotal
if &$done() 0 0 0
81 }
82  
83 # translate token ids to token spacing/text
84 my @output = map {
85 0 ▶ $token_cache->{$_} // ($token_cache->{$_} = $self->_token_info($_))
Condition0%0/3
$token_cache->{$_} // ($token_cache->{$_} = $self->_token_info($_))
l!l&&r!l&&!r
000
MC/DC0%0/2
$token_cache->{$_} // ($token_cache->{$_} = $self->_token_info($_))
$token_cache->{$_} ($token_cache->{$_} = $self->_token_info($_))
Truth table0%0/3
A // B
A= $token_cache->{$_}B= ($token_cache->{$_} = $self->_token_info($_))
ABresult
1X1
011
000
86 } @$best_reply;
87 0 return \@output;
88 }
89  
90 # Calculate the probability we wish to pick each token as the pivot.
91 # This uses -log2(p) as a method for inverting token probability,
92 # ensuring that our rarer tokens are picked more often.
93 sub _get_pivot_probabilites {
94 0 ▶ my ($self, $token_counts) = @_;
Subroutine _get_pivot_probabilites: not called CC=4 SCAR=30.0
95  
96 0 ▶ return [] if !@$token_counts;
Branch: 1 branch
BranchTrueFalseTotal
unless @$token_counts 0 0 0
97 0 ▶ return [[$token_counts->[0], 1]] if @$token_counts == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @$token_counts == 1 0 0 0
98  
99 # calculate the (non-normalized) probability we want each to occur
100 0 my $count_sum = sum(map { $_->[1] } @$token_counts);
101 0 my $p = [];
102 0 my $p_sum = 0;
103 0 for my $token_count (map { $_->[1] } @$token_counts) {
104 0 my $token_p = -log(($token_count/$count_sum))/log(2);
105 0 push @$p, $token_p;
106 0 $p_sum += $token_p;
107 }
108  
109 # normalize the probabilities
110 my @probs = map {
111 0 [$token_counts->[$_], $p->[$_] / $p_sum];
112 0 } 0..$#{ $token_counts };
113  
114 0 return \@probs;
115 }
116  
117 sub _generate_reply {
118 0 ▶ my ($self, $token_probs, $expr_cache) = @_;
Subroutine _generate_reply: not called CC=3 SCAR=24.8
119  
120 0 my ($pivot_expr_id, @token_ids) = @_;
121 0 ▶ if (@$token_probs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$token_probs) { } 0 0 0
122 0 my $pivot_token_id = $self->_choose_pivot($token_probs);
123 0 ($pivot_expr_id, @token_ids) = $self->_random_expr($pivot_token_id);
124 }
125 else {
126 0 ($pivot_expr_id, @token_ids) = $self->_random_expr();
127 0 ▶ return if !defined $pivot_expr_id; # no expressions in the database
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pivot_expr_id 0 0 0
128 }
129  
130 # construct the end of the reply
131 0 $self->_construct_reply('next', $pivot_expr_id, \@token_ids, $expr_cache);
132  
133 # construct the beginning of the reply
134 0 $self->_construct_reply('prev', $pivot_expr_id, \@token_ids, $expr_cache);
135  
136 0 return \@token_ids;
137 }
138  
139 sub _evaluate_reply {
140 0 ▶ my ($self, $input_token_ids, $reply_token_ids, $cache) = @_;
Subroutine _evaluate_reply: not called CC=11 SCAR=48.8
141 0 my $order = $self->order;
142 0 my $score = 0;
143  
144 0 for my $idx (0 .. $#{ $reply_token_ids } - $order) {
145 0 my $next_token_id = $reply_token_ids->[$idx];
146  
147 0 ▶ if (any { $_ == $next_token_id } @$input_token_ids) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if (&any(sub { $_ == $next_token_id; } , @$input_token_ids)) 0 0 0
148 0 my @expr = @$reply_token_ids[$idx .. $idx+$order-1];
149 0 my $key = join('_', @expr)."-$next_token_id";
150  
151 0 ▶ if (!defined $cache->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cache->{$key}) 0 0 0
152 0 $cache->{$key} = $self->_expr_token_probability('next', \@expr, $next_token_id);
153 }
154 0 ▶ if ($cache->{$key} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache->{$key} > 0) 0 0 0
155 0 $score -= log($cache->{$key})/log(2);
156 }
157 }
158 }
159  
160 0 for my $idx (0 .. $#{ $reply_token_ids } - $order) {
161 0 my $prev_token_id = $reply_token_ids->[$idx];
162  
163 0 ▶ if (any { $_ == $prev_token_id } @$input_token_ids) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if (&any(sub { $_ == $prev_token_id; } , @$input_token_ids)) 0 0 0
164 0 my @expr = @$reply_token_ids[$idx+1 .. $idx+$order];
165 0 my $key = "$prev_token_id-".join('_', @expr);
166  
167 0 ▶ if (!defined $cache->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cache->{$key}) 0 0 0
168 0 $cache->{$key} = $self->_expr_token_probability('prev', \@expr, $prev_token_id);
169 }
170 0 ▶ if ($cache->{$key} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache->{$key} > 0) 0 0 0
171 0 $score -= log($cache->{$key})/log(2);
172 }
173 }
174 }
175  
176 # Prefer shorter replies. This behavior is present but not
177 # documented in recent MegaHAL.
178 0 my $score_divider = 1;
179 0 ▶ if (@$reply_token_ids >= 8) {
Branch: 2 branches
BranchTrueFalseTotal
if (@$reply_token_ids >= 8) { } 0 0 0
elsif (@$reply_token_ids >= 16) { } 0 0 0
180 0 $score /= sqrt(@$reply_token_ids - 1);
181 }
182 elsif (@$reply_token_ids >= 16) {
183 0 $score /= @$reply_token_ids;
184 }
185  
186 0 return $score;
187 }
188  
189 sub _expr_token_probability {
190 0 ▶ my ($self, $pos, $expr, $token_id) = @_;
Subroutine _expr_token_probability: not called CC=2 SCAR=17.9
191 0 my $order = $self->order;
192  
193 0 my $expr_id = $self->_expr_id_add($expr);
194  
195 0 $self->{"_sth_${pos}_token_count"}->execute($expr_id, $token_id);
196 0 my $expr2token = $self->{"_sth_${pos}_token_count"}->fetchrow_array();
197 0 ▶ return 0 if !$expr2token;
Branch: 1 branch
BranchTrueFalseTotal
unless $expr2token 0 0 0
198  
199 0 $self->{"_sth_${pos}_token_links"}->execute($expr_id);
200 0 my $expr2all = $self->{"_sth_${pos}_token_links"}->fetchrow_array();
201 0 return $expr2token / $expr2all;
202 }
203  
204 sub _choose_pivot {
205 0 ▶ my ($self, $token_probs) = @_;
Subroutine _choose_pivot: not called CC=3 SCAR=24.8
206  
207 0 my $random = rand;
208 0 my $p = 0;
209 0 for my $token (@$token_probs) {
210 0 $p += $token->[1];
211 0 ▶ return $token->[0][0] if $p > $random;
Branch: 1 branch
BranchTrueFalseTotal
if $p > $random 0 0 0
212 }
213  
214 0 return;
215 }
216  
217 sub _too_similar {
218 0 ▶ my ($self, $input_token_ids, $reply_token_ids) = @_;
Subroutine _too_similar: not called CC=3 SCAR=24.8
219  
220 0 my %input_token_ids = map { +$_ => 1 } @$input_token_ids;
221  
222 0 for my $reply_token_id (@$reply_token_ids) {
223 0 ▶ return if !$input_token_ids{$reply_token_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $input_token_ids{$reply_token_id} 0 0 0
224 }
225 0 return 1;
226 }
227  
228 1 __PACKAGE__->meta->make_immutable;
229  
230 =encoding utf8
231  
232 =head1 NAME
233  
234 Hailo::Engine::Scored - MegaHAL-style reply scoring for L<Hailo|Hailo>
235  
236 =head1 DESCRIPTION
237  
238 This backend implements the logic of replying to and learning from
239 input using the resources given to the L<engine
240 roles|Hailo::Role::Engine>. It is inherits from
241 L<Hailo::Engine::Default|Hailo::Engine::Default> and only overrides its
242 C<reply> method.
243  
244 It generates multiple replies and applies a scoring algorithm to them, then
245 returns the best one, similar to MegaHAL.
246  
247 =head1 ATTRIBUTES
248  
249 =head2 C<engine_args>
250  
251 This is a hash reference which can have the following keys:
252  
253 =head3 C<iterations>
254  
255 The number of replies to generate before returning the best one.
256  
257 =head3 C<interval>
258  
259 The time (in seconds) to spend on generating replies before returning the
260 best one.
261  
262 You can not specify both C<iterations> and C<interval> at the same time. If
263 neither is specified, a default C<interval> of 0.5 seconds will be used.
264  
265 =head1 AUTHORS
266  
267 Hinrik E<Ouml>rn SigurE<eth>sson, hinrik.sig@gmail.com
268  
269 This module was based on code from Peter Teichman's Cobe project.
270  
271 =head1 LICENSE AND COPYRIGHT
272  
273 Copyright 2010 Hinrik E<Ouml>rn SigurE<eth>sson and
274 E<AElig>var ArnfjE<ouml>rE<eth> Bjarmason <avar@cpan.org>
275  
276 This program is free software, you can redistribute it and/or modify
277 it under the same terms as Perl itself.
278  
279 =cut
↑ Summary blib/lib/Hailo/Engine/Default.pm »