? users online
  • Logout
    • Open hangout
    • Open chat for current file
<div class="notebook">

<div class="nb-cell markdown" name="intro">
# Lab: Reasoning Systems

Course: **Human-Centered Artificial Intelligence** @ [Jagiellonian University](https://uj.edu.pl/)&lt;br&gt;
Timing: **60 minutes**&lt;br&gt;
Author: Krzysztof Kutt &amp; [GEIST Research Group](https://geist.re)

Our Motto: **Thinking, not only clicking** - predict behaviour before running an experiment. During checkpoints, explain the results rather than only showing the output.

## Sources and licence

This notebook adapts the treatment of unification, forward chaining, backward chaining, and logic programming from **Artificial Intelligence: A Modern Approach**, 4th ed., especially Sections 9.2-9.4. The practical environment is [SWISH](https://swish.swi-prolog.org/), the browser interface to SWI-Prolog.

The notebook adds original examples, experiments, and checkpoint prompts. The cultural-heritage knowledge base is fictional and deliberately small.

## How to use this notebook

- A **program cell** defines facts and rules (it is not executed).
- A **query cell** contains a goal to execute. Do not write the `?-` prompt.
- Variables begin with an uppercase letter or `_`; atoms normally begin with lowercase letters.
- End every fact, rule, and query with a full stop.
- Request more solutions to observe backtracking.
- Each later experiment provides the local facts and rules it needs, so it can be run independently.
</div>

<div class="nb-cell markdown" name="quick">
## Prolog quick reference

```prolog
% Fact
created_by(starry_night, van_gogh).

% Rule
movement_of(Object, Movement) :-
    created_by(Object, Creator),
    associated_with(Creator, Movement).
```

Useful notation:

- comma means conjunction;
- `_` is an anonymous variable;
- `\+ Goal` is negation as failure;
- `X \= Y` succeeds when the terms cannot be unified.
</div>

<div class="nb-cell markdown" name="segment1">
# Segment 1: Facts, rules, queries, and unification

**How can a program answer questions that were not stored as explicit facts?**

Predict each result before running the query.
</div>

<div class="nb-cell program" name="kb1">
object(starry_night).
object(sunflowers).
object(guernica).
object(the_scream).
object(girl_with_a_pearl_earring).
object(the_persistence_of_memory).

created_by(starry_night, van_gogh).
created_by(sunflowers, van_gogh).
created_by(guernica, picasso).
created_by(the_scream, munch).
created_by(girl_with_a_pearl_earring, vermeer).
created_by(the_persistence_of_memory, dali).

associated_with(van_gogh, post_impressionism).
associated_with(picasso, cubism).
associated_with(munch, expressionism).
associated_with(vermeer, dutch_golden_age).
associated_with(dali, surrealism).

depicts(starry_night, landscape).
depicts(sunflowers, plants).
depicts(guernica, war).
depicts(the_scream, anxiety).
depicts(girl_with_a_pearl_earring, portrait).
depicts(the_persistence_of_memory, time).

held_by(starry_night, moma).
held_by(guernica, reina_sofia).
held_by(the_scream, national_museum_oslo).
held_by(girl_with_a_pearl_earring, mauritshuis).
held_by(the_persistence_of_memory, moma).

located_in(moma, new_york).
located_in(reina_sofia, madrid).
located_in(national_museum_oslo, oslo).
located_in(mauritshuis, the_hague).

movement_of(Object, Movement) :-
    created_by(Object, Creator),
    associated_with(Creator, Movement).

city_of(Object, City) :-
    held_by(Object, Museum),
    located_in(Museum, City).

museum_in(City, Museum) :- located_in(Museum, City).
</div>

<div class="nb-cell markdown" name="exp11">
### Experiment 1.1: Query stored and derived knowledge

Compare directly stored facts with conclusions obtained through rules.
</div>

<div class="nb-cell query" name="q11a">
created_by(starry_night, Who).
</div>

<div class="nb-cell query" name="q11b">
created_by(Object, van_gogh).
</div>

<div class="nb-cell query" name="q11c">
movement_of(guernica, Movement).
</div>

<div class="nb-cell query" name="q11d">
city_of(Object, new_york).
</div>

<div class="nb-cell markdown" name="exp12">
### Experiment 1.2: Argument order is part of the representation

Predict why one query succeeds and the other fails.
</div>

<div class="nb-cell query" name="q12a">
museum_in(new_york, Museum).
</div>

<div class="nb-cell query" name="q12b">
museum_in(moma, new_york).
</div>

<div class="nb-cell markdown" name="exp13">
### Experiment 1.3: Unification

Unification looks for one consistent substitution that makes two terms identical.

Pay particular attention to **repeated variables**. One variable must receive the same value wherever it occurs.

Before running each query, predict:

1. whether the terms unify;
2. which values are assigned to variables;
3. why unification fails when no consistent substitution exists.
</div>

<div class="nb-cell query" name="q13a">
created_by(Object, van_gogh) = created_by(starry_night, Creator).
</div>

<div class="nb-cell query" name="q13b">
work(Object, Object) = work(starry_night, sunflowers).
</div>

<div class="nb-cell query" name="q13c">
work(Object, Object) = work(starry_night, starry_night).
</div>

<div class="nb-cell query" name="q13d">
work(First, Second) = work(starry_night, sunflowers).
</div>

<div class="nb-cell query" name="q13e">
relation(X, f(X)) = relation(a, f(a)).
</div>

<div class="nb-cell markdown" name="exp13note">
#### Interpretation

In the second query, `Object` occurs twice. It would have to be both `starry_night` and `sunflowers`, which is impossible because these are different atoms.

The comparisons show that:

- one variable represents one value within a substitution;
- different variables may receive different values;
- a repeated variable expresses an equality requirement between positions.
</div>

<div class="nb-cell markdown" name="segment2">
# Segment 2: Data-driven forward chaining

**What can be derived by repeatedly applying rules to available facts?**

The rules below are stored as data using `fc_rule(Head, BodyList)`. The engine repeatedly adds new conclusions until no rule can add another fact. This finite, function-free fragment is Datalog-like.
</div>

<div class="nb-cell program" name="fcengine">
% Explicit input facts
fc_fact(created_by(starry_night, van_gogh)).
fc_fact(created_by(sunflowers, van_gogh)).
fc_fact(created_by(guernica, picasso)).
fc_fact(associated_with(van_gogh, post_impressionism)).
fc_fact(associated_with(picasso, cubism)).
fc_fact(held_by(starry_night, moma)).
fc_fact(held_by(guernica, reina_sofia)).
fc_fact(located_in(moma, new_york)).
fc_fact(located_in(reina_sofia, madrid)).
fc_fact(depicts(starry_night, landscape)).
fc_fact(depicts(guernica, war)).

% Rules stored as data
fc_rule(movement_of(Object, Movement),
        [created_by(Object, Creator), associated_with(Creator, Movement)]).
fc_rule(city_of(Object, City),
        [held_by(Object, Museum), located_in(Museum, City)]).
fc_rule(movement_example(Movement, Object),
        [movement_of(Object, Movement), depicts(Object, _Topic)]).

% A rule body is true when every goal matches a known fact.
fc_body_true([], _Known).
fc_body_true([Goal|Goals], Known) :-
    member(Goal, Known),
    fc_body_true(Goals, Known).

% Collect conclusions available now but not already known.
fc_new_facts(Known, NewFacts) :-
    findall(Head,
            ( fc_rule(Head, Body),
              fc_body_true(Body, Known),
              \+ memberchk(Head, Known)
            ),
            RawFacts),
    sort(RawFacts, NewFacts).

% Start with explicit facts and repeat rounds until the fixed point.
forward_chain(Rounds, Closure) :-
    findall(Fact, fc_fact(Fact), RawFacts),
    sort(RawFacts, InitialFacts),
    fc_rounds(InitialFacts, [], Rounds, Closure).

fc_rounds(Known, Acc, Rounds, Closure) :-
    fc_new_facts(Known, NewFacts),
    ( NewFacts == [] -&gt;
        reverse(Acc, Rounds),
        Closure = Known
    ; append(Known, NewFacts, Combined),
      sort(Combined, UpdatedKnown),
      fc_rounds(UpdatedKnown, [NewFacts|Acc], Rounds, Closure)
    ).
</div>

<div class="nb-cell markdown" name="exp21">
### Experiment 2.1: Build the closure round by round

Forward chaining starts with the explicit `fc_fact/1` statements.

- A **round** contains facts derived for the first time in that iteration.
- The **closure** contains all explicit facts and every fact derived in all rounds.
- A **fixed point** is reached when another round adds nothing new.

Predict which conclusions can be derived directly and which require an earlier derived conclusion.
</div>

<div class="nb-cell query" name="q21">
forward_chain(Rounds, Closure).
</div>

<div class="nb-cell markdown" name="exp21note">
`movement_of/2` and `city_of/2` appear in the first round. `movement_example/2` appears in the second because it needs a derived `movement_of/2` fact.

The rounds are the inference history. Their union with the initial facts is the closure.
</div>

<div class="nb-cell markdown" name="exp22">
### Experiment 2.2: Ask questions about the closure

`forward_chain/2` computes the closure. `member/2` then checks whether a selected conclusion belongs to it. A conclusion exists only when every premise of its rule is supported.
</div>

<div class="nb-cell query" name="q22a">
forward_chain(_Rounds, Closure), member(movement_of(starry_night, Movement), Closure).
</div>

<div class="nb-cell query" name="q22b">
forward_chain(_Rounds, Closure), member(city_of(guernica, City), Closure).
</div>

<div class="nb-cell query" name="q22c">
forward_chain(_Rounds, Closure), member(city_of(sunflowers, City), Closure).
</div>

<div class="nb-cell markdown" name="exp22note">
The final query correctly returns `false`. No `held_by(sunflowers, Museum)` fact is available, so no city can be derived.

Here, `false` means that the conclusion is absent from the closure. It does not prove that the artwork has no location in the real world.
</div>

<div class="nb-cell markdown" name="exp23">
### Experiment 2.3: Add another inference step

The new rule uses `movement_example/2`, which is already derived in Round 2. Predict the round in which `notable_example/1` appears, then inspect `Rounds` and `Closure`.
</div>

<div class="nb-cell program" name="fcengine_ext">
% Complete local setup for this experiment
fc_fact(created_by(starry_night, van_gogh)).
fc_fact(created_by(sunflowers, van_gogh)).
fc_fact(created_by(guernica, picasso)).
fc_fact(associated_with(van_gogh, post_impressionism)).
fc_fact(associated_with(picasso, cubism)).
fc_fact(depicts(starry_night, landscape)).
fc_fact(depicts(guernica, war)).

fc_rule(movement_of(Object, Movement),
        [created_by(Object, Creator), associated_with(Creator, Movement)]).
fc_rule(movement_example(Movement, Object),
        [movement_of(Object, Movement), depicts(Object, _Topic)]).
fc_rule(notable_example(Object),
        [movement_example(_Movement, Object)]).

fc_body_true([], _Known).
fc_body_true([Goal|Goals], Known) :-
    member(Goal, Known), fc_body_true(Goals, Known).
fc_new_facts(Known, NewFacts) :-
    findall(Head,
            ( fc_rule(Head, Body), fc_body_true(Body, Known),
              \+ memberchk(Head, Known) ),
            RawFacts),
    sort(RawFacts, NewFacts).
forward_chain(Rounds, Closure) :-
    findall(Fact, fc_fact(Fact), RawFacts), sort(RawFacts, Initial),
    fc_rounds(Initial, [], Rounds, Closure).
fc_rounds(Known, Acc, Rounds, Closure) :-
    fc_new_facts(Known, New),
    ( New == [] -&gt; reverse(Acc, Rounds), Closure = Known
    ; append(Known, New, Combined), sort(Combined, Updated),
      fc_rounds(Updated, [New|Acc], Rounds, Closure)
    ).
</div>

<div class="nb-cell query" name="q23">
forward_chain(Rounds, Closure), member(notable_example(Object), Closure).
</div>

<div class="nb-cell markdown" name="exp23note">
`notable_example/1` appears in Round 3: Round 1 derives `movement_of/2`, Round 2 derives `movement_example/2`, and Round 3 applies the new rule.
</div>

<div class="nb-cell markdown" name="checkpoint1">
## Checkpoint 1: Representation, unification, and forward chaining

Present a compact account containing:

1. the difference between a fact, a rule, and a query;
2. one successful and one failed unification;
3. why the repeated-variable query fails;
4. how `movement_of/2` is derived;
5. the difference between a round and the closure;
6. one conclusion requiring several rounds;
7. why this finite Datalog-style program terminates;
8. one limitation of the forward-chaining engine.
</div>

<div class="nb-cell markdown" name="segment3">
# Segment 3: Goal-directed backward chaining and Prolog execution

**How does Prolog work backward from a query to the facts needed to prove it?**

Each experiment contains its own local program and can be run independently.
</div>

<div class="nb-cell markdown" name="exp31">
### Experiment 3.1: Follow a backward proof

Before running the query, expand `city_of(starry_night, City)` into the smaller goals required by its rule.
</div>

<div class="nb-cell program" name="kb31">
held_by(starry_night, moma).
located_in(moma, new_york).

city_of(Object, City) :-
    held_by(Object, Museum),
    located_in(Museum, City).
</div>

<div class="nb-cell query" name="q31">
city_of(starry_night, City).
</div>

<div class="nb-cell markdown" name="exp31note">
Prolog replaces the query with `held_by(starry_night, Museum)` and `located_in(Museum, City)`. The first goal binds `Museum = moma`; the second binds `City = new_york`.
</div>

<div class="nb-cell markdown" name="exp32">
### Experiment 3.2: Choice points and backtracking

Two objects are related when they share a creator or a holding institution. Request all answers and inspect the alternative proof paths.
</div>

<div class="nb-cell program" name="kb32">
created_by(starry_night, van_gogh).
created_by(sunflowers, van_gogh).
held_by(starry_night, moma).
held_by(the_persistence_of_memory, moma).

related(Object1, Object2) :-
    created_by(Object1, Creator),
    created_by(Object2, Creator),
    Object1 \= Object2.
related(Object1, Object2) :-
    held_by(Object1, Museum),
    held_by(Object2, Museum),
    Object1 \= Object2.
</div>

<div class="nb-cell query" name="q32a">
related(starry_night, Other).
</div>

<div class="nb-cell query" name="q32b">
setof(Other, related(starry_night, Other), UniqueOthers).
</div>

<div class="nb-cell markdown" name="exp32note">
Prolog explores one clause and later backtracks to alternative clauses or facts. `setof/3` collects sorted, distinct answers; it changes presentation, not the available proofs.
</div>

<div class="nb-cell markdown" name="exp33">
### Experiment 3.3: Recursion and termination

Compare a recursive relation that first follows an edge with a left-recursive version that recurses before choosing an edge.
</div>

<div class="nb-cell program" name="kb33">
influenced(impressionism, post_impressionism).
influenced(post_impressionism, expressionism).
influenced(cubism, surrealism).
influenced(expressionism, modernism).
influenced(surrealism, modernism).

influences(X, Y) :- influenced(X, Y).
influences(X, Y) :- influenced(X, Z), influences(Z, Y).

bad_influences(X, Y) :- bad_influences(X, Z), influenced(Z, Y).
bad_influences(X, Y) :- influenced(X, Y).
</div>

<div class="nb-cell query" name="q33a">
influences(post_impressionism, modernism).
</div>

<div class="nb-cell query" name="q33b">
setof(Movement, influences(Movement, modernism), Movements).
</div>

<div class="nb-cell query" name="q33c">
catch(call_with_time_limit(1, bad_influences(post_impressionism, modernism)), Error, true).
</div>

<div class="nb-cell markdown" name="exp33note">
The first definition reaches a direct edge before recurring. The left-recursive definition may follow an infinite branch under Prolog's depth-first execution. Logical intent alone does not guarantee termination.
</div>

<div class="nb-cell markdown" name="segment4">
# Segment 4: Missing knowledge, negation, and explanations

**Does a failed query mean that its conclusion is false?**

Prolog uses negation as failure: `\+ Goal` succeeds when Prolog cannot prove `Goal`. This is an operational rule, not evidence that the opposite is true in the real world.
</div>

<div class="nb-cell markdown" name="exp41">
### Experiment 4.1: Missing knowledge is not explicit falsity

There is no recorded holding institution for `sunflowers`. Predict both results.
</div>

<div class="nb-cell program" name="kb41">
object(starry_night).
object(sunflowers).
object(guernica).
object(the_scream).
object(girl_with_a_pearl_earring).
object(the_persistence_of_memory).
held_by(starry_night, moma).
held_by(guernica, reina_sofia).
held_by(the_scream, national_museum_oslo).
held_by(girl_with_a_pearl_earring, mauritshuis).
held_by(the_persistence_of_memory, moma).
</div>

<div class="nb-cell query" name="q41a">
held_by(sunflowers, Museum).
</div>

<div class="nb-cell query" name="q41b">
\+ held_by(sunflowers, _Museum).
</div>

<div class="nb-cell markdown" name="exp41note">
The first query cannot be proved. The second succeeds because the first fails. The careful reading is: no holding institution can be proved from this program.
</div>

<div class="nb-cell markdown" name="exp42">
### Experiment 4.2: Bind variables before negation

The first query asks whether no object at all is held by MoMA. The second selects each known object before testing that object.
</div>

<div class="nb-cell program" name="kb42">
object(starry_night).
object(sunflowers).
object(guernica).
object(the_scream).
object(girl_with_a_pearl_earring).
object(the_persistence_of_memory).
held_by(starry_night, moma).
held_by(guernica, reina_sofia).
held_by(the_scream, national_museum_oslo).
held_by(girl_with_a_pearl_earring, mauritshuis).
held_by(the_persistence_of_memory, moma).
</div>

<div class="nb-cell query" name="q42a">
\+ held_by(Object, moma).
</div>

<div class="nb-cell query" name="q42b">
object(Object), \+ held_by(Object, moma).
</div>

<div class="nb-cell markdown" name="exp42note">
Negation with unbound variables is often misleading. Bind the relevant object first when you mean “which known objects cannot be proved to have this property?”
</div>

<div class="nb-cell markdown" name="exp43">
### Experiment 4.3: Return an explanation with the answer

The final argument records which rule and value justified the recommendation.
</div>

<div class="nb-cell program" name="kb43">
created_by(the_persistence_of_memory, dali).
associated_with(dali, surrealism).
depicts(starry_night, landscape).
depicts(the_persistence_of_memory, time).

movement_of(Object, Movement) :-
    created_by(Object, Creator),
    associated_with(Creator, Movement).

interested_in(alex, time).
interested_in(alex, surrealism).

recommended(Object, User, same_topic(Topic)) :-
    interested_in(User, Topic), depicts(Object, Topic).
recommended(Object, User, related_movement(Movement)) :-
    interested_in(User, Movement), movement_of(Object, Movement).
</div>

<div class="nb-cell query" name="q43">
recommended(Object, alex, Explanation).
</div>

<div class="nb-cell markdown" name="exp43note">
The reason term is not a full proof tree, but it shows that a reasoning system can return a structured justification rather than only `true` or `false`.
</div>

<div class="nb-cell markdown" name="checkpoint2">
## Checkpoint 2: Backward chaining, control, and explanations

Present a compact account containing:

1. how `city_of(starry_night, City)` is reduced to smaller goals;
2. where choice points arise in `related/2`;
3. how backtracking produces another answer;
4. why `influences/2` terminates;
5. why `bad_influences/2` may not terminate;
6. why failed proof is not equivalent to explicit real-world falsity;
7. why variables should usually be bound before negation as failure;
8. how the explanation term relates to the rule that produced the recommendation.
</div>

<div class="nb-cell markdown" name="md1">
Complete one controlled modification:

- add one alternative proof;
- add one influence edge;
- reverse two goals;
- change clause order;
- add one cycle;
- add the missing collection fact for `sunflowers`;
- add one recommendation rule.
</div>

<div class="nb-cell markdown" name="md2">
Predict the effect before running it. Keep unrelated clauses unchanged. Compare the relevant query before and after the change.
</div>

<div class="nb-cell program" name="checkpoint2work">
% CHECKPOINT 2: Add your controlled modification here.
% Use a new predicate name if you want to preserve the original version.
</div>

<div class="nb-cell query" name="checkpoint2query">
true.
</div>

<div class="nb-cell markdown" name="advanced">
# Optional advanced tasks

## Advanced task 1: Compare reasoning effort

Instrument the forward-chaining engine and one backward-chaining program to count rule applications, tested facts, derived conclusions, or attempted goals. Compare three questions: a direct conclusion, a multi-step conclusion, and an unprovable conclusion. Explain when materializing the closure is worth its initial cost.

## Advanced task 2: Return a complete proof tree

Extend the explanation mechanism so that it recursively distinguishes facts from rule-supported conclusions, for example:

```prolog
proof(city_of(starry_night, new_york),
      [fact(held_by(starry_night, moma)),
       fact(located_in(moma, new_york))]).
```

Test at least two successful queries and one failed query. Explain what information your proof structure preserves and omits.

## Advanced task 3: Make recursion safe in a cyclic graph

Add a cycle to the influence graph. Implement `safe_influences/2` using an additional list of visited movements, so that one movement is not visited twice on the same path. Compare the original and cycle-safe predicates on reachable and unreachable queries.
</div>

</div>