I’m playing with Matlab’s Global Optimization Toolbox and learning about genetic algorithms. My goal is to implement an algorithm that can navigate in 2D space, searching for the shortest path from a start point to an end point while avoiding simple, static obstacles along the way.
start_point = [65, 275];
end_point = [510, 210];
num_points = 4; % How many intermediate points between start and finish
% Dimensions of the 2D space
x_min = 0;
x_max = 600;
y_min = 0;
y_max = 600;
% The obstacle is a polygon with given vertices
obstacle_x = [30, 100, 170, 220, 195, 130, 130, 100];
obstacle_y = [215, 170, 210, 260, 330, 340, 280, 230];
% Constraints
lb = repmat([x_min, y_min], num_points, 1);
ub = repmat([x_max, y_max], num_points, 1);
options = optimoptions('ga', ...
'PopulationSize', 100, ...
'MaxGenerations', 150, ...
'Display', 'final', ...
'UseParallel', true);
objective_function = @(points) objective(points, start_point, end_point, obstacle_x, obstacle_y);
[best_points, fval] = ga(objective_function, num_points * 2, [], [], [], [], lb, ub, @constraints, options);
% Draw everything on a graph
full_path = [start_point; reshape(best_points, num_points, 2); end_point];
figure;
plot(full_path(:, 1), full_path(:, 2), '-o', 'LineWidth', 2);
xlabel('X');
ylabel('Y');
title('Shortest path around obstacle');
grid on;
hold on;
scatter(start_point(1), start_point(2), 100, 'g', 'filled');
scatter(end_point(1), end_point(2), 100, 'r', 'filled');
fill(obstacle_x, obstacle_y, [0.7, 0.7, 0.7], 'EdgeColor', 'k');
legend('Path', 'Start', 'End', 'Obstacle', 'Location', 'Best');
hold off;
% Objective function
function d = objective(points, start_point, end_point, obstacle_x, obstacle_y)
full_points = [start_point; reshape(points, [], 2); end_point];
d = sum(sqrt(sum(diff(full_points).^2, 2)));
% Penalize touching obstacle
[in_poly, ~] = inpolygon(full_points(:, 1), full_points(:, 2), obstacle_x, obstacle_y);
if any(in_poly)
d = d + 10000 * sum(in_poly);
end
end
function [c, ceq] = constraints(points)
c = [];
ceq = [];
end```
My problem is that when I run this code the algorithm seems to ignore my obstacle, going in a straight line towards the end point.
The issue remains consistent when I run the algorithm with different population sizes and max generation constraints