예제 #1
0
        public void TestSpeciateAll_Manhattan()
        {
            IRandomSource rng                = RandomDefaults.CreateRandomSource(0);
            var           distanceMetric     = new ManhattanDistanceMetric();
            var           speciationStrategy = new GeneticKMeansSpeciationStrategy <double>(distanceMetric, 50, RandomDefaults.CreateRandomSource());

            TestSpeciateAll(100, 3, 2, 0.5, distanceMetric, speciationStrategy, rng);
            TestSpeciateAll(100, 10, 10, 0.2, distanceMetric, speciationStrategy, rng);
            TestSpeciateAll(100, 30, 10, 0.1, distanceMetric, speciationStrategy, rng);
        }
예제 #2
0
        public void SpeciateAdd_Manhattan()
        {
            IRandomSource rng                = RandomDefaults.CreateRandomSource(2);
            var           distanceMetric     = new ManhattanDistanceMetric();
            var           speciationStrategy = new RegularizedGeneticKMeansSpeciationStrategy <double>(distanceMetric, 50, 0.1, 4);

            TestSpeciateAdd(100, 3, 2, 0.5, distanceMetric, speciationStrategy, rng, false);
            TestSpeciateAdd(100, 10, 10, 0.2, distanceMetric, speciationStrategy, rng, false);
            TestSpeciateAdd(100, 30, 10, 0.1, distanceMetric, speciationStrategy, rng, false);
        }
예제 #3
0
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm list ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// </summary>
        public ModuleNeatEvolutionAlgorithm <NeatGenome>[] CreateEvolutionAlgorithms(int populationSize)
        {
            // Create the modules.
            List <Module> modules = new List <Module>();

            for (int i = 0; i < _moduleCount; i++)
            {
                // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
                IDistanceMetric distanceMetricPitch = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
                ISpeciationStrategy <NeatGenome> speciationStrategyPitch = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetricPitch, _parallelOptions);
                IDistanceMetric distanceMetricRhythm = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
                ISpeciationStrategy <NeatGenome> speciationStrategyRhythm = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetricRhythm, _parallelOptions);


                // Create complexity regulation strategy.
                IComplexityRegulationStrategy complexityRegulationPitch =
                    ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);
                IComplexityRegulationStrategy complexityRegulationRhythm =
                    ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);


                // Create and add a new module with strategies and the evolution parameters.
                Module module = new Module((i + 1), _eaParams,
                                           speciationStrategyPitch, speciationStrategyRhythm,
                                           complexityRegulationPitch, complexityRegulationRhythm);
                modules.Add(module);
            }

            // Hook-up the modules with each other in circular order.
            // TODO Right now, they are hooked-up in circular order. Check whether it should be done otherwise.
            //for (int i = 0; i < modules.Count; i++)
            //{
            //    modules[i].SetParasiteModule(i != modules.Count - 1 ? modules[i + 1] : modules[0], _parasiteCount,
            //        _championCount, CreateGenomeDecoder());
            //}
            foreach (var module in modules)
            {
                module.SetParasiteModules(modules.Except(new List <Module>()
                {
                    module
                }).ToList(), _parasiteCount, _championCount, CreateGenomeDecoder(), CreateGenomeDecoder());
            }

            // Initialize each module.
            foreach (var module in modules)
            {
                var rhythmFactory = CreateGenomeFactory();
                var pitchFactory  = CreateGenomeFactory();
                module.Initialize(rhythmFactory, pitchFactory, populationSize);
            }

            // Finished. Return the evolution algorithms
            return
                (modules.Select(m => m.RhythmEvolutionAlgorithm).Concat(modules.Select(m => m.PitchEvolutionAlgorithm)).ToArray());
        }
예제 #4
0
        private NeatEvolutionAlgorithm <NeatGenome> GenerateTeam()
        {
            NeatEvolutionAlgorithmParameters neatParams = new NeatEvolutionAlgorithmParameters();

            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(0.4, 1.0, 0.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric);

            IComplexityRegulationStrategy complexityStrategy = new NullComplexityRegulationStrategy();

            return(new NeatEvolutionAlgorithm <NeatGenome>(neatParams, speciationStrategy, complexityStrategy));
        }
예제 #5
0
        private NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm_private(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList, HyperNEAT_Args args = null)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1, 0, 10);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, _parallelOptions);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> retVal = new NeatEvolutionAlgorithm <NeatGenome>(NeatEvolutionAlgorithmParameters, speciationStrategy, complexityRegulationStrategy);

            // Genome Decoder
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = null;

            if (args == null)
            {
                genomeDecoder = CreateGenomeDecoder();
            }
            else
            {
                genomeDecoder = CreateGenomeDecoder(args);
            }

            // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
            IGenomeListEvaluator <NeatGenome> genomeEvaluator = null;

            if (_phenomeEvaluator != null)
            {
                IGenomeListEvaluator <NeatGenome> innerEvaluator = new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, _phenomeEvaluator, _parallelOptions);

                // Wrap the list evaluator in a 'selective' evaluator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
                // that were in the population in previous generations (elite genomes). This is determined by examining each genome's evaluation info object.
                genomeEvaluator = new SelectiveGenomeListEvaluator <NeatGenome>(
                    innerEvaluator,
                    SelectiveGenomeListEvaluator <NeatGenome> .CreatePredicate_OnceOnly());
            }
            else if (_phenomeEvaluators != null)
            {
                // Use the multi tick evaluator
                genomeEvaluator = new TickGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, _phenomeEvaluators, _phenometickeval_roundRobinManager, _phenometickeval_worldTick);
            }
            else
            {
                throw new ApplicationException("One of the phenome evaluators needs to be populated");
            }

            // Initialize the evolution algorithm.
            retVal.Initialize(genomeEvaluator, genomeFactory, genomeList);

            // Finished. Return the evolution algorithm
            return(retVal);
        }
        private static void InitialiseSpecies(NeatPopulation <double> neatPop)
        {
            // Create a speciation strategy instance.
            var distanceMetric     = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            var speciationStrategy = new Speciation.GeneticKMeans.Parallelized.GeneticKMeansSpeciationStrategy <double>(distanceMetric, 5, 4);

            // Apply the speciation strategy.
            var           genomeComparerDescending = new GenomeComparerDescending(PrimaryFitnessInfoComparer.Singleton);
            IRandomSource rng = RandomDefaults.CreateRandomSource(0);

            neatPop.InitialiseSpecies(speciationStrategy, 3, genomeComparerDescending, rng);
        }
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome population and their associated/parent genome factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, _parallelOptions);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

            // Create IBlackBox evaluator.
            DoublePoleBalancingEvaluator evaluator;

            switch (_variantStr)
            {
            case "DoublePole":
                evaluator = new DoublePoleBalancingEvaluator();
                break;

            case "DoublePoleNv":
                evaluator = new DoublePoleBalancingEvaluatorNv();
                break;

            case "DoublePoleNvAntiWiggle":
                evaluator = new DoublePoleBalancingEvaluatorNvAntiWiggle();
                break;

            default:
                throw new SharpNeatException(string.Format("DoublePoleBalancing experiment config XML specifies unknown variant [{0}]", _variantStr));
            }

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder();

            // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
            IGenomeListEvaluator <NeatGenome> innerEvaluator = new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, evaluator, _parallelOptions);

            // Wrap the list evaluator in a 'selective' evaulator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
            // that were in the population in previous generations (elite genomes). This is determiend by examining each genome's evaluation info object.
            IGenomeListEvaluator <NeatGenome> selectiveEvaluator = new SelectiveGenomeListEvaluator <NeatGenome>(
                innerEvaluator,
                SelectiveGenomeListEvaluator <NeatGenome> .CreatePredicate_OnceOnly());

            // Initialize the evolution algorithm.
            ea.Initialize(selectiveEvaluator, genomeFactory, genomeList);

            // Finished. Return the evolution algorithm
            return(ea);
        }
예제 #8
0
        private NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeListEvaluator <NeatGenome> evaluator, List <NeatGenome> list)
        {
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy           = new KMeansClusteringStrategy <NeatGenome>(distanceMetric);
            IComplexityRegulationStrategy    complexityRegulationStrategy = new DefaultComplexityRegulationStrategy(ComplexityCeilingType.Absolute, _complexityThreshold);

            NeatEvolutionAlgorithm <NeatGenome> neatEvolutionAlgorithm = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

            var genomeFactory = new NeatGenomeFactory(_inputCount.Value, _outputCount.Value, _neatGenomeParams);

            neatEvolutionAlgorithm.Initialize(evaluator, genomeFactory, list);

            return(neatEvolutionAlgorithm);
        }
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList, IGenomeListEvaluator <NeatGenome> eval = null)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, _parallelOptions);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = new NullComplexityRegulationStrategy();// ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

            // Create the MC evaluator
            PasswordCrackingEvaluator.Passwords = _passwords;

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, MarkovChain> genomeDecoder = CreateGenomeDecoder();

            // If we're running specially on Condor, skip this
            if (eval == null)
            {
                _evaluator = new PasswordCrackingEvaluator(_guesses, Hashed);

                // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
                //    IGenomeListEvaluator<NeatGenome> innerEvaluator = new ParallelGenomeListEvaluator<NeatGenome, MarkovChain>(genomeDecoder, _evaluator, _parallelOptions);
                IGenomeListEvaluator <NeatGenome> innerEvaluator = new ParallelNEATGenomeListEvaluator <NeatGenome, MarkovChain>(genomeDecoder, _evaluator, this);

                /*
                 * // Wrap the list evaluator in a 'selective' evaulator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
                 * // that were in the population in previous generations (elite genomes). This is determiend by examining each genome's evaluation info object.
                 * IGenomeListEvaluator<NeatGenome> selectiveEvaluator = new SelectiveGenomeListEvaluator<NeatGenome>(
                 *                                                                      innerEvaluator,
                 *                                                                      SelectiveGenomeListEvaluator<NeatGenome>.CreatePredicate_OnceOnly());
                 */


                // Initialize the evolution algorithm.
                ea.Initialize(innerEvaluator, genomeFactory, genomeList);
            }
            else
            {
                // Initialize the evolution algorithm.
                ea.Initialize(eval, genomeFactory, genomeList);
            }



            // Finished. Return the evolution algorithm
            return(ea);
        }
예제 #10
0
    private void Start()
    {
        int populationSize = 100;
        NetworkActivationScheme activationScheme = NetworkActivationScheme.CreateAcyclicScheme();

        NeatGenomeParameters neatParams = new NeatGenomeParameters();

        neatParams.ActivationFn    = TanH.__DefaultInstance;
        neatParams.FeedforwardOnly = activationScheme.AcyclicNetwork;

        IGenomeDecoder <NeatGenome, IBlackBox> neatDecoder = new NeatGenomeDecoder(activationScheme);

        IGenomeFactory <NeatGenome> neatFactory = new NeatGenomeFactory(3, 3, neatParams);
        List <NeatGenome>           genomeList  = neatFactory.CreateGenomeList(populationSize, 0);
        ArenaEvaluator evaluator = GetComponent <ArenaEvaluator>();

        evaluator.Initialize(neatDecoder);

        IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);

        // Evolution parameters
        NeatEvolutionAlgorithmParameters neatEvolutionParams = new NeatEvolutionAlgorithmParameters();

        neatEvolutionParams.SpecieCount = 10;
        ISpeciationStrategy <NeatGenome> speciationStrategy           = new KMeansClusteringStrategy <NeatGenome>(distanceMetric);
        IComplexityRegulationStrategy    complexityRegulationStrategy = new DefaultComplexityRegulationStrategy(ComplexityCeilingType.Absolute, 10);

        NeatEvolutionAlgorithm <NeatGenome> ea = GetComponent <UnityEvolutionAlgorithm>();

        ea.Construct(neatEvolutionParams, speciationStrategy, complexityRegulationStrategy, new NullGenomeListEvaluator <NeatGenome, IBlackBox>());
        ea.Initialize(evaluator, neatFactory, genomeList);
        ea.UpdateScheme = new UpdateScheme(1); // This needs to be set AFTER Initialize is called

        ea.PausedEvent += (sender, e) =>
        {
            //ea.StartContinue();
        };
        ea.GenerationEvent += (sender, gen) =>
        {
            Debug.Log($"Generation {gen}");
            Debug.Log($"Highest fitness: {ea.CurrentChampGenome.EvaluationInfo.Fitness}");
            nnMesh.GenerateMesh(ea.CurrentChampGenome);
            ea.RequestPause();
            StartCoroutine(PauseRoutine(ea));
        };

        ea.StartContinue();
    }
예제 #11
0
    public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
    {
        IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
        ISpeciationStrategy <NeatGenome> speciationStrategy           = new KMeansClusteringStrategy <NeatGenome>(distanceMetric);
        IComplexityRegulationStrategy    complexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

        BraidNeatEvolutionAlgorithm <NeatGenome> ea = new BraidNeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

        // Create black box evaluator
        BraidEvaluator evaluator = new BraidEvaluator(m_optimizer);
        IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder  = CreateGenomeDecoder();
        IGenomeListEvaluator <NeatGenome>      innerEvaluator = new BraidListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, evaluator, m_optimizer);

        ea.Initialize(innerEvaluator, genomeFactory, genomeList);
        return(ea);
    }
        /// <summary>
        ///     Configures and instantiates the initialization evolutionary algorithm.
        /// </summary>
        /// <param name="parallelOptions">Synchronous/Asynchronous execution settings.</param>
        /// <param name="genomeList">The initial population of genomes.</param>
        /// <param name="genomeDecoder">The decoder to translate genomes into phenotypes.</param>
        /// <param name="startingEvaluations">
        ///     The number of evaluations that preceeded this from which this process will pick up
        ///     (this is used in the case where we're restarting a run because it failed to find a solution in the allotted time).
        /// </param>
        protected void InitializeAlgorithm(ParallelOptions parallelOptions, List <NeatGenome> genomeList,
                                           IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder, ulong startingEvaluations)
        {
            ParallelOptions     = parallelOptions;
            InitialPopulation   = genomeList;
            StartingEvaluations = startingEvaluations;
            GenomeDecoder       = genomeDecoder;

            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);

            SpeciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, parallelOptions);

            // Create complexity regulation strategy.
            ComplexityRegulationStrategy =
                ExperimentUtils.CreateComplexityRegulationStrategy(ComplexityRegulationStrategyDefinition,
                                                                   ComplexityThreshold);
        }
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome2 population and their associated/parent genome2 factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome>[] CreateEvolutionAlgorithms(IGenomeFactory <NeatGenome> genomeFactory1, List <NeatGenome> genomeList1,
                                                                               IGenomeFactory <NeatGenome> genomeFactory2, List <NeatGenome> genomeList2)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric1 = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy1 = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric1, _parallelOptions);

            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric2 = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy2 = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric2, _parallelOptions);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy1 = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy2 = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea1 = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy1, complexityRegulationStrategy1);
            NeatEvolutionAlgorithm <NeatGenome> ea2 = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy2, complexityRegulationStrategy2);

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder1 = CreateGenomeDecoder();
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder2 = CreateGenomeDecoder();

            // Create phenome evaluators. Note we are evolving one population of X players and one of O players.
            ICoevolutionPhenomeEvaluator <IBlackBox> phenomeEvaluator1 = new TicTacToeHostParasiteEvaluator(SquareTypes.X);
            ICoevolutionPhenomeEvaluator <IBlackBox> phenomeEvaluator2 = new TicTacToeHostParasiteEvaluator(SquareTypes.O);

            // Create a genome list evaluator. This packages up the genome decoder with the phenome evaluator.
            HostParasiteCoevolutionListEvaluator <NeatGenome, IBlackBox> genomeListEvaluator1 = new HostParasiteCoevolutionListEvaluator <NeatGenome, IBlackBox>(_parasiteCount, _championCount, ea2, genomeDecoder1, phenomeEvaluator1);
            HostParasiteCoevolutionListEvaluator <NeatGenome, IBlackBox> genomeListEvaluator2 = new HostParasiteCoevolutionListEvaluator <NeatGenome, IBlackBox>(_parasiteCount, _championCount, ea1, genomeDecoder2, phenomeEvaluator2);

            // Initialize the evolution algorithms.
            ea1.Initialize(genomeListEvaluator1, genomeFactory1, genomeList1);
            ea2.Initialize(genomeListEvaluator2, genomeFactory2, genomeList2);

            // Set the evolution algorithms to update every generation.
            ea1.UpdateScheme = new UpdateScheme(1);
            ea2.UpdateScheme = new UpdateScheme(1);

            // Finished. Return the evolution algorithms
            return(new [] { ea1, ea2 });
        }
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome2 population and their associated/parent genome2 factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, new ParallelOptions());

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder();


            // Finished. Return the evolution algorithm
            return(ea);
        }
예제 #15
0
        private static ISpeciationStrategy <NeatGenome <double>, double> CreateSpeciationStrategy(
            INeatExperiment <double> neatExperiment)
        {
            // Resolve a degreeOfParallelism (-1 is allowed in config, but must be resolved here to an actual degree).
            int degreeOfParallelismResolved = ResolveDegreeOfParallelism(neatExperiment);

            // Define a distance metric to use for k-means speciation; this is the default from sharpneat 2.x.
            IDistanceMetric <double> distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);

            // Use k-means speciation strategy; this is the default from sharpneat 2.x.
            // Create a serial (single threaded) strategy if degreeOfParallelism is one.
            if (degreeOfParallelismResolved == 1)
            {
                return(new Neat.Speciation.GeneticKMeans.GeneticKMeansSpeciationStrategy <double>(distanceMetric, 5));
            }

            // Create a parallel (multi-threaded) strategy for degreeOfParallelism > 1.
            return(new Neat.Speciation.GeneticKMeans.Parallelized.GeneticKMeansSpeciationStrategy <double>(distanceMetric, 5, degreeOfParallelismResolved));
        }
예제 #16
0
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(
            IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10;
            // for matched genes the distance is their weight difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy =
                new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = new NullComplexityRegulationStrategy();

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea =
                new NeatEvolutionAlgorithm <NeatGenome>(this.eaParams, speciationStrategy, complexityRegulationStrategy);

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = this.CreateGenomeDecoder();

            var evaluator = new Evaluator();

            // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
            //IGenomeListEvaluator<NeatGenome> innerEvaluator =
            //    new SerialGenomeListEvaluator<NeatGenome, IBlackBox>(genomeDecoder, evaluator);
            IGenomeListEvaluator <NeatGenome> innerEvaluator =
                new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, evaluator);

            // Wrap the list evaluator in a 'selective' evaluator that will only evaluate new genomes.
            // That is, we skip re-evaluating any genomes that were in the population in previous
            // generations (elite genomes). This is determined by examining each genome's evaluation info object.
            IGenomeListEvaluator <NeatGenome> selectiveEvaluator =
                new SelectiveGenomeListEvaluator <NeatGenome>(
                    innerEvaluator,
                    SelectiveGenomeListEvaluator <NeatGenome> .CreatePredicate_OnceOnly());

            // Initialize the evolution algorithm.
            ea.Initialize(selectiveEvaluator, genomeFactory, genomeList);
            ea.UpdateScheme = new UpdateScheme(1);

            // Finished. Return the evolution algorithm
            return(ea);
        }
    /// <summary>
    /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
    /// of the algorithm are also constructed and connected up.
    /// This overload accepts a pre-built genome population and their associated/parent genome factory.
    /// </summary>
    public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
    {
        Debug.Log("........CreateEvolutionAlgorithm: Setting parameters");
        // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
        IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
        ISpeciationStrategy <NeatGenome> speciationStrategy = new KMeansClusteringStrategy <NeatGenome>(distanceMetric);

        // Create complexity regulation strategy.
        IComplexityRegulationStrategy complexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

        Debug.Log("........CreateEvolutionAlgorithm: Creating ea");
        // Create the evolution algorithm.
        NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

        Debug.Log("........CreateEvolutionAlgorithm: Creating evaluator");
        // Create IBlackBox evaluator.
        CPPNRepairEvaluator2 evaluator = new CPPNRepairEvaluator2(this);

        evaluator.SetOriginalFeatures(_originalFeatures);

        Debug.Log("........CreateEvolutionAlgorithm: Creating genome decoder and serial evaluator");
        // Create genome decoder.
        IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder();

        // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
        IGenomeListEvaluator <NeatGenome> innerEvaluator = new SerialGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, evaluator);

        // Wrap the list evaluator in a 'selective' evaulator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
        // that were in the population in previous generations (elite genomes). This is determiend by examining each genome's evaluation info object.

        /*IGenomeListEvaluator<NeatGenome> selectiveEvaluator = new SelectiveGenomeListEvaluator<NeatGenome>(
         *                                                                      innerEvaluator,
         *                                                                      SelectiveGenomeListEvaluator<NeatGenome>.CreatePredicate_OnceOnly());
         */
        // Initialize the evolution algorithm.
        Debug.Log("........CreateEvolutionAlgorithm: Initializing ea");
        ea.Initialize(innerEvaluator, genomeFactory, genomeList);

        Debug.Log("........CreateEvolutionAlgorithm: Returning");
        // Finished. Return the evolution algorithm
        return(ea);
    }
예제 #18
0
        /*
         *      List<NeatGenome> CreateNewGenome(IGenomeFactory<NeatGenome> genomeFactory)
         *      {
         *              Console.WriteLine("Saved genome not found, creating new files.");
         *              return genomeFactory.CreateGenomeList(_populationSize, 0);
         *      }
         */

        /// <summary>
        /// Creates and returns a NeatEvolutionAlgorithm object ready for running
        /// the NEAT algorithm/search. Various sub-parts of the algorithm are also
        /// constructed and connected up. This overload accepts a pre-built genome2
        /// population and their associated/parent genome2 factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(
            IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Creates distance metric. Mismatched genes have a fixed distance of 10;
            // for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);

            //ISpeciationStrategy<NeatGenome> speciationStrategy = new KMeansClusteringStrategy<NeatGenome>(distanceMetric);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, _parallelOptions);

            IComplexityRegulationStrategy complexityRegulationStrategy =
                ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);
            // Creates the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> evolAlgorithm = new NeatEvolutionAlgorithm <NeatGenome>(
                _eaParams, speciationStrategy, complexityRegulationStrategy, userName);
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new NeatGenomeDecoder(_activationScheme);
            // Creates a genome2 list evaluator. This packages up the genome2 decoder with the genome2 evaluator.
            IGenomeListEvaluator <NeatGenome> genomeListEvaluator =
                new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, PhenomeEvaluator, _parallelOptions);

            //To use single-thread evaluator:
            //IGenomeListEvaluator<NeatGenome> genomeListEvaluator =
            //        new SerialGenomeListEvaluator<NeatGenome, IBlackBox>(genomeDecoder, PhenomeEvaluator, false);
            // Wraps the list evaluator in a 'selective' evaulator that will only
            // evaluate new genomes. That is, we skip re-evaluating any genomes
            // that were in the population in previous generations (elite genomes).
            // This is determiend by examining each genome's evaluation info object.

            /*
             * int reevaluationPeriod = 1;
             * genomeListEvaluator = new SelectiveGenomeListEvaluator<NeatGenome>(
             *      genomeListEvaluator,
             *      SelectiveGenomeListEvaluator<NeatGenome>.CreatePredicate_PeriodicReevaluation(reevaluationPeriod));
             */
            genomeListEvaluator = new SelectiveGenomeListEvaluator <NeatGenome>(
                genomeListEvaluator,
                SelectiveGenomeListEvaluator <NeatGenome> .CreatePredicate_OnceOnly());
            // Initializes the evolution algorithm.
            evolAlgorithm.Initialize(genomeListEvaluator, genomeFactory, genomeList);
            // Finished. Return the evolution algorithm
            return(evolAlgorithm);
        }
예제 #19
0
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome population and their associated/parent genome factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, _parallelOptions);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

            // Create IBlackBox evaluator.
            DeepBeliefNetworkBiasEvaluator evaluator = new DeepBeliefNetworkBiasEvaluator();

            // Create genome decoder. Decodes to a neural network packaged with an activation scheme that defines a fixed number of activations per evaluation.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder(_lengthCppnInput);

            // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
            IGenomeListEvaluator <NeatGenome> innerEvaluator = null;

            if (Constants.IS_MULTI_THREADING)
            {
                innerEvaluator = new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, evaluator, _parallelOptions);
            }
            else
            {
                innerEvaluator = new SerialGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, evaluator);
            }

            // Wrap the list evaluator in a 'selective' evaulator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
            // that were in the population in previous generations (elite genomes). This is determiend by examining each genome's evaluation info object.
            IGenomeListEvaluator <NeatGenome> selectiveEvaluator = new SelectiveGenomeListEvaluator <NeatGenome>(
                innerEvaluator,
                SelectiveGenomeListEvaluator <NeatGenome> .CreatePredicate_OnceOnly());

            // Initialize the evolution algorithm.
            ea.Initialize(selectiveEvaluator, genomeFactory, genomeList);

            // Finished. Return the evolution algorithm
            return(ea);
        }
예제 #20
0
    public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory,
                                                                        List <NeatGenome> genomeList)
    {
        IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
        ISpeciationStrategy <NeatGenome> speciationStrategy           = new KMeansClusteringStrategy <NeatGenome>(distanceMetric);
        IComplexityRegulationStrategy    complexityRegulationStrategy =
            ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);
        NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy,
                                                                                         complexityRegulationStrategy);
        // Creates black box evaluator
        SimpleEvaluator evaluator = new SimpleEvaluator(_optimizer);
        IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder  = CreateGenomeDecoder();
        IGenomeListEvaluator <NeatGenome>      innerEvaluator = new UnityParallelListEvaluator <NeatGenome, IBlackBox>(
            genomeDecoder, evaluator, _optimizer);
        IGenomeListEvaluator <NeatGenome> selectiveEvaluator = new SelectiveGenomeListEvaluator <NeatGenome>(
            innerEvaluator, SelectiveGenomeListEvaluator <NeatGenome> .CreatePredicate_OnceOnly());

        ea.Initialize(innerEvaluator, genomeFactory, genomeList);
        return(ea);
    }
예제 #21
0
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy =
                new KMeansClusteringStrategy <NeatGenome>(distanceMetric);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy =
                ExperimentUtils.CreateComplexityRegulationStrategy("absolute", 10);

            // Create the evolution algorithm.
            var ea = new NeatEvolutionAlgorithm <NeatGenome>(
                NeatEvolutionAlgorithmParameters,
                speciationStrategy,
                complexityRegulationStrategy);

            // Create IBlackBox evaluator.
            // var evaluator = new RemoteXorEvaluator();
            var evaluator = new RemoteBatchXorEvaluator();
            //LocalXorEvaluator evaluator = new LocalXorEvaluator();

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, FastCyclicNetwork> genomeDecoder = _decoder;

            // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
            IGenomeListEvaluator <NeatGenome> innerEvaluator = new BatchGenomeListEvaluator <NeatGenome, FastCyclicNetwork>(genomeDecoder, evaluator);

            // Wrap the list evaluator in a 'selective' evaulator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
            // that were in the population in previous generations (elite genomes). This is determined by examining each genome's evaluation info object.
            IGenomeListEvaluator <NeatGenome> selectiveEvaluator = new SelectiveGenomeListEvaluator <NeatGenome>(
                innerEvaluator,
                SelectiveGenomeListEvaluator <NeatGenome> .CreatePredicate_OnceOnly());

            // Initialize the evolution algorithm.
            ea.Initialize(selectiveEvaluator, genomeFactory, genomeList);

            // Finished. Return the evolution algorithm
            return(ea);
        }
예제 #22
0
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome2 population and their associated/parent genome2 factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, new ParallelOptions());

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = new NullComplexityRegulationStrategy();// ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder();

            // Create a genome list evaluator. This packages up the genome decoder with the phenome evaluator.
            _evaluator = new ForagingEvaluator <NeatGenome>(genomeDecoder, _world, _agentType, _navigationEnabled, _hidingEnabled)
            {
                MaxTimeSteps             = _timeStepsPerGeneration,
                EvoParadigm              = _paradigm,
                MemParadigm              = _memory,
                GenerationsPerMemorySize = _memGens,
                MaxMemorySize            = _maxMemorySize,
                TeachParadigm            = _teaching,
                TrialId              = TrialId,
                PredatorCount        = _predCount,
                PredatorDistribution = PredatorDistribution,
                PredatorTypes        = _predTypes,
                PredatorGenerations  = _predGens,
                DistinguishPredators = _distinguishPreds,
                LogDiversity         = _logDiversity
            };

            // Initialize the evolution algorithm.
            ea.Initialize(_evaluator, genomeFactory, genomeList);

            // Finished. Return the evolution algorithm
            return(ea);
        }
예제 #23
0
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome population and their associated/parent genome factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, _parallelOptions);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, _complexityRegulationStrategy);

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder();

            INoveltyScorer <NeatGenome>          noveltyScorer          = new TuringNoveltyScorer <NeatGenome>(_noveltySearchParams);
            IGeneticDiversityScorer <NeatGenome> geneticDiversityScorer = new GeneticDiversityKnn <NeatGenome>(_neatGenomeParams.ConnectionWeightRange);
            IMultiObjectiveScorer multiObjectiveScorer = new NSGAII(_multiObjectiveParams);

            _listEvaluator = new MultiObjectiveListEvaluator <NeatGenome, IBlackBox>(
                genomeDecoder,
                _evaluator,
                noveltyScorer,
                geneticDiversityScorer,
                multiObjectiveScorer,
                _multiThreading,
                _parallelOptions);

            _listEvaluator.MultiObjectiveParams = _multiObjectiveParams;
            _listEvaluator.ReportInterval       = _logInterval;

            NoveltySearchEnabled  = _noveltySearchParams?.Enabled ?? false;
            MultiObjectiveEnabled = _multiObjectiveParams?.Enabled ?? false;

            // Initialize the evolution algorithm.
            ea.Initialize(_listEvaluator, genomeFactory, genomeList);

            ea.UpdateScheme = new UpdateScheme(1);
            // Finished. Return the evolution algorithm
            return(ea);
        }
예제 #24
0
        private static void Train()
        {
            File.WriteAllText($"{NeatConsts.experimentName}/fitness.csv", "generation,firness\n");

            var neatGenomeFactory = new NeatGenomeFactory(NeatConsts.ViewX * NeatConsts.ViewY * NeatConsts.typeIds.Count, 1);
            var genomeList        = neatGenomeFactory.CreateGenomeList(NeatConsts.SpecCount, 0);
            var eaParams          = new NeatEvolutionAlgorithmParameters
            {
                SpecieCount = NeatConsts.SpecCount
            };

            //var distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            var distanceMetric = new ManhattanDistanceMetric();

            var parallelOptions    = new ParallelOptions();
            var speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, parallelOptions);
            //var speciationStrategy = new KMeansClusteringStrategy<NeatGenome>(distanceMetric);
            //var speciationStrategy = new RandomClusteringStrategy<NeatGenome>();

            var complexityRegulationStrategy = new NullComplexityRegulationStrategy();
            //var complexityRegulationStrategy = new DefaultComplexityRegulationStrategy(ComplexityCeilingType.Relative, 0.50);

            var ea = new NeatEvolutionAlgorithm <NeatGenome>(eaParams, speciationStrategy, complexityRegulationStrategy);
            var activationScheme    = NetworkActivationScheme.CreateCyclicFixedTimestepsScheme(1);
            var genomeDecoder       = new NeatGenomeDecoder(activationScheme);
            var phenomeEvaluator    = new GameEvaluator();
            var genomeListEvaluator = new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, phenomeEvaluator, parallelOptions);

            ea.Initialize(genomeListEvaluator, neatGenomeFactory, genomeList);
            ea.UpdateScheme = new UpdateScheme(NeatConsts.LogRate);
            ea.StartContinue();
            ea.UpdateEvent += Ea_UpdateEvent;
            while (ea.RunState != RunState.Paused)
            {
            }
            ea.Stop();
        }
예제 #25
0
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome population and their associated/parent genome factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weight difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, _parallelOptions);

            // Create complexity regulation strategy.
            IComplexityRegulationStrategy complexityRegulationStrategy = ExperimentUtils.CreateComplexityRegulationStrategy(_complexityRegulationStr, _complexityThreshold);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder();

            // All-encompassing info object
            _info = new Info(this, ea, genomeDecoder);

            // Create IBlackBox evaluator.
            IPDEvaluator evaluator = new IPDEvaluator(ref _info);

            // Create a genome list evaluator. This packages up the genome decoder with the genome evaluator.
            IGenomeListEvaluator <NeatGenome> innerEvaluator = new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, evaluator, _parallelOptions);

            // Wrap the list evaluator in a 'selective' evaluator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
            // that were in the population in previous generations (elite genomes). This is determined by examining each genome's evaluation info object.
            IGenomeListEvaluator <NeatGenome> selectiveEvaluator = new SelectiveGenomeListEvaluator <NeatGenome>(
                innerEvaluator,
                SelectiveGenomeListEvaluator <NeatGenome> .CreatePredicate_OnceOnly());

            // Initialize the evolution algorithm.
            ea.Initialize(selectiveEvaluator, genomeFactory, genomeList);


            // Finished. Return the evolution algorithm
            return(ea);
        }
예제 #26
0
        public NeatEvolutionAlgorithm <double> CreateNeatEvolutionAlgorithm()
        {
            // Create a genome evaluator.
            var genomeListEvaluator = CreateGenomeListEvaluator(out int inputCount, out int outputCount);

            // Create an initial population.
            _metaNeatGenome          = CreateMetaNeatGenome(inputCount, outputCount);
            _eaSettings              = new NeatEvolutionAlgorithmSettings();
            _eaSettings.SpeciesCount = 40;
            _neatPop = CreatePopulation(_metaNeatGenome, 600);

            // Create a speciation strategy instance.
            var distanceMetric     = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            var speciationStrategy = new SharpNeat.Neat.Speciation.GeneticKMeans.Parallelized.GeneticKMeansSpeciationStrategy <double>(distanceMetric, 5);

            // Create an asexual reproduction settings object (default settings).
            var reproductionAsexualSettings = new NeatReproductionAsexualSettings();

            // Create a sexual reproduction settings object (default settings).
            var reproductionSexualSettings = new NeatReproductionSexualSettings();

            // Create a connection weight mutation scheme.
            var weightMutationScheme = WeightMutationSchemeFactory.CreateDefaultScheme(_metaNeatGenome.ConnectionWeightScale);

            // Pull all of the parts together into an evolution algorithm instance.
            var ea = new NeatEvolutionAlgorithm <double>(
                _eaSettings,
                genomeListEvaluator,
                speciationStrategy,
                _neatPop,
                reproductionAsexualSettings,
                reproductionSexualSettings,
                weightMutationScheme);

            return(ea);
        }
예제 #27
0
    public void TestSingleMatchGenomes()
    {
        var connGenes1 = new ConnectionGenes <double>(5);

        connGenes1[0] = (0, 10, 1.0);
        connGenes1[1] = (1, 11, 2.0);
        connGenes1[2] = (2, 12, 3.0);
        connGenes1[3] = (3, 13, 4.0);
        connGenes1[4] = (4, 14, 5.0);

        var connGenes2 = new ConnectionGenes <double>(1);

        connGenes2[0] = (4, 14, 20.0);

        var distanceMetric = new ManhattanDistanceMetric();

        // GetDistance() tests.
        Assert.Equal(25, distanceMetric.CalcDistance(connGenes1, connGenes2));
        Assert.Equal(25, distanceMetric.CalcDistance(connGenes2, connGenes1));

        // TestDistance() tests.
        Assert.True(distanceMetric.TestDistance(connGenes1, connGenes2, 25 + 0.001));
        Assert.False(distanceMetric.TestDistance(connGenes1, connGenes2, 25 - 0.001));
    }
예제 #28
0
        public static void Main(string[] args)
        {
            var random   = new Random();
            var circuits = circuitsFilePaths().ToArray();

            var perceptionStep        = TimeSpan.FromSeconds(0.1);
            var simulationStep        = TimeSpan.FromSeconds(0.05); // 20Hz
            var maximumSimulationTime = TimeSpan.FromSeconds(60);

            var tracks = circuits.Select(circuitPath => Track.Load($"{circuitPath}/circuit_definition.json"));
            var worlds = tracks.Select(track => new StandardWorld(track, simulationStep)).ToArray();

            var inputSamplesCount       = 3;
            var maximumScanningDistance = 200;

            ILidar createLidarFor(ITrack track)
            => new Lidar(track, inputSamplesCount, Angle.FromDegrees(135), maximumScanningDistance);

            var settings = new EvolutionSettings
            {
                PopulationSize      = 1000,
                SpeciesCount        = 30,
                ElitismProportion   = 0,
                ComplexityThreshold = 50
            };

            // prepare simulation
            var parameters = new NeatEvolutionAlgorithmParameters
            {
                ElitismProportion = settings.ElitismProportion,
                SpecieCount       = settings.SpeciesCount
            };

            var distanceMetric  = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 4
            };
            var speciationStrategy           = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, parallelOptions);
            var complexityRegulationStrategy = new DefaultComplexityRegulationStrategy(ComplexityCeilingType.Absolute, settings.ComplexityThreshold);

            var evolutionaryAlgorithm = new NeatEvolutionAlgorithm <NeatGenome>(
                parameters,
                speciationStrategy,
                complexityRegulationStrategy);

            var phenomeEvaluator = new RaceSimulationEvaluator(
                random,
                simulationStep,
                perceptionStep,
                maximumSimulationTime,
                worlds,
                createLidarFor);

            var genomeDecoder       = new NeatGenomeDecoder(NetworkActivationScheme.CreateAcyclicScheme());
            var genomeListEvaluator = new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(
                genomeDecoder,
                phenomeEvaluator);

            evolutionaryAlgorithm.Initialize(
                genomeListEvaluator,
                genomeFactory: new NeatGenomeFactory(
                    inputNeuronCount: inputSamplesCount,
                    outputNeuronCount: 2,
                    DefaultActivationFunctionLibrary.CreateLibraryNeat(new BipolarSigmoid()),
                    new NeatGenomeParameters
            {
                FeedforwardOnly                     = true,
                AddNodeMutationProbability          = 0.03,
                DeleteConnectionMutationProbability = 0.05,
                ConnectionWeightMutationProbability = 0.08,
                FitnessHistoryLength                = 10,
            }),
                settings.PopulationSize);

            var lastVisualization = DateTimeOffset.Now;

            evolutionaryAlgorithm.UpdateEvent += onUpdate;
            evolutionaryAlgorithm.StartContinue();

            Console.WriteLine("Press enter to stop the evolution.");
            Console.ReadLine();
            Console.WriteLine("Finishing the evolution.");

            evolutionaryAlgorithm.Stop();
            Console.WriteLine("Evolution is stopped.");

            // simulate best individual
            Console.WriteLine("Simulating best individual...");
            evaluate(evolutionaryAlgorithm.CurrentChampGenome);
            Console.WriteLine("Done.");

            void onUpdate(object sender, EventArgs e)
            {
                Console.WriteLine($"Generation #{evolutionaryAlgorithm.CurrentGeneration}");
                Console.WriteLine($"- max fitness:  {evolutionaryAlgorithm.Statistics._maxFitness}");
                Console.WriteLine($"- mean fitness: {evolutionaryAlgorithm.Statistics._meanFitness}");
                Console.WriteLine();

                if (DateTimeOffset.Now - lastVisualization > TimeSpan.FromSeconds(35))
                {
                    lastVisualization = DateTimeOffset.Now;
                    Console.WriteLine("Simulating currently best individual...");
                    evaluate(evolutionaryAlgorithm.CurrentChampGenome);
                }
            }

            void evaluate(NeatGenome genome)
            {
                var worldId = random.Next(0, worlds.Length - 1);
                var world   = worlds[worldId];

                var bestIndividual = genomeDecoder.Decode(genome);
                var agent          = new NeuralNetworkAgent(createLidarFor(world.Track), bestIndividual);
                var simulation     = new Simulation.Simulation(agent, world);
                var summary        = simulation.Simulate(simulationStep, perceptionStep, maximumSimulationTime);

                File.Copy($"{circuits[worldId]}/visualization.svg", "C:/Users/simon/Projects/racer-experiment/simulator/src/visualization.svg", overwrite: true);
                IO.Simulation.StoreResult(world.Track, world.VehicleModel, summary, "", "C:/Users/simon/Projects/racer-experiment/simulator/src/report.json");
            }
        }