Exemple #1
0
def tsetter_action(agent, **kwargs):
    execution_key = get_exec_key(kwargs=kwargs)
    return common_action(agent,
                         get_group(RED_FOLLOWERS, execution_key=execution_key),
                         get_group(BLUE_FOLLOWERS,
                                   execution_key=execution_key),
                         gt,
                         lt, **kwargs)
Exemple #2
0
 def setUp(self, props=None):
     set_up()
     self.wolf = create_wolf(TEST_WNAME, TEST_WNUM)
     self.sheep = create_sheep(TEST_SNAME, TEST_SNUM)
     self.wolves = get_group(WOLF_GROUP)
     self.wolves += self.wolf
     # make a new plural for sheep!
     self.sheeps = get_group(SHEEP_GROUP)
     self.sheeps += self.sheep
     get_env().place_member(self.sheep, None)
     get_env().place_member(self.wolf, None)
Exemple #3
0
def tsetter_action(agent, **kwargs):
    """
    Action for trend setters
    """
    return common_action(
        agent,
        get_group(RED_FOLLOWERS, agent.exec_key),
        get_group(BLUE_FOLLOWERS, agent.exec_key),
        gt,
        lt,
        **kwargs)
Exemple #4
0
def follower_action(agent, **kwargs):
    """
    Action for followers
    """
    return common_action(
        agent,
        get_group(RED_TSETTERS, agent.exec_key),
        get_group(BLUE_TSETTERS, agent.exec_key),
        lt,
        gt,
        **kwargs
    )
Exemple #5
0
def transaction(store, consumer):
    """
    Add money to the store's capital from consumer.
    """
    capital = store.get_attr(CAPITAL) + consumer.get_attr(SPENDING_POWER)
    store.set_attr(CAPITAL, capital)
    if NOT_DEBUG:
        print(store.name, store.get_attr(CAPITAL))
        bb_grp = get_group(BIG_BOX, store.exec_key)
        mp_grp = get_group(MP_STORE, store.exec_key)
        debug_retailer(bb_grp)
        debug_retailer(mp_grp)
Exemple #6
0
def wolfram_action(wolf_env, **kwargs):
    """
    The action that will be taken every period.
    """
    execution_key = kwargs[EXEC_KEY]

    row_above_idx = get_env_attr("prev_row_idx", execution_key=execution_key)

    active_row_idx = wolf_env.height - wolf_env.get_periods()

    wolf_env.user.tell("Checking agents in row {} against the rule {}".format(
        active_row_idx, get_env_attr("rule_num", execution_key=execution_key)))

    if active_row_idx < 1:
        gone_far_enough()
        return DONT_MOVE
    else:
        next_row_idx = active_row_idx - 1

        next_row = wolf_env.get_row_hood(next_row_idx)

        left_color = \
            agent_color(x=0, y=active_row_idx, execution_key=execution_key)

        x = 0

        row_above = wolf_env.get_row_hood(row_above_idx)

        for agent_nm in row_above:
            if DEBUG:
                print("Checking agent at", row_above[agent_nm])
            if (x > 0) and (x < wolf_env.width - 1):
                middle_color = agent_color(agent_nm=agent_nm,
                                           execution_key=execution_key)
                right_color = agent_color(x=x + 1,
                                          y=active_row_idx,
                                          execution_key=execution_key)
                if DEBUG:
                    print("  Left: %d, middle: %d, right: %d" %
                          (left_color, middle_color, right_color))
                if next_color(
                        get_env_attr("rule_dict", execution_key=execution_key),
                        left_color, middle_color, right_color):
                    wolf_env.add_switch(
                        next_row[agent_nm_from_xy(x, next_row_idx)],
                        get_group(WHITE, execution_key),
                        get_group(BLACK, execution_key))
                left_color = middle_color
            x += 1

    set_env_attr("prev_row_idx", next_row_idx, execution_key=execution_key)
    return DONT_MOVE
Exemple #7
0
def wolf_action(agent, **kwargs):
    if agent.duration <= 0:
        return rem_agent(agent, **kwargs)
    else:
        prey = get_prey(agent, get_group(SHEEP_GROUP, kwargs=kwargs), **kwargs)
        if prey is not None:
            eat(agent, prey, **kwargs)
        else:
            agent.duration /= 2
        agent[TIME_TO_REPR] -= 1
        if agent[TIME_TO_REPR] == 0:
            reproduce(agent, create_wolf, get_group(WOLF_GROUP, kwargs=kwargs),
                      **kwargs)
        return False
Exemple #8
0
def gameoflife_action(biosphere):
    """
    The action that will be taken every period for the enviornment.
    Loops through the list of agents that has to come alive and die
        and carries out the corresponding action.
    """
    global to_come_alive
    global to_die
    global reset_lists
    b = get_group(BLACK)
    for agent_pos in to_come_alive:
        if DEBUG:
            print("Agent at", agent_pos, "will come alive")
        if biosphere.get_agent_at(agent_pos[0], agent_pos[1]) is None:
            agent = create_game_cell(agent_pos[0], agent_pos[1])
            b += agent
            biosphere.place_member(agent, xy=(agent_pos[0], agent_pos[1]))
    for agent in to_die:
        if not isinstance(agent, tuple):
            if DEBUG:
                print("Agent at", agent, "will die")
            agent.die()
            b.del_member(agent)
            biosphere.remove_location(agent.get_x(), agent.get_y())
    reset_lists = True
    return True
Exemple #9
0
def populate_board(patterns, pattern_num, execution_key=CLI_EXEC_KEY):
    agent_locs = patterns[pattern_num]
    b = get_group(BLACK, execution_key)
    for loc in agent_locs:
        agent = create_game_cell(loc[X], loc[Y])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #10
0
def central_bank_action(agent, **kwargs):
    """
    If exchanges are down "enough", distribute coupons!
    Enough is a parameter.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    CB_interven_pts = get_env_attr("CB_interven_pts",
                                   execution_key=execution_key)
    set_env_attr("num_rounds",
                 get_env_attr("num_rounds", execution_key=execution_key) + 1,
                 execution_key=execution_key)
    co_op_mbrs = get_group(CO_OP_MEMBERS, execution_key=execution_key)
    unemp_rate = get_env_attr("last_per_unemp",
                              execution_key=execution_key,
                              default_value=0) / len(co_op_mbrs) * 100
    unemp_threshold = agent["percent_change"]
    if unemp_rate >= unemp_threshold:
        user_tell("Unemployment has risen to " + str(unemp_rate) +
                  " more than default value " + str(unemp_threshold) +
                  " CB Intervened")
        CB_interven_pts.append([
            get_env_attr("num_rounds", execution_key=execution_key),
            get_env_attr("last_per_exchg", execution_key=execution_key)
        ])
        distribute_coupons(agent, execution_key=execution_key)
    return True
Exemple #11
0
def populate_board_tumbler(width, height):
    center = [width // 2, height // 2]
    # this code is clearly awful: we must re-code this
    # per the mathematical pattern underlying this crap
    b = get_group(BLACK)
    agent_loc = [(center[0] - 1, center[1]), (center[0] - 2, center[1]),
                 (center[0] + 1, center[1]),
                 (center[0] + 2, center[1]), (center[0] - 1, center[1] - 1),
                 (center[0] - 2, center[1] - 1),
                 (center[0] + 1, center[1] - 1),
                 (center[0] + 2, center[1] - 1),
                 (center[0] - 1, center[1] - 2),
                 (center[0] - 1, center[1] - 3),
                 (center[0] - 1, center[1] - 4),
                 (center[0] + 1, center[1] - 2),
                 (center[0] + 1, center[1] - 3),
                 (center[0] + 1, center[1] - 4),
                 (center[0] - 3, center[1] - 3),
                 (center[0] - 3, center[1] - 4),
                 (center[0] - 3, center[1] - 5),
                 (center[0] - 2, center[1] - 5),
                 (center[0] + 3, center[1] - 3),
                 (center[0] + 3, center[1] - 4),
                 (center[0] + 3, center[1] - 5),
                 (center[0] + 2, center[1] - 5)]

    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #12
0
def bacterium_action(agent, **kwargs):
    """
    Algorithm:
        1) sense env
            (toxin_level = calc_toxin(toxins, agent))
        2) see if it is worse or better than previous env
        3) if worse, change direction
            (agent["angle"] = new_angle)
        4) move (done automatically by returning False)
    """
    if DEBUG:
        user_tell("I'm " + agent.name + " and I'm hungry.")

    execution_key = CLI_EXEC_KEY
    if EXEC_KEY in kwargs:
        execution_key = kwargs[EXEC_KEY]

    toxin_level = calc_toxin(get_group(TOXINS, execution_key=execution_key),
                             agent)
    nutrient_level = calc_nutrient(
        get_group(NUTRIENTS, execution_key=execution_key), agent)
    if agent["prev_toxicity"] is not None:
        toxin_change = toxin_level - agent["prev_toxicity"]
    else:
        toxin_change = sys.maxsize * (-1)

    if agent["prev_nutricity"] is not None:
        nutrient_change = nutrient_level - agent["prev_nutricity"]
    else:
        nutrient_change = sys.maxsize * (-1)

    threshold = DEF_THRESHOLD
    agent["prev_toxicity"] = toxin_level
    agent["prev_nutricity"] = nutrient_level

    if (toxin_change > nutrient_change) or (threshold >= toxin_level):
        if agent["angle"] is None:
            new_angle = randint(0, 360)
        else:
            angle_shift = randint(45, 315)
            new_angle = agent["angle"] + angle_shift
        if (new_angle > 360):
            new_angle = new_angle % 360
        agent["angle"] = new_angle

    # return False means to move
    return False
Exemple #13
0
def populate_board_small_exploder(width, height, execution_key=CLI_EXEC_KEY):
    center = [width // 2, height // 2]
    agent_loc = get_agent_rules("small_exploder", center)
    b = get_group(BLACK, execution_key)
    for loc in agent_loc:
        agent = create_game_cell(loc[X], loc[Y])
        b += agent
        get_env().place_member(agent, xy=loc)
 def test_get_group(self):
     """
     Don't worry about using a "real" group: just make sure we
     get what was added!
     """
     add_group("Group name", "Test")
     grp = get_group("Group name")
     self.assertEqual(grp, "Test")
Exemple #15
0
def get_util(store):
    """
    Get utility depending on the store type.
    """
    if store.primary_group() == get_group(BIG_BOX):
        return calc_util(store)
    else:
        return calc_util(store) + get_env_attr("mp_pref")
Exemple #16
0
def height_rpt(env, **kwargs):
    natural = get_group(NATURAL)
    geneng = get_group(GENENG)
    num_natural = len(natural)
    num_geneng = len(geneng)
    total_nat_height = 0
    # total_gen_height = 0
    for agent_nm in natural:
        agent = get_registration(agent_nm)
        total_nat_height += agent["height"]
    user_tell("\n**************")
    user_tell("Height Report:")
    user_tell("**************")
    user_tell(f"For the {num_natural} people in the natural group,")
    user_tell("we have an average height of: " +
              f"{total_nat_height / num_natural}")
    user_tell(f"For the {num_geneng} people in the gen eng group,")
    user_tell("we have an average height of:")
Exemple #17
0
def distribute_coupons(agent, execution_key=CLI_EXEC_KEY):
    """
    Distribute coupons from central bank randomly to each babysitter.
    Coupons are gaussian distributed based on extra_coupons and extra_dev.
    """
    co_op_members = get_group(CO_OP_MEMBERS, execution_key=execution_key)
    for bbsit in co_op_members:
        co_op_members[bbsit]['coupons'] += int(
            gaussian(agent["extra_coupons"], agent["extra_dev"]))
Exemple #18
0
def populate_board_glider(width, height):
    b = get_group(BLACK)
    center = [width // 2, height // 2]
    agent_loc = [(center[0], center[1]), (center[0] - 1, center[1] + 1),
                 (center[0] + 1, center[1] + 1),
                 (center[0] + 1, center[1]), (center[0], center[1] - 1)]
    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #19
0
def populate_board_lightweight_spaceship(width,
                                         height,
                                         execution_key=CLI_EXEC_KEY):
    center = [width // 2, height // 2]
    agent_loc = get_agent_rules("spaceship", center)
    b = get_group(BLACK, execution_key)
    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #20
0
def get_color(group, execution_key=None):
    """
    Returns W or B, W for white and B for black
        when passed in a group.
    W and B are integer values:- 0 and 1, respectively.
    """
    if group == get_group(WHITE, execution_key):
        return W
    else:
        return B
Exemple #21
0
def populate_board_exploder(width, height):
    center = [width // 2, height // 2]
    agent_loc = [(center[0], center[1]), (center[0], center[1] - 4)]
    b = get_group(BLACK)
    for i in range(0, 5):
        agent_loc.append((center[0] - 2, center[1] - i))
        agent_loc.append((center[0] + 2, center[1] - i))
    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #22
0
def switch(agent_nm, grp1_nm, grp2_nm, execution_key=None):
    """
    Move agent from grp1 to grp2.
    We first must recover agent objects from the registry.
    """
    agent = get_registration(agent_nm, execution_key=execution_key)
    if agent is None:
        user_log_notif("In switch; could not find agent: " + str(agent))
    grp1 = get_group(grp1_nm, execution_key=execution_key)
    if grp1 is None:
        user_log_notif("In switch; could not find from group: " + str(grp1))
    grp2 = get_group(grp2_nm, execution_key=execution_key)
    if grp2 is None:
        user_log_notif("In switch; could not find to group: " + str(grp2))
    split_em = split(grp1, agent)
    joined_em = join(grp2, agent)
    if DEBUG and split_em and joined_em:
        user_log_notif("Switched agent " + str(agent) + " from grp " +
                       grp1_nm + "(id: " + str(id(grp1)) + ")" + " to grp " +
                       grp2_nm + "(id: " + str(id(grp2)) + ")")
Exemple #23
0
def wolf_action(agent, **kwargs):
    if agent.duration <= 0 or agent.duration == agent[TIME_TO_EMIGRATE]:
        return rem_agent(agent, **kwargs)
    else:
        execution_key = get_exec_key(kwargs=kwargs)
        prey = get_prey(agent,
                        get_group(SHEEP_GROUP, execution_key=execution_key),
                        **kwargs)
        if prey is not None:
            eat(agent, prey, **kwargs)
        agent[TIME_TO_REPR] -= 1
        # wolves can have a litter between 4 & 6 pups
        num_of_babies = randint(4, 6)
        while num_of_babies > 0:
            reproduce(agent, create_wolf,
                      get_group(WOLF_GROUP, execution_key=execution_key),
                      **kwargs)
            num_of_babies -= 1
        agent.duration -= 1
        return False
Exemple #24
0
def populate_board_exploder(width, height, execution_key=CLI_EXEC_KEY):
    center = [width // 2, height // 2]
    agent_loc = get_agent_rules("exploder", center)
    b = get_group(BLACK, execution_key)
    for i in range(0, 5):
        agent_loc.append((center[X] - 2, center[Y] - i))
        agent_loc.append((center[X] + 2, center[Y] - i))
    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #25
0
def coop_action(coop_env, **kwargs):
    execution_key = get_exec_key(kwargs=kwargs)
    sitters = get_sitters(get_group(CO_OP_MEMBERS,
                                    execution_key=execution_key))
    going_out = get_going_out(
        get_group(CO_OP_MEMBERS, execution_key=execution_key))

    exchanges = min(len(sitters), len(going_out))
    sitter_agents = [agent for agent in sitters]
    going_out_agents = [agent for agent in going_out]

    for i in range(exchanges):
        sitter, outer = sitter_agents[i], going_out_agents[i]
        sitters[sitter]['coupons'] += 1
        going_out[outer]['coupons'] -= 1

    set_env_attr("last_per_exchg", exchanges, execution_key=execution_key)
    set_env_attr("last_per_unemp",
                 max(len(sitters), len(going_out)) - exchanges,
                 execution_key=execution_key)
    return True
Exemple #26
0
def populate_board_tumbler(width, height, execution_key=CLI_EXEC_KEY):
    """
    Tumbler is a classic GOL pattern.
    But this must be recoded to eliminate all the hard-coding of positions.
    """
    center = [width // 2, height // 2]
    b = get_group(BLACK, execution_key)
    agent_loc = get_agent_rules("tumbler", center)
    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #27
0
def populate_board_n_vertical_row(width, height, n=10):
    center = [width // 2, height // 2]
    agent_loc = []
    top = (n // 2) + (n % 2)
    bottom = n // 2
    b = get_group(BLACK)
    for t in range(top):
        agent_loc.append((center[0], center[1] + t))
    for b in range(1, bottom):
        agent_loc.append((center[0], center[1] - b))
    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #28
0
def populate_board_n_horizontal_row(width, height, n=10):
    center = [width // 2, height // 2]
    agent_loc = []
    right = (n // 2) + (n % 2)
    left = n // 2
    b = get_group(BLACK)
    for r in range(right):
        agent_loc.append((center[0] + r, center[1]))
    for le in range(1, left):
        agent_loc.append((center[0] - le, center[1]))
    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #29
0
def populate_board_lightweight_spaceship(width, height):
    center = [width // 2, height // 2]
    agent_loc = [(center[0], center[1]), (center[0] - 1, center[1]),
                 (center[0] - 2, center[1]),
                 (center[0] - 3, center[1]), (center[0], center[1] - 1),
                 (center[0], center[1] - 2),
                 (center[0] - 4, center[1] - 1),
                 (center[0] - 1, center[1] - 3),
                 (center[0] - 4, center[1] - 3)]
    b = get_group(BLACK)
    for loc in agent_loc:
        agent = create_game_cell(loc[0], loc[1])
        b += agent
        get_env().place_member(agent, xy=loc)
Exemple #30
0
def get_prey(agent, sheep, **kwargs):
    """
        Wolves eat active sheep from the neighbourhood
    """
    exec_key = get_exec_key(kwargs=kwargs)
    if len(get_group(SHEEP_GROUP, exec_key)) <= 0:
        raise NoSheep("All out of sheep!")

    return get_env(execution_key=exec_key) \
        .get_neighbor_of_groupX(agent,
                                SHEEP_GROUP,
                                hood_size=get_env_attr(
                                    "prey_dist",
                                    execution_key=exec_key))