def loadCLIPS(): clips.Load(os.path.join('src', 'clips', 'peces.pont')) clips.Load(os.path.join('src', 'clips', 'peces.clp')) clips.Load(os.path.join('src', 'clips', 'peces.pins')) clips.Reset() clips.SendCommand('(set-salience-evaluation when-activated)') clips.SendCommand('(set-strategy depth)') printCLIPS() loadFishFromCLIPS(True)
def set_value(self, value): self._value = value if (self._fact): sstr = '(bind ?*ans* (modify %d (name %s)) )' % (self._fact, self.value) clips.SendCommand(sstr) self._fact = clips.Eval('?*ans*').Index
def set_flag(self, flag, value): self.flags[flag] = value if (self._fact): sstr = '(bind ?*ans* (modify %d (%s %s)) )' % (self._fact, flag, value) clips.SendCommand(sstr) self._fact = clips.Eval('?*ans*').Index
def __setitem__(self, name, value): 'sets the slot by name' self._slots[name] = value if (self.clips_id != None): #notification to clips engine clips.SendCommand('(modify %s (%s %s) )' % (self.clips_id, name, value))
def set_children(self, children): self._children=children if(self._fact): child_ids=[str(child._id) for child in self.children] sstr='(bind ?*ans* (modify %d (children %s)) )' % (self._fact, ' '.join(self.child_ids)) clips.SendCommand(sstr) self._fact=clips.Eval('?*ans*').Index
def set_number(self, number): self._number=number if(number in [MatlabParser.INT, MatlabParser.FLOAT, MatlabParser.NUMBER]): self.set_flag('is_scalar', True) if(self._fact): sstr='(bind ?*ans* (modify %d (name %s)) )' % (self._fact, self.name) clips.SendCommand(sstr) self._fact=clips.Eval('?*ans*').Index
def run(self): """ Start or resume an interactive CLIPS shell """ exit_flag = False while not exit_flag: self.__lineno = 1 s = "" dic = {'cmdno': self.__cmdno, 'lineno': self.__lineno} prompt = self.__ps1 % dic try: while not self.cmd_complete(s): if s: s += " " s += raw_input(prompt).strip() self.__lineno += 1 dic = {'cmdno': self.__cmdno, 'lineno': self.__lineno} prompt = self.__ps2 % dic except ValueError as e: _sys.stderr.write("[SHELL] %s\n" % str(e)) except EOFError: _clips.ErrorStream.Read() exit_flag = True try: if not exit_flag: _clips.SendCommand(s, True) except _clips.ClipsError as e: _sys.stderr.write("[PYCLIPS] %s\n" % str(e)) self.__cmdno += 1 r0 = _clips.StdoutStream.Read() r1 = _clips.DisplayStream.Read() tx = _clips.TraceStream.Read() r = "" if r0: r += r0 if r1: r += r1 t = _clips.ErrorStream.Read() if r: r = "%s\n" % r.rstrip() if t: t = "%s\n" % t.rstrip() if tx: t = "%s\n" % tx.rstrip() + t if t: _sys.stderr.write(t) if r: _sys.stdout.write(r)
def add_wrong_rules(): #reads in from wrong-rule.txt file = open("wrong-rule.txt", "r") header = file.readline().split() ngram, no_of_root_rules = int(header[0]), int(header[1]) for i in xrange(no_of_root_rules): header = file.readline().split() root, no_of_subrules = header[0], int(header[1]) for j in xrange(no_of_subrules): root, leaf = file.readline().split("-") leaf = leaf.rstrip() command = "(assert (wrong-bigram-rule (root %s)(wrong-rule %s %s)))" % ( root, root, leaf) #flag for scaling clips.SendCommand(command) file.close()
class GrapherClipsShell(object): """an interactive CLIPS shell""" def __init__(self): self.__ps1 = "GRAPHER[%(cmdno)s/%(lineno)s]> " self.__ps2 = "GRAPHER[%(cmdno)s/%(lineno)s]: " self.__cmdno = 1 self.__lineno = 1 def __cmdcomplete(self, cms): """check if CLIPS command is complete (stolen from 'commline.c')""" def eat_ws(s, i): """eat up whitespace""" while i < len(s) and s[i] in _string.whitespace: i += 1 return i def eat_string(s, i): """eat up strings""" if s[i] != '"' or i >= len(s): return i i += 1 while i < len(s): if s[i] == '"': return i + 1 else: if s[i] == '\\': i += 1 i += 1 if i > len(s): raise ValueError, "non-terminated string" return i def eat_comment(s, i): """eat up comments""" if s[i] != ';' or i >= len(s): return i while i < len(s) and s[i] not in '\n\r': i += 1 return i + 1 s = cms.strip() if len(s) == 0: return False depth = 0 i = 0 while i < len(s): c = s[i] if c in '\n\r' and depth == 0: return True elif c == '"': i = eat_string(s, i) elif c == ';': i = eat_comment(s, i) elif c == '(': depth += 1 i += 1 elif c == ')': depth -= 1 i += 1 elif c in _string.whitespace: i = eat_ws(s, i) else: i += 1 if depth < 0: raise ValueError, "invalid command" if depth == 0: return True else: return False def InteractiveShellRun(self): """start or resume an interactive CLIPS shell""" exitflag = False while not exitflag: self.__lineno = 1 s = "" dic = {'cmdno': self.__cmdno, 'lineno': self.__lineno} prompt = self.__ps1 % dic try: while not self.__cmdcomplete(s): if s: s += " " s += raw_input(prompt).strip() self.__lineno += 1 dic = {'cmdno': self.__cmdno, 'lineno': self.__lineno} prompt = self.__ps2 % dic except ValueError, e: _sys.stderr.write("[SHELL] %s\n" % str(e)) except EOFError: _cm.ErrorStream.Read() exitflag = True try: if not exitflag: _cm.SendCommand(s, True) except _cm.ClipsError, e: _sys.stderr.write("[PYCLIPS] %s\n" % str(e))
def add_bigram_as_fact(t1, t2): command = "(assert (bigram (tags %s %s) (words \"%s\" \"%s\")))" % ( t1[1], t2[1], t1[0], t2[0]) clips.SendCommand(command) # print command
def stepCLIPS(): global PASO clips.SendCommand('(run 1)') PASO += 1 loadFishFromCLIPS(False) printCLIPS()
def Run(times=''): _clipsLock.acquire() clips.SendCommand('(run ' + str(times) + ')') _clipsLock.release()
#with CaptureOutput() as capturer: # clips.PrintFacts() # print capturer.get_lines() #print h #clips.PrintRules() #clips.Matches() clips.Save("rulez.clp") #clips.Ppdefrule() #subprocess.call(["ls", "-l"]) #print subprocess.check_output(['ls','-l']) #clips.FindRule("""ClutchNoise""") #clips.SendCommand("""(rules)""") #clips.StdinStream.Write("""(rules)""") #clips.Build("""rules""") #t = clips.RuleList() #clips.Run() #clips.StdoutStream.Read() #clips.Call("""ppdefrule""","""EngineStart""") #print t clips.SendCommand("(assert (Engine fails to start))") clips.SendCommand("(assert (Spark is good))") #clips.SendCommand("(ppdefrule "+"EngineStart"+")") #clips.Run() #clips.PrintFacts() #sys.stdout = open("/dev/stdout", "w") clips.PrintRules()
def system_run(input_ set): if 'hazard' in input_set: clips.Clear() clips.Reset() eng_var[:]=[] eng_var.append(input_set['lat']) eng_var.append(input_set['long']) eng_var.append(clips.BuildTemplate("entity", """ (slot aid (type STRING)) (slot latitude (type NUMBER)) (slot longitude (type NUMBER)) (slot quantity (type NUMBER)) """, "template for a entity")) eng_var.append(clips.BuildTemplate("allies", """ (slot username (type STRING)) (slot foraid (type STRING)) (slot action (type STRING)) (slot quantity (type NUMBER)) """, "template for a allies")) eng_var.append(input_set['control']) eng_var.append(clips.BuildTemplate("disaster", """ (slot hazard (type STRING)) (slot latitude (type NUMBER)) (slot longitude (type NUMBER)) (slot span (type NUMBER)) """, "template for a disaster")) d=clips.Fact(eng_var[5]) d.Slots['hazard'] = input_set['hazard'] d.Slots['latitude'] = input_set['lat'] d.Slots['longitude'] = input_set['long'] d.Slots['span'] = input_set['span'] d.Assert() facts[:] = [] fields[:] = [] list_map[:] = [] clips.RegisterPythonFunction(invoke_pronearea) clips.RegisterPythonFunction(display_disaster) clips.RegisterPythonFunction(invoke_entity) clips.RegisterPythonFunction(invoke_useralert) clips.RegisterPythonFunction(invoke_user_allocate ) clips.RegisterPythonFunction(invoke_user_deallocate) clips.RegisterPythonFunction(invoke_message) clips.RegisterPythonFunction(invoke_alert_area) clips.BatchStar("/home/jishnu/PycharmProjects/dmis/controlunit/expertsystem/inference.clp") clips.Run() if 'refresh' in input_set: if len(eng_var)==0: return {'fact': facts, 'field': fields,'map_data':list_map} message_dealer(input_set['control'],eng_var[0],eng_var[1],eng_var[2]) user_status_checking() clips.Run() if 'send' in input_set: if len(eng_var)==0: return {'fact': facts, 'field': fields,'map_data':list_map} message_handler(input_set['control'],input_set['selectaid'],input_set['parameter']) if 'deallocate' in input_set: try: clips.Assert("(DeallocateAll)") except clips.ClipsError: print("Error in Deallocation") clips.Run() facts[:] = [] fields[:] = [] list_map[:] = [] clips.SendCommand("run") print (clips.PrintFacts()) list_temp=list(facts) list_temp.reverse() return {'fact':list_temp,'field':list(set(fields)),'map_data':list_map}