예제 #1
0
def test_neighbour_cells():
    """Test if the method 'neighbour_cell(loc)' returns the correctly
    habitable neighbours of a given localization"""
    island_maps = ("OOOOO\nOJDJO\nOMJMO\nOJMJO\nOOOOO",
                   "OOOOO\nOJMJO\nOMJMO\nOJDJO\nOOOOO",
                   "OOOOO\nOJMJO\nODJMO\nOJMJO\nOOOOO",
                   "OOOOO\nOJMJO\nOMJDO\nOJMJO\nOOOOO")
    ini_pop = [
        {
            "loc": (2, 2),
            "pop": [
                {"species": "Herbivore", "age": 5, "weight": 20}],
        }]
    for island_map in island_maps:
        t = BioSim(island_map, ini_pop, None)
        neighbours = [type(neighbour).__name__ for neighbour
                      in t.island.neighbour_cells(loc=(2, 2))]
        assert 'Desert' in neighbours
        assert len(neighbours) is 1
    island_map = ("OOOOO\nOJDJO\nOOJJO\nOJSJO\nOOOOO")
    t = BioSim(island_map, ini_pop, None)
    neighbours = [type(neighbour).__name__ for neighbour
                  in t.island.neighbour_cells(loc=(2, 2))]
    assert 'Jungle' in neighbours
    assert 'Savannah' in neighbours
    assert 'Desert' in neighbours
    assert len(neighbours) is 3
예제 #2
0
def reset_landscape_defaults():
    # no setup
    yield
    BioSim(island_map="W", ini_pop=[],
           seed=1).set_landscape_parameters('L', {'f_max': 800.0})
    BioSim(island_map="W", ini_pop=[],
           seed=1).set_landscape_parameters('H', {'f_max': 300.0})
예제 #3
0
 def biosim_with_animals(self):
     """
     Create Biosim instance with population for further testing
     """
     biosim = BioSim(island_map='WWWWW\nWLDHW\nWWWWW', plot_graph=False)
     biosim.add_population([{
         "loc": (2, 2),
         "pop": [{
             "species": "Carnivore",
             "age": 5,
             "weight": 20
         } for _ in range(20)]
     }, {
         "loc": (2, 2),
         "pop": [{
             "species": "Herbivore",
             "age": 5,
             "weight": None
         } for _ in range(50)]
     }, {
         "loc": (2, 3),
         "pop": [{
             "species": "Herbivore",
             "age": 5,
             "weight": 0
         } for _ in range(20)]
     }])
     return biosim
def test_carnivore_feed():
    """Many testes for the method 'carnivore_feed()':
    1. Test carnivore weight increases after feeding herbivore
    """
    island_map = "OOO\nOJO\nOOO"
    ini_herbs = [{
        "loc": (1, 1),
        "pop": [{
            "species": "Herbivore",
            "age": 5,
            "weight": 40
        } for _ in range(150)],
    }]
    ini_carns = [{
        "loc": (1, 1),
        "pop": [{
            "species": "Carnivore",
            "age": 5,
            "weight": 40
        } for _ in range(40)],
    }]
    t = BioSim(island_map, ini_herbs, None)
    t.add_population(ini_carns)
    loc = (1, 1)
    cell_object = t.island.cells[loc]
    carn_start_weight = np.sum(carn.weight
                               for carn in cell_object.population['Carnivore'])
    cell_object.carnivore_feed()
    carn_new_weight = np.sum(carn.weight
                             for carn in cell_object.population['Carnivore'])

    assert carn_start_weight < carn_new_weight
def test_animal_death():
    island_map = "OOO\nOJO\nOOO"
    ini_herbs = [{
        "loc": (1, 1),
        "pop": [{
            "species": "Herbivore",
            "age": 5,
            "weight": rd.randint(1, 5)
        } for _ in range(150)],
    }]
    ini_carns = [{
        "loc": (1, 1),
        "pop": [{
            "species": "Carnivore",
            "age": 5,
            "weight": rd.randint(1, 5)
        } for _ in range(40)],
    }]
    t = BioSim(island_map, ini_herbs, None)
    t.add_population(ini_carns)
    loc = (1, 1)
    cell_object = t.island.cells[loc]
    cell_object.die()
    assert len(cell_object.population["Carnivore"]) < 40
    assert len(cell_object.population["Herbivore"]) < 150
예제 #6
0
def test_population_to_cell():
    """ Tests that you can add and store animals in a cell of the map. """

    sim = BioSim(island_map="OOO\nOJO\nOOO",
                 ini_pop=[{
                     "loc": (1, 1),
                     "pop": [{
                         "species": "Herbivore",
                         "age": 1,
                         "weight": 15.0
                     }]
                 }],
                 seed=0)

    assert len(sim.map.array_map[1, 1].present_herbivores) == 1
    sim.add_population([
        {
            "loc": (1, 1),
            "pop": [
                {
                    "species": "Herbivore",
                    "age": 1,
                    "weight": 10.0
                },
                {
                    "species": "Carnivore",
                    "age": 1,
                    "weight": 10.0
                },
            ],
        },
    ])

    assert len(sim.map.array_map[1, 1].present_herbivores) + len(
        sim.map.array_map[1, 1].present_carnivores) == 3
예제 #7
0
def test_cannot_move_of_of_map():
    """ Test that you don't raise any errors when trying to leave the map """
    test_map = 'O'
    sim = BioSim(island_map=test_map, ini_pop=[], seed=3)
    sim.map.array_map[0, 0].present_herbivores.append(Herbivore(3, 20))
    sim.migration_cycle()

    assert len(sim.map.array_map[0, 0].present_herbivores) == 1
def test_set_animal_parameters():
    """Test if the method set_animal_parameters() raises a TypeError
    if it is given a non-string type parameter_key argument.

    * Test if the method set_animal_parameters() raises a TypeError
    if it is given a non-dict type parameter_values argument.

    * Test if the method set_animal_parameters() raises a ValueError
    if it is given a unknown parameter.

    * Test if the method set_animal_parameters() correctly sets the
    parameters of all species and animal_objects"""
    island_map = ("OOO\nOJO\nOOO")
    ini_pop = [{
        "loc": (1, 1),
        "pop": [{
            "species": "Herbivore",
            "age": 5,
            "weight": 20
        }, {
            "species": "Herbivore",
            "age": 5,
            "weight": 20
        }, {
            "species": "Carnivore",
            "age": 5,
            "weight": 20
        }, {
            "species": "Carnivore",
            "age": 5,
            "weight": 20
        }]
    }]
    t = BioSim(island_map, ini_pop, None)
    with pytest.raises(TypeError):
        t.set_landscape_parameters(1, {'zeta': 3.2, 'xi': 1.8})
        t.set_landscape_parameters('Herbivore', ['zeta', 3.2])
        t.set_landscape_parameters('Carnivore', ['zeta', 3.2])
    with pytest.raises(ValueError):
        t.set_animal_parameters('Herbivore', {'eeta': 3.2})
        t.set_animal_parameters('Carnivore', {'eeta': 3.2})
    loc = (1, 1)
    t.set_animal_parameters('Herbivore', {'zeta': 3.2, 'xi': 1.8})
    t.set_animal_parameters('Carnivore', {'zeta': 3.2, 'xi': 1.8})
    herb1_parameters = t.island.habitable_cells[loc].population['Herbivore'][
        0].parameters
    carn1_parameters = t.island.habitable_cells[loc].population['Carnivore'][
        0].parameters
    herb2_parameters = t.island.habitable_cells[loc].population['Herbivore'][
        0].parameters
    carn2_parameters = t.island.habitable_cells[loc].population['Carnivore'][
        0].parameters
    assert herb1_parameters['zeta'] and herb2_parameters['zeta'] is 3.2
    assert herb1_parameters['xi'] and herb2_parameters['xi'] is 1.8
    assert carn1_parameters['zeta'] and carn2_parameters['zeta'] is 3.2
    assert carn1_parameters['xi'] and carn2_parameters['xi'] is 1.8
def test_figure_saved(figfile_root):
    """Test that figures are saved during simulation"""

    sim = BioSim(
        island_map="WWWW\nWLHW\nWWWW", ini_pop=[], seed=1, img_base=figfile_root, img_fmt="png"
    )
    sim.simulate(2, vis_years=1, img_years=1)

    assert os.path.isfile(figfile_root + "_00000.png")
    assert os.path.isfile(figfile_root + "_00001.png")
예제 #10
0
def test_figure_saved(figfile_root):
    """Test that figures are saved during simulation"""

    sim = BioSim(island_map="OOOO\nOJSO\nOOOO",
                 ini_pop=[],
                 seed=1,
                 img_base=figfile_root,
                 img_fmt='png')
    sim.simulate(2, vis_years=1, img_years=1)

    assert os.path.isfile(figfile_root + '_00000.png')
    assert os.path.isfile(figfile_root + '_00001.png')
 def test_set_landscape_parameters(self):
     BioSim.set_landscape_parameters('S', {'alpha': 3.9})
     assert Savanna.alpha == 3.9
     with pytest.raises(KeyError):
         BioSim.set_landscape_parameters('B', {'alpha': 42, 'f_max': 42})
     with pytest.raises(ValueError):
         BioSim.set_landscape_parameters('S', {'alpha': 42, 'f_max': -5})
     with pytest.raises(TypeError):
         BioSim.set_landscape_parameters('S', {'alpha': 42, 'maximus': 42})
     assert Savanna.alpha == 3.9
     BioSim.set_landscape_parameters('S', {'alpha': 0.3, 'f_max': 300})
     assert Savanna.alpha == 0.3
def test_figure_saved(figfile_root):
    """Test that figures are saved during simulation"""

    sim = BioSim(
        island_geography="OOOO\nOJSO\nOOOO",
        initial_population=[],
        seed=1,
        img_base=figfile_root,
        img_fmt="png",
    )
    sim.simulate(2, vis_years=1, img_years=1)

    assert os.path.isfile(figfile_root + "_00000.png")
    assert os.path.isfile(figfile_root + "_00001.png")
예제 #13
0
def test_consistensy_simulation_one_cell_two_species():
    ini_herb = [{
        "species": "Herbivore",
        "age": 5,
        "weight": 20
    } for _ in range(100)]
    ini_carn = [{
        "species": "Carnivore",
        "age": 5,
        "weight": 20
    } for _ in range(20)]
    ini_pop = [{"loc": (2, 2), "pop": ini_herb}]
    n_herb = 0
    n_carn = 0
    for _ in range(1, 51):
        sim = BioSim(island_map="WWW\nWLW\nWWW", ini_pop=ini_pop, tmean=True)
        sim.simulate(num_years=50, vis_years=1)
        sim.add_population([{"loc": (2, 2), "pop": ini_carn}])
        sim.simulate(num_years=150, vis_years=1)
        n_herb += sim.mean["Herbivore"]
        n_carn += sim.mean["Carnivore"]
    n_herb /= 50
    n_carn /= 50
    assert n_herb == pt.approx(85, abs=17)
    assert n_carn == pt.approx(41, abs=10)
예제 #14
0
def test_consistensy_simulation_one_cell_one_species():
    n_animals = 0
    for _ in range(50):
        sim = BioSim(island_map="WWW\nWLW\nWWW",
                     ini_pop=[{
                         "loc": (2, 2),
                         "pop": [{
                             "species": "Herbivore",
                             "age": 5,
                             "weight": 20
                         } for _ in range(100)]
                     }],
                     tmean=True)
        sim.simulate(num_years=200, vis_years=None)
        n_animals += sim.mean["Herbivore"]
    assert n_animals / 50 == pt.approx(200, abs=25)
 def test_add_population(self):
     sim = BioSim()
     assert sim.island.map[(1, 2)].num_animals == 0
     sim.add_population([{
         'loc': (1, 2),
         'pop': [{
             "species": "Herbivore",
             "age": 5,
             "weight": 40
         }, {
             "species": "Carnivore",
             "age": 10,
             "weight": 14.5
         }]
     }])
     assert sim.island.map[(1, 2)].num_animals == 2
def test_herbivore_feed():
    """Many testes for the method 'herbivore_feed()':
    1. if the fodder reduces when a animal eats it.
    2. if the weight of the animal increases after eat.
    3. if the fitness of the animal updates after eat.
    """
    island_map = "OOO\nOJO\nOOO"
    ini_pop = [{
        "loc": (1, 1),
        "pop": [{
            "species": "Herbivore",
            "age": 10,
            "weight": 10
        }]
    }]
    t = BioSim(island_map, ini_pop, None)
    loc = (1, 1)
    previous_fodder = t.island.cells[loc].fodder
    previous_herbivore_weight = t.island.cells[loc].population['Herbivore'][
        0].weight
    previous_herbivore_fitness = t.island.cells[loc].population['Herbivore'][
        0].fitness
    t.island.cells[loc].herbivore_feed()
    afterwards_fodder = t.island.cells[loc].fodder
    afterwards_herbivore_weight = t.island.cells[loc].population['Herbivore'][
        0].weight
    afterwards_herbivore_fitness = t.island.cells[loc].population['Herbivore'][
        0].fitness
    assert previous_fodder > afterwards_fodder
    assert previous_herbivore_weight < afterwards_herbivore_weight
    assert previous_herbivore_fitness is not afterwards_herbivore_fitness
def test_migration():
    """This tests the migration method checking if the animals have
    moved to the all 4th neighbour cells."""
    island_map = "OOOOO\nOMJMO\nOJDJO\nOMJMO\nOOOOO"
    ini_pop = [{
        "loc": (2, 2),
        "pop": [{
            "species": "Herbivore",
            "age": np.random.randint(1, 5),
            "weight": np.random.randint(20, 40)
        } for _ in range(1000)],
    }]

    t, loc = BioSim(island_map, ini_pop, 1), (2, 2)

    for k, v in t.island.habitable_cells.items():
        v.migrate(t.island.neighbour_cells(k))

    for k, v in t.island.habitable_cells.items():
        v.add_new_migrated()

    north_neighbour = t.island.cells[(1, 2)].population['Herbivore']
    south_neighbour = t.island.cells[(3, 2)].population['Herbivore']
    west_neighbour = t.island.cells[(2, 1)].population['Herbivore']
    east_neighbour = t.island.cells[(2, 3)].population['Herbivore']

    assert north_neighbour is not 0
    assert south_neighbour is not 0
    assert west_neighbour is not 0
    assert east_neighbour is not 0
def test_animal_got_old():
    """Test if the method 'get_old()' correctly increases in 1 year all
    the animal_objects stored in a specific geo_object"""
    island_map = "OOOOO\nOJJJO\nOOOOO"
    ini_pop = [{
        "loc": (1, 2),
        "pop": [{
            "species": "Herbivore",
            "age": 5,
            "weight": 20
        }, {
            "species": "Herbivore",
            "age": 2,
            "weight": 20
        }],
    }]
    t, loc = BioSim(island_map, ini_pop, None), (1, 2)
    geo_object = t.island.habitable_cells[loc]
    herb_object_1 = geo_object.population['Herbivore'][0]
    herb_object_2 = geo_object.population['Herbivore'][1]
    herb_young_1 = herb_object_1.age
    herb_young_2 = herb_object_2.age
    geo_object.get_old()
    herb_older_1 = herb_object_1.age
    herb_older_2 = herb_object_2.age
    assert herb_older_1 is (herb_young_1 + 1)
    assert herb_older_2 is (herb_young_2 + 1)
def test_initial_population():
    """Test that population can be placed on construction"""

    BioSim(island_map="WWWW\nWLHW\nWWWW",
           ini_pop=[{
               'loc': (2, 2),
               'pop': [{
                   'species': 'Herbivore',
                   'age': 1,
                   'weight': 10.
               }, {
                   'species': 'Carnivore',
                   'age': 1,
                   'weight': 10.
               }]
           }, {
               'loc': (2, 3),
               'pop': [{
                   'species': 'Herbivore',
                   'age': 1,
                   'weight': 10.
               }, {
                   'species': 'Carnivore',
                   'age': 1,
                   'weight': 10.
               }]
           }],
           seed=1)
def test_animal_loose_weight():
    """Test if the method 'lose_weight()' correctly looses the weight
    of the animal"""
    island_map = "OOOOO\nOJJJO\nOOOOO"
    ini_pop = [{
        "loc": (1, 2),
        "pop": [{
            "species": "Herbivore",
            "age": 5,
            "weight": 20
        }, {
            "species": "Herbivore",
            "age": 2,
            "weight": 20
        }],
    }]
    t, loc = BioSim(island_map, ini_pop, None), (1, 2)
    geo_object = t.island.habitable_cells[loc]
    herb_object_1 = geo_object.population['Herbivore'][0]
    herb_object_2 = geo_object.population['Herbivore'][1]
    before_weight_herb1 = herb_object_1.weight
    before_weight_herb2 = herb_object_2.weight
    geo_object.lose_weight()
    after_weight_herb1 = herb_object_1.weight
    after_weight_herb2 = herb_object_2.weight
    assert before_weight_herb1 > after_weight_herb1
    assert before_weight_herb2 > after_weight_herb2
예제 #21
0
def test_get_population_numbers():
    """Test if the method 'get_population_numbers()' correctly gets the
    entire population of each geo_object and returns a dictionary, such
    that: {'Row': [], 'Col': [], 'Herbivore': [], 'Carnivore': []}"""
    island_map = "OOOOO\nOJJJO\nOOOOO"
    ini_pop = [
        {"loc": (1, 1),
         "pop": [{"species": "Herbivore", "age": 5, "weight": 20},
                 {"species": "Herbivore", "age": 5, "weight": 20},
                 {"species": "Carnivore", "age": 5, "weight": 20}]},
        {"loc": (1, 2),
         "pop": [{"species": "Herbivore", "age": 5, "weight": 20},
                 {"species": "Carnivore", "age": 5, "weight": 20}]}]

    t = BioSim(island_map, ini_pop, None)
    pop = t.island.get_population_numbers()
    row_loc, col_loc = pop['Row'][0], pop['Col'][0]
    pop_herb, pop_carn = pop['Herbivore'][0], pop['Carnivore'][0]
    assert (row_loc and col_loc and pop_herb and pop_carn) is 0

    row_loc, col_loc = pop['Row'][6], pop['Col'][6]
    pop_herb, pop_carn = pop['Herbivore'][6], pop['Carnivore'][6]
    assert row_loc and col_loc is 1 and pop_herb is 2 and pop_carn is 1

    row_loc, col_loc = pop['Row'][7], pop['Col'][7]
    pop_herb, pop_carn = pop['Herbivore'][7], pop['Carnivore'][7]
    assert row_loc is 1 and col_loc is 2 and pop_herb and pop_carn is 1
예제 #22
0
def test_animal_got_old():
    """Test if the method 'get_old()' correctly increases in 1 year a
    specie_object age"""
    island_map = "OOOOO\nOJJJO\nOOOOO"
    ini_pop = [{
        "loc": (1, 2),
        "pop": [{
            "species": "Herbivore",
            "age": 5,
            "weight": 20
        }, {
            "species": "Carnivore",
            "age": 4,
            "weight": 20
        }],
    }]
    t, loc = BioSim(island_map, ini_pop, None), (1, 2)
    herb_object = t.island.habitable_cells[loc].population['Herbivore'][0]
    carn_object = t.island.habitable_cells[loc].population['Carnivore'][0]
    herb_age_1 = herb_object.age
    carn_age_1 = carn_object.age
    herb_object.get_old()
    carn_object.get_old()
    herb_age_2 = herb_object.age
    carn_age_2 = carn_object.age
    assert herb_age_2 is (herb_age_1 + 1)
    assert carn_age_2 is (carn_age_1 + 1)
def test_simulation_large_island():
    """Test to see that a island with column or row length bigger than 23
    initialize self._large_island.
    """
    map = """\
               OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
               ODDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDO
               ODDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDO
               ODDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDO
               ODDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDO
               ODDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDO
               ODDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDO
               ODDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDO
               OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"""
    sim = BioSim(island_map=map, ini_pop=[], seed=1)
    sim.simulate(1, 1)
    assert sim._large_island
def test_invalid_boundary(bad_boundary):
    """Non-ocean boundary must raise error"""
    with pytest.raises(ValueError):
        BioSim(
            island_map="{}OO\nOJO\nOOO".format(bad_boundary),
            ini_pop=[],
            seed=1,
        )
예제 #25
0
def test_change_weight_simulation():
    """ Tests that a herbivore living in a jungle cell will gain weight. """

    sim = BioSim(island_map="OOO\nOJO\nOOO",
                 ini_pop=[{
                     "loc": (1, 1),
                     "pop": [{
                         "species": "Herbivore",
                         "age": 1,
                         "weight": 35.0
                     }]
                 }],
                 seed=0)

    assert sim.map.array_map[1, 1].present_herbivores[0].weight == 35.0
    sim.simulate(5)
    assert sim.map.array_map[1, 1].present_herbivores[0].weight != 35.0
def test_invalid_boundary(bad_boundary):
    """Non-ocean boundary must raise error"""
    with pytest.raises(ValueError):
        BioSim(
            island_geography="{}OO\nOJO\nOOO".format(bad_boundary),
            initial_population=[],
            seed=1,
        )
    def test_sim_with_seed(self):
        sim1 = BioSim(seed=1)
        sim1.clean_simulation(10)
        num_sim1 = sim1.num_animals_per_species

        sim2 = BioSim(seed=1)
        sim2.clean_simulation(10)
        num_sim2 = sim2.num_animals_per_species

        assert num_sim1 == num_sim2
    def test_simulate(self):
        sim = BioSim(img_base=r'test_sim_every_second_img')
        sim.simulate(10, img_years=2)
        assert os.path.isfile(r'test_sim_every_second_img' + '_00005' + '.png')
        assert not os.path.isfile(r'test_sim_every_second_img' + '_00006' +
                                  '.png')

        with pytest.raises(ValueError):
            sim = BioSim(img_base=r'test_sim')
            sim.simulate(10, 5, 4)
예제 #29
0
 def test_map_from_str(self):
     """
     Test that the map string is properly saved
     """
     island_map = """WWW
             WDW
             WWW"""
     sim = BioSim(island_map=island_map)
     assert sim._island.map_str == island_map
def test_set_plot_limits():
    """Test that y-axis and color limits for plots can be set."""
    BioSim(
        island_map="W",
        ini_pop=[],
        seed=1,
        ymax_animals=20,
        cmax_animals={"Herbivore": 10, "Carnivore": 20},
    )