Beispiel #1
0
def resume_sources():
    """resume loads any non-agent related persistence data. it is a pre-requisite
    to loading the agent KBs"""
    if not _resumeState:
        return
    console("Resuming sources...")
    persist_root_dir = get_persist_root_dir()
    persist_src_dir = get_persist_src_dir()
    if not os.path.exists(persist_root_dir) or not os.path.exists(
            persist_src_dir):
        console("Could not find %s or %s" %
                (persist_root_dir, persist_src_dir))
        return

    try:
        from spark.internal.parse.processing import SPU_RECORD
        SPU_RECORD.restore()

        _init_resume_data()
        # set_resuming(True)
        # set_source_locator(persist__must_find_file)

        # _load_persisted_sources()
        _load_default_module()

        # set_source_locator(default__must_find_file)
        # set_resuming(False)
        console("DONE resuming sources")
    except AnyException, e:
        console("ERROR resuming sources")
        errid = NEWPM.displayError()
        NEWPM.pm(errid)
Beispiel #2
0
def resume_sources():
    """resume loads any non-agent related persistence data. it is a pre-requisite
    to loading the agent KBs"""
    if not _resumeState:
        return
    console("Resuming sources...")
    persist_root_dir = get_persist_root_dir()
    persist_src_dir = get_persist_src_dir()
    if not os.path.exists(persist_root_dir) or not os.path.exists(persist_src_dir):
        console("Could not find %s or %s" % (persist_root_dir, persist_src_dir))
        return

    try:
        from spark.internal.parse.processing import SPU_RECORD
        SPU_RECORD.restore()

        _init_resume_data()
        # set_resuming(True)
        # set_source_locator(persist__must_find_file)

        # _load_persisted_sources()
        _load_default_module()

        # set_source_locator(default__must_find_file)
        # set_resuming(False)
        console("DONE resuming sources")
    except AnyException, e:
        console("ERROR resuming sources")
        errid = NEWPM.displayError()
        NEWPM.pm(errid)
Beispiel #3
0
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
Beispiel #4
0
 def pm(self):
     if self._errid:
         NEWPM.pm(self._errid)
     else:
         print "CANNOT perform post-mortem on a Failure restored from persisted state"
Beispiel #5
0
 def pm(self):
     if self._errid:
         NEWPM.pm(self._errid)
     else:
         print "CANNOT perform post-mortem on a Failure restored from persisted state"
Beispiel #6
0
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
Beispiel #7
0
            arityOrFacts = impl.persist_arity_or_facts(agent)
            if isinstance(arityOrFacts, int):
                b, z = optBZ([None] * arityOrFacts)
                facts = [[b.bTermEval(agent, x) for x in z] \
                        for s in impl.solutions(agent, b, z) if s]
            elif arityOrFacts == None:
                raise LowError(
                    "persist_arity_or_facts method for %s returned None" %
                    impl.symbol)
            else:
                facts = arityOrFacts
            for fact in facts:
                writeFact(agent, impl.symbol, fact, output)
        except AnyException, f:
            errid = NEWPM.displayError()
            NEWPM.pm(errid)
            if isinstance(impl, DefaultImp):
                #use the predsym
                errOutput.write("%s(DefaultImp): %s\n" % (impl.symbol, str(f)))
            else:
                errOutput.write("%s: %s\n" % (impl.__class__.__name__, str(f)))
        #Testing Script. Begin:


#        #chronometers[esm].stop()
#Testing Script. End.


def writeFact(agent, functorSymbol, fact, output):
    """Write a single fact."""
    output.write("(")
Beispiel #8
0
#            #chronometers[esm].start()            
            #Testing Script. End.
            arityOrFacts = impl.persist_arity_or_facts(agent)
            if isinstance(arityOrFacts, int):
                b, z = optBZ([None]*arityOrFacts)
                facts = [[b.bTermEval(agent, x) for x in z] \
                        for s in impl.solutions(agent, b, z) if s]
            elif arityOrFacts == None:
                raise LowError("persist_arity_or_facts method for %s returned None"%impl.symbol)
            else:
                facts = arityOrFacts
            for fact in facts:
                writeFact(agent, impl.symbol, fact, output)
        except AnyException, f:
            errid = NEWPM.displayError()
            NEWPM.pm(errid)
            if isinstance(impl, DefaultImp):
                #use the predsym
                errOutput.write("%s(DefaultImp): %s\n"%(impl.symbol,str(f)))
            else:
                errOutput.write("%s: %s\n"%(impl.__class__.__name__,str(f)))
        #Testing Script. Begin:
#        #chronometers[esm].stop()
        #Testing Script. End.

def writeFact(agent, functorSymbol, fact, output):
    """Write a single fact."""
    output.write("(")
    output.write(functorSymbol.name)
    for arg in fact:
        output.write(" ")