Пример #1
0
    def test_mouse(self, output=False):
        agent = Agent(output=output)
        vision = Vision(agent)
        hands = Hands(agent)
        mouse = Mouse(hands, vision)
        self.button = None
        end = 20.0

        def update():
            if agent.time() < end:

                def fn():
                    vision.clear()
                    agent.wait(1.0)
                    self.button = Visual(random.randint(0, 500),
                                         random.randint(0, 500), 30, 30,
                                         'button')
                    vision.add(self.button, "X")

                agent.run_thread(fn)

        update()

        def fn(visual):
            if visual.equals(self.button):
                update()

        mouse.add_click_fn(fn)
        while agent.time() < end:
            visual = vision.wait_for(isa='button')
            mouse.point_and_click(visual)
        agent.wait_for_all()
        self.assertGreaterEqual(agent.time(), end)
Пример #2
0
    def test_mouse(self, output=False):
        agent = Agent(output=output)
        env = Environment()
        vision = Vision(agent, env.display)
        motor = Motor(agent, vision, env)
        self.button = None
        end = 20.0

        def update():
            if agent.time() < end:

                def fn():
                    vision.clear()
                    agent.wait(1.0)
                    self.button = env.display.add_button(
                        random.randint(0, 500), random.randint(0, 500), 'X')

                agent.run_thread(fn)

        update()

        def fn(visual):
            if visual.obj == 'X':
                update()

        env.mouse.add_click_fn(fn)
        while agent.time() < end:
            visual = vision.wait_for(isa='button')
            motor.point_and_click(visual)
        agent.wait_for_all()
        self.assertGreaterEqual(agent.time(), end)
Пример #3
0
    def __init__(self):
        super().__init__(output=True)
        self.vision = Vision(self)
        self.memory = Memory(self)
        self.audition = Audition(self)
        self.typing = Typing(Hands(self))

        def interpreter(words):
            if words[0] == 'read':
                sem = Item(isa='action', type='read', object=words[1])
                pointer = self.vision.find(isa='pointer')
                if pointer is not None:
                    self.vision.encode(pointer)
                    sem.set('x', pointer.x).set('y', pointer.y)
                return sem
            elif words[0] == 'done':
                return Item(isa='done')
            else:
                return Item(isa='action', type=words[0], object=words[1])

        self.language = Language(self)
        self.language.add_interpreter(interpreter)

        def executor(action, context):
            if action.type == 'read':
                query = Query(x=action.x, y=action.y)
                context.set(action.object, self.vision.find_and_encode(query))
            elif action.type == 'type':
                self.typing.type(context.get(action.object))

        self.instruction = Instruction(
            self, self.memory, self.audition, self.language)
        self.instruction.add_executor(executor)
Пример #4
0
class ACEUndifferentiatedAgent(Agent):
    def __init__(self):
        """Initializes the agent"""
        super().__init__(output=True)
        self.memory = Memory(self)
        self.vision = Vision(self)
        self.audition = Audition(self)
        self.typing = Typing(Hands(self))

        self.language = Language(self)
        self.language.add_interpreter(self.interpret)

        self.instruction = Instruction(self, self.memory, self.audition,
                                       self.language)
        self.instruction.add_executor(self.execute)

    def _ace_to_owl(self, text):
        """Converts ACE instruction text to OWL XML using the web API"""
        url = 'http://attempto.ifi.uzh.ch/ws/ape/apews.perl'
        params = {
            'text': text,
            'guess': 'on',
            # 'solo': 'owlxml',
            'cdrs': 'on',
            'cowlxml': 'on',
        }
        data = parse.urlencode(params).encode()
        req = request.Request(url, parse.urlencode(params).encode())
        res = request.urlopen(req)
        xml_string = res.read().decode('utf-8')
        print(xml_string)
        xml = ElementTree.fromstring(xml_string)
        print(xml)
        # print(ElementTree.tostring(xml, encoding='utf8', method='xml'))

    def interpret(self, words):
        self._ace_to_owl(' '.join(words))
        if words[0] == 'read':
            sem = Item(isa='action', type='read', object=words[1])
            pointer = self.vision.find(isa='pointer')
            if pointer is not None:
                self.vision.encode(pointer)
                sem.set('x', pointer.x).set('y', pointer.y)
            return sem
        elif words[0] == 'done':
            return Item(isa='done')
        else:
            return Item(isa='action', type=words[0], object=words[1])

    def execute(self, action, context):
        if action.type == 'read':
            query = Query(x=action.x, y=action.y)
            context.set(action.object, self.vision.find_and_encode(query))
        elif action.type == 'type':
            self.typing.type(context.get(action.object))

    def run(self, time=300):
        goal = self.instruction.listen_and_learn()
        self.instruction.execute(goal)
Пример #5
0
    def __init__(self):
        """Initializes the agent"""
        super().__init__(output=True)
        self.memory = Memory(self)
        self.vision = Vision(self)
        self.audition = Audition(self)
        self.hands = Hands(self)
        self.mouse = Mouse(self.hands, self.vision)
        self.typing = Typing(self.hands)

        self.language = Language(self)
        self.language.add_interpreter(self.interpret)
Пример #6
0
    def __init__(self):
        """Initializes the agent"""
        super().__init__(output=True)
        self.memory = Memory(self)
        self.vision = Vision(self)
        self.audition = Audition(self)
        self.typing = Typing(Hands(self))

        self.language = Language(self)
        self.language.add_interpreter(self.interpret)

        self.instruction = Instruction(self, self.memory, self.audition,
                                       self.language)
        self.instruction.add_executor(self.execute)
Пример #7
0
class PVTAgent(Agent):
    def __init__(self):
        """Initializes the agent"""
        super().__init__(output=True)
        self.vision = Vision(self)
        self.audition = Audition(self)
        self.typing = Typing(Hands(self))

    def run(self, time=300):
        while self.time() < time:
            visual = self.vision.wait_for(seen=False)
            self.vision.start_encode(visual)
            self.typing.type('j')
            self.vision.get_encoded()
Пример #8
0
class PVTAgent(Agent):
    def __init__(self, env):
        """Initializes the agent"""
        super().__init__(output=True)
        self.vision = Vision(self, env.display)  #, eyes=Eyes(self))
        self.motor = Motor(self, self.vision, env)

    def run(self, time=60):
        while self.time() < time:
            visual = self.vision.wait_for(isa='letter',
                                          region='pvt',
                                          seen=False)
            self.vision.start_encode(visual)
            self.motor.type(' ')
            self.vision.get_encoded()
Пример #9
0
    def test_instruction_read(self, output=False):
        agent = Agent(output=output)
        memory = Memory(agent)
        env = Environment()
        vision = Vision(agent, env.display)
        audition = Audition(agent, env.speakers)

        def interpreter(words):
            if words[0] == 'read':
                sem = Item(isa='action', type='read', object=words[1])
                pointer = vision.find(isa='pointer')
                if pointer is not None:
                    vision.encode(pointer)
                    sem.set('x', pointer.x).set('y', pointer.y)
                return sem
            elif words[0] == 'done':
                return Item(isa='done')
            else:
                return Item(isa='action', type=words[0], object=words[1])

        language = Language(agent)
        language.add_interpreter(interpreter)

        def executor(action, context):
            query = Query(x=action.x, y=action.y)
            context.set(action.object, vision.find_and_encode(query))

        instruction = Instruction(agent, memory, audition, language)
        instruction.add_executor(executor)

        equation = ['3', 'x', '/', '12', '=', '15', '/', '4']
        for i in range(0, len(equation)):
            env.display.add_text(50 + 50 * i, 50, equation[i])
        pointer = env.display.add(50, 50, 1, 1, 'pointer', 'pointer')

        speech = [
            'to solve', ['read a', (50, 50)], ['read A', (300, 50)], 'done'
        ]

        def thread():
            for line in speech:
                agent.wait(3.0)
                if isinstance(line, str):
                    audition.add(Aural(isa='speech'), line)
                else:
                    audition.add(Aural(isa='speech'), line[0])
                    loc = line[1]
                    pointer.move(loc[0], loc[1])

        agent.run_thread(thread)

        goal = instruction.listen_and_learn()
        self.assertEqual('solve', goal)

        context = instruction.execute(goal)
        self.assertEqual('3', context.a)
        self.assertEqual('15', context.A)

        agent.wait_for_all()
Пример #10
0
    def __init__(self, env, output=True):
        super().__init__(output=output)

        #basic pass-ins for now for speed of testing
        self.memory = OntologyMemory(self,stopOldServer=False,owlFile='uagent.owl')
        self.vision = Vision(self, env.display)
        self.audition = Audition(self, env.speakers)
        self.motor = Motor(self, self.vision, env)

        self.interpreter = Interpreter(self.memory)

        self.language = Language(self)
        self.language.add_interpreter(lambda words:
                                      self.interpreter.interpret_ace(' '.join(words)))

        self.condition_handler = ConditionHandler(self)
        self.action_handler = ActionHandler(self)
Пример #11
0
 def test_typing(self, output=False):
     agent = Agent(output=output)
     env = Environment()
     vision = Vision(agent, env.display)
     motor = Motor(agent, vision, env)
     motor.type('Hello there. What\'s up?')
     agent.wait_for_all()
     self.assertAlmostEqual(6.597, agent.time(), 1)
Пример #12
0
 def run_trial(self, sentence):
     agent = Agent(output=False)
     eyes = Eyes(agent)
     vision = Vision(agent, eyes)
     tracker = EyeTracker(eyes)
     self.add_visuals(sentence, vision)
     self.read_sentence(agent, vision)
     agent.wait_for_all()
     self.analyze_trial(sentence, tracker)
Пример #13
0
class VSAgent(Agent):

    def __init__(self, env):
        """Initializes the agent"""
        super().__init__(output=True)
        self.vision = Vision(self, env.display) #, eyes=Eyes(self))
        self.motor = Motor(self, self.vision, env)

    def run(self, time):
        while self.time() < time:
            self.vision.wait_for(isa='letter', seen=False)
            visual = self.vision.search_for(
                Query(isa='letter', color='red', region='vs'), 'X')
            if visual:
                # self.log('target present')
                self.motor.type('w')
                self.wait(1.0)
            else:
                # self.log('target absent')
                self.motor.type('r')
                self.wait(1.0)
Пример #14
0
class SearchAgent(Agent):

    def __init__(self):
        super().__init__(output=True)
        self.vision = Vision(self)
        self.audition = Audition(self)
        self.typing = Typing(Hands(self))

    def run(self, time=300):
        while self.time() < time:
            visual = self.vision.wait_for(seen=False)
            while (visual is not None
                    and not visual.isa == 'vertical-line'):
                obj = self.vision.encode(visual)
                print('**** skip')
                visual = self.vision.find(seen=False)
            if visual:
                print('**** found')
                self.typing.type('j')
                self.vision.encode(visual)
            else:
                print('**** not found')
                self.typing.type('k')
Пример #15
0
    def test_vision(self, output=False):
        agent = Agent(output=output)
        display = Environment().display
        eyes = Eyes(agent)
        vision = Vision(agent, display, eyes)
        eyes.move_to(100, 100)
        display.add_text(50, 50, 'Hello')
        display.add_text(150, 150, 'Goodbye')

        self.assertEqual(
            "Hello", vision.find_and_encode(Query(isa='text').lt('x', 100)))
        self.assertEqual("Goodbye", vision.find_and_encode(seen=False))

        vision.start_wait_for(isa='cross')
        agent.wait(2.0)
        display.add(200, 200, 20, 20, 'cross', "cross")
        self.assertEqual("cross", vision.encode(vision.get_found()))
        self.assertAlmostEqual(2.7, agent.time(), 1)
        agent.wait_for_all()
Пример #16
0
    def run_trial(self):
        agent = Agent(output=False)
        memory = Memory(agent, Memory.OPTIMIZED_DECAY)
        memory.decay_rate = .5
        memory.activation_noise = .5
        memory.retrieval_threshold = -1.8
        memory.latency_factor = .450
        vision = Vision(agent)
        typing = Typing(Hands(agent))
        self.trial_start = 0
        self.block_index = 0

        def fn():
            for i in range(PairedAssociatesTest.N_BLOCKS):
                self.block_index = i
                pairs = PairedAssociatesTest.PAIRS.copy()
                random.shuffle(pairs)
                for pair in pairs:
                    self.trial_start = agent.time()
                    vision.clear().add(Visual(50, 50, 20, 20, 'word'), pair[0])
                    agent.wait(5.0)
                    vision.clear().add(
                        Visual(50, 50, 20, 20, 'digit'), pair[1])
                    agent.wait(5.0)
        agent.run_thread(fn)

        def type_fn(c):
            self.rt.add(self.block_index, agent.time() - self.trial_start)
        typing.add_type_fn(type_fn)
        for i in range(PairedAssociatesTest.N_BLOCKS):
            for _ in range(len(PairedAssociatesTest.PAIRS)):
                word = vision.encode(vision.wait_for(isa='word'))
                chunk = memory.recall(word=word)
                if chunk:
                    typing.type(chunk.get('digit'))
                    self.correct.add(i, 1)
                else:
                    self.correct.add(i, 0)
                digit = vision.encode(vision.wait_for(isa='digit'))
                memory.store(word=word, digit=digit)
        agent.wait_for_all()
Пример #17
0
    def test_instruction_type(self, output=False):
        agent = Agent(output=output)
        env = Environment()
        memory = Memory(agent)
        vision = Vision(agent, env.display)
        audition = Audition(agent, env.speakers)
        motor = Motor(agent, vision, env)

        def interpreter(words):
            if words[0] == 'read':
                sem = Item(isa='action', type='read', object=words[1])
                pointer = vision.find(isa='pointer')
                if pointer is not None:
                    vision.encode(pointer)
                    sem.set('x', pointer.x).set('y', pointer.y)
                return sem
            elif words[0] == 'done':
                return Item(isa='done')
            else:
                return Item(isa='action', type=words[0], object=words[1])

        language = Language(agent)
        language.add_interpreter(interpreter)

        def executor(action, context):
            if action.type == 'read':
                query = Query(x=action.x, y=action.y)
                context.set(action.object, vision.find_and_encode(query))
            elif action.type == 'type':
                motor.type(context.get(action.object))

        instruction = Instruction(agent, memory, audition, language)
        instruction.add_executor(executor)

        typed = []

        def type_handler(key):
            typed.append(key)

        env.keyboard.add_type_fn(type_handler)

        env.display.add_text(50, 50, 'a')
        pointer = env.display.add(50, 50, 1, 1, 'pointer', 'pointer')

        speech = ['to type', ['read letter', (50, 50)], 'type letter', 'done']

        def thread():
            for line in speech:
                agent.wait(3.0)
                if isinstance(line, str):
                    audition.add(Aural(isa='speech'), line)
                else:
                    audition.add(Aural(isa='speech'), line[0])
                    loc = line[1]
                    pointer.move(loc[0], loc[1])

        agent.run_thread(thread)

        goal = instruction.listen_and_learn()
        self.assertEqual('type', goal)

        context = instruction.execute(goal)
        self.assertEqual('a', context.letter)

        agent.wait_for_all()

        self.assertEqual(['a'], typed)
Пример #18
0
 def __init__(self):
     """Initializes the agent"""
     super().__init__(output=True)
     self.vision = Vision(self)
     self.audition = Audition(self)
     self.typing = Typing(Hands(self))
Пример #19
0
class UndifferentiatedAgent(Agent):

    def __init__(self, env, output=True):
        super().__init__(output=output)

        #basic pass-ins for now for speed of testing
        self.memory = OntologyMemory(self,stopOldServer=False,owlFile='uagent.owl')
        self.vision = Vision(self, env.display)
        self.audition = Audition(self, env.speakers)
        self.motor = Motor(self, self.vision, env)

        self.interpreter = Interpreter(self.memory)

        self.language = Language(self)
        self.language.add_interpreter(lambda words:
                                      self.interpreter.interpret_ace(' '.join(words)))

        self.condition_handler = ConditionHandler(self)
        self.action_handler = ActionHandler(self)

        # #Not used at the moment.
        # self.item_role_list = ['target','stimulus','distractor','responseButton','infoButton']
        # #"ItemRole" in the Ontology.

        # #For future implementations (trying to use other labs' instructions)
        # self.agent_synonym_list = ['subject','participant','you']

    def is_action(self, rule):
        for action in rule.actions:
            if self.action_handler._has(action['name']):
                return True
        return False

    def check_condition(self, cond, context):
        handler = self.condition_handler._get(cond['name'])
        if handler:
            self.think('check condition "{}"'.format(cond))
            return handler(cond, context)
        else:
            return True

    def execute_action(self, action, context):
        handler = self.action_handler._get(action['name'])
        if handler:
            self.think('execute action "{}"'.format(action))
            handler(action, context)

    def process_rule(self, rule, context):
        if self.is_action(rule):
            self.think('process rule "{}"'.format(rule))
            for cond in rule.conditions:
                if not self.check_condition(cond, context):
                    return False
            for action in rule.actions:
                self.execute_action(action, context)
            return True

    def run(self, time=60):

        instr_visual = self.vision.wait_for(isa='text')
        instructions = self.vision.encode(instr_visual)
        self.language.interpret(instructions)

        while self.time() < time:
            context = Chunk()
            for rule in self.memory.recall_ground_rules():
                self.process_rule(rule, context)
Пример #20
0
 def __init__(self, env):
     """Initializes the agent"""
     super().__init__(output=True)
     self.vision = Vision(self, env.display)  #, eyes=Eyes(self))
     self.motor = Motor(self, self.vision, env)
Пример #21
0
    def test_vision(self, output=False):
        agent = Agent(output=output)
        eyes = Eyes(agent)
        vision = Vision(agent, eyes)
        eyes.move_to(100, 100)
        vision.add(Visual(50, 50, 20, 20, 'text'), "Hello")
        vision.add(Visual(150, 150, 20, 20, 'text'), "Goodbye")

        self.assertEqual("Hello", vision.find_and_encode(
            Query(isa='text').lt('x', 100)))
        self.assertEqual("Goodbye", vision.find_and_encode(seen=False))

        vision.start_wait_for(isa='cross')
        agent.wait(2.0)
        vision.add(Visual(200, 200, 20, 20, 'cross'), "cross")
        self.assertEqual("cross", vision.encode(vision.get_found()))
        self.assertAlmostEqual(2.7, agent.time(), 1)
        agent.wait_for_all()
Пример #22
0
                def fn():
                    self.vision.clear()
                    self.agent.wait(1.0)
                    self.button = Visual(random.randint(0, 500),
                                         random.randint(0, 500), 30, 30,
                                         'button')
                    self.vision.add(self.button, "X")

                self.agent.run_thread(fn)

        update_target()

        def click_target(visual):
            if visual.equals(self.button):
                update_target()

        self.mouse.add_click_fn(click_target)

        while self.agent.time() < seconds:
            visual = self.vision.wait_for(isa='button')
            self.mouse.point_and_click(visual)


if __name__ == "__main__":
    agent = Agent(output=True)
    vision = Vision(agent)
    mouse = Mouse(Hands(agent, Hands.ON_MOUSE), vision)
    game = ClickAMole(agent, vision, mouse)
    game.play(20.0)
    agent.wait_for_all()
Пример #23
0
 def __init__(self):
     super().__init__(output=True)
     self.vision = Vision(self)
     self.audition = Audition(self)
     self.typing = Typing(Hands(self))
Пример #24
0
class OWLUndifferentiatedAgent(Agent):

    def __init__(self):
        """Initializes the agent"""
        super().__init__(output=True)
        self.memory = Memory(self)
        self.vision = Vision(self)
        self.audition = Audition(self)
        self.hands = Hands(self)
        self.mouse = Mouse(self.hands, self.vision)
        self.typing = Typing(self.hands)

        self.language = Language(self)
        self.language.add_interpreter(self.interpret)

        # self.instruction = Instruction(
        #     self, self.memory, self.audition, self.language)
        # self.instruction.add_executor(self.execute)

    def _interpret_predicate(self, text, isa='fact', last=None):
        chunk = None
        (pred, args) = text.replace(')', '').split('(')
        args = args.split(',')
        if len(args) == 1:
            chunk = Chunk(isa=isa, predicate='isa',
                          subject=args[0], object=pred)
        elif len(args) == 2:
            chunk = Chunk(isa=isa, predicate=pred,
                          subject=args[0], object=args[1])
        if chunk:
            if last:
                chunk.set('last', last.id)
            self.memory.store(chunk)
        return chunk

    def _interpret_rule(self, text):
        lhs, rhs = text.split('=>')
        pred_pat = re.compile(r'[A-Za-z_-]+\([A-Za-z_,-]*\)')

        rule = Chunk(isa='rule')
        self.memory.store(rule)

        last = rule
        for t in pred_pat.findall(lhs):
            chunk = self._interpret_predicate(t, isa='condition', last=last)
            last = chunk

        last = rule
        for t in pred_pat.findall(rhs):
            chunk = self._interpret_predicate(t, isa='action', last=last)
            last = chunk

        return rule

    def _interpret_owl(self, text):
        text = text.replace(' ', '')
        if text.find('=>') >= 0:
            return self._interpret_rule(text)
        else:
            return self._interpret_predicate(text)

    def interpret(self, words):
        return self._interpret_owl(''.join(words))

    def _deep_find(self, isa):
        visual = self.vision.find(isa=isa, seen=False)
        if visual:
            return visual
        else:
            part_of = self.memory.recall(predicate='isPartOf', object=isa)
            if part_of:
                return self._deep_find(part_of.subject)
            else:
                return None

    def _execute_condition(self, cond, context):
        if cond.predicate == 'appearsIn':
            visual = self._deep_find(cond.subject)
            if visual:
                context.set('visual', visual)
                visobj = self.vision.encode(visual)
                context.set(cond.subject, visobj)
                return True
        return False

    def _execute_action(self, action, context):
        if action.subject == 'Subject':
            print('**************  ' + action.predicate)

            if action.predicate == 'click':
                visual = context.get('visual')
                self.mouse.point_and_click(visual)

            elif action.predicate == 'remember':
                pass

    def execute(self, chunk, context):
        if chunk.isa == 'rule':

            cond = self.memory.recall(isa='condition', last=chunk.id)
            while cond:
                if not self._execute_condition(cond, context):
                    return False
                cond = self.memory.recall(isa='condition', last=cond.id)

            act = self.memory.recall(isa='action', last=chunk.id)
            while act:
                self._execute_action(act, context)
                act = self.memory.recall(isa='action', last=act.id)

            return True

    def run(self, time=300):
        context = Item()

        chunk = None
        done = Query(predicate='isa', object='done')
        while not (chunk and done.matches(chunk)):
            text = self.audition.listen_for_and_encode()
            chunk = self.language.interpret(text)

        while self.time() < time:
            chunk = self.memory.recall(isa='rule')
            self.execute(chunk, context)