Esempio n. 1
0
def test_environment_parameter():
    e = Lowlands()
    assert e.environment is not None
    assert type(e.environment) == str
    def __init__(self,
                 island_map=None,
                 ini_pop=[],
                 seed=None,
                 ymax_animals=20,
                 cmax_animals={
                     'Herbivore': 10,
                     'Carnivore': 20
                 },
                 hist_specs=None,
                 img_dir=None,
                 img_name=_DEFAULT_GRAPHICS_NAME,
                 img_fmt='png',
                 img_base=None):
        if seed is None:
            random.seed(100)
        else:
            random.seed(seed)
        self.island = []
        self.letter_island = island_map
        self.total_herb_pop = 0
        self.total_carn_pop = 0
        self.num_animals = 0
        self.num_animals_per_species = {'Carnivore': 0, 'Herbivore': 0}
        self.cycles = 50
        self._fig = None
        self._herb_heat = None
        self._herb_axis = None
        self._carn_heat = None
        self._carn_axis = None
        self._mean_ax = None
        self._mean_line = None
        self.island_map = None
        self._img_ctr = 0
        self._img_fmt = img_fmt
        self.herbivore_line = None
        self.carnivore_line = None
        self.animal_dictionary = {}
        self.island_dataframe = None
        self.herbivore_dataframe = None
        self.carnivore_dataframe = None
        self.year = 0
        self.final_year = None
        self.axt = None

        if img_dir is not None:
            self._img_base = os.path.join(img_dir, img_name)
        else:
            self._img_base = img_base
        self.map_split = island_map.split('\n')
        self.map_length = len(self.map_split[0])
        for index in range(len(self.map_split)):
            if len(self.map_split[index - 1]) != self.map_length:
                raise ValueError("All map rows must be have equal lenght.")

        if len(self.map_split) > 3:
            if 'L' in (self.map_split[0] or self.map_split[-1]):
                raise ValueError('The island must be surrounded by water')
            elif 'H' in (self.map_split[0] or self.map_split[-1]):
                raise ValueError('The island must be surrounded by water')
            elif 'D' in (self.map_split[0] or self.map_split[-1]):
                raise ValueError('The island must be surrounded by water')

            for row in self.map_split:
                if row[0] != 'W':
                    raise ValueError('The island must be surrounded by water')
                elif row[-1] != 'W':
                    raise ValueError('The island must be surrounded by water')

        for letter in island_map:
            if letter == 'W':
                self.island.append(IslandCell(Water()))
            elif letter == 'L':
                self.island.append(IslandCell(Lowlands()))
            elif letter == 'H':
                self.island.append(IslandCell(Highlands()))
            elif letter == 'D':
                self.island.append(IslandCell(Desert()))
            elif letter == '\n':
                pass
            else:
                raise ValueError(
                    "Input map must consist of Water ('W'), Lowland('L'),\
                                 Desert('D'), Highland('H')")
        # Give each cell its coordinate
        r = 1
        c = 1
        i = 0
        for cell in self.island:
            cell.coordinate = (r, c)
            c += 1
            i += 1
            if i == (self.map_length * r):
                r += 1
                c = 1
        # find each cells neighboring cells
        for cell in self.island:
            index = self.island.index(cell)
            if index + 1 <= len(self.island) - 1:
                cell.neighbors[0] = self.island[index + 1]
            if index - 1 >= 0:
                cell.neighbors[1] = self.island[index - 1]
            if index - self.map_length > 0:
                cell.neighbors[2] = self.island[index - self.map_length]
            if index + self.map_length < len(self.island):
                cell.neighbors[3] = self.island[index + self.map_length]

        # find index to place animals in

        if type(ini_pop) != list:
            raise TypeError('Input population must be a list')
        elif len(ini_pop) == 0:
            pass
        elif type(ini_pop[0]) != dict:
            raise TypeError('Input population list must contain a dictionary')
        else:
            for key in ini_pop[0]:
                if key not in ['loc', 'pop']:
                    raise KeyError(
                        'Input population dictionary must only contain loc and pop'
                    )
                elif key == 'loc':
                    if type(ini_pop[0][key]) != tuple:
                        TypeError('Input location must be a tuple')
                    elif len(ini_pop[0][key]) != 2:
                        raise IndexError(
                            'Input loc must consist of two numbers')
                    else:
                        for value in ini_pop[0][key]:
                            if type(value) != int:
                                raise TypeError(
                                    "Input loc tuple must consist of two integers"
                                )
                            elif value <= 0:
                                raise ValueError(
                                    "Input integer must be a positive number and not zero"
                                )
                        for cell in self.island:
                            if cell.coordinate == ini_pop[0]['loc']:
                                index = self.island.index(cell)
                elif key == 'pop':
                    if type(ini_pop[0][key]) != list:
                        raise TypeError('Input population must be a list')
                    else:
                        for dic in ini_pop[0][key]:
                            if type(dic) != dict:
                                raise TypeError(
                                    'Input population must come in the form of dictionaries '
                                    'in the list')
                            elif len(dic) != 3:
                                raise ValueError(
                                    "Dictionary must contain three keys: species,age,weight"
                                )
                            elif "species" and "age" and "weight" not in dic:
                                raise ValueError(
                                    "Dictionary must contain three keys: species,age,weight"
                                )
                            elif type(dic['age']) != int and type(
                                    'weight') not in [int, float]:
                                raise ValueError(
                                    "Age must be an integer and weight must be an integer or float"
                                )
                            elif dic['age'] < 0 or dic['weight'] <= 0:
                                raise ValueError(
                                    "Age must be a positive number and \
                                weight must not equal zero and be positive")
                            elif dic['species'] not in [
                                    'Herbivore', 'Carnivore'
                            ]:
                                raise NameError(
                                    'Species must be a herbivore or carnivore')

                            elif dic['species'] == 'Herbivore':
                                if self.island[
                                        index].location.environment == 'W':
                                    raise TypeError(
                                        "Animals can't swim, do not place them in water"
                                    )
                                self.island[index].cell_herb_pop.append \
                                    (Herbivore(dic['age'], dic['weight']))
                            else:
                                self.island[index].cell_carn_pop.append \
                                    (Carnivore(dic['age'], dic['weight']))
Esempio n. 3
0
def test_rest_food():
    e = Lowlands()
    e.food = None
    e.reset_food()
    assert e.food is not None
Esempio n. 4
0
 def test_lowlands_list_as_params(self):
     """
     Test to see if an error is raised when inserting a list as environment params
     """
     with pytest.raises(TypeError):
         assert Lowlands().set_lowlands_params(['f_max', 70])
Esempio n. 5
0
def test_food():
    e = Lowlands()
    assert e.food is not None
Esempio n. 6
0
 def test_lowlands_fmax_negative(self):
     """
     Test to see if an error is raised when giving f_max a negative number
     """
     with pytest.raises(ValueError):
         assert Lowlands().set_lowlands_params({'f_max': -800})
Esempio n. 7
0
 def test_lowlands_wrong_param(self):
     """
     Test to see if an error is raised when inserting a parameter
     """
     with pytest.raises(KeyError):
         assert Lowlands().set_lowlands_params({'food': 700})