def __init__(self, N):
        #Number of agents
        self.num_agents = N * N

        #The two grids can have just one agent per cell, it is dimensions NxN, and it is toroidal
        self.oldActivatorGrid = SingleGrid(N, N, True)
        self.oldInhibitorGrid = SingleGrid(N, N, True)
        self.currentActivatorGrid = SingleGrid(N, N, True)
        self.currentInhibitorGrid = SingleGrid(N, N, True)

        #Determine how our model will pick agent to interact with
        self.schedule = RandomActivation(self)

        # Create agents
        for i in range(self.num_agents):
            #Initialize a cell with uniqueID = i
            a = Cell(i, self)

            #Add our agent to our scheduler
            self.schedule.add(a)

            #Choose a random, unoccupied cell in our grid and add our agent to it
            #position_agent stores the x and y value for each of our agents
            locationTuple = self.oldActivatorGrid.find_empty()
            if (locationTuple) == (N / 2, N / 2):
                a.act = 2 * a.act
            self.oldActivatorGrid.place_agent(a, locationTuple)
            self.oldInhibitorGrid.place_agent(a, locationTuple)
            self.currentActivatorGrid.place_agent(a, locationTuple)
            self.currentInhibitorGrid.place_agent(a, locationTuple)
Пример #2
0
 def __init__(self, N):
     self.num_agents = N
     self.i = 1
     self.grid = SingleGrid(120, 120, True)
     self.grid1 = SingleGrid(120, 120, True)
     self.schedule = RandomActivation(self)
     self.schedule_dados = BaseScheduler(self)
     # Create agents
     for i in range(self.num_agents):
         a = Ant(i, self)
         self.schedule.add(a)
         x = self.random.randrange(self.grid.width)
         y = self.random.randrange(self.grid.height)
         #z = np.asarray([x,y])
         #print(z)
         plt.axis([-10, 125, -10, 125])
         #plt.scatter(x,y)
         self.grid.place_agent(a, (x, y))
     #create data
     for i in range(150):
         b = dado(i, self)
         self.schedule_dados.add(b)
         x = self.random.randrange(self.grid1.width)
         y = self.random.randrange(self.grid1.height)
         #print(x,y)
         z = np.asarray([x, y])
         plt.axis([-10, 125, -10, 125])
         plt.scatter(x, y)
         self.grid1.place_agent(b, (x, y))
Пример #3
0
    def __init__(self, config):
        '''
        Create a new Spatial Game Model

        Args:
            self.dimension: GameGrid size. There will be one agent per grid cell.
            self.num_moves_per_set: The number of moves each player makes with each other before evolving
            self.game_type: The type of game to play
            self.game_mode: The mode of that game to play
            self.cull_score: The minimum score a player must achieve in order to survive
        '''
        super().__init__()

        if config['square']:
            self.dimension = config['dimension']
            self.grid = SingleGrid(self.dimension, self.dimension, torus=config['periodic_BC'])
            self.height = self.dimension
            self.width = self.dimension
        else:
            self.height = config['height']
            self.width = config['width']
            self.dimension = self.width
            self.grid = SingleGrid(self.width, self.height, torus=config['periodic_BC'])

        self.step_num = 0

        self.num_moves_per_set = config['num_moves_per_set']

        self.initial_population_sizes = config['initial_population_sizes']
        self.biomes = config['biomes']
        if self.biomes:
            self.biome_boundaries = biome_boundaries(self.initial_population_sizes, self.width)

        self.cull_score = config['cull_score']
        self.kill_crowded = config['kill_crowded']

        self.probability_adoption = config['probability_adoption']
        self.probability_mutation = config['probability_mutation']
        self.probability_exchange = config['probability_exchange']
        self.probability_playing = config['probability_playing']
        self.probability_death = config['probability_death']

        self.agent_strategies = config['agent_strategies']
        self.agent_moves = config['agent_moves']

        self.schedule = RandomActivation(self)
        self.running = True

        # self.datacollector_populations = DataCollector()
        # self.datacollector_probabilities = DataCollector()

        self.num_mutating = 0
        self.fraction_mutating = 0

        self.num_dead = 0
        self.num_dying = 0
        self.num_evolving = 0
        self.fraction_evolving = 0
        self.crowded_players = []
    def __init__(self, grid_height, grid_width, percentage_of_cell_alive):
        """
        Constructor
        """

        self.grid = SingleGrid(grid_width, grid_height, False)
        self.scheduler = SimultaneousActivation(self)
        self.number_of_agent = grid_width * grid_height

        # Creation of all agent
        for i in range(self.number_of_agent):

            # Randomly chooses the initial state of the agent (0 is alive and 1 is dead)
            # We use choices from the random module because it allows us to specify a distribution
            # (ie. a list of probability for each state). Choices will return a list with ne element
            # which is our state
            probability_alive = percentage_of_cell_alive / 100
            probability_dead = 1 - probability_alive
            state = choices([0, 1], [probability_dead, probability_alive])[0]

            # Creating the agent and adding it to the scheduler
            agent = CellAgent(i, state, self)
            self.scheduler.add(agent)

            # Adding the new agent to the grid
            agent_coordinates = self.grid.find_empty()
            self.grid.place_agent(agent, agent_coordinates)

        # Define if the simulation is running or not
        self.running = True
    def __init__(self, n_agents: int, width: int, height: int,
                 agent_reach_radius: int, prior_sample_size: int,
                 initial_sd: float, start_p_h: float, *args: Any,
                 **kwargs: Any) -> None:
        """
        Create the model.
        :param n_agents: Number of agents to place.
        :param width: Width of the grid.
        :param height: Height of the grid.
        :param agent_reach_radius: Radius around the agent in which it can connect.
        :param prior_sample_size: Size of initial belief sample.
        :param initial_sd: Initial standard deviation of the agents' beliefs.
        :param start_p_h: Initial p|h value.
        """
        super().__init__(*args, **kwargs)
        self.n_agents = n_agents

        self.agent_range = agent_reach_radius

        self.prior_sample_size = prior_sample_size
        self.initial_sd = initial_sd
        self.start_p_h = start_p_h

        self.grid = SingleGrid(width, height, torus=True)
        self.schedule = RandomActivation(self)

        print('Placing agents.')
        for i in range(self.n_agents):
            agent = ConspiracyAgent(i, self)
            self.schedule.add(agent)

            self.grid.position_agent(agent)
        print('Finished placing agents.')
Пример #6
0
    def __init__(self, height=30, width=30, density=0.1, oxy_den_count=1):
        """
        """

        self.height = height
        self.width = width
        self.density = density

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(width, height, torus=True)
        self.datacollector = DataCollector(
            {"happy": "happy"},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {
                "x": lambda a: a.pos[0],
                "y": lambda a: a.pos[1]
            },
        )

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if self.random.random() < self.density:
                agent = SchellingAgent((x, y), self)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)
Пример #7
0
    def __init__(self, width, height, num_agents):
        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(width, height, torus = True)
        self.num_agents = num_agents
        
        # to collect info about how many agents are happy, average similarity of neighbors, length of residence
        self.datacollector = DataCollector(model_reporters = {"Happy": lambda m: m.happy, "Similar": lambda m: m.similar, "Residence": lambda m: m.avg_residence}, agent_reporters = {"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})
        
        self.avg_residence = 0
        self.happy = 0
        self.similar = 0
        self.running = True
        
        for i in range(self.num_agents):   
            # white
            if random.random() < 0.70:
                agent_type = 1
                income = np.random.normal(54000, 41000)
            
            # black
            else:
                agent_type = 0
                income = np.random.normal(32000, 40000)

            # add new agents
            agent = NewAgent(i, self, agent_type, income)
            self.schedule.add(agent)
            
            # assign the initial coords of the agents
            x = self.random.randrange(self.grid.width)
            y = self.random.randrange(self.grid.height)

            self.grid.position_agent(agent, (x, y))
Пример #8
0
    def __init__(self, N, length=100, lanes=1, timer=3):
        self.num_agents = N
        self.grid = SingleGrid(length, lanes, torus=True)
        model_stages = [
            "acceleration", "braking", "randomisation", "move", "delete"
        ]
        self.schedule = StagedActivation(self, stage_list=model_stages)

        # Create agent
        for i in range(self.num_agents):
            agent = CarAgent(i, self, False)
            # Add to schedule
            self.schedule.add(agent)
            # Add to grid (randomly)
            self.grid.position_agent(agent)

        # Add the traffic light
        self.traffic_light = TrafficLight(0, self, timer, 20, 20)
        self.average_velocity = CarAgent.init_velocity
        self.datacollector = DataCollector(agent_reporters={
            "Position": "pos",
            "Velocity": "velocity"
        },
                                           model_reporters={
                                               "Average Velocity":
                                               "average_velocity",
                                               "Amount of cars": "agent_count",
                                               "On Ramp Queue":
                                               get_on_ramp_queue,
                                               "Waiting Queue":
                                               get_waiting_queue
                                           })

        self.running = True
Пример #9
0
    def __init__(self,
                 height=20,
                 width=20,
                 density=0.8,
                 minority_fraction=0.2,
                 tolerance_threshold=4,
                 seed=None):
        super().__init__(seed=seed)
        self.height = height
        self.width = width
        self.density = density
        self.minority_fraction = minority_fraction

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(width, height, torus=True)
        self.datacollector = DataCollector(
            model_reporters={'happy': count_happy})

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if self.random.random() < self.density:
                if self.random.random() < self.minority_fraction:
                    agent_color = Color.RED
                else:
                    agent_color = Color.BLUE

                agent = SchellingAgent((x, y), self, agent_color,
                                       tolerance_threshold)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)
Пример #10
0
 def __init__(self, N, width=2, height=2):
     super().__init__(self, N)
     self.num_agents = N
     self.schedule = RandomActivation(self)
     self.grid = SingleGrid(height, width, torus=True)
     self.running = True
     self.current_orientation = None
     self.datacollector = DataCollector(
         model_reporters={"Current orientation": "current_orientation"},
         agent_reporters={
             "Passed cars": "passed_cars",
             "Light": "light"
         })
     agents = []
     orientation = None
     for i in range(self.num_agents):
         cars = random.randint(0, 4)
         if (i % 2 == 0):
             orientation = Orientation.HORIZONTAL
         else:
             orientation = Orientation.VERTICAL
         t = TrafficLightAgent(i, self, cars, orientation)
         agents.append(t)
     self.set_traffic_lights(agents, self.__priority(agents))
     for agent in agents:
         self.schedule.add(agent)
Пример #11
0
    def __init__(self, height=8, width=8,
                 number_of_agents=2,
                 schedule_type="Simultaneous",
                 rounds=1,):


        # Model Parameters
        self.height = height
        self.width = width
        self.number_of_agents = number_of_agents
        self.step_count = 0
        self.schedule_type = schedule_type
        self.payoffs = {("C", "C"): 3,
                        ("C", "D"): 0,
                        ("D", "C"): 5,
                        ("D", "D"): 2}


        # Model Functions
        self.schedule = self.schedule_types[self.schedule_type](self)
        self.grid = SingleGrid(self.height, self.width, torus=True)

        # Find list of empty cells
        self.coordinates = [(x, y) for x in range(self.width) for y in range(self.height)]

        self.agentIDs = list(range(1, (number_of_agents + 1)))

        self.make_agents()
        self.running = True
Пример #12
0
    def __init__(self, height=20, width=20, density=0.8, minority_pc=0.2, homophily=3):
        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(width, height, torus=True)

        self.happy = 0
        self.datacollector = DataCollector(
            {"happy": "happy"},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]})

        # Set up agents
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if self.random.random() < self.density:
                if self.random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent((x, y), self, agent_type)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)
Пример #13
0
    def __init__(self,
                 height=20,
                 width=20,
                 density=.8,
                 group_ratio=.66,
                 minority_ratio=.5,
                 homophily=3):
        self.height = height
        self.width = width
        self.density = density
        self.group_ratio = group_ratio
        self.minority_ratio = minority_ratio
        self.homophily = homophily
        self.happy = 0
        self.segregated = 0

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(height, width, torus=False)

        self.place_agents()
        self.datacollector = DataCollector({
            'happy': (lambda m: m.happy),
            'segregated': (lambda m: m.segregated)
        })
        self.running = True
Пример #14
0
 def initialize_grid(self):
     """
     Initializes the initial Grid
     """
     self.grid = SingleGrid(width=self.width,
                            height=self.height,
                            torus=self.toric)
Пример #15
0
 def setUp(self):
     self.space = SingleGrid(50, 50, False)
     self.agents = []
     for i, pos in enumerate(TEST_AGENTS_GRID):
         a = MockAgent(i, None)
         self.agents.append(a)
         self.space.place_agent(a, pos)
Пример #16
0
    def __init__(self, n_students, n_active: int, width: int, height: int):
        self.running = True
        self.schedule = SimultaneousActivation(self)
        self.grid = SingleGrid(width, height, torus=False)
        self.n_students: int = n_students
        self._semester_gen = self._gen_semester_code()
        self.semester = next(self._semester_gen)
        self.ALL_GENDERS = gen_gender(self.n_students)

        # Majors
        self.F1SEQ1_MAJORS = gen_f1seq1_majors(self.n_students)
        self.major_switcher = MajorSwitch()

        # Adding Student to KSU Environment
        for i in range(self.n_students):
            # Percentage of student agent that will be active and the rest inactive
            per_active = n_active / 100

            if np.random.binomial(1, per_active):
                student = Student(i, self, self.ALL_GENDERS[i])
                student.majors.append(self.F1SEQ1_MAJORS[i])
            else:
                student = Student(i, self, self.ALL_GENDERS[i], False)
                student.majors.append("N/A")

            self.schedule.add(student)
            self.grid.position_agent(student)

        self.datacollector = DataCollector(
            agent_reporters={
                "GPA": "gpa",
                "ATTEMPTED_HRS": "attempted_hrs",
                "EARNED_HRS": "earned_hrs",
                "Major": "curr_major"
            })
Пример #17
0
    def __init__(self,
                 width=50,
                 height=50,
                 proportion_producers=0.3,
                 proportion_consumers=0.3):
        self.running = True
        self.schedule = BaseScheduler(self)
        self.grid = SingleGrid(width, height, torus=False)

        initial_activator = Producer("Initial activator", self, activated=True)
        center_coords = (math.floor(width / 2), math.floor(height / 2))

        ## Rolled into the placement of other cells
        # self.schedule.add(initial_activator)
        # self.grid.place_agent(initial_activator, center_coords)

        # roll a die and place Producer, Consumer or undifferentiated cell
        for x in range(width):
            for y in range(height):
                roll = r.random()
                coords = (x, y)

                if coords == center_coords:
                    agent = initial_activator
                elif roll <= proportion_producers:
                    agent = Producer(coords, self)
                elif roll <= proportion_producers + proportion_consumers:
                    agent = Consumer(coords, self)
                else:
                    agent = Cell(coords, self)

                self.schedule.add(agent)
                self.grid.place_agent(agent, coords)
Пример #18
0
    def __init__(self,
                 width=50,
                 height=50,
                 torus=True,
                 num_bug=50,
                 seed=42,
                 strategy=None):
        super().__init__(seed=seed)
        self.number_of_bug = num_bug
        if not (strategy in ["stick", "switch"]):
            raise TypeError("'strategy' must be one of {stick, switch}")
        self.strategy = strategy

        self.grid = SingleGrid(width, height, torus)
        self.schedule = RandomActivation(self)
        data = {
            "Bean": lambda m: m.number_of_bean,
            "Corn": lambda m: m.number_of_corn,
            "Soy": lambda m: m.number_of_soy,
            "Bug": lambda m: m.number_of_bug,
        }
        self.datacollector = DataCollector(data)

        # create foods
        self._populate(Bean)
        self._populate(Corn)
        self._populate(Soy)

        # create bugs
        for i in range(self.number_of_bug):
            pos = self.grid.find_empty()
            bug = Bug(i, self)
            bug.strategy = self.strategy
            self.grid.place_agent(bug, pos)
            self.schedule.add(bug)
Пример #19
0
    def __init__(self, height, width, schedule_type, payoffs=None):
        '''
        Create a new Spatial Prisoners' Dilemma Model.

        Args:
            height, width: Grid size. There will be one agent per grid cell.
            schedule_type: Can be "Sequential", "Random", or "Simultaneous".
                           Determines the agent activation regime.
            payoffs: (optional) Dictionary of (move, neighbor_move) payoffs.
        '''
        self.grid = SingleGrid(height, width, torus=True)
        self.schedule_type = schedule_type
        self.schedule = self.schedule_types[self.schedule_type](self)

        # Create agents
        for x in range(width):
            for y in range(height):
                agent = PDAgent((x, y), self)
                self.grid.place_agent(agent, (x, y))
                self.schedule.add(agent)

        self.datacollector = DataCollector({
            "Cooperating_Agents":
            lambda m: len([a for a in m.schedule.agents if a.move == "C"])
        })

        self.running = True
        self.datacollector.collect(self)
Пример #20
0
 def __init__(self, N=2, width=20, height=10):
     self.N = N  # num of agents
     self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))  # tuples are fast
     self.grid = SingleGrid(width, height, torus=False)
     self.schedule = RandomActivation(self)
     self.make_walker_agents()
     self.running = True
Пример #21
0
    def __init__(self, height=50, width=50, density=0.8, minority_pc=0.5, homophily=3):
        '''
        '''

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(height, width, torus=True)

        self.happy = 0
        self.running = True

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x = cell[1]
            y = cell[2]
            if random.random() < self.density:
                if random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent = SchellingAgent((x, y), self, agent_type)
                self.grid.position_agent(agent, (x, y))
                self.schedule.add(agent)
Пример #22
0
    def __init__(self, width, height, eta, theta, gamma):
        super().__init__()
        self.grid = SingleGrid(width, height, True)
        self.schedule = RandomActivation(self)
        self.eta = eta
        self.theta = theta
        self.gamma = gamma
        self.nAgents = width * height

        self.avgA = self.A0
        self.avgBD = theta * gamma / self.OMEGA
        self.avgN = (gamma * self.DELTA_T /
                     (1 - math.exp(-self.avgA * self.DELTA_T)))

        for i in range(width):
            for j in range(height):

                newId = self.id + 1
                newAgent = LatticeAgent(newId, self, [], (j, i))
                self.schedule.add(newAgent)
                self.grid.position_agent(newAgent, j, i)
                self.id = newId + 1

        for k in range(round(self.avgN * width * height)):
            acell = random.choice(self.schedule.agents)
            acell.burglers.append(Burgler())
Пример #23
0
    def __init__(
        self,
        height=20,
        width=20,
        density=0.8,
        minority_pc=0.2,
        homophily=3,
        education_boost=0,
        education_pc=0.2,
        seed=None,
    ):
        """Seed is used to set randomness in the __new__ function of the Model superclass."""
        # pylint: disable-msg=unused-argument,super-init-not-called

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc
        self.homophily = homophily
        self.education_boost = education_boost
        self.education_pc = education_pc

        self.schedule = RandomActivation(self)
        self.grid = SingleGrid(height, width, torus=True)

        self.happy = 0
        self.datacollector = DataCollector(
            {"happy": "happy"},  # Model-level count of happy agents
            # For testing purposes, agent's individual x and y
            {
                "x": lambda a: a.pos[0],
                "y": lambda a: a.pos[1]
            },
        )

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x_coord = cell[1]
            y_coord = cell[2]
            if self.random.random() < self.density:
                if self.random.random() < self.minority_pc:
                    agent_type = 1
                else:
                    agent_type = 0

                agent_homophily = homophily
                if self.random.random() < self.education_pc:
                    agent_homophily += self.education_boost

                agent = SchellingAgent((x_coord, y_coord), self, agent_type,
                                       agent_homophily)
                self.grid.position_agent(agent, (x_coord, y_coord))
                self.schedule.add(agent)

        self.running = True
        self.datacollector.collect(self)
Пример #24
0
 def __init__(self, N, width=20, height=10):
     self.running = True
     self.N = N  # num of agents
     self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))  # tuples are fast
     self.grid = SingleGrid(width, height, torus=False)
     self.schedule = RandomActivation(self)
     load_scene('shape_model/crossing.txt', self.grid, self)
     """
Пример #25
0
    def __init__(self, height, width, depreciation_rate, mobility, status,
                 stat_var, d_factor):
        # Set model parameters
        self.depreciation_rate = depreciation_rate
        self.mobility = mobility
        self.status = status
        self.stat_var = stat_var
        self.d_factor = d_factor
        self.height = height

        # Global tracking variables
        self.mean_income = 0.0

        self.schedule = SimultaneousActivation(self)
        self.grid = SingleGrid(height, width, torus=False)

        self.datacollector = DataCollector(model_reporters={
            "status":
            lambda m: m.status,
            "income":
            lambda m: m.mean_income,
            "condition":
            lambda m: m.mean_condition
        },
                                           agent_reporters={
                                               "x": lambda a: a.pos[0],
                                               "y": lambda a: a.pos[1]
                                           })

        self.running = True
        self.hit_bottom = False
        self.last_bottom = 0
        self.gent_time = None

        self.conditions = np.zeros((width, height))

        # Set up agents
        # We use a grid iterator that returns
        # the coordinates of a cell as well as
        # its contents. (coord_iter)
        for cell in self.grid.coord_iter():
            x, y = cell[1], cell[2]

            self.conditions[x, y] = bounded_normal(0.50, 0.1, 0.0, 1.0)

            # Income initially differs little from property conditions
            while True:
                income = self.conditions[x, y] + np.random.normal(0.0, 0.025)
                if income >= 0.0 and income <= 1.0:
                    self.mean_income += income
                    break

            agent = PropertyAgent((x, y), self, income)
            self.grid.position_agent(agent, (x, y))
            self.schedule.add(agent)

        self.mean_condition = np.sum(self.conditions) / self.conditions.size
        self.mean_income /= self.conditions.size
Пример #26
0
    def __init__(self, wiggle_angle, number_particles, probability_of_sticking, 
                 neighbor_influence, num_seeds):
        self.running = True # necessário para que o modelo seja chamado pelo servidor web
        self.wiggle_angle = wiggle_angle
        self.number_particles = number_particles
        " indica com que probabilidade uma partícula vermelha se torna verde " 
        " e pára ao tocar uma partícula verde"
        self.probability_of_sticking = probability_of_sticking
        "indica se o número de vizinhos verdes influencia a probabilidade de"
        "grudar"
        self.neighbor_influence = neighbor_influence
        if num_seeds <= 0: # número de sementes deve ser positivo
            raise ValueError("Number of seeds should be greater than zero.")
        self.num_seeds = num_seeds
        "direções das particulas"
        "(1,0) direita; (0, 1) cima; (-1, 0) esquerda (0, -1) baixo"
        self.headings = ((1, 0), (0, 1), (-1, 0), (0, -1))
        self.schedule = BaseScheduler(self)

        "tamanho do grid definido em função do número de partículas, como na" 
        "visualização; pode ser um valor comum aos dois"
        width = height = round(2 * round(math.sqrt(number_particles)))
        
        "apenas um agente por célula"
        self.grid = SingleGrid(width, height, True)
        
        "Cria as sementes"
        for i in range(self.num_seeds):
            if self.num_seeds == 1:
                """
                Coloca a semente no centro do grid. O modelo final do NetLogo,
                com a extensão 3, não coloca uma semente unitária no centro,
                mas em uma posição aleatória também.
                """
                x = round(self.grid.width / 2);
                y = round(self.grid.height / 2);
                "o angulo e o a probabilidade de colar não são relevantes, já" 
                "que as sementes não se movem"
                particle = Particle(i, self, GREEN_COLOR, 0, (x, y))
                self.grid.place_agent(particle, (x, y))
            else:
                """
                Coloca as sementes em posições aleatórias. A posição 
                será atribuída pelo método position_agent
                """
                particle = Particle(i, self, GREEN_COLOR, 0, (0, 0))
                self.grid.position_agent(particle)
            
            self.schedule.add(particle)

        "Cria as partículas"
        for i in range(self.number_particles):
           
            "a posição será atribuída pelo método position_agent"
            heading = self.random.choice(self.headings)
            particle = Particle(i, self, RED_COLOR, heading, (0, 0))
            self.grid.position_agent(particle)
            self.schedule.add(particle)
Пример #27
0
 def __init__(self, height, width, model):
     self.navigationGrid = SingleGrid(height, width, False)
     self.planGrid = MultiGrid(height, width, False)
     self.planAgents = defaultdict(list)
     self.perceptionAgents = {}
     self.model = model
     agent = FarmAgent(0, self.model.farmPos, self)
     self.navigationGrid.place_agent(agent, self.model.farmPos)
     self.attendancePoints = list()
Пример #28
0
    def __init__(self, SM_inputs, height=20, width=20):

        self.height = height  # height of the canvas
        self.width = width  # width of the canvas

        self.SM_inputs = SM_inputs  # inputs for the entire model

        self.stepCount = 0  # int - [-] - initialisation of step counter
        self.agenda_PC = None  # initialisation of agenda policy core issue tracker
        self.policy_implemented_number = None  # initialisation of policy number tracker
        self.policy_formulation_run = False  # check value for running policy formulation

        self.w_el_influence = self.SM_inputs[
            9]  # float - [-] - electorate influence weight constant
        # todo - consider also saving the electorate influence parameter

        self.schedule = RandomActivation(self)  # mesa random activation method
        self.grid = SingleGrid(height, width,
                               torus=True)  # mesa grid creation method

        # creation of the datacollector vector
        self.datacollector = DataCollector(
            # Model-level variables
            model_reporters={
                "step": "stepCount",
                "AS_PF": get_problem_policy_chosen,
                "agent_attributes": get_agents_attributes,
                "electorate_attributes": get_electorate_attributes
            },
            # Agent-level variables
            agent_reporters={
                "x":
                lambda a: a.pos[0],
                "y":
                lambda a: a.pos[1],
                "Agent type":
                lambda a: type(a),
                "Issuetree":
                lambda a: getattr(a, 'issuetree', [None])[
                    a.unique_id if isinstance(a, ActiveAgent) else 0]
            })

        self.len_S, self.len_PC, self.len_DC, self.len_CR = belief_tree_input(
        )  # setting up belief tree
        self.policy_instruments, self.len_ins, self.PF_indices = policy_instrument_input(
        )  # setting up policy instruments
        init_active_agents(self, self.len_S, self.len_PC, self.len_DC,
                           self.len_CR, self.len_PC, self.len_ins,
                           self.SM_inputs)  # setting up active agents
        init_electorate_agents(self, self.len_S, self.len_PC, self.len_DC,
                               self.SM_inputs)  # setting up passive agents
        init_truth_agent(self, self.len_S, self.len_PC, self.len_DC,
                         self.len_ins)  # setting up truth agent

        self.running = True
        self.numberOfAgents = self.schedule.get_agent_count()
        self.datacollector.collect(self)
Пример #29
0
    def __init__(self,
                 N,
                 width,
                 height,
                 init_price,
                 init_ei,
                 grow_ei,
                 fixed,
                 rnd,
                 p_q,
                 p_ei,
                 min_neighbor,
                 sub,
                 subsell,
                 burn,
                 seed=None):
        self.num_agents = (width * height)
        self.grid = SingleGrid(width, height, True)
        self.schedule = RandomActivation(self)
        self.running = True
        self.ext_inc = init_ei
        self.grow_ei = grow_ei
        self.min_neighbor = min_neighbor
        self.p_q = p_q
        self.p_ei = p_ei
        self.last_price = 0
        self.price = self.init_price = init_price
        self.tick = 0
        self.true_supply = 0
        self.stock = 0
        self.subtrue = False
        self.sub = sub
        self.subsell = subsell
        self.burn = burn
        self.burned = 0
        self.tax = 0

        print(f'{p_q}, {p_ei}, {min_neighbor}')

        # Create agents
        for i in range(self.num_agents):
            a = MoneyAgent(i, self, N, fixed, rnd)
            self.schedule.add(a)
            self.grid.place_agent(a, (0, 0))
            if i < self.num_agents - 1:
                self.grid.move_to_empty(a)
        self.supply = [k.color for k in self.schedule.agents].count('yellow')

        self.datacollector = DataCollector(
            model_reporters={
                "Supply": compute_supply,
                "Price": compute_price,
                "Stock": compute_stock,
                "Burned": compute_burned
            }
            #agent_reporters={"Wealth": "wealth"}
        )
Пример #30
0
    def __init__(self, width: int = 5, height: int = 5):
        super().__init__()
        self.active_agent = Turtle(self.next_id(), self)
        self.active_agent.active = True

        self.grid = SingleGrid(width, height, True)
        self.grid.position_agent(self.active_agent, width // 2, height // 2)

        self.schedule = BaseScheduler(self)
        self.schedule.add(self.active_agent)