def determine_fitness(self, population_size): ''' Determine Fitness Returns a fitness value for each clone by determining performance in simulation. Fitness is evaluated primarily based on race performance (time, distance), but undesireable behaviors such as letting the battery voltage stay too low will be punished with a decrease in fitness value. ''' self.environment = para.environment # **temporary replacement for environment** self.performances = [] self.distances = [] # runs each clone through simulation to determine its fitness for n in range(population_size): # export clone's network parameters and environment to set up a race competition = race.Race(self.clones[n], self.environment) # runs through a race allowing clone network to determine strategy competition.race() # aborts evolution proccess if a fatal error occurs self.abort_evolution = competition.abort # evaluate performance performance = competition.argo.position**2 / competition.argo.race_time / para.environment[ 0] self.performances.append(performance) print('average performance: ', np.sum(self.performances) / population_size)
def main(): # STEP 1: print('Starting Race') data = scrape_data.log_data(1, progress_keys()) race_stats = race.Race(len(data)) musher_objects = [] for musher in data: musher_objects.append(mushers.Mushers(musher)) update_insert_sql.start_race(musher_objects) # STEPS 2-6: # list of the logs we'll be using in the sim log_nums = sim_log_nums() print('Working log #1: 1 of %s' % (len(log_nums)+1)) sleep(5*60) for log in log_nums[1:]: print('Working log #%s: %s of %s' % (log, (log_nums.index(log) +1), (len(log_nums) +1))) # STEP 2: updated_list = scrape_data.log_data(log, progress_keys()) musher_list = [] # STEP #3: for musher in updated_list: new_musher = mushers.Mushers(musher) race_stats.add_checkpoints(musher['Checkpoint']) new_musher.tally_points(musher, race_stats.get_num_mushers(), race_stats.get_dog_checks(), race_stats.reached_Nome()) musher_list.append(new_musher) # STEP 4: update_insert_sql.update_race(musher_list) # STEP 5: sleep(5*60) print('Race Finished')
import race import turn import ship import fabrication # gal = galaxy.Galaxy() galaxy.gal.init_gen() game_exit = 0 while game_exit != 1 : galaxy.gal.galaxy2html("graph") action = input("input command: ") if action == "makeciv": race.Race(galaxy.gal) elif action == "turn" or action == "t": turn.gala_time.time_turn() elif action == "cheatship": has_ai = input("0 if no ai, anything else if it is: ") sys = None for system in galaxy.gal.systems: if system.planets: for planet in system.planets: if planet.owner != None: sys = system break if sys is None: continue new_ship = ship.Ship(sys) if not has_ai:
def main(): '''Assumes the Iditarod has started, and updates the table''' # get the available logs original_logs = get_all_logs() # if logs are empty, try again in 5 while not original_logs: original_logs = get_all_logs() sleep(5 * 60) # ---------------------------------------------------------------------------------------- # RACE HAS BEGUN BABY # ---------------------------------------------------------------------------------------- # give a time out to the while loop timeout = 24 * 60 * 60 data = scrape_data.log_data(1, progress_keys()) race_stats = race.Race(len(data)) musher_objects = [] for musher in data: musher_objects.append(mushers.Mushers(musher)) update_insert_sql.start_race(musher_objects) # STEPS 2-6: # list of the logs we'll be using in the sim new_logs = get_all_logs() print('Working log #1') sleep(5 * 60) lindex = 0 while original_logs != new_logs or timeout: # log log = new_logs[lindex] if original_logs == new_logs: timeout -= 5 * 60 sleep(5 * 60) # skip already used logs elif log in original_logs: lindex += 1 continue else: # reset timeout timeout = 24 * 60 * 60 print('Working log #%s' % log) # STEP 2: updated_list = scrape_data.log_data(log, progress_keys()) race_stats.add_checkpoints(updated_list[0]['Checkpoint']) musher_list = [] # STEP #3: for musher in updated_list: new_musher = mushers.Mushers(musher) new_musher.tally_points(musher, race_stats.get_num_mushers(), race_stats.get_dog_checks(), race_stats.reached_Nome()) musher_list.append(new_musher) # STEP 4: update_insert_sql.update_race(musher_list) # STEP 5: sleep(5 * 60) # add used log to original original_logs.append(log) # add any new logs to the new_log list added_logs = get_all_logs() for l in added_logs: if l not in new_logs: new_logs.append(l) lindex += 1 # wait three weeks before deleting the table sleep(60 * 60 * 24 * 7 * 3) update_insert_sql.clear_table()
async def restart(ctx): if ctx.channel.id in races: await ctx.send(msg.MSG_RE_START) else: await ctx.send(msg.MSG_RACE_CREATE) races[ctx.channel.id] = race.Race(ctx.channel.id)
async def start(ctx): if ctx.channel.id not in races: await ctx.send(msg.MSG_RACE_CREATE) races[ctx.channel.id] = race.Race(ctx.channel.id) else: await ctx.send(msg.MSG_CONF_EXIST)
def reproduce(self, selection_bias, inheritance_rate, population_size, generation): ''' Reproduce - creates a child network based on clone performance A new mutation equal to the weighted average of ckone mutations is applied to the original network. Weights are proportional to (clone performance[i] - average clone performance)^selection_bias Inheritance rate scales how big the new mutation is. ''' # Create list of weights mean_performance = np.sum(self.performances) / population_size weights = [(((performance - mean_performance)) / mean_performance)** selection_bias * inheritance_rate for performance in self.performances] # Initialize child network child_net = self.parameters[:] # Loop through the numpy arrays that make up the parameters for parameter_type in [0, 1]: # No 2 index to preserve self.sizes for index in range(len(self.sizes) - 1): # Initialize np array from 1st clone **required to sum** parameter_deltas = (self.mutations[0][parameter_type][index] * weights[0] * inheritance_rate) # Add weighted np arrays from rest of clones, for clone in range(1, population_size): parameter_deltas = ( parameter_deltas + self.mutations[clone][parameter_type][index] * weights[clone] * inheritance_rate) # Normalize by population size and update child_net parameter_deltas = parameter_deltas / float(population_size) child_net[parameter_type][index] = (child_net[parameter_type]\ [index] + parameter_deltas) # Determine and display performance of child network competition = race.Race(child_net, self.environment) if generation % 200 == True: competition.race(True) print("show graph") plt.figure(1, figsize=(30, 50)) plt.subplot(611) np_battery_tracker = np.array( competition.battery_tracker) / para.battery_max_charge plt.title("battery") plt.plot(np_battery_tracker) plt.subplot(612) plt.title("distance") plt.plot(competition.distance_tracker) plt.subplot(613) plt.title("velocity") plt.plot(competition.velocity_tracker) plt.subplot(614) plt.title("irradiance") plt.plot(competition.irradiance_tracker) plt.subplot(615) #plt.title("rolling loss") #plt.plot(competition.rolling_loss_tracker) #plt.subplot(616) #plt.title("aero loss") #plt.plot(competition.aero_loss_tracker) plt.savefig("graphs.png") else: competition.race() print( 'new gen: ', competition.argo.position**2 / competition.argo.race_time / para.environment[0])
vector.sub(vector.sub(dir, stop), self.velocity)) return vector.normalize(vector.sub(dir, stop)) class TweakedAI(race.BaseAI): def __init__(self, scale: float = 1.0): super().__init__() self.color = (40 * scale, 0, 255) self.scale = scale def evaluate(self, goal, goal2): dir = vector.normalize(vector.from_to(self.position, goal)) stop = vector.normalize(self.velocity) stop = vector.mult(stop, vector.dot(stop, dir) * self.scale) return vector.normalize(vector.sub(dir, stop)) def __repr__(self): return "TweakedAI (%.1f)" % self.scale if __name__ == "__main__": r = race.Race(time=40) r.add_racer(EasyAI()) r.add_racer(DragAI(1)) r.add_racer(DragAI(2)) r.add_racer(PerpAI()) r.add_racer(CombinedAI()) r.add_racer(StoppingAI()) r.add_racer(TweakedAI(1)) r.start_pygame_race()