Ejemplo n.º 1
0
        private void initializeNetworks()
        {
            //UpdateMessage("Loading neural networks.");
            // initialize modules
            const string      CHAMPION_FILE = @"host_parasite_champion_to_load.xml";
            List <NeatGenome> anns;

            XmlConfigurator.Configure(new System.IO.FileInfo("log4net.properties"));

            // Load config XML.
            XmlDocument xmlConfig = new XmlDocument();
            //load genomes
            // Save the best genome to file
            XmlReaderSettings xwSettings = new XmlReaderSettings();

            using (XmlReader xw = XmlReader.Create(CHAMPION_FILE, xwSettings))
            {
                anns = NeatGenomeXmlIO.ReadCompleteGenomeList(xw, false);
            }

            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new NeatGenomeDecoder(new SharpNeat.Decoders.NetworkActivationScheme(2));

            rhythm1 = new NeatPlayer(genomeDecoder.Decode(anns[0]));
            rhythm2 = new NeatPlayer(genomeDecoder.Decode(anns[1]));
            pitch1  = new NeatPlayer(genomeDecoder.Decode(anns[2]));
            pitch2  = new NeatPlayer(genomeDecoder.Decode(anns[3]));
        }
Ejemplo n.º 2
0
    public void RunBest()
    {
        Time.timeScale = 1;

        NeatGenome genome = null;


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

        // 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);

        GameObject     obj        = Instantiate(Unit, Unit.transform.position, Unit.transform.rotation) as GameObject;
        UnitController controller = obj.GetComponent <UnitController>();

        ControllerMap.Add(phenome, controller);

        controller.Activate(phenome);
    }
        public void RunBest()
        {
            Time.timeScale = 1;

            NeatGenome genome = null;

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

            // Genomedecoders convert genomes to pheonomes
            var genomeDecoder = experiment.CreateGenomeDecoder();

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

            GameObject obj = Instantiate(Unit, transform.position, Unit.transform.rotation) as GameObject;

            obj.AddComponent <Creature>();
            UnitController controller = obj.GetComponent <UnitController>();

            ControllerMap.Add(phenome, controller);

            controller.Activate(phenome);
        }
Ejemplo n.º 4
0
        public List <NeatGenome> LoadPopulation(string filename, int amountToLoad)
        {
            if (File.Exists(Application.dataPath + HelperConstants.saveDirectory + filename))
            {
                List <NeatGenome> genomes;
                using (XmlReader xr = XmlReader.Create(Application.dataPath + HelperConstants.saveDirectory + filename))
                {
                    NeatGenomeFactory genomeFactory = (NeatGenomeFactory)CreateGenomeFactory();
                    genomes = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, genomeFactory);
                }

                var newGenomes = new List <NeatGenome>(amountToLoad);
                while (newGenomes.Count < amountToLoad)
                {
                    for (int i = 0; i < genomes.Count; i++)
                    {
                        if (newGenomes.Count >= amountToLoad)
                        {
                            break;
                        }
                        newGenomes.Add(genomes[i]);
                    }
                }
                Debug.Assert(newGenomes.Count == amountToLoad);
                return(newGenomes);
            }
            else
            {
                Debug.Log("Could not load pop from " + Application.dataPath + HelperConstants.saveDirectory + filename);
                return(null);
            }
        }
Ejemplo n.º 5
0
    private NeatGenome loadGenome(string filename)
    {
        NeatGenome genome = null;

        DirectoryInfo dir = new DirectoryInfo(Application.persistentDataPath + string.Format("/{0}", folder_prefix));

        if (dir.Exists)
        {
            FileInfo[] info = dir.GetFiles(filename + ".xml");
            print(info.Length);
            foreach (FileInfo f in info)
            {
                try {
                    using (XmlReader xr = XmlReader.Create(Application.persistentDataPath + string.Format("/{0}/{1}", folder_prefix, f.Name)))
                        genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory()) [0];
                } catch (Exception e1) {
                    print(" Error loading genome from file!\nLoading aborted.\n" + e1.Message);
                    continue;
                }
            }
//				Debug.Log ("Filled map with " + map + " elites.");
//			}
        }



        return(genome);
    }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Load a population of genomes from an XmlReader and returns the genomes in a new list.
        /// The genome factory for the genomes can be obtained from any one of the genomes.
        /// </summary>
        public List <NeatGenome> LoadPopulation(XmlReader xr)
        {
            NeatGenomeFactory genomeFactory = (NeatGenomeFactory)CreateGenomeFactory();

            return(NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, genomeFactory));
            // return NeatGenomeUtils.LoadPopulation(xr, false, this.InputCount, this.OutputCount);
        }
Ejemplo n.º 8
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);
    }
Ejemplo n.º 9
0
        private static void Play()
        {
            var       neatGenomeFactory = new NeatGenomeFactory(NeatConsts.ViewX * NeatConsts.ViewY * NeatConsts.typeIds.Count, 1);
            var       activationScheme  = NetworkActivationScheme.CreateCyclicFixedTimestepsScheme(1);
            var       genomeDecoder     = new NeatGenomeDecoder(activationScheme);
            XmlReader xr;

            while (true)
            {
                try
                {
                    xr = XmlReader.Create($"{NeatConsts.experimentName}/best.xml");
                    break;
                }
                catch (Exception)
                {
                }
            }
            var genome  = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, neatGenomeFactory)[0];
            var phenome = genomeDecoder.Decode(genome);

            using var game = new Game(true);
            var brain = new BlackBoxBrain(phenome, game);

            while (!game.hasEnded)
            {
                brain.Step();
                Thread.Sleep(200);
            }
        }
Ejemplo n.º 10
0
    public void RunBest()
    {
        Time.timeScale = 1;
        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("Error loading genome from file!\nLoading aborted.\n"
                  + e1.Message);
            return;
        }

        // 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);

        Reset();
        carMove.Activate(phenome, Target);
    }
Ejemplo n.º 11
0
    /**
     * Assigns an AI brain to this player. This is used when
     * loading a brain from an existing neural network xml champion file.
     */
    public AIFighter getFighterBrain()
    {
        //try to load a champion file. If any issues, use default AI.
        try
        {
            // Initialise log4net (log to console).
            XmlConfigurator.Configure(new FileInfo("log4net.properties"));

            // Experiment classes encapsulate much of the nuts and bolts of setting up a NEAT search.
            AIExperiment experiment = new AIExperiment(new AIFighterEvaluatorFactory());

            // Load config XML.
            XmlDocument xmlConfig = new XmlDocument();
            xmlConfig.Load("ai.config.xml");
            experiment.Initialize("AI", xmlConfig.DocumentElement);

            // assign genome decoder for reading champion files
            IGenomeDecoder <NeatGenome, IBlackBox> decoder = experiment.CreateGenomeDecoder();

            //load existing champion file into a genome
            string     championFileLocation = "coevolution_champion.xml";
            XmlReader  xr     = XmlReader.Create(championFileLocation);
            NeatGenome genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false)[0];

            //decode genome into a usable AIFighter brain.
            return(new AIFighter(decoder.Decode(genome)));
        }
        catch (System.Exception e)
        {
            Debug.Log("Unable to load CHAMPION xml file. It may not exist.\n" + e);
            return(null);
        }
    }
Ejemplo n.º 12
0
        NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(bool load)
        {
            // Create a genome2 factory with our neat genome2 parameters object and the appropriate number of input and output neuron genes.
            var genomeFactory = new NeatGenomeFactory(TetrisEvaluator.NumInputs, TetrisEvaluator.NumOutputs);

            // Create an initial population of randomly generated genomes.
            List <NeatGenome> genomeList = null;

            if (load)
            {
                try
                {
                    using (var reader = XmlReader.Create("SavedProgress.xml"))
                        genomeList = NeatGenomeXmlIO.ReadCompleteGenomeList(reader, true, genomeFactory);
                    Console.WriteLine("Loaded network!");
                }
                catch
                {
                    load = false;
                }
            }
            if (!load)
            {
                genomeList = genomeFactory.CreateGenomeList(150, 0);
            }

            var parallelOpts = new ParallelOptions()
            {
                MaxDegreeOfParallelism = -1
            };
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            var distanceMetric     = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            var speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, parallelOpts);

            // Create the evolution algorithm.
            var ea = new NeatEvolutionAlgorithm <NeatGenome>(new NeatEvolutionAlgorithmParameters {
                SpecieCount = 10
            }, speciationStrategy, new DefaultComplexityRegulationStrategy(ComplexityCeilingType.Absolute, 50));

            // Create genome2 decoder.
            var genomeDecoder = new NeatGenomeDecoder(NetworkActivationScheme.CreateCyclicFixedTimestepsScheme(2));

            // Create a genome2 list evaluator. This packages up the genome2 decoder with the genome2 evaluator.
            IGenomeListEvaluator <NeatGenome> genomeListEvaluator = new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(genomeDecoder, tetrisEvaluator, parallelOpts);

            // 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 genome2's evaluation info object.
            //if (!EvaluateParents)
            //genomeListEvaluator = new SelectiveGenomeListEvaluator<NeatGenome>(genomeListEvaluator, SelectiveGenomeListEvaluator<NeatGenome>.CreatePredicate_OnceOnly());

            ea.UpdateEvent += Ea_UpdateEvent;

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

            // Finished. Return the evolution algorithm
            return(ea);
        }
Ejemplo n.º 13
0
    public NeatGenome LoadGenome()
    {
        NeatGenome genome = null;

        using (XmlReader xr = XmlReader.Create(champFileSavePath))
            genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory())[0];

        return(genome);
    }
Ejemplo n.º 14
0
    public void RunBest()
    {
        Time.timeScale      = 1;
        Time.fixedDeltaTime = 0.02f;
        NeatGenome genome = null;


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

        // 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);

        // Reset();

        Vector3 dir = new Vector3(UnityEngine.Random.Range(-1f, 1f), 0, UnityEngine.Random.Range(-1f, 1f));
        Vector3 pos = dir.normalized * 20;

        pos.y = 1;
        GameObject      obj  = Instantiate(HammerRobot, pos, Quaternion.identity) as GameObject;
        FightController robo = obj.GetComponent <FightController>();

        //   robo.RunBestOnly = true;

        if (Settings.Brain.MultipleTargets)
        {
            GameObject t = Instantiate(Target, new Vector3(0, 1, 0), Quaternion.identity) as GameObject;
            t.transform.localScale = new Vector3(1, 1, 1);
            TargetController tc = t.AddComponent <TargetController>();
            tc.Activate(obj.transform);
            bestTargetDict.Add(robo, tc);
            robo.Activate(phenome, t);
        }
        else
        {
            Target.GetComponent <TargetController>().Activate();
            robo.Activate(phenome, Target);
        }
        BestRunners.Add(robo);
    }
Ejemplo n.º 15
0
        private void loadGenomeFromFile(bool readFunctionIds)
        {
            // Have the user choose the genome XML file.
            var result = openFileDialog.ShowDialog();

            if (result != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }


            NeatGenome genome = null;

            // Try to load the genome from the XML document.
            try
            {
                using (XmlReader xr = XmlReader.Create(openFileDialog.FileName))
                    genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, readFunctionIds)[0];
            }
            catch (Exception e1)
            {
                MessageBox.Show("Error loading genome from file!\nLoading aborted.\n" + e1.Message);
                return;
            }

            // Get a genome decoder that can convert genomes to phenomes.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = null;

            if (!readFunctionIds)
            {
                // If we don't need to read function IDs, get a NEAT decoder.
                genomeDecoder = _experiment.CreateGenomeDecoder();
            }
            else
            {
                // Reading in function IDs implies that we need a HyperNEAT decoder.
                genomeDecoder = _hyperNeatExperiment.CreateGenomeDecoder();
            }

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

            // Set the NEAT player's brain to the newly loaded neural network.
            _neatPlayer.Brain = phenome;

            // Show the option to select the NEAT player
            if (neatPlayerToolStripMenuItem.Enabled == false)
            {
                neatPlayerToolStripMenuItem.Enabled = true;
            }
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            //Initialise log4net (log to console).
            XmlConfigurator.Configure(new FileInfo("log4net.properties"));

            // Experiment classes encapsulate much of the nuts and bolts of setting up a NEAT search.
            GameExperiment experiment = new GameExperiment();

            // Load config XML.
            XmlDocument xmlConfig = new XmlDocument();

            xmlConfig.Load("game.config.xml");
            experiment.Initialize("BrainGene", xmlConfig.DocumentElement);

            if (LEARN)
            {
                // Create evolution algorithm and attach update event.
                _ea              = experiment.CreateEvolutionAlgorithm();
                _ea.UpdateEvent += new EventHandler(ea_UpdateEvent);

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

                //Hit return to quit.
                Console.ReadLine();
            }
            else
            {
                // Have the user choose the genome XML file.

                NeatGenome genome = null;

                // Try to load the genome from the XML document.
                using (XmlReader xr = XmlReader.Create("C:\\Users\\Cantino\\Documents\\School\\Capstone\\NeatTicTacToe\\BrainGene\\bin\\Debug\\game_champion_gen_0.xml"))
                    genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory())[0];

                // 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);

                // Set the NEAT player's brain to the newly loaded neural network.
                NeatPlayer player = new NeatPlayer(null);
                player.Brain = phenome;
                Game game = new Game(player, 0);
                Console.WriteLine(game.PlayGameToEnd());
                // Show the option to select the NEAT player
                Console.ReadLine();
            }
        }
Ejemplo n.º 17
0
    public void RunBest(int mode)     //0 for normal best, 1 for experimental best
    {
        Time.timeScale = 1;

        NeatGenome genome = null;

        Debug.Log(champFileSavePath);
        string FileString;

        Color visualEffect = Color.blue;

        if (mode == 0)
        {
            FileString = champFileSavePath;
        }
        else
        {
            FileString   = champFileSavePath2;
            visualEffect = Color.red;
        }
        // Try to load the genome from the XML document.
        try
        {
            using (XmlReader xr = XmlReader.Create(FileString))
                genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory())[0];
        }
        catch (Exception e1)
        {
            // print(champFileLoadPath + " Error loading genome from file!\nLoading aborted.\n"
            //						  + e1.Message + "\nJoe: " + champFileLoadPath);
            Debug.Log("get error in best");
            return;
        }

        // 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);

        GameObject     obj        = Instantiate(Unit, Unit.transform.position, Unit.transform.rotation) as GameObject;
        UnitController controller = obj.GetComponent <UnitController>();

        obj.GetComponent <SpriteRenderer> ().color = visualEffect;

        ControllerMap.Add(phenome, controller);

        controller.Activate(phenome);
    }
Ejemplo n.º 18
0
        private void GenomesToAcceptability(IList <TGenome> genomeList)
        {
            string TEMP_NETWORK_FILE = string.Format("____temp{0}____network.xml", TrialId);

            var neatGenomeParams = new NeatGenomeParameters()
            {
                ActivationFn = PlainSigmoid.__DefaultInstance,
                InitialInterconnectionsProportion = 1
            };

            int inputs = _world.PlantTypes.Count() * World.SENSORS_PER_OBJECT_TYPE
                         + _world.Predators.Count() * World.SENSORS_PER_OBJECT_TYPE
                         + 1;
            int outputs = 2;

            var factory = new NeatGenomeFactory(inputs, outputs, neatGenomeParams);

            for (int i = 0; i < _agents.Length; i++)
            {
                // Decode the genome.
                IBlackBox phenome             = _genomeDecoder.Decode(genomeList[i]);
                IAcceptabilityFunction accept = new RecurrentNeuralAcceptability(phenome);

                // Check that the genome is valid.
                if (phenome == null)
                {
                    Console.WriteLine("Couldn't decode genome {0}!", i);
                    _agents[i] = new SpinningAgent(i);
                    continue;
                }

                // Create a feed forward network with 10 hidden nodes and random weights
                SocialExperiment.CreateNetwork(TEMP_NETWORK_FILE, inputs, outputs);
                using (var xr = XmlReader.Create(TEMP_NETWORK_FILE))
                {
                    var controllerGenome  = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, factory)[0];
                    var controllerPhenome = _genomeDecoder.Decode((TGenome)controllerGenome);
                    _agents[i] = new SocialAgent(i, _genomeList[i].SpecieIdx, controllerPhenome, _agentsNavigate, _agentsHide, accept)
                    {
                        MemorySize = CurrentMemorySize
                    };
                    var network = (FastCyclicNetwork)controllerPhenome;
                    network.Momentum             = ((SocialAgent)_agents[i]).Momentum;
                    network.BackpropLearningRate = ((SocialAgent)_agents[i]).LearningRate;
                }
            }

            File.Delete(TEMP_NETWORK_FILE);
        }
Ejemplo n.º 19
0
    void ea_UpdateEvent(object sender, EventArgs e)
    {
        Utility.Log(string.Format("gen={0:N0} bestFitness={1:N6}",
                                  _ea.CurrentGeneration, _ea.Statistics._maxFitness));



        Fitness = _ea.Statistics._maxFitness;

        Generation = _ea.CurrentGeneration;

        if (MaxAllFitness < Fitness)
        {
            MaxAllFitness = (float)Fitness;

            float timeTemp = Time.timeScale;
            Time.timeScale    = 0;
            AllGenerationBest = _ea.CurrentChampGenome;

            XmlWriterSettings _xwSettings = new XmlWriterSettings();
            _xwSettings.Indent = true;

            NeatGenome genome = null;

            bool fileAlreadyExist = File.Exists(champFileSavePath2);

            try
            {
                using (XmlReader xr = XmlReader.Create(champFileSavePath2)) {
                    genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory()) [0];
                }
            }catch (Exception ex) {
            }

            using (XmlWriter xw = XmlWriter.Create(champFileSavePath2, _xwSettings))
            {
                if ((fileAlreadyExist && genome.EvaluationInfo.Fitness < MaxAllFitness) || !fileAlreadyExist)
                {
                    experiment.SavePopulation(xw, new NeatGenome[] { _ea.CurrentChampGenome });
                    Debug.Log("saved new best: " + AllGenerationBest.EvaluationInfo.Fitness);
                }
            }
            Time.timeScale = timeTemp;


//			Debug.Log(_ea.CurrentChampGenome.EvaluationInfo.Fitness+" vs "+AllGenerationBest.EvaluationInfo.Fitness);
        }
    }
Ejemplo n.º 20
0
        public NeatStrategy(string file, string name)
        {
            NeatGenome genome = null;

            using (XmlReader xr = XmlReader.Create(file))
                genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false)[0];

            var experiment = new HexagonExperiment();

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

            // Decode the genome into a phenome (neural network).
            Brain = genomeDecoder.Decode(genome);
        }
Ejemplo n.º 21
0
    NeatGenome LoadChampion()
    {
        NeatGenome genome = null;

        // Try to load the genome from the XML document.
        try
        {
            // It would make more sense to use LoadGenome instead of ReadCompleteGenomeList
            using (XmlReader xr = XmlReader.Create(champFileSavePath))
                genome = NeatGenomeXmlIO.ReadCompleteGenomeList(
                    xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory())[0];
        }
        catch (Exception e1)
        {
        }
        return(genome);
    }
Ejemplo n.º 22
0
        public void LoadPopulation()
        {
            Debug.Assert(_GenomeFactory != null);

            var fi = new FileInfo(_GenomeFile);

            if (fi.Exists)
            {
                using (XmlReader xr = XmlReader.Create(_GenomeFile))
                {
                    _GenomeList = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, _GenomeFactory);
                }
            }
            else
            {
                _GenomeList = _GenomeFactory.CreateGenomeList(_PopulationSize, 0);
            }
        }
Ejemplo n.º 23
0
        public static List <NeatGenome> LoadPopulation(XmlReader xr, bool nodeFnIds, int inputCount, int outputCount)
        {
            List <NeatGenome> list = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, nodeFnIds, new NeatGenomeFactory(inputCount, outputCount));

            for (int index = list.Count - 1; index > -1; --index)
            {
                NeatGenome neatGenome = list[index];
                if (neatGenome.InputNodeCount != inputCount)
                {
                    NeatGenomeUtils.__log.ErrorFormat("Loaded genome has wrong number of inputs for currently selected experiment. Has [{0}], expected [{1}].", (object)neatGenome.InputNodeCount, (object)inputCount);
                    list.RemoveAt(index);
                }
                else if (neatGenome.OutputNodeCount != outputCount)
                {
                    NeatGenomeUtils.__log.ErrorFormat("Loaded genome has wrong number of outputs for currently selected experiment. Has [{0}], expected [{1}].", (object)neatGenome.OutputNodeCount, (object)outputCount);
                    list.RemoveAt(index);
                }
            }
            return(list);
        }
Ejemplo n.º 24
0
    private void ActivateFromFile()
    {
        NeatGenome       genome     = null;
        SimpleExperiment experiment = new SimpleExperiment();
        XmlDocument      xmlConfig  = new XmlDocument();
        TextAsset        textAsset  = (TextAsset)Resources.Load("experiment.config");

        xmlConfig.LoadXml(textAsset.text);

        experiment.Initialize("Tmp Experiment", xmlConfig.DocumentElement, 8 + 2, 1);

        string champFileSavePath = Application.persistentDataPath + "/car_movement.champ.xml";

        using (XmlReader xr = XmlReader.Create(champFileSavePath))
            genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory())[0];

        var genomeDecoder = experiment.CreateGenomeDecoder();

        box = genomeDecoder.Decode(genome);
    }
Ejemplo n.º 25
0
        private void loadNEATPlayerToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            // Have the user choose the genome XML file.
            var result = openFileDialog.ShowDialog();

            if (result != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }


            NeatGenome genome = null;

            // Try to load the genome from the XML document.
            try
            {
                using (XmlReader xr = XmlReader.Create(openFileDialog.FileName))
                    genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false)[0];
            }
            catch (Exception e1)
            {
                MessageBox.Show("Error loading genome from file!\nLoading aborted.\n" + e1.Message);
                return;
            }

            // 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);

            // Set the NEAT player's brain to the newly loaded neural network.
            _neatPlayer.Brain = phenome;

            // Show the option to select the NEAT player
            if (neatPlayerToolStripMenuItem.Enabled == false)
            {
                neatPlayerToolStripMenuItem.Enabled = true;
            }
        }
Ejemplo n.º 26
0
    public void RunBest()
    {
        timeScale = 1;

        NeatGenome genome = null;


        // Try to load the genome from the XML document.
        try
        {
            TextAsset popTxtAsset = (TextAsset)Resources.Load(champFileSavePath);
            string    stream      = popTxtAsset.text;

            string      xrString = stream;
            XmlDocument xdoc     = new XmlDocument();
            xdoc.LoadXml(xrString);

            using (XmlReader xr = new XmlNodeReader(xdoc))
                genome = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory())[0];
        }
        catch (Exception e1)
        {
            Debug.LogError(" Error loading genome from file!\nLoading aborted.\n" + e1.Message + "\nin: " + champFileSavePath);
            return;
        }

        // 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);

        GameObject     obj        = Instantiate(Unit, Unit.transform.position, Unit.transform.rotation) as GameObject;
        UnitController controller = obj.GetComponent <UnitController>();

        ControllerMap.Add(phenome, controller);

        controller.Activate(phenome);
    }
Ejemplo n.º 27
0
        /// <summary>
        ///     Reads in seed NEAT genomes used to bootstrap MCC experiments.
        /// </summary>
        /// <param name="seedNeatPath">
        ///     The path of the single NEAT genome or a directory containing multiple XML genome definitions.
        /// </param>
        /// <param name="neatGenomeFactory">The NEAT genome factory to assign to each genome.</param>
        /// <returns>The list of seed NEAT genomes.</returns>
        public static List <NeatGenome> ReadSeedNeatGenomes(string seedNeatPath, NeatGenomeFactory neatGenomeFactory)
        {
            var neatGenomes = new List <NeatGenome>();

            // Get the NEAT genome files in the given path
            var neatGenomeFiles = GetGenomeFiles(seedNeatPath);

            // Read in all NEAT genomes and add them to the list
            foreach (var neatGenomeFile in neatGenomeFiles)
            {
                using (var xr = XmlReader.Create(neatGenomeFile))
                {
                    // Read in the NEAT genomes
                    var curNeatGenomes = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, neatGenomeFactory);

                    // Add the genomes to the overall genome list
                    neatGenomes.AddRange(curNeatGenomes);
                }
            }

            return(neatGenomes);
        }
Ejemplo n.º 28
0
        public IBlackBox BestPhenome()
        {
            var genomeFactory = new NeatGenomeFactory(this.InputCount, this.OutputCount, new NeatGenomeParameters());

            //var genomeFactory = new SharpNeat.Genomes.HyperNeat.CppnGenomeFactory(
            //    this.InputCount,
            //    this.OutputCount,
            //    SharpNeat.Network.DefaultActivationFunctionLibrary.CreateLibraryCppn(),
            //    new NeatGenomeParameters());

            List <NeatGenome> genomeList;

            using (XmlReader xr = XmlReader.Create(this.xmlPopulationFile))
            {
                genomeList = NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, genomeFactory);
            }

            //var decoder = new NeatGenomeDecoder(NetworkActivationScheme.CreateCyclicFixedTimestepsScheme(1));
            var decoder = new NeatGenomeDecoder(NetworkActivationScheme.CreateAcyclicScheme());

            return(decoder.Decode(genomeList[0]));
        }
Ejemplo n.º 29
0
    public void RunBest()
    {
        Time.timeScale = 1;
        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("Error loading genome from file!\nLoading aborted.\n"
                  + e1.Message);
            return;
        }

        // 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);

        // Reset();

        Vector3 dir = new Vector3(UnityEngine.Random.Range(-1f, 1f), 0, UnityEngine.Random.Range(-1f, 1f));
        Vector3 pos = dir.normalized * 20;

        pos.y = 1;
        GameObject obj = Instantiate(Robot, pos, Quaternion.identity) as GameObject;
        CarMove    car = obj.GetComponent <CarMove>();

        car.RunBestOnly = true;
        Target.GetComponent <TargetMovement>().Activate();
        car.Activate(phenome, Target);
    }
Ejemplo n.º 30
0
    void loadMap()
    {
        string path = Application.persistentDataPath + string.Format("/{0}/map/", folder_prefix);

        DirectoryInfo dir = new DirectoryInfo(path);

        if (dir.Exists)
        {
            FileInfo[] info = dir.GetFiles("*.xml");

            foreach (FileInfo f in info)
            {
                int key = int.Parse(f.Name.Substring(0, f.Name.Length - 4));

                try {
                    using (XmlReader xr = XmlReader.Create(path + f.Name))
                        map.Add(key, NeatGenomeXmlIO.ReadCompleteGenomeList(xr, false, (NeatGenomeFactory)experiment.CreateGenomeFactory()) [0]);
                } catch (Exception e1) {
                    print(" Error loading genome from file!\nLoading aborted.\n" + e1.Message);
                    continue;
                }
            }
        }
    }