def evaluate_remaining_letters(self, letters: List[str]) -> float: evaluation_points = 0 vowels = consonants = blanks = 0 evaluated_letters = [] for letter in letters: if letter in Dictionary.vowels: vowels += 1 elif letter in Dictionary.consonants: consonants += 1 else: blanks += 1 evaluation_points += Heuristics.evaluate_first_letter(letter) if letter in evaluated_letters: evaluation_points += evaluated_letters.count( letter) * Heuristics.evaluate_another_letter(letter) evaluated_letters.append(letter) evaluation_points += Heuristics.check_pairs(letters) if self.sack.is_empty(): if not letters: evaluation_points += self.points_for_letters( self.letters_remaining) else: evaluation_points -= blanks * Heuristics.evaluate_first_letter( BLANK) evaluation_points += Heuristics.evaluate_vowels_and_consonants( vowels, consonants) return evaluation_points
def permute_init(number_of_individuals, jobs): population = [] by_not_random = round(number_of_individuals * 0.1 * 0.4) by_not_random_mwr = round(number_of_individuals * 0.1 * 0.6) by_random = round(number_of_individuals * 0.9 * 0.4) by_random_mwr = round(number_of_individuals * 0.9 * 0.6) while len(population) < by_not_random: population.append( Heuristics.localization_random_tasks(jobs, randomly=False)) while len(population) < by_not_random_mwr: population.append(Heuristics.localization_mwr(jobs, randomly=False)) while len(population) < by_random: population.append(Heuristics.localization_random_tasks(jobs)) while len(population) < by_random_mwr: population.append(Heuristics.localization_mwr(jobs)) while len(population) < number_of_individuals: population.append(Heuristics.localization_random_tasks(jobs)) return population
def longest_shortest_init(number_of_individuals, jobs): population = [] random_population = round(number_of_individuals * 0.4) generated = 0 while generated < number_of_individuals: if generated < random_population: population.append(Heuristics.random_choice_tasks(jobs)) else: population.append( Heuristics.longest_shortest_probability_tasks(jobs)) generated += 1 return population
def __init__(self, attribute, value, dataset, min_case_per_rule): self.attribute = attribute self.value = value self.covered_cases = self._get_cases(dataset.data, dataset.get_col_index(attribute), value) self._heuristic = Heuristics(dataset).get_heuristic(attribute, value) self._available = self._set_availability(min_case_per_rule)
def minimax(self, depth, board, is_maximizing): possibleMoves = self.available_moves(self.game.board) if (depth == 0): heur = Heuristics(self.game) return heur.evaluate(board) if (is_maximizing): bestMove = -9999 for x in possibleMoves: move = x original_pieces = self.game.get_original_pieces( board, x[0][0], x[0][1], x[1][0], x[1][1]) try: self.game.execute_turn(x[0][0], x[0][1], x[1][0], x[1][1]) bestMove = max( bestMove, self.minimax(depth - 1, board, not is_maximizing)) self.game.revert_turn(x[0][0], x[0][1], x[1][0], x[1][1], original_pieces[0], original_pieces[1]) except: bestMove = max( bestMove, self.minimax(depth - 1, board, not is_maximizing)) return bestMove else: bestMove = 9999 for x in possibleMoves: move = x original_pieces = self.game.get_original_pieces( board, x[0][0], x[0][1], x[1][0], x[1][1]) try: self.game.execute_turn(x[0][0], x[0][1], x[1][0], x[1][1]) bestMove = min( bestMove, self.minimax(depth - 1, board, not is_maximizing)) self.game.revert_turn(x[0][0], x[0][1], x[1][0], x[1][1], original_pieces[0], original_pieces[1]) except: bestMove = min( bestMove, self.minimax(depth - 1, board, not is_maximizing)) return bestMove
def a_star_search(problem, null=False): """ Search the node that has the lowest combined cost and heuristic first. """ visited = {str(problem.get_start_state()): (None, None)} p_queue = PriorityQueue() p_queue.push((problem.get_start_state(), 0), 0) while not p_queue.is_empty(): temp_state, total_cost = p_queue.pop() if problem.is_goal_state(temp_state): actions = [] curr = str(temp_state) while visited[curr][0] is not None: actions.insert(0, visited[curr][1]) curr = str(visited[curr][0]) return actions else: for successor in problem.get_successors(temp_state): str_state = str(successor[0]) if str_state not in visited: heuristic_obj = Heuristics(successor[0]) visited[str_state] = temp_state, successor[1] new_total_cost = total_cost + successor[2] p_queue.push((successor[0], new_total_cost), new_total_cost + heuristic_obj.get_weighted_sum(null=null))
""" Let's play the tic-tac-toe game! @author: milos """ from tictactoe import TicTacToe from player import Player from heuristics import Heuristics from naive_heuristics import NaiveHeuristics # define heuristics basic_h = Heuristics() naive_h = NaiveHeuristics() #define players playerA = Player(1, basic_h, 'Player A') playerB = Player(1, naive_h, 'Player B') stats = {'Player A wins': 0, 'Player B wins': 0, 'Tied': 0} # set the board size of the game board_size = 10 # set the ply search for the player k = 2 print('Players using K-ply =', k) playerA.set_k_ply(k) playerB.set_k_ply(k) # start the game with players A and B # use print_steps=False to remove printouts of moves game = TicTacToe(board_size, playerA, playerB, print_steps=True)
from processorDag import ProcessorDAG from taskDag import TaskDAG from heuristics import Heuristics import random sizeOfDataSet = 100 dirDataSet = 'dataset' processorDag = ProcessorDAG() processorDag.importDag(dirDataSet + '/processors.dag') taskDag1 = TaskDAG() taskDag1.importDag(dirDataSet + '/1.dag') schedule = Heuristics.HEFT(taskDag1, processorDag) noOfAcceptedRequests = 0 for id in range(2, sizeOfDataSet + 1): taskDag = TaskDAG() taskDag.importDag(dirDataSet + '/' + str(id) + '.dag') tmpSchedule = Heuristics.DynamicHEFT(schedule, taskDag) makespan = tmpSchedule.aft - taskDag.arrivalTime if makespan <= taskDag.deadline: noOfAcceptedRequests += 1 schedule.processorExecutionSlots = tmpSchedule.processorExecutionSlots[:] print(str(id) + ': accepted') print("No of tasks allocated on fog nodes: " + str(tmpSchedule.getNoOfTasksAllocatedToFogNodes())) print("No of tasks allocated on cloud nodes: " +
""" test object/board setup -- pulled from test.py """ z = Obj2048(0) t = Obj2048(2) f = Obj2048(4) e = Obj2048(8) s = Obj2048(16) WIN = Obj2048(2048) EWIN = Obj2048(4096) x = Board2048(np.array([[t, z, z, f], [z, t, f, e], [e, f, t, z], [e, z, EWIN, WIN]])) """ Extract rows and columns from numpy grid""" grid = hu.expose_val(x.grid) row1 = grid[0, :] row2 = grid[1, :] row3 = grid[2, :] row4 = grid[3, :] col1 = grid[:, 0] col2 = grid[:, 1] col3 = grid[:, 2] col4 = grid[:, 3] row1_ascending = hu.ascending(row1) row1_descending = hu.descending(row1) row2_ascending = hu.ascending(row2) row2_descending = hu.descending(row2)
def conditional_precedence_reserving_mutation(problem, child, probability): new_child = Heuristics.mutation_operation(child, probability) new_child2 = Heuristics.mutation_machine(new_child, probability) return min([child, new_child, new_child2], key=lambda x: Chromosome.compute_makespan(x, problem))
def precedence_reserving_mutation(problem, child, probability): new_child = Heuristics.mutation_operation(child, probability) new_child2 = Heuristics.mutation_machine(new_child, probability) return new_child2
import argparse import datetime import logging import os import sys import HeuristicTester from apis.LocalApi import LocalWikipediaApi as LocalApi from apis.SqlApi import SqlWikipediaApi as SqlApi from apis.WikipediaApi import WikipediaApi from heuristics import Heuristics, TFIDF, WordNet, Doc2Vec apis = {"WikipediaApi": WikipediaApi, "LocalApi": LocalApi, "SqlApi": SqlApi} heuristics = { "bfs": Heuristics.BfsHeuristic(), "dfs": Heuristics.DfsHeuristic(), "null": Heuristics.NullHeuristic(), "tfidf": TFIDF.TfidfHeuristic("corpora/1000.txt", 10), "wordnet": WordNet.WordNetHeuristic(), "doc2vec": Doc2Vec.Doc2VecHeuristic(True) } log = logging.getLogger(__name__) def get_valid_heuristics(): return heuristics def get_valid_apis():
class Minimax: saved_moves1 = [] saved_moves2 = [] def __init__(self, depth, mode1, mode2): self.max_depth = depth self.my_heuristics = Heuristics(mode1) self.their_heuristics = Heuristics(mode2) def value_gamestate(self, gamestate, player, me): if me: opponent = player % 2 if gamestate.check_end_game(): if gamestate.get_who_wins() == gamestate.player_turn: return sys.maxsize else: return -sys.maxsize + 1 else: val = self.my_heuristics.value_my_pieces( gamestate, player - 1, opponent) + self.my_heuristics.value_opponents_pieces( gamestate, player - 1, opponent) return val else: opponent = player % 2 if gamestate.check_end_game(): if gamestate.get_who_wins() == gamestate.player_turn: return sys.maxsize else: return -sys.maxsize + 1 else: val = self.their_heuristics.value_my_pieces( gamestate, player - 1, opponent) + self.their_heuristics.value_opponents_pieces( gamestate, player - 1, opponent) return val def min_alpha_beta(self, alpha, beta, depth, gamestate): # Caso o jogo acabe ou chegue ai fim retorna o valor do estado if depth == 0 or gamestate.check_end_game(): return self.value_gamestate(gamestate, gamestate.player_turn, False) min_value = sys.maxsize # Gera todas as possiveis posições para o estado do jogo atual possible_positions = gamestate.generate_valid_moves( gamestate.player_turn) # Itera sobre essas posições e, para cada uma, cria um novo gamestate que vai ser depois avaliado for i in gamestate.players[gamestate.player_turn - 1].pieces.keys(): if i in possible_positions.keys(): for j in possible_positions[i]: # Cria uma cópia do gamestate atual para mover a peça e depois calcular o seu valor new_game_state = copy.deepcopy(gamestate) new_game_state.move_piece( new_game_state.players[gamestate.player_turn - 1].pieces[i], j) new_game_state.change_turn() value = self.max_alpha_beta(alpha, beta, depth - 1, new_game_state) # Se o valor do gamestate gerado for menor do que o menor valor que ele tem guardado então este # passa a ser o melhor gamestate if type(value) == tuple: if value[0] < min_value: min_value = min(min_value, value[0]) beta = min(beta, value[0]) elif value < min_value: min_value = min(min_value, value) beta = min(beta, value) if beta <= alpha: return min_value return min_value def max_alpha_beta(self, alpha, beta, depth, gamestate): # Caso o jogo acabe ou chegue ai fim retorna o valor do estado if depth == 0 or gamestate.check_end_game(): return self.value_gamestate(gamestate, gamestate.player_turn, True) max_value = -sys.maxsize + 1 best_move = [] # Gera todas as possiveis posições para o estado do jogo atual possible_positions = gamestate.generate_valid_moves( gamestate.player_turn) # Itera sobre essas posições e, para cada uma, cria um novo gamestate que vai ser depois avaliado for i in gamestate.players[gamestate.player_turn - 1].pieces.keys(): if i in possible_positions.keys(): for j in possible_positions[i]: # Cria uma cópia do gamestate atual para mover a peça e depois calcular o seu valor new_game_state = copy.deepcopy(gamestate) new_game_state.move_piece( new_game_state.players[gamestate.player_turn - 1].pieces[i], j) new_game_state.change_turn() value = self.min_alpha_beta(alpha, beta, depth - 1, new_game_state) # Se o valor do gamestate gerado for maior do que o maior valor que ele tem guardado então este # passa a ser o melhor gamestate if value > max_value: max_value = max(max_value, value) best_move = [i, j] alpha = max(alpha, value) if beta <= alpha: if gamestate.player_turn == 1: self.saved_moves1.append([gamestate, best_move]) else: self.saved_moves2.append([gamestate, best_move]) return max_value, best_move # Só vale a pena guardar caso estejamos num depth diferente ao inicial pois se não estariamos a guardar o # gamestate inicial if depth != self.max_depth: if gamestate.player_turn == 1: self.saved_moves1.append([gamestate, best_move]) else: self.saved_moves2.append([gamestate, best_move]) return max_value, best_move def play(self, gamestate): # Caso ele já tenha o gamestate guardado, então já sabe qual a melhor jogado if gamestate.player_turn == 1: for i in range(0, len(self.saved_moves1)): if gamestate == self.saved_moves1[i][0]: time.sleep(1) return self.saved_moves1[i][1] else: for i in range(0, len(self.saved_moves2)): if gamestate == self.saved_moves2[i][0]: time.sleep(1) return self.saved_moves2[i][1] # Se não, dá reset ao moves guardados para poupar memória if gamestate.player_turn == 1: self.saved_moves1.clear() if gamestate.player_turn == 2: self.saved_moves2.clear() max_value, best_move = self.max_alpha_beta(-sys.maxsize + 1, sys.maxsize, self.max_depth, gamestate) return best_move
def __init__(self, depth, mode1, mode2): self.max_depth = depth self.my_heuristics = Heuristics(mode1) self.their_heuristics = Heuristics(mode2)