def setUp(self): self.model = Model(model_nm="Test model", grp_struct=DEF_GRP_STRUCT) self.exec_key = self.model.exec_key self.agent = Agent("Test agent", exec_key=self.model.exec_key) self.agent2 = Agent("Test agent 2", exec_key=self.model.exec_key) self.blue_grp = get_agent(BLUE_GRP_NM, self.exec_key) self.red_grp = get_agent(RED_GRP_NM, self.exec_key)
def setUp(self): self.exec_key = get_exec_key() self.env = Env("test_env", exec_key=self.exec_key) (self.space, self.newton) = create_space(self.exec_key) self.test_agent = Agent("test agent", exec_key=self.exec_key) self.test_agent2 = Agent("test agent 2", exec_key=self.exec_key) self.test_agent3 = Agent("test agent 3", exec_key=self.exec_key) self.test_agent4 = Agent("test agent 4", exec_key=self.exec_key)
def setUp(self): self.ff = ForestFire(MODEL_NAME, grp_struct=ff_grps) ''' self.htree = plant_tree("htree", 1, exec_key=self.ff.exec_key) self.oftree = plant_tree("oftree", 1, state=OF, exec_key=self.ff.exec_key) ''' self.htree = Agent(name="htree", exec_key=self.ff.exec_key) self.oftree = Agent(name="oftree", exec_key=self.ff.exec_key)
def test_should_only_pickle_once(self, dump, load): agent1 = Agent("test_agent1", action=self.agent_action, exec_key=self.exec_key) agent2 = Agent("test_agent2", action=self.agent_action, exec_key=self.exec_key) registry.save_reg(self.exec_key) self.assertTrue(registry[self.exec_key]['functions'] is not None) pickle_files = list( filter(lambda file: 'agent-agent_action.pkl' in file, [value for value in registry[self.exec_key] ['functions'].values()])) self.assertTrue(len(pickle_files) != 0) self.assertTrue(len(pickle_files) == 1)
def create_littlewood(): return Agent("Littlewood", exec_key=exec_key, attrs={ "friend": 141.0, "number": 1729.0 })
def create_ramsey(): return Agent("Ramsey", exec_key=exec_key, attrs={ "friend": 282.9, "number": 3.14 })
def __json_to_object(self, serial_obj, exec_key): """ Takes a serial JSON object back into a live Python object. """ restored_obj = dict() restored_groups = [] model_deserialized = False for obj_name in serial_obj: should_restore_object = isinstance(serial_obj[obj_name], dict) and "type" in serial_obj[ obj_name] if should_restore_object: if serial_obj[obj_name]["type"] == "TestUser": restored_obj[obj_name] = TermUser(name=obj_name, serial_obj=serial_obj[ obj_name], exec_key=exec_key) if serial_obj[obj_name]["type"] == "APIUser": restored_obj[obj_name] = APIUser(name=obj_name, serial_obj=serial_obj[ obj_name], exec_key=exec_key) if serial_obj[obj_name]["type"] == "Agent": restored_obj[obj_name] = Agent(name=obj_name, serial_obj=serial_obj[ obj_name], exec_key=exec_key) elif serial_obj[obj_name]["type"] == "Model": from lib.model import Model print(f'restoring model for key {exec_key}') restored_obj[obj_name] = Model(exec_key=exec_key, serial_obj=serial_obj[ obj_name]) model_deserialized = True elif serial_obj[obj_name]["type"] == "Group": from lib.group import Group restored_obj[obj_name] = Group(exec_key=exec_key, serial_obj=serial_obj[ obj_name], name=serial_obj[obj_name][ 'name']) restored_groups.append(restored_obj[obj_name]) elif serial_obj[obj_name]["type"] == "Env": restored_obj[obj_name] = Env(exec_key=exec_key, serial_obj=serial_obj[ obj_name], name=serial_obj[obj_name][ 'name']) else: restored_obj[obj_name] = serial_obj[obj_name] self.registries[exec_key][obj_name] = restored_obj[obj_name] if model_deserialized: restored_obj['model'].groups = restored_groups restored_obj['model'].env = restored_obj['env'] self.registries[exec_key]['model'] = restored_obj['model'] return restored_obj
def exec_trade(): """ 本番トレード実行 """ # トレード時間のみトレードを実行 now = datetime.now() judge_trade_time = JudgeTradeTime(date_time=now) if judge_trade_time.is_trade_time(): # webから現在価格を取得(ついでにDBに格納) price = ScrapeRate().get_rate() # agent, chart_monitorを初期化 chart_monitor = ChartMonitor() chart_monitor.get_saved_data() # 最新のデータで更新 agent = Agent(price) agent.get_saved_data() # 最新のデータで更新 # 取引の実行 date_time = datetime.now() if chart_monitor.identify_chart(price, date_time): has_trade = agent.monitor_transition( chart_monitor.current_rate, chart_monitor.prev_top, chart_monitor.prev_bottom, chart_monitor.has_over_top, chart_monitor.has_bellow_bottom) # 取引記録をデータベースに保存 agent.save_log(date_time=chart_monitor.datetime, has_trade=has_trade) chart_monitor.save_log()
def create_other_leibniz(): return Agent("Leibniz", attrs={ "place": 1.0, "time": LEIBBYEAR }, action=leib_action, exec_key=exec_key, duration=20)
def create_wine(name, i, action=None, **kwargs): return Agent(WINE_AGENT, action=seek_a_trade, attrs={ GOODS: wine_goods, UTIL: 0, PRE_TRADE_UTIL: 0, TRADE_WITH: "Cheese holders" }, **kwargs)
def create_tsetter(name, i, props=None, color=RED_SIN, action=None, exec_key=0): """ Create a trendsetter: all RED to start. """ return Agent(TSETTER_PRENM + str(i), action=action, exec_key=exec_key, attrs={COLOR_PREF: color, DISPLAY_COLOR: color})
def create_follower(name, i, props=None, color=BLUE_SIN, action=None, exec_key=0): """ Create a follower: all BLUE to start. """ return Agent(FOLLOWER_PRENM + str(i), action=action, exec_key=exec_key, attrs={COLOR_PREF: color, DISPLAY_COLOR: color})
def create_cheese(name, i, action=None, **kwargs): return Agent(CHEESE_AGENT, action=seek_a_trade, attrs={ GOODS: cheese_goods, UTIL: 0, PRE_TRADE_UTIL: 0, TRADE_WITH: "Wine holders" }, **kwargs)
def create_newton(): return Agent("Newton", attrs={ "place": 0.0, "time": 1658.0, "achieve": 43.9 }, action=newt_action, exec_key=exec_key, duration=30)
def create_bb(name, **kwargs): """ Create a big box store. """ return Agent(name=name, attrs={ "expense": bb_expense, "capital": bb_capital }, action=bb_action)
def create_bb(name, mbr_id, bb_capital, action=None, **kwargs): """ Create a big box store. """ return Agent(name=name + str(mbr_id), action=retailer_action, attrs={ EXPENSE: bb_expense, CAPITAL: bb_capital }, **kwargs)
def create_mp(store_grp, i, **kwargs): """ Create a mom and pop store. """ return Agent(name=str(store_grp) + " " + str(i), attrs={ "expense": mp_stores[store_grp]["per_expense"], "capital": mp_stores[store_grp]["init_capital"] }, action=mp_action, **kwargs)
def place_agent(agent, state=CM, **kwargs): """ Place a new agent. By default, they start out calm. """ name = AGENT_PREFIX if(state == CM): agent = Agent(name, action=agent_action, attrs={"state": state, "save_neighbors": True}) return agent agent = Agent(name, action=agent_action, attrs={"state": state, "save_neighbors": True}) for x in range(grid_width): for y in range(grid_height): dist = random.random() if per_panic > dist: agent = Agent(name=("(%d,%d)" % (x, y)), action=agent_action, attrs={"state": PN, "save_neighbors": True}, execution_key=execution_key) loc = eval(agent.name) panic += agent get_env().place_member(agent, xy=loc) # place_agent(agent, state=PN) else: agent = Agent(name=("(%d,%d)" % (x, y)), action=agent_action, attrs={"state": CM, "save_neighbors": True}, execution_key=execution_key) loc = eval(agent.name) calm += agent get_env().place_member(agent, xy=loc) # place_agent(agent) return agent
def create_drinker(name, i, exec_key=None, action=drinker_action): """ Create a drinker, who starts with a random motivation. """ rand_motive = random.random() recent_crowds = [HALF_FULL] * mem_capacity return Agent(name + str(i), attrs={ MOTIV: rand_motive, MEMORY: recent_crowds }, action=action, exec_key=exec_key)
def create_consumer(name, i, action=None, **kwargs): """ Create consumers """ spending_power = random.randint(MIN_CONSUMER_SPENDING, MAX_CONSUMER_SPENDING) return Agent(name + str(i), action=consumer_action, attrs={ SPENDING_POWER: spending_power, LAST_UTIL: 0.0, ITEM_NEEDED: get_rand_good() }, **kwargs)
def create_trader(name, i, action=None, **kwargs): """ A func to create a trader. """ return Agent( name + str(i), action=action, # goods will now be a dictionary like: # goods["cow"] = [cowA, cowB, cowC, etc.] attrs={ GOODS: {}, "util": 0, "pre_trade_util": 0 }, **kwargs)
def create_consumer(name, i, props=None, **kwargs): """ Create consumers """ spending_power = random.randint(MIN_CONSUMER_SPENDING, MAX_CONSUMER_SPENDING) consumer_books = { "spending power": spending_power, "last util": 0.0, "item needed": get_rand_good() } return Agent(name + str(i), attrs=consumer_books, action=consumer_action, **kwargs)
def create_mp(store_grp, i, action=None, **kwargs): """ Create a mom and pop store. """ store_num = i % len(mp_stores) store = mp_stores[mp_stores_type[store_num]] return Agent(name=str(store_grp) + " " + str(i), action=retailer_action, attrs={ EXPENSE: store[PER_EXPENSE], CAPITAL: store[INIT_CAPITAL], GOODS_SOLD: cons_goods[store_num], UTIL_ADJ: store[UTIL_ADJ] }, **kwargs)
def create_entr(name, i, action=None, **kwargs): """ Create an agent. """ # TO BE FIXED starting_cash = DEF_ENTR_CASH resources = copy.deepcopy(DEF_CAP_WANTED) return Agent(name + str(i), action=entr_action, attrs={ "cash": starting_cash, "wants": resources, "have": {} }, **kwargs)
def create_rholder(name, i, action=None, **kwargs): """ Create an agent. """ # TO BE FIXED # k_price = DEF_K_PRICE resources = copy.deepcopy(DEF_CAP_WANTED) # num_resources = len(resources) price_list = copy.deepcopy(DEF_EACH_CAP_PRICE) starting_cash = DEF_RHOLDER_CASH return Agent(name + str(i), action=rholder_action, attrs={ "cash": starting_cash, "resources": resources, "price": price_list }, **kwargs)
def from_json(self, serial_obj): # from registry.run_dict import mbr_creator_dict super().from_json(serial_obj) self.color = serial_obj["color"] self.num_mbrs_ever = serial_obj["num_mbrs_ever"] # we loop through the members of this group for nm in serial_obj["members"]: member = serial_obj["members"][nm] if member["type"] == "Agent": self.members[nm] = Agent(name=nm, serial_obj=member, exec_key=member['exec_key']) elif member["type"] == "Group": self.members[nm] = Group(name=nm, serial_obj=member, exec_key=member['exec_key']) mem_create_nm = serial_obj["mbr_creator"] self.mbr_creator = mem_create_nm
def from_json(self, serial_obj): """ Turn a serilaized JSON stream back into a group: """ super().from_json(serial_obj) self.mbr_creator = self._restore_func(serial_obj, "mbr_creator") self.color = serial_obj["color"] self.num_mbrs_ever = serial_obj["num_mbrs_ever"] # we loop through the members of this group for nm in serial_obj["members"]: member = serial_obj["members"][nm] if member["type"] == "Agent": self.members[nm] = Agent(name=nm, serial_obj=member, exec_key=member['exec_key']) elif member["type"] == "Group": self.members[nm] = Group(name=nm, serial_obj=member, exec_key=member['exec_key'])
def create_ramanujan(): return Agent("Ramanujan", exec_key=exec_key, duration=5, action=ram_action)
def create_hardy(): return Agent("Hardy", attrs={ANM: AGE}, exec_key=exec_key, duration=10)
from lib.agent import Agent from lib.stats import Statistics from lib.snake import Environment import pygame from lib.config import EPISODE """ Train the agent and neural network for a number of episodes. """ agent = Agent() stat = Statistics() episode = 0 while True: if episode > EPISODE: break episode += 1 print(f'Episode:{episode}') # pylint: disable=no-member pygame.init() env = Environment(stat, episode, agent, True, False) env.run() env.agent.model.save_weights('weights/weights.hdf5') del env pygame.quit()