本文整理汇总了Python中mesa.space.MultiGrid.place_agent方法的典型用法代码示例。如果您正苦于以下问题:Python MultiGrid.place_agent方法的具体用法?Python MultiGrid.place_agent怎么用?Python MultiGrid.place_agent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mesa.space.MultiGrid
的用法示例。
在下文中一共展示了MultiGrid.place_agent方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: WalkerWorld
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class WalkerWorld(Model):
'''
Random walker world.
'''
height = 10
width = 10
def __init__(self, height, width, agent_count):
'''
Create a new WalkerWorld.
Args:
height, width: World size.
agent_count: How many agents to create.
'''
self.height = height
self.width = width
self.grid = MultiGrid(self.height, self.width, torus=True)
self.agent_count = agent_count
self.schedule = RandomActivation(self)
# Create agents
for i in range(self.agent_count):
x = random.randrange(self.width)
y = random.randrange(self.height)
a = WalkerAgent((x, y), self, True)
self.schedule.add(a)
self.grid.place_agent(a, (x, y))
def step(self):
self.schedule.step()
示例2: Money_Model
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class Money_Model(Model):
def __init__(self, N, width=50, height=50, torus=True):
self.num_agents = N
self.schedule = RandomActivation(self)
self.grid = MultiGrid(height, width, torus)
self.create_agents()
self.dc = DataCollector({"Gini": lambda m: m.compute_gini()},
{"Wealth": lambda a: a.wealth})
self.running = True
def create_agents(self):
for i in range(self.num_agents):
a = Money_Agent(i)
self.schedule.add(a)
x = random.randrange(self.grid.width)
y = random.randrange(self.grid.height)
self.grid.place_agent(a, (x, y))
def step(self):
self.dc.collect(self)
self.schedule.step()
def run_model(self, steps):
for i in range(steps):
self.step()
def compute_gini(self):
agent_wealths = [agent.wealth for agent in self.schedule.agents]
x = sorted(agent_wealths)
N = self.num_agents
B = sum( xi * (N-i) for i,xi in enumerate(x) ) / (N*sum(x))
return (1 + (1/N) - 2*B)
示例3: MoneyModel
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class MoneyModel(Model):
"""A simple model of an economy where agents exchange currency at random.
All the agents begin with one unit of currency, and each time step can give
a unit of currency to another agent. Note how, over time, this produces a
highly skewed distribution of wealth.
"""
def __init__(self, N, width, height):
self.num_agents = N
self.running = True
self.grid = MultiGrid(height, width, True)
self.schedule = RandomActivation(self)
self.datacollector = DataCollector(
model_reporters={"Gini": compute_gini},
agent_reporters={"Wealth": lambda a: a.wealth}
)
# Create agents
for i in range(self.num_agents):
a = MoneyAgent(i, self)
self.schedule.add(a)
# Add the agent to a random grid cell
x = random.randrange(self.grid.width)
y = random.randrange(self.grid.height)
self.grid.place_agent(a, (x, y))
def step(self):
self.datacollector.collect(self)
self.schedule.step()
def run_model(self, n):
for i in range(n):
self.step()
示例4: MoneyModel
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class MoneyModel(Model):
"""A model with some number of agents."""
def __init__(self, N, width, height):
self.num_agents = N
self.running = True
self.grid = MultiGrid(height, width, True)
self.schedule = RandomActivation(self)
self.datacollector = DataCollector(model_reporters={"Gini": compute_gini},
agent_reporters={"Wealth": lambda a: a.wealth})
# Create agents
for i in range(self.num_agents):
a = MoneyAgent(i)
self.schedule.add(a)
# Add the agent to a random grid cell
x = random.randrange(self.grid.width)
y = random.randrange(self.grid.height)
self.grid.place_agent(a, (x, y))
def step(self):
self.datacollector.collect(self)
self.schedule.step()
def run_model(self, n):
for i in range(n):
self.step()
示例5: TestMultiGrid
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class TestMultiGrid(unittest.TestCase):
'''
Testing a toroidal MultiGrid
'''
torus = True
def setUp(self):
'''
Create a test non-toroidal grid and populate it with Mock Agents
'''
width = 3
height = 5
self.grid = MultiGrid(width, height, self.torus)
self.agents = []
counter = 0
for x in range(width):
for y in range(height):
for i in range(TEST_MULTIGRID[x][y]):
counter += 1
# Create and place the mock agent
a = MockAgent(counter, None)
self.agents.append(a)
self.grid.place_agent(a, (x, y))
def test_agent_positions(self):
'''
Ensure that the agents are all placed properly on the MultiGrid.
'''
for agent in self.agents:
x, y = agent.pos
assert agent in self.grid[x][y]
def test_neighbors(self):
'''
Test the toroidal MultiGrid neighborhood methods.
'''
neighborhood = self.grid.get_neighborhood((1, 1), moore=True)
assert len(neighborhood) == 8
neighborhood = self.grid.get_neighborhood((1, 4), moore=True)
assert len(neighborhood) == 8
neighborhood = self.grid.get_neighborhood((0, 0), moore=False)
assert len(neighborhood) == 4
neighbors = self.grid.get_neighbors((1, 4), moore=False)
assert len(neighbors) == 0
neighbors = self.grid.get_neighbors((1, 4), moore=True)
assert len(neighbors) == 5
neighbors = self.grid.get_neighbors((1, 1), moore=False,
include_center=True)
assert len(neighbors) == 7
neighbors = self.grid.get_neighbors((1, 3), moore=False, radius=2)
assert len(neighbors) == 11
示例6: Charts
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class Charts(Model):
# grid height
grid_h = 20
# grid width
grid_w = 20
"""init parameters "init_people", "rich_threshold", and "reserve_percent"
are all UserSettableParameters"""
def __init__(self, height=grid_h, width=grid_w, init_people=2, rich_threshold=10,
reserve_percent=50,):
self.height = height
self.width = width
self.init_people = init_people
self.schedule = RandomActivation(self)
self.grid = MultiGrid(self.width, self.height, torus=True)
# rich_threshold is the amount of savings a person needs to be considered "rich"
self.rich_threshold = rich_threshold
self.reserve_percent = reserve_percent
# see datacollector functions above
self.datacollector = DataCollector(model_reporters={
"Rich": get_num_rich_agents,
"Poor": get_num_poor_agents,
"Middle Class": get_num_mid_agents,
"Savings": get_total_savings,
"Wallets": get_total_wallets,
"Money": get_total_money,
"Loans": get_total_loans},
agent_reporters={
"Wealth": lambda x: x.wealth})
# create a single bank for the model
self.bank = Bank(1, self, self.reserve_percent)
# create people for the model according to number of people set by user
for i in range(self.init_people):
# set x, y coords randomly within the grid
x = self.random.randrange(self.width)
y = self.random.randrange(self.height)
p = Person(i, (x, y), self, True, self.bank, self.rich_threshold)
# place the Person object on the grid at coordinates (x, y)
self.grid.place_agent(p, (x, y))
# add the Person object to the model schedule
self.schedule.add(p)
self.running = True
self.datacollector.collect(self)
def step(self):
# tell all the agents in the model to run their step function
self.schedule.step()
# collect data
self.datacollector.collect(self)
def run_model(self):
for i in range(self.run_time):
self.step()
示例7: WolfSheepPredation
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class WolfSheepPredation(Model):
'''
Wolf-Sheep Predation Model
'''
initial_sheep = 100
initial_wolves = 50
sheep_gain_from_food = 4
grass = False
wolf_gain_from_food = 20
sheep_reproduce = 0.04
wolf_reproduce = 0.05
height = 20
width = 20
def __init__(self, height=20, width=20,
initial_sheep=100, initial_wolves=50, sheep_reproduce=0.04,
wolf_reproduce=0.05, wolf_gain_from_food=20,
grass=False, sheep_gain_from_food=4):
'''
Create a new Wolf-Sheep model with the given parameters.
Args:
initial_sheep: Number of sheep to start with
initial_wolves: Number of wolves to start with
sheep_reproduce: Probability of each sheep reproducing each step
wolf_reproduce: Probability of each wolf reproducing each step
wolf_gain_from_food: Energy a wolf gains from eating a sheep
grass: Whether to have the sheep eat grass for energy
sheep_gain_from_food: Energy sheep gain from grass, if enabled.
'''
# Set parameters
self.height = height
self.width = width
self.initial_sheep = initial_sheep
self.initial_wolves = initial_wolves
self.sheep_reproduce = sheep_reproduce
self.wolf_reproduce = wolf_reproduce
self.wolf_gain_from_food = wolf_gain_from_food
self.grass = grass
self.sheep_gain_from_food = sheep_gain_from_food
self.schedule = RandomActivation(self)
self.grid = MultiGrid(self.height, self.width, torus=True)
# Create sheep:
for i in range(self.initial_sheep):
x = random.randrange(self.width)
y = random.randrange(self.height)
sheep = Sheep(self.grid, x, y, True)
self.grid.place_agent(sheep, (x, y))
self.schedule.add(sheep)
# Create wolves
for i in range(self.initial_wolves):
x = random.randrange(self.width)
y = random.randrange(self.height)
energy = random.randrange(2 * self.wolf_gain_from_food)
wolf = Wolf(self.grid, x, y, True, energy)
self.grid.place_agent(wolf, (x, y))
self.schedule.add(wolf)
self.running = True
def step(self):
self.schedule.step()
示例8: WolfSheep
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class WolfSheep(Model):
'''
Wolf-Sheep Predation Model
'''
height = 20
width = 20
initial_sheep = 100
initial_wolves = 50
sheep_reproduce = 0.04
wolf_reproduce = 0.05
wolf_gain_from_food = 20
grass = False
grass_regrowth_time = 30
sheep_gain_from_food = 4
verbose = False # Print-monitoring
description = 'A model for simulating wolf and sheep (predator-prey) ecosystem modelling.'
def __init__(self, height=20, width=20,
initial_sheep=100, initial_wolves=50,
sheep_reproduce=0.04, wolf_reproduce=0.05,
wolf_gain_from_food=20,
grass=False, grass_regrowth_time=30, sheep_gain_from_food=4):
'''
Create a new Wolf-Sheep model with the given parameters.
Args:
initial_sheep: Number of sheep to start with
initial_wolves: Number of wolves to start with
sheep_reproduce: Probability of each sheep reproducing each step
wolf_reproduce: Probability of each wolf reproducing each step
wolf_gain_from_food: Energy a wolf gains from eating a sheep
grass: Whether to have the sheep eat grass for energy
grass_regrowth_time: How long it takes for a grass patch to regrow
once it is eaten
sheep_gain_from_food: Energy sheep gain from grass, if enabled.
'''
super().__init__()
# Set parameters
self.height = height
self.width = width
self.initial_sheep = initial_sheep
self.initial_wolves = initial_wolves
self.sheep_reproduce = sheep_reproduce
self.wolf_reproduce = wolf_reproduce
self.wolf_gain_from_food = wolf_gain_from_food
self.grass = grass
self.grass_regrowth_time = grass_regrowth_time
self.sheep_gain_from_food = sheep_gain_from_food
self.schedule = RandomActivationByBreed(self)
self.grid = MultiGrid(self.height, self.width, torus=True)
self.datacollector = DataCollector(
{"Wolves": lambda m: m.schedule.get_breed_count(Wolf),
"Sheep": lambda m: m.schedule.get_breed_count(Sheep)})
# Create sheep:
for i in range(self.initial_sheep):
x = self.random.randrange(self.width)
y = self.random.randrange(self.height)
energy = self.random.randrange(2 * self.sheep_gain_from_food)
sheep = Sheep(self.next_id(), (x, y), self, True, energy)
self.grid.place_agent(sheep, (x, y))
self.schedule.add(sheep)
# Create wolves
for i in range(self.initial_wolves):
x = self.random.randrange(self.width)
y = self.random.randrange(self.height)
energy = self.random.randrange(2 * self.wolf_gain_from_food)
wolf = Wolf(self.next_id(), (x, y), self, True, energy)
self.grid.place_agent(wolf, (x, y))
self.schedule.add(wolf)
# Create grass patches
if self.grass:
for agent, x, y in self.grid.coord_iter():
fully_grown = self.random.choice([True, False])
if fully_grown:
countdown = self.grass_regrowth_time
else:
countdown = self.random.randrange(self.grass_regrowth_time)
patch = GrassPatch(self.next_id(), (x, y), self,
fully_grown, countdown)
self.grid.place_agent(patch, (x, y))
self.schedule.add(patch)
self.running = True
self.datacollector.collect(self)
def step(self):
#.........这里部分代码省略.........
示例9: Sugarscape2ConstantGrowback
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class Sugarscape2ConstantGrowback(Model):
'''
Sugarscape 2 Constant Growback
'''
verbose = True # Print-monitoring
def __init__(self, height=50, width=50,
initial_population=100):
'''
Create a new Constant Growback model with the given parameters.
Args:
initial_population: Number of population to start with
'''
# Set parameters
self.height = height
self.width = width
self.initial_population = initial_population
self.schedule = RandomActivationByBreed(self)
self.grid = MultiGrid(self.height, self.width, torus=False)
self.datacollector = DataCollector({"SsAgent": lambda m: m.schedule.get_breed_count(SsAgent), })
# Create sugar
import numpy as np
sugar_distribution = np.genfromtxt("sugarscape/sugar-map.txt")
for _, x, y in self.grid.coord_iter():
max_sugar = sugar_distribution[x, y]
sugar = Sugar((x, y), self, max_sugar)
self.grid.place_agent(sugar, (x, y))
self.schedule.add(sugar)
# Create agent:
for i in range(self.initial_population):
x = random.randrange(self.width)
y = random.randrange(self.height)
sugar = random.randrange(6, 25)
metabolism = random.randrange(2, 4)
vision = random.randrange(1, 6)
ssa = SsAgent((x, y), self, False, sugar, metabolism, vision)
self.grid.place_agent(ssa, (x, y))
self.schedule.add(ssa)
self.running = True
def step(self):
self.schedule.step()
self.datacollector.collect(self)
if self.verbose:
print([self.schedule.time,
self.schedule.get_breed_count(SsAgent)])
def run_model(self, step_count=200):
if self.verbose:
print('Initial number Sugarscape Agent: ',
self.schedule.get_breed_count(SsAgent))
for i in range(step_count):
self.step()
if self.verbose:
print('')
print('Final number Sugarscape Agent: ',
self.schedule.get_breed_count(SsAgent))
示例10: BankReserves
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class BankReserves(Model):
"""
This model is a Mesa implementation of the Bank Reserves model from NetLogo.
It is a highly abstracted, simplified model of an economy, with only one
type of agent and a single bank representing all banks in an economy. People
(represented by circles) move randomly within the grid. If two or more people
are on the same grid location, there is a 50% chance that they will trade with
each other. If they trade, there is an equal chance of giving the other agent
$5 or $2. A positive trade balance will be deposited in the bank as savings.
If trading results in a negative balance, the agent will try to withdraw from
its savings to cover the balance. If it does not have enough savings to cover
the negative balance, it will take out a loan from the bank to cover the
difference. The bank is required to keep a certain percentage of deposits as
reserves and the bank's ability to loan at any given time is a function of
the amount of deposits, its reserves, and its current total outstanding loan
amount.
"""
# grid height
grid_h = 20
# grid width
grid_w = 20
"""init parameters "init_people", "rich_threshold", and "reserve_percent"
are all UserSettableParameters"""
def __init__(self, height=grid_h, width=grid_w, init_people=2, rich_threshold=10,
reserve_percent=50,):
self.height = height
self.width = width
self.init_people = init_people
self.schedule = RandomActivation(self)
self.grid = MultiGrid(self.width, self.height, torus=True)
# rich_threshold is the amount of savings a person needs to be considered "rich"
self.rich_threshold = rich_threshold
self.reserve_percent = reserve_percent
# see datacollector functions above
self.datacollector = DataCollector(model_reporters={
"Rich": get_num_rich_agents,
"Poor": get_num_poor_agents,
"Middle Class": get_num_mid_agents,
"Savings": get_total_savings,
"Wallets": get_total_wallets,
"Money": get_total_money,
"Loans": get_total_loans},
agent_reporters={
"Wealth": lambda x: x.wealth})
# create a single bank for the model
self.bank = Bank(1, self, self.reserve_percent)
# create people for the model according to number of people set by user
for i in range(self.init_people):
# set x, y coords randomly within the grid
x = self.random.randrange(self.width)
y = self.random.randrange(self.height)
p = Person(i, (x, y), self, True, self.bank, self.rich_threshold)
# place the Person object on the grid at coordinates (x, y)
self.grid.place_agent(p, (x, y))
# add the Person object to the model schedule
self.schedule.add(p)
self.running = True
self.datacollector.collect(self)
def step(self):
# tell all the agents in the model to run their step function
self.schedule.step()
# collect data
self.datacollector.collect(self)
def run_model(self):
for i in range(self.run_time):
self.step()
示例11: DDAModel
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class DDAModel(Model):
"""A simple DDA model"""
_width = _WIDTH # width and height of the world. These shouldn't be changed
_height = _HEIGHT
def __init__(self, N, iterations, bleedout_rate=np.random.normal(0.5, scale=0.1), mp=False):
"""
Create a new instance of the DDA model.
Parameters:
N - the number of agents
iterations - the number of iterations to run the model for
blr - the bleedout rate (the probability that agents leave at the midpoint) (default normal distribution
with mean=0.5 and sd=0.1)
mp - whether to use multiprocess (agents call step() method at same time) (doesn't work!) (default False)
"""
self.num_agents = N
self._bleedout_rate = bleedout_rate
self.iterations = iterations
self.mp = mp
# Locations of important parts of the environment. These shouldn't be changed
self.graveyard = (0, 0) # x,y locations of the graveyard
self.loc_a = (1, 0) # Location a (on left side of street)
self.loc_b = (23, 0) # Location b (on the right side)
self.loc_mid = (12, 0) # The midpoint
# 'Cameras' that store the number of agents who pass them over the course of an hour. The historical counts
# are saved by mesa using the DataCollector
self._camera_a = 0 # Camera A
self._camera_b = 0 # Camera B
self._camera_m = 0 # The midpoint
# Set up the scheduler. Note that this isn't actually used (see below re. agent's stepping)
self.schedule = RandomActivation(self) # Random order for calling agent's step methods
# For multiprocess step method
self.pool = Pool()
# Create the environment
self.grid = MultiGrid(DDAModel._width, DDAModel._height, False)
# Define a variable that can be used to indicate whether the model has finished
self.running = True
# Create a distribution that tells us the number of agents to be added to the world at each
self._agent_dist = DDAModel._make_agent_distribution(N)
# Create all the agents
for i in range(self.num_agents):
a = DDAAgent(i, self)
self.schedule.add(a) # Add the agents to the schedule
# All agents start as 'retired' in the graveyard
a.state = AgentStates.RETIRED
self.grid.place_agent(a, self.graveyard) # All agents start in the graveyard
print("Created {} agents".format(len(self.schedule.agents)))
# Define a collector for model data
self.datacollector = DataCollector(
model_reporters={"Bleedout rate": lambda m: m.bleedout_rate,
"Number of active agents": lambda m: len(m.active_agents()),
"Camera A counts": lambda m: m.camera_a,
"Camera B counts": lambda m: m.camera_b,
"Camera M counts": lambda m: m.camera_m
},
agent_reporters={"Location (x)": lambda agent: agent.pos[0],
"State": lambda agent: agent.state
}
)
def step(self):
"""Advance the model by one step."""
print("Iteration {}".format(self.schedule.steps))
self.datacollector.collect(self) # Collect data about the model
# See if the model has finished running.
if self.schedule.steps >= self.iterations:
self.running = False
return
# Things to do every hour.
# - 1 - reset the camera counters
# - 2 - activate some agents
num_to_activate = -1
s = self.schedule.steps # Number of steps (for convenience)
if s % 60 == 0: # On the hour
# Reset the cameras
self._reset_cameras()
# Calculate the number of agents to activate
num_to_activate = int(self._agent_dist[int((s / 60) % 24)])
print("\tActivating {} agents on hour {}".format(num_to_activate, s % 60))
else:
num_to_activate = 0
assert num_to_activate >= 0, \
#.........这里部分代码省略.........
示例12: Trade
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
#.........这里部分代码省略.........
self.prices = prices
e = {} # Embeddedness
for i in range(ini_sellers):
e[i] = 0.8*np.random.rand() + 0.2 # 0.2 - 1.0
for i in range(self.num_w):
e[i] = 0
self.e = e
'''Create buyers'''
for i in range(self.ini_buyers):
# It seems coincidence in the same cell is allowed
x = np.random.randint(self.width)
y = np.random.randint(self.height)
α = d['alpha']
trust = {}
β = d['beta']*np.random.rand()
for j in range(ini_sellers):
trust[j] = np.random.rand()
for j in range(self.num_w):
trust[j] = self.trust_w
γ = d['gamma']
'''
Network ties
ties[j]=0 means 'no connection with bid=j buyer'
ties[own bid] = 0 or 1 means nothing.
'''
ties = dict(zip(range(ini_buyers),[0]*ini_buyers))
buyer = Buyer(i, self.grid, (x, y), True, α, trust, β, γ, ties)
self.buyers[i] = buyer # Dictionary key is an integer
self.grid.place_agent(buyer, (x, y))
self.schedule.add(buyer)
'''Create sellers'''
for i in range(self.ini_sellers):
x = np.random.randint(self.width)
y = np.random.randint(self.height)
cash = self.ini_cash
costs = self.costs
price = self.prices[i]
w = False
if i < self.num_w:
w = True
e = self.e[i]
seller = Seller(i, self.grid, (x, y), True, cash, costs, price, w, e)
self.sellers[i] = seller
self.grid.place_agent(seller, (x, y))
self.schedule.add(seller)
self.running = True
def step(self):
'''Initialization'''
self.cnt += 1
self.sid_alive = [] # Excluding Wal-Mart
for sid, seller in self.sellers.items():
if seller.csa == False:
'''Adjacent sales'''
seller.sales = 0
'''Customer list'''
示例13: Movement
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class Movement(Model):
def __init__(self, width = 0, height = 0, torus = False,
time = 0, step_in_year = 0,
number_of_families = family_setting, number_of_monkeys = 0, monkey_birth_count = 0,
monkey_death_count = 0, monkey_id_count = 0,
number_of_humans = 0, grid_type = human_setting, run_type = run_setting, human_id_count = 0):
# change the # of families here for graph.py, but use server.py to change # of families in the movement model
# torus = False means monkey movement can't 'wrap around' edges
super().__init__()
self.width = width
self.height = height
self.time = time # time increases by 1/73 (decimal) each step
self.step_in_year = step_in_year # 1-73; each step is 5 days, and 5 * 73 = 365 days in a year
self.number_of_families = number_of_families
self.number_of_monkeys = number_of_monkeys # total, not in each family
self.monkey_birth_count = monkey_birth_count
self.monkey_death_count = monkey_death_count
self.monkey_id_count = monkey_id_count
self.number_of_humans = number_of_humans
self.grid_type = grid_type # string 'with_humans' or 'without_humans'
self.run_type = run_type # string with 'normal_run' or 'first_run'
self.human_id_count = human_id_count
# width = self._readASCII(vegetation_file)[1] # width as listed at the beginning of the ASCII file
# height = self._readASCII(vegetation_file)[2] # height as listed at the beginning of the ASCII file
width = 85
height = 100
self.grid = MultiGrid(width, height, torus) # creates environmental grid, sets schedule
# MultiGrid is a Mesa function that sets up the grid; options are between SingleGrid and MultiGrid
# MultiGrid allows you to put multiple layers on the grid
self.schedule = RandomActivation(self) # Mesa: Random vs. Staged Activation
# similar to NetLogo's Ask Agents - determines order (or lack of) in which each agents act
empty_masterdict = {'Outside_FNNR': [], 'Elevation_Out_of_Bound': [], 'Household': [], 'PES': [], 'Farm': [],
'Forest': [], 'Bamboo': [], 'Coniferous': [], 'Broadleaf': [], 'Mixed': [], 'Lichen': [],
'Deciduous': [], 'Shrublands': [], 'Clouds': [], 'Farmland': []}
# generate land
if self.run_type == 'first_run':
gridlist = self._readASCII(vegetation_file)[0] # list of all coordinate values; see readASCII function
gridlist2 = self._readASCII(elevation_file)[0] # list of all elevation values
gridlist3 = self._readASCII(household_file)[0] # list of all household coordinate values
gridlist4 = self._readASCII(pes_file)[0] # list of all PES coordinate values
gridlist5 = self._readASCII(farm_file)[0] # list of all farm coordinate values
gridlist6 = self._readASCII(forest_file)[0] # list of all managed forest coordinate values
# The '_populate' function below builds the environmental grid.
for x in [Elevation_Out_of_Bound]:
self._populate(empty_masterdict, gridlist2, x, width, height)
for x in [Household]:
self._populate(empty_masterdict, gridlist3, x, width, height)
for x in [PES]:
self._populate(empty_masterdict, gridlist4, x, width, height)
for x in [Farm]:
self._populate(empty_masterdict, gridlist5, x, width, height)
for x in [Forest]:
self._populate(empty_masterdict, gridlist6, x, width, height)
for x in [Bamboo, Coniferous, Broadleaf, Mixed, Lichen, Deciduous,
Shrublands, Clouds, Farmland, Outside_FNNR]:
self._populate(empty_masterdict, gridlist, x, width, height)
self.saveLoad(empty_masterdict, 'masterdict_veg', 'save')
self.saveLoad(self.grid, 'grid_veg', 'save')
self.saveLoad(self.schedule, 'schedule_veg', 'save')
# Pickling below
load_dict = {} # placeholder for model parameters, leave this here even though it does nothing
if self.grid_type == 'with_humans':
empty_masterdict = self.saveLoad(load_dict, 'masterdict_veg', 'load')
self.grid = self.saveLoad(self.grid, 'grid_veg', 'load')
if self.grid_type == 'without_humans':
empty_masterdict = self.saveLoad(load_dict, 'masterdict_without_humans', 'load')
self.grid = self.saveLoad(load_dict, 'grid_without_humans', 'load')
masterdict = empty_masterdict
startinglist = masterdict['Broadleaf'] + masterdict['Mixed'] + masterdict['Deciduous']
# Agents will start out in high-probability areas.
for coordinate in masterdict['Elevation_Out_of_Bound'] + masterdict['Household'] + masterdict['PES'] \
+ masterdict['Farm'] + masterdict['Forest']:
if coordinate in startinglist:
startinglist.remove(coordinate)
# Creation of resources (yellow dots in simulation)
# These include Fuelwood, Herbs, Bamboo, etc., but right now resource type and frequency are not used
if self.grid_type == 'with_humans':
for line in _readCSV('hh_survey.csv')[1:]: # see 'hh_survey.csv'
hh_id_match = int(line[0])
resource_name = line[1] # frequency is monthly; currently not-used
frequency = float(line[2]) / 6 # divided by 6 for 5-day frequency, as opposed to 30-day (1 month)
y = int(line[5])
x = int(line[6])
resource = Resource(_readCSV('hh_survey.csv')[1:].index(line),
self, (x, y), hh_id_match, resource_name, frequency)
self.grid.place_agent(resource, (int(x), int(y)))
resource_dict.setdefault(hh_id_match, []).append(resource)
if self.run_type == 'first_run':
self.saveLoad(resource_dict, 'resource_dict', 'save')
#.........这里部分代码省略.........
示例14: SugarscapeModel
# 需要导入模块: from mesa.space import MultiGrid [as 别名]
# 或者: from mesa.space.MultiGrid import place_agent [as 别名]
class SugarscapeModel(Model):
def __init__(self, height=50, width=50, init_agents=500, max_metabolism=3, max_vision=10, max_init_sugar=5, min_age=30, max_age=60, init_poll=3, ex_ratio=2, ex_mod=1, poll_growth_rule=True, inheritance_rule=True):
self.height = height
self.width = width
self.init_agents = init_agents
self.init_poll = init_poll
self.max_metabolism = max_metabolism
self.max_vision = max_vision
self.max_init_sugar = max_init_sugar
self.min_age = min_age
self.max_age = max_age
self.ex_ratio = ex_ratio
self.ex_mod = ex_mod
self.replacement_rule = True
self.pollution_rule = False
self.diffusion_rule = False
self.push_rule = False
self.poll_growth_rule = poll_growth_rule
self.expend_rule = True
self.inheritance_rule = inheritance_rule
self.map = self.import_map()
self.grid = MultiGrid(height, width, torus=True)
self.schedule = RandomActivationByType(self)
self.datacollector = DataCollector({'Pollution': (lambda m: m.total_pollution),
'Wealth': (lambda m: m.total_wealth/m.init_agents),
'Agents': (lambda m: len(m.schedule.agents_by_type[ScapeAgent]))},
{'Wealth': self.collect_wealth,
'Metabolism': self.collect_metabolism,
'Vision': self.collect_vision})
self.total_wealth = 0
self.total_pollution = 0
self.populate_sugar()
self.populate_agents()
def step(self):
''' Step method run by the visualization module'''
self.schedule.step([ScapeAgent, SugarPatch])
self.datacollector.collect(self)
# if self.schedule.time == 20:
# self.pollution_rule = True
if self.schedule.time == 30:
self.push_rule = True
self.total_wealth = 0
self.total_pollution = 0
for agent in self.schedule.agents_by_type[ScapeAgent]:
self.total_wealth += agent.wealth
for patch in self.schedule.agents_by_type[SugarPatch]:
self.total_pollution += patch.pollution
def import_map(self):
''' Imports a text file into an array to be used when generating and
placing the sugar Agents into the grid
'''
f = open('Maps/sugar_map.txt', 'r')
map_list = []
for line in f:
num_list = line.split(' ')
for num in num_list:
map_list.append(int(num[0]))
return map_list
def new_agent(self, uid, inheritance):
''' Place a new agent on the sugarscape in order to replace a death'''
free = False
while not free:
location = random.choice([cell for cell in self.grid.coord_iter()])
if len(location[0]) == 1:
free = True
pos = (location[1], location[2])
patch = self.grid.get_cell_list_contents([pos])[0]
if self.inheritance_rule:
if inheritance == 'rand':
wealth = random.randint(1, self.max_init_sugar)
else:
wealth = inheritance
else:
wealth = random.randint(1, self.max_init_sugar)
agent = ScapeAgent(uid, pos, wealth, random.randint(1,self.max_metabolism), random.randint(1,self.max_vision), random.randint(self.min_age, self.max_age), patch, self.ex_ratio, self.ex_mod)
self.grid.place_agent(agent, agent.pos)
self.schedule.add(agent)
def populate_agents(self):
''' Place ScapeAgent's in random unoccupied locations on the grid with randomomized
sets of parameters
'''
cells = [(cell[1], cell[2]) for cell in self.grid.coord_iter()]
#.........这里部分代码省略.........