示例#1
0
def test_invalid_character():
    """Test if the method 'check_invalid_character(geos)' identifies
    an invalid character on the island_map"""
    island_map = "OOOOO\nOJAJO\nOOOOO"
    island_map = Island.list_geo_cells(island_map)
    with pytest.raises(ValueError):
        Island.check_invalid_character(island_map)
 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 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 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
示例#5
0
    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
示例#6
0
    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_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}
示例#8
0
 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)]
示例#9
0
 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_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
示例#11
0
def test_invalid_line_lengths():
    """Test if the method 'check_invalid_line_lengths(geos)' identifies
    a different horizontal (line/row) length on the island_maps"""
    island_maps = ("OOOOOO\nOJJJO\nOOOOO",
                   "OOOOO\nOOJJJO\nOOOOO",
                   "OOOOO\nOJJJO\nOOOOOO")
    for island_map in island_maps:
        island_map = Island.list_geo_cells(island_map)
        with pytest.raises(ValueError):
            Island.check_invalid_line_lengths(island_map)
 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'])
示例#13
0
 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])
示例#14
0
    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()]
示例#15
0
 def create_island(self):
     """
     Creating island object
     """
     self.island = Island("""\
                     WWWWWWWW
                     WLLLLLWW
                     WHLLLLWW
                     WLDDLLWW
                     WHWWWWWW
                     WWWWWWWW""")
    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_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)
示例#19
0
    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)
示例#20
0
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_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
示例#22
0
    def test_get_direction(self):
        """
        Test for getting direction to move.

        Returns
        -------

        """
        pis = (20, 30, 10, 40)
        options = ['right', 'up', 'left', 'down']
        direction = Island.get_direction(pis)
        assert direction in options
        pis = (0, 0, 0, 0)
        option = 'do not move'
        assert Island.get_direction(pis) == option
示例#23
0
def test_invalid_boundary():
    """Test if the method 'check_invalid_boundary(geos)' identifies
    a different boundary for island_maps than only 'Oceans'"""
    island_maps = ("JOOOO\nOJJJO\nOOOOO",
                   "OOOOJ\nOJJJO\nOOOOO",
                   "OOJOO\nOJJJO\nOOOOO",
                   "OOOOO\nJJJJO\nOOOOO",
                   "OOOOO\nOJJJJ\nOOOOO",
                   "OOOOO\nOJJJO\nJOOOO",
                   "OOOOO\nOJJJO\nOOOOJ",
                   "OOOOO\nOJJJO\nOOJOO")
    for island_map in island_maps:
        island_map = Island.list_geo_cells(island_map)
        with pytest.raises(ValueError):
            Island.check_invalid_boundary(island_map)
示例#24
0
    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
示例#25
0
    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
示例#27
0
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
示例#28
0
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)
示例#29
0
    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))
示例#30
0
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)