[关闭]
@TangWill 2019-06-29T21:51:03.000000Z 字数 47280 阅读 646

粒子群优化算法项目文档


唐麒 17301138

cpp


Part 1 对粒子群优化算法的理解


目标函数优化问题可以描述为:


或:

这里为搜索空间,为目标函数。(1)式描述的优化问题称为极大化问题,(2)式描述的称为极小化问题。

粒子群优化算法PSO(Particle Swarm Optimization)是一种基于群体的自适应的搜索优化方法。PSO 中,每个优化问题的潜在解都是搜索空间中的一只鸟,称之为粒子。所有的粒子都有一个由被优化的函数决定的适值( fitness value) ,每个粒子还有一个速度决定它们飞翔的方向和距离。然后粒子们就追随当前的最优粒子在解空间中搜索。

PSO初始化为一群随机粒子(随机解),然后通过迭代找到最优解。在每一次迭代中,粒子通过跟踪两个极值来更新自己;第一个就是粒子本身所找到的最优解,这个解称为个体极值;另一个极值是整个种群目前找到的最优解,这个极值是全局极值。另外也可以不用整个种群而只是用其中一部分作为粒子的邻居,那么在所有邻居中的极值就是局部极值。

假设在一个 维的目标搜索空间中,有 个粒子组成一个群落,其中第 个粒子表示为一个维的向量

个粒子的“飞行”速度也是一个维的向量,记为

个粒子迄今为止搜索到的最优位置称为个体极值,记为

整个粒子群迄今为止搜索到的最优位置为全局极值,记为

在找到这两个最优值时,粒子根据如下的公式(1.1)和( 1.2)来更新自己的速度和位置:


其中: 为学习因子,也称加速常数(acceleration constant), 为[0,1]范围内的均匀随机数。式(3)右边由三部分组成,第一部分为“惯性(inertia)”或“动量(momentum)”部分,反映了粒子的运动“习惯(habit)”,代表粒子有维持自己先前速度的趋势;第二部分为“认知(cognition)”部分,反映了粒子对自身历史经验的记忆(memory)或回忆(remembrance),代表粒子有向自身历史最佳位置逼近的趋势;第三部分为“社会(social)”部分,反映了粒子间协同合作与知识共享的群体历史经验。


Part 2 算法设计


这部分内容主要是针对本文主要研究问题的类型确定粒子群算法具体实现过程和一些参数的选择。

算法流程框图

Created with Raphaël 2.1.2开始初始化每个粒子的速度和位置计算每个粒子的适应值求出每个粒子的个体最优求出整个群体的全局最优根据方程(3)对粒子的速度进行优化是否满足结束条件?输出结果结束yesno

算法实现

算法的流程如下:

  1. 初始化粒子群,包括群体规模 ,每个粒子的位置 和速度
    1. 计算每个粒子的适应度值 ;
    2. 对每个粒子,用它的适应度值 和个体极值 比较,如果 ,则用 替换掉 ;
    3. 对每个粒子,用它的适应度值 和全局极值 比较,如果 则用 替 ;
    4. 根据公式(3),(4)更新粒子的速度 和位置 ;
    5. 如果满足结束条件(误差足够好或到达最大循环次数)退出,否则返回2。

算法的构成要素

对于构成粒子群算法的各个参数进行设定。本算法中主要的参数变量为惯性权值 ,学习因子 ,群体的大小 ,迭代次数 ,粒子维数

(1)群体大小
通常,群体太小则不能提供足够的采样点,以致算法性能很差,容易陷入局部最优;群体太大尽管可以增加优化信息,阻止早熟收敛的发生,但无疑会增加计算量,造成收敛时间太长,表现为收敛速度缓慢。本文对函数的优化选择种群规模为40000。

(2)最大迭代次数
迭代次数越多能保证解的收敛性,但是影响运算速度,本文对函数的优化选最大迭代次数为80次,利用大量的种群和较少的迭代次数,优化效果明显。

(3)惯性权值
惯性权重 表示在多大程度上保留原来的速度。 较大,全局收敛能力强,局部收敛能力弱; 较小,局部收敛能力强,全局收敛能力弱。

(4)学习因子
加速常数 分别用于控制粒子指向自身或邻域最佳位置的运动。建议 ,并通常取 。本文中取

(5)粒子维数
粒子维数取决于待优化函数的维数。

(6)粒子空间的初始化
较好的选择粒子初始化空间,将大大缩短收敛的时间。在本文中我们主要是选用随机对粒子进行初始化。

测试函数

编号 函数 取值范围 维度
10
10
10
10
10
10
10
10
10
10
10
10
10
2
4

part 3 代码实例


class Particle

封装了单个粒子的类;

Particle.h

  1. //
  2. // Created by tq on 2019/6/18.
  3. //
  4. #ifndef _PARTICLE_H_
  5. #define _PARTICLE_H_
  6. /*
  7. Particle:封装了单个粒子的类;
  8. 该类的数据成员,包括粒子的:
  9. 坐标维度:in_dims,坐标,适应值,位置上下限,速度上下限,惯性系数,
  10. 全局速度因子,局部速度因子,速度上下限,速度范围因子,局部最优解,全局最优解,
  11. 方法: 随机初始化、计算适应值、更新全局最优、更新局部最优
  12. */
  13. class Particle {
  14. public:
  15. float *velocity; //速度
  16. float fitness; //粒子的适应值
  17. float *position; //粒子的坐标
  18. float fitness_pbest; //粒子的历史最优适应值
  19. float *position_pbest; //粒子的历史最优坐标
  20. float fitness_gbest; //粒子的全局最优适应值
  21. float *position_gbest; //粒子的全局最优坐标
  22. Particle(int dims, float *inmax, float *inmin, float *vmax, float *vmin, float _w, float _c1, float _c2,
  23. int _index); //Particle:构造函数
  24. void init();//init:随机初始化粒子的速度和位置
  25. void get_fitness();//get_fitness:计算当前坐标的适应值
  26. void init_pbest();//init_pbest:初始化历史最优
  27. void updata_pbest();//updata_pbest:更新历史最优
  28. void get_gbest(float *_in_gbest, float _fitness_gbest);//get_gbest: 更新全局最优
  29. void updata_v();//updata_v::更新速度
  30. void updata_in();//updata_in:更新坐标
  31. private:
  32. int index; //函数索引
  33. int dimension; //坐标维度
  34. float *position_max, *position_min; //位置上下限
  35. float *velocity_max, *velocity_min; //速度上下限
  36. float w, c1, c2; //惯性系数,局部速度因子、全局速度因子
  37. };
  38. #endif // _PARTICLE_H_

particle.cpp

  1. //
  2. // Created by tq on 2019/6/18.
  3. //
  4. #include <iostream>
  5. #include<algorithm>
  6. #include"Particle.h"
  7. #include"funs.h"
  8. using namespace std;
  9. Particle::Particle(int dims, float *inmax, float *inmin, float *vmax, float *vmin, float _w, float _c1,float _c2, int _index) {
  10. index = _index;
  11. dimension = dims; //坐标维度
  12. fitness = 0.0; //粒子的适应值
  13. position = new float[dimension]; //粒子的坐标
  14. velocity = new float[dimension]; //速度
  15. fitness_pbest = 0.0; //粒子的历史最优适应值
  16. position_pbest = new float[dimension]; //粒子的历史最优坐标
  17. fitness_gbest = 0.0; //粒子的全局最优适应值
  18. position_gbest = new float[dimension]; //粒子的全局最优坐标
  19. position_max = inmax; //位置上限
  20. position_min = inmin; //位置下限
  21. velocity_max = vmax; //速度上限
  22. velocity_min = vmin; //速度下限
  23. w = _w; //惯性系数,
  24. c1 = _c1; //历史速度因子
  25. c2 = _c2; //全局速度因子
  26. }
  27. void Particle::init() { // 随机初始化坐标
  28. position = random_array(dimension, position_max, position_min);
  29. // 随机初始化速度
  30. velocity = random_array(dimension, velocity_max, velocity_min);
  31. }
  32. void Particle::get_fitness() {
  33. //计算适应值
  34. fitness = fitness_fun(position, index, dimension);
  35. }
  36. void Particle::init_pbest() {
  37. //将坐标值和适应值,直接拷贝
  38. copy_(position, position_pbest, dimension);
  39. fitness_pbest = fitness;
  40. }
  41. void Particle::updata_pbest() { //如果当前粒子的适应值大于历史最优值pbest,重新拷贝
  42. if (fitness <= fitness_pbest)
  43. copy_(position, position_pbest, dimension);
  44. fitness_pbest = fitness;
  45. }
  46. void Particle::get_gbest(float *_in_gbest, float _fitness_gbest) { //将传入的全局最优,赋值给当前粒子的全局最优
  47. //全局最优需要比较所有粒子的适应值,
  48. //所以先在外部对所有粒子进行比较。然后再传入。
  49. copy_(_in_gbest, position_gbest, dimension);
  50. fitness_gbest = _fitness_gbest;
  51. }
  52. void Particle::updata_v() {
  53. //根据如下公式更新速度
  54. //v=v*w + (pbestin-in)*c1 + (gbestin-in)*c2
  55. //速度不得超过上限、下限
  56. for (int i = 0; i < dimension; i++) {
  57. velocity[i] = velocity[i] * w + (position_pbest[i] - position[i]) * c1 + (position_gbest[i] - position[i]) * c2;
  58. if (velocity[i] > velocity_max[i]) { velocity[i] = velocity_max[i]; }
  59. if (velocity[i] < velocity_min[i]) { velocity[i] = velocity_min[i]; }
  60. }
  61. }
  62. void Particle::updata_in() {
  63. //更新位置。位置不得超过上限、下限
  64. for (int i = 0; i < dimension; i++) {
  65. position[i] = position[i] + velocity[i];
  66. if (position[i] > position_max[i]) { position[i] = position_max[i]; }
  67. if (position[i] < position_min[i]) { position[i] = position_min[i]; }
  68. }
  69. }

class Pso

标准粒子群算法
成员:多个Particle,速度因子、惯性因子等

Pso.h

  1. //
  2. // Created by tq on 2019/6/18.
  3. //
  4. #ifndef _PSO_H_
  5. #define _PSO_H_
  6. #include "Particle.h"
  7. #include <vector>
  8. using namespace std;
  9. /*
  10. Pso类:标准粒子群算法
  11. 成员:多个Particle,速度因子、惯性因子等
  12. */
  13. class Pso {
  14. protected:
  15. int index;
  16. int swarm_amount; //粒子群数量
  17. int in_dim; //粒子坐标的维度
  18. float w, c1, c2;
  19. float *max_in;
  20. float *min_in;
  21. float *max_v;
  22. float *min_v;
  23. float *fitness_list;
  24. float v_scale = 0.1; //速度范围因子。建议0.05<v_scale<0.2
  25. float w_col = 1.0; // 惯性衰减因子,建议0.96<w_col<1.0
  26. float v_col = 1.0; //速度衰减因子,建议0.96<v_col<1.0
  27. vector<Particle> vector_pso; //存储所有粒子的容器
  28. public:
  29. float *in_gbest_final; //存放最终的最优坐标
  30. float fitness_gbest_final; //最优坐标对应的最优适应值
  31. Pso(int _swarm_amount, int dim, float _w, float *_max, float *_min, float v_scale_, int _index);//Pso:构造函数
  32. void set_w_col(float w_col); //set_w_col:设置惯性衰减因子
  33. void set_v_col(float v_col);//set_v_col:设置速度衰减因子
  34. void gbest(int flag);//gbest:计算全局最优gbest
  35. void initialize(); //initialize:初始化每个粒子的坐标值、速度、适应值、局部最优、全局最优、
  36. void update();//update:更新坐标值、速度、适应值、局部最优、全局最优、
  37. void pso_iteration(int circle_);//pso_iteration:循环迭代。circle_表示迭代次数
  38. };
  39. #endif // _PSO_H_

Pso.cpp

  1. //
  2. // Created by tq on 2019/6/18.
  3. //
  4. #include <iostream>
  5. #include <stdlib.h>
  6. #include <vector>
  7. #include <time.h>
  8. #include<algorithm>
  9. #include "Pso.h"
  10. #include"funs.h"
  11. using namespace std;
  12. //构造函数:初始化参数
  13. Pso::Pso(int _swarm_amount, int dim, float _w, float *_max, float *_min, float v_scale_, int _index) {
  14. index = _index;
  15. in_dim = dim;
  16. in_gbest_final = new float[in_dim];
  17. swarm_amount = _swarm_amount;
  18. fitness_list = new float[swarm_amount];
  19. w = _w;
  20. c1 = (1 - w) / 2;
  21. c2 = (1 - w) / 2;
  22. min_in = new float[in_dim];
  23. max_in = new float[in_dim];
  24. min_v = new float[in_dim];
  25. max_v = new float[in_dim];
  26. max_in = _max;
  27. min_in = _min;
  28. v_scale = v_scale_;
  29. for (int i = 0; i < in_dim; i++) {
  30. max_v[i] = (_max[i] - _min[i]) * v_scale;
  31. min_v[i] = -(_max[i] - _min[i]) * v_scale;
  32. }
  33. }
  34. //设置惯性衰减系数
  35. void Pso::set_w_col(float w_col_) {
  36. w_col = w_col_;
  37. }
  38. //设置速度范围的衰减系数
  39. void Pso::set_v_col(float v_col_) {
  40. v_col = v_col_;
  41. }
  42. //更新粒子群的全局最优解gbest
  43. void Pso::gbest(int init_flag) {
  44. float *in_gbest_temp = new float[in_dim]; //存放每轮的最优粒子坐标
  45. float fitness_gbest_temp; //每一轮最优适应值
  46. get_min(swarm_amount, vector_pso, in_gbest_temp, &fitness_gbest_temp, in_dim);
  47. for (int i = 0; i < swarm_amount; i++) {
  48. //如果是处于第一轮迭代,或者fitness_gbest_temp优于粒子的gbest
  49. //将粒子的gbest替换为fitness_gbest_temp和in_gbest_temp
  50. if (init_flag == 0 || fitness_gbest_temp < vector_pso[i].fitness_gbest) {
  51. vector_pso[i].get_gbest(in_gbest_temp, fitness_gbest_temp);
  52. }
  53. }
  54. }
  55. //初始化粒子群的坐标、速度、历史最优、全局最优
  56. void Pso::initialize() {
  57. for (int i = 0; i < swarm_amount; i++) {
  58. Particle single(in_dim, max_in, min_in, max_v, min_v, w, c1, c2, index);
  59. single.init();
  60. single.get_fitness();
  61. single.init_pbest();
  62. vector_pso.push_back(single);
  63. }
  64. gbest(0);
  65. }
  66. //更新粒子群的速度、坐标、历史最优、全局最优
  67. void Pso::update() {
  68. if (w_col != 1.0) {
  69. w = w * w_col; //衰减w
  70. c1 = (1 - w) / 2; //增加c1
  71. c2 = (1 - w) / 2; //增加c2
  72. }
  73. if (v_col != 1.0) {
  74. v_scale = v_scale * v_col; //衰减v_scale
  75. }
  76. for (int i = 0; i < swarm_amount; i++) {
  77. vector_pso[i].updata_v();
  78. vector_pso[i].updata_in();
  79. vector_pso[i].get_fitness();
  80. vector_pso[i].updata_pbest();
  81. }
  82. gbest(1);
  83. }
  84. //初始化,并且反复进行circle_轮的迭代
  85. void Pso::pso_iteration(int circle_) {
  86. this->initialize();
  87. for (int i = 0; i < circle_; i++) {
  88. if (i % 5 == 0) {
  89. cout << i << "nd iteration ..." << endl;
  90. }
  91. this->update();
  92. }
  93. //get_final_gbest:计算最终的最优粒子
  94. get_final_gbest(swarm_amount, vector_pso, in_gbest_final, &fitness_gbest_final, in_dim);
  95. }

function

提供了适应度函数的计算等方法

functions.h

  1. //
  2. // Created by tq on 2019/6/18.
  3. //
  4. #ifndef FUNS_H_
  5. #define FUNS_H_
  6. #include <vector>
  7. #include "Particle.h"
  8. using namespace std;
  9. //random_single:生成0-1的浮点数
  10. float random_single();
  11. //random_array:随机生成dims维度的数组
  12. float *random_array(int dims, float *max_, float *min_);
  13. //fitness_fun:生成适应值的函数
  14. float fitness_fun(float *x, int mode, int dimension);
  15. //copy_:数组 深拷贝
  16. void copy_(float src[], float dst[], int dims);
  17. //get_min:通过计算,得到适应值最小的粒子
  18. void get_min(int mount, vector<Particle> temp_pso, float *max_in, float *max_fit, int in_dims_);
  19. //get_final_gbest:通过计算,得到最终的最优解
  20. void get_final_gbest(int mount, vector<Particle> temp_pso, float *final_in, float *final_fit, int in_dims_);
  21. #endif // FUNS_H_

functions.cpp

  1. //
  2. // Created by tq on 2019/6/18.
  3. //
  4. #include <iostream>
  5. #include <stdlib.h>
  6. #include <time.h>
  7. #include <vector>
  8. #include <math.h>
  9. #include "Particle.h"
  10. #include "functions.h"
  11. using namespace std;
  12. //生成随机数
  13. float random_single() {
  14. return ((float) (rand() % 1000)) / 1000.0;
  15. }
  16. //生成维度为dims的随机数组
  17. float *random_array(int dims, float *max_, float *min_) {
  18. float *temp = new float[dims];
  19. for (int i = 0; i < dims; i++) {
  20. float random_ = random_single();
  21. temp[i] = (max_[i] - min_[i]) * random_ + min_[i];
  22. }
  23. return temp;
  24. }
  25. //fitness_fun:适应度函数使用
  26. float fitness_fun(float *x, int index, int dimension) {
  27. float sum = 0;
  28. switch (index) {
  29. case 1: {
  30. for (auto i = 0; i < dimension; i++) {
  31. sum += pow(x[i], 2);
  32. }
  33. break;
  34. }
  35. case 2: {
  36. double temp = 1;
  37. for (auto i = 0; i < dimension; i++) {
  38. temp *= abs(x[i]);
  39. }
  40. for (auto i = 0; i < dimension; i++) {
  41. sum += abs(x[i]);
  42. }
  43. sum = sum + temp;
  44. break;
  45. }
  46. case 3: {
  47. double temp = 0;
  48. for (auto i = 0; i < dimension; i++) {
  49. for (auto j = 0; j < i; j++) {
  50. temp += x[i];
  51. }
  52. sum += pow(temp, 2);
  53. }
  54. break;
  55. }
  56. case 4: {
  57. sum = abs(x[0]);
  58. for (auto i = 1; i < dimension; i++) {
  59. if (abs(x[i]) > sum)
  60. sum = abs(x[i]);
  61. }
  62. break;
  63. }
  64. case 5: {
  65. sum = 10 * (100 * pow((x[1] - pow(x[0], 2)), 2) + pow(x[0] - 1, 2));
  66. break;
  67. }
  68. case 6: {
  69. for (auto i = 0; i < dimension; i++) {
  70. sum += pow(floor(x[i] + 0.5), 2);
  71. }
  72. break;
  73. }
  74. case 7: {
  75. for (auto i = 0; i < dimension; i++) {
  76. sum += ((i + 1) * pow(x[i], 4) + (rand() % (1 - 0)) + 0);
  77. }
  78. break;
  79. }
  80. case 8: {
  81. sum = 10 * (-x[0] * sin(sqrt(abs(x[0]))));
  82. break;
  83. }
  84. case 9: {
  85. sum = 10 * (pow(x[0], 2) - 10 * cos(2 * M_PI * x[0]) + 10);
  86. break;
  87. }
  88. case 10: {
  89. double e = 1.0;
  90. int n = 0;
  91. double u = 1.0;
  92. do {
  93. n++;
  94. u = u / n;
  95. e = e + u;
  96. } while (u >= 1.0E-6);
  97. float temp1 = 0, temp2 = 0;
  98. for (auto i = 0; i < dimension; i++) {
  99. temp1 += pow(x[i], 2);
  100. temp2 += cos(2 * M_PI * x[i]);
  101. }
  102. sum += (-20 * exp(-0.2 * sqrt(temp1 / dimension)) - exp(temp2 / dimension) + 20 + e);
  103. break;
  104. }
  105. case 11: {
  106. float temp1 = 0, temp2 = 1;
  107. for (auto i = 0; i < dimension; i++) {
  108. temp1 += pow(x[i], 2);
  109. temp2 *= cos(x[i] / sqrt(i + 1));
  110. }
  111. sum = temp1 / 4000 - temp2 + 1;
  112. break;
  113. }
  114. case 12: {
  115. float y[10] = {0};
  116. for (auto i = 0; i < dimension; i++) {
  117. y[i] = 1 + (x[i] + 1) / 4;
  118. }
  119. float temp = 0;
  120. for (auto i = 0; i < dimension - 1; i++) {
  121. temp += pow(y[i] - 1, 2) * (1 + 10 * pow(sin(M_PI * y[i + 1]), 2));
  122. }
  123. sum = (10 * pow(sin(M_PI * y[0]), 2) + temp + pow(y[dimension - 1], 2)) * M_PI / dimension;
  124. for (auto i = 0; i < dimension; i++) {
  125. sum +=
  126. (x[i] > 10 ? 100 * pow((x[i] - 10), 4) : x[i] < -10 ? 100 * pow((-x[i] - 10), 4)
  127. : 0);
  128. }
  129. break;
  130. }
  131. case 13: {
  132. float temp = 0;
  133. for (auto i = 0; i < dimension; i++) {
  134. temp += pow(x[i] - 1, 2) * (1 + pow(sin(3 * M_PI * x[i]) + 1, 2));
  135. }
  136. sum = 0.1 * (pow(sin(3 * M_PI * x[0]), 2) + temp +
  137. pow(x[dimension - 1] - 1, 2) * (1 + pow(sin(2 * M_PI * x[dimension - 1]), 2)));
  138. for (auto i = 0; i < dimension; i++) {
  139. sum +=
  140. (x[i] > 5 ? 100 * pow((x[i] - 5), 4) : x[i] < -5 ? 100 * pow((-x[i] - 5), 4)
  141. : 0);
  142. }
  143. break;
  144. }
  145. case 14: {
  146. float temp = 0;
  147. int matrix[2][25] = {{-32, 16, 0, 16, 32, -32, -16, 0, 16, 32, -32, -16, 0, 16, 32, -32, -16, 0, 16, 32, -32, -16, 0, 16, 32},
  148. {-32, -32, -32, -32, -32, -16, -16, -16, -16, -16, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 32, 32, 32, 32, 32}};
  149. for (auto j = 0; j < 25; j++) {
  150. float _temp = 0;
  151. for (auto i = 0; i < dimension; i++) {
  152. _temp += pow(x[i] - matrix[i][j], 6);
  153. }
  154. temp += (1 / (j + 1 + _temp));
  155. }
  156. sum = pow(1 / 500 + temp, -1);
  157. break;
  158. }
  159. case 15: {
  160. float a[11] = {0.1957, 0.1947, 0.1735, 0.16, 0.0844, 0.0627, 0.0456, 0.0342, 0.0323, 0.0235, 0.0246};
  161. float b[11] = {0.25, 0.5, 1, 2, 4, 6, 8, 10, 12, 14, 16};
  162. for (auto i = 0; i < 11; i++) {
  163. sum += pow(a[i] - (x[0] * (pow(1 / b[i], 2) + 1 / b[i] * x[1])) /
  164. (pow(1 / b[i], 2) + 1 / b[i] * x[2] + x[3]), 2);
  165. }
  166. break;
  167. }
  168. }
  169. return sum;
  170. }
  171. //数组复制
  172. void copy_(float src[], float dst[], int dims) {
  173. for (int i = 0; i < dims; i++) {
  174. dst[i] = src[i];
  175. }
  176. }
  177. //通过计算,得到vector中的最小适应值和对应的坐标
  178. void get_min(int mount, vector<Particle> temp_pso, float *min_in, float *min_fit, int in_dims_) {
  179. for (int i = 0; i < mount; i++) {
  180. if (i == 0 || temp_pso[i].fitness < *min_fit) {
  181. *min_fit = temp_pso[i].fitness;
  182. copy_(temp_pso[i].position, min_in, in_dims_);
  183. }
  184. }
  185. }
  186. //通过计算,得到最终的最优解
  187. void get_final_gbest(int mount, vector<Particle> temp_pso, float *final_in, float *final_fit, int in_dims_) {
  188. for (int i = 0; i < mount; i++) {
  189. if (i == 0 || temp_pso[i].fitness < *final_fit) {
  190. *final_fit = temp_pso[i].fitness_gbest;
  191. copy_(temp_pso[i].position, final_in, in_dims_);
  192. }
  193. }
  194. }

main

  1. //
  2. // Created by tq on 2019/6/18.
  3. //
  4. #include <iostream>
  5. #include <stdlib.h>
  6. #include <vector>
  7. #include <time.h>
  8. #include <math.h>
  9. #include "Particle.h"
  10. #include "Pso.h"
  11. #include "functions.h"
  12. #include <iomanip>
  13. using namespace std;
  14. int main() {
  15. srand(time(0)); //随机种子
  16. int amout_ = 40000; //粒子数
  17. float w_ = 0.8; // 惯性权重
  18. // 通常情况下,全局加速因子 c1、历史加速因子c2 ,等于 (1-w)/2
  19. float v_scale_ = 0.1; //速度比例因子。最大速度、最小速度的范围
  20. int iteration = 80;//迭代次数
  21. //本适应度函数是两维。网友可以根据自身需要更改适应度函数、
  22. int index, in_dims_, up_low;
  23. cout << "*********选择函数********" << endl;
  24. cout << "1. Sphere Model " << endl;
  25. cout << "2. Schwefel’s Problem 2.22 " << endl;
  26. cout << "3. Schwefel’s Problem 1.2 " << endl;
  27. cout << "4. Schwefel’s Problem 2.21 " << endl;
  28. cout << "5. Generalized Rosenbrock’s Function " << endl;
  29. cout << "6. Step Function " << endl;
  30. cout << "7. Quartic Function i.e. Niose " << endl;
  31. cout << "8. Generalized Schwefel’s Problem 2.26 " << endl;
  32. cout << "9. Generalized Rastrigin’s Function " << endl;
  33. cout << "10. Ackley’s Function " << endl;
  34. cout << "11. Generalized Griewank Function " << endl;
  35. cout << "12. Generalized Penalized Function " << endl;
  36. cout << "13. Generalized Penalized Function " << endl;
  37. cout << "14. Shekel’s Foxholes Function " << endl;
  38. cout << "15. Kowalik’s Function " << endl;
  39. cout << "*************************" << endl;
  40. cout << "Please input the function index: " << endl;
  41. cin >> index;
  42. cout << "Please input the dimension: " << endl;
  43. cin >> in_dims_;
  44. cout << "Please input the up and low: " << endl;
  45. cin >> up_low;;
  46. float max_in[10]; //输入参数的上限
  47. for (auto i = 0; i < in_dims_; i++) {
  48. max_in[i] = up_low;;
  49. }
  50. float min_in[10]; //输入参数的下限
  51. for (auto i = 0; i < in_dims_; i++) {
  52. min_in[i] = -up_low;;
  53. }
  54. Pso pso_(amout_, in_dims_, w_, max_in, min_in, v_scale_, index);
  55. pso_.set_w_col(0.99); //设置惯性衰减系数。惯性系数每次迭代乘以0.99。c1和c2相应增加
  56. pso_.set_v_col(0.99); //设置速度衰减因子。速度的上限和下限。随着迭代衰减
  57. pso_.pso_iteration(iteration); //执行
  58. cout << "********* Complete Iteration ********" << endl;
  59. cout << "*****final_gbest fitness:" << setiosflags(ios::fixed) << setprecision(4) << pso_.fitness_gbest_final
  60. << endl;
  61. cout << "********* Complete Iteration ********" << endl;
  62. }

Part 4 结果展示




















Part 5 基于Qt的Pso可视化


在实现PSO算法对15个函数的测试后,尝试用Qt对PSO优化过程进行可视化,如图。

代码如下:
psoparameters.h

  1. #ifndef PSOPARAMETERS_H
  2. #define PSOPARAMETERS_H
  3. #include <QWidget>
  4. #include <map>
  5. namespace Ui {
  6. class PSOParameters;
  7. }
  8. class PSOParameters : public QWidget
  9. {
  10. Q_OBJECT
  11. public:
  12. explicit PSOParameters(QWidget *parent = 0);
  13. ~PSOParameters();
  14. void setResult(double result);
  15. void setProgress(const double &ratio);
  16. void showParameters( std::map<QString,double> &pso);
  17. signals:
  18. void changeParameter(QString target, double value, bool type);
  19. void beginToProcess(bool type);
  20. private slots:
  21. void on_LineEditGroup_textChanged(const QString &arg1);
  22. void on_LineEditGroup_textEdited(const QString &arg1);
  23. void on_LineEditGroup_editingFinished();
  24. void on_LineEditGeneration_editingFinished();
  25. void on_LineEditSpeed1_editingFinished();
  26. void on_LineEditSpeed2_editingFinished();
  27. void on_LineEditUp_editingFinished();
  28. void on_LineEditDown_cursorPositionChanged(int arg1, int arg2);
  29. void on_LineEditDown_editingFinished();
  30. void on_LineEditGroup_D_editingFinished();
  31. void on_LineEditGeneration_D_editingFinished();
  32. void on_LineEditUp_D_editingFinished();
  33. void on_LineEditDown_D_editingFinished();
  34. void on_horizontalSliderWeight_valueChanged(int value);
  35. void on_ComboBoxDimension_currentTextChanged(const QString &arg1);
  36. void on_horizontalSliderFactor_D_valueChanged(int value);
  37. void on_horizontalSliderCR_D_valueChanged(int value);
  38. void on_ComboBoxDimension_D_currentTextChanged(const QString &arg1);
  39. void on_pushButtonProcess_clicked();
  40. void on_comboBoxFunction_currentIndexChanged(int index);
  41. private:
  42. Ui::PSOParameters *ui;
  43. };
  44. #endif // PSOPARAMETERS_H

psoparameters.cpp

  1. #include "psoparameters.h"
  2. #include "ui_psoparameters.h"
  3. #include <QDebug>
  4. PSOParameters::PSOParameters(QWidget *parent) :
  5. QWidget(parent),
  6. ui(new Ui::PSOParameters)
  7. {
  8. ui->setupUi(this);
  9. //设置输入限制
  10. ui->LineEditGroup->setValidator(new QIntValidator(10, 300));
  11. ui->LineEditGeneration->setValidator(new QIntValidator());
  12. ui->LineEditSpeed1->setValidator(new QDoubleValidator(0.0,10.0,10));
  13. ui->LineEditSpeed2->setValidator(new QDoubleValidator(0.0, 10.0,10));
  14. ui->LineEditUp->setValidator(new QDoubleValidator());
  15. ui->LineEditDown->setValidator(new QDoubleValidator());
  16. ui->LineEditGroup_D->setValidator(new QIntValidator());
  17. ui->LineEditGeneration_D->setValidator(new QIntValidator());
  18. ui->LineEditUp_D->setValidator(new QDoubleValidator());
  19. ui->LineEditDown_D->setValidator(new QDoubleValidator());
  20. ui->lineEditResult->setReadOnly(true);
  21. }
  22. PSOParameters::~PSOParameters()
  23. {
  24. delete ui;
  25. }
  26. void PSOParameters::setResult(double result)
  27. {
  28. ui->lineEditResult->setText(QString::number(result,10,3));
  29. ui->lineEditResult->repaint();
  30. }
  31. void PSOParameters::setProgress(const double &ratio)
  32. {
  33. double tmp = ratio + 0.01;
  34. ui->progressBar->setValue(tmp*100);
  35. ui->progressBar->repaint();
  36. }
  37. void PSOParameters::showParameters( std::map<QString,double> &pso)
  38. {
  39. //设置pso的参数
  40. ui->LineEditGroup->setText(QString::number(static_cast<int>(pso["population"]),10));
  41. ui->LineEditGeneration->setText(QString::number(static_cast<int>(pso["generation"]),10));
  42. double ratio = pso["w"];
  43. ui->horizontalSliderWeight->setValue(static_cast<int>(ratio*100));
  44. ui->LineEditSpeed1->setText(QString::number(pso["c1"],10,2));
  45. ui->LineEditSpeed2->setText(QString::number(pso["c1"],10,2));
  46. ui->ComboBoxDimension->setCurrentText(QString::number(static_cast<int>(pso["dimension"])));
  47. ui->LineEditUp->setText(QString::number(pso["upbounding"],10,2));
  48. ui->LineEditDown->setText(QString::number(pso["lowbounding"],10,2));
  49. }
  50. void PSOParameters::on_LineEditGroup_textChanged(const QString &arg1)
  51. {
  52. Q_UNUSED(arg1);
  53. }
  54. void PSOParameters::on_LineEditGroup_textEdited(const QString &arg1)
  55. {
  56. Q_UNUSED(arg1);
  57. }
  58. void PSOParameters::on_LineEditGroup_editingFinished()
  59. {
  60. double value = ui->LineEditGroup->text().toDouble();
  61. emit changeParameter(tr("population"),value, false);
  62. }
  63. void PSOParameters::on_LineEditGeneration_editingFinished()
  64. {
  65. double value = ui->LineEditGeneration->text().toDouble();
  66. emit changeParameter(tr("generation"),value, false);
  67. }
  68. void PSOParameters::on_LineEditSpeed1_editingFinished()
  69. {
  70. double value = ui->LineEditSpeed1->text().toDouble();
  71. emit changeParameter(tr("c1"),value, false);
  72. }
  73. void PSOParameters::on_LineEditSpeed2_editingFinished()
  74. {
  75. double value = ui->LineEditSpeed2->text().toDouble();
  76. emit changeParameter(tr("c2"),value, false);
  77. }
  78. void PSOParameters::on_LineEditUp_editingFinished()
  79. {
  80. double value = ui->LineEditUp->text().toDouble();
  81. emit changeParameter(tr("upbounding"),value, false);
  82. }
  83. void PSOParameters::on_LineEditDown_cursorPositionChanged(int arg1, int arg2)
  84. {
  85. Q_UNUSED(arg1);
  86. Q_UNUSED(arg2);
  87. }
  88. void PSOParameters::on_LineEditDown_editingFinished()
  89. {
  90. double value = ui->LineEditDown->text().toDouble();
  91. emit changeParameter(tr("lowbounding"),value, false);
  92. }
  93. void PSOParameters::on_LineEditGroup_D_editingFinished()
  94. {
  95. double value = ui->LineEditGroup_D->text().toDouble();
  96. emit changeParameter(tr("population"),value, true);
  97. }
  98. void PSOParameters::on_LineEditGeneration_D_editingFinished()
  99. {
  100. double value = ui->LineEditGeneration_D->text().toDouble();
  101. emit changeParameter(tr("generation"),value, true);
  102. }
  103. void PSOParameters::on_LineEditUp_D_editingFinished()
  104. {
  105. double value = ui->LineEditUp_D->text().toDouble();
  106. emit changeParameter(tr("upbounding"),value, true);
  107. }
  108. void PSOParameters::on_LineEditDown_D_editingFinished()
  109. {
  110. double value = ui->LineEditDown_D->text().toDouble();
  111. emit changeParameter(tr("lowbounding"),value, true);
  112. }
  113. void PSOParameters::on_horizontalSliderWeight_valueChanged(int value)
  114. {
  115. double ratio = value/100.0;
  116. ui->labelWeight->setText(QString::number(ratio,10,1));
  117. emit changeParameter(tr("w"),ratio,false);
  118. }
  119. void PSOParameters::on_ComboBoxDimension_currentTextChanged(const QString &arg1)
  120. {
  121. int value = arg1.toInt();
  122. emit changeParameter(tr("dimension"),static_cast<double>(value),false);
  123. }
  124. void PSOParameters::on_horizontalSliderFactor_D_valueChanged(int value)
  125. {
  126. double ratio = value/200.0;
  127. ui->labelFactor_D->setText(QString::number(ratio,10,1));
  128. emit changeParameter(tr("F"),ratio,true);
  129. }
  130. void PSOParameters::on_horizontalSliderCR_D_valueChanged(int value)
  131. {
  132. double ratio = value/100.0;
  133. ui->labelCR_D->setText(QString::number(ratio,10,1));
  134. emit changeParameter(tr("CR"),ratio,true);
  135. }
  136. void PSOParameters::on_ComboBoxDimension_D_currentTextChanged(const QString &arg1)
  137. {
  138. int value = arg1.toInt();
  139. emit changeParameter(tr("dimension"),static_cast<double>(value),true);
  140. }
  141. void PSOParameters::on_pushButtonProcess_clicked()
  142. {
  143. emit beginToProcess(true);
  144. }
  145. void PSOParameters::on_comboBoxFunction_currentIndexChanged(int index)
  146. {
  147. int value = index + 1;
  148. emit changeParameter(tr("function"),value, false);
  149. emit changeParameter(tr("function"),value, true);
  150. }

algorithm.h

  1. #ifndef ALGORITHM_H
  2. #define ALGORITHM_H
  3. #include <map>
  4. #include <QString>
  5. #include <QObject>
  6. #include <vector>
  7. class Algorithm : public QObject
  8. {
  9. Q_OBJECT
  10. public:
  11. //double result;//存储结果
  12. static void dataInitialization(int func_num, int dimension);
  13. Algorithm():minY(0.0),maxY(10000000000.0){}
  14. void setParameters(const QString &target, double value){
  15. parameters[target] = value;
  16. }
  17. double getParameters(const QString &target){
  18. return parameters[target];
  19. }
  20. void resetParameters(std::vector<std::pair<QString,double> > &parm);//设置参数
  21. virtual void initial();
  22. virtual void process(){
  23. return;
  24. }
  25. double getResult(std::vector<double> ans);
  26. std::map<QString,double>& getParameterList(){
  27. return parameters;
  28. }
  29. signals:
  30. void processFinished(double result);
  31. void frameUpdate(double midret,const std::vector<double>& target,
  32. const double &ymin,const double &ymax,
  33. const int &curGen,const int &totalGen,
  34. const std::pair<int,double> &bestValue);//运行过程中的动态更新
  35. protected:
  36. std::vector<std::vector<std::vector<double> > > group;//群体
  37. std::vector<double> currentValue;
  38. std::pair<int,double> bestValue;
  39. double minY,maxY,avgValue;
  40. void calcCurrentValue(const std::vector<std::vector<double> > &target);
  41. private:
  42. std::map<QString, double> parameters;//参数列表
  43. };
  44. class PSOAlgorithm : public Algorithm{//粒子群算法
  45. Q_OBJECT
  46. public:
  47. std::vector<double> gBest; //全局最优解
  48. PSOAlgorithm(){}
  49. virtual void initial();
  50. virtual void process();
  51. void update(int curGeneration);//更新速度和位置
  52. void curAndgloBest(int curGeneration);//计算全局最优与当前最优
  53. private:
  54. std::vector<std::vector<double> >velocity;//速度
  55. std::vector<std::vector<double> >pBest;//当前每个的最优解
  56. };
  57. #endif // ALGORITHM_H

algorithm.cpp

  1. #include <ctime>
  2. #include <cmath>
  3. #include <cstdlib>
  4. #include "algorithm.h"
  5. #include "MyFunction.cpp"
  6. #include <QDebug>
  7. #include <iostream>
  8. #include <float.h>
  9. void Algorithm::dataInitialization(int func_num, int dimension)
  10. {
  11. initialization(func_num, dimension);
  12. }
  13. void Algorithm::resetParameters(std::vector<std::pair<QString, double> > &parm)
  14. {
  15. for(auto it = parm.begin();it != parm.end();++it){
  16. this->setParameters(it->first,it->second);
  17. }
  18. }
  19. void Algorithm::initial()
  20. {
  21. //初始化
  22. minY = DBL_MAX;
  23. maxY = -11000000;
  24. srand((unsigned)time(nullptr));
  25. int population = static_cast<int>(getParameters(tr("population")));//种群大小
  26. int dimension = static_cast<int>(getParameters(tr("dimension")));//维度
  27. int generation = static_cast<int>(getParameters(tr("generation")));//迭代次数
  28. double lowbounding = getParameters(tr("lowbounding"));
  29. double upbounding = getParameters(tr("upbounding"));
  30. group.clear();
  31. group.resize(generation,std::vector<std::vector<double> >(population,
  32. std::vector<double>(dimension,0.0)));
  33. for (int i = 0; i < population; i++) {
  34. for (int j = 0; j < dimension; j++) {
  35. group[0][i][j] = lowbounding +
  36. (double)(rand() / (double)RAND_MAX) * (upbounding - lowbounding);
  37. }
  38. }
  39. currentValue.clear();
  40. currentValue.resize(population,0.0);
  41. }
  42. double Algorithm::getResult(std::vector<double> ans)
  43. {
  44. int dimension = static_cast<int>(getParameters(tr("dimension")));
  45. int func_num = static_cast<int>(getParameters(tr("function")));//函数编号
  46. return functions(ans,func_num,dimension);
  47. }
  48. void Algorithm::calcCurrentValue(const std::vector<std::vector<double> > &target)
  49. {
  50. minY = DBL_MAX;
  51. maxY = -11000000;
  52. avgValue = 0;
  53. int dimension = static_cast<int>(getParameters(tr("dimension")));
  54. int func_num = static_cast<int>(getParameters(tr("function")));//函数编号
  55. for(uint x = 0;x < target.size();++x){
  56. currentValue[x] = functions(target[x],func_num,dimension);
  57. avgValue += currentValue[x];
  58. minY = std::min(minY,currentValue[x]);
  59. maxY = std::max(maxY,currentValue[x]);
  60. }
  61. avgValue /= target.size();
  62. }
  63. //以下为粒子群算法
  64. void PSOAlgorithm::initial()
  65. {
  66. Algorithm::initial();
  67. int population = static_cast<int>(getParameters(tr("population")));//种群大小
  68. int dimension = static_cast<int>(getParameters(tr("dimension")));//维度
  69. gBest.clear();
  70. pBest.clear();
  71. velocity.clear();
  72. gBest.resize(dimension, 0.0);
  73. pBest.resize(population,std::vector<double>(dimension, 0.0));
  74. velocity.resize(population,std::vector<double>(dimension,0.0));
  75. bestValue.first = 0;
  76. bestValue.second = DBL_MAX;
  77. }
  78. void PSOAlgorithm::process()
  79. {
  80. curAndgloBest(0);//计算初始代最优解
  81. int generation = static_cast<int>(getParameters(tr("generation")));//迭代次数
  82. for (auto current = 1; current < generation; ++current) {
  83. update(current);
  84. curAndgloBest(current);
  85. calcCurrentValue(pBest);
  86. if(generation <= 100 || (generation > 100 && generation % 2 == 0))
  87. emit frameUpdate(avgValue,currentValue,minY,maxY,current,generation,bestValue);
  88. }
  89. emit processFinished(bestValue.second);
  90. }
  91. void PSOAlgorithm::update(int curGeneration)
  92. {//更新速度和位置
  93. int dimension = static_cast<int>(getParameters(tr("dimension")));
  94. int population = static_cast<int>(getParameters(tr("population")));
  95. double w = getParameters(tr("w"));//惯性权重
  96. double c1 = getParameters(tr("c1"));//加速系数
  97. double c2 = getParameters(tr("c2"));//加速系数
  98. double upbounding = getParameters(tr("upbounding"));//上界
  99. double lowbounding = getParameters(tr("lowbounding"));//下界
  100. for(auto i = 0;i < population;++i){
  101. for(auto j = 0;j < dimension;++j){
  102. double pre = velocity[i][j];
  103. //更新速度
  104. velocity[i][j] = w*pre +
  105. c1*(double)(rand()/(double)RAND_MAX)*
  106. (pBest[i][j] - group[curGeneration - 1][i][j])
  107. +
  108. c2*(double)(rand()/(double)RAND_MAX)*
  109. (gBest[j] - group[curGeneration - 1][i][j]);
  110. if(velocity[i][j] > 200)velocity[i][j] = 200;
  111. //位置更新
  112. group[curGeneration][i][j] = group[curGeneration-1][i][j] + velocity[i][j];
  113. //边界处理
  114. if(group[curGeneration][i][j] > upbounding)
  115. group[curGeneration][i][j] = upbounding;
  116. if(group[curGeneration][i][j] < lowbounding)
  117. group[curGeneration][i][j] = lowbounding;
  118. }
  119. }
  120. }
  121. void PSOAlgorithm::curAndgloBest(int curGeneration)
  122. {//计算当前最优解和全局最优解
  123. int population = static_cast<int>(getParameters(tr("population")));
  124. int dimension = static_cast<int>(getParameters(tr("dimension")));
  125. int func_num = static_cast<int>(getParameters(tr("function")));//函数编号
  126. for (auto i = 0; i < population; ++i) {
  127. double value = functions(group[curGeneration][i], func_num, dimension);
  128. if (value < functions(pBest[i], func_num, dimension))
  129. pBest[i] = group[curGeneration][i];
  130. if (functions(pBest[i], func_num, dimension) < functions(gBest, func_num, dimension)){
  131. gBest = pBest[i];
  132. bestValue.first = i;
  133. bestValue.second = functions(pBest[i], func_num, dimension);
  134. }
  135. }
  136. }

curvedialog.h

  1. #ifndef CURVEDIALOG_H
  2. #define CURVEDIALOG_H
  3. #include <QDialog>
  4. namespace Ui {
  5. class CurveDialog;
  6. }
  7. class PSOParameters;
  8. class CurveDialog : public QDialog
  9. {
  10. Q_OBJECT
  11. public:
  12. explicit CurveDialog(QWidget *parent = 0);
  13. ~CurveDialog();
  14. PSOParameters *setting;
  15. private:
  16. Ui::CurveDialog *ui;
  17. };
  18. #endif // CURVEDIALOG_H

curvedialog.cpp

  1. #include "curvedialog.h"
  2. #include "ui_curvedialog.h"
  3. #include "psoparameters.h"
  4. #include <QHBoxLayout>
  5. #include <QDebug>
  6. CurveDialog::CurveDialog(QWidget *parent) :
  7. QDialog(parent),
  8. ui(new Ui::CurveDialog)
  9. {
  10. ui->setupUi(this);
  11. //非模态对话框
  12. this->setModal(false);
  13. //布局
  14. setting = new PSOParameters(this);
  15. QHBoxLayout *layout = new QHBoxLayout;
  16. layout->addWidget(setting);
  17. this->setLayout(layout);
  18. }
  19. CurveDialog::~CurveDialog()
  20. {
  21. delete ui;
  22. }

mainwindow.h

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3. #include <QMainWindow>
  4. #include <QtCharts/QChartView>
  5. #include <QtCharts/QScatterSeries>
  6. #include <QtCharts/QLineSeries>
  7. #include <QString>
  8. namespace Ui {
  9. class MainWindow;
  10. }
  11. class PSOParameters;
  12. class PSOAlgorithm;
  13. class CurveDialog;
  14. class MainWindow : public QMainWindow
  15. {
  16. Q_OBJECT
  17. public:
  18. explicit MainWindow(QWidget *parent = 0);
  19. ~MainWindow();
  20. void addPoint(int x,double y);//曲线点
  21. void reset();//曲线重置
  22. void loadStyleSheet(const QString &styleSheetFile);
  23. protected slots:
  24. void setParameters(QString target, double value);
  25. void beginProcess();//开始运行
  26. void setResult(double result);//设置结果数值
  27. void frameUpdate(double midret,const std::vector<double>& target,
  28. const double &ymin,const double &ymax,
  29. const int &curGen,const int &totalGen,
  30. const std::pair<int,double> &bestValue);//运行过程中的动态设置
  31. private:
  32. bool begin;
  33. Ui::MainWindow *ui;
  34. PSOAlgorithm* pso_algo;
  35. QtCharts::QScatterSeries *series;
  36. QtCharts::QScatterSeries *bestSol;
  37. QtCharts::QLineSeries *seriesCurve;
  38. QtCharts::QChartView *chartView;
  39. QtCharts::QChartView *chartViewCurve;
  40. CurveDialog *curveDlg;
  41. double maxY;
  42. //参数列表
  43. std::vector<std::pair<QString,double> > psoParm;
  44. void createChart();
  45. };
  46. #endif // MAINWINDOW_H

mainwindow.cpp

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3. #include "psoparameters.h"
  4. #include "curvedialog.h"
  5. #include "algorithm.h"
  6. #include <QtCharts/QChart>
  7. #include <QMessageBox>
  8. #include <QHBoxLayout>
  9. #include <float.h>
  10. #include <QDebug>
  11. using namespace QtCharts;
  12. MainWindow::MainWindow(QWidget *parent) :
  13. QMainWindow(parent),
  14. begin(false), ui(new Ui::MainWindow)
  15. {
  16. ui->setupUi(this);
  17. QWidget *centeral = new QWidget(this);
  18. this->setCentralWidget(centeral);
  19. this->setWindowTitle("PSO");
  20. this->loadStyleSheet(":/qss/new.qss");
  21. //创建图表
  22. createChart();
  23. //布局
  24. QHBoxLayout *layout = new QHBoxLayout();
  25. layout->addWidget(chartView);
  26. layout->addWidget(chartViewCurve);
  27. centeral->setLayout(layout);
  28. curveDlg = new CurveDialog(this);
  29. connect(curveDlg->setting,&PSOParameters::changeParameter,this,&MainWindow::setParameters);
  30. connect(curveDlg->setting,&PSOParameters::beginToProcess,this,&MainWindow::beginProcess);
  31. //算法处理部分
  32. pso_algo = new PSOAlgorithm();
  33. connect(pso_algo,&PSOAlgorithm::processFinished,this,&MainWindow::setResult);
  34. connect(pso_algo,&PSOAlgorithm::frameUpdate,this,&MainWindow::frameUpdate);
  35. psoParm = {
  36. std::pair<QString,double>("population",100.0),
  37. std::pair<QString,double>("dimension",10.0),
  38. std::pair<QString,double>("function",1.0),
  39. std::pair<QString,double>("generation",500),
  40. std::pair<QString,double>("w",0.5),
  41. std::pair<QString,double>("c1",2.0),
  42. std::pair<QString,double>("c2",2.0),
  43. std::pair<QString,double>("upbounding",100.0),
  44. std::pair<QString,double>("lowbounding",-100.0)
  45. };
  46. pso_algo->resetParameters(psoParm);
  47. curveDlg->setting->showParameters(pso_algo->getParameterList());
  48. curveDlg->show();
  49. }
  50. MainWindow::~MainWindow()
  51. {
  52. delete ui;
  53. delete pso_algo;
  54. }
  55. void MainWindow::addPoint(int x, double y)
  56. {
  57. chartViewCurve->chart()->axisX()->setRange(1,x+1);
  58. if(y > maxY){
  59. maxY = y;
  60. double lowb = 100.0*pso_algo->getParameters(tr("function"));
  61. chartViewCurve->chart()->axisY()->setRange(lowb-100.0,maxY);
  62. }
  63. seriesCurve->append(QPointF(x,y));
  64. chartViewCurve->repaint();
  65. }
  66. void MainWindow::reset()
  67. {
  68. seriesCurve->clear();
  69. maxY = DBL_MIN;
  70. }
  71. void MainWindow::setParameters(QString target, double value)
  72. {
  73. for(auto it = psoParm.begin();it != psoParm.end();++it){
  74. if(it->first == target){
  75. it->second = value;
  76. pso_algo->setParameters(target,value);
  77. break;
  78. }
  79. }
  80. }
  81. void MainWindow::beginProcess()
  82. {
  83. //检查当前的函数是否有对应的维度
  84. if(begin){
  85. QMessageBox::warning(this,tr(u8"警告"),
  86. tr(u8"当前算法任务尚未完成!"));
  87. return;
  88. }
  89. begin = true;
  90. reset();//曲线重置
  91. int func_num = pso_algo->getParameters("function");
  92. int dimension = pso_algo->getParameters("dimension");
  93. Algorithm::dataInitialization(func_num,dimension);
  94. pso_algo->initial();
  95. pso_algo->process();
  96. }
  97. void MainWindow::setResult(double result)
  98. {
  99. curveDlg->setting->setResult(result);
  100. begin = false;
  101. }
  102. void MainWindow::frameUpdate(double midret,const std::vector<double> &target,
  103. const double &ymin,const double &ymax,
  104. const int &curGen,const int &totalGen,
  105. const std::pair<int,double> &bestValue)
  106. {
  107. //设置显示结果
  108. curveDlg->setting->setResult(bestValue.second);
  109. //设置显示图表
  110. chartView->chart()->axisX()->setRange(0,target.size()+2);
  111. chartView->chart()->axisY()->setRange(ymin-10,ymax+10);
  112. series->clear();
  113. for(uint x = 0;x < target.size();++x){
  114. series->append(x+1,target[x]);
  115. }
  116. chartView->repaint();
  117. //设置显示最优解
  118. bestSol->clear();
  119. bestSol->append(bestValue.first,bestValue.second);
  120. //设置显示进度
  121. double ratio = static_cast<double>(curGen)/totalGen;
  122. curveDlg->setting->setProgress(ratio);
  123. //设置显示收敛曲线
  124. addPoint(curGen,midret);
  125. //防止未响应
  126. qApp->processEvents();
  127. }
  128. void MainWindow::createChart()
  129. {
  130. // 构建图表,种群个体是适应值
  131. QChart *chart = new QChart();
  132. chart->legend()->hide(); // 隐藏图例
  133. // 构建 series,作为图表的数据源
  134. series = new QtCharts::QScatterSeries(chart);
  135. series->setMarkerSize(10.0);
  136. bestSol = new QScatterSeries(chart);
  137. bestSol->setMarkerSize(25.0);
  138. chart->addSeries(series); // 将 series 添加至图表中
  139. chart->addSeries(new QScatterSeries(chart));
  140. chart->addSeries(bestSol); //将bestSol 添加至图表中
  141. chart->createDefaultAxes(); // 基于已添加到图表的 series 来创轴
  142. chart->setTitle(tr(u8"种群个体函数值")); // 设置图表的标题
  143. // 构建 QChartView,并设置抗锯齿、标题、大小
  144. chartView = new QChartView(this);
  145. chartView->setChart(chart);
  146. chartView->setRenderHint(QPainter::Antialiasing);
  147. QChart::ChartTheme theme = static_cast<QChart::ChartTheme>(2);
  148. chartView->chart()->setTheme(theme);
  149. QChart *chart2 = new QChart();
  150. chart2->legend()->hide(); // 隐藏图例
  151. seriesCurve = new QLineSeries(chart);
  152. chart2->addSeries(seriesCurve); // 将 series 添加至图表中
  153. chart2->createDefaultAxes(); // 基于已添加到图表的 series 来创轴
  154. chart2->setTitle(tr(u8"收敛曲线")); // 设置图表的标题
  155. chartViewCurve = new QChartView(this);
  156. chartViewCurve->setChart(chart2);
  157. chartViewCurve->setRenderHint(QPainter::Antialiasing);
  158. chartViewCurve->chart()->setTheme(theme);
  159. chartViewCurve->chart()->axisX()->gridVisibleChanged(false);
  160. chartViewCurve->chart()->axisY()->gridVisibleChanged(false);
  161. }
  162. /*load qss style*/
  163. void MainWindow::loadStyleSheet(const QString &styleSheetFile)
  164. {
  165. QFile file(styleSheetFile);
  166. file.open(QFile::ReadOnly);
  167. if (file.isOpen())
  168. {
  169. QString styleSheet = this->styleSheet();
  170. styleSheet += QLatin1String(file.readAll());//读取样式表文件
  171. this->setStyleSheet(styleSheet);//把文件内容传参
  172. file.close();
  173. }
  174. else
  175. {
  176. QMessageBox::information(this,"tip","cannot find qss file");
  177. }
  178. }

main.cpp

  1. #include <QApplication>
  2. #include "algorithm.h"
  3. #include "mainwindow.h"
  4. int main(int argc, char* argv[])
  5. {
  6. QApplication app(argc,argv);
  7. MainWindow window;
  8. window.show();
  9. return app.exec();
  10. }

MyFunction.cpp

  1. //#include <WINDOWS.H>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <stdlib.h>
  5. #include <malloc.h>
  6. #include <fstream>
  7. #include <string>
  8. #include <vector>
  9. #include <iostream>
  10. #include <QDebug>
  11. using namespace std;
  12. #define INF 1.0e99
  13. #define EPS 1.0e-14
  14. #define E 2.7182818284590452353602874713526625
  15. #define PI 3.1415926535897932384626433832795029
  16. void initialization(int func_num, int dimension);
  17. double functions(vector<double> x, int func_name,int dimension);
  18. void F1(double *, double *, int, double *, double *, int, int); /* Sphere */
  19. void F2(double *, double *, int, double *, double *, int, int);
  20. void F3(double *, double *, int, double *, double *, int, int);
  21. void F4(double *, double *, int, double *, double *, int, int);
  22. void F5(double *, double *, int, double *, double *, int, int);
  23. void F6(double *, double *, int, double *, double *, int, int);
  24. void F7(double *, double *, int, double *, double *, int, int);
  25. void F8(double *, double *, int, double *, double *, int, int);
  26. void F9(double *, double *, int, double *, double *, int, int);
  27. void F10(double *, double *, int, double *, double *, int, int);
  28. void F11(double *, double *, int, double *, double *, int, int);
  29. void F12(double *, double *, int, double *, double *, int, int);
  30. void F13(double *, double *, int, double *, double *, int, int);
  31. void F14(double *, double *, int, double *, double *, int, int);
  32. void F15(double *, double *, int, double *, double *, int, int);
  33. void shiftfunc(double*, double*, int, double*);
  34. void rotatefunc(double*, double*, int, double*);
  35. void sr_func(double *, double *, int, double*, double*, double, int, int); /* shift and rotate */
  36. double *OShift, *M, *y, *z, *x_bound;
  37. int ini_flag = 0, n_flag, func_flag, *SS;
  38. void initialization(int func_num, int dimension) {
  39. int cf_num = 10, i, j;
  40. fstream infile;
  41. char FileName[256];
  42. int nx = dimension;
  43. free(M);
  44. free(OShift);
  45. free(y);
  46. free(z);
  47. free(x_bound);
  48. y = (double *)malloc(sizeof(double) * nx);
  49. z = (double *)malloc(sizeof(double) * nx);
  50. x_bound = (double *)malloc(sizeof(double) * nx);
  51. for (i = 0; i<nx; i++) {
  52. x_bound[i] = 100.0;
  53. }
  54. if (!(nx == 2 || nx == 10 || nx == 20 || nx == 30 || nx == 50 || nx == 100))
  55. {
  56. printf("\nError: Test functions are only defined for D=2,10,20,30,50,100.\n");
  57. }
  58. if (nx == 2 && ((func_num >= 17 && func_num <= 22) || (func_num >= 29 && func_num <= 30)))
  59. {
  60. printf("\nError: hf01,hf02,hf03,hf04,hf05,hf06,cf07&cf08 are NOT defined for D=2.\n");
  61. }
  62. /* Load Matrix M*/
  63. sprintf(FileName, "D:/BJTU/CPP/Pso/AILearning-master/SingleObjectiveOpt/input_data/M_%d_D%d.txt", func_num, nx);
  64. infile.open(FileName);
  65. //std::cout << FileName << "\n";
  66. //fpt = fopen(FileName, "r");
  67. if (!infile)
  68. {
  69. printf("\n Error: Cannot open input file %s for reading \n", FileName);
  70. }
  71. if (func_num<20)
  72. {
  73. M = (double*)malloc(nx*nx * sizeof(double));
  74. if (M == NULL)
  75. printf("\nError: there is insufficient memory available!\n");
  76. for (i = 0; i<nx*nx; i++)
  77. {
  78. infile >> M[i];
  79. //cout << M[i] << endl;
  80. //fscanf(fpt, "%Lf", &M[i]);
  81. }
  82. }
  83. else
  84. {
  85. M = (double*)malloc(cf_num*nx*nx * sizeof(double));
  86. if (M == NULL)
  87. printf("\nError: there is insufficient memory available!\n");
  88. for (i = 0; i<cf_num*nx*nx; i++)
  89. {
  90. infile >> M[i];
  91. //fscanf(fpt, "%Lf", &M[i]);
  92. }
  93. }
  94. infile.close();
  95. //fclose(fpt);
  96. /* Load shift_data */
  97. sprintf(FileName, "D:/BJTU/CPP/Pso/AILearning-master/SingleObjectiveOpt/input_data/shift_data_%d.txt", func_num);
  98. //std::cout << "fileName->" << FileName << std::endl;
  99. infile.open(FileName);
  100. //fpt = fopen(FileName, "r");
  101. if (!infile)
  102. {
  103. printf("\n Error: Cannot open input file for reading \n");
  104. }
  105. if (func_num<20)
  106. {
  107. OShift = (double *)malloc(nx * sizeof(double));
  108. if (OShift == NULL)
  109. printf("\nError: there is insufficient memory available!\n");
  110. for (i = 0; i<nx; i++)
  111. {
  112. infile >> OShift[i];
  113. //fscanf(fpt, "%Lf", &OShift[i]);
  114. }
  115. }
  116. else
  117. {
  118. OShift = (double *)malloc(nx*cf_num * sizeof(double));
  119. if (OShift == NULL)
  120. printf("\nError: there is insufficient memory available!\n");
  121. for (i = 0; i<cf_num - 1; i++)
  122. {
  123. for (j = 0; j<nx; j++)
  124. {
  125. infile >> OShift[i*nx + j];
  126. //fscanf(fpt, "%Lf", &OShift[i*nx + j]);
  127. }
  128. //fscanf(fpt, "%*[^\n]%*c");
  129. }
  130. for (j = 0; j<nx; j++)
  131. {
  132. infile >> OShift[(cf_num - 1)*nx + j];
  133. //fscanf(fpt, "%Lf", &OShift[(cf_num - 1)*nx + j]);
  134. }
  135. }
  136. infile.close();
  137. //fclose(fpt);
  138. /* Load Shuffle_data */
  139. if (func_num >= 11 && func_num <= 20)
  140. {
  141. sprintf(FileName, "D:/BJTU/CPP/Pso/AILearning-master/SingleObjectiveOpt/input_data/shuffle_data_%d_D%d.txt", func_num, nx);
  142. infile.open(FileName);
  143. //fpt = fopen(FileName, "r");
  144. if (!infile)
  145. {
  146. printf("\n Error: Cannot open input file for reading \n");
  147. }
  148. SS = (int *)malloc(nx * sizeof(int));
  149. if (SS == NULL)
  150. printf("\nError: there is insufficient memory available!\n");
  151. for (i = 0; i<nx; i++)
  152. {
  153. infile >> SS[i];
  154. cout << "Shuffle->" << SS[i];
  155. //fscanf(fpt, "%d", &SS[i]);
  156. }
  157. infile.close();
  158. //fclose(fpt);
  159. }
  160. else if (func_num == 29 || func_num == 30)
  161. {
  162. sprintf(FileName, "D:/BJTU/CPP/Pso/AILearning-master/SingleObjectiveOpt/input_data/shuffle_data_%d_D%d.txt", func_num, nx);
  163. infile.open(FileName);
  164. //fpt = fopen(FileName, "r");
  165. if (!infile)
  166. {
  167. printf("\n Error: Cannot open input file for reading \n");
  168. }
  169. SS = (int *)malloc(nx*cf_num * sizeof(int));
  170. if (SS == NULL)
  171. printf("\nError: there is insufficient memory available!\n");
  172. for (i = 0; i<nx*cf_num; i++)
  173. {
  174. infile >> SS[i];
  175. //fscanf(fpt, "%d", &SS[i]);
  176. }
  177. infile.close();
  178. //fclose(fpt);
  179. }
  180. n_flag = nx;
  181. func_flag = func_num;
  182. ini_flag = 1;
  183. }
  184. double functions(vector<double> v, int func_num,int dimension) {
  185. double* x = (double *)malloc(dimension * sizeof(double));
  186. for (int i = 0; i<dimension; i++)
  187. x[i] = v[i];
  188. int nx = dimension;
  189. //qDebug()<<nx;
  190. double result = 0;
  191. if (func_num>0 && func_num <= 30)
  192. {
  193. switch (func_num)
  194. {
  195. case 1:
  196. F1(x, &result, nx, OShift, M, 1, 1);
  197. break;
  198. case 2:
  199. F2(x, &result, nx, OShift, M, 1, 1);
  200. break;
  201. case 3:
  202. F3(x, &result, nx, OShift, M, 1, 1);
  203. break;
  204. case 4:
  205. F4(x, &result, nx, OShift, M, 1, 1);
  206. break;
  207. case 5:
  208. F5(x, &result, nx, OShift, M, 1, 1);
  209. break;
  210. case 6:
  211. F6(x, &result, nx, OShift, M, 1, 1);
  212. break;
  213. case 7:
  214. F7(x, &result, nx, OShift, M, 1, 1);
  215. break;
  216. case 8:
  217. F8(x, &result, nx, OShift, M, 1, 1);
  218. break;
  219. case 9:
  220. F9(x, &result, nx, OShift, M, 1, 1);
  221. break;
  222. case 10:
  223. F10(x, &result, nx, OShift, M, 1, 1);
  224. break;
  225. case 11:
  226. F11(x, &result, nx, OShift, M, 1, 1);
  227. break;
  228. case 12:
  229. F12(x, &result, nx, OShift, M, 1, 1);
  230. break;
  231. case 13:
  232. F13(x, &result, nx, OShift, M, 1, 1);
  233. break;
  234. case 14:
  235. F14(x, &result, nx, OShift, M, 1, 1);
  236. break;
  237. case 15:
  238. F15(x, &result, nx, OShift, M, 1, 1);
  239. break;
  240. default:
  241. printf("\nError: There are only 30 test functions in this test suite!\n");
  242. result = 0.0;
  243. break;
  244. }
  245. return result;
  246. }
  247. }
  248. void F1(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag) /* Sphere */
  249. {
  250. int i;
  251. f[0] = 0.0;
  252. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  253. for (i = 0; i<nx; i++)
  254. {
  255. f[0] += z[i] * z[i];
  256. }
  257. }
  258. void F2(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  259. {
  260. int i;
  261. f[0] = 0.0;
  262. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  263. double temp = 1;
  264. for (i = 0; i < nx; i++) {
  265. temp *= fabs(z[i]);
  266. }
  267. for (auto i = 0; i < nx; i++) {
  268. f[0] += fabs(z[i]);
  269. }
  270. f[0] = f[0] + temp;
  271. }
  272. void F3(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  273. {
  274. f[0] = 0.0;
  275. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  276. double temp = 0;
  277. for (auto i = 0; i < nx; i++) {
  278. for (auto j = 0; j < i; j++) {
  279. temp += z[i];
  280. }
  281. f[0]+= pow(temp, 2);
  282. }
  283. }
  284. void F4(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  285. {
  286. f[0] = 0.0;
  287. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  288. f[0] = abs(z[0]);
  289. for (auto i = 1; i < nx; i++) {
  290. if (abs(z[i]) > f[0] )
  291. f[0] = abs(z[i]);
  292. }
  293. }
  294. void F5(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  295. {
  296. f[0] = 0.0;
  297. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  298. f[0] = 10 * (100 * pow((z[1] - pow(z[0], 2)), 2) + pow(z[0] - 1, 2));
  299. }
  300. void F6(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  301. {
  302. f[0] = 0.0;
  303. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  304. for (auto i = 0; i <nx; i++) {
  305. f[0] += pow(floor(z[i] + 0.5), 2);
  306. }
  307. }
  308. void F7(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  309. {
  310. f[0] = 0.0;
  311. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  312. for (auto i = 0; i < nx; i++) {
  313. f[0] += ((i + 1) * pow(z[i], 4) + (rand() % (1 - 0)) + 0);
  314. }
  315. }
  316. void F8(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  317. {
  318. f[0] = 0.0;
  319. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  320. for(auto i=0;i<nx;i++)
  321. {
  322. f[0]+=(z[i] * sin(sqrt(abs(z[i]))));
  323. }
  324. f[0]=-f[0];
  325. }
  326. void F9(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  327. {
  328. f[0] = 0.0;
  329. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  330. f[0] = 10 * (pow(z[0], 2) - 10 * cos(2 * PI *z[0]) + 10);
  331. }
  332. void F10(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  333. {
  334. f[0] = 0.0;
  335. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  336. float temp1 = 0, temp2 = 0;
  337. for (auto i = 0; i < nx; i++) {
  338. temp1 += pow(z[i], 2);
  339. temp2 += cos(2 * PI * z[i]);
  340. }
  341. f[0] += (-20 * exp(-0.2 * sqrt(temp1 / nx)) - exp(temp2 / nx) + 20 + E);
  342. }
  343. void F11(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  344. {
  345. f[0] = 0.0;
  346. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  347. float temp1 = 0, temp2 = 1;
  348. for (auto i = 0; i < nx; i++) {
  349. temp1 += pow(z[i], 2);
  350. temp2 *= cos(z[i] / sqrt(i + 1));
  351. }
  352. f[0]= temp1 / 4000 - temp2 + 1;
  353. }
  354. void F12(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  355. {
  356. f[0] = 0.0;
  357. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  358. float y[10] = {0};
  359. for (auto i = 0; i < nx; i++) {
  360. y[i] = 1 + (z[i] + 1) / 4;
  361. }
  362. float temp = 0;
  363. for (auto i = 0; i < nx - 1; i++) {
  364. temp += pow(y[i] - 1, 2) * (1 + 10 * pow(sin(PI * y[i + 1]), 2));
  365. }
  366. f[0] = (10 * pow(sin(PI * y[0]), 2) + temp + pow(y[nx - 1], 2)) * PI / nx;
  367. for (auto i = 0; i < nx; i++) {
  368. f[0] +=(z[i] > 10 ? 100 * pow((z[i] - 10), 4) : z[i] < -10 ? 100 * pow((-z[i] - 10), 4): 0);
  369. }
  370. }
  371. void F13(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  372. {
  373. f[0] = 0.0;
  374. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  375. float temp = 0;
  376. for (auto i = 0; i < nx; i++) {
  377. temp += pow(z[i] - 1, 2) * (1 + pow(sin(3 * PI *z[i]) + 1, 2));
  378. }
  379. f[0] = 0.1 * (pow(sin(3 * PI * z[0]), 2) + temp +
  380. pow(z[nx - 1] - 1, 2) * (1 + pow(sin(2 * PI * z[nx - 1]), 2)));
  381. for (auto i = 0; i < nx; i++) {
  382. f[0] +=
  383. (z[i] > 5 ? 100 * pow((z[i] - 5), 4) : z[i] < -5 ? 100 * pow((-z[i] - 5), 4)
  384. : 0);
  385. }
  386. }
  387. void F14(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  388. {
  389. f[0] = 0.0;
  390. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  391. float temp = 0;
  392. int matrix[2][25] = {{-32, 16, 0, 16, 32, -32, -16, 0, 16, 32, -32, -16, 0, 16, 32, -32, -16, 0, 16, 32, -32, -16, 0, 16, 32},
  393. {-32, -32, -32, -32, -32, -16, -16, -16, -16, -16, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 32, 32, 32, 32, 32}};
  394. for (auto j = 0; j < 25; j++) {
  395. float _temp = 0;
  396. for (auto i = 0; i < nx; i++) {
  397. _temp += pow(z[i] - matrix[i][j], 6);
  398. }
  399. temp += (1 / (j + 1 + _temp));
  400. }
  401. f[0] = pow(1 / 500 + temp, -1);
  402. }
  403. void F15(double *x, double *f, int nx, double *Os, double *Mr, int s_flag, int r_flag)
  404. {
  405. f[0] = 0.0;
  406. sr_func(x, z, nx, Os, Mr, 1.0, s_flag, r_flag); /* shift and rotate */
  407. float a[11] = {0.1957, 0.1947, 0.1735, 0.16, 0.0844, 0.0627, 0.0456, 0.0342, 0.0323, 0.0235, 0.0246};
  408. float b[11] = {0.25, 0.5, 1, 2, 4, 6, 8, 10, 12, 14, 16};
  409. for (auto i = 0; i < 11; i++) {
  410. f[0] += pow(a[i] - (z[0] * (pow(1 / b[i], 2) + 1 / b[i] * z[1])) /
  411. (pow(1 / b[i], 2) + 1 / b[i] * z[2] + z[3]), 2);
  412. }
  413. }
  414. void shiftfunc(double *x, double *xshift, int nx, double *Os)
  415. {
  416. int i;
  417. for (i = 0; i<nx; i++)
  418. {
  419. xshift[i] = x[i] - Os[i];
  420. }
  421. }
  422. void rotatefunc(double *x, double *xrot, int nx, double *Mr)
  423. {
  424. int i, j;
  425. for(i=0;i<nx;i++)xrot[i] = 0;
  426. for (i = 0; i<nx; i++)
  427. {
  428. for (j = 0; j<nx; j++)
  429. {
  430. xrot[i] = xrot[i] + x[j] * Mr[i*nx + j];
  431. }
  432. }
  433. }
  434. void sr_func(double *x, double *sr_x, int nx, double *Os, double *Mr, double sh_rate, int s_flag, int r_flag) /* shift and rotate */
  435. {
  436. int i;
  437. if (s_flag == 1)
  438. {
  439. if (r_flag == 1)
  440. {
  441. shiftfunc(x, y, nx, Os);
  442. for (i = 0; i<nx; i++)//shrink to the original search range
  443. {
  444. y[i] = y[i] * sh_rate;
  445. }
  446. rotatefunc(y, sr_x, nx, Mr);
  447. }
  448. else
  449. {
  450. shiftfunc(x, sr_x, nx, Os);
  451. for (i = 0; i<nx; i++)//shrink to the original search range
  452. {
  453. sr_x[i] = sr_x[i] * sh_rate;
  454. }
  455. }
  456. }
  457. else
  458. {
  459. if (r_flag == 1)
  460. {
  461. for (i = 0; i<nx; i++)//shrink to the original search range
  462. {
  463. y[i] = x[i] * sh_rate;
  464. }
  465. rotatefunc(y, sr_x, nx, Mr);
  466. }
  467. else
  468. for (i = 0; i<nx; i++)//shrink to the original search range
  469. {
  470. sr_x[i] = x[i] * sh_rate;
  471. }
  472. }
  473. }

Part 5 粒子群优化算法优劣


添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注