def optionalGetVariableValueString(bindings, var): try: return value_str(bindings.getVariableValue(ABSTRACT, var)) except LowError: errid = NEWPM.displayError() print "VARIABLE %s WAS NOT BOUND CORRECTLY!!!" % var return "???"
def persist_strrep(sparkData): val = value_str(inverse_eval(sparkData)) if val is None: raise Exception("cannot create persistable representation for %s"%sparkData) # if val.startswith("<"): # NEWPM.recordLocation(val) return val
def format_string(format, args): newmsg = [] state = 0 aList = list(args) aList.reverse() for ch in format: if state == 0: number = "" if ch == '%': state = 1 else: newmsg.append(ch) elif state == 1: if ch == '%': newmsg.append(ch) state = 0 elif ch == 's': newmsg.append(to_string(_popArg(aList))) state = 0 elif ch == 'r': newmsg.append(value_str(_popArg(aList))) state = 0 elif ch.isdigit(): number = "%" + ch state = 2 elif ch == "d": newmsg.append("%d" % _popArg(aList)) state = 0 else: raise SyntaxError("Invalid format command: %%%s" % ch) elif state == 2: if ch.isdigit(): number = number + ch elif ch == "d": mess = number + "d" newmsg.append(mess % _popArg(aList)) state = 0 else: raise SyntaxError("Invalid format command: %s" % (number + ch)) if state == 1: raise SyntaxError("Unused Format string ends in %") if aList: aList.reverse() raise SyntaxError("Unused arguments in format string: %s" % value_str(List(aList))) return "".join(newmsg)
def value_to_icl(self, value): from spark.io.oaa import InvalidTermError, value_to_icl try: return value_to_icl(value) except InvalidTermError: errid = NEWPM.displayError() result = "<NO ICL EQUIVALENT:%s>" % value_str(value) return value_to_icl(result)
def value_to_icl(self, value): from spark.io.oaa import InvalidTermError, value_to_icl try: return value_to_icl(value) except InvalidTermError: errid = NEWPM.displayError() result = "<NO ICL EQUIVALENT:%s>"%value_str(value) return value_to_icl(result)
def _strrep(spark_data): term = inverse_eval(spark_data) if term is None: #XXX: NEED BETTER EXCEPTION CLASS HERE raise Exception( "ERROR: cannot create SPARK-L representation for %s type, value is %s" % (type(spark_data), spark_data)) return value_str(term)
def value_km_str(x): "convert x to a KM string" # TODO: make this work for real if isString(x) or isInteger(x) \ or isFloat(x) or isSymbol(x): return value_str(x) else: return None
def persist_strrep(sparkData): val = value_str(inverse_eval(sparkData)) if val is None: raise Exception("cannot create persistable representation for %s" % sparkData) # if val.startswith("<"): # NEWPM.recordLocation(val) return val
def format_string(format, args): newmsg = [] state = 0 aList = list(args) aList.reverse() for ch in format: if state == 0: number = "" if ch =='%': state = 1 else: newmsg.append(ch) elif state == 1: if ch =='%': newmsg.append(ch) state = 0 elif ch == 's': newmsg.append(to_string(_popArg(aList))) state = 0 elif ch =='r': newmsg.append(value_str(_popArg(aList))) state = 0 elif ch.isdigit(): number = "%" + ch state = 2 elif ch == "d": newmsg.append("%d"%_popArg(aList)) state = 0 else: raise SyntaxError("Invalid format command: %%%s"%ch) elif state == 2: if ch.isdigit(): number = number + ch elif ch == "d": mess = number + "d" newmsg.append(mess%_popArg(aList)) state = 0 else: raise SyntaxError("Invalid format command: %s"%(number+ch)) if state == 1: raise SyntaxError("Unused Format string ends in %") if aList: aList.reverse() raise SyntaxError("Unused arguments in format string: %s"%value_str(List(aList))) return "".join(newmsg)
def appendNotFromConds(fromConds, expr): "Append the negation of condition expr to all paths in fromConds" str_expr = str(expr) if str_expr == "(False)": return fromConds elif str_expr == "(True)": return NULL_FROM_CONDS else: return tuple([x + (value_str("~"+str_expr),) for x in fromConds])
def appendNotFromConds(fromConds, expr): "Append the negation of condition expr to all paths in fromConds" str_expr = str(expr) if str_expr == "(False)": return fromConds elif str_expr == "(True)": return NULL_FROM_CONDS else: return tuple([x + (value_str("~" + str_expr), ) for x in fromConds])
def fullString(self): try: return self.expr.getLocationString(self[0]) except: print "ERROR GETTING THE LOCATION STRING OF THE ERROR" import traceback traceback.print_exc() print from spark.internal.parse.basicvalues import value_str return "- %s\n%s" % (self[0], value_str(self.expr))
def fullString(self): try: return self.expr.getLocationString(self[0]) except: print "ERROR GETTING THE LOCATION STRING OF THE ERROR" import traceback traceback.print_exc() print from spark.internal.parse.basicvalues import value_str return "- %s\n%s"%(self[0], value_str(self.expr))
def ppl_term(agent, expr, map, output): value = map.meval(agent, expr) # TODO: This assumes that variables are never rebound by failure if value is not None: return value_km_str(value) if isinstance(expr, NonAnonVarPatExpr): return map.mapfind(Symbol(expr.varid), "v") elif isinstance(expr, ConstantPatExpr): return value_km_str(expr.get_value()) elif isinstance(expr, ListPatExpr): elements = [ppl_term(agent, elt, map, output) \ for elt in expr] return "(list " + " ".join(elements) + ")" else: return "(sparkeval " + value_str(str(expr)) + ")"
def tfPrintState(self): print "Display of TFrame %s" % self if self._estack: taskexpr = self._estack[-1] for v in taskexpr.used_before(): try: print "Var %s=%s" % (v, value_str(self.bindings.get_either(v))) except: print "Var %s=?" % v if self._subgoal_event: print taskexpr.error("Subgoal=%s\n", self._subgoal_event) else: print taskexpr.error("") else: print "State=%s" % self._completed
def tfPrintState(self): print "Display of TFrame %s" % self if self._estack: taskexpr = self._estack[-1] for v in taskexpr.used_before(): try: print "Var %s=%s" % ( v, value_str(self.bindings.get_either(v))) except: print "Var %s=?" % v if self._subgoal_event: print taskexpr.error("Subgoal=%s\n", self._subgoal_event) else: print taskexpr.error("") else: print "State=%s" % self._completed
def ppl_term(agent, expr, map, output): value = map.meval( agent, expr) # TODO: This assumes that variables are never rebound by failure if value is not None: return value_km_str(value) if isinstance(expr, NonAnonVarPatExpr): return map.mapfind(Symbol(expr.varid), "v") elif isinstance(expr, ConstantPatExpr): return value_km_str(expr.get_value()) elif isinstance(expr, ListPatExpr): elements = [ppl_term(agent, elt, map, output) \ for elt in expr] return "(list " + " ".join(elements) + ")" else: return "(sparkeval " + value_str(str(expr)) + ")"
def log_incoming_result(requestId, errnum, result): commsDebug("Incoming result %s %s %s", (requestId), value_str(errnum), value_str(result))
def _strrep(spark_data): term = inverse_eval(spark_data) if term is None: #XXX: NEED BETTER EXCEPTION CLASS HERE raise Exception("ERROR: cannot create SPARK-L representation for %s type, value is %s"%(type(spark_data), spark_data)) return value_str(term)
def oaa_construct(sym, *args): if not isSymbol(sym): raise LowError( "oaastruct requires a symbol for its first argument, not %s", value_str(sym)) return Structure(sym, args)
def log_outgoing_request(requestId, method, args): if requestId is None: requestId = allocateId() commsDebug("Outgoing request %s %s %s", (requestId), value_str(method), value_str(args)) return requestId
def process_command(agent, next): """Process a command in the interpreter loop. Return True if interpreter should exit, False otherwise""" # NOTE: updates to the commands in this list need to be mirrored in print_help() try: # Things that can be done whether we are stepping or not if next.startswith("module "): # change module text = next[6:].strip() if len(text): load_module(agent, text) else: print 'Please enter in a module name, e.g. "module spark.lang.builtin"' elif next == "trace": print "Turning tracing on." enable_tracing() elif next == "notrace": print "Turning tracing off." disable_tracing() elif next == "persist": print "Persisting SPARK agent knowledge base" user_directed_persist(agent) elif next == "step" or next == "pause": print "Turning stepping on." enable_stepping() elif next == "nostep" or next == "resume": print "Turning stepping off." disable_stepping() elif next.startswith("monitor "): text = next[8:].strip() if len(text): add_trace_monitor(text) else: print 'Please type in a string to ignore during tracing, e.g. "ignore EXECUTING"' elif next.startswith("ignore "): text = next[7:].strip() if len(text): add_trace_ignore(text) else: print 'Please type in a string to monitor for during tracing, e.g. "monitor FAILED"' elif next == "exit": print "exiting SPARK interpreter" return True elif next == "help": print_help() elif next == "clear all": # essentially undoes everything from this session print "removing all new facts and intentions..." clear_all(agent) print "session refreshed" elif next == "clear filters": clear_filters() print "step/trace filters cleared" elif next.startswith("get "): if next == "get intentions": # just prints intention ID #s # XXX: get rid of java calls (kwc) print "Root Objectives:" print "--------------------" intentions = agent.get_intentions() for intent in intentions: print " ", intent try: from com.sri.ai.spark.model.task import IntentionStructure from com.sri.ai.spark.model.util import TextModel print "" print "Task structure:" print "--------------------" structure = IntentionStructure(agent, agent._intention_structure) print TextModel.getIntentionStructureModel(structure) except ImportError: pass # XXX:TODO:there is an excessive number of e_d_m_l calls here. # talk to dm to see if this is necessary elif next == "get predicates": ensure_default_module_loaded(agent) names = get_local_predicates(agent) _print_sym_list(agent, "displaying local predicates", names) elif next == "get functions": ensure_default_module_loaded(agent) names = get_local_functions(agent) _print_sym_list(agent, "displaying local functions", names) elif next == "get tasks": ensure_default_module_loaded(agent) names = get_local_tasks(agent) _print_sym_list(agent, "displaying actions", names) elif next == "get all predicates": ensure_default_module_loaded(agent) names = get_all_predicates(agent) _print_sym_list(agent, "displaying all predicates", names) elif next == "get all functions": ensure_default_module_loaded(agent) names = get_all_functions(agent) _print_sym_list(agent, "displaying all functions", names) elif next == "get all tasks": ensure_default_module_loaded(agent) names = get_all_tasks(agent) _print_sym_list(agent, "displaying actions", names) else: print "Invalid command: don't know how to get '%s'" % next[4:] elif next.startswith("debugon "): if next == "debugon oaa": M.spark__io__oaa.debug.on() elif next == "debugon pubsub": M.iris__events.debug.on() elif next == "debugon tir": M.task_manager__tir.debug.on() else: print "Invalid command: don't know how to debugon '%s'" % next[8:] elif next.startswith("debugoff "): if next == "debugoff oaa": M.spark__io__oaa.debug.off() elif next == "debugoff pubsub": M.iris__events.debug.off() elif next == "debugoff tir": M.task_manager__tir.debug.off() else: print "Invalid command: don't know how to debugoff '%s'" % next[9:] elif next.startswith("debug"): debug_arg = next[5:].strip() id_num = None if debug_arg != "": try: id_num = string.atoi(debug_arg) except AnyException: errid = NEWPM.displayError() NEWPM.pm(id_num) elif next == "python": runPyConsole() elif next == "" and get_step_controller().step(): pass elif next == "": print "" # ignoring blank input line" # Remaining commands require the kb lock (don't block!) else: # We have the KB lock if next.startswith("test "): agent.test(next[4:], get_modname()) elif next.startswith("eval ") or next.startswith("evaluate "): term = next[5:] if next.startswith("evaluate "): term = term[4:] result = agent.eval(term, get_modname()) print "->", value_str(result) elif next.startswith("run "): term = next[4:] print "synchronously running command" ext = agent.run(term, get_modname()) ext.thread_event.wait() if ext.result is SUCCESS: print "SUCCEEDED" else: print "FAILED", ext.result elif next.startswith("addfact "): print "adding fact to KB" agent.run("[conclude: " + next[7:] + "]", get_modname()) elif next.startswith("removefact "): print "adding fact to KB" agent.run("[retract: " + next[10:] + "]", get_modname()) elif next.startswith("unload "): # drop module modname = next[6:].strip() agent.unload_modpath(Symbol(modname)) elif next.startswith("["): print "running command" agent.run(next, get_modname()) else: print "ignoring unrecognized request:", next except AnyException: errid = NEWPM.displayError() return False
def process_command(agent, next): """Process a command in the interpreter loop. Return True if interpreter should exit, False otherwise""" #NOTE: updates to the commands in this list need to be mirrored in print_help() try: # Things that can be done whether we are stepping or not if next.startswith("module "): # change module text = next[6:].strip() if (len(text)): load_module(agent, text) else: print 'Please enter in a module name, e.g. "module spark.lang.builtin"' elif next == "trace": print "Turning tracing on." enable_tracing() elif next == "notrace": print "Turning tracing off." disable_tracing() elif next == "persist": print "Persisting SPARK agent knowledge base" user_directed_persist(agent) elif next == "step" or next == "pause": print "Turning stepping on." enable_stepping() elif next == "nostep" or next == "resume": print "Turning stepping off." disable_stepping() elif next.startswith("monitor "): text = next[8:].strip() if (len(text)): add_trace_monitor(text) else: print 'Please type in a string to ignore during tracing, e.g. "ignore EXECUTING"' elif next.startswith("ignore "): text = next[7:].strip() if (len(text)): add_trace_ignore(text) else: print 'Please type in a string to monitor for during tracing, e.g. "monitor FAILED"' elif next == "exit": print "exiting SPARK interpreter" return True elif next == "help": print_help() elif next == "clear all": # essentially undoes everything from this session print "removing all new facts and intentions..." clear_all(agent) print "session refreshed" elif next == "clear filters": clear_filters() print "step/trace filters cleared" elif next.startswith("get "): if next == "get intentions": # just prints intention ID #s #XXX: get rid of java calls (kwc) print "Root Objectives:" print "--------------------" intentions = agent.get_intentions() for intent in intentions: print " ", intent try: from com.sri.ai.spark.model.task import IntentionStructure from com.sri.ai.spark.model.util import TextModel print "" print "Task structure:" print "--------------------" structure = IntentionStructure(agent, agent._intention_structure) print TextModel.getIntentionStructureModel(structure) except ImportError: pass #XXX:TODO:there is an excessive number of e_d_m_l calls here. #talk to dm to see if this is necessary elif next == "get predicates": ensure_default_module_loaded(agent) names = get_local_predicates(agent) _print_sym_list(agent, "displaying local predicates", names) elif next == "get functions": ensure_default_module_loaded(agent) names = get_local_functions(agent) _print_sym_list(agent, "displaying local functions", names) elif next == "get tasks": ensure_default_module_loaded(agent) names = get_local_tasks(agent) _print_sym_list(agent, "displaying actions", names) elif next == "get all predicates": ensure_default_module_loaded(agent) names = get_all_predicates(agent) _print_sym_list(agent, "displaying all predicates", names) elif next == "get all functions": ensure_default_module_loaded(agent) names = get_all_functions(agent) _print_sym_list(agent, "displaying all functions", names) elif next == "get all tasks": ensure_default_module_loaded(agent) names = get_all_tasks(agent) _print_sym_list(agent, "displaying actions", names) else: print "Invalid command: don't know how to get '%s'" % next[4:] elif next.startswith("debugon "): if next == "debugon oaa": M.spark__io__oaa.debug.on() elif next == "debugon pubsub": M.iris__events.debug.on() elif next == "debugon tir": M.task_manager__tir.debug.on() else: print "Invalid command: don't know how to debugon '%s'" % next[ 8:] elif next.startswith("debugoff "): if next == "debugoff oaa": M.spark__io__oaa.debug.off() elif next == "debugoff pubsub": M.iris__events.debug.off() elif next == "debugoff tir": M.task_manager__tir.debug.off() else: print "Invalid command: don't know how to debugoff '%s'" % next[ 9:] elif next.startswith("debug"): debug_arg = next[5:].strip() id_num = None if debug_arg != "": try: id_num = string.atoi(debug_arg) except AnyException: errid = NEWPM.displayError() NEWPM.pm(id_num) elif next == "python": runPyConsole() elif next == "" and get_step_controller().step(): pass elif next == "": print "" #ignoring blank input line" # Remaining commands require the kb lock (don't block!) else: # We have the KB lock if next.startswith("test "): agent.test(next[4:], get_modname()) elif next.startswith("eval ") or next.startswith("evaluate "): term = next[5:] if next.startswith("evaluate "): term = term[4:] result = agent.eval(term, get_modname()) print "->", value_str(result) elif next.startswith("run "): term = next[4:] print "synchronously running command" ext = agent.run(term, get_modname()) ext.thread_event.wait() if ext.result is SUCCESS: print "SUCCEEDED" else: print "FAILED", ext.result elif next.startswith("addfact "): print "adding fact to KB" agent.run("[conclude: " + next[7:] + "]", get_modname()) elif next.startswith("removefact "): print "adding fact to KB" agent.run("[retract: " + next[10:] + "]", get_modname()) elif next.startswith("unload "): # drop module modname = next[6:].strip() agent.unload_modpath(Symbol(modname)) elif next.startswith("["): print "running command" agent.run(next, get_modname()) else: print "ignoring unrecognized request:", next except AnyException: errid = NEWPM.displayError() return False
def __str__(self): return "<Rebindable:%s>"%value_str(self.get_value())
def oaa_construct(sym, *args): if not isSymbol(sym): raise LowError("oaastruct requires a symbol for its first argument, not %s", value_str(sym)) return Structure(sym, args)
def __str__(self): return "<Rebindable:%s>" % value_str(self.get_value())
def log_outgoing_result(requestId, errnum, result): commsDebug("Outgoing result %s %s %s", (requestId), value_str(errnum), value_str(result))