Skip to content

Instantly share code, notes, and snippets.

@adamstirtan
Created March 16, 2024 14:55
Show Gist options
  • Select an option

  • Save adamstirtan/815bce42623aca994ba9f887750ac80b to your computer and use it in GitHub Desktop.

Select an option

Save adamstirtan/815bce42623aca994ba9f887750ac80b to your computer and use it in GitHub Desktop.
ParticleSwarmSharp Quickstart
IRandomization random = new BasicRandomization();
int populationSize = 25;
int dimensions = 1;
double minX = -10;
double maxX = 10;
var particles = new List<IParticle>();
for (int i = 0; i < populationSize; i++)
{
ClassicParticle particle = new(dimensions)
{
Position = random.GetDoubles(dimensions, minX, maxX),
Velocity = random.GetDoubles(dimensions, 0, 1)
};
particles.Add(particle);
}
IPopulation population = new Population(particles);
IFitness fitness = new FuncFitness(candidate =>
{
double x = candidate.Position[0];
return Math.Pow(x, 2);
});
IParticleSwarm pso = new ParticleSwarm(
population,
fitness,
new FitnessStagnationTermination(20));
pso.BestParticleChanged += (sender, e) =>
{
Console.WriteLine(e.ToString());
};
pso.GenerationComplete += (sender, e) =>
{
Console.WriteLine(e.ToString());
};
pso.TerminationReached += (sender, e) =>
{
Console.WriteLine(e.ToString());
};
pso.Stopped += (sender, e) =>
{
Console.WriteLine(e.ToString());
};
pso.Start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment