public MathModel SynthesizeModel(Point[] trainingPoints)
        {
            var means = trainingPoints.Means();
            var standardDeviations = trainingPoints.StandardDeviations(means);

            if (Parameters.UseDataNormalization)
            {
                trainingPoints           = _pointsNormalizer.ApplyProcessing(trainingPoints);
                NormalizedTrainingPoints = trainingPoints.DeepCopyByExpressionTree();
            }

            var evolutionEnginesFactory = new EnginesFactory();
            var evolutionEngine         = evolutionEnginesFactory.Create(Parameters.EvolutionParameters);
            var positiveTrainingPoints  = trainingPoints.Where(tp => tp.ClassificationType == ClassificationType.Positive).ToArray();
            var negativeTrainingPoints  = trainingPoints.Where(tp => tp.ClassificationType == ClassificationType.Negative).ToArray();
            var evaluator = new Evaluator(positiveTrainingPoints, negativeTrainingPoints, _constraintsBuilder);

            //HACK TODO

            //var numberOfConstraintsCoefficients = Parameters.MaximumNumberOfConstraints * (Parameters.NumberOfDimensions + 1);
            //var constraintsCoefficients = new List<double>(numberOfConstraintsCoefficients);
            //var benchmarkConstraintsIndexer = 0;

            //for (var i = 0; i < Parameters.MaximumNumberOfConstraints; i++)
            //{
            //    if (benchmarkConstraintsIndexer >= Benchmark.Constraints.Length)
            //        benchmarkConstraintsIndexer = 0;

            //    constraintsCoefficients.AddRange(Benchmark.Constraints[benchmarkConstraintsIndexer].Terms.Select(t => t.Coefficient));
            //    constraintsCoefficients.Add(Benchmark.Constraints[benchmarkConstraintsIndexer++].LimitingValue);
            //}

            //PopulationGeneratorBase.ObjectCoefficients = constraintsCoefficients.ToArray();

            //

            Solution bestSolution;

            if (Parameters.UseSeeding)
            {
                var singleConstraintModel = Parameters.TypeOfBenchmark == BenchmarkType.Balln && Parameters.AllowQuadraticTerms
                    ? Benchmark.Constraints.Take(1).DeepCopyByExpressionTree().ToArray()
                    : new[] { new LinearConstraint(Benchmark.Constraints.First().Terms.Where(t => t.Type == TermType.Linear).ToArray(), 0) };
                var singleConstraintBuilder   = new ConstraintsBuilder(singleConstraintModel);
                var singleConstraintEvaluator = new Evaluator(positiveTrainingPoints, negativeTrainingPoints, singleConstraintBuilder);
                var seedingProcessor          = new SeedingProcessor(singleConstraintEvaluator, _constraintsBuilder, positiveTrainingPoints);

                bestSolution = evolutionEngine.RunEvolution(evaluator, seedingProcessor);
            }
            else
            {
                bestSolution = evolutionEngine.RunEvolution(evaluator);
            }

            CoreEvolutionSteps = evolutionEngine.EvolutionSteps;

            Statistics.EvolutionStatistics = evolutionEngine.Statistics;
            var synthesizedConstraints = _constraintsBuilder.BuildConstraints(bestSolution);

            if (Parameters.UseDataNormalization)
            {
                NormalizedSynthesizedConstraints = synthesizedConstraints.DeepCopyByExpressionTree();
                _constaintsDenormalizer          = new StandardScoreConstraintsDenormalizer(means, standardDeviations);
                synthesizedConstraints           = _constaintsDenormalizer.ApplyProcessing(synthesizedConstraints);
            }

            if (Parameters.TrackEvolutionSteps)
            {
                var evolutionStepsAsSolutions = evolutionEngine.EvolutionStepsSimple.ToList();

                foreach (var evolutionStepsAsSolution in evolutionStepsAsSolutions)
                {
                    var evolutionStep = _constraintsBuilder.BuildConstraints(evolutionStepsAsSolution);

                    if (Parameters.UseDataNormalization)
                    {
                        NormalizedEvolutionSteps.Add(evolutionStep.DeepCopyByExpressionTree());
                        evolutionStep = _constaintsDenormalizer.ApplyProcessing(evolutionStep);
                    }

                    EvolutionSteps.Add(evolutionStep);
                }
            }

            if (Parameters.UseRedundantConstraintsRemoving)
            {
                _stoper.Restart();
                synthesizedConstraints = _redundantConstraintsRemover.ApplyProcessing(synthesizedConstraints);
                _stoper.Stop();
                Statistics.RedundantConstraintsRemovingTime = _stoper.Elapsed;
            }

            MathModel = new MathModel(synthesizedConstraints, Benchmark);
            Statistics.NumberOfConstraints = synthesizedConstraints.Length;
            Statistics.MeanAngle           = Parameters.TypeOfBenchmark != BenchmarkType.Balln ? _meanAngleCalculator.Calculate(synthesizedConstraints, Benchmark.Constraints) : double.NaN;

            return(MathModel);
        }
예제 #2
0
        private static void RunExperiment(ExperimentParameters experimentParameters)//, DatabaseContext databaseX)
        {
            var database = new DatabaseContext(DatabaseFullPath);
            var version  = new Version(DateTime.Now);
            var stoper   = new Stopwatch();

            //if (database.Exists(experimentParameters))
            //{
            //    Console.WriteLine("BYLEM WIDZIALEM");
            //    //database.Dispose();
            //    return;
            //}

            database.Insert(version);
            database.Insert(experimentParameters);
            database.Insert(experimentParameters.EvolutionParameters);

            IDictionary <int, EvolutionStep> evolutionSteps = null;

            try
            {
                var enginesFactory = new EnginesFactory();

                var engine = enginesFactory.Create(experimentParameters);

                var distanceCalculator      = new CanberraDistanceCalculator();
                var positivePointsGenerator = new PositivePointsGenerator();
                stoper.Restart();
                var positiveTrainingPoints = positivePointsGenerator.GeneratePoints(experimentParameters.NumberOfPositivePoints, engine.Benchmark.Domains, engine.Benchmark.Constraints);
                stoper.Stop();
                engine.Statistics.PositiveTrainingPointsGenerationTime = stoper.Elapsed;

                var negativePointsGenerator = new NegativePointsGenerator(positiveTrainingPoints, distanceCalculator, new NearestNeighbourDistanceCalculator(distanceCalculator));
                //var negativeTrainingPoints = negativePointsGenerator.GeneratePoints(experimentParameters.NumberOfNegativePoints, engine.Benchmark.Domains);
                stoper.Restart();
                var negativeTrainingPoints = negativePointsGenerator.GeneratePoints(experimentParameters.NumberOfNegativePoints, engine.Benchmark.Domains, engine.Benchmark.Constraints);
                stoper.Stop();
                engine.Statistics.NegativeTrainingPointsGenerationTime = stoper.Elapsed;
                //Console.WriteLine("Evolution starts!");
                var trainingPoints = positiveTrainingPoints.Concat(negativeTrainingPoints).ToArray();

                stoper.Restart();
                var mathModel = engine.SynthesizeModel(trainingPoints);
                stoper.Stop();
                engine.Statistics.TotalSynthesisTime = stoper.Elapsed;

                database.Insert(mathModel);

                var testPointsGenerator = new TestPointsGenerator();
                stoper.Restart();
                var testPoints = testPointsGenerator.GeneratePoints(experimentParameters.NumberOfTestPoints, engine.Benchmark.Domains, engine.Benchmark.Constraints);
                stoper.Stop();
                engine.Statistics.TestPointsGenerationTime = stoper.Elapsed;

                var statistics = engine.EvaluateModel(testPoints);

                database.Insert(statistics);

                evolutionSteps = engine.CoreEvolutionSteps;
                //Logger.Instance.Log(experimentParameters);

                //Logger.Instance.Log(mathModel);
                //Logger.Instance.Log(statistics);

                //database.Insert(Logger.Instance.GetLogAsString());
            }
            catch (Exception exception)
            {
                database.Insert(exception);
            }

            database.Save();

            if (evolutionSteps != null && experimentParameters.TrackEvolutionSteps)
            {
                Logger.Instance.Log(evolutionSteps);
                var logsFullPath = Path.GetFullPath(LogsDirPath + experimentParameters.GetFileName("Log", ".cmplog"));
                File.WriteAllText(logsFullPath, StringCompressor.CompressString(Logger.Instance.GetLogAsString()));
            }
            //GlobalStoper.Stop();
            //Console.WriteLine(GlobalStoper.ElapsedMilliseconds);
            //Console.ReadKey();
            database.Dispose();
        }
예제 #3
0
        static void Main(string[] args)
        {
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
            //CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-US");
            //Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            var experimentParameters = new ExperimentParameters(
                numberOfDimensions: 2,
                basePopulationSize: 10,
                offspringPopulationSize: 100,
                numberOfGenerations: 100,
                //seed: new Random().Next(),
                seed: 1,
                //seed: 1971749862,
                //oneFifthRuleCheckInterval: 10,
                //individualLearningRate: 0.1, //0.47287080450158792
                //globalLearningRate: 0.1, //0.31622776601683794
                typeOfParentsSelection: ParentsSelectionType.Even,
                typeOfStdDeviationsRecombination: RecombinationType.Intermediate,
                typeOfRotationsRecombination: RecombinationType.Intermediate,
                useRedundantConstraintsRemoving: true,
                useDataNormalization: true,
                allowQuadraticTerms: true,
                useRecombination: false,
                trackEvolutionSteps: true,
                useSeeding: true,
                numberOfParentsSolutionsToSelect: 5,
                numberOfPositivePoints: 500,
                numberOfNegativePoints: 1500,
                //ballnBoundaryValue: 10,
                //simplexnBoundaryValue: 10,
                typeOfBenchmark: BenchmarkType.Simplexn);

            var enginesFactory = new EnginesFactory();

            var engine = enginesFactory.Create(experimentParameters);

            var distanceCalculator      = new CanberraDistanceCalculator();
            var positivePointsGenerator = new PositivePointsGenerator();
            var positiveTrainingPoints  = positivePointsGenerator.GeneratePoints(experimentParameters.NumberOfPositivePoints, engine.Benchmark.Domains, engine.Benchmark.Constraints);

            var negativePointsGenerator = new NegativePointsGenerator(positiveTrainingPoints, distanceCalculator, new NearestNeighbourDistanceCalculator(distanceCalculator));
            //var negativeTrainingPoints = negativePointsGenerator.GeneratePoints(experimentParameters.NumberOfNegativePoints, engine.Benchmark.Domains);
            var negativeTrainingPoints = negativePointsGenerator.GeneratePoints(experimentParameters.NumberOfNegativePoints, engine.Benchmark.Domains, engine.Benchmark.Constraints);

            var trainingPoints = positiveTrainingPoints.Concat(negativeTrainingPoints).ToArray();

            var testPointsGenerator = new TestPointsGenerator();
            var testPoints          = testPointsGenerator.GeneratePoints(experimentParameters.NumberOfTestPoints, engine.Benchmark.Domains, engine.Benchmark.Constraints);

            Console.WriteLine("Evolution starts!");
            var mathModel = engine.SynthesizeModel(trainingPoints);

            var statistics = engine.EvaluateModel(testPoints);

            var visualization = PrepareVisualisation(experimentParameters, engine, positiveTrainingPoints, negativeTrainingPoints,
                                                     testPoints);

            visualization.Show();

            Console.WriteLine("==========================================");
            Console.WriteLine("=============== PARAMETERS ===============");
            Console.WriteLine("==========================================");
            Console.WriteLine(experimentParameters.ToPrintableString());
            Console.WriteLine();
            Console.WriteLine("==========================================");
            Console.WriteLine("============= REFERENCE MODEL ============");
            Console.WriteLine("==========================================");
            Console.WriteLine(mathModel.ReferenceModelInLpFormat);
            Console.WriteLine();
            Console.WriteLine("==========================================");
            Console.WriteLine("============ SYNTHESIZED MODEL ===========");
            Console.WriteLine("==========================================");
            Console.WriteLine(mathModel.SynthesizedModelInLpFormat);
            Console.WriteLine();
            Console.WriteLine("==========================================");
            Console.WriteLine("=============== STATISTICS ===============");
            Console.WriteLine("==========================================");
            Console.WriteLine(statistics.ToPrintableString());
            Console.WriteLine();
            Console.ReadKey();
        }