In C# I have written a genetic algorithm that creates geometry for a CAD program (Rhino). This algorithm is contained in a library and I have written a small windows forms plugin for the CAD program. A call to the GA.run() function will return a List which populates a ListBox and selecting an Item will generate the geometry in the CAD program.
In the windows forms application I create an instance of the GA class and by clicking the start button the various GA settings are gathered from the form and the GA.run() function is called. Now, as this is a genetic algorithm, it will run a number of generations before returning. However, I would like to have the option of stopping the function before it runs all generations. How can I stop the GA.run() function from within my plugin? When I hit the run button, the windows forms application "pauses" until GA.run() returns its List...
I guess there is a better way of calling GA.run()? ..
stop button code:
private void runBtn_Click(object sender, EventArgs e)
{
// get rule settings
SettingsHolder gaSettings = new SettingsHolder();
gaSettings.GenMaxrun = (int)gensNUD.Value;
..
gaAlgo = new GA(algoSettings);
try
{
currentPopulation = paretoAlgo.run();
}
catch(Exception e)
{
MessageBox.Show("exc while trying run: " + e);
}
// iterate list and list in form
popLB.Items.Clear();
foreach (Chromosome c in currentPopulation)
{
popLB.Items.Add(new KeyValuePair<String, int> (c.present(), id));
}
}
GA.run():
public List<Chromosome> run()
{
try
{
initPop();
// loop until genMaxrun or no new achieved
do
{
// create geometries from chromosomes
foreach (Chromosome chromo in population)
{
chromo.embryogeny(Settings);
}
// step 2:Fitness
// union the population and archive
unionPop = new List<Chromosome>(population);
unionPop.AddRange(archive);
calculateDomination(unionPop);
foreach(Chromosome chromo in unionPop)
{
chromo.calculateRawFitness(unionPop);
chromo.calculateDensity(unionPop);
chromo.setFitness();
}
environmentalSelection();
// increase Generation +1
generation += 1;
// create new population...
population = reproduction(generation);
}
while (generation < Settings.GenMaxrun);
}
catch (Exception e)
{
throw new Exception("Error in SPEA run", e);
}
return archive;
}
Is there a way to add a check within the while-loop of run()? Can a stop button click event in the forms application change a parameter of GA (as it is executing the run() function) and the run() function will abort? Or can I make a check from the GA.run() to a parameter in the caller? Or do I need to use threads?
Let me know if I need to explain something more accurately.
Cheers, Eirik