/[jsFind]/trunk/jsFind.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Annotation of /trunk/jsFind.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 7 - (hide annotations)
Wed Jul 21 15:34:03 2004 UTC (19 years, 9 months ago) by dpavlin
File size: 15625 byte(s)
documentaton fix and better info message

1 dpavlin 1 package jsFind;
2    
3     use 5.008004;
4     use strict;
5     use warnings;
6    
7     our $VERSION = '0.01';
8    
9     =head1 NAME
10    
11     jsFind - generate index for jsFind using B-Tree
12    
13     =head1 SYNOPSIS
14    
15     use jsFind;
16    
17    
18    
19     =head1 DESCRIPTION
20    
21     This module can be used to create index files for jsFind, powerful tool for
22     adding a search engine to a CDROM archive or catalog without requiring the
23     user to install anything.
24    
25     Main difference between this module and scripts delivered with jsFind are:
26    
27     =over 5
28    
29     =item *
30    
31     You don't need to use swish-e to create index
32    
33     =item *
34    
35     You can programatically (and incrementaly) create index for jsFind
36    
37     =back
38    
39     =head1 METHODS
40    
41     This module contains two packages C<jsFind> and C<jsFind::Node>.
42    
43     =head2 jsFind methods
44    
45     =cut
46    
47     use Exporter 'import';
48     use Carp;
49    
50     our @ISA = qw(Exporter);
51    
52     BEGIN {
53     import 'jsFind::Node';
54     }
55    
56     =head3 new
57    
58     Create new tree. Arguments are C<B> which is maximum numbers of keys in
59     each node and optional C<Root> node. Each root node may have child nodes.
60    
61     All nodes are objects from C<jsFind::Node>.
62    
63     my $t = new jsFind(B => 4);
64    
65     =cut
66    
67     my $DEBUG = 1;
68    
69     sub new {
70     my $package = shift;
71     my %ARGV = @_;
72     croak "Usage: {$package}::new(B => number [, Root => root node ])"
73     unless exists $ARGV{B};
74     if ($ARGV{B} % 2) {
75     my $B = $ARGV{B} + 1;
76     carp "B must be an even number. Using $B instead.";
77     $ARGV{B} = $B;
78     }
79    
80     my $B = $ARGV{B};
81     my $Root = exists($ARGV{Root}) ? $ARGV{Root} : jsFind::Node->emptynode;
82     bless { B => $B, Root => $Root } => $package;
83     }
84    
85     =head3 B_search
86    
87     Search, insert, append or replace data in B-Tree
88    
89 dpavlin 5 $t->B_search(
90     Key => 'key value',
91     Data => { "path" => {
92     "t" => "title of document",
93     "f" => 99,
94 dpavlin 7 },
95 dpavlin 5 },
96     Insert => 1,
97     Append => 1,
98     );
99 dpavlin 1
100     Semantics:
101    
102     If key not found, insert it iff C<Insert> argument is present.
103    
104     If key B<is> found, replace existing data iff C<Replace> argument
105     is present or add new datum to existing iff C<Append> argument is present.
106    
107     =cut
108    
109     sub B_search {
110     my $self = shift;
111     my %args = @_;
112     my $cur_node = $self->root;
113     my $k = $args{Key};
114     my $d = $args{Data};
115     my @path;
116    
117     if ($cur_node->is_empty) { # Special case for empty root
118     if ($args{Insert}) {
119     $cur_node->kdp_insert($k => $d);
120     return $d;
121     } else {
122     return undef;
123     }
124     }
125    
126     # Descend tree to leaf
127     for (;;) {
128    
129     # Didn't hit bottom yet.
130    
131     my($there, $where) = $cur_node->locate_key($k);
132     if ($there) { # Found it!
133     if ($args{Replace}) {
134     $cur_node->kdp_replace($where, $k => $d);
135     } elsif ($args{Append}) {
136     $cur_node->kdp_append($where, $k => $d);
137     }
138     return $cur_node->data($where);
139     }
140    
141     # Not here---must be in a subtree.
142    
143     if ($cur_node->is_leaf) { # But there are no subtrees
144     return undef unless $args{Insert}; # Search failed
145     # Stuff it in
146     $cur_node->kdp_insert($k => $d);
147     if ($self->node_overfull($cur_node)) { # Oops--there was no room.
148     $self->split_and_promote($cur_node, @path);
149     }
150     return $d;
151     }
152    
153     # There are subtrees, and the key is in one of them.
154    
155     push @path, [$cur_node, $where]; # Record path from root.
156    
157     # Move down to search the subtree
158     $cur_node = $cur_node->subnode($where);
159    
160     # and start over.
161     } # for (;;) ...
162    
163     croak ("How did I get here?");
164     }
165    
166    
167    
168     sub split_and_promote_old {
169     my $self = shift;
170     my ($cur_node, @path) = @_;
171    
172     for (;;) {
173     my ($newleft, $newright, $kdp) = $cur_node->halves($self->B / 2);
174     my ($up, $where) = @{pop @path};
175     if ($up) {
176     $up->kdp_insert(@$kdp);
177     my ($tthere, $twhere) = $up->locate_key($kdp->[0]);
178     croak "Couldn't find key `$kdp->[0]' in node after just inserting it!"
179     unless $tthere;
180     croak "`$kdp->[0]' went into node at `$twhere' instead of expected `$where'!"
181     unless $twhere == $where;
182     $up->subnode($where, $newleft);
183     $up->subnode($where+1, $newright);
184     return unless $self->node_overfull($up);
185     $cur_node = $up;
186     } else { # We're at the top; make a new root.
187     my $newroot = new jsFind::Node ([$kdp->[0]],
188     [$kdp->[1]],
189     [$newleft, $newright]);
190     $self->root($newroot);
191     return;
192     }
193     }
194    
195     }
196    
197     sub split_and_promote {
198     my $self = shift;
199     my ($cur_node, @path) = @_;
200    
201     for (;;) {
202     my ($newleft, $newright, $kdp) = $cur_node->halves($self->B / 2);
203     my ($up, $where) = @{pop @path} if (@path);
204     if ($up) {
205     $up->kdp_insert(@$kdp);
206     if ($DEBUG) {
207     my ($tthere, $twhere) = $up->locate_key($kdp->[0]);
208     croak "Couldn't find key `$kdp->[0]' in node after just inserting it!"
209     unless $tthere;
210     croak "`$kdp->[0]' went into node at `$twhere' instead of expected `$where'!"
211     unless $twhere == $where;
212     }
213     $up->subnode($where, $newleft);
214     $up->subnode($where+1, $newright);
215     return unless $self->node_overfull($up);
216     $cur_node = $up;
217     } else { # We're at the top; make a new root.
218     my $newroot = new jsFind::Node([$kdp->[0]],
219     [$kdp->[1]],
220     [$newleft, $newright]);
221     $self->root($newroot);
222     return;
223     }
224     }
225     }
226    
227     =head3 B
228    
229     Return B (maximum number of keys)
230    
231     my $max_size = $t->B;
232    
233     =cut
234    
235     sub B {
236     $_[0]{B};
237     }
238    
239     =head3 root
240    
241     Returns root node
242    
243     my $root = $t->root;
244    
245     =cut
246    
247     sub root {
248     my ($self, $newroot) = @_;
249     $self->{Root} = $newroot if defined $newroot;
250     $self->{Root};
251     }
252    
253     =head3 node_overfull
254    
255     Returns if node is overfull
256    
257     if ($node->node_overfull) { something }
258    
259     =cut
260    
261     sub node_overfull {
262     my $self = shift;
263     my $node = shift;
264     $node->size > $self->B;
265     }
266    
267     =head3 to_string
268    
269     Returns your tree as formatted string.
270    
271     my $text = $root->to_string;
272    
273     Mostly usefull for debugging as output leaves much to be desired.
274    
275     =cut
276    
277     sub to_string {
278     $_[0]->root->to_string;
279     }
280    
281     =head3 to_dot
282    
283     Create Graphviz graph of your tree
284    
285     my $dot_graph = $root->to_dot;
286    
287     =cut
288    
289     sub to_dot {
290     my $self = shift;
291    
292     my $dot = qq/digraph dns {\nrankdir=LR;\n/;
293     $dot .= $self->root->to_dot;
294     $dot .= qq/\n}\n/;
295    
296     return $dot;
297     }
298    
299     =head3 to_jsfind
300    
301     Create xml index files for jsFind. This should be called after
302     your B-Tree has been filled with data.
303    
304     $root->to_jsfind('/full/path/to/index/dir/');
305    
306     Returns number of nodes in created tree.
307    
308     =cut
309    
310     sub to_jsfind {
311     my $self = shift;
312    
313     my $path = shift || confess "to_jsfind need path to your index!";
314    
315     $path .= "/" if ($path =~ /\/$/);
316 dpavlin 7 carp "create directory for index '$path': $!" if (! -w $path);
317 dpavlin 1
318     return $self->root->to_jsfind($path,"0");
319     }
320    
321    
322     # private, default cmd function
323     sub default_cmp {
324     $_[0] cmp $_[1];
325     }
326    
327     #####################################################################
328    
329     =head2 jsFind::Node methods
330    
331     Each node has C<k> key-data pairs, with C<B> <= C<k> <= C<2B>, and
332     each has C<k+1> subnodes, which might be null.
333    
334     The node is a blessed reference to a list with three elements:
335    
336     ($keylist, $datalist, $subnodelist)
337    
338     each is a reference to a list list.
339    
340     The null node is represented by a blessed reference to an empty list.
341    
342     =cut
343    
344     package jsFind::Node;
345    
346     use warnings;
347     use strict;
348    
349     use Carp;
350     use File::Path;
351    
352     my $KEYS = 0;
353     my $DATA = 1;
354     my $SUBNODES = 2;
355    
356     =head3 new
357    
358     Create New node
359    
360     my $node = new jsFind::Node ($keylist, $datalist, $subnodelist);
361    
362     You can also mit argument list to create empty node.
363    
364     my $empty_node = new jsFind::Node;
365    
366     =cut
367    
368     sub new {
369     my $self = shift;
370     my $package = ref $self || $self;
371     croak "Internal error: jsFind::Node::new called with wrong number of arguments."
372     unless @_ == 3 || @_ == 0;
373     bless [@_] => $package;
374     }
375    
376     =head3 locate_key
377    
378     Locate key in node using linear search. This should probably be replaced
379     by binary search for better performance.
380    
381     my ($found, $index) = $node->locate_key($key, $cmp_coderef);
382    
383     Argument C<$cmp_coderef> is optional reference to custom comparison
384     operator.
385    
386     Returns (1, $index) if $key[$index] eq $key.
387    
388     Returns (0, $index) if key could be found in $subnode[$index].
389    
390     In scalar context, just returns 1 or 0.
391    
392     =cut
393    
394     sub locate_key {
395     # Use linear search for testing, replace with binary search.
396     my $self = shift;
397     my $key = shift;
398     my $cmp = shift || \&jsFind::default_cmp;
399     my $i;
400     my $cmp_result;
401     my $N = $self->size;
402     for ($i = 0; $i < $N; $i++) {
403     $cmp_result = &$cmp($key, $self->key($i));
404     last if $cmp_result <= 0;
405     }
406    
407     # $i is now the index of the first node-key greater than $key
408     # or $N if there is no such. $cmp_result is 0 iff the key was found.
409     (!$cmp_result, $i);
410     }
411    
412    
413     =head3 emptynode
414    
415     Creates new empty node
416    
417     $node = $root->emptynode;
418     $new_node = $node->emptynode;
419    
420     =cut
421    
422     sub emptynode {
423     new($_[0]); # Pass package name, but not anything else.
424     }
425    
426     =head3 is_empty
427    
428     Test if node is empty
429    
430     if ($node->is_empty) { something }
431    
432     =cut
433    
434     # undef is empty; so is a blessed empty list.
435     sub is_empty {
436     my $self = shift;
437     !defined($self) || $#$self < 0;
438     }
439    
440     =head3 key
441    
442     Return C<$i>th key from node
443    
444     my $key = $node->key($i);
445    
446     =cut
447    
448     sub key {
449     # my ($self, $n) = @_;
450     # $self->[$KEYS][$n];
451    
452     # speedup
453     $_[0]->[$KEYS][$_[1]];
454     }
455    
456     =head3 data
457    
458     Return C<$i>th data from node
459    
460     my $data = $node->data($i);
461    
462     =cut
463    
464     sub data {
465     my ($self, $n) = @_;
466     $self->[$DATA][$n];
467     }
468    
469     =head3 kdp_replace
470    
471     Set key data pair for C<$i>th element in node
472    
473     $node->kdp_replace($i, "key value" => {
474     "data key 1" => "data value 1",
475     "data key 2" => "data value 2",
476     };
477    
478     =cut
479    
480     sub kdp_replace {
481     my ($self, $n, $k => $d) = @_;
482     if (defined $k) {
483     $self->[$KEYS][$n] = $k;
484     $self->[$DATA][$n] = $d;
485     }
486     [$self->[$KEYS][$n],
487     $self->[$DATA][$n]];
488     }
489    
490     =head3 kdp_insert
491    
492     # No return value.
493    
494     =cut
495    
496     sub kdp_insert {
497     my $self = shift;
498     my ($k => $d) = @_;
499     my ($there, $where) = $self->locate_key($k) unless $self->is_empty;
500    
501     if ($there) { croak("Tried to insert `$k => $d' into node where `$k' was already present."); }
502    
503     # undef fix
504     $where ||= 0;
505    
506     splice(@{$self->[$KEYS]}, $where, 0, $k);
507     splice(@{$self->[$DATA]}, $where, 0, $d);
508     splice(@{$self->[$SUBNODES]}, $where, 0, undef);
509     }
510    
511     =head3 kdp_append
512    
513     Adds new data keys and values to C<$i>th element in node
514    
515     $node->kdp_append($i, "key value" => {
516     "added data key" => "added data value",
517     };
518    
519     =cut
520    
521     sub kdp_append {
522     my ($self, $n, $k => $d) = @_;
523     if (defined $k) {
524     $self->[$KEYS][$n] = $k;
525     my ($kv,$dv) = %{$d};
526     $self->[$DATA][$n]->{$kv} = $dv;
527     }
528     [$self->[$KEYS][$n],
529     $self->[$DATA][$n]];
530     }
531    
532     =head3 subnode
533    
534     Set new or return existing subnode
535    
536     # return 4th subnode
537     my $my_node = $node->subnode(4);
538    
539     # create new subnode 5 from $my_node
540     $node->subnode(5, $my_node);
541    
542     =cut
543    
544     sub subnode {
545     my ($self, $n, $newnode) = @_;
546     $self->[$SUBNODES][$n] = $newnode if defined $newnode;
547     $self->[$SUBNODES][$n];
548     }
549    
550     =head3 is_leaf
551    
552     Test if node is leaf
553    
554     if ($node->is_leaf) { something }
555    
556     =cut
557    
558     sub is_leaf {
559     my $self = shift;
560     ! defined $self->[$SUBNODES][0]; # undefined subnode means leaf node.
561     }
562    
563     =head3 size
564    
565     Return number of keys in the node
566    
567     my $nr = $node->size;
568    
569     =cut
570    
571     sub size {
572     my $self = shift;
573     return scalar(@{$self->[$KEYS]});
574     }
575    
576     =head3 halves
577    
578     # Accept an index $n
579     # Divide into two nodes so that keys 0 .. $n-1 are in one node
580     # and keys $n+1 ... $size are in the other.
581    
582     =cut
583    
584     sub halves {
585     my $self = shift;
586     my $n = shift;
587     my $s = $self->size;
588     my @right;
589     my @left;
590    
591     $left[$KEYS] = [@{$self->[$KEYS]}[0 .. $n-1]];
592     $left[$DATA] = [@{$self->[$DATA]}[0 .. $n-1]];
593     $left[$SUBNODES] = [@{$self->[$SUBNODES]}[0 .. $n]];
594    
595     $right[$KEYS] = [@{$self->[$KEYS]}[$n+1 .. $s-1]];
596     $right[$DATA] = [@{$self->[$DATA]}[$n+1 .. $s-1]];
597     $right[$SUBNODES] = [@{$self->[$SUBNODES]}[$n+1 .. $s]];
598    
599     my @middle = ($self->[$KEYS][$n], $self->[$DATA][$n]);
600    
601     ($self->new(@left), $self->new(@right), \@middle);
602     }
603    
604     =head3 to_string
605    
606     Dumps tree as string
607    
608     my $str = $root->to_string;
609    
610     =cut
611    
612     sub to_string {
613     my $self = shift;
614     my $indent = shift || 0;
615     my $I = ' ' x $indent;
616     return '' if $self->is_empty;
617     my ($k, $d, $s) = @$self;
618     my $result = '';
619     $result .= defined($s->[0]) ? $s->[0]->to_string($indent+2) : '';
620     my $N = $self->size;
621     my $i;
622     for ($i = 0; $i < $N; $i++) {
623     # $result .= $I . "$k->[$i] => $d->[$i]\n";
624     $result .= $I . "$k->[$i]\n";
625     $result .= defined($s->[$i+1]) ? $s->[$i+1]->to_string($indent+2) : '';
626     }
627     $result;
628     }
629    
630     =begin comment
631    
632     use Data::Dumper;
633    
634     sub to_string {
635     my $self = shift;
636     my $indent = shift || 0;
637     my $path = shift || '0';
638     return '' if $self->is_empty;
639     my ($k, $d, $s) = @$self;
640     my $result = '';
641     $result .= defined($s->[0]) ? $s->[0]->to_string($indent+1,"$path/0") : '';
642     my $N = $self->size;
643     for (my $i = 0; $i < $N; $i++) {
644     my $dump = Dumper($d->[$i]);
645     $dump =~ s/[\n\r\s]+/ /gs;
646     $dump =~ s/\$VAR1\s*=\s*//;
647     $result .= sprintf("%-5s [%2d] %2s: %s => %s\n", $path, $i, $indent, $k->[$i], $dump);
648     $result .= defined($s->[$i+1]) ? $s->[$i+1]->to_string($indent+1,"$path/$i") : '';
649     }
650     $result;
651     }
652    
653     =end comment
654    
655     =head3 to_dot
656    
657     Recursivly walk nodes of tree
658    
659     =cut
660    
661     sub to_dot {
662     my $self = shift;
663     my $parent = shift;
664    
665     return '' if $self->is_empty;
666    
667     my $dot = '';
668    
669     my ($k, $d, $s) = @$self;
670     my $N = $self->size;
671    
672     my @dot_keys;
673    
674     my $node_name = $parent || '_';
675     $node_name =~ s/\W+//g;
676     $node_name .= " [$N]";
677    
678     for (my $i = 0; $i <= $N; $i++) {
679     if (my $key = $k->[$i]) {
680     push @dot_keys, qq{<$i>$key};
681     }
682     $dot .= $s->[$i]->to_dot(qq{"$node_name":$i}) if ($s->[$i]);
683     }
684     push @dot_keys, qq{<$N>...} if (! $self->is_leaf);
685    
686     my $label = join("|",@dot_keys);
687     $dot .= qq{"$node_name" [ shape=record, label="$label" ];\n};
688    
689     $dot .= qq{$parent -> "$node_name";\n} if ($parent);
690    
691     $dot;
692     }
693    
694     =head3 to_jsfind
695    
696     Create jsFind xml files
697    
698     my $nr=$tree->to_dot('/path/to/index','0');
699    
700     Returns number of elements created
701    
702     =cut
703    
704     sub to_jsfind {
705     my $self = shift;
706     my ($path,$file) = @_;
707    
708     return 0 if $self->is_empty;
709    
710     my $nr_keys = 0;
711    
712     my ($k, $d, $s) = @$self;
713     my $N = $self->size;
714    
715     my ($key_xml, $data_xml) = ("<n>","<d>");
716    
717     for (my $i = 0; $i <= $N; $i++) {
718     my $key = lc($k->[$i]);
719    
720     if ($key) {
721     $key_xml .= qq{<k>$key</k>};
722     $data_xml .= qq{<e>};
723     #use Data::Dumper;
724     #print Dumper($d->[$i]);
725     foreach my $path (keys %{$d->[$i]}) {
726     $data_xml .= '<l f="'.($d->[$i]->{$path}->{'f'} || 1).'" t="'.($d->[$i]->{$path}->{'t'} || 'no title').'">'.$path.'</l>';
727     $nr_keys++;
728     }
729     $data_xml .= qq{</e>};
730     }
731    
732     $nr_keys += $s->[$i]->to_jsfind("$path/$file","$i") if ($s->[$i]);
733     }
734    
735     $key_xml .= "</n>";
736     $data_xml .= "</d>";
737    
738     if (! -e $path) {
739     mkpath($path) || croak "can't create dir '$path': $!";
740     }
741    
742     open(K, "> ${path}/${file}.xml") || croak "can't open '$path/$file.xml': $!";
743     open(D, "> ${path}/_${file}.xml") || croak "can't open '$path/_$file.xml': $!";
744    
745     print K $key_xml;
746     print D $data_xml;
747    
748     close(K);
749     close(D);
750    
751     return $nr_keys;
752     }
753    
754     1;
755     __END__
756    
757     =head1 SEE ALSO
758    
759     jsFind web site L<http://www.elucidsoft.net/projects/jsfind/>
760    
761     B-Trees in perl web site L<http://perl.plover.com/BTree/>
762    
763     =head1 AUTHORS
764    
765     Mark-Jonson Dominus E<lt>mjd@pobox.comE<gt> wrote C<BTree.pm> which was
766     base for this module
767    
768     Shawn P. Garbett E<lt>shawn@elucidsoft.netE<gt> wrote jsFind
769    
770     Dobrica Pavlinusic E<lt>dpavlin@rot13.orgE<gt> wrote this module
771    
772     =head1 COPYRIGHT AND LICENSE
773    
774     Copyright (C) 2004 by Dobrica Pavlinusic
775    
776     This program is free software; you can redistribute it and/or modify it
777     under the terms of the GNU General Public License as published by the Free
778     Software Foundation; either version 2 of the License, or (at your option)
779     any later version. This program is distributed in the hope that it will be
780     useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
781     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
782     Public License for more details.
783    
784     =cut

  ViewVC Help
Powered by ViewVC 1.1.26