def parallel_evaluation(compressed_pop, chunk): # This function will run in parallel from neat.nn import nn_pure as nn # don't print OS calls to stdout: #http://www.parallelpython.com/component/option,com_smf/Itemid,29/topic,103.0 print("Evaluating chunk %d at %s" %(chunk, os.popen("hostname").read())) # decompress the pickled object decompress_pop = zlib.decompress(compressed_pop) # unpickle it sub_pop = pickle.loads(decompress_pop) # XOR-2 INPUTS = ((0, 0), (0, 1), (1, 0), (1, 1)) OUTPUTS = (0, 1, 1, 0) fitness = [] for c in sub_pop: net = nn.create_ffphenotype(c) error = 0.0 for i, input in enumerate(INPUTS): output = net.sactivate(input) # serial activation error += (output[0] - OUTPUTS[i])**2 fitness.append(1 - math.sqrt(error/len(OUTPUTS))) # when finished, return the list of fitness values return fitness
def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) fitness = MAX_FITNESS possible_fitness = 0 num_correct = 0 for i in range(len(games)): game = games[i] inputs = [] home_stats = teams[game.home()].team_stats() away_stats = teams[game.away()].team_stats() for i in range(0, len(home_stats)): inputs.append(home_stats[i] - away_stats[i]) #print inputs outputs = net.sactivate(inputs) home_win_prob = outputs[0] margin = outputs[1] r = random.random() if (r < home_win_prob) == (game.result() > 0): fitness -= math.fabs(margin - (math.fabs(game.result()) / float(100))) else: fitness -= math.fabs(game.result()) / float(100) chromo.fitness = fitness / float(MAX_FITNESS)
def parallel_evaluation(compressed_pop, chunk): # This function will run in parallel from neat.nn import nn_pure as nn # don't print OS calls to stdout: #http://www.parallelpython.com/component/option,com_smf/Itemid,29/topic,103.0 print "Evaluating chunk %d at %s" % (chunk, os.popen("hostname").read()) # decompress the pickled object decompress_pop = zlib.decompress(compressed_pop) # unpickle it sub_pop = pickle.loads(decompress_pop) # XOR-2 INPUTS = ((0, 0), (0, 1), (1, 0), (1, 1)) OUTPUTS = (0, 1, 1, 0) fitness = [] for c in sub_pop: net = nn.create_ffphenotype(c) error = 0.0 for i, input in enumerate(INPUTS): output = net.sactivate(input) # serial activation error += (output[0] - OUTPUTS[i])**2 fitness.append(1 - math.sqrt(error / len(OUTPUTS))) # when finished, return the list of fitness values return fitness
def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) fitness = MAX_FITNESS possible_fitness = 0 num_correct = 0 for game in games: #print #print game.home() + " vs " + game.away() inputs = [] home_stats = teams[game.home()].team_stats() away_stats = teams[game.away()].team_stats() for i in range(0, len(home_stats)): inputs.append(home_stats[i]-away_stats[i]) #print inputs outputs = net.sactivate(inputs) home_win_prob = outputs[0] margin = outputs[1] r = random.random() if (r < home_win_prob) == (game.result() > 0): fitness -= math.fabs(margin - (math.fabs(game.result())/float(100))) else: fitness -= math.fabs(game.result())/float(100) chromo.fitness = fitness / float(MAX_FITNESS)
def eval_fitness(population): #global melhor_score for chromo in population: net = nn.create_ffphenotype(chromo) score = play_with_AI(net) chromo.fitness = score
def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) wins = 0 # run 7 games for i in range(0, 20): net.flush() wins += do_stuff(net) chromo.fitness = wins
def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) error = 0.0 for i, inputs in enumerate(data): net.flush() # not strictly necessary in feedforward nets output = net.sactivate(inputs) # serial activation error += (output[0] - target[i])**2 chromo.fitness = 1 - math.sqrt(error/len(target))
def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) play = neatGame.Game() temp = 0.0 for x in range(NUMAVG): temp += play.main_loop(False, net) temp = temp / NUMAVG chromo.fitness = temp / 10000.0
def predict(self, data): if(not self.network): raise Exception("Classifier must be fit before it can be used for predictions") brain = nn.create_ffphenotype(self.network) predictions = [] for i, inputs in enumerate(data): output = brain.sactivate(inputs) # serial activation predictions.append(output[0]) return [self.discretize_prediction(prediction) for prediction in predictions]
def eval_fitness(population): global INPUTS global OUTPUTS counter = 0 for chromo in population: brain = nn.create_ffphenotype(chromo) error = 0.0 for i, inputs in enumerate(INPUTS): brain.flush() output = brain.sactivate(inputs) error += (output[0] - OUTPUTS[i])**2 chromo.fitness = 1 - error """
def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) error = 0.0 #error_stanley = 0.0 for i, inputs in enumerate(INPUTS): net.flush() # not strictly necessary in feedforward nets output = net.sactivate(inputs) # serial activation error += (output[0] - OUTPUTS[i])**2 #error_stanley += math.fabs(output[0] - OUTPUTS[i]) #chromo.fitness = (4.0 - error_stanley)**2 # (Stanley p. 43) chromo.fitness = 1 - math.sqrt(error/len(OUTPUTS))
def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) error = 0.0 #error_stanley = 0.0 for i, inputs in enumerate(INPUTS): net.flush() # not strictly necessary in feedforward nets output = net.sactivate(inputs) # serial activation error += (output[0] - OUTPUTS[i])**2 #error_stanley += math.fabs(output[0] - OUTPUTS[i]) #chromo.fitness = (4.0 - error_stanley)**2 # (Stanley p. 43) chromo.fitness = 1 - math.sqrt(error / len(OUTPUTS))
def eval_fitness(population): """ Create a fitness function that returns higher values for better solutions. For this task, we first calculate the sum-squared error of a network on the XOR task. Good networks will have low error, so the fitness is 1 - sqrt(avgError). """ for chromo in population: brain = nn.create_ffphenotype(chromo) error = 0.0 for i, inputs in enumerate(INPUTS): brain.flush() output = brain.sactivate(inputs) error += (output[0] - OUTPUTS[i])**2 chromo.fitness = 1 - math.sqrt(error/len(OUTPUTS))
def main(argv=None): if argv is None: argv = sys.argv[1:] if len(argv) != 1: print "Usage: python evaluateXOR.py chromo_file" return chromo_file = argv[0] fp = open(chromo_file, "r") chromo = pickle.load(fp) fp.close() print chromo visualize.draw_net(chromo, "_" + chromo_file) # Let's check if it's really solved the problem print '\nNetwork output:' brain = nn.create_ffphenotype(chromo) for i, inputs in enumerate(INPUTS): output = brain.sactivate(inputs) # serial activation print "%1.5f \t %1.5f" % (OUTPUTS[i], output[0])
def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) fitness = MAX_FITNESS possible_fitness = 0 num_correct = 0 for i in range(100, len(games)): game = games[i] inputs = shapes[i] #print inputs outputs = net.sactivate(inputs) home_win_prob = outputs[0] margin = outputs[0] if ((game.result() > 0) != (margin > 0)): fitness -= 1 chromo.fitness = fitness / float(MAX_FITNESS)
#print "A fitness was " + str(chromo.fitness) population.Population.evaluate = eval_fitness pop = population.Population() pop.epoch(eval_fitness, 100, report=True, save_best=False) winner = pop.population[0] print 'Number of evaluations: %d' %winner.id # Visualize the winner network (requires PyDot) #visualize.draw_net(winner) # best chromosome # Plots the evolution of the best/average fitness (requires Biggles) #visualize.plot_stats(pop.stats) # Visualizes speciation #visualize.plot_species(pop.species_log) # Let's check if it's really solved the problem print '\nBest network output:' brain = nn.create_ffphenotype(winner) print brain.neurons print brain.synapses # saves the winner file = open('winner_chromosome', 'w') pickle.dump(winner, file) file.close()
def __init__(self, chromo, logfile): self.nnet = nn.create_ffphenotype(chromo) # used to save information about the agent's behavior self.logfile = logfile
def __init__(self, chromo): # Turn the flat chromosome into a neural network self.nnet = nn.create_ffphenotype(chromo)
population.Population.evaluate = eval_fitness pop = population.Population() pop.epoch(eval_fitness, 300, report=True, save_best=False) winner = pop.population[0] print 'Number of evaluations: %d' % winner.id # Visualize the winner network (requires PyDot) #visualize.draw_net(winner) # best chromosome # Plots the evolution of the best/average fitness (requires Biggles) #visualize.plot_stats(pop.stats) # Visualizes speciation #visualize.plot_species(pop.species_log) # Let's check if it's really solved the problem print '\nBest network output:' brain = nn.create_ffphenotype(winner) print brain.neurons print brain.synapses # saves the winner file = open('winner_chromosome', 'w') pickle.dump(winner, file) file.close() file = open("winner_chromosome") chromo = pickle.load(file) best_net = nn.create_ffphenotype(chromo) file.close()
import random import cPickle as pickle from scraper import Scraper from neat.nn import nn_pure as nn file = open("winner_chromosome") chromo = pickle.load(file) best_net = nn.create_ffphenotype(chromo) file.close() stats_scraper = Scraper() teams = stats_scraper.retrieve_teams() standings = dict.fromkeys(teams.keys(), 0) # for home_team in teams.keys(): # for away_team in teams.keys(): # inputs = [] # home_stats = teams[home_team].team_stats() # away_stats = teams[away_team].team_stats() # for i in range(0, len(home_stats)): # inputs.append(home_stats[i]-away_stats[i]) # outcome_prediction = best_net.sactivate(inputs)[0] # if random.random() < outcome_prediction: # standings[home_team] += 1 # else: # standings[away_team] += 1
def evolve(company, stock_data, outfile, results_dict): global INPUTS global OUTPUTS # inputs (list of lists -- inner lists are ten-day stock price trends, which move forward # one day at a time in the outer list) # print "input len:", len(INPUTS) # print "output len:", len(OUTPUTS) #INPUTS = [] #OUTPUTS = [] data_list = [] for key in stock_data[company]: if key == 'Date': continue new_data = stock_data[company][key] new_data['date'] = key data_list.append(new_data) data_list.sort(key=operator.itemgetter('date')) for i in range(4, len(data_list) - 1): data_to_add = [] for j in range(i - 4, i + 1): data_to_add.append(float(data_list[j]['open'])) INPUTS.append(data_to_add) #print INPUTS # outputs #OUTPUTS = [] for i in range(5, len(data_list)): #OUTPUTS.append(float(data_list[i]['open'])) if float(data_list[i]['open']) > float(data_list[i - 1]['open']): OUTPUTS.append(1) else: OUTPUTS.append(0) #print OUTPUTS #return # NEAT if not os.path.isfile("company_chromos/best_chromo_99_%s" % company): print "we have to evolve this chromo" population.Population.evaluate = eval_fitness pop = population.Population(company) pop.epoch(100, report=True, save_best=True) # visualize.plot_stats(pop.stats) # visualize.plot_species(pop.species_log) # evaluate try: fp = open("company_chromos/best_chromo_99_%s" % company, "r") except IOError: print "we couldn't evolve this chromo, oh well" return chromo = pickle.load(fp) fp.close() #chromo = pickle.load(BEST_CHROMO) #chromo = BEST_CHROMO #print chromo #visualize.draw_net(chromo, "_" + "best_chromo_99") # Let's check if it's really solved the prolem #print '\nNetwork output:' brain = nn.create_ffphenotype(chromo) counter1 = 0 counter2 = 0 counter3 = 0 counter4 = 0 counter5 = 0 counter6 = 0 counter7 = 0 counter8 = 0 counter9 = 0 counter10 = 0 """ for i, inputs in enumerate(INPUTS): output = brain.sactivate(inputs) counter6 += output[0] avg_value = counter6/len(INPUTS) """ # care more about the "weighted median" which is unbiased output_list = [] avg_counter = 0 for i, inputs in enumerate(INPUTS): output = brain.sactivate(inputs) output_list.append(output[0]) for value in OUTPUTS: if value == 0: counter6 += 1 median_value = sorted(output_list)[counter6] avg_value = sorted(output_list)[len(output_list) / 2] for i, inputs in enumerate(INPUTS): output = brain.sactivate(inputs) #print "%1.5f \t %1.5f" %(OUTPUTS[i], output[0]) if OUTPUTS[i] == 1: counter3 += 1 else: counter5 += 1 if OUTPUTS[i] == 1 and output[0] > 0.5: counter1 += 1 elif OUTPUTS[i] == 0 and output[0] < 0.5: counter4 += 1 if OUTPUTS[i] == 1 and output[0] > median_value: counter7 += 1 elif OUTPUTS[i] == 0 and output[0] < median_value: counter8 += 1 if OUTPUTS[i] == 1 and output[0] > avg_value: counter9 += 1 elif OUTPUTS[i] == 0 and output[0] < avg_value: counter10 += 1 counter2 += 1 outfile.write("\n--STATISTICS--\n\n") s = "COMPANY: %s\n" % company outfile.write(s) s = "len(INPUTS): %d\n" % len(INPUTS) outfile.write(s) s = "NUMBER OF 1'S: %d\n" % counter3 outfile.write(s) s = "NUMBER OF 0'S: %d\n" % (counter2 - counter3) outfile.write(s) s = "1'S CORRECT: %d/%d (%.3f%%)\n" % (counter1, counter3, float(counter1) / counter3 * 100) outfile.write(s) s = "0's CORRECT: %d/%d (%.3f%%)\n" % (counter4, counter5, float(counter4) / counter5 * 100) outfile.write(s) s = "GOT %d OUT OF %d CORRECT OVERALL (%.3f%%)\n" % ( counter1 + counter4, counter2, float(counter1 + counter4) / counter2 * 100) outfile.write(s) s = "NUMBER OF 1'S CORRECT WHEN COMPARED TO WEIGHTED MEDIAN: %d/%d (%.3f%%)\n" % ( counter7, counter3, float(counter7) / counter3 * 100) outfile.write(s) s = "NUMBER OF 0'S CORRECT WHEN COMPARED TO WEIGHTED MEDIAN: %d/%d (%.3f%%)\n" % ( counter8, counter5, float(counter8) / counter5 * 100) outfile.write(s) s = "NUMBER OF 1'S CORRECT WHEN COMPARED TO AVERAGE VALUE: %d/%d (%.3f%%)\n" % ( counter9, counter3, float(counter9) / counter3 * 100) outfile.write(s) s = "NUMBER OF 0'S CORRECT WHEN COMPARED TO AVERAGE VALUE: %d/%d (%.3f%%)\n" % ( counter10, counter5, float(counter10) / counter5 * 100) outfile.write(s) # create a dictionary with the "results" of the training # key: company symbol # value: {chromo file, stat (NO, ACTUAL, AVG, MEDIAN), % ones correct, % zeroes correct} # note that stat is a string, and no means at least one of 1's/0's was correct < 50% of the time results_dict[company] = {} # results_dict[company]["chromo"] = chromo if min(counter1, counter4) > min(counter7, counter8): if min(counter1, counter4) > min(counter9, counter10): if counter1 < counter3 / 2 or counter4 < counter5 / 2: stat = "NO" else: stat = "ACTUAL" ones = float(counter1) / counter3 * 100 zeroes = float(counter4) / counter5 * 100 else: if counter9 < counter3 / 2 or counter10 < counter5 / 2: stat = "NO" else: stat = "AVERAGE" ones = float(counter9) / counter3 * 100 zeroes = float(counter10) / counter5 * 100 else: if min(counter7, counter8) > min(counter9, counter10): if counter7 < counter3 / 2 or counter8 < counter5 / 2: stat = "NO" else: stat = "MEDIAN" ones = float(counter7) / counter3 * 100 zeroes = float(counter8) / counter5 * 100 else: if counter9 < counter3 / 2 or counter10 < counter5 / 2: stat = "NO" else: stat = "AVERAGE" ones = float(counter9) / counter3 * 100 zeroes = float(counter10) / counter5 * 100 if stat == "NO": ones = 0 zeroes = 0 results_dict[company]["stat"] = stat results_dict[company]["ones_percent"] = ones results_dict[company]["zeroes_percent"] = zeroes results_dict[company]["average"] = avg_value results_dict[company]["median"] = median_value dict_string = json.dumps(results_dict) outfile = open('network_output.txt', 'w') outfile.write(dict_string) outfile.close()
import random import cPickle as pickle import math from scraper import Scraper from neat import visualize from neat.nn import nn_pure as nn stats_scraper = Scraper() games = stats_scraper.get_games() file = open("winner_chromosome") chromo = pickle.load(file) best_net = nn.create_ffphenotype(chromo) file.close() visualize.draw_net(chromo) print '\nBest network output:' brain = nn.create_ffphenotype(chromo) print brain.neurons print brain.synapses file = open("shapes") shapes = pickle.load(file) file.close() j = 0 s = float(0) tp = float(0) fp = float(0) fn = float(0) hw = float(0)
def main(): # network output dictionary infile = open('network_output.txt', 'r') results = json.loads(infile.readlines()[0]) infile.close() # stock data dictionary (same as obtain_data_test.py) company_dict = get_companies() company_dict, stock_data = get_stock_data(company_dict) # starting variables start_money = 1000 transaction_costs = 0 current_stocks = {} start_date = datetime.date(2015, 7, 26) test_results = {} for i in range(30): start_date += datetime.timedelta(days=1) if start_date.weekday() == 5 or start_date.weekday() == 6: continue test_results[start_date] = {} # build the data dictionary (subset of stock_data for the last few dates) test_data = {} for company in company_dict: test_data[company] = {} for key in stock_data[company]: if key == 'Date': continue if dateutil.parser.parse(key).date() < start_date: continue #new_data = stock_data[company][key] #new_data['date'] = key #data_list.append(new_data) test_data[company][key] = stock_data[company][key] test_data[company][key]['date'] = key #data_list.sort(key=operator.itemgetter('date')) # see how many predictions we get right for the first day (August 3rd) count_correct_gain = 0 count_correct_loss = 0 count_incorrect = 0 count_wtf = 0 inputs = {} for company in results: if company not in test_data.keys(): print "WTF?" count_wtf += 1 continue if results[company]['stat'] == "NO": continue inputs[company] = [] for key in test_data[company]: inputs[company].append(test_data[company][key]) inputs[company].sort(key=operator.itemgetter('date')) # load the brain and test try: fp = open("company_chromos/best_chromo_99_%s" % company, "r") except IOError: print "damn, couldn't load the chromo" continue chromo = pickle.load(fp) fp.close() brain = nn.create_ffphenotype(chromo) #network_inputs = inputs[company][0:5] network_inputs = [] if len(inputs[company]) < 6: continue for i in range(5): network_inputs.append(inputs[company][i]['open']) #print network_inputs output = brain.sactivate(network_inputs) actual_output = output[0] if results[company]['stat'] == "ACTUAL": if actual_output > 0.5 and inputs[company][5]['open'] > inputs[ company][4]['open']: count_correct_gain += 1 elif actual_output < 0.5 and inputs[company][5][ 'open'] < inputs[company][4]['open']: count_correct_loss += 1 else: count_incorrect += 1 elif results[company]['stat'] == "AVERAGE": if actual_output > results[company]['average'] and inputs[ company][5]['open'] > inputs[company][4]['open']: count_correct_gain += 1 elif actual_output < results[company]['average'] and inputs[ company][5]['open'] < inputs[company][4]['open']: count_correct_loss += 1 else: count_incorrect += 1 elif results[company]['stat'] == "MEDIAN": if actual_output > results[company]['median'] and inputs[ company][5]['open'] > inputs[company][4]['open']: count_correct_gain += 1 elif actual_output < results[company]['median'] and inputs[ company][5]['open'] < inputs[company][4]['open']: count_correct_loss += 1 else: count_incorrect += 1 print "CURRENT TABS:" print "CORRECT GAIN:", count_correct_gain print "CORRECT LOSS:", count_correct_loss print "CORRECT TOTAL:", count_correct_gain + count_correct_loss print "INCORRECT TOTAL:", count_incorrect test_results[start_date]["correct_gain"] = count_correct_gain test_results[start_date]["correct_loss"] = count_correct_loss test_results[start_date][ "correct_total"] = count_correct_gain + count_correct_loss test_results[start_date]["incorrect_total"] = count_incorrect for date in test_results: print date, test_results[date] print "wtf_count:", count_wtf
from neat import config, population, chromosome, genome, visualize from neat.nn import nn_pure as nn from checkpoint import Checkpointer #from player_2048 import * import sys pop = Checkpointer.restore_checkpoint(sys.argv[1]) winner = pop.stats[0][-1] print('Number of evaluations: %d' % winner.id) # Visualize the winner network (requires PyDot) #visualize.draw_net(winner) # best chromosome # Plots the evolution of the best/average fitness (requires Biggles) #visualize.plot_stats(pop.stats) # Visualizes speciation #visualize.plot_species(pop.species_log) print pop.species_log # Let's check if it's really solved the problem print('\nBest network output:') brain = nn.create_ffphenotype(winner) score = play_with_AI(brain) print 'score do melhor: ' + str(int(score))
def eval_individual(chromo, currentGen, logFP=None): if currentGen > 0: chromo_file = "blue_best_chromo_" + str(currentGen-1) while not os.path.isfile(chromo_file): pass time.sleep(1) else: chromo_file = "blue_init_chromo" fp = open(chromo_file, "r") opponentChromo = pickle.load(fp) fp.close() redBrain = nn.create_ffphenotype(chromo) blueBrain = nn.create_ffphenotype(opponentChromo) trials = 2 steps = 125 score = 0 for trial in range(trials): redEng.simulation[0].setPose('redRobot', 5, 1, 0) redEng.simulation[0].setPose('blueRobot', 5, 9, math.pi) redEng.simulation[0].eval("self.refillLights(0.3)") redLight = 0 blueLight = 0 redCounter = 0 blueCounter = 0 accomplished = 0 for i in range(steps): redBrain.flush() blueBrain.flush() redEng.update() blueEng.update() redResult = redEng.eat(-1) blueResult = blueEng.eat(-1) if redResult > 0: redLight = 1 redCounter = 1 if logFP: logFP.write("Red robot has the ball\n") elif blueResult > 0: blueLight = 1 blueCounter = 1 if logFP: logFP.write("Blue robot has the ball\n") redPosition = redEng.simulation[0].getPose('redRobot') bluePosition = redEng.simulation[0].getPose('blueRobot') xdist = redPosition[0] - bluePosition[0] ydist = redPosition[1] - bluePosition[1] dist = math.sqrt(xdist**2 + ydist**2) if dist < 0.75: if redLight > 0: redLight = 0 blueLight = 1 redEng.simulation[0].setPose('redRobot', 5, 1, 0) elif blueLight > 0: redLight = 1 blueLight = 0 redEng.simulation[0].setPose('blueRobot', 5, 9, math.pi) if redEng.stall: break sonar = min([s.distance() for s in redEng.range["front"]]) xdistFromBase = redPosition[0] - 5 ydistFromBase = redPosition[1] - 1 heading = redPosition[2] xdistFromOpponent = xdist ydistFromOpponent = ydist opponentHeading = bluePosition[2] redIn = redEng.light[0].value redIn.append(sonar/10.0) redIn.append(redLight) redIn.append(blueLight) redIn.append(xdistFromBase) redIn.append(ydistFromBase) redIn.append(heading) redIn.append(xdistFromOpponent) redIn.append(ydistFromOpponent) redIn.append(opponentHeading) # print "redIn:", redIn redOut = redBrain.sactivate(redIn) bluesonar = min([s.distance() for s in blueEng.range["front"]]) bluexdistFromBase = bluePosition[0] - 5 blueydistFromBase = bluePosition[1] - 9 blueheading = bluePosition[2] bluexdist = bluePosition[0] - redPosition[0] blueydist = bluePosition[1] - redPosition[1] bluexdistFromOpponent = bluexdist blueydistFromOpponent = blueydist blueopponentHeading = bluePosition[2] blueIn = blueEng.light[0].value blueIn.append(bluesonar/10.0) blueIn.append(redLight) blueIn.append(blueLight) blueIn.append(bluexdistFromBase) blueIn.append(blueydistFromBase) blueIn.append(blueheading) blueIn.append(bluexdistFromOpponent) blueIn.append(blueydistFromOpponent) blueIn.append(blueopponentHeading) # print "blueIn:", blueIn blueOut = blueBrain.sactivate(blueIn) distFromBase = math.sqrt(xdistFromBase**2 + ydistFromBase**2) if redLight and distFromBase < 0.5: score += 24 accomplished = 1 break # took out ".robot" between redEng and motors, e.g. if redLight: redEng.motors(0.7*redOut[0], 0.7*redOut[1]) blueEng.motors(blueOut[0], blueOut[1]) elif blueLight: blueEng.motors(0.7*blueOut[0], 0.7*blueOut[1]) redEng.motors(redOut[0], redOut[1]) else: redEng.motors(redOut[0], redOut[1]) blueEng.motors(blueOut[0], blueOut[1]) if redCounter == 0 and blueCounter == 0 and not accomplished: xdistFromLight = redPosition[0] - 5 ydistFromLight = redPosition[1] - 5 distFromLight = math.sqrt(xdistFromLight**2 + ydistFromLight**2) score += 8 - distFromLight # fitness between 1 and 8 (approx) elif redCounter == 0 and not accomplished: distFromOpponent = math.sqrt(xdistFromOpponent**2 + ydistFromOpponent**2) score += 16 - distFromOpponent elif redCounter == 1 and redLight == 1 and not accomplished: distFromBase = math.sqrt(xdistFromBase**2 + ydistFromBase**2) score += 24 - distFromBase elif not accomplished: distFromOpponent = math.sqrt(xdistFromOpponent**2 + ydistFromOpponent**2) score += 20 - distFromOpponent blueEng.stop() redEng.stop() return score
def eval_individual(chromo, currentGen, logFP=None): if currentGen > 0: chromo_file = "blue_best_chromo_" + str(currentGen - 1) while not os.path.isfile(chromo_file): pass time.sleep(1) else: chromo_file = "blue_init_chromo" fp = open(chromo_file, "r") opponentChromo = pickle.load(fp) fp.close() redBrain = nn.create_ffphenotype(chromo) blueBrain = nn.create_ffphenotype(opponentChromo) trials = 2 steps = 125 score = 0 for trial in range(trials): redEng.simulation[0].setPose('redRobot', 5, 1, 0) redEng.simulation[0].setPose('blueRobot', 5, 9, math.pi) redEng.simulation[0].eval("self.refillLights(0.3)") redLight = 0 blueLight = 0 redCounter = 0 blueCounter = 0 accomplished = 0 for i in range(steps): redBrain.flush() blueBrain.flush() redEng.update() blueEng.update() redResult = redEng.eat(-1) blueResult = blueEng.eat(-1) if redResult > 0: redLight = 1 redCounter = 1 if logFP: logFP.write("Red robot has the ball\n") elif blueResult > 0: blueLight = 1 blueCounter = 1 if logFP: logFP.write("Blue robot has the ball\n") redPosition = redEng.simulation[0].getPose('redRobot') bluePosition = redEng.simulation[0].getPose('blueRobot') xdist = redPosition[0] - bluePosition[0] ydist = redPosition[1] - bluePosition[1] dist = math.sqrt(xdist**2 + ydist**2) if dist < 0.75: if redLight > 0: redLight = 0 blueLight = 1 redEng.simulation[0].setPose('redRobot', 5, 1, 0) elif blueLight > 0: redLight = 1 blueLight = 0 redEng.simulation[0].setPose('blueRobot', 5, 9, math.pi) if redEng.stall: break sonar = min([s.distance() for s in redEng.range["front"]]) xdistFromBase = redPosition[0] - 5 ydistFromBase = redPosition[1] - 1 heading = redPosition[2] xdistFromOpponent = xdist ydistFromOpponent = ydist opponentHeading = bluePosition[2] redIn = redEng.light[0].value redIn.append(sonar / 10.0) redIn.append(redLight) redIn.append(blueLight) redIn.append(xdistFromBase) redIn.append(ydistFromBase) redIn.append(heading) redIn.append(xdistFromOpponent) redIn.append(ydistFromOpponent) redIn.append(opponentHeading) # print "redIn:", redIn redOut = redBrain.sactivate(redIn) bluesonar = min([s.distance() for s in blueEng.range["front"]]) bluexdistFromBase = bluePosition[0] - 5 blueydistFromBase = bluePosition[1] - 9 blueheading = bluePosition[2] bluexdist = bluePosition[0] - redPosition[0] blueydist = bluePosition[1] - redPosition[1] bluexdistFromOpponent = bluexdist blueydistFromOpponent = blueydist blueopponentHeading = bluePosition[2] blueIn = blueEng.light[0].value blueIn.append(bluesonar / 10.0) blueIn.append(redLight) blueIn.append(blueLight) blueIn.append(bluexdistFromBase) blueIn.append(blueydistFromBase) blueIn.append(blueheading) blueIn.append(bluexdistFromOpponent) blueIn.append(blueydistFromOpponent) blueIn.append(blueopponentHeading) # print "blueIn:", blueIn blueOut = blueBrain.sactivate(blueIn) distFromBase = math.sqrt(xdistFromBase**2 + ydistFromBase**2) if redLight and distFromBase < 0.5: score += 24 accomplished = 1 break # took out ".robot" between redEng and motors, e.g. if redLight: redEng.motors(0.7 * redOut[0], 0.7 * redOut[1]) blueEng.motors(blueOut[0], blueOut[1]) elif blueLight: blueEng.motors(0.7 * blueOut[0], 0.7 * blueOut[1]) redEng.motors(redOut[0], redOut[1]) else: redEng.motors(redOut[0], redOut[1]) blueEng.motors(blueOut[0], blueOut[1]) if redCounter == 0 and blueCounter == 0 and not accomplished: xdistFromLight = redPosition[0] - 5 ydistFromLight = redPosition[1] - 5 distFromLight = math.sqrt(xdistFromLight**2 + ydistFromLight**2) score += 8 - distFromLight # fitness between 1 and 8 (approx) elif redCounter == 0 and not accomplished: distFromOpponent = math.sqrt(xdistFromOpponent**2 + ydistFromOpponent**2) score += 16 - distFromOpponent elif redCounter == 1 and redLight == 1 and not accomplished: distFromBase = math.sqrt(xdistFromBase**2 + ydistFromBase**2) score += 24 - distFromBase elif not accomplished: distFromOpponent = math.sqrt(xdistFromOpponent**2 + ydistFromOpponent**2) score += 20 - distFromOpponent blueEng.stop() redEng.stop() return score