public static GenomeList CreateGenomeList(NeatGenome seedGenome, int length, NeatParameters neatParameters, IdGenerator idGenerator)
        {
            //Build the list.
            GenomeList genomeList = new GenomeList();

            // Use the seed directly just once.
            NeatGenome newGenome = new NeatGenome(seedGenome, idGenerator.NextGenomeId);

            genomeList.Add(newGenome);

            // For the remainder we alter the weights.
            for (int i = 1; i < length; i++)
            {
                newGenome = new NeatGenome(seedGenome, idGenerator.NextGenomeId);

                // Reset the connection weights
                foreach (ConnectionGene connectionGene in newGenome.ConnectionGeneList)
                {
                    connectionGene.Weight += (Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange / 2.0;
                }
                //newGenome.ConnectionGeneList.Add(new ConnectionGene(idGenerator.NextInnovationId,5,newGenome.NeuronGeneList[Utilities.Next(newGenome.NeuronGeneList.Count-7)+7].InnovationId ,(Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange/2.0));
                //newGenome.ConnectionGeneList.Add(new ConnectionGene(idGenerator.NextInnovationId, 6, newGenome.NeuronGeneList[Utilities.Next(newGenome.NeuronGeneList.Count - 7) + 7].InnovationId, (Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange / 2.0));
                genomeList.Add(newGenome);
            }

            //

            return(genomeList);
        }
Beispiel #2
0
 public void initalizeEvoManager(int cInputs, int cOuputs, NeatParameters np, IPopulationEvaluator popEval)
 {
     cppnInputs     = cInputs;
     cppnOutputs    = cOuputs;
     neatParams     = np;
     populationEval = popEval;
 }
Beispiel #3
0
        public static GenomeList CreateGenomeListPreserveIDs(NeatParameters neatParameters, IdGenerator idGenerator,
                                                             int inputNeuronCount, int outputNeuronCount, float connectionProportion, int length, AssessGenotypeFunction assess)
        {
            GenomeList genomeList = new GenomeList();

            int testCount = 0; int maxTests = 5;

            //for (int i = 0; i < length; i++)
            while (genomeList.Count < length)
            {
                IGenome genome = CreateGenomePreserveID(neatParameters, idGenerator, inputNeuronCount, outputNeuronCount, connectionProportion);

                if (assess != null && assess(genome) && testCount++ < maxTests)
                {
                    //after adding the genome, reset test count
                    genomeList.Add(genome);
                    testCount = 0;
                }
                else if (assess == null)
                {
                    genomeList.Add(genome);
                }
                else if (testCount >= maxTests)
                {
                    genomeList.Add(genome);
                    testCount = 0;
                }
            }

            return(genomeList);
        }
Beispiel #4
0
 public Multiobjective(NeatParameters _np)
 {
     np         = _np;
     population = new GenomeList();
     ranks      = new List <RankInformation>();
     nov        = new noveltyfixed(10.0);
     doNovelty  = false;
     generation = 0;
 }
 public Multiobjective(NeatParameters _np)
 {
     np         = _np;
     population = new GenomeList();
     ranks      = new List <RankInformation>();
     nov        = new noveltyfixed(10.0);
     doNovelty  = _np.noveltySearch;
     Console.WriteLine("multiobjective novelty " + doNovelty);
     generation = 0;
 }
        /// <summary>
        /// Construct a GenomeList. This can be used to construct a new Population object.
        /// </summary>
        /// <param name="evolutionAlgorithm"></param>
        /// <param name="inputNeuronCount"></param>
        /// <param name="outputNeuronCount"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static GenomeList CreateGenomeList(NeatParameters neatParameters, IdGenerator idGenerator, int inputNeuronCount, int outputNeuronCount, float connectionProportion, int length, bool neatBrain = false)
        {
            GenomeList genomeList = new GenomeList();

            for (int i = 0; i < length; i++)
            {
                idGenerator.ResetNextInnovationNumber();
                genomeList.Add(CreateGenome(neatParameters, idGenerator, inputNeuronCount, outputNeuronCount, connectionProportion, neatBrain));
            }

            return(genomeList);
        }
        /// <summary>
        /// Construct a GenomeList. This can be used to construct a new Population object.
        /// </summary>
        /// <param name="evolutionAlgorithm"></param>
        /// <param name="inputNeuronCount"></param>
        /// <param name="outputNeuronCount"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        // Schrum: Added outputsPerPolicy
        public static GenomeList CreateGenomeList(NeatParameters neatParameters, IdGenerator idGenerator, int inputNeuronCount, int outputNeuronCount, int outputsPerPolicy, float connectionProportion, int length)
        {
            GenomeList genomeList = new GenomeList();

            for (int i = 0; i < length; i++)
            {
                idGenerator.ResetNextInnovationNumber();
                // Schrum: Added outputsPerPolicy
                genomeList.Add(CreateGenome(neatParameters, idGenerator, inputNeuronCount, outputNeuronCount, outputsPerPolicy, connectionProportion));
            }

            return(genomeList);
        }
Beispiel #8
0
        EvolutionManager()
        {
            //generic neat params, if need to change, just create a function that swaps them in
            neatParams = new NeatParameters();
            //neatParams.noveltySearch = true;
            //neatParams.noveltyFloat = true;
            neatParams.multiobjective   = true;
            neatParams.archiveThreshold = 0.5;
            //neatParams.archiveThreshold = 300000.0;

            //maybe we load this idgenerator from server or local database, just keep that in mind
            idgen = new IdGenerator();

            //we just default to this, but it doesn't have to be so
            this.setDefaultCPPNs(4, 3);

            genomeListDictionary.Add(CurrentGenomePool, new GenomeList());
        }
        public static GenomeList CreateGenomeList(Population seedPopulation, int length, NeatParameters neatParameters, IdGenerator idGenerator)
        {
            //Build the list.
            GenomeList genomeList = new GenomeList();
            int        seedIdx    = 0;

            for (int i = 0; i < length; i++)
            {
                NeatGenome newGenome = new NeatGenome((NeatGenome)seedPopulation.GenomeList[seedIdx], idGenerator.NextGenomeId);

                // Reset the connection weights
                foreach (ConnectionGene connectionGene in newGenome.ConnectionGeneList)
                {
                    connectionGene.Weight = (Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange / 2.0;
                }

                genomeList.Add(newGenome);

                if (++seedIdx >= seedPopulation.GenomeList.Count)
                {                       // Back to first genome.
                    seedIdx = 0;
                }
            }
            return(genomeList);
        }
        /// <summary>
        /// Create a default minimal genome that describes a NN with the given number of inputs and outputs.
        /// </summary>
        /// <returns></returns>
        public static IGenome CreateGenome(NeatParameters neatParameters, IdGenerator idGenerator, int inputNeuronCount, int outputNeuronCount, float connectionProportion, bool neatBrain)
        {
            IActivationFunction actFunct;
            NeuronGene          neuronGene;                                  // temp variable.
            NeuronGeneList      inputNeuronGeneList  = new NeuronGeneList(); // includes bias neuron.
            NeuronGeneList      outputNeuronGeneList = new NeuronGeneList();
            NeuronGeneList      neuronGeneList       = new NeuronGeneList();
            ConnectionGeneList  connectionGeneList   = new ConnectionGeneList();

            // IMPORTANT NOTE: The neurons must all be created prior to any connections. That way all of the genomes
            // will obtain the same innovation ID's for the bias,input and output nodes in the initial population.
            // Create a single bias neuron.
            //TODO: DAVID proper activation function change to NULL?

            actFunct   = ActivationFunctionFactory.GetActivationFunction("NullFn");
            neuronGene = new NeuronGene(idGenerator.NextInnovationId, NeuronType.Bias, actFunct, 0f);
            inputNeuronGeneList.Add(neuronGene);
            neuronGeneList.Add(neuronGene);

            // Create input neuron genes.

            for (int i = 0; i < inputNeuronCount; i++)
            {
                //TODO: DAVID proper activation function change to NULL?
                neuronGene = new NeuronGene(idGenerator.NextInnovationId, NeuronType.Input, actFunct, 0f);
                inputNeuronGeneList.Add(neuronGene);
                neuronGeneList.Add(neuronGene);
            }

            // Create output neuron genes.
            if (neatBrain)
            {
                actFunct = ActivationFunctionFactory.GetActivationFunction("SteepenedSigmoidApproximation");
            }
            else
            {
                actFunct = ActivationFunctionFactory.GetActivationFunction("BipolarSigmoid");
            }
            for (int i = 0; i < outputNeuronCount; i++)
            {
                //actFunct = ActivationFunctionFactory.GetRandomActivationFunction(neatParameters);
                //TODO: DAVID proper activation function
                neuronGene = new NeuronGene(idGenerator.NextInnovationId, NeuronType.Output, actFunct, 1f);
                outputNeuronGeneList.Add(neuronGene);
                neuronGeneList.Add(neuronGene);
            }

            // Loop over all possible connections from input to output nodes and create a number of connections based upon
            // connectionProportion.
            foreach (NeuronGene targetNeuronGene in outputNeuronGeneList)
            {
                foreach (NeuronGene sourceNeuronGene in inputNeuronGeneList)
                {
                    // Always generate an ID even if we aren't going to use it. This is necessary to ensure connections
                    // between the same neurons always have the same ID throughout the generated population.
                    uint connectionInnovationId = idGenerator.NextInnovationId;

                    if (Utilities.NextDouble() < connectionProportion)
                    {                           // Ok lets create a connection.
                        connectionGeneList.Add(new ConnectionGene(connectionInnovationId,
                                                                  sourceNeuronGene.InnovationId,
                                                                  targetNeuronGene.InnovationId,
                                                                  (Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange / 2.0)); // Weight 0 +-5
                    }
                }
            }

            // Don't create any hidden nodes at this point. Fundamental to the NEAT way is to start minimally!
            return(new NeatGenome(idGenerator.NextGenomeId, neuronGeneList, connectionGeneList, inputNeuronCount, outputNeuronCount));
        }
 /// <summary>
 /// CPPNGenomeFactory constructor. Used to generate a minimal CPPN
 /// </summary>
 /// <param name="neatParameters"></param>
 /// <param name="idGenerator"></param>
 /// <param name="inputNeuronCount"></param>
 /// <param name="outputNeuronCount"></param>
 /// <param name="connectionProportion"></param>
 public CPPNGenomeFactory(NeatParameters neatParameters, IdGenerator idGenerator, int inputNeuronCount, int outputNeuronCount, float connectionProportion)
 {
     cppnGenerator     = new GenomeFactory();
     listOfCppnGenomes = cppnGenerator.CreateGenomeList(neatParameters, idGenerator, inputNeuronCount, outputNeuronCount, connectionProportion, Chromaria.Simulator.populationSize);
 }
Beispiel #12
0
        /// <summary>
        /// This function contains all of the pre-run logic that doesn't involve graphics.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            // Create the world / region system
            // Note: The morphology must be generated in advance of the Load
            INetwork morphologyCPPN = loadCPPNFromXml(initialMorphologyFilename).Decode(ActivationFunctionFactory.GetActivationFunction("BipolarSigmoid"));

            morphology = generateMorphology(morphologyCPPN);
            redTexture = generateSolidMorphology(morphology);
            InitializeRegions();

            // Initialize a log to track some instance-specific data
            using (System.IO.StreamWriter file = new System.IO.StreamWriter("RunInfo.txt", true))
            {
                file.WriteLine("Novelty search run");
                file.WriteLine("Start time: " + DateTime.Now.ToString("HH:mm:ss tt"));
                if (freezeAfterPlanting)
                {
                    file.WriteLine("Individuals are immobilized once they attempt to plant.");
                }
                else
                {
                    file.WriteLine("Individuals are allowed to keep moving even if/after they attempt to plant.");
                }
                file.WriteLine("Morphology genome XML filename: " + initialControllerFilename);
                file.WriteLine("Behavior update interval: " + behaviorUpdateInterval);
                file.WriteLine("Planting weight: " + plantingWeight);
                file.WriteLine("Position weight: " + positionWeight);
                file.WriteLine("Population size: " + populationSize);
                file.WriteLine("Archive threshold: " + archiveThreshold);
            }

            // Initialize some static variables for the simulation
            numBidirectionalPlanters    = 0;
            numFirstTrialPlanters       = 0;
            numSecondTrialPlanters      = 0;
            numBidirectionalMisplanters = 0;
            numFirstTrialMisplanters    = 0;
            numSecondTrialMisplanters   = 0;
            firstTrial = true;

            // Set the NEAT parameters
            neatParams = new NeatParameters();
            neatParams.archiveThreshold = archiveThreshold;
            neatParams.noveltyFixed     = true;
            neatParams.noveltySearch    = true;

            // Configure the HyperNEAT substrate
            controllerSubstrate             = new ControllerSubstrate(308, 4, 108, new BipolarSigmoid());
            controllerSubstrate.weightRange = 5.0;
            controllerSubstrate.threshold   = 0.2;

            // Create a genome factory to generate a list of CPPN genomes
            cppnGenerator  = new GenomeFactory();
            idGen          = new IdGenerator();
            cppnGenomeList = cppnGenerator.CreateGenomeList(neatParams, idGen, 4, 8, 1.0f, populationSize);
            GenomeIndexOfCurrentCreature = 0;

            // Initialize the folders for storing the archive and planters
            noveltyLogsFolder = Directory.GetCurrentDirectory() + "\\archive\\" + GenomeIndexOfCurrentCreature + "\\";
            if (!Directory.Exists(noveltyLogsFolder))
            {
                Directory.CreateDirectory(noveltyLogsFolder);
            }
            plantersFolder = Directory.GetCurrentDirectory() + "\\planters\\" + GenomeIndexOfCurrentCreature + "\\";
            if (!Directory.Exists(plantersFolder))
            {
                Directory.CreateDirectory(plantersFolder);
            }

            // Create an initial population based on the genome list
            popn = new Population(idGen, cppnGenomeList);

            // Set the generation counter
            // Note: This must be kept seperately from the EA generation counter because novelty search here does't follow the traditional loop.
            generation = 1;

            // Create the EA
            // (Don't run the EA until the first generation has had a chance to go through the simulation.
            // The EA call happens in Simulator.NewGeneration().)
            ea = new EvolutionAlgorithm(popn, new ChromariaPopulationEvaluator(new ChromariaNetworkEvaluator()), neatParams);

            // Initialize the behavior trackers for this individual
            ea.Population.GenomeList[GenomeIndexOfCurrentCreature].Behavior = new BehaviorType();
            ea.Population.GenomeList[GenomeIndexOfCurrentCreature].Behavior.behaviorList = new List <double>();

            // Generate the initial creature
            int      x             = initialBoardWidth / 2;
            int      y             = initialBoardHeight / 2;
            INetwork newController = controllerSubstrate.generateGenome(ea.Population.GenomeList[GenomeIndexOfCurrentCreature].Decode(ActivationFunctionFactory.GetActivationFunction("BipolarSigmoid"))).Decode(ActivationFunctionFactory.GetActivationFunction("BipolarSigmoid"));

            if (bidirectionalTrials)
            {
                currentCreature = new NNControlledCreature(morphology, x, y, initialHeading + (float)(Math.PI / 2.0), newController, this, drawSensorField, trackPlanting, defaultNumSensors, freezeAfterPlanting);
            }
            else
            {
                currentCreature = new NNControlledCreature(morphology, x, y, initialHeading, newController, this, drawSensorField, trackPlanting, defaultNumSensors, freezeAfterPlanting);
            }
            currentCreature.DrawOrder = 1;
            indexOfCurrentCreature    = Components.Count - 1;

            // Add the creature to the simulator's region lists
            int currentPointer = Components.Count - 1;

            regions[y / regionHeight, x / regionWidth].Add(currentPointer);
            if ((x % regionWidth > (x + morphology.Width) % regionWidth) && (y % regionHeight > (y + morphology.Height) % regionHeight) && !regions[(y + morphology.Height) / regionHeight, (x + morphology.Width) / regionWidth].Contains(currentPointer))
            {
                regions[(y + morphology.Height) / regionHeight, (x + morphology.Width) / regionWidth].Add(currentPointer);
            }
            if (x % regionWidth > (x + morphology.Width) % regionWidth && !regions[(y / regionHeight), (x + morphology.Width) / regionWidth].Contains(currentPointer))
            {
                regions[(y / regionHeight), (x + morphology.Width) / regionWidth].Add(currentPointer);
            }
            if (y % regionHeight > (y + morphology.Height) % regionHeight && !(regions[(y + morphology.Height) / regionHeight, x / regionWidth].Contains(currentPointer)))
            {
                regions[(y + morphology.Height) / regionHeight, x / regionWidth].Add(currentPointer);
            }

            // Preliminarily update the creature's sensors so its first movements are actually based on what's underneath its starting position
            currentCreature.InitializeSensor();

            plantedInColoredSpace1 = false;
            plantedInColoredSpace2 = false;
            plantedInWhiteSpace1   = false;
            plantedInWhiteSpace2   = false;
            numUpdates             = 0;
        }
Beispiel #13
0
        public static IGenome CreateGenomePreserveID(NeatParameters neatParameters, IdGenerator idGenerator, int inputNeuronCount, int outputNeuronCount, float connectionProportion)
        {
            IActivationFunction actFunct;
            NeuronGene          neuronGene;                                  // temp variable.
            NeuronGeneList      inputNeuronGeneList  = new NeuronGeneList(); // includes bias neuron.
            NeuronGeneList      outputNeuronGeneList = new NeuronGeneList();
            NeuronGeneList      neuronGeneList       = new NeuronGeneList();
            ConnectionGeneList  connectionGeneList   = new ConnectionGeneList();

            int nodeCount = 0;

            WINManager win = WINManager.SharedWIN;

            // IMPORTANT NOTE: The neurons must all be created prior to any connections. That way all of the genomes
            // will obtain the same innovation ID's for the bias,input and output nodes in the initial population.
            // Create a single bias neuron.
            //TODO: DAVID proper activation function change to NULL?
            actFunct = ActivationFunctionFactory.GetActivationFunction("NullFn");
            //neuronGene = new NeuronGene(idGenerator.NextInnovationId, NeuronType.Bias, actFunct);
            WINNode neuronNode = win.findOrInsertNodeWithProperties(idGenerator,
                                                                    WINNode.NodeWithProperties(nodeCount++, NeuronType.Bias)
                                                                    );

            neuronGene = new NeuronGene(null, neuronNode.UniqueID, NeuronGene.INPUT_LAYER, NeuronType.Bias, actFunct);
            inputNeuronGeneList.Add(neuronGene);
            neuronGeneList.Add(neuronGene);

            // Create input neuron genes.
            actFunct = ActivationFunctionFactory.GetActivationFunction("NullFn");
            for (int i = 0; i < inputNeuronCount; i++)
            {
                //TODO: DAVID proper activation function change to NULL?
                //neuronGene = new NeuronGene(idGenerator.NextInnovationId, NeuronType.Input, actFunct);
                neuronNode = win.findOrInsertNodeWithProperties(idGenerator, WINNode.NodeWithProperties(nodeCount++, NeuronType.Input));

                neuronGene = new NeuronGene(null, neuronNode.UniqueID, NeuronGene.INPUT_LAYER, NeuronType.Input, actFunct);
                inputNeuronGeneList.Add(neuronGene);
                neuronGeneList.Add(neuronGene);
            }

            // Create output neuron genes.
            //actFunct = ActivationFunctionFactory.GetActivationFunction("NullFn");
            for (int i = 0; i < outputNeuronCount; i++)
            {
                actFunct = ActivationFunctionFactory.GetActivationFunction("BipolarSigmoid");
                //actFunct = ActivationFunctionFactory.GetRandomActivationFunction(neatParameters);
                //TODO: DAVID proper activation function
                //neuronGene = new NeuronGene(idGenerator.NextInnovationId, NeuronType.Output, actFunct);
                neuronNode = win.findOrInsertNodeWithProperties(idGenerator, WINNode.NodeWithProperties(nodeCount++, NeuronType.Output));

                neuronGene = new NeuronGene(null, neuronNode.UniqueID, NeuronGene.OUTPUT_LAYER, NeuronType.Output, actFunct);
                outputNeuronGeneList.Add(neuronGene);
                neuronGeneList.Add(neuronGene);
            }


            int           currentConnCount = 0;
            WINConnection winConn;

            // Loop over all possible connections from input to output nodes and create a number of connections based upon
            // connectionProportion.
            foreach (NeuronGene targetNeuronGene in outputNeuronGeneList)
            {
                foreach (NeuronGene sourceNeuronGene in inputNeuronGeneList)
                {
                    // Always generate an ID even if we aren't going to use it. This is necessary to ensure connections
                    // between the same neurons always have the same ID throughout the generated population.
                    //PAUL NOTE:
                    //instead of generating and not using and id, we use the target and connection properties to uniquely identify a connection in WIN
                    //uint connectionInnovationId = idGenerator.NextInnovationId;

                    if (Utilities.NextDouble() < connectionProportion)
                    {
                        // Ok lets create a connection.
                        //first we search or create the winconnection object
                        winConn = win.findOrInsertConnectionWithProperties(idGenerator,
                                                                           WINConnection.ConnectionWithProperties(currentConnCount, sourceNeuronGene.InnovationId, targetNeuronGene.InnovationId));

                        //our winconn will have our innovationID, and our weight like normal
                        //this will also respect the idgenerator, since it gets sent in as well, for legacy purposes
                        connectionGeneList.Add(new ConnectionGene(winConn.UniqueID,
                                                                  sourceNeuronGene.InnovationId,
                                                                  targetNeuronGene.InnovationId,
                                                                  (Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange / 2.0)
                                               );
                        //(Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange / 2.0));  // Weight 0 +-5
                    }

                    currentConnCount++;
                }
            }
            //WIN will eventually be in control of all the genomes that are created as well, but not quite yet!
            //TODO: WIN should be generating genomeIDs explicitly

            // Don't create any hidden nodes at this point. Fundamental to the NEAT way is to start minimally!
            return(new NeatGenome(idGenerator.NextGenomeId, neuronGeneList, connectionGeneList, inputNeuronCount, outputNeuronCount));
        }
Beispiel #14
0
        public static GenomeList CreateGenomeListPreserveIDs(GenomeList seedGenomes, int length, NeatParameters neatParameters, IdGenerator idGenerator, AssessGenotypeFunction assess)
        {
            //Eventually, WIN will be brought in to maintain the genomes, for now, no need

            //Build the list.
            GenomeList genomeList = new GenomeList();

            if (length < seedGenomes.Count)
            {
                throw new Exception("Attempting to generate a population that is smaller than the number of seeds (i.e. some seeds will be lost). Please change pop size to accomodate for all seeds.");
            }
            NeatGenome newGenome;

            for (int i = 0; i < seedGenomes.Count; i++)
            {
                // Use each seed directly just once.
                newGenome = new NeatGenome((NeatGenome)seedGenomes[i], idGenerator.NextGenomeId);
                genomeList.Add(newGenome);
            }

            int testCount = 0; int maxTests = 5;

            // For the remainder we alter the weights.
            //for (int i = 1; i < length; i++)
            //{
            while (genomeList.Count < length)
            {
                newGenome = new NeatGenome((NeatGenome)seedGenomes[Utilities.Next(seedGenomes.Count)], idGenerator.NextGenomeId);

                // Reset the connection weights

                //in this particular instance, we would take a snapshot of the genome AFTER mutation for WIN purposes. But we don't track genomes yet
                foreach (ConnectionGene connectionGene in newGenome.ConnectionGeneList)
                {
                    connectionGene.Weight += (0.1 - Utilities.NextDouble() * 0.2);
                }

                //!connectionGene.Weight = (Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange/2.0;
                //Console.WriteLine((0.1 - Utilities.NextDouble() * 0.2));
                //newGenome.ConnectionGeneList.Add(new ConnectionGene(idGenerator.NextInnovationId,5,newGenome.NeuronGeneList[Utilities.Next(newGenome.NeuronGeneList.Count-7)+7].InnovationId ,(Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange/2.0));
                //newGenome.ConnectionGeneList.Add(new ConnectionGene(idGenerator.NextInnovationId, 6, newGenome.NeuronGeneList[Utilities.Next(newGenome.NeuronGeneList.Count - 7) + 7].InnovationId, (Utilities.NextDouble() * neatParameters.connectionWeightRange) - neatParameters.connectionWeightRange / 2.0));
                //if we have an assess function, it should be used for generating this individual!


                if (assess != null && assess(newGenome) && testCount++ < maxTests)
                {
                    //after adding the genome, reset test count
                    genomeList.Add(newGenome);
                    testCount = 0;
                }
                else if (assess == null)
                {
                    genomeList.Add(newGenome);
                }
                else if (testCount >= maxTests)
                {
                    genomeList.Add(newGenome);
                    testCount = 0;
                }
            }

            //

            return(genomeList);
        }
Beispiel #15
0
        void generateSampleCPPNs()
        {
            NeatParameters np    = new NeatParameters();
            IdGenerator    idGen = new IdGenerator();

            idGen.ResetNextInnovationNumber();

            Random r = new Random();

            JObject root = new JObject();
            JObject meta = new JObject();

            JArray networkArray = new JArray();

            //how many random input tests?
            int testCount    = 100;
            int networkCount = 20;

            meta.Add("networkCount", networkCount);
            meta.Add("sampleCount", testCount);

            Console.WriteLine("All Networks start will run:" + networkCount * testCount);


            for (int n = 0; n < networkCount; n++)
            {
                Console.WriteLine("Network start:" + n);

                JObject networkJSON = new JObject();
                //create our genome
                var inputCount  = r.Next(4) + 3;
                var outputCount = r.Next(3) + 1;
                //radnom inputs 3-6, random outputs 1-3
                var genome = GenomeFactory.CreateGenome(np, idGen, inputCount, outputCount, 1);

                Console.WriteLine("Genoem created:" + n);

                Hashtable nodeHT = new Hashtable();
                Hashtable connHT = new Hashtable();

                //mutate our genome
                for (int m = 0; m < 20; m++)
                {
                    ((NeatGenome)genome).Mutate(np, idGen, nodeHT, connHT);
                    Console.WriteLine("Mutation done: " + m);
                }

                Console.WriteLine("Mutations done:" + n);

                //now turn genome into a network
                var network = genome.Decode(null);

                Console.WriteLine("genome decoded:" + n);


                //turn network into JSON, and save as the network object
                networkJSON.Add("network", JObject.FromObject(network));

                JArray inputsAndOutputs = new JArray();

                Console.WriteLine("starting tests:" + n);

                for (var t = 0; t < testCount; t++)
                {
                    Console.WriteLine("Test " + t + " :" + "for" + n);
                    JArray inputSamples  = new JArray();
                    JArray outputSamples = new JArray();

                    network.ClearSignals();
                    Console.WriteLine("Testclear " + t + " :" + "for" + n);

                    //var saveInputs = new float[inputCount];

                    for (int ins = 0; ins < inputCount; ins++)
                    {
                        //inputs from -1,1
                        var inF = (float)(2 * r.NextDouble() - 1);
                        //saveInputs[ins] = inF;
                        network.SetInputSignal(ins, inF);
                        //add our random input
                        inputSamples.Add(JToken.FromObject(inF));
                    }

                    Console.WriteLine("Testrecursive next" + t + " :" + "for" + n);

                    //run our network, and save the response
                    ((ModularNetwork)network).RecursiveActivation();
                    //network.MultipleSteps(30);

                    Console.WriteLine("recursive done " + t + " :" + "for" + n);

                    //var saveOuts = new float[outputCount];

                    for (var outs = 0; outs < outputCount; outs++)
                    {
                        //saveOuts[outs] = network.GetOutputSignal(outs);
                        //keep our outputs in an output array
                        outputSamples.Add(JToken.FromObject(network.GetOutputSignal(outs)));
                    }

                    //network.ClearSignals();
                    //network.SetInputSignals(saveInputs);
                    //network.MultipleSteps(30);
                    ////((ModularNetwork)network).RecursiveActivation();
                    //for (var outs = 0; outs < outputCount; outs++)
                    //{
                    //    Console.WriteLine("Difference in activation: " + Math.Abs(network.GetOutputSignal(outs) - saveOuts[outs]));
                    //}


                    Console.WriteLine("test reached past outputs " + t + " :" + "for" + n);

                    JObject test = new JObject();
                    test.Add("inputs", inputSamples);
                    test.Add("outputs", outputSamples);
                    inputsAndOutputs.Add(test);
                    Console.WriteLine("Ins/outs done " + t + " :" + "for" + n);
                }

                Console.WriteLine("tests ended:" + n);

                //we add our inputs/outs for this json network
                networkJSON.Add("tests", inputsAndOutputs);

                //finally, we add our network json to the network array
                networkArray.Add(networkJSON);

                Console.WriteLine("Network finished:" + n);
            }

            Console.WriteLine("All newtorks finished, cleaning up");

            //add our networks, and add our meta information
            root.Add("networks", networkArray);
            root.Add("meta", meta);

            //and away we go! Let's save to file!


            using (System.IO.StreamWriter file = new System.IO.StreamWriter("testgenomes.json"))
            {
                file.WriteLine(root.ToString());
            }
        }
Beispiel #16
0
        void buildBodyExamples()
        {
            //we need to create random genomes, then save their generated bodies!
            NeatParameters np    = new NeatParameters();
            IdGenerator    idGen = new IdGenerator();

            idGen.ResetNextInnovationNumber();

            Random r = new Random();

            JObject root = new JObject();
            JObject meta = new JObject();

            JArray genomeArray = new JArray();

            //how many random input tests?
            int genomeCount = 20;

            meta.Add("genomeCount", genomeCount);
            meta.Add("weightRange", HyperNEATParameters.weightRange);

            NeatGenome seed = EvolutionManager.SharedEvolutionManager.getSeed();

            int tEmpty     = 0;
            int emptyCount = genomeCount / 4;

            for (int n = genomeArray.Count; n < genomeCount; n = genomeArray.Count)
            {
                //create our genome
                var inputCount  = r.Next(4) + 3;
                var outputCount = r.Next(3) + 1;
                //radnom inputs 3-6, random outputs 1-3
                var genome = GenomeFactory.CreateGenomePreserveID(seed, idGen);//np, idGen, inputCount, outputCount, 1);


                Hashtable nodeHT = new Hashtable();
                Hashtable connHT = new Hashtable();

                //mutate our genome
                for (int m = 0; m < 20; m++)
                {
                    ((NeatGenome)genome).Mutate(np, idGen, nodeHT, connHT);
                }

                //now turn genome into a network
                var network = genome.Decode(null);

                //turn network into JSON, and save as the network object
                //genomeJSON.Add("network", JObject.FromObject(network));

                //now we need a body
                bool isEmptyBody;
                //convert to body object
                var bodyObject = simpleCom.simpleExperiment.genomeIntoBodyObject(genome, out isEmptyBody);

                if ((isEmptyBody && tEmpty++ < emptyCount) || (!isEmptyBody))
                {
                    //create object and add body info to it, then save it in our array
                    JObject genomeJSON = new JObject();

                    genomeJSON.Add("genome", JObject.FromObject(genome, new JsonSerializer()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }));
                    genomeJSON.Add("network", JObject.FromObject(network, new JsonSerializer()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }));
                    //save our body object from test
                    genomeJSON.Add("body", JObject.FromObject(bodyObject));
                    genomeJSON.Add("isEmpty", isEmptyBody.ToString());

                    //finally, we add our network json to the body array
                    genomeArray.Add(genomeJSON);
                }
            }

            //add our networks, and add our meta information
            root.Add("genomeCount", genomeArray.Count);
            root.Add("genomes", genomeArray);
            root.Add("meta", meta);

            //and away we go! Let's save to file!
            using (System.IO.StreamWriter file = new System.IO.StreamWriter("testgenomebodies.json"))
            {
                file.WriteLine(root.ToString());
            }
        }