Guest User

Untitled

a guest
Feb 16th, 2013
906
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 14.76 KB | None | 0 0
  1. function [x,fval,exitFlag,output,population,scores] = ga(fun,nvars,Aineq,bineq,Aeq,beq,lb,ub,nonlcon,intcon,options)
  2. %GA    Constrained optimization using genetic algorithm.
  3. %   GA attempts to solve problems of the following forms:
  4. %       min F(X)  subject to:  A*X  <= B, Aeq*X  = Beq (linear constraints)
  5. %        X                     C(X) <= 0, Ceq(X) = 0 (nonlinear constraints)
  6. %                              LB <= X <= UB
  7. %                              X(i) integer, where i is in the index
  8. %                              vector INTCON (integer constraints)
  9. %
  10. %   Note: If INTCON is not empty, then no equality constraints are allowed.
  11. %   That is:-
  12. %   * Aeq and Beq must be empty
  13. %   * Ceq returned from NONLCON must be empty
  14. %
  15. %   X = GA(FITNESSFCN,NVARS) finds a local unconstrained minimum X to the
  16. %   FITNESSFCN using GA. NVARS is the dimension (number of design
  17. %   variables) of the FITNESSFCN. FITNESSFCN accepts a vector X of size
  18. %   1-by-NVARS, and returns a scalar evaluated at X.
  19. %
  20. %   X = GA(FITNESSFCN,NVARS,A,b) finds a local minimum X to the function
  21. %   FITNESSFCN, subject to the linear inequalities A*X <= B. Linear
  22. %   constraints are not satisfied when the PopulationType option is set to
  23. %   'bitString' or 'custom'. See the documentation for details.
  24. %
  25. %   X = GA(FITNESSFCN,NVARS,A,b,Aeq,beq) finds a local minimum X to the
  26. %   function FITNESSFCN, subject to the linear equalities Aeq*X = beq as
  27. %   well as A*X <= B. (Set A=[] and B=[] if no inequalities exist.) Linear
  28. %   constraints are not satisfied when the PopulationType option is set to
  29. %   'bitString' or 'custom'. See the documentation for details.
  30. %
  31. %   X = GA(FITNESSFCN,NVARS,A,b,Aeq,beq,lb,ub) defines a set of lower and
  32. %   upper bounds on the design variables, X, so that a solution is found in
  33. %   the range lb <= X <= ub. Use empty matrices for lb and ub if no bounds
  34. %   exist. Set lb(i) = -Inf if X(i) is unbounded below;  set ub(i) = Inf if
  35. %   X(i) is unbounded above. Linear constraints are not satisfied when the
  36. %   PopulationType option is set to 'bitString' or 'custom'. See the
  37. %   documentation for details.
  38. %
  39. %   X = GA(FITNESSFCN,NVARS,A,b,Aeq,beq,lb,ub,NONLCON) subjects the
  40. %   minimization to the constraints defined in NONLCON. The function
  41. %   NONLCON accepts X and returns the vectors C and Ceq, representing the
  42. %   nonlinear inequalities and equalities respectively. GA minimizes
  43. %   FITNESSFCN such that C(X)<=0 and Ceq(X)=0. (Set lb=[] and/or ub=[] if
  44. %   no bounds exist.) Nonlinear constraints are not satisfied when the
  45. %   PopulationType option is set to 'bitString' or 'custom'. See the
  46. %   documentation for details.
  47. %
  48. %   X = GA(FITNESSFCN,NVARS,A,b,Aeq,beq,lb,ub,NONLCON,options) minimizes
  49. %   with the default optimization parameters replaced by values in the
  50. %   structure OPTIONS. OPTIONS can be created with the GAOPTIMSET function.
  51. %   See GAOPTIMSET for details.
  52. %
  53. %   X = GA(FITNESSFCN,NVARS,A,b,[],[],lb,ub,NONLCON,INTCON) requires that
  54. %   the variables listed in INTCON take integer values. Note that GA does
  55. %   not solve problems with integer and equality constraints. Pass empty
  56. %   matrices for the Aeq and beq inputs if INTCON is not empty.
  57. %
  58. %   X = GA(FITNESSFCN,NVARS,A,b,[],[],lb,ub,NONLCON,INTCON,options)
  59. %   minimizes with integer constraints and the default optimization
  60. %   parameters replaced by values in the structure OPTIONS. OPTIONS can be
  61. %   created with the GAOPTIMSET function. See GAOPTIMSET for details.
  62. %
  63. %   X = GA(PROBLEM) finds the minimum for PROBLEM. PROBLEM is a structure
  64. %   that has the following fields:
  65. %       fitnessfcn: <Fitness function>
  66. %            nvars: <Number of design variables>
  67. %            Aineq: <A matrix for inequality constraints>
  68. %            bineq: <b vector for inequality constraints>
  69. %              Aeq: <Aeq matrix for equality constraints>
  70. %              beq: <beq vector for equality constraints>
  71. %               lb: <Lower bound on X>
  72. %               ub: <Upper bound on X>
  73. %          nonlcon: <Nonlinear constraint function>
  74. %           intcon: <Index vector for integer variables>
  75. %          options: <Options structure created with GAOPTIMSET>
  76. %         rngstate: <State of the random number generator>
  77. %
  78. %   [X,FVAL] = GA(FITNESSFCN, ...) returns FVAL, the value of the fitness
  79. %   function FITNESSFCN at the solution X.
  80. %
  81. %   [X,FVAL,EXITFLAG] = GA(FITNESSFCN, ...) returns EXITFLAG which
  82. %   describes the exit condition of GA. Possible values of EXITFLAG and the
  83. %   corresponding exit conditions are
  84. %
  85. %     1 Average change in value of the fitness function over
  86. %        options.StallGenLimit generations less than options.TolFun and
  87. %        constraint violation less than options.TolCon.
  88. %     3 The value of the fitness function did not change in
  89. %        options.StallGenLimit generations and constraint violation less
  90. %        than options.TolCon.
  91. %     4 Magnitude of step smaller than machine precision and constraint
  92. %        violation less than options.TolCon. This exit condition applies
  93. %        only to nonlinear constraints.
  94. %     5 Fitness limit reached and constraint violation less than
  95. %        options.TolCon.
  96. %     0 Maximum number of generations exceeded.
  97. %    -1 Optimization terminated by the output or plot function.
  98. %    -2 No feasible point found.
  99. %    -4 Stall time limit exceeded.
  100. %    -5 Time limit exceeded.
  101. %
  102. %   [X,FVAL,EXITFLAG,OUTPUT] = GA(FITNESSFCN, ...) returns a
  103. %   structure OUTPUT with the following information:
  104. %             rngstate: <State of the random number generator before GA started>
  105. %          generations: <Total generations, excluding HybridFcn iterations>
  106. %            funccount: <Total function evaluations>
  107. %        maxconstraint: <Maximum constraint violation>, if any
  108. %              message: <GA termination message>
  109. %
  110. %   [X,FVAL,EXITFLAG,OUTPUT,POPULATION] = GA(FITNESSFCN, ...) returns the
  111. %   final POPULATION at termination.
  112. %
  113. %   [X,FVAL,EXITFLAG,OUTPUT,POPULATION,SCORES] = GA(FITNESSFCN, ...) returns
  114. %   the SCORES of the final POPULATION.
  115. %
  116. %
  117. %   Example:
  118. %     Unconstrained minimization of 'rastriginsfcn' fitness function of
  119. %     numberOfVariables = 2
  120. %      x = ga(@rastriginsfcn,2)
  121. %
  122. %     Display plotting functions while GA minimizes
  123. %      options = gaoptimset('PlotFcns',...
  124. %        {@gaplotbestf,@gaplotbestindiv,@gaplotexpectation,@gaplotstopping});
  125. %      [x,fval,exitflag,output] = ga(@rastriginsfcn,2,[],[],[],[],[],[],[],options)
  126. %
  127. %   An example with inequality constraints and lower bounds
  128. %    A = [1 1; -1 2; 2 1];  b = [2; 2; 3];  lb = zeros(2,1);
  129. %    % Use mutation function which can handle constraints
  130. %    options = gaoptimset('MutationFcn',@mutationadaptfeasible);
  131. %    [x,fval,exitflag] = ga(@lincontest6,2,A,b,[],[],lb,[],[],options);
  132. %
  133. %     FITNESSFCN can also be an anonymous function:
  134. %        x = ga(@(x) 3*sin(x(1))+exp(x(2)),2)
  135. %
  136. %   If FITNESSFCN or NONLCON are parameterized, you can use anonymous
  137. %   functions to capture the problem-dependent parameters. Suppose you want
  138. %   to minimize the fitness given in the function myfit, subject to the
  139. %   nonlinear constraint myconstr, where these two functions are
  140. %   parameterized by their second argument a1 and a2, respectively. Here
  141. %   myfit and myconstr are MATLAB file functions such as
  142. %
  143. %        function f = myfit(x,a1)
  144. %        f = exp(x(1))*(4*x(1)^2 + 2*x(2)^2 + 4*x(1)*x(2) + 2*x(2) + a1);
  145. %
  146. %   and
  147. %
  148. %        function [c,ceq] = myconstr(x,a2)
  149. %        c = [1.5 + x(1)*x(2) - x(1) - x(2);
  150. %              -x(1)*x(2) - a2];
  151. %        % No nonlinear equality constraints:
  152. %         ceq = [];
  153. %
  154. %   To optimize for specific values of a1 and a2, first assign the values
  155. %   to these two parameters. Then create two one-argument anonymous
  156. %   functions that capture the values of a1 and a2, and call myfit and
  157. %   myconstr with two arguments. Finally, pass these anonymous functions to
  158. %   GA:
  159. %
  160. %     a1 = 1; a2 = 10; % define parameters first
  161. %     % Mutation function for constrained minimization
  162. %     options = gaoptimset('MutationFcn',@mutationadaptfeasible);
  163. %     x = ga(@(x)myfit(x,a1),2,[],[],[],[],[],[],@(x)myconstr(x,a2),options)
  164. %
  165. %   Example: Solving a mixed-integer optimization problem
  166. %   An example of optimizing a function where a subset of the variables are
  167. %   required to be integers:
  168. %  
  169. %   % Define the objective and call GA. Here variables x(2) and x(3) will
  170. %   % be integer.
  171. %   fun = @(x) (x(1) - 0.2)^2 + (x(2) - 1.7)^2 + (x(3) -5.1)^2;
  172. %   x = ga(fun,3,[],[],[],[],[],[],[],[2 3])
  173. %          
  174. %   See also GAOPTIMSET, FITNESSFUNCTION, GAOUTPUTFCNTEMPLATE, PATTERNSEARCH, @.
  175.  
  176. %   Copyright 2003-2011 The MathWorks, Inc.
  177. %   $Revision: 1.1.6.9 $  $Date: 2011/05/09 00:50:31 $
  178.  
  179. % If the first arg is not a gaoptimset, then it's a fitness function followed by a genome
  180. % length. Here we make a gaoptimset from the args.
  181. defaultopt = struct('PopulationType', 'doubleVector', ...
  182.     'PopInitRange', [0;1], ...
  183.     'PopulationSize', 20, ...
  184.     'EliteCount', 2, ...
  185.     'CrossoverFraction', 0.8, ...
  186.     'MigrationDirection','forward', ...
  187.     'MigrationInterval',20, ...
  188.     'MigrationFraction',0.2, ...
  189.     'Generations', 100, ...
  190.     'TimeLimit', inf, ...
  191.     'FitnessLimit', -inf, ...
  192.     'StallGenLimit', 50, ...
  193.     'StallTimeLimit', inf, ...
  194.     'TolFun', 1e-6, ...
  195.     'TolCon', 1e-6, ...
  196.     'InitialPopulation',[], ...
  197.     'InitialScores', [], ...
  198.     'InitialPenalty', 10, ...
  199.     'PenaltyFactor', 100, ...
  200.     'PlotInterval',1, ...
  201.     'CreationFcn',@gacreationuniform, ...
  202.     'FitnessScalingFcn', @fitscalingrank, ...
  203.     'SelectionFcn', @selectionstochunif, ...
  204.     'CrossoverFcn',@crossoverscattered, ...
  205.     'MutationFcn',{{@mutationgaussian 1  1}}, ...
  206.     'HybridFcn',[], ...
  207.     'Display', 'final', ...
  208.     'PlotFcns', [], ...
  209.     'OutputFcns', [], ...
  210.     'Vectorized','off', ...
  211.     'UseParallel', 'never');
  212.  
  213. % Check number of input arguments
  214. errmsg = nargchk(1,11,nargin);
  215. if ~isempty(errmsg)
  216.     error(message('globaloptim:ga:numberOfInputs', errmsg));
  217. end
  218.  
  219. % If just 'defaults' passed in, return the default options in X
  220. if nargin == 1 && nargout <= 1 && isequal(fun,'defaults')
  221.     x = defaultopt;
  222.     return
  223. end
  224.  
  225. if nargin < 11, options = [];
  226.     if nargin < 10,  intcon = [];
  227.         if nargin < 9,  nonlcon = [];
  228.             if nargin < 8, ub = [];
  229.                 if nargin < 7, lb = [];
  230.                     if nargin <6, beq = [];
  231.                         if nargin <5, Aeq = [];
  232.                             if nargin < 4, bineq = [];
  233.                                 if nargin < 3, Aineq = [];
  234.                                 end
  235.                             end
  236.                         end
  237.                     end
  238.                 end
  239.             end
  240.         end
  241.     end
  242. end
  243.  
  244. % Is third argument a structure
  245. if nargin == 3 && isstruct(Aineq) % Old syntax
  246.     options = Aineq; Aineq = [];
  247. end
  248.  
  249. % Is tenth argument a structure? If so, integer constraints have not been
  250. % specified
  251. if nargin == 10 && isstruct(intcon)
  252.     options = intcon;
  253.     intcon = [];
  254. end
  255.  
  256. % One input argument is for problem structure
  257. if nargin == 1
  258.     if isa(fun,'struct')
  259.         [fun,nvars,Aineq,bineq,Aeq,beq,lb,ub,nonlcon,intcon,rngstate,options] = separateOptimStruct(fun);
  260.         % Reset the random number generators
  261.         resetDfltRng(rngstate);
  262.     else % Single input and non-structure.
  263.         error(message('globaloptim:ga:invalidStructInput'));
  264.     end
  265. end
  266.  
  267. % If fun is a cell array with additional arguments get the function handle
  268. if iscell(fun)
  269.     FitnessFcn = fun{1};
  270. else
  271.     FitnessFcn = fun;
  272. end
  273.  
  274. % Only function handles or inlines are allowed for FitnessFcn
  275. if isempty(FitnessFcn) ||  ~(isa(FitnessFcn,'inline') || isa(FitnessFcn,'function_handle'))
  276.     error(message('globaloptim:ga:needFunctionHandle'));
  277. end
  278.  
  279. % We need to check the nvars here before we call any solver
  280. valid =  isnumeric(nvars) && isscalar(nvars)&& (nvars > 0) ...
  281.     && (nvars == floor(nvars));
  282. if ~valid
  283.     error(message('globaloptim:ga:notValidNvars'));
  284. end
  285.  
  286. % Specific checks and modification of options for mixed integer GA
  287. if ~isempty(intcon)  
  288.     % Check whether the user has specified options that the mixed integer
  289.     % solver will either ignore or error.
  290.     gaminlpvalidateoptions(options);    
  291.     % If a user doesn't specify PopInitRange, we want to set it to the
  292.     % bounds when we create the initial population. Need to store a flag
  293.     % that indicates whether the user has specified PopInitRange so we can
  294.     % do this in the creation function.
  295.     UserSpecPopInitRange = isa(options, 'struct') && ...
  296.         isfield(options, 'PopInitRange') && ~isempty(options.PopInitRange);
  297.     % Change the default options for PopulationSize and EliteCount here.
  298.     defaultopt.PopulationSize = max(min(10*nvars, 100), 40);
  299.     defaultopt.EliteCount = floor(0.05*defaultopt.PopulationSize);
  300. end
  301.  
  302. user_options = options;
  303. % Use default options if empty
  304. if ~isempty(options) && ~isa(options,'struct')
  305.         error(message('globaloptim:ga:optionsNotAStruct'));
  306. elseif isempty(options)
  307.     options = defaultopt;
  308. end
  309. % Take defaults for parameters that are not in options structure
  310. options = gaoptimset(defaultopt,options);
  311.  
  312. % All inputs should be double
  313. try
  314.     dataType = superiorfloat(nvars,Aineq,bineq,Aeq,beq,lb,ub);
  315.     if ~isequal('double', dataType)
  316.         error(message('globaloptim:ga:dataType'))
  317.     end
  318. catch
  319.     error(message('globaloptim:ga:dataType'))
  320. end
  321.  
  322. [x,fval,exitFlag,output,population,scores,FitnessFcn,nvars,Aineq,bineq,Aeq,beq,lb,ub, ...
  323.     NonconFcn,options,Iterate,type] = gacommon(nvars,fun,Aineq,bineq,Aeq,beq,lb,ub,nonlcon,intcon,options,user_options);
  324.  
  325. if exitFlag < 0
  326.     return;
  327. end
  328.  
  329. % Turn constraints into right size if they are empty.
  330. if isempty(Aineq)
  331.     Aineq = zeros(0,nvars);
  332. end
  333. if isempty(bineq)
  334.     bineq = zeros(0,1);
  335. end
  336. if isempty(Aeq)
  337.     Aeq = zeros(0,nvars);
  338. end
  339. if isempty(beq)
  340.     beq = zeros(0,1);
  341. end
  342.  
  343. % Call appropriate single objective optimization solver
  344. if ~isempty(intcon)  
  345.     [x,fval,exitFlag,output,population,scores] = gaminlp(FitnessFcn,nvars, ...
  346.         Aineq,bineq,Aeq,beq,lb,ub,NonconFcn,intcon,options,output,Iterate,...
  347.         UserSpecPopInitRange);
  348. else    
  349.     switch (output.problemtype)
  350.         case 'unconstrained'
  351.             [x,fval,exitFlag,output,population,scores] = gaunc(FitnessFcn,nvars, ...
  352.                 options,output,Iterate);
  353.         case {'boundconstraints', 'linearconstraints'}
  354.             [x,fval,exitFlag,output,population,scores] = galincon(FitnessFcn,nvars, ...
  355.                 Aineq,bineq,Aeq,beq,lb,ub,options,output,Iterate);
  356.         case 'nonlinearconstr'
  357.             [x,fval,exitFlag,output,population,scores] = gacon(FitnessFcn,nvars, ...
  358.                 Aineq,bineq,Aeq,beq,lb,ub,NonconFcn,options,output,Iterate,type);
  359.     end
  360. end
Advertisement
Add Comment
Please, Sign In to add comment