Exemplo n.º 1
0
    def test_get_current_time(self):
        solution = Solution(temp_test_case, 1, 100)
        solution.answer = list(temp_test_case)
        solution.alphas = [1, 1, 1]

        ans = Solution.get_current_time(solution, 'Kraków',
                                        solution.all_available_time)
        [current_time, currently_available_time] = ans

        self.assertEqual(0, current_time)
        self.assertEqual(73, currently_available_time
                         )  # 100-[Warszawa(15)+trasa(2)+Lublin(10)] = 73

        # ---------------------------------------------------

        solution = Solution(temp_test_case_2, 1, 100)
        solution.answer = list(temp_test_case)
        solution.alphas = [1, 1, 1]

        ans = Solution.get_current_time(solution, 'Warszawa',
                                        solution.all_available_time)
        [current_time, currently_available_time] = ans

        self.assertEqual(0, current_time)
        self.assertEqual(50, currently_available_time
                         )  # 100-[Kraków(30)+trasa(2)+Lublin(20)] = 50
Exemplo n.º 2
0
 def test_solution_functions(self):
     rating1 = [3, 2, 1, 3]
     skill1 = [[1, 1, 2, 2], [2, 1, 1, 2], [1, 1, 2, 1]]
     sol1 = [2, 2, 0, 0]
     solution1 = Solution(employee_number=3,
                          company_number=len(sol1),
                          premade_list=sol1)
     self.assertEqual(solution1.f_target(rating1, skill1), 13)
     emp_time = [1.5, 2, 1]
     comp_time = [1, 1, 0.5, 0.5]
     parameters = Parameters(rating1, skill1, emp_time, comp_time)
     self.assertEqual(solution1.f_penalty(emp_time, comp_time), 4)
     self.assertEqual(solution1.adaptation(parameters), 9)
Exemplo n.º 3
0
def load_populacja(params: Parameters) -> Population:
    temp_employee_number = 0
    temp_company_number = 0
    population_size = 0
    solutions = []
    f = open("populacja.txt", "r")
    f_lines = f.readlines()
    for i in range(len(f_lines)):
        if f_lines[i] == 'EMPLOYEE_NUMBER' + '\n':
            temp_employee_number = int(f_lines[i + 1])
        if f_lines[i] == 'COMPANY_NUMBER' + '\n':
            temp_company_number = int(f_lines[i + 1])
        if f_lines[i] == 'POPULATION_NUMBER' + '\n':
            population_size = int(f_lines[i + 1])
        if f_lines[i] == 'POPULATION_MEMBERS' + '\n':
            for j in range(population_size):
                solutions.append(line2list(f_lines[i + 1 + j]))
    f.close()
    solution_list = []
    for j in range(population_size):
        solution_list.append(
            Solution(temp_employee_number,
                     temp_company_number,
                     premade_list=solutions[j]))
    return Population(params, solution_list)
Exemplo n.º 4
0
    def test_init(self):
        solution = Solution(temp_test_case, 10, 100)

        self.assertEqual(len(temp_test_case), len(solution.answer))
        self.assertEqual(len(temp_test_case), len(solution.alphas))
        self.assertEqual(100, solution.all_available_time)
        self.assertEqual(len(temp_test_case), len(solution.t_displacement))
        self.assertEqual(temp_test_case, solution.test_case)
Exemplo n.º 5
0
    def test_set_and_get_solution(self):
        board = Board()

        room = random.choice(list(board.rooms.items()))
        player_card = random.choice(list(board.player_cards.items()))
        weapon = random.choice(list(board.weapons.items()))

        room = {room[0]: room[1]}
        player_card = {player_card[0]: player_card[1]}
        weapon = {weapon[0]: weapon[1]}

        solution = Solution(room, player_card, weapon)
        r, p, w = solution.get_solution()

        self.assertEqual(r, room)
        self.assertEqual(p, player_card)
        self.assertEqual(w, weapon)
Exemplo n.º 6
0
    def test_check_solution(self):
        board = Board()

        room = random.choice(list(board.rooms.items()))
        player_card = random.choice(list(board.player_cards.items()))
        weapon = random.choice(list(board.weapons.items()))

        room = {room[0]: room[1]}
        player_card = {player_card[0]: player_card[1]}
        weapon = {weapon[0]: weapon[1]}

        solution = Solution(room, player_card, weapon)

        b = solution.check_solution(list(room.values())[0], list(player_card.values())[0], list(weapon.values())[0])
        self.assertEqual(b, True)

        b = solution.check_solution('h', list(player_card.values())[0], list(weapon.values())[0])
        self.assertEqual(b, False)
Exemplo n.º 7
0
    def test_it_instanciates_a_user(self):
        expectedLon = 3.879483
        expectedLat = 43.608177

        user = Solution(lines, StringToDecimal).user()

        assert isinstance(user, User)
        assert user.lat == expectedLat
        assert user.lon == expectedLon
Exemplo n.º 8
0
 def matrix_to_solution(self, matrix: List[List[bool]]) -> Solution:
     """
     transforms a two-dimensional binary list into a chromosome
     """
     cars: List[Car] = [
         Car(self.dataset.bonus) for _ in range(self.dataset.ncars)
     ]
     solution: Solution = Solution(cars, self.dataset.rides.copy())
     solution.matrix_allocation(matrix)
     return solution
Exemplo n.º 9
0
def algorithm(test_case: dict, velocity: int, available_time: int, t_max: int,
              t_min: int, num_of_neig: int, len_of_sol: int) -> List[Solution]:

    solution = Solution(test_case, velocity, available_time)
    current_solution = deepcopy(solution)
    best_solutions = []

    for temperature in range(t_max, t_min, -1):
        solution = deepcopy(current_solution)
        temp_list = []
        for iterator in range(0, num_of_neig):
            if_not_exist = Solution.neighborhood_of_solution(solution)
            temp_list.append((deepcopy(solution), if_not_exist))
            if if_not_exist:
                break
        temp_list.sort(key=lambda sol: sol[0].satisfaction_points,
                       reverse=True)
        if_not_exist = temp_list[0][1]
        solution = temp_list[0][0]

        if if_not_exist:
            if_doesnt_work = Solution.neigh_if_few_test_cases(solution)
            if if_doesnt_work:
                best_solutions.append(current_solution)
                break

        next_solution = deepcopy(solution)

        difference_of_energy = next_solution.satisfaction_points - current_solution.satisfaction_points

        if difference_of_energy > 0:
            current_solution = next_solution
            best_solutions.append(next_solution)
        elif exp(difference_of_energy / temperature) > random():
            current_solution = next_solution

        if len(best_solutions) > len_of_sol:
            best_solutions.sort(key=lambda sol: sol.satisfaction_points)
            del best_solutions[0]

    return best_solutions
Exemplo n.º 10
0
    def generate_public_cards_and_solution(self, player_cards, rooms, weapons,
                                           players):
        """Generates the card deck and the solution to the game, deals out the cards to the players
        
        Args:
            player_cards: the dict of player_cards
            rooms: the dict of rooms
            weapons: the dict of weapons
            players: the dict of players

        Returns:
            Arr: all the cards which can be taken by the players
            CardDeck: the empty card deck for some reason ( I should of removed this as a return )
            Solution: the solution to the game

        """
        public_cards = player_cards | rooms | weapons

        player_cards_chosen = random.choice(list(player_cards.items()))
        rooms_chosen = random.choice(list(rooms.items()))
        weapons_chosen = random.choice(list(weapons.items()))

        del public_cards[player_cards_chosen[0]]
        del public_cards[rooms_chosen[0]]
        del public_cards[weapons_chosen[0]]

        solution = Solution({rooms_chosen[0]: rooms_chosen[1]},
                            {player_cards_chosen[0]: player_cards_chosen[1]},
                            {weapons_chosen[0]: weapons_chosen[1]})
        card_deck = CardDeck()
        card_deck.convert_dict_and_add_to_deck(public_cards)

        # The most simplistic method was a buggy mess for some reason so I just had to improvise with a not so efficient method instead

        cards = []
        card_dicts = []
        player_objs = list(players.values())

        for c in range(len(card_deck)):
            cards.append(card_deck.pop_card())

        cards_split = np.array_split(cards, len(players))

        for i in range(len(players)):
            card_dicts.append(
                {k: v
                 for d in cards_split[i] for k, v in d.items()})

        for i in range(len(player_objs)):
            player_objs[i].hand.convert_dict_and_add_to_deck(card_dicts[i])

        return public_cards, card_deck, solution
Exemplo n.º 11
0
    def solve(self):
        # housekeeping
        step_counter = 0

        # loop through iterations approximating solution, storing values and
        # times used in this instance's meshes
        while self.current_time < self.end_time:
            # housekeeping variable
            step_counter += 1
            # performs operations on instance variables
            self.forward_step(step_counter)

        self.solution = Solution(self.time_mesh, self.value_mesh, str(self))
Exemplo n.º 12
0
    def __init__(self, ivp, end_time):
        """ Initialising instance variables """
        # simple setting of input values
        self.ivp = ivp
        self.current_time = self.ivp.initial_time
        self.end_time = end_time

        # produces empty time and value meshes
        self.time_mesh = self.build_time_mesh()
        self.value_mesh = self.build_value_mesh(self.ivp.get_dimension())

        # creates empty solution object for print method
        self.solution = Solution(self.time_mesh, self.value_mesh, str(self))
Exemplo n.º 13
0
 def __init__(self, parameters: Parameters, test_list: List[Solution] = None):
     # Population posiada pola: lista główna osobników tj. rozwiązań, tu trafia lista po inicjalizacji i po danym
     # etapie algorytmu, lista tymczasowa, uzywana w operatorach do przechowania potomków przed zmergowaniem z listą
     # główną (elitaryzm?), parametry algorytmu.
     if not test_list:
         self.main_list = [Solution(employee_number=len(parameters.skills_matrix),
                                    company_number=len(parameters.skills_matrix[0]))
                           for i in range(parameters.population_count)]
     elif len(test_list) != parameters.population_count:
         raise MeasuresError
     else:
         self.main_list = test_list
     self.temporary_list = None
     self.parameters = parameters
Exemplo n.º 14
0
    def test_count_satisfaction_points(self):

        solution = Solution(temp_test_case, 10, 100)

        solution.answer = list(temp_test_case)
        solution.alphas = [1, 1, 1]
        Solution.count_satisfaction_points(solution)

        self.assertEqual(10, solution.satisfaction_points)
Exemplo n.º 15
0
 def test_population_init(self):
     rating1 = [1, 2, 3.5, 4, 5]  # 5 firm
     skill1 = [[2, 2, 1, 3, 2], [1, 1, 1, 2, 1], [2, 3, 2, 1,
                                                  1]]  # 3 pracowników
     emp_time1 = [1.8, 2, 0.7]
     comp_time1 = [1, 2, 2.5, 1.5, 0.8]
     params = Parameters(rating=rating1,
                         skills_matrix=skill1,
                         employee_time=emp_time1,
                         company_time=comp_time1)
     current_population = Population(parameters=params)
     self.assertEqual(len(current_population.main_list), 10)
     custom_list = [
         Solution(employee_number=len(params.skills_matrix),
                  company_number=len(params.skills_matrix[0]))
         for i in range(5)
     ]
     with self.assertRaises(MeasuresError):
         Population(parameters=params, test_list=custom_list)
Exemplo n.º 16
0
 def create_random_population(self):
     """
     creates random population with size equal to max_population_size
     """
     start = tm.time()
     progress = tqdm(total=self.max_population_size,
                     desc='Creating first random population')
     while len(self.population) < self.max_population_size:
         cars: List[Car] = [
             Car(self.dataset.bonus) for _ in range(self.dataset.ncars)
         ]
         random_solution: Solution = Solution(cars,
                                              self.dataset.rides.copy())
         random_solution.randomize_allocation()
         self.population.append(random_solution)
         progress.update(1)
         progress.set_postfix_str(
             'Generated Chromosomes = {}, Time Elapsed = {:.2f} seconds'.
             format(len(self.population),
                    tm.time() - start))
     progress.close()
     progress.clear()
Exemplo n.º 17
0
    def greedy_solve(self) -> Solution:
        def manhattan_distance(v1, v2):
            return abs(v1[0] - v2[0]) + abs(v1[1] - v2[1])

        solution = Solution([Car(self.bonus) for _ in range(self.ncars)],
                            self.rides.copy())

        step = 0
        progress = tqdm(total=self.steps, desc='Building initial solution')

        while step < self.steps:

            for car in solution.cars:

                if car.step > step:
                    continue

                ride_priority = [
                    sys.maxsize for _ in solution.unallocated_rides
                ]

                rides_available: bool = False

                for ride_id, ride in enumerate(solution.unallocated_rides):

                    distance_to_car = manhattan_distance(
                        car.position, ride.orig)

                    if step + distance_to_car > self.steps:
                        continue

                    if step + distance_to_car + ride.distance > ride.latest_finish:
                        continue

                    earliest_start = ride.earliest_start - step
                    ride_priority[ride_id] = abs(distance_to_car -
                                                 earliest_start)

                    rides_available = True

                if not rides_available:
                    continue

                ride_id = None
                priority = sys.maxsize
                for ri, rp in enumerate(ride_priority):
                    if rp < priority:
                        ride_id = ri
                        priority = rp

                ride = solution.unallocated_rides[int(ride_id)]

                distance_to_car = manhattan_distance(car.position, ride.orig)
                ride_start = max([step + distance_to_car, ride.earliest_start])
                car.step = ride_start + ride.distance

                car.allocate_ride(ride)
                car.position = ride.dest
                solution.unallocated_rides.remove(ride)

            step += 1
            progress.update(1)

        progress.close()

        return solution
Exemplo n.º 18
0
 def empty_solution(self) -> Solution:
     return Solution([Car(self.bonus) for _ in range(self.ncars)],
                     self.rides.copy())
Exemplo n.º 19
0
 def test0(self):
     s0 = Solution(open("test_data/0.in"))
     result = s0.solve()
     self.assertEqual(result[0], "Case #1: 2 1")
     self.assertEqual(result[1], "Case #2: IMPOSSIBLE")
     self.assertEqual(result[2], "Case #3: 1 1")
Exemplo n.º 20
0
 def test_it_returns_the_closest_defibrilator(self):
     assert Solution(lines, StringToDecimal).getClosest(
         Algorithm).name() == "Maison de la Prevention Sante"
Exemplo n.º 21
0
    def test_it_creates_an_array_of_defibrilators(self):
        defibrilators = Solution(lines, StringToDecimal).defibrilators()

        assert len(defibrilators) == 3
        for defibrilator in defibrilators:
            assert isinstance(defibrilator, Defibrilator)
Exemplo n.º 22
0
 def test1(self):
     s0 = Solution(open("test_data/1.in"))
     result = s0.solve()
     self.assertEqual(result[0], "Case #1: 1 25")
     self.assertEqual(result[1], "Case #2: 2 1")
Exemplo n.º 23
0
 def test_cannot_be_instanciate_without_a_StringFormator(self):
     with self.assertRaises(ValueError):
         Solution(lines, None)
Exemplo n.º 24
0
 def test_cannot_be_instanciate_without_lines(self):
     with self.assertRaises(ValueError):
         Solution(None, StringToDecimal)
Exemplo n.º 25
0
 def test2(self):
     s0 = Solution(open("test_data/2.in"))
     result = s0.solve()
     self.assertEqual(result[0], "Case #1: 8 29")
     self.assertEqual(result[1], "Case #2: 2 9")
     self.assertEqual(result[2], "Case #3: 83 100")
Exemplo n.º 26
0
import pytest
from src.solution import Solution

s = Solution()

def test_case0():
    assert s.removeElement([3, 2, 2, 3], 3) == 2
Exemplo n.º 27
0
 def test0(self):
     s0 = Solution(open("test_data/0.in"))
     result = s0.solve()
     self.assertEqual(result[0], "Case #1: None")
Exemplo n.º 28
0
import random
import copy

from src.solution import Solution

n_courses = 3
table_sizes = [8, 7, 7]

pop_size = 2500
greedy = True

random.seed(1234)

solutions = [
    Solution([
        np.split(np.random.permutation(np.arange(sum(table_sizes))),
                 np.cumsum(table_sizes)[:-1]) for x in range(n_courses)
    ], n_courses, table_sizes) for y in range(pop_size)
]

for i, solution in enumerate(solutions):
    if i % 100 == 0:
        print(str(i) + '/' + str(pop_size))
    local_optimum = (solution.get_score() == 0)
    while not local_optimum:
        new_solution = solution.improve_solution(greedy)
        if new_solution is None:
            local_optimum = True
        else:
            solution = new_solution
            if new_solution.get_score() == 0:
                local_optimum = True