/// <summary> /// Returns the distance to provided particle. /// </summary> /// <param name="particle"></param> /// <returns></returns> public double DistanceTo(Particle particle) { // Construct words bool[] currentParticleWord = CompressAutomatonRepresentation(Position.OnePositions); bool[] anotherParticleWord = CompressAutomatonRepresentation(particle.Position.OnePositions); return currentParticleWord.Where((t, i) => t != anotherParticleWord[i]).Count(); }
public void MoveParticleTest() { Position bestPosition = new Position(3, 4, 23) { OnePositions = new[,] { { 1, 1, 3, 1 }, { 2, 1, 3, 2 }, { 2, 1, 2, 2 } } }; List<string> wordsSet = new List<string>(); wordsSet.Add("012"); TargetFunction f = new TargetFunction(new Automaton(bestPosition), wordsSet, wordsSet); Particle firstParticle = new Particle(3, 4) { Position = bestPosition }; firstParticle.MoveParticle(bestPosition, 2, 2); Assert.AreEqual(firstParticle.Position.CompareTo(bestPosition), 0); }
public void DistanceToTest() { // Arrange Particle firstParticle = new Particle(3, 2) { Position = { OnePositions = new[,] { { 1, 0 }, { 1, 0 }, { 0, 1 } } } }; Particle secondParticle = new Particle(3, 2) { Position = { OnePositions = new[,] { { 0, 1 }, { 1, 0 }, { 0, 1 } } } }; // Act double distance = firstParticle.DistanceTo(secondParticle); // Assert Assert.AreEqual(4, distance); }
private Automaton GetBestAutomatonFromSpace(int numberOfStates) { Position bestPositionSoFar = null; int lowestErrorSoFar = int.MaxValue; int c1, c2; int iteration = 0; Particle[] particles = new Particle[_particleNumber]; GenerateParticles(particles, numberOfStates); Position globalBest; // Possible changes c1 = c2 = 2; System.Console.WriteLine("PSO start!"); do { // Update global best globalBest = particles[0].PersonalBestPosition; foreach (Particle p in particles) if (p.PersonalBestPosition.CompareTo(globalBest) < 0) globalBest = p.PersonalBestPosition; // Move particles and check errors for (int i = 0; i < particles.Length; i++) { Particle p = particles[i]; p.MoveParticle(globalBest, c1, c2); if (p.timeSinceBestChanged > 3) p = particles[i] = new Particle(_alphabetCount, numberOfStates, i * (i % 2) + i + i * 3); int currentErrors = p.Position.TargetFunctionValue; if (currentErrors < lowestErrorSoFar) { Debug.WriteLine("Found better particle! Updating... {0} {1} {2}", numberOfStates, currentErrors, lowestErrorSoFar); lowestErrorSoFar = currentErrors; bestPositionSoFar = Position.DeepClone(p.Position); } } iteration++; System.Console.WriteLine("Next iteration {0}", iteration); } while (iteration < _maxIterationCount); return new Automaton(bestPositionSoFar); }
private void GenerateParticles(Particle[] particles, int stateCount) { for (int i = 0; i < particles.Length; i++) particles[i] = new Particle(_alphabetCount, stateCount, i * (i % 2) + i + i * 3); }