def cal_value_fector(self,gene): gene = gene.copy() Comparison_1 = [1] * 50 Comparison_2 = [3] * 50 (rounds_1, c1_1, c1_2) = _PyPacwar.battle(gene, Comparison_1) (rounds_2, c2_1, c2_2) = _PyPacwar.battle(gene, Comparison_2) return (rounds_1 + rounds_2,c1_1 - c1_2,c2_1 - c2_2)
def ref_value(self): ''' :param gene: :return value factor of gene combat ''' gene = self.gene Comparison_1 = [1] * 50 Comparison_2 = [3] * 50 (rounds_1, c1_1, c1_2) = _PyPacwar.battle(gene, Comparison_1) (rounds_2, c2_1, c2_2) = _PyPacwar.battle(gene, Comparison_2) return rounds_1 + rounds_2,c1_1 - c1_2,c2_1 - c2_2
def next(original): #change one res = [] for i in range(len(original)): nbr = original[:] for j in range(4): nbr[i] = j (rounds1, c11, c12) = _PyPacwar.battle(nbr, ones) (rounds2, c21, c22) = _PyPacwar.battle(nbr, threes) if c11 > c12 and c21 > c22: res.append([rounds1+rounds2, c11, c12, nbr[:]]) res.sort() if res==[]: return [] else: return res[0]
def main(): res = [] threes = [3] * 50 ones = [1] * 50 for pp in range(4): origin = [1] * 50 for i in range(50): test = origin[:] for j in range(4): test[i] = j (rounds1, c11, c12) = _PyPacwar.battle(test, ones) (rounds2, c21, c22) = _PyPacwar.battle(test, threes) if (c11 > c12): res.append([rounds1, test[:]]) res.sort() print('test gene', res, '\n')
def run_pacWar(GE1, GE2, idx): (rounds, c1, c2) = _PyPacwar.battle(GE1[idx[0]], GE2[idx[1]]) scores = GAPacWar.get_scores(rounds, c1, c2) ge1_scores[idx[0]] += scores[0] ge2_scores[idx[1]] += scores[1] #print(scores) return scores
def check_if_champions(pop): champs = writers.read_champions() new_champs = [] new_scores = [] for p in pop: gene1 = p[0] for champ in champs: gene2 = champ[0] if (gene2, 0) not in new_champs: rounds, survivors1, survivors2 = battle(gene1, gene2) gene2_score = real_score((gene2, 0), pop) new_champs.append((gene2, 0)) new_scores.append(gene2_score) if (gene1, 0) not in new_champs: if survivors1 > survivors2: gene1_score = real_score((gene1, 0), pop) new_champs.append((gene1, 0)) new_scores.append(gene1_score) new_champs = sort_genes(new_champs, new_scores)[0:12] writers.clear_champions() writers.write_genes(new_champs, "champions.txt") #print(new_champs) print("Best Gene: ", new_champs[0][0], max(new_scores)) return new_champs
def main(): ones = [1]*50 threes = [3]*50 print "Example Python module in C for Pacwar" print "all ones versus all threes ..." (rounds,c1,c2) = _PyPacwar.battle(ones, threes) print "Number of rounds:", rounds print "Ones PAC-mites remaining:", c1 print "Threes PAC-mites remaining:", c2
def main(): ones = [1] * 50 threes = [3] * 50 print "Example Python module in C for Pacwar" print "all ones versus all threes ..." (rounds, c1, c2) = _PyPacwar.battle(ones, threes) print "Number of rounds:", rounds print "Ones PAC-mites remaining:", c1 print "Threes PAC-mites remaining:", c2
def main(): minheap = [] for i in range(50): minheap = [] Gene = [3]*50 Gene = Gene.copy() for j in range(4): Gene = Gene.copy() Gene[i] = j test_gene = PacMite(Gene) values = test_gene.value_factor if values[1] > 0 and values[2] > 0 and values[0]<500: #print(Gene,values) heappush(minheap,(Gene,values)) print(minheap[0]) Comparison_1 = [1] * 50 Comparison_2 = [3] * 50 res = [1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] print(_PyPacwar.battle(res, Comparison_1), _PyPacwar.battle(res, Comparison_2))
def run_GA(population): # generate random population of 50 if len(population) == 0: for x in range(0,50): population.append(generate_random_gene()) for run in range(0,100): # initialize score and freq dictionaries to 0 for each gene in random # population population_to_score = {} population_to_freq = {} for gene in population: population_to_score[gene] = 0 population_to_freq[gene] = 0 # battle and score each random gene in population again random competitor random_competitor = generate_random_gene() for gene in population: (rounds, c1, c2) = _PyPacwar.battle(transform_string_to_array(gene), transform_string_to_array(random_competitor)) population_to_score[gene] = score_battle(rounds, c1, c2) # find the sum of scores score_sum = 0 for gene in population_to_score: score_sum += population_to_score[gene] # find the proportion of each score for gene in population_to_score: population_to_freq[gene] = population_to_score[gene]*1.0 / score_sum # sort population frequencies in desc order population_to_freq_sorted = sorted(population_to_freq.items(), key=operator.itemgetter(1), reverse=True) # selection for mating mating_pool = [] for x in range(0,50): rand = random.random() cum_sum = 0 for pair in population_to_freq_sorted: cum_sum += pair[1] if (cum_sum > rand): mating_pool.append(pair[0]) break population = [] while len(population) < 50: mom = mating_pool[random.randint(0, 49)] dad = mating_pool[random.randint(0, 49)] (child1, child2) = crossover(mom, dad) population.append(transform_array_to_string(child1)) population.append(transform_array_to_string(child2)) return population[random.randint(0,49)]
def HC(iteration_limit,firstgeneration,initial_mutation_sitenumber): res=[] # choose the training set #random_start=[] #random_set_length=1 #for _ in range(random_set_length): #random_start.append([random.randint(0,3) for i in range(50)]) #start=random_start[:][0] k=500 while k!=0: select_position_mutation=[random.randint(0,49) for i in range(initial_mutation_sitenumber)] for i in select_position_mutation: start=firstgeneration[:] start[i]=random.randint(0,3) (rounds1, c11, c12) = _PyPacwar.battle(start, ones) (rounds2, c21, c22) = _PyPacwar.battle(start, threes) if c11>c12 and c21>c22: break k-=1 currentrounds=rounds1+rounds2 while iteration_limit!=0: nbrnode=next(start) # best after battle if nbrnode==[]: return start else: next_gene=nbrnode[3] next_rounds=nbrnode[0] if next_gene == start: return start else: if currentrounds <next_rounds: return start else: start=next_gene[:] iteration_limit -= 1 return next_gene
def dueling_stage(population): duels = [population[i:i + 2] for i in range(0, len(population), 2)] newpop = [] for duel in duels: gene1 = duel[0][0] gene2 = duel[1][0] rounds, survivors1, survivors2 = battle(gene1, gene2) if survivors1 > survivors2: newpop.append((gene1, 0.0)) else: newpop.append((gene2, 0.0)) print(len(newpop)) return newpop
def main(): Comparison_1 = [1] * 50 Comparison_2 = [3] * 50 prev = ([1] * 50, 500) pos = [0, 1, 2, 3] cur = ([1] * 50, 500) while prev[1] >= cur[1]: i = 1 res = [] cur = prev for i in range(50): Gene = cur[0].copy() for j in pos: Gene[i] = j Gene.copy() (rounds_1, c1_1, c1_2) = _PyPacwar.battle(Gene, Comparison_1) (rounds_2, c2_1, c2_2) = _PyPacwar.battle(Gene, Comparison_2) if int(c1_1) - int(c1_2) > 0 and c2_1 - c2_2 > 0: a = _PyPacwar.battle(Gene, Comparison_1) b = _PyPacwar.battle(Gene, Comparison_2) heappush(res, (a[0] + b[0], a[0], b[0], Gene)) cur = (res[0][0], res[0][3]) print('Iteration Number:', i, res[0], '/n') '''
def vanilla_score(gene1, gene2): rounds, survivors1, survivors2 = battle(gene1, gene2) i = 0 if survivors2 > survivors1: i = 1 if rounds < 100: return (20, 0)[i] elif rounds < 200: return (19, 1)[i] elif rounds < 300: return (18, 2)[i] elif rounds < 500: return (17, 3)[i] else: if survivors1 == 0 or survivors2 == 0: return (17, 3)[i] if survivors1 > survivors2: c = survivors1 / survivors2 else: c = survivors2 / survivors1 if c > 10: return (13, 7)[i] elif c > 3: return (12, 8)[i] elif c > 1.5: return (11, 9)[i] return 10
def hillClimb(): current = generateRandomGene() newBestScore = -9999999 newBest = None while 1: for i in range(len(current)): for j in range(0, 4): new = list(current) if current[i] == j: continue new[i] = j (rounds, c1, c2) = _PyPacwar.battle(new, current) thisScore = battleScore((rounds, c1, c2)) if thisScore >= newBestScore: newBestScore = thisScore newBest = new if newBest != current: current = newBest else: return current
def rankGenes(genes, wantToLog): n = len(genes) scores = [0] * n for i in range(n): for j in range(i + 1, n): iscore = battleScore(_PyPacwar.battle(genes[i], genes[j])) scores[i] += iscore / float(n) scores[j] += (20 - iscore) / float(n) scoresAndGenes = zip(genes, scores) scoresAndGenes.sort(lambda x, y: 1 if x[1] - y[1] > 0 else -1, None, True) r = 1 for s in scoresAndGenes: logMsg = "Rank " + str(r) + ", avg score " + str(s[1]) + ": " + str( s[0]) + "." print logMsg if wantToLog: with open("log.txt", "a") as f: f.write(logMsg) r += 1 return scoresAndGenes
def main(): good_population = [] for x in range(0,50): print "GA run#: " + str(x+1) good_population.append(run_GA([])) print "" best_gene = run_GA(good_population) print "Best Gene: " + best_gene # best_gene = "30022011131103123330231133202322103221230311223123" print "" # test "best" gene against 100 random ones. print stats num_wins = 0 num_losses = 0 num_rounds = 0 num_remaining = 0 for x in range(0,250): random_gene = generate_random_gene() (rounds,c1,c2) = _PyPacwar.battle(transform_string_to_array(best_gene), transform_string_to_array(random_gene)) if c1 == 0: num_losses += 1 else: num_wins += 1 num_remaining += c1 num_rounds += rounds percentage_win = 1.0*num_wins/250 avg_rounds = 1.0*num_rounds/num_wins avg_remaining = 1.0*num_remaining/num_wins print "Num Wins: " + str(num_wins) print "Num Losses: " + str(num_losses) print "Percentage Win: " + str(percentage_win) print "Average Rounds to Win: " + str(avg_rounds) print "Average Remaining when Win:" + str(avg_remaining)
def battleResults(gene1, gene2, wantToLog): print "gene1: " + str(gene1) print "gene2: " + str(gene2) (rounds, c1, c2) = _PyPacwar.battle(gene1, gene2) gene1Score = battleScore((rounds, c1, c2)) gene2Score = 20 - gene1Score print "Number of rounds:", rounds print "gene1 PAC-mites remaining:", c1 print "gene2 PAC-mites remaining:", c2 print "gene1 score: " + str(gene1Score) + ". gene2 score: " + str( gene2Score) print "" if wantToLog: with open("log.txt", "a") as f: f.write("gene1: " + str(gene1) + "\n") f.write("gene2: " + str(gene2) + "\n") f.write("Number of rounds:" + str(rounds) + "\n") f.write("gene1 PAC-mites remaining:" + str(c2) + "\n") f.write("gene2 PAC-mites remaining:" + str(c2) + "\n") f.write("gene1 score: " + str(gene1Score) + ". gene2 score: " + str(gene2Score) + "\n") f.write("\n\n")
def outcome_of_duel(i, j): #i and j are in list (rounds, c1, c2) = _PyPacwar.battle(i, j) if c1 > c2: # i win if rounds < 100: return 20, 0 elif rounds < 199: return 19, 1 elif rounds < 299: return 18, 2 elif rounds < 500: return 17, 3 elif c1 / c2 > 10: return 13, 7 elif c1 / c2 > 3: return 12, 8 elif c1 / c2 > 1.5: return 11, 9 else: return 10, 10 elif c1 == c2: return 10, 10 else: if rounds < 100: return 0, 20 elif rounds < 199: return 1, 19 elif rounds < 299: return 2, 18 elif rounds < 500: return 3, 17 elif c1 / c2 > 10: return 7, 13 elif c1 / c2 > 3: return 8, 12 elif c1 / c2 > 1.5: return 9, 11 else: return 10, 10
def main(): # read the input file candidates = [] with open('dummy.txt', 'r') as f: candidates_temp = f.readlines() for i in range(len(candidates_temp)): temp1 = candidates_temp[i].strip('\n') if temp1 not in candidates: candidates.append(temp1) # read the test set with open('testset.txt', 'r') as f: test_warrior = f.readlines() for i in range(len(test_warrior)): test_warrior[i] = test_warrior[i].strip('\n') test_warrior = test_warrior[0:10000] # battle now!! battle_res = [] for i in candidates: score = 0 candidates_ = [int(x) for x in i] wintimes = 0 for j in test_warrior: (rounds, c1, c2) = _PyPacwar.battle(candidates_, [int(x) for x in j]) if c1 > c2: # win!! wintimes += 1 if rounds < 50: score += 3 elif rounds < 200: score += 2 else: score += 1 battle_res.append([score, wintimes, i]) battle_res.sort(reverse=1) with open('battleres.txt', 'a') as f: for m in battle_res: f.write(str(m) + '\n')
def hillClimbVSCompetitors(competitors, restartUntilBetterFound, mutateOrNot, wantToLog, startGene=generateRandomGene(), restartFunction=None, restartThresholdScore=10, strictlyBeats=False, mutateAmount=4): current = startGene newBestScore = -9999999 newBest = None newGeneSucks = False preMutateBest = None preMutateBestScore = 0 roundsStuckAtMutation = 0 roundsStuckThreshold = 200 while 1: keepClimbing = False new = list(current) for i in range(len(current)): og = new[i] geneSucks = False for j in range(0, 4): if new[i] == j: continue new[i] = j totalScore = 0 for competitor in competitors: (rounds, c1, c2) = _PyPacwar.battle(new, competitor) theScore = battleScore((rounds, c1, c2)) if strictlyBeats and theScore <= restartThresholdScore: geneSucks = True # print "Gene sucks! Only got score of " + str(theScore) + " while required is " + str(restartThresholdScore) + " versus gene " + str(competitor) totalScore += theScore # print "Avg = " + str(float(totalScore) / len(competitors)) if totalScore > newBestScore: keepClimbing = True newBestScore = totalScore newBest = list(new) newGeneSucks = geneSucks # print "Found better gene with score " + str(newBestScore) + ". " + str(newBest) new[i] = og if keepClimbing: current = newBest else: if restartUntilBetterFound and ( float(newBestScore) / len(competitors) <= restartThresholdScore or newGeneSucks): # print "Hill climb found local maxima, and it sucked with average score of " + \ # str(float(newBestScore)/len(competitors)) + "..." if mutateOrNot or restartFunction is None: if newBestScore > preMutateBestScore: preMutateBest = list(current) preMutateBestScore = newBestScore print "New Best Score: " + str(newBestScore) roundsStuckAtMutation = 0 else: roundsStuckAtMutation += 1 if roundsStuckAtMutation == roundsStuckThreshold: print "Stuck at mutation for " + str( roundsStuckThreshold ) + " rounds! Mega mutating." # Fishy line below. This will most probably decrease the strength of the preMutateBest... # Not sure if this is the correct approach. preMutateBest = mutate(preMutateBest, wantToLog, mutateAmount * 2) roundsStuckAtMutation = 0 current = list(preMutateBest) current = mutate(current, wantToLog, mutateAmount) else: current = restartFunction() newBest = None newBestScore = -9999999 newGeneSucks = False else: logMsg = "Hill Climb found " if strictlyBeats: logMsg += "strictly " logMsg += "better gene! " + str(current) print logMsg if wantToLog: with open("log.txt", "a") as f: f.write(logMsg + "\n") return current
def evaluate(self, GE1, GE2, parallel=True, verbose=0): ''' GE1: genes for specie 1 GE2: genes for specie 2 ''' #assert len(GE1) == len(GE2) #pop_size = len(GE1) #start_time = time.time() if parallel: assert verbose == 0 global ge1_scores global ge2_scores ge1_scores = Array('d', [0] * len(GE1)) ge2_scores = Array('d', [0] * len(GE2)) self.p = Pool(multiprocessing.cpu_count()) for i in xrange(len(GE1)): for j in xrange(len(GE2)): # bottleneck res = self.p.apply_async(run_pacWar, args=( GE1, GE2, (i, j), )) #scores = res.get(timeout=1) if verbose: print( "The duel lasted %d rounds, specie 1 remains: %d, specie 2 remains: %d" % (rounds, c1, c2)) print( "The final scores for GE1[%d] vs GE2[%d] are: %d : %d" % (i, j, scores[0], scores[1])) self.p.close() self.p.join() ge1_scores = list(ge1_scores) ge2_scores = list(ge2_scores) #print(time.time() - start_time) if not parallel: ge1_scores = [0.0] * len(GE1) ge2_scores = [0.0] * len(GE2) for i in xrange(len(GE1)): for j in xrange(len(GE2)): # bottleneck (rounds, c1, c2) = _PyPacwar.battle(GE1[i], GE2[j]) scores = self.get_scores(rounds, c1, c2) ge1_scores[i] += scores[0] ge2_scores[j] += scores[1] if verbose: print( "The duel lasted %d rounds, specie 1 remains: %d, specie 2 remains: %d" % (rounds, c1, c2)) print( "The final scores for GE1[%d] vs GE2[%d] are: %d : %d" % (i, j, scores[0], scores[1])) ge1_scores = [i / len(GE2) for i in ge1_scores] ge2_scores = [i / len(GE1) for i in ge2_scores] return ge1_scores, ge2_scores
def main(): base_threes = [3] * 50 threes = [3] * 50 nfittest = 50 initial = [] initial += [[ 0, 1, 1, 0, 3, 3, 1, 1, 3, 0, 2, 2, 1, 1, 3, 2, 2, 3, 3, 2, 0, 2, 2, 3, 2, 1, 3, 2, 3, 1, 3, 1, 3, 1, 1, 1, 1, 2, 3, 0, 2, 1, 0, 1, 1, 2, 3, 1, 2, 3 ], [ 3, 0, 3, 3, 3, 1, 1, 3, 0, 0, 1, 2, 3, 1, 2, 3, 3, 3, 0, 1, 2, 3, 0, 1, 1, 1, 1, 0, 0, 3, 1, 0, 3, 3, 0, 2, 2, 1, 1, 1, 0, 0, 1, 2, 3, 1, 2, 2, 1, 2 ], [ 3, 3, 2, 0, 3, 2, 1, 2, 1, 0, 0, 3, 0, 1, 1, 1, 1, 1, 3, 3, 2, 0, 0, 1, 2, 3, 3, 3, 3, 3, 2, 1, 0, 3, 3, 1, 2, 0, 2, 0, 1, 1, 2, 2, 2, 3, 0, 1, 1, 0 ], [ 3, 1, 1, 1, 3, 1, 0, 1, 2, 2, 0, 1, 3, 1, 0, 2, 2, 3, 2, 2, 1, 1, 2, 2, 2, 3, 0, 0, 0, 1, 2, 0, 2, 1, 3, 3, 0, 1, 1, 1, 0, 3, 3, 0, 1, 3, 3, 1, 0, 3 ], [ 2, 0, 0, 0, 3, 1, 1, 3, 2, 0, 2, 3, 1, 3, 1, 3, 2, 2, 2, 2, 0, 2, 0, 1, 0, 0, 1, 3, 3, 3, 2, 3, 0, 2, 1, 2, 2, 0, 2, 3, 2, 1, 1, 0, 3, 3, 0, 2, 3, 1 ], [ 2, 1, 1, 3, 3, 2, 1, 3, 0, 2, 0, 0, 1, 1, 1, 1, 1, 0, 3, 3, 0, 2, 3, 2, 0, 0, 2, 1, 0, 0, 3, 0, 2, 0, 1, 0, 0, 2, 1, 0, 2, 0, 3, 0, 3, 1, 1, 2, 2, 1 ], [ 2, 2, 3, 0, 3, 1, 0, 0, 3, 0, 3, 0, 3, 2, 1, 3, 0, 2, 0, 0, 1, 0, 0, 0, 3, 3, 1, 3, 0, 3, 3, 0, 0, 1, 2, 1, 1, 0, 2, 1, 1, 3, 0, 2, 0, 2, 1, 0, 2, 1 ], [ 0, 1, 3, 0, 3, 3, 3, 3, 1, 0, 2, 0, 0, 1, 2, 2, 3, 0, 3, 3, 1, 3, 3, 3, 2, 3, 0, 3, 1, 1, 3, 2, 3, 2, 2, 0, 2, 2, 0, 3, 0, 2, 3, 0, 1, 0, 2, 0, 1, 0 ], [ 0, 3, 1, 3, 2, 1, 3, 2, 0, 1, 0, 0, 3, 0, 2, 3, 3, 2, 0, 1, 1, 1, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1, 0, 0, 3, 3, 0, 2, 3, 2, 3, 0, 0, 2, 3, 3, 3, 1 ]] for i in range(0, 75): initial += [randomSpecies()] while True: myHeap = [] for i in range(0, len(initial)): (rounds, c1, c2) = _PyPacwar.battle(initial[i], threes) if c2 < c1: print "Win against 3! " print initial[ i], " candidate: ", c1, " threes: ", c2, " rounds: ", rounds heapq.heappush(myHeap, (-20 - (c1 / (c2 + 1.0)), initial[i])) continue else: score = -(pow(c1, 0.5) + pow(rounds, 0.3) + (14.0 / math.log(c2 - c1 + 2, 2))) # if i<10: # print initial[i]," candidate: ",c1," threes: ",c2," rounds: ",rounds," score: ",score heapq.heappush(myHeap, (score, initial[i])) fittest = heapq.nsmallest( nfittest, myHeap ) #fittest is a list of 'nfittest' no. of tuples where each tuple is (score,gene) (rounds, c1, c2) = _PyPacwar.battle(fittest[0][1], threes) print() print "Fittest after tournament: ", fittest[ 0], " candidate: ", c1, " threes: ", c2, " rounds: ", rounds (rounds, c1, c2) = _PyPacwar.battle(fittest[1][1], threes) print "2nd Fittest after tournament: ", fittest[ 1], " candidate: ", c1, " threes: ", c2, " rounds: ", rounds initial = crossAndMutate(fittest) print "intial size: ", len(initial)