def test_main():
    resource = Resource('poison in body', ['amount', 'kind'])
    resource.set_values([10.0, 'mercury'])

    agent = Agent('thin agent', strict_engine=True)
    agent.set_scaffold(resource)

    ams = AgentManagementSystem('exterior laws', [agent])

    mapper = ResourceMap('scale down', 'scale', 'amount', ('factor', ))
    kwargs = {
        'poison_amount_getter': lambda: agent.resource['amount'],
        'doodle': 2.0
    }
    compulsion = Compulsion('natural decay',
                            simple_decline,
                            mapper,
                            compel_func_kwargs=kwargs)
    ams.set_law(compulsion)

    count = 0
    for agent in ams.shuffle_nodes(True, 5, False):
        before = agent.resource['amount']
        ams.compel(agent, 'natural decay')
        after = agent.resource['amount']
        assert (before == REF[count][0])
        assert (after == REF[count][1])
        count += 1
def test_main(set_random):

    essence = Essence('inclinations', ['t_1', 't_2', 't_3', 't_4', 't_5'])
    essence.set_values([0.0, 0.0, 0.0, 0.0, 0.0])

    agent = Agent('thin agent', strict_engine=True)
    agent.set_scaffold(essence)

    ams = AgentManagementSystem('exterior laws', [agent])

    mapper_1 = EssenceMap('tweak', 'wiener', 't_1', ('range_step', ))
    mapper_2 = EssenceMap('tweak', 'wiener', 't_2', ('range_step', ))
    mapper_3 = EssenceMap('tweak', 'wiener', 't_3', ('range_step', ))
    mapper_4 = EssenceMap('tweak', 'wiener', 't_4', ('range_step', ))
    mapper_5 = EssenceMap('tweak', 'wiener', 't_5', ('range_step', ))
    mapper = MapCollection([mapper_1, mapper_2, mapper_3, mapper_4, mapper_5])
    mutate = MultiMutation('jumps', lambda: 1.0, mapper, mutation_prob=0.5)
    ams.set_law(mutate)

    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[0])]))
    ams.mutate(agent, 'jumps')
    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[1])]))
    ams.mutate(agent, 'jumps')
    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[2])]))
    ams.mutate(agent, 'jumps')
    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[3])]))
    ams.mutate(agent, 'jumps')
    vals = agent.essence.values()
    assert (all([x == pytest.approx(y) for x, y in zip(vals, REF[4])]))
def test_main(set_random):

    essence = Essence('inclinations', ['t_1', 't_2', 'volatility'])
    essence.set_values([0.7, 1.5, 0.5])

    agent = Agent('thin agent', strict_engine=True)
    agent.set_scaffold(essence)

    ams = AgentManagementSystem('exterior laws', [agent])

    mapper_1 = EssenceMap('tweak_1', 'wiener', 't_1', ('range_step', ))
    mapper_2 = EssenceMap('tweak_2', 'wiener', 't_2', ('range_step', ))
    mutate_1 = Mutation('jumps_1',
                        essence.__getitem__,
                        mapper_1,
                        mutation_prob=0.5,
                        mutate_func_kwargs={'key': 'volatility'})
    mutate_2 = Mutation('jumps_2',
                        essence.__getitem__,
                        mapper_2,
                        mutation_prob=0.5,
                        mutate_func_kwargs={'key': 'volatility'})
    ams.set_laws(mutate_1, mutate_2)

    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[0])
    ]))
    ams.mutate(agent, 'jumps_1')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[1])
    ]))
    ams.mutate(agent, 'jumps_1')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[2])
    ]))
    ams.mutate(agent, 'jumps_1')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[3])
    ]))
    ams.mutate(agent, 'jumps_1')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[4])
    ]))
    ams.mutate(agent, 'jumps_2')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[5])
    ]))
    ams.mutate(agent, 'jumps_2')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[6])
    ]))
    ams.mutate(agent, 'jumps_2')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[7])
    ]))
    ams.mutate(agent, 'jumps_2')
    assert (all([
        a == pytest.approx(b) for a, b in zip(agent.essence.values(), REF[8])
    ]))
def test_main():
    #
    # Define Messages
    #
    belief = Belief('stressed', ('degree', ))
    belief.set_values(10.0)
    direction1 = Direction('collect_amount', ('intake_volume', ))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_molecules', ('A', 'B', 'C'))
    agent_resources.set_values([2.0, 1.0, 0.5])
    added_a = ResourceMap('get_A', 'delta_scale', 'A', (
        'add',
        'dilute',
    ))
    added_b = ResourceMap('get_B', 'delta_scale', 'B', (
        'add',
        'dilute',
    ))
    added_c = ResourceMap('get_C', 'delta_scale', 'C', (
        'add',
        'dilute',
    ))
    add_internal = MapCollection([added_a, added_b, added_c])

    #
    # Define Organs and their associated messages
    #
    moulder1 = Moulder('discard_or_not', make_decision, belief, direction1)

    env = Env()
    actuator1 = Actuator('collect', env.excretor, direction1, add_internal)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(moulder1)
    agent.set_organ(actuator1)
    agent.set_scaffold(agent_resources)

    #
    # Decide on direction and execute action
    #
    agent.mould('discard_or_not')
    agent.act('collect')

    for mol in REF:
        assert (isclose(REF[mol], agent.resource[mol], abs_tol=0.0001))

    try:
        agent.act('collect')
        raise AssertionError(
            'Acting twice in sequence did not raise correct exception')
    except EmptyFlashError:
        pass
Beispiel #5
0
def test_main():
    resource = Resource('harvest', ('wheat', 'rye', 'barley', 'oats'))
    resource.set_values([35.0, 12.0, 8.0, 6.0])
    agent1 = Agent('farmer Joe', strict_engine=True)
    agent1.set_scaffold(resource)

    resource = Resource('food producer', ('wheat', 'rye', 'barley', 'oats',
                                          'cash_on_hand'))
    resource.set_values([0.0, 0.0, 0.0, 0.0, 100.0])
    agent2 = Agent('yummy Inc', strict_engine=True)
    agent2.set_scaffold(resource)

    ams = AgentManagementSystem('food market', [agent1, agent2])
    uuid_of_yummy = list(ams.agents_in_scope.values())[1].agent_id_system

    mapper = ResourceMap('cash loss', 'scale', 'cash_on_hand', ('factor',))
    amort = Compulsion('amortization', interest_rate, mapper)
    ams.set_law(amort)

    mapper_wheat = ResourceMap('loss of wheat', 'scale', 'wheat', ('factor',))
    mapper_rye = ResourceMap('loss of rye', 'scale', 'rye', ('factor',))
    mapper_barley = ResourceMap('loss of barley', 'scale', 'barley', ('factor',))
    mapper_oats = ResourceMap('loss of oats', 'scale', 'oats', ('factor',))
    mapper_cereal = MapCollection([mapper_wheat, mapper_rye, mapper_barley, mapper_oats])
    sloppy = Compulsion('sloppy', lambda : 4*[0.88], mapper_cereal)
    ams.set_law(sloppy)

    ams.make_lawbook_entry(['sloppy'], agent_name_selector=farm_name_test)
    ams.make_lawbook_entry(['amortization'], agent_ids=[uuid_of_yummy])

    for agent in ams.cycle_nodes(True, 2):
        ams.engage_all_verbs(agent, validate_lawbook=True)

    vals1 = agent1.resource.values()
    vals2 = agent2.resource.values()

    assert (vals1 == REF1)
    assert (vals2 == REF2)

    ams.compel(agent2, 'sloppy')

    try:
        ams.compel(agent2, 'sloppy', validate_lawbook=True)
    except RuntimeError as e:
        if 'Compulsion sloppy is not in law book' in str(e):
            pass
        else:
            raise AssertionError('Exception was not properly raised')

    try:
        ams.compel(agent1, 'amortization')
    except KeyError as e:
        if 'cash_on_hand' in str(e):
            pass
        else:
            raise AssertionError('Exception was not properly raised')
Beispiel #6
0
def test_main():

    # Not fully implemented
    assert 1==2

    battery = Resource('battery power', ('potential',))
    battery.set_values(0.401)
    suck_power = ResourceMap('suck power', 'delta', 'potential', ('reduction',))
    b1 = Buzz('sound stimulation', ('band_1', 'band_2', 'band_3'))
    s1 = Sensor('sound in surrounding', listen, b1, suck_power)
    belief_1 = Belief('The word was spoken', ('probability',))
    int1 = Interpreter('Was the word spoken?', word_estimator, b1, belief_1)
    dir_1 = Direction('follow up request', ('word_section_1', 'word_section_2',
                                            'word_section_3', 'word_section_4'))
    moul1 = Moulder('What response to give', responder, belief_1, dir_1)
    a1 = Actuator('loudspeaker vibrations', loudspeaker_api, dir_1, suck_power)
    moul2 = Moulder('Select warn statement', warn_statement, None, dir_1,
                    resource_op_input=battery)

    bc = AutoBeliefCondition('Sufficiently confident of word spoken',
                             lambda p: p > 0.75, 'The word was spoken')
    rc = AutoResourceCondition('Sufficient power left',
                               lambda pot: pot > 0.2, 'potential')
    clausul_1 = Clause('listen for the word',
                       [('sense', 'sound in surrounding'),
                        ('interpret', 'Was the word spoken?')],
                       condition=bc)

    clausul_2 = Clause('say something to the user',
                       [('mould', 'What response to give'),
                        ('act', 'loudspeaker vibrations')])
    clausul_3 = Clause('power check', condition=rc)
    clausul_4 = Clause('power warn',
                       [('mould', 'Select warn statement'),
                        ('act', 'loudspeaker vibrations')])

    plan = Plan('Clever stuff')
    plan.add_cargo('pronounce', 'listen for the word')
    plan.add_cargo('pronounce', 'say something to the user')
    plan.add_cargo('pronounce', 'power check')
    plan.add_cargo('pronounce', 'power warn')
    plan.add_dependency(2, 0, 3)
    plan.add_dependency(0, 1)
    plan.stamp_and_approve()

    agent = Agent('smart loudspeaker')
    agent.set_organs(s1, int1, moul1, moul2, a1)
    agent.set_messages(b1, belief_1, dir_1)
    agent.set_scaffold(battery)
    agent.set_policies(clausul_1, clausul_2, clausul_3, clausul_4, plan)

    agent.enact('Clever stuff')
    agent.enact('Clever stuff')
    agent.enact('Clever stuff')
    agent.enact('Clever stuff')
def test_main():
    #
    # Define Messages
    #
    feature = Feature('colour', ('hue', 'saturation', 'lightness'))

    #
    # Define Scaffold
    #
    agent_essence = Essence('my_parameters',
                            ('hue', 'saturation', 'lightness', 'mood'))
    agent_essence.set_values([0.9, 0.4, 1.0, 'jubilant'])
    slicer_of_essence = MessageOperator(
        agent_essence, slice_labels=['hue', 'saturation', 'lightness'])
    #
    # Define Organs and their associated messages
    #
    cortex = Cortex('colour_revealer',
                    expose_distort,
                    slicer_of_essence,
                    feature,
                    cortex_func_kwargs={'distort_degree': 0.05})

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(cortex)
    agent.set_scaffold(agent_essence)

    #
    # Tickle the cortex
    #
    tickle_me_1 = agent.tickle('colour_revealer')
    for val, ref_val in zip(tickle_me_1.values(), REF1):
        assert (val == pytest.approx(ref_val, abs=1e-3))

    tickle_me_2 = agent.tickle('colour_revealer')
    for val, ref_val in zip(tickle_me_2.values(), REF2):
        assert (val == pytest.approx(ref_val, abs=1e-3))

    agent_essence.set_values([0.0, 0.0, 0.0, 'hey'])
    tickle_me_3 = agent.tickle('colour_revealer')
    for val, ref_val in zip(tickle_me_3.values(), REF3):
        assert (val == pytest.approx(ref_val, abs=1e-3))
def test_main():
    #
    # Define Messages
    #
    belief = Belief('Projectile status', ('speed', 'height', 'angle'))
    belief.set_values([100.0, 0.3, 0.2])
    direction = Direction('motion', ('horizontal direction',
                                     'horizontal magnitude',
                                     'vertical direction',
                                     'vertical magnitude'))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_resource', ('internal_energy',))
    agent_resources.set_values(20.0)
    change_energy = ResourceMap('adjust_energy', 'delta', 'internal_energy', ('expend_energy',))

    #
    # Define Organs and their associated messages
    #
    moulder = Moulder('take evasive action?', make_decision,
                      belief, direction,
                      change_energy)
    splitter_1 = MessageOperator(direction, slice_labels=['horizontal direction',
                                                          'horizontal magnitude'])
    splitter_2 = MessageOperator(direction, slice_labels=['vertical direction',
                                                          'vertical magnitude'])
    actuator1 = Actuator('move left right', move_rule_horizontal, splitter_1)
    actuator2 = Actuator('move up down', move_rule_vertical, splitter_2)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(moulder)
    agent.set_organ(actuator1)
    agent.set_organ(actuator2)
    agent.set_scaffold(agent_resources)
    agent.set_message(belief)

    #
    # Decide on direction and execute action
    #
    agent.mould('take evasive action?')
    agent.act('move up down')
    agent.act('move left right')
    assert (agent.resource['internal_energy'] == REF_E[0])
    belief.set_values([100.0, 1.3, -0.5])
    agent.mould('take evasive action?')
    agent.act('move up down')
    agent.act('move left right')
    assert (agent.resource['internal_energy'] == REF_E[1])
    for e1, e2 in zip(REPO, REF_REPO):
        assert(e1 == e2)

    try:
        agent.act('move up down')
        raise AssertionError('Action without preceding moulding did not raise exception')
    except EmptyFlashError:
        pass
    else:
        raise AssertionError('Action without preceding moulding did not raise expected exception')
    try:
        agent.act('move left right')
        raise AssertionError('Action without preceding moulding did not raise exception')
    except EmptyFlashError:
        pass
    else:
        raise AssertionError('Action without preceding moulding did not raise expected exception')
Beispiel #9
0
def test_main():
    #
    # Define Messages
    #
    buzz = Buzz('nerve_endings', ('first', 'second'))
    belief_1 = Belief('chance_of_rain', ('probability', ))
    belief_2 = Belief('ambiguity_kills_me', ('mood', ))
    direction = Direction('get_which_umbrella', ('any', 'colour'))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_resource', ('energy', ))
    agent_resources.set_values([100.0])
    change_energy = ResourceMap('adjust_energy', 'delta', 'energy',
                                ('how_much', ))

    #
    # Define Organs and their associated messages
    #
    interpreter_1 = Interpreter('will_it_rain',
                                rain_predictor,
                                buzz,
                                belief_1,
                                resource_map_output=change_energy)
    interpreter_2 = Interpreter('am_i_unlucky',
                                mood_maker,
                                belief_1,
                                belief_2,
                                resource_map_output=change_energy)
    total_belief = MessageOperator([belief_1, belief_2], extend=True)
    moulder = Moulder('fetch_umbrella_type', make_decision, total_belief,
                      direction, change_energy)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent._set('buzz', 'nerve_endings', buzz)
    agent.set_organ(moulder)
    agent.set_organ(interpreter_1)
    agent.set_organ(interpreter_2)
    agent.set_scaffold(agent_resources)

    #
    # Decide on direction and execute action
    #
    agent.buzz['nerve_endings'].set_values([0.2, 0.2])
    agent.interpret('will_it_rain')
    agent.interpret('am_i_unlucky')
    agent.mould('fetch_umbrella_type')
    assert (agent.direction['get_which_umbrella'].values() == REF[0])
    assert (agent.resource.values()[0] == pytest.approx(REF_RESOURCE[0]))

    agent.buzz['nerve_endings'].set_values([1.0, 0.6])
    agent.interpret('will_it_rain')
    agent.interpret('am_i_unlucky')
    agent.mould('fetch_umbrella_type')
    assert (agent.direction['get_which_umbrella'].values() == REF[1])
    assert (agent.resource.values()[0] == pytest.approx(REF_RESOURCE[1]))

    agent.buzz['nerve_endings'].set_values([1.0, 2.6])
    agent.interpret('will_it_rain')
    agent.interpret('am_i_unlucky')
    agent.mould('fetch_umbrella_type')
    assert (agent.direction['get_which_umbrella'].values() == REF[2])
    assert (agent.resource.values()[0] == pytest.approx(REF_RESOURCE[2]))
def test_main():
    #
    # Define Messages
    #
    belief = Belief('rich_environment',
                    ('stuff_1', 'stuff_2', 'stuff_3', 'stuff_4'))
    belief.set_values([0.7, 0.3, 0.6, 0.1])
    direction1 = Direction('grab_this_much', ('grab_volume', ))
    direction2 = Direction('shout_loud', ('volume', ))

    #
    # Define Scaffold and Map for it
    #
    agent_resources = Resource('internal_resource',
                               ('internal_energy', 'carrot', 'leek'))
    agent_resources.set_values([100.0, 4, 5])
    change_energy = ResourceMap('adjust_energy', 'delta', 'internal_energy',
                                ('expend_energy', ))
    change_carrot = ResourceMap('adjust_carrot', 'delta', 'carrot',
                                ('tweak_carrot', ))
    change_leek = ResourceMap('adjust_leek', 'delta', 'leek', ('tweak_leek', ))
    hoarding_food = MapCollection([change_carrot, change_leek])

    #
    # Define Organs and their associated messages
    #
    moulder1 = Moulder('reach_and_grab', make_decision, belief, direction1,
                       change_energy)
    moulder2 = Moulder('shout_how_much', shouter, belief, direction2)

    env = Env()
    actuator1 = Actuator('grab_it', env.grabber, direction1, hoarding_food)
    actuator2 = Actuator('shout', env.shout_into_void, direction2)

    #
    # Initialize Agent
    #
    agent = Agent('test_agent', strict_engine=True)
    agent.set_organ(moulder1)
    agent.set_organ(moulder2)
    agent.set_organ(actuator1)
    agent.set_organ(actuator2)
    agent.set_scaffold(agent_resources)

    #
    # Decide on direction and execute action
    #
    agent.mould('reach_and_grab')
    agent.act('grab_it')

    assert (agent.resource.values() == REF_RESOURCE_OUTCOME)

    agent.mould('shout_how_much')
    agent.act('shout')
    agent.mould('shout_how_much')
    agent.act('shout')

    assert (isclose(env.loud_cumsum, 3.4))

    try:
        agent.act('shout')
        raise AssertionError(
            'Action without preceding moulding did not raise exception')
    except EmptyFlashError:
        pass
    else:
        raise AssertionError(
            'Action without preceding moulding did not raise expected exception'
        )
Beispiel #11
0
def test_main():
    belief = Belief('dummy', ('a1', ))
    resource = Resource('internal energy', ('level', ))
    mapper = ResourceMap('eat energy', 'delta', 'level', ('shift', ))
    interpreter1 = Interpreter('thinker',
                               lambda x: (x + 1, -1),
                               belief,
                               belief,
                               resource_map_output=mapper)
    interpreter2 = Interpreter('thinker X',
                               lambda x: (x + 1, -3),
                               belief,
                               belief,
                               resource_map_output=mapper)
    battery = AutoResourceCondition('battery left', lambda x: x > 0)
    heart_1 = Heartbeat('big heart',
                        battery,
                        ticker_arithmetic=lambda: 2,
                        max_ticker=4)
    heart_2 = Heartbeat('small heart',
                        battery,
                        ticker_arithmetic=lambda: 1,
                        max_ticker=4)

    agent_1 = Agent('A1')
    agent_1.set_organs(interpreter1, interpreter2)
    belief.set_values([1])
    resource.set_values([10])
    agent_1.set_message(belief)
    agent_1.set_scaffold(resource)
    agent_1.set_policies(heart_1, heart_2)

    assert (agent_1.belief['dummy'].values()[0] == REF_B1[0])
    assert (agent_1.inert == REF_I1[0])
    agent_1.pump('big heart')
    agent_1.interpret('thinker')
    assert (agent_1.belief['dummy'].values()[0] == REF_B1[1])
    assert (agent_1.inert == REF_I1[1])
    agent_1.pump('big heart')
    agent_1.interpret('thinker')
    assert (agent_1.belief['dummy'].values()[0] == REF_B1[2])
    assert (agent_1.inert == REF_I1[2])
    agent_1.pump('big heart')
    agent_1.interpret('thinker')
    assert (agent_1.belief['dummy'].values()[0] == REF_B1[3])
    assert (agent_1.inert == REF_I1[3])

    agent_1.revive()
    assert (agent_1.inert == False)

    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[0])
    assert (agent_1.inert == REF_I2[0])
    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[1])
    assert (agent_1.inert == REF_I2[1])
    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[2])
    assert (agent_1.inert == REF_I2[2])
    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[3])
    assert (agent_1.inert == REF_I2[3])
    agent_1.pump('small heart')
    agent_1.interpret('thinker X')
    assert (agent_1.belief['dummy'].values()[0] == REF_B2[4])
    assert (agent_1.inert == REF_I2[4])