reason

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

View Source
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.

View Source
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

View Source
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

func Key(t semantic.Triple) string

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 Bind

type Bind map[string]string

Bind maps a variable name, written without its leading '?', to the term it matched.

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

func (e Engine) Run(ctx context.Context, facts []semantic.Triple) (*Model, error)

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.

func (Fact) Key

func (f Fact) Key() string

Key names the assertion this fact carries.

func (Fact) String

func (f Fact) String() string

String renders the fact as predicate(subject, object).

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) All

func (m *Model) All() []Fact

All returns every fact in the model, given first, then derived.

func (*Model) Derived

func (m *Model) Derived() []Fact

Derived returns only what the run added, in the order it was derived.

func (*Model) Fact

func (m *Model) Fact(key string) (Fact, bool)

Fact returns the fact a key names.

func (*Model) Given

func (m *Model) Given() []Fact

Given returns the facts the model started from, as they were accepted: deduplicated, and without any that stated nothing.

func (*Model) Has

func (m *Model) Has(t semantic.Triple) bool

Has reports whether the model holds a claim, given or derived.

func (*Model) Match

func (m *Model) Match(p Pattern) []Bind

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

func (m *Model) Prov(agent string) ([]prov.Entity, []prov.Activity)

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.

func (*Model) Triples

func (m *Model) Triples() []semantic.Triple

Triples returns the derived facts as triples, ready to fold into a graph. The derivation stays behind in the model: a triple carries no room for it.

func (*Model) Why

func (m *Model) Why(key string) ([]Fact, error)

Why returns the derivation of a fact: everything it rests on, leaves first, ending with the fact itself. A given fact rests on nothing and so explains itself in one line. Each fact appears once however many derivations reached it.

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

func (p Pattern) Fill(b Bind) (semantic.Triple, bool)

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

func (p Pattern) Match(t semantic.Triple, b Bind) (Bind, bool)

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.

func (Pattern) String

func (p Pattern) String() string

String renders the pattern as predicate(subject, object), the form Parse reads.

func (Pattern) Vars

func (p Pattern) Vars() []string

Vars lists the variables in the pattern, subject first, without repeats.

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

func Inverse(from, to string) Rule

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

func Parse(s string) (Rule, error)

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

func Symmetric(pred string) Rule

Symmetric returns the rule that reads a predicate both ways: p(x, y) gives p(y, x).

func Transitive

func Transitive(pred string) Rule

Transitive returns the rule that closes a predicate under composition: p(x, y) and p(y, z) give p(x, z).

func (Rule) Check

func (r Rule) Check() error

Check reports whether the rule can fire: something to match, something to derive, and no head variable the body leaves unbound. An unbound head variable would derive a fact with a hole in it, which is why this is an error and not a warning.

func (Rule) String

func (r Rule) String() string

String renders the rule in the Horn-clause form Parse reads.

type Schema

type Schema interface {
	Ancestors(term string) []string
}

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.

type Tree

type Tree map[string]string

Tree is a hierarchy written child to parent, the common case and the smallest thing that satisfies Schema.

func (Tree) Ancestors

func (t Tree) Ancestors(term string) []string

Ancestors walks the parents of a term, nearest first. A cycle stops the walk rather than hanging it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL