DFAState.pm untested

filter: Statementstmt 0.0% 0 / 524 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 150 MC/DCmcdc 0.0% 0 / 78 Subroutinesub 0.0% 0 / 47 Podpod 0.0% 0 / 40 totaltotal 0.0% 0 / 895 CC 29 SCAR 21.1
CC
29
Cov
0%
absorb
20.0
autogen_nums
20.0
dropped_edge
20.0
CRAP 8.2
1 package IDS::DFAState;
2 $IDS::DFAState::VERSION = "1.1";
3  
4 =head1 NAME
5  
6 IDS::DFAState - A state in a Deterministic Finite Automata (L<DFA>)
7 or a Hidden Markov Model (L<HMM>).
8  
9 =head1 SYNOPSIS
10  
11 A usage synopsis would go here. Since it is not here, read on.
12  
13 =head1 DESCRIPTION
14  
15 =head2 Introduction
16  
17 This class is for people writing various forms of finite
18 automata. It is unlikely to be useful to others.
19  
20 Note that a state is rarely accessed other than through a reference.
21 A token is always a simple string.
22  
23 A state consists of the following:
24  
25 =over
26  
27 =item inbound
28  
29 A hash with key of a reference to a state and a value of a reference to
30 a hash indexed by tokens that that that cause a transition to us (the
31 value of this hash is just "1"; we use a hash because it is a set and
32 not a list). If the hash is empty, we will be pruned shortly.
33  
34 Class methods that provide information relating to this variable:
35  
36 =over
37  
38 =item L</in_links>
39  
40 How many states have transitions to us
41  
42 =item L</in_states>
43  
44 What states have transitions to us
45  
46 =item L</in_tokens>
47  
48 what are the tokens causing an inbound transition
49  
50 =item L</exists_inbound_from>
51  
52 If a state is in the list
53  
54 =back
55  
56 Functions that change this variable:
57  
58 =over
59  
60 =item L</add_inbound>
61  
62 Add an inbound state
63  
64 =item L</absorb>
65  
66 =item L</dropped_edge>
67  
68 =back
69  
70 =item outbound
71  
72 A hash, indexed by tokens causing the transition, of references
73 to states that we can transition to. We can have only one outbound
74 transition per token, so this is a DFA and not a NFA state.
75 Functions that provide information relating to this
76 variable:
77  
78 =over
79  
80 =item L</out_links>
81  
82 How many outbound links do we have
83  
84 =item L</out_states>
85  
86 States we can reach
87  
88 =item L</out_tokens>
89  
90 Tokens causing transitions
91  
92 =item L</token_to>
93  
94 What token causes a transition to a specified state
95  
96 =item L</next>
97  
98 What state we transition to for a given token.
99  
100 =back
101  
102 Functions that change this variable:
103  
104 =over
105  
106 =item L</add_outbound>
107  
108 =item L</absorb>
109  
110 =item L</move>
111  
112 =item L</drop_edge>
113  
114 =item L</drop_link_to>
115  
116 =back
117  
118 =item out_count
119  
120 Out_count keeps track of every time an edge is traversed. When used in
121 a DFA, the counts may be used to know which edges are not used, and thus
122 are candidates for pruning. When used in a HMM, out_count keeps track
123 of every time an edge is traversed for computing probabilities later.
124 This variable is a hash, indexed by the token causing the transition,
125 with the value being the count.
126  
127 Functions that provide information relating to this variable:
128  
129 =over
130  
131 =item L</out_count>
132  
133 the count for a given token
134  
135 =back
136  
137 Functions that change this variable:
138  
139 =over
140  
141 =item L</followed>
142  
143 =item L</reset_counters>
144  
145 =back
146  
147 As well as all of the functions that manipulate the variable outbound.
148  
149 =item visits
150  
151 When the DFA is being used, visits keep track of the number of times
152 this node has been visited. It is used in pruning to delete un-used
153 nodes. Functions that provide information relating to this variable:
154  
155 =over
156  
157 =item L</visits>
158  
159 =back
160  
161 Functions that change this variable:
162  
163 =over
164  
165 =item L</visited>
166  
167 =item L</reset_counters>
168  
169 =back
170  
171 Sanity says that the sum of the out counts should equal this count.
172  
173 =item verbose
174  
175 As the state does operations, it will print messages that might be
176 helpful for debugging. These are controlled by the verbosity level.
177 The higher the value, the more verbose. Values beyond 2 are unlikely to
178 be useful.
179  
180 =back
181  
182  
183 =head2 Methods
184  
185 The only callers of these methods should be methods in L<DFA>, L<HMM>,
186 or related classes.
187  
188 =cut
189  
190 use strict;
191 use warnings;
192 use IO::Handle;
193 use Carp qw(cluck carp confess);
194 use Tie::RefHash;
195 use IDS::Utils qw(fh_or_stdout);
196 use Tk;
197  
198 =head2 Methods related to construction
199  
200 Construction involves not just attaching one state to another, but also
201 the merging of states.
202  
203 =over
204  
205 =item new()
206  
207 =item new(verbosity)
208  
209 Creates a new IDS::DFAState. The verbosity level defaults to 0 if it is not
210 supplied.
211  
212 =item add_outbound(token, to)
213  
214 During construction, add an outbound transition for the specified
215 token to the specified state.
216  
217 =item add_inbound(inref, intoken)
218  
219 Private method. Add a reference to a state that transitions to us.
220  
221 =item absorb(otherstate)
222  
223 Absorb the transitions from another (similar) state. Any tokens that
224 our state does not have are added. The resulting counter is the sum of
225 the current and other states.
226  
227 All tokens in common must go to the same place or an error results.
228  
229 =item move(from, to)
230  
231 Move outbound transitions from the "from" state to the "to" state.
232 This function will be called during a state merge, to reset the
233 transitions to the new state.
234  
235 The counter is not changed since all that occurs is a move; the count
236 can still be considered valid.
237  
238 =back
239  
240 =cut
241  
242 sub new {
243 my $invocant = shift;
244 my $class = ref($invocant) || $invocant;
245 my $self = {
246 "outbound" => {}, # transition table keyed by token; this
247 # implies that we have a DFA and not a NFA
248 # since we can only have one outbound link
249 # per token.
250 "out_count" => {}, # counters for the times the edge has been used
251 "inbound" => {}, # what states have transitions into this one?
252 "visits" => 0, # counter for uses of this node
253 "verbose" => shift || 0,
254 };
255 tie %{$self->{"inbound"}}, 'Tie::RefHash';
256 bless($self, $class); # consecrate
257 return $self;
258 }
259  
260 sub add_outbound {
261 my $self = shift;
262 my $token = shift;
263 defined($token) or
264 confess *add_outbound{PACKAGE} . "::add_outbound Missing token";
265 my $to = shift;
266 defined($to) or
267 confess *add_outbound{PACKAGE} . "::add_outbound Missing to";
268 $to->isa("IDS::DFAState") or
269 confess *add_outbound{PACKAGE} . "::add_outbound 'to' is wrong type";
270  
271 # sanity check that we are not moving an existing transition
272 confess "Moving an existing transition from $self to $to on $token"
273 if exists(${$self->{"outbound"}}{$token}) and
274 ${$self->{"outbound"}}{$token} ne $to;
275  
276 # See if the transition already exists; if so, we are done.
277 return if exists(${$self->{"outbound"}}{$token}) &&
278 ${$self->{"outbound"}}{$token} eq $to;
279
280 ${$self->{"outbound"}}{$token} = $to;
281 ${$self->{"out_count"}}{$token} = 1;
282 $to->add_inbound($self, $token);
283 }
284  
285 sub add_inbound {
286 my $self = shift;
287 my $inref = shift;
288 my $intoken = shift;
289 defined($inref) or confess "Missing inref in call to add_inbound";
290 $inref->isa("IDS::DFAState") or
291 confess *add_inbound{PACKAGE} . "::add_inbound 'inref' is wrong type";
292 defined($intoken) or confess "Missing intoken in call to add_inbound";
293  
294 ${${$self->{"inbound"}}{$inref}}{$intoken} = 1;
295 }
296  
297 sub absorb {
298 my $self = shift;
299 my $other = shift or
300 confess *absorb{PACKAGE} . "::absorb Missing 'other'";
301 $other->isa("IDS::DFAState") or
302 confess *absorb{PACKAGE} . "::absorb 'other' is wrong type";
303
304 $self eq $other and
305 confess *absorb{PACKAGE} . "::absorb Trying to absorb myself!";
306  
307 # take over the outbound transitions
308 for my $token ($other->out_tokens()) {
309 my $next = $other->next($token);
310  
311 # First, a sanity check to make sure we can stay a DFA
312 exists(${$self->{"outbound"}}{$token}) and
313 ${$self->{"outbound"}}{$token} ne $next and
314 confess *absorb{PACKAGE} . "::absorb link clash for $token!";
315  
316 # Do we already have this transition, or do we need to add it?
317 if (exists(${$self->{"outbound"}}{$token}) &&
318 ${$self->{"outbound"}}{$token} eq $next) {
319 # only need to add counter
320 ${$self->{"out_count"}}{$token} += $other->out_count($token);
321 } else {
322 # otherwise, need to add everything
323 ${$self->{"outbound"}}{$token} = $next;
324 exists(${$self->{"out_count"}}{$token}) or
325 ${$self->{"out_count"}}{$token} = 0;
326 ${$self->{"out_count"}}{$token} += $other->out_count($token);
327 # update list of inbound states in the destination state
328 $next->replace_inbound($other, $self);
329 print STDERR "Absorbing from $other transition for '$token' to $next\n"
330 if $self->{"verbose"} > 0;
331 }
332 }
333  
334 # adjust the inbound transitions to point to us
335 my @inbound = $other->in_states();
336 for my $s (@inbound) {
337 $s->move($other, $self);
338 print STDERR "moving $s from $other to $self\n"
339 if $self->{"verbose"} > 0;
340 }
341 }
342  
343 # update the inbound state hash to reflect a change in an inbound
344 # link
345 sub replace_inbound {
346 my $self = shift;
347 my $from = shift or
348 confess *move{PACKAGE} . "::move Missing 'from'";
349 $from->isa("IDS::DFAState") or
350 confess *move{PACKAGE} . "::move 'from' is wrong type";
351 my $to = shift or
352 confess *move{PACKAGE} . "::move Missing 'to'";
353 $to->isa("IDS::DFAState") or
354 confess *move{PACKAGE} . "::move 'to' is wrong type";
355  
356 map {${${$self->{"inbound"}}{$to}}{$_} = 1} keys %{${$self->{"inbound"}}{$from}};
357 delete(${$self->{"inbound"}}{$from});
358 }
359  
360 sub move {
361 my $self = shift;
362 my $from = shift or
363 confess *move{PACKAGE} . "::move Missing 'from'";
364 $from->isa("IDS::DFAState") or
365 confess *move{PACKAGE} . "::move 'from' is wrong type";
366 my $to = shift or
367 confess *move{PACKAGE} . "::move Missing 'to'";
368 $to->isa("IDS::DFAState") or
369 confess *move{PACKAGE} . "::move 'to' is wrong type";
370  
371 for my $t (keys %{$self->{"outbound"}}) {
372 if (${$self->{"outbound"}}{$t} eq $from) {
373 ${$self->{"outbound"}}{$t} = $to;
374 ### Update inbound link in destination
375 # ${$self->{"out_count"}}{$t} is not changed since all we are
376 # doing is a move; the count can still be considered valid.
377 print STDERR "Moved from $from to $to for token $t\n"
378 if $self->{"verbose"};
379 }
380 }
381 }
382  
383 =head2 I/O methods
384  
385 =over
386  
387 =item print_edges(node_map, filehandle)
388  
389 =item print_edges(node_map)
390  
391 Print the edges associated with this state. If a filehandle is supplied,
392 print there, STDOUT otherwise.
393  
394 The node_map is a mapping from node (IDS::DFAState) reference to the node
395 number assigned to a node by the L<DFA> or L<HMM>.
396  
397 =item print_vcg_edges(node_map)
398  
399 Print the outbound transitions in VCG format. See L<SEE ALSO> for a
400 reference for the VCG format.
401  
402 The node_map is a mapping from a node (IDS::DFAState) reference to the node
403 number assigned to a node by the L<DFA> or L<HMM>.
404  
405 =item print_vcg_node(node_number)
406  
407 Print information about this node (state) in VCG format. The
408 node_number is our node number.
409  
410 =back
411  
412 =cut
413  
414 sub print_edges {
415 my $self = shift;
416 my $node_map = shift or
417 confess *print_edges{PACKAGE} . "::print_edges no node_map";
418 my $fh = fh_or_stdout(shift);
419 my ($src, $dst, $cnt, $label);
420  
421 unless (defined($node_map->{$self})) {
422 carp "$self (src) has no node map entry!";
423 next EDGE;
424 }
425 EDGE: for my $token (keys %{$self->{"outbound"}}) {
426 unless (defined($node_map->{${$self->{"outbound"}}{$token}})) {
427 carp ${$self->{"outbound"}}{$token} . " (dst) ($token) has no node map!";
428 next EDGE;
429 }
430 $src = $node_map->{$self};
431 $dst = $node_map->{${$self->{"outbound"}}{$token}};
432 $cnt = ${$self->{"out_count"}}{$token};
433 print $fh "State $src To $dst count $cnt Token:\n $token\n";
434 }
435 }
436  
437 sub print_vcg_edges {
438 my $self = shift;
439 my $node_map = shift or
440 confess *print_vcg_edges{PACKAGE} . "::print_vcg_edges no node_map";
441 my $fh = fh_or_stdout(shift);
442 my ($src, $dst, $label);
443  
444 unless (defined($node_map->{$self})) {
445 carp "$self (src; vcg) has no node map entry!";
446 next EDGE;
447 }
448 EDGE: for my $token (keys %{$self->{"outbound"}}) {
449 unless (defined($node_map->{${$self->{"outbound"}}{$token}})) {
450 carp ${$self->{"outbound"}}{$token} . " (dst; vcg) ($token) has no node map!";
451 next EDGE;
452 }
453 $src = $node_map->{$self};
454 $dst = $node_map->{${$self->{"outbound"}}{$token}};
455 $label = $token;
456 $label =~ s/"/'/g; # so we can use " in the edge descr
457 print $fh 'edge: { sourcename: "' . $src . '" ' .
458 'label: "' . $label . '" ' .
459 'targetname: "' . $dst . '" }' .
460 "\n";
461 }
462 }
463  
464 sub print_vcg_node {
465 my $self = shift;
466 my $n = shift;
467 defined($n) or
468 confess *print_vcg_node{PACKAGE} . "::print_vcg_node no node number";
469 my $fh = fh_or_stdout(shift);
470 my ($level, $label, $title);
471  
472 $level = "";
473 if ($n == 0) {
474 $level = "level: 1";
475 $label = 'label: "(START)"';
476 } else {
477 $label = 'label: "' . $n . " " . $self . '"'; # debugging
478 #$label = 'label: "' . $n . '"'; # normal use
479 }
480 $title = 'title: "' . $n . '"';
481  
482 print $fh "node: { $title $label $level }\n";
483 }
484  
485 # for debugging purposes
486 sub print {
487 my $self = shift;
488 my $fh = fh_or_stdout(shift, fileno(STDERR));
489  
490 print $fh "self $self visits ", $self->{"visits"}, "\n";
491 print $fh " Inbound ", $self->in_links, "\n";
492 map { print $fh " $_\n" } $self->in_tokens;
493  
494 print $fh " Outbound\n";
495 for my $token (keys %{$self->{"outbound"}}) {
496 print $fh " $token -> ", ${$self->{"outbound"}}{$token}, "\n";
497 }
498 }
499  
500 =head2 Methods related to adapting the FA, counters and their maintenance
501  
502 L<DFA> adaptive learning (from the point of view of a IDS::DFAState) is keeping
503 track of nodes and edges as they are used, and then dropping the edges
504 which are not used enough to warrant keeping them.
505  
506 The counters are also used by a L<HMM> for calculating probabilities.
507  
508 =over
509  
510 =item visited()
511  
512 Increment the visited counter for the node.
513  
514 =item visits()
515  
516 Return the value of the visited counter.
517  
518 =item followed(token)
519  
520 Increment the counter for an edge associated with a token. Note that
521 the edge must exist.
522  
523 =item out_count(token)
524  
525 Return the counter associated with the transition for the specified
526 token.
527  
528 =item set_count(token, value)
529  
530 Set the counter associated with the transition for the specified
531 token to the given value.
532  
533 =item reset_counters()
534  
535 Reset the node and edge counters to 0.
536  
537 =item probability(token)
538  
539 Return the probability of taking the edge assocaited with the specified
540 token. The probability is calculated as
541 out_count(token) / sum of out_count(all tokens)
542  
543 =item drop_edges(threshold)
544  
545 Drop all edges with a use count below the threshold.
546  
547 =item drop_edge(token)
548  
549 Internal use only. Drop the edge associated with the specified token.
550  
551 =item dropped_edge(fromref)
552  
553 Internal use only. An edge to us from the state referenced by fromref
554 was dropped. Update the inbound array to remove the given node that used
555 to come to us.
556  
557 =item drop_all_edges()
558  
559 This node is about to be dropped; drop all of our edges. This function
560 does not work if loops exist in the automaton. A solution is to let the
561 edges drop off from non-use and then use a function that has yet to be
562 written to drop nodes with no in or out edges.
563  
564 =item drop_link_to(state)
565  
566 The state is about to be dropped. Remove all links to it.
567  
568 =back
569  
570 Note that the dropping of an edge will not cause a node to be deleted.
571 Only the pruning will so that. This means that we will keep dead-end
572 and unreachable nodes until the pruning drops them from lack of use.
573 The various drop functions should only ensure the consistency of both
574 sides of the link they are operating on.
575  
576 =cut
577  
578 sub visited {
579 my $self = shift;
580 $self->{"visits"}++;
581 }
582  
583 sub visits {
584 my $self = shift;
585 return $self->{"visits"};
586 }
587  
588 sub followed {
589 my $self = shift;
590 my $t = shift;
591 defined($t) or
592 confess *followed{PACKAGE} . "::followed Missing token";
593  
594 if (exists(${$self->{"outbound"}}{$t})) {
595 ${$self->{"out_count"}}{$t}++;
596 } else {
597 carp "Trying to update a counter for the nonexistent token '$t'\n";
598 }
599 }
600  
601 # This is a test func, and has no bearing on reality
602 sub autogen_nums {
603 my $self = shift;
604  
605 my ($min, $max, $outdegree, $count, %counts, $t, $tnv, %novalues);
606  
607 $outdegree = scalar(keys %{$self->{"outbound"}});
608 $min = $outdegree;
609 $max = 0;
610 %novalues = ();
611 for $t (keys %{$self->{"outbound"}}) {
612 $count = $self->out_count($t);
613 $min = $count if $count < $min;
614 $max = $count if $count > $max;
615 $counts{$t} = $count;
616 $tnv = $t;
617 $tnv =~ s/:.*//;
618 $novalues{$tnv}++;
619 }
620 return ($min, $max, $outdegree, $max != 0 ? $outdegree / $max : undef, \%novalues);
621 }
622  
623 sub set_count {
624 my $self = shift;
625 my $t = shift;
626 defined($t) or
627 confess *out_count{PACKAGE} . "::out_count Missing token";
628 my $v = shift;
629 defined($t) or
630 confess *out_count{PACKAGE} . "::out_count Missing count value";
631  
632 ${$self->{"out_count"}}{$t} = $v;
633 }
634  
635 sub out_count {
636 my $self = shift;
637 my $t = shift;
638 defined($t) or
639 confess *out_count{PACKAGE} . "::out_count Missing token";
640  
641 return ${$self->{"out_count"}}{$t};
642 }
643  
644 sub reset_counters {
645 my $self = shift;
646  
647 $self->{"visits"} = 0;
648 map {${$self->{"out_count"}}{$_} = 0} keys %{$self->{"out_count"}};
649 }
650  
651 sub probability {
652 my $self = shift;
653 my $token = shift;
654  
655 my ($sum);
656  
657 exists(${$self->{"out_count"}}{$token}) or return undef;
658  
659 $sum = 0;
660 map { $sum += ${$self->{"out_count"}}{$_}; } keys %{$self->{"out_count"}};
661  
662 return ${$self->{"out_count"}}{$token} / $sum;
663 }
664  
665 sub drop_edges {
666 my $self = shift;
667 my $thresh = shift;
668 defined($thresh) or
669 confess *drop_edges{PACKAGE} . "::drop_edges Missing threshold";
670 my ($t, $v, $n);
671
672 # each can handle deletions of the element with key $t as it iterates
673 $n = 0;
674 while (($t, $v) = each(%{$self->{"out_count"}})) {
675 if ($v < $thresh) {
676 $self->drop_edge($t) if $v < $thresh;
677 $n++;
678 }
679 }
680 return $n;
681 }
682  
683 sub drop_edge {
684 my $self = shift;
685 my $token = shift;
686 defined($token) or
687 confess *drop_edge{PACKAGE} . "::drop_edge Missing token";
688  
689 exists(${$self->{"outbound"}}{$token}) or
690 confess *drop_edge{PACKAGE} . "::drop_edge no outbound edge for $token";
691  
692 my $other = ${$self->{"outbound"}}{$token};
693 $other->dropped_edge($self, $token);
694 delete ${$self->{"outbound"}}{$token};
695 delete ${$self->{"out_count"}}{$token};
696 }
697  
698 sub dropped_edge {
699 my $self = shift;
700 my $from = shift;
701 defined($from) or
702 confess *dropped_edge{PACKAGE} . "::dropped_edge Missing 'from'";
703 $from->isa("IDS::DFAState") or
704 confess *dropped_edge{PACKAGE} . "::dropped_edge 'from' is wrong type";
705 my $token = shift;
706 defined($token) or
707 confess *dropped_edge{PACKAGE} . "::dropped_edge Missing 'token'";
708  
709 my $inbound = $self->{"inbound"};
710 unless (exists(${$inbound}{$from})) {
711 cluck *dropped_edge{PACKAGE} . "::dropped_edge no inbound transition from $from to $self";
712 $from->browse("from: $from");
713 $self->browse("to: $self");
714 exit(1);
715 }
716 my $intokens = ${$inbound}{$from};
717 unless (exists(${$intokens}{$token})) {
718 cluck *dropped_edge{PACKAGE} . "::dropped_edge no inbound transition from $from to $self on $token!";
719 $from->browse("from: $from");
720 $self->browse("to: $self");
721 exit(1);
722 }
723  
724 # delete the entry in the list of tokens
725 delete(${$intokens}{$token});
726  
727 # if there are no tokens left coming from this state, delete the
728 # entry for this state
729 if (scalar(keys(%{$intokens})) == 0) {
730 delete(${$inbound}{$from});
731 }
732 }
733  
734 sub drop_all_edges {
735 my $self = shift;
736 my ($t, $v, $s);
737  
738 while (($t, $v) = each(%{$self->{"outbound"}})) {
739 $self->drop_edge($t);
740 }
741
742 for $s (keys %{$self->{"inbound"}}) {
743 for $t (keys %{${$self->{"inbound"}}{$s}}) {
744 $s->drop_link_to($self, $t);
745 }
746 delete(${$self->{"inbound"}}{$s});
747 }
748 }
749  
750 sub drop_link_to {
751 my $self = shift;
752 my $to = shift;
753 defined($to) or
754 confess *drop_link_to{PACKAGE} . "::drop_link_to Missing 'to'";
755 $to->isa("IDS::DFAState") or
756 confess *drop_link_to{PACKAGE} . "::drop_link_to 'to' is wrong type";
757 my $token = shift;
758 defined($token) or
759 confess *drop_link_to{PACKAGE} . "::drop_link_to Missing 'token'";
760  
761 confess "No link from $self on token $token\n"
762 unless exists(${$self->{"outbound"}}{$token});
763 confess "No link from $self to $to on token $token\n"
764 unless ${$self->{"outbound"}}{$token} eq $to;
765  
766 delete ${$self->{"outbound"}}{$token};
767 delete ${$self->{"out_count"}}{$token};
768 }
769  
770 =head2 Methods for information about this state
771  
772 =over
773  
774 =item in_states()
775  
776 Return a list or reference to an array (depending on if we are called
777 in scalar or list context) which is a list of inbound states.
778  
779 =item in_links()
780  
781 Return the number of inbound links we have.
782  
783 =item out_tokens()
784  
785 Return a list of tokens that cause a transition out of this state.
786  
787 =item out_states()
788  
789 Return a list of states to which this state has transitions.
790  
791 =item out_links()
792  
793 Return the number of outbound edges.
794  
795 =back
796  
797 =cut
798  
799 sub in_states {
800 my $self = shift;
801 my @states = ();
802  
803 if (wantarray) {
804 return keys %{$self->{"inbound"}};
805 } else {
806 @states = keys %{$self->{"inbound"}};
807 return \@states;
808 }
809 }
810  
811 sub in_links {
812 my $self = shift;
813 return scalar(keys %{$self->{"inbound"}});
814 }
815  
816 sub out_tokens {
817 my $self = shift;
818 return keys %{$self->{"outbound"}};
819 }
820  
821 sub out_states {
822 my $self = shift;
823 return values %{$self->{"outbound"}};
824 }
825  
826 sub out_links {
827 my $self = shift;
828  
829 return scalar(keys %{$self->{"outbound"}});
830 }
831  
832 =over
833  
834 =item in_tokens()
835  
836 Return a list of tokens that cause a transition into this state.
837  
838 =back
839  
840 =cut
841  
842 sub in_tokens {
843 my $self = shift;
844  
845 # tokens for a given state $s are
846 # keys(%{${$self->{"inbound"}}{$s}})
847 # return $self->uniq(map {keys(%{${$self->{"inbound"}}{$_}})} keys(%{$self->{"inbound"}}));
848 my @instates = keys(%{$self->{"inbound"}});
849 my @intokens = map {$_->token_to($self)} @instates;
850 return @intokens;
851 }
852  
853 =over
854  
855 =item token_to(state)
856  
857 Return the token that causes a transition to the specified state.
858  
859 =item token_from(state)
860  
861 Return the token that causes a transition from the specified state, or
862 undef if the state claims to have no transition to us.
863  
864 =back
865  
866 =cut
867  
868 sub token_to {
869 my $self = shift;
870 my $state = shift;
871 defined($state) or
872 confess *token_to{PACKAGE} . "::token_to Missing 'state'";
873 $state->isa("IDS::DFAState") or
874 confess *token_to{PACKAGE} . "::token_to 'state' is wrong type";
875  
876 for my $token (keys %{$self->{"outbound"}}) {
877 return $token if ${$self->{"outbound"}}{$token} eq $state;
878 }
879 cluck "IDS::DFAState::token_to returning undef for $state!";
880 return undef;
881 }
882  
883 sub tokens_from {
884 my $self = shift;
885 my $state = shift;
886 defined($state) or
887 confess *token_to{PACKAGE} . "::token_to Missing 'state'";
888 $state->isa("IDS::DFAState") or
889 confess *token_to{PACKAGE} . "::token_to 'state' is wrong type";
890  
891 return keys(%{${$self->{"inbound"}}{$state}});
892 }
893  
894 =over
895  
896 =item next(token)
897  
898 Given a token, return the next state.
899  
900 =back
901  
902 =cut
903  
904 sub next {
905 my $self = shift;
906 my $token = shift;
907 defined($token) or
908 confess *next{PACKAGE} . "::next called without a token";
909  
910 cluck "IDS::DFAState::next returning undef for '$token'" unless
911 (exists(${$self->{"outbound"}}{$token}) &&
912 defined(${$self->{"outbound"}}{$token})) ||
913 $self->{"verbose"} < 3;
914 return ${$self->{"outbound"}}{$token};
915 }
916  
917 =over
918  
919 =item exists_inbound_from(from)
920  
921 Verify that ``from'' is in the list of inbound states.
922  
923 =back
924  
925 =cut
926  
927 sub exists_inbound_from {
928 my $self = shift;
929 my $from = shift or
930 confess *exists_inbound_from{PACKAGE} . "::exists_inbound_from Missing 'from'";
931 $from->isa("IDS::DFAState") or
932 confess *exists_inbound_from{PACKAGE} . "::exists_inbound_from 'from' is wrong type";
933  
934 return exists(${$self->{"inbound"}}{$from});
935 }
936  
937 =over
938  
939 =item compare(otherstate)
940  
941 Compare the current state with another state. The return value is 0 if
942 they are identical, 1 otherwise. This return value may seem odd, but it
943 was inspired by the perl cmp and <=> operators. However, the concept of
944 greater than and less than is not well defined.
945  
946 Two states are considered identical iff:
947  
948 =over
949  
950 =item *
951 They have the same number of outbound states.
952  
953 =item *
954 Every token for one state has a transition in the other state with the
955 same destination.
956  
957 =back
958  
959 =back
960  
961 Note that the inbound states may be different for the compared states
962 and they will still test as identical. This is on purpose to allow the
963 merging to occur.
964  
965 =cut
966  
967 sub compare {
968 my $self = shift;
969 my $other = shift or
970 confess *compare{PACKAGE} . "::compare Missing 'other'";
971 $other->isa("IDS::DFAState") or
972 confess *compare{PACKAGE} . "::compare 'other' is wrong type";
973  
974 if ($self eq $other) {
975 carp "IDS::DFAState: comparison with self";
976 return 0;
977 }
978  
979 my $n = keys %{$self->{"outbound"}};
980 if (keys(%{$other->{"outbound"}}) != $n) {
981 return 1;
982 }
983  
984 # At this point, we know that the number of keys is the same.
985 # Therefore, we just check to see if they are all go to the same
986 # place. We do this by counting the number that do not match, in a
987 # backwards sort of way.
988 map { exists(${$other->{"outbound"}}{$_}) and
989 ${$other->{"outbound"}}{$_} eq ${$self->{"outbound"}}{$_} and
990 $n--;
991 } keys %{$self->{"outbound"}};
992  
993 return $n;
994 }
995  
996  
997 # Tk methods for browsing; only the top-level call is public
998  
999 sub browse {
1000 my $self = shift;
1001 my $label = shift || "(START)";
1002  
1003 my $main = MainWindow->new;
1004  
1005 $self->tk_children($main, $self, $label);
1006 MainLoop;
1007 }
1008  
1009 sub tk_children {
1010 my $self = shift;
1011 my $window = shift;
1012 defined($window) or
1013 confess *tk_children{PACKAGE} . "::tk_children window undefined.";
1014 my $state = shift;
1015 defined($state) or
1016 confess *tk_children{PACKAGE} . "::tk_children state undefined";
1017 my $label = shift;
1018 defined($label) or
1019 confess *tk_children{PACKAGE} . "::tk_children label undefined";
1020  
1021 my ($nodeinfo, $tocanvas, $fromcanvas);
1022  
1023 # remove all items currently in the window; we want a clean window
1024 map { $_->destroy } $window->children;
1025  
1026 $fromcanvas = $self->tk_fromlist($window, $state);
1027 $fromcanvas->grid(-column => 0, -row => 0);
1028  
1029 $nodeinfo = $state->in_links . " inbound states\n";
1030 $nodeinfo .= "$label\n(" . scalar($state) . "); node count " .
1031 $state->visits . "\n";
1032 $nodeinfo .= $state->out_links . " outbound states";
1033 $window->Label(-text => $nodeinfo)->grid(-column => 0, -row => 1);
1034  
1035 $tocanvas = $self->tk_tolist($window, $state);
1036 $tocanvas->grid(-column => 0, -row => 2);
1037  
1038 $window->Button(
1039 -text => "Done.",
1040 -command => sub {$window->destroy}
1041 )->grid(-column => 0, -row => 3);
1042 }
1043  
1044 sub tk_fromlist {
1045 my $self = shift;
1046 my $window = shift;
1047 defined($window) or
1048 confess *tk_children{PACKAGE} . "::tk_children window undefined.";
1049 my $state = shift;
1050 defined($state) or
1051 confess *tk_children{PACKAGE} . "::tk_children state undefined";
1052  
1053 my ($x, $y, $token, $button, $s, $canvas, $n, $coderef);
1054  
1055 $canvas = $self->tk_setup_bcanvas($window);
1056  
1057 $y = 0.1 * $canvas->reqheight;
1058 $x = 0.1 * $canvas->reqwidth;
1059 $n = 1;
1060 for $s ($state->in_states) {
1061 $token = $s->token_to($state) || "UNDEF!";
1062 $coderef = sub { $self->tk_children($window, $s, $token) };
1063 $y = $self->tk_addbutton($canvas, $n++ . ". $s $token", $coderef,
1064 $x, $y);
1065 }
1066 $canvas->configure(-scrollregion => ['0c', '-10p', '0c', ($n * 19) . "p"]);
1067  
1068 return $canvas;
1069 }
1070  
1071 sub tk_tolist {
1072 my $self = shift;
1073 my $window = shift;
1074 defined($window) or
1075 confess *tk_children{PACKAGE} . "::tk_children window undefined.";
1076 my $state = shift;
1077 defined($state) or
1078 confess *tk_children{PACKAGE} . "::tk_children state undefined";
1079  
1080 my ($canvas, $token, $button, $s, $x, $y, $next, $n, $label, $coderef);
1081  
1082 $canvas = $self->tk_setup_bcanvas($window);
1083  
1084 $y = 0.1 * $canvas->reqheight;
1085 $x = 0.1 * $canvas->reqwidth;
1086  
1087 $n = 1;
1088 for $token ($state->out_tokens) {
1089 $next = $state->next($token);
1090 $label = $n++ . ". $next; $token; " . $state->out_count($token);
1091 $coderef = sub { $self->tk_children($window, $next, $token) };
1092 $y = $self->tk_addbutton($canvas, $label, $coderef, $x, $y);
1093 }
1094 $canvas->configure(-scrollregion => ['0c', '-10p', '0c', ($n * 19) . "p"]);
1095 return $canvas;
1096 }
1097  
1098 sub tk_setup_bcanvas {
1099 my $self = shift;
1100 my $window = shift;
1101 defined($window) or
1102 confess *tk_children{PACKAGE} . "::tk_children window undefined.";
1103  
1104 my $canvas;
1105  
1106 $canvas = $window->Scrolled("Canvas",
1107 -scrollbars => "osow",
1108 -width => 600,
1109 -height => 300,
1110 # -scrollregion => ['0c', '-10p', '0c', '1000p']
1111 );
1112 $canvas->CanvasBind('<2>' => [ scanMark => Ev('x'), Ev('y') ]);
1113 $canvas->CanvasBind('<B2-Motion>' => [ scanDragto => Ev('x'), Ev('y') ]);
1114  
1115 return $canvas;
1116 }
1117  
1118 sub tk_addbutton {
1119 my $self = shift;
1120 my $window = shift;
1121 defined($window) or
1122 confess *tk_children{PACKAGE} . "::tk_children window undefined.";
1123 my $buttontext = shift;
1124 defined($buttontext) or
1125 confess *tk_children{PACKAGE} . "::tk_children buttontext undefined.";
1126 my $coderef = shift;
1127 defined($coderef) or
1128 confess *tk_children{PACKAGE} . "::tk_children coderef undefined.";
1129 my $x = shift;
1130 defined($x) or
1131 confess *tk_children{PACKAGE} . "::tk_children x undefined.";
1132 my $y = shift;
1133 defined($y) or
1134 confess *tk_children{PACKAGE} . "::tk_children y undefined.";
1135  
1136 my ($button);
1137  
1138 $button = $window->Button(
1139 -text => $buttontext,
1140 -command => $coderef,
1141 );
1142 $window->createWindow($x, $y,
1143 -width=>$button->reqwidth,
1144 -anchor => "nw",
1145 -window => $button
1146 );
1147 return $y + $button->reqheight;
1148 }
1149  
1150 =head1 AUTHOR INFORMATION
1151  
1152 Copyright 2005-2007, Kenneth Ingham. All rights reserved.
1153  
1154 This library is free software; you can redistribute it and/or modify
1155 it under the same terms as Perl itself.
1156  
1157 Address bug reports and comments to: ids_test at i-pi.com. When sending
1158 bug reports, please provide the versions of IDS::Test.pm, IDS::Algorithm.pm,
1159 IDS::DataSource.pm, the version of Perl, and the name and version of the
1160 operating system you are using. Since Kenneth is a PhD student, the
1161 speed of the response depends on how the research is proceeding.
1162  
1163 =head1 BUGS
1164  
1165 Please report them.
1166  
1167 =head1 SEE ALSO
1168  
1169 L<IDS::Algorithm>, L<DFA>, L<HMM>
1170  
1171 VCG - Visualization of Compiler Graphs, Design Report and User
1172 Documentation, Ref. Compare, USAAR-1049-visual, January 1994, updated
1173 January 1995
1174  
1175 =cut
1176  
1177  
1178 1;