def do(self, theEnv, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-13.7.html#Heading450 """ args = list(args) args.reverse() try: for theModule in args: theModule = self.resolve( theEnv, self.semplify(theEnv, theModule, types.Symbol, ("ALL", "symbol"))) if not theEnv.modulesManager.isDefined(theModule): raise InvalidArgValueError("Unable to find defmodule %s" % theModule) else: theEnv.network.agenda.focusStack.append(theModule) return types.Symbol("TRUE") except IndexError: return types.Symbol("FALSE")
def do(self, theEnv, theName=None, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.4.html#Heading245 """ theName = self.resolve(theEnv, theName) if isinstance( theName, (types.FunctionCall, types.Variable)) else theName if theName is None: toClose = theEnv.RESOURCES.keys() elif not isinstance(theName, types.Symbol): raise InvalidArgTypeError( "Function open expected argument #1 to be of type symbol") else: toClose = [theName.evaluate()] if len(toClose) > 0: try: for resourceName in toClose: theEnv.RESOURCES[resourceName].close() del theEnv.RESOURCES[resourceName] return types.Symbol("TRUE") except KeyError: return types.Symbol("FALSE") else: return types.Symbol("FALSE")
def test_AlphaMemoryPropagationTemplate(self): types.DefTemplateConstruct("aTemplate", self.MM, None, [ types.SingleSlotDefinition("A"), types.SingleSlotDefinition("B"), types.SingleSlotDefinition("C") ]) self.network.addRule(types.DefRuleConstruct("A", self.MM, lhs=[ types.TemplatePatternCE("aTemplate", self.MM, [ types.SingleFieldLhsSlot("A", types.Symbol("A")), types.SingleFieldLhsSlot("B", types.Symbol("B")), types.SingleFieldLhsSlot("C", types.Symbol("C")) ]) ])) self.assertIsInstance(self.network._root.children[0].children[0].children[0].children[0].children[0].memory.children[0], JoinNode) trap = activationCatcher() self.network._root.children[0].children[0].children[0].children[0].children[0].memory.appendChild(trap) self.network.assertFact(fact({"A": types.Symbol("A"), "B": types.Symbol("B"), "C": types.Symbol("C")}, "aTemplate")) self.assertTrue(trap.rightCatch)
def do(self, theEnv, theName=None, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.4.html#Heading248 """ theName = self.resolve(theEnv, theName) if isinstance( theName, (types.FunctionCall, types.Variable)) else theName if theName is None or (isinstance(theName, types.Symbol) and theName.pyEqual("t")): theResource = theEnv.RESOURCES["stdin"] elif not isinstance(theName, types.Symbol): raise InvalidArgTypeError( "Function read expected argument #1 to be of type symbol") else: theResource = theEnv.RESOURCES[theName.evaluate()] try: theString = theResource.readline() # python file.readline() doc: # An empty string is returned only when EOF is encountered immediately # @see http://docs.python.org/release/2.4.4/lib/bltin-file-objects.html if theString == "": return types.Symbol("EOF") return types.String(theString) except EOFError: return types.Symbol("EOF") except IOError: return types.Symbol("*** READ ERROR ***")
def test_NetworkPlotting_TemplateAlphaAndDummyJoinOnly(self): types.DefTemplateConstruct("aTemplate", self.MM, None, [ types.SingleSlotDefinition("A"), types.SingleSlotDefinition("B"), types.SingleSlotDefinition("C") ]) self.network.addRule( types.DefRuleConstruct( "A", self.MM, lhs=[ types.TemplatePatternCE("aTemplate", self.MM, [ types.SingleFieldLhsSlot("A", types.Symbol("A")), types.SingleFieldLhsSlot("B", types.Symbol("B")), types.SingleFieldLhsSlot("C", types.Symbol("C")) ]) ])) # manually fire the network ready event self.network.eventsManager.fire(EventsManager.E_NETWORK_READY, self.network) self.network.eventsManager.fire(EventsManager.E_NETWORK_SHUTDOWN, self.network)
def test_PushOne(self): Scope("A", self.theEnv.modulesManager) self.theEnv.modulesManager.changeCurrentScope("MAIN") self.assertTrue(self.forInput(types.Symbol("A")) .expect(types.Symbol("TRUE"))) self.assertEqual(self.theEnv.network.agenda.focusStack[-1], "A")
def test_Concatenation(self): theWme = WME(1, OrderedFact([])) self.assertTrue( self.forInput(types.Symbol("ciao"), types.String("mucca albero"), types.Integer(1), types.Float(1.5), theWme).expect( types.Symbol("ciaomucca albero11.5" + str(theWme))))
def do(self, theEnv, thePath, theName, theMode=None, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.4.html#Heading244 """ thePath = self.resolve(theEnv, thePath) if isinstance( thePath, (types.FunctionCall, types.Variable)) else thePath theName = self.resolve(theEnv, theName) if isinstance( theName, (types.FunctionCall, types.Variable)) else theName theMode = self.resolve(theEnv, theMode) if isinstance(theMode, (types.FunctionCall, types.Variable)) \ else theMode if theMode is not None else types.String("r") if not isinstance(thePath, (types.String, types.Symbol)): raise InvalidArgTypeError( "Function open expected argument #1 to be of type string or symbol" ) # normalize the string to a path. In documentation: # all special chars and \ in the path must be escaped # these means that the path is already a valid path # for python thePath = thePath.evaluate() if isinstance( thePath, types.Symbol) else thePath.evaluate()[1:-1] if not isinstance(theName, types.Symbol): raise InvalidArgTypeError( "Function open expected argument #2 to be of type symbol") # check if a resource with the same logical name is already used assert isinstance(theEnv, FunctionEnv) if theEnv.RESOURCES.has_key(theName.evaluate()): raise InvalidArgValueError( "Illegal logical name used for open function: %s" % theName.evaluate()) if not isinstance(theMode, types.String): raise InvalidArgTypeError( "Function open expected argument #3 to be of type string") # normalize the mode removing quotes if <String> theMode = theMode.evaluate()[1:-1] modeMap = {"r": "rU", "r+": "rU+", "w": "w", "a": "a"} import myclips try: theMode = modeMap[theMode] fileResource = open(thePath, theMode) theEnv.RESOURCES[theName.evaluate()] = fileResource return types.Symbol("TRUE") except KeyError: myclips.logger.error("Invalid mode for Open: %s", theMode) return types.Symbol("FALSE") except IOError, e: myclips.logger.error("IOError in Open: %s", e) return types.Symbol("FALSE")
def do(self, theEnv, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.12.html#Heading316 """ try: return types.Symbol(theEnv.network.agenda.focusStack.pop()) except IndexError: return types.Symbol("FALSE")
def test_JoinNodeIntraElementVarBindingTestInBetaNetwork(self): self.network.addRule(types.DefRuleConstruct("A", self.MM, lhs=[ types.OrderedPatternCE([ types.SingleFieldVariable(types.Symbol("varA")), types.SingleFieldVariable(types.Symbol("varA")), types.Symbol("C"), ], self.MM) ])) self.assertIsInstance(self.network._root.children[0].children[0].children[0].memory.children[0], JoinNode) self.assertTrue(self.network._root.children[0].children[0].children[0].memory.children[0].isLeftRoot()) trap = activationCatcher() self.network._root.children[0].children[0].children[0].memory.children[0].appendChild(trap) f = fact([types.Symbol("A"), types.Symbol("B"), types.Symbol("C")]) self.network.assertFact(f) self.assertFalse(trap.leftCatch) f = fact([types.Symbol("A"), types.Symbol("A"), types.Symbol("C")]) self.network.assertFact(f) self.assertTrue(trap.leftCatch)
def test_NegativeJoinBetaCircuitTrueCondition(self): self.network.addRule(types.DefRuleConstruct("A", self.MM, lhs=[ types.OrderedPatternCE([ types.Symbol("A"), types.Symbol("B"), types.Symbol("C"), ], self.MM), types.NotPatternCE( types.OrderedPatternCE([ types.Symbol("C"), types.Symbol("B"), types.Symbol("A"), ], self.MM)) ])) trap = activationCatcher() (self.network._root.children[0] #MAIN .children[0] #C .children[0] #B .children[0] #A .children[0] #LEN .memory #AM .children[0]).prependChild(trap) self.network.assertFact(fact([types.Symbol("A"), types.Symbol("B"), types.Symbol("C")])) self.assertTrue(trap.leftCatch)
def test_DummyJoinNodeCreationAfterFirstPatternCE(self): self.network.addRule(types.DefRuleConstruct("A", self.MM, lhs=[ types.OrderedPatternCE([ types.Symbol("A"), types.Symbol("B"), types.Symbol("C"), ], self.MM) ])) self.assertIsInstance(self.network._root.children[0].children[0].children[0].children[0].children[0].memory.children[0], JoinNode) self.assertTrue(self.network._root.children[0].children[0].children[0].children[0].children[0].memory.children[0].isLeftRoot())
def do(self, theEnv, theSubSet, theMultifield, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.2.html#Heading221 """ theSubSet = self.semplify(theEnv, theSubSet, list, ("1", "multifield")) theMultifield = self.semplify(theEnv, theMultifield, list, ("2", "multifield")) return types.Symbol("TRUE") if set(theSubSet) <= set( theMultifield) else types.Symbol("FALSE")
def test_ErrorOnInvalidInput(self): self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.Symbol("1"), types.Integer(2), types.String("blabla")) self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.Integer(2), types.Symbol("1"), types.String("blabla")) self.assertRaises(InvalidArgTypeError, self.theFunc.do, self.theEnv, types.Integer(1), types.Integer(2), types.Integer("100"))
def test_JoinNodeVarBindingOnOrderedPatternCEWithNegativeTermOverVariable(self): self.network.addRule(types.DefRuleConstruct("A", self.MM, lhs=[ types.OrderedPatternCE([ types.Symbol("A"), types.SingleFieldVariable(types.Symbol("varA")), types.Symbol("C"), ], self.MM), types.OrderedPatternCE([ types.NegativeTerm(types.SingleFieldVariable(types.Symbol("varA")), True), types.UnnamedSingleFieldVariable(), types.Symbol("C"), ], self.MM) ])) self.assertIsInstance(self.network._root.children[0].children[0].children[0].memory.children[0], JoinNode) self.assertFalse(self.network._root.children[0].children[0].children[0].memory.children[0].isLeftRoot()) trap = activationCatcher() self.network._root.children[0].children[0].children[0].memory.children[0].appendChild(trap) f = fact([types.Symbol("A"), types.Symbol("B"), types.Symbol("C")]) self.network.assertFact(f) self.assertTrue(trap.leftCatch)
def test_ReturnFalseIfNotFound(self): self.assertTrue( self.forInput( types.String("w"), types.String("Nel mezzo del cammin di nostra vita")).expect( types.Symbol("FALSE")))
def do(self, theEnv, aPath, *args, **kargs): """ function handler implementation """ aPath = self.resolve( theEnv, self.semplify(theEnv, aPath, types.Lexeme, ('1', 'symbol or string'))) aPath = os.path.abspath(aPath) if not exists(aPath): raise InvalidArgValueError( "Function load was unable to open file %s" % aPath) oldcwd = os.getcwd() os.chdir(os.path.dirname(aPath)) aFile = open(aPath, 'rU') aString = aFile.read() try: parsed = theEnv.network.getParser().parse(aString, extended=True) except Exception, e: print >> theEnv.RESOURCES['werror'], theEnv.network.getParser( ).ExceptionPPrint(e, aString) os.chdir(oldcwd) return types.Symbol('FALSE')
def do(self, theEnv, *args, **kwargs): # 1) read params informations and resolve the values from the *args list theBindings = {} for index, theParam in enumerate(self._params): if isinstance(theParam, types.SingleFieldVariable): theBindings[theParam.evaluate()] = self.semplify(theEnv, args[index]) elif isinstance(theParam, types.MultiFieldVariable): theBindings[theParam.evaluate()] = [self.semplify(theEnv, x) for x in args[index:None]] # it's useless to iterate more, # the only multifield variable allowed must be the last # params. So, even if other params are available in the _params # they have to be ignored because are illegal break # 2) create a theEnv copy with new bindings theNewEnv = FunctionEnv(theBindings, theEnv.network, theEnv.modulesManager, theEnv.RESOURCES) returnValue = types.Symbol("FALSE") # 3) execute the list of actions # to do this, i could use semplify. This whay i always got back the # types.Class value form, not the python one for theAction in self._actions: # theAction is a function call or a variable. In both # cases the returnValue of semplify is a types.BaseParsedType instance returnValue = self.semplify(theNewEnv, theAction) # 4) return the last action return value! return returnValue
def do(self, theEnv, theValue, theComparison, theThen, *args, **kargs): """ handler of the Case function: check theValue against theComparison: if they match the actions in the case arguments are executed otherwise an InvalidCaseException is raised to return control to the outer switch function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.6.html#Heading287 """ returnValue = types.Symbol("FALSE") # check for case format first: if not isinstance(theThen, types.Symbol) or theThen.pyEqual("then"): raise InvalidArgValueError("The `then` keyword is expected as second argument of a case clause") # resolve theComparison to its real value if isinstance(theComparison, (types.FunctionCall, types.Variable)): theComparison = self.resolve(theEnv, theComparison) # this is not the case if theValue != theComparison: raise InvalidCaseException() # CLIPS documentation: # the return value of a case function is the one returned from the last # action in the case arguments for action in args: # function are executed if isinstance(action, (types.FunctionCall, types.Variable)): returnValue = self.resolve(theEnv, action) else: returnValue = action return returnValue
def do(self, funcEnv, *args, **kargs): """ Retract function handler implementation """ returnValue = types.Symbol("FALSE") for wme in args: # revolve variables, function calls, fact-id and fact-address wme = self.resolveFact( funcEnv, self.semplify(funcEnv, wme, (WME, types.Integer, types.Symbol), ("ALL", "fact-address, fact-index or *"))) if isinstance(wme, list): # wme was <Symbol:*> # the resolve gave me back a list of wme to retract for rWme in wme: returnValue = funcEnv.network.retractFact(rWme) else: returnValue = funcEnv.network.retractFact(wme) return returnValue
def do(self, funcEnv, variable, *args, **kargs): """ handler of the Bind function: set a global variable running value if variable is a global one or set a new local variable value @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.6.html#Heading279 """ returnValue = types.Symbol("FALSE") # i can't use the resolve method to get # the variable name, because resolve will resolve to the value # instead, i need to variable name assert isinstance(variable, types.Variable) # this can give me ?*NAME* or ?NAME varName = variable.evaluate() # compute the new value if len(args) == 0: # no expression is passed. New value is None newValue = None elif len(args) == 1: # it's a single argument newValue = self.semplify(funcEnv, args[0]) else: # more than one, create a multifield for them newValue = [self.semplify(funcEnv, arg) for arg in args] if isinstance(variable, types.GlobalVariable): # so i need to modify the definition in the globalsManager for the current scope definition = funcEnv.network.modulesManager.currentScope.globalsvars.getDefinition( variable.evaluate()) # linkedType in a GlobalVarDefinition is a types.GlobalAssignment if newValue is not None: definition.linkedType.runningValue = newValue returnValue = newValue else: # as for http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.6.html # in Bind documentation: # if the new value of the global is None, the original value have to be restored definition.linkedType.runningValue = definition.linkedType.value returnValue = definition.linkedType.value else: # the variable is a rule-scope variable if newValue is not None: # bind the new variable funcEnv.variables[varName] = newValue returnValue = newValue else: # as for http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-12.6.html # in Bind documentation: # if the new value of a local variable is None, the variable must be unbound del funcEnv.variables[varName] return returnValue
def do(self, theEnv, theValue, *args, **kargs): """ handler of the _TypeTesting function: execute the comparison """ # check theValue type and resolve (if needed) if isinstance(theValue, (types.FunctionCall, types.Variable)): theValue = self.resolve(theEnv, theValue) # execute comparison between types if isinstance(theValue, self._cmpType): returnValue = types.Symbol("TRUE") else: returnValue = types.Symbol("FALSE") return returnValue
def test_ErrorOnDefRuleEval(self): theString = """ (defrule r (A B C) => ) """ theResult = self.theFunc.do(self.theEnv, types.String(theString)) self.assertEqual(theResult, types.Symbol("FALSE"))
def do(self, theEnv, *args, **kargs): """ handler of the function @see: http://www.comp.rgu.ac.uk/staff/smc/teaching/clips/vol1/vol1-13.7.html#Heading453 """ return types.Symbol(theEnv.network.agenda.strategy)
def do(self, theEnv, theValue, *args, **kargs): """ handler of the Oddp function """ # check theValue type and resolve (if needed) if isinstance(theValue, (types.FunctionCall, types.Variable)): theValue = self.resolve(theEnv, theValue) pyValue = theValue.evaluate() if bool(pyValue & 1): returnValue = types.Symbol("TRUE") else: returnValue = types.Symbol("FALSE") return returnValue
def do(self, theEnv, theArg, *args, **kargs): """ handler of the function """ # comparison is done against the <Symbol:FALSE> theValue = types.Symbol("FALSE") # resolve the real value # before comparison theArg = self.semplify(theEnv, theArg) # types + value comparison if theValue == theArg: return types.Symbol("TRUE") # return <Symbol:TRUE> else: return theValue
def test_InputClassKept(self): theString = "This_Is_a_MiXed_StrIng" theResultString = self.theFunc.do(self.theEnv, types.String(theString)) theResultSymbol = self.theFunc.do(self.theEnv, types.Symbol(theString)) self.assertEqual(theResultString.__class__, types.String) self.assertEqual(theResultSymbol.__class__, types.Symbol)
def test_AlphaCircuitCompilationOrdered(self): self.network.addRule(types.DefRuleConstruct("A", self.MM, lhs=[ types.OrderedPatternCE([ types.Symbol("A"), types.Symbol("B"), types.Symbol("C"), ], self.MM) ])) self.assertIsInstance(self.network._root, RootNode) self.assertIsInstance(self.network._root.children[0], PropertyTestNode) self.assertIsInstance(self.network._root.children[0].children[0], PropertyTestNode) self.assertIsInstance(self.network._root.children[0].children[0].children[0], PropertyTestNode) self.assertIsInstance(self.network._root.children[0].children[0].children[0].children[0], PropertyTestNode) self.assertIsInstance(self.network._root.children[0].children[0].children[0].children[0].children[0], PropertyTestNode) self.assertIsInstance(self.network._root.children[0].children[0].children[0].children[0].children[0].memory, AlphaMemory) self.assertIsInstance(self.network._root.children[0].children[0].children[0].children[0].children[0].memory.children[0], JoinNode)
def do(self, funcEnv, *args, **kargs): """ handler of the Assert function: assert new fact in the network working memory """ returnValue = types.Symbol("FALSE") for fact in args: # revolve variables and function calls fact = self.createFact(funcEnv, fact) returnValue = funcEnv.network.assertFact(fact) returnValue = returnValue[0] if returnValue[1] else types.Symbol( "FALSE") return returnValue
def do(self, theEnv, *args, **kargs): """ handler of the function """ # comparison is done against the <Symbol:TRUE> theValue = types.Symbol("TRUE") for theArg in args: # resolve the real value # before comparison if isinstance(theArg, (types.FunctionCall, types.Variable)): theArg = self.resolve(theEnv, theArg) # types + value comparison if theValue == theArg: return theValue # return <Symbol:TRUE> return types.Symbol("FALSE")