Subsections


2. Module Contents

This chapter gives a detailed description of top-level functions and constants in the PyCLIPS module. It's not intended to be a CLIPS reference: the official CLIPS Reference Guide still remains the main source of documentation for this. This Guide will often be referred to for information about the engine itself, and the user is expected to know the CLIPS language and structure sufficiently with respect to his goals.

Although the PyCLIPS user is not supposed to know CLIPS API, it is advisable to have its reference at least at hand to sometimes understand how PyCLIPS interacts with CLIPS itself. Besides the programmatic approach offered by PyCLIPS is vastly different to the C API - with the occasional exception of the intrinsic logic.

We will first describe the top level functions.


2.1 Top Level Functions and Constants


2.1.1 Constants

Several constants are provided in order to configure CLIPS environment or to instruct some functions to behave in particular ways.

2.1.1.1 Scope Save Constants

Constants to decide what to save in CLIPS dump files (see the SaveInstances(), BSaveInstances() and SaveFacts() functions).

Constant Description
LOCAL_SAVE save objects having templates defined in current Module
VISIBLE_SAVE save all objects visible to current Module

2.1.1.2 Salience Evaluation Constants

Constants to tell the underlying engine when salience has to be evaluated (see the EngineConfig.SalienceEvaluation property).

Constant Description
WHEN_DEFINED evaluate salience on rule definition (the default)
WHEN_ACTIVATED evaluate salience on rule activation (dynamic salience)
EVERY_CYCLE evaluate salience on every execution cycle (dynamic salience)

2.1.1.3 Conflict Resolution Strategy Constants

Constants to specify the way the underlying engine should resolve conflicts among rules having the same salience (see the EngineConfig.Strategy property).

Constant Description
DEPTH_STRATEGY newly activated rule comes first
BREADTH_STRATEGY newly activated rule comes last
LEX_STRATEGY strategy based on time tags applied to facts
MEA_STRATEGY strategy based on time tags applied to facts
COMPLEXITY_STRATEGY newly activated rule comes before rules of lower specificity
SIMPLICITY_STRATEGY newly activated rule comes before rules of higher specificity
RANDOM_STRATEGY assign place in agenda randomly

In the table above, the term specificity refers to the number of comparisons in the LHS of a rule.

2.1.1.4 Class Definition Default Mode Constants

Constants to specify default mode used for classes definition. Please refer to Clips Reference Guide Vol. I: Basic Programming Guide for details about the usage of the two modes, as the meaning is quite complex and outside the scope of this manual (see the EngineConfig.ClassDefaultsMode property).

Constant Description
CONVENIENCE_MODE set the default class mode to convenience
CONSERVATION_MODE set the default class mode to conservation

2.1.1.5 Message Handler Type Constants

Constants to define the execution time, the purpose and the behaviour of message handlers: see function BuildMessageHandler() and the following members of the Class class: AddMessageHandler() and FindMessageHandler(). The following table summarizes the analogous one found in Clips Reference Guide Vol. I: Basic Programming Guide.

Constant Description
AROUND only to set up an environment for the message
AFTER to perform auxiliary work after the primary message
BEFORE to perform auxiliary work before the primary message
PRIMARY to perform most of the work for the message

2.1.1.6 Template Slot Default Type Constants

It's possible to inspect whether or not a Template slot has been defined to have a default value, and in case it is, if its default value is static (that is, constant) or dynamically generated (for instance, using a function like gensym). See the documentation of Template for more details.

Constant Description
NO_DEFAULT the slot has no default value
STATIC_DEFAULT the default value is a constant
DYNAMIC_DEFAULT the default value is dynamically generated

Notice that NO_DEFAULT evaluates to False, so it's legal to use the Template.Slot.HasDefault() function just to test the presence of a default value. Please also note that NO_DEFAULT is only returned when the default value for a slot is set to ?NONE as stated in the Clips Reference Guide Vol. II: Advanced Programming Guide.


2.1.2 Functions

AgendaChanged( )
test whether or not Agenda has changed since last call.

Assert( o)
Assert a Fact (already created or from a string). This perhaps needs some explanation: CLIPS allows the creation of facts based on Templates, and in PyCLIPS this is done by instancing a Fact with a Template argument. The resulting Fact slots can then be modified and the object can be used to make an assertion, either by using the Fact Assert() function or this version od Assert().

BLoad( filename)
Load the constructs from a binary file named filename. Binary files are not human-readable and contain all the construct information.

BLoadInstances( filename)
Load Instances from binary file named filename. Binary files are not human-readable and contain all the construct information.

BSave( filename)
Save constructs to a binary file named filename.

BSaveInstances( filename [, mode=LOCAL_SAVE])
Save Instances to binary file named filename. The mode parameter can be one of LOCAL_SAVE (for all Instances whose Definstances are defined in current Module) or VISIBLE_SAVE (for all Instances visible to current Module).

BatchStar( filename)
Execute commands stored in text file named as specified in filename.

BrowseClasses( name)
Print the list of Classes that inherit from specified one.

Build( construct)
Build construct given in argument as a string. The string must enclose a full construct in the CLIPS language.

BuildClass( name, text [, comment])
Build a Class with specified name and body. comment is the optional comment to give to the object. This function is the only one that can be used to create Classes with multiple inheritance.

BuildDeffacts( name, text [, comment])
Build a Deffacts object with specified name and body. comment is the optional comment to give to the object.

BuildDefinstances( name, text [, comment])
Build a Definstances having specified name and body. comment is the optional comment to give to the object.

BuildFunction( name, args, text [, comment])
Build a Function with specified name, arguments and body. comment is the optional comment to give to the object. args can be either a blank-separated string containing argument names, or a sequence of strings corresponding to argument names. Such argument names should be coherent to the ones used in the function body (that is, text). The argument list, if expressed as a string, should not be surrounded by brackets. None can also be used as the argument list if the function has no arguments.

BuildGeneric( name, text [, comment])
Build a Generic with specified name and body. comment is the optional comment to give to the object.

BuildGlobal( name, [, value])
Build a Global variable with specified name and value. The value parameter can be of any of the types supported by CLIPS: it can be expressed as a Python value (with type defined in Python: the module will try to pass to CLIPS a value of an according type), but for types that normally do not exist in Python (such as Symbols) an explicit conversion is necessary. If the value is omitted, then the module assigns Nil to the variable.

BuildInstance( name, defclass [, overrides])
Build an Instance of given Class overriding specified slots. If no slot is specified to be overridden, then the Instance will assume default values.

BuildMessageHandler( name, class, args, text [, type, comment])
Add a new message handler to the supplied class, with specified name, body (the text argument) and argument list: this can be specified either as a sequence of variable names or as a single string of whitespace separated variable names. Variable names (expressed as strings) can also be wildcard parameters, as specified in the Clips Reference Guide Vol. I: Basic Programming Guide. The type parameter should be one of AROUND, AFTER, BEFORE, PRIMARY defined at the module level: if omitted it will be considered as PRIMARY. The body must be enclosed in brackets, as it is in CLIPS syntax. The function returns the index of the message handler within the specified Class.

BuildModule( name [, text, comment])
Build a Module with specified name and body. comment is the optional comment to give to the object. The current Module is set to the new one.

BuildRule( name, lhs, rhs [, comment])
Build a Rule object with specified name and body. comment is the optional comment to give to the object. The lhs and rhs parameters correspond to the left-hand side and right-hand side of a Rule.

BuildTemplate( name, text [, comment])
Build a Template object with specified name and body. comment is the optional comment to give to the object.

Call( func, args)
Call a CLIPS internal Function with the given argument string. The args parameter, in its easiest form, can be a list of arguments separated by blank characters using CLIPS syntax. There are other forms that can be used, depending on how many arguments the called function requires: if it accepts a single argument, the caller can just specify the argument2.1possibly cast using one of the wrapper classes described below. When the function accepts multiple arguments it is possible to specify them as a sequence of values (either a list or a tuple) of basic2.2values. It is always preferable to convert these values using the wrapper classes in order to avoid ambiguity, especially in case of string arguments.

ClassList( )
Return the list of Class names.

Clear( )
Clear current Environment.

ClearPythonFunctions( )
Unregister all user defined Python functions from PyCLIPS.

ClearFocusStack( )
Clear focus stack.

CurrentEnvironment( )
Return an Environment object representing current CLIPS environment. This is useful for switching between environments in a PyCLIPS session. Please note that almost all environment operations are disallowed on the returned object until another Environment is selected as current: all operations on current Environment should be performed using the top level module functions.

CurrentModule( )
Return current module as a Module object.

DeffactsList( )
Return a list of Deffacts names in current Module.

DefinstancesList( )
Retrieve list of all Definstances names.

Eval( expr)
Evaluate expression passed as argument. Expressions that only have side effects (e.g. printout expressions) return None.

ExternalTracebackEnabled( )
Return True if functions called from within CLIPS using the engine function python-call will print a standard traceback to sys.stderr on exceptions, False otherwise. This function is retained for backwards compatibility only: please use the ExternalTraceback flag of the DebugConfig object to enable or disable this feature instead.

FactList( )
Return list of Facts in current Module.

FactListChanged( )
Test whether Fact list is changed since last call.

FindClass( name)
Find a Class by name.

FindDeffacts( name)
Find a Deffacts by name.

FindDefinstances( name)
Find a Definstances by name.

FindFunction( name)
Find a Function by name.

FindGeneric( name)
Find a Generic function by name.

FindGlobal( name)
Find a Global variable by name.

FindInstance( name)
Find an Instance in all Modules (including imported).

FindInstanceLocal( name)
Find an Instance in non imported Modules.

FindModule( name)
Find a Module in list by name.

FindRule( name)
Find a Rule by name.

FindTemplate( name)
Find a Template by name.

FocusStack( )
Get list of Module names in focus stack.

FunctionList( )
Return the list of Function names.

GenericList( )
Return the list of Generic names.

GlobalList( )
Return the list of Global variable names.

GlobalsChanged( )
Test whether or not Global variables have changed since last call.

InitialActivation( )
Return first Activation object in current CLIPS Environment.

InitialClass( )
Return first Class in current CLIPS Environment.

InitialDeffacts( )
Return first Deffacts in current CLIPS Environment.

InitialDefinstances( )
Return first Definstances in current CLIPS Environment.

InitialFact( )
Return first Fact in current CLIPS Environment.

InitialFunction( )
Return first Function in current CLIPS Environment.

InitialGeneric( )
Return first Generic in current CLIPS Environment.

InitialGlobal( )
Return first Global variable in current CLIPS Environment.

InitialInstance( )
Return first Instance in current CLIPS Environment.

InitialModule( )
Return first Module in current CLIPS Environment.

InitialRule( )
Return first Rule in current CLIPS Environment.

InitialTemplate( )
Return first Template in current CLIPS Environment.

InstancesChanged( )
Test if Instances have changed since last call.

Load( filename)
Load constructs from the specified file named filename.

LoadFacts( filename)
Load Facts from the specified file named filename.

LoadFactsFromString( s)
Load Facts from the specified string.

LoadInstances( filename)
Load Instances from file named filename.

LoadInstancesFromString( s)
Load Instances from the specified string.

MessageHandlerList( )
Return list of MessageHandler constructs.

MethodList( )
Return the list of all methods.

ModuleList( )
Return the list of Module names.

PopFocus( )
Pop focus.

PrintAgenda( )
Print Rules in Agenda to standard output.

PrintBreakpoints( )
Print a list of all breakpoints to standard output.

PrintClasses( )
Print a list of all Classes to standard output.

PrintDeffacts( )
Print a list of all Deffacts to standard output.

PrintDefinstances( )
Print a list of all Definstances to standard output.

PrintFacts( )
Print Facts to standard output.

PrintFocusStack( )
Print focus stack to standard output.

PrintFunctions( )
Print a list of all Functions to standard output.

PrintGenerics( )
Print list of Generic functions to standard output.

PrintGlobals( )
print a list of Global variables to standard output

PrintInstances( [class])
Print a list of Instances to standard output. If the class argument is omitted, all Instances in the subsystem will be shown. The class parameter can be a Class object or a string containing a Class name.

PrintMessageHandlers( )
Print a list of all MessageHandlers.

PrintModules( )
Print a list of Modules to standard output.

PrintRules( )
Print a list of Rules to standard output.

PrintSubclassInstances( [class])
Print subclass Instances to standard output for the Class specified. If the class argument is omitted, all instances in the subsystem will be shown. The class parameter can be a string containing a Class name or a Class object.

PrintTemplates( )
Print Template names to standard output.

RefreshAgenda( )
Refresh Agenda Rules for current Module.

RegisterPythonFunction( callable [, name])
Register the function callable for use within CLIPS via the engine function python-call. If the parameter name of type str is not given, then the __name__ attribute of the first argument will be used. name is the name that will be used in CLIPS to refer to the function. See appendix for a more detailed explanation.

ReorderAgenda( )
Reorder Agenda Rules for current Module.

Reset( )
Reset current Environment.

RestoreInstancesFromString( s)
Restore Instances from the specified string.

RuleList( )
Return a list of Rule names in current Module.

Run( [limit])
Execute Rules up to limit (which is an int if given). If limit is omitted, then no limitation is assumed and the program runs countinuously until all rules are executed. The function returns the number of rules that have been fired2.3.

Save( filename)
Save constructs to the file specified by filename. The constructs are saved in text (human readable) form.

SaveFacts( filename [, mode=LOCAL_SAVE])
Save current Facts to file specified by filename. The mode parameter can be one of LOCAL_SAVE (for all Facts whose Templates are defined in current Module) or VISIBLE_SAVE (for all Facts visible to current Module).

SaveInstances( filename [, mode=LOCAL_SAVE])
Save Instances to file specified by filename. The mode parameter can be one of LOCAL_SAVE (for all Instances whose Definstances are defined in current Module) or VISIBLE_SAVE (for all Instances visible to current Module).

SendCommand( cmd [, verbose=False])
Send a command to the underlying CLIPS engine, as if it was typed at the console in an interactive CLIPS session. This command could actually be useful when embedding a CLIPS shell in a Python program. Please note that other input than commands, in such a case, should be entered using the StdinStream input stream. If verbose is set to True the possible2.4 command output is sent to the appropriate output stream.

SetExternalTraceback( [enabled=True])
Allow or disallow functions called from within the CLIPS engine using python-call to print a standard traceback to sys.stderr in case an exception occurs. Please note that this does not mean that a real exception arises, as there is no possibility to catch Python exceptions in CLIPS code. In such case all failing Python functions will return the symbol FALSE to CLIPS2.5. This behaviour is initially set to False, as it is useful only for debugging purposes. This function is retained for backwards compatibility only: please use the ExternalTraceback flag of the DebugConfig object to enable or disable this feature instead.

ShowGlobals( )
Print list of Global variables and their values to standard output (the PrintGlobals() functions only prints out Global variable names).

TemplateList( )
Return a list of Template names.

UnregisterPythonFunction( name)
Remove the function referred as name within the CLIPS engine from the set of functions that can be called via python-call calls.

Among other exception types, arising in cases that can also occur in Python, the PyCLIPS module can raise exceptions specific to CLIPS identified by the following:

exception ClipsError
Exception raised when an operation fails in the CLIPS subsystem: normally it occurs when CLIPS finds an error, when an iteration is over or when an invalid value is passed to CLIPS. This exception is accompanied by explanatory text preceded by an alphanumeric code that can be used to programmatically identify the error.

exception ClipsMemoryError
Severe memory error raised when the CLIPS subsystem is unable to allocate the needed memory. In normal circumstances, when an error of this type occurs, the CLIPS system has become inconsistent and the only way to recover is exiting. This exception is raised only in order to allow a developer to notify the user of the impossibility to continue.

See Also:

Clips Reference Guide Vol. II: Advanced Programming Guide
contains detailed information about CLIPS API and internal structures
Clips Reference Guide Vol. I: Basic Programming Guide
the main reference for the CLIPS language



Footnotes

... argument2.1
It must be of a type compatible with CLIPS. If a string is supplied, however, it will be considered as a list of arguments separated by whitespace: in order to explicitly pass a string it has either to be converted or to be specified surrounded by double quotes.
... basic2.2
Complex values, as multifield, are not supported: CLIPS does not allow external calls with non-constant arguments and there is no possibility to build a multifield in place without an explicit function call.
... fired2.3
This means, for instance, that continuously using this function and checking whether or not the result is less than the specified limit can give more control over the running CLIPS subprogram, eventually giving the ability to actively check for the end of the program.
... possible2.4
Except for the CLIPS printing functions, as for instance printout, that issue an output even when the flag is not set.
... CLIPS2.5
This is not always an error condition because a function can intentionally return boolean values to CLIPS. However the CLIPS engine will report an error message which can be read from the error stream.