This commit is contained in:
Vitor Santos Costa
2016-11-16 17:17:33 -06:00
parent 56905d86ae
commit 8d1cc35a8a
36 changed files with 1523 additions and 2164 deletions

View File

@@ -1,5 +1,7 @@
Boolean Decision Making in YAP (#BDDs)
==============================
This is an experimental interface to BDD libraries. It is not as
This is an experimental interface to BDD libraries. It is not as
sophisticated as simplecudd, but it should be fun to play around with bdds.
It currently works with cudd only, although it should be possible to
@@ -9,10 +11,7 @@ with cudd binaries. This works:
- in fedora with standard package
- in osx with hand-compiled and ports package
In ubuntu, you may want to install the fedora rpm, or just contact me
for instructions.
Good Luck!
Vitor
In ubuntu, you may want to install the fedora rpm, or just download the package from the original
and compile it.
.

528
packages/chr/chr.md Normal file
View File

@@ -0,0 +1,528 @@
CHR: Constraint Handling Rules {#chr}
==============================
This chapter is written by Tom Schrijvers, K.U. Leuven for the hProlog
system. Adjusted by Jan Wielemaker to fit the SWI-Prolog documentation
infrastructure and remove hProlog specific references.
The CHR system of SWI-Prolog is the K.U.Leuven CHR system. The
runtime environment is written by Christian Holzbaur and Tom
Schrijvers while the compiler is written by Tom Schrijvers. Both are
integrated with SWI-Prolog and licenced under compatible conditions
with permission from the authors. Porting and maintenance on YAP is
the entire responsability of Vítor Santos Costa.
The main reference for SWI-Prolog's CHR system is:
+ T. Schrijvers, and B. Demoen, <em>The K.U.Leuven CHR System: Implementation and Application</em>, First Workshop on Constraint Handling Rules: Selected
Contributions (Fruwirth, T. and Meister, M., eds.), pp. 1--5, 2004.
# Introduction
Constraint Handling Rules (CHR) is a committed-choice bottom-up language
embedded in Prolog. It is designed for writing constraint solvers and is
particularily useful for providing application-specific constraints.
It has been used in many kinds of applications, like scheduling,
model checking, abduction, type checking among many others.
CHR has previously been implemented in other Prolog systems (SICStus,
Eclipse, Yap), Haskell and Java. This CHR system is based on the
compilation scheme and runtime environment of CHR in SICStus.
In this documentation we restrict ourselves to giving a short overview
of CHR in general and mainly focus on elements specific to this
implementation. For a more thorough review of CHR we refer the reader to
[Freuhwirth:98]. More background on CHR can be found at the CHR web site.
### Syntax and Semantics
We present informally the syntax and semantics of CHR.
#### CHR Syntax
The syntax of CHR rules in hProlog is the following:
~~~~~
rules --> rule, rules.
rules --> [].
rule --> name, actual_rule, pragma, [atom(`.`)].
name --> atom, [atom(`@`)].
name --> [].
actual_rule --> simplification_rule.
actual_rule --> propagation_rule.
actual_rule --> simpagation_rule.
simplification_rule --> constraints, [atom(`<=>`)], guard, body.
propagation_rule --> constraints, [atom(`==>`)], guard, body.
simpagation_rule --> constraints, [atom(`\`)], constraints, [atom(`<=>`)],
guard, body.
constraints --> constraint, constraint_id.
constraints --> constraint, [atom(`,`)], constraints.
constraint --> compound_term.
constraint_id --> [].
constraint_id --> [atom(`#`)], variable.
guard --> [].
guard --> goal, [atom(`|`)].
body --> goal.
pragma --> [].
pragma --> [atom(`pragma`)], actual_pragmas.
actual_pragmas --> actual_pragma.
actual_pragmas --> actual_pragma, [atom(`,`)], actual_pragmas.
actual_pragma --> [atom(`passive(`)], variable, [atom(`)`)].
~~~~~
Additional syntax-related terminology:
+ *head:* the constraints in an `actual_rule` before
the arrow (either `<=>` or `==>`)
#### Semantics Semantics
In this subsection the operational semantics of CHR in Prolog are presented
informally. They do not differ essentially from other CHR systems.
When a constraint is called, it is considered an active constraint and
the system will try to apply the rules to it. Rules are tried and executed
sequentially in the order they are written.
A rule is conceptually tried for an active constraint in the following
way. The active constraint is matched with a constraint in the head of
the rule. If more constraints appear in the head they are looked for
among the suspended constraints, which are called passive constraints in
this context. If the necessary passive constraints can be found and all
match with the head of the rule and the guard of the rule succeeds, then
the rule is committed and the body of the rule executed. If not all the
necessary passive constraint can be found, the matching fails or the
guard fails, then the body is not executed and the process of trying and
executing simply continues with the following rules. If for a rule,
there are multiple constraints in the head, the active constraint will
try the rule sequentially multiple times, each time trying to match with
another constraint.
This process ends either when the active constraint disappears, i.e. it
is removed by some rule, or after the last rule has been processed. In
the latter case the active constraint becomes suspended.
A suspended constraint is eligible as a passive constraint for an active
constraint. The other way it may interact again with the rules, is when
a variable appearing in the constraint becomes bound to either a nonvariable
or another variable involved in one or more constraints. In that case the
constraint is triggered, i.e. it becomes an active constraint and all
the rules are tried.
### Rules
There are three different kinds of rules, each with their specific semantics:
+ simplification
The simplification rule removes the constraints in its head and calls its body.
+ propagation
The propagation rule calls its body exactly once for the constraints in
its head.
+ simpagation
The simpagation rule removes the constraints in its head after the
`\` and then calls its body. It is an optimization of
simplification rules of the form: \[constraints_1, constraints_2 <=>
constraints_1, body \] Namely, in the simpagation form:
~~~~~
constraints1 \ constraints2 <=> body
~~~~~
_constraints1_
constraints are not called in the body.
#### Rule Names
Naming a rule is optional and has no semantical meaning. It only functions
as documentation for the programmer.
### Pragmas
The semantics of the pragmas are:
+ passive(Identifier)
The constraint in the head of a rule _Identifier_ can only act as a
passive constraint in that rule.
Additional pragmas may be released in the future.
### CHR_Options Options
It is possible to specify options that apply to all the CHR rules in the module.
Options are specified with the `option/2` declaration:
~~~~~
option(Option,Value).
~~~~~
Available options are:
+ check_guard_bindings
This option controls whether guards should be checked for illegal
variable bindings or not. Possible values for this option are
`on`, to enable the checks, and `off`, to disable the
checks.
+ optimize
This is an experimental option controlling the degree of optimization.
Possible values are `full`, to enable all available
optimizations, and `off` (default), to disable all optimizations.
The default is derived from the SWI-Prolog flag `optimise`, where
`true` is mapped to `full`. Therefore the commandline
option `-O` provides full CHR optimization.
If optimization is enabled, debugging should be disabled.
+ debug
This options enables or disables the possibility to debug the CHR code.
Possible values are `on` (default) and `off`. See
`debugging` for more details on debugging. The default is
derived from the prolog flag `generate_debug_info`, which
is `true` by default. See `-nodebug`.
If debugging is enabled, optimization should be disabled.
+ mode
This option specifies the mode for a particular constraint. The
value is a term with functor and arity equal to that of a constraint.
The arguments can be one of `-`, `+` or `?`.
The latter is the default. The meaning is the following:
+ -
The corresponding argument of every occurrence
of the constraint is always unbound.
+ +
The corresponding argument of every occurrence
of the constraint is always ground.
+ ?
The corresponding argument of every occurrence
of the constraint can have any instantiation, which may change
over time. This is the default value.
The declaration is used by the compiler for various optimizations.
Note that it is up to the user the ensure that the mode declaration
is correct with respect to the use of the constraint.
This option may occur once for each constraint.
+ type_declaration
This option specifies the argument types for a particular constraint. The
value is a term with functor and arity equal to that of a constraint.
The arguments can be a user-defined type or one of
the built-in types:
+ int
The corresponding argument of every occurrence
of the constraint is an integer number.
+ float
...{} a floating point number.
+ number
...{} a number.
+ natural
...{} a positive integer.
+ any
The corresponding argument of every occurrence
of the constraint can have any type. This is the default value.
Currently, type declarations are only used to improve certain
optimizations (guard simplification, occurrence subsumption, ...{}).
+ type_definition
This option defines a new user-defined type which can be used in
type declarations. The value is a term of the form
`type(` _name_`,` _list_`)`, where
_name_ is a term and _list_ is a list of alternatives.
Variables can be used to define generic types. Recursive definitions
are allowed. Examples are
~~~~~
type(bool,[true,false]).
type(complex_number,[float + float * i]).
type(binary_tree(T),[ leaf(T) | node(binary_tree(T),binary_tree(T)) ]).
type(list(T),[ [] | [T | list(T)]).
~~~~~
The mode, type_declaration and type_definition options are provided
for backward compatibility. The new syntax is described below.
### CHR in Prolog Programs
The CHR constraints defined in a particulary chr file are
associated with a module. The default module is `user`. One should
never load different chr files with the same CHR module name.
#### Constraint Declarations
Every constraint used in CHR rules has to be declared.
There are two ways to do this. The old style is as follows:
~~~~~
option(type_definition,type(list(T),[ [] , [T|list(T)] ]).
option(mode,foo(+,?)).
option(type_declaration,foo(list(int),float)).
:- constraints foo/2, bar/0.
~~~~~
The new style is as follows:
~~~~~
:- chr_type list(T) ---> [] ; [T|list(T)].
:- constraints foo(+list(int),?float), bar.
~~~~~
#### Compilation
The
SWI-Prolog CHR compiler exploits term_expansion/2 rules to translate
the constraint handling rules to plain Prolog. These rules are loaded
from the library chr. They are activated if the compiled file
has the chr extension or after finding a declaration of the
format below.
~~~~~
:- constraints ...
~~~~~
It is adviced to define CHR rules in a module file, where the module
declaration is immediately followed by including the chr
library as examplified below:
~~~~~
:- module(zebra, [ zebra/0 ]).
:- use_module(library(chr)).
:- constraints ...
~~~~~
Using this style CHR rules can be defined in ordinary Prolog
pl files and the operator definitions required by CHR do not
leak into modules where they might cause conflicts.
#### CHR Debugging
The CHR debugging facilities are currently rather limited. Only tracing
is currently available. To use the CHR debugging facilities for a CHR
file it must be compiled for debugging. Generating debug info is
controlled by the CHR option debug, whose default is derived
from the SWI-Prolog flag `generate_debug_info`. Therefore debug
info is provided unless the `-nodebug` is used.
#### Ports
vFor CHR constraints the four standard ports are defined:
+ call
A new constraint is called and becomes active.
+ exit
An active constraint exits: it has either been inserted in the store after
trying all rules or has been removed from the constraint store.
+ fail
An active constraint fails.
+ redo
An active constraint starts looking for an alternative solution.
In addition to the above ports, CHR constraints have five additional
ports:
+ wake
A suspended constraint is woken and becomes active.
+ insert
An active constraint has tried all rules and is suspended in
the constraint store.
+ remove
An active or passive constraint is removed from the constraint
store, if it had been inserted.
+ try
An active constraints tries a rule with possibly
some passive constraints. The try port is entered
just before committing to the rule.
+ apply
An active constraints commits to a rule with possibly
some passive constraints. The apply port is entered
just after committing to the rule.
#### Tracing
Tracing is enabled with the chr_trace/0 predicate
and disabled with the chr_notrace/0 predicate.
When enabled the tracer will step through the `call`,
`exit`, `fail`, `wake` and `apply` ports,
accepting debug commands, and simply write out the other ports.
The following debug commans are currently supported:
~~~~~
CHR debug options:
<cr> creep c creep
s skip
g ancestors
n nodebug
b break
a abort
f fail
? help h help
~~~~~
Their meaning is:
+ creep
Step to the next port.
+ skip
Skip to exit port of this call or wake port.
+ ancestors
Print list of ancestor call and wake ports.
+ nodebug
Disable the tracer.
+ break
Enter a recursive Prolog toplevel. See break/0.
+ abort
Exit to the toplevel. See abort/0.
+ fail
Insert failure in execution.
+ help
Print the above available debug options.
#### CHR Debugging Predicates
The chr module contains several predicates that allow
inspecting and printing the content of the constraint store.
+ chr_trace
Activate the CHR tracer. By default the CHR tracer is activated and
deactivated automatically by the Prolog predicates trace/0 and
notrace/0.
### CHR_Examples Examples
Here are two example constraint solvers written in CHR.
+
The program below defines a solver with one constraint,
`leq/2`, which is a less-than-or-equal constraint.
~~~~~
:- module(leq,[cycle/3, leq/2]).
:- use_module(library(chr)).
:- constraints leq/2.
reflexivity @ leq(X,X) <=> true.
antisymmetry @ leq(X,Y), leq(Y,X) <=> X = Y.
idempotence @ leq(X,Y) \ leq(X,Y) <=> true.
transitivity @ leq(X,Y), leq(Y,Z) ==> leq(X,Z).
cycle(X,Y,Z):-
leq(X,Y),
leq(Y,Z),
leq(Z,X).
~~~~~
+
The program below implements a simple finite domain
constraint solver.
~~~~~
:- module(dom,[dom/2]).
:- use_module(library(chr)).
:- constraints dom/2.
dom(X,[]) <=> fail.
dom(X,[Y]) <=> X = Y.
dom(X,L1), dom(X,L2) <=> intersection(L1,L2,L3), dom(X,L3).
intersection([],_,[]).
intersection([H|T],L2,[H|L3]) :-
member(H,L2), !,
intersection(T,L2,L3).
intersection([_|T],L2,L3) :-
intersection(T,L2,L3).
~~~~~
### Compatibility with SICStus CHR
There are small differences between CHR in SWI-Prolog and newer
YAPs and SICStus and older versions of YAP. Besides differences in
available options and pragmas, the following differences should be
noted:
+ [The handler/1 declaration]
In SICStus every CHR module requires a `handler/1`
declaration declaring a unique handler name. This declaration is valid
syntax in SWI-Prolog, but will have no effect. A warning will be given
during compilation.
+ [The rules/1 declaration]
In SICStus, for every CHR module it is possible to only enable a subset
of the available rules through the `rules/1` declaration. The
declaration is valid syntax in SWI-Prolog, but has no effect. A
warning is given during compilation.
+ [Sourcefile naming]
SICStus uses a two-step compiler, where chr files are
first translated into pl files. For SWI-Prolog CHR
rules may be defined in a file with any extension.
### Guidelines
In this section we cover several guidelines on how to use CHR to write
constraint solvers and how to do so efficiently.
+ [Set semantics]
The CHR system allows the presence of identical constraints, i.e.
multiple constraints with the same functor, arity and arguments. For
most constraint solvers, this is not desirable: it affects efficiency
and possibly termination. Hence appropriate simpagation rules should be
added of the form:
~~~~~
{constraint \ constraint <=> true}.
~~~~~
+ [Multi-headed rules]
Multi-headed rules are executed more efficiently when the constraints
share one or more variables.
+ [Mode and type declarations]
Provide mode and type declarations to get more efficient program execution.
Make sure to disable debug (`-nodebug`) and enable optimization
(`-O`).

View File

@@ -1,538 +1,2 @@
%
% chr.pl is generated automatically.
% This package is just here to work as a stub for YAP analysis.
%
/**
@defgroup CHR CHR: Constraint Handling Rules
@ingroup swi
This chapter is written by Tom Schrijvers, K.U. Leuven for the hProlog
system. Adjusted by Jan Wielemaker to fit the SWI-Prolog documentation
infrastructure and remove hProlog specific references.
The CHR system of SWI-Prolog is the K.U.Leuven CHR system. The runtime
environment is written by Christian Holzbaur and Tom Schrijvers while the
compiler is written by Tom Schrijvers. Both are integrated with SWI-Prolog
and licenced under compatible conditions with permission from the authors.
The main reference for SWI-Prolog's CHR system is:
+ T. Schrijvers, and B. Demoen, <em>The K.U.Leuven CHR System: Implementation and Application</em>, First Workshop on Constraint Handling Rules: Selected
Contributions (Fruwirth, T. and Meister, M., eds.), pp. 1--5, 2004.
# Introduction
Constraint Handling Rules (CHR) is a committed-choice bottom-up language
embedded in Prolog. It is designed for writing constraint solvers and is
particularily useful for providing application-specific constraints.
It has been used in many kinds of applications, like scheduling,
model checking, abduction, type checking among many others.
CHR has previously been implemented in other Prolog systems (SICStus,
Eclipse, Yap), Haskell and Java. This CHR system is based on the
compilation scheme and runtime environment of CHR in SICStus.
In this documentation we restrict ourselves to giving a short overview
of CHR in general and mainly focus on elements specific to this
implementation. For a more thorough review of CHR we refer the reader to
[Freuhwirth:98]. More background on CHR can be found at the CHR web site.
### Syntax and Semantics
We present informally the syntax and semantics of CHR.
#### CHR Syntax
The syntax of CHR rules in hProlog is the following:
~~~~~
rules --> rule, rules.
rules --> [].
rule --> name, actual_rule, pragma, [atom(`.`)].
name --> atom, [atom(`@`)].
name --> [].
actual_rule --> simplification_rule.
actual_rule --> propagation_rule.
actual_rule --> simpagation_rule.
simplification_rule --> constraints, [atom(`<=>`)], guard, body.
propagation_rule --> constraints, [atom(`==>`)], guard, body.
simpagation_rule --> constraints, [atom(`\`)], constraints, [atom(`<=>`)],
guard, body.
constraints --> constraint, constraint_id.
constraints --> constraint, [atom(`,`)], constraints.
constraint --> compound_term.
constraint_id --> [].
constraint_id --> [atom(`#`)], variable.
guard --> [].
guard --> goal, [atom(`|`)].
body --> goal.
pragma --> [].
pragma --> [atom(`pragma`)], actual_pragmas.
actual_pragmas --> actual_pragma.
actual_pragmas --> actual_pragma, [atom(`,`)], actual_pragmas.
actual_pragma --> [atom(`passive(`)], variable, [atom(`)`)].
~~~~~
Additional syntax-related terminology:
+ *head:* the constraints in an `actual_rule` before
the arrow (either `<=>` or `==>`)
#### Semantics Semantics
In this subsection the operational semantics of CHR in Prolog are presented
informally. They do not differ essentially from other CHR systems.
When a constraint is called, it is considered an active constraint and
the system will try to apply the rules to it. Rules are tried and executed
sequentially in the order they are written.
A rule is conceptually tried for an active constraint in the following
way. The active constraint is matched with a constraint in the head of
the rule. If more constraints appear in the head they are looked for
among the suspended constraints, which are called passive constraints in
this context. If the necessary passive constraints can be found and all
match with the head of the rule and the guard of the rule succeeds, then
the rule is committed and the body of the rule executed. If not all the
necessary passive constraint can be found, the matching fails or the
guard fails, then the body is not executed and the process of trying and
executing simply continues with the following rules. If for a rule,
there are multiple constraints in the head, the active constraint will
try the rule sequentially multiple times, each time trying to match with
another constraint.
This process ends either when the active constraint disappears, i.e. it
is removed by some rule, or after the last rule has been processed. In
the latter case the active constraint becomes suspended.
A suspended constraint is eligible as a passive constraint for an active
constraint. The other way it may interact again with the rules, is when
a variable appearing in the constraint becomes bound to either a nonvariable
or another variable involved in one or more constraints. In that case the
constraint is triggered, i.e. it becomes an active constraint and all
the rules are tried.
### Rules
There are three different kinds of rules, each with their specific semantics:
+ simplification
The simplification rule removes the constraints in its head and calls its body.
+ propagation
The propagation rule calls its body exactly once for the constraints in
its head.
+ simpagation
The simpagation rule removes the constraints in its head after the
`\` and then calls its body. It is an optimization of
simplification rules of the form: \[constraints_1, constraints_2 <=>
constraints_1, body \] Namely, in the simpagation form:
~~~~~
constraints1 \ constraints2 <=> body
~~~~~
_constraints1_
constraints are not called in the body.
#### Rule Names
Naming a rule is optional and has no semantical meaning. It only functions
as documentation for the programmer.
### Pragmas
The semantics of the pragmas are:
+ passive(Identifier)
The constraint in the head of a rule _Identifier_ can only act as a
passive constraint in that rule.
Additional pragmas may be released in the future.
### CHR_Options Options
It is possible to specify options that apply to all the CHR rules in the module.
Options are specified with the `option/2` declaration:
~~~~~
option(Option,Value).
~~~~~
Available options are:
+ check_guard_bindings
This option controls whether guards should be checked for illegal
variable bindings or not. Possible values for this option are
`on`, to enable the checks, and `off`, to disable the
checks.
+ optimize
This is an experimental option controlling the degree of optimization.
Possible values are `full`, to enable all available
optimizations, and `off` (default), to disable all optimizations.
The default is derived from the SWI-Prolog flag `optimise`, where
`true` is mapped to `full`. Therefore the commandline
option `-O` provides full CHR optimization.
If optimization is enabled, debugging should be disabled.
+ debug
This options enables or disables the possibility to debug the CHR code.
Possible values are `on` (default) and `off`. See
`debugging` for more details on debugging. The default is
derived from the prolog flag `generate_debug_info`, which
is `true` by default. See `-nodebug`.
If debugging is enabled, optimization should be disabled.
+ mode
This option specifies the mode for a particular constraint. The
value is a term with functor and arity equal to that of a constraint.
The arguments can be one of `-`, `+` or `?`.
The latter is the default. The meaning is the following:
+ -
The corresponding argument of every occurrence
of the constraint is always unbound.
+ +
The corresponding argument of every occurrence
of the constraint is always ground.
+ ?
The corresponding argument of every occurrence
of the constraint can have any instantiation, which may change
over time. This is the default value.
The declaration is used by the compiler for various optimizations.
Note that it is up to the user the ensure that the mode declaration
is correct with respect to the use of the constraint.
This option may occur once for each constraint.
+ type_declaration
This option specifies the argument types for a particular constraint. The
value is a term with functor and arity equal to that of a constraint.
The arguments can be a user-defined type or one of
the built-in types:
+ int
The corresponding argument of every occurrence
of the constraint is an integer number.
+ float
...{} a floating point number.
+ number
...{} a number.
+ natural
...{} a positive integer.
+ any
The corresponding argument of every occurrence
of the constraint can have any type. This is the default value.
Currently, type declarations are only used to improve certain
optimizations (guard simplification, occurrence subsumption, ...{}).
+ type_definition
This option defines a new user-defined type which can be used in
type declarations. The value is a term of the form
`type(` _name_`,` _list_`)`, where
_name_ is a term and _list_ is a list of alternatives.
Variables can be used to define generic types. Recursive definitions
are allowed. Examples are
~~~~~
type(bool,[true,false]).
type(complex_number,[float + float * i]).
type(binary_tree(T),[ leaf(T) | node(binary_tree(T),binary_tree(T)) ]).
type(list(T),[ [] | [T | list(T)]).
~~~~~
The mode, type_declaration and type_definition options are provided
for backward compatibility. The new syntax is described below.
### CHR in Prolog Programs
The CHR constraints defined in a particulary chr file are
associated with a module. The default module is `user`. One should
never load different chr files with the same CHR module name.
#### Constraint Declarations
Every constraint used in CHR rules has to be declared.
There are two ways to do this. The old style is as follows:
~~~~~
option(type_definition,type(list(T),[ [] , [T|list(T)] ]).
option(mode,foo(+,?)).
option(type_declaration,foo(list(int),float)).
:- constraints foo/2, bar/0.
~~~~~
The new style is as follows:
~~~~~
:- chr_type list(T) ---> [] ; [T|list(T)].
:- constraints foo(+list(int),?float), bar.
~~~~~
#### Compilation
The
SWI-Prolog CHR compiler exploits term_expansion/2 rules to translate
the constraint handling rules to plain Prolog. These rules are loaded
from the library chr. They are activated if the compiled file
has the chr extension or after finding a declaration of the
format below.
~~~~~
:- constraints ...
~~~~~
It is adviced to define CHR rules in a module file, where the module
declaration is immediately followed by including the chr
library as examplified below:
~~~~~
:- module(zebra, [ zebra/0 ]).
:- use_module(library(chr)).
:- constraints ...
~~~~~
Using this style CHR rules can be defined in ordinary Prolog
pl files and the operator definitions required by CHR do not
leak into modules where they might cause conflicts.
#### CHR Debugging
The CHR debugging facilities are currently rather limited. Only tracing
is currently available. To use the CHR debugging facilities for a CHR
file it must be compiled for debugging. Generating debug info is
controlled by the CHR option debug, whose default is derived
from the SWI-Prolog flag `generate_debug_info`. Therefore debug
info is provided unless the `-nodebug` is used.
#### Ports
For CHR constraints the four standard ports are defined:
+ call
A new constraint is called and becomes active.
+ exit
An active constraint exits: it has either been inserted in the store after
trying all rules or has been removed from the constraint store.
+ fail
An active constraint fails.
+ redo
An active constraint starts looking for an alternative solution.
In addition to the above ports, CHR constraints have five additional
ports:
+ wake
A suspended constraint is woken and becomes active.
+ insert
An active constraint has tried all rules and is suspended in
the constraint store.
+ remove
An active or passive constraint is removed from the constraint
store, if it had been inserted.
+ try
An active constraints tries a rule with possibly
some passive constraints. The try port is entered
just before committing to the rule.
+ apply
An active constraints commits to a rule with possibly
some passive constraints. The apply port is entered
just after committing to the rule.
#### Tracing
Tracing is enabled with the chr_trace/0 predicate
and disabled with the chr_notrace/0 predicate.
When enabled the tracer will step through the `call`,
`exit`, `fail`, `wake` and `apply` ports,
accepting debug commands, and simply write out the other ports.
The following debug commans are currently supported:
~~~~~
CHR debug options:
<cr> creep c creep
s skip
g ancestors
n nodebug
b break
a abort
f fail
? help h help
~~~~~
Their meaning is:
+ creep
Step to the next port.
+ skip
Skip to exit port of this call or wake port.
+ ancestors
Print list of ancestor call and wake ports.
+ nodebug
Disable the tracer.
+ break
Enter a recursive Prolog toplevel. See break/0.
+ abort
Exit to the toplevel. See abort/0.
+ fail
Insert failure in execution.
+ help
Print the above available debug options.
#### CHR Debugging Predicates
The chr module contains several predicates that allow
inspecting and printing the content of the constraint store.
+ chr_trace
Activate the CHR tracer. By default the CHR tracer is activated and
deactivated automatically by the Prolog predicates trace/0 and
notrace/0.
### CHR_Examples Examples
Here are two example constraint solvers written in CHR.
+
The program below defines a solver with one constraint,
`leq/2`, which is a less-than-or-equal constraint.
~~~~~
:- module(leq,[cycle/3, leq/2]).
:- use_module(library(chr)).
:- constraints leq/2.
reflexivity @ leq(X,X) <=> true.
antisymmetry @ leq(X,Y), leq(Y,X) <=> X = Y.
idempotence @ leq(X,Y) \ leq(X,Y) <=> true.
transitivity @ leq(X,Y), leq(Y,Z) ==> leq(X,Z).
cycle(X,Y,Z):-
leq(X,Y),
leq(Y,Z),
leq(Z,X).
~~~~~
+
The program below implements a simple finite domain
constraint solver.
~~~~~
:- module(dom,[dom/2]).
:- use_module(library(chr)).
:- constraints dom/2.
dom(X,[]) <=> fail.
dom(X,[Y]) <=> X = Y.
dom(X,L1), dom(X,L2) <=> intersection(L1,L2,L3), dom(X,L3).
intersection([],_,[]).
intersection([H|T],L2,[H|L3]) :-
member(H,L2), !,
intersection(T,L2,L3).
intersection([_|T],L2,L3) :-
intersection(T,L2,L3).
~~~~~
### Compatibility with SICStus CHR
There are small differences between CHR in SWI-Prolog and newer
YAPs and SICStus and older versions of YAP. Besides differences in
available options and pragmas, the following differences should be
noted:
+ [The handler/1 declaration]
In SICStus every CHR module requires a `handler/1`
declaration declaring a unique handler name. This declaration is valid
syntax in SWI-Prolog, but will have no effect. A warning will be given
during compilation.
+ [The rules/1 declaration]
In SICStus, for every CHR module it is possible to only enable a subset
of the available rules through the `rules/1` declaration. The
declaration is valid syntax in SWI-Prolog, but has no effect. A
warning is given during compilation.
+ [Sourcefile naming]
SICStus uses a two-step compiler, where chr files are
first translated into pl files. For SWI-Prolog CHR
rules may be defined in a file with any extension.
### Guidelines
In this section we cover several guidelines on how to use CHR to write
constraint solvers and how to do so efficiently.
+ [Set semantics]
The CHR system allows the presence of identical constraints, i.e.
multiple constraints with the same functor, arity and arguments. For
most constraint solvers, this is not desirable: it affects efficiency
and possibly termination. Hence appropriate simpagation rules should be
added of the form:
~~~~~
{constraint \ constraint <=> true}.
~~~~~
+ [Multi-headed rules]
Multi-headed rules are executed more efficiently when the constraints
share one or more variables.
+ [Mode and type declarations]
Provide mode and type declarations to get more efficient program execution.
Make sure to disable debug (`-nodebug`) and enable optimization
(`-O`).
*/
:- include(chr_op).

119
packages/clpqr/clpqr.md Normal file
View File

@@ -0,0 +1,119 @@
Constraint Logic Programming over Rationals and Reals {#clpqr}
=====================================================
YAP now uses the CLP(R) package developed by <em>Leslie De Koninck</em>,
K.U. Leuven as part of a thesis with supervisor Bart Demoen and daily
advisor Tom Schrijvers, and distributed with SWI-Prolog.
This CLP(R) system is a port of the CLP(Q,R) system of Sicstus Prolog
and YAP by Christian Holzbaur: Holzbaur C.: OFAI clp(q,r) Manual,
Edition 1.3.3, Austrian Research Institute for Artificial
Intelligence, Vienna, TR-95-09, 1995,
<http://www.ai.univie.ac.at/cgi-bin/tr-online?number+95-09> This
port only contains the part concerning real arithmetics. This manual
is roughly based on the manual of the above mentioned *CLP(QR)*
implementation.
Please note that the clpr library is <em>not</em> an
`autoload` library and therefore this library must be loaded
explicitely before using it:
~~~~~
:- use_module(library(clpr)).
~~~~~
### Solver Predicates {#CLPQR_Solver_Predicates}
The following predicates are provided to work with constraints:
### Syntax of the predicate arguments {#CLPQR_Syntax}
The arguments of the predicates defined in the subsection above are
defined in the following table. Failing to meet the syntax rules will
result in an exception.
~~~~~
<Constraints> ---> <Constraint> \ single constraint \
| <Constraint> , <Constraints> \ conjunction \
| <Constraint> ; <Constraints> \ disjunction \
<Constraint> ---> <Expression> {<} <Expression> \ less than \
| <Expression> {>} <Expression> \ greater than \
| <Expression> {=<} <Expression> \ less or equal \
| {<=}(<Expression>, <Expression>) \ less or equal \
| <Expression> {>=} <Expression> \ greater or equal \
| <Expression> {=\=} <Expression> \ not equal \
| <Expression> =:= <Expression> \ equal \
| <Expression> = <Expression> \ equal \
<Expression> ---> <Variable> \ Prolog variable \
| <Number> \ Prolog number (float, integer) \
| +<Expression> \ unary plus \
| -<Expression> \ unary minus \
| <Expression> + <Expression> \ addition \
| <Expression> - <Expression> \ substraction \
| <Expression> * <Expression> \ multiplication \
| <Expression> / <Expression> \ division \
| abs(<Expression>) \ absolute value \
| sin(<Expression>) \ sine \
| cos(<Expression>) \ cosine \
| tan(<Expression>) \ tangent \
| exp(<Expression>) \ exponent \
| pow(<Expression>) \ exponent \
| <Expression> {^} <Expression> \ exponent \
| min(<Expression>, <Expression>) \ minimum \
| max(<Expression>, <Expression>) \ maximum \
~~~~~
### Use of unification {#CLPQR_Unification}
Instead of using the `{}/1` predicate, you can also use the standard
unification mechanism to store constraints. The following code samples
are equivalent:
+ Unification with a variable
~~~~~
{X =:= Y}
{X = Y}
X = Y
~~~~~
+ Unification with a number
~~~~~
{X =:= 5.0}
{X = 5.0}
X = 5.0
~~~~~
#### Non-Linear Constraints {#CLPQR_NonhYlinear_Constraints}
In this version, non-linear constraints do not get solved until certain
conditions are satisfied. We call these conditions the _isolation_ axioms.
They are given in the following table.
~~~~~
A = B * C when B or C is ground or // A = 5 * C or A = B * 4 \\
A and (B or C) are ground // 20 = 5 * C or 20 = B * 4 \\
A = B / C when C is ground or // A = B / 3
A and B are ground // 4 = 12 / C
X = min(Y,Z) when Y and Z are ground or // X = min(4,3)
X = max(Y,Z) Y and Z are ground // X = max(4,3)
X = abs(Y) Y is ground // X = abs(-7)
X = pow(Y,Z) when X and Y are ground or // 8 = 2 ^ Z
X = exp(Y,Z) X and Z are ground // 8 = Y ^ 3
X = Y ^ Z Y and Z are ground // X = 2 ^ 3
X = sin(Y) when X is ground or // 1 = sin(Y)
X = cos(Y) Y is ground // X = sin(1.5707)
X = tan(Y)
~~~~~

View File

@@ -38,7 +38,10 @@
the GNU General Public License.
*/
/** @defgroup clpr_implementation CLP(QR) Predicates
@ingroup clpqr
*/
/** @pred bb_inf(+ _Ints_,+ _Expression_,- _Inf_)
The same as bb_inf/5 but without returning the values of the integers

View File

@@ -1,16 +1,24 @@
USING THE GECODE MODULE
USING THE GECODE MODULE (#Gecode)
=======================
There are two ways to use the gecode interface from YAP. The original approach,
designed by Denys Duchier, requires loading the library:
:- use_module(library(gecode)).
A second approach is closer to CLP(FD), and is described in:
- \ref Gecode_and_ClPbBFDbC
In what follows, we refer the reader to the~\cite{gecode} manual for the necessary background.
CREATING A SPACE
================
----------------
Space := space
CREATING VARIABLES
==================
-----------------
Unlike in Gecode, variable objects are not bound to a specific Space. Each one
actually contains an index with which it is possible to access a Space-bound
@@ -49,7 +57,7 @@ kept. Thus marking variables as "kept" is purely an optimization.
CONSTRAINTS AND BRANCHINGS
==========================
---------------------------
all constraint and branching posting functions are available just like in
Gecode. Wherever a XXXArgs or YYYSharedArray is expected, simply use a list.
@@ -68,7 +76,7 @@ represented by atoms with the same name as the Gecode constant
(e.g. 'INT_VAR_SIZE_MIN').
SEARCHING FOR SOLUTIONS
=======================
--------------------
SolSpace := search(Space)
@@ -90,7 +98,7 @@ a_d=N
to set the adaptive distance for recomputation
EXTRACTING INFO FROM A SOLUTION
===============================
------------------------------
An advantage of non Space-bound variables, is that you can use them both to
post constraints in the original space AND to consult their values in
@@ -126,7 +134,7 @@ variables, and returns resp. either a value, or a list of values:
Val := unknown_values(Space,V)
DISJUNCTORS
===========
-----------
Disjunctors provide support for disjunctions of clauses, where each clause is a
conjunction of constraints:

574
packages/myddas/myddas.md Normal file
View File

@@ -0,0 +1,574 @@
The MYDDAS Data-base interface {#myddas}
==============================
The MYDDAS database project was developed within a FCT project aiming at
the development of a highly efficient deductive database system, based
on the coupling of the MySQL relational database system with the YAP
Prolog system. MYDDAS was later expanded to support the ODBC interface.
@defgroup Requirements_and_Installation_Guide Requirements and Installation Guide
ee
Next, we describe how to usen of the YAP with the MYDDAS System. The
use of this system is entirely depend of the MySQL development libraries
or the ODBC development libraries. At least one of the this development
libraries must be installed on the computer system, otherwise MYDDAS
will not compile. The MySQL development libraries from MySQL 3.23 an
above are know to work. We recommend the usage of MySQL versus ODBC,
but it is possible to have both options installed
At the same time, without any problem. The MYDDAS system automatically
controls the two options. Currently, MYDDAS is know to compile without
problems in Linux. The usage of this system on Windows has not been
tested yet. MYDDAS must be enabled at configure time. This can be done
with the following options:
+ --enable-myddas
This option will detect which development libraries are installed on the computer system, MySQL, ODBC or both, and will compile the Yap system with the support for which libraries it detects;
+ --enable-myddas-stats
This option is only available in MySQL. It includes code to get
statistics from the MYDDAS system;
+ --enable-top-level
This option is only available in MySQL. It enables the option to interact with the MySQL server in
two different ways. As if we were on the MySQL Client Shell, and as if
we were using Datalog.
@defgroup MYDDAS_Architecture MYDDAS Architecture
The system includes four main blocks that are put together through the
MYDDAS interface: the Yap Prolog compiler, the MySQL database system, an
ODBC level and a Prolog to SQL compiler. Current effort is put on the
MySQL interface rather than on the ODBC interface. If you want to use
the full power of the MYDDAS interface we recommend you to use a MySQL
database. Other databases, such as Oracle, PostGres or Microsoft SQL
Server, can be interfaced through the ODBC layer, but with limited
performance and features support.
The main structure of the MYDDAS interface is simple. Prolog queries
involving database goals are translated to SQL using the Prolog to SQL
compiler; then the SQL expression is sent to the database system, which
returns the set of tuples satisfying the query; and finally those tuples
are made available to the Prolog engine as terms. For recursive queries
involving database goals, the YapTab tabling engine provides the
necessary support for an efficient evaluation of such queries.
An important aspect of the MYDDAS interface is that for the programmer
the use of predicates which are defined in database relations is
completely transparent. An example of this transparent support is the
Prolog cut operator, which has exactly the same behaviour from
predicates defined in the Prolog program source code, or from predicates
defined in database as relations.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Name = 'John Doe',
Number = 123456789 ?
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Backtracking can then be used to retrieve the next row
of the relation phonebook. Records with particular field values may be
selected in the same way as in Prolog. (In particular, no mode
specification for database predicates is required). For instance:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- phonebook(Letter,'John Doe',Letter).
Letter = 'D',
Number = 123456789 ?
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generates the query
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SELECT A.Letter , 'John Doe' , A.Number
FROM 'phonebook' A
WHERE A.Name = 'John Doe';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@defgroup View_Level_Interface View Level Interface
@pred db view(+,+,+).
@pred db view(+,+).
If we import a database relation, such as an edge relation representing the edges of a directed graph, through
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_import('Edge',edge).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sqliand we then write a query to retrieve all the direct cycles in the
graph, such as
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- edge(A,B), edge(B,A).
A = 10,
B = 20 ?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this is clearly inefficient [3], because of relation-level
access. Relation-level access means that a separate SQL query will be
generated for every goal in the body of the clause. For the second
`edge/2` goal, a SQL query is generated using the variable bindings that
result from the first `edge/2` goal execution. If the second
`edge/2` goal
fails, or if alternative solutions are demanded, backtracking access the
next tuple for the first `edge/2` goal and another SQL query will be
generated for the second `edge/2` goal. The generation of this large
number of queries and the communication overhead with the database
system for each of them, makes the relation-level approach inefficient.
To solve this problem the view level interface can be used for the
definition of rules whose bodies includes only imported database
predicates. One can use the view level interface through the predicates
db_view/3 and `db_view/2`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_view(Conn,PredName(Arg_1,...,Arg_n),DbGoal).
?- db_view(PredName(Arg_1,...,Arg_n),DbGoal).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All arguments are standard Prolog terms. _Arg1_ through _Argn_
define the attributes to be retrieved from the database, while
_DbGoal_ defines the selection restrictions and join
conditions. _Conn_ is the connection identifier, which again can be
dropped. Calling predicate `PredName/n` will retrieve database
tuples using a single SQL query generated for the _DbGoal_. We next show
an example of a view definition for the direct cycles discussed
above. Assuming the declaration:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_import('Edge',edge).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
we
write:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_view(direct_cycle(A,B),(edge(A,B), edge(B,A))).
yes
?- direct_cycle(A,B)).
A = 10,
B = 20 ?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This call generates the SQL
statement:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SELECT A.attr1 , A.attr2
FROM Edge A , Edge B
WHERE B.attr1 = A.attr2 AND B.attr2 = A.attr1;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Backtracking, as in relational level interface, can be used to retrieve the next row of the view.
The view interface also supports aggregate function predicates such as
`sum`, `avg`, `count`, `min` and `max`. For
instance:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_view(count(X),(X is count(B, B^edge(10,B)))).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generates the query :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SELECT COUNT(A.attr2)
FROM Edge A WHERE A.attr1 = 10;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To know how to use db `view/3`, please refer to Draxler's Prolog to
SQL Compiler Manual.
@defgroup Accessing_Tables_in_Data_Sources_Using_SQL Accessing Tables in Data Sources Using SQL
@pred db_sql(+,+,?).
@pred db_sql(+,?).
It is also possible to explicitly send a SQL query to the database server using
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_sql(Conn,SQL,List).
?- db_sql(SQL,List).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
where _SQL_ is an arbitrary SQL expression, and _List_ is a list
holding the first tuple of result set returned by the server. The result
set can also be navigated through backtracking.
Example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_sql('SELECT * FROM phonebook',LA).
LA = ['D','John Doe',123456789] ?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@defgroup Insertion_of_Rows Insertion of Rows
@ingroup MYDDAS
@pred db_assert(+,+).
@pred db_assert(+).
Assuming you have imported the related base table using
`db_import/2` or db_import/3, you can insert to that table
by using db_assert/2 predicate any given fact.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_assert(Conn,Fact).
?- db_assert(Fact).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The second argument must be declared with all of its arguments bound to
constants. For example assuming `helloWorld` is imported through
`db_import/2`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_import('Hello World',helloWorld).
yes
?- db_assert(helloWorld('A' ,'Ana',31)).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This, would generate the following query
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
INSERT INTO helloWorld
VALUES ('A','Ana',3)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
which would insert into the helloWorld, the following row:
`A,Ana,31`. If we want to insert `NULL` values into the
relation, we call db_assert/2 with a uninstantiated variable in
the data base imported predicate. For example, the following query on
the YAP-prolog system:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_assert(helloWorld('A',NULL,31)).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Would insert the row: `A,null value,31` into the relation
`Hello World`, assuming that the second row allows null values.
*/
/** @pred db insert(+,+,+).
@pred db insert(+,+).
This predicate would create a new database predicate, which will insert
any given tuple into the database.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_insert(Conn,RelationName,PredName).
?- db_insert(RelationName,PredName).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This would create a new predicate with name _PredName_, that will
insert tuples into the relation _RelationName_. is the connection
identifier. For example, if we wanted to insert the new tuple
`('A',null,31)` into the relation `Hello World`, we do:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_insert('Hello World',helloWorldInsert).
yes
?- helloWorldInsert('A',NULL,31).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@defgroup Types_of_Attributes Types of AttributesL
@pred db_get_attributes_types(+,+,?).
@pred db_get_attributes_types(+,?).
The prototype for this predicate is the following:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_get_attributes_types(Conn,RelationName,ListOfFields).
?- db_get_attributes_types(RelationName,ListOfFields).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the
predicate `db_get_attributes types/2` or db_get_attributes_types/3, to
know what are the names and attributes types of the fields of a given
relation. For example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_get_attributes_types(myddas,'Hello World',LA).
LA = ['Number',integer,'Name',string,'Letter',string] ?
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
where <tt>Hello World</tt> is the name of the relation and <tt>myddas</tt> is the
connection identifier.
@defgroup Number_of_Fields Number of Fields
@pred db_number_of_fields(+,?).
@pred db_number_of_fields(+,+,?).
The prototype for this
predicate is the following:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_number_of_fields(Conn,RelationName,Arity).
?- db_number_of_fields(RelationName,Arity).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the predicate db_number_of_fields/2 or
`db_number_of_fields/3` to know what is the arity of a given
relation. Example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_number_of_fields(myddas,'Hello World',Arity).
Arity = 3 ?
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
where `Hello World` is the name of the
relation and `myddas` is the connection identifier.
@defgroup Describing_a_Relation Describing a Relation
@pred db_datalog_describe(+,+).
@pred db_datalog_describe(+).
The db `datalog_describe/2` predicate does not really returns any
value. It simply prints to the screen the result of the MySQL describe
command, the same way as `DESCRIBE` in the MySQL prompt would.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_datalog_describe(myddas,'Hello World').
+----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
+ Number | int(11) | YES | | NULL | |
+ Name | char(10) | YES | | NULL | |
+ Letter | char(1) | YES | | NULL | |
+----------+----------+------+-----+---------+-------+
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@pred db_describe(+,+).
@pred db_describe(+)
The `db_describe/3` predicate does the same action as
db_datalog_describe/2 predicate but with one major
difference. The results are returned by backtracking. For example, the
last query:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_describe(myddas,'Hello World',Term).
Term = tableInfo('Number',int(11),'YES','',null(0),'') ? ;
Term = tableInfo('Name',char(10),'YES','',null(1),'' ? ;
Term = tableInfo('Letter',char(1),'YES','',null(2),'') ? ;
no
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@defgroup Enumerating_Relations Enumeration Relations Describing_a_Relation Describing a Relation
/@pred db_datalog_show_tables(+).
@pred db_datalog_show_tables
If we need to know what relations exists in a given MySQL Schema, we can use
the `db_datalog_show_tables/1` predicate. As <tt>db_datalog_describe/2</tt>,
it does not returns any value, but instead prints to the screen the result of the
`SHOW TABLES` command, the same way as it would be in the MySQL prompt.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_datalog_show_tables(myddas).
+-----------------+
| Tables_in_guest |
+-----------------+
| Hello World |
+-----------------+
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@pred db_show_tables(+, ?).
@pred db_show_tables(?)
The db_show_tables/2 predicate does the same action as
`db_show_tables/1` predicate but with one major difference. The
results are returned by backtracking. For example, given the last query:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_show_tables(myddas,Table).
Table = table('Hello World') ? ;
no
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@defgroup The_MYDDAS_MySQL_Top_Level The MYDDAS MySQL Top Level
@pred db_top_level(+,+,+,+,+).
@pred db_top_level(+,+,+,+).
Through MYDDAS is also possible to access the MySQL Database Server, in
the same wthe mysql client. In this mode, is possible to query the
SQL server by just using the standard SQL language. This mode is exactly the same as
different from the standard mysql client. We can use this
mode, by invoking the db top level/5. as one of the following:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_top_level(mysql,Connection,Host/Database,User,Password).
?- db_top_level(mysql,Connection,Host/Database/Port,User,Password).
?- db_top_level(mysql,Connection,Host/Database/UnixSocket,User,Password).
?- db_top_level(mysql,Connection,Host/Database/Port/UnixSocket,User,Password).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage is similar as the one described for the db_open/5 predicate
discussed above. If the login is successful, automatically the prompt of
the mysql client will be used. For example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_top_level(mysql,con1,localhost/guest_db,guest,'').
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
opens a
connection identified by the `con1` atom, to an instance of a MySQL server
running on host `localhost`, using database guest `db` and user `guest` with
empty password. After this is possible to use MYDDAS as the mysql
client.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_top_level(mysql,con1,localhost/guest_db,guest,'').
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor.
Commands end with ; or \g.
Your MySQL connection id is 4468 to server version: 4.0.20
Type 'help;' or '\h' for help.
Type '\c' to clear the buffer.
mysql> exit
Bye
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@defgroup Other_MYDDAS_Properties Other MYDDAS Properties
@pred db_verbose(+).
When we ask a question to YAP, using a predicate asserted by
db_import/3, or by db_view/3, this will generate a SQL
`QUERY`. If we want to see that query, we must to this at a given
point in our session on YAP.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_verbose(1).
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we want to
disable this feature, we must call the `db_verbose/1` predicate with the value 0.
@pred db_top_level(+,+,+,+).
@pred db_module(?).
When we create a new database predicate, by using db_import/3,
db_view/3 or db_insert/3, that predicate will be asserted
by default on the `user` module. If we want to change this value, we can
use the db_module/1 predicate to do so.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_module(lists).
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By executing this predicate, all of the predicates asserted by the
predicates enumerated earlier will created in the lists module.
If we want to put back the value on default, we can manually put the
value user. Example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_module(user).
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We can also see in what module the predicates are being asserted by doing:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_module(X).
X=user
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@pred db_my_result_set(?).
The MySQL C API permits two modes for transferring the data generated by
a query to the client, in our case YAP. The first mode, and the default
mode used by the MYDDAS-MySQL, is to store the result. This mode copies all the
information generated to the client side.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_my_result_set(X).
X=store_result
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The other mode that we can use is use result. This one uses the result
set created directly from the server. If we want to use this mode, he
simply do
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_my_result_set(use_result).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
After this command, all
of the database predicates will use use result by default. We can change
this by doing again `db_my_result_set(store_result)`.
@pred db_my_sql_mode(+Conn,?SQL_Mode).
@pred db_my_sql_mode(?SQL_Mode).
The MySQL server allows the user to change the SQL mode. This can be
very useful for debugging proposes. For example, if we want MySQL server
not to ignore the INSERT statement warnings and instead of taking
action, report an error, we could use the following SQL mode.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?-db_my_sql_mode(traditional). yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can see the available SQL Modes at the MySQL homepage at
<http://www.mysql.org>.

View File

@@ -104,685 +104,6 @@
]).
/**
@defgroup MYDDAS The MYDDAS Data-base interface.
@ingroup YAPPackages
@{
The MYDDAS database project was developed within a FCT project aiming at
the development of a highly efficient deductive database system, based
on the coupling of the MySQL relational database system with the YAP
Prolog system. MYDDAS was later expanded to support the ODBC interface.
*/
/** @defgroup Requirements_and_Installation_Guide Requirements and Installation Guide
ee
Next, we describe how to usen of the YAP with the MYDDAS System. The
use of this system is entirely depend of the MySQL development libraries
or the ODBC development libraries. At least one of the this development
libraries must be installed on the computer system, otherwise MYDDAS
will not compile. The MySQL development libraries from MySQL 3.23 an
above are know to work. We recommend the usage of MySQL versus ODBC,
but it is possible to have both options installed
At the same time, without any problem. The MYDDAS system automatically
controls the two options. Currently, MYDDAS is know to compile without
problems in Linux. The usage of this system on Windows has not been
tested yet. MYDDAS must be enabled at configure time. This can be done
with the following options:
+ --enable-myddas
This option will detect which development libraries are installed on the computer system, MySQL, ODBC or both, and will compile the Yap system with the support for which libraries it detects;
+ --enable-myddas-stats
This option is only available in MySQL. It includes code to get
statistics from the MYDDAS system;
+ --enable-top-level
This option is only available in MySQL. It enables the option to interact with the MySQL server in
two different ways. As if we were on the MySQL Client Shell, and as if
we were using Datalog.
*/
%% @}
/** @defgroup MYDDAS_Architecture MYDDAS Architecture
@ingroup MYDDAS
@{
The system includes four main blocks that are put together through the
MYDDAS interface: the Yap Prolog compiler, the MySQL database system, an
ODBC level and a Prolog to SQL compiler. Current effort is put on the
MySQL interface rather than on the ODBC interface. If you want to use
the full power of the MYDDAS interface we recommend you to use a MySQL
database. Other databases, such as Oracle, PostGres or Microsoft SQL
Server, can be interfaced through the ODBC layer, but with limited
performance and features support.
The main structure of the MYDDAS interface is simple. Prolog queries
involving database goals are translated to SQL using the Prolog to SQL
compiler; then the SQL expression is sent to the database system, which
returns the set of tuples satisfying the query; and finally those tuples
are made available to the Prolog engine as terms. For recursive queries
involving database goals, the YapTab tabling engine provides the
necessary support for an efficient evaluation of such queries.
An important aspect of the MYDDAS interface is that for the programmer
the use of predicates which are defined in database relations is
completely transparent. An example of this transparent support is the
Prolog cut operator, which has exactly the same behaviour from
predicates defined in the Prolog program source code, or from predicates
defined in database as relations.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Name = 'John Doe',
Number = 123456789 ?
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Backtracking can then be used to retrieve the next row
of the relation phonebook. Records with particular field values may be
selected in the same way as in Prolog. (In particular, no mode
specification for database predicates is required). For instance:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- phonebook(Letter,'John Doe',Letter).
Letter = 'D',
Number = 123456789 ?
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generates the query
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SELECT A.Letter , 'John Doe' , A.Number
FROM 'phonebook' A
WHERE A.Name = 'John Doe';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
%% @}
/** @defgroup View_Level_Interface View Level Interface
@ingroup MYDDAS
@{
*/
/**
@pred db view(+,+,+).
@pred db view(+,+).
If we import a database relation, such as an edge relation representing the edges of a directed graph, through
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_import('Edge',edge).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
sqliand we then write a query to retrieve all the direct cycles in the
graph, such as
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- edge(A,B), edge(B,A).
A = 10,
B = 20 ?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this is clearly inefficient [3], because of relation-level
access. Relation-level access means that a separate SQL query will be
generated for every goal in the body of the clause. For the second
`edge/2` goal, a SQL query is generated using the variable bindings that
result from the first `edge/2` goal execution. If the second
`edge/2` goal
fails, or if alternative solutions are demanded, backtracking access the
next tuple for the first `edge/2` goal and another SQL query will be
generated for the second `edge/2` goal. The generation of this large
number of queries and the communication overhead with the database
system for each of them, makes the relation-level approach inefficient.
To solve this problem the view level interface can be used for the
definition of rules whose bodies includes only imported database
predicates. One can use the view level interface through the predicates
db_view/3 and `db_view/2`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_view(Conn,PredName(Arg_1,...,Arg_n),DbGoal).
?- db_view(PredName(Arg_1,...,Arg_n),DbGoal).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All arguments are standard Prolog terms. _Arg1_ through _Argn_
define the attributes to be retrieved from the database, while
_DbGoal_ defines the selection restrictions and join
conditions. _Conn_ is the connection identifier, which again can be
dropped. Calling predicate `PredName/n` will retrieve database
tuples using a single SQL query generated for the _DbGoal_. We next show
an example of a view definition for the direct cycles discussed
above. Assuming the declaration:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_import('Edge',edge).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
we
write:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_view(direct_cycle(A,B),(edge(A,B), edge(B,A))).
yes
?- direct_cycle(A,B)).
A = 10,
B = 20 ?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This call generates the SQL
statement:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SELECT A.attr1 , A.attr2
FROM Edge A , Edge B
WHERE B.attr1 = A.attr2 AND B.attr2 = A.attr1;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Backtracking, as in relational level interface, can be used to retrieve the next row of the view.
The view interface also supports aggregate function predicates such as
`sum`, `avg`, `count`, `min` and `max`. For
instance:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_view(count(X),(X is count(B, B^edge(10,B)))).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
generates the query :
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SELECT COUNT(A.attr2)
FROM Edge A WHERE A.attr1 = 10;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To know how to use db `view/3`, please refer to Draxler's Prolog to
SQL Compiler Manual.
*/
%% @}
/** @defgroup Accessing_Tables_in_Data_Sources_Using_SQL Accessing Tables in Data Sources Using SQL
@ingroup MYDDAS
@{
*/
/** @pred db_sql(+,+,?).
@pred db_sql(+,?).
It is also possible to explicitly send a SQL query to the database server using
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_sql(Conn,SQL,List).
?- db_sql(SQL,List).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
where _SQL_ is an arbitrary SQL expression, and _List_ is a list
holding the first tuple of result set returned by the server. The result
set can also be navigated through backtracking.
Example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_sql('SELECT * FROM phonebook',LA).
LA = ['D','John Doe',123456789] ?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
%% @}
/** @defgroup Insertion_of_Rows Insertion of Rows
@ingroup MYDDAS
@{
*/
/** @pred db_assert(+,+).
@pred db_assert(+).
Assuming you have imported the related base table using
`db_import/2` or db_import/3, you can insert to that table
by using db_assert/2 predicate any given fact.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_assert(Conn,Fact).
?- db_assert(Fact).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The second argument must be declared with all of its arguments bound to
constants. For example assuming `helloWorld` is imported through
`db_import/2`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_import('Hello World',helloWorld).
yes
?- db_assert(helloWorld('A' ,'Ana',31)).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This, would generate the following query
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
INSERT INTO helloWorld
VALUES ('A','Ana',3)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
which would insert into the helloWorld, the following row:
`A,Ana,31`. If we want to insert `NULL` values into the
relation, we call db_assert/2 with a uninstantiated variable in
the data base imported predicate. For example, the following query on
the YAP-prolog system:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_assert(helloWorld('A',NULL,31)).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Would insert the row: `A,null value,31` into the relation
`Hello World`, assuming that the second row allows null values.
*/
/** @pred db insert(+,+,+).
@pred db insert(+,+).
This predicate would create a new database predicate, which will insert
any given tuple into the database.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_insert(Conn,RelationName,PredName).
?- db_insert(RelationName,PredName).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This would create a new predicate with name _PredName_, that will
insert tuples into the relation _RelationName_. is the connection
identifier. For example, if we wanted to insert the new tuple
`('A',null,31)` into the relation `Hello World`, we do:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_insert('Hello World',helloWorldInsert).
yes
?- helloWorldInsert('A',NULL,31).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
%% @}
/** @defgroup Types_of_Attributes Types of AttributesL
@ingroup MYDDAS
@{
*/
/** @pred db_get_attributes_types(+,+,?).
@pred db_get_attributes_types(+,?).
The prototype for this predicate is the following:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_get_attributes_types(Conn,RelationName,ListOfFields).
?- db_get_attributes_types(RelationName,ListOfFields).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the
predicate `db_get_attributes types/2` or db_get_attributes_types/3, to
know what are the names and attributes types of the fields of a given
relation. For example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_get_attributes_types(myddas,'Hello World',LA).
LA = ['Number',integer,'Name',string,'Letter',string] ?
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
where <tt>Hello World</tt> is the name of the relation and <tt>myddas</tt> is the
connection identifier.
*/
%% @}
/** @defgroup Number_of_Fields Number of Fields
@ingroup MYDDAS
@{
*/
/** @pred db_number_of_fields(+,?).
@pred db_number_of_fields(+,+,?).
The prototype for this
predicate is the following:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_number_of_fields(Conn,RelationName,Arity).
?- db_number_of_fields(RelationName,Arity).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the predicate db_number_of_fields/2 or
`db_number_of_fields/3` to know what is the arity of a given
relation. Example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_number_of_fields(myddas,'Hello World',Arity).
Arity = 3 ?
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
where `Hello World` is the name of the
relation and `myddas` is the connection identifier.
*/
%% @}
/** @defgroup Describing_a_Relation Describing a Relation
@ingroup MYDDAS
@{
*/
/** @pred db_datalog_describe(+,+).
@pred db_datalog_describe(+).
The db `datalog_describe/2` predicate does not really returns any
value. It simply prints to the screen the result of the MySQL describe
command, the same way as `DESCRIBE` in the MySQL prompt would.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_datalog_describe(myddas,'Hello World').
+----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
+ Number | int(11) | YES | | NULL | |
+ Name | char(10) | YES | | NULL | |
+ Letter | char(1) | YES | | NULL | |
+----------+----------+------+-----+---------+-------+
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/** @pred db_describe(+,+).
@pred db_describe(+)
The `db_describe/3` predicate does the same action as
db_datalog_describe/2 predicate but with one major
difference. The results are returned by backtracking. For example, the
last query:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_describe(myddas,'Hello World',Term).
Term = tableInfo('Number',int(11),'YES','',null(0),'') ? ;
Term = tableInfo('Name',char(10),'YES','',null(1),'' ? ;
Term = tableInfo('Letter',char(1),'YES','',null(2),'') ? ;
no
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
%% @}
/** @defgroup Enumerating_Relations Enumeration Relations Describing_a_Relation Describing a Relation
@ingroup MYDDAS
@{
*/
/** @pred db_datalog_show_tables(+).
@pred db_datalog_show_tables
If we need to know what relations exists in a given MySQL Schema, we can use
the `db_datalog_show_tables/1` predicate. As <tt>db_datalog_describe/2</tt>,
it does not returns any value, but instead prints to the screen the result of the
`SHOW TABLES` command, the same way as it would be in the MySQL prompt.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_datalog_show_tables(myddas).
+-----------------+
| Tables_in_guest |
+-----------------+
| Hello World |
+-----------------+
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/** @pred db_show_tables(+, ?).
@pred db_show_tables(?)
The db_show_tables/2 predicate does the same action as
`db_show_tables/1` predicate but with one major difference. The
results are returned by backtracking. For example, given the last query:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_show_tables(myddas,Table).
Table = table('Hello World') ? ;
no
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
%%@}
/** @defgroup The_MYDDAS_MySQL_Top_Level The MYDDAS MySQL Top Level
@ingroup MYDDAS
@{
*/
/**
@pred db_top_level(+,+,+,+,+).
@pred db_top_level(+,+,+,+).
Through MYDDAS is also possible to access the MySQL Database Server, in
the same wthe mysql client. In this mode, is possible to query the
SQL server by just using the standard SQL language. This mode is exactly the same as
different from the standard mysql client. We can use this
mode, by invoking the db top level/5. as one of the following:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_top_level(mysql,Connection,Host/Database,User,Password).
?- db_top_level(mysql,Connection,Host/Database/Port,User,Password).
?- db_top_level(mysql,Connection,Host/Database/UnixSocket,User,Password).
?- db_top_level(mysql,Connection,Host/Database/Port/UnixSocket,User,Password).
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage is similar as the one described for the db_open/5 predicate
discussed above. If the login is successful, automatically the prompt of
the mysql client will be used. For example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_top_level(mysql,con1,localhost/guest_db,guest,'').
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
opens a
connection identified by the `con1` atom, to an instance of a MySQL server
running on host `localhost`, using database guest `db` and user `guest` with
empty password. After this is possible to use MYDDAS as the mysql
client.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_top_level(mysql,con1,localhost/guest_db,guest,'').
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor.
Commands end with ; or \g.
Your MySQL connection id is 4468 to server version: 4.0.20
Type 'help;' or '\h' for help.
Type '\c' to clear the buffer.
mysql> exit
Bye
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
%%@}
/** @defgroup Other_MYDDAS_Properties Other MYDDAS Properties
@ingroup MYDDAS
@{
*/
/**
@pred db_verbose(+).
When we ask a question to YAP, using a predicate asserted by
db_import/3, or by db_view/3, this will generate a SQL
`QUERY`. If we want to see that query, we must to this at a given
point in our session on YAP.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_verbose(1).
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we want to
disable this feature, we must call the `db_verbose/1` predicate with the value 0.
\
*/
/**
@pred db_top_level(+,+,+,+).
*/
/** @pred db_module(?).
When we create a new database predicate, by using db_import/3,
db_view/3 or db_insert/3, that predicate will be asserted
by default on the `user` module. If we want to change this value, we can
use the db_module/1 predicate to do so.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_module(lists).
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
By executing this predicate, all of the predicates asserted by the
predicates enumerated earlier will created in the lists module.
If we want to put back the value on default, we can manually put the
value user. Example:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_module(user).
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We can also see in what module the predicates are being asserted by doing:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_module(X).
X=user
yes
?-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/** @pred db_my_result_set(?).
The MySQL C API permits two modes for transferring the data generated by
a query to the client, in our case YAP. The first mode, and the default
mode used by the MYDDAS-MySQL, is to store the result. This mode copies all the
information generated to the client side.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_my_result_set(X).
X=store_result
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The other mode that we can use is use result. This one uses the result
set created directly from the server. If we want to use this mode, he
simply do
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?- db_my_result_set(use_result).
yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
After this command, all
of the database predicates will use use result by default. We can change
this by doing again `db_my_result_set(store_result)`.
*/
/** @pred db_my_sql_mode(+Conn,?SQL_Mode).
@pred db_my_sql_mode(?SQL_Mode).
The MySQL server allows the user to change the SQL mode. This can be
very useful for debugging proposes. For example, if we want MySQL server
not to ignore the INSERT statement warnings and instead of taking
action, report an error, we could use the following SQL mode.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
?-db_my_sql_mode(traditional). yes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can see the available SQL Modes at the MySQL homepage at
<http://www.mysql.org>.
*/
%% @}
@@ -837,7 +158,7 @@
c_sqlite3_query/5,
sqlite3_result_set/1,
c_sqlite3_number_of_fields/3
]).
#endif /* MYDDAS_MYSQL */
@@ -1089,7 +410,7 @@ db_open(odbc,Connection,ODBCEntry,User,Password) :-
set_value(Connection,Con).
#endif
#ifdef MYDDAS_SQLITE3
db_open(sqlite3,Connection,File,User,Password) :-
db_open(sqlite3,Connection,File,User,Password) :-
'$error_checks'(db_open(sqlite3,Connection,File,User,Password)),
c_sqlite3_connect(File,User,Password,Con),
set_value(Connection,Con).
@@ -1456,7 +777,7 @@ db_update(Connection,WherePred-SetPred):-
( ConType == mysql ->
db_my_result_set(Mode),
c_db_my_query(SQL,_,Conn,Mode,_)
;
;
ConType == mysql ->
postgres_result_set(Mode),
c_postgres_query(SQL,_,Conn,Mode,_)

View File

@@ -1,7 +1,5 @@
@defgroup YAPRaptor An RDF Reader for YAP.
@ingroup YAPPackages
#YAP raptor Interface
WWW Reader/Writers for YAP. (#YAPRaptor)
###########################
This provides YAP a rdf reader using
[raptor](http://librdf.org/raptor/). The library is available for
@@ -21,3 +19,5 @@ Predicate = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type',
Subject = 'http://www.example.org/law_and_order_ci' ?
~~~~{.prolog}
The code also includes a library under developent to connect Yap and libXML2.

View File

@@ -1,10 +1,228 @@
The R Prolog Progrmming Interface (#real)
===================================
Real
---
@file real.pl
@author Nicos Angelopoulos
@author Vitor Santos Costa
@version 1:0:4, 2013/12/25, sinter_class
@license Perl Artistic License
@defgroup libReal An interface to the R statistical software.
@ingroup packages
Real is a c-based interface for connecting R to Prolog.
YAP introduces a development version of real, developed to experiment
This library enables the communication with an R process started as a shared library.
It is the result of the efforts of two research groups that have worked in parallel.
The syntactic emphasis on a minimalistic interface.
In the doc/ directory of the distribution there is user's guide, a published paper
and html documentation from PlDoc (doc/html/real.html). There is large number
of examples in `examples/for_real.pl`.
A single predicate (<-/2,<-/1) channels
the bulk of the interactions. In addition to using R as a shared library, real uses
the c-interfaces of SWI/Yap and R to pass objects in both directions.
The usual mode of operation is to load Prolog values on to R variables and then call
R functions on these values. The return value of the called function can be either placed
on R variable or passed back to Prolog. It has been tested extensively on current
SWI and YAP on Linux machines but it should also compile and work on MS operating systems and Macs.
The main modes for utilising the interface are
~~~~
<- +Rexpr
<- +Rvar
~~~~
Print Rvar or evaluate expression Rexpr in R
~~~~
+Rvar <- +PLdata
+Rexpr <- +PLdata
-PLvar <- +Rvar
-PLvar <- +Rexpr
+Rexpr1 <- +Rexpr2
~~~~
Pass Prolog data to R, pass R data to Prolog or assign an R expression to
an assignable R expression.
@defgroup TestingR Testing Real
There is a raft of examples packed in a singl```e file that test the library.
~~~~
?- [pack(real/examples/for_real)].
?- for_real.
?- edit( pack(real/examples/for_real) ).
~~~~
@defgroup RSyntax Prolog and R Syntax
There are syntactic conventions in R that make unparsable prolog code.
Notably function and variable names are allowed to contain dots, square brackets are used
to access parts of vectors and arrays and functions are allowed empty argument tuples.
We have introduced relevant syntax which allows for easy transition between prolog and R.
Prolog constructs are converted by the library as follows:
* =|..|= within atoms -> =|.|= (ex. =| as..integer(c(1,2,3)) -> as.integer(c(1,2,3))|= )
* =|^[]|= after atoms -> =|[]|= (ex. =|a^[2] -> a[2] |=)
* =|(.)|= at the end of atoms that are known R functions -> =|()|= (ex. =|dev..off(.) -> dev.off()|= )
* =|[]|= -> c() (which equal to R's NULL value)
* ( f(x) :- (..)) -> f(x) (...)
* Lists of lists are converted to matrices. All first level lists must have the same length.
* Filenames must be given as Prolog strings.
* R specific operators (eg. %*% should be quoted in Prolog.
* + prepends strings, for (Prolog) atoms: +'String'
* Expressions that pose difficulty in translation can always be passed as unquoted Prolog atoms or strings.
]]* since 0:1:2 foo() is valid syntax: =|<- dev..off() |= works now (with no need for dev..off(.))
* since 0:1:2 mat[1] is valid syntax: =|m[1] <- 4|= works now (with no need for m^[...])
@defgroup RDataTransfer Mapping Data betweenn Prolog and R
R vectors are mapped to prolog lists and matrices are mapped to nested lists.
The convention works the other way around too.
There are two ways to pass prolog data to R. The more efficient one is by using
~~~~
Rvar <- PLdata
~~~~
Where Pldata is one of the basic data types (number,boolean) a list or a c/n term.
This transfers via C data between R and Prolog. In what follows atomic PLval data
are simply considered as singleton lists.
Flat Pldata lists are translated to R vectors and lists of one level of nesting to R matrices
(which are 2 dimensional arrays in R parlance). The type of values of the vector or matrice is
taken to be the type of the first data element of the Pldata according to the following :
* integer -> integer
* float -> double
* atom -> char
* boolean -> logical
Booleans are represented in prolog as true/false atoms.
Currently arrays of aribtrary dimensions are not supported in the low-level interface.
Note that in R a scalar is just a one element vector. When passing non-scalars the
interface will assume the type of the object is that of the first scalar until it encounters
something different.
Real will currently re-start and repopulate partial integers for floats as illustrated
below:
~~~~
r <- [1,2,3]. % pass 1,2,3 to an R vector r
R <- r. % pass contents of R vector r to Prolog variable R
R = [1, 2, 3].
i <- [1,2,3.1]. % r is now a vector of floats, rather than integers
I <- i.
I = [1.0, 2.0, 3.1].
~~~~
However, not all possible "corrections" are currently supported. For instance,
~~~~
?- c <- [a,b,c,1].
ERROR: real:set_R_variable/2: Type error: `boolean' expected, found `a'
~~~~
In the data passing mode we map Prolog atoms to R strings-
~~~~
?- x <- [abc,def].
true.
?- <- x.
[1] "abc" "def"
true.
?- X <- x.
X = [abc, def].
~~~~
In addition, Prolog data can be passed through the expression mechanism.
That is, data appearing in an arbitrary R expression will be parsed and be part of the long
string that will be passed from Prolog to R for evaluation.
This is only advisable for short data structures. For instance,
~~~~
tut_4a :-
state <- c(+"tas", +"sa", +"qld", +"nsw", +"nsw"),
<- state.
tut_4b :-
state <- c(+tas, +sa, +qld, +nsw, +nsw),
<- state.
~~~~
Through this interface it is more convenient to be explicit about R chars by Prolog prepending
atoms or codes with + as in the above example.
@defgroup RealExamples Examples
~~~~
?- e <- numeric(.).
yes
?- e^[3] <- 17.
yes
?- e[3] <- 17.
yes
?- Z <- e.
Z = ['$NaN','$NaN',17.0]
?- e^[10] <- 12.
yes
?- Z <- e.
Z = ['$NaN','$NaN',17.0,'$NaN','$NaN','$NaN','$NaN','$NaN','$NaN',12.0]
rtest :-
y <- rnorm(50), % get 50 random samples from normal distribution
<- y, % print the values via R
x <- rnorm(y), % get an equal number of normal samples
<- x11(width=5,height=3.5), % create a plotting window
<- plot(x,y) % plot the two samples
r_wait, % wait for user to hit Enter
% <- dev..off(.). % old syntax, still supported
<- dev.off(). % close the plotting window. foo() now acceptable in supported Prologs
tut6 :-
d <- outer(0:9, 0:9),
fr <- table(outer(d, d, "-")),
<- plot(as..numeric(names(fr)), fr, type="h", xlab="Determinant", ylab="Frequency").
tut4b :-
state <- [tas,sa,qld,nsw,nsw,nt,wa],
statef <- factor(state),
incmeans <- tapply( c(60, 49, 40, 61, 64, 60, 59), statef, mean ),
<- incmeans.
logical :-
t <- [1,2,3,4,5,1],
s <- t~~~~1,
<- s,
S <- s,
write( s(S) ), nl.
~~~~
#### Info
@see http://stoics.org.uk/~nicos/sware/real
@see pack(real/examples/for_real)
@see pack(real/doc/real.html)
@see pack(real/doc/guide.pdf)
@see pack(real/doc/padl2013-real.pdf)
@see http://www.r-project.org/
Also @subpaage yap-real describes the YAP specfic details in real.
*/Development of real in YAP (#yap-real)
---------------------------
YAP includes a development version of real, designed to experiment
with the internals of the implementation of R. It includes major
changes and is likely to be much less stable than the version
maintained by Nicos ANgelopoulos. We refer to the version herein as
@@ -56,4 +274,3 @@ March, 2014
Updates: Vitor Santos Costa
Dec. 2015

View File

@@ -10,15 +10,6 @@
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/**
@file real.pl
@author Nicos Angelopoulos
@author Vitor Santos Costa
@version 1:0:4, 2013/12/25, sinter_class
@license Perl Artistic License
*/
:- module(real, [
start_r/0,
@@ -76,220 +67,6 @@
%:- set_prolog_flag(double_quotes, string ).
/** @defgroup libReal An interface to the R statistical software.
@ingroup packages
#### Introduction
This library enables the communication with an R process started as a shared library.
It is the result of the efforts of two research groups that have worked in parallel.
The syntactic emphasis on a minimalistic interface.
In the doc/ directory of the distribution there is user's guide, a published paper
and html documentation from PlDoc (doc/html/real.html). There is large number
of examples in `examples/for_real.pl`.
A single predicate (<-/2,<-/1) channels
the bulk of the interactions. In addition to using R as a shared library, real uses
the c-interfaces of SWI/Yap and R to pass objects in both directions.
The usual mode of operation is to load Prolog values on to R variables and then call
R functions on these values. The return value of the called function can be either placed
on R variable or passed back to Prolog. It has been tested extensively on current
SWI and YAP on Linux machines but it should also compile and work on MS operating systems and Macs.
The main modes for utilising the interface are
~~~~
<- +Rexpr
<- +Rvar
~~~~
Print Rvar or evaluate expression Rexpr in R
~~~~
+Rvar <- +PLdata
+Rexpr <- +PLdata
-PLvar <- +Rvar
-PLvar <- +Rexpr
+Rexpr1 <- +Rexpr2
~~~~
Pass Prolog data to R, pass R data to Prolog or assign an R expression to
an assignable R expression.
#### Testing
There is a raft of examples packed in a singl```e file that test the library.
~~~~
?- [pack(real/examples/for_real)].
?- for_real.
?- edit( pack(real/examples/for_real) ).
~~~~
#### Syntax
There are syntactic conventions in R that make unparsable prolog code.
Notably function and variable names are allowed to contain dots, square brackets are used
to access parts of vectors and arrays and functions are allowed empty argument tuples.
We have introduced relevant syntax which allows for easy transition between prolog and R.
Prolog constructs are converted by the library as follows:
* =|..|= within atoms -> =|.|= (ex. =| as..integer(c(1,2,3)) -> as.integer(c(1,2,3))|= )
* =|^[]|= after atoms -> =|[]|= (ex. =|a^[2] -> a[2] |=)
* =|(.)|= at the end of atoms that are known R functions -> =|()|= (ex. =|dev..off(.) -> dev.off()|= )
* =|[]|= -> c() (which equal to R's NULL value)
* ( f(x) :- (..)) -> f(x) (...)
* Lists of lists are converted to matrices. All first level lists must have the same length.
* Filenames must be given as Prolog strings.
* R specific operators (eg. %*% should be quoted in Prolog.
* + prepends strings, for (Prolog) atoms: +'String'
* Expressions that pose difficulty in translation can always be passed as unquoted Prolog atoms or strings.
]]* since 0:1:2 foo() is valid syntax: =|<- dev..off() |= works now (with no need for dev..off(.))
* since 0:1:2 mat[1] is valid syntax: =|m[1] <- 4|= works now (with no need for m^[...])
#### Data transfers
R vectors are mapped to prolog lists and matrices are mapped to nested lists.
The convention works the other way around too.
There are two ways to pass prolog data to R. The more efficient one is by using
~~~~
Rvar <- PLdata
~~~~
Where Pldata is one of the basic data types (number,boolean) a list or a c/n term.
This transfers via C data between R and Prolog. In what follows atomic PLval data
are simply considered as singleton lists.
Flat Pldata lists are translated to R vectors and lists of one level of nesting to R matrices
(which are 2 dimensional arrays in R parlance). The type of values of the vector or matrice is
taken to be the type of the first data element of the Pldata according to the following :
* integer -> integer
* float -> double
* atom -> char
* boolean -> logical
Booleans are represented in prolog as true/false atoms.
Currently arrays of aribtrary dimensions are not supported in the low-level interface.
Note that in R a scalar is just a one element vector. When passing non-scalars the
interface will assume the type of the object is that of the first scalar until it encounters
something different.
Real will currently re-start and repopulate partial integers for floats as illustrated
below:
~~~~
r <- [1,2,3]. % pass 1,2,3 to an R vector r
R <- r. % pass contents of R vector r to Prolog variable R
R = [1, 2, 3].
i <- [1,2,3.1]. % r is now a vector of floats, rather than integers
I <- i.
I = [1.0, 2.0, 3.1].
~~~~
However, not all possible "corrections" are currently supported. For instance,
~~~~
?- c <- [a,b,c,1].
ERROR: real:set_R_variable/2: Type error: `boolean' expected, found `a'
~~~~
In the data passing mode we map Prolog atoms to R strings-
~~~~
?- x <- [abc,def].
true.
?- <- x.
[1] "abc" "def"
true.
?- X <- x.
X = [abc, def].
~~~~
In addition, Prolog data can be passed through the expression mechanism.
That is, data appearing in an arbitrary R expression will be parsed and be part of the long
string that will be passed from Prolog to R for evaluation.
This is only advisable for short data structures. For instance,
~~~~
tut_4a :-
state <- c(+"tas", +"sa", +"qld", +"nsw", +"nsw"),
<- state.
tut_4b :-
state <- c(+tas, +sa, +qld, +nsw, +nsw),
<- state.
~~~~
Through this interface it is more convenient to be explicit about R chars by Prolog prepending
atoms or codes with + as in the above example.
#### Examples
~~~~
?- e <- numeric(.).
yes
?- e^[3] <- 17.
yes
?- e[3] <- 17.
yes
?- Z <- e.
Z = ['$NaN','$NaN',17.0]
?- e^[10] <- 12.
yes
?- Z <- e.
Z = ['$NaN','$NaN',17.0,'$NaN','$NaN','$NaN','$NaN','$NaN','$NaN',12.0]
rtest :-
y <- rnorm(50), % get 50 random samples from normal distribution
<- y, % print the values via R
x <- rnorm(y), % get an equal number of normal samples
<- x11(width=5,height=3.5), % create a plotting window
<- plot(x,y) % plot the two samples
r_wait, % wait for user to hit Enter
% <- dev..off(.). % old syntax, still supported
<- dev.off(). % close the plotting window. foo() now acceptable in supported Prologs
tut6 :-
d <- outer(0:9, 0:9),
fr <- table(outer(d, d, "-")),
<- plot(as..numeric(names(fr)), fr, type="h", xlab="Determinant", ylab="Frequency").
tut4b :-
state <- [tas,sa,qld,nsw,nsw,nt,wa],
statef <- factor(state),
incmeans <- tapply( c(60, 49, 40, 61, 64, 60, 59), statef, mean ),
<- incmeans.
logical :-
t <- [1,2,3,4,5,1],
s <- t~~~~1,
<- s,
S <- s,
write( s(S) ), nl.
~~~~
#### Info
@see http://stoics.org.uk/~nicos/sware/real
@see pack(real/examples/for_real)
@see pack(real/doc/real.html)
@see pack(real/doc/guide.pdf)
@see pack(real/doc/padl2013-real.pdf)
@see http://www.r-project.org/
*/
%%%
init_r_env :-

View File

@@ -1,5 +1,4 @@
User Defined Indexers.
======================
User-Defined Indexing (#yap-udi-indexers)
=====================
YAP UDI indexers.