def test_new_year(self) -> None: """ Check that migration works """ np.random.seed(1) # Should never migrate to a water cell for _ in range(1000): k = Island('WWW\nWLW\nWWW') k.map[1][1].add_animal("Herbivore", 10, 100) k.map[1][1].herbivores[0].set_params( {"omega": 0}) # Should never die in the new year k.new_year() assert k.map[1][1].n_herbivores == 1 np.random.seed(1) n_migrated = 1 for _ in range(1000): k = Island('WWWW\nWLLW\nWLLW\nWWWW') k.map[1][1].add_animal("Herbivore", age=1, weight=1000) k.map[1][1].add_animal("Carnivore", age=1, weight=1000) # Probability should be 1/8 to move (0.25*1)/2 (Only two squares possible to move to) k.new_year() if k.map[1][1].n_herbivores != 1: n_migrated += 1 p_migration = n_migrated / 1000 assert p_migration == pytest.approx( 0.125, abs=1e-1) # TODO check if this is right
def __init__(self, island_map, ini_pop, seed, ymax_animals=None, cmax_animals=None, hist_specs=None, img_base=None, img_fmt='png'): """ :ivar : island map , is a formatted string This documentation should appear in html. This is inside INIT of class BioSim :return None """ self.object_matrix = Island().create_map(island_map) self.rgb_map = Island().rgb_for_map(island_map) self.add_population(ini_pop) self.current_year = 0 self.x_axis_limit = 0 # Set up visualization self.viz = Visualization() self.viz.set_plots_for_first_time(rgb_map=self.rgb_map)
def test_make_map_ready(self) -> None: """ Checks if it raises ValueError when the edges is not water """ with pytest.raises(ValueError): Island("WLW\nWLW\nWWW") with pytest.raises(ValueError): Island("WWW\nLLW\nWWW") with pytest.raises(ValueError): Island("WWW\nWLW\nWLW")
def test_wrong_boundaries1(): """Test that adding a cell that is not water at the edges raises ValueError.""" default_geography = """\ HWW WLW WWW""" with pytest.raises(ValueError): Island(island_map=default_geography) default_geography = """\ WWW LLW WWW""" with pytest.raises(ValueError): Island(island_map=default_geography)
def test_get_pi_values_carnivores_with_herbs_and_carns(self): """ Test for getting pi values We also test with extra herbivores and carnivores in adjacent cells Returns ------- """ i1 = Island(ISLE_MAP2) coordinate = (2, 3) i1.add_animal_island((2, 2), INI_HERB[0]['pop']) i1.add_animal_island((3, 3), INI_HERB[0]['pop']) i1.add_animal_island((3, 3), INI_CARN[0]['pop']) correct_weight_left = 400 correct_weight_right = 400 eleft = correct_weight_left / 50 edown = correct_weight_right / ((20 + 1) * 50) correct_pi_left = math.exp(1 * eleft) correct_pi_up = 0 correct_pi_right = 0 correct_pi_down = math.exp(1 * edown) assert i1.get_pi_values_carnivores(coordinate) == pytest.approx( (correct_pi_right, correct_pi_up, correct_pi_left, correct_pi_down))
def jungle_island_animals(self): """ Function to create an island that can be used for testing the Herbivore-class :return: Returns the Island-class with a map and animals and the Herbivore-class """ added_list = [{ 'loc': (3, 3), 'pop': [{ 'species': 'Herbivore', 'age': 21, 'weight': 17.3 }, { 'species': 'Herbivore', 'age': 30, 'weight': 19.3 }, { 'species': 'Herbivore', 'age': 10, 'weight': 107.3 }, { 'species': 'Herbivore', 'age': 1, 'weight': 20.3 }] }] a = Island("OOOOO\nOJJJO\nOJJJO\nOJJJO\nOOOOO") a.add_animals(added_list) b = Herbivores() return a, b
def jungle_island_animals(self): """Creats an island that consists of a 3X3 jungle square in tha middle, that contains 4 animals(3 Herbivores and one carnivore) for later convenience """ added_list = [{ 'loc': (3, 3), 'pop': [{ 'species': 'Herbivore', 'age': 21, 'weight': 17.3 }, { 'species': 'Herbivore', 'age': 30, 'weight': 19.3 }, { 'species': 'Herbivore', 'age': 10, 'weight': 107.3 }, { 'species': 'Carnivore', 'age': 1, 'weight': 20.3 }] }] a = Island("OOOOO\nOJJJO\nOJJJO\nOJJJO\nOOOOO") a.add_animals(added_list) b = Herbivores() return a, b
def test_not_enough_herbs_to_eat(self): """Tests that the animal eats what is left and nothing more when they cannot fill their F""" animal_list = [{ 'loc': (1, 1), 'pop': [{ 'species': 'Carnivore', 'age': 5, 'weight': 53.3 }, { 'species': 'Herbivore', 'age': 500, 'weight': 20 }, { 'species': 'Herbivore', 'age': 500, 'weight': 20 }] }] a = Island('OOO\nOJO\nOOO') b = Carnivores() c = Herbivores() a.add_animals(animal_list) b.set_new_params({'beta': 1, 'F': 50, 'DeltaPhiMax': 0.0001}) c.calculate_fitness((1, 1), a.herbs) b.calculate_fitness((1, 1), a.carns) b.carnivores_eat((1, 1), a, a.carns) assert len(a.herbs[(1, 1)]) == 0 assert a.carns[(1, 1)][0]['weight'] == 93.3
def test_default_init(): """Tests that map and population is added in init function.""" default_pop = [ { "loc": (2, 2), "pop": [{ "species": "Carnivore", "age": 5, "weight": 20.0 } for _ in range(20)], }, { "loc": (2, 2), "pop": [{ "species": "Herbivore", "age": 5, "weight": 20.0 } for _ in range(50)], }, ] default_geography = """\ WWW WLW WWW""" island = Island(default_geography, default_pop) assert island.initial_pop is not None assert isinstance(island.island_map[(2, 2)], Lowland) assert len(island.island_map[(2, 2)].herbivore_list) == 50 assert len(island.island_map[(2, 2)].carnivore_list) == 20
def test_migration(self): """ Test for migration Returns ------- """ i1 = Island(ISLE_MAP2) Herbivore.set_parameters({'mu': 1.0}) Carnivore.set_parameters({'mu': 1.0}) coordinate = (2, 3) i1.add_animal_island(coordinate, INI_HERB[0]['pop']) i1.add_animal_island(coordinate, INI_CARN[0]['pop']) for herbivore in i1.cells[2, 3].herbivores: herbivore.fitness = 1 for carnivore in i1.cells[2, 3].carnivores: carnivore.fitness = 1 i1.migration() # can only move left or down len_left_herb = len(i1.cells[2, 2].herbivores) len_down_herb = len(i1.cells[3, 3].herbivores) len_left_carn = len(i1.cells[2, 2].carnivores) len_down_carn = len(i1.cells[3, 3].carnivores) assert (len_down_herb + len_left_herb, len_left_carn + len_down_carn) == (20, 20)
def __init__(self, island_map, ini_pop=None, seed=12345, img_dir=None, img_name=DEFAULT_GRAPHICS_NAME, img_format='png'): random.seed(seed) np.random.seed(seed) self.island_map = island_map self.island = Island(island_map) if ini_pop is not None: self.add_population(ini_pop) self.island.animals_on_island() self.fig = None self.ax1 = None self.ax2 = None self.ax3 = None self.ax4 = None self.line_herbivore = None self.line_carnivore = None self.herbivore_density = None self.carnivore_density = None self.year_ax = None self.year_txt = None self.vis_index = 0 self.last_step = 0 self.year = 0 self.x_lim = (0, 100) # line graph ordinate limits, default values self.y_lim = (0, 15000) # line graph abscissa limits, default values self.user_limits = False self.herbivore_color_code = (0, 300) # population map color code limits self.carnivore_color_code = (0, 300) # population map color code limits self.img_counter = 0 if img_dir is not None: self.img_base = os.path.join(img_dir, img_name) else: self.img_base = None self.img_format = img_format
def test_wrong_length(): """Test that a map with inconsistent line length raises ValueError.""" default_geography = """\ WWW WLLW WWW""" with pytest.raises(ValueError): Island(island_map=default_geography)
def setup(self): self.island = Island(self.geogr_simple) self.island.build_map() for row in self.island.island: for cell in row: if cell.passable: cell.herbivores = [Herbivore(weight=50) for _ in range(10)] cell.carnivores = [Carnivore(weight=50) for _ in range(10)]
def test_set_food(self): """Tests that set_food places the inicial amount of food for the given tile""" a = self.simple_island() a.set_food((1, 3)) b = Island("OOOOO\nOSSSO\nOSSSO\nOSSSO\nOOOOO") b.set_food((1, 3)) assert a.food == {(1, 3): 800} assert b.food == {(1, 3): 300}
def test_more_migration(self): """Testing that the animals moves into every tile and in every direction""" animals = [{ 'loc': (2, 2), 'pop': [{ 'species': 'Herbivore', 'age': 5, 'weight': 13.3 }] }, { 'loc': (2, 2), 'pop': [{ 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }] }] a = Island("OOOOO\nOJJJO\nOJJJO\nOJJJO\nOOOOO") b = Herbivores() a.add_animals(animals) for i in range(a.rader): for j in range(a.col): a.set_food((i, j)) b.calculate_fitness((2, 2), a.herbs) for _ in range(20): b.migration_calculations(a, a.herbs) b.migration_execution(a, a.herbs) for i in range(1, 3): for j in range(1, 3): assert (i, j) in a.herbs.keys()
def test_invalid_moving(self): """Tests that the animals does not move to tiles that they are not allowed to enter""" population = [{ 'loc': (2, 2), 'pop': [{ 'species': 'Herbivore', 'age': 5, 'weight': 13.3 }] }, { 'loc': (2, 2), 'pop': [{ 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }, { 'species': 'Herbivore', 'age': 4, 'weight': 10 }] }] a = Island("OOOOO\nOOOOO\nOOJOO\nOOMOO\nOOOOO") b = Herbivores() for i in range(a.rader): for j in range(a.col): a.set_food((i, j)) a.add_animals(population) b.calculate_fitness((2, 2), a.herbs) for _ in range(30): b.migration_calculations(a, a.herbs) b.migration_execution(a, a.herbs) assert (2, 1) not in a.herbs.keys() assert len(a.herbs[(2, 2)]) == 9
def test_surrounding_cells_2(): """ Tests that no surrounding cells is returned if all are mountain and ocean """ island = Island("OOO\nOJM\nMMM") island.build_map() cor = island.surrounding_cells((1, 1)) nt.assert_list_equal(cor, [])
def test_wrong_landscapes_key(): """Test that wrong landscape keys raise ValueError.""" default_geography = """\ WWW WRW WWW""" with pytest.raises(ValueError): Island(island_map=default_geography)
def test_invalid_moving_carns(self): """ Tests invalid moving is not happening""" population1 = [{ 'loc': (2, 2), 'pop': [{ 'species': 'Carnivore', 'age': 5, 'weight': 13.3 }] }, { 'loc': (2, 2), 'pop': [{ 'species': 'Carnivore', 'age': 4, 'weight': 10 }, { 'species': 'Carnivore', 'age': 4, 'weight': 10 }, { 'species': 'Carnivore', 'age': 4, 'weight': 10 }, { 'species': 'Carnivore', 'age': 4, 'weight': 10 }, { 'species': 'Carnivore', 'age': 4, 'weight': 10 }, { 'species': 'Carnivore', 'age': 4, 'weight': 10 }, { 'species': 'Carnivore', 'age': 4, 'weight': 10 }, { 'species': 'Carnivore', 'age': 4, 'weight': 10 }] }] a = Island("OOOOO\nOOMOO\nOOJOO\nOOMOO\nOOJOO") b = Carnivores() c = Herbivores() a.add_animals(population1) b.calculate_fitness((2, 2), a.carns) b.migration_calculations(a, c, a.carns) assert len(a.carns[(2, 2)]) == 9 assert (3, 2) not in a.carns.keys() assert len(b.idx_for_animals_to_remove) == 0 b.migration_execution(a, a.carns) assert len(a.carns[(2, 2)]) == 9
def test_check_surrounded_by_ocean(self): """ verifying if value error is raised when edges dont contain ocean cells """ map_str = """ OOOOOOOJOOOO OMSOOOOOSMMO OOOOOOOOOOOO""" with pytest.raises(ValueError) as err: Island(map_str) assert err.type is ValueError
def test_surrounding_cells(): """ Test that the function surrounding cells returns the right cells """ island = Island("JJJJJJ\nJJJJJJ\nJJJJJJ\nJJJJJJ\nJJJJJJ\nJJJJJJ") island.build_map() cor = island.surrounding_cells((5, 5)) true = [(4, 5), (5, 4), (5, 6), (6, 5)] for index in range(len(cor)): nt.assert_equal(cor[index], true[index])
def test_adjacent_cells(self): """ Testing if the adjacent_cells output is in the list of adjacent cells """ map_str = """ OOOOOOOOOOOO OMSOOOOOSMMO OOOOOOOOOOOO""" island = Island(map_str) island.string_to_array() assert all(j in island.adjacent_cells(0, 0) for j in ['O', 'O'])
def create_island(self): """ Creating island object """ self.island = Island("""\ WWWWWWWW WLLLLLWW WHLLLLWW WLDDLLWW WHWWWWWW WWWWWWWW""")
def test_get_random_coordinates(self): """ Test for getting random coordinates, for type and length. Returns ------- """ i1 = Island(ISLE_MAP2) assert [type(a) == tuple for a in i1.get_random_coordinates()] assert [len(a) == 2 for a in i1.get_random_coordinates()]
def test_string_to_array(self): """ testing the string_to_array method by verifying the individual cell and also by looking at the type of output """ map_str = """ OOOOOOOOOOOO OMSOODOOSMMO OOOOOOOOOOOO""" island = Island(map_str) assert island.string_to_array()[0][0] == 'O' assert island.string_to_array()[1][10] == 'M' assert type(island.string_to_array()).__name__ == 'ndarray'
def test_create_array_with_landscape_objects(self): """ Testing create_array_with_landscape_objects by manually verifying if it returns instantiates correct cell object """ map_str = """ OOOOOOOOOOOO OMSOOOOOSMMO OOOOOOOOOOOO""" island = Island(map_str) assert isinstance(island.create_array_with_landscape_objects()[0][0], Ocean) assert isinstance(island.create_array_with_landscape_objects()[1][10], Mountain)
def test_string_to_array(self): """ Test for the method Island.string_to_array Returns ------- """ i1 = Island(ISLE_MAP) arry = i1.string_to_array() correct_arry = np.array([['O', 'O', 'O'], ['O', 'S', 'O'], ['O', 'O', 'O']]) assert np.array_equal(arry, correct_arry)
def test_water_cell(self): """ Firstly: To test the animal can't go through the water Secondly: To test if the available fodder in water is 0 """ i = Island("WWWW\nWLHW\nWWWW") ini_herb = [{'loc': (0, 1), 'pop': [{'species': 'Herbivore', 'age': 5, 'weight': 20}]}] with pytest.raises(ValueError): i.place_animals(ini_herb) w = Water() assert w.set_fodder() is None
def __init__(self, island_map=None, ini_pop=None, seed=None): """ Constructor creates island from given map, and adds initial population to island. All parameters needed to create animals are contained within ini_pop. :param island_map: String containing letters representing each type of landscape :param ini_pop: List of initial_populations. [pop1, pop2] :param seed: Seed for rng """ if seed is not None: np.random.seed(seed) random.seed(seed) else: random.seed(1234) np.random.seed(987654) if island_map is None: island_map = """OOOOOOO OJJSJJO OJSSSJO OJSMSJO OJSMSJO OJJJJJO OOOOOOO""" self.island_map = island_map self.island = Island(self.island_map) self.island.build_map() self.vis_steps = None self.img_steps = None self.years_sim = 0 self.heat = None if ini_pop is None: ini_herbs = [{'loc': (3, 3), 'pop': [{'species': 'Herbivore', 'age': 5, 'weight': 20} for _ in xrange(150)]}] ini_carns = [{'loc': (3, 3), 'pop': [{'species': 'Carnivore', 'age': 5, 'weight': 20} for _ in xrange(40)]}] ini_pop = ini_herbs + ini_carns self.add_population(ini_pop) self.fig = None
def test_add_animals(self): """ Testing add_animals and total_animals_per_species methods """ map_str = """ OOOOOOOOOOOO OMSOOOOOSMMO OOOOOOOOOOOO""" island = Island(map_str) animals = [ { "loc": (1, 1), "pop": [ { "species": "Herbivore", "age": 10, "weight": 10.0 }, { "species": "Carnivore", "age": 11, "weight": 11.0 }, ], }, { "loc": (1, 2), "pop": [ { "species": "Herbivore", "age": 10, "weight": 10.0 }, { "species": "Herbivore", "age": 11, "weight": 11.0 }, { "species": "Carnivore", "age": 12, "weight": 12.0 }, ], }, ] island.add_animals(animals) assert island.total_animals_per_species('Herbivore') == 3 assert island.total_animals_per_species('Carnivore') == 2