#include < ctime > #include < cstdlib > #include < memory > #define frand() ((double)rand()/(double)RAND_MAX) #define MAXLONG (2147483647) double * pso_optimization( int s, int p, int d, int T, double c1, double c2, double * vmax, double wmax, double wmin, double * domax, double * domin, CAL_FIT cal_fit, void * adds) ... { srand(time(NULL)); double *swm_v = (double*)malloc(s*p*d*sizeof(double)); double *swm_d = (double*)malloc(s*p*d*sizeof(double)); double *sbest = (double*)malloc(s*d*sizeof(double)); double *gbest = (double*)malloc(d*sizeof(double)); double *fswm_v = swm_v, *fswm_d = swm_d; memset(swm_v, 0, sizeof(swm_v)); double *fdomax = domax, *fdomin = domin, *fvmax = vmax; for (int i = 0; i < s; i++) for (int j = 0; j < p; j++) ...{ fdomax = domax; fdomin = domin; for (int k = 0; k < d; k++, fdomax++, fdomin++, fswm_d++) *fswm_d = (frand()*(*fdomax-*fdomin))+*fdomin; } double *fsbest = sbest, fitness = 0; double nowbest = 0, *nowidx = NULL; double nowsbest = 0, *nowsidx = NULL; double *ffsbest = NULL, *fgbest = NULL; double w = 0; for (int t = 0; t < T; t++) ...{ w = wmax-(double)t*(wmax-wmin)/(double)T; fswm_d = swm_d; fsbest = sbest; nowidx = NULL; nowbest = -MAXLONG; for (int i = 0; i < s; i++, fsbest+=d) ...{ nowsbest = -MAXLONG; nowsidx = NULL; for (int j = 0; j < p; j++, fswm_d+=d) ...{ fitness = cal_fit(fswm_d, d, adds); if (fitness >= nowsbest) ...{ nowsbest = fitness; nowsidx = fswm_d; } } memcpy(fsbest, nowsidx, d*sizeof(double)); if (nowsbest >= nowbest) ...{ nowbest = nowsbest; nowidx = fsbest; } } memcpy(gbest, nowidx, d*sizeof(double)); if (t >= T) break; fsbest = sbest; fswm_v = swm_v; fswm_d = swm_d; for (int i = 0; i < s; i++) ...{ for (int j = 0; j < p; j++) ...{ fgbest = gbest; ffsbest = fsbest; fdomax = domax; fdomin = domin; fvmax = vmax; for (int k = 0; k < d; k++, fgbest++, ffsbest++, fswm_v++, fswm_d++, fdomax++, fdomin++, fvmax++) ...{ *fswm_v = max(-*fvmax, min(*fswm_v*w+c1*frand()*(*ffsbest-*fswm_d)+c2*frand()*(*fgbest-*fswm_d), *fvmax)); *fswm_d = max(*fdomin, min(*fswm_d+*fswm_v, *fdomax)); } } fsbest = ffsbest; } } free(swm_v); free(swm_d); free(sbest); return gbest;}