public static double Simulate(Specimen spec) { var fkf = spec.ToFedKf(); var meas = new double[4]; var n = DirectCosinsMatrix; //var nt = n.Transpose(); //var c = SensorsOutputCovariances.Inverse(); //var pseudoInverse = (nt * n).Inverse() * nt; var err = 0.0; int lng = Math.Min(Signals.RowCount, MaxSimLength); var results = new Vector3[lng]; results[0] = new Vector3 { X = 0.0, Y = 0.0, Z = 0.0 }; for (int i = 0; i < lng; i++) { var sigRow = Signals.Row(i); var noiseRow = Noises.Row(i); var targRow = Targets.Row(i); meas[0] = sigRow[0] + noiseRow[0]; meas[1] = sigRow[1] + noiseRow[1]; meas[2] = sigRow[2] + noiseRow[2]; meas[3] = sigRow[3] + noiseRow[3]; DenseMatrix inps; if (i > 0) { inps = n * results[i - 1].ToMatrix(); } else { inps = new DenseMatrix(4, 1, 0.0); } var res = fkf.Step(meas, inps.ToColumnWiseArray()); var errs = new double[] { res[0, 0] - targRow[0], res[1, 0] - targRow[1], res[2, 0] - targRow[2] }; err += (errs[0] * errs[0]) + (errs[1] * errs[1]) + (errs[2] * errs[2]); results[i] = new Vector3 { X = res[0, 0], Y = res[1, 0], Z = res[2, 0] }; if (PrintSimResults) { Console.WriteLine(res.ToColumnWiseArray().Print()); } if (double.IsNaN(err)) { return double.NaN; } } if (PrintSimResults) { FileParser.Write3ColonFile(@"Data\Evaluations1000.csv", results); } return 1/err*lng; }
private void Initiation() { Console.WriteLine("\n=== Starting Initiation ==="); Console.WriteLine("Population Size: {0};\nGenome Size: {1};\nGene Value Range: [{2}; {3}]\n\n", this.PopulationSize, this.GenomeSize, Specimen.MinGeneValue, Specimen.MaxGeneValue); _currGeneration = new List <Specimen>(); var newSpecies = Enumerable.Range(0, PopulationSize).AsParallel().Select(i => { var newSpec = new Specimen { Length = this.GenomeSize }; SpecimenHelper.GenerateGenes(ref newSpec); var fitness = FitnessFunction(newSpec); // FIXME: Replace '1e5' magic number with well described constant newSpec.Fitness = double.IsNaN(fitness) ? 0 : (double.IsInfinity(fitness) ? 1e5 : fitness); Console.WriteLine("Specimen {1} has Fitness: {0}", newSpec.Fitness, i); return(newSpec); }).OrderBy(s => s.Fitness).Take(this.PopulationSize); _currGeneration = newSpecies.ToList(); // Huge load starts here :) _fitnessTable = new List <double>(); foreach (var spec in _currGeneration) { if (!_fitnessTable.Any()) { _fitnessTable.Add(spec.Fitness); } else { _fitnessTable.Add(_fitnessTable.Last() + spec.Fitness); } } TotalFitness = _currGeneration.Sum(spec => spec.Fitness); var best = _currGeneration.Last(); Console.WriteLine("=== Initiation Result ===\n"); Console.WriteLine("Best Specimen:\n{0}", best.Print()); }
private void ShowBestOfAllTime(List <List <Specimen> > generations, PopulationSetting population) { Specimen best = null; Specimen worst = null; int bestGeneration = 0; int worstGeneration = 0; var bestList = new List <Specimen>(); var tempList = new List <Specimen>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < generations.Count; i++) { tempList = generations[i]; tempList.Sort((a, b) => population.FittingFunction(a).CompareTo(population.FittingFunction(b))); bestList.Add(tempList[0]); } for (int i = 0; i < bestList.Count; i++) { best = bestList[0]; worst = bestList[1]; if (population.FittingFunction(bestList[i]) < population.FittingFunction(best)) { best = bestList[i]; bestGeneration = i; } if (population.FittingFunction(bestList[i]) > population.FittingFunction(worst)) { worst = bestList[i]; worstGeneration = i; } } sb.Append("\n\nВывод\n"); sb.Append("Лучший из всех в поколении №" + (bestGeneration + 1) + ": " + best + "\n Значение функции: " + population.FittingFunction(best) + "\n\n"); sb.Append("Худший из всех в поколении №" + (worstGeneration + 1) + ": " + worst + "\n Значение функции: " + population.FittingFunction(worst) + "\n"); Console.WriteLine(sb); }
private void Selection() { var tempGenerationContainer = new ConcurrentBag <Specimen>(); if (this.Elitism) { var elite = _currGeneration.Last(); tempGenerationContainer.Add(elite); } for (int i = 0; i < this.PopulationSize / 2.5; i++) { int pidx1 = this.PopulationSize - i - 1; int pidx2 = pidx1; while (pidx1 == pidx2 || _currGeneration[pidx1].IsSimilar(_currGeneration[pidx2])) { pidx2 = RouletteSelection(); } var parent1 = _currGeneration[pidx1].Mutate(); var parent2 = _currGeneration[pidx2].Mutate(); //Console.WriteLine("Selected Species {0} and {1}", pidx1, pidx2); var children = Rnd.NextDouble() < this.CrossoverRate ? parent1.Crossover(parent2) : new List <Specimen> { _currGeneration[pidx1], _currGeneration[pidx2] }; foreach (var ch in children.AsParallel()) { if (double.IsNaN(ch.Fitness)) { var fitness = FitnessFunction(ch); var newChild = new Specimen { Genes = ch.Genes, Length = ch.Length, Fitness = double.IsNaN(fitness) ? 0 : (double.IsInfinity(fitness) ? 1e5 : fitness) }; tempGenerationContainer.Add(newChild); } else { tempGenerationContainer.Add(ch); } } } _currGeneration = tempGenerationContainer.OrderByDescending(s => s.Fitness).Take(this.PopulationSize).Reverse().ToList(); _fitnessTable = new List <double>(); foreach (var spec in _currGeneration) { if (!_fitnessTable.Any()) { _fitnessTable.Add(spec.Fitness); } else { _fitnessTable.Add(_fitnessTable.Last() + spec.Fitness); } } TotalFitness = _currGeneration.Sum(spec => spec.Fitness); Console.WriteLine("=== Selection Result ===\n\n"); Console.WriteLine("\n--- Top 5 ---"); var best = _currGeneration.Last(); Console.WriteLine("Best Specimen:\n{0}\n", best.Print()); int j = 1; foreach (var spec in _currGeneration.AsEnumerable().Reverse().Take(5).Skip(1)) { Console.WriteLine("Specimen {0} has Fitness: {1}\n", j++, spec.Fitness); // FIXME: Printout Genes } Console.WriteLine("Average Fitness: {0}\n", TotalFitness / PopulationSize); }
static void Main(string[] args) { if (args.Length > 0) { var cmd = args[0].ToLower(CultureInfo.InvariantCulture); switch (cmd) { case "simulate": case "simulation": InitializeSimulator(); FedKfSim.PrintSimResults = true; var spec = new Specimen(); SpecimenHelper.SetGenes(ref spec, ReadSimulationGenes()); FedKfSim.Simulate(spec); break; case "set": var settingName = args[1]; var settingValue = args[2]; var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings[settingName].Value = settingValue; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); Console.WriteLine("'{0}' set to {1}", settingName, settingValue); break; case "print": Console.WriteLine("Current settings:"); foreach (var name in ConfigurationManager.AppSettings.AllKeys.AsParallel()) { var value = ConfigurationManager.AppSettings[name]; Console.WriteLine("'{0}' => {1}", name, value); } break; case "help": case "?": case "-h": PrintHelp(); break; default: Console.Error.WriteLine(string.Format("\nARGUMENT ERROR\n'{0}' is unknown command!\n", cmd)); PrintHelp(); break; } } else { InitializeSimulator(); var genCount = int.Parse(ConfigurationManager.AppSettings["GenerationsCount"]); var popSize = int.Parse(ConfigurationManager.AppSettings["PopulationSize"]); var crossOver = double.Parse(ConfigurationManager.AppSettings["CrossoverRate"], FileParser.NumberFormat); var mutRate = double.Parse(ConfigurationManager.AppSettings["MutationRate"], FileParser.NumberFormat); var maxGeneVal = double.Parse(ConfigurationManager.AppSettings["MaxGeneValue"], FileParser.NumberFormat); var minGeneVal = double.Parse(ConfigurationManager.AppSettings["MinGeneValue"], FileParser.NumberFormat); var genomeLength = int.Parse(ConfigurationManager.AppSettings["GenomeLength"]); SpecimenHelper.SimilarityThreshold = double.Parse( ConfigurationManager.AppSettings["SimilarityThreshold"], FileParser.NumberFormat); var ga = new Ga(genomeLength) { FitnessFunction = FedKfSim.Simulate, Elitism = true, GenerationsCount = genCount, PopulationSize = popSize, CrossoverRate = crossOver, MutationRate = mutRate }; FedKfSim.PrintSimResults = false; ga.Go(maxGeneVal, minGeneVal); } Console.ReadLine(); }
private void Selection() { var tempGenerationContainer = new ConcurrentBag<Specimen>(); if (this.Elitism) { var elite = _currGeneration.Last(); tempGenerationContainer.Add(elite); } for (int i = 0; i < this.PopulationSize / 2.5; i++) { int pidx1 = this.PopulationSize - i - 1; int pidx2 = pidx1; while (pidx1 == pidx2 || _currGeneration[pidx1].IsSimilar(_currGeneration[pidx2])) { pidx2 = RouletteSelection(); } var parent1 = _currGeneration[pidx1].Mutate(); var parent2 = _currGeneration[pidx2].Mutate(); //Console.WriteLine("Selected Species {0} and {1}", pidx1, pidx2); var children = Rnd.NextDouble() < this.CrossoverRate ? parent1.Crossover(parent2) : new List<Specimen> { _currGeneration[pidx1], _currGeneration[pidx2] }; foreach (var ch in children.AsParallel()) { if (double.IsNaN(ch.Fitness)) { var fitness = FitnessFunction(ch); var newChild = new Specimen { Genes = ch.Genes, Length = ch.Length, Fitness = double.IsNaN(fitness) ? 0 : (double.IsInfinity(fitness) ? 1e5 : fitness) }; tempGenerationContainer.Add(newChild); } else { tempGenerationContainer.Add(ch); } } } _currGeneration = tempGenerationContainer.OrderByDescending(s => s.Fitness).Take(this.PopulationSize).Reverse().ToList(); _fitnessTable = new List<double>(); foreach (var spec in _currGeneration) { if (!_fitnessTable.Any()) { _fitnessTable.Add(spec.Fitness); } else { _fitnessTable.Add(_fitnessTable.Last() + spec.Fitness); } } TotalFitness = _currGeneration.Sum(spec => spec.Fitness); Console.WriteLine("=== Selection Result ===\n\n"); Console.WriteLine("\n--- Top 5 ---"); var best = _currGeneration.Last(); Console.WriteLine("Best Specimen:\n{0}\n", best.Print()); int j = 1; foreach (var spec in _currGeneration.AsEnumerable().Reverse().Take(5).Skip(1)) { Console.WriteLine("Specimen {0} has Fitness: {1}\n", j++, spec.Fitness); // FIXME: Printout Genes } Console.WriteLine("Average Fitness: {0}\n", TotalFitness/PopulationSize); }
private void Initiation() { Console.WriteLine("\n=== Starting Initiation ==="); Console.WriteLine("Population Size: {0};\nGenome Size: {1};\nGene Value Range: [{2}; {3}]\n\n", this.PopulationSize, this.GenomeSize, Specimen.MinGeneValue, Specimen.MaxGeneValue); _currGeneration = new List<Specimen>(); var newSpecies = Enumerable.Range(0, PopulationSize).AsParallel().Select(i => { var newSpec = new Specimen { Length = this.GenomeSize }; SpecimenHelper.GenerateGenes(ref newSpec); var fitness = FitnessFunction(newSpec); // FIXME: Replace '1e5' magic number with well described constant newSpec.Fitness = double.IsNaN(fitness) ? 0 : (double.IsInfinity(fitness) ? 1e5 : fitness); Console.WriteLine("Specimen {1} has Fitness: {0}", newSpec.Fitness, i); return newSpec; }).OrderBy(s => s.Fitness).Take(this.PopulationSize); _currGeneration = newSpecies.ToList(); // Huge load starts here :) _fitnessTable = new List<double>(); foreach (var spec in _currGeneration) { if (!_fitnessTable.Any()) { _fitnessTable.Add(spec.Fitness); } else { _fitnessTable.Add(_fitnessTable.Last() + spec.Fitness); } } TotalFitness = _currGeneration.Sum(spec => spec.Fitness); var best = _currGeneration.Last(); Console.WriteLine("=== Initiation Result ===\n"); Console.WriteLine("Best Specimen:\n{0}", best.Print()); }
abstract public Specimen CrossoverWith(Specimen secondParent);
public override Specimen CrossoverWith(Specimen secondParent) { return(new ArithmeticSpecimen(this, secondParent as ArithmeticSpecimen)); }