Skip to content

Commit

Permalink
Fixed localbest in parallel computing
Browse files Browse the repository at this point in the history
  • Loading branch information
Bqrry4 committed Jan 16, 2024
1 parent 0057e99 commit 4371d96
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions PSOClusteringAlgorithm/PSOClusteringAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,12 @@ public IParticle RunPSO()
});


//social best
IParticle sbest = null;
//if GBest is choosen
//social global best
IParticle gbest = null;
//if GBest is choosen -> init
if (VicinitySize == 0)
{
sbest = Particles.Aggregate((min, current) => min.Cost < current.Cost ? min : current).Clone();
gbest = Particles.Aggregate((min, current) => min.Cost < current.Cost ? min : current).Clone();
}

//needed for the random factor
Expand All @@ -211,14 +211,20 @@ public IParticle RunPSO()

for (int t = 0; t < tmax; t++)
{

//needed to check convergency
int particlesStillMoving = 0;
//foreach (var particle in Particles)
Parallel.ForEach(Particles, (particle, state, particleIndex) =>
{
//social best
IParticle sbest;
//find best in particle's vicinity
if (VicinitySize != 0)
if (gbest != null)
{
sbest = gbest;
}
else //search in vicinity
{
mux.WaitOne();
sbest = GetBestInParticleVicinity((int)particleIndex);
Expand Down Expand Up @@ -272,11 +278,11 @@ public IParticle RunPSO()
//updating right away when gbest
if (VicinitySize == 0)
{
//updating sbest
//updating gbest
mux.WaitOne();
if (particle.Cost < sbest.Cost)
if (particle.Cost < gbest.Cost)
{
sbest = particle.Clone();
gbest = particle.Clone();
}
mux.ReleaseMutex();
}
Expand All @@ -289,8 +295,13 @@ public IParticle RunPSO()
break;
}
}
//solution is sbest
return sbest;

return VicinitySize == 0 ?
//solution is gbest
gbest :
//solution is the best particle in swarm
Particles.Aggregate((min, current) => min.Cost < current.Cost ? min : current).Clone();

}

}
Expand Down

0 comments on commit 4371d96

Please sign in to comment.