solver

package
v0.0.0-...-7578981 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2023 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package solver contains solving, constraints and context logic.

Index

Constants

View Source
const (
	RED    = "\x1b[31m"
	GREEN  = "\x1b[32m"
	BLUE   = "\x1b[34m"
	YELLOW = "\x1b[33m"
	CYAN   = "\x1b[36m"

	RESET = "\x1b[0m"
)
View Source
const MAX_DEPTH = 300 // maximum depth control for state/uids
View Source
const MIN_DEPTH = 30 // minimum depth control for state/uids
View Source
const VERSION = "0.6.5"

Variables

View Source
var (
	ErrPred = fmt.Errorf("predicate cannot apply")
	ErrDiff = fmt.Errorf("diff predicate fails")
)
View Source
var AtomPredicate = map[string]bool{
	"!":     true,
	"fail":  true,
	"rules": true,
}

Known atomic predicates.

View Source
var CompPredicateMap = map[string]int{
	"rule":    -1,
	"query":   -1,
	"dot":     -1,
	"and":     2,
	"or":      2,
	"number":  1,
	"integer": 1,
	"load":    -1,
	"print":   -1,
	"eq":      2,
	"diff":    2,
}

Known compound predicates with their imperative arity. A compund predicate MUST be a CompoundTerm. Arity set to -1 means it can vary. Assumes only canonical form. Constant values are eliminated (numbers, strings ...) as well as underscore.

View Source
var ErrDepthControl = fmt.Errorf("maximum allowed nesting depth reached - truncating search tree")
View Source
var ErrInvalidConstraintEmptyRange = fmt.Errorf("invalid constraint, specified range is empty")
View Source
var ErrInvalidConstraintNaN = fmt.Errorf("invalid constraint (NaN)")
View Source
var ErrInvalidConstraintSimplify = fmt.Errorf("incompatible constraints detected when simplifying")
View Source
var ErrNaN = fmt.Errorf("not a number (NaN)")
View Source
var ErrNotImplemented = fmt.Errorf(RED + "not implemented" + RESET) // should be removed later on //TODO
View Source
var ErrPositiveOccur = fmt.Errorf("positive occur check")
View Source
var ErrUnificationImpossible = fmt.Errorf("unification impossible")
View Source
var ZeroNumber, OneNumber = parser.ZeroNumber, parser.OneNumber

useful numbers

Functions

func FindNextRule

func FindNextRule(st *State) (*State, Term)

Find the next rule applicable in the current context. Returns an alpha-transformed rule. Only consider rules whose index is higher or equal to st.NextRule New State is created if a choice was made between multiple applicable rules. Return nil if no rule available. Will enforce the constraints of MAX_DEPTH when doing alpha-substitution.

func FindVar

func FindVar(v Variable, t Term) (found bool)

Find if Variable exists in Term

func FindVars

func FindVars(t Term) map[Variable]bool

Get the set of all vars in Term

func Repl

func Repl()

convenience entry point, same as NewSession().Repl()

func SameStructure

func SameStructure(t1, t2 Term) bool

Does the structure of both terms seem to match and should be considered, regardless of potential constraints . It may not be unifiable later. Do not check too deep into the structure, since predicates or expressions can be hidden inside that will disappear later. Float and Integer could unify if same float64 value. The goal is to eliminate early non match.

func SortConstraintAscending

func SortConstraintAscending(constraints []Constraint)

compare constraints based on their variable. Panic if nil constraint.

func SortConstraintsDescending

func SortConstraintsDescending(constraints []Constraint)

compare constraints based on their variable. Panic if nil constraint.

Types

type Atom

type Atom = parser.Atom

type CompoundTerm

type CompoundTerm = parser.CompoundTerm

type Constraint

type Constraint interface {
	// deep copy
	Clone() Constraint
	// Check will check validity of constraint, clean it or simplify it.
	// It will return the constraint itself,  possibly modified, or nil if constraint should be ignored (
	// CAUTION : return can be nil, despite a nil error !
	// An error means the constraint is impossible to satisfy (e.g. positive occur check, empty number interval, ...)
	Check() (Constraint, error)
	// simplify c, taking into account the calling constraint (unchanged).
	// if error, other results are not significant and should not be used.
	// If changed, replace c by all of cc (possibly empty, to just suppress c).
	// If changed is false, cc has no meaning.
	// Input constraints MUST BE checked
	// Output constraints are checkedutput.
	Simplify(c Constraint) (cc []Constraint, changed bool, err error)
	String() string
	GetV() Variable // Get (a copy of) the main variable forthe constraint
}

a Constraint is immutable

func CheckAddConstraint

func CheckAddConstraint(cc []Constraint, cl ...Constraint) ([]Constraint, error)

Check (individual), and Add a constraint to the list, return error for backtracking. Simplification not performed. Avoid later workload by notadding nil constraints.

func FilterSolutions

func FilterSolutions(cc []Constraint) []Constraint

Filter constraints to display, keeping only 0 Nsp.

func SimplifyConstraints

func SimplifyConstraints(constraints []Constraint) ([]Constraint, error)

Attempt to simplify constraint list. Return error if an incompatibility was detected. Constraints are supposed to have been checked before calling this function. Its is a garantee that returned constraints are checked.

func Unify

func Unify(cList []Constraint, head Term, goal Term) ([]Constraint, error)

Unify recursively unifies rule head and goal. We avoid state directly, by just appending to a list of constraints. Simplification will occur later. No predicates are handled here. No backtracking is done.

type Number

type Number = parser.Number

type Session

type Session struct {
	// contains filtered or unexported fields
}

Set of rules that can be applied in a state

func NewSession

func NewSession() *Session

func (*Session) AddRule

func (sess *Session) AddRule(rules ...CompoundTerm)

AddRule, no dedup.

func (*Session) AdjustDepthControl

func (s *Session) AdjustDepthControl()

heuristic to adjust depth control called when adding new rules. multiple calls will increase the limit ...

func (Session) CountRules

func (sess Session) CountRules() int

Count known rules in DB

func (*Session) ForceDepthControl

func (s *Session) ForceDepthControl(limit int)

Force the limit beyond which search trees will be truncated. Use at your own risks !

func (Session) ListRules

func (sess Session) ListRules() string

func (*Session) Repl

func (sess *Session) Repl()

main repl loop

func (*Session) ResetSession

func (sess *Session) ResetSession()

Reset the global session

type SolutionHandler

type SolutionHandler func(st *State) *State

Handles a solution. A solution is assumed when goals are empty. Return value indicates what to do next. The state MAY be modified, typically by changing to parent state for backtracking. If returned state is nil, Solve exits.

type State

type State struct {
	Constraints []Constraint
	Goals       []Term   // Goals we are trying to erase. They are ordered in the order they should be executed.
	Parent      *State   // for backtracking
	Uid         int      // Unique id for alpha-conversion of rules
	NextRule    int      // index of the next rule to consider. It may not be applicable.
	Session     *Session // pointer to current session
}

State maintains the current state of the puzzle current state, and is used for backtracking. A new state is created if and only if we have to make a choice and backtracking may be necessary.

func ApplyRule

func ApplyRule(st *State, rule Term) (*State, error)

Apply a rule to the state. No new state is created, no backtracking is performed here, an error is returned instead. Goals and constraints are potentially updated. Returns err!=nil if backtracking will be required.

func DoPredicate

func DoPredicate(st *State) (*State, error)

Execute predicates (recursively if needed) using the functor of the first goal. Includes removing underscore. Constant values (numbers, strings ...) are kept. State MAY change, if alternative must be considered (eg : 'or'), but only by forking. No backtracking is performed at this level, error is returned instead.

func NewState

func NewState(parent *State) *State

Creates a new state, using provided parent. Constraints and goals cloned from parent. Rules are copied but not cloned. Uid is copied verbatim. Next rule is set to 0.

func NewStateWithSession

func NewStateWithSession(sess *Session) *State

Create a new root state (ie, with nil parent) but with an existing session.

func Solve

func Solve(st *State, sh SolutionHandler) *State

Solve for a given state. Backtracking is managed only in this function.

func (State) CheckDepth

func (st State) CheckDepth() error

Check if maxdepth is reached.

func (*State) RulesHistory

func (st *State) RulesHistory() string

a printable explanation of the rules applied to reach this state. rules are listed in the order they were applied.

func (State) String

func (st State) String() string

type String

type String = parser.String

type Term

type Term = parser.Term

Aliases to parser types.

func ReplaceVar

func ReplaceVar(v Variable, t Term, w Term) (res Term, found bool)

Replace Variable v with the term w in t. If replacement occurs, Term is cloned and found flag is set.

type Underscore

type Underscore = parser.Underscore

type VarGTENum

type VarGTENum struct {
	V     Variable
	Value Number
}

Ensure V >= Value

func (VarGTENum) Check

func (c VarGTENum) Check() (Constraint, error)

Check implements Constraint.

func (VarGTENum) Clone

func (c VarGTENum) Clone() Constraint

Clone implements Constraint.

func (VarGTENum) GetV

func (c VarGTENum) GetV() Variable

func (VarGTENum) Simplify

func (c1 VarGTENum) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

Simplify implements Constraint.

func (VarGTENum) String

func (c VarGTENum) String() string

String implements Constraint.

type VarGTNum

type VarGTNum struct {
	V     Variable
	Value Number
}

Ensure V > Value

func (VarGTNum) Check

func (c VarGTNum) Check() (Constraint, error)

Check implements Constraint.

func (VarGTNum) Clone

func (c VarGTNum) Clone() Constraint

Clone implements Constraint.

func (VarGTNum) GetV

func (c VarGTNum) GetV() Variable

func (VarGTNum) Simplify

func (c1 VarGTNum) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

Simplify implements Constraint.

func (VarGTNum) String

func (c VarGTNum) String() string

String implements Constraint.

type VarINT

type VarINT struct{ V Variable }

Force V to be any integer number NaN is not considered a valid number.

func (VarINT) Check

func (c VarINT) Check() (Constraint, error)

Check implements Constraint.

func (VarINT) Clone

func (c VarINT) Clone() Constraint

Clone implements Constraint.

func (VarINT) GetV

func (c VarINT) GetV() Variable

func (VarINT) Simplify

func (c1 VarINT) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

Simplify implements Constraint.

func (VarINT) String

func (c VarINT) String() string

String implements Constraint.

type VarIsAtom

type VarIsAtom struct {
	V Variable
	A Atom
}

func (VarIsAtom) Check

func (c VarIsAtom) Check() (Constraint, error)

Check will check validity of constraint, clean it or simplify it. It will return the constraint itself, possibly modified, or nil if constraint should be ignored ( CAUTION : return can be nil, despite a nil error ! An error means the constraint is impossible to satisfy (e.g. positive occur check, empty number interval, ...)

func (VarIsAtom) Clone

func (c VarIsAtom) Clone() Constraint

Clone implements Constraint.

func (VarIsAtom) GetV

func (c VarIsAtom) GetV() Variable

func (VarIsAtom) Simplify

func (c1 VarIsAtom) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

simplify c2, taking into account the calling constraint c1 (unchanged). if error, other results are not significant and should not be used. If changed, replace c by all of cc (possibly empty, to just suppress c). If changed is false, cc has no meaning. Input constraints MUST BE checked Output constraints are checked

func (VarIsAtom) String

func (c VarIsAtom) String() string

String implements Constraint.

type VarIsCompoundTerm

type VarIsCompoundTerm struct {
	V Variable
	T Term
}

Constraint for X = term

func (VarIsCompoundTerm) Check

func (c VarIsCompoundTerm) Check() (Constraint, error)

Check will check validity of constraint, clean it or simplify it. It will return the constraint itself, possibly modified, or nil if constraint should be ignored ( CAUTION : return can be nil, despite a nil error ! An error means the constraint is impossible to satisfy (e.g. positive occur check, empty number interval, ...)

func (VarIsCompoundTerm) Clone

func (c VarIsCompoundTerm) Clone() Constraint

Clone implements Constraint.

func (VarIsCompoundTerm) GetV

func (c VarIsCompoundTerm) GetV() Variable

func (VarIsCompoundTerm) Simplify

func (c1 VarIsCompoundTerm) Simplify(c Constraint) (cc []Constraint, changed bool, err error)

Simplify implements Constraint.

func (VarIsCompoundTerm) String

func (v VarIsCompoundTerm) String() string

String implements Constraint.

type VarIsNum

type VarIsNum struct {
	V     Variable
	Value Number
}

Ensure V = Number Value

func (VarIsNum) Check

func (c VarIsNum) Check() (Constraint, error)

Check implements Constraint.

func (VarIsNum) Clone

func (c VarIsNum) Clone() Constraint

Clone implements Constraint.

func (VarIsNum) GetV

func (c VarIsNum) GetV() Variable

func (VarIsNum) Simplify

func (c1 VarIsNum) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

Simplify implements Constraint.

func (VarIsNum) String

func (c VarIsNum) String() string

String implements Constraint.

type VarIsString

type VarIsString struct {
	V Variable
	S String
}

func (VarIsString) Check

func (c VarIsString) Check() (Constraint, error)

Check will check validity of constraint, clean it or simplify it. It will return the constraint itself, possibly modified, or nil if constraint should be ignored ( CAUTION : return can be nil, despite a nil error ! An error means the constraint is impossible to satisfy (e.g. positive occur check, empty number interval, ...)

func (VarIsString) Clone

func (c VarIsString) Clone() Constraint

Clone implements Constraint.

func (VarIsString) GetV

func (c VarIsString) GetV() Variable

func (VarIsString) Simplify

func (c1 VarIsString) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

simplify c2, taking into account the calling constraint c1 (unchanged). if error, other results are not significant and should not be used. If changed, replace c by all of cc (possibly empty, to just suppress c). If changed is false, cc has no meaning. Input constraints MUST BE checked Output constraints are checkedutput.

func (VarIsString) String

func (c VarIsString) String() string

String implements Constraint.

type VarIsVar

type VarIsVar struct {
	V Variable
	W Variable
}

func (VarIsVar) Check

func (c VarIsVar) Check() (Constraint, error)

Check will check validity of constraint, clean it or simplify it. It will return the constraint itself, possibly modified, or nil if constraint should be ignored ( CAUTION : return can be nil, despite a nil error ! An error means the constraint is impossible to satisfy (e.g. positive occur check, empty number interval, ...) There is a cannonical order of variables, with Y = Y means Y is latest (highest Nsp)

func (VarIsVar) Clone

func (c VarIsVar) Clone() Constraint

Clone implements Constraint.

func (VarIsVar) GetV

func (c VarIsVar) GetV() Variable

func (VarIsVar) Simplify

func (c1 VarIsVar) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

simplify c2, taking into account the calling constraint c1 (unchanged). if error, other results are not significant and should not be used. If changed, replace c by all of cc (possibly empty, to just suppress c). If changed is false, cc has no meaning. Input constraints MUST BE checked Output constraints are checked

func (VarIsVar) String

func (c VarIsVar) String() string

String implements Constraint.

type VarLTENum

type VarLTENum struct {
	V     Variable
	Value Number
}

Ensure V <= Value

func (VarLTENum) Check

func (c VarLTENum) Check() (Constraint, error)

Check implements Constraint.

func (VarLTENum) Clone

func (c VarLTENum) Clone() Constraint

Clone implements Constraint.

func (VarLTENum) GetV

func (c VarLTENum) GetV() Variable

func (VarLTENum) Simplify

func (c1 VarLTENum) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

Simplify implements Constraint.

func (VarLTENum) String

func (c VarLTENum) String() string

String implements Constraint.

type VarLTNum

type VarLTNum struct {
	V     Variable
	Value Number
}

Ensure V < Value

func (VarLTNum) Check

func (c VarLTNum) Check() (Constraint, error)

Check implements Constraint.

func (VarLTNum) Clone

func (c VarLTNum) Clone() Constraint

Clone implements Constraint.

func (VarLTNum) GetV

func (c VarLTNum) GetV() Variable

func (VarLTNum) Simplify

func (c1 VarLTNum) Simplify(c2 Constraint) (cc []Constraint, changed bool, err error)

Simplify implements Constraint.

func (VarLTNum) String

func (c VarLTNum) String() string

String implements Constraint.

type Variable

type Variable = parser.Variable

Jump to

Keyboard shortcuts

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