def save(self, ind: BeamNGIndividual, prefix: str = None): if not prefix: prefix = ind.name self.folder.mkdir(parents=True, exist_ok=True) ind_path = self.folder.joinpath(prefix + '.json') ind_path.write_text(json.dumps(ind.to_dict())) m1 , m2 = ind.get_members() # fig, (left, right) = plt.subplots(ncols=2) # fig.set_size_inches(15, 10) # ml, mr = ind.members_by_distance_to_boundary() # def plot(member: BeamNGMember, ax): # ax.set_title(f'dist to bound ~ {np.round(member.distance_to_boundary, 2)}', fontsize=12) # road_points = RoadPoints.from_nodes(member.sample_nodes) # road_points.plot_on_ax(ax) # # plot(ml, left) # plot(mr, right) # fig.suptitle(f'members distance = {ind.members_distance} ; oob_ff = {ind.oob_ff}') # fig.savefig(self.folder.joinpath(prefix + '_both_roads.svg')) # plt.close(fig) sim_path1 = self.folder.joinpath(prefix + '_1_simulation.json') sim_path2 = self.folder.joinpath(prefix + '_2_simulation.json') if m1.simulation != None: with open(sim_path1, 'w') as f: f.write(json.dumps({ m1.simulation.f_params: m1.simulation.params._asdict(), m1.simulation.f_info: m1.simulation.info.__dict__, m1.simulation.f_road: m1.simulation.road.to_dict(), m1.simulation.f_records: [r._asdict() for r in m1.simulation.states] })) if m2.simulation != None: with open(sim_path2, 'w') as f: f.write(json.dumps({ m2.simulation.f_params: m2.simulation.params._asdict(), m2.simulation.f_info: m2.simulation.info.__dict__, m2.simulation.f_road: m2.simulation.road.to_dict(), m2.simulation.f_records: [r._asdict() for r in m2.simulation.states] }))
def mutation(self, x, seed): """ Mutate the solution x """ # "apply mutation" road = x.m.clone() y: BeamNGIndividual = BeamNGIndividual(road, self.config) y.seed = seed y.mutate() return y
def save(self, ind: BeamNGIndividual, prefix: str = None): if not prefix: prefix = ind.name self.folder.mkdir(parents=True, exist_ok=True) ind_path = self.folder.joinpath(prefix + '.json') ind_path.write_text(json.dumps(ind.to_dict())) fig, (left, right) = plt.subplots(ncols=2) fig.set_size_inches(15, 10) ml, mr = ind.members_by_distance_to_boundary() def plot(member: BeamNGMember, ax): ax.set_title(f'dist to bound ~ {np.round(member.distance_to_boundary, 2)}', fontsize=12) road_points = RoadPoints.from_nodes(member.sample_nodes) road_points.plot_on_ax(ax) plot(ml, left) plot(mr, right) fig.suptitle(f'members distance = {ind.members_distance} ; oob_ff = {ind.oob_ff}') fig.savefig(self.folder.joinpath(prefix + '_both_roads.svg')) plt.close(fig)
def generate_random_solution(self): """ To ease the bootstrap of the algorithm, we can generate the first solutions in the feature space, so that we start filling the bins """ # "Generate random solution" seed = self.problem._seed_pool_strategy.get_seed() road = seed.clone().mutate() road.config = self.config individual: BeamNGIndividual = BeamNGIndividual(road, self.config) individual.seed = seed return individual
def save(self, ind: BeamNGIndividual, prefix=None): if not prefix: prefix = ind.name self.folder.mkdir(parents=True, exist_ok=True) def save_road_img(member: BeamNGMember, name): filepath = self.folder.joinpath(name) # BeamNGRoadImagery.from_sample_nodes(member.sample_nodes).save(filepath.with_suffix('.jpg')) BeamNGRoadImagery.from_sample_nodes(member.sample_nodes).save(filepath.with_suffix('.svg')) ind_path = self.folder.joinpath(prefix + '.json') ind_path.write_text(json.dumps(ind.to_dict())) save_road_img(ind.m1, ind.name + '_m1_road') save_road_img(ind.m2, ind.name + '_m2_road')
def deap_evaluate_individual(self, individual: BeamNGIndividual): return individual.evaluate()
def load(self, prefix: str) -> BeamNGIndividual: ind_path = self.folder.joinpath(prefix + '.json') ind = BeamNGIndividual.from_dict(json.loads(ind_path.read_text())) return ind
def initial_population_generator(path, config, problem): all_roads = [ filename for filename in glob.glob(str(path) + "\*.json", recursive=True) ] type = config.Feature_Combination shuffle(all_roads) roads = all_roads original_set = list() individuals = [] popsize = config.POPSIZE for road in roads: with open(road) as json_file: data = json.load(json_file) sample_nodes = data["road"]["nodes"] for node in sample_nodes: node[2] = -28.0 sample_nodes = np.array(sample_nodes) records = data["records"] bbox_size = (-250.0, 0.0, 250.0, 500.0) road_bbox = RoadBoundingBox(bbox_size) member = BeamNGMember(data["control_nodes"], [tuple(t) for t in sample_nodes], 20, road_bbox) member.config = config member.problem = problem simulation_id = time.strftime('%Y-%m-%d--%H-%M-%S', time.localtime()) sim_name = member.config.simulation_name.replace( '$(id)', simulation_id) simulation_data = SimulationData(sim_name) states = [] for record in records: state = VehicleState(timer=record["timer"], pos=record["pos"], dir=record["dir"], vel=record["vel"], steering=record["steering"], steering_input=record["steering_input"], brake=record["brake"], brake_input=record["brake_input"], throttle=record["throttle"], throttle_input=record["throttle_input"], wheelspeed=record["wheelspeed"], vel_kmh=record["vel_kmh"]) sim_data_record = SimulationDataRecord( **state._asdict(), is_oob=record["is_oob"], oob_counter=record["oob_counter"], max_oob_percentage=record["max_oob_percentage"], oob_distance=record["oob_distance"]) states.append(sim_data_record) simulation_data.params = SimulationParams( beamng_steps=data["params"]["beamng_steps"], delay_msec=int(data["params"]["delay_msec"])) simulation_data.road = DecalRoad.from_dict(data["road"]) simulation_data.info = SimulationInfo() simulation_data.info.start_time = data["info"]["start_time"] simulation_data.info.end_time = data["info"]["end_time"] simulation_data.info.elapsed_time = data["info"]["elapsed_time"] simulation_data.info.success = data["info"]["success"] simulation_data.info.computer_name = data["info"]["computer_name"] simulation_data.info.id = data["info"]["id"] simulation_data.states = states if len(states) > 0: member.distance_to_boundary = simulation_data.min_oob_distance() member.simulation = simulation_data individual: BeamNGIndividual = BeamNGIndividual(member, config) #individual.evaluate() b = tuple() feature_dimensions = generate_feature_dimension(type) for ft in feature_dimensions: i = feature_simulator(ft.feature_simulator, individual) b = b + (i, ) individuals.append([b, road, individual]) starting_point = choice(individuals) original_set.append(starting_point) i = 0 best_ind = individuals[0] while i < popsize - 1: max_dist = 0 for ind in individuals: dist = get_min_distance_from_set(ind, original_set) if dist > max_dist: max_dist = dist best_ind = ind original_set.append(best_ind) i += 1 base = config.initial_population_folder storage = SeedStorage(base) for index, road in enumerate(original_set): dst = storage.get_path_by_index(index + 1) ind = road[2] #copy(road[1], dst) with open(road[1]) as ff: json_file = json.load(ff) with open(dst, 'w') as f: f.write( json.dumps({ "control_nodes": json_file["control_nodes"], ind.m.simulation.f_params: ind.m.simulation.params._asdict(), ind.m.simulation.f_info: ind.m.simulation.info.__dict__, ind.m.simulation.f_road: ind.m.simulation.road.to_dict(), ind.m.simulation.f_records: [r._asdict() for r in ind.m.simulation.states] }))
def generate_random_solution_without_sim(self): """ To ease the bootstrap of the algorithm, we can generate the first solutions in the feature space, so that we start filling the bins """ # "Generate random solution" path = self.problem._seed_pool_strategy.get_seed() with open(path) as json_file: data = json.load(json_file) sample_nodes = data["road"]["nodes"] for node in sample_nodes: node[2] = -28.0 sample_nodes = np.array(sample_nodes) records = data["records"] bbox_size = (-250.0, 0.0, 250.0, 500.0) road_bbox = RoadBoundingBox(bbox_size) member = BeamNGMember(data["control_nodes"], [tuple(t) for t in sample_nodes], len(data["control_nodes"]), road_bbox) member.config = self.config member.problem = self.problem simulation_id = time.strftime('%Y-%m-%d--%H-%M-%S', time.localtime()) sim_name = member.config.simulation_name.replace( '$(id)', simulation_id) simulation_data = SimulationData(sim_name) states = [] for record in records: state = VehicleState(timer=record["timer"], pos=record["pos"], dir=record["dir"], vel=record["vel"], steering=record["steering"], steering_input=record["steering_input"], brake=record["brake"], brake_input=record["brake_input"], throttle=record["throttle"], throttle_input=record["throttle_input"], wheelspeed=record["wheelspeed"], vel_kmh=record["vel_kmh"]) sim_data_record = SimulationDataRecord( **state._asdict(), is_oob=record["is_oob"], oob_counter=record["oob_counter"], max_oob_percentage=record["max_oob_percentage"], oob_distance=record["oob_distance"]) states.append(sim_data_record) simulation_data.params = SimulationParams( beamng_steps=data["params"]["beamng_steps"], delay_msec=int(data["params"]["delay_msec"])) simulation_data.road = DecalRoad.from_dict(data["road"]) simulation_data.info = SimulationInfo() simulation_data.info.start_time = data["info"]["start_time"] simulation_data.info.end_time = data["info"]["end_time"] simulation_data.info.elapsed_time = data["info"]["elapsed_time"] simulation_data.info.success = data["info"]["success"] simulation_data.info.computer_name = data["info"]["computer_name"] simulation_data.info.id = data["info"]["id"] simulation_data.states = states if len(states) > 0: member.distance_to_boundary = simulation_data.min_oob_distance() member.simulation = simulation_data individual: BeamNGIndividual = BeamNGIndividual( member, self.config) individual.seed = path else: print("*********Bug************") return individual