Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.02 KB | None | 0 0
  1. from mesa.visualization.ModularVisualization import ModularServer
  2. from mesa.visualization.UserParam import UserSettableParameter
  3. from mesa.visualization.modules import ChartModule
  4. from mesa.visualization.modules import NetworkModule
  5. from .model import BoltzmannWealthModelNetwork
  6.  
  7.  
  8. def network_portrayal(G):
  9.     # The model ensures there is 0 or 1 agent per node
  10.  
  11.     portrayal = dict()
  12.     portrayal['nodes'] = [{'id': node_id,
  13.                            'size': 3 if agents else 1,
  14.                            'color': '#CC0000' if not agents or agents[0].wealth == 0 else '#007959',
  15.                            'label': None if not agents else 'Agent:{} Wealth:{}'.format(agents[0].unique_id,
  16.                                                                                         agents[0].wealth),
  17.                            }
  18.                           for (node_id, agents) in G.nodes.data('agent')]
  19.  
  20.     portrayal['edges'] = [{'id': edge_id,
  21.                            'source': source,
  22.                            'target': target,
  23.                            'color': '#140078',
  24.                            }
  25.                           for edge_id, (source, target) in enumerate(G.edges)]
  26.  
  27.     return portrayal
  28.  
  29.  
  30. grid = NetworkModule(network_portrayal, 500, 500, library='sigma')
  31. chart = ChartModule([
  32.     {"Label": "Gini", "Color": "Black"}],
  33.     data_collector_name='datacollector'
  34. )
  35.  
  36. model_params = {
  37.     "num_agents": UserSettableParameter('slider', "Number of agents", 7, 2, 10, 1,
  38.                                         description="Choose how many agents to include in the model"),
  39.     "num_nodes": UserSettableParameter('slider', "Number of nodes", 10, 3, 12, 1,
  40.                                        description="Choose how many nodes to include in the model, with at "
  41.                                                    "least the same number of agents")#,
  42.     #"wealth": UserSettableParameter('slider', "Initial Wealth", 1000,1,10,1,
  43.                                   #     description="Choose how much starting wealth "
  44.                                     #               "least the same number of agents")
  45. }
  46.  
  47. server = ModularServer(BoltzmannWealthModelNetwork, [grid, chart], "Money Model", model_params)
  48. server.port = 8521
  49.  
  50.  
  51.  
  52. from mesa import Agent, Model
  53. from mesa.time import RandomActivation
  54. from mesa.datacollection import DataCollector
  55. import networkx as nx
  56. import random
  57.  
  58. from mesa.space import NetworkGrid
  59.  
  60.  
  61. def compute_gini(model):
  62.     agent_wealths = [agent.wealth for agent in model.schedule.agents]
  63.     x = sorted(agent_wealths)
  64.     N = model.num_agents
  65.     B = sum(xi * (N - i) for i, xi in enumerate(x)) / (N * sum(x))
  66.     return 1 + (1 / N) - 2 * B
  67.  
  68.  
  69. class BoltzmannWealthModelNetwork(Model):
  70.     """A model with some number of agents."""
  71.  
  72.     def __init__(self, num_agents=7, num_nodes=10):
  73.        
  74.        
  75.         #self.wealth = wealth
  76.         self.num_agents = num_agents
  77.         self.num_nodes = num_nodes if num_nodes >= self.num_agents else self.num_agents
  78.         self.G = nx.erdos_renyi_graph(n=self.num_nodes, p=0.5)
  79.         self.grid = NetworkGrid(self.G)
  80.         self.schedule = RandomActivation(self)
  81.         self.datacollector = DataCollector(
  82.             model_reporters={"Gini": compute_gini},
  83.             agent_reporters={"Wealth": lambda _: _.wealth}
  84.         )
  85.  
  86.         list_of_random_nodes = self.random.sample(self.G.nodes(), self.num_agents)
  87.  
  88.         # Create agents
  89.         for i in range(self.num_agents):
  90.             a = MoneyAgent(i, self)
  91.             self.schedule.add(a)
  92.             # Add the agent to a random node
  93.             self.grid.place_agent(a, list_of_random_nodes[i])
  94.  
  95.         self.running = True
  96.         self.datacollector.collect(self)
  97.  
  98.     def step(self):
  99.         self.schedule.step()
  100.         # collect data
  101.         self.datacollector.collect(self)
  102.  
  103.     def run_model(self, n):
  104.         for i in range(n):
  105.             self.step()
  106.  
  107.  
  108. class MoneyAgent(Agent):
  109.     """ An agent with fixed initial wealth."""
  110.  
  111.     def __init__(self, unique_id, model):
  112.         super().__init__(unique_id, model)
  113.         self.wealth = 1
  114.  
  115.     def move(self):
  116.         possible_steps = [node for node in self.model.grid.get_neighbors(self.pos, include_center=False) if
  117.                           self.model.grid.is_cell_empty(node)]
  118.         if len(possible_steps) > 0:
  119.             new_position = self.random.choice(possible_steps)
  120.             self.model.grid.move_agent(self, new_position)
  121.  
  122.     def give_money(self):
  123.  
  124.         neighbors_nodes = self.model.grid.get_neighbors(self.pos, include_center=False)
  125.         neighbors = self.model.grid.get_cell_list_contents(neighbors_nodes)
  126.         if len(neighbors) > 0:
  127.             other = self.random.choice(neighbors)
  128.             newval = random.uniform(0, 1)
  129.             newval = (newval*100)/100
  130.             #newval = format(newval, '.2f')
  131.             other.wealth += newval
  132.             self.wealth -= newval
  133.  
  134.     def step(self):
  135.         self.move()
  136.         if self.wealth > 0:
  137.             self.give_money()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement