示例#1
0
    public void Initialize()
    {
        /*** Initialize experiment ***/
        experiment = new PCGNeatExperiment() as INeatExperiment;
        // Null because not reading settings from xmlFile
        experiment.Initialize("PCG Conetent EA", null);

        /*** Randomly generate population ***/
        // Set initial settings
        // ? means it is nullable
        int?popSize = experiment.DefaultPopulationSize;

        // Create a genome factory appropriate for the experiment.
        IGenomeFactory <NeatGenome> genomeFactory = experiment.CreateGenomeFactory();

        // Create an initial population of randomly generated genomes.
        // 0u is a struct for a 32 bit unsigned integer
        List <NeatGenome> genomeList = genomeFactory.CreateGenomeList(popSize.Value, 0u);

        // Check number of species is <= the number of the genomes.
        if (genomeList.Count < experiment.NeatEvolutionAlgorithmParameters.SpecieCount)
        {
            Debug.Log("Genome count must be >= specie count. Genomes=" + genomeList.Count
                      + "  Species=" + experiment.NeatEvolutionAlgorithmParameters.SpecieCount);
            return;
        }

        /*** Create the algorithm interface ***/
        contentEA = experiment.CreateEvolutionAlgorithm(genomeFactory, genomeList);
    }
示例#2
0
        /// <summary>
        /// Loads a list of genomes from the save file fitting the experiment name and the ExperimentFileType.
        /// </summary>
        private static List <NeatGenome> ReadGenomes(INeatExperiment experiment, ExperimentFileType fileType, bool createNewGenesIfNotLoadable = true)
        {
            List <NeatGenome> genomeList    = null;
            NeatGenomeFactory genomeFactory = (NeatGenomeFactory)experiment.CreateGenomeFactory();

            string filePath = GetSaveFilePath(experiment.Name, fileType);

            try
            {
                using (XmlReader xr = XmlReader.Create(filePath))
                {
                    genomeList = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, genomeFactory);

                    if (genomeList != null && genomeList.Count > 0)
                    {
                        Utility.Log("Successfully loaded the genomes of the '" + fileType.ToString() + "' for the experiment '" + experiment.Name + "' from the location:\n" + filePath);
                    }
                }
            }
            catch (Exception e1)
            {
                Utility.Log("Error loading genome from file, could not find the file at: " + filePath + "\n" + e1.Message);

                if (createNewGenesIfNotLoadable)
                {
                    genomeList = genomeFactory.CreateGenomeList(experiment.DefaultPopulationSize, 0);
                }
            }
            return(genomeList);
        }
示例#3
0
        private NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm()
        {
            int popSize = _experiment.DefaultPopulationSize;
            IGenomeFactory <NeatGenome>         genomeFactory = _experiment.CreateGenomeFactory();
            List <NeatGenome>                   genomeList    = genomeFactory.CreateGenomeList(popSize, 0);
            NeatEvolutionAlgorithm <NeatGenome> ea            = _experiment.CreateEvolutionAlgorithm(genomeFactory, genomeList);

            return(ea);
        }
示例#4
0
    public static IBlackBox LoadBrain(string filePath, INeatExperiment experiment)
    {
        NeatGenome genome = null;


        // Try to load the genome from the XML document.
        try
        {
            using (XmlReader xr = XmlReader.Create(filePath))
                genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory())[0];
        }
        catch (Exception e1)
        {
            print(filePath + " Error loading genome from file!\nLoading aborted.\n"
                  + e1.Message + "\nJoe: " + filePath);
            return(null);
        }

        // Get a genome decoder that can convert genomes to phenomes.
        var genomeDecoder = experiment.CreateGenomeDecoder();

        // Decode the genome into a phenome (neural network).
        var phenome = genomeDecoder.Decode(genome);

        return(phenome);
    }
示例#5
0
    //public static IBlackBox LoadBrain(string filePath)
    //{
    //    OptimizationExperiment experiment = new OptimizationExperiment();
    //    XmlDocument xmlConfig = new XmlDocument();
    //    TextAsset textAsset = (TextAsset)Resources.Load("phototaxis.config");
    //    //      xmlConfig.Load(OptimizerParameters.ConfigFile);
    //    xmlConfig.LoadXml(textAsset.text);
    // //   experiment.SetOptimizer(this);
    //    experiment.Initialize(OptimizerParameters.Name, xmlConfig.DocumentElement, OptimizerParameters.NumInputs, OptimizerParameters.NumOutputs);
    //    return LoadBrain(filePath, experiment);
    //}
    public static IBlackBox LoadBrain(string filePath, INeatExperiment experiment)
    {
        NeatGenome genome = null;

        // Try to load the genome from the XML document.
        try
        {
            using (XmlReader xr = XmlReader.Create(filePath))
                genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory())[0];
        }
        catch (Exception e1)
        {
            print(filePath + " Error loading genome from file!\nLoading aborted.\n"
                                      + e1.Message + "\nJoe: " + filePath);
            return null;
        }

        // Get a genome decoder that can convert genomes to phenomes.
        var genomeDecoder = experiment.CreateGenomeDecoder();

        // Decode the genome into a phenome (neural network).
        var phenome = genomeDecoder.Decode(genome);

        return phenome;
    }
    public void Initialize()
    {
        /*** Initialize experiment ***/
        experiment = new PCGNeatExperiment() as INeatExperiment;
        // Null because not reading settings from xmlFile
        experiment.Initialize("PCG Conetent EA",null);

        /*** Randomly generate population ***/
        // Set initial settings
        // ? means it is nullable
        int? popSize = experiment.DefaultPopulationSize;

        // Create a genome factory appropriate for the experiment.
        IGenomeFactory<NeatGenome> genomeFactory = experiment.CreateGenomeFactory();

        // Create an initial population of randomly generated genomes.
        // 0u is a struct for a 32 bit unsigned integer
        List<NeatGenome> genomeList = genomeFactory.CreateGenomeList(popSize.Value, 0u);

        // Check number of species is <= the number of the genomes.
        if (genomeList.Count < experiment.NeatEvolutionAlgorithmParameters.SpecieCount)
        {
            Debug.Log("Genome count must be >= specie count. Genomes=" + genomeList.Count
                + "  Species=" + experiment.NeatEvolutionAlgorithmParameters.SpecieCount);
            return;
        }

        /*** Create the algorithm interface ***/
        contentEA = experiment.CreateEvolutionAlgorithm(genomeFactory, genomeList);
    }
示例#7
0
文件: Program.cs 项目: rinde/NeatSim
        static void Main(string[] args)
        {
            // This program expects certain command line options, that are defined as annotated properties in the NeatSimConsole.Options class
            // We instantiate this class...
            _options = new Options();
            // ... and pass the arguments to this program to the options parser, who uses it to set the properties in 'options'.
            // If the command line options are incorrect, ParseArgumentsStrict prints a help message to the screen and exits...
            if (!CommandLine.Parser.Default.ParseArgumentsStrict(args, _options))
            {
                // ... therefore, this should really never ever happen.
                throw new SystemException("Something went wrong parsing arguments.");
            }
            // Now, all the properties in 'options' are set.

            FastRandom.__seedRng = new FastRandom(_options.Seed);

            // Initialise log4net (log to console).
            // XmlConfigurator.Configure(new FileInfo("log4net.properties"));


            // We instatiate a remote batch simulation experiment, and use the properties set in the XML file to initialize the experiment.
            // The XML file contains properties like the number of generations to run the program for, and the number of individuals in the population.
            // For properties that are not set in the XML file, we initialize default values.
            _experiment = new RemoteBatchSimExperiment();
            var xmlConfig = new XmlDocument();

            try
            {
                xmlConfig.Load("neatsim.config.xml");
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(@"Could not find neatsim.config.xml. Aborting.");
                return;
            }

            _experiment.Initialize("NeatSim", xmlConfig.DocumentElement);
            // The XML file cannot contain information about the inital number of connected neurons.
            // We want to initialize our population minimally, and do this by setting an absurdly small initial connections proportion.
            // The number of connected input neurons will always be at least one.
            // Note that there is an absurdly small chance that more than a single neuron will be connected in generation one.
            _experiment.NeatGenomeParameters.InitialInterconnectionsProportion = 0.0000000000001;

            // Create a genome factory with our neat genome parameters object and the appropriate number of input and output neuron genes.
            _genomeFactory = _experiment.CreateGenomeFactory();
            // Create an initial population of randomly generated genomes ('born' in generation 0).
            _genomeList = _genomeFactory.CreateGenomeList(_options.PopulationSize, 0);

            // Create evolution algorithm and attach update events.
            _ea              = _experiment.CreateEvolutionAlgorithm(_genomeFactory, _genomeList);
            _ea.PausedEvent += (s, e) => Console.WriteLine(_ea.RunState == RunState.Paused
                                                               ? @"Program is paused"
                                                               : _ea.RunState == RunState.Running
                                                                     ? @"Program is unpaused."
                                                                     : @"Program is in unknown state...");
            _neatSimLogger = new NeatSimLogger(_options.LogFileName + '_' + DateTime.Now.ToString("yyyyMMdd"));
            //
            var nextGeneration = _ea.CurrentGeneration;
            var doneEvent      = new AutoResetEvent(false);

            _ea.UpdateEvent += (s, e) =>
            {
                if (_ea.CurrentGeneration < nextGeneration)
                {
                    Console.WriteLine("Aborting!");
                    return;
                }
                Console.WriteLine(string.Format("gen={0:N0} bestFitness={1:N6}", _ea.CurrentGeneration, _ea.Statistics._maxFitness));
                SaveChampionGenome();
                _neatSimLogger.Log(_ea);
                if (_ea.CurrentGeneration >= _options.Generations)
                {
                    _ea.Stop();
                    _neatSimLogger.Close();
                    doneEvent.Set();
                }
                nextGeneration++;
            };

            // Start algorithm (it will run on a background thread).
            _ea.StartContinue();

            // Hit return to quit.
            //Console.ReadLine();
            doneEvent.WaitOne();
        }
示例#8
0
        static void Main(string[] args)
        {
            // This program expects certain command line options, that are defined as annotated properties in the NeatSimConsole.Options class
            // We instantiate this class...
            _options = new Options();
            // ... and pass the arguments to this program to the options parser, who uses it to set the properties in 'options'.
            // If the command line options are incorrect, ParseArgumentsStrict prints a help message to the screen and exits...
            if (!CommandLine.Parser.Default.ParseArgumentsStrict(args, _options))
            {
                // ... therefore, this should really never ever happen.
                throw new SystemException("Something went wrong parsing arguments.");
            }
            // Now, all the properties in 'options' are set.

            FastRandom.__seedRng = new FastRandom(_options.Seed);

            // Initialise log4net (log to console). 
            // XmlConfigurator.Configure(new FileInfo("log4net.properties"));

            
            // We instatiate a remote batch simulation experiment, and use the properties set in the XML file to initialize the experiment.
            // The XML file contains properties like the number of generations to run the program for, and the number of individuals in the population.
            // For properties that are not set in the XML file, we initialize default values.
            _experiment = new RemoteBatchSimExperiment();
            var xmlConfig = new XmlDocument();
            try
            {
                xmlConfig.Load("neatsim.config.xml");
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(@"Could not find neatsim.config.xml. Aborting.");
                return;
            }

            _experiment.Initialize("NeatSim", xmlConfig.DocumentElement);
            // The XML file cannot contain information about the inital number of connected neurons.
            // We want to initialize our population minimally, and do this by setting an absurdly small initial connections proportion.
            // The number of connected input neurons will always be at least one.
            // Note that there is an absurdly small chance that more than a single neuron will be connected in generation one.
            _experiment.NeatGenomeParameters.InitialInterconnectionsProportion = 0.0000000000001;

            // Create a genome factory with our neat genome parameters object and the appropriate number of input and output neuron genes.
            _genomeFactory = _experiment.CreateGenomeFactory();
            // Create an initial population of randomly generated genomes ('born' in generation 0).
            _genomeList = _genomeFactory.CreateGenomeList(_options.PopulationSize, 0);

            // Create evolution algorithm and attach update events.
            _ea = _experiment.CreateEvolutionAlgorithm(_genomeFactory, _genomeList);
            _ea.PausedEvent += (s, e) => Console.WriteLine(_ea.RunState == RunState.Paused
                                                               ? @"Program is paused"
                                                               : _ea.RunState == RunState.Running
                                                                     ? @"Program is unpaused."
                                                                     : @"Program is in unknown state...");
            _neatSimLogger = new NeatSimLogger(_options.LogFileName + '_' + DateTime.Now.ToString("yyyyMMdd"));
            //
            var nextGeneration = _ea.CurrentGeneration;
            var doneEvent = new AutoResetEvent(false);
            _ea.UpdateEvent += (s, e) =>
                {
                    if (_ea.CurrentGeneration < nextGeneration)
                    {
                        Console.WriteLine("Aborting!");
                        return;
                    }
                    Console.WriteLine(string.Format("gen={0:N0} bestFitness={1:N6}", _ea.CurrentGeneration, _ea.Statistics._maxFitness));
                    SaveChampionGenome();
                    _neatSimLogger.Log(_ea);
                    if (_ea.CurrentGeneration >= _options.Generations)
                    {
                        _ea.Stop();
                        _neatSimLogger.Close();
                        doneEvent.Set();
                    }
                    nextGeneration++;
                };

            // Start algorithm (it will run on a background thread).
            _ea.StartContinue();

            // Hit return to quit.
            //Console.ReadLine();
            doneEvent.WaitOne();
        }