Documentation
¶
Overview ¶
Package reason derives the facts a set of triples implies but does not state: what a transitive predicate reaches, what a symmetric or inverse predicate reads backwards, what a class hierarchy entails, and whatever rules a caller writes.
There is one way a fact gets derived — forward chaining to a fixpoint — so there is one place to look when asking why. Transitivity, symmetry and inverse are rules, not special cases, and a schema contributes the two entailments a hierarchy licenses. Every derived fact names the rule that produced it and the facts it rests on: an assertion nobody can explain is not evidence, and the point of deriving it was to answer for it later.
Example ¶
Reasoning over a small graph: a schema lifts the stated predicate to the one the rule is written in terms of, the rule closes over the result, and the model answers for what it derived.
package main
import (
"context"
"fmt"
"github.com/hanzoai/semantic"
"github.com/hanzoai/semantic/reason"
)
func main() {
facts := []semantic.Triple{
{Subject: "ada", Predicate: "mother", Object: "bob"},
{Subject: "bob", Predicate: "mother", Object: "cy"},
}
closure, err := reason.Engine{
Rules: []reason.Rule{reason.Transitive("parent")},
Prop: reason.Tree{"mother": "parent"},
}.Run(context.Background(), facts)
if err != nil {
fmt.Println(err)
return
}
for _, f := range closure.Derived() {
fmt.Println(f)
}
why, err := closure.Why(reason.Key(semantic.Triple{Subject: "ada", Predicate: "parent", Object: "cy"}))
if err != nil {
fmt.Println(err)
return
}
fmt.Println("because:")
for _, step := range why {
if step.Rule == "" {
fmt.Println(" " + step.String())
continue
}
fmt.Println(" " + step.String() + " by " + step.Rule)
}
}
Output: parent(ada, bob) parent(bob, cy) parent(ada, cy) because: mother(ada, bob) parent(ada, bob) by subproperty mother(bob, cy) parent(bob, cy) by subproperty parent(ada, cy) by transitive parent
Index ¶
- Constants
- Variables
- func Key(t semantic.Triple) string
- type Bind
- type Engine
- type Fact
- type Model
- func (m *Model) All() []Fact
- func (m *Model) Derived() []Fact
- func (m *Model) Fact(key string) (Fact, bool)
- func (m *Model) Given() []Fact
- func (m *Model) Has(t semantic.Triple) bool
- func (m *Model) Match(p Pattern) []Bind
- func (m *Model) Prov(agent string) ([]prov.Entity, []prov.Activity)
- func (m *Model) Triples() []semantic.Triple
- func (m *Model) Why(key string) ([]Fact, error)
- type Pattern
- type Rule
- type Schema
- type Tree
Examples ¶
Constants ¶
const DefaultDepth = 32
DefaultDepth bounds derivation when Engine.Depth is zero. Rules only ever recombine terms that are already present, so a program does reach a fixpoint on its own; the bound is what keeps a large one from running away and what lets a caller ask for shallow entailment on purpose.
const Type = "type"
Type is the predicate read as a statement of class when Engine.Type is empty, and the predicate subclass entailment walks.
Variables ¶
var ( // ErrRule reports a rule that cannot fire: an empty body, a malformed // atom, or a head variable the body never binds. ErrRule = errors.New("reason: bad rule") // ErrDepth reports that derivation stopped at Engine.Depth with facts // still arriving. What was derived up to that point is sound, but the // closure is incomplete. ErrDepth = errors.New("reason: depth exhausted") // ErrMissing reports a key no fact in the model carries. ErrMissing = errors.New("reason: no such fact") )
Functions ¶
func Key ¶
Key names an assertion. Two triples with the same subject, predicate and object are the same claim however each was arrived at, so the key is what the fixpoint stops on and what a premise points at. Terms are used as written: fold names before reasoning if the source spells them differently.
Types ¶
type Engine ¶
type Engine struct {
Rules []Rule
Class Schema // subclass hierarchy: x type C, and C under P, give x type P
Prop Schema // subproperty hierarchy: p(x, y), and p under q, give q(x, y)
Type string // the predicate that states a class; empty means "type"
Depth int // rounds of derivation allowed; zero means DefaultDepth
}
Engine derives what a set of triples implies. The zero value derives nothing, which is the honest answer when it has been given no rule and no schema.
func (Engine) Run ¶
Run derives everything the rules and the schema entail, and returns the model: the facts it was given, then the facts it derived, each carrying its derivation.
A rule that cannot fire is reported before any work is done. Stopping early — at Engine.Depth, or on a cancelled context — returns the partial model alongside the error, because facts already derived are still sound and still explained; a caller that needs the whole closure must check the error rather than the fact count.
Reaching the bound with the last round still adding facts reports ErrDepth whether or not another round would have found anything, since the run stopped before it could tell. Certifying that a closure is complete therefore takes one more round than producing it.
type Fact ¶
type Fact struct {
semantic.Triple
Rule string // what derived it; empty when it was given
Premises []string // keys of the facts it was derived from, in body order
Depth int // rounds of derivation behind it; zero when it was given
}
Fact is a triple and how it got there. A given fact names no rule and rests on nothing; a derived one names both, so it can be answered for.
type Model ¶
type Model struct {
// contains filtered or unexported fields
}
Model is what a run closed to: the facts it was given and the facts they entail, each with its derivation. Order is the order things arrived — given facts first, then derived facts round by round — so two runs over the same input read the same.
func (*Model) Given ¶
Given returns the facts the model started from, as they were accepted: deduplicated, and without any that stated nothing.
func (*Model) Match ¶
Match returns one binding per fact the pattern matches, in model order. It is how a question is asked of the closure: leave a variable where the answer goes.
func (*Model) Prov ¶
Prov renders the model in PROV-O terms: every fact is an Entity named by its Key, and every derived fact was generated by an Activity whose kind is the rule that fired and which used the premises. Given facts have no activity, because this run did not derive them. The agent is the caller's to name and to declare; the record joins whatever prov.Log it is written to without translation.
type Pattern ¶
type Pattern struct{ Subject, Predicate, Object string }
Pattern is a triple with variables. A term beginning with '?' is a variable and binds whatever stands in its place; every other term matches exactly. A variable used twice in one rule must match the same term both times, which is what joins the atoms of a body together.
func (Pattern) Fill ¶
Fill substitutes the bindings into the pattern. It reports false when a variable is unbound, because a triple with a hole in it is not a fact.
func (Pattern) Match ¶
Match extends the bindings with what this pattern binds against a triple, and reports whether the two agree. The bindings passed in are never written to: a failed match must leave the caller's state alone.
type Rule ¶
type Rule struct {
Name string
Body []Pattern
Head Pattern
Score float64 // weight of what it derives; zero means 1
}
Rule derives Head from every binding that satisfies the whole of Body at once. Variables are shared across the rule, so an atom that reuses a variable narrows the match rather than widening it.
A rule with no Name explains itself: what a derived fact records is the rule written out.
func Inverse ¶
Inverse returns the rule from(x, y) gives to(y, x). Being inverse is mutual but a rule is not, so add Inverse(to, from) as well to read the pair in both directions.
func Parse ¶
Parse reads a rule in Horn-clause form:
ancestor(?x, ?y) :- parent(?x, ?z), ancestor(?z, ?y).
An atom is a triple written predicate(subject, object), and a term beginning with '?' is a variable. Datalog's convention of capitalising variables is not used here: the terms are names out of real data and many of them are capitalised already. The trailing period is optional.
Example ¶
Rules can be read from text, which is what makes them configuration rather than code.
package main
import (
"context"
"fmt"
"github.com/hanzoai/semantic"
"github.com/hanzoai/semantic/reason"
)
func main() {
r, err := reason.Parse("grandparent(?x, ?y) :- parent(?x, ?z), parent(?z, ?y).")
if err != nil {
fmt.Println(err)
return
}
m, err := reason.Engine{Rules: []reason.Rule{r}}.Run(context.Background(), []semantic.Triple{
{Subject: "tom", Predicate: "parent", Object: "bob"},
{Subject: "bob", Predicate: "parent", Object: "ann"},
})
if err != nil {
fmt.Println(err)
return
}
for _, b := range m.Match(reason.Pattern{Subject: "tom", Predicate: "grandparent", Object: "?who"}) {
fmt.Println(b["who"])
}
}
Output: ann
func Symmetric ¶
Symmetric returns the rule that reads a predicate both ways: p(x, y) gives p(y, x).
func Transitive ¶
Transitive returns the rule that closes a predicate under composition: p(x, y) and p(y, z) give p(x, z).
type Schema ¶
Schema is the one thing entailment needs from an ontology: the terms a term specialises, nearest first. An unknown term has none. Engine reads a schema twice over, once for classes and once for properties, because those are two hierarchies and conflating them would entail things nobody said.
The method is named for what an ontology already calls this, so a schema that answers Ancestors satisfies it as it stands. Keeping it an interface is what lets reasoning depend on a hierarchy without depending on where the hierarchy is kept.