def find_multiple(cards: Cards, level_to_beat: int, cards_to_find: int): """ :param cards: :param level_to_beat: :param cards_to_find: :rtype: Combination """ if cards_to_find <= 0 or cards_to_find > 4: raise ValueError('Illegal combination_type %s' % cards_to_find) if cards_to_find == 1: for card in (cards - Phoenix()).cards: if card.power > level_to_beat: return Combination(cards_list=[card]) # if no card could have been player, try to take the lead with your Phoenix # Phoenix can not be played on a Dragon if cards.phoenix_flag and level_to_beat < Dragon().power: return Combination(cards_list=[Phoenix()]) # TODO - TO REFACTOR WITH LOGIC if cards_to_find == 2: for i in range(len(cards.cards) - 1): card = cards.cards[i] if card.power > level_to_beat and card.power == cards.cards[ i + 1].power: return Cards(cards_list=[card, cards.cards[i + 1]]) if cards_to_find == 3: for i in range(len(cards.cards) - 2): card = cards.cards[i] if card.power > level_to_beat and card.power == cards.cards[ i + 2].power: return Cards(cards_list=[ card, cards.cards[i + 1], cards.cards[i + 2] ]) if cards_to_find == 4: for i in range(len(cards.cards) - 3): card = cards.cards[i] if card.power > level_to_beat and card.power == cards.cards[ i + 3].power: return Cards(cards_list=[ card, cards.cards[i + 1], cards.cards[i + 2], cards.cards[i + 3] ]) # If no combination found, try to use Phoenix to play if cards.phoenix_flag and 1 <= cards_to_find < 4 and cards.size > 1: return Hand.find_multiple(cards - Phoenix(), level_to_beat, cards_to_find - 1) + Phoenix()
def get_combination_to_play(self, trick, wish=None): combination_to_play = None if Mahjong() in self.hand.cards: return Combination(cards_list=[Mahjong()]) # if there is a trick being played last_play = trick.get_last_play() if last_play: last_combination = last_play.combination combination_to_play = self.hand.find_lowest_combination( last_combination.level, last_combination.type) # If we are leading else: for combination_type in self.lead_preference: # -1 otherwise the dog is never played combination_to_play = self.hand.find_lowest_combination( -1, combination_type) # as soon as a combination is found, play it if combination_to_play: break return combination_to_play
def read(self): """ Reads COMBINATION_FILE into a list of Combinations.""" combos = [] tmp = self._file_manipulator.read_file_to_list() for item in tmp: combos.append(Combination(item.split(';'))) return combos
def find_steps_old(cards, level_to_beat, steps_length=None): if steps_length is None: steps_length = 2 starting_pairs_level = level_to_beat - steps_length + 1 first_pair = Hand.find_multiple(cards, starting_pairs_level, 2) # If no pairs if not first_pair: return starting_step_pair = Combination(cards_list=first_pair.cards) while starting_step_pair: start_pair_level = starting_step_pair.level curr_steps_combination = starting_step_pair # for i in range(1, length): # while number_of_steps < steps_length: for number_of_steps in range(1, steps_length + 1): target_level = start_pair_level + number_of_steps - 1 # TODO - Potential issue if the phoenix is need in the middle of it or at the beginning next_pair = Hand.find_multiple(cards - starting_step_pair, target_level, 2) if next_pair: next_pair_combi = Combination(cards_list=next_pair.cards) if next_pair_combi.level == target_level + 1: curr_steps_combination = curr_steps_combination + next_pair number_of_steps += 1 if number_of_steps == steps_length: return Cards( cards_list=curr_steps_combination.cards) else: # Next pairs level is too high - Use this pair as a new start starting_step_pair = next_pair_combi break # if there is no next pair, the hand does not contain any pairs # No steps could be done, return None else: return
def test_triples(self): cards = [ Card(name='2', suit='Pagoda'), Card(name='2', suit='Sword'), Card(name='2', suit='Jade') ] combination = Combination(cards_list=cards) self.assertEqual(combination.type, 'TRIO')
def addCombination(self, combinationName, partNames): partsList = [] for name in partNames: part = self.registry[name] if part.getRemainingVolume() > 0: part.removeVolume(1) else: raise Exception('Not enough volume for ' + name) partsList.append(part) combination = Combination(combinationName, partsList) self.combinations[combinationName] = combination
def play(self, indices) : """ Play the combination of cards defined by the given *indices*. ======= =============================================================== indices list of int; the indices of the cards to play as they appear in *self.cards* ======= =============================================================== """ cards = [self.cards[i] for i in indices] combination = Combination(cards) return combination
def find_all_multiples(cards: Cards, multiple: int): cards = cards - Dog() - Dragon() buckets = Cards.bucketize_hands(cards.cards) multiples = [] for level in range(Mahjong().power + 1, Dragon().power): cards_this_level = buckets[level] if (Phoenix().power in buckets.keys()) and (multiple != 4): cards_this_level.append(Phoenix()) if len(cards_this_level) > 1: for pair in itertools.combinations(cards_this_level, multiple): multiples.append(Combination(cards_list=list(pair))) return multiples
def calculate_remain_f_ratio(self, threshold=5000): #self.check_point = max( threshold, int(self.f_left/2) ) self.check_point = int(self.f_left / 2) c = Combination(self.f_left, len(self.arms), self.n_points * len(self.arms), self.get_ranks()) ratio = c.combination / float(sum(c.combination)) if self.verbose: print('\nRecalculate ratio:', c.combination, '[%s]' % ','.join('%6.3f' % i for i in ratio)) return np.array(ratio)
def run_serial(self): logger.info( LogPhrases.NEW_COMBINATION.format(Database.SERIAL_COMBINATION_ID)) serial_dir_path = os.path.join(self.combinations_dir, Database.SERIAL_COMBINATION_ID) if self.mode == ComparMode.CONTINUE and self.db.combination_has_results( Database.SERIAL_COMBINATION_ID): job_results = self.db.get_combination_results( Database.SERIAL_COMBINATION_ID)['run_time_results'] else: shutil.rmtree(serial_dir_path, ignore_errors=True) os.mkdir(serial_dir_path) self.__copy_sources_to_combination_folder(serial_dir_path) Timer.inject_atexit_code_to_main_file( os.path.join(serial_dir_path, self.main_file_rel_path), self.files_loop_dict, serial_dir_path) if self.is_make_file: compiler_type = Makefile.NAME makefile = Makefile(serial_dir_path, self.makefile_exe_folder_rel_path, self.makefile_output_exe_file_name, self.makefile_commands) makefile.make() else: compiler_type = self.binary_compiler_type try: self.__run_binary_compiler(serial_dir_path) except e.CombinationFailure as ex: raise e.CompilationError(str(ex)) combination = Combination( combination_id=Database.SERIAL_COMBINATION_ID, compiler_name=compiler_type, parameters=None) job = Job(directory=serial_dir_path, exec_file_args=self.main_file_parameters, combination=combination) job = self.execute_job(job) job_results = job.get_job_results()['run_time_results'] for file_dict in job_results: if 'dead_code_file' not in file_dict.keys(): for loop_dict in file_dict['loops']: if 'dead_code' not in loop_dict.keys(): key = (file_dict['file_id_by_rel_path'], loop_dict['loop_label']) self.serial_run_time[key] = loop_dict['run_time'] if not self.save_combinations_folders: self.__delete_combination_folder(serial_dir_path) logger.info('Finish to work on serial combination')
def find_all_fullhouses(cards: Cards): duos = Hand.find_all_multiples(cards, 2) trios = Hand.find_all_multiples(cards, 3) fullhouses = [] for trio in trios: possible_duos = [duo for duo in duos if trio.level != duo.level] if trio.phoenix_flag: possible_duos = [ duo for duo in possible_duos if not duo.phoenix_flag ] for possible_duo in possible_duos: fullhouse_cards = trio.cards.copy() fullhouse_cards.extend(possible_duo.cards) fullhouses.append(Combination(cards_list=fullhouse_cards)) return fullhouses
def generate(self, separator="&", length=3): """ Generates a new combination with the given separator and of the given length that is currently not in COMBINATION_FILE.""" combo = Combination() combo.separator = separator used = self.read() f = FileManipulator(WORD_FILE) words = f.read_file_to_length_list() del f combo.generate(length, words) while combo in used: combo.generate(separator, length, words) self._file_manipulator.add_line_to_file(str(combo)) return combo
def loadJSONCombinations(registry): loadedCombinations = {} with open('combinations.json') as json_file: existingCombos = json.load(json_file) for jsonCombo in existingCombos['Combinations']: comboName = jsonCombo['Combination Name'] partNameList = jsonCombo['Parts'] inRegistry = True for partName in partNameList: if partName not in registry: inRegistry = False if inRegistry: newCombination = Combination(comboName, partNameList) loadedCombinations[partName] = newCombination return loadedCombinations
def calAll(self): self.errs = [0] * 5 bias = Bias(self.data, self.test) bias.calculateBias() answers, predicts = bias.predict() err = evaluationRMSE(answers, predicts) self.errs[0] = err print("Bias: %f" % err) similarity = Similarity(self.data, self.test) similarity.calculateBias() similarity.calcSimiMatrix() answers, predicts = similarity.predict() err = evaluationRMSE(answers, predicts) self.errs[1] = err print("Similarity: %f" % err) svd = SVD(self.data, self.test) svd.generaterMat() svd.calcSVD() answers, predicts = svd.predict() err = evaluationRMSE(answers, predicts) self.errs[2] = err print("SVD: %f" % err) matFactory = MatFactory(self.data, self.test) matFactory.train(20, 35) answers, predicts = matFactory.predict() err = evaluationRMSE(answers, predicts) self.errs[3] = err print("MatFactory: %f" % evaluationRMSE(answers, predicts)) combination = Combination(self.data) combination.separateData() combination.calculate() combination.train(alpha=0.01, iter=10000) answers, predicts = combination.predict(self.test) err = evaluationRMSE(answers, predicts) self.errs[4] = err print("Combination: %f" % err) return self.errs
def find_lowest_combination(self, level_to_beat, combination_type, length=None): # call find_pairs multiples = ['SINGLE', 'PAIR', 'TRIO', 'SQUAREBOMB'] if combination_type in multiples: cards_combination = self.find_multiple( self, level_to_beat, multiples.index(combination_type) + 1) # TODO Straight and steps length elif combination_type == 'STRAIGHT': cards_combination = self.find_straight(self, level_to_beat, length) elif combination_type == 'STRAIGHTBOMB': cards_combination = self.find_straight(self, level_to_beat, length, bomb=True) elif combination_type == 'FULLHOUSE': trio = self.find_multiple(self, level_to_beat, 3) if trio is None: return duo = self.find_multiple(self - trio, level_to_beat, 2) if duo is None: return cards_combination = duo + trio elif combination_type == 'STEPS': cards_combination = self.find_steps(self, level_to_beat, length) else: raise ValueError() if cards_combination: return Combination(cards_list=cards_combination.cards)
def test_to_fix(self): cards = 'Phoenix, 2_Pa, 3_Pa, 4_Pa, 5_Pa, 5_Sw, 5_Ja, 5_St' combination = Combination(cards_string=cards) self.assertIsNone(combination.type)
def find_all_straights(cards: Cards): #TODO fix levels #TODO, put the level in there to differentiate phoenix at start and end #TODO Sort the combinations # remove Dog and Dragon from any straights cards = cards - Dog() - Dragon() buckets = Cards.bucketize_hands(cards.cards) power_values = buckets.keys() possible_straights_power_values = [] # Get all possible power combinations for start in range(Mahjong().power, Dragon().power): length = 0 current_straight_values = [] for next_value in range(start, Dragon().power): found = False new_value = None if next_value in power_values: found = True new_value = next_value elif Phoenix().power in power_values and Phoenix( ).power not in current_straight_values: if next_value != 1: found = True new_value = Phoenix().power if found and new_value not in current_straight_values: current_straight_values.append(new_value) length += 1 if length >= 5: possible_straights_power_values.append( current_straight_values.copy()) elif not found: break # Now that we have the powers, we get all possible straights straights = [] for straight in possible_straights_power_values: straight_cards = [buckets[power] for power in straight] for combinations in itertools.product(*straight_cards): # straights.append(Cards(cards_list=list(combinations))) straights.append(Combination(cards_list=list(combinations))) # We replace the phoenix in all the straights where we can new_straights = [] for straight in straights: if Phoenix() not in straight.cards: for card in straight.cards: if not card == Mahjong(): new_cards = straight - card + Phoenix() new_combo = Combination(cards_list=new_cards.cards) new_straights.append(new_combo) # new_straights.append(straight - card + Phoenix()) straights.extend(new_straights) straights.sort() return straights
def create_obj(self, code): try: Combination(code, should_create_db = True) return (code, True) except Exception as e: return (code, False)
elif card.flag == 1: return card.color + '_' + 'reverse' elif card.flag == 2: return card.color + '_' + 'skip' elif card.flag == 3: return card.color + '_' + '+2' elif card.flag == 4: return 'black_wildcard' elif card.flag == 5: return 'black_+4' game = UNO_Game(Deck()) #default is two control players game.player1 = Heuristic_v1(game, 'P1') game.player2 = Combination(game, 'P2') #options for different kinds of AIs to use if len(sys.argv) > 1: if sys.argv[1] == 'bestfirst': print('cannot set player 1 to bestfirst, ai not yet implemented') if len(sys.argv) > 2: if sys.argv[2] == 'bestfirst': print('cannot set player 1 to bestfirst, ai not yet implemented') game.turn = game.player1 #P1 gets first turn print('size of', game.player1.name, 'hand is', str(len(game.player1.hand.cards))) print('size of', game.player2.name, 'hand is', str(len(game.player2.hand.cards))) print('size of discard pile is', str(len(game.discard_pile.cards)))
def run(self): self.iteration = self.iteration + 1 # Choose best cluster to update ranks = self.get_ranks(self.clusters) remain_f_allocation = Combination(self.problem.remaining_evaluations, len(self.clusters), self.n_points, ranks, model='linear', debug=False).combination self.remain_f_allocation += np.array(remain_f_allocation) best_arm = np.argmax(self.remain_f_allocation) remain_f = np.amax(remain_f_allocation) if self.algo_type == 'CMA': if self.algos[best_arm].stop(): self.remain_f_allocation[ best_arm] = -self.remain_f_allocation[best_arm] if self.verbose: print('CMA-ES at cluster %d stops!!' % (best_arm)) #draw_contour( function_id, clusters=bandit.clusters ) return print('Update cluster %d' % best_arm) # TODO #self.remain_f_allocation[best_arm] = 0 self.remain_f_allocation[best_arm] -= len( self.clusters[best_arm].population) # Transform data points to [0-1] space and resume algorithm original_points = [ p.phenome for p in self.clusters[best_arm].population ] trans_points = self.clusters[best_arm].transform(original_points).clip( 0, 1) fitness_values = [ p.objective_values for p in self.clusters[best_arm].population ] new_trans_positions = self.update_positions(best_arm, trans_points, fitness_values) # Update cluster.population new_positions = self.clusters[best_arm].transform_inverse( new_trans_positions) solutions = [Individual(position) for position in new_positions] try: self.problem.batch_evaluate(solutions) except ResourcesExhausted: self.should_terminate = True return self.clusters[best_arm].population = sorted( solutions, key=attrgetter('objective_values')) ranks = self.get_ranks(self.clusters) for i, cluster in enumerate(self.clusters): cluster.ranks = ranks[i] self.best_solution = self.update_best_solution() # Check if need to recluster trans_mean_position = np.mean(new_trans_positions, axis=0) best_point = self.clusters[best_arm].population[0].phenome trans_best_point = self.clusters[best_arm].transform([best_point ]).clip(0, 1)[0] margin = 0.05 if ((trans_best_point < margin).any() or (trans_best_point > 1-margin).any()) and \ ((trans_mean_position < 2*margin).any() or (trans_mean_position > 1-2*margin).any()): if self.verbose: print('Reclustering...') print('due to best_point of cluster %d at: %r' % (best_arm, trans_best_point)) print(' and mean at: %r' % (trans_mean_position)) if args.draw_contour > 0: draw_contour(self.function_id, clusters=self.clusters) self.shift_matrix(best_arm, best_point) if args.draw_contour > 0: draw_contour(self.function_id, clusters=self.clusters) self.recluster(len(self.clusters)) if args.draw_contour > 0: draw_contour(self.function_id, clusters=self.clusters) self.update_statistics(best_arm)
def generate_optimal_code(self): logger.info('Start to combine the Compar combination') optimal_loops_data = [] # copy final results into this folder compar_combination_folder_path = self.create_combination_folder( self.COMPAR_COMBINATION_FOLDER_NAME, base_dir=self.working_directory) final_files_list = self.make_absolute_file_list( compar_combination_folder_path) for file_id_by_rel_path, loops in self.files_loop_dict.items(): current_file = { "file_id_by_rel_path": file_id_by_rel_path, 'optimal_loops': [] } for loop_id in range(1, loops[0] + 1): start_label = Fragmentator.get_start_label() + str(loop_id) end_label = Fragmentator.get_end_label() + str(loop_id) try: current_optimal_id, current_loop = self.db.find_optimal_loop_combination( file_id_by_rel_path, str(loop_id)) # update the optimal loops list current_loop['_id'] = current_optimal_id current_file["optimal_loops"].append(current_loop) except e.DeadCodeFile: current_file["dead_code_file"] = True break except e.DeadCodeLoop: current_file["optimal_loops"].append({ '_id': Database.SERIAL_COMBINATION_ID, 'loop_label': str(loop_id), 'dead_code': True }) current_optimal_id = Database.SERIAL_COMBINATION_ID # if the optimal combination is the serial => do nothing if current_optimal_id != Database.SERIAL_COMBINATION_ID: current_optimal_combination = Combination.json_to_obj( self.db.get_combination_from_static_db( current_optimal_id)) current_combination_folder_path = self.create_combination_folder( ComparConfig.OPTIMAL_CURRENT_COMBINATION_FOLDER_NAME, base_dir=self.working_directory) files_list = self.make_absolute_file_list( current_combination_folder_path) current_comp_name = current_optimal_combination.compiler_name # get direct file path to inject params src_file_path = list( filter( lambda x: x['file_id_by_rel_path'] == file_id_by_rel_path, files_list)) src_file_path = src_file_path[0]['file_full_path'] # parallelize and inject self.parallel_compilation_of_one_combination( current_optimal_combination, current_combination_folder_path) # replace loop in c file using final_files_list target_file_path = list( filter( lambda x: x['file_id_by_rel_path'] == file_id_by_rel_path, final_files_list)) target_file_path = target_file_path[0]['file_full_path'] Compar.replace_loops_in_files(src_file_path, target_file_path, start_label, end_label) Compar.add_to_loop_details_about_comp_and_combination( target_file_path, start_label, current_optimal_id, current_comp_name) sleep(1) # prevent IO error shutil.rmtree(current_combination_folder_path) optimal_loops_data.append(current_file) # remove timers code Timer.remove_timer_code( self.make_absolute_file_list(compar_combination_folder_path)) # inject new code Timer.inject_timer_to_compar_mixed_file( os.path.join(compar_combination_folder_path, self.main_file_rel_path), compar_combination_folder_path) self.generate_summary_file(optimal_loops_data, compar_combination_folder_path) try: logger.info('Compiling Compar combination') self.compile_combination_to_binary(compar_combination_folder_path, inject=False) job = Job( compar_combination_folder_path, Combination(Database.COMPAR_COMBINATION_ID, ComparConfig.MIXED_COMPILER_NAME, None), []) logger.info('Running Compar combination') self.execute_job(job, self.serial_run_time) except Exception as ex: msg = f'Exception in Compar: {ex}\ngenerate_optimal_code: cannot compile compar combination' self.save_combination_as_failure(Database.COMPAR_COMBINATION_ID, msg, compar_combination_folder_path) logger.info( LogPhrases.NEW_COMBINATION.format( Database.FINAL_RESULTS_COMBINATION_ID)) # Check for best total runtime best_runtime_combination_id = self.db.get_total_runtime_best_combination( ) best_combination_obj = None if best_runtime_combination_id != Database.COMPAR_COMBINATION_ID: logger.info( f'Combination #{best_runtime_combination_id} is more optimal than Compar combination' ) best_combination_obj = Combination.json_to_obj( self.db.get_combination_from_static_db( best_runtime_combination_id)) final_results_folder_path = self.create_combination_folder( self.FINAL_RESULTS_FOLDER_NAME, self.working_directory) try: if best_runtime_combination_id != Database.SERIAL_COMBINATION_ID: self.parallel_compilation_of_one_combination( best_combination_obj, final_results_folder_path) self.compile_combination_to_binary(final_results_folder_path) summary_file_path = os.path.join( compar_combination_folder_path, ComparConfig.SUMMARY_FILE_NAME) summary_file_new_path = os.path.join( final_results_folder_path, ComparConfig.SUMMARY_FILE_NAME) shutil.move(summary_file_path, summary_file_new_path) except Exception as ex: raise Exception( f"Total runtime calculation - The optimal file could not be compiled, combination" f" {best_runtime_combination_id}.\n{ex}") else: logger.info(f'Compar combination is the optimal combination') final_folder_path = os.path.join(self.working_directory, self.FINAL_RESULTS_FOLDER_NAME) if os.path.exists(final_folder_path): shutil.rmtree(final_folder_path) shutil.copytree(compar_combination_folder_path, final_folder_path) # remove compar code from all the files in final result folder final_folder_path = os.path.join(self.working_directory, self.FINAL_RESULTS_FOLDER_NAME) Timer.remove_timer_code( self.make_absolute_file_list(final_folder_path)) final_combination_results = self.db.get_combination_results( best_runtime_combination_id) if final_combination_results: final_combination_results[ '_id'] = Database.FINAL_RESULTS_COMBINATION_ID final_combination_results[ 'from_combination'] = best_runtime_combination_id self.db.insert_new_combination_results(final_combination_results) with open( os.path.join(final_folder_path, Timer.TOTAL_RUNTIME_FILENAME), 'w') as f: f.write(str(final_combination_results['total_run_time'])) self.update_summary_file( final_folder_path, best_runtime_combination_id, final_combination_results['total_run_time'], best_combination_obj) # format all optimal files self.format_c_files([ file_dict['file_full_path'] for file_dict in self.make_absolute_file_list(final_folder_path) ]) self.db.remove_unused_data(Database.COMPAR_COMBINATION_ID) self.db.remove_unused_data(Database.FINAL_RESULTS_COMBINATION_ID) final_result_speedup, final_result_runtime = self.db.get_final_result_speedup_and_runtime( ) logger.info( LogPhrases.FINAL_RESULTS_SUMMARY.format(final_result_speedup, final_result_runtime)) if self.clear_db: self.clear_related_collections() self.db.close_connection()
def add(self, prev_app): a = Combination() tkinter.messagebox.showinfo("ADDED", "SUCCESSFULY ADDED TO DATABASE") prev_app.destroy() self.adminMain()
def test_pairs(self): cards = [Card(name='2', suit='Pagoda'), Card(name='2', suit='Sword')] combination = Combination(cards_list=cards) self.assertEqual(combination.type, 'PAIR') self.assertEqual(combination.level, 2)
def test_straight_with_phoenix(self): cards = '2_Sw, 3_Pa, 5_Pa, Phoenix, 6_Pa' combination = Combination(cards_string=cards) self.assertEqual(combination.type, 'STRAIGHT')
def test_wrong_pairs(self): cards = [Card(name='2', suit='Pagoda'), Card(name='3', suit='Sword')] Combination(cards_list=cards)
def get(self, index): return Combination( self._file_manipulator.read_file_to_list()[index].split(';'))
def test_pairs_with_phoenix(self): cards = [Card(name='2', suit='Pagoda'), Phoenix()] combination = Combination(cards_list=cards) self.assertEqual(combination.type, 'PAIR') self.assertEqual(combination.level, 2)
def init_combination_info(self): trading_info = self.comb_info_client.get() for _, code_id in trading_info['code'].iteritems(): if str(code_id) not in self.combination_objs: self.combination_objs[str(code_id)] = Combination( code_id, self.dbinfo)
def test_fullhouse(self): cards = ' 2_Pa, 2_Sw, 2_Ja, 5_Pa, 5_Sw' combination = Combination(cards_string=cards) self.assertEqual(combination.type, 'FULLHOUSE')