Beispiel #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);
    }
        /// <summary>
        /// Writes a list of genomes to the save file fitting the experiment name and the ExperimentFileType.
        /// </summary>
        private static bool WriteGenomes(INeatExperiment experiment, IList <NeatGenome> genomeList, ExperimentFileType fileType)
        {
            XmlWriterSettings _xwSettings = new XmlWriterSettings();

            _xwSettings.Indent = true;

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

            DirectoryInfo dirInf = new DirectoryInfo(Application.persistentDataPath);

            if (!dirInf.Exists)
            {
                Debug.Log("ExperimentIO - Creating subdirectory");
                dirInf.Create();
            }
            try
            {
                using (XmlWriter xw = XmlWriter.Create(filePath, _xwSettings))
                {
                    NeatGenomeXmlIO.WriteComplete(xw, genomeList, false);
                    Debug.Log("Successfully saved the genomes of the '" + fileType.ToString() + "' for the experiment '" + experiment.Name + "' to the location:\n" + filePath);
                }
            }
            catch (Exception e1)
            {
                Debug.Log("Error saving the genomes of the '" + fileType.ToString() + "' for the experiment '" + experiment.Name + "' to the location:\n" + filePath);
                return(false);
            }
            return(true);
        }
Beispiel #3
0
    // Initialize with pre-existing xml data
    public void Initialize(string xmlData)
    {
        /*** Initialize experiment ***/
        experiment = new PCGNeatExperiment() as INeatExperiment;
        // Null because not reading settings from xmlFile
        experiment.Initialize("PCG Conetent EA", null);

        /*** Load population of genomes from xml string ***/
        List <NeatGenome> genomeList;

        using (XmlReader xr = XmlReader.Create(new StringReader(xmlData)))
        {
            genomeList = experiment.LoadPopulation(xr);
        }

        if (genomeList.Count == 0)
        {
            Debug.LogError("No genomes loaded from XML data from network. Check data is being read correctly.");
            return;
        }
        else
        {
            Debug.Log("Loaded " + genomeList.Count + " Genomes");
        }

        /*** Create the algorithm interface ***/
        contentEA = experiment.CreateEvolutionAlgorithm(genomeList[0].GenomeFactory, genomeList);
    }
        /// <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);
        }
        /// <summary>
        /// Deletes all savefiles of the specified experiment, which is the population file and the champion file (best genome).
        /// </summary>
        public static void DeleteAllSaveFiles(INeatExperiment experiment)
        {
            File.Delete(GetSaveFilePath(experiment.Name, ExperimentFileType.Champion));
            File.Delete(GetSaveFilePath(experiment.Name, ExperimentFileType.Population));

            Debug.Log("ExperimentIO - Deleted all savefiles.");
        }
    // Initialize with pre-existing xml data
    public void Initialize(string xmlData, PCGSharpHighLevelFeatures originalFeatures)
    {
        /*** Initialize experiment ***/
        experiment = new CPPNRepairExperiment() as INeatExperiment;
        // Null because not reading settings from xmlFile
        experiment.Initialize("PCG Conetent EA", null);

        /*** Load population of genomes from xml string ***/
        List <NeatGenome> genomeList;

        using (XmlReader xr = XmlReader.Create(new StringReader(xmlData)))
        {
            genomeList = experiment.LoadPopulation(xr);
        }

        if (genomeList.Count == 0)
        {
            Debug.LogError("No genomes loaded from XML data from network. Check data is being read correctly.");
            return;
        }
        else
        {
            Debug.Log("Loaded " + genomeList.Count + " Genomes");
        }
        Debug.Log(".........Population loaded");

        ((CPPNRepairExperiment)experiment).SetOriginalFeatures(originalFeatures);
        Debug.Log("........Original features added to experiment");

        /*** Create the algorithm interface ***/
        contentEA = experiment.CreateEvolutionAlgorithm(genomeList[0].GenomeFactory, genomeList);
        Debug.Log("........Content EA created");
    }
    private void btnSearchStart_Click(object sender, EventArgs e)
    {
        if (_eaRunner is not null)
        {   // Resume existing EA & update GUI state.
            _eaRunner.StartOrResume();
            UpdateUIState();
            return;
        }

        // Get the current neat experiment, with parameters set from the UI.
        INeatExperiment <double> neatExperiment = GetNeatExperiment();

        // Create evolution algorithm and runner.
        NeatEvolutionAlgorithm <double> ea = NeatUtils.CreateNeatEvolutionAlgorithm(neatExperiment, _neatPop);

        ea.Initialise();

        _eaRunner = new EvolutionAlgorithmRunner(ea, UpdateScheme.CreateTimeSpanUpdateScheme(TimeSpan.FromSeconds(1)));

        // Attach event listeners.
        _eaRunner.UpdateEvent += _eaRunner_UpdateEvent;

        // Start the algorithm & update GUI state.
        _eaRunner.StartOrResume();
        UpdateUIState();
    }
Beispiel #8
0
        public GenomeIo(INeatExperiment neatExperiment)
        {
            _neatExperiment = neatExperiment;

            _championGenomeMemoryStream = new MemoryStream();
            _xmlWriterSettings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 };
        }
Beispiel #9
0
        /// <summary>
        /// Create a new instance of <see cref="NeatEvolutionAlgorithm{T}"/> for the given neat experiment, and neat population.
        /// </summary>
        /// <param name="neatExperiment">A neat experiment instance; this conveys everything required to create a new evolution algorithm instance that is ready to be run.</param>
        /// <param name="neatPop">A pre constructed/loaded neat population; this must be compatible with the provided neat experiment, otherwise an exception will be thrown.</param>
        /// <returns>A new instance of <see cref="NeatEvolutionAlgorithm{T}"/>.</returns>
        public static NeatEvolutionAlgorithm <double> CreateNeatEvolutionAlgorithm(
            INeatExperiment <double> neatExperiment,
            NeatPopulation <double> neatPop)
        {
            // Validate MetaNeatGenome and NeatExperiment are compatible; normally the former should have been created based on the latter, but this is not enforced.
            MetaNeatGenome <double> metaNeatGenome = neatPop.MetaNeatGenome;

            ValidateCompatible(neatExperiment, metaNeatGenome);

            // Create a genomeList evaluator based on the experiment's configuration settings.
            var genomeListEvaluator = CreateGenomeListEvaluator(neatExperiment);

            // Create a speciation strategy based on the experiment's configuration settings.
            var speciationStrategy = CreateSpeciationStrategy(neatExperiment);

            // Create an instance of the default connection weight mutation scheme.
            var weightMutationScheme = WeightMutationSchemeFactory.CreateDefaultScheme(neatExperiment.ConnectionWeightScale);

            // Pull all of the parts together into an evolution algorithm instance.
            var ea = new NeatEvolutionAlgorithm <double>(
                neatExperiment.NeatEvolutionAlgorithmSettings,
                genomeListEvaluator,
                speciationStrategy,
                neatPop,
                neatExperiment.ComplexityRegulationStrategy,
                neatExperiment.ReproductionAsexualSettings,
                neatExperiment.ReproductionSexualSettings,
                weightMutationScheme);

            return(ea);
        }
Beispiel #10
0
        /// <summary>
        /// Create a new instance of <see cref="NeatEvolutionAlgorithm{T}"/> for the given neat experiment.
        /// </summary>
        /// <param name="neatExperiment">A neat experiment instance; this conveys everything required to create a new evolution algorithm instance that is ready to be run.</param>
        /// <returns>A new instance of <see cref="NeatEvolutionAlgorithm{T}"/>.</returns>
        public static NeatEvolutionAlgorithm <double> CreateNeatEvolutionAlgorithm(
            INeatExperiment <double> neatExperiment)
        {
            // Create a genomeList evaluator based on the experiment's configuration settings.
            var genomeListEvaluator = CreateGenomeListEvaluator(neatExperiment);

            // Create a MetaNeatGenome.
            var metaNeatGenome = CreateMetaNeatGenome(neatExperiment);

            // Create an initial population of genomes.
            NeatPopulation <double> neatPop = NeatPopulationFactory <double> .CreatePopulation(
                metaNeatGenome,
                connectionsProportion : neatExperiment.InitialInterconnectionsProportion,
                popSize : neatExperiment.PopulationSize);

            // Create a speciation strategy based on the experiment's configuration settings.
            var speciationStrategy = CreateSpeciationStrategy(neatExperiment);

            // Create an instance of the default connection weight mutation scheme.
            var weightMutationScheme = WeightMutationSchemeFactory.CreateDefaultScheme(neatExperiment.ConnectionWeightScale);

            // Pull all of the parts together into an evolution algorithm instance.
            var ea = new NeatEvolutionAlgorithm <double>(
                neatExperiment.NeatEvolutionAlgorithmSettings,
                genomeListEvaluator,
                speciationStrategy,
                neatPop,
                neatExperiment.ComplexityRegulationStrategy,
                neatExperiment.ReproductionAsexualSettings,
                neatExperiment.ReproductionSexualSettings,
                weightMutationScheme);

            return(ea);
        }
Beispiel #11
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);
    }
 private static void ReadNeatReproductionSexualSettings(
     INeatExperiment <T> target, JsonElement jelem)
 {
     if (jelem.TryGetProperty("reproductionSexualSettings", out JsonElement settingsElem))
     {
         NeatReproductionSexualSettingsJsonReader.Read(target.ReproductionSexualSettings, settingsElem);
     }
 }
 private static void ReadNeatEvolutionAlgorithmSettings(
     INeatExperiment <T> target, JsonElement jelem)
 {
     if (jelem.TryGetProperty("evolutionAlgorithmSettings", out JsonElement settingsElem))
     {
         NeatEvolutionAlgorithmSettingsJsonReader.Read(target.NeatEvolutionAlgorithmSettings, settingsElem);
     }
 }
        private void GetSettingsFromUI(INeatExperiment <double> experiment)
        {
            GetSettingsFromUI(experiment.NeatEvolutionAlgorithmSettings);
            GetSettingsFromUI(experiment.ReproductionAsexualSettings);

            experiment.PopulationSize = GetValue(txtPopulationSize, experiment.PopulationSize);
            experiment.InitialInterconnectionsProportion = GetValue(txtInitialInterconnectionsProportion, experiment.InitialInterconnectionsProportion);
        }
Beispiel #15
0
        public static List <NeatGenome> ReadChampions(INeatExperiment experiment)
        {
            return(ReadChampionGenomes(experiment, ExperimentFileType.Population, false));
            // if (championPop == null || championPop.Count == 0)
            //     return null;

            // return championPop[0];
        }
 private static void ReadComplexityRegulationStrategy(
     INeatExperiment <T> target, JsonElement jelem)
 {
     if (jelem.TryGetProperty("complexityRegulationStrategy", out JsonElement settingsElem))
     {
         target.ComplexityRegulationStrategy = ComplexityRegulationStrategyJsonReader.Read(settingsElem);
     }
 }
Beispiel #17
0
 public EvolutionAlgorithmHostGenerational(
     INeatExperiment <double> experiment,
     int stopGenerationCount)
 {
     _experiment          = experiment;
     _stopGenerationCount = stopGenerationCount;
     _stopwatch           = new Stopwatch();
 }
Beispiel #18
0
    static void Main(string[] args)
    {
        // Intercept termination of the console app, to flush and close the output file stream
        // (apparently the 'finally' block below is not executed if the app is terminated with Ctrl-C).
        Console.CancelKeyPress += delegate
        {
            if (__streamWriter is not null)
            {
                __streamWriter.Close();
            }
        };

        // Read command line arguments.
        StopCondition?stopCond = ArgUtils.ReadArgs(args, out string?experimentId, out string?filename);

        if (stopCond is null || experimentId is null || filename is null)
        {
            return;
        }

        // Initialise log4net (log to console).
        var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.properties"));

        // Create and configure a NEAT experiment instance.
        INeatExperiment <double>?experiment = InitExperiment(experimentId);

        if (experiment is null)
        {
            return;
        }

        // Create an evolution algorithm host.
        IEvolutionAlgorithmHost eaHost = CreateEvolutionAlgorithmHost(experiment, stopCond);

        // Open and initialise the output file.
        __streamWriter = InitOutputFile(filename);
        try
        {
            // Run the main efficacy sampling loop until the process is terminated.
            for (;;)
            {
                Sample s = eaHost.Sample();
                __streamWriter.WriteLine($"{s.ElapsedTimeSecs},{s.GenerationCount},{s.BestFitness:0.#####},{s.MeanFitness:0.#####},{s.MaxComplexity:0.#####},{s.MeanComplexity:0.#####},{s.EvaluationCount}");
                __streamWriter.Flush();
            }
        }
        finally
        {
            if (__streamWriter is not null)
            {
                __streamWriter.Close();
            }
        }
    }
 private static IEvolutionAlgorithmHost CreateEvolutionAlgorithmHost(
     INeatExperiment <double> experiment,
     StopCondition stopCond)
 {
     return(stopCond.StopConditionType switch
     {
         StopConditionType.ElapsedClockTime => new EvolutionAlgorithmHostClockTime(experiment, stopCond.Value),
         StopConditionType.GenerationCount => new EvolutionAlgorithmHostGenerational(experiment, stopCond.Value),
         _ => throw new ArgumentException(nameof(stopCond)),
     });
Beispiel #20
0
        private static void ReadNeatReproductionAsexualSettings(
            INeatExperiment <T> target, JObject jobj)
        {
            JObject settingsJobj = (JObject)jobj["reproductionAsexualSettings"];

            if (settingsJobj != null)
            {
                NeatReproductionAsexualSettingsJsonReader.Read(target.ReproductionAsexualSettings, settingsJobj);
            }
        }
Beispiel #21
0
        private static void ReadNeatEvolutionAlgorithmSettings(
            INeatExperiment <T> target, JObject jobj)
        {
            JObject settingsJobj = (JObject)jobj["evolutionAlgorithmSettings"];

            if (settingsJobj != null)
            {
                NeatEvolutionAlgorithmSettingsJsonReader.Read(target.NeatEvolutionAlgorithmSettings, settingsJobj);
            }
        }
Beispiel #22
0
        private static void ReadComplexityRegulationStrategy(
            INeatExperiment <T> target, JObject jobj)
        {
            JObject settingsJobj = (JObject)jobj["complexityRegulationStrategy"];

            if (settingsJobj != null)
            {
                target.ComplexityRegulationStrategy = ComplexityRegulationStrategyJsonReader.Read(settingsJobj);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Loads the saved champion genome from the champion safe file of the specified experiment (by default: myexperimentname.champ.xml).
        /// If the file does not exist, then null is returned.
        /// </summary>
        public static NeatGenome ReadChampion(INeatExperiment experiment)
        {
            List <NeatGenome> championPop = ReadGenomes(experiment, ExperimentFileType.Champion, false);

            if (championPop == null || championPop.Count == 0)
            {
                return(null);
            }

            return(championPop[0]);
        }
Beispiel #24
0
        private static INeatExperiment <double> InitExperiment_BinaryElevenMultiplexer()
        {
            // Read experiment json config from file.
            // Note. We read the entire contents into a string; we don't ever expect to see large json files here, so this fine.
            string jsonStr = File.ReadAllText("config/binary-eleven-multiplexer.config.json");

            // Create an instance of INeatExperiment for the binary 11-multiplexer task, configured using the supplied json config.
            var experimentFactory = new BinaryElevenMultiplexerExperimentFactory();
            INeatExperiment <double> neatExperiment = experimentFactory.CreateExperiment(jsonStr);

            return(neatExperiment);
        }
Beispiel #25
0
    private INeatExperiment <double> GetNeatExperiment()
    {
        // Create a new experiment instance if one has not already been created.
        if (_neatExperiment is null)
        {
            _neatExperiment = CreateAndConfigureExperiment((ExperimentInfo)cmbExperiments.SelectedItem);
        }

        // Read settings from the UI into the experiment instance, and return.
        GetSettingsFromUI(_neatExperiment);
        return(_neatExperiment);
    }
Beispiel #26
0
        private static INeatExperiment <double> InitExperiment_Sinewave()
        {
            // Read experiment json config from file.
            // Note. We read the entire contents into a string; we don't ever expect to see large json files here, so this fine.
            string jsonStr = File.ReadAllText("config/generative-sinewave.config.json");

            // Create an instance of INeatExperiment for the generative sinewave task, configured using the supplied json config.
            var experimentFactory = new GenerativeFnRegressionExperimentFactory();
            INeatExperiment <double> neatExperiment = experimentFactory.CreateExperiment(jsonStr);

            return(neatExperiment);
        }
Beispiel #27
0
 private static IGenomeDecoder <NeatGenome <double>, IBlackBox <double> > CreateGenomeDecoder(
     INeatExperiment <double> neatExperiment)
 {
     if (neatExperiment.IsAcyclic)
     {
         return(NeatGenomeDecoderFactory.CreateGenomeDecoderAcyclic(
                    neatExperiment.EnableHardwareAcceleratedNeuralNets));
     }
     return(NeatGenomeDecoderFactory.CreateGenomeDecoderCyclic(
                neatExperiment.CyclesPerActivation,
                neatExperiment.EnableHardwareAcceleratedNeuralNets));
 }
Beispiel #28
0
        /// <summary>
        /// Read json from a file into a target instance of <see cref="NeatExperiment{T}"/>.
        /// Settings that are present are read and set on the target settings object; all other settings
        /// remain unchanged on the target object.
        /// </summary>
        /// <param name="target">The target settings object to store the read values on.</param>
        /// <param name="filename">The filename of the json to read from.</param>
        public static void ReadFile(
            INeatExperiment <T> target, string filename)
        {
            // Read the entire contents into a string; we don't ever expect to see large json files here, so this fine.
            string jsonStr = File.ReadAllText(filename);

            // TODO: Switch to System.Text.Json.JsonDocument.
            // Parse the json string.
            var jobj = JObject.Parse(jsonStr);

            // Read the parsed json into our target experiment object.
            Read(target, jobj);
        }
Beispiel #29
0
    private void btnCreateRandomPop_Click(object sender, EventArgs e)
    {
        INeatExperiment <double> neatExperiment = GetNeatExperiment();
        MetaNeatGenome <double>  metaNeatGenome = NeatUtils.CreateMetaNeatGenome(neatExperiment);

        // Create an initial population of genomes.
        _neatPop = NeatPopulationFactory <double> .CreatePopulation(
            metaNeatGenome,
            connectionsProportion : neatExperiment.InitialInterconnectionsProportion,
            popSize : neatExperiment.PopulationSize);

        // Update UI.
        UpdateUIState();
    }
Beispiel #30
0
        /// <summary>
        /// Create a <see cref="MetaNeatGenome{T}"/> based on the parameters supplied by an <see cref="INeatExperiment{T}"/>.
        /// </summary>
        /// <param name="neatExperiment">The neat experiment.</param>
        /// <returns>A new instance of <see cref="MetaNeatGenome{T}"/>.</returns>
        public static MetaNeatGenome <double> CreateMetaNeatGenome(INeatExperiment <double> neatExperiment)
        {
            // Resolve the configured activation function name to an activation function instance.
            var actFnFactory = new DefaultActivationFunctionFactory <double>(neatExperiment.EnableHardwareAcceleratedActivationFunctions);
            var activationFn = actFnFactory.GetActivationFunction(neatExperiment.ActivationFnName);

            var metaNeatGenome = new MetaNeatGenome <double>(
                inputNodeCount: neatExperiment.EvaluationScheme.InputCount,
                outputNodeCount: neatExperiment.EvaluationScheme.OutputCount,
                isAcyclic: neatExperiment.IsAcyclic,
                activationFn: activationFn,
                connectionWeightScale: neatExperiment.ConnectionWeightScale);

            return(metaNeatGenome);
        }
Beispiel #31
0
    private void cmbExperiments_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Clear any existing references, as these are specific to each experiment.
        _neatExperiment = null;
        _experimentUI   = null;

        // Close the genome form if it is open, as the content of this form is specific to each experiment.
        GenomeForm bestGenomeForm = _bestGenomeForm;

        if (bestGenomeForm is not null)
        {
            // Note. This will trigger the FormClosed event which will do further clean-up; Close() will also Dispose() the form.
            bestGenomeForm.Close();
        }
    }
    // Initialize with pre-existing xml data
    public void Initialize(string xmlData)
    {
        /*** Initialize experiment ***/
        experiment = new PCGNeatExperiment() as INeatExperiment;
        // Null because not reading settings from xmlFile
        experiment.Initialize("PCG Conetent EA",null);

        /*** Load population of genomes from xml string ***/
        List<NeatGenome> genomeList;
        using(XmlReader xr = XmlReader.Create(new StringReader(xmlData)))
        {
            genomeList = experiment.LoadPopulation(xr);
        }

        if(genomeList.Count == 0) {
            Debug.LogError("No genomes loaded from XML data from network. Check data is being read correctly.");
            return;
        }
        else
            Debug.Log("Loaded " + genomeList.Count + " Genomes");

        /*** Create the algorithm interface ***/
        contentEA = experiment.CreateEvolutionAlgorithm(genomeList[0].GenomeFactory, genomeList);
    }
    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);
    }
Beispiel #34
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;
    }
Beispiel #35
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();
        }