Knowledge representation and chaining
A knowledge representation makes some relationships explicit and allows others to be inferred. Forward chaining starts from known facts and repeatedly applies supported rules. Backward chaining starts from a query and searches for facts or rules that support it. On the finite positive propositional rule fragment used here, both can answer whether a named atom follows from the KB. Neither method estimates the probability that the atom is true in the real world.
From propositions to predicates and graphs
Propositions can describe one machine at a time, such as low_battery_M1. First-order logic can instead express predicates with arguments: LowBattery(M1) and FailedStart(M1), where M1 is a constant naming an individual. The predicate LowBattery(x) describes a property; ConnectedTo(x,y) describes a relation. A variable such as x ranges over individuals in a domain. A universal rule can be written ∀x ((LowBattery(x) ∧ FailedStart(x)) → CheckBattery(x)). The same rule applies to each individual. The existential statement ∃x LowBattery(x) says at least one individual has a low battery but does not name which one. Quantifier order matters: ∀x ∃y ConnectedTo(x,y) need not mean ∃y ∀x ConnectedTo(x,y).
For a toy domain explicitly restricted to M1 and M2, substitute each name into the universal rule to create two ground rules (rules without variables). Never combine LowBattery(M1) and FailedStart(M2) to infer CheckBattery(M1). Arbitrary first-order domains need not be finite or fully named; unrestricted first-order reasoning is not implemented by the examples. A knowledge graph can store facts as labeled edges, for example M1 —hasPart→ Battery1. A graph is a representation, not automatically a proof system: the meaning of an edge and any inference rules must be defined. Ontologies define concepts and relations more formally; RDF/OWL are possible technologies, not dependencies of this exercise.
Forward chaining: build the closure
Use the three machine facts and two rules from the previous lesson. In round 1, check_battery becomes known. In round 2, review_manual becomes known. In round 3, no new fact can be added. This stable set is the least fixed point, often called the deductive closure for these atoms. Repeatedly applying the rules does not remove facts. The function takes a snapshot of known facts for each round and updates after all rules have been checked, so reversing rule order does not change the final closure.
def forward_chain(facts, rules): known = set(facts) while True: additions = {head for premises, head in rules if all(p in known for p in premises)} - known if not additions: return sorted(known) known.update(additions)
facts = ["low_battery", "failed_start", "manual_available"]rules = [(["check_battery", "manual_available"], "review_manual"), (["low_battery", "failed_start"], "check_battery")]print(forward_chain(facts, rules))print(forward_chain(["failed_start"], rules))Expected output: ['check_battery', 'failed_start', 'low_battery', 'manual_available', 'review_manual'] then ['failed_start']. The output includes the original facts. Every successful round adds at least one previously unknown rule head; there are finitely many heads, so the loop terminates. A cycle A → B, B → A cannot create either fact without some supporting evidence. With A already known, B follows. The repeated full scan favors readability; indexed rule engines can avoid scanning unrelated rules.
Backward chaining: search for a proof
To prove review_manual, find a rule with that head. It requires both check_battery and manual_available. The latter is an initial fact. To prove check_battery, recursively prove low_battery and failed_start; both are initial facts. A goal may have multiple supporting rules (OR between alternatives); each rule requires every premise (AND within that rule). Search succeeds if any rule has all premises supported. An unsupported goal returns False, meaning not derivable in this KB, not necessarily false in the world.
def backward_chain(facts, rules, goal): known = set(facts)
def prove(atom, active): if atom in known: return True if atom in active: return False branch = active | {atom} for premises, head in rules: if head == atom and all(prove(p, branch) for p in premises): return True return False
return prove(goal, set())
facts = ["low_battery", "failed_start", "manual_available"]rules = [(["check_battery", "manual_available"], "review_manual"), (["low_battery", "failed_start"], "check_battery")]print(backward_chain(facts, rules, "review_manual"))print(backward_chain(facts, rules, "replace_battery"))cycle = [(["b"], "a"), (["a"], "b"), (["seed"], "b")]print(backward_chain(["seed"], cycle, "a"))print(backward_chain([], cycle, "a"))Expected output: True, False, True, False on separate lines. For the last two calls, a depends on b and b can depend on a or seed. With seed present, the recursive attempt that returns to a is rejected, but the alternative rule for b still succeeds. Without seed, neither can be supported. The active set contains only ancestors on this proof branch; each recursive call builds a new set. A global visited set or caching failure across different active sets can incorrectly reject a valid proof. No general-purpose caching or proof trace is implemented here.
Choose a reasoning method and state its limits
Forward chaining is useful when many questions will be asked of a stable KB or when new facts should trigger further conclusions. Backward chaining is useful for a small number of goals when much of the KB is irrelevant. Both examples assume finite ground positive rules, finite strings, no function terms, no explicit negation, no changing facts, and no contradictory rule semantics. Both are sound and complete for positive atom entailment in this fragment; the backward method can repeat subproblems and use exponential time, and Python recursion depth limits it to small fixtures. Neither is a full first-order theorem prover, an OWL reasoner, a probabilistic model, or a production expert system.
An expert system combines domain knowledge with a reasoning procedure and typically an explanation or user interface. For a real system, keep rule identifiers, source and timestamps, track which facts support each recommendation, validate contradictory reports, request missing observations, and rederive conclusions after facts are withdrawn. A probabilistic model instead may rank uncertain hypotheses using a validated statistical model. A language model generates text and can phrase an explanation but its fluency is not a proof. A hybrid assistant could retrieve evidence and show a deterministic rule trace, with human review before any consequential action.
Practice: compare both strategies
Using the fixture, remove manual_available. Predict whether check_battery and review_manual are derivable. Add an unconditional rule for manual_available and compare both methods again. Then add an unsupported circular pair of rules; verify that neither creates evidence from nothing. In the chapter project, implement a read-only toy assistant that reports supported versus not established and refuses conflicting input reports. Do not use real machinery or perform actions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Knowledge representation and chaining — understanding check
Apply the rules and explain the scope of the inference.
Which representation correctly uses one rule for every machine?
Why does forward_chain terminate for the finite positive rule base in this lesson?
If one rule with the queried goal as its head cannot be proved, what should backward chaining do before declaring the goal unsupported?
With A → B and B → A, no initial facts, what can the positive engine derive?
What does a False result from backward_chain mean under the stated finite positive-rule contract?