def test_get_circular_region_list(set_up_food_fixed, food_grid_indices=range(3)):
    tree, positions_dict = set_up_food_fixed
    food_grids = []
    for idx in food_grid_indices:
        food_grids.append(positions_dict["nested food"][idx])
    grid_info = positions_dict["food grid info"]

    radii = []
    centers = []
    for grid in grid_info:
        centers.append(grid[2])
        radii.append(grid[3])

    unique_radii = set(radii)
    radii = array(radii)  # because later elementwise == is used
    centers = array(centers)  # because later boolean index is used
    for radius in unique_radii:
        matching_centers = centers[radii == radius]
        result = tree.get_circular_region_list(matching_centers, radius)

        for i, circular_region in enumerate(result):
            compare_to_region = tree.get_circular_region(centers[i], radii[i])
            for obj in circular_region:
                assert (obj in compare_to_region)
            for obj in compare_to_region:
                assert (obj in circular_region)
Beispiel #2
0
    def __init__(self, width, height):
        pygame.init()
        display_info = pygame.display.Info()

        # Currently not used
        self.width = width
        self.height = height
        self.res_width = display_info.current_w
        self.res_height = display_info.current_h
        self.state = None

        # Only works for windows --> need to check operating system
        if platform.system() == 'Windows':
            from ctypes import windll
            windll.user32.SetProcessDPIAware()
            true_res = (windll.user32.GetSystemMetrics(0),
                        windll.user32.GetSystemMetrics(1))
            self.screen = pygame.display.set_mode(true_res, pygame.FULLSCREEN)

        else:
            self.screen = pygame.display.set_mode(
                (self.res_width, self.res_height), pygame.FULLSCREEN)

        self.background_color = pygame.Color("white")
        self.mouse_pos = pygame.mouse.get_pos()
        self.mouse_event = pygame.mouse.get_pressed()
        self.elements = {}
        self.event_dict = {}
        self.FONT = pygame.font.Font(None, 32)
        self.pos = [array([-500, 500]), array([500, -500])]
Beispiel #3
0
    def __init__(self, width, height):
        pygame.init()
        display_info = pygame.display.Info()
        self.res_width = display_info.current_w
        self.res_height = display_info.current_h
        self.win_height = height
        self.win_width = width
        self.width = width
        self.height = height

        self.screen = pygame.display.set_mode((self.width, self.height))
        self.fullscreenflag = False
        self.origwidth = self.width
        self.state = None

        # Only works for windows --> need to check operating system

        self.background_color = pygame.Color("white")
        self.mouse_pos = pygame.mouse.get_pos()
        self.mouse_event = pygame.mouse.get_pressed()
        self.elements = {}
        self.event_dict = {}
        self.FONT = pygame.font.Font(None, 32)
        self.pos = [array([-500, 500]), array([500, -500])]
        self.usercolor = None
def set_up_tree_nests_fixed():
    """Sets up nests at fixed position. Use this if you do not want two nests to be created at one position."""
    tree = KdTreeAndDict()
    positions = [array([5, 5]), array([-5, -5]), array([1000, 1000])]
    colors = ['red', 'green', 'blue']
    tree.create_nests(colors, positions, size=1, health=100)

    return tree, positions
Beispiel #5
0
def set_up_foods():
    player = Player("Nobody", (178, 58, 238))
    position = array([5., 5.])
    intensity = 20.
    pheromone1 = Pheromone(position, player, intensity)
    position = array([4., 5.])
    intensity = 10.
    pheromone2 = Pheromone(position, player, intensity)
    pheromones = [pheromone1, pheromone2]
    return pheromones
def test_get_k_nearest_list(set_up_food_fixed, position_list=(array([-9, -9]), array([0, 0]), array([9, 9]))):
    """Tests the get_k_nearest_list() function and calls compares by comparing to multiple get_k_nearest() calls"""
    tree, positions_dict = set_up_food_fixed
    position_list = list(position_list)
    # k >= 1
    for k in range(5):
        nearest_objects, dists = tree.get_k_nearest_list(position_list, k + 1)
        for i, obj_list in enumerate(nearest_objects):
            compare_to_obj, compare_to_dists = tree.get_k_nearest(position_list[i], k + 1)
            assert (obj_list == compare_to_obj)
            assert ((dists[i] == compare_to_dists).any())
Beispiel #7
0
def set_up_tree_nests_fixed():
    """Sets up nests at fixed position. Use this if you do not want two nests to be created at one position."""
    tree = KdTreeAndDict()
    positions = [array([5, 5]), array([-5, -5]), array([1000, 1000])]
    players = [Player("franz", (0, 0, 0)),
               Player("calvin", (178, 58, 238)),
               Player("hobbes", (122, 86, 201))]

    tree.create_nests(players, positions, size=1, health=100)

    return tree, positions
Beispiel #8
0
 def __init__(self, width, height):
     pygame.init()
     self.state = None
     self.size = width, height
     self.screen = pygame.display.set_mode(self.size)
     self.background_color = pygame.Color("white")
     self.mouse_pos = pygame.mouse.get_pos()
     self.mouse_event = pygame.mouse.get_pressed()
     self.elements = {}
     self.event_dict = {}
     self.FONT = pygame.font.Font(None, 32)
     self.pos = [array([-500, 500]), array([500, -500])]
Beispiel #9
0
def test_move_randomly():
    ant.has_food = False
    ant.position = array([0, 0])
    ant.momentum = array([0, 0])
    previous_position = array(ant.position)
    position = ant.move([])
    assert np.isclose(position, ant.position).all(), 'position not updated'
    assert np.isclose(1, np.linalg.norm(
        ant.momentum)).all(), 'momentum not one: %r' % ant.momentum
    assert np.isclose(1, np.linalg.norm(
        ant.position -
        previous_position)).all(), 'movement not one: %r' % ant.position
Beispiel #10
0
def test_move_randomly(set_up_environment):
    player, nest, ant = set_up_environment
    ant.has_food = 0.
    ant.position = array([0., 0.])
    ant.direction = array([0., 0.])
    init_position = array(ant.position)
    position, _ = ant.update([])
    assert np.isclose(1., np.linalg.norm(
        ant.direction)), 'direction not one: %r' % ant.direction
    assert np.isclose(
        1.,
        np.linalg.norm(ant.position -
                       init_position)), 'movement not one: %r' % ant.position
Beispiel #11
0
def test_move_has_food():
    ant.has_food = True
    ant.position = array([10, 0])
    position = ant.move([])
    # asserting that y-move is towards the nest
    assert np.isclose(position, array([9,
                                       0])).all(), 'incorrect y-move direction'
    # asserting that the position is updated
    assert np.isclose(ant.position, position).all(), 'position not updated'
    ant.position = array([0, 10])
    position = ant.move([])
    # asserting that x-move is towards the nest
    assert np.isclose(position, array([0,
                                       9])).all(), 'incorrect x-move direction'
Beispiel #12
0
    def __init__(self, player_list):
        """ Initialize player list and create nests for all the players

        :param player_list: (list) that contains current players IDs

        """
        self.players = player_list
        self.world = KdTreeAndDict()
        positions = []
        for i in range(len(player_list)):
            positions.append(random(2) * 250)
        self.world.create_nests(player_list, positions, health=100, size=10)
        self.generate_random_food(array([-250, 250]), array([250, -250]), 50,
                                  [5] * 50)
Beispiel #13
0
def test_get_circular_region(set_up_food_fixed, food_grid_indices=range(3)):
    tree, positions_dict = set_up_food_fixed
    food_grids = []
    for idx in food_grid_indices:
        food_grids.append(positions_dict["nested food"][idx])
    grid_info = positions_dict["food grid info"]

    # corners should not be in the result
    for i, grid in enumerate(food_grids):
        center = grid_info[i][2]
        radius = grid_info[i][3]
        objects = tree.get_circular_region(center, radius)
        positions = [obj.position for obj in objects]
        for position in positions:
            assert (array_in_list(position, grid))

        corners = [
            center + array([i, j]) for j in [+radius, -radius]
            for i in [+radius, -radius]
        ]
        for corner in corners:
            assert (not array_in_list(corner, positions))

        for point in grid:
            if not array_in_list(point, corners):
                assert (array_in_list(point, positions))
Beispiel #14
0
 def __init__(self):
     super(ModelParams, self).__init__()
     self.food_min_size = 0.
     self.nest_initial_food = 0.
     self.creating_ant_cost = 1.
     self.nest_min_health = 0.
     self.pheromone_initial_strength = 1.
     self.pheromone_min_strength = 1e-8
     self.pheromone_added_strength = 1.
     self.pheromone_decay_factor = 0.75
     self.ant_has_food = 0.
     self.ant_initial_energy = 100.
     self.ant_initial_direction = array([0., 0.])
     self.ant_initial_pheromone_strength = 0.
     self.ant_loading_capacity = 1.
     self.min_pheromone_strength = 1.
     self.max_pheromone_strength = 10.
     self.pheromone_dist_decay = 0.95
     self.ant_direction_memory = 0.5
     self.ant_foodiness = 1.
     self.ant_inscentiveness = 1.
     self.ant_directionism = 1.
     self.ant_explorativeness = 1.
     self.ant_min_energy = 0.
     self.ant_min_dist_to_nest = 1.
     self.ant_min_dist_to_food = 1.
     self.ant_max_dist_to_pheromone = 1.
     self.circular_region_radius = 10
     self.tree_distance_type = 2
     self.circular_region_distance = 2
     self.square_region_distance = np.inf
def test_get_at_position(set_up_food_fixed, position=array([-100, -100]), compare_to_index=3):
    tree, positions = set_up_food_fixed
    obj_list = tree.get_at_position(position)
    obj_positions = [obj.position for obj in obj_list]
    for obj_position in obj_positions:
        assert ((obj_position == position).all())
    assert (obj_positions == positions["nested food"][compare_to_index])
Beispiel #16
0
    def __init__(self):
        super(AntModelParams, self).__init__()
        # Energy
        # self.initial_energy = 100.  # TODO remove when different initial values per ant are created
        self.energy_increase = 10.
        self.maximum_energy = 1000.
        self.min_energy = 0.

        # Pheromone
        # self.initial_pheromone_strength = 0.
        self.initial_direction = array([0., 0.])
        self.min_pheromone_strength = 1.
        self.max_pheromone_strength = 100.
        self.pheromone_dist_decay = 0.95

        # Food
        # self.loading_capacity = 1.

        # Movement and distances
        self.direction_memory = 0.75
        self.min_dist_to_nest = 1.5
        self.min_dist_to_food = 1.5
        self.min_dist_to_nest_scout = 4.
        self.min_dist_to_food_scout = 4.
        self.max_dist_to_pheromone = 1.
Beispiel #17
0
def test_unload_food(set_up_environment):
    player, nest, ant = set_up_environment
    ant.has_food = 1.
    ant.position = array([0., 0.])
    init_nest_food = nest.food
    init_ant_food = ant.has_food
    ant.unload_food()
    assert ant.has_food == 0., 'food is not unloaded'
    assert nest.food == (init_ant_food +
                         init_nest_food), 'some food is lost in unloading'
Beispiel #18
0
 def move_to(self, obj_position):
     """
     changing the position of the ant towards the given obj_position with step size of one
     direction is updated
     :param obj_position: the position of object which the ant should move towards
     :return: the updated position
     """
     # Go towards the position of obj_position
     if distance(obj_position - self.position) > 0.:
         return_movement = (obj_position - self.position) / distance(obj_position - self.position)
     else:
         return_movement = array([0., 0.])  # THIS IS NOT THE BEST IMPLEMENTATION
     self.position += return_movement
     self.direction = return_movement
     return self.position
def test_get_k_nearest(set_up_food_fixed, center_position=array([0, 0]), almost_center_pos=array([0.1, 0.1]),
                       nested_food_ind=0,
                       k_greater_1=4):
    """Tests for fixed data whether k-nearest objects are returned using the 'small_grid' in the 'set_up_food_fixed'
    fixture.
    The optional parameters are resent because I think they might enable simpler randomized testing."""
    tree, positions_dict = set_up_food_fixed

    # k = 1
    nearest_obj, dist = tree.get_k_nearest(center_position, 1)
    for obj in nearest_obj:
        assert (issubclass(type(obj), GameObject))
        assert ((obj.position == center_position).all())
    nearest_obj, dist = tree.get_k_nearest(almost_center_pos, 1)
    for obj in nearest_obj:
        assert (issubclass(type(obj), GameObject))
        assert ((obj.position == center_position).any())

    # k > 1
    actual_positions = positions_dict["nested food"][nested_food_ind]
    original_len = len(actual_positions)
    nearest_objs, dists = tree.get_k_nearest(center_position, k_greater_1)
    max_norm = 0
    for obj in nearest_objs:
        assert (issubclass(type(obj), GameObject))
        position = obj.position
        dist_form_center = linalg.norm(array(position) - array(center_position))
        if dist_form_center > max_norm:
            max_norm = dist_form_center
        assert (array_in_list(position, actual_positions))
        actual_positions = array_remove_from_list(position, actual_positions)
    assert (not array_in_list(center_position, actual_positions))
    assert (original_len - k_greater_1 == len(actual_positions))
    for far_away_position in actual_positions:
        dist = linalg.norm(array(far_away_position) - array(center_position))
        assert (dist >= max_norm)
Beispiel #20
0
    def __init__(self, color, home_nest):
        """Initialize ant object color and position

        :param color: (str) Color of the ant
        :param home_nest: (Nest) Coordinates of ant position

        """
        position = home_nest.position
        super(Ant, self).__init__(position)
        # TODO: assign id
        self.color = color
        self.has_food = False
        self.energy = 100
        self.momentum = array([0., 0.])
        self.home = home_nest
def test_get_rectangle_region(set_up_food_fixed, food_grid_indices=range(3)):
    tree, positions_dict = set_up_food_fixed
    food_grids = []
    for idx in food_grid_indices:
        food_grids.append(positions_dict["nested food"][idx])
    grid_info = positions_dict["food grid info"]

    for i, grid in enumerate(food_grids):
        top_left_square = grid_info[i][0]
        top_left_rectangle = array([top_left_square[0], top_left_square[1] - 0.5])
        bottom_right = grid_info[i][1]
        objects = tree.get_rectangle_region(top_left_rectangle, bottom_right)
        positions = [obj.position for obj in objects]
        for position in positions:
            assert (array_in_list(position, grid))

        for point in grid:
            if point[1] > top_left_rectangle[1]:
                assert (not array_in_list(point, positions))
            else:
                assert (array_in_list(point, positions))
Beispiel #22
0
def test_move_has_food(set_up_environment):
    player, nest, ant = set_up_environment
    ant.has_food = 1.

    # asserting that y-move is towards the nest
    ant.position = array([10., 0.])
    position, _ = ant.update([])
    assert np.isclose(position,
                      array([9., 0.])).all(), 'incorrect y-move direction'

    # asserting that x-move is towards the nest
    ant.position = array([0., 10.])
    position, _ = ant.update([])
    assert np.isclose(position,
                      array([0., 9.])).all(), 'incorrect x-move direction'

    # asserting the arrival
    ant.position = array([0., 0.])
    position, _ = ant.update([])
    assert np.isclose(position,
                      array([0., 0.])).all(), 'moves after reaching the object'
Beispiel #23
0
def nest_creation_fixed():
    position = array([0.5, 0.5])
    player = Player(name="Nobody", color=(178, 58, 238))
    size = 5
    health = 10
    return (position, player, size, health)
Beispiel #24
0
from src.model.ant import Ant
from src.model.nest import Nest
from src.utils import array
import numpy as np

nest = Nest(position=array([0, 0]), color='red', size=10, health=100)
ant = Ant(color='red', home_nest=nest)


def test_move_has_food():
    ant.has_food = True
    ant.position = array([10, 0])
    position = ant.move([])
    # asserting that y-move is towards the nest
    assert np.isclose(position, array([9,
                                       0])).all(), 'incorrect y-move direction'
    # asserting that the position is updated
    assert np.isclose(ant.position, position).all(), 'position not updated'
    ant.position = array([0, 10])
    position = ant.move([])
    # asserting that x-move is towards the nest
    assert np.isclose(position, array([0,
                                       9])).all(), 'incorrect x-move direction'


def test_move_randomly():
    ant.has_food = False
    ant.position = array([0, 0])
    ant.momentum = array([0, 0])
    previous_position = array(ant.position)
    position = ant.move([])
def set_up_food_fixed(set_up_tree_nests_fixed):
    """Sets up food.
    Please never remove positions and when adding, add to positions far away from existing ones.
    Other wise you might mess up other tests"""
    tree, nest_positions = set_up_tree_nests_fixed

    small_grid = [array([-1, -1]), array([-1, 0]), array([0, -1]), array([0, 0]), array([0, 1]),
                  array([1, 0]), array([1, 1]), array([-1, 1]), array([1, -1])]
    another_small_grid = [array([8, 8]), array([8, 9]), array([9, 8]), array([9, 9]), array([9, 10]),
                          array([10, 9]), array([10, 10]), array([8, 10]), array([10, 8])]
    yet_another_small_grid = [array([-8, -8]), array([-8, -9]), array([-9, -8]), array([-9, -9]),
                              array([-9, -10]), array([-10, -9]), array([-10, -10]), array([-8, -10]),
                              array([-10, -8])]
    food_grid_info = [((-1, 1), (1, -1), (0, 0), 1), ((8, 10), (10, 8), (9, 9), 1),
                      ((-10, -8), (-8, -10), (-9, -9), 1)]

    stacked_food = [array([-100, -100]), array([-100, -100]), array([-100, -100])]

    all_food_position_lists = [small_grid, another_small_grid, yet_another_small_grid, stacked_food]
    food_positions = [position for sublist in all_food_position_lists for position in sublist]
    sizes = [1] * len(food_positions)
    tree.create_food(food_positions, sizes)
    all_positions_flat = nest_positions.copy()
    all_positions_flat.extend(food_positions)

    all_positions = {"all positions": all_positions_flat,
                     "nests": nest_positions,
                     "nested food": all_food_position_lists,
                     "flat food": food_positions,
                     "food grid info": food_grid_info}
    return tree, all_positions
Beispiel #26
0
def set_up_environment():
    player = Player(name="Nobody", color=(178, 58, 238))
    nest = Nest(position=array([0., 0.]), player=player, size=10., health=100.)
    ant = Worker(player=player, home_nest=nest, speed=1)
    return player, nest, ant
Beispiel #27
0
def set_up_food_fixed():
    position = array([0.5, 0.5])
    size1 = 5.
    size2 = -2.
    return position, size1, size2
Beispiel #28
0
def set_up_food():
    food = Food(position=array([13., 17.]), size=1)
    return food
 def _update_tree(self):
     """Update the tree"""
     keys = list(self.all_objects.keys())
     self.point_matrix = array(keys)
     self.kd_tree = cKDTree(self.point_matrix)
Beispiel #30
0
def set_up_nest():
    position = array([0.5, 0.5])
    color = (178, 58, 238)
    size = 5
    health = 10
    return position, color, size, health