def test_distance_between():
    environment = [0, 0, 0, 0]
    agent1 = [0, 0, 0, 0]
    agent2 = [5, 3, 3, 5]
    agent = agentframework.Agent(environment, agent1)
    agent1_2 = agentframework.Agent(environment, agent2)
    assert distance_between(agent, agent) == 0
    assert distance_between(agent1_2, agent) != 0
Example #2
0
def run():
    # To allow the model to be run multiple times with differing variables, without closing down the window, the agents and environment need to be cleared.
    # Otherwise, the agents will be appened with the new value, meaning there will be more agents than actually appear, so they wouldn't move correctly.
    agents.clear()
    #environment.clear()
    global environment
    environment = import_csv()
    # Gets the three user defined values from the GUI spinboxes.
    global num_of_iterations
    num_of_iterations = int(noit.get())
    print("Iterations = " + noit.get())
    global num_of_agents
    num_of_agents = int(noag.get())
    print("Agents = " + noag.get())
    global neighbourhood
    neighbourhood = int(neigh.get())
    print("Neighbourhood = " + neigh.get())
    # Make the agents with x/y values from the web scraped data
    for i in range(num_of_agents):
        y = int(td_ys[i].text)
        x = int(td_xs[i].text)
        # Generating a 6 digit hexidecimal number to assign a colour to each agent.
        # Without this, the colour of each agent changes because of random.shuffle in the update function.
        hex_number = '#{:02x}{:02x}{:02x}'.format(
            *map(lambda x: random.randint(0, 255), range(3)))
        agents.append(
            agentframework.Agent(environment, agents, x, y, hex_number))
# global animation
    animation = matplotlib.animation.FuncAnimation(fig,
                                                   update,
                                                   frames=gen_function,
                                                   repeat=False)
    print("2", len(agents))
    canvas.draw()
Example #3
0
    def _create_agents(self):
        """
        Generate new set of agents using the current model parameters

        Returns
        -------
        None.

        """

        # Reset the current agents list
        self.agents = []

        # Get the initial start positions
        start_xs, start_ys = self.start_positions

        # Create all agents
        for i in range(self.num_of_agents):

            # Get the initial start position
            y = int(start_ys[i].text if len(start_ys) > i else random.
                    randint(0, self.environment.y_length - 1))
            x = int(start_xs[i].text if len(start_xs) > i else random.
                    randint(0, self.environment.x_length - 1))

            # Add new Agent to the model
            self.agents.append(
                agentframework.Agent(self.environment, self.agents, y, x,
                                     self.agent_store_size,
                                     self.agent_bite_size))
Example #4
0
def setup_agents():
    '''
    Function to set up Class Agent (sheep) and Class Dogs (sheepdogs) using values from GUI sliders
    Initalise sheep and sheepdogs into the agentframework
    
    Returns:
        if uncommented, prints number of sheep and number of wolves, as selected on GUI slider
    '''
    global num_of_agents  # global variable defining number of sheep updated by value on GUI slider
    global num_of_dogs  # global variable defining number of sheepdogs updated by value on GUI slider
    num_of_agents = slide1.get()
    num_of_dogs = slide2.get()
    print('Total number of Agents (sheep):', num_of_agents)
    print('Total number of sheepdogs:', num_of_dogs)

    # Make the sheep
    for i in range(num_of_agents):
        agents.append(agentframework.Agent(environment, agents, dogs))
#        print('agents:', agents[i])

#    # check sheep can return info about a different sheep
#    print('Agent 6 from agent 1 point of view', agents[1].agents[6].x)

# Make the sheep dogs
    for i in range(num_of_dogs):
        y = int(td_ys[i].text)  # integer obtained from html file
        x = int(td_xs[i].text)  # integer obtained from html file
        dogs.append(agentframework.Dog(environment, agents, dogs, y, x))
Example #5
0
def update(frame_number):  # Module for creating animation

    fig.clear()

    # Make the agents.

    for i in range(num_of_agents):  # Repeat for number of agents
        y = int(
            td_ys[i].text)  # Extracts the y value from the rest of the text
        x = int(
            td_xs[i].text)  # Extracts the x value from the rest of the text
        agents.append(agentframework.Agent(
            agents, environment, y,
            x))  # Pass arguments to module and return result into a

# Move the agents.

    for j in range(num_of_iterations):  # For each entry do...
        for i in range(num_of_agents):  # For each entry do...
            agents[i].move()  # Move the agent
            agents[i].eat()  # Eat the agent
            agents[i].share_with_neighbours(neighbourhood)

# Plot points

    matplotlib.pyplot.xlim(0, int(max(
        environment[1])))  # Set the extent of the Y axis
    matplotlib.pyplot.ylim(0, int(max(
        environment[0])))  # Set the extent of the X axis
    matplotlib.pyplot.imshow(environment)
    for i in range(num_of_agents):
        matplotlib.pyplot.scatter(agents[i].x, agents[i].y)
Example #6
0
def test_distance_between():
    """ 
    Testing the  "distance_between()" function by adding two agents to the 
    "agents_list" and then ensuring that there is a distance between the first
    and second agent, whereas there is no distance between the second agent and 
    itself. 
    """
    environment = [[2, 2], [2, 2]]

    agents_list = []
    agents_list.append(agentframework.Agent(environment, agents_list, 0, 0))
    agents_list.append(agentframework.Agent(environment, agents_list, 0, 1))

    assert agents_list[0].distance_between(
        agents_list[1]) == 1, "There is a distance!"
    assert agents_list[1].distance_between(
        agents_list[1]) == 0, "There is no distance!"
Example #7
0
def create_agents(num_agents):
    agents = []
    for i in range(num_agents):
        if i < len(td_ys):
            y = int(td_ys[i].text)
            x = int(td_xs[i].text)
            agents.append(
                ag.Agent(environment_initial, agents, y_value=y, x_value=x))
        else:  #add random agents if data too small.
            agents.append(ag.Agent(environment_initial, agents))
    #check if there is enough data for all the agents, if not warn user of random coordinates:
    if num_agents > len(td_xs):
        print(
            'Warning : The number of agents exeeds the ' + str(len(td_xs)) +
            ' available coordinates in sourced data. Random coordinates were allocated to '
            + str(num_agents - len(td_xs)) + ' agents.')
    return (agents)
Example #8
0
def sel():

    global num_of_agents
    num_of_agents = agentslider.get()   #This allows the number of agents to be defined by the slider on the GUI interface

#Creating agent loop#
    for i in range(num_of_agents):
        y = int(td_ys[i].text)
        x = int(td_xs[i].text)
        agents.append(agentframework.Agent(environment, agents, y, x))
Example #9
0
def run():
    """Reads in parameters from silders and checkboxes and initiates the animation to be plotted."""

    # initialise
    global num_agents
    global max_age
    global optimised_movement
    global breed
    global min_age_for_preg
    global preg_duration
    global agents

    # makes the button reusable
    global carry_on
    carry_on = True
    # re-import the clean environment for every run of the simulation
    global environment 
    environment = import_environment()

    # read in simulation parameters from the GUI widgets
    optimised_movement = opt_var.get()
    breed = babies_var.get()
    max_age = max_age_slider.get()
    min_age_for_preg = min_preg_age_slider.get()
    preg_duration = preg_duration_slider.get()
    num_agents = n_slider.get()

    # create initial list of agents
    agents = []
    for _ in range(num_agents):
        agents.append(af.Agent(environment,agents)) 
    
    # print parameters to console
    print(
    '\n#### Run started with parameters:\n\
    {} agents\n\
    {} max age\n\
    {} movement\n\
    {} breeding\n\
    {} minimum age for pregnancy\n\
    {} duration of pregnancy\n'\
        .format(
        num_agents,
        max_age,
        ('Optimised' if optimised_movement else 'Random'),
        ('Enabled' if breed else 'Disabled'),
        min_age_for_preg,
        preg_duration
        )
    )

    # run animation
    animation = anim.FuncAnimation(fig, update, frames=gen_function, repeat=False)
    # and place it into the GUI
    anim_placeholder.draw()
Example #10
0
def run():
    for i in range(num_of_agents):
        agents.append(agentframework.Agent(random.randint(0,yrange)\
        , random.randint(0,xrange), environment, agents, neighbourhood))

    animation = matplotlib.animation.FuncAnimation(fig,
                                                   update,
                                                   frames=gen_function,
                                                   interval=1,
                                                   repeat=False)
    canvas.draw()
Example #11
0
def update(frame_number):

    fig.clear()
    global carry_on

    # Omnivorous move, eat and share.
    for j in range(num_of_iterations):
        for i in range(num_of_agents):
            agents[i].move()
            agents[i].eat()
            agents[i].share_with_neighbours(neighbourhood)

# Vegetarians move and convinced omnivorous to be vegetarians.
    for j in range(num_of_iterations):
        for l in range(num_of_agents2):
            agents2[l].move()
            a_chased = agents2[l].chase(ep_area, agents)

        for k in a_chased:
            chased.append(agentframework.Agent(environment, agents))
            agents.remove(k)

#Setting the Stopping condition
#when there is iqual o more number of omnivorous transformed in vegetarians
    if (len(agents2) == len(chased)) | (len(agents2) < len(chased)):
        carry_on = False
        print("stopping condition")

#Animation
#Displaying environment data
    pyp.xlim(0, 100)
    pyp.ylim(0, 100)
    pyp.imshow(environment)
    for a in agents:
        pyp.scatter(a.x, a.y, c="red", marker="+")
        #print(a.x,a.y)
    for b in agents2:
        pyp.scatter(b.x, b.y, c="green", marker="D")
        #print(b.x,b.y)
#Print converted vegetarians
    for c in chased:
        pyp.scatter(c.x, c.y, c="blue", marker="d")
def update(frame_number):
    
    fig.clear()   
   

    for i in range(num_of_agents):
        agents.append(agentframework.Agent(environment,agents))



# Move and eat agents with every move or iteration.
    for j in range(num_of_iterations):
        for i in range(num_of_agents):
            agents[i].move()
            agents[i].eat()
            agents[i].share_with_neighbours(neighbourhood)
            
            
        
   
        
        
# Loop through the agents in self.agents .
    # Calculate the distance between self and the current other agent:
    # distance = self.distance_between(agent) 
    # If distance is less than or equal to the neighbourhood
        # Sum self.store and agent.store .
        # Divide sum by two to calculate average.
        # self.store = average
            # agent.store = average
    # End if
# End loop         
      
      
       
    
# plot
    matplotlib.pyplot.xlim(0, 299)
    matplotlib.pyplot.ylim(0, 299)
    for i in range(num_of_agents):
        matplotlib.pyplot.scatter(agents[i].x,agents[i].y)    
    matplotlib.pyplot.imshow(environment)    
Example #13
0
def makeAgents(num_of_agents):
    agentslist = []
    # Initialisation - Make the agents.
    for i in range(num_of_agents):
        y = int(td_xs[i].text)
        x = int(td_ys[i].text)
        agents.append(agentframework.Agent(y, x, environment, agentslist))

    # List of agents
    for i in range(num_of_agents):
        agentslist = (agents[i].y, agents[i].x)
        #Test that agents are returning other agents positions
        print(agents[2], agentslist)

    # Total number of agents check
    num_of_agents = len(agents)
    print("num_of_agents", num_of_agents)

    # Print out agents
    for i in range(num_of_agents):
        print(agents[i])
Example #14
0
def sel():
    
    global num_of_agents
    global td_ys
    global td_xs
    global agents
    global wolf_agents
    num_of_agents = w.get()
    # Pass in agents from web scrape, environment variable (and self as always).
    for i in range(num_of_agents):
        y = int(td_ys[i].text)
        x = int(td_xs[i].text)
        #print(x, y)
        agents.append(agentframework.Agent(environment, agents, y, x))
        
        
    for i in range(num_of_agents):
        y = random.randint(0,100)
        x = random.randint(0,100)
        #print(x, y)
        wolf_agents.append(agentframework.wolf_agent(environment, wolf_agents, agents, y, x))
Example #15
0
def update(frame_number):  # Module for creating animation

    fig.clear()
    #    global carry_on

    # Make the agents.

    for i in range(num_of_agents):  # Repeat for number of agents
        a = agentframework.Agent(
            agents,
            environment)  # Pass arguments to module and return result into a
        agents.append(a)  # Apend a to end of List

# Move the agents.

    for j in range(num_of_iterations):
        for i in range(num_of_agents):
            agents[i].move()
            agents[i].eat()
            agents[i].share_with_neighbours(neighbourhood)


#def gen_function(b = [0]):
#    a = 0
#    global carry_on #Not actually needed as we're not assigning, but clearer
#    while (a < 10) & (carry_on) :
#        yield a			# Returns control and waits next call.
#        a = a + 1

#Plot points

#   maxy = int(max(environment[1]))            # Get maximum value of Y
#   maxx = int(max(environment[0]))            # Get maximum value of x
    matplotlib.pyplot.xlim(0, int(max(
        environment[1])))  # Set the extent of the Y axis
    matplotlib.pyplot.ylim(0, int(max(
        environment[0])))  # Set the extent of the X axis
    matplotlib.pyplot.imshow(environment)
    for i in range(num_of_agents):
        matplotlib.pyplot.scatter(agents[i].x, agents[i].y)
Example #16
0
def update(frame_number):

    fig.clear()
    global carry_on

    #Reads in the data file with environment data.
    f = open("in.txt", newline='')  # Opens file in.txt.
    reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)  #Reader
    for row in reader:  #list of rows
        rowlist = []
        environment.append(rowlist)
        for value in row:  #list of values.
            rowlist.append(value)
    #f.close() #Closes in.txt file after processing.

    # Sets up agents with environment data,y and x.
    for i in range(num_of_agents):
        y = int(td_ys[i].text)
        x = int(td_xs[i].text)
        agents.append(agentframework.Agent(environment, agents, y, x))
        #Print (y)
        #Print (x)

    #Agent random walk,eat,share using loop.
    for j in range(num_of_iterations):
        for i in range(num_of_agents):
            random.shuffle(agents)
            agents[i].move()
            agents[i].eat()
            agents[i].share_with_neighbours(neighbourhood)

    #Random stop model for model.
    if random.random() < 0.1:
        carry_on = False
        print("stopping condition")
    matplotlib.pyplot.xlim(0, 99)
    matplotlib.pyplot.ylim(0, 99)
    matplotlib.pyplot.imshow(environment)
    for i in range(num_of_agents):
        matplotlib.pyplot.scatter(agents[i].x, agents[i].y)
Example #17
0
def initialise_agents(num_of_agents, environment):
    """
    Create our agents.

    Parameters
    ----------
    environment : 2D list
        Represents the environment of our agents. Number of rows must equal 
        the number of columns (square matrix).
    size : int
        Size/dimension of 2D list.

    Returns
    -------
    agents : list of Agent()
        List of Agent() class.

    """
    agents = []
    # Make the agents.
    for i in range(num_of_agents):
        agents.append(agentframework.Agent(environment, agents))
    return agents
Example #18
0
def setup():
    #this is done to allow for connection with scale bar
    global num_of_agents
    #global allows to be seen outside of def function, agents=sheep
    num_of_agents = scale_sheep.get()
    #number of agents, connecting with scale bar
    global num_of_wolves
    #number of wolves
    num_of_wolves = scale_wolves.get()
    #set number of wolves
    global wolves
    #make wolves global
    wolves = []
    #makes wolves list
    global agents
    #makes agents global
    agents = []
    # Make the agents list

    for i in range(num_of_agents):
        #setting x y for sheep
        y = int(td_ys[i].text)
        #grabing text from html
        x = int(td_xs[i].text)
        #grabing text from html
        agents.append(agentframework.Agent(environment, agents, wolves, x, y))
        #connects agents to the environment, and grabs from framework
        #print(agents[i])

    for i in range(num_of_wolves):
        #seeting up num of wolves
        x = random.randint(150, 199)
        #seting wolves random starting x coordinate
        y = random.randint(0, 50)
        #setting agents random y starting points
        wolves.append(agentframework.Wolf(environment, wolves, agents, x, y))
Example #19
0
def update(frame_number):
    fig.clear()
    global carry_on
    #Fill the agents list.
    for i in range(num_of_agents):
        agents.append(agentframework.Agent(environment, agents))

    #Shuffle the order in which we look through our agents. Move the agents, make them eat the environment and share food collected with their neighbours.
    for j in range(num_of_iterations):
        for i in range(num_of_agents):
            shuffle(agents)
            agents[i].move()
            agents[i].eat()
            agents[i].share_with_neighbours(neighbourhood)
    #Ensure that if the agent eats more than 90 food then the model stops.
    if object1.agent_eats > 90:
        carry_on = False
        print("stopping condition")
    #Plot the model linking the agents and placing them on the environment to interact with it.
    matplotlib.pyplot.xlim(0, 99)
    matplotlib.pyplot.ylim(0, 99)
    matplotlib.pyplot.imshow(environment)
    for i in range(num_of_agents):
        matplotlib.pyplot.scatter(agents[i].x, agents[i].y)
Example #20
0
import matplotlib.pyplot
import agentframework


def distance_between(agents_row_a, agents_row_b):
    return (((agents_row_a.x - agents_row_b.x)**2) +
            ((agents_row_a.y - agents_row_b.y)**2))**0.5


num_of_agents = 10
num_of_iterations = 100
agents = []

# Make the agents.
for i in range(num_of_agents):
    agents.append(agentframework.Agent())

# Move the agents.
for j in range(num_of_iterations):
    for i in range(num_of_agents):
        agents[i].move()  # uses the move method from class Agents.

matplotlib.pyplot.xlim(0, 99)
matplotlib.pyplot.ylim(0, 99)
for i in range(num_of_agents):
    matplotlib.pyplot.scatter(
        agents[i].x,
        agents[i].y)  # as in line 7 and 8 pulls from Agents class.
matplotlib.pyplot.show()

for agents_row_a in agents:
Example #21
0

# Create the environments list by reading data from a text file.
# Used the csv import to parse the text file as it is comma seperated.
with open("assets/in.txt") as f:
    reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
    for row in reader:
        rowlist = []
        for value in row:
            rowlist.append(value)
        environment.append(rowlist)


# Create the agents list with the environment
for i in range(num_of_agents):
    agents.append(agentframework.Agent(environment))


# Move the agents.
for j in range(num_of_iterations):
    for i in range(num_of_agents):
        agents[i].move()
        agents[i].eat()


# Plot the agents
matplotlib.pyplot.xlim(0, 99)
matplotlib.pyplot.ylim(0, 99)
matplotlib.pyplot.imshow(environment)
for i in range(num_of_agents):
    matplotlib.pyplot.scatter(agents[i]._x, agents[i]._y)
f.close()  # Don't close until you are done with the reader;
# the data is read on request.

# Parameters
agents = []
num_of_agents = 25
num_of_iterations = 15
neighbourhood = 20

# Plotting settings?
fig = matplotlib.pyplot.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1])

# creating agents in a container
for i in range(num_of_agents):
    agents.append(agentframework.Agent(environment, agents, neighbourhood))


#Movement, eating and sharing
# Defining a function to be called in the animation commando further below
def update(frame_number):

    fig.clear()

    for j in range(num_of_agents):
        random.shuffle(agents)  # Shuffles the list in every new iteration
        for i in range(num_of_iterations):
            agents[j].move()
            agents[j].eat()
            agents[j].share_with_neighbours(neighbourhood)
Example #23
0
num_of_iterations = 10

#Agents object
agents = []

#Create a neighbourhood for each agent, this is 20 units distance
neighbourhood = 20
"""Create the agents"""
#For-Loop to append the agents to move randomly within the environment
#ranging from 0 to 99
print("Create Agents")
#Print the co-ordinates for the agents with co-ordinates from data.html
for i in range(num_of_agents):
    y = int(td_ys[i].text)  #make td_ys into integer data
    x = int(td_xs[i].text)  #make td_xs into integer data
    agents.append(agentframework.Agent(i, environment, agents, x, y))
print(i)  #prints number of agents from data.html minus 1
i = i + 1

#Below prints co-ordinates for an agent with known co-ordinates
agents.append(agentframework.Agent(i, environment, agents, 50, 50))
i = i + 1
#Below prints co-ordinates for another agent with known co-ordinates
agents.append(agentframework.Agent(i, environment, agents, 51, 51))
print("num_of_agents", num_of_agents)  #prints agents with co-ordinates from
#data.html

num_of_agents = len(agents)
print("num_of_agents", num_of_agents)  #prints total number of agents
for i in range(num_of_agents):
    print("Agent Starting co-ordinates, and store value")
def update(frame_number):
    """Determines the code that should be run for each frame of the matplotlib animation.
    
    Return:
    None
    """
    fig.clear()
    global carry_on

    # Loops for running the behaviour and interactions of the agents.
    # Print statements used for testing.
    for j in range(num_of_iterations):
        # Shuffle function used to randomise the order sheep are processed with each iteration.
        random.shuffle(sheep)
        print("Number of sheep is " + str(len(sheep)))

        # Interactions if more than 1 sheep.
        if len(sheep) > 1:
            for i in range(len(sheep) - 1):
                sheep[i].move()
                sheep[i].eat()
                sheep[i].share_with_neighbours(neighbourhood)
                sheep[i].lambing(lamb_distance)
                if sheep[i].lambing(lamb_distance) == "Lamb":
                    sheep.append(agentframework.Agent(environment, sheep))
                    print("Sheep added")
                    print(len(sheep))
                    print("Sheep moved")
            # Wolf movements and interactions.
            for k in range(num_of_wolves):
                wolves[k].move()
                wolves[k].hunting(hunting_distance, sheep)
                if wolves[k].hunting(hunting_distance, sheep) == "Hunted":
                    del (sheep[0])
                    print("Sheep eaten")
                    print(len(sheep))
            # Stopping condition for animation if all sheep are eaten.
            if len(sheep) == 0:
                carry_on = False
                print("All sheep have been eaten")
                break
            # Stopping condition for animation if number of sheep is greater than or equal to 100.
            if len(sheep) >= 100:
                carry_on = False
                print("100 or more sheep in the field!")
                break
        else:
            for i in range(1):
                sheep[i].move()
                sheep[i].eat()
            # Wolf movements and interactions.
            for k in range(num_of_wolves):
                wolves[k].move()
                wolves[k].hunting(hunting_distance, sheep)
                if wolves[k].hunting(hunting_distance, sheep) == "Hunted":
                    del (sheep[0])
                    print("Sheep eaten")
                    print(len(sheep))
            # Stopping condition for animation if all sheep are eaten.
            if len(sheep) == 0:
                carry_on = False
                print("All sheep have been eaten")
                break
            break
        break

    # Generate scatterplot of sheep and wolves after model iterations.
    matplotlib.pyplot.xlim(0, 99)
    matplotlib.pyplot.ylim(0, 99)

    for i in range(len(sheep)):
        matplotlib.pyplot.scatter(sheep[i].x, sheep[i].y, color='white')
        matplotlib.pyplot.imshow(environment)
    for j in range(num_of_wolves):
        matplotlib.pyplot.scatter(wolves[j].x, wolves[j].y, color='black')
        matplotlib.pyplot.imshow(environment)
lamb_distance = 8
hunting_distance = 10
sheep = []
wolves = []

# Variables to create the matplotlib window for the animation.
fig = matplotlib.pyplot.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1])

ax.set_autoscale_on(False)

# Make the agents.
# Addition of environment as argument for Agent class to allow interaction between agents and environment.
# Addition of agents as argument for Agent class to allow agents to interact with each other.
for i in range(num_of_sheep):
    sheep.append(agentframework.Agent(environment, sheep))

# Make the wolves.
# Use of environment and agents as arguments to allow interactions.
for i in range(num_of_wolves):
    wolves.append(agentframework.Wolves(environment, sheep, wolves))

# Setting carry_on variable for gen_function below.
carry_on = True


# Creating model animation.
def update(frame_number):
    """Determines the code that should be run for each frame of the matplotlib animation.
    
    Return:
random_seed = 50
neighbourhood = 20
#controlling how many agents there are:
num_of_agents = 10
#specify the number of times the agents are to be moved:
num_of_iterations = 100
#create list "agents":
agents = []

#make agents a random integer between inc 0 and 99 and add them to the list of agents
#takes agents created in "agentframework" module
#puts y and x coordinates in list "agents"
for i in range(num_of_agents):
    random_seed += 1
    agents.append(
        agentframework.Agent(random_seed, environment, neighbourhood, agents))
#print("agents created in framework and stored in agents list; number of agents created is determined by value assigned to num_of_agents:")
#print(agents[i])

#move the agents num_of_iterations times. "% 100" in "agentframework" creates torus environment, creating boundary to prevent agents leaving the space
for j in range(num_of_iterations):
    for i in range(num_of_agents):
        agents[i].move()
        agents[i].eat()
print("randomly moved the agents num_of_iterations times:")
#print(agents)

#call eat for each agent
for j in range(num_of_iterations):
    random.shuffle(agents)
    for i in range(num_of_agents):
# Read in the environment
reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
# Shift environment into a 2.D list
for row in reader:
    rowlist = []
    # Add each value to rowlist
    for value in row:
        rowlist.append(value)
# Attach rowlist to environment
    environment.append(rowlist)
# Close the file
f.close()

# Create a line of code to convince self that agentframeowrk file is connected
a = agentframework.Agent(environment, agents)
# print(a.x, a.y)

#Loop through and create the agents and append information about environment and other agents
# Make the agents.
for i in range(num_of_agents):
    agents.append(agentframework.Agent(environment, agents))


# Animating the model
# Create the update function
def update(frame_number):

    fig.clear()  # Clear figure
    global carry_on
Example #28
0
# Constructs the GUI slider.
def setup_agents():
    """The number of Sheep and Foxes in the environment are chosen by operating the slider."""
    global num_of_agents  # Global variable defines number of Sheep as selected using the slider.
    global num_of_foxes  # Global variable defines number of Foxes as selected using the slider.
    num_of_agents = sheepslider.get()
    num_of_foxes = foxesslider.get()
    print('Total Sheep chosen:',
          num_of_agents)  # Prints total number of Sheep as selected.
    print('Total Foxes chosen:',
          num_of_foxes)  # Prints total number of Foxes as selected.


# Initialise Agent (Sheep) Loop.
for i in range(num_of_agents):
    agents.append(agentframework.Agent(environment, agents, foxes))
#print('Agents:',agents[i]) # Prints to ensure Sheep xy coordinates are being generated.

# Initialise Foxes Loop against html-derived coordinates.
for i in range(num_of_foxes):
    y = int(td_ys[i].text
            )  # Foxes move according to the xy coordinates from the html file.
    x = int(td_xs[i].text)
    foxes.append(agentframework.Foxes(environment, agents, foxes, x, y))
#print('Foxes:',foxes[i]) # Prints to ensure Foxes xy coordinates are being generated.

# Agents (Sheep) move if the above specifications work.
carry_on = True  # A Boolean value; the animation carries on running unless told otherwise.


def distance_between(agents_row_a, agents_row_b):
Example #29
0
        rowlist = []
        for value in row:
            rowlist.append(value)
        environment.append(rowlist)  #add data to the environment iterable

### INITIALISE MODEL AND CHANGE FUNCTIONS ###

# initialise the agents
for i in range(num_of_agents):

    #set the x and y coordinates from the web scraped daa
    y = int(td_ys[i].text)
    x = int(td_xs[i].text)

    #give the agent environment, coordinates and add to list of agents
    agents.append(agentframework.Agent(environment, agents, y, x))


def update(frame_number):
    """
    Function to to move and interact agents with environment for each frame update
    """

    fig.clear()
    global carry_on
    global storeMax

    #This creates a loop to access each individual agent
    for i in range(num_of_agents):

        # Move the agents, consume the environment and share with other agents
Example #30
0
    Number
        Euclidean distance in a 2D space between a and b.
    """
    return (((a.x - b.x)**2) + ((a.y - b.y)**2))**0.5


# Initialise variables
num_of_agents = 10
num_of_iterations = 100
neighbourhood = 20

# Make the agents.
agents = []
for i in range(num_of_agents):
    agents.append(
        agentframework.Agent(i, random.randint(0, 99), random.randint(0, 99),
                             environment, agents))
    #print(agents[i]) # Check the agents are created
print("Initial agents")
for i in range(num_of_agents):
    print(agents[i])

## Test the distance function
#d = distance_between(agentframework.Agent(0, 0, environment, agents),
#agentframework.Agent(3, 4, environment, agents))
#print(d)

# Move the agents.
for j in range(num_of_iterations):
    for i in range(num_of_agents):
        agents[i].move()  # uses the move method from class Agent.
        agents[i].eat()  # uses the eat method in Agent class.