コード例 #1
0
 def test_feed(self, herbivore_list):
     carnivore = Carnivore(5, 100)
     sorted_list = sorted(herbivore_list, key=lambda var: var.fitness)
     length_a = len(sorted_list)
     weight_a = carnivore.weight
     new_list = carnivore.feed(sorted_list)
     length_b = len(new_list)
     weight_b = carnivore.weight
     assert length_b < length_a
     assert weight_a < weight_b
     assert weight_b - weight_a <= carnivore.F * carnivore.beta
     # Should add tests that changes DeltaPhiMax and checks
     # that part of the code
     carnivore.set_parameters(DeltaPhiMax=0.5)
     carnivore = Carnivore(5, 100)
     assert carnivore.fitness > 0.5
     sorted_list = sorted(herbivore_list, key=lambda var: var.fitness)
     for herbivore in sorted_list:
         herbivore.weight = 200
         herbivore._compute_fitness = False
         herbivore._fitness = 0.0
     times_to_eat = len(sorted_list)
     herbivores_eaten = 0
     while len(sorted_list) > 0:
         carnivore.feed(sorted_list)
         herbivores_eaten += 1
     assert herbivores_eaten == times_to_eat
     reset_parameters()
コード例 #2
0
def test_value_error_for_age_and_weight():
    """Test that age and weight can't be negative values, and that these raises ValueError."""
    with pytest.raises(ValueError):
        Herbivore(age=-9)

    with pytest.raises(ValueError):
        Herbivore(weight=-4)

    with pytest.raises(ValueError):
        Carnivore(age=-40)

    with pytest.raises(ValueError):
        Carnivore(weight=-8)
コード例 #3
0
    def test_animal_dying(self, mocker):
        carn = Carnivore(20, 0)
        dead = carn.animal_dying()
        assert dead is True

        herb = Herbivore(5, 20)
        mocker.patch('random.random', return_value=0.001)
        dead = herb.animal_dying()
        assert dead is True

        carn = Carnivore(5, 20)
        mocker.patch('random.random', return_value=0.9)
        dead = carn.animal_dying()
        assert dead is False
コード例 #4
0
def test_death_probability(mocker):
    """Test that the death function returns true if the mocked value is lower than the probability
    of death. Also the opposite if the mocked value is higher than the probability of death."""
    mocker.patch("numpy.random.random", return_value=0)
    herb = Herbivore(5, 10)
    carn = Carnivore(6, 15)
    assert herb.death() is True
    assert carn.death() is True

    mocker.patch("numpy.random.random", return_value=1)
    herb = Herbivore(5, 10)
    carn = Carnivore(6, 15)
    assert herb.death() is False
    assert carn.death() is False
コード例 #5
0
    def test_fittest_carn_eats_first(self, mocker):
        """
        Tests to see if the fittest of three carnivores is the
        one that gets to eat the Herbivore
        """
        mocker.patch('random.random', return_value=0)

        self.island.cell_carn_pop = [Carnivore(1, 20), Carnivore(1, 20), Carnivore(5, 30)]
        self.island.cell_herb_pop = [Herbivore()]
        self.island.location.food = 0
        self.island.execute_feeding()

        assert self.island.cell_carn_pop[2].weight > 30 \
               and self.island.cell_carn_pop[0].weight == 20
コード例 #6
0
def test_add_population():
    """Test if population can be added to landscapes"""
    l_scape = Landscape()
    l_scape.add_population(Herbivore(5, 20))
    l_scape.add_population(Carnivore(5, 20))
    assert len(l_scape.herbivore_list) == 1
    assert len(l_scape.carnivore_list) == 1
コード例 #7
0
def test_death_weight():
    """Testing that the animal dies if the weight is 0."""
    herb = Herbivore(3, 0)
    carn = Carnivore(5, 0)

    assert herb.death() is True
    assert carn.death() is True
コード例 #8
0
def test_move(mocker):
    """Test that the move function returns True if the random value is lower than the probability
    to move, and False if the probability is lower than the random value."""
    mocker.patch("numpy.random.random", return_value=0)
    herbivore = Herbivore(5, 20)
    carnivore = Carnivore(5, 20)

    assert herbivore.move() is True
    assert carnivore.move() is True

    mocker.patch("numpy.random.random", return_value=1)
    herbivore = Herbivore(5, 20)
    carnivore = Carnivore(5, 20)

    assert herbivore.move() is False
    assert carnivore.move() is False
コード例 #9
0
 def test_set_Carn_params_negative_number(self):
     """
     Test to see if an error is raised if a negative number is inserted as a parameter
     replacement
     """
     with pytest.raises(ValueError):
         assert Carnivore().set_carn_params(new_params={'zeta': -5})
コード例 #10
0
 def test_set_Carn_params_non_int_float(self):
     """
     Test to see if an error is raised if a non int or float is inserted as a parameter
      replacement
     """
     with pytest.raises(TypeError):
         assert Carnivore().set_carn_params(new_params={'zeta': 'four'})
コード例 #11
0
 def test_set_Carn_parmas_non_dict(self):
     """
     Test to see if an error is raised if a non dictionary is inserted as a parameter
     replacement
     """
     with pytest.raises(TypeError):
         assert Carnivore().set_carn_params(new_params=['zeta', 0.4])
コード例 #12
0
 def test_set_Carn_params_wrong_key(self):
     """
     Test to see if an error is raised if non-existing key is inserted as a parameter
     replacement
     """
     with pytest.raises(KeyError):
         assert Carnivore().set_carn_params(new_params={'z': 16})
コード例 #13
0
    def test_procreation(self, mocker):
        herb = Herbivore(4, 30)
        herb_born = herb.procreation(1)
        assert herb_born is None

        carn = Carnivore(4, 30)
        carn_born = carn.procreation(1)
        assert carn_born is None

        herb = Herbivore(4, 30)
        weight = herb.weight
        lose_weight = (
            herb.params_dict["zeta"] *
            (herb.params_dict["w_birth"] + herb.params_dict["sigma_birth"]))
        assert weight < lose_weight
        for _ in range(10):
            procreation = herb.procreation(10)
            assert procreation is None

        herb = Herbivore(5, 40)
        phi = herb.phi
        mocker.patch('random.random', return_value=0.0001)
        herb.procreation(2)
        mocker.patch('random.gauss', return_value=5)
        herb.weight = 40 - (herb.params_dict["xi"] *
                            herb.get_initial_weight_offspring())
        phi_procreated = herb.phi
        assert herb.weight == 34  # NOT WORKING CHECK IT OUT!!!!
        assert phi > phi_procreated
コード例 #14
0
    def add_newborn_animals(self):
        """
        Iterates over both population lists of grown animals, in turn, and
        makes all animals procreate using the animal's birth_process_method.
        If birth_process returns a weight, a new animal will be born.
        Thus, a new class instance is added to the
        correct population list.
        """
        initial_num_herbs = len(self.pop_herb)
        for animal in self.pop_herb[:initial_num_herbs]:
            baby_weight = animal.birth_process(initial_num_herbs)
            if type(baby_weight) is (float or int):
                self.pop_herb.append(
                    Herbivore({
                        "species": "Herbivore",
                        "age": 0,
                        "weight": baby_weight
                    }))
                self.pop_herb[-1].fitness_must_be_updated = True

        initial_num_carns = len(self.pop_carn)
        for animal in self.pop_carn[:initial_num_carns]:
            baby_weight = animal.birth_process(initial_num_carns)
            if type(baby_weight) is (float or int):
                self.pop_carn.append(
                    Carnivore({
                        "species": "Carnivore",
                        "age": 0,
                        "weight": baby_weight
                    }))
                self.pop_carn[-1].fitness_must_be_updated = True
コード例 #15
0
 def test_set_Carn_params_wrong_eta(self):
     """
     Test to see if an error is raised when parameter Omega is replaced with a number
     that is not between 0 and 1
     """
     with pytest.raises(ValueError):
         assert Carnivore().set_carn_params(new_params={'eta': 1.5})
コード例 #16
0
def test_eat_if_eaten(mocker):
    """Test that carnivores wont eat more meat than their parameter ['F'] says."""
    mocker.patch("numpy.random.random", return_value=0)
    carn = Carnivore(5, 20)
    herbs = [Herbivore(6, 20), Herbivore(6, 20), Herbivore(6, 20)]
    carn.eat(herbs)
    assert carn.weight == 57.5
コード例 #17
0
    def test_migration(self, mocker):
        cell = SingleCell()
        neighbor_cells = [((10, 10), Water), ((10, 10), Water),
                          ((10, 10), Water), ((10, 10), Water)]
        herb_migrate, carn_migrate = cell.migrate(neighbor_cells)
        assert isinstance(herb_migrate, list)
        assert isinstance(carn_migrate, list)

        carn = Carnivore(age=1, weight=50)
        carn.has_migrated = False
        cell.present_carnivores.append(carn)

        cell.animals_allocate([{
            'species': 'Herbivore',
            'age': 5,
            'weight': 30
        } for _ in range(20)])
        for _ in range(10):
            herb_migrate = cell.migrate(neighbor_cells)
        assert herb_migrate

        herb_migrate, carn_migrate = cell.migrate(neighbor_cells)
        assert len(herb_migrate + carn_migrate) > 0
        assert carn.has_migrated is True

        herb = Herbivore(age=1, weight=60)
        cell.animals_allocate(herb)
        herb.has_migrated = False
        assert herb.has_migrated is True

        mocker.patch('random.choice', return_value=((5, 5), Lowland))
コード例 #18
0
 def test_constructor_carnivore(self, example_properties):
     """
     Checks that class is initialized with correct weight and age.
     """
     carnivore = Carnivore(example_properties)
     assert carnivore.age == example_properties["age"]
     assert carnivore.weight == example_properties["weight"]
コード例 #19
0
    def test_hunt_herb(self, mocker):
        herb_phi_sorted_list = [
            Herbivore(5, 20),
            Herbivore(20, 2),
            Herbivore(3, 16)
        ]
        herb_phi_sorted_list = sorted(herb_phi_sorted_list,
                                      key=lambda x: getattr(x, 'phi'))
        num_herb = len(herb_phi_sorted_list)

        carn = Carnivore(10, 2)
        del_herb = carn.hunt_herb(herb_phi_sorted_list)
        assert carn.phi < herb_phi_sorted_list[2].phi
        assert del_herb == [] and num_herb == 3

        carn = Carnivore(5, 20)
        assert carn.phi > herb_phi_sorted_list[2].phi

        mocker.patch('random.random', return_value=0.01)
        del_herb = carn.hunt_herb(herb_phi_sorted_list)
        assert len(del_herb) == 3

        carn = Carnivore(5, 20)
        phi_not_eaten = carn.phi
        herb_phi_sorted_list = [Herbivore(20, 2)]
        carn.hunt_herb(herb_phi_sorted_list)
        phi_eaten = carn.phi
        assert carn.weight == 21.5
        assert phi_not_eaten < phi_eaten

        carn = Carnivore(5, 20)
        herb_phi = [Herbivore(5, 0)]
        del_herb = carn.hunt_herb(herb_phi)
        assert len(del_herb) == 1

        carn = Carnivore(5, 20)
        herb_phi_sorted_list = [
            Herbivore(3, 10),
            Herbivore(3, 10),
            Herbivore(3, 10),
            Herbivore(3, 10),
            Herbivore(3, 10),
            Herbivore(20, 60),
            Herbivore(3, 10)
        ]
        del_herb = carn.hunt_herb(herb_phi_sorted_list)
        assert len(del_herb) == 5
コード例 #20
0
    def test_get_initial_weight(self, mocker):
        mocker.patch('random.gauss', return_value=5)

        herb = Herbivore(3, None)
        assert herb.get_initial_weight_offspring() == 5

        carn = Carnivore(2, None)
        assert carn.get_initial_weight_offspring() == 5
コード例 #21
0
def test_fitness_herb_more_than_carn():
    """Test that the carnivore won't eat if the herbivore fitness is higher that the carnivores."""
    carn = Carnivore(2, 5)
    carn_weight = carn.weight
    herb = [Herbivore(6, 25), Herbivore(6, 25), Herbivore(6, 25)]

    assert carn.eat(herb)
    assert carn_weight == carn.weight
コード例 #22
0
def test_no_birth_weight_to_low():
    """Test that the birth function returns None if the weight of the animal is to low."""
    herb = Herbivore(5, 15)
    carn = Carnivore(5, 15)
    nr_animals = 2

    assert herb.birth(nr_animals) is None
    assert carn.birth(nr_animals) is None
コード例 #23
0
 def test_remove_migrated_carn(self):
     cell = BaseCell()
     assert len(cell.carnivores) == 0
     carnivore = Carnivore()
     cell.add_migrated_carn(carnivore)
     assert len(cell.carnivores) == 1
     cell.remove_migrated_carn(carnivore)
     assert len(cell.carnivores) == 0
コード例 #24
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)]
コード例 #25
0
    def test_set_parameters(self):

        params = {'w_birth': -8.0, 'eta': 2, 'DeltaPhiMax': 0}
        with pytest.raises(ValueError):
            Herbivore().set_parameters(params)

        params = {'eta': 2, 'DeltaPhiMax': 10.0}
        with pytest.raises(ValueError):
            Herbivore().set_parameters(params)

        params = {'DeltaPhiMax': 0}
        with pytest.raises(ValueError):
            Carnivore().set_parameters(params)

        params = {'Invalid parameter': 0}
        with pytest.raises(ValueError):
            Carnivore().set_parameters(params)
コード例 #26
0
def test_eat_if_eaten_enough_deltaphimax_low(mocker):
    """Test that the carnivores wont eat more that their parameter ['F'] when the difference in
    fitness is bigger than DeltaPhiMax"""
    mocker.patch("numpy.random.random", return_value=0)
    carn = Carnivore(5, 20)
    herbs = [Herbivore(6, 20), Herbivore(6, 20), Herbivore(6, 20)]
    carn.eat(herbs)
    assert carn.weight == 57.5
コード例 #27
0
 def test_init(self):
     test_carnivore = Carnivore(10, 20)
     assert hasattr(test_carnivore, 'age')
     assert test_carnivore.age is not None
     assert hasattr(test_carnivore, 'weight')
     assert test_carnivore.weight is not None
     assert hasattr(test_carnivore, 'fitness')
     assert test_carnivore.fitness is not None
     assert 0 <= test_carnivore.fitness <= 1
コード例 #28
0
 def test_false_when_prob_of_killing_is_zero(self, example_properties):
     """
     Asserts that kill method returns False when prob_kill is zero.
     """
     herbivore = Herbivore(example_properties)
     carnivore = Carnivore(example_properties)
     herbivore.find_fitness()
     carnivore.fitness = 0.5
     assert carnivore.kill(herbivore) is False
コード例 #29
0
def test_birth(mocker):
    """Test that the animals can't reproduce if only one animal is present regardless of random
     value."""
    mocker.patch("numpy.random.random", return_value=0)
    herb = Herbivore(5, 35)
    carn = Carnivore(5, 30)
    nr_animals = 1

    assert herb.birth(nr_animals) is None
    assert carn.birth(nr_animals) is None

    mocker.patch("numpy.random.random", return_value=1)
    herb = Herbivore(5, 35)
    carn = Carnivore(5, 30)
    nr_animals = 1

    assert herb.birth(nr_animals) is None
    assert carn.birth(nr_animals) is None
コード例 #30
0
def test_init_carnivore():
    alpha = 0.001
    n = 10000
    a = Carnivore()
    norm_disp = np.random.normal(a.params["w_birth"], a.params["sigma_birth"],
                                 n)
    weight_list = []
    for _ in range(n):
        a = Carnivore()
        weight_list.append(a.weight)
    x = np.concatenate((weight_list, norm_disp))
    k2, p = stats.normaltest(x)
    assert p >= alpha
    assert a.age == 0

    a: Carnivore = Carnivore(age=2, weight=10)
    assert a.age == 2
    assert a.weight == 10