def create_map_dict(self):
        """
        Iterates through geography dictionary and creates a new dictionary of
        the entire map. This dict has coordinates as keys and
        instances of landscape classes as values. Each landscape instance has
        the population list of it's coordinate as input.

        :raise ValueError: if invalid landscape type is given in geography
            string
        """
        self.create_geography_dict()
        self.create_population_dict()

        for location, landscape_type in self.geography.items():
            if landscape_type is "J":
                if location in self.population.keys():
                    self.map[location] = Jungle(self.population[location])
                else:
                    self.map[location] = Jungle([])
            elif landscape_type is "S":
                if location in self.population.keys():
                    self.map[location] = Savannah(self.population[location])
                else:
                    self.map[location] = Savannah([])
            elif landscape_type is "D":
                if location in self.population.keys():
                    self.map[location] = Desert(self.population[location])
                else:
                    self.map[location] = Desert([])
            elif landscape_type is "O":
                self.map[location] = Ocean([])
            elif landscape_type is "M":
                self.map[location] = Mountain([])
            else:
                raise ValueError(f"Invalid landscape type {landscape_type}")
Esempio n. 2
0
    def build_map(self):
        """
        Builds island based on input string.
        Island biomes are placed in a two dimensional array
        """

        geography = [
            list(row) for row in self.island_map.replace(" ", "").split("\n")
        ]
        for row in geography:
            temp = []
            for cell in row:
                if cell == "J":
                    temp.append(Jungle())
                elif cell == "S":
                    temp.append(Savannah())
                elif cell == "D":
                    temp.append(Desert())
                elif cell == "M":
                    temp.append(Mountain())
                elif cell == "O":
                    temp.append(Ocean())
                else:
                    raise ValueError('"{}" is not properly defined! '
                                     'Use capital letters.')
            self.island_temp.append(temp)
        self.island = np.array(self.island_temp)
 def landscape_data(self, animal_objects):
     carn1, carn2, herb1, herb2 = animal_objects
     animals = {'Herbivore': [herb1, herb2], 'Carnivore': [carn1, carn2]}
     landscapes_dict = {
         'S': Savannah(),
         'O': Ocean(),
         'D': Desert(),
         'M': Mountain(),
         'J': Jungle()
     }
     for species, animals in animals.items():
         for animal in animals:
             landscapes_dict['S'].add_animal(animal)
             landscapes_dict['D'].add_animal(animal)
             landscapes_dict['J'].add_animal(animal)
     return landscapes_dict
Esempio n. 4
0
    def landscape_data(self, animal_objects):
        herb1, herb2, carn1, carn2 = animal_objects
        animals = {'Herbivore': [herb1, herb2], 'Carnivore': [carn1, carn2]}

        landscapes_dict = {
            'W': Water(),
            'H': Highland(),
            'L': Lowland(),
            'D': Desert()
        }
        for species, animals in animals.items():
            for animal in animals:
                landscapes_dict['L'].add_animal(animal)
                landscapes_dict['D'].add_animal(animal)
                landscapes_dict['H'].add_animal(animal)
        return landscapes_dict
Esempio n. 5
0
    def array_to_island(self):
        """
        Converts the array from the method string_to_array into a island.

        changes the array consisting of strings into an array consisting of
        instances of classes depedning on the letter that was previously in
        the array, for example 'J' would turn into an instance of the
        Jungle-class. These are stored in Island.cells

        Returns
        -------

        Raises
        ------
        SyntaxError
            If self.map contain other letters than 'J', 'S', 'D', 'O', 'M'.

        """

        array_map = self.string_to_array()
        array_shape = np.shape(array_map)   # type: tuple

        nested = list(np.zeros(array_shape))
        for i, e in enumerate(nested):
            nested[i] = list(e)

        for i in range(array_shape[0]):
            for j in range(array_shape[1]):
                if array_map[i, j] == 'J':
                    nested[i][j] = Jungle()
                elif array_map[i, j] == 'S':
                    nested[i][j] = Savannah()
                elif array_map[i, j] == 'D':
                    nested[i][j] = Desert()
                elif array_map[i, j] == 'O':
                    nested[i][j] = Ocean()
                elif array_map[i, j] == 'M':
                    nested[i][j] = Mountain()
                else:
                    raise SyntaxError("Island geography multi-line string "
                                      "must only have these letters: "
                                      "'J', 'S', 'D', 'O', 'M'")

        self.cells = np.array(nested)
Esempio n. 6
0
    def desert(self):
        """Creates a fixture of a desert class instance.

        """
        return Desert()
 def test_grow(self):
     desert = Desert()
     desert.fodder_regrow()
     assert desert.get_fodder() == 0
 def test_init(self):
     desert = Desert()
     assert type(desert.present_herbivores) is list
     assert type(desert.present_carnivores) is list
     assert desert.get_fodder() == 0
    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']))
 def desert_cell(self):
     """Create basic desert instance"""
     return Desert()
 def desert(self):
     return Desert()
 def test_constructor_desert(self, example_pop_herb):
     """
     Asserts that Desert class enables initialization of class instances.
     """
     desert = Desert(example_pop_herb)
     assert isinstance(desert, Desert)
Esempio n. 13
0
 def test_init(self):
     desert = Desert()
     assert type(desert.herbivores) is list
     assert type(desert.carnivores) is list
     assert desert.fodder == 0
     assert desert.passable is True