示例#1
0
 public string PickNext(IRandomSource random)
 {
     var l = Builders.Build<uint>(random) / (double)uint.MaxValue;
     return Links
         .OrderBy (_ => Builders.Build<int>(random))
         .Where (i => i.Probability > l)
         .Select(i => i.Value)
         .FirstOrDefault ();
 }
        /// <summary>
        /// Take a sample from the distribution, using the provided <see cref="IRandomSource"/> as the source of entropy.
        /// </summary>
        /// <returns>A random sample.</returns>
        public double Sample(IRandomSource rng)
        {
            if (null != _sample)
            {
                double x = _sample.Value;
                _sample = null;
                return(x);
            }

            // Note. The Box-Muller transform generates samples in pairs.
            (double x1, double x2) = BoxMullerGaussian.Sample(rng, _mean, _stdDev);

            // Return the first sample and store the other for future use.
            _sample = x2;
            return(x1);
        }
 /// <summary>
 /// Create a sampler for the uniform distribution with interval [0,max) or (-max,max).
 /// </summary>
 /// <typeparam name="T">Data type of the samples.</typeparam>
 /// <param name="max">Maximum value (exclusive).</param>
 /// <param name="signed">If true the distribution has interval (-max,max); otherwise [0,max).</param>
 /// <param name="rng">Random source.</param>
 /// <returns>A new instance of <see cref="ISampler{T}"/>.</returns>
 public static ISampler <T> CreateSampler <T>(double max, bool signed, IRandomSource rng)
     where T : struct
 {
     if (typeof(T) == typeof(double))
     {
         return((ISampler <T>) new Double.UniformDistributionSampler(max, signed, rng));
     }
     else if (typeof(T) == typeof(float))
     {
         return((ISampler <T>) new Float.UniformDistributionSampler((float)max, signed, rng));
     }
     else
     {
         throw new ArgumentException("Unsupported type argument");
     }
 }
示例#4
0
        /// <summary>
        /// For each species, allocate the EliteSizeInt, OffspringCount (broken down into OffspringAsexualCount and OffspringSexualCount),
        /// and SelectionSizeInt values.
        /// </summary>
        /// <param name="pop">The NEAT population to update species allocation sizes for.</param>
        /// <param name="eaSettings">Evolution algorithm settings object.</param>
        /// <param name="rng">Random source.</param>
        private static void UpdateEliteSelectionOffspringCounts(
            NeatPopulation <T> pop,
            NeatEvolutionAlgorithmSettings eaSettings,
            IRandomSource rng)
        {
            Species <T>[] speciesArr = pop.SpeciesArray !;

            // Loop the species, calculating and storing the various size/count properties.
            int bestGenomeSpeciesIdx = pop.NeatPopulationStats.BestGenomeSpeciesIdx;

            for (int i = 0; i < speciesArr.Length; i++)
            {
                bool isBestGenomeSpecies = (bestGenomeSpeciesIdx == i);
                AllocateEliteSelectionOffspringCounts(speciesArr[i], eaSettings, isBestGenomeSpecies, rng);
            }
        }
示例#5
0
        /// <summary>
        /// Fill an array with samples from the standard Gaussian distribution, i.e. with mean of 0 and standard deviation of 1.
        /// </summary>
        /// <param name="rng">Random source.</param>
        /// <param name="buf">The array to fill with samples.</param>
        public static void Sample(IRandomSource rng, double[] buf)
        {
            int i = 0;

            for (; i <= buf.Length - 2; i += 2)
            {
                var pair = Sample(rng);
                buf[i]     = pair.Item1;
                buf[i + 1] = pair.Item2;
            }

            if (i < buf.Length)
            {
                buf[i] = Sample(rng).Item1;
            }
        }
示例#6
0
        /// <summary>
        /// Fill an array with samples from a Gaussian distribution with the specified mean and standard deviation.
        /// </summary>
        /// <param name="rng">Random source.</param>
        /// <param name="mean">Distribution mean.</param>
        /// <param name="stdDev">Distribution standard deviation.</param>
        /// <param name="buf">The array to fill with samples.</param>
        public static void Sample(IRandomSource rng, double mean, double stdDev, double[] buf)
        {
            int i = 0;

            for (; i <= buf.Length - 2; i += 2)
            {
                var pair = Sample(rng);
                buf[i]     = mean + (pair.Item1 * stdDev);
                buf[i + 1] = mean + (pair.Item2 * stdDev);
            }

            if (i < buf.Length)
            {
                buf[i] = mean + (Sample(rng).Item1 *stdDev);
            }
        }
示例#7
0
        /// <summary>
        /// Fill a span with samples from a Gaussian distribution with the specified mean and standard deviation.
        /// </summary>
        /// <param name="rng">Random source.</param>
        /// <param name="mean">Distribution mean.</param>
        /// <param name="stdDev">Distribution standard deviation.</param>
        /// <param name="span">The span to fill with samples.</param>
        public static void Sample(IRandomSource rng, float mean, float stdDev, Span <float> span)
        {
            int i = 0;

            for (; i <= span.Length - 2; i += 2)
            {
                var pair = Sample(rng);
                span[i]     = mean + (pair.Item1 * stdDev);
                span[i + 1] = mean + (pair.Item2 * stdDev);
            }

            if (i < span.Length)
            {
                span[i] = mean + (Sample(rng).Item1 *stdDev);
            }
        }
示例#8
0
        /// <summary>
        /// Randomly shuffles a sub-span of items within a list.
        /// </summary>
        /// <param name="list">The list to shuffle.</param>
        /// <param name="rng">Random number generator.</param>
        /// <param name="startIdx">The index of the first item in the segment.</param>
        /// <param name="endIdx">The index of the last item in the segment, i.e. endIdx is inclusive; the item at endIdx will participate in the shuffle.</param>
        public static void Shuffle <T>(IList <T> list, IRandomSource rng, int startIdx, int endIdx)
        {
            // Fisher–Yates shuffle.
            // https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

            // Determine how many items in the list will be being shuffled
            int itemCount = (endIdx - startIdx);

            for (int i = endIdx; i > startIdx; i--)
            {
                int swapIdx = startIdx + rng.Next((i - startIdx) + 1);
                T   tmp     = list[swapIdx];
                list[swapIdx] = list[i];
                list[i]       = tmp;
            }
        }
示例#9
0
        /// <summary>
        /// Fill a span with samples from the standard Gaussian distribution, i.e. with mean of 0 and standard deviation of 1.
        /// </summary>
        /// <param name="rng">Random source.</param>
        /// <param name="span">The span to fill with samples.</param>
        public static void Sample(IRandomSource rng, Span <float> span)
        {
            int i = 0;

            for (; i <= span.Length - 2; i += 2)
            {
                var pair = Sample(rng);
                span[i]     = pair.Item1;
                span[i + 1] = pair.Item2;
            }

            if (i < span.Length)
            {
                span[i] = Sample(rng).Item1;
            }
        }
示例#10
0
 /// <summary>
 /// Create a sampler for the Gaussian distribution with the specified mean and standard deviation.
 /// </summary>
 /// <typeparam name="T">Data type of the samples.</typeparam>
 /// <param name="mean">Distribution mean.</param>
 /// <param name="stdDev">Distribution standard deviation.</param>
 /// <param name="rng">Random source.</param>
 /// <returns>A new instance of <see cref="ISampler{T}"/>.</returns>
 public static ISampler <T> CreateSampler <T>(double mean, double stdDev, IRandomSource rng)
     where T : struct
 {
     if (typeof(T) == typeof(double))
     {
         return((ISampler <T>) new Double.ZigguratGaussianSampler(mean, stdDev, rng));
     }
     else if (typeof(T) == typeof(float))
     {
         return((ISampler <T>) new Float.ZigguratGaussianSampler((float)mean, (float)stdDev, rng));
     }
     else
     {
         throw new ArgumentException("Unsupported type argument");
     }
 }
示例#11
0
 /// <summary>
 /// Create a new child genome based on the genetic content of two parent genome.
 /// </summary>
 /// <param name="parent1">Parent 1.</param>
 /// <param name="parent2">Parent 2.</param>
 /// <param name="rng">Random source.</param>
 /// <returns>A new child genome.</returns>
 public NeatGenome <T> CreateGenome(
     NeatGenome <T> parent1,
     NeatGenome <T> parent2,
     IRandomSource rng)
 {
     try
     {
         return(CreateGenomeInner(parent1, parent2, rng));
     }
     finally
     {
         // Clear down ready for re-use of the builder on the next call to CreateGenome().
         // Re-using in this way avoids having to de-alloc and re-alloc memory, thus reducing garbage collection overhead.
         _connGeneListBuilder.Clear();
     }
 }
示例#12
0
        private List <NeatGenome <T> > CreateOffspring(
            Species <T>[] speciesArr,
            DiscreteDistribution speciesDist,
            DiscreteDistribution[] genomeDistArr,
            double interspeciesMatingProportion,
            IRandomSource rng)
        {
            // Calc total number of offspring to produce for the population as a whole.
            int offspringCount = speciesArr.Sum(x => x.Stats.OffspringCount);

            // Create an empty list to add the offspring to (with preallocated storage).
            var offspringList = new List <NeatGenome <T> >(offspringCount);

            for (int speciesIdx = 0; speciesIdx < speciesArr.Length; speciesIdx++)
            {
                // Get the current species.
                Species <T> species = speciesArr[speciesIdx];

                // Get the DiscreteDistribution for genome selection within this species.
                DiscreteDistribution genomeDist = genomeDistArr[speciesIdx];

                // Determine how many offspring to create through asexual and sexual reproduction.
                SpeciesStats stats = species.Stats;
                int          offspringCountAsexual = stats.OffspringAsexualCount;
                int          offspringCountSexual  = stats.OffspringSexualCount;

                // Special case: A species with a single genome marked for selection, cannot perform intra-species sexual reproduction.
                if (species.Stats.SelectionSizeInt == 1)
                {
                    // Note. here we assign all the sexual reproduction allocation to asexual reproduction. In principle
                    // we could still perform inter species sexual reproduction, but that complicates the code further
                    // for minimal gain.
                    offspringCountAsexual += offspringCountSexual;
                    offspringCountSexual   = 0;
                }

                // Create a copy of speciesDist with the current species removed from the set of possibilities.
                // Note. The remaining probabilities are normalised to sum to one.
                DiscreteDistribution speciesDistUpdated = speciesDist.RemoveOutcome(speciesIdx);

                // Create offspring from the current species.
                CreateSpeciesOffspringAsexual(species, genomeDist, offspringCountAsexual, offspringList, rng);
                CreateSpeciesOffspringSexual(speciesArr, species, speciesDistUpdated, genomeDistArr, genomeDist, offspringCountSexual, offspringList, rng);
            }

            return(offspringList);
        }
    public void UpdateSpeciesAllocationSizes()
    {
        IRandomSource rng = RandomDefaults.CreateRandomSource(0);

        NeatEvolutionAlgorithmSettings eaSettings = new()
        {
            SpeciesCount = 4
        };

        // Create population.
        NeatPopulation <double> neatPop = CreateNeatPopulation(100, eaSettings.SpeciesCount, 2, 2, 1.0);

        // Manually set-up some species.
        var speciesArr = neatPop.SpeciesArray;

        speciesArr[0].GenomeList.AddRange(neatPop.GenomeList.Take(25));
        speciesArr[1].GenomeList.AddRange(neatPop.GenomeList.Skip(25).Take(25));
        speciesArr[2].GenomeList.AddRange(neatPop.GenomeList.Skip(50).Take(25));
        speciesArr[3].GenomeList.AddRange(neatPop.GenomeList.Skip(75).Take(25));

        // Manually assign fitness scores to the genomes.
        speciesArr[0].GenomeList.ForEach(x => x.FitnessInfo = new FitnessInfo(100.0));
        speciesArr[1].GenomeList.ForEach(x => x.FitnessInfo = new FitnessInfo(200.0));
        speciesArr[2].GenomeList.ForEach(x => x.FitnessInfo = new FitnessInfo(400.0));
        speciesArr[3].GenomeList.ForEach(x => x.FitnessInfo = new FitnessInfo(800.0));

        // Invoke species target size calcs.
        neatPop.UpdateStats(PrimaryFitnessInfoComparer.Singleton, rng);
        SpeciesAllocationCalcs <double> .UpdateSpeciesAllocationSizes(
            neatPop, eaSettings, RandomDefaults.CreateRandomSource());

        // Species target sizes should be relative to the species mean fitness.
        double totalMeanFitness = 1500.0;
        double popSize          = 100.0;

        Assert.Equal((100.0 / totalMeanFitness) * popSize, speciesArr[0].Stats.TargetSizeReal);
        Assert.Equal((200.0 / totalMeanFitness) * popSize, speciesArr[1].Stats.TargetSizeReal);
        Assert.Equal((400.0 / totalMeanFitness) * popSize, speciesArr[2].Stats.TargetSizeReal);
        Assert.Equal((800.0 / totalMeanFitness) * popSize, speciesArr[3].Stats.TargetSizeReal);

        // Note. Discretized target sizes will generally be equal to ceil(TargetSizeReal) or floor(TargetSizeReal),
        // but may not be due to the target size adjustment logic that is used to ensure that sum(TargetSizeInt) is equal
        // to the required population size.

        // Check that sum(TargetSizeInt) is equal to the required population size.
        Assert.Equal(speciesArr.Sum(x => x.Stats.TargetSizeInt), neatPop.GenomeList.Count);
    }
        public void TestCreateGenome()
        {
            var metaNeatGenome = new MetaNeatGenome <double>(
                inputNodeCount: 10,
                outputNodeCount: 20,
                isAcyclic: true,
                activationFn: new SharpNeat.NeuralNet.Double.ActivationFunctions.ReLU());

            var genomeBuilder = NeatGenomeBuilderFactory <double> .Create(metaNeatGenome);

            int count = 100;
            NeatPopulation <double> pop = NeatPopulationFactory <double> .CreatePopulation(metaNeatGenome, 0.1, count, RandomDefaults.CreateRandomSource());

            var strategy = new UniformCrossoverReproductionStrategy <double>(
                pop.MetaNeatGenome.IsAcyclic,
                0.02,
                genomeBuilder,
                pop.GenomeIdSeq, pop.GenerationSeq);

            IRandomSource rng = RandomDefaults.CreateRandomSource(0);

            var cyclicGraphAnalysis = new CyclicGraphAnalysis();

            for (int i = 0; i < 1000; i++)
            {
                // Randomly select two parents from the population.
                var genome1 = pop.GenomeList[rng.Next(count)];
                var genome2 = pop.GenomeList[rng.Next(count)];

                var childGenome = strategy.CreateGenome(genome1, genome2, rng);

                // The connection genes should be sorted.
                Assert.IsTrue(SortUtils.IsSortedAscending(childGenome.ConnectionGenes._connArr));

                // The child genome should describe an acyclic graph, i.e. the new connection should not have
                // formed a cycle in the graph.
                var digraph = childGenome.DirectedGraph;
                Assert.IsFalse(cyclicGraphAnalysis.IsCyclic(digraph));

                // The child genome node IDs should be a superset of those from parent1 + parent2.
                var childNodeIdSet = GetNodeIdSet(childGenome);
                var parentIdSet    = GetNodeIdSet(genome1);
                parentIdSet.IntersectWith(GetNodeIdSet(genome2));

                Assert.IsTrue(childNodeIdSet.IsSupersetOf(parentIdSet));
            }
        }
示例#15
0
        public void WriteZeroBytes()
        {
            byte[] buf = Array.Empty<byte>();
            MemoryBlockStream ms = new MemoryBlockStream();
            ms.Write(buf, 0, 0);
            Assert.Equal(0, ms.Length);

            IRandomSource rng = RandomDefaults.CreateRandomSource(1234567);
            byte[] buf2 = new byte[100];
            rng.NextBytes(buf2);
            ms.Write(buf2);

            Assert.Equal(ms.ToArray(), buf2);

            ms.Write(buf, 0, 0);
            Assert.Equal(ms.Length, buf2.Length);
        }
示例#16
0
 public AddNodeStrategy(
     MetaNeatGenome <T> metaNeatGenome,
     INeatGenomeBuilder <T> genomeBuilder,
     Int32Sequence genomeIdSeq,
     Int32Sequence innovationIdSeq,
     Int32Sequence generationSeq,
     AddedNodeBuffer addedNodeBuffer,
     IRandomSource rng)
 {
     _metaNeatGenome  = metaNeatGenome;
     _genomeBuilder   = genomeBuilder;
     _genomeIdSeq     = genomeIdSeq;
     _innovationIdSeq = innovationIdSeq;
     _generationSeq   = generationSeq;
     _addedNodeBuffer = addedNodeBuffer;
     _rng             = rng;
 }
        public void Setup()
        {
            // Alloc arrays.
            _keysRandom = new int[ArrayLength];
            _keysNaturalRandom = new int[ArrayLength];
            _vals = new int[ArrayLength];
            _arrays = new int[ArrayCount][];

            for(int i=0; i < _arrays.Length; i++) {
                _arrays[i] = new int[ArrayLength];
            }

            // Fill key arrays with random values.
            IRandomSource rng = RandomDefaults.CreateRandomSource(123);
            SortBenchmarkUtils.InitRandom(_keysRandom, rng);
            SortBenchmarkUtils.InitNatural(_keysNaturalRandom, rng);
        }
示例#18
0
        /// <summary>
        /// Construct with the given distribution and a random source.
        /// </summary>
        /// <param name="rng">Random source.</param>
        public UniformDistributionSampler(float max, bool signed, IRandomSource rng)
        {
            _max    = max;
            _signed = signed;
            _rng    = rng;

            // Note. We predetermine which of these two function variants to use at construction time,
            // thus avoiding a branch on each invocation of Sample() (i.e. this is a micro-optimization).
            if (signed)
            {
                _sampleFn = (r) => UniformDistribution.SampleSigned(r, _max);
            }
            else
            {
                _sampleFn = (r) => UniformDistribution.Sample(r, _max);
            }
        }
示例#19
0
        /// <summary>
        /// Randomly shuffles a sub-span of items within a list.
        /// </summary>
        /// <param name="list">The list to shuffle.</param>
        /// <param name="rng">Random number generator.</param>
        /// <param name="startIdx">The index of the first item in the segment.</param>
        /// <param name="endIdx">The index of the last item in the segment, i.e. endIdx is inclusive; the item at endIdx will participate in the shuffle.</param>
        public static void Shuffle <T>(IList <T> list, IRandomSource rng, int startIdx, int endIdx)
        {
            // Determine how many items in the list will be being shuffled
            int itemCount = (endIdx - startIdx);

            // This approach was suggested by Jon Skeet in a dotNet newsgroup post and
            // is also the technique used by the OpenJDK. The use of rnd.Next(i+1) introduces
            // the possibility of swapping an item with itself, I suspect the reasoning behind this
            // has to do with ensuring the probability of each possible permutation is approximately equal.
            for (int i = endIdx; i > startIdx; i--)
            {
                int swapIndex = startIdx + rng.Next((i - startIdx) + 1);
                T   tmp       = list[swapIndex];
                list[swapIndex] = list[i];
                list[i]         = tmp;
            }
        }
示例#20
0
        /// <summary>
        /// Initializes the data generator.
        /// </summary>
        public DataGenerator(IRandomSource random)
        {
            m_maxArrayLength       = 100;
            m_maxStringLength      = 100;
            m_maxXmlAttributeCount = 10;
            m_maxXmlElementCount   = 10;
            m_minDateTimeValue     = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            m_maxDateTimeValue     = new DateTime(2100, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            m_random = random;
            m_boundaryValueFrequency = 20;
            m_namespaceUris          = new NamespaceTable();
            m_serverUris             = new StringTable();

            // create a random source if none provided.
            if (m_random == null)
            {
                m_random = new RandomSource();
            }

            // load the boundary values.
            m_boundaryValues = new SortedDictionary <string, object[]>();

            for (int ii = 0; ii < s_AvailableBoundaryValues.Length; ii++)
            {
                m_boundaryValues[s_AvailableBoundaryValues[ii].SystemType.Name] =
                    s_AvailableBoundaryValues[ii].Values.ToArray();
            }

            // load the localized tokens.
            m_tokenValues = LoadStringData("Opc.Ua.Types.Utils.LocalizedData.txt");

            if (m_tokenValues.Count == 0)
            {
                m_tokenValues = LoadStringData("Opc.Ua.Utils.LocalizedData.txt");
            }

            // index the available locales.
            m_availableLocales = new string[m_tokenValues.Count];

            int index = 0;

            foreach (string locale in m_tokenValues.Keys)
            {
                m_availableLocales[index++] = locale;
            }
        }
        /// <summary>
        /// Construct a new instance.
        /// </summary>
        /// <param name="eaSettings">NEAT evolution algorithm settings.</param>
        /// <param name="evaluator">An evaluator of lists of genomes.</param>
        /// <param name="speciationStrategy">Speciation strategy.</param>
        /// <param name="population">An initial population of genomes.</param>
        /// <param name="reproductionAsexualSettings">Asexual reproduction settings.</param>
        /// <param name="reproductionSexualSettings">Sexual reproduction settings.</param>
        /// <param name="weightMutationScheme">Connection weight mutation scheme.</param>
        /// <param name="rng">Random source.</param>
        public NeatEvolutionAlgorithm(
            NeatEvolutionAlgorithmSettings eaSettings,
            IGenomeListEvaluator <NeatGenome <T> > evaluator,
            ISpeciationStrategy <NeatGenome <T>, T> speciationStrategy,
            NeatPopulation <T> population,
            NeatReproductionAsexualSettings reproductionAsexualSettings,
            NeatReproductionSexualSettings reproductionSexualSettings,
            WeightMutationScheme <T> weightMutationScheme,
            IRandomSource rng)
        {
            _eaSettings         = eaSettings ?? throw new ArgumentNullException(nameof(eaSettings));
            _evaluator          = evaluator ?? throw new ArgumentNullException(nameof(evaluator));
            _speciationStrategy = speciationStrategy ?? throw new ArgumentNullException(nameof(speciationStrategy));
            _pop = population ?? throw new ArgumentNullException(nameof(population));

            if (reproductionAsexualSettings == null)
            {
                throw new ArgumentNullException(nameof(reproductionAsexualSettings));
            }
            if (reproductionSexualSettings == null)
            {
                throw new ArgumentNullException(nameof(reproductionSexualSettings));
            }

            _rng = rng;

            if (eaSettings.SpeciesCount > population.PopulationSize)
            {
                throw new ArgumentException("Species count is higher then the population size.");
            }

            _generationSeq = new Int32Sequence();

            _reproductionAsexual = new NeatReproductionAsexual <T>(
                _pop.MetaNeatGenome, _pop.GenomeBuilder,
                _pop.GenomeIdSeq, population.InnovationIdSeq, _generationSeq,
                _pop.AddedNodeBuffer, reproductionAsexualSettings, weightMutationScheme);

            _reproductionSexual = new NeatReproductionSexual <T>(
                _pop.MetaNeatGenome, _pop.GenomeBuilder,
                _pop.GenomeIdSeq, population.InnovationIdSeq, _generationSeq,
                _pop.AddedNodeBuffer, reproductionSexualSettings);

            _offspringBuilder = new OffspringBuilder <T>(_reproductionAsexual, _reproductionSexual, _eaSettings.InterspeciesMatingProportion);
        }
        private static NeatGenome <double> CreateAndTestChildGenome(
            NeatGenome <double> parentGenome,
            AddNodeStrategy <double> strategy,
            IRandomSource rng)
        {
            var nodeIdSet = GetNodeIdSet(parentGenome);
            var connSet   = GetDirectedConnectionSet(parentGenome);

            var childGenome = strategy.CreateChildGenome(parentGenome, rng);

            // The connection genes should be sorted.
            Assert.IsTrue(SortUtils.IsSortedAscending(childGenome.ConnectionGenes._connArr));

            // The child genome should have one more connection than parent.
            Assert.AreEqual(parentGenome.ConnectionGenes.Length + 1, childGenome.ConnectionGenes.Length);

            // The child genome should have one more node ID than the parent.
            var childNodeIdSet = GetNodeIdSet(childGenome);
            var newNodeIdList  = new List <int>(childNodeIdSet.Except(nodeIdSet));

            Assert.AreEqual(1, newNodeIdList.Count);
            int newNodeId = newNodeIdList[0];

            // The child genome's new connections should not be a duplicate of any of the existing/parent connections.
            var childConnSet = GetDirectedConnectionSet(childGenome);
            var newConnList  = new List <DirectedConnection>(childConnSet.Except(connSet));

            Assert.AreEqual(2, newConnList.Count);

            // The parent should have one connection that the child does not, i.e. the connection that was replaced.
            var removedConnList = new List <DirectedConnection>(connSet.Except(childConnSet));

            Assert.AreEqual(1, removedConnList.Count);

            // The two new connections should connect to the new node ID.
            var connRemoved = removedConnList[0];
            var connA       = newConnList[0];
            var connB       = newConnList[1];

            Assert.IsTrue(
                (connA.SourceId == connRemoved.SourceId && connA.TargetId == newNodeId && connB.SourceId == newNodeId && connB.TargetId == connRemoved.TargetId) ||
                (connB.SourceId == connRemoved.SourceId && connB.TargetId == newNodeId && connA.SourceId == newNodeId && connA.TargetId == connRemoved.TargetId));

            return(childGenome);
        }
示例#23
0
        public static void TestSpeciateAdd(
            int popSize,
            int inputNodeCount,
            int outputNodeCount,
            double connectionsProportion,
            IDistanceMetric <double> distanceMetric,
            ISpeciationStrategy <NeatGenome <double>, double> speciationStrategy,
            IRandomSource rng,
            bool validateNearestSpecies = true)
        {
            // Create population.
            NeatPopulation <double> neatPop = CreateNeatPopulation(popSize, inputNodeCount, outputNodeCount, connectionsProportion);

            // Split the population into three.
            int popSize1 = popSize / 3;
            int popSize2 = popSize / 3;
            int popSize3 = popSize - (popSize1 + popSize2);

            var genomeList1 = neatPop.GenomeList.GetRange(0, popSize1);
            var genomeList2 = neatPop.GenomeList.GetRange(popSize1, popSize2);
            var genomeList3 = neatPop.GenomeList.GetRange(popSize1 + popSize2, popSize3);

            for (int i = 0; i < 6; i++)
            {
                int speciesCount = rng.Next(1, (neatPop.GenomeList.Count / 4) + 1);

                var fullGenomeList = new List <NeatGenome <double> >(genomeList1);

                // Invoke speciation strategy, and run tests
                var speciesArr = speciationStrategy.SpeciateAll(genomeList1, speciesCount, rng);
                ValidationTests(speciesArr, distanceMetric, speciesCount, fullGenomeList, validateNearestSpecies);

                // Add second batch of genomes, and re-run tests.
                speciationStrategy.SpeciateAdd(genomeList2, speciesArr, rng);

                fullGenomeList.AddRange(genomeList2);
                ValidationTests(speciesArr, distanceMetric, speciesCount, fullGenomeList, validateNearestSpecies);

                // Add third batch of genomes, and re-run tests.
                speciationStrategy.SpeciateAdd(genomeList3, speciesArr, rng);

                fullGenomeList.AddRange(genomeList3);
                ValidationTests(speciesArr, distanceMetric, speciesCount, fullGenomeList, validateNearestSpecies);
            }
        }
示例#24
0
        private static void TestRangeRandomOrderInner(int start, int count, IRandomSource rng)
        {
            // Enumerate the sequence and store the result in an array.
            int[] arr = EnumerableUtils.RangeRandomOrder(start, count, rng).ToArray();

            // Perform some simple tests.
            AssertSimpleTests(start, count, arr);

            // Basic randomness test.
            // As we progress through the sequence, count the number of times and entry is higher and lower than the previous entry.
            // For an ordered sequence the 'lower' count will be zero. For a truly random sequence the two counts have an expected
            // 50/50 distribution, although any given random sequence may differ substantially from the expected value. By fixing the
            // random seed we at least ensure that the unit test will pass rather than passing most of the time(!)
            CountLowHighTransitions(arr, out int lo, out int hi);

            Assert.IsTrue(hi > 46);
            Assert.IsTrue(lo > 46);
        }
        public NeatReproductionSexual(
            MetaNeatGenome <T> metaNeatGenome,
            INeatGenomeBuilder <T> genomeBuilder,
            Int32Sequence genomeIdSeq,
            Int32Sequence innovationIdSeq,
            Int32Sequence generationSeq,
            AddedNodeBuffer addedNodeBuffer,
            NeatReproductionSexualSettings settings,
            IRandomSourceBuilder rngBuilder)
        {
            _settings = settings;
            _rng      = rngBuilder.Create();

            _strategy = new UniformCrossoverReproductionStrategy <T>(
                metaNeatGenome, genomeBuilder,
                genomeIdSeq, generationSeq,
                rngBuilder.Create());
        }
        public AddCyclicConnectionStrategy(
            MetaNeatGenome <T> metaNeatGenome,
            INeatGenomeBuilder <T> genomeBuilder,
            Int32Sequence genomeIdSeq,
            Int32Sequence innovationIdSeq,
            Int32Sequence generationSeq,
            IRandomSource rng)
        {
            _metaNeatGenome  = metaNeatGenome;
            _genomeBuilder   = genomeBuilder;
            _genomeIdSeq     = genomeIdSeq;
            _innovationIdSeq = innovationIdSeq;
            _generationSeq   = generationSeq;

            _weightDistA = ContinuousDistributionFactory.CreateUniformDistribution <T>(_metaNeatGenome.ConnectionWeightRange, true);
            _weightDistB = ContinuousDistributionFactory.CreateUniformDistribution <T>(_metaNeatGenome.ConnectionWeightRange * 0.01, true);
            _rng         = rng;
        }
示例#27
0
        public void SampleUniformWithoutReplacement_SampleAllChoices()
        {
            const int     size = 5;
            IRandomSource rng  = RandomDefaults.CreateRandomSource();

            // Sample all of the elements.
            int[] sampleArr = new int[size];
            DiscreteDistribution.SampleUniformWithoutReplacement(rng, size, sampleArr);

            // Sort the samples.
            Array.Sort(sampleArr);

            // Confirm that all of the choices were selected.
            for (int i = 0; i < size; i++)
            {
                Assert.Equal(i, sampleArr[i]);
            }
        }
示例#28
0
 public MemoryStreamFuzzer(MemoryStream strmA, MemoryBlockStream strmB, int seed)
 {
     _strmA          = strmA;
     _strmB          = strmB;
     _rng            = RandomDefaults.CreateRandomSource((ulong)seed);
     _opDistribution = new DiscreteDistribution(
         new double[]
     {
         0.688,      // Write
         0.05,       // Write byte
         0.05,       // Change read/write head position.
         0.05,       // SetLength
         0.05,       // Seek
         0.002,      // Trim
         0.01,       // Read byte
         0.1,        // Read
     });
 }
示例#29
0
        /// <summary>Generates a sequence of integral numbers within a specified range and in random order.</summary>
        /// <param name="start">The value of the first integer in the sequence.</param>
        /// <param name="count">The number of sequential integers to generate.</param>
        /// <param name="rng">Random source.</param>
        /// <returns>A new IEnumerable{int}.</returns>
        public static IEnumerable <int> RangeRandomOrder(int start, int count, IRandomSource rng)
        {
            if (count < 0 || (((long)start + count) - 1L) > int.MaxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            // Initialise an array of all indexes to be yielded.
            int[] arr = ArrayPool <int> .Shared.Rent(count);

            try
            {
                for (int i = 0; i < count; i++)
                {
                    arr[i] = start + i;
                }

                // Yield all values in turn, applying a Fisher–Yates shuffle as we go in order to randomize the yield order.
                // See https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
                for (int i = count - 1; i > 0; i--)
                {
                    // Select at random from the remaining available slots.
                    int selectIdx = rng.Next(i + 1);

                    // Store the yield value.
                    int tmp = arr[selectIdx];

                    // Replace the selected slot value with a value that has not yet been selected.
                    // This is half of the Fisher–Yates swap, but since we don't need the final
                    // shuffled array we can omit moving the yielded value into its new slot.
                    arr[selectIdx] = arr[i];

                    // Yield the value from the randomly selected slot.
                    yield return(tmp);
                }

                // Yield final value.
                yield return(arr[0]);
            }
            finally
            {
                ArrayPool <int> .Shared.Return(arr);
            }
        }
    public void SelectSubset_Uniqueness()
    {
        IRandomSource rng = RandomDefaults.CreateRandomSource();

        var strategy = new CardinalSubsetSelectionStrategy(30);

        for (int i = 0; i < 20; i++)
        {
            int[]         idxArr = strategy.SelectSubset(20, rng);
            HashSet <int> idxSet = new();

            for (int j = 0; j < idxArr.Length; j++)
            {
                int val = idxArr[j];
                Assert.DoesNotContain(val, idxSet);
                idxSet.Add(val);
            }
        }
    }
        public void TestAddNode1()
        {
            var pop           = CreateNeatPopulation();
            var genomeBuilder = NeatGenomeBuilderFactory <double> .Create(pop.MetaNeatGenome);

            var genome = pop.GenomeList[0];

            var strategy = new AddNodeStrategy <double>(
                pop.MetaNeatGenome, genomeBuilder,
                pop.GenomeIdSeq, pop.InnovationIdSeq, pop.GenerationSeq,
                pop.AddedNodeBuffer);

            IRandomSource rng = RandomDefaults.CreateRandomSource();

            for (int i = 0; i < 10000; i++)
            {
                NeatGenome <double> childGenome = CreateAndTestChildGenome(genome, strategy, rng);
            }
        }
示例#32
0
        public string Generate(int maxLength, IRandomSource random)
        {
            ChainItem current = null;
            var result = new StringBuilder();
            int count = 0;

            while (count < maxLength)
            {
                if (current == null)
                {
                    current = _items.Values.Where (i => i.CanStart).OrderBy (_ => Builders.Build<int>(random)).First ();
                    result.Append (current.Value);
                    count++;
                    continue;
                }

                if (current.CanFinish && Builders.Build<byte>(random) % 10 < 3)
                {
                    result.Append (_endOfSequence + _separator);
                    current = null;
                    continue;
                }

                var next = current.PickNext(random);
                if (next == null)
                {
                    result.Append (_endOfSequence + _separator);
                    current = null;
                    continue;
                }

                current = _items [next];
                result.Append (_separator + current.Value);
                count++;
            }

            return result.ToString ();
        }
示例#33
0
 public static void Start(IRandomSource source)
 {
     _current = new Session(source);
 }
示例#34
0
 static int Generate(IRandomSource source)
 {
     return Math.Abs(Builders.Build<short>(source)) % 9000 + 1000;
 }
        /// <summary>
        /// Initializes the random numbers generator.
        /// </summary>
        public RandomSourceManager()
        {
            RandomSourceSettings settings = UserSettings.GetSettings(typeof(RandomSourceSettings)) as RandomSourceSettings;
            if (settings != null)
            {
                // Try reading the random source specified in the settings
                IRandomSource selectedRandomSource = null;
                foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes("/RandomSourcesSupport/RandomSource"))
                {
                    IRandomSource randomSource = node.CreateInstance() as IRandomSource;
                    string randomSourceDescription;

                    if (randomSource is IDescription)
                        randomSourceDescription = ((IDescription)randomSource).Description;
                    else
                        randomSourceDescription = string.Empty;

                    if (randomSourceDescription == settings.RngRandomSource)
                    {
                        selectedRandomSource = randomSource;
                        break;
                    }
                }

                if (selectedRandomSource == null)
                {
                    // If the random source is still null use the default one
                    TypeExtensionNode node = ExtensionsDefault.GetDefault("/RandomSourcesSupport/RandomSource");
                    if (node != null)
                        selectedRandomSource = node.CreateInstance() as IRandomSource;
                }

                // Set the random source and initialize it
                this.randomSource = selectedRandomSource;
            }
        }
 internal void SetRandomSource(IRandomSource randomSource)
 {
     Random = randomSource;
 }
示例#37
0
 private Session(IRandomSource source)
 {
     Source = source;
 }