custom data type optimization using the genetic algorithm -凯发k8网页登录
this example shows how to use the genetic algorithm to minimize a function using a custom data type. the genetic algorithm is customized to solve the traveling salesman problem.
traveling salesman problem
the traveling salesman problem is an optimization problem where there is a finite number of cities, and the cost of travel between each city is known. the goal is to find an ordered set of all the cities for the salesman to visit such that the cost is minimized. to solve the traveling salesman problem, we need a list of city locations and distances, or cost, between each of them.
our salesman is visiting cities in the united states. the file usborder.mat
contains a map of the united states in the variables x
and y
, and a geometrically simplified version of the same map in the variables xx
and yy
.
load('usborder.mat','x','y','xx','yy'); plot(x,y,'color','red'); hold on;
we will generate random locations of cities inside the border of the united states. we can use the inpolygon
function to make sure that all the cities are inside or very close to the us boundary.
cities = 40; locations = zeros(cities,2); n = 1; while (n <= cities) xp = rand*1.5; yp = rand; if inpolygon(xp,yp,xx,yy) locations(n,1) = xp; locations(n,2) = yp; n = n 1; end end plot(locations(:,1),locations(:,2),'bo');
blue circles represent the locations of the cities where the salesman needs to travel and deliver or pickup goods. given the list of city locations, we can calculate the distance matrix for all the cities.
distances = zeros(cities); for count1=1:cities, for count2=1:count1, x1 = locations(count1,1); y1 = locations(count1,2); x2 = locations(count2,1); y2 = locations(count2,2); distances(count1,count2)=sqrt((x1-x2)^2 (y1-y2)^2); distances(count2,count1)=distances(count1,count2); end; end;
customizing the genetic algorithm for a custom data type
by default, the genetic algorithm solver solves optimization problems based on double and binary string data types. the functions for creation, crossover, and mutation assume the population is a matrix of type double, or logical in the case of binary strings. the genetic algorithm solver can also work on optimization problems involving arbitrary data types. you can use any data structure you like for your population. for example, a custom data type can be specified using a matlab® cell array. in order to use ga
with a population of type cell array you must provide a creation function, a crossover function, and a mutation function that will work on your data type, e.g., a cell array.
required functions for the traveling salesman problem
this section shows how to create and register the three required functions. an individual in the population for the traveling salesman problem is an ordered set, and so the population can easily be represented using a cell array. the custom creation function for the traveling salesman problem will create a cell array, say p
, where each element represents an ordered set of cities as a permutation vector. that is, the salesman will travel in the order specified in p{i}
. the creation function will return a cell array of size populationsize
.
type create_permutations.m
function pop = create_permutations(nvars,fitnessfcn,options) %create_permutations creates a population of permutations. % pop = create_permutation(nvars,fitnessfcn,options) creates a population % of permutations pop each with a length of nvars. % % the arguments to the function are % nvars: number of variables % fitnessfcn: fitness function % options: options structure used by the ga % 凯发官网入口首页 copyright 2004-2007 the mathworks, inc. totalpopulationsize = sum(options.populationsize); n = nvars; pop = cell(totalpopulationsize,1); for i = 1:totalpopulationsize pop{i} = randperm(n); end
the custom crossover function takes a cell array, the population, and returns a cell array, the children that result from the crossover.
type crossover_permutation.m
function xoverkids = crossover_permutation(parents,options,nvars, ... fitnessfcn,thisscore,thispopulation) % crossover_permutation custom crossover function for traveling salesman. % xoverkids = crossover_permutation(parents,options,nvars, ... % fitnessfcn,thisscore,thispopulation) crossovers parents to produce % the children xoverkids. % % the arguments to the function are % parents: parents chosen by the selection function % options: options created from optimoptions % nvars: number of variables % fitnessfcn: fitness function % state: state structure used by the ga solver % thisscore: vector of scores of the current population % thispopulation: matrix of individuals in the current population % 凯发官网入口首页 copyright 2004-2015 the mathworks, inc. nkids = length(parents)/2; xoverkids = cell(nkids,1); % normally zeros(nkids,nvars); index = 1; for i=1:nkids % here is where the special knowledge that the population is a cell % array is used. normally, this would be thispopulation(parents(index),:); parent = thispopulation{parents(index)}; index = index 2; % flip a section of parent1. p1 = ceil((length(parent) -1) * rand); p2 = p1 ceil((length(parent) - p1- 1) * rand); child = parent; child(p1:p2) = fliplr(child(p1:p2)); xoverkids{i} = child; % normally, xoverkids(i,:); end
the custom mutation function takes an individual, which is an ordered set of cities, and returns a mutated ordered set.
type mutate_permutation.m
function mutationchildren = mutate_permutation(parents ,options,nvars, ... fitnessfcn, state, thisscore,thispopulation,mutationrate) % mutate_permutation custom mutation function for traveling salesman. % mutationchildren = mutate_permutation(parents,options,nvars, ... % fitnessfcn,state,thisscore,thispopulation,mutationrate) mutate the % parents to produce mutated children mutationchildren. % % the arguments to the function are % parents: parents chosen by the selection function % options: options created from optimoptions % nvars: number of variables % fitnessfcn: fitness function % state: state structure used by the ga solver % thisscore: vector of scores of the current population % thispopulation: matrix of individuals in the current population % mutationrate: rate of mutation % 凯发官网入口首页 copyright 2004-2015 the mathworks, inc. % here we swap two elements of the permutation mutationchildren = cell(length(parents),1);% normally zeros(length(parents),nvars); for i=1:length(parents) parent = thispopulation{parents(i)}; % normally thispopulation(parents(i),:) p = ceil(length(parent) * rand(1,2)); child = parent; child(p(1)) = parent(p(2)); child(p(2)) = parent(p(1)); mutationchildren{i} = child; % normally mutationchildren(i,:) end
we also need a fitness function for the traveling salesman problem. the fitness of an individual is the total distance traveled for an ordered set of cities. the fitness function also needs the distance matrix to calculate the total distance.
type traveling_salesman_fitness.m
function scores = traveling_salesman_fitness(x,distances) %traveling_salesman_fitness custom fitness function for tsp. % scores = traveling_salesman_fitness(x,distances) calculate the fitness % of an individual. the fitness is the total distance traveled for an % ordered set of cities in x. distance(a,b) is the distance from the city % a to the city b. % 凯发官网入口首页 copyright 2004-2007 the mathworks, inc. scores = zeros(size(x,1),1); for j = 1:size(x,1) % here is where the special knowledge that the population is a cell % array is used. normally, this would be pop(j,:); p = x{j}; f = distances(p(end),p(1)); for i = 2:length(p) f = f distances(p(i-1),p(i)); end scores(j) = f; end
ga
will call our fitness function with just one argument x
, but our fitness function has two arguments: x
, distances
. we can use an anonymous function to capture the values of the additional argument, the distances matrix. we create a function handle fitnessfcn
to an anonymous function that takes one input x
, but calls traveling_salesman_fitness
with x
, and distances. the variable, distances has a value when the function handle fitnessfcn
is created, so these values are captured by the anonymous function.
%distances defined earlier
fitnessfcn = @(x) traveling_salesman_fitness(x,distances);
we can add a custom plot function to plot the location of the cities and the current best route. a red circle represents a city and the blue lines represent a valid path between two cities.
type traveling_salesman_plot.m
function state = traveling_salesman_plot(options,state,flag,locations) % traveling_salesman_plot custom plot function for traveling salesman. % state = traveling_salesman_plot(options,state,flag,locations) plot city % locations and connecting route between them. this function is specific % to the traveling salesman problem. % 凯发官网入口首页 copyright 2004-2006 the mathworks, inc. persistent x y xx yy if strcmpi(flag,'init') load('usborder.mat','x','y','xx','yy'); end plot(x,y,'color','red'); axis([-0.1 1.5 -0.2 1.2]); hold on; [unused,i] = min(state.score); genotype = state.population{i}; plot(locations(:,1),locations(:,2),'bo'); plot(locations(genotype,1),locations(genotype,2)); hold off
once again we will use an anonymous function to create a function handle to an anonymous function which calls traveling_salesman_plot
with the additional argument locations
.
%locations defined earlier my_plot = @(options,state,flag) traveling_salesman_plot(options, ... state,flag,locations);
genetic algorithm options setup
first, we will create an options container to indicate a custom data type and the population range.
options = optimoptions(@ga, 'populationtype', 'custom','initialpopulationrange', ... [1;cities]);
we choose the custom creation, crossover, mutation, and plot functions that we have created, as well as setting some stopping conditions.
options = optimoptions(options,'creationfcn',@create_permutations, ... 'crossoverfcn',@crossover_permutation, ... 'mutationfcn',@mutate_permutation, ... 'plotfcn', my_plot, ... 'maxgenerations',500,'populationsize',60, ... 'maxstallgenerations',200,'usevectorized',true);
finally, we call the genetic algorithm with our problem information.
numberofvariables = cities;
[x,fval,reason,output] = ...
ga(fitnessfcn,numberofvariables,[],[],[],[],[],[],[],options)
optimization terminated: maximum number of generations exceeded. x = 1x1 cell array {[14 12 36 3 5 11 40 25 38 37 7 30 28 10 23 21 27 4 1 29 26 31 9 24 ... ]} fval = 5.3846 reason = 0 output = struct with fields: problemtype: 'unconstrained' rngstate: [1x1 struct] generations: 500 funccount: 28563 message: 'optimization terminated: maximum number of generations exceeded.' maxconstraint: [] hybridflag: []
the plot shows the location of the cities in blue circles as well as the path found by the genetic algorithm that the salesman will travel. the salesman can start at either end of the route and at the end, return to the starting city to get back home.