protected override double GetSwapImprovement(int i, int j) { var original = GetCost(); var originalSolution = Solution.ToList(); var swapper = new SwapOp { Index1 = i, Index2 = j }; swapper.Swap(Solution); var newCost = GetCost(); Solution = originalSolution.ToArray(); return(original - newCost); }
public void Update() { var gBest = _particles.MinBy(a => _calculatePerformance(a.BestPosition)).BestPosition.ToList(); Solution = gBest.ToArray(); Cost = _calculatePerformance(Solution); Parallel.ForEach(_particles, particle => //foreach (var particle in _particles) { var myGbestList = gBest.ToList(); var tempVelocities = new List <SwapOp>(); for (var i = 0; i < _solutionLength; i++) { if (particle.Position[i] != particle.BestPosition[i]) { var swap = new SwapOp { Probability = Alpha, Index1 = i, Index2 = particle.BestPosition.ToList().IndexOf(particle.Position[i]) }; if (swap.Index2 == -1) { var x = 0; } tempVelocities.Add(swap); swap.Swap(particle.BestPosition); } if (particle.Position[i] != myGbestList[i]) { var swap = new SwapOp { Probability = Beta, Index1 = i, Index2 = myGbestList.IndexOf(particle.Position[i]) }; if (swap.Index2 == -1) { var x = 0; } tempVelocities.Add(swap); swap.Swap(particle.BestPosition); } } foreach (var tempVelocity in tempVelocities) { if (Program.GetRN() < tempVelocity.Probability) { tempVelocity.Swap(particle.Position); } } var cost = _calculatePerformance(particle.Position); var bestCost = _calculatePerformance(particle.BestPosition); if (cost < bestCost) { particle.Position.CopyTo(particle.BestPosition, 0); } }); }