def logger_setup(self, message: Message): self.log_actor = self.createActor( "log_actor.LogActor") #, globalName="log_actor") log_basis = {} log_basis["message_type"] = "setup" # setting short name for environment #self.short_name = message.get_payload()["short_name"] logging.info("ENVIRONMENT should have : " + str(message.get_payload())) short_name = message.get_payload()["short_name"] # self.short_name = "environment" # if "address_book" not in dir(self): # self.address_book = AddressBook(self) # logging.info("ENVIRONMENT short name is : " + str(self.short_name)) log_basis["simulation_run_id"] = message.get_payload( )["simulation_run_id"] log_basis["simulation_id"] = message.get_payload()["simulation_id"] log_basis["run_number"] = message.get_payload( )["simulation_run_number"] log_basis["run_code"] = message.get_payload()["run_code"] log_basis["status"] = message.get_payload()["status"] log_basis["mes_directory"] = message.get_payload()["mes_directory"] log_basis["data_logging"] = message.get_payload()["data_logging"] log_basis["simulation_configuration"] = message.get_payload( )["simulation_configuration"] self.send(self.log_actor, log_basis)
def agent_action_forward(self, message: Message): subject_id = message.get_payload()["subject_id"] subject_agent_map = self.subject_map[subject_id] new_message = Message() new_message.set_directive(message.get_payload()["action"]) new_message.set_sender(self.myAddress) new_message.set_payload(message.get_payload()) self.send(subject_agent_map, new_message)
def setup_agent_requests(self, message: Message): if "address_book" not in dir(self): self.address_book = AddressBook(self) if "agents" not in dir(self): self.agents = [] self.agent_addresses = [] # ensure that the actor system and institution are running... #message = MessageSpace.create_agent(agent_class) num_agents = message.get_payload().number agent_class = message.get_payload().source_class # need to check source hash for simulation source_hash = message.get_payload().source_hash # memory = False # agent_memory = None # if "agent_memory" in message.get_payload().keys(): # memory = True # agent_memory = message.get_payload()["agent_memory"] if "subjects" in dir(self): self.subject_map = {} for i in range(num_agents): agent_number = i + 1 new_agent = self.createActor(agent_class, sourceHash=source_hash) self.send(new_agent, agent_class + " " + str(agent_number)) self.agent_addresses.append(new_agent) self.agents.append([new_agent, agent_class]) agent_info = {} agent_info["address_type"] = "agent" agent_info["address"] = new_agent agent_info["component_class"] = agent_class agent_info["component_number"] = agent_number agent_info["short_name"] = agent_class + " " + str(agent_number) self.address_book.add_address(agent_info["short_name"], agent_info) new_message = Message() #new_message.set_sender(self.myAddress) new_message.set_directive("simulation_properties") new_message.set_sender(self.myAddress) payload = {} #if "mtree_properties" not in dir(self): payload["log_actor"] = self.log_actor #payload["dispatcher"] = self.createActor("Dispatcher", globalName="dispatcher") payload["properties"] = self.mtree_properties payload["agent_information"] = agent_info if "subjects" in dir(self): payload["subject_id"] = self.subjects[i]["subject_id"] self.subject_map[payload["subject_id"]] = new_agent # if memory: # payload["agent_memory"] = agent_memory new_message.set_payload(payload) self.send(new_agent, new_message)
def auction_result(self, message: Message): #logging.log(EXPERIMENT, "Agent received item for bid %s", message.get_payload()) if message.get_payload()["status"] == "winner": if "win_rate" not in self.agent_memory.keys(): self.agent_memory["win_rate"] = 0 self.agent_memory["win_rate"] = self.agent_memory["win_rate"] + 1 elif message.get_payload()["status"] == "loser": if "loss_rate" not in self.agent_memory.keys(): self.agent_memory["loss_rate"] = 0 self.agent_memory["loss_rate"] = self.agent_memory["loss_rate"] + 1
def new_season(self, message: Message): """ Receives information about the start of the new epidemic season, whenever a new season starts. """ if self.debug: logging.log(EXPERIMENT, f'agent {self.unique_id} entered new_season') choice = message.get_payload()["choice"] seed = message.get_payload()["seed"] new_season_state = message.get_payload()["new_season_state"] prob_of_infection = message.get_payload()["prob_of_infection"] #agents who were vaccinated in the previous season should remain vaccinated if self.current_state == 'V' and new_season_state != 'V': logging.log( EXPERIMENT, f"ERROR: Agent {self.unique_id} somehow lost vaccination at the beginning of a new season" ) #update your current state for the new season self.current_state = new_season_state #if the agent was offered a choice, decide whether or not to get vaccinated if choice: if prob_of_infection >= ( 1 / self.cost_of_infection ): #get vaccinated if the probability of infection is high in your region self.current_state = 'V' else: #if the probability of infection is not so high, start the season susceptible self.current_state = 'S' #finally, consider whether this agent is a seed of the infection if seed: if self.current_state != 'V': #if a seed agent is not vaccinated, they start the season Infected self.current_state = 'In' if self.debug: logging.log( EXPERIMENT, f"Agent {self.unique_id} is facing a prob_of_infection of {prob_of_infection} " f"in hub {self.hub}, along with a cost_of_infection of {self.cost_of_infection}." ) #register with the insitution again. The institution will figure out whether/how the simulation should proceed self.start_registration() if self.debug: logging.log(EXPERIMENT, f'agent {self.unique_id} exited new_season')
def update_mes_status(self, message: Message = None): new_message = Message() new_message.set_sender(self.myAddress) new_message.set_directive("update_mes_status") payload = message.get_payload() new_message.set_payload(payload) self.send(self.log_actor, new_message)
def auction_result(self, message: Message): logging.log(EXPERIMENT, "Agent received item for bid %s", message.get_payload()) new_message = Message() # declare message new_message.set_sender(self.myAddress) # set the sender of message to this actor new_message.set_directive("register_collateral") new_message.set_payload({"bid": self.min_value}) self.send(self.collateral_institution, new_message) # receiver_of_message, message
def bid_at_price(self, message: Message): self.current_price = message.get_payload()["current_price"] self.institution = message.get_sender() self.log_data("Agent alerted that current price is " + str(self.current_price)) if self.current_price < self.max_bid: self.make_bid()
def start_auction(self, message: Message): if self.mtree_properties["num_auctions"] > 0: self.mtree_properties[ "num_auctions"] = self.mtree_properties["num_auctions"] - 1 print("INSTITUTION: Starting Auction") self.agents = message.get_payload()["agents"] self.bids = [] self.bids_outstanding = len(self.agents) self.item_for_auction = random.randint(self.min_item_value, self.max_item_value) for agent in self.agents: new_message = Message() # declare message new_message.set_sender( self.myAddress) # set the sender of message to this actor new_message.set_directive("item_for_bidding") new_message.set_payload({ "min_value": self.min_item_value, "max_value": self.max_item_value }) self.send(agent, new_message) # receiver_of_message, message else: print("AUCTIONS COMPLETED") new_message = Message() # declare message new_message.set_sender( self.myAddress) # set the sender of message to this actor new_message.set_directive("close_environment") self.send(self.environment, new_message) # receiver_of_message, message
def item_for_bidding(self, message: Message): self.min_value = message.get_payload()["min_value"] self.max_value = message.get_payload()["max_value"] self.institution = message.get_sender() logging.log(EXPERIMENT, "Agent received item for bid %s - %s", str(self.min_value), str(self.max_value)) self.make_bid()
def accept_bid(self, message: Message): bidder = message.get_sender() bid = message.get_payload()["bid"] self.bids.append((bid, bidder)) self.bids_outstanding -= 1 if self.bids_outstanding == 0: self.complete_auction()
def initialize_agents(self, message: Message): '''give each of the agents their attributes and sends the info to institution for data collecting''' # contains the theta and sd payload = message.get_payload() #self.theta = payload["theta"] #self.sd = payload["sd"] #make the message to send to each agent message = Message() message.set_sender(self) message.set_directive("initialize_agents") message.set_payload(payload) #send message to all agents for agent in self.agents: self.send(agent, message) #create message for the institution message = Message() message.set_sender(self) message.set_directive("theta_sd") message.set_payload(payload) #send the theta and delta to the institution for data collection for institution in self.institutions: self.send(institution, message)
def initialize_rows(self, message: Message): '''makes the rows of the choices as list of tuples''' payload = message.get_payload() #set the rewards reward_A_1 = payload["reward_A_1"] reward_A_2 = payload["reward_A_2"] reward_B_1 = payload["reward_B_1"] reward_B_2 = payload["reward_B_2"] num_rows = payload["num_rows"] # number of rows in the bundle # creates each row and append to bundle for i in range(1, num_rows + 1): optionA = ([((i / num_rows), reward_A_1), ((((num_rows - i) / num_rows)), reward_A_2), "A_%d" % i]) optionB = ([((i / num_rows), reward_B_1), ((((num_rows - i) / num_rows)), reward_B_2), "B_%d" % i]) self.bundle.append([optionA, optionB]) # append each row to the bundle self.experiment = payload["experiment"] self.total_experiments = payload["total_experiments"] self.run = payload["run"] self.total_runs = payload["total_runs"]
def start_auction(self, message: Message): if self.auctions > 0: self.auctions -= 1 self.agents = message.get_payload()["agents"] self.bids = [] self.starting_price = random.randint(self.min_item_value, self.max_item_value) self.alert_agents_of_price(self.starting_price)
def bid_for_item(self, message: Message): bidder = message.get_sender() bid = int(message.get_payload()["bid"]) if bid > self.last_bid: self.last_bid = bid self.last_bid_time = time.time() self.bids.append((bid, bidder)) self.alert_agents_of_price(self.last_bid)
def register_for_collateral(self, message: Message): self.agents = message.get_payload()["agents"] for agent in self.agents: new_message = Message() # declare message new_message.set_sender( self.myAddress) # set the sender of message to this actor new_message.set_directive("register_for_collateral") self.send(agent, new_message) # receiver_of_message, message
def init_agents(self, message: Message): """ Receives the initial state of the agent from the environment, either susceptible or infected. """ if self.debug: logging.log(EXPERIMENT, f'agent {self.unique_id} entered init_agents') #save the agent's current SIS state from the environment, plus the institution's address self.current_state = message.get_payload()["current_state"] self.hub = message.get_payload()["hub"] self.institution_address = message.get_payload()["institution_address"] self.environment_address = message.get_sender().myAddress #save data about the SEIR simulation self.number_of_agents = message.get_payload()["number_of_agents"] self.rate_of_infection_per_contact = message.get_payload( )["rate_of_infection_per_contact"] self.recovery_rate = message.get_payload()["recovery_rate"] self.incubation_period = message.get_payload()["incubation_period"] self.cost_of_infection = message.get_payload()["cost_of_infection"] #create a unique_id for this agent self.unique_id = 'A' + str(datetime.now()) + str( random.randrange(0, 100000000)) #register with the matching institution for the first time self.start_registration() if self.debug: logging.log(EXPERIMENT, f'agent {self.unique_id} exited init_agents')
def excepted_mes(self, message: Message): new_message = Message() new_message.set_sender(self.myAddress) new_message.set_directive("excepted_mes") try: new_message.set_payload(message.get_payload()) except: new_message.set_payload(message) self.send(self.dispatcher, new_message)
def notify(self, message: Message): """ In this method, the agent receives information about the previous round from the institution, and it keeps track of its own S/I status. """ if self.debug: logging.log(EXPERIMENT, f'agent {self.unique_id} entered notify') #keep count of how many time periods each agent has spent infected if self.current_state == 'In': self.time_infected += 1 #also check whether the agent randomly recovers (with probability equal to self.recovery_rate) recovery_lottery = random.random() if recovery_lottery <= self.recovery_rate: if self.debug: logging.log( EXPERIMENT, f"Agent {self.unique_id} has recovered after spending {self.time_infected} time periods infected!" ) self.current_state = 'R' elif self.current_state == 'Ex': self.time_exposed += 1 #check whether the agent will randomly transition from Exposed to Infected incubation_lottery = random.random() transition_rate = ( 1 / self.incubation_period ) #the probability of transition is 1/incubation_period if incubation_lottery <= transition_rate: if self.debug: logging.log( EXPERIMENT, f"Agent {self.unique_id} has become infectious after spending {self.time_exposed} time periods infected!" ) self.current_state = 'In' #learn from the institution whether this agent was exposed during the matching process exposed = message.get_payload()["exposed"] #TEST: only a Susceptible agent can be infected if (exposed == True) and (self.current_state != 'S'): self.error_log( f"A non-Susceptible agent has been exposed, current_state = {self.current_state}" ) #change the agent's current state to exposed before the next round if exposed == True: self.current_state = 'Ex' #register with the insitution again. The institution will figure out whether/how the simulation should proceed self.start_registration() if self.debug: logging.log(EXPERIMENT, f'agent {self.unique_id} exited notify')
def simulation_properties(self, message: Message): if "address_book" not in dir(self): self.address_book = AddressBook(self) self.log_actor = message.get_payload()["log_actor"] if "mtree_properties" not in dir(self): self.mtree_properties = {} if "properties" in message.get_payload().keys(): self.mtree_properties = message.get_payload()["properties"] self.simulation_id = message.get_payload()["simulation_id"] if "run_number" in message.get_payload().keys(): self.run_number = message.get_payload()["run_number"] if "institution_info" in message.get_payload().keys(): self.institution_info = message.get_payload()["institution_info"] self.short_name = message.get_payload( )["institution_info"]["short_name"] #self.log_actor = message.get_payload()["log_actor"] #self.dispatcher = message.get_payload()["dispatcher"] #self.dispatcher = self.createActor("Dispatcher", globalName="dispatcher") self.environment = message.get_payload()["environment"]
def initialize_boxes(self, message: Message): print("Initializing boxes inside environment") payload = message.get_payload() box_list = payload["box_list"] self.box_list = box_list print(self.box_list) print("Now sending box list to the institution for use") message = Message() message.set_directive("prepare_box_list") payload = {} payload["box_list"] = self.box_list # we will also send the agent list to the institution for it to keep track of payload["agent_list"] = self.agents message.set_payload(payload) self.send(self.institutions[0], message)
def start_auction(self, message: Message): if self.auctions > 0: self.auctions -= 1 print("INSTITUTION: Starting Auction") self.agents = message.get_payload()["agents"] self.bids = [] self.bids_outstanding = len(self.agents) self.item_for_auction = random.randint(self.min_item_value, self.max_item_value) for agent in self.agents: new_message = Message() # declare message new_message.set_sender( self.myAddress) # set the sender of message to this actor new_message.set_directive("item_for_bidding") new_message.set_payload({ "min_value": self.min_item_value, "max_value": self.max_item_value }) self.send(agent, new_message) # receiver_of_message, message
def simulation_properties(self, message: Message): self.dispatcher = message.get_sender() #self.log_actor = message.get_payload()["log_actor"] if "mtree_properties" not in dir(self): self.mtree_properties = {} self.mtree_properties = message.get_payload()["properties"] self.simulation_id = message.get_payload()["simulation_id"] self.simulation_run_id = message.get_payload()["simulation_run_id"] if "subjects" in message.get_payload().keys(): self.subjects = message.get_payload()["subjects"] logging.info("Subjects list available...") logging.info(self.subjects) # if "subjects" in message.get_payload()["properties"].keys(): # self.subjects = message.get_payload()["properties"]["subjects"] # logging.info("Subjects list available...") # logging.info(self.subjects) if "run_number" in message.get_payload().keys(): self.run_number = message.get_payload()["run_number"]
def address_book_update(self, message: Message): addresses = message.get_payload() self.address_book.merge_addresses(addresses)
def set_endowment(self, message: Message): self.endowment = message.get_payload()["endowment"]
def auction_result(self, message: Message): logging.log(EXPERIMENT, "Agent received item for bid %s", message.get_payload())
def init_institution(self, message: Message): """ Receives the simulation data from the environment. """ if self.debug: logging.log(EXPERIMENT, 'institution entered init_institution') #save data about the SEIR simulation self.number_of_agents = message.get_payload()["number_of_agents"] self.rate_of_infection_per_contact = message.get_payload( )["rate_of_infection_per_contact"] self.address_list = message.get_payload()["address_list"] self.recovery_rate = message.get_payload()["recovery_rate"] self.number_of_hubs = message.get_payload()["number_of_hubs"] self.degree_of_homophily = message.get_payload()["degree_of_homophily"] self.inst_unique_id = 'I' + str(datetime.now()) + str( random.randrange(0, 100000000)) self.hub_densities = message.get_payload()["hub_densities"] self.hub_sizes = message.get_payload()["hub_sizes"] self.probability_vacc_choice = message.get_payload( )["probability_vacc_choice"] self.number_of_seasons = message.get_payload()["number_of_seasons"] self.cost_of_infection = message.get_payload()["cost_of_infection"] self.incubation_period = message.get_payload()["incubation_period"] self.log_time_period_data = message.get_payload( )["log_time_period_data"] self.recovery_rate = message.get_payload()["recovery_rate"] #initialize the dictionary for storing hub data for i in range(self.number_of_hubs): self.dict_of_hubs[i] = {} self.dict_of_hubs[i]['agents'] = [] self.dict_of_hubs[i]['number_of_connections'] = self.hub_densities[ i] #initiaize the list of lists to store data for each season for i in range(self.number_of_seasons): self.time_period_data.append([]) if self.debug: logging.log(EXPERIMENT, 'institution exited init_institution')
def register(self, message: Message): """ Receives registration from each agent and compiles a list of registered agents. When the length of that list matches self.number_of_agents, start time_period 0. """ if self.debug: logging.log(EXPERIMENT, "institution entered register") #save the address, current_state, and group of the registering agent agent_address = message.get_sender().myAddress current_state = message.get_payload()["current_state"] agent_hub = message.get_payload()["hub"] #if this is the first agent to be registered in this time period, initialize a new dictionary if len(self.time_period_data[self.season]) == self.time_period: self.time_period_data[self.season].append({}) #add this agent to the record for the time period self.time_period_data[self.season][ self.time_period][f"{agent_address}"] = {} #start a record of all registered agents: self.registered_agents.append(agent_address) #add the agent to the list for its hub self.dict_of_hubs[agent_hub]['agents'].append(agent_address) if self.time_period == 0 and self.season == 0: #generate the agent's entry in the network structure dictionary self.network_structure[f"{agent_address}"] = {} self.network_structure[f"{agent_address}"]["hub"] = agent_hub self.network_structure[f"{agent_address}"]["neighbors"] = [] self.network_structure[f"{agent_address}"][ "number_of_connections"] = self.dict_of_hubs[agent_hub][ "number_of_connections"] if self.debug: logging.log( EXPERIMENT, f"INSTITUTION: registered agent = {agent_address} from hub = {agent_hub}" ) #we need to calculate the number of infected agents. When this number is 0, end this season. if current_state == 'In': self.number_of_infected += 1 #find out whether the agent is currently susceptible, exposed, infectious, or recovered self.time_period_data[self.season][self.time_period][ f"{agent_address}"]["starting_state"] = current_state #log the number of registered agents so far if self.debug: logging.log( EXPERIMENT, f"INSTITUTION: registered_agents = {len(self.registered_agents)}, number of agents = {self.number_of_agents}, number of infected = {self.number_of_infected}" ) #when the number of registered agents matches the total number of agents, start the simulation #also check that there are still any infected agents if len(self.registered_agents ) == self.number_of_agents and self.number_of_infected > 0: #in the first time_period of the first season, generate a random network structure if self.time_period == 0 and self.season == 0: self.generate_heterogeneous_network() #in all time periods, process one round of the simulation and notify agents of exposure status self.run_basic_simulation() self.notify_agents() self.time_period += 1 #move to the next time period self.registered_agents = [ ] #reinitialize the registered_agents list for the next time period self.number_of_infected = 0 #reinitialize the number of infected for the next time period elif len(self.registered_agents ) == self.number_of_agents and self.number_of_infected == 0: self.start_new_season() self.registered_agents = [ ] #reinitialize the registered_agents list for the next time period self.number_of_infected = 0 #reinitialize the number of infected for the next time period self.registered_agents = [ ] #reinitialize the registered_agents list for the next time period self.number_of_infected = 0 #reinitialize the number of infected for the next time period if self.debug: logging.log(EXPERIMENT, "institution exited register")
def create_institution(self, message: Message): if "institutions" not in dir(self): self.institutions = [] if "address_book" not in dir(self): self.address_book = AddressBook(self) institution_class = message.get_payload()["institution_class"] source_hash = message.get_payload()["source_hash"] institution_order = message.get_payload()["order"] new_institution = self.createActor(institution_class, sourceHash=source_hash) # Insitutiton Initialization Message 1 self.send(new_institution, institution_class + " " + str(institution_order)) # Insitutiton Initialization Message 2 startup_payload = {} startup_payload["address_type"] = "institution" startup_payload["address"] = new_institution startup_payload["component_class"] = institution_class startup_payload["component_number"] = 1 startup_payload["short_name"] = institution_class + " " + str( institution_order) startup_payload["properties"] = self.mtree_properties startup_payload["environment"] = self.myAddress startup_payload["simulation_id"] = self.simulation_id startup_payload["simulation_run_id"] = self.simulation_run_id startup_payload["log_actor"] = self.log_actor if "run_number" in dir(self): startup_payload["run_number"] = self.run_number self.send(new_institution, startup_payload) institution_info = {} institution_info["address_type"] = "institution" institution_info["address"] = new_institution institution_info["component_class"] = institution_class institution_info["component_number"] = 1 institution_info["short_name"] = institution_class + " " + str( institution_order) self.address_book.add_address(institution_info["short_name"], institution_info) new_message = Message() #new_message.set_sender(self.myAddress) new_message.set_directive("simulation_properties") payload = {} #if "mtree_properties" not in dir(self): #payload["dispatcher"] = self.createActor("Dispatcher", globalName="dispatcher") payload["environment"] = self.myAddress payload["properties"] = self.mtree_properties payload["simulation_id"] = self.simulation_id payload["simulation_run_id"] = self.simulation_run_id payload["log_actor"] = self.log_actor if "run_number" in dir(self): payload["run_number"] = self.run_number payload["institution_info"] = institution_info new_message.set_payload(payload) #self.send(new_institution, new_message) self.institutions.append(new_institution)
def external_reminder(self, message: Message): reminder_message = message.get_payload()["reminder_message"] seconds_to_reminder = message.get_payload()["seconds_to_reminder"] self.reminder(seconds_to_reminder, reminder_message)