topheader Welcome 18.206.194.83 @ research.scios.ch on Tue Sep 17 2:43:14 CEST 2019
 
topheader
 

PyXSI - CLIPS Expert System in Python

You need a XSI/CLIPS ENV library (DLL) and you have to adjust the path in the code below. Library source code for win32 is available on request either as MVC or Pelles C version.

Important Note

"""
THIS IS RESEARCH CODE PUBLISHED DUE TO REPEATED REQUESTS. USE AT YOUR OWN RISK. 
THERE IS ABSOLUTELY NO WARRANTY AND WE CANNOT PROVIDE ANY PUBLIC SUPPORT. 
CUSTOMERS HAVE TO LOGIN FOR SUPPORT REQUESTS.
"""

Code

# -*- coding: UTF-8 -*-
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#;;;    _____      _ ____  _____    _  _______ ____
#;;;   / ___/_____(_) __ \/ ___/    |/ / ___//  _/
#;;;   \__ \/ ___/ / / / /\__ \    |   /\__ \ / /
#;;;  ___/ / /__/ / /_/ /___/ /   /   |___/ // /
#;;; /____/\___/_/\____//____/   /_/_/____/___/
#;;;
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#;;; $Id:: xsi_env.py 13 2011-08-16 13:44:42Z scios                           $
#;;; (C) 1998-2011 SciOS Scientific Operating Systems GmbH
#;;; http://www.scios.ch
#;;; FOR INTERNAL USE ONLY.
#;;; HEAD URL: $HeadURL:: file:///F:/SVN/PyXSI/xsi_env.py                     $
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#;;; PROJECT ...............................: XSI
#;;; SUBPROJECT ............................: PyXSI
#;;; MODULE ................................: xsi_env.py
#;;; VERSION ...............................: 0.0.1
#;;; CREATION DATE .........................: 01.01.2000
#;;; MODIFICATION DATE .....................: 28.07.2011
#;;; PROGRAMMING LANGUAGE(S) ...............: Python
#;;; INTERPRETER/COMPILER ..................: Python 2.7 r27:82525
#;;; OPERATING SYSTEM(S) ...................: WIN32
#;;; CREATOR(S) ............................: kp
#;;; CLIENT(S) .............................: scios
#;;; URL ...................................: research.scios.ch
#;;; EMAIL .................................: xps@scios.ch
#;;; COPYRIGHT .............................: (C) 2011, SciOS GmbH
#;;; LICENSE ...............................: BSD-2
#;;; DEPENDENCIES ..........................: CTypes, XSI-ENV.dll
#;;; IMPORTS ...............................: see code below
#;;; EXPORTS ...............................: --
#;;; COMMENTS ..............................: XSI+ removed
#;;; SHORT DESCRIPTION .....................: XSI/CLIPS Python interface
#;;; DOCUMENTATION PATH ....................: --
#;;; IDE ...................................: PyScripter V 2.4.2.2
#;;; SVN REVISION ..........................: $Rev:: 13                       $
#;;; REVISION DATE .........................: $Date:: 2011-08-16 15:44:42 +02#$
#;;; REVISED BY ............................: $Author:: scios                 $
#;;; REVISION HISTORY ......................: --
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#
# Copyright (c) 2011, SciOS Scientific Operating Systems GmbH
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
#
#   Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#!/usr/bin/env python
 
"""
This module provides an interface to the XSI/CLIPS production system via
ctypes. The XSI-ENV library (written in ANSI C) is wrapped, and a lot of
functions are available as methods in the XSI class. The XSI class will
use only one environment since multi-environment processing can be done
with instances. It is however possible to use the library functions without
the class.
 
All exported functions of the library are listed below (an extract of the
definition file) and those that were wrapped into the XSI class are marked
with a '#' instead of a leading underscore.
 
NOTE: This is a public version of XSI-ENV, containing only the CLIPS env
functions and some utilities to fetch and convert several CLIPS structures.
There are no PostgreSQL, Scheme, IUP, ... functions as in XSI+. It makes
little sense anyway to incorporate that functionality into Python.
 
For a description of the C library functions, see
 
  CLIPS Reference Manual
  Volume II
  XSI/CLIPS Advanced Programming Guide
  http://xps.scios.ch/inet/doku.php?id=clips:apg
 
  or:
  CLIPS Online Documentation
  Advanced Programming Guide
  http://clipsrules.sourceforge.net/OnlineDocs.html
 
  The manuals are also included in the XSI/CLIPS distribution in various
  formats (pdf, djvu, odt, html).
 
 
(*)
ctypes is a foreign function library for Python. It provides C compatible
data types, and allows calling functions in DLLs or shared libraries.
It can be used to wrap these libraries in pure Python.
 
LIBRARY "XSI-ENV"
DESCRIPTION "SciOS XSI/CLIPS Environment Library, Release 27-07-2011"
STACKSIZE 100000000
VERSION 2.2
 
EXPORTS
    #CreateEnvironment
    #DestroyEnvironment
    _EnvActivateRouter
    _EnvAddBitMap
    _EnvAddClearFunction
    _EnvAddDouble
    _EnvAddExternalAddress
    _EnvAddLong
    _EnvAddPeriodicFunction
    _EnvAddResetFunction
    _EnvAddRouter
    _EnvAddRouterWithContext
    _EnvAddRunFunction
    _EnvAddRunFunctionWithContext
    _EnvAddSymbol
    _EnvAgenda
    _EnvArgCountCheck
    _EnvArgRangeCheck
    _EnvArgTypeCheck
    _EnvAssert
    #EnvAssertString
    _EnvAssignFactSlotDefaults
    _EnvBatchStar
    _EnvBinaryLoadInstances
    _EnvBinarySaveInstances
    _EnvBload
    _EnvBrowseClasses
    _EnvBsave
    #EnvBuild
    _EnvClassAbstractP
    _EnvClassReactiveP
    _EnvClassSlots
    _EnvClassSubclasses
    _EnvClassSuperclasses
    #EnvClear
    _EnvClearFocusStack
    _EnvCreateFact
    _EnvCreateMultifield
    _EnvCreateRawInstance
    _EnvDeactivateRouter
    _EnvDecrementFactCount
    _EnvDecrementGCLocks
    _EnvDecrementInstanceCount
    _EnvDefineFunction
    _EnvDefineFunction2
    _EnvDefineFunction2WithContext
    _EnvDefineFunctionWithContext
    _EnvDefruleHasBreakpoint
    _EnvDeftemplateSlotAllowedValues
    _EnvDeftemplateSlotCardinality
    _EnvDeftemplateSlotDefaultP
    _EnvDeftemplateSlotDefaultValue
    _EnvDeftemplateSlotExistP
    _EnvDeftemplateSlotFacetExistP
    _EnvDeftemplateSlotFacetValue
    _EnvDeftemplateSlotMultiP
    _EnvDeftemplateSlotNames
    _EnvDeftemplateSlotRange
    _EnvDeftemplateSlotSingleP
    _EnvDeftemplateSlotTypes
    _EnvDeleteActivation
    _EnvDeleteInstance
    _EnvDeleteRouter
    _EnvDescribeClass
    _EnvDirectGetSlot
    _EnvDirectPutSlot
    _EnvDribbleActive
    _EnvDribbleOff
    _EnvDribbleOn
    #EnvEval
    _EnvExitRouter
    _EnvFactDeftemplate
    _EnvFactExistp
    _EnvFactIndex
    #EnvFacts
    _EnvFactSlotNames
    _EnvFindDefclass
    _EnvFindDeffacts
    _EnvFindDeffunction
    _EnvFindDefgeneric
    _EnvFindDefglobal
    _EnvFindDefinstances
    _EnvFindDefmessageHandler
    _EnvFindDefmodule
    _EnvFindDefrule
    _EnvFindDeftemplate
    _EnvFindInstance
    _EnvFocus
    #EnvFunctionCall
    _EnvGetActivationBasisPPForm
    _EnvGetActivationName
    _EnvGetActivationPPForm
    _EnvGetAgendaChanged
    _EnvGetAutoFloatDividend
    _EnvGetBetaMemoryResizing
    _EnvGetClassDefaultsMode
    _EnvGetConserveMemory
    _EnvGetConstructNameString
    _EnvGetcRouter
    _EnvGetCurrentModule
    _EnvGetDefclassList
    _EnvGetDefclassWatchInstances
    _EnvGetDefclassWatchSlots
    _EnvGetDeffactsList
    _EnvGetDeffunctionList
    _EnvGetDeffunctionWatch
    _EnvGetDefgenericList
    _EnvGetDefgenericWatch
    _EnvGetDefglobalList
    _EnvGetDefglobalValue
    _EnvGetDefglobalValueForm
    _EnvGetDefglobalWatch
    _EnvGetDefinstancesList
    _EnvGetDefmessageHandlerList
    _EnvGetDefmessageHandlerName
    _EnvGetDefmessageHandlerPPForm
    _EnvGetDefmessageHandlerType
    _EnvGetDefmessageHandlerWatch
    _EnvGetDefmethodDescription
    _EnvGetDefmethodList
    _EnvGetDefmethodPPForm
    _EnvGetDefmethodWatch
    _EnvGetDefmoduleList
    _EnvGetDefmoduleName
    _EnvGetDefmodulePPForm
    _EnvGetDefruleList
    _EnvGetDefruleWatchActivations
    _EnvGetDefruleWatchFirings
    _EnvGetDeftemplateList
    _EnvGetDeftemplateWatch
    _EnvGetDynamicConstraintChecking
    _EnvGetFactDuplication
    #EnvGetFactList
    _EnvGetFactListChanged
    #EnvGetFactPPForm
    _EnvGetFactSlot
    _EnvGetFocus
    _EnvGetFocusChanged
    _EnvGetFocusStack
    _EnvGetGlobalsChanged
    _EnvGetHaltRules
    _EnvGetIncrementalReset
    _EnvGetInstanceClass
    _EnvGetInstanceName
    _EnvGetInstancePPForm
    _EnvGetInstancesChanged
    _EnvGetMethodRestrictions
    _EnvGetNextActivation
    _EnvGetNextDefclass
    _EnvGetNextDeffacts
    _EnvGetNextDeffunction
    _EnvGetNextDefgeneric
    _EnvGetNextDefglobal
    _EnvGetNextDefinstances
    _EnvGetNextDefmessageHandler
    _EnvGetNextDefmethod
    _EnvGetNextDefmodule
    _EnvGetNextDefrule
    _EnvGetNextDeftemplate
    _EnvGetNextFact
    _EnvGetNextFactInTemplate
    _EnvGetNextFocus
    _EnvGetNextInstance
    _EnvGetNextInstanceInClass
    _EnvGetNextInstanceInClassAndSubclasses
    _EnvGetResetGlobals
    _EnvGetSalienceEvaluation
    _EnvGetSequenceOperatorRecognition
    _EnvGetStaticConstraintChecking
    _EnvGetStrategy
    _EnvGetWatchItem
    _EnvHalt
    _EnvIncrementFactCount
    _EnvIncrementGCLocks
    _EnvIncrementInstanceCount
    _EnvInitializeEnvironment
    _EnvInstances
    _EnvIsDefclassDeletable
    _EnvIsDeffactsDeletable
    _EnvIsDeffunctionDeletable
    _EnvIsDefgenericDeletable
    _EnvIsDefglobalDeletable
    _EnvIsDefinstancesDeletable
    _EnvIsDefmessageHandlerDeletable
    _EnvIsDefmethodDeletable
    _EnvIsDefruleDeletable
    _EnvIsDeftemplateDeletable
    _EnvJoinActivity
    _EnvListDefclasses
    _EnvListDeffacts
    _EnvListDeffunctions
    _EnvListDefgenerics
    _EnvListDefglobals
    _EnvListDefinstances
    _EnvListDefmessageHandlers
    _EnvListDefmethods
    _EnvListDefmodules
    _EnvListDefrules
    _EnvListDeftemplates
    _EnvListFocusStack
    #EnvLoad
    _EnvLoadFacts
    _EnvLoadFactsFromString
    _EnvLoadInstances
    _EnvLoadInstancesFromString
    _EnvMakeInstance
    _EnvMatches
    _EnvMatchesCount
    _EnvMemRequests
    _EnvMemUsed
    _EnvPopFocus
    _EnvPPFact
    _EnvPreviewSend
    _EnvPrintRouter
    _EnvPutFactSlot
    _EnvRefresh
    _EnvRefreshAgenda
    _EnvReleaseMem
    _EnvRemoveBreak
    _EnvRemoveClearFunction
    _EnvRemovePeriodicFunction
    _EnvRemoveResetFunction
    _EnvRemoveRunFunction
    _EnvReorderAgenda
    #EnvReset
    _EnvRestoreInstances
    _EnvRestoreInstancesFromString
    _EnvRetract
    _EnvRtnArgCount
    _EnvRtnDouble
    _EnvRtnLexeme
    _EnvRtnLong
    _EnvRtnUnknown
    #EnvRun
    #EnvSave
    _EnvSaveFacts
    _EnvSaveInstances
    _EnvSend
    _EnvSetActivationSalience
    _EnvSetAfterOpenFunction
    _EnvSetAgendaChanged
    _EnvSetAutoFloatDividend
    _EnvSetBeforeOpenFunction
    _EnvSetBetaMemoryResizing
    _EnvSetBreak
    _EnvSetClassDefaultsMode
    _EnvSetConserveMemory
    _EnvSetCurrentModule
    _EnvSetDefclassWatchInstances
    _EnvSetDefclassWatchSlots
    _EnvSetDeffunctionWatch
    _EnvSetDefgenericWatch
    _EnvSetDefglobalValue
    _EnvSetDefglobalWatch
    _EnvSetDefmessageHandlerWatch
    _EnvSetDefmethodWatch
    _EnvSetDefruleWatchActivations
    _EnvSetDefruleWatchFirings
    _EnvSetDeftemplateWatch
    _EnvSetDynamicConstraintChecking
    _EnvSetFactDuplication
    _EnvSetFactListChanged
    _EnvSetFocusChanged
    _EnvSetGlobalsChanged
    _EnvSetHaltRules
    _EnvSetIncrementalReset
    _EnvSetInstancesChanged
    _EnvSetMultifieldErrorValue
    _EnvSetOutOfMemoryFunction
    _EnvSetResetGlobals
    _EnvSetSalienceEvaluation
    _EnvSetSequenceOperatorRecognition
    _EnvSetStaticConstraintChecking
    _EnvSetStrategy
    _EnvSetWatchItem
    _EnvShowBreaks
    _EnvShowDefglobals
    _EnvSlotAllowedClasses
    _EnvSlotAllowedValues
    _EnvSlotCardinality
    _EnvSlotDefaultP
    _EnvSlotDefaultValue
    _EnvSlotDirectAccessP
    _EnvSlotExistP
    _EnvSlotFacets
    _EnvSlotInitableP
    _EnvSlotPublicP
    _EnvSlotRange
    _EnvSlotSources
    _EnvSlotTypes
    _EnvSlotWritableP
    _EnvSubclassP
    _EnvSuperclassP
    _EnvUndefclass
    _EnvUndeffacts
    _EnvUndeffunction
    _EnvUndefgeneric
    _EnvUndefglobal
    _EnvUndefinstances
    _EnvUndefmessageHandler
    _EnvUndefmethod
    _EnvUndefrule
    _EnvUndeftemplate
    _EnvUngetcRouter
    _EnvUnmakeInstance
    _EnvUnwatch
    _EnvUserFunctions
    _EnvValidInstanceAddress
    _EnvWatch
    _xsi_version
	  _xsi_get_integer
	  _xsi_get_double
	  _xsi_get_long
	  _xsi_get_float
	  _xsi_get_string
	  _xsi_get_pointer
	  _xsi_get_type
    _xsi_get_length
    _xsi_get_begin
    _xsi_get_end
    _xsi_get_mf_type
    _xsi_get_mf_value
    _xsi_value_to_string
    _xsi_value_to_double
    _xsi_value_to_long
 
"""
 
__author__    = "Kurt Pagani <pagani@scios.ch>"
__svnid__     = "$Id: xsi_env.py 13 2011-08-16 13:44:42Z scios $"
__revision__  = "$Rev: 13 $"[6:-2]
 
 
#;;;;;;;;;;;;
# Imports ;;;
#;;;;;;;;;;;;
import ctypes
from ctypes import *
 
 
#;;;;;;;;;;;;;;;;;;
# DLL path/name ;;;
#;;;;;;;;;;;;;;;;;;
xsi_dll_path = "C:\\DEVELOPMENT\\XSI-DLL\\XSI-ENV\\Release\\"
xsi_dll_path2 = "C:\\DEVELOPMENT\\XSI-DLL-MVC\\XSI-ENV-MVC\\XSI-ENV\\Release\\"
xsi_dll_file = "XSI-ENV.dll"
 
#;;;;;;;;;;;;;;;;;;;;;;;;;
# Load the library/dll ;;;
#;;;;;;;;;;;;;;;;;;;;;;;;;
xsidll = cdll.LoadLibrary(xsi_dll_path2 + xsi_dll_file)
 
 
#;;;;;;;;;;;;;;;;;;;;;;;;;
# XSI/CLIPS data types ;;;
#;;;;;;;;;;;;;;;;;;;;;;;;;
FLOAT = 0
INTEGER = 1
SYMBOL = 2
STRING = 3
MULTIFIELD = 4
EXTERNAL_ADDRESS = 5
FACT_ADDRESS = 6
INSTANCE_ADDRESS = 7
INSTANCE_NAME = 8
 
#;;;;;;;;;;;;;;;;;;;;;;;;
# NULL (null pointer) ;;;
#;;;;;;;;;;;;;;;;;;;;;;;;
NULL = null_ptr = POINTER(c_int)()
 
 
#;;;;;;;;;;;;;;;
# Class: XSI ;;;
#;;;;;;;;;;;;;;;
class XSI():
  """
  Interface to XSI/CLIPS via the XSI-ENV.DLL.
  Note: this is a public version of XSI-ENV, containing only the CLIPS env
  functions and some utilities to fetch and convert several CLIPS structures.
  There are no PostgreSQL, Scheme, IUP, ... functions as in XSI+. It makes
  little sense anyway to incorporate that functionality into Python.
  """
 
  #;;;;;;;;;;;;;;;;;;;
  # CType settings ;;;
  #;;;;;;;;;;;;;;;;;;;
 
  # Get functions (fetch data depending on type)
  GetDouble  = xsidll.xsi_get_double
  GetLong    = xsidll.xsi_get_long
  GetString  = xsidll.xsi_get_string
  GetPointer = xsidll.xsi_get_pointer
  GetLength  = xsidll.xsi_get_length
  GetBegin   = xsidll.xsi_get_begin
  GetEnd     = xsidll.xsi_get_end
  GetMFType  = xsidll.xsi_get_mf_type
  GetMFValue = xsidll.xsi_get_mf_value
 
  # Conversion of multifield (MF) values
  ValueToString = xsidll.xsi_value_to_string
  ValueToDouble = xsidll.xsi_value_to_double
  ValueToLong   = xsidll.xsi_value_to_long
 
  # Arg and return types
  GetDouble.restype  = c_double
  GetLong.restype    = c_long
  GetString.restype  = c_char_p
  GetPointer.restype = c_void_p
  GetLength.restype  = c_int
  GetBegin.restype   = c_int
  GetEnd.restype     = c_int
  GetMFType.restype  = c_int
  GetMFValue.restype = c_void_p
  ValueToString.restype  =  c_char_p
  ValueToString.argtypes = [c_void_p]
  ValueToDouble.restype  =  c_double
  ValueToDouble.argtypes = [c_void_p]
  ValueToLong.restype    =  c_long
  ValueToLong.argtypes   = [c_void_p]
 
 
  def __init__(self, load = None, batch = None, buffer_size = 64000):
 
    """
    Initialize.
    load = filename: load constructs in filename
    batch = filename: execute (batch) commands in filename
    buffer_size = N (bytes): caller buffer to fetch results (default 64k).
    """
 
    # theEnv (a XSI/CLIPS environment pointer).
    # There may be more environments created (in a subclass for example)
    self.env = xsidll.CreateEnvironment()
 
    # Main buffer (allocate storage to fetch (NOT storing) results)
    self.buffer = create_string_buffer(buffer_size)
 
    # Buffer size
    self.buffer_size = buffer_size
 
  def Load(self, file):
    """
    int Load(fileName);
    char *fileName;
    Purpose: Loads a set of constructs into the CLIPS data base
             (the C equivalent of the CLIPS load command).
    Arguments: A string representing the name of the file.
    Returns: Returns an integer; Zero if the file couldn’t be opened, -1
    if the file was opened but an error occurred while loading, and 1 if
    the file was opened an no errors occurred while loading. If syntactic
    errors are in the constructs, Load still will attempt to read the entire
    file and error notices will be sent to werror.
    Other: The load function is not available for use in run-time programs
    (since individual constructs cannot be added or deleted). To execute
    different sets of constructs, the switching feature must be used in a
    run-time program
    """
    return xsidll.EnvLoad(self.env, file)
 
 
  def Reset(self):
    """
    void Reset();
    Purpose: Resets the CLIPS environment (the C equivalent of the CLIPS
    reset command).
    Arguments: None.
    Returns: No meaningful return value.
    Other: This function can trigger garbage collection.
    """
    xsidll.EnvReset(self.env)
 
 
  def Run(self, runLimit = -1):
    """
    long long runLimit;
    Purpose: Allows rules to execute (the C equivalent of the CLIPS run
             command).
    Arguments: An integer which defines how many rules should fire before
               returning. If runLimit is a negative integer, rules will fire
               until the agenda is empty.
    Returns: Returns an integer value; the number of rules that were fired.
    """
    return xsidll.EnvRun(self.env, runLimit)
 
 
  def GetMultifield(self, mf_p):
    """
    Extract a CLIPS multifield from the data object pointer mf_p and
    return it as a Python list.
    Note: CLIPS types SYMBOL and INSTANCE_NAME are returned as strings.
    """
    mf_list = []
    mf_length = self.GetLength(mf_p)
    mf_begin  = self.GetBegin(mf_p)
    mf_end    = self.GetEnd(mf_p)
 
    if mf_begin > mf_end: return mf_list
 
    mf_range  = range(mf_begin, mf_end + 1)
 
    for i in mf_range:
 
      f_type = self.GetMFType(mf_p, i)
 
      if f_type in [STRING, SYMBOL, INSTANCE_NAME]:
        mf_list.append(self.ValueToString(self.GetMFValue(mf_p, i)))
      elif f_type in [FLOAT]:
        mf_list.append(self.ValueToDouble(self.GetMFValue(mf_p, i)))
      elif f_type in [INTEGER]:
        mf_list.append(self.ValueToLong(self.GetMFValue(mf_p, i)))
      elif f_type in [FACT_ADDRESS]:
        mf_list.append(self.GetMFValue(mf_p, i))
      else:
        mf_list.append(False)
 
    return mf_list
 
 
  def GetType(self, result):
    """
    Return the CLIPS type stored in the argument pointer 'result'.
    The return value is an integer in [0..8]:
      FLOAT = 0
      INTEGER = 1
      SYMBOL = 2
      STRING = 3
      MULTIFIELD = 4
      EXTERNAL_ADDRESS = 5
      FACT_ADDRESS = 6
      INSTANCE_ADDRESS = 7
      INSTANCE_NAME = 8
    """
    return xsidll.xsi_get_type(result)
 
 
  def GetResult(self, result):
    """
    Return the value stored in the data object pointer 'result'.
    The value depends on the CLIPS type and may be a Python string,
    integer, float, ctypes pointer or a list.
    """
 
    rtype = self.GetType(result)
 
    if rtype == FLOAT:
      return(self.GetDouble(result))
    elif rtype == INTEGER:
      return(self.GetLong(result))
    elif rtype == SYMBOL:
      return(self.GetString(result))
    elif rtype == STRING:
      return(self.GetString(result))
    elif rtype == INSTANCE_NAME:
      return(self.GetString(result))
    elif rtype == FACT_ADDRESS:
      return(self.GetPointer(result))
    elif rtype == MULTIFIELD:
      return(self.GetMultifield(result))
    elif rtype == INSTANCE_ADDRESS:
      return(self.GetPointer(result))
    elif rtype == EXTERNAL_ADDRESS:
      return(self.GetPointer(result))
    else:
      pass
 
 
  def Eval(self, expr):
    """
    int Eval(expressionString, &result);
    char *expressionString;
    DATA_OBJECT result;
    Purpose: Allows an expression to be evaluated (the C equivalent of the
             CLIPS eval command).
    Arguments: 1) A string containing the expression to be evaluated.
               2) Caller’s buffer for storing the result of the evaluation.
    Returns: Returns an integer. 1 if the expression was successfully
             evaluated, otherwise 0.
    Other: The Eval function is not available for use in run-time programs.
    """
    result = pointer(self.buffer)
    xsidll.EnvEval(self.env, expr, result)
    return self.GetResult(result)
 
 
  def Build(self, constr):
    """
    int Build(constructString);
    char *constructString;
    Purpose: Allows a construct to be defined (the C equivalent of the CLIPS
             build command).
    Arguments: 1) A string containing the construct to be added.
    Returns: Returns an integer. 1 if the construct was successfully parsed,
             otherwise 0.
    Other: The Build function is not available for use in run-time programs
    """
    return xsidll.EnvBuild(self.env, constr)
 
 
  def Clear(self):
    """
    void Clear();
    Purpose: Clears the CLIPS environment (the C equivalent of the CLIPS clear
             command).
    Arguments: None.
    Returns: No meaningful return value.
    Other: This function can trigger garbage collection.
    """
    xsidll.EnvClear(self.env)
 
 
  def FunctionCall(self, functionName, args):
    """
    int FunctionCall(functionName,arguments,&result);
    char *functionName,*arguments;
    DATA_OBJECT result;
    Purpose: Allows CLIPS system functions, deffunctions and generic functions
             to be called from C.
    Arguments: 1) The name of the system function, deffunction or generic
                  function to be called.
               2) A string containing any constant arguments separated by
                  blanks (this argument can be NULL).
               3) Caller’s buffer for storing the result of the function call.
    Returns: An integer; TRUE (1) if an error occurred while evaluating the
             function, otherwise FALSE (0).
    Other: This function can trigger garbage collection.
    """
    result = pointer(self.buffer)
    xsidll.EnvFunctionCall(self.env, functionName, args, result)
    return self.GetResult(result)
 
 
  def Save(self, fileName):
    """
    int Save(fileName);
    char *fileName;
    Purpose: Saves a set of constructs to the specified file (the C equivalent
             of the CLIPS save command).
    Arguments: A string representing the name of the file.
    Returns: Returns an integer; if zero, an error occurred while opening the
             file. If non-zero no errors were detected while performing the
             save.
    """
    return xsidll.EnvSave(self.env, fileName)
 
 
  def AssertString(self, factstr):
    """
    void *AssertString(string);
    char *string;
    Purpose: Asserts a fact into the CLIPS fact-list (the C equivalent of the
             CLIPS assert-string command).
    Arguments: One argument; a pointer to a string containing a list of
               primitive data types (symbols, strings, integers, floats,
               and/or instance names).
    Returns: A generic pointer to a fact structure.
    Other: This function can trigger garbage collection.
 
    WARNING: If the return value from AssertString is stored as part of a
    persistent data structure or in a static data area, then the function
    IncrementFactCount should be called to insure that the fact cannot
    be disposed while external references to the fact still exist.
    """
    return xsidll.EnvAssertString(self.env, factstr)
 
 
  def Facts(self, logicalName = 'stdout', module = null_ptr,
                  start = -1, end = -1, max = -1):
    """
    void Facts(logicalName,theModule,start,end,max);
    char *logicalName;
    void *theModule;
    long long start, end, max;
 
    Purpose:
    Prints the list of all facts currently in the fact-list (the C equivalent
    of the CLIPS facts command). Output is sent to the logical name wdisplay.
 
    Arguments:
    1) The logical name to which the listing output is sent.
    2) A generic pointer to the module containing the facts to be listed
    (all facts visible to that module). A NULL pointer indicates that
    all facts in all modules should be listed.
    3) The start index of the facts to be listed. Facts with indices less
    than this value are not listed. A value of -1 indicates that the
    argument is unspecified and should not restrict the facts printed.
    4) The end index of the facts to be listed. Facts with indices greater
    than this value are not listed. A value of -1 indicates that the
    argument is unspecified and should not restrict the facts printed.
    5) The maximum number of facts to be listed. Facts in excess of
    this limit are not listed. A value of -1 indicates that the argument
    is unspecified and should not restrict the facts printed.
 
    Returns:
    No meaningful return value.
    """
    xsidll.EnvFacts(self.env, logicalName, module, start, end, max)
 
 
  def GetFactList(self, module = null_ptr):
    """
    void GetFactList(&returnValue,theModule);
    DATA_OBJECT returnValue;
    void *theModule;
 
    Purpose:
    Returns the list of facts visible to the specified module as a
    multifield value in the returnValue DATA_OBJECT (the C
    equivalent of the CLIPS get-fact-list function).
 
    Arguments:
    1) A pointer to the caller’s DATA_OBJECT in which the return
    value will be stored. The multifield functions described in
    section 3.2.4 can be used to retrieve the deffacts names from the
    list.
    2) A generic pointer to the module from which the list will be
    extracted. A NULL pointer indicates that the list is to be
    extracted from al l modules.
 
    Returns:
    No meaningful return value.
    """
    result = pointer(self.buffer)
    xsidll.EnvGetFactList(self.env, result, module)
    return self.GetResult(result)
 
 
  def GetFactPPForm(self, factPtr):
    """
    void GetFactPPForm(buffer,bufferLength,factPtr);
    char *buffer;
    unsigned bufferLength;
    void *factPtr;
 
    Purpose:
    Returns the pretty print representation of a fact in the caller's buffer.
    Arguments:
    1) A pointer to the caller's character buffer.
    2) The maximum number of characters which could be stored in
    the caller's buffer (not including space for the terminating null
    character).
    3) A generic pointer to a fact data structure.
    Returns: No meaningful return value. The fact pretty print form is stored
    in the caller's buffer.
    """
    result = pointer(self.buffer)
    xsidll.EnvGetFactPPForm(self.env, result, self.buffer_size, factPtr)
    return self.GetResult(result)
 
 
  def Retract(self, factPtr):
    """
    int Retract(factPtr);
    void *factPtr;
 
    Purpose:
    Retracts a fact from the CLIPS fact-list (the C equivalent of the
    CLIPS retract command).
 
    Arguments:
    A generic pointer to a fact structure (usually captured as the return
    value from a call to AssertString or Assert). If the NULL pointer is
    used, then all facts will be retracted.
 
    Returns:
    An integer; zero (0) if fact already has been retracted, otherwise a
    one (1).
 
    Other:
    The caller of RetractFact is responsible for insuring that the fact
    passed as an argument is still valid. The functions
    IncrementFactCount and DecrementFactCount can be used to
    inform CLIPS whether a fact is still in use.
    This function can trigger garbage collection.
    """
    return xsidll.EnvRetract(self.env, factPtr)
 
 
  def DestroyEnvironment(self):
    """
    int DestroyEnvironment(theEnv);
    void *theEnv;
 
    Purpose: Destroys the specified environment deallocating all memory
    associated with it.
 
    Arguments: A generic pointer to an environment data structure.
 
    Returns: Boolean value. TRUE if the environment was successfully
    destroyed, otherwise FALSE.
 
    Other: You should not call this function to destroy an environment that
    is currently executing.
    """
    return xsidll.DestroyEnvironment(self.env)
 
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # AGENDA COMMANDS                               ;;;
  # The following commands manipulate the agenda. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
  def agenda(self, module = "MAIN"):
    """
    AGENDA
    Displays all activations on the agenda of the specified module.
    (agenda [<module-name>])
    """
    self.Eval('(agenda %s)' % module)
 
  def rules(self, module = ""):
    """
    Display the rules.
    (rules <module-name>)
    """
    self.Eval('(rules %s)' % module)
 
  def clear_focus_stack(self):
    """
    CLEAR-FOCUS-STACK
    Removes all modules from the focus stack.
    (clear-focus-stack)
    """
    self.Eval('(clear-focus-stack)')
 
  def focus(self, modules):
    """
    FOCUS
    Pushes one or more modules onto the focus stack.
    (focus <module-name>+)
    """
    self.Eval('(focus %s)' % modules)
 
  def get_salience_evaluation(self):
    """
    GET-SALIENCE-EVALUATION
    Returns the salience evaluation behavior.
    (get-salience-evaluation)
    """
    self.Eval('(get-salience-evaluation)')
 
  def get_strategy(self):
    """
    GET-STRATEGY
    Returns the current conflict resolution strategy.
    (get-strategy)
    """
    self.Eval('(get-strategy)')
 
  def halt(self):
    """
    HALT
    Stops rule execution.
    (halt)
    """
    self.Eval('(halt)')
 
  def list_focus_stack(self):
    """
    LIST-FOCUS-STACK
    Lists all module names on the focus stack.
    (list-focus-stack)
    """
    self.Eval('(list-focus-stack)')
 
  def refresh_agenda(self, module = ""):
    """
    REFRESH-AGENDA
    Forces reevaluation of salience of rules on the agenda of the
    specified module.
    (refresh-agenda [<module-name>])
    """
    self.Eval('(refresh-agenda %s)' % module)
 
  def run(self, limit = -1):
    """
    RUN
    Starts execution of rules. Rules fire until agenda is empty or the
    number of rule firings limit specified by the first argument is reached
    (infinity if unspecified).
    (run [<integer-expression>])
    """
    self.Eval('(run %i)' % limit)
 
  def set_salience_evaluation(self, behavior = "when-defined"):
    """
    SET-SALIENCE-EVALUATION
    Sets the salience evaluation behavior.
    (set-salience-evaluation <behavior>)
     <behavior> ::= when-defined | when-activated | every-cycle
    """
    self.Eval('(set-salience-evaluation %s)' % behavior)
 
  def set_strategy(self, strategy = "depth"):
    """
    SET-STRATEGY
    Sets the current conflict resolution strategy.
   (set-strategy <strategy>)
     <strategy> ::= depth | breadth | simplicity | complexity |
                    lex | mea | random
    """
    self.Eval('(set-strategy %s)' % strategy)
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  #;;; COOL COMMANDS                                                     ;;;
  #;;; The commands manipulating the XSI Object-Oriented Language (COOL) ;;;
  #;;; are divided into four categories.                                 ;;;
  #;;; Subtopics:                                                        ;;;
  #;;;   CLASS_COMMANDS                                                  ;;;
  #;;;   DEFINSTANCES_COMMANDS                                           ;;;
  #;;;   INSTANCES_COMMANDS                                              ;;;
  #;;;   MESSAGE-HANDLER_COMMANDS                                        ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
  #;;;;;;;;;;;;;;;;;;;
  # CLASS_COMMANDS ;;;
  #;;;;;;;;;;;;;;;;;;;
  def browse_classes(self, class_name = ""):
    """
    BROWSE-CLASSES
    Provides a rudimentary display of the inheritance relationships
    between a class and all its subclasses.
    (browse-classes [<class-name>])
    """
    self.Eval('(browse-classes %s)' % class_name)
 
  def describe_class(self, class_name):
    """
    DESCRIBE-CLASS
    Provides a verbose description of a class.
    (describe-class <class-name>)
    """
    self.Eval('(describe-class %s)' % class_name)
 
  def list_defclasses(self, module = ""):
    """
    LIST-DEFCLASSES
    Displays the list of all defclasses in the specified module
    (or the current module if none specified).
    (list-defclasses [<module-name>])
    """
    self.Eval('(list-defclasses %s)' % module)
 
  def ppdefclass(self, class_name):
    """
    PPDEFCLASS
    Displays the text of a given defclass.
    (ppdefclass <class-name>)
    """
    self.Eval('(ppdefclass %s)' % class_name)
 
  def undefclass(self, class_name):
    """
    UNDEFCLASS
    Deletes a defclass, all its subclasses, and all associated instances.
    (undefclass <class-name>)
    """
    self.Eval('(undefclass %s)' % class_name)
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;
  # DEFINSTANCES COMMANDS ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;
  def list_definstances(self, module = ""):
    """
    LIST-DEFINSTANCES
    Displays the list of all definstances in the specified module
    (or the current module if none specified).
    (list-definstances [<module-name>])
    """
    self.Eval('(list-definstances %s)' % module)
 
  def ppdefinstances(self, definstances_name):
    """
    PPDEFINSTANCES
    Displays the text of a given definstances.
    (ppdefinstances <definstances-name>)
    """
    self.Eval('(ppdefinstances %s)' % definstances_name)
 
  def undefinstances(self, definstances_name):
    """
    UNDEFINSTANCES
    Deletes a definstances
    (undefinstances <definstances-name>)
    """
    self.Eval('(undefinstances %s)' % definstances_name)
 
  #;;;;;;;;;;;;;;;;;;;;;;;
  # INSTANCES COMMANDS ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;
  def instances(self, str_arg = ""):
    """
    INSTANCES
    Displays a list of instances.
    (instances [<module-name> [<class-name> [inherit]]])
    """
    self.Eval('(instances %s)' % str_arg)
 
  def load_instances(self, filename):
    """
    LOAD-INSTANCES
    Loads instances from the specified file.
    (load-instances <file-name>)
    """
    self.Eval('(load-instances %s)' % filename)
 
  def ppinstance(self):
    """
    PPINSTANCE
    Prints the slots of the active instance when called from within
    the body of a message-handler.
    (ppinstance)
    """
    self.Eval('(ppinstance)')
 
  def restore_instances(self, filename):
    """
    RESTORE-INSTANCES
    Loads instances from the specified file.
    (restore-instances <file-name>)
    """
    self.Eval('(restore-instances %s)' % filename)
 
  def save_instances(self, filename):
    """
    SAVE-INSTANCES
    Saves all instances to the specified file.
    (save-instances <file-name>)
    """
    self.Eval('(save-instances %s)' % filename)
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # MESSAGE HANDLER COMMANDS ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def list_defmessage_handlers(self):
    """
    """
    self.Eval('')
 
  def ppdefmessage_handler(self, str_arg):
    """
    LIST-DEFMESSAGE-HANDLERS
    Displays a list of all (or some) defmessage-handlers.
    (list-defmessage-handlers [<class-name> [<handler-name>
    [<handler-type>]]])
    """
    self.Eval('(list-defmessage-handlers %s)' % str_arg)
 
  def preview_send(self, str_arg):
    """
    PPDEFMESSAGE-HANDLER
    Displays the text of a given defmessage-handler.
    (ppdefmessage-handler <class-name> <handler-name>
    [<handler-type>])
    """
    self.Eval('(ppdefmessage-handler %s)' % str_arg )
 
  def undefmessage_handler(self, str_arg):
    """
    UNDEFMESSAGE-HANDLER
    Deletes a defmessage-handler.
    (undefmessage-handler <class-name> <handler-name> [<handler-type>])
    """
    self.Eval('(undefmessage-handler %s)' % str_arg)
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # DEBUGGING COMMANDS                                         ;;;
  # The following commands control the XSI debugging features. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def dribble_off(self):
    """
    DRIBBLE-OFF
    Closes the trace file.
    (dribble-off)
    """
    self.Eval('(dribble-off)')
 
  def dribble_on(self, filename):
    """
    DRIBBLE-ON
    Sends trace information to the specified file.
    (dribble-on <file-name>)
    """
    self.Eval('(dribble-on %s)' % filename)
 
  def list_watch_items(self, watch_item = ""):
    """
    LIST-WATCH-ITEMS
    Displays the current state of watch items.
    (list-watch-items [<watch-item>])
    """
    self.Eval('(list-watch-items %s)' % watch_item)
 
  def unwatch(self, watch_item):
    """
    UNWATCH
    Disables trace information for the specified item.
    (unwatch <watch-item>)
    """
    self.Eval('(unwatch %s)' % watch_item)
 
  def watch(self, watch_item = "all"):
    """
    WATCH
    Enables trace information for the specified item.
 
    (watch <watch-item>)
    <watch-item> ::= all |
        compilations |
        statistics |
        focus |
        messages |
        deffunctions <deffunction-name>* |
        globals <global-name>* |
        rules <rule-name>* |
        activations <rule-name>* |
        facts <deftemplate-name>* |
        instances <class-name>* |
        slots <class-name>* |
        message-handlers <handler-spec-1>* [<handler-spec-2>]) |
        generic-functions <generic-name>* |
        methods <method-spec-1>* [<method-spec-2>]
 
    <handler-spec-1> ::= <class-name> <handler-name> <handler-type>
    <handler-spec-2> ::= <class-name> [<handler-name> [<handler-type>]]
 
    <method-spec-1> ::= <generic-name> <method-index>
    <method-spec-2> ::= <generic-name> [<method-index>]
    """
    self.Eval('(watch %s)' % watch_item)
 
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # DEFFACTS COMMANDS                           ;;;
  # The following commands manipulate deffacts. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def ppdeffacts(self, deffacts_name):
    """
    PPDEFFACTS
    Displays the text of a given deffacts.
    (ppdeffacts <deffacts-name>)
    """
    self.Eval('(ppdeffacts %s)' % deffacts_name)
 
  def list_deffacts(self, module = ""):
    """
    LIST-DEFFACTS
    Displays the list of all deffacts in the specified module
    (or the current module if none specified).
    (list-deffacts [<module-name>])
    """
    self.Eval('(list-deffacts %s)' % module)
 
  def undeffacts(self, deffacts_name):
    """
    UNDEFFACTS
    Deletes a deffacts.
    (undeffacts <deffacts-name>)
    """
    self.Eval('(undeffacts %s)' % deffacts_name)
 
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # DEFFUNCTION COMMANDS                            ;;;
  # The following commands manipulate deffunctions. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def ppdeffunction(self, deffunction_name):
    """
    PPDEFFUNCTION
    Displays the text of a given deffunction.
    (ppdeffunction <deffunction-name>)
    """
    self.Eval('(ppdeffunction %s)' % deffunction_name)
 
  def list_deffunctions(self, module = ""):
    """
    LIST-DEFFUNCTIONS
    Displays the list of all deffunctions in the specified module
    (or the current module if none specified).
    (list-deffunctions [<module-name>])
    """
    self.Eval('(list-deffunctions %s)' % module)
 
  def undeffunction(self, deffunction_name):
    """
    UNDEFFUNCTION
    Deletes a deffunction.
    (undeffunction <deffunction-name>)
    """
    self.Eval('(undeffunction %s)' % deffunction_name)
 
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # DEFGLOBAL COMMANDS                            ;;;
  # The following commands manipulate defglobals. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def ppdefglobal(self, global_variable_name):
    """
    PPDEFGLOBAL
    Displays the text of a given global variable.
    (ppdefglobal <global_variable_name>)
    """
    self.Eval('(ppdefglobal %s)' % global_variable_name)
 
  def list_defglobals(self, module = ""):
    """
    LIST-DEFGLOBALS
    Displays the list of all global variables in the specified module
    (or the current module if none specified).
    (list-defglobals [<module-name>])
    """
    self.Eval('(list-defglobals %s)' % module)
 
  def undefglobal(self, global_variable_name):
    """
    UNDEFGLOBAL
    Deletes a global variable.
    (undefglobal <global_variable_name>)
    """
    self.Eval('(undefglobal %s)' % global_variable_name)
 
  def get_reset_globals(self):
    """
    GET-RESET-GLOBALS
    Returns the reset global variables behavior.
    (get-reset-globals)
    """
    self.Eval('(get-reset-globals)')
 
  def set_reset_globals(self, boolean = 'TRUE'):
    """
    SET-RESET-GLOBALS
    Sets the reset global variables behavior.
    (set-reset-globals <boolean-expression>)
    """
    self.Eval('(set-reset-globals %s)' % boolean)
 
  def show_defglobals(self, module = ""):
    """
    SHOW-DEFGLOBALS
    Displays the name and current value of all defglobals in the specified
    module (or the current module if none specified).
    (show-defglobals [<module-name>])
    """
    self.Eval('(show-defglobals %s)' % module)
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # DEFMODULE COMMANDS                            ;;;
  # The following commands manipulate defmodules. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def ppdefmodule(self, defmodule_name):
    """
    PPDEFMODULE
    Displays the text of a given defmodule.
    (ppdefmodule <defmodule-name>)
    """
    self.Eval('(ppdefmodule %s)' % defmodule_name)
 
  def list_defmodules(self):
    """
    LIST-DEFMODULES
    Displays the list of all defmodules
    (list-defmodules)
    """
    self.Eval('(list-defmodules)')
 
  def set_current_module(self, module):
    """
    SET-CURRENT-MODULE
    Sets the current module.
   (set-current-module <module-name>)
    """
    self.Eval('(set-current-module %s)' % module)
 
  def get_current_module(self):
    """
    GET-CURRENT-MODULE
    Returns the current module.
   (get-current-module)
    """
    self.Eval('(get-current-module)')
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # DEFRULE COMMANDS                            ;;;
  # The following commands manipulate defrules. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def ppdefrule(self, rule_name):
    """
    PPDEFRULE
    Displays the text of a given rule.
    (ppdefrule <rule-name>)
    """
    self.Eval('(ppdefrule %s)' % rule_name)
 
  def list_defrules(self, module = ""):
    """
    LIST-DEFRULES
    Displays the list of all defrules in the specified module
    (or the current module if none specified).
    (list-defrules [<module-name>])
    """
    self.Eval('(list-defrules %s)' % module)
 
  def undefrule(self, rule_name):
    """
    UNDEFRULE
    Deletes a defrule.
    (undefrule <rule-name>)
    """
    self.Eval('(undefrule %s)' % rule_name)
 
  def get_incremental_reset(self):
    """
    GET-INCREMENTAL-RESET
    Returns the incremental reset behavior.
    (get-incremental-reset)
    """
    self.Eval('(get-incremental-reset)')
 
  def set_incremental_reset(self, boolean = 'TRUE'):
    """
    SET-INCREMENTAL-RESET
    Sets the incremental reset behavior.
    (set-incremental-reset <boolean-expression>)
    """
    self.Eval('(set-incremental-reset %)' % boolean)
 
  def set_break(self, rule_name):
    """
    SET-BREAK
    Sets a breakpoint on a rule.
    (set-break <rule-name>)
    """
    self.Eval('(set-break %s)' % rule_name)
 
  def show_breaks(self, module = ""):
    """
    SHOW-BREAKS
    Displays all rules having breakpoints.
    (show-breaks [<module-name>])
    """
    self.Eval('(show-breaks %s)' % module)
 
  def remove_break(self, rule_name = ""):
    """
    REMOVE-BREAK
    Removes a breakpoint on a rule.
    (remove-break [<rule-name>])
    """
    self.Eval('(remove-break %s)' % rule_name)
 
  def matches(self, rule_name):
    """
    MATCHES
    Displays the facts which match the patterns of a rule.
    (matches <rule-name>)
    """
    self.Eval('(matches %s)' % rule_name)
 
  def refresh(self, rule_name):
    """
    REFRESH
    Places all current activations of a rule on the agenda.
    (refresh <rule-name>)
    """
    self.Eval('(refresh %s)' % rule_name)
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # DEFTEMPLATE COMMANDS                            ;;;
  # The following commands manipulate deftemplates. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def ppdeftemplate(self, deftemplate_name):
    """
    PPDEFTEMPLATE
    Displays the text of a given deftemplate.
    (ppdeftemplate <deftemplate-name>)
    """
    self.Eval('(ppdeftemplate %s)' % deftemplate_name)
 
  def list_deftemplates(self, module = ""):
    """
    LIST-DEFTEMPLATES
    Displays the list of all deftemplates in the specified module
    (or the current module if none specified).
    (list-deftemplates [<module-name>])
    """
    self.Eval('(list-deftemplates %s)' % module)
 
  def undeftemplate(self, deftemplate_name):
    """
    UNDEFTEMPLATE
    Deletes a deftemplate.
    (undeftemplate <deftemplate-name>)
    """
    self.Eval('(undeftemplate %s)' % deftemplate_name)
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # ENVIRONMENT COMMANDS                                      ;;;
  # The following commands control the XSI/CLIPS environment. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def apropos(self, lexeme):
    """
    APROPOS
    Displays all symbols currently defined in XSI/CLIPS which contain a
    specified substring.
    (apropos <lexeme>)
    """
    self.Eval('(apropos %s)' % lexeme)
 
  def batch(self, filename):
    """
    BATCH
    Executes commands from a file.
    (batch <file-name>)
    """
    self.Eval('(batch %s)' % filename)
 
  def batch_star(self, filename):
    """
    BATCH*
    Executes commands from a file.
    (batch <file-name>)
    """
    self.Eval('(batch* %s)' % filename)
 
  def bload(self, filename):
    """
    BLOAD
    Loads a binary image from a file.
    (bload <file-name>)
    """
    self.Eval('(bload %s)' % filename)
 
  def bsave(self, filename):
    """
    BSAVE
    Saves a binary image to a file.
    (bsave <file-name>)
    """
    self.Eval('(bsave %s)' % filename)
 
  def clear(self):
    """
    CLEAR
    Clears the XSI environment.
    (clear)
    """
    self.Eval('(clear)')
 
  def exit(self):
    """
    EXIT
    Exits the XSI environment.
    (exit)
    """
    self.Eval('(exit)')
 
  def get_auto_float_dividend(self):
    """
    GET-AUTO-FLOAT-DIVIDEND
    Returns the current value of the auto-float dividend behaviour.
    (get-auto-float-dividend)
    """
    self.Eval('(get-auto-float-dividend)')
 
  def get_dynamic_constraint_checking(self):
    """
    GET-DYNAMIC-CONSTRAINT-CHECKING
    Returns the current value of the dynamic constraint checking behaviour.
    (get-dynamic-constraint-checking)
    """
    self.Eval('(get-dynamic-constraint-checking)')
 
  def get_static_constraint_checking(self):
    """
    GET-STATIC-CONSTRAINT-CHECKING
    Returns the current value of the static constraint checking behaviour.
    (get-static-constraint-checking)
    """
    self.Eval('(get-static-constraint-checking)')
 
  def load(self, filename):
    """
    LOAD
    Loads constructs from a file.
    (load <file-name>)
    """
    self.Eval('(load %s)' % filename)
 
  def load_star(self, filename):
    """
    LOAD
    Loads constructs from a file.
    (load <file-name>)
    """
    self.Eval('(load* %s)' % filename)
 
  def options(self):
    """
    OPTIONS
    Lists the settings of XSI compiler flags.
    (options)
    """
    self.Eval('(options)')
 
  def reset(self):
    """
    RESET
    Resets the XSI environment.
    (reset)
    """
    self.Eval('(reset)')
 
  def save(self, filename):
    """
    SAVE
    Saves constructs to a file.
    (save <file-name>)
    """
    self.Eval('(save %s)' % filename)
 
  def set_auto_float_dividend(self, boolean = 'TRUE'):
    """
    SET-AUTO-FLOAT-DIVIDEND
    Sets the auto-float dividend behaviour.
    (set-auto-float-dividend <boolean-expression>)
    """
    self.Eval('(set-auto-float-dividend %s)' % boolean)
 
  def set_dynamic_constraint_checking(self, boolean = 'TRUE'):
    """
    SET-DYNAMIC-CONSTRAINT-CHECKING
    Sets the dynamic constraint checking behaviour.
    (set-dynamic-constraint-checking <boolean-expression>)
    """
    self.Eval('(set-dynamic-constraint-checking %s)' % boolean)
 
  def set_static_constraint_checking(self, boolean = 'TRUE'):
    """
    SET-STATIC-CONSTRAINT-CHECKING
    Sets the static constraint checking behaviour.
    (set-static-constraint-checking <boolean-expression>)
    """
    self.Eval('(set-static-constraint-checking %s)' % boolean)
 
  def system(self, command):
    """
    SYSTEM
    Appends its arguments together to form a command which is then sent to
    the operating system.
    (system <lexeme-expression>*)
    """
    self.Eval('(system %s)' % command)
 
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # FACTS COMMANDS                                          ;;;
  # The following commands display information about facts. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def dependencies(self, spec):
    """
    DEPENDENCIES
    Lists the partial matches from which a fact or instance receives
    logical support.
    (dependencies <fact-or-instance-specifier>)
    """
    self.Eval('(dependencies %s)' % spec)
 
  def dependents(self, spec):
    """
    DEPENDENTS
    Lists all facts or instances which receive logical support from a
    fact or instance.
    (dependents <fact-or-instance-specifier>)
    """
    self.Eval('(dependents %s)' % spec)
 
  def facts(self, str_arg = ""):
    """
    FACTS
    Display the facts in the fact-list.
    (facts [<module-name>]
       [<start-integer-expression>
       [<end-integer-expression>
       [<max-integer-expression>]]])
    """
    self.Eval('(facts %s)' % str_arg)
 
  def get_fact_duplication(self):
    """
    GET-FACT-DUPLICATION
    Returns the fact duplication behavior.
    (get-fact-duplication)
    """
    self.Eval('(get-fact-duplication)')
 
  def set_fact_duplication(self, boolean = 'TRUE'):
    """
    SET-FACT-DUPLICATION
    Sets the fact duplication behavior.
    (set-fact-duplication <boolean-expression>)
    """
    self.Eval('(set-fact-duplication %s)' % boolean)
 
  def load_facts(self, filename):
    """
    LOAD-FACTS
    Asserts facts loaded from a file.
    (load-facts <file-name>)
    """
    self.Eval('(load-facts %s)' % filename)
 
  def save_facts(self, filename, scope = ""):
    """
    SAVE-FACTS
    Saves facts to a file.
    (save-facts <file-name> [<save-scope> <deftemplate-names>*])
    <save-scope> ::= visible | local
    """
    self.Eval('(save-facts %s %s)' % (filename, scope))
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # GENERIC FUNCTION COMMANDS                            ;;;
  # The following commands manipulate generic functions. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def ppdefgeneric(self, defgeneric_name):
    """
    PPDEFGENERIC
    Displays the text of a given generic function header.
    (ppdefgeneric <defgeneric-name>)
    """
    self.Eval('(ppdefgeneric %s)' % defgeneric_name)
 
  def list_defgenerics(self, module = ""):
    """
    LIST-DEFFGENERICS
    Displays the list of all defgenerics in the specified module
    (or the current module if none specified).
    (list-defgenerics [<module-name>])
    """
    self.Eval('(list-defgenerics %s)' % module)
 
  def undefgeneric(self, defgeneric_name):
    """
    UNDEFGENERIC
    Deletes a defgeneric.
    (undefgeneric <defgeneric-name>)
    """
    self.Eval('(undefgeneric %s)' % defgeneric_name)
 
  def preview_generic(self, defgeneric_name, expr = ""):
    """
    PREVIEW-GENERIC
    Lists all applicable methods for a particular generic function call
    in order of decreasing precedence.
    (preview-generic <generic-function-name> <expression>*)
    """
    self.Eval('preview-generic %s %s' % (defgeneric_name, expr))
 
  def ppdefmethod(self, defmethod_name, index):
    """
    PPDEFMETHOD
    Displays the text of a given method.
    (ppdefmethod <defmethod-name> <index>)
    """
    self.Eval('(ppdefmethod %s %i)' % (defmethod_name, index))
 
  def list_defmethods(self, defmethod_name = ""):
    """
    LIST-DEFFMETHODS
    Displays a list of generic function methods.
    (list-defmethods [<defmethod-name>])
    """
    self.Eval('(list-defmethods %s)' % defmethod_name)
 
  def undefmethod(self, defmethod_name, index):
    """
    UNDEFMETHOD
    Deletes a defmethod.
    (undefmethod <defmethod-name> <index>)
    """
    self.Eval('(undefmethod %s %i)' % (defmethod_name, index))
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # MEMORY COMMANDS                                               ;;;
  # The following commands display XSI memory status information. ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def conserve_mem(self, status = 'on'):
    """
    CONSERVE-MEM
    Turns on or off the storage of information used for the save and
    pretty-print commands.
    (conserve-mem <status>)
     <status> ::= on | off
    """
    self.Eval('(conserve-mem %s)' % status)
 
  def mem_requests(self):
    """
    MEM-REQUESTS
    Returns the number of times XSI has requested memory from the
    operating system.
    (mem-requests)
    """
    self.Eval('(mem-requests)')
 
  def mem_used(self):
    """
    MEM-USED
    Returns number of bytes of memory XSI is using.
    (mem-used)
    """
    self.Eval('(mem-used)')
 
  def release_mem(self):
    """
    RELEASE-MEM
    Releases all free memory held internally by XSI to the operating system.
    Returns the amount of memory freed.
    (release-mem)
    """
    self.Eval('(release-mem)')
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # TEXT PROCESSING COMMANDS                                       ;;;
  # The following commands can be used by users to maintain their  ;;;
  # own information system similar to the help facility.           ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def fetch(self, filename):
    """
    FETCH
    Loads the named file into the internal lookup table.
    (fetch <file-name>)
    """
    self.Eval('(fetch %s)' % filename)
 
  def toss(self, filename):
    """
    TOSS
    Unloads the named file from the internal lookup table.
    (toss <file-name>)
    """
    self.Eval('(toss %s)' % filename)
 
  def print_region(self, str_arg):
    """
    PRINT-REGION
    Looks up the specified entry in a particular file which has been
    previously loaded into the lookup table and prints the contents of
    that entry to the specified logical name.
    (print-region <logical-name> <lookup-file> <topic-field>*)
    """
    self.Eval('(print-region %s)' % str_arg)
 
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  # PROFILING COMMANDS                                               ;;;
  # The following commands provide the ability to profile CLIPS/XSI  ;;;
  # programs for performance.                                        ;;;
  #;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  def get_profile_percent_threshold(self):
    """
    GET-PROFILE-PERCENT-THRESHOLD
    Returns the current value of the profile percent threshold.
    (get-profile-percent-threshold)
    """
    self.Eval('(get-profile-percent-threshold)')
 
  def profile(self, arg = "off"):
    """
    PROFILE
    Enables/disables profiling of constructs and user functions
    (profile constructs | user-functions | off)
    """
    self.Eval('(profile %s)' % arg)
 
  def profile_info(self):
    """
    PROFILE-INFO
    Displays profiling information currently collected for constructs
    or user functions.
    (profile-info)
    """
    self.Eval('(profile-info)')
 
  def profile_reset(self):
    """
    PROFILE-RESET
    Resets all profiling information currently collected for constructs
    and user functions.
    (profile-reset)
    """
    self.Eval('(profile-reset)')
 
  def set_profile_percent_threshold(self, percent):
    """
    SET-PROFILE-PERCENT-THRESHOLD
    Sets the minimum percentage of time that must be spent executing a
    construct or user function for it to be displayed by the
    profile-info command.
    (set-profile-percent-threshold <number in the range 0 to 100>)
    """
    self.Eval('(set-profile-percent-threshold %d)' % percent)
 
 
  #;;;;;;;;;;;;;;;
  # CONSTRUCTS ;;;
  #;;;;;;;;;;;;;;;
  def defclass(self, name, comment = "", isa = "INITIAL-OBJECT",
    role = "concrete", pattern_match = "reactive",
    slots = [], handler_docs = []):
 
    tpl = """ (defclass %s "%s"
                (is-a %s)
                (role %s)
                (pattern-match %s)
                 %s
                 %s)
          """
 
    build = tpl % (name, comment, isa, role, pattern_match,
                   ''.join(slots), ''.join(handler_docs))
 
    self.Build(build)
 
 
 
 
 
def main():
    pass
 
if __name__ == '__main__':
    main()
 
 
py_xsi.txt · Last modified: 2012/01/08 15:55 by admin
topheader
© 1998-2019, SciOS Scientific Operating Systems GmbH

Legal | Credits | Profile | Contact | Customer Login