AI-ExpertSystem-Advanced
view release on metacpan or search on metacpan
lib/AI/ExpertSystem/Advanced.pm view on Meta::CPAN
match with the causes of a goal.
L<inference_facts> is a L<AI::ExpertSystem::Advanced::Dictionary>, it will
store the name of the fact, the rule that caused these facts to be copied to
this dictionary, the sign and the algorithm that triggered it.
=cut
has 'inference_facts' => (
is => 'ro',
isa => 'AI::ExpertSystem::Advanced::Dictionary');
=item B<knowledge_db>
The object reference of the knowledge database L<AI::ExpertSystem::Advanced> is
using.
=cut
has 'knowledge_db' => (
is => 'rw',
isa => 'AI::ExpertSystem::Advanced::KnowledgeDB::Base',
required => 1);
=item B<asked_facts>
During the L<backward()> algorithm there will be cases when there's no clarity
if a fact exists. In these cases the L<backward()> will be asking the user
(via automation or real questions) if a fact exists.
Going back to the L<initial_facts> example of symptoms and diseases. Imagine
the algorithm is checking a rule, some of the facts of the rule make a match
with the ones of L<initial_facts> or L<inference_facts> but some wont, for
these I<unsure> facts the L<backward()> will ask the user if a symptom (a fact)
exists. All these asked facts will be stored here.
=cut
has 'asked_facts' => (
is => 'ro',
isa => 'AI::ExpertSystem::Advanced::Dictionary');
=item B<visited_rules>
Keeps a record of all the rules the algorithms have visited and also the number
of causes each rule has.
=cut
has 'visited_rules' => (
is => 'ro',
isa => 'AI::ExpertSystem::Advanced::Dictionary');
=item B<verbose>
my $ai = AI::ExpertSystem::Advanced->new(
viewer_class => 'terminal',
knowledge_db => $yaml_kdb,
initial_facts => ['I'],
verbose => 1);
By default this is turned off. If you want to know what happens behind the
scenes turn this on.
Everything that needs to be debugged will be passed to the L<debug()> method
of your L<viewer>.
=cut
has 'verbose' => (
is => 'rw',
isa => 'Bool',
default => 0);
=item B<viewer>
Is the object L<AI::ExpertSystem::Advanced> will be using for printing what is
happening and for interacting with the user (such as asking the
L<asked_facts>).
This is practical if you want to use a viewer object that is not provided by
L<AI::ExpertSystem::Advanced::Viewer::Factory>.
=cut
has 'viewer' => (
is => 'rw',
isa => 'AI::ExpertSystem::Advanced::Viewer::Base');
=item B<viewer_class>
Is the the class name of the L<viewer>.
You can decide to use the viewers L<AI::ExpertSystem::Advanced::Viewer::Factory>
offers, in this case you can pass the object or only the name of your favorite
viewer.
=cut
has 'viewer_class' => (
is => 'rw',
isa => 'Str',
default => 'terminal');
=item B<found_factor>
In your knowledge database you can give different I<weights> to the facts of
each rule (eg to define what facts have more I<priority>). During the
L<mixed()> algorithm it will be checking what causes are found in the
L<inference_facts> and in the L<asked_facts> dictionaries, then the total
number of matches (or total number of certainity factors of each rule) will
be compared versus the value of this factor, if it's higher or equal then the
rule will be triggered.
You can read the documentation of the L<mixed()> algorithm to know the two
ways this factor can be used.
=cut
has 'found_factor' => (
is => 'rw',
isa => 'Num',
default => '0.5');
=item B<shot_rules>
All the rules that are shot are stored here. This is a hash, the key of each
item is the rule id while its value is the precision time when the rule was
shot.
lib/AI/ExpertSystem/Advanced.pm view on Meta::CPAN
my $question = $self->{'knowledge_db'}->get_question($fact);
if (!defined $question) {
$question = "Do you have $fact?";
}
my @options = qw(Y N U);
my $answer = $self->{'viewer'}->ask($question, @options);
return $answer;
}
=head2 B<get_rule_by_goal($goal)>
Looks in the L<knowledge_db> for the rule that has the given goal. If a rule
is found its number is returned, otherwise undef.
=cut
sub get_rule_by_goal {
my ($self, $goal) = @_;
return $self->{'knowledge_db'}->find_rule_by_goal($goal);
}
=head2 B<forward()>
use AI::ExpertSystem::Advanced;
use AI::ExpertSystem::Advanced::KnowledgeDB::Factory;
my $yaml_kdb = AI::ExpertSystem::Advanced::KnowledgeDB::Factory->new('yaml',
{
filename => 'examples/knowledge_db_one.yaml'
});
my $ai = AI::ExpertSystem::Advanced->new(
viewer_class => 'terminal',
knowledge_db => $yaml_kdb,
initial_facts => ['F', 'J']);
$ai->forward();
$ai->summary();
The forward chaining algorithm is one of the main methods used in Expert
Systems. It starts with a set of variables (known as initial facts) and reads
the available rules.
It will be reading rule by rule and for each one it will compare its causes
with the initial, inference and asked facts. If all of these causes are in the
facts then the rule will be shoot and all of its goals will be copied/converted
to inference facts and will restart reading from the first rule.
=cut
sub forward {
my ($self) = @_;
confess "Can't do forward algorithm with no initial facts" unless
$self->{'initial_facts_dict'};
my ($more_rules, $current_rule) = (1, undef);
while($more_rules) {
$current_rule = $self->{'knowledge_db'}->get_next_rule($current_rule);
# No more rules?
if (!defined $current_rule) {
$self->{'viewer'}->debug("We are done with all the rules, bye")
if $self->{'verbose'};
$more_rules = 0;
last;
}
$self->{'viewer'}->debug("Checking rule: $current_rule") if
$self->{'verbose'};
if ($self->is_rule_shot($current_rule)) {
$self->{'viewer'}->debug("We already shot rule: $current_rule")
if $self->{'verbose'};
next;
}
$self->{'viewer'}->debug("Reading rule $current_rule")
if $self->{'verbose'};
$self->{'viewer'}->debug("More rules to check, checking...")
if $self->{'verbose'};
my $rule_causes = $self->get_causes_by_rule($current_rule);
# any of our rule facts match with our facts to check?
if ($self->compare_causes_with_facts($current_rule)) {
# shoot and start again
$self->shoot($current_rule, 'forward');
# Undef to start reading from the first rule.
$current_rule = undef;
next;
}
}
return 1;
}
=head2 B<backward()>
use AI::ExpertSystem::Advanced;
use AI::ExpertSystem::Advanced::KnowledgeDB::Factory;
my $yaml_kdb = AI::ExpertSystem::Advanced::KnowledgeDB::Factory->new('yaml',
{
filename => 'examples/knowledge_db_one.yaml'
});
my $ai = AI::ExpertSystem::Advanced->new(
viewer_class => 'terminal',
knowledge_db => $yaml_kdb,
goals_to_check => ['J']);
$ai->backward();
$ai->summary();
The backward algorithm starts with a set of I<assumed> goals (facts). It will
start reading goal by goal. For each goal it will check if it exists in the
initial, inference and asked facts (see L<is_goal_in_our_facts()>) for more
information).
=over 4
=item *
If the goal exist then it will be removed from the dictionary, it will also
verify if there are more visited rules to shoot.
If there are still more visited rules to shoot then it will check from what
rule the goal comes from, if it was copied from a rule then this data will
exist. With this information then it will see how many of the causes of this
given rule are still in the L<goals_to_check_dict>.
In case there are still causes of this rule in L<goals_to_check_dict> then the
amount of causes pending will be reduced by one. Otherwise (if the amount is
0) then the rule of this last removed goal will be shoot.
=item *
If the goal doesn't exist in the mentioned facts then the goal will be searched
in the goals of every rule.
In case it finds the rule that has the goal, this rule will be marked (added)
to the list of visited rules (L<visited_rules>) and also all of its causes
will be added to the top of the L<goals_to_check_dict> and it will start
reading again all the goals.
If there's the case where the goal doesn't exist as a goal in the rules then
it will ask the user (via L<ask_about()>) for the existence of it. If user is
not sure about it then the algorithm ends.
=back
=cut
sub backward {
my ($self) = @_;
my ($more_goals, $current_goal, $total_goals) = (
1,
0,
scalar(@{$self->{'goals_to_check'}}));
WAIT_FOR_MORE_GOALS: while($more_goals) {
READ_GOAL: while(my $goal = $self->{'goals_to_check_dict'}->iterate) {
if ($self->is_goal_in_our_facts($goal)) {
$self->{'viewer'}->debug("The goal $goal is in our facts")
if $self->{'debug'};
# Matches with any visiited rule?
my $rule_no = $self->{'goals_to_check_dict'}->get_value(
$goal, 'rule');
# Take out this goal so we don't end with an infinite loop
$self->{'viwer'}->debug("Removing $goal from goals to check")
if $self->{'debug'};
$self->{'goals_to_check_dict'}->remove($goal);
# Update the iterator
$self->{'goals_to_check_dict'}->populate_iterable_array();
# no more goals, what about rules?
if ($self->{'visited_rules'}->size() eq 0) {
$self->{'viewer'}->debug("No more goals to read")
if $self->{'verbose'};
$more_goals = 0;
next WAIT_FOR_MORE_GOALS;
}
if (defined $rule_no) {
my $causes_total = $self->{'visited_rules'}->get_value(
$rule_no, 'causes_total');
my $causes_pending = $self->{'visited_rules'}->get_value(
$rule_no, 'causes_pending');
if (defined $causes_total and defined $causes_pending) {
# No more pending causes for this rule, lets shoot it
if ($causes_pending-1 le 0) {
my $last_rule = $self->remove_last_visited_rule();
if ($last_rule eq $rule_no) {
$self->{'viewer'}->debug("Going to shoot $last_rule")
if $self->{'debug'};
$self->shoot($last_rule, 'backward');
} else {
$self->{'viewer'}->print_error(
"Seems the rule ($rule_no) of goal " .
"$goal is not the same as the last " .
"visited rule ($last_rule)");
$more_goals = 0;
next WAIT_FOR_MORE_GOALS;
}
} else {
$self->{'visited_rules'}->update($rule_no,
{
causes_pending => $causes_pending-1
});
}
}
}
# How many objetives we have? if we are zero then we are done
if ($self->{'goals_to_check_dict'}->size() lt 0) {
$more_goals = 0;
} else {
$more_goals = 1;
}
# Re verify if there are more goals to check
next WAIT_FOR_MORE_GOALS;
} else {
# Ugh, the fact is not in our inference facts or asked facts,
# well, lets find the rule where this fact belongs
my $rule_of_goal = $self->get_rule_by_goal($goal);
if (defined $rule_of_goal) {
$self->{'viewer'}->debug("Found a rule with $goal as a goal")
if $self->{'debug'};
# Causes of this rule
my $rule_causes = $self->get_causes_by_rule($rule_of_goal);
# Copy the causes of this rule to our goals to check
$self->copy_to_goals_to_check($rule_of_goal, $rule_causes);
# We just *visited* this rule, lets check it
$self->visit_rule($rule_of_goal, $rule_causes->size());
# and yes.. we have more goals to check!
$self->{'goals_to_check_dict'}->populate_iterable_array();
$more_goals = 1;
next WAIT_FOR_MORE_GOALS;
} else {
# Ooops, lets ask about this
# We usually get to this case when any of the copied causes
# does not exists as a goal in any of the rules
my $answer = $self->ask_about($goal);
if (
$answer eq FACT_SIGN_POSITIVE or
$answer eq FACT_SIGN_NEGATIVE) {
$self->{'asked_facts'}->append($goal,
{
name => $goal,
sign => $answer,
algorithm => 'backward'
});
} else {
$self->{'viewer'}->debug(
"Don't know of $goal, nothing else to check"
);
return 0;
}
$self->{'goals_to_check_dict'}->populate_iterable_array();
$more_goals = 1;
next WAIT_FOR_MORE_GOALS;
}
}
}
}
return 1;
}
=head2 B<mixed()>
As its name says, it's a mix of L<forward()> and L<backward()> algorithms, it
requires to have at least one initial fact.
The first thing it does is to run the L<forward()> algorithm (hence the need of
at least one initial fact). If the algorithm fails then the mixed algorithm
also ends unsuccessfully.
Once the first I<run> of L<forward()> algorithm happens it starts looking for
any positive inference fact, if only one is found then this ends the algorithm
with the assumption it knows what's happening.
In case no positive inference fact is found then it will start reading the
rules and creating a list of intuitive facts.
For each rule it will get a I<certainty factor> of its causes versus the
initial, inference and asked facts. In case the certainity factor is greater or
equal than L<found_factor> then all of its goals will be copied to the
intuitive facts (eg, read it as: it assumes the goals have something to do with
our first initial facts).
Once all the rules are read then it verifies if there are intuitive facts, if
no facts are found then it ends with the intuition, otherwise it will run the
L<backward()> algorithm for each one of these facts (eg, each fact will be
converted to a goal). After each I<run> of the L<backward()> algorithm it will
verify for any positive inference fact, if just one is found then the algorithm
ends.
At the end (if there are still no positive inference facts) it will run the
L<forward()> algorithm and restart (by looking again for any positive inference
fact).
A good example to understand how this algorithm is useful is: imagine you are
a doctor and know some of the symptoms of a patient. Probably with the first
symptoms you have you can get to a positive conclusion (eg that a patient has
I<X> disease). However in case there's still no clue, then a set of questions
(done by the call of L<backward()>) of symptons related to the initial symptoms
will be asked to the user. For example, we know that that the patient has a
headache but that doesn't give us any positive answer, what if the patient has
flu or another disease? Then a set of these I<related> symptons will be asked
to the user.
=cut
sub mixed {
my ($self) = @_;
if (!$self->forward()) {
$self->{'viewer'}->print_error("The first execution of forward failed");
return 0;
}
use Data::Dumper;
while(1) {
# We are satisfied if only one inference fact is positive (eg, means we
# got to our result)
while(my $fact = $self->{'inference_facts'}->iterate) {
my $sign = $self->{'inference_facts'}->get_value($fact, 'sign');
if ($sign eq FACT_SIGN_POSITIVE) {
$self->{'viewer'}->debug(
"We are done, a positive fact was found"
);
return 1;
}
}
my $intuitive_facts = AI::ExpertSystem::Advanced::Dictionary->new(
stack => []);
my ($more_rules, $current_rule) = (1, undef);
while($more_rules) {
$current_rule = $self->{'knowledge_db'}->get_next_rule($current_rule);
# No more rules?
if (!defined $current_rule) {
$self->{'viewer'}->debug("We are done with all the rules, bye")
if $self->{'verbose'};
$more_rules = 0;
last;
}
# Wait, we already shot this rule?
if ($self->is_rule_shot($current_rule)) {
$self->{'viewer'}->debug("We already shot rule: $current_rule")
if $self->{'verbose'};
next;
}
my $factor = $self->get_causes_match_factor($current_rule);
if ($factor ge $self->{'found_factor'} && $factor lt 1.0) {
# Copy all of the goals (usually only one) of the current rule to
# the intuitive facts
my $goals = $self->get_goals_by_rule($current_rule);
while(my $goal = $goals->iterate_reverse) {
$intuitive_facts->append($goal,
{
name => $goal,
sign => $goals->get_value($goal, 'sign')
});
}
}
}
if ($intuitive_facts->size() eq 0) {
$self->{'viewer'}->debug("Done with intuition") if
$self->{'verbose'};
return 1;
}
$intuitive_facts->populate_iterable_array();
# now each intuitive fact will be a goal
while(my $fact = $intuitive_facts->iterate) {
$self->{'goals_to_check_dict'}->append(
$fact,
{
name => $fact,
sign => $intuitive_facts->get_value($fact, 'sign')
});
$self->{'goals_to_check_dict'}->populate_iterable_array();
print "Running backward for $fact\n";
if (!$self->backward()) {
$self->{'viewer'}->debug("Backward exited");
return 1;
}
# Now we have inference facts, anything positive?
$self->{'inference_facts'}->populate_iterable_array();
while(my $inference_fact = $self->{'inference_facts'}->iterate) {
my $sign = $self->{'inference_facts'}->get_value(
$inference_fact, 'sign');
if ($sign eq FACT_SIGN_POSITIVE) {
$self->{'viewer'}->print(
"Done, a positive inference fact found"
);
return 1;
}
}
}
$self->forward();
}
}
=head2 B<summary($return)>
The main purpose of any expert system is the ability to explain: what is
happening, how it got to a result, what assumption(s) it required to make,
the fatcs that were excluded and the ones that were used.
This method will use the L<viewer> (or return the result) in YAML format of all
the rules that were shot. It will explain how it got to each one of the causes
so a better explanation can be done by the L<viewer>.
If C<$return> is defined (eg, it got any parameter) then the result wont be
passed to the L<viewer>, instead it will be returned as a string.
=cut
sub summary {
my ($self, $return) = @_;
# any facts we found via inference?
if (scalar @{$self->{'inference_facts'}->{'stack'}} eq 0) {
$self->{'viewer'}->print_error("No inference was possible");
} else {
my $summary = {};
# How the rules started being shot?
my $order = 1;
# So, what rules we shot?
foreach my $shot_rule (sort(keys %{$self->{'shot_rules'}})) {
$summary->{'rules'}->{$shot_rule} = {
order => $order,
};
$order++;
# Get the causes and goals of this rule
my $causes = $self->get_causes_by_rule($shot_rule);
$causes->populate_iterable_array();
while(my $cause = $causes->iterate) {
# How we got to this cause? Is it an initial fact,
# an inference fact? or by forward algorithm?
my ($method, $sign, $algorithm);
if ($self->{'asked_facts'}->find($cause)) {
$method = 'Question';
$sign = $self->{'asked_facts'}->get_value($cause, 'sign');
$algorithm = $self->{'asked_facts'}->get_value($cause, 'algorithm');
( run in 0.409 second using v1.01-cache-2.11-cpan-9288abcf80b )