def calculate_fitness(self, individuals): fitness = [] for individual in individuals: track = generate_track(chromosome_elements=individual) s = np.array([track[0].x, track[0].y]) e = np.array([track[-1].x, track[-1].y]) fitness.append(1 / np.linalg.norm(s - e)) return fitness
def fitness( chromosome_elements: List[ChromosomeElem], penalty_coefs: Tuple[float, float], ) -> float: # generate track points track_points = generate_track(chromosome_elements=chromosome_elements) # calculate distance between start and end points start_point = TrackPoint(track_points[0].x, track_points[0].y - 2) end_point = track_points[-1] disp = math.sqrt((start_point.x - end_point.x)**2 + (start_point.y - end_point.y)**2) # find all vertices of the track vertices = track_vertices(track_points=[end_point] + track_points, chromosome_elements=chromosome_elements) # calculate number of line-segment intersections num_intersects = 0 for i in range(len(vertices) - 2): for j in range(i + 1, len(vertices) - 1): p1, p2 = vertices[i], vertices[i + 1] p3, p4 = vertices[j], vertices[j + 1] x1, x2, x3, x4 = p1.x, p2.x, p3.x, p4.x y1, y2, y3, y4 = p1.y, p2.y, p3.y, p4.y # check if segments intersect denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if denom != 0: t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denom if 0 < t <= 1: u = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom if 0 < u <= 1: num_intersects += 1 # calculate difference in vehicle direction at start and end points angle = math.atan2(end_point.y - track_points[-2].y, end_point.x - track_points[-2].x) if angle <= -math.pi / 2: angle += 2 * math.pi diff_direction = abs(math.pi / 2 - angle) # combine results return disp + penalty_coefs[0] * num_intersects + penalty_coefs[ 1] * diff_direction
from ga.chromosome_elem import ChromosomeElem from track_generator.command import Command from track_generator.generator import generate_track import matplotlib.pyplot as plt if __name__ == '__main__': chromosome_elements = [ ChromosomeElem(command=Command.S, value=11), ChromosomeElem(command=Command.DY, value=15.5), ChromosomeElem(command=Command.R, value=9), ChromosomeElem(command=Command.S, value=10) ] track_points = generate_track(chromosome_elements=chromosome_elements) plot_x = [track_point.x for track_point in track_points] plot_y = [track_point.y for track_point in track_points] plt.scatter(plot_x, plot_y) plt.show()