blib/lib/Lingua/Word/Parser.pm

filter: Statementstmt 87.9% 175 / 199 Branchbran 62.9% 34 / 54 Conditioncond 70.0% 7 / 10 MC/DCmcdc 50.0% 3 / 6 Subroutinesub 90.4% 19 / 21 Podpod 100% 5 / 5 totaltotal 82.3% 243 / 295 CC 47 SCAR 25.4
CC
47
Cov
82%
_db_fetch
72.0
_reconstruct
9.0
score_parts
7.0
CRAP 12.7
↑ Summary
1 package Lingua::Word::Parser;
2 2 our $AUTHORITY = 'cpan:GENE';
3  
4 # ABSTRACT: Parse a word into scored known and unknown parts
5  
6 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 2 our $VERSION = '0.0900';
10  
11 2 ▶use Bit::Vector ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use DBI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use IO::File ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 2 ▶use Memoize qw(memoize);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 memoize('_grouping');
17 2 memoize('_rle');
18  
19  
20  
21 sub new {
22 2 ▶ my $class = shift;
Subroutine new: called CC=3 SCAR=11.2
Pod documented
23 2 my %args = @_;
24 my $self = {
25 file => $args{file},
26 dbhost => $args{dbhost} || 'localhost',
27 dbtype => $args{dbtype} || 'mysql',
28 dbname => $args{dbname},
29 dbuser => $args{dbuser},
30 dbpass => $args{dbpass},
31 lex => $args{lex},
32 word => $args{word},
33 2 ▶ known => {},
Condition50%2/4
$args{'dbhost'} || 'localhost'
l!l
02
$args{'dbtype'} || 'mysql'
l!l
02
MC/DC0%0/1
$args{'dbhost'} || 'localhost'
$args{'dbhost'}
MC/DC0%0/1
$args{'dbtype'} || 'mysql'
$args{'dbtype'}
Truth table50%1/2
A
A= $args{'dbhost'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'dbtype'}
Aresult
11
00
34 masks => {},
35 combos => [],
36 score => {},
37 };
38 2 bless $self, $class;
39 2 $self->_init(%args);
40 2 return $self;
41 }
42 sub _init {
43 2 ▶ my ($self, %args) = @_;
Subroutine _init: called CC=4 SCAR=14.5
44  
45 # Set the length of our word.
46 2 $self->{wlen} = length $self->{word};
47  
48 # Set lex if given data.
49 2 ▶ if ( $self->{file} && -e $self->{file} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'file'} and -e $self->{'file'}) { } 1 1 2
elsif ($self->{'dbname'}) { } 0 1 1
Condition66%2/3
$self->{"file"} and -e $self->{"file"}
!ll&&!rl&&r
101
MC/DC50%1/2
$self->{"file"} and -e $self->{"file"}
$self->{"file"} -e $self->{"file"}
Truth table66%2/3
A and B
A= $self->{"file"}B= -e $self->{"file"}
ABresult
0X0
100
111
50 1 $self->_fetch_lex;
51 }
52 elsif( $self->{dbname} )
53 {
54 0 $self->_db_fetch;
55 }
56 }
57  
58 sub _fetch_lex {
59 1 ▶ my $self = shift;
Subroutine _fetch_lex: called CC=3 SCAR=11.0
60  
61 1 my $i = 0;
62  
63 # Open the given file for reading...
64 1 my $fh = IO::File->new;
65 1 ▶ $fh->open($self->{file}, '<') or die "Can't read file: '$self->{file}'";
Branch: 1 branch
BranchTrueFalseTotal
$fh->open($self->{"file"}, "<") or die qq[Can't read file: '$self->{"file"}'] 0 1 1
66 1 for ( <$fh> ) {
67 9 $i++;
68 # Split space-separated entries.
69 9 chomp;
70 9 my ($re, $defn) = split /\s+/, $_, 2;
71 # Add the entry to the lexicon.
72 9 $self->{lex}{$i} = { defn => $defn, re => qr/$re/ };
73 }
74 1 $fh->close;
75  
76 1 return $self->{lex};
77 }
78  
79 sub _db_fetch {
80 0 ▶ my $self = shift;
Subroutine _db_fetch: not called CC=8 SCAR=42.8
81  
82 0 my $dsn;
83 0 ▶ if (lc($self->{dbtype}) eq 'sqlite') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $self->{'dbtype'} eq 'sqlite') { } 0 0 0
84 0 $dsn = "DBI:$self->{dbtype}:dbname=$self->{dbname};$self->{dbhost}";
85 }
86 else {
87 0 $dsn = "DBI:$self->{dbtype}:$self->{dbname};$self->{dbhost}";
88 }
89  
90 0 ▶ my $dbh = DBI->connect( $dsn, $self->{dbuser}, $self->{dbpass}, { RaiseError => 1, AutoCommit => 1 } )
Branch: 1 branch
BranchTrueFalseTotal
my $dbh = "DBI"->connect($dsn, $self->{"dbuser"}, $self->{"dbpass"}, {"RaiseError", 1, "AutoCommit", 1}) or die qq[Unable to connect to $self->{"dbname"}: $DBI::errstr\n] 0 0 0
91 or die "Unable to connect to $self->{dbname}: $DBI::errstr\n";
92  
93 0 my $sql = 'SELECT id, affix, definition FROM fragment';
94  
95 0 my $sth = $dbh->prepare($sql);
96 0 ▶ $sth->execute or die "Unable to execute '$sql': $DBI::errstr\n";
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute or die "Unable to execute '${sql}': $DBI::errstr\n" 0 0 0
97  
98 0 ▶ while( my @row = $sth->fetchrow_array ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@row) = $sth->fetchrow_array) 0 0 0
99 0 my ($id, $part, $defn) = @row;
100 0 $self->{lex}{$id} = { re => qr/$part/, defn => $defn };
101 }
102 0 ▶ die "Fetch terminated early: $DBI::errstr\n" if $DBI::errstr;
Branch: 1 branch
BranchTrueFalseTotal
if $DBI::errstr 0 0 0
103  
104 0 ▶ $sth->finish or die "Unable to finish '$sql': $DBI::errstr\n";
Branch: 1 branch
BranchTrueFalseTotal
$sth->finish or die "Unable to finish '${sql}': $DBI::errstr\n" 0 0 0
105  
106 0 ▶ $dbh->disconnect or die "Unable to disconnect from $self->{dbname}: $DBI::errstr\n";
Branch: 1 branch
BranchTrueFalseTotal
$dbh->disconnect or die qq[Unable to disconnect from $self->{"dbname"}: $DBI::errstr\n] 0 0 0
107 }
108  
109  
110 sub knowns {
111 1 ▶ my $self = shift;
Subroutine knowns: called CC=4 SCAR=13.9
Pod documented
112  
113 # The identifier for the known and masks lists.
114 1 my $id = 0;
115  
116 1 for my $i (values %{ $self->{lex} }) {
117 9 ▶ while ($self->{word} =~ /$i->{re}/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"word"} =~ /$i->{"re"}/g) 10 9 19
118 # Match positions.
119 10 my ($m, $n) = ($-[0], $+[0]);
120 # Get matched word-part.
121 10 my $part = substr $self->{word}, $m, $n - $m;
122  
123 10 ▶ next if $n == $m; # skip zero-width matches instead of padding the mask
Branch: 1 branch
BranchTrueFalseTotal
if $n == $m 0 10 10
124  
125 # Create the part-of-word bitmask.
126 10 my $mask = 0 x $m; # Before known
127 10 $mask .= 1 x ($n - $m); # Known part
128 10 $mask .= 0 x ($self->{wlen} - $n); # After known
129  
130 # Output our progress.
131 # warn sprintf "%s %s - %s, %s (%d %d), %s\n",
132 # $mask,
133 # $i->{re},
134 # substr($self->{word}, 0, $m),
135 # $part,
136 # $m,
137 # $n - 1,
138 # substr($self->{word}, $n),
139 # ;
140  
141 # Save the known as a member of a list keyed by starting position.
142 $self->{known}{$id} = {
143 part => $part,
144 span => [$m, $n - 1],
145 defn => $i->{defn},
146 10 mask => $mask,
147 };
148  
149 # Save the relationship between mask and id.
150 10 $self->{masks}{$mask} = $id++;
151 }
152 }
153  
154 1 return $self->{known};
155 }
156  
157  
158 sub power {
159 1 ▶ my $self = shift;
Subroutine power: called CC=2 SCAR=6.9
Pod documented
160  
161 # Precompute each mask's [start, end) span once
162 1 my @spans;
163 1 for my $mask (keys %{ $self->{masks} }) {
164 10 $mask =~ /^(0*)(1+)/;
165 10 push @spans, { start => length($1), end => length($1) + length($2), mask => $mask };
166 }
167 1 @spans = sort { $a->{start} <=> $b->{start} } @spans;
168  
169 # Recursively extend only with spans that don't overlap what's already chosen
170 1 my @combos;
171 my $extend;
172 $extend = sub {
173 216 ▶ my ($from_idx, $chosen) = @_;
Subroutine __ANON__: called CC=5 SCAR=16.1
174 216 ▶ push @combos, [ map { $_->{mask} } @$chosen ] if @$chosen;
Branch: 1 branch
BranchTrueFalseTotal
if @$chosen 215 1 216
175 216 for my $idx ($from_idx .. $#spans) {
176 306 my $span = $spans[$idx];
177 306 ▶ next if @$chosen && $span->{start} < $chosen->[-1]{end};
Branch: 1 branch
BranchTrueFalseTotal
if @$chosen and $span->{"start"} < $chosen->[-1]{"end"} 91 215 306
Condition100%3/3
@$chosen and $span->{"start"} < $chosen->[-1]{"end"}
!ll&&!rl&&r
1020591
MC/DC100%2/2
@$chosen and $span->{"start"} < $chosen->[-1]{"end"}
@$chosen $span->{"start"} < $chosen->[-1]{"end"}
Truth table100%3/3
A and B
A= @$chosenB= $span->{"start"} < $chosen->[-1]{"end"}
ABresult
0X0
100
111
178 215 $extend->($idx + 1, [ @$chosen, $span ]);
179 }
180 1 };
181 1 $extend->(0, []);
182  
183 1 $self->{combos} = \@combos;
184  
185 # Hand back the "non-overlapping powerset."
186 1 return $self->{combos};
187 }
188  
189  
190 sub score {
191 1 ▶ my $self = shift;
Subroutine score: called CC=3 SCAR=11.0
Pod documented
192 1 my ( $open_separator, $close_separator ) = @_;
193  
194 1 my $parts = $self->score_parts( $open_separator, $close_separator );
195  
196 1 for my $mask ( keys %$parts ) {
197 179 my $familiarity = sprintf "%.2f chunks / %.2f chars", @{ $self->_familiarity($mask) };
198  
199 179 for my $element ( @{ $parts->{$mask} } ) {
200 my $score = sprintf "%d:%d chunks / %d:%d chars",
201 $element->{score}{knowns}, $element->{score}{unknowns},
202 430 $element->{score}{knownc}, $element->{score}{unknownc};
203  
204 430 my $part = join ', ', @{ $element->{partition} };
205  
206 430 my $defn = join ', ', @{ $element->{definition} };
207  
208 430 push @{ $self->{score}{$mask} }, {
209 score => $score,
210 familiarity => $familiarity,
211 partition => $part,
212 definition => $defn,
213 };
214 }
215 }
216  
217 1 return $self->{score};
218 }
219  
220 sub _familiarity {
221 609 ▶ my ( $self, $mask ) = @_;
Subroutine _familiarity: called CC=4 SCAR=13.9
222  
223 609 my @chunks = grep { $_ ne "" } split /(0+)/, $mask;
224  
225 # Figure out how many chars are only 1s and
226 # Figure out how many chunks are made up of 1s:
227 609 my $char_1s = 0;
228 609 my $chunk_1s = 0;
229 609 for my $chunk (@chunks) {
230 2577 ▶ $char_1s += $chunk =~ /0/ ? 0 : length($chunk);
Branch: 1 branch
BranchTrueFalseTotal
$chunk =~ /0/ ? : 1209 1368 2577
231 2577 ▶ $chunk_1s += $chunk =~ /0/ ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$chunk =~ /0/ ? : 1209 1368 2577
232 }
233  
234 609 return [ $chunk_1s / @chunks, $char_1s / length($mask) ];
235 }
236  
237  
238 sub score_parts {
239 2 ▶ my $self = shift;
Subroutine score_parts: called CC=7 SCAR=19.5
Pod documented
240 2 my ( $open_separator, $close_separator, $line_terminator ) = @_;
241  
242 2 ▶ $line_terminator = '' unless defined $line_terminator;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line_terminator 2 0 2
243  
244 # Visit each combination...
245 2 my $i = 0;
246 2 for my $c (@{ $self->{combos} }) {
247 430 $i++;
248 430 my $together = $self->_or_together(@$c);
249  
250 # Breakdown knowns vs unknowns and knowncharacters vs unknowncharacters.
251 430 my %count = (
252 knowns => 0,
253 unknowns => 0,
254 knownc => 0,
255 unknownc => 0,
256 );
257  
258 430 for my $x ( reverse sort @$c ) {
259 # Run-length encode an "un-digitized" string.
260 1440 my $y = _rle($x);
261 1440 my ( $knowns, $unknowns, $knownc, $unknownc ) = _grouping($y);
262 # Accumulate the counters!
263 1440 $count{knowns} += $knowns;
264 1440 $count{unknowns} += $unknowns;
265 1440 $count{knownc} += $knownc;
266 1440 $count{unknownc} += $unknownc;
267 }
268  
269 430 my ( $s, $m ) = _reconstruct( $self->{word}, $c, $open_separator, $close_separator );
270  
271 430 my $defn = [];
272 430 for my $k ( @$m )
273 {
274 1440 for my $j ( keys %{ $self->{known} } )
275 {
276 14400 ▶ push @$defn, $self->{known}{$j}{defn} if $self->{known}{$j}{mask} eq $k;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"known"}{$j}{"mask"} eq $k 1440 12960 14400
277 }
278 }
279  
280 430 push @{ $self->{score_parts}{$together} }, {
281 score => \%count,
282 partition => $s,
283 definition => $defn,
284 familiarity => $self->_familiarity($together),
285 };
286 }
287  
288 2 return $self->{score_parts};
289 }
290  
291 sub _grouping {
292 10 ▶ my $scored = shift;
Subroutine _grouping: called CC=4 SCAR=13.9
293 10 my @groups = $scored =~ /([ku]\d+)/g;
294 10 my ( $knowns, $unknowns ) = ( 0, 0 );
295 10 my ( $knownc, $unknownc ) = ( 0, 0 );
296 10 for ( @groups ) {
297 26 ▶ if ( /k(\d+)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/k(\d+)/) 10 16 26
298 10 $knowns++;
299 10 $knownc += $1;
300 }
301 26 ▶ if ( /u(\d+)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (/u(\d+)/) 16 10 26
302 16 $unknowns++;
303 16 $unknownc += $1;
304 }
305 }
306 10 return $knowns, $unknowns, $knownc, $unknownc;
307 }
308  
309 sub _rle {
310 10 ▶ my $scored = shift;
Subroutine _rle: called CC=1 SCAR=0.0
311 # Run-length encode an "un-digitized" string.
312 10 $scored =~ s/1/k/g; # Undigitize
313 10 $scored =~ s/0/u/g; # "
314 # Count contiguous chars.
315 10 $scored =~ s/(.)\1*/$1 . length(substr($scored, $-[0], $+[0]-$-[0]))/ge;
316 10 return $scored;
317 }
318  
319 sub _does_not_overlap {
320 0 ▶ my $self = shift;
Subroutine _does_not_overlap: not called CC=2 SCAR=17.9
321  
322 # Get our masks to check.
323 0 my ($mask, $check) = @_;
324  
325 # Create the bitstrings to compare.
326 0 my $bitmask = Bit::Vector->new_Bin($self->{wlen}, $mask);
327 0 my $orclone = Bit::Vector->new_Bin($self->{wlen}, $check);
328 0 my $xorclone = Bit::Vector->new_Bin($self->{wlen}, $check);
329  
330 # Compute or and xor for the strings.
331 0 $orclone->Or($bitmask, $orclone);
332 0 $xorclone->Xor($bitmask, $xorclone);
333  
334 # Return the "or & xor equivalent sibling."
335 0 ▶ return $xorclone->equal($orclone) ? $orclone->to_Bin : 0;
Branch: 1 branch
BranchTrueFalseTotal
$xorclone->equal($orclone) ? : 0 0 0
336 }
337  
338 sub _or_together {
339 430 ▶ my $self = shift;
Subroutine _or_together: called CC=2 SCAR=6.9
340  
341 # Get our masks to score.
342 430 my @masks = @_;
343  
344 # Initialize the bitmask to return, to zero.
345 430 my $result = Bit::Vector->new_Bin($self->{wlen}, (0 x $self->{wlen}));
346  
347 430 for my $mask (@masks) {
348 # Create the bitstrings to compare.
349 1440 my $bitmask = Bit::Vector->new_Bin($self->{wlen}, $mask);
350  
351 # Get the union of the bit strings.
352 1440 $result->Or($result, $bitmask);
353 }
354  
355 # Return the "or sum."
356 430 return $result->to_Bin;
357 }
358  
359 sub _reconstruct {
360 430 ▶ my ( $word, $masks, $open_separator, $close_separator ) = @_;
Subroutine _reconstruct: called CC=9 SCAR=22.0
361  
362 430 ▶ $open_separator = '<' unless defined $open_separator;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $open_separator 215 215 430
363 430 ▶ $close_separator = '>' unless defined $close_separator;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $close_separator 215 215 430
364  
365 430 my $strings = [];
366 430 my $my_masks = [];
367  
368 430 for my $mask (reverse sort @$masks) {
369 1440 my $i = 0;
370 1440 my $last = 0;
371 1440 my $string = '';
372 1440 for my $m ( split //, $mask ) {
373 14400 ▶ if ( $m ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m) { } 2376 12024 14400
374 2376 ▶ $string .= $open_separator unless $last;
Branch: 1 branch
BranchTrueFalseTotal
unless $last 1440 936 2376
375 2376 $string .= substr( $word, $i, 1 );
376 2376 $last = 1;
377 }
378 else {
379 12024 ▶ $string .= $close_separator if $last;
Branch: 1 branch
BranchTrueFalseTotal
if $last 1152 10872 12024
380 12024 $string .= substr( $word, $i, 1 );
381 12024 $last = 0;
382 }
383 14400 $i++;
384 }
385 1440 ▶ $string .= $close_separator if $last;
Branch: 1 branch
BranchTrueFalseTotal
if $last 288 1152 1440
386 1440 push @$strings, $string;
387 1440 push @$my_masks, $mask;
388 }
389  
390 430 return $strings, $my_masks;
391 }
392  
393 2 1;
394  
395 __END__
↑ Summary