QQ登录

只需要一步,快速开始

 注册地址  找回密码
查看: 7544|回复: 2
打印 上一主题 下一主题

粒子群算法PSO源代码 MATLAB

[复制链接]

522

主题

10

听众

4072

积分

自我介绍
学习中!

优秀斑竹奖 元老勋章 新人进步奖 最具活力勋章

群组Matlab讨论组

群组C 语言讨论组

群组每天多学一点点

群组数学趣味、游戏、IQ等

群组南京邮电大学数模协会

跳转到指定楼层
1#
发表于 2010-6-18 12:39 |只看该作者 |倒序浏览
  1. function [x, fval, exitflag, output] = pso(objfunc, nvars, options)
  2. % PSO   Particle Swarm Optimization Algorithm
  3. %
  4. % PSO attempts to solve continuous optimization problem of the form
  5. %
  6. %       min OBJFUNC(X)
  7. %        X
  8. %
  9. % No constraints on the values of entries of X can be imposed, not ewen box contraints in form of
  10. % the lower and upper bound. Any desired constraints should be dealth with by modification of the
  11. % objective function: by introduction of penalty functions, by reformulation of the problem, or some
  12. % other way.
  13. %
  14. % In the present implementation, only classical 'star topology' PSO is considered, where each
  15. % particle is interconnected with each other particle, and there are no subswarms. Also, no
  16. % additional, GA like, operators are applied to the particles during the search.
  17. %
  18. %   PSO(OBJFUNC, NVARS) Optimizes objective OBJFUNC defined as a real-valued function of a single,
  19. %   real-valued vector argument. Dimensionality of the search space, that is the number of entries
  20. %   in the argument of OBJFUNC, is defined in NVARS. PSO expects at least these two arguments.
  21. %   Failure to provide any of them will result in error.
  22. %
  23. %   PSO(OBJFUNC, NVARS, OPTIONS) Enables the user to specify a number of settings in order to
  24. %   customize or fine-tune the performance of the algorithm. OPTIONS is a structure containing
  25. %   desired values of these settings. Detailed description of available parameters is given in the
  26. %   sequel.
  27. %
  28. %   X = PSO(...) Returns vector at which objective attains its minimal value. Due to the nature of
  29. %   PSO algorithm, this is not guaranteed to be neither exact global nor local optimum, yet PSO is
  30. %   robust optimizer, well suited for complex, multimodal problems. Well tuned, it can give VERY
  31. %   GOOD and quite commonly EXCELENT solution to the problem at hand. In most cases, this is all
  32. %   that is needed.
  33. %
  34. %   [X, FVAL] = PSO(...) In addition to the optimal X, it returns the value of the objective at X,
  35. %   FVAL = OBJFUNC(X).
  36. %
  37. %   [X, FVAL, EXITFLAG] = PSO(...) Returns indication concerning a reason why the algorithm stopped.
  38. %   In the current implementation the only supported return values are 0 and 1. EXITFLAG 0 denotes
  39. %   that maximum number of iterations has been achieved, while EXITFLAG 1 is used in testing mode,
  40. %   if the value of global minimum has been found prior to achieving the maximal number of
  41. %   iteration.
  42. %
  43. %   [X, FVAL, EXITFLAG, OUTPUT] = PSO(...) Returns OUTPUT structure containing valuable information
  44. %   concerning performance of the algorithm in the present run. The exact members of this structure
  45. %   are variable, and depend on the settings specified in the OPTIONS structure. In general, there
  46. %   are four levels of detail that can be specified. The 'LOW' detail level means that the algorithm
  47. %   keeps track of objective value for the best, the mean and the worst particle in the swarm in
  48. %   each generation. If the 'MEDIUM' level is specified, exact position and index of the global best
  49. %   particle are tracked for during each iteration. If the 'HIGH' level is specified, exact position
  50. %   of each particle in the swarm is logged during the entire search process. If the swarm is large
  51. %   and the number of generations is great, high level output logging can result in considerable
  52. %   memmory consumption. Finally, the output log level can be set to 'NONE', meaning that no data is
  53. %   wanted within the OUTPUT structure. The exact way for specifying output logging level is given
  54. %   below.
  55. %
  56. %   OPTIONS = PSO('options') Returns default options structure. Usefull when one desires to change
  57. %   values of only a handfull of options.
  58. %
  59. %   The OPTIONS structure contains the following entries
  60. %
  61. %     options.npart           The number of particles in the swarm.
  62. %     options.niter           The maximal number of iterations.
  63. %     options.cbi             Initial value of the individual-best acceleration factor.
  64. %     options.cbf             Final value of the individual-best acceleration factor.
  65. %     options.cgi             Initial value of the global-best acceleration factor.
  66. %     options.cgf             Final value of the global-best acceleration factor.
  67. %     options.wi              Initial value of the inertia factor.
  68. %     options.wf              Final value of the inertia factor.
  69. %     options.vmax            Absolute speed limit. If specified, the speed is clamped to the range
  70. %                             [-options.vmax, options.vmax]. It is the primary speed limit, if set
  71. %                             to NaN, the VMAXSCALE options is used.
  72. %     options.vmaxscale       Relative speed limit. Used only if absolute limit is unspecified, i.e.
  73. %                             set to NaN. If used, must be a scalar quantity, and denotes the amount
  74. %                             of initial population span (the INITSPAN option) used as the speed
  75. %                             limit.
  76. %     options.vspaninit       The initial velocity span. Initial velocities are initialized
  77. %                             uniformly in [-VSPANINIT, VSPANINIT]. This option must be specified.
  78. %     options.initoffset      Offset of the initial population. Can be scalar or column-vector of
  79. %                             dimension NVARS.
  80. %     options.initspan        Span of the initial population. Can be scalar or column-vector of
  81. %                             dimension NVARS.
  82. %     options.trustoffset     If set to 1 (true) and offset is vector, than the offset is
  83. %                             believed to be a good solution candidate, so it is included in
  84. %                             the initial swarm.
  85. %     options.initpopulation  The user-suplied initial population. If this is set to something
  86. %                             meaningfull, then INITSPAN, INITOFFSET and TRUSTOFFSET are
  87. %                             ignored. If set to NaN then the above mentioned offset is used.
  88. %     options.verbose_period  The verbose period, i.e. the number of iterations after which the
  89. %                             results are prompted to the user. If set to 0, then verbosing is
  90. %                             skipped.
  91. %     options.plot            If set to 1, evolution of the global best is ploted to the user after
  92. %                             the optimization process. The objective value of the best, mean
  93. %                             and worse particle troughout the optimization process are plotted
  94. %                             in the single graph.
  95. %     options.output_level    The output log level. Possible values are: 'none', 'low',
  96. %                             'medium', 'high'. Each log level denotes a specific amount of
  97. %                             information to be returned to the end user. If less than 4 output
  98. %                             arguments are specified log level is ignored, since it would only
  99. %                             occupate (possibly) large amount of useless memory.
  100. %     options.globalmin       Global minimum, used for testing only. If specified, the algorithm
  101. %                             will stop as soon as the difference between GLOBALMIN option and
  102. %                             current global best becomes less than TOL option.
  103. %     options.tol             Precision tolerance, used for testing only. It is maximal difference
  104. %                             between current global best and GLOBALMIN option at which the
  105. %                             algorithm stops. If GLOBALMIN options is set to NaN this option is
  106. %                             ignored, and the algorithm stops after the maximal number of iteration
  107. %                             has been achieved.
  108. %
  109. %   The OUTPUT structure is the fallowing
  110. %
  111. %     output.itersno          The actual number of iterations. Usualy the same as NITER options, but
  112. %                             can be less if in testing mode (if GLOBALMIN option is specified).
  113. %
  114. %     If at least LOW level output logging is specified:
  115. %
  116. %     output.gbest_array
  117. %     output.gmean_array
  118. %     output.gworst_array     Arrays containing the objective value of the best, mean and worst
  119. %                             particle in each iteration. In fact, gmean_array does not contain
  120. %                             objective value for any concrete particle, but instead it contains the
  121. %                             mean objective value for the entire swarm in each iteration.
  122. %
  123. %     If at least MEDIUM level output logging is specified:
  124. %
  125. %     output.gbes**x_array   The array ontaining indices of the best particle in each iteration.
  126. %     output.Xbest            Matrix of dimension NITERxNVARS, containing, as rows, global best
  127. %                             particles in each iteration.
  128. %
  129. %     Only if HIGH level output logging is specified:
  130. %
  131. %     output.X                3D matrix of dimension NPARTxNVARSxNITER containing the entire
  132. %                             population in each iteration.
  133. %
  134. %
  135. %   The following examples ilustrate the use of PSO function in several common cases.
  136. %
  137. %   Suppose we are attempting to optimize 5-dimensional objective f(x) = x*x'. Since, it is assumed
  138. %   that objective receives a row-vector, the objective is in fact a 5D paraboliod. The easiest way
  139. %   to optimize would be to write
  140. %
  141. %   obj = @(x) x*x';
  142. %   [xopt, fopt] = pso(obj, 5);
  143. %
  144. %   The preseding code lines would yield XOPT as the found near-optimal solution and FOPT as the
  145. %   objective value in such point. Of course, other outputs can be obtained as described earlier.
  146. %
  147. %   If one should choose to change the default options (say to specify different number of particles
  148. %   and iterations), the code would look something like this
  149. %
  150. %   obj = @(x) x*x';
  151. %   options = pso('options');
  152. %   options.niter = 500;
  153. %   options.npart = 60;
  154. %   [xopt, fopt] = pso(obj, 5);
  155. %
  156. %   Other options can be specified as well on the exactly the same way. The best way to explore the
  157. %   option structure is to experiment.
  158. %
  159. %   PSO is compatible with MATLAB 7 and higher. Some modifications are needed for it to work under
  160. %   lower versions of MATLAB.

  161. % Copyright (C) Milan Rapaic ([email]repmilan@yahoo.com[/email]), 2007-05-10 ... 2008-10-12


  162. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  163. % Checking the number of input and output arguments.                                               %
  164. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  165. msg = nargchk(1, 3, nargin);
  166. if ~isempty(msg)
  167.     error('mrr:myoptim:pso:pso:narginerr', 'Inadequate number of input arguments.');
  168. end

  169. msg = nargchk(0, 4, nargout);
  170. if ~isempty(msg)
  171.     error('mrr:myoptim:pso:pso:nargouterr', 'Inadequate number of output arguments.');
  172. end

  173. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  174. % The body of the algorithm.                                                                       %
  175. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  176. if nargin==1 && ischar(objfunc) && strcmp(objfunc, 'options')
  177.     % User desired only to access the default OPTIONS structure.
  178.     if nargout<=1
  179.         x = getDefaultOptions();
  180.     else
  181.         % The user required multiple outputs, yet only default options can be returned.
  182.         error('mrr:myoptim:pso:pso:nargouterr', ...
  183.             'Cannot expext more than one output when only OPTIONS are required.');
  184.     end
  185. else
  186.     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  187.     % User requested optimization to be conducted on a given objective.                            %
  188.     % The following code deals with initializations and validations of options structure.          %
  189.     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  190.    
  191.     % If no options are specified, use the default ones.
  192.     if nargin<3, options=getDefaultOptions(); end
  193.    
  194.     % Determination of output level, that is of amount of data to be collected in OUTPUT structure.
  195.     if nargout == 4
  196.         % User supplied four output arguments, therefore output level is determined from the OPTIONS
  197.         % structure. The output_level variable is used to code the desired log level: 0 ('none'), 1
  198.         % ('low'), 2 ('medium') and 3 ('high).
  199.         if strcmp(options.output_level, 'none')
  200.             if options.plot == 0
  201.                 output_level = 0;
  202.             else
  203.                 output_level = 1;
  204.             end
  205.         elseif strcmp(options.output_level, 'low')
  206.             output_level = 1;
  207.         elseif strcmp(options.output_level, 'medium')
  208.             output_level = 2;
  209.         elseif strcmp(options.output_level, 'high')
  210.             output_level = 3;
  211.         else
  212.             error('mrr:myoptim:pso:pso:optionserr:output_level', ...
  213.                 'Invalid value of the OUTPUT_LEVEL options specified.');
  214.         end
  215.     else
  216.         % User has not supplied forth output argument. The only reason to log information during the
  217.         % run is to be able to plot to to the user after the optimization process. Therefore, if
  218.         % ploting is requested low level logging is used.
  219.         if options.plot == 1
  220.             output_level = 1;
  221.         else
  222.             output_level = 0;
  223.         end
  224.     end
  225.   
  226.     % Maximum velocity can be specified in absolute amount, or relative to the initial span.
  227.     % If both values are specified, the absolute velocity limit is taken into account, while the
  228.     % relative is ignored. Whatever the initial specification of the maximal velocity, the curent
  229.     % code block will generate a column vector, vmax, containing maximal velocity along each
  230.     % dimension of search space.
  231.     if ~all(isnan(options.vmax))
  232.         % It is not allowed to let some of the entries of the VMAX option to be NaN and others to
  233.         % have numerical or Inf values.
  234.         if any(isnan(options.vmax))
  235.             error('mrr:myoptim:pso:pso:optionserr:vmax', ...
  236.                 'VMAX option cannot have some Inf and some numerical (or Inf) values.');
  237.         end
  238.         % Warning of the confusing entries within the OPTIONS structure.
  239.         if ~isnan(options.vmaxscale)
  240.             warning('mrr:myoptim:pso:pso:optionserr:vmaxconflict', ...
  241.                 'Both relative and absolute velocity limit are specified. The relative limit is ignored.');
  242.         end     
  243.         if length(options.vmax) == 1
  244.             vmax = options.vmax*ones(nvars, 1);
  245.         elseif length(options.vmax) == nvars
  246.             % Maximal velocity should be a column-vector or a scalar.
  247.             if size(options.vmax, 1) ~= length(options.vmax)
  248.                 error('mrr:myopim:pso:pso:optionserr:vmax', ...
  249.                     'VMAX option should be specified as column-vector, or as a scalar value.');
  250.             end
  251.             vmax = options.vmax;
  252.         else
  253.             error('mrr:myoptim:pso:pso:optionserr:vmax', ...
  254.                 'Inadequate dimension of VMAX option. Should be a scalar, or a column vector with NVARS elements.');
  255.         end
  256.     else
  257.         % It is not valid to specify both VMAX and VMAXSCALE option as NaN.
  258.         if isnan(options.vmaxscale)
  259.             error('mrr:myoptim:pso:pso:optionserr:vmaxscale', ...
  260.                 'Either VMAX or VMAXSCALE options should be different than NaN.');
  261.         end
  262.         % Contrary to the VMAX options, VMAXSCALE option must allways be a scalar. The initial span
  263.         % should take into account the different scaling among the cooedinates of the search space.
  264.         if length(options.vmaxscale) == 1
  265.             if length(options.initspan) == 1
  266.                 vmax = options.vmaxscale*options.initspan*ones(nvars, 1);
  267.             else
  268.                 % If the dimension of INITSPAN option is not correct, the function will break later,
  269.                 % therefore, no need to check validity now.
  270.                 vmax = options.vmaxscale*options.initspan;
  271.             end
  272.         else
  273.             error('mrr:myoptim:pso:pso:optionserr:vmax', ...
  274.                 'Inadequate dimension of VMAXSCALE option. Must be a scalar.');
  275.         end
  276.     end
  277.     vmax = repmat(vmax', options.npart, 1);
  278.    
  279.     % Initial population.
  280.     % If the initial population is not supplied by the user, each particle of the initial population
  281.     % is spred in [INITOFFSET-INITSPAN, INITOFFSET+INITSPAN] where both INITOFFSET and INITSPAN
  282.     % are specified within the OPTIONS structure. Both of these options are either scalars or
  283.     % column-vectors of appropriate size. If INITPOPULATION option is specified, both INITOFFSET and
  284.     % INITSPAN options are ignored.
  285.     if ~isnan(options.initpopulation)
  286.         % The user supplied complete initial population within the OPTIONS structure.
  287.         % The size of the supplied population must be consistent with population size and number of
  288.         % variables. If no, an error is reported.
  289.         [pno, pdim] = size(options.initpopulation);
  290.         if (pno ~= options.npart) || (pdim ~= nvars)
  291.             error('mrr:myoptim:pso:pso:optionserr:initpopulation', ...
  292.                 ['The format of initial population is inconsistent with desired population', ...
  293.                  'size or dimension of search space - INITPOPULATION options is invalid']);
  294.         end
  295.         X = options.initpopulation;
  296.     elseif (length(options.initoffset) == 1) && (length(options.initspan) == 1)
  297.         % The same offset and span is specified for each dimension of the search space
  298.         X = (rand(options.npart, nvars)-0.5)*2*options.initspan + options.initoffset;
  299.     elseif (length(options.initoffset) ~= size(options.initoffset, 1)) || ...
  300.            (length(options.initspan) ~= size(options.initspan, 1))
  301.         error('mrr:myoptim:pso:pso:optionserr:initoffset_initspan', ...
  302.             'Both INITOFFSET and INITSPAN options must be either scalars or column-vectors.');
  303.     elseif (length(options.initoffset) ~= nvars) || (length(options.initspan) ~= nvars)
  304.         error('mrr:myoptim:pso:pso:optionserr:init', ...
  305.             'Both INITOFFSET and INITSPAN options must be scalars or column-vectors of length NVARS.');
  306.     else      
  307.         initoffset = repmat(options.initoffset', options.npart, 1);
  308.         initspan   = repmat(options.initspan', options.npart, 1);
  309.         X = (rand(options.npart, nvars)-0.5)*2.*initspan + initoffset;
  310.         % TRUSTOFFSET option is used when OFFSET option is, in fact, previously known good (or very
  311.         % good) solution to the problem at hand. When set to logical true (1), offset is inserted in
  312.         % the initial population. Thus, it is guaranteed that objective value at solution is not
  313.         % greater than objective value at that, previously known, good point.
  314.         if (options.trustoffset)
  315.             X(1, :) = options.initoffset';
  316.         end
  317.     end
  318.    
  319.     % Initial velocities.
  320.     % Velocities are initialized uniformly in [-VSPANINIT, VSPANINIT].
  321.     if any(isnan(options.vspaninit))
  322.         error('mrr:myoptim:pso:pso:optionserr:vspaninit', ...
  323.                 'VSPANINIT option must not contain NaN entries.');
  324.     elseif isscalar(options.vspaninit)
  325.         V = (rand(options.npart, nvars)-0.5)*2*options.vspaninit;
  326.     else
  327.         if (length(options.vspaninit) ~= size(options.vspaninit, 1)) || ...
  328.            (length(options.vspaninit) ~= nvars)
  329.             error('mrr:myoptim:pso:pso:optionserr:vspaninit', ...
  330.                 'VSPANINIT option must be either scalar or column-vector of length NVARS');
  331.         end
  332.         V = (rand(options.npart, nvars)-0.5)*2.*repmat(options.vspaninit', options.npart, 1);
  333.     end
  334.       
  335.     % Initial scores (objective values).
  336.     % Initialization of the best personal score and position, as well as global best score and
  337.     % position.
  338.     Y = calcobjfunc(objfunc, X);
  339.     Ybest = Y;                      % The best individual score for each particle - initialization.
  340.     Xbest = X;                      % The best individual position for each particle -
  341.                                     % initialization.
  342.     [GYbest, gbest] = min(Ybest);   % GYbest is the best score within the entire swarm.
  343.                                     % gbest is the index of particle that achived YGbest.
  344.     gbest = gbest(1);               % In case when more than one particle achieved the best
  345.                                     % score, we choose the one with the lowest index as the
  346.                                     % best one.
  347.                                     
  348.     % These variables are used in testing mode only.
  349.     tolbreak = ~isnan(options.globalmin);
  350.     foundglobal = 0;
  351.     if tolbreak && ~isscalar(options.globalmin)
  352.         error('mrr:myoptim:pso:pso:optionserr:globalmin', ...
  353.             'globalmin option, if specified, option must be a scalar value equal to the global minimum of the objective function');
  354.     end
  355.    
  356.     % Initialization of the OUTPUT structure.
  357.     % The output structure is filled and initialized differently depending on the OUTPUT_LEVEL
  358.     % options, or equivalently depending on the output_level variable.
  359.     if output_level >= 0
  360.         % NONE log level
  361.         output.itersno = options.niter;
  362.         if output_level >= 1
  363.             % LOW log level
  364.             output.gbest_array = NaN*ones(options.niter+1, 1);
  365.             output.gmean_array = NaN*ones(options.niter+1, 1);
  366.             output.gworst_array = NaN*ones(options.niter+1, 1);
  367.             output.gbest_array(1) = GYbest;
  368.             output.gmean_array(1) = mean(Ybest);
  369.             output.gworst_array(1) = max(Ybest);
  370.             if output_level >= 2
  371.                 % MEDIUM log level
  372.                 output.gbes**x_array = NaN*ones(options.niter+1, 1);
  373.                 output.Xbest = NaN*ones(options.niter+1, nvars);
  374.                 output.gbes**x_array(1) = gbest;
  375.                 output.Xbest(1, :) = X(gbest, :);
  376.                 if output_level == 3
  377.                     % HIGH log level
  378.                     output.X = NaN*zeros(options.npart, nvars, options.niter+1);
  379.                     output.X(:,:,1) = X;
  380.                 end
  381.             end
  382.         end
  383.     end
  384.    
  385.     if options.verbose_period ~= 0
  386.         disp 'PSO algorithm: Initiating the optimization process.'
  387.     end

  388.     % Denotes normal algorithm termination.
  389.     exitflag = 0;
  390.    
  391.     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  392.     % The main loop.                                                                               %
  393.     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  394.     for iter = 1:options.niter
  395.         
  396.         % Verbosing, if neccessary.
  397.         if options.verbose_period ~= 0
  398.             if rem(iter, options.verbose_period) == 0
  399.                disp(['iteration ', int2str(iter), '. best criteria = ', num2str(GYbest)]);
  400.             end
  401.         end
  402.         
  403.         % Calculating PSO parameters
  404.         w = linrate(options.wf, options.wi, options.niter, 0, iter);
  405.         cp = linrate(options.cbf, options.cbi, options.niter, 0, iter);
  406.         cg = linrate(options.cgf, options.cgi, options.niter, 0, iter);

  407.         % For later calculations only
  408.         GXbest = repmat(Xbest(gbest, :), options.npart, 1);

  409.         % Calculating speeds
  410.         V = w*V + cp*rand(size(V)).*(Xbest-X) + cg*rand(size(V)).*(GXbest-X);
  411.         V = min(vmax, abs(V)).*sign(V);

  412.         % Population is moving
  413.         X = X + V;
  414.         Y = calcobjfunc(objfunc, X);

  415.         % Calculating new individually best values
  416.         mask = Y<Ybest;
  417.         mask = repmat(mask, 1, nvars);
  418.         Xbest = mask.*X +(~mask).*Xbest;
  419.         Ybest = min(Y,Ybest);
  420.         
  421.         % Calculating new globally best value
  422.         [GYbest, gbest] = min(Ybest);
  423.         gbest = gbest(1);
  424.         
  425.         % Filling in the OUTPUT structure.
  426.         if output_level >= 0
  427.             % NONE log level
  428.             if output_level >= 1
  429.                 % LOW log level
  430.                 output.gbest_array(iter+1)  = GYbest;
  431.                 output.gmean_array(iter+1)  = mean(Ybest);
  432.                 output.gworst_array(iter+1) = max(Ybest);
  433.                 if output_level >= 2
  434.                     % MEDIUM log level
  435.                     output.gbes**x_array(iter+1) = gbest;
  436.                     output.Xbest(iter+1, :) = X(gbest, :);
  437.                     if output_level == 3
  438.                         % HIGH log level
  439.                         output.X(:,:,iter+1) = X;
  440.                     end
  441.                 end
  442.             end
  443.         end
  444.         
  445.         % The code used in testing mode only.
  446.         if tolbreak && abs(GYbest - options.globalmin)<options.tol
  447.             output.itersno = iter;
  448.             foundglobal = 1;
  449.             break
  450.         end

  451.     end
  452.    
  453.     if options.verbose_period ~= 0
  454.         disp 'Optimization process finished.'
  455.     end
  456.    
  457.     % Setting up the output variables.
  458.     % X is set to be the final global best position, since that is the best position ever achieved
  459.     % by any of the particles in the swarm. FVAL is set to be the value of the objective in X.
  460.     x = Xbest(gbest, :); x = x(:);
  461.     fval = GYbest;
  462.    
  463.     % The global moptimum has been found prior to achieving the maximal number of iteration.
  464.     if foundglobal, exitflag = 1; end;
  465.    
  466.     % Plotting the algorithm behavior at each iteration.
  467.     if options.plot
  468.         r = 0:options.niter;
  469.         figure
  470.         plot(r, output.gbest_array, 'k.', r, output.gmean_array, 'r.', r, output.gworst_array, 'b.');
  471.         str = sprintf('Best objective value : %g', fval);
  472.         title(str);
  473.         legend({'best objective', 'mean objective', 'worst objective'})
  474.     end
  475.    
  476. end

  477. function Y = calcobjfunc(func, X)
  478. % CALCOBJFUNC   A helper function used to calculate objective function value for a series of points.
  479. np = size(X,1);
  480. Y = zeros(np,1);
  481. for i = 1:np
  482.     Y(i) = func(X(i,:));
  483. end

  484. function opts = getDefaultOptions
  485. % GETDEFAULTOPTIONS     Returns a structure containing the default options.
  486. %
  487. %   This function, in fact, defines default values of the options within the options structure.
  488. opts.npart          = 30;       % The number of particles.
  489. opts.niter          = 100;      % The number of iterations.
  490. opts.cbi            = 2.5;      % Initial value of the individual-best acceleration factor.
  491. opts.cbf            = 0.5;      % Final value of the individual-best acceleration factor.
  492. opts.cgi            = 0.5;      % Initial value of the global-best acceleration factor.
  493. opts.cgf            = 2.5;      % Final value of the global-best acceleration factor.
  494. opts.wi             = 0.9;      % Initial value of the inertia factor.
  495. opts.wf             = 0.4;      % Final value of the inertia factor.
  496. opts.vmax           = Inf;      % Absolute speed limit. It is the primary speed limit.
  497. opts.vmaxscale      = NaN;      % Relative speed limit. Used only if absolute limit is unspecified.
  498. opts.vspaninit      = 1;        % The initial velocity span. Initial velocities are initialized
  499.                                 % uniformly in [-VSPANINIT, VSPANINIT].
  500. opts.initoffset     = 0;        % Offset of the initial population.
  501. opts.initspan       = 1;        % Span of the initial population.
  502. opts.trustoffset    = 0;        % If set to 1 (true) and offset is vector, than the offset is
  503.                                 % believed to be a good solution candidate, so it is included in
  504.                                 % the initial swarm.
  505. opts.initpopulation = NaN;      % The user-suplied initial population. If this is set to something
  506.                                 % meaningfull, then INITSPAN, INITOFFSET and TRUSTOFFSET are
  507.                                 % ignored.
  508. opts.verbose_period = 10;       % The verbose period, i.e. the number of iterations after which the
  509.                                 % results are prompted to the user. If set to 0, then verbosing is
  510.                                 % skipped.
  511. opts.plot           = 0;        % If set to 1, evolution of the gbest is ploted to the user after
  512.                                 % the optimization process. The objective value of the best, mean
  513.                                 % and worse particle troughout the optimization process are plotted
  514.                                 % in the single graph.
  515. opts.output_level   = 'low';    % The output log level. Possible values are: 'none', 'low',
  516.                                 % 'medium', 'high'.
  517. opts.globalmin      = NaN;      % Global minimum, used for testing only
  518. opts.tol            = 1e-6;     % Precision tolerance, used for testing only

  519. function x = linrate(xmax, xmin, tmax, tmin, t)
  520. % LINRATE   Linear interpolation of value X in instant T, defined by previously known points
  521. %           (tmin, xmin), (tmax, xmax)
  522. x = xmin + ((xmax-xmin)/(tmax-tmin))*(tmax-t);
复制代码

转播转播0 分享淘帖0 分享分享0 收藏收藏0 支持支持0 反对反对0 微信微信
第一次用linux登录madio,纪念一下
linmatsas 实名认证       

53

主题

13

听众

3591

积分

逍遥游

自我介绍
额。。。。世界上最讨厌的事情就是自我介绍。。。

邮箱绑定达人 新人进步奖 发帖功臣 最具活力勋章

群组Matlab讨论组

群组数学建模

群组小草的客厅

群组2012数学一考研交流

群组C 语言讨论组

2#
发表于 2010-6-18 12:43 |只看该作者
回复

使用道具 举报

mathcyang 实名认证       

2

主题

3

听众

123

积分

自我介绍
一只特立独行的猪

群组Matlab讨论组

群组数学建模保研联盟

群组数学趣味、游戏、IQ等

群组Latex研学群

群组数学问题

3#
发表于 2010-6-23 15:27 |只看该作者
回复

使用道具 举报

qq
收缩
  • 电话咨询

  • 04714969085

关于我们| 联系我们| 诚征英才| 对外合作| 产品服务| QQ

手机版|Archiver| |繁體中文 手机客户端  

蒙公网安备 15010502000194号

Powered by Discuz! X2.5   © 2001-2013 数学建模网-数学中国 ( 蒙ICP备14002410号-3 蒙BBS备-0002号 )     论坛法律顾问:王兆丰

GMT+8, 2025-8-4 01:08 , Processed in 0.505600 second(s), 49 queries .

回顶部