def rawoaasolve(agent, sparkgoal, sparkparams, sparkpattern=None): oaa = _oaa(agent) iclgoal = value_to_icl(sparkgoal) iclparams = value_to_icl(sparkparams) iclanswers = IclList() debug("calling oaaSolve on %s", iclgoal) functor = iclgoal.functor logInfo("rawoaasolve[%s]"%functor) result = oaa.oaaSolve(iclgoal, iclparams, iclanswers) logInfo("rawoaasolve complete[%s]"%functor) if result: debug("oaaSolve returned success: %s", iclanswers) if not iclanswers.isList(): raise LowError("The call to oaaSolve returned a non-IclList answer: %s"%iclanswers) if sparkpattern is None: ans = icl_to_value(iclanswers) else: bindings = HashMap() iclpattern = value_to_icl(sparkpattern) anslist = [] for iclans in iclanswers.iterator(): bindings.clear() if UNIFIER.matchTerms(iclans, iclgoal, bindings): anslist.append(icl_to_value(UNIFIER.deref(iclpattern, bindings))) else: raise LowError("The call to oaaSolve returned an answer that doesn't unify with the query:\nans=%s\query=%s"%(iclans, iclgoal)) ans = List(anslist) logInfo("rawoaasolve answers deconstructed[%s]"%functor) return ans else: debug("oaaSolve return failure: %s", iclanswers) logError("rawoaasolve return failure with answers [%s]"%iclanswers) raise OAAError("The call to oaaSolve [goal %s] failed and returned %s"\ %(functor, iclanswers))
def get_online_agents(agent): oaa = get_oaa(agent) OAAAGENTS = [] tTerm = IclTerm.fromString(True, "agent_data(Id,Type,ready,Sv,Name,Info)") answers = IclList() oaa.oaaSolve(tTerm, IclList(IclTerm.fromString(True, "block(true)")),answers) for i in range(answers.size()): OAAAGENTS.append(answers.getTerm(i).getTerm(4).toIdentifyingString()) # Name is term #4. return OAAAGENTS
def get_online_agents(agent): oaa = get_oaa(agent) OAAAGENTS = [] tTerm = IclTerm.fromString(True, "agent_data(Id,Type,ready,Sv,Name,Info)") answers = IclList() oaa.oaaSolve(tTerm, IclList(IclTerm.fromString(True, "block(true)")), answers) for i in range(answers.size()): OAAAGENTS.append(answers.getTerm(i).getTerm( 4).toIdentifyingString()) # Name is term #4. return OAAAGENTS
def value_to_icl(x): # DOESN'T HANDLE INFINITE STRUCTURES WELL "Map a value to an ICL object" if isinstance(x, types.IntType): return IclInt(x) elif isinstance(x, types.LongType): return IclInt(x) elif isinstance(x, types.FloatType): return IclFloat(x) elif isinstance(x, basestring): try: return IclStr(str(x)) except: #OAA has a hard-limit on string length return IclDataQ(String(str(x)).getBytes()) elif isinstance(x, types.TupleType): al = ArrayList(len(x)) for elt in x: al.add(value_to_icl(elt)) return IclList(al) elif isStructure(x): s = x.functor.name nargs = len(x) if nargs == 0: # treat as '@@'("absname") args = (s, ) s = NULLARY_FUNCTOR else: args = x al = ArrayList(nargs) for elt in args: al.add(value_to_icl(elt)) return IclStruct(s, al) elif isinstance(x, IclTerm): return x elif isVariable(x) and x.isLocal(): return ICL_CONSTRUCTOR.createVariable(-1, -1, x.name) # name = x.name # if name[1] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": # return IclVar(name[1:]) # else: # return IclVar("_"+name[1:]) elif isSymbol(x): # treat as '@'("absname") al = ArrayList(1) al.add(IclStr(x.name)) return IclStruct(ATOM_FUNCTOR, al) elif x is None: # treat as '#'(0) al = ArrayList(1) al.add(IclInt(0)) return IclStruct(REF_FUNCTOR, al) elif hasattr(x, "coerceToSPARKForOAA"): return value_to_icl(x.coerceToSPARKForOAA()) else: # treat as '#'(<id>) id = getId(x) print "Unusual object type=%s id=%s being passed to OAA: %r" \ % (type(x), id, x) al = ArrayList(1) al.add(IclInt(id)) return IclStruct(REF_FUNCTOR, al)
def oaaStart(agent, opt_host, opt_port, opt_agentname): if opt_host is None: opt_host = "" if opt_port is None: opt_port = 0 if opt_agentname is None: opt_agentname = "RandomAgent" solvablefacts = agent.factslist0(Solvable) al = ArrayList(len(solvablefacts)) # may need more if multiple arities debug("solvablefacts= %s", solvablefacts) #debug("act_arity_imp= %s/%s", act_arity_imp, ACT_ARITY) #debug("TEST") #debug("pred_imp=%s", current_agent(bindings)._pred_imp) for (str, sym) in solvablefacts: #from spark.internal.parse.newparse import symbol_get_syminfo decl = agent.getDecl(sym) minarity = decl.modes[0].sigreq if decl.modes[0].sigrep: maxarity = minarity + 8 else: maxarity = minarity for arity in range(minarity, maxarity + 1): #debug("Adding %s/%s", str, arity) args = ArrayList(arity) for i in range(arity): args.add(IclVar("_" + ` i `)) al.add(IclStruct(str, args)) # THREADRUN solvables = IclList(al) if opt_host == "": hosticl = IclVar("Host") else: hosticl = IclStr(opt_host) if opt_port == 0: porticl = IclVar("Port") else: porticl = IclInt(opt_port) address = IclStruct("tcp", hosticl, porticl) libcom = LibCom(LibComTcpProtocol(), []) oaa = LibOaa(libcom) if not libcom.comConnect(CONNECTION_ID, address, EMPTY_ICL_LIST): raise OAAError("Cannot connect to %s" % address) # register callback #print "Registering callback" oaa.oaaRegisterCallback(APP_DO_EVENT, \ OAASolveEventListener(oaa, agent)) # register solvables #print "Registering solvables", solvables oaa.oaaRegister(CONNECTION_ID, opt_agentname, solvables, \ EMPTY_ICL_LIST) # call ready #print "Calling oaaReady" oaa.oaaReady(True) # print messages # EPILOGUE _set_oaa(agent, oaa) return [opt_host, opt_port, opt_agentname]
def _sbi_task_icl_rep(agent, task, pi_name): """generate icl representation for a task with no tframe, return IclList. subroutine for _sub_build_intention_icl""" #assert(task._tframe is None) event_icl_list = _sbi_pi_arraylist_rep(agent, task, pi_name) #return intention with no subtasks return IclStruct('intention', event_icl_list[0], \ event_icl_list[1], event_icl_list[2], \ IclList(ArrayList()))
def return_solutions(self): answer = IclList(self._answerlist) debug("ExternalSolve returning solutions %r", answer) try: self._oaa.oaaReturnDelayedSolutions(self._id, answer) debug("ExternalSolve called oaaReturnDelayedSolutions, %s, %s",\ self._id, answer) except AnyException: print "Exception while returning solutions to oaa", self._id NEWPM.displayError() debug("ExternalSolve return_solutions finishing")
def rawoaasolve(agent, sparkgoal, sparkparams, sparkpattern=None): oaa = _oaa(agent) iclgoal = value_to_icl(sparkgoal) iclparams = value_to_icl(sparkparams) iclanswers = IclList() debug("calling oaaSolve on %s", iclgoal) functor = iclgoal.functor logInfo("rawoaasolve[%s]" % functor) result = oaa.oaaSolve(iclgoal, iclparams, iclanswers) logInfo("rawoaasolve complete[%s]" % functor) if result: debug("oaaSolve returned success: %s", iclanswers) if not iclanswers.isList(): raise LowError( "The call to oaaSolve returned a non-IclList answer: %s" % iclanswers) if sparkpattern is None: ans = icl_to_value(iclanswers) else: bindings = HashMap() iclpattern = value_to_icl(sparkpattern) anslist = [] for iclans in iclanswers.iterator(): bindings.clear() if UNIFIER.matchTerms(iclans, iclgoal, bindings): anslist.append( icl_to_value(UNIFIER.deref(iclpattern, bindings))) else: raise LowError( "The call to oaaSolve returned an answer that doesn't unify with the query:\nans=%s\query=%s" % (iclans, iclgoal)) ans = List(anslist) logInfo("rawoaasolve answers deconstructed[%s]" % functor) return ans else: debug("oaaSolve return failure: %s", iclanswers) logError("rawoaasolve return failure with answers [%s]" % iclanswers) raise OAAError("The call to oaaSolve [goal %s] failed and returned %s"\ %(functor, iclanswers))
def build_intention_icl(agent): """builds an IclList representation of the agent's current intention structure. this representation only includes task tframes and their associated goals/tasks""" intentions = ArrayList() intention_structure = agent._intention_structure for root in intention_structure.get_root_tframes(): tree = _sub_build_intention_icl(agent, root) for iclstruct in tree: if not (isinstance(iclstruct, IclStruct)): raise AssertionError intentions.add(iclstruct) return IclList(intentions)
def oaaPSolve(agent, namestring, params, *args): ans = None #Testing Script. Begin: # global chronometers # chronometers["oaaPSolve"].start() #Testing Script. End. oaa = _oaa(agent) goal = construct_goal(agent, namestring, args) iclanswers = IclList() debug("calling oaaSolve on %s", goal) completed_without_exception = False functor = goal.functor #------- #print "Goal: %s, params: %s"%(goal, params) try: #debug("Calling oaaSolve(%s, %s, %s)", goal, value_to_icl(params), iclanswers) logInfo("oaasolve[%s]" % functor) result = oaa.oaaSolve(goal, value_to_icl(params), iclanswers) #print "RESULT is %s"%result #debug("Call to oaaSolve returned %s with answers %s", result, iclanswers) completed_without_exception = True finally: if not completed_without_exception: #record exception on its way up print "DEBUG: oaaSolve raised an exception" errid = NEWPM.displayError() if completed_without_exception: logInfo("oaasolve complete[%s]" % functor) if result: debug("oaaSolve returned success: %s", iclanswers) answers = deconstruct_answers(namestring, args, iclanswers) logInfo("oaasolve answers deconstructed[%s]" % functor) debug("deconstructed: %s", answers) if answers: ans = answers[0] else: debug("oaaSolve return failure: %s", iclanswers) raise OAAError("The call to oaaSolve [goal %s] failed and returned %s"\ %(functor, iclanswers)) #Testing Script. Begin: # chronometers["oaaPSolve"].stop() #Testing Script. End. return ans
def createList(self, start, end, elements): al = ArrayList(len(elements)) for elt in elements: al.add(elt) return IclList(al)
def oaaStop(agent): if _has_oaa(agent): oaa = _oaa(agent) oaa.oaaDisconnect(IclList()) _unset_oaa(agent, oaa) return True
from java.io import FileInputStream from java.lang import String except ImportError: print "WARNING: Cannot access java.util - OAA interface will not work" def ArrayList(n): print "WARNING: ATTEMPTING TO CALL java.util.ArrayList WITHIN PYTHON" return [None] * n try: from com.sri.oaa2.icl import IclInt, IclFloat, IclStr, IclVar, IclStruct, IclList, IclTerm, IclDataQ, Unifier from com.sri.oaa2.lib import OAAEventListener, LibOaa from com.sri.oaa2.com import LibCom, LibComTcpProtocol EMPTY_ICL_LIST = IclList() UNIFIER = Unifier.getInstance() # Tell SPARK how to print IclTerms readably imported = True # Removing "stdout" from the root logger: from org.apache.log4j import LogManager LogManager.getRootLogger().removeAppender("stdout") except ImportError: print "WARNING: Cannot access OAA or log4j Java packages - OAA interface will not work" if not imported: class OAAEventListener: pass else: #setup the java-based OAA manager
def _sub_build_intention_icl(agent, tframe): """builds the IclList representation of a single intention/taskexprtframe. subroutine of build_intention_icl""" ################################################## # locals: # intention_rep: holds the list representation # of the the intention as it is being constructed. # it has all of the IclStruct params except the subtasks # subtask_list: holds a list of IclLists that represent subtasks # subtasks: list of the subevents of the current tframe # tframe_children: list of child tframes according to the agent ################################################## ################################################## # setup the intention representation, if necessary ################################################## intention_rep = None #print "current tframe", tframe.name(), tframe.__class__.__name__ if isinstance(tframe, TaskExprTFrame) and not isinstance( tframe.event(), PseudoGoalEvent): name = tframe_procedure_instance(tframe).name() intention_rep = _sbi_pi_arraylist_rep(agent, tframe.event(), name) #note: at this point, we still need to fill in the children slot ################################################## # build list of sub-tasks ################################################## subtask_list = [] # - traverse goals w/o pi's first subtasks = procedure_instance_subtasks(agent, tframe) for task in subtasks: #print "examining task: ", task.name(), task.__class__.__name__, task._tframe # look for tasks that don't have a tframe yet and # add their descriptions if isinstance(task, GoalEvent) and (task._tframe is None or isinstance( task._tframe, BasicImpTFrame)): # currently signify no proc with an empty stringx # appends an IclList subtask_list.append(_sbi_task_icl_rep(agent, task, "")) # - traverse tframe children tframe_children = agent.tframe_children(tframe) for child in tframe_children: #print "examining frame: ", child.name() subtree = _sub_build_intention_icl(agent, child) if subtree is not None: subtask_list.extend(subtree) ################################################## # compute return value ################################################## # if we have a taskexpr tframe (intention_rep not None), # put the subtask list into the children slot if intention_rep is not None: subtask_arraylist = _sbi_list_arraylist(subtask_list) return [IclStruct('intention', intention_rep[0], \ intention_rep[1], intention_rep[2], IclList(subtask_arraylist))] # we don't have a taskexpr tframe, but still include the task children in the # icl representation else: return subtask_list
def makeIclList(elements): from spark.io.oaa import ArrayList, IclList al = ArrayList(len(elements)) for elt in elements: al.add(elt) return IclList(al)