blib/lib/Search/ContextGraph.pm

filter: Statementstmt 67.5% 444 / 657 Branchbran 45.3% 118 / 260 Conditioncond 45.4% 30 / 66 MC/DCmcdc 22.8% 8 / 35 Subroutinesub 73.2% 52 / 71 Podpod 70.0% 35 / 50 totaltotal 60.3% 687 / 1139 CC 198 SCAR 29.7
CC
198
Cov
60%
add_file
132.0
distance_matrix
90.0
rename
42.0
CRAP 19.5
↑ Summary blib/lib/Search/bench.pl »
1 package Search::ContextGraph;
2  
3 14 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 14 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 14 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 14 ▶use base "Storable";
Subroutine BEGIN: called CC=1 SCAR=0.0
7 14 ▶use File::Find;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 14 ▶use IO::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 14 our $VERSION = '0.15';
11  
12  
13 14 my $count = 0;
14  
15  
16 =head1 NAME
17  
18 Search::ContextGraph - spreading activation search engine
19  
20 =head1 SYNOPSIS
21  
22 use Search::ContextGraph;
23  
24 my $cg = Search::ContextGraph->new();
25  
26 # first you add some documents, perhaps all at once...
27
28 my %docs = (
29 'first' => [ 'elephant', 'snake' ],
30 'second' => [ 'camel', 'pony' ],
31 'third' => { 'snake' => 2, 'constrictor' => 1 },
32 );
33  
34 $cg->bulk_add( %docs );
35
36 # or in a loop...
37
38 foreach my $title ( keys %docs ) {
39 $cg->add( $title, $docs{$title} );
40 }
41  
42 # or from a file...
43  
44 my $cg = Search::ContextGraph->load_from_dir( "./myfiles" );
45  
46 # you can store a graph object for later use
47
48 $cg->store( "stored.cng" );
49
50 # and retrieve it later...
51
52 my $cg = ContextGraph->retrieve( "stored.cng" );
53
54
55 # SEARCHING
56
57 # the easiest way
58  
59 my @ranked_docs = $cg->simple_search( 'peanuts' );
60  
61  
62 # get back both related terms and docs for more power
63  
64 my ( $docs, $words ) = $cg->search('snake');
65  
66  
67 # you can use a document as your query
68  
69 my ( $docs, $words ) = $cg->find_similar('First Document');
70  
71  
72 # Or you can query on a combination of things
73  
74 my ( $docs, $words ) =
75 $cg->mixed_search( { docs => [ 'First Document' ],
76 terms => [ 'snake', 'pony' ]
77 );
78  
79  
80 # Print out result set of returned documents
81 foreach my $k ( sort { $docs->{$b} <=> $docs->{$a} }
82 keys %{ $docs } ) {
83 print "Document $k had relevance ", $docs->{$k}, "\n";
84 }
85  
86  
87  
88 # Reload it
89 my $new = Search::ContextGraph->retrieve( "filename" );
90  
91  
92  
93 =head1 DESCRIPTION
94  
95 Spreading activation is a neat technique for building search engines that
96 return accurate results for a query even when there is no exact keyword match.
97 The engine works by building a data structure called a B<context graph>, which
98 is a giant network of document and term nodes. All document nodes are connected
99 to the terms that occur in that document; similarly, every term node is connected
100 to all of the document nodes that term occurs in. We search the graph by
101 starting at a query node and distributing a set amount of energy to its neighbor
102 nodes. Then we recurse, diminishing the energy at each stage, until this
103 spreading energy falls below a given threshold. Each node keeps track of
104 accumulated energy, and this serves as our measure of relevance.
105  
106 This means that documents that have many words in common will appear similar to the
107 search engine. Likewise, words that occur together in many documents will be
108 perceived as semantically related. Especially with larger, coherent document
109 collections, the search engine can be quite effective at recognizing synonyms
110 and finding useful relationships between documents. You can read a full
111 description of the algorithm at L<http://www.nitle.org/papers/Contextual_Network_Graphs.pdf>.
112  
113 The search engine gives expanded recall (relevant results even when there is no
114 keyword match) without incurring the kind of computational and patent issues
115 posed by latent semantic indexing (LSI). The technique used here was originally
116 described in a 1981 dissertation by Scott Preece.
117  
118 =head1 CONSTRUCTORS
119  
120 =over
121  
122 =item new %PARAMS
123  
124 Object constructor. Possible parameters:
125  
126 =over
127  
128 =item auto_reweight
129  
130 Rebalance the graph every time a change occurs. Default is true.
131 Disable and do by hand using L<reweight_graph> for better performance in
132 graphs with frequent updates/additions/deletions.
133  
134  
135 =item debug LEVEL
136  
137 Set this to 1 or 2 to turn on verbose debugging output
138  
139 =item max_depth
140  
141 Set the maximum distance to spread energy out from the start
142 node. Default is effectively unlimited. You can tweak it using L<set_max_depth>.
143 Comes in handy if you find searches are too slow.
144  
145 =item xs
146  
147 When true, tells the module to use compiled C internals. This reduces
148 memory requirements by about 60%, but actually runs a little slower than the
149 pure Perl version. Don't bother to turn it on unless you have a huge graph.
150 Default is pure Perl.
151  
152 =over
153  
154 =item * using the compiled version makes it impossible to store the graph to disk.
155  
156 =item * xs is B<broken> in version 0.09. But it will return in triumph!
157  
158 =back
159  
160 =item START_ENERGY
161  
162 Initial energy to assign to a query node. Default is 100.
163  
164 =item ACTIVATE_THRESHOLD
165  
166 Minimal energy needed to propagate search along the graph. Default is 1.
167  
168 =item COLLECT_THRESHOLD
169  
170 Minimal energy needed for a node to enter the result set. Default is 1.
171  
172 =back
173  
174 =cut
175  
176  
177 17 ▶sub new {
Subroutine new: called CC=7 SCAR=19.6
Pod documented
178 17 my ( $class, %params) = @_;
179  
180 # backwards compatible...
181 17 *add_document = \&add;
182 17 *add_documents = \&bulk_add;
183
184 # plucene friendly
185 17 *optimize = \&reweight_graph;
186 17 *is_indexed = \&has_doc;
187
188 # fail on all unknown paramters (helps fight typos)
189 17 my @allowed = qw/debug auto_reweight use_global_weights max_depth START_ENERGY ACTIVATE_THRESHOLD COLLECT_THRESHOLD use_file xs/;
190 17 my %check;
191 17 $check{$_}++ foreach @allowed;
192
193 17 my @forbidden;
194 17 foreach my $k ( keys %params ) {
195 15 ▶ push @forbidden, $k unless exists $check{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $check{$k} 0 15 15
196 }
197 17 ▶ if ( @forbidden ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@forbidden) 0 17 17
198 0 croak "The following unrecognized parameters were detected: ",
199 join ", ", @forbidden;
200 }
201  
202  
203 17 my $obj = bless
204 { debug => 0,
205 auto_reweight => 1,
206 use_global_weights => 1,
207 max_depth => 100000000,
208 START_ENERGY => 100,
209 ACTIVATE_THRESHOLD => 1,
210 COLLECT_THRESHOLD => .2,
211 %params,
212  
213 depth => 0,
214 neighbors => {},
215  
216 },
217 $class;
218
219
220 17 ▶ if ( $obj->{use_file} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj->{"use_file"}) 1 16 17
221 1 my %neighbors;
222 14 ▶ use MLDBM qw/DB_File Storable/;
Subroutine BEGIN: called CC=1 SCAR=0.0
223 14 ▶ use Fcntl;
Subroutine BEGIN: called CC=1 SCAR=0.0
224 1 warn "Using MLDBM: $obj->{use_file}";
225 1 ▶ $obj->{neighbors} = tie %neighbors, 'MLDBM', $obj->{use_file} or die $!;
Branch: 1 branch
BranchTrueFalseTotal
$obj->{"neighbors"} = tie(%neighbors, "MLDBM", $obj->{"use_file"}) or die $! 0 1 1
226 #$obj->{neighbors} = \%neighbors;
227
228
229 }
230  
231 16 return $obj;
232  
233 }
234  
235  
236 =item load_from_dir DIR [, \&PARSE ]
237  
238 Load documents from a directory. Takes two arguments, a directory path
239 and an optional parsing subroutine. If the parsing subroutine is passed
240 an argument, it will use it to extract term tokens from the file.
241 By default, the file is split on whitespace and stripped of numbers and
242 punctuation.
243  
244 =cut
245  
246 {
247 14 my $parse_sub;
248  
249 0 ▶ sub load_from_dir {
Subroutine load_from_dir: not called CC=5 SCAR=34.0
Pod documented
250 0 my ( $class, $dir, $code ) = @_;
251  
252 0 ▶ croak "$dir is not a directory" unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 0 0
253  
254 0 require File::Find;
255 0 ▶ unless ( defined $code
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $code and ref $code and ref $code eq "CODE") 0 0 0
Condition0%0/6
defined $code and ref $code and ref $code eq "CODE"
!ll&&!rl&&r
000
defined $code and ref $code
!ll&&!rl&&r
000
MC/DC0%0/3
defined $code and ref $code and ref $code eq "CODE"
defined $code ref $code ref $code eq "CODE"
Truth table0%0/4
A and B and C
A= defined $codeB= ref $codeC= ref $code eq "CODE"
ABCresult
0XX0
10X0
1100
1111
256 and ref $code
257 and ref $code eq 'CODE' ) {
258 0 ▶ $code = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
259 0 my $text = shift;
260 0 $text =~ s/[^\w]/ /gs;
261 0 my @toks = split /\s+/m, $text;
262 0 return grep { length($_) > 1 } @toks;
263 0 };
264 }
265  
266 0 $parse_sub = $code;
267 0 my %docs;
268  
269 # Recursively open every file and provide the contents
270 # to whatever parsing subroutine we're using
271  
272 my $reader =
273  
274 0 ▶ sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
275 0 my ( $parse ) = @_;
276 0 ▶ return if /^\./;
Branch: 1 branch
BranchTrueFalseTotal
if /^\./ 0 0 0
277 0 ▶ return unless -f $_;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $_ 0 0 0
278 0 ▶ open my $fh, $_ or
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, $_ or croak("Could not open file $File::Find::name: $!") 0 0 0
279 croak "Could not open file $File::Find::name: $!";
280 0 local $/;
281 0 my $contents = <$fh>;
282 0 ▶ close $fh or croak "failed to close filehandle";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("failed to close filehandle") 0 0 0
283 0 my @words = $parse_sub->($contents);
284 0 $docs{ $File::Find::name } = \@words;
285 0 };
286  
287  
288 0 find( $reader , $dir );
289 0 my $self = __PACKAGE__->new();
290 0 $self->bulk_add( %docs );
291 0 return $self;
292 }
293 }
294  
295  
296  
297 =item load_from_tdm FILENAME
298  
299 Opens and loads a term-document matrix (TDM) file to initialize the graph.
300 The TDM encodes information about term-to-document links.
301 This is a legacy method mainly for the convenience of the module author.
302 For notes on the proper file format, see the README file.
303 =cut
304  
305 14 ▶sub load_from_tdm {
Subroutine load_from_tdm: called CC=3 SCAR=11.2
Pod documented
306 1 my ( $self, $file ) = @_;
307 1 ▶ croak "TDM file $file does not exist" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 0 1 1
308 1 ▶ return if $self->{'loaded'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"loaded"} 0 1 1
309 1 $self->_read_tdm( $file );
310 1 $self->{'loaded'} = 1;
311 1 $self->reweight_graph();
312 }
313  
314  
315 =item rename OLD, NEW
316  
317 Renames a document. Will return undef if the new name is already in use.
318  
319 =cut
320 0 ▶sub rename {
Subroutine rename: not called CC=6 SCAR=37.4
Pod documented
321  
322 0 my ( $self, $old, $new ) = @_;
323 0 ▶ croak "rename method needs two arguments" unless
Branch: 1 branch
BranchTrueFalseTotal
unless defined $old and defined $new 0 0 0
Condition0%0/3
defined $old and defined $new
!ll&&!rl&&r
000
MC/DC0%0/2
defined $old and defined $new
defined $old defined $new
Truth table0%0/3
A and B
A= defined $oldB= defined $new
ABresult
0X0
100
111
324 defined $old and defined $new;
325 croak "document $old not found" unless
326 0 ▶ exists $self->{neighbors}{ _nodeify('D', $old ) };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"neighbors"}{_nodeify("D", $old)} 0 0 0
327
328 0 my $bad = _nodeify( 'D', $old );
329 0 my $good = _nodeify( 'D', $new );
330
331 0 ▶ return if exists $self->{neighbors}{$good};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"neighbors"}{$good} 0 0 0
332
333 0 my $s = $self->{neighbors};
334 0 foreach my $n ( keys %{ $s->{$bad} } ) {
335 $s->{$good}{$n} =
336 $s->{$n}{$good} =
337 0 $s->{$bad}{$n};
338 0 delete $s->{$bad}{$n};
339 0 delete $s->{$n}{$bad};
340 }
341 0 delete $s->{$bad};
342 0 return 1;
343  
344 }
345  
346  
347  
348 =item retrieve FILENAME
349  
350 Loads a previously stored graph from disk, using Storable.
351  
352 =cut
353  
354 1 ▶sub retrieve {
Subroutine retrieve: called CC=3 SCAR=11.4
Pod documented
355 1 my ( $self, $file ) = @_;
356 1 ▶ croak "Must provide a filename to retrieve graph"
Branch: 1 branch
BranchTrueFalseTotal
unless $file 0 1 1
357 unless $file;
358 1 ▶ croak "'$file' is not a file" unless
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 0 1 1
359 -f $file;
360  
361 1 Storable::retrieve( $file );
362 }
363  
364  
365 =back
366  
367 =head1 ACCESSORS
368  
369 =over
370  
371 =item [get|set]_activate_threshold
372  
373 Accessor for node activation threshold value. This value determines how far
374 energy can spread in the graph. Lower it to increase the number of results.
375 Default is 1.
376  
377 =cut
378  
379 2 ▶sub get_activate_threshold { $_[0]->{'ACTIVATE_THRESHOLD'} }
Subroutine get_activate_threshold: called CC=1 SCAR=0.0
Pod undocumented
380 3 ▶sub set_activate_threshold {
Subroutine set_activate_threshold: called CC=3 SCAR=11.0
Pod undocumented
381 3 my ( $self, $threshold ) = @_;
382 3 ▶ croak "Can't set activate threshold to zero"
Branch: 1 branch
BranchTrueFalseTotal
unless $threshold 1 2 3
383 unless $threshold;
384 2 ▶ croak "Can't set activate threshold to negative value"
Branch: 1 branch
BranchTrueFalseTotal
unless $threshold > 0 1 1 2
385 unless $threshold > 0;
386 1 $self->{'ACTIVATE_THRESHOLD'} = $_[1];
387 }
388  
389  
390 =item [get|set]_auto_reweight
391  
392 Accessor for auto reweight flag. If true, edge weights will be recalculated
393 every time a document is added, updated or removed. This can significantly slow
394 down large graphs. On by default.
395  
396 =cut
397  
398 0 ▶sub get_auto_reweight{ $_[0]->{auto_reweight} }
Subroutine get_auto_reweight: not called CC=1 SCAR=6.9
Pod undocumented
399 0 ▶sub set_auto_reweight{ $_[0]->{auto_reweight} = $_[0]->[1]; }
Subroutine set_auto_reweight: not called CC=1 SCAR=6.9
Pod undocumented
400  
401  
402 =item [get|set]_collect_threshold
403  
404 Accessor for collection threshold value. This determines how much energy a
405 node must have to make it into the result set. Lower it to increase the
406 number of results. Default is 1.
407  
408 =cut
409  
410 2 ▶sub get_collect_threshold {
Subroutine get_collect_threshold: called CC=2 SCAR=7.6
Pod undocumented
411 return ( $_[0]->{'xs'} ?
412 $_[0]->{Graph}->collectionThreshold :
413 2 ▶ $_[0]->{'COLLECT_THRESHOLD'})
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'xs'} ? : 0 2 2
414 }
415  
416 2 ▶sub set_collect_threshold {
Subroutine set_collect_threshold: called CC=4 SCAR=13.9
Pod undocumented
417 2 my ( $self, $newval ) = @_;
418  
419 2 ▶ $newval ||=0;
Condition100%2/2
$newval ||= 0
l!l
11
MC/DC100%1/1
$newval ||= 0
$newval
Truth table100%2/2
A
A= $newval
Aresult
11
00
420  
421 $self->{Graph}->collectionThreshold( $newval )
422 2 ▶ if $self->{'xs'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"xs"} 0 2 2
423  
424 2 ▶ $self->{'COLLECT_THRESHOLD'} = $newval || 0;
Condition100%2/2
$newval || 0
l!l
11
MC/DC100%1/1
$newval || 0
$newval
Truth table100%2/2
A
A= $newval
Aresult
11
00
425 2 return 1;
426 }
427  
428 =item [get|set]_debug_mode LEVEL
429  
430 Turns debugging on or off. 1 is verbose, 2 is very verbose, 0 is off.
431  
432 =cut
433  
434 0 ▶sub get_debug_mode { $_[0]->{debug} }
Subroutine get_debug_mode: not called CC=1 SCAR=6.9
Pod undocumented
435 0 ▶sub set_debug_mode {
Subroutine set_debug_mode: not called CC=1 SCAR=6.9
Pod undocumented
436 0 my ( $self, $mode ) = @_;
437 0 $self->{'debug'} = $mode;
438 }
439  
440  
441  
442 =item [get|set]_initial_energy
443  
444 Accessor for initial energy value at the query node. This controls how
445 much energy gets poured into the graph at the start of the search.
446 Increase this value to get more results from your queries.
447  
448 =cut
449  
450 2 ▶sub get_initial_energy { $_[0]->{'START_ENERGY'} }
Subroutine get_initial_energy: called CC=1 SCAR=0.0
Pod undocumented
451 2 ▶sub set_initial_energy {
Subroutine set_initial_energy: called CC=3 SCAR=11.0
Pod undocumented
452 2 my ( $self, $start_energy ) = @_;
453 2 ▶ croak "Can't set initial energy to zero"
Branch: 1 branch
BranchTrueFalseTotal
unless $start_energy 0 2 2
454 unless $start_energy;
455 2 ▶ croak "Can't set initial energy to negative value"
Branch: 1 branch
BranchTrueFalseTotal
unless $start_energy > 0 1 1 2
456 unless $start_energy > 0;
457 1 $self->{'START_ENERGY'} = $start_energy ;
458 }
459  
460 =item [get|set]_max_depth LEVEL
461  
462 You can tell the graph to cut off searches after a certain distance from
463 the query node. This can speed up searches on very large graphs, and has
464 little adverse effect, especially if you are interested in just the first
465 few search results. Set this value to undef to restore the default (10^8).
466  
467 =cut
468  
469 3 ▶sub get_max_depth { $_[0]->{max_depth} }
Subroutine get_max_depth: called CC=1 SCAR=0.0
Pod undocumented
470 3 ▶sub set_max_depth { croak "Tried to set maximum depth to an undefined value"
Subroutine set_max_depth: called CC=3 SCAR=11.0
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[1] 1 2 3
471 unless defined $_[1];
472 2 ▶ $_[0]->{max_depth} = $_[1] || 100000000
Condition100%2/2
$_[1] || 100000000
l!l
11
MC/DC100%1/1
$_[1] || 100000000
$_[1]
Truth table100%2/2
A
A= $_[1]
Aresult
11
00
473 }
474  
475  
476  
477  
478 =back
479  
480 =head1 METHODS
481  
482 =over
483  
484 =item add DOC, WORDS
485  
486 Add a document to the search engine. Takes as arguments a unique doc
487 identifier and a reference to an array or hash of words in the
488 document.
489 For example:
490  
491 TITLE => { WORD1 => COUNT1, WORD2 => COUNT2 ... }
492  
493 or
494  
495 TITLE => [ WORD1, WORD2, WORD3 ]
496  
497 Use L<bulk_add> if you want to pass in a bunch of docs all at once.
498  
499 =cut
500  
501  
502 426 ▶sub add {
Subroutine add: called CC=13 SCAR=25.9
Pod documented
503  
504 426 my ( $self, $title, $words ) = @_;
505  
506  
507 426 ▶ croak "Please provide a word list" unless defined $words;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $words 0 426 426
508 426 ▶ croak "Word list is not a reference to an array or hash"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $words and ref $words eq "HASH" or ref $words eq "ARRAY" 0 426 426
Condition66%4/6
ref $words and ref $words eq "HASH" or ref $words eq "ARRAY"
l!l&&r!l&&!r
74190
ref $words and ref $words eq "HASH"
!ll&&!rl&&r
04197
MC/DC0%0/3
ref $words and ref $words eq "HASH" or ref $words eq "ARRAY"
ref $words ref $words eq "HASH" ref $words eq "ARRAY"
Truth table40%2/5
A and B or C
A= ref $wordsB= ref $words eq "HASH"C= ref $words eq "ARRAY"
ABCresult
11X1
0X11
1011
0X00
1000
509 unless ref $words and ref $words eq "HASH" or ref $words eq "ARRAY";
510  
511 426 ▶ croak "Please provide a document identifier" unless defined $title;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $title 0 426 426
512  
513 426 my $dnode = _nodeify( 'D', $title );
514 croak "Tried to add document with duplicate identifier: '$title'\n"
515 426 ▶ if exists $self->{neighbors}{$dnode};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"neighbors"}{$dnode} 1 425 426
516  
517 425 my @list;
518 425 ▶ if ( ref $words eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $words eq 'ARRAY') { } 419 6 425
519 419 @list = @{$words};
520 } else {
521 6 @list = keys %{$words};
522 }
523  
524 425 ▶ croak "Tried to add a document with no content" unless scalar @list;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @list 0 425 425
525  
526 425 my @edges;
527 425 foreach my $term ( @list ) {
528 13500 my $tnode = _nodeify( 'T', lc( $term ) );
529  
530 # Local weight for the document
531 13500 ▶ my $lcount = ( ref $words eq 'HASH' ? $words->{$term} : 1 );
Branch: 1 branch
BranchTrueFalseTotal
ref $words eq 'HASH' ? : 13 13487 13500
532  
533 # Update number of docs this word occurs in
534 13500 my $gcount = ++$self->{term_count}{lc( $term )};
535  
536 13500 my $final_weight = 1;
537 13500 push @edges, [ $dnode, $tnode, $final_weight, $lcount ];
538  
539 }
540 425 $self->{reweight_flag} = 1;
541 425 __normalize( \@edges );
542  
543  
544 =cut
545  
546 DEVELOPMENT
547  
548 if ( $self->{supersize} ) {
549 my $n = $self->{neighbors};
550 foreach my $e ( @edges ) {
551 #warn "adding edge $e->[0], $e->[1]\n";
552
553 $n->{$e->[0]} = {} unless exists $n->{$e->[0]};
554 $n->{$e->[1]} = {} unless exists $n->{$e->[1]};
555
556 my $tmp = $n->{$e->[0]};
557 $tmp->{$e->[1]} = join ',', $e->[2], $e->[3];
558 $tmp = $n->{$e->[1]};
559 $tmp->{$e->[0]} = join ',', $e->[2], $e->[3];
560 }
561 =cut
562  
563
564 # PURE PERL VERSION
565 #} else {
566 425 foreach my $e ( @edges ) {
567 13500 $self->{neighbors}{$e->[0]}{$e->[1]} = join ',', $e->[2], $e->[3];
568 13500 $self->{neighbors}{$e->[1]}{$e->[0]} = join ',', $e->[2], $e->[3];
569 }
570 #}
571
572
573 #print "Reweighting graph\n";
574 425 ▶ $self->reweight_graph() if $self->{auto_reweight};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"auto_reweight"} 250 175 425
575 425 return 1;
576  
577 }
578  
579  
580 =item add_file PATH [, name => NAME, parse => CODE]
581  
582 Adds a document from a file. By default, uses the PATH provided as the document
583 identifier, and parses the file by splitting on whitespace. If a fancier title,
584 or more elegant parsing behavior is desired, pass in named arguments as indicated.
585 NAME can be any string, CODE should be a reference to a subroutine that takes one
586 argument (the contents of the file) and returns an array of tokens, or a hash in the
587 form TOKEN => COUNT, or a reference to the same.
588  
589 =cut
590  
591 0 ▶sub add_file {
Subroutine add_file: not called CC=11 SCAR=48.8
Pod documented
592 0 my ( $self, $path, %params ) = @_;
593
594 0 ▶ croak "Invalid file '$path' provided to add_file method."
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and -f $path 0 0 0
Condition0%0/3
defined $path and -f $path
!ll&&!rl&&r
000
MC/DC0%0/2
defined $path and -f $path
defined $path -f $path
Truth table0%0/3
A and B
A= defined $pathB= -f $path
ABresult
0X0
100
111
595 unless defined $path and -f $path;
596
597 0 ▶ my $title = ( exists $params{name} ? $params{name} : $path );
Branch: 1 branch
BranchTrueFalseTotal
exists $params{'name'} ? : 0 0 0
598  
599 0 local $/;
600 0 ▶ open my $fh, $path or croak "Unable to open $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, $path or croak("Unable to open ${path}: $!") 0 0 0
601 0 my $content = <$fh>;
602
603 0 my $ref;
604
605 0 ▶ if ( exists $params{parse} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{'parse'}) { } 0 0 0
606 croak "code provided is not a reference" unless
607 0 ▶ ref $params{parse};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $params{"parse"} 0 0 0
608 croak "code provided is not a subroutine" unless
609 0 ▶ ref $params{parse} eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $params{"parse"} eq "CODE" 0 0 0
610
611 0 $ref = $params{parse}->( $content );
612 0 ▶ croak "did not get an appropriate reference back after parsing"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ref and ref $ref =~ /(HASH|ARRAY)/ 0 0 0
Condition0%0/3
ref $ref and ref $ref =~ /(HASH|ARRAY)/
!ll&&!rl&&r
000
MC/DC0%0/2
ref $ref and ref $ref =~ /(HASH|ARRAY)/
ref $ref ref $ref =~ /(HASH|ARRAY)/
Truth table0%0/3
A and B
A= ref $refB= ref $ref =~ /(HASH|ARRAY)/
ABresult
0X0
100
111
613 unless ref $ref and ref $ref =~ /(HASH|ARRAY)/;
614
615
616 } else {
617
618 0 ▶ my $code = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
619 0 my $txt = shift;
620 0 $txt =~ s/\W/ /g;
621 0 my @toks = split m/\s+/, $txt;
622 0 \@toks;
623 0 };
624 0 $ref = $code->($content);
625 }
626
627 0 ▶ return unless $ref;
Branch: 1 branch
BranchTrueFalseTotal
unless $ref 0 0 0
628 0 $self->add( $title, $ref );
629
630 }
631  
632 =item bulk_add DOCS
633  
634 Add documents to the graph in bulk. Takes as an argument a hash
635 whose keys are document identifiers, and values are references
636 to hashes in the form { WORD1 => COUNT, WORD2 => COUNT...}
637 This method is faster than adding in documents one by one if
638 you have auto_rebalance turned on.
639  
640 =cut
641  
642 3 ▶sub bulk_add {
Subroutine bulk_add: called CC=3 SCAR=11.0
Pod documented
643  
644 3 my ( $self, %incoming_docs ) = @_;
645  
646 # Disable graph rebalancing until we've added everything
647 {
648 3 local $self->{auto_reweight} = 0;
649  
650 3 foreach my $doc ( keys %incoming_docs ) {
651 6 $self->add( $doc, $incoming_docs{$doc});
652 }
653 }
654 2 ▶ $self->reweight_graph() if $self->{auto_reweight};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"auto_reweight"} 2 0 2
655 }
656  
657  
658 =item degree NODE
659  
660 Given a raw node, returns the degree (raw node means the node must
661 be prefixed with 'D:' or 'T:' depending on type )
662  
663 =cut
664  
665 5 ▶sub degree { scalar keys %{$_[0]->{neighbors}{$_[1]}} }
Subroutine degree: called CC=1 SCAR=0.0
Pod documented
666  
667  
668 =item delete DOC
669  
670 Remove a document from the graph. Takes a document identifier
671 as an argument. Returns 1 if successful, undef otherwise.
672  
673 =cut
674  
675 37 ▶sub delete {
Subroutine delete: called CC=11 SCAR=24.7
Pod documented
676  
677 37 my ( $self, $type, $name ) = @_;
678
679 37 ▶ croak "Must provide a node type to delete() method" unless defined $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 37 37
680 37 ▶ croak "Invalid type $type passed to delete method. Must be one of [TD]"
Branch: 1 branch
BranchTrueFalseTotal
unless $type =~ /^[TD]$/io 0 37 37
681 unless $type =~ /^[TD]$/io;
682 37 ▶ croak "Please provide a node name" unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 37 37
683
684 37 ▶ return unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 37 37
685 37 my $node = _nodeify( $type, $name);
686  
687 37 my $n = $self->{neighbors};
688 croak "Found a neighborless node $node"
689 37 ▶ unless exists $n->{$node};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $n->{$node} 0 37 37
690  
691 37 my @terms = keys %{ $n->{$node} };
692  
693 warn "found ", scalar @terms, " neighbors attached to $node\n"
694 37 ▶ if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 37 37
695 # Check to see if we have orphaned any terms
696 37 foreach my $t ( @terms ) {
697
698 1205 delete $n->{$node}{$t};
699 1205 delete $n->{$t}{$node};
700  
701 1205 ▶ if ( scalar keys %{ $n->{$t} } == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$$n{$t};} == 0) 976 229 1205
702 976 ▶ warn "\tdeleting orphaned node $t" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 976 976
703 976 my ( $subtype, $name ) = $t =~ /^(.):(.*)$/;
704 #$self->delete( $subtype, $name );
705 976 delete $n->{$t};
706 }
707 }
708  
709 37 delete $n->{$node};
710 37 $self->check_consistency();
711 37 $self->{reweight_flag} = 1;
712 37 ▶ $self->reweight_graph if $self->{auto_reweight};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"auto_reweight"} 37 0 37
713 37 1;
714 }
715  
716  
717  
718 =item has_doc DOC
719  
720 Returns true if the document with identifier DOC is in the collection
721  
722 =cut
723  
724 4 ▶sub has_doc {
Subroutine has_doc: called CC=3 SCAR=11.0
Pod documented
725 4 my ( $self, $doc ) = @_;
726 4 ▶ carp "Received undefined value for has_doc" unless defined $doc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $doc 0 4 4
727 4 my $node = _nodeify( 'D', $doc );
728 4 ▶ return exists $self->{neighbors}{$node} || undef;
Condition100%2/2
exists $self->{'neighbors'}{$node} || undef
l!l
22
MC/DC100%1/1
exists $self->{'neighbors'}{$node} || undef
exists $self->{'neighbors'}{$node}
Truth table100%2/2
A
A= exists $self->{'neighbors'}{$node}
Aresult
11
00
729 }
730  
731 =item has_term TERM
732  
733 Returns true if the term TERM is in the collection
734  
735 =cut
736  
737 4 ▶sub has_term {
Subroutine has_term: called CC=3 SCAR=11.0
Pod documented
738 4 my ( $self, $term ) = @_;
739 4 ▶ carp "Received undefined value for has_term" unless defined $term;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $term 0 4 4
740 4 my $node = _nodeify( 'T', $term );
741 4 ▶ return exists $self->{neighbors}{$node} || undef;
Condition100%2/2
exists $self->{'neighbors'}{$node} || undef
l!l
22
MC/DC100%1/1
exists $self->{'neighbors'}{$node} || undef
exists $self->{'neighbors'}{$node}
Truth table100%2/2
A
A= exists $self->{'neighbors'}{$node}
Aresult
11
00
742 }
743  
744  
745  
746 =item distance NODE1, NODE2, TYPE
747  
748 Calculates the distance between two nodes of the same type (D or T)
749 using the formula:
750  
751 distance = ...
752 =cut
753  
754 0 ▶sub distance {
Subroutine distance: not called CC=6 SCAR=37.4
Pod documented
755 0 my ( $self, $n1, $n2, $type ) = @_;
756 0 ▶ croak unless $type;
Branch: 1 branch
BranchTrueFalseTotal
unless $type 0 0 0
757 0 $type = lc( $type );
758 0 ▶ croak unless $type =~ /^[dt]$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $type =~ /^[dt]$/ 0 0 0
759 0 ▶ my $key = ( $type eq 't' ? 'terms' : 'documents' );
Branch: 1 branch
BranchTrueFalseTotal
$type eq 't' ? : 0 0 0
760 0 my @shared = $self->intersection( $key => [ $n1, $n2 ] );
761 0 ▶ return 0 unless @shared;
Branch: 1 branch
BranchTrueFalseTotal
unless @shared 0 0 0
762 #warn "Found ", scalar @shared, " nodes shared between $n1 and $n2\n";
763
764 0 my $node1 = _nodeify( $type, $n1 );
765 0 my $node2 = _nodeify( $type, $n2 );
766 # formula is w(t1,d1)/deg(d1) + w(t1,d2)/deg(d2) ... ) /deg( t1 )
767
768 #warn "Calculating distance\n";
769 0 my $sum1 = 0;
770 0 my $sum2 = 0;
771 0 foreach my $next ( @shared ) {
772 0 my ( undef, $lcount1) = split m/,/, $self->{neighbors}{$node1}{$next};
773 0 my ( undef, $lcount2) = split m/,/, $self->{neighbors}{$node2}{$next};
774  
775 0 my $degree = $self->degree( $next );
776 #warn "\t degree of $next is $degree\n";
777 0 my $elem1 = $lcount1 / $degree;
778 0 $sum1 += $elem1;
779 0 my $elem2 = $lcount2 / $degree;
780 0 $sum2 += $elem2;
781 }
782 #warn "sum is $sum1, $sum2\n";
783 0 my $final = ($sum1 / $self->degree( $node1 )) + ( $sum2 / $self->degree( $node2 ));
784 #warn "final is $final\n";
785 0 return $final;
786
787
788 }
789  
790 =item distance_matrix TYPE LIMIT
791  
792 Used for clustering using linear local embedding. Produces a similarity matrix
793 in a format I'm too tired to document right now. LIMIT is the maximum number
794 of neighbors to keep for each node.
795  
796 =cut
797  
798 0 ▶sub distance_matrix {
Subroutine distance_matrix: not called CC=9 SCAR=45.0
Pod documented
799 0 my ( $self, $type, $limit ) = @_;
800 0 ▶ croak "Must provide type argument to distance_matrix()"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 0 0
801 unless defined $type;
802 0 ▶ croak "must provide limit" unless $limit;
Branch: 1 branch
BranchTrueFalseTotal
unless $limit 0 0 0
803 0 my @nodes;
804 0 ▶ if ( lc( $type ) eq 'd' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (lc $type eq 'd') { } 0 0 0
elsif (lc $type eq 't') { } 0 0 0
805 0 @nodes = $self->doc_list();
806 } elsif ( lc( $type ) eq 't' ) {
807 0 @nodes = $self->term_list();
808 } else {
809 0 croak "Unsupported type $type";
810 }
811
812 0 my @ret;
813 0 my $count = 0;
814 0 foreach my $from ( @nodes ) {
815 0 warn $from, " - $count\n";
816 0 $count++;
817 0 my $index = -1;
818 0 my @found;
819 0 foreach my $to ( @nodes ) {
820 0 $index++;
821 0 ▶ next if $from eq $to;
Branch: 1 branch
BranchTrueFalseTotal
if $from eq $to 0 0 0
822 0 my $dist = $self->distance( $from, $to, $type );
823 0 ▶ push @found, [ $index, $dist ] if $dist;
Branch: 1 branch
BranchTrueFalseTotal
if $dist 0 0 0
824 #print( $index++, ' ', $dist, " " ) if $dist;
825 }
826 0 my @sorted = sort { $b->[1] <=> $a->[1] } @found;
827 0 my @final = splice ( @sorted, 0, $limit );
828 0 push @ret, join " ", ( map { join ' ', $_->[0], substr($_->[1], 0, 7) }
829 0 sort { $a->[0] <=> $b->[0] }
830 @final), "\n";
831 #print "\n";
832 }
833 0 return join "\n", @ret;
834  
835 }
836  
837 =item intersection @NODES
838  
839 Returns a list of neighbor nodes that all the given nodes share in common
840  
841 =cut
842  
843 2 ▶sub intersection {
Subroutine intersection: called CC=5 SCAR=16.1
Pod documented
844 2 my ( $self, %nodes ) = @_;
845 2 my @nodes;
846 2 ▶ if ( exists $nodes{documents} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $nodes{"documents"}) 1 1 2
847 1 push @nodes, map { _nodeify( 'D', $_ ) } @{ $nodes{documents}};
848 }
849 2 ▶ if ( exists $nodes{terms} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $nodes{"terms"}) 1 1 2
850 1 push @nodes, map { _nodeify( 'T', $_ ) } @{ $nodes{terms}};
851 }
852
853 2 my %seen;
854 2 foreach my $n ( @nodes ) {
855 4 my @neighbors = $self->_neighbors( $n );
856 4 $seen{ $_ }++ foreach @neighbors;
857 }
858 4 return map { s/^[DT]://; $_ }
859 2 grep { $seen{$_} == scalar @nodes }
860 keys %seen;
861 }
862  
863 =item raw_search @NODES
864  
865 Given a list of nodes, returns a hash of nearest nodes with relevance values,
866 in the format NODE => RELEVANCE, for all nodes above the threshold value.
867 (You probably want one of L<search>, L<find_similar>, or L<mixed_search> instead).
868  
869 =cut
870  
871 21 ▶sub raw_search {
Subroutine raw_search: called CC=2 SCAR=6.9
Pod documented
872 21 my ( $self, @query ) = @_;
873  
874 21 $self->_clear();
875 21 foreach ( @query ) {
876 26 $self->_energize( $_, $self->{'START_ENERGY'});
877 }
878 21 my $results_ref = $self->_collect();
879  
880  
881 21 return $results_ref;
882 }
883  
884  
885  
886  
887 =item reweight_graph
888  
889 Iterates through the graph, calculating edge weights and normalizing
890 around nodes. This method is automatically called every time a
891 document is added, removed, or updated, unless you turn the option
892 off with auto_reweight(0). When adding a lot of docs, this can be
893 time consuming, so either set auto_reweight to off or use the
894 L<bulk_add> method to add lots of docs at once
895  
896 =cut
897  
898 297 ▶sub reweight_graph {
Subroutine reweight_graph: called CC=8 SCAR=20.9
Pod documented
899 297 my ( $self ) = @_;
900  
901 297 my $n = $self->{neighbors}; #shortcut
902 297 my $doc_count = $self->doc_count();
903 #print "Renormalizing for doc count $doc_count\n" if $self->{debug};
904 297 foreach my $node ( keys %{$n} ) {
905  
906 152521 ▶ next unless $node =~ /^D:/o;
Branch: 1 branch
BranchTrueFalseTotal
unless $node =~ /^D:/o 147126 5395 152521
907 5395 ▶ warn "reweighting at node $node\n" if $self->{debug} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} > 1 0 5395 5395
908 5395 my @terms = keys %{ $n->{$node} };
909 5395 my @edges;
910 5395 foreach my $t ( @terms ) {
911  
912 186166 my $pair = $n->{$node}{$t};
913 186166 my ( undef, $lcount ) = split /,/, $pair;
914 186166 ( my $term = $t ) =~ s/^T://;
915 186166 ▶ croak "did not receive a local count" unless $lcount;
Branch: 1 branch
BranchTrueFalseTotal
unless $lcount 0 186166 186166
916 186166 my $weight;
917 186166 ▶ if ( $self->{use_global_weights} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'use_global_weights'}) { } 186166 0 186166
918  
919 186166 my $gweight = log( $doc_count / $self->doc_count( $term ) ) + 1;
920 186166 my $lweight = log( $lcount ) + 1;
921 186166 $weight = ( $gweight * $lweight );
922
923 } else {
924  
925 0 $weight = log( $lcount ) + 1;
926 }
927 186166 push @edges, [ $node, $t, $weight, $lcount ];
928 }
929  
930 5395 __normalize( \@edges );
931  
932 5395 foreach my $e ( @edges ) {
933 186166 my $pair = join ',', $e->[2], $e->[3];
934 186166 $n->{$node}{$e->[1]} = $n->{$e->[1]}{$node} = $pair;
935 }
936 }
937 297 $self->{reweight_flag} = 0;
938 297 return 1;
939 }
940  
941  
942  
943  
944 =item update ID, WORDS
945  
946 Given a document identifier and a word list, updates the information for
947 that document in the graph. Returns the number of changes made
948  
949 =cut
950  
951 2 ▶sub update {
Subroutine update: called CC=16 SCAR=30.1
Pod documented
952  
953 2 my ( $self, $id, $words ) = @_;
954  
955 2 ▶ croak "update not implemented in XS" if $self->{xs};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"xs"} 0 2 2
956 2 ▶ croak "Must provide a document identifier to update_document" unless defined $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 0 2 2
957 2 my $dnode = _nodeify( 'D', $id );
958  
959 2 ▶ return unless exists $self->{neighbors}{$dnode};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"neighbors"}{$dnode} 1 1 2
960 1 ▶ croak "must provide a word list "
Branch: 1 branch
BranchTrueFalseTotal
unless defined $words and ref $words and ref $words eq "HASH" || ref $words eq "ARRAY" 0 1 1
Condition33%3/9
defined $words and ref $words and ref $words eq "HASH" || ref $words eq "ARRAY"
!ll&&!rl&&r
001
defined $words and ref $words
!ll&&!rl&&r
001
ref $words eq "HASH" or ref $words eq "ARRAY"
l!l&&r!l&&!r
010
MC/DC0%0/4
defined $words and ref $words and ref $words eq "HASH" || ref $words eq "ARRAY"
defined $words ref $words ref $words eq "HASH" ref $words eq "ARRAY"
Truth table20%1/5
A and B and C or D
A= defined $wordsB= ref $wordsC= ref $words eq "HASH"D= ref $words eq "ARRAY"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
961 unless defined $words and
962 ref $words and
963 ( ref $words eq 'HASH' or
964 ref $words eq 'ARRAY' );
965  
966 1 my $n = $self->{neighbors}{$dnode};
967
968 # Get the current word list
969 1 my @terms = keys %{ $n };
970  
971 1 ▶ if ( ref $words eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $words eq "ARRAY") 1 0 1
972 1 my %words;
973 1 $words{$_}++ foreach @$words;
974 1 $words = \%words;
975 }
976  
977 1 local $self->{auto_reweight} = 0;
978  
979 1 my $must_reweight = 0;
980 1 my %seen;
981  
982 1 foreach my $term ( keys %{$words} ) {
983  
984 4 my $t = _nodeify( 'T', $term );
985  
986 4 ▶ if ( exists $n->{$t} ){
Branch: 1 branch
BranchTrueFalseTotal
if (exists $n->{$t}) { } 3 1 4
987  
988 # Update the local count, if necessary
989 3 my $curr_val = $n->{$t};
990 3 my ( undef, $loc ) = split m/,/, $curr_val;
991  
992 3 ▶ unless ( $loc == $words->{$term} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($loc == $words->{$term}) 0 3 3
993 0 $n->{$t} = join ',', 1, $words->{$term};
994 0 $must_reweight++;
995 }
996 }
997  
998 else {
999  
1000 $n->{$t} =
1001 $self->{neighbors}{$t}{$dnode} =
1002 1 join ',', 1, $words->{$term};
1003 1 $must_reweight++;
1004 }
1005  
1006 4 $seen{$t}++;
1007 }
1008  
1009 # Check for deleted words
1010 1 foreach my $t ( @terms ) {
1011 $must_reweight++
1012 3 ▶ unless exists $seen{$t};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $seen{$t} 0 3 3
1013 }
1014  
1015 1 ▶ $self->reweight_graph() if
Branch: 1 branch
BranchTrueFalseTotal
if $must_reweight 1 0 1
1016 $must_reweight;
1017  
1018 1 return $must_reweight;
1019  
1020 }
1021  
1022  
1023 =item doc_count [TERM]
1024  
1025 Returns a count of all documents that TERM occurs in.
1026 If no argument is provided, returns a document count
1027 for the entire collection.
1028  
1029 =cut
1030  
1031 186498 ▶sub doc_count {
Subroutine doc_count: called CC=4 SCAR=13.9
Pod documented
1032 186498 my ( $self, $term ) = @_;
1033 186498 ▶ if ( defined $term ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $term) { } 186189 309 186498
1034 186189 ▶ $term = _nodeify( 'T', $term ) unless $term =~ /^T:/;
Branch: 1 branch
BranchTrueFalseTotal
unless $term =~ /^T:/ 186189 0 186189
1035 186189 my $node = $self->{neighbors}{$term};
1036 186189 ▶ return 0 unless defined $node;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node 3 186186 186189
1037 186186 return scalar keys %{$node};
1038 } else {
1039 return scalar grep /D:/,
1040 309 keys %{ $self->{'neighbors'} };
1041 }
1042 }
1043  
1044  
1045 =item doc_list [TERM]
1046  
1047 Returns a sorted list of document identifiers that contain
1048 TERM, in ASCII-betical order. If no argument is given,
1049 returns a sorted document list for the whole collection.
1050  
1051 =cut
1052  
1053 4 ▶sub doc_list {
Subroutine doc_list: called CC=4 SCAR=15.0
Pod documented
1054 4 my ( $self, $term ) = @_;
1055 4 my $t;
1056 4 ▶ if ( defined $term and $term !~ /T:/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $term and not $term =~ /T:/) 0 4 4
Condition33%1/3
defined $term and not $term =~ /T:/
!ll&&!rl&&r
400
MC/DC0%0/2
defined $term and not $term =~ /T:/
defined $term not $term =~ /T:/
Truth table33%1/3
A and not(B)
A= defined $termB= not $term =~ /T:/
ABresult
0X0
100
111
1057 0 $t = _nodeify( 'T', $term );
1058 }
1059 my $hash = ( defined $term ?
1060 $self->{neighbors}{$t} :
1061 4 ▶ $self->{neighbors} );
Branch: 1 branch
BranchTrueFalseTotal
defined $term ? : 0 4 4
1062  
1063 136 sort map { s/^D://o; $_ }
1064 4 grep /^D:/, keys %{ $hash };
1065 }
1066  
1067  
1068 0 ▶sub dump {
Subroutine dump: not called CC=2 SCAR=17.9
Pod undocumented
1069 0 my ( $self ) = @_;
1070 0 my @docs = $self->doc_list();
1071  
1072 0 foreach my $d ( @docs ) {
1073 0 print $self->dump_node( $d );
1074 }
1075 }
1076  
1077 =item dump_node NODE
1078  
1079 Lists all of the neighbors of a node, together with edge
1080 weights connecting to them
1081  
1082 =cut
1083  
1084 2 ▶sub dump_node {
Subroutine dump_node: called CC=2 SCAR=6.9
Pod documented
1085 2 my ( $self, $node ) = @_;
1086  
1087 2 my @lines;
1088 2 push @lines, join "\t", "COUNT", "WEIGHT", "NEIGHBOR";
1089  
1090 2 foreach my $n ( keys %{ $self->{neighbors}{$node} } ) {
1091 116 my $v = $self->{neighbors}{$node}{$n};
1092 116 my ( $weight, $count ) = split /,/, $v;
1093 116 push @lines, join "\t", $count, substr( $weight, 0, 8 ), $n;
1094 }
1095 2 return @lines;
1096 }
1097  
1098  
1099  
1100 =item dump_tdm [FILE]
1101  
1102 Dumps internal state in term-document matrix (TDM) format, which looks
1103 like this:
1104  
1105 A B C B C B C
1106 A B C B C B C
1107 A B C B C B C
1108  
1109 Where each row represents a document, A is the number of terms in the
1110 document, B is the term node and C is the edge weight between the doc
1111 node and B. Mostly used as a legacy format by the module author.
1112 Doc and term nodes are printed in ASCII-betical sorted order, zero-based
1113 indexing. Up to you to keep track of the ID => title mappings, neener-neener!
1114 Use doc_list and term_list to get an equivalently sorted list
1115  
1116 =cut
1117  
1118 0 ▶sub dump_tdm {
Subroutine dump_tdm: not called CC=6 SCAR=37.4
Pod documented
1119 0 my ( $self, $file ) = @_;
1120  
1121 0 my $counter = 0;
1122 0 my %lookup;
1123 0 $lookup{$_} = $counter++ foreach $self->term_list;
1124  
1125 0 my @docs = $self->doc_list;
1126  
1127 0 my $fh;
1128 0 ▶ if ( defined $file ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file) { } 0 0 0
1129 0 ▶ open $fh, "> $file" or croak
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "> $file" or croak("Could not open TDM output file: $!") 0 0 0
1130 "Could not open TDM output file: $!";
1131 } else {
1132 0 *fh = *STDOUT;
1133 }
1134 0 foreach my $doc ( @docs ) {
1135 0 my $n = $self->{neighbors}{$doc};
1136  
1137 0 my $row_count = scalar keys %{$n};
1138 0 print $fh $row_count;
1139  
1140 0 foreach my $t ( sort keys %{$doc} ) {
1141 0 my $index = $lookup{$t};
1142 0 my ( $weight, undef ) = split m/,/, $n->{$t};
1143 0 print $fh ' ', $index, ' ', $weight;
1144 }
1145 0 print $fh "\n";
1146 }
1147 }
1148  
1149  
1150  
1151 =item near_neighbors [NODE]
1152  
1153 Returns a list of neighbor nodes of the same type (doc/doc, or term/term) two
1154 hops away.
1155  
1156 =cut
1157  
1158 0 ▶sub near_neighbors {
Subroutine near_neighbors: not called CC=3 SCAR=24.8
Pod documented
1159 0 my ( $self, $name, $type ) = @_;
1160
1161 0 my $node = _nodeify( $type, $name );
1162
1163 0 my $n = $self->{neighbors}{$node};
1164
1165 0 my %found;
1166 0 foreach my $next ( keys %{$n} ) {
1167 0 foreach my $mynext ( keys %{ $self->{neighbors}{$next} }){
1168 0 $found{$mynext}++;
1169 }
1170 }
1171 0 delete $found{$node};
1172 0 return keys %found;
1173 }
1174  
1175  
1176 =item term_count [DOC]
1177  
1178 Returns the number of unique terms in a document or,
1179 if no document is specified, in the entire collection.
1180  
1181 =cut
1182  
1183 10 ▶sub term_count {
Subroutine term_count: called CC=3 SCAR=15.7
Pod documented
1184 10 my ( $self, $doc ) = @_;
1185 10 ▶ if ( defined $doc ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $doc) { } 0 10 10
1186 0 my $node = $self->{neighbors}{ _nodeify( 'D', $doc) };
1187 0 ▶ return 0 unless defined $node;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node 0 0 0
1188 0 return scalar keys %{$node};
1189 } else {
1190 return scalar grep /T:/,
1191 10 keys %{ $self->{neighbors} };
1192 }
1193 }
1194  
1195  
1196 =item term_list [DOC]
1197  
1198 Returns a sorted list of unique terms appearing in the document
1199 with identifier DOC, in ASCII-betical order. If no argument is
1200 given, returns a sorted term list for the whole collection.
1201  
1202 =cut
1203  
1204 4 ▶sub term_list {
Subroutine term_list: called CC=2 SCAR=6.9
Pod documented
1205 4 my ( $self, $doc ) = @_;
1206  
1207 my $node = ( defined $doc ?
1208 $self->{neighbors}{ _nodeify( 'D', $doc) } :
1209 $self->{neighbors}
1210 4 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
defined $doc ? : 1 3 4
1211  
1212 1791 sort map { s/^T://o; $_ }
1213 4 grep /^T:/, keys %{ $node };
1214 }
1215  
1216  
1217  
1218 =item word_count [TERM]
1219  
1220 Returns the total occurence count for a term, or if no argument is given,
1221 a word count for the entire collection. The word count is always greater than
1222 or equal to the term count.
1223  
1224 =cut
1225  
1226 4 ▶sub word_count {
Subroutine word_count: called CC=5 SCAR=16.1
Pod documented
1227  
1228 4 my ( $self, $term ) = @_;
1229  
1230 4 my $n = $self->{neighbors}; # shortcut
1231  
1232 4 my $count = 0;
1233 4 my @terms;
1234 4 ▶ if ( defined $term ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $term) { } 3 1 4
1235 3 push @terms, $term;
1236 } else {
1237 1 @terms = $self->term_list();
1238 }
1239  
1240 4 foreach my $term (@terms ) {
1241 879 ▶ $term = _nodeify( 'T', $term) unless $term =~/^T:/o;
Branch: 1 branch
BranchTrueFalseTotal
unless $term =~ /^T:/o 879 0 879
1242 879 foreach my $doc ( keys %{ $n->{$term} } ) {
1243 1092 ( undef, my $lcount ) = split /,/, $n->{$term}{$doc};
1244 1092 $count += $lcount;
1245 }
1246 }
1247  
1248 4 return $count;
1249 }
1250  
1251  
1252  
1253  
1254  
1255 =item search @QUERY
1256  
1257 Searches the graph for all of the words in @QUERY. Use find_similar if you
1258 want to do a document similarity instead, or mixed_search if you want
1259 to search on any combination of words and documents. Returns a pair of hashrefs:
1260 the first a reference to a hash of docs and relevance values, the second to
1261 a hash of words and relevance values.
1262  
1263 =cut
1264  
1265 14 ▶sub search {
Subroutine search: called CC=1 SCAR=0.0
Pod documented
1266 14 my ( $self, @query ) = @_;
1267 14 my @nodes = _nodeify( 'T', @query );
1268 14 my $results = $self->raw_search( @nodes );
1269 14 my ($docs, $words) = _partition( $results );
1270 14 return ( $docs, $words);
1271 }
1272  
1273  
1274  
1275 =item simple_search QUERY
1276  
1277 This is the DWIM method - takes a query string as its argument, and returns an array
1278 of documents, sorted by relevance.
1279  
1280 =cut
1281  
1282 1 ▶sub simple_search {
Subroutine simple_search: called CC=1 SCAR=0.0
Pod documented
1283 1 my ( $self, $query ) = @_;
1284 1 my @words = map { s/\W+//g; lc($_) }
1285 split m/\s+/, $query;
1286 1 my @nodes = _nodeify( 'T', @words );
1287 1 my $results = $self->raw_search( @nodes );
1288 1 my ($docs, $words) = _partition( $results );
1289 1 my @sorted_docs = sort { $docs->{$b} <=> $docs->{$a} } keys %{$docs};
1290 1 return @sorted_docs;
1291 }
1292  
1293 =item find_by_title @TITLES
1294  
1295 Given a list of patterns, searches for documents with matching titles
1296  
1297 =cut
1298  
1299 3 ▶sub find_by_title {
Subroutine find_by_title: called CC=3 SCAR=11.0
Pod documented
1300 3 my ( $self, @titles ) = @_;
1301 3 my @found;
1302 3 my @docs = $self->doc_list();
1303 3 my $pattern = join '|', @titles;
1304 3 my $match_me = qr/$pattern/i;
1305 #warn $match_me, "\n";
1306 3 foreach my $d ( @docs ) {
1307 # warn $d, "\n";
1308 102 ▶ push @found, $d if $d =~ $match_me;
Branch: 1 branch
BranchTrueFalseTotal
if $d =~ /$match_me/ 13 89 102
1309 }
1310 3 return @found;
1311 }
1312  
1313  
1314 =item find_similar @DOCS
1315  
1316 Given an array of document identifiers, performs a similarity search
1317 and returns a pair of hashrefs. First hashref is to a hash of docs and relevance
1318 values, second is to a hash of words and relevance values.
1319  
1320 =cut
1321  
1322 4 ▶sub find_similar {
Subroutine find_similar: called CC=1 SCAR=0.0
Pod documented
1323 4 my ( $self, @docs ) = @_;
1324 4 my @nodes = _nodeify( 'D', @docs );
1325 4 my $results = $self->raw_search( @nodes );
1326 4 my ($docs, $words) = _partition( $results );
1327 4 return ( $docs, $words);
1328 }
1329  
1330  
1331 =item merge TYPE, GOOD, @BAD
1332  
1333 Combine all the nodes in @BAD into the node with identifier GOOD.
1334 First argument must be one of 'T' or 'D' to indicate term or
1335 document nodes. Used to combine synonyms in the graph.
1336  
1337 =cut
1338  
1339 2 ▶sub merge {
Subroutine merge: called CC=8 SCAR=20.9
Pod documented
1340 2 my ( $self, $type, $good, @bad ) = @_;
1341 2 ▶ croak "must provide a type argument to merge"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 2 2
1342 unless defined $type;
1343 2 ▶ croak "Invalid type argument $type to merge [must be one of (D,T)]"
Branch: 1 branch
BranchTrueFalseTotal
unless $type =~ /^[DT]/io 0 2 2
1344 unless $type =~ /^[DT]/io;
1345
1346 2 my $target = _nodeify( $type, $good );
1347 2 my @sources = _nodeify( $type, @bad );
1348
1349 2 my $tnode = $self->{neighbors}{$target};
1350
1351  
1352 2 foreach my $bad_node ( @sources ) {
1353 #print "Examining $bad_node\n";
1354 2 ▶ next if $bad_node eq $target;
Branch: 1 branch
BranchTrueFalseTotal
if $bad_node eq $target 0 2 2
1355 2 my %neighbors = %{$self->{neighbors}{$bad_node}};
1356
1357 2 foreach my $n ( keys %neighbors ) {
1358
1359 #print "\t $target ($bad_node) neighbor $n\n";
1360 14 ▶ if ( exists $self->{neighbors}{$target}{$n} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{'neighbors'}{$target}{$n}) { } 5 9 14
1361 #print "\t\t$n has link to $bad_node\n";
1362 # combine the local counts for the term members of the edge
1363 5 my $curr_val = $tnode->{$n};
1364 5 my $aug_val = $self->{neighbors}{$bad_node}{$n};
1365 5 my ($w1, $c1) = split m/,/, $curr_val;
1366 5 my ($w2, $c2) = split m/,/, $aug_val;
1367 5 my $new_count = $c1 + $c2;
1368 5 $curr_val =~ s/,\d+$/,$new_count/;
1369 5 $tnode->{$n} = $curr_val;
1370
1371
1372 } else {
1373
1374 die "sanity check failed for existence test"
1375 9 ▶ if exists $self->{neighbors}{$target}{$n};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"neighbors"}{$target}{$n} 0 9 9
1376
1377 9 my $val = $self->{neighbors}{$bad_node}{$n};
1378
1379 #print "\tno existing link -- reassigning $target -- $n\n";
1380 # reassign the current value of this edge
1381
1382 9 $self->{neighbors}{$n}{$target} = $val;
1383 9 $self->{neighbors}{$target}{$n} = $val;
1384 }
1385
1386 14 delete $self->{neighbors}{$bad_node}{$n};
1387 14 delete $self->{neighbors}{$n}{$bad_node};
1388 }
1389 2 delete $self->{neighbors}{$bad_node};
1390 }
1391 }
1392  
1393 =item mixed_search @DOCS
1394  
1395 Given a hashref in the form:
1396 { docs => [ 'Title 1', 'Title 2' ],
1397 terms => ['buffalo', 'fox' ], }
1398 }
1399 Runs a combined search on the terms and documents provided, and
1400 returns a pair of hashrefs. The first hashref is to a hash of docs
1401 and relevance values, second is to a hash of words and relevance values.
1402  
1403 =cut
1404  
1405 1 ▶sub mixed_search {
Subroutine mixed_search: called CC=6 SCAR=19.5
Pod documented
1406 1 my ( $self, $incoming ) = @_;
1407  
1408 1 ▶ croak "must provide hash ref to mixed_search method"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $incoming and ref $incoming and ref $incoming eq "HASH" 0 1 1
Condition33%2/6
defined $incoming and ref $incoming and ref $incoming eq "HASH"
!ll&&!rl&&r
001
defined $incoming and ref $incoming
!ll&&!rl&&r
001
MC/DC0%0/3
defined $incoming and ref $incoming and ref $incoming eq "HASH"
defined $incoming ref $incoming ref $incoming eq "HASH"
Truth table25%1/4
A and B and C
A= defined $incomingB= ref $incomingC= ref $incoming eq "HASH"
ABCresult
0XX0
10X0
1100
1111
1409 unless defined $incoming &&
1410 ref( $incoming ) &&
1411 ref( $incoming ) eq 'HASH';
1412  
1413 1 ▶ my $tref = $incoming->{'terms'} || [];
Condition50%1/2
$incoming->{'terms'} || []
l!l
10
MC/DC0%0/1
$incoming->{'terms'} || []
$incoming->{'terms'}
Truth table50%1/2
A
A= $incoming->{'terms'}
Aresult
11
00
1414 1 ▶ my $dref = $incoming->{'docs'} || [];
Condition50%1/2
$incoming->{'docs'} || []
l!l
10
MC/DC0%0/1
$incoming->{'docs'} || []
$incoming->{'docs'}
Truth table50%1/2
A
A= $incoming->{'docs'}
Aresult
11
00
1415  
1416 1 my @dnodes = _nodeify( 'D', @{$dref} );
1417 1 my @tnodes = _nodeify( 'T', @{$tref} );
1418  
1419 1 my $results = $self->raw_search( @dnodes, @tnodes );
1420 1 my ($docs, $words) = _partition( $results );
1421 1 return ( $docs, $words);
1422 }
1423  
1424  
1425 =item store FILENAME
1426  
1427 Stores the object to a file for later use. Not compatible (yet)
1428 with compiled XS version, which will give a fatal error.
1429  
1430 =cut
1431  
1432 1 ▶sub store {
Subroutine store: called CC=2 SCAR=7.6
Pod documented
1433 1 my ( $self, @args ) = @_;
1434 1 ▶ if ( $self->{'xs'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'xs'}) { } 0 1 1
1435 0 croak "Cannot store object when running in XS mode.";
1436 } else {
1437 1 $self->SUPER::nstore(@args);
1438 }
1439 }
1440  
1441  
1442 # Partition - internal method.
1443 # Takes a result set and splits it into two hashrefs - one for
1444 # words and one for documents
1445  
1446 20 ▶sub _partition {
Subroutine _partition: called CC=3 SCAR=11.0
1447 20 my ( $e ) = @_;
1448 20 my ( $docs, $words );
1449 20 foreach my $k ( sort { $e->{$b} <=> $e->{$a} }
1450 20 keys %{ $e } ) {
1451  
1452 270 (my $name = $k ) =~ s/^[DT]://o;
1453 $k =~ /^D:/ ?
1454 $docs->{$name} = $e->{$k} :
1455 270 ▶ $words->{$name} = $e->{$k} ;
Branch: 1 branch
BranchTrueFalseTotal
$k =~ /^D:/ ? : 46 224 270
1456 }
1457 20 return ( $docs, $words );
1458 }
1459  
1460 # return a list of all neighbor nodes
1461 4 ▶sub _neighbors {
Subroutine _neighbors: called CC=2 SCAR=7.0
1462 4 my ( $self, $node ) = @_;
1463 4 ▶ return unless exists $self->{neighbors}{$node};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"neighbors"}{$node} 0 4 4
1464 4 return keys %{ $self->{neighbors}{$node} };
1465 }
1466  
1467  
1468 201075 ▶sub _nodeify {
Subroutine _nodeify: called CC=3 SCAR=11.0
1469 201075 my ( $prefix, @list ) = @_;
1470 201075 my @nodes;
1471 201075 foreach my $item ( @list ) {
1472 201079 push @nodes, uc($prefix).':'.$item;
1473 }
1474 201075 ▶ ( wantarray ? @nodes : $nodes[0] );
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 27 201048 201075
1475 }
1476  
1477  
1478  
1479 1 ▶sub _read_tdm {
Subroutine _read_tdm: called CC=12 SCAR=30.8
1480 1 my ( $self, $file ) = @_;
1481 1 ▶ print "Loading TDM...\n" if $self->{'debug'} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} > 1 0 1 1
1482  
1483 1 ▶ croak "File does not exist" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 0 1 1
1484 1 ▶ open my $fh, $file or croak "Could not open $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, $file or croak("Could not open ${file}: $!") 1 0 1
1485 1 for ( 1..4 ){
1486 4 my $skip = <$fh>;
1487 }
1488 1 my %neighbors;
1489 1 my $doc = 0;
1490  
1491  
1492 ######### XS VERSION ##############
1493 1 ▶ if ( $self->{'xs'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'xs'}) { } 0 1 1
1494  
1495 0 my $map = $self->{'node_map'}; # shortcut alias
1496 0 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 0 0 0
1497 0 chomp;
1498 0 my $dindex = $self->_add_node( "D:$doc", 2 );
1499 #warn "Added node $doc\n";
1500 0 my ( $count, %vals ) = split;
1501 0 ▶ while ( my ( $term, $edge ) = each %vals ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %vals) 0 0 0
1502 0 $self->{'term_count'}{$term}++;
1503 0 my $tnode = "T:$term";
1504  
1505 my $tindex = ( defined $map->{$tnode} ?
1506 0 ▶ $map->{$tnode} :
Branch: 1 branch
BranchTrueFalseTotal
defined $map->{$tnode} ? : 0 0 0
1507 $self->_add_node( $tnode, 1 )
1508 );
1509 0 $self->{Graph}->set_edge( $dindex, $tindex, $edge );
1510 }
1511 0 $doc++;
1512 }
1513  
1514 ####### PURE PERL VERSION ##########
1515 } else {
1516 1 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 177 1 178
1517 177 chomp;
1518 177 my $dnode = "D:$doc";
1519 177 my ( $count, %vals ) = split;
1520 177 ▶ while ( my ( $term, $edge ) = each %vals ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %vals) 12986 177 13163
1521 12986 $self->{'term_count'}{$term}++;
1522 12986 my $tnode = "T:$term";
1523  
1524 12986 $neighbors{$dnode}{$tnode} = $edge.',1';
1525 12986 $neighbors{$tnode}{$dnode} = $edge.',1';
1526 }
1527 177 $doc++;
1528 }
1529 1 $self->{'neighbors'} = \%neighbors;
1530 }
1531  
1532 1 ▶ print "Loaded.\n" if $self->{'debug'} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} > 1 0 1 1
1533 1 $self->{'from_TDM'} = 1;
1534 1 $self->{'doc_count'} = $doc;
1535 }
1536  
1537  
1538  
1539 # XS version only
1540 #
1541 # This sub maintains a mapping between node names and integer index
1542 # values.
1543  
1544 0 ▶sub _add_node {
Subroutine _add_node: not called CC=4 SCAR=30.0
1545 0 my ( $self, $node_name, $type ) = @_;
1546 0 ▶ croak "Must provide a type" unless $type;
Branch: 1 branch
BranchTrueFalseTotal
unless $type 0 0 0
1547 0 ▶ croak "Must provide a node name" unless $node_name;
Branch: 1 branch
BranchTrueFalseTotal
unless $node_name 0 0 0
1548 croak "This node already exists" if
1549 0 ▶ $self->{'node_map'}{$node_name};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"node_map"}{$node_name} 0 0 0
1550  
1551 0 my $new_id = $self->{'next_free_id'}++;
1552 0 $self->{'node_map'}{$node_name} = $new_id;
1553 0 $self->{'id_map'}[$new_id] = $node_name;
1554 0 $self->{'Graph'}->add_node( $new_id, $type );
1555  
1556 0 return $new_id;
1557 }
1558  
1559  
1560  
1561 #
1562 # INTERNAL METHODS
1563 #
1564  
1565 # each node should have the same number of inbound
1566 # and outbound links
1567  
1568 37 ▶sub check_consistency {
Subroutine check_consistency: called CC=8 SCAR=21.2
Pod undocumented
1569  
1570 37 my ( $self ) = @_;
1571 37 my %inbound;
1572 my %outbound;
1573
1574
1575 37 foreach my $node ( keys %{$self->{neighbors}} ) {
1576 17194 ▶ next unless $node =~ /^[DT]:/; # for MLDBM compatibility
Branch: 1 branch
BranchTrueFalseTotal
unless $node =~ /^[DT]:/ 0 17194 17194
1577 17194 $outbound{$node} = scalar keys %{$self->{neighbors}{$node}};
1578 17194 foreach my $neighbor ( keys %{ $self->{neighbors}{$node} } ) {
1579 39868 $inbound{$neighbor}++;
1580 }
1581 }
1582
1583 37 my $in = scalar keys %inbound;
1584 37 my $out = scalar keys %outbound;
1585 37 ▶ carp "number of nodes with inbound links ($in) does not match number of nodes with outbound links ( $out )"
Branch: 1 branch
BranchTrueFalseTotal
unless scalar keys %inbound == scalar keys %outbound 0 37 37
1586 unless scalar keys %inbound == scalar keys %outbound;
1587
1588 37 foreach my $node ( keys %inbound ) {
1589 17194 ▶ $outbound{$node} ||= 0;
Condition50%1/2
$outbound{$node} ||= 0
l!l
171940
MC/DC0%0/1
$outbound{$node} ||= 0
$outbound{$node}
Truth table50%1/2
A
A= $outbound{$node}
Aresult
11
00
1590 carp "$node has $inbound{$node} inbound links, $outbound{$node} outbound links\n"
1591 17194 ▶ unless $inbound{$node} == $outbound{$node};
Branch: 1 branch
BranchTrueFalseTotal
unless $inbound{$node} == $outbound{$node} 0 17194 17194
1592 }
1593  
1594 }
1595  
1596  
1597 =item have_edge RAWNODE1, RAWNODE2
1598  
1599 Returns true if the nodes share an edge. Node names must be prefixed with 'D' or 'T'
1600 as appropriate.
1601  
1602 =cut
1603  
1604 0 ▶sub have_edge {
Subroutine have_edge: not called CC=1 SCAR=6.9
Pod documented
1605 0 my ( $self, $node1, $node2 ) = @_;
1606 0 return exists $self->{neighbors}{$node1}{$node2};
1607 }
1608  
1609  
1610 {
1611  
1612 14 my %visited;
1613 my %component;
1614 14 my $depth;
1615
1616 =item connected_components
1617  
1618 Returns an array of connected components in the graph. Each component is a list
1619 of nodes that are mutually accessible by traveling along edges.
1620  
1621 =cut
1622  
1623 0 ▶ sub connected_components {
Subroutine connected_components: not called CC=4 SCAR=30.0
Pod documented
1624 0 my ( $self ) = @_;
1625
1626 0 %visited = (); # clear any old info
1627 0 %component = ();
1628
1629
1630 0 my $n = $self->{neighbors};
1631
1632
1633 0 my @node_list = keys %{$n};
1634 0 my @components;
1635
1636 0 ▶ while ( @node_list ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@node_list) 0 0 0
1637 0 my $start = shift @node_list;
1638 0 ▶ next if exists $visited{$start};
Branch: 1 branch
BranchTrueFalseTotal
if exists $visited{$start} 0 0 0
1639
1640 0 ▶ last unless $start;
Branch: 1 branch
BranchTrueFalseTotal
unless $start 0 0 0
1641 0 warn "Visiting neighbors for $start\n";
1642 0 visit_neighbors( $n, $start );
1643 0 push @components, [ keys %component ];
1644 0 %component = ();
1645 }
1646
1647 0 warn "Found ", scalar @components, " connected components\n";
1648 0 return @components;
1649
1650
1651 }
1652  
1653 0 ▶ sub visit_neighbors {
Subroutine visit_neighbors: not called CC=3 SCAR=24.8
Pod undocumented
1654 0 my ( $g, $l ) = @_;
1655 0 ▶ return if $visited{$l};
Branch: 1 branch
BranchTrueFalseTotal
if $visited{$l} 0 0 0
1656 0 $depth++;
1657 0 $visited{$l}++; $component{$l}++;
1658 0 warn $depth, " $l\n";
1659 0 my @neigh = keys %{ $g->{$l} };
1660 0 foreach my $n ( @neigh ) {
1661 0 visit_neighbors( $g, $n );
1662 }
1663 0 $depth--;
1664 }
1665 }
1666  
1667  
1668 # Wipe the graph free of stored energies
1669  
1670 14 ▶sub _clear {
Subroutine _clear: called CC=1 SCAR=0.0
1671 21 my ( $self ) = @_;
1672 21 $self->{'energy'} = undef;
1673 }
1674  
1675  
1676 # Gather the stored energy values from the graph
1677  
1678 21 ▶sub _collect {
Subroutine _collect: called CC=3 SCAR=11.0
1679 21 my ( $self ) = @_;
1680 21 my $e = $self->{'energy'};
1681 21 my $result = {};
1682 21 foreach my $k ( keys %{$self->{'energy'}} ) {
1683 291 ▶ next unless $e->{$k} > $self->{'COLLECT_THRESHOLD'};
Branch: 1 branch
BranchTrueFalseTotal
unless $e->{$k} > $self->{"COLLECT_THRESHOLD"} 18 273 291
1684 273 $result->{$k} = $e->{$k};
1685 }
1686 21 return $result;
1687 }
1688  
1689  
1690  
1691  
1692 # Assign a starting energy ENERGY to NODE, and recursively distribute the
1693 # energy to neighbor nodes. Singleton nodes get special treatment
1694  
1695 393 ▶sub _energize {
Subroutine _energize: called CC=12 SCAR=26.1
1696  
1697 393 my ( $self, $node, $energy ) = @_;
1698  
1699  
1700 393 ▶ return unless defined $self->{neighbors}{$node};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"neighbors"}{$node} 0 393 393
1701 393 ▶ my $orig = $self->{energy}{$node} || 0;
Condition100%2/2
$self->{'energy'}{$node} || 0
l!l
102291
MC/DC100%1/1
$self->{'energy'}{$node} || 0
$self->{'energy'}{$node}
Truth table100%2/2
A
A= $self->{'energy'}{$node}
Aresult
11
00
1702 393 $self->{energy}->{$node} += $energy;
1703 393 ▶ return if ( $self->{depth} == $self->{max_depth} );
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"depth"} == $self->{"max_depth"} 0 393 393
1704 393 $self->{depth}++;
1705  
1706 393 ▶ if ( $self->{'debug'} > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"} > 1) 0 393 393
1707 0 print ' ' x $self->{'depth'};
1708 0 print "$node: energizing $orig + $energy\n";
1709 }
1710  
1711  
1712 393 my $n = $self->{neighbors};
1713
1714 #sleep 1;
1715 393 my $degree = scalar keys %{ $n->{$node} };
1716  
1717  
1718 393 ▶ if ( $degree == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($degree == 0) 0 393 393
1719
1720 0 carp "WARNING: reached a node without neighbors: $node at search depth $self->{depth}\n";
1721 0 $self->{depth}--;
1722 0 return;
1723 }
1724
1725
1726 393 my $subenergy = $energy / (log($degree)+1);
1727  
1728  
1729 # At singleton nodes (words that appear in only one document, for example)
1730 # Don't spread energy any further. This avoids a "reflection" back and
1731 # forth from singleton nodes to their neighbors.
1732  
1733 393 ▶ if ( $degree == 1 and $energy < $self->{'START_ENERGY'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($degree == 1 and $energy < $self->{'START_ENERGY'}) { } 50 343 393
elsif ($subenergy > $self->{'ACTIVATE_THRESHOLD'}) { } 69 274 343
Condition100%3/3
$degree == 1 and $energy < $self->{"START_ENERGY"}
!ll&&!rl&&r
339450
MC/DC100%2/2
$degree == 1 and $energy < $self->{"START_ENERGY"}
$degree == 1 $energy < $self->{"START_ENERGY"}
Truth table100%3/3
A and B
A= $degree == 1B= $energy < $self->{"START_ENERGY"}
ABresult
0X0
100
111
1734  
1735 #do nothing
1736  
1737 } elsif ( $subenergy > $self->{ACTIVATE_THRESHOLD} ) {
1738 print ' ' x $self->{'depth'},
1739 "$node: propagating subenergy $subenergy to $degree neighbors\n"
1740 69 ▶ if $self->{'debug'} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} > 1 0 69 69
1741 69 foreach my $neighbor ( keys %{ $n->{$node} } ) {
1742 367 my $pair = $n->{$node}{$neighbor};
1743 367 my ( $edge, undef ) = split /,/, $pair;
1744 367 my $weighted_energy = $subenergy * $edge;
1745 print ' ' x $self->{'depth'},
1746 " edge $edge ($node, $neighbor)\n"
1747 367 ▶ if $self->{'debug'} > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} > 1 0 367 367
1748 367 $self->_energize( $neighbor, $weighted_energy );
1749 }
1750 }
1751 393 $self->{'depth'}--;
1752 393 return 1;
1753 }
1754  
1755  
1756 # Given an array, normalize using cosine normalization
1757  
1758 5820 ▶sub __normalize {
Subroutine __normalize: called CC=6 SCAR=19.6
1759 5820 my ( $arr ) = @_;
1760  
1761 5820 ▶ croak "Must provide array ref to __normalize" unless
Branch: 1 branch
BranchTrueFalseTotal
unless defined $arr and ref $arr and ref $arr eq "ARRAY" 0 5820 5820
Condition33%2/6
defined $arr and ref $arr and ref $arr eq "ARRAY"
!ll&&!rl&&r
005820
defined $arr and ref $arr
!ll&&!rl&&r
005820
MC/DC0%0/3
defined $arr and ref $arr and ref $arr eq "ARRAY"
defined $arr ref $arr ref $arr eq "ARRAY"
Truth table25%1/4
A and B and C
A= defined $arrB= ref $arrC= ref $arr eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
1762 defined $arr and
1763 ref $arr and
1764 ref $arr eq 'ARRAY';
1765  
1766 5820 my $sum;
1767 5820 $sum += $_->[2] foreach @{$arr};
1768 5820 $_->[2]/= $sum foreach @{$arr};
1769 5820 return 1;
1770 }
1771  
1772  
1773  
1774  
1775 18 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=0.0
1776 undef $_[0]->{Graph}
1777 18 }
1778  
1779 14 1;
1780  
1781 __END__
↑ Summary blib/lib/Search/bench.pl »