Пример #1
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
Пример #2
0
def create_non_drinker(name, i, **kwargs):
    """
    Create an agent.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    return Agent(name + str(i), action=drinker_action,
                 attrs={MOTIV: DEF_MOTIV}, execution_key=execution_key)
Пример #3
0
def create_resident(name, i, group=BLUE, **kwargs):
    """
    Creates agent of specified color type
    """
    execution_key = get_exec_key(kwargs=kwargs)
    if group == BLUE:
        grp_idx = BLUE_GRP_IDX
        mean_tol = get_prop('mean_tol',
                            DEF_TOLERANCE,
                            execution_key=execution_key)
    else:
        grp_idx = RED_GRP_IDX
        mean_tol = -get_prop(
            'mean_tol', DEF_TOLERANCE, execution_key=execution_key)
    dev = get_prop('deviation', DEF_SIGMA, execution_key=execution_key)
    this_tolerance = get_tolerance(mean_tol, dev)
    return Agent(name + str(i),
                 action=seg_agent_action,
                 attrs={
                     TOLERANCE:
                     this_tolerance,
                     GRP_INDEX:
                     grp_idx,
                     "hood_changed":
                     True,
                     "just_moved":
                     False,
                     "hood_size":
                     get_prop('hood_size',
                              DEF_HOOD_SIZE,
                              execution_key=execution_key)
                 },
                 execution_key=execution_key)
Пример #4
0
def seek_a_trade(agent, comp=False, **kwargs):
    execution_key = get_exec_key(kwargs=kwargs)
    nearby_agent = get_env(
        execution_key=execution_key).get_closest_agent(agent)
    if nearby_agent is not None:
        negotiate(agent, nearby_agent, comp)
        return MOVE
Пример #5
0
def tree_action(agent, **kwargs):
    """
    This is what trees do each turn in the forest.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    old_state = agent["state"]
    if is_healthy(agent):
        if exists_neighbor(agent, pred=is_on_fire,
                           execution_key=execution_key):
            if DEBUG2:
                user_log_notif("Setting nearby tree on fire!")
            agent["state"] = NF
    # if we didn't catch on fire above, do probabilistic transition:
    if old_state == agent["state"]:
        # we gotta do these str/int shenanigans with state cause
        # JSON only allows strings as dict keys
        agent["state"] = \
            str(prob_state_trans(int(old_state),
                                 get_env_attr(TRANS_TABLE,
                                              execution_key=execution_key)))
        if DEBUG2:
            if agent["state"] == NF:
                user_log_notif("Tree spontaneously catching fire.")

    if old_state != agent["state"]:
        # if we entered a new state, then...
        env = get_env(execution_key=execution_key)
        group_map = get_env_attr(GROUP_MAP, execution_key=execution_key)
        if group_map is None:
            user_log_err("group_map is None!")
            return True
        agent.has_acted = True
        env.add_switch(agent, group_map[old_state], group_map[agent["state"]])
    return True
Пример #6
0
def neighbor_ratio(agent, pred_one, pred_two=None, size=1, region_type=None,
                   **kwargs):
    execution_key = get_exec_key(kwargs=kwargs)
    return get_env(execution_key=execution_key) \
        .neighbor_ratio(agent, pred_one,
                        pred_two=pred_two,
                        size=size,
                        region_type=region_type)
Пример #7
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)
Пример #8
0
def record_exchanges(pop_hist, **kwargs):
    """
    This is our hook into the env to record the number of exchanges each
    period.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    pop_hist.record_pop(
        "Exchanges", get_env_attr("last_per_exchg",
                                  execution_key=execution_key))
Пример #9
0
def sell(agent, **kwargs):
    execution_key = get_exec_key(kwargs=kwargs)
    market_maker = get_env(execution_key=execution_key)[MARKET_MAKER]

    price = market_maker["asset_price"] * DEF_NUM_ASSET
    if agent["num_stock"] >= DEF_NUM_ASSET:
        market_maker["sell"] += 1
        agent["capital"] += price
        agent["num_stock"] -= DEF_NUM_ASSET
Пример #10
0
def is_isolated(agent, **kwargs):
    '''
    Checks if agent is maintaining distancing.
    '''
    execution_key = get_exec_key(kwargs=kwargs)
    return not exists_neighbor(agent,
                               size=get_prop('distancing', DEF_DISTANCING,
                                             execution_key=execution_key),
                               execution_key=execution_key)
Пример #11
0
def get_num_of_neighbors(agent, exclude_self=False, pred=None, size=1,
                         region_type=None, **kwargs):
    exec_key = get_exec_key(kwargs=kwargs)
    return get_env(execution_key=exec_key) \
        .get_num_of_neighbors(agent,
                              exclude_self=True,
                              pred=None,
                              size=size,
                              region_type=region_type)
Пример #12
0
def exists_neighbor(agent, pred=None, exclude_self=True, size=1,
                    region_type=None, **kwargs):
    execution_key = get_exec_key(kwargs=kwargs)
    return get_env(execution_key=execution_key) \
        .exists_neighbor(agent,
                         pred=pred,
                         exclude_self=exclude_self,
                         size=size,
                         region_type=region_type)
Пример #13
0
def create_tsetter(name, i, props=None, color=RED_SIN, **kwargs):
    """
    Create a trendsetter: all RED to start.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    return Agent(TSETTER_PRENM + str(i),
                 action=tsetter_action,
                 attrs={COLOR_PREF: color,
                        DISPLAY_COLOR: color}, execution_key=execution_key)
Пример #14
0
def reproduce(agent, create_func, group, **kwargs):
    """
    Agents reproduce when TIME_TO_REPR reaches 0
    """
    execution_key = get_exec_key(kwargs=kwargs)
    if DEBUG:
        user_debug(str(agent.name) + " is having a baby!")
    get_env(execution_key=execution_key).add_child(group)
    agent[TIME_TO_REPR] = agent["orig_repr_time"]
Пример #15
0
def create_follower(name, i, props=None, color=BLUE_SIN, **kwargs):
    """
    Create a follower: all BLUE to start.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    return Agent(FOLLOWER_PRENM + str(i),
                 action=follower_action,
                 attrs={COLOR_PREF: color,
                        DISPLAY_COLOR: color}, execution_key=execution_key)
Пример #16
0
def value_investor_action(agent, **kwargs):
    # Determine if value investors should buy or sell the stock
    execution_key = get_exec_key(kwargs=kwargs)
    market_maker = get_env(execution_key=execution_key)[MARKET_MAKER]

    if market_maker["asset_price"] >= agent["high_price"]:
        sell(agent, **kwargs)
    elif market_maker["asset_price"] <= agent["low_price"]:
        buy(agent, **kwargs)

    return True
Пример #17
0
def social_distancing(agent, **kwargs):
    """
    This function sets a new angle for the agent's movement.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    curr_region = CircularRegion(get_env(execution_key=execution_key),
                                 agent.get_pos(), DEF_PERSON_MOVE * 2)
    agents_in_range = curr_region.get_agents(
        get_env(execution_key=execution_key), pred=None)
    new_angle = get_move_angle(agent, agents_in_range)
    agent["angle"] = new_angle
Пример #18
0
def create_resident(name, i, state=CALM, **kwargs):
    """
    Creates agent of specified color type
    """
    execution_key = get_exec_key(kwargs=kwargs)
    return Agent(name + str(i),
                 action=panic_agent_action,
                 attrs={"state": state,
                        "hood_size": get_prop('hood_size',
                                              DEF_HOOD_SIZE,
                                              execution_key=execution_key),
                        "save_neighbours": True}, execution_key=execution_key)
Пример #19
0
def create_nutrient(name, i, **kwargs):
    """
    Create a nutrient.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    nutrient = Agent(name + str(i),
                     action=nutrient_action,
                     execution_key=execution_key)
    nutrient["max_move"] = get_prop("nutrient_move",
                                    DEF_NUTRIENT_MOVE,
                                    execution_key=execution_key)
    return nutrient
Пример #20
0
def create_toxin(name, i, **kwargs):
    """
    Create a toxin.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    toxin = Agent(name + str(i),
                  action=toxin_action,
                  execution_key=execution_key)
    toxin["max_move"] = get_prop("toxin_move",
                                 DEF_TOXIN_MOVE,
                                 execution_key=execution_key)
    return toxin
Пример #21
0
def trend_follower_action(agent, **kwargs):
    # Determine if trend followers should buy
    # or sell the stock
    execution_key = get_exec_key(kwargs=kwargs)
    market_maker = get_env(execution_key=execution_key)[MARKET_MAKER]

    if trend_direction(agent, market_maker["asset_price"],
                       market_maker["price_hist"]) == 1:
        buy(agent, **kwargs)
    else:
        sell(agent, **kwargs)

    return True
Пример #22
0
def create_market_maker(name, **kwargs):
    """
    Create a market maker.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    market_maker = Agent(name,
                         action=market_maker_action,
                         execution_key=execution_key)
    market_maker["buy"] = 0
    market_maker["sell"] = 0
    market_maker["asset_price"] = DEF_PRICE
    market_maker["prev_asset_price"] = DEF_PRICE
    market_maker["price_hist"] = [DEF_PRICE]
    return market_maker
Пример #23
0
def plant_tree(name, i, state=HE, **kwargs):
    """
    Plant a new tree!
    By default, they start out healthy.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    name = TREE_PREFIX
    return Agent(name + str(i),
                 action=tree_action,
                 attrs={
                     "state": state,
                     "save_neighbors": True
                 },
                 execution_key=execution_key)
Пример #24
0
def create_sheep(name, i, **kwargs):
    """
    Method to create sheep
    """
    exec_key = get_exec_key(kwargs=kwargs)
    time_to_repro = randint(1, SHEEP_REPRO_PERIOD)
    return Agent(AGT_SHEEP_NAME + str(i),
                 duration=SHEEP_LIFESPAN,
                 action=sheep_action,
                 attrs={
                     TIME_TO_REPR: time_to_repro,
                     "orig_repr_time": SHEEP_REPRO_PERIOD
                 },
                 execution_key=exec_key)
Пример #25
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))
Пример #26
0
def create_trader(name, i, **kwargs):
    execution_key = get_exec_key(kwargs=kwargs)
    return Agent(name + str(i),
                 action=seek_a_trade_w_comp,
                 attrs={
                     "goods": {
                         "truck": {
                             AMT_AVAIL: 0,
                             UTIL_FUNC: "steep_util_func",
                             "incr": 0,
                             COMPLEMENTS: ["fuel", "land"]
                         },
                         "penguin": {
                             AMT_AVAIL: 0,
                             UTIL_FUNC: "steep_util_func",
                             "incr": 0,
                             COMPLEMENTS: ["pet_food", "meat"]
                         },
                         "pet_food": {
                             AMT_AVAIL: 0,
                             UTIL_FUNC: "steep_util_func",
                             "incr": 0,
                             COMPLEMENTS: ["penguin", "meat"]
                         },
                         "fuel": {
                             AMT_AVAIL: 0,
                             UTIL_FUNC: "steep_util_func",
                             "incr": 0,
                             COMPLEMENTS: ["truck", "land"]
                         },
                         "land": {
                             AMT_AVAIL: 0,
                             UTIL_FUNC: "steep_util_func",
                             "incr": 0,
                             COMPLEMENTS: ["truck", "fuel"]
                         },
                         "meat": {
                             AMT_AVAIL: 0,
                             UTIL_FUNC: "steep_util_func",
                             "incr": 0,
                             COMPLEMENTS: ["penguin", "pet_food"]
                         }
                     },
                     "graph": create_graph(),
                     "util": 0,
                     "pre_trade_util": 0,
                     "trades_with": "trader"
                 },
                 execution_key=execution_key)
Пример #27
0
 def __init__(self, space=None, center=None, radius=None, agents_move=True,
              **kwargs):
     self.execution_key = get_exec_key(kwargs)
     if (space is None):
         space = get_env(execution_key=self.execution_key)
     self.space = space
     self.center = center
     self.radius = radius
     self.name = "Circle"
     self.agents_move = agents_move
     self.my_sub_regs = []
     if self.agents_move:
         self.my_agents = []
     else:
         self.my_agents = self._load_agents()
Пример #28
0
def create_wolf(name, i, **kwargs):
    """
    Method to create wolf
    """
    execution_key = get_exec_key(kwargs=kwargs)
    time_to_repro = randint(1, WOLF_REPRO_PERIOD)

    return Agent(AGT_WOLF_NAME + str(i),
                 duration=WOLF_LIFESPAN,
                 action=wolf_action,
                 attrs={
                     TIME_TO_REPR: time_to_repro,
                     "orig_repr_time": WOLF_REPRO_PERIOD
                 },
                 execution_key=execution_key)
Пример #29
0
def create_bacterium(name, i, **kwargs):
    """
    Create a baterium.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    bacterium = Agent(name + str(i),
                      action=bacterium_action,
                      execution_key=execution_key)
    bacterium["prev_toxicity"] = None
    bacterium["prev_nutricity"] = None
    bacterium["angle"] = None
    bacterium["max_move"] = get_prop("bacterium_move",
                                     DEF_BACTERIUM_MOVE,
                                     execution_key=execution_key)
    return bacterium
Пример #30
0
def seg_agent_action(agent, **kwargs):
    """
    If the agent is surrounded by more "others" than it
    is comfortable with, the agent will move.
    The whole idea here is to count those in other group
    and those in my group, and get the ratio.
    """
    execution_key = get_exec_key(kwargs=kwargs)
    agent_group = agent.group_name()
    ratio_num = neighbor_ratio(agent,
                               lambda agent: agent.group_name() == agent_group,
                               size=agent['hood_size'],
                               execution_key=execution_key)
    if DEBUG2:
        print("ratio test" + str(ratio_num))
    return env_favorable(ratio_num, agent[TOLERANCE])