public ApproximationWrap(double[,] data, int functionsSet, int populationSize, int geneticMethod, int selectionMethod, float minRange, float lengthRange) { _data = data; // create fitness function SymbolicRegressionFitness fitness = new SymbolicRegressionFitness(data, constants); // create gene function IGPGene gene = (functionsSet == 0) ? (IGPGene) new SimpleGeneFunction(6) : (IGPGene) new ExtendedGeneFunction(6); // create population Population = new Population(populationSize, (geneticMethod == 0) ? (IChromosome) new GPTreeChromosome(gene) : (IChromosome) new GEPChromosome(gene, 15), fitness, (selectionMethod == 0) ? (ISelectionMethod) new EliteSelection() : (selectionMethod == 1) ? (ISelectionMethod) new RankSelection() : (ISelectionMethod) new RouletteWheelSelection()); // solution array solution = new double[50, 2]; // calculate X values to be used with solution function for (int j = 0; j < 50; j++) { solution[j, 0] = minRange + (double)j * lengthRange / 49; } }
// Worker thread void SearchSolution() { // create fitness function var fitness = new SymbolicRegressionFitness(data, new double[] { 1, 2, 3, 5, 7 }); // create gene function var gene = (functionsSet == 0) ? new SimpleGeneFunction(6) : (IGPGene) new ExtendedGeneFunction(6); // create population var population = new Population(populationSize, (geneticMethod == 0) ? new GPTreeChromosome(gene) : (IChromosome) new GEPChromosome(gene, 15), fitness, (selectionMethod == 0) ? new EliteSelection() : (selectionMethod == 1) ? new RankSelection() : (ISelectionMethod) new RouletteWheelSelection() ); // iterations var i = 1; // solution array var solution = new double[50, 2]; var input = new double[6] { 0, 1, 2, 3, 5, 7 }; // calculate X values to be used with solution function for (var j = 0; j < 50; j++) { solution[j, 0] = chart.RangeX.Min + (double)j * chart.RangeX.Length / 49; } // loop while (!needToStop) { // run one epoch of genetic algorithm population.RunEpoch(); try { // get best solution var bestFunction = population.BestChromosome.ToString(); // calculate best function for (var j = 0; j < 50; j++) { input[0] = solution[j, 0]; solution[j, 1] = PolishExpression.Evaluate(bestFunction, input); } chart.UpdateDataSeries("solution", solution); // calculate error var error = 0.0; for (int j = 0, k = data.GetLength(0); j < k; j++) { input[0] = data[j, 0]; error += Math.Abs(data[j, 1] - PolishExpression.Evaluate(bestFunction, input)); } // set current iteration's info SetText(currentIterationBox, i.ToString()); SetText(currentErrorBox, error.ToString("F3")); } catch { // remove any solutions from chart in case of any errors chart.UpdateDataSeries("solution", null); } // increase current iteration i++; // if ((iterations != 0) && (i > iterations)) { break; } } // show solution SetText(solutionBox, population.BestChromosome.ToString()); // enable settings controls EnableControls(true); }