NextDouble() публичный Метод

Returns the next pseudo-random Double value.

There are two common ways to create a double floating point using MT19937: using GenerateUInt32 and dividing by 0xFFFFFFFF + 1, or else generating two double words and shifting the first by 26 bits and adding the second.

In a newer measurement of the randomness of MT19937 published in the journal "Monte Carlo Methods and Applications, Vol. 12, No. 5-6, pp. 385 ñ 393 (2006)" entitled "A Repetition Test for Pseudo-Random Number Generators", it was found that the 32-bit version of generating a double fails at the 95% confidence level when measuring for expected repetitions of a particular number in a sequence of numbers generated by the algorithm.

Due to this, the 53-bit method is implemented here and the 32-bit method of generating a double is not. If, for some reason, the 32-bit method is needed, it can be generated by the following: (Double)NextUInt32() / ((UInt64)UInt32.MaxValue + 1);

public NextDouble ( ) : Double
Результат Double
 public void SampleKnownValues()
 {
     var mt = new MersenneTwister(0);
     Assert.AreEqual(mt.NextDouble(), 0.5488135023042560);
     Assert.AreEqual(mt.NextDouble(), 0.5928446163889021);
     Assert.AreEqual(mt.NextDouble(), 0.7151893649715930);
     Assert.AreEqual(mt.NextDouble(), 0.8442657440900803);
 }
 public void SampleKnownValues()
 {
     var mt = new MersenneTwister(0);
     Assert.AreEqual(mt.NextDouble(), 0.5488135024320365);
     Assert.AreEqual(mt.NextDouble(), 0.5928446165269344);
     Assert.AreEqual(mt.NextDouble(), 0.7151893651381110);
     Assert.AreEqual(mt.NextDouble(), 0.8442657442866512);
 }
Пример #3
0
 public static void InitTree(ISymbolicExpressionTree tree, MersenneTwister twister, List<string> varNames) {
   foreach (var node in tree.IterateNodesPostfix()) {
     if (node is VariableTreeNode) {
       var varNode = node as VariableTreeNode;
       varNode.Weight = twister.NextDouble() * 20.0 - 10.0;
       varNode.VariableName = varNames[twister.Next(varNames.Count)];
     } else if (node is ConstantTreeNode) {
       var constantNode = node as ConstantTreeNode;
       constantNode.Value = twister.NextDouble() * 20.0 - 10.0;
     }
   }
 }
Пример #4
0
        private void addRandomEntries(ISpatialIndex <IExtents, BoundedInt32> rTree)
        {
            Random rnd = new MersenneTwister();

            for (Int32 i = 0; i < 100000; i++)
            {
                Double xMin = rnd.NextDouble() * (rnd.Next(0, 1) == 1 ? -1 : 1) * rnd.Next();
                Double xMax = rnd.NextDouble() * (rnd.Next(0, 1) == 1 ? -1 : 1) * rnd.Next();
                Double yMin = rnd.NextDouble() * (rnd.Next(0, 1) == 1 ? -1 : 1) * rnd.Next();
                Double yMax = rnd.NextDouble() * (rnd.Next(0, 1) == 1 ? -1 : 1) * rnd.Next();

                IExtents bounds = _factories.GeoFactory.CreateExtents2D(xMin, yMin, xMax, yMax);
                rTree.Insert(new BoundedInt32(i, bounds));
            }
        }
Пример #5
0
        public override double[] GenerateExample(MersenneTwister rng)
        {
            var x = new double[Dimensions];

            return(x.Select((v, i) => rng.NextDouble() * (GlobalVariables.Range * (i + 1)) + (i + 1) - (GlobalVariables.R * (i + 1)))
                   .ToArray());
        }
Пример #6
0
        static void Main()
        {
            MersenneTwister randGen = new MersenneTwister();

            Console.WriteLine("100 uniform random integers in [0,{0}]:",
                              MersenneTwister.MaxRandomInt);
            int i;

            for (i = 0; i < 100; ++i)
            {
                Console.Write("{0} ", randGen.Next());
                if (i % 5 == 4)
                {
                    Console.WriteLine("");
                }
            }
            Console.WriteLine("100 uniform random doubles in [0,1]:");
            for (i = 0; i < 100; ++i)
            {
                Console.Write("{0} ", randGen.NextDouble().ToString("F8"));
                if (i % 5 == 4)
                {
                    Console.WriteLine("");
                }
            }
            Console.WriteLine("Press ENTER to quit");
            Console.ReadLine();
        }
        private void doRestructure()
        {
            WaitHandle[] events = new WaitHandle[] { _userIdleEvent, _machineIdleEvent, _terminateEvent };

            while (_terminating == 0)
            {
                // Wait on restructure or terminate events
                WaitHandle.WaitAny(events, _periodMilliseconds, false);

                if (Interlocked.CompareExchange(ref _terminating, 0, 0) == 1)
                {
                    return;
                }

                // If there have been no inserts since last restructure, we don't need another restructure
                if (Interlocked.CompareExchange(ref _insertedEntriesSinceLastRestructure, 0, 0) == 0)
                {
                    continue;
                }

                // The restructure only takes place if it exceeds the probability for restructure
                // as specified in the restructuring heuristic
                if (_restructuringHeuristic.ExecutionPercentage >= _executionProbability.NextDouble() * 100.0)
                {
                    _restructureStrategy.RestructureNode(Root);
                    Interlocked.Exchange(ref _insertedEntriesSinceLastRestructure, 0);
                }
            }
        }
        public Solution[] GeneratePopulation(ExperimentParameters experimentParameters)
        {
            var basePopulationSize = experimentParameters.BasePopulationSize;
            var population         = new Solution[basePopulationSize];

            for (var i = 0; i < basePopulationSize; i++)
            {
                population[i] = new Solution(experimentParameters);

                var lenght = population[i].ObjectCoefficients.Length;

                for (var j = 0; j < lenght; j++)
                {
                    population[i].ObjectCoefficients[j]        = _randomGenerator.NextDouble();
                    population[i].StdDeviationsCoefficients[j] = _randomGenerator.NextDoublePositive();
                }

                lenght = population[i].RotationsCoefficients.Length;

                for (var j = 0; j < lenght; j++)
                {
                    population[i].RotationsCoefficients[j] = _randomGenerator.NextDoublePositive();
                }
            }

            return(population);
        }
Пример #9
0
 public static Double NextDouble()
 {
     lock (Lock)
     {
         return(Random.NextDouble(true));
     }
 }
Пример #10
0
        /// <summary>Raised after the game begins a new day (including when the player loads a save).</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void OnDayStarted(object sender, DayStartedEventArgs e)
        {
            if (OurMoon.GetMoonRiseTime() <= 0600 || OurMoon.GetMoonRiseTime() >= 2600 && ModConfig.ShowMoonPhase)
            {
                Game1.addHUDMessage(new HUDMessage(Helper.Translation.Get("moon-text.moonriseBefore6", new { moonPhase = OurMoon.DescribeMoonPhase(), riseTime = OurMoon.GetMoonRiseDisplayTime() })));
            }

            if (OurMoon == null)
            {
                Monitor.Log("OurMoon is null");
                return;
            }

            if (Dice.NextDouble() < ModConfig.EclipseChance && ModConfig.EclipseOn && OurMoon.CurrentPhase == MoonPhase.FullMoon &&
                SDate.Now().DaysSinceStart > 2)
            {
                IsEclipse = true;
                var n = new HUDMessage(Helper.Translation.Get("moon-text.solareclipse"))
                {
                    color    = Color.SeaGreen,
                    fadeIn   = true,
                    timeLeft = 4000,
                    noIcon   = true
                };
                Game1.addHUDMessage(n);

                Monitor.Log("There's a solar eclipse today!", LogLevel.Info);
            }

            OurMoon.OnNewDay();
            OurMoon.HandleMoonAfterWake();
        }
Пример #11
0
        private void UpdateRealizations()
        {
            var realizations = new ItemList <BoolArray>(RealizationsSize);
            var rand         = new MersenneTwister();

            for (var i = 0; i < RealizationsSize; i++)
            {
                var newRealization = new BoolArray(Probabilities.Length);
                var countOnes      = 0;
                do
                {
                    countOnes = 0;
                    for (var j = 0; j < Probabilities.Length; j++)
                    {
                        newRealization[j] = Probabilities[j] < rand.NextDouble();
                        if (newRealization[j])
                        {
                            countOnes++;
                        }
                    }
                    // only generate realizations with at least 4 cities visited
                } while (countOnes < 4 && Probabilities.Length > 3);
                realizations.Add(newRealization);
            }
            Realizations = realizations;
        }
Пример #12
0
        public CorpusDocument GetRandomDocument(MersenneTwister rnd)
        {
            var n          = rnd.NextDouble();
            var documentId = (int)Math.Floor(n * (double)NbDocuments);

            return(GetDocument(documentId));
        }
        // The points inside the sphere are uniformly distributed
        // For explanation look at: http://math.stackexchange.com/a/87238
        public IList <Point> Generate(int dimensions, double radius, double[] center, int positives,
                                      int negatives = 0, int multiplicity = 1)
        {
            var totalPointsCount = positives + negatives;

            var result = new List <Point>(totalPointsCount);

            for (var i = 0; i < totalPointsCount; i++)
            {
                var isPositive        = i < positives;
                var randomCoordinates = _normalDistribution.Samples().Take(dimensions).ToArray();
                var length            = Math.Sqrt(randomCoordinates.Select(c => Math.Pow(c, 2)).Sum());
                var u           = _random.NextDouble();
                var coordinates =
                    randomCoordinates.Select(c => radius * Math.Pow(u, (isPositive ? 1.0 : -1.0) / dimensions) * c / length).ToArray();
                var pointCoordinates =
                    coordinates.Zip(center, (first, second) => first + second).ToArray();

                result.Add(new Point(pointCoordinates)
                {
                    Label = isPositive
                });
            }

            return(result);
        }
        //public void CalculateNearestNeighbourDistances()
        //{
        //    var numberOfPositiveMeasurePoints = _positiveMeasurePoints.Length;

        //    for (var i = 0; i < numberOfPositiveMeasurePoints; i++)
        //    {
        //        _positiveMeasurePoints[i].DistanceToNearestNeighbour = int.MaxValue;

        //        for (var j = 0; j < numberOfPositiveMeasurePoints; j++)
        //        {
        //            if (i == j)
        //            {
        //                continue;
        //            }

        //            var distanceBetweenPoints = _distanceCalculator.Calculate(_positiveMeasurePoints[i].Coordinates,
        //                _positiveMeasurePoints[j].Coordinates);

        //            if (distanceBetweenPoints < _positiveMeasurePoints[i].DistanceToNearestNeighbour)
        //            {
        //                _positiveMeasurePoints[i].DistanceToNearestNeighbour = distanceBetweenPoints;
        //            }
        //        }
        //    }
        //}

        public Point[] GeneratePoints(int numberOfPointsToGenerate, IBenchmark benchmark)
        {
            var numberOfDimensions = benchmark.Domains.Length;
            var points             = new Point[numberOfPointsToGenerate];

            for (var i = 0; i < numberOfPointsToGenerate; i++)
            {
                points[i] = new Point(numberOfDimensions, ClassificationType.Negative);
                var currentPoint = points[i];
                var isSatisfyingNearestNeighbourConstraints = false;

                while (isSatisfyingNearestNeighbourConstraints == false)
                {
                    isSatisfyingNearestNeighbourConstraints = true;

                    for (var j = 0; j < numberOfDimensions; j++)
                    {
                        currentPoint.Coordinates[j] = _randomGenerator.NextDouble(benchmark.Domains[j].LowerLimit, benchmark.Domains[j].UpperLimit);
                        //currentPoint.Coordinates[j] = _randomGenerator.NextDouble(-500, 500);
                    }

                    for (var j = 0; j < _positiveMeasurePoints.Length; j++)
                    {
                        if (IsOutsideNeighbourhood(currentPoint, _positiveMeasurePoints[j]))
                        {
                            continue;
                        }
                        isSatisfyingNearestNeighbourConstraints = false;
                        break;
                    }
                }
            }

            return(points);
        }
Пример #15
0
        private void Init(Corpus corpus)
        {
            var rnd = new MersenneTwister(-1115574245);

            for (int k = 0; k < K; k++)
            {
                double sum = 0;
                // Seed.
                for (int i = 0; i < NUM_INIT; i++)
                {
                    var doc = corpus.GetRandomDocument(rnd);
                    for (int n = 0; n < doc.NbTerms; n++)
                    {
                        var word = doc.GetWord(n);
                        LogBeta[k, word] = LogBeta[k, word] + doc.GetCount(n);
                    }
                }

                // Smooth.
                for (int n = 0; n < LogBeta.ColumnCount; n++)
                {
                    var randomNumber = rnd.NextDouble();
                    LogBeta[k, n] = LogBeta[k, n] + SEED_INIT_SMOOTH + randomNumber;
                    sum          += LogBeta[k, n];
                }

                sum = MathHelper.SafeLog(sum);
                // Normalize
                for (int n = 0; n < LogBeta.ColumnCount; n++)
                {
                    LogBeta[k, n] = MathHelper.SafeLog(LogBeta[k, n]) - sum;
                }
            }
        }
Пример #16
0
        //HACK TODO - this is original method
        protected override Point GetAllowedPoint(Domain[] domains, Constraint[] constraints)
        {
            var numberOfDimensions = domains.Length;
            var point = new Point(numberOfDimensions, ClassificationType.Negative);

            var isSatisfyingNearestNeighbourConstraints = false;

            while (isSatisfyingNearestNeighbourConstraints == false)
            {
                isSatisfyingNearestNeighbourConstraints = true;

                for (var j = 0; j < numberOfDimensions; j++)
                {
                    point.Coordinates[j] = _randomGenerator.NextDouble(domains[j].LowerLimit, domains[j].UpperLimit);
                }

                for (var j = 0; j < _positiveMeasurePoints.Length; j++)
                {
                    if (!IsOutsideNeighbourhood(point, _positiveMeasurePoints[j]))
                    {
                        isSatisfyingNearestNeighbourConstraints = false;
                        break;
                    }
                }
            }

            return(point);
        }
Пример #17
0
        /// <summary>
        /// This function handles the end of the day.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnEndOfDay(object sender, EventArgs e)
        {
            if (Conditions.HasWeather(CurrentWeather.Frost) && WeatherOpt.AllowCropDeath)
            {
                Farm f = Game1.getFarm();
                int  count = 0, maxCrops = (int)Math.Floor(SDVUtilities.CropCountInFarm(f) * WeatherOpt.DeadCropPercentage);

                foreach (KeyValuePair <Vector2, TerrainFeature> tf in f.terrainFeatures)
                {
                    if (count >= maxCrops)
                    {
                        break;
                    }

                    if (tf.Value is HoeDirt curr && curr.crop != null)
                    {
                        if (Dice.NextDouble() > WeatherOpt.CropResistance)
                        {
                            CropList.Add(tf.Key);
                            count++;
                        }
                    }
                }

                if (count > 0)
                {
                    foreach (Vector2 v in CropList)
                    {
                        HoeDirt hd = (HoeDirt)f.terrainFeatures[v];
                        hd.crop.dead = true;
                    }

                    queuedMsg = new HUDMessage(Helper.Translation.Get("hud-text.desc_frost_killed", new { deadCrops = count }), Color.SeaGreen, 5250f, true)
                    {
                        whatType = 2
                    };
                }
            }

            if (IsEclipse)
            {
                IsEclipse = false;
            }

            //moon works after frost does
            OurMoon.HandleMoonAtSleep(Game1.getFarm(), Helper.Translation);
        }
Пример #18
0
        public static void MyClassInitialize(TestContext testContext)
        {
            random      = new MersenneTwister();
            coordinates = new DoubleMatrix(ProblemSize, 2);
            distances   = new DistanceMatrix(ProblemSize, ProblemSize);
            for (var i = 0; i < ProblemSize; i++)
            {
                coordinates[i, 0] = random.Next(ProblemSize * 10);
                coordinates[i, 1] = random.Next(ProblemSize * 10);
            }
            for (var i = 0; i < ProblemSize - 1; i++)
            {
                for (var j = i + 1; j < ProblemSize; j++)
                {
                    distances[i, j] = Math.Round(Math.Sqrt(Math.Pow(coordinates[i, 0] - coordinates[j, 0], 2) + Math.Pow(coordinates[i, 1] - coordinates[j, 1], 2)));
                    distances[j, i] = distances[i, j];
                }
            }

            probabilities = new DoubleArray(ProblemSize);
            for (var i = 0; i < ProblemSize; i++)
            {
                probabilities[i] = random.NextDouble();
            }

            realizations = new ItemList <BoolArray>(RealizationsSize);
            for (var i = 0; i < RealizationsSize; i++)
            {
                var countOnes      = 0;
                var newRealization = new BoolArray(ProblemSize);
                while (countOnes < 4) //only generate realizations with at least 4 cities visited
                {
                    countOnes = 0;
                    for (var j = 0; j < ProblemSize; j++)
                    {
                        newRealization[j] = random.NextDouble() < probabilities[j];
                        if (newRealization[j])
                        {
                            countOnes++;
                        }
                    }
                }
                realizations.Add(newRealization);
            }

            tour = new Permutation(PermutationTypes.RelativeUndirected, ProblemSize, random);
        }
Пример #19
0
        /// <summary>
        /// Coroutine used to infer the next pose based on the given goal
        /// </summary>
        /// <param name="goal"></param>
        IEnumerator Infer(Vector2 goal)
        {
            float scale = 0.2f;

            if (useNik)
            {
                for (int i = 0; i < 40; i++)
                {
                    Vector2 cur     = GetCurrentPosition();
                    int[]   curPose = GetCurrentPose();
                    Vector2 pos     = Vector2.MoveTowards(cur, goal, Vector2.Distance(cur, goal) * scale);
                    Debug.DrawLine(cur, pos, Color.green, 60f);
                    int[] nextPose = nik.Infer(cur.x, cur.y, pos.x, pos.y, curPose[0], curPose[1]);
                    if ((nextPose[0] == 0 && nextPose[1] == 0) ||
                        (nextPose[0] == curPose[0] && nextPose[1] == curPose[1]))
                    {
                        scale = (float)(0.1 + rng.NextDouble() * 0.4);
                        continue;
                    }
                    yield return(arm.Pose(nextPose[0], nextPose[1]));

                    yield return(new WaitForEndOfFrame());

                    if (arm.touching && arm.touching.transform.Equals(target))
                    {
                        yield break;
                    }
                }
            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    Vector2 cur      = GetCurrentPosition();
                    int[]   curPose  = GetCurrentPose();
                    Vector2 pos      = Vector2.MoveTowards(cur, goal, Vector2.Distance(cur, goal) * scale);
                    int[]   nextPose = InverseKinematics(pos);
                    if ((nextPose[0] == 0 && nextPose[1] == 0) ||
                        (nextPose[0] == curPose[0] && nextPose[1] == curPose[1]))
                    {
                        scale = (float)(0.1 + rng.NextDouble() * 0.4);
                        continue;
                    }
                    yield return(arm.Pose(nextPose[0], nextPose[1]));
                }
            }
        }
Пример #20
0
        /// <summary>Raised before the game begins writes data to the save file (except the initial save creation).</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void OnSaving(object sender, SavingEventArgs e)
        {
            if (!Context.IsMainPlayer)
            {
                return;
            }
            if (Conditions.HasWeather(CurrentWeather.Frost) && WeatherOpt.AllowCropDeath)
            {
                Farm f        = Game1.getFarm();
                int  count    = 0,
                     maxCrops = (int)Math.Floor(SDVUtilities.CropCountInFarm(f) * WeatherOpt.DeadCropPercentage);

                foreach (KeyValuePair <Vector2, TerrainFeature> tf in f.terrainFeatures.Pairs)
                {
                    if (count >= maxCrops)
                    {
                        break;
                    }

                    if (tf.Value is HoeDirt curr && curr.crop != null)
                    {
                        if (Dice.NextDouble() > WeatherOpt.CropResistance)
                        {
                            CropList.Add(tf.Key);
                            count++;
                        }
                    }
                }

                if (count > 0)
                {
                    foreach (Vector2 v in CropList)
                    {
                        HoeDirt hd = (HoeDirt)f.terrainFeatures[v];
                        hd.crop.dead.Value = true;
                    }

                    queuedMsg = new HUDMessage(
                        Helper.Translation.Get("hud-text.desc_frost_killed", new { deadCrops = count }),
                        Color.SeaGreen, 5250f, true)
                    {
                        whatType = 2
                    };
                }
            }
        }
Пример #21
0
 /// <summary>
 /// Generate example from within [i - 2r, i + 2r]
 /// </summary>
 /// <param name="rng"></param>
 /// <returns></returns>
 public override double[] GenerateExample( MersenneTwister rng )
 {
     var x = new double[Dimensions];
     return x.Select(
             (v, i) =>
                 rng.NextDouble() * GlobalVariables.R * 4 + (i+1) - 2 * GlobalVariables.R )
             .ToArray();
 }
Пример #22
0
        public override double[] GenerateExample(MersenneTwister rng)
        {
            var x = new double[Dimensions];

            return(x.Select(
                       v =>
                       rng.NextDouble() * (3 + GlobalVariables.R) - 1).ToArray());
        }
Пример #23
0
 public static void InitTree(ISymbolicExpressionTree tree, MersenneTwister twister, List <string> varNames)
 {
     foreach (var node in tree.IterateNodesPostfix())
     {
         if (node is VariableTreeNode)
         {
             var varNode = node as VariableTreeNode;
             varNode.Weight       = twister.NextDouble() * 20.0 - 10.0;
             varNode.VariableName = varNames[twister.Next(varNames.Count)];
         }
         else if (node is ConstantTreeNode)
         {
             var constantNode = node as ConstantTreeNode;
             constantNode.Value = twister.NextDouble() * 20.0 - 10.0;
         }
     }
 }
Пример #24
0
        /// <summary>Performs the actual drop sampling.</summary>
        /// <param name="poolName">The name of the item pool to sample from.</param>
        /// <param name="position">The position at which to drop the items.</param>
        private void SampleDrop(string poolName, FarPosition position)
        {
            // Get the actual item pool to pull items from.
            var pool = FactoryLibrary.GetItemPool(poolName);

            // Get the list of possible drops.
            var dropInfo = new List <ItemPool.DropInfo>(pool.Items);

            // Randomizer used for sampling of items. Seed it based on the item
            // pool and the drop position, to get a deterministic result for
            // each drop, regardless in which order they happen.
            var hasher = new Hasher();

            hasher.Write(poolName);
            hasher.Write(position);
            var random = new MersenneTwister(hasher.Value);

            // And shuffle it. This is important, to give each entry an equal
            // chance to be picked. Otherwise the first few entries have a much
            // better chance, because we stop after reaching a certain number
            // of items.
            for (var i = dropInfo.Count; i > 1; i--)
            {
                // Pick random element to swap.
                var j = random.NextInt32(i); // 0 <= j <= i - 1
                // Swap.
                var tmp = dropInfo[j];
                dropInfo[j]     = dropInfo[i - 1];
                dropInfo[i - 1] = tmp;
            }

            var dropCount = 0;

            for (int i = 0, j = dropInfo.Count; i < j; i++)
            {
                var item = dropInfo[i];

                // Give the item a chance to be dropped.
                if (item.Probability > random.NextDouble())
                {
                    // Random roll succeeded, drop the item.
                    var entity = FactoryLibrary.SampleItem(Manager, item.ItemName, position, random);

                    // Make the item visible (per default items are hidden).
                    foreach (IDrawable drawable in Manager.GetComponents(entity, DrawableTypeId))
                    {
                        drawable.Enabled = true;
                    }

                    // Did a drop, check if we're done.
                    dropCount++;
                    if (dropCount == pool.MaxDrops)
                    {
                        break;
                    }
                }
            }
        }
Пример #25
0
 private void SpaceEvents_ChooseNightlyFarmEvent(object sender, EventArgsChooseNightlyFarmEvent e)
 {
     if (OurMoon.CurrentPhase() == MoonPhase.BlueMoon && !Game1.weddingToday &&
         (e.NightEvent == null || (e.NightEvent is SoundInTheNightEvent &&
                                   Helper.Reflection.GetField <NetInt>(e.NightEvent, "behavior").GetValue().Value == 2)))
     {
         if (Dice.NextDouble() < 0.025 && !Game1.currentSeason.Equals("winter"))
         {
             e.NightEvent = new FairyEvent();
         }
         else if (Dice.NextDouble() < 0.025)
         {
             e.NightEvent = new WitchEvent();
         }
         else if (Dice.NextDouble() < 0.025)
         {
             e.NightEvent = new WitchEvent();
         }
         else if (Dice.NextDouble() < 0.025)
         {
             e.NightEvent = new SoundInTheNightEvent(1);
         }
         else if (Dice.NextDouble() < 0.025)
         {
             e.NightEvent = new SoundInTheNightEvent(0);
         }
         else if (Dice.NextDouble() < 0.025)
         {
             e.NightEvent = new SoundInTheNightEvent(3);
         }
     }
 }
Пример #26
0
  public override void Main() {
    DateTime start = DateTime.UtcNow;

    QuadraticAssignmentProblem qap;
    if (vars.Contains("qap")) qap = vars.qap;
    else {
      var provider = new DreznerQAPInstanceProvider();
      var instance = provider.GetDataDescriptors().Single(x => x.Name == "dre56");
      var data = provider.LoadData(instance);
      qap = new QuadraticAssignmentProblem();
      qap.Load(data);
      vars.qap = qap;
    }

    const uint seed = 0;
    const int popSize = 100;
    const int generations = 1000;
    const double mutationRate = 0.05;

    var random = new MersenneTwister(seed);
    var population = new Permutation[popSize];
    var qualities = new double[popSize];
    var nextGen = new Permutation[popSize];
    var nextQual = new double[popSize];

    var qualityChart = new DataTable("Quality Chart");
    var qualityRow = new DataRow("Best Quality");
    qualityChart.Rows.Add(qualityRow);
    vars.qualityChart = qualityChart;

    for (int i = 0; i < popSize; i++) {
      population[i] = new Permutation(PermutationTypes.Absolute, qap.Weights.Rows, random);
      qualities[i] = QAPEvaluator.Apply(population[i], qap.Weights, qap.Distances);
    }
    var bestQuality = qualities.Min();
    var bestQualityGeneration = 0;

    for (int g = 0; g < generations; g++) {
      var parents = population.SampleProportional(random, 2 * popSize, qualities, windowing: true, inverseProportional: true).ToArray();
      for (int i = 0; i < popSize; i++) {
        nextGen[i] = PartiallyMatchedCrossover.Apply(random, parents[i * 2], parents[i * 2 + 1]);
        if (random.NextDouble() < mutationRate) Swap2Manipulator.Apply(random, nextGen[i]);
        nextQual[i] = QAPEvaluator.Apply(nextGen[i], qap.Weights, qap.Distances);
        if (nextQual[i] < bestQuality) {
          bestQuality = nextQual[i];
          bestQualityGeneration = g;
        }
      }
      qualityRow.Values.Add(bestQuality);
      Array.Copy(nextGen, population, popSize);
      Array.Copy(nextQual, qualities, popSize);
    }

    vars.elapsed = new TimeSpanValue(DateTime.UtcNow - start);
    vars.bestQuality = bestQuality;
    vars.bestQualityFoundAt = bestQualityGeneration;
  }
Пример #27
0
        public void ensure_NextDouble_returns_a_value_between_0_and_1()
        {
            var random = new MersenneTwister();

            for (int i = 0; i < 10000; i++)
            {
                Assert.InRange(random.NextDouble(), 0.0, 1.0);
            }
        }
Пример #28
0
        /// <summary>
        /// Handles events that fire at sleep.
        /// </summary>
        /// <param name="f"></param>
        public int HandleMoonAtSleep(Farm f, IMonitor Logger)
        {
            if (f == null)
            {
                return(0);
            }

            int cropsAffected = 0;

            if (CurrentPhase == MoonPhase.FullMoon)
            {
                foreach (var TF in f.terrainFeatures.Pairs)
                {
                    if (TF.Value is HoeDirt curr && curr.crop != null && Dice.NextDouble() < ModConfig.CropGrowthChance)
                    {
                        if (ModConfig.Verbose)
                        {
                            Logger.Log($"Advancing crop at {TF.Key}", LogLevel.Trace);
                        }
                        SDVUtilities.AdvanceArbitrarySteps(f, curr, TF.Key);
                    }
                }

                return(cropsAffected);
            }

            if (CurrentPhase == MoonPhase.NewMoon && ModConfig.HazardousMoonEvents)
            {
                if (f != null)
                {
                    foreach (KeyValuePair <Vector2, TerrainFeature> TF in f.terrainFeatures.Pairs)
                    {
                        if (TF.Value is HoeDirt curr && curr.crop != null)
                        {
                            if (Dice.NextDouble() < ModConfig.CropHaltChance)
                            {
                                //SDVUtilities.DeAdvanceCrop(f, curr, TF.Key, 1);
                                curr.state.Value = 0;
                                cropsAffected++;
                                if (ModConfig.Verbose)
                                {
                                    Logger.Log($"Deadvancing crop at {TF.Key}", LogLevel.Trace);
                                }
                            }
                        }
                    }
                }


                return(cropsAffected);
            }
            return(cropsAffected);
        }
Пример #29
0
    public static void QuickStart_MersenneTwister()
    {
        // MersenneTwister is a pseudo-random number generator.
        var mt    = new MersenneTwister(42);
        var ul    = mt.NextUInt64(); // [0, 2^64-1]
        var d     = mt.NextDouble(); // [0,1)
        var bytes = new byte[10];

        mt.NextBytes(bytes);
    }
Пример #30
0
        internal static void CheckForStaticRainChanges(WeatherConditions curr, MersenneTwister Dice, double ChanceForNonNormalRain)
        {
            if (Game1.isLightning && Game1.isRaining)
            {
                curr.SetRainAmt(130);
            }
            double rainOdds, newRainOdds;

            rainOdds    = Dice.NextDouble();
            newRainOdds = Dice.NextDouble();

            //random chance to just set rain at a differnt number
            if (rainOdds < ChanceForNonNormalRain)
            {
                //yay use of probablity distribution
                ProbabilityDistribution <RainLevels> RainSpread = new ProbabilityDistribution <RainLevels>(RainLevels.Normal);
                RainSpread.AddNewCappedEndPoint(.12, RainLevels.Sunshower);
                RainSpread.AddNewCappedEndPoint(.28, RainLevels.Light);
                RainSpread.AddNewCappedEndPoint(.351, RainLevels.Normal);
                RainSpread.AddNewCappedEndPoint(.1362, RainLevels.Moderate);
                RainSpread.AddNewCappedEndPoint(.09563, RainLevels.Heavy);
                RainSpread.AddNewCappedEndPoint(.0382, RainLevels.Severe);
                RainSpread.AddNewCappedEndPoint(.0094, RainLevels.Torrential);
                RainSpread.AddNewCappedEndPoint(.0049, RainLevels.Typhoon);
                RainSpread.AddNewCappedEndPoint(.00287, RainLevels.NoahsFlood);

                if (!(RainSpread.GetEntryFromProb(newRainOdds, out RainLevels Result)))
                {
                    Result = RainLevels.Normal;
                    ClimatesOfFerngill.Logger.Log("The rain probablity spread has failed to find an rain level. Falling back to normal rain", LogLevel.Error);
                }

                curr.SetRainAmt(WeatherUtilities.ReturnRndRainAmtInLevel(Dice, Result));

                if (ClimatesOfFerngill.WeatherOpt.Verbose)
                {
                    ClimatesOfFerngill.Logger.Log($"We've set the rain to a non normal value - with roll {rainOdds} for setting non normal, and {newRainOdds} for category {Result}, resulting in new rain target {curr.AmtOfRainDrops} in category {WeatherUtilities.GetRainCategory(curr.AmtOfRainDrops)}");
                }
            }

            curr.TodayRain += curr.AmtOfRainDrops;
            curr.RefreshRainAmt();
        }
        public double[] GenerateR(int seed, int length)
        {
            var rnd    = new MersenneTwister(seed + 1, true);
            var result = new double[length];

            for (int i = 0; i < length; i++)
            {
                result[i] = rnd.NextDouble();
            }
            return(result);
        }
Пример #32
0
 public static Dataset CreateRandomDataset(MersenneTwister twister, int rows, int columns) {
   double[,] data = new double[rows, columns];
   for (int i = 0; i < rows; i++) {
     for (int j = 0; j < columns; j++) {
       data[i, j] = twister.NextDouble() * 2.0 - 1.0;
     }
   }
   IEnumerable<string> variableNames = new string[] { "y" }.Concat(Enumerable.Range(0, columns - 1).Select(x => "x" + x.ToString()));
   Dataset ds = new Dataset(variableNames, data);
   return ds;
 }
        protected virtual Point GetAllowedPoint(Domain[] domains, Constraint[] constraints)
        {
            var numberOfDimensions = domains.Length;
            var point = new Point(numberOfDimensions, ClassificationType.Neutral);

            for (var i = 0; i < numberOfDimensions; i++)
            {
                point.Coordinates[i] = _randomGenerator.NextDouble(domains[i].LowerLimit, domains[i].UpperLimit);
            }

            return(point);
        }
Пример #34
0
        public void MoveWeather()
        {
            updateRaindropPosition();

            TimeSpan timeSpan;

            if (Game1.currentLocation.IsOutdoors)
            {
                for (int index = 0; index < this.rainDrops.Length; ++index)
                {
                    if (this.rainDrops[index].frame == 0)
                    {
                        ref int local = ref this.rainDrops[index].accumulator;
                        int     num3  = local;
                        timeSpan = Game1.currentGameTime.ElapsedGameTime;
                        int milliseconds = timeSpan.Milliseconds;
                        local = num3 + milliseconds;
                        if (this.rainDrops[index].accumulator >= 70)
                        {
                            this.rainDrops[index].position += new Vector2(
                                (float)(index * 8 / this.rainDrops.Length - 16),
                                (float)(32 - index * 8 / this.rainDrops.Length));
                            this.rainDrops[index].accumulator = 0;
                            if (pRNG.NextDouble() < 0.1)
                            {
                                ++this.rainDrops[index].frame;
                            }
                            if ((double)this.rainDrops[index].position.Y > (double)(Game1.viewport.Height + 64))
                            {
                                this.rainDrops[index].position.Y = -64f;
                            }
                        }
                    }
                    else
                    {
                        ref int local = ref this.rainDrops[index].accumulator;
                        int     num3  = local;
                        timeSpan = Game1.currentGameTime.ElapsedGameTime;
                        int milliseconds = timeSpan.Milliseconds;
                        local = num3 + milliseconds;
                        if (this.rainDrops[index].accumulator > 70)
                        {
                            this.rainDrops[index].frame       = (this.rainDrops[index].frame + 1) % 4;
                            this.rainDrops[index].accumulator = 0;
                            if (this.rainDrops[index].frame == 0)
                            {
                                this.rainDrops[index].position = new Vector2(
                                    (float)pRNG.Next(Game1.viewport.Width),
                                    (float)pRNG.Next(Game1.viewport.Height));
                            }
                        }
                    }
Пример #35
0
        public void OnNewDay()
        {
            IsBloodMoon   = false;
            IsSuperMoon   = false;
            IsHarvestMoon = false;
            IsBlueMoon    = false;

            if (CurrentPhase() == MoonPhase.FullMoon || CurrentPhase() == MoonPhase.BloodMoon)
            {
                if (Game1.currentSeason == "fall")
                {
                    if (Game1.dayOfMonth - GetMoonCycleLength < 1)
                    {
                        IsHarvestMoon = true;
                        Game1.addHUDMessage(new TCHUDMessage(Translations.Get("moon-text.harvestmoon"), CurrentPhase()));
                    }
                }
            }

            if (Game1.currentSeason == "fall" && Game1.dayOfMonth == 27)
            {
                Game1.addHUDMessage(new TCHUDMessage(Translations.Get("moon-text.spiritmoon"), MoonPhase.SpiritsMoon));
            }

            if (Dice.NextDouble() < ModConfig.SuperMoonChances)
            {
                IsSuperMoon = true;
                Game1.addHUDMessage(new TCHUDMessage(Translations.Get("moon-text.supermoon"), CurrentPhase()));
            }

            if (MoonTracker is null)
            {
                Monitor.Log("Error: Moon Tracker is null", LogLevel.Info);
            }
            else
            {
                if (MoonTracker.FullMoonThisSeason && CurrentPhase() == MoonPhase.FullMoon || CurrentPhase() == MoonPhase.BloodMoon)
                {
                    IsBlueMoon = true;
                    Game1.addHUDMessage(new TCHUDMessage(Translations.Get("moon-text.bluemoon"), CurrentPhase()));
                    Game1.player.team.sharedDailyLuck.Value += .025;
                }
                else
                {
                    MoonTracker.FullMoonThisSeason = true;
                }
            }

            if (!(MoonTracker is null))
            {
                MoonTracker.IsEclipseTomorrow = SetEclipseTomorrow();
            }
Пример #36
0
    public static void MyClassInitialize(TestContext testContext) {
      random = new MersenneTwister();
      coordinates = new DoubleMatrix(ProblemSize, 2);
      distances = new DistanceMatrix(ProblemSize, ProblemSize);
      for (var i = 0; i < ProblemSize; i++) {
        coordinates[i, 0] = random.Next(ProblemSize * 10);
        coordinates[i, 1] = random.Next(ProblemSize * 10);
      }
      for (var i = 0; i < ProblemSize - 1; i++) {
        for (var j = i + 1; j < ProblemSize; j++) {
          distances[i, j] = Math.Round(Math.Sqrt(Math.Pow(coordinates[i, 0] - coordinates[j, 0], 2) + Math.Pow(coordinates[i, 1] - coordinates[j, 1], 2)));
          distances[j, i] = distances[i, j];
        }
      }

      probabilities = new DoubleArray(ProblemSize);
      for (var i = 0; i < ProblemSize; i++) {
        probabilities[i] = random.NextDouble();
      }

      realizations = new ItemList<BoolArray>(RealizationsSize);
      for (var i = 0; i < RealizationsSize; i++) {
        var countOnes = 0;
        var newRealization = new BoolArray(ProblemSize);
        while (countOnes < 4) { //only generate realizations with at least 4 cities visited
          countOnes = 0;
          for (var j = 0; j < ProblemSize; j++) {
            newRealization[j] = random.NextDouble() < probabilities[j];
            if (newRealization[j]) countOnes++;
          }
        }
        realizations.Add(newRealization);
      }

      tour = new Permutation(PermutationTypes.RelativeUndirected, ProblemSize, random);
    }
Пример #37
0
    protected override List<List<double>> GenerateValues() {
      List<List<double>> data = new List<List<double>>();
      for (int i = 0; i < AllowedInputVariables.Count(); i++) {
        data.Add(Enumerable.Range(0, TestPartitionEnd)
          .Select(_ => xRandom.NextDouble())
          .ToList());
      }

      var random = new MersenneTwister();
      var selectedFeatures =
        Enumerable.Range(0, AllowedInputVariables.Count())
        .Where(_ => random.NextDouble() < selectionProbability)
        .ToArray();

      w = selectedFeatures.Select(_ => weightRandom.NextDouble()).ToArray();
      var target = new List<double>();
      for (int i = 0; i < data[0].Count; i++) {
        var s = selectedFeatures
          .Select(index => data[index][i])
          .ToArray();
        target.Add(ScalarProd(s, w));
      }
      var targetSigma = target.StandardDeviation();
      var noisePrng = new NormalDistributedRandom(random, 0, targetSigma * Math.Sqrt(noiseRatio / (1.0 - noiseRatio)));

      data.Add(target.Select(t => t + noisePrng.NextDouble()).ToList());

      // set property listing the selected features as string[]
      this.selectedFeatures = selectedFeatures.Select(i => AllowedInputVariables[i]).ToArray();
      optimalRSquared = 1 - noiseRatio;
      return data;
    }
    public void AllArchitectureAlteringOperatorsDistributionTest() {
      var trees = new List<ISymbolicExpressionTree>();
      var newTrees = new List<ISymbolicExpressionTree>();
      var grammar = Grammars.CreateArithmeticAndAdfGrammar();
      var random = new MersenneTwister(31415);
      SymbolicExpressionTreeStringFormatter formatter = new SymbolicExpressionTreeStringFormatter();
      IntValue maxTreeSize = new IntValue(MAX_TREE_LENGTH);
      IntValue maxTreeHeigth = new IntValue(MAX_TREE_DEPTH);
      IntValue maxDefuns = new IntValue(3);
      IntValue maxArgs = new IntValue(3);
      for (int i = 0; i < POPULATION_SIZE; i++) {
        var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
        Util.IsValid(tree);
        trees.Add(tree);
      }
      Stopwatch stopwatch = new Stopwatch();
      int failedEvents = 0;
      for (int g = 0; g < N_ITERATIONS; g++) {
        for (int i = 0; i < POPULATION_SIZE; i++) {
          if (random.NextDouble() < 0.5) {
            // manipulate
            stopwatch.Start();
            var selectedTree = (ISymbolicExpressionTree)trees.SampleRandom(random).Clone();
            var oldTree = (ISymbolicExpressionTree)selectedTree.Clone();
            bool success = false;
            int sw = random.Next(6);
            switch (sw) {
              case 0: success = ArgumentCreater.CreateNewArgument(random, selectedTree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); break;
              case 1: success = ArgumentDeleter.DeleteArgument(random, selectedTree, 3, 3); break;
              case 2: success = ArgumentDuplicater.DuplicateArgument(random, selectedTree, 3, 3); break;
              case 3: success = SubroutineCreater.CreateSubroutine(random, selectedTree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); break;
              case 4: success = SubroutineDuplicater.DuplicateSubroutine(random, selectedTree, 3, 3); break;
              case 5: success = SubroutineDeleter.DeleteSubroutine(random, selectedTree, 3, 3); break;
            }
            stopwatch.Stop();
            if (!success) failedEvents++;
            Util.IsValid(selectedTree);
            newTrees.Add(selectedTree);
          } else {
            stopwatch.Start();
            // crossover
            SymbolicExpressionTree par0 = null;
            SymbolicExpressionTree par1 = null;
            do {
              par0 = (SymbolicExpressionTree)trees.SampleRandom(random).Clone();
              par1 = (SymbolicExpressionTree)trees.SampleRandom(random).Clone();
            } while (par0.Length > MAX_TREE_LENGTH || par1.Length > MAX_TREE_LENGTH);
            var newTree = SubtreeCrossover.Cross(random, par0, par1, 0.9, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
            stopwatch.Stop();
            Util.IsValid(newTree);
            newTrees.Add(newTree);
          }
        }
        trees = new List<ISymbolicExpressionTree>(newTrees);
        newTrees.Clear();
      }
      var msPerOperation = stopwatch.ElapsedMilliseconds / ((double)POPULATION_SIZE * (double)N_ITERATIONS);
      Console.WriteLine("AllArchitectureAlteringOperators: " + Environment.NewLine +
        "Operations / s: ~" + Math.Round(1000.0 / (msPerOperation)) + "operations / s)" + Environment.NewLine +
        "Failed events: " + failedEvents * 100.0 / (double)(POPULATION_SIZE * N_ITERATIONS / 2.0) + "%" + Environment.NewLine +
        Util.GetSizeDistributionString(trees, 200, 5) + Environment.NewLine +
        Util.GetFunctionDistributionString(trees) + Environment.NewLine +
        Util.GetNumberOfSubtreesDistributionString(trees) + Environment.NewLine +
        Util.GetTerminalDistributionString(trees) + Environment.NewLine
        );

      Assert.IsTrue(failedEvents * 100.0 / (POPULATION_SIZE * N_ITERATIONS / 2.0) < 75.0); // 25% of architecture operations must succeed
      //mkommend: commented due to performance issues on the builder
      // Assert.IsTrue(Math.Round(1000.0 / (msPerOperation)) > 800); // must achieve more than 800 ops per second
    }
Пример #39
0
        /// <summary>
        /// returns an ideally spaced grid over the actual detected spots
        /// </summary>
        /// <param name="grid"></param>
        /// <returns></returns>
        private static grid2D OverlayIdealGrid(calibrationDot[,] grid,
                                               List<calibrationDot> corners,
                                               ref int grid_offset_x, ref int grid_offset_y,
                                               int random_seed)
        {
            grid2D overlay_grid = null;
            int grid_tx = -1;
            int grid_ty = -1;
            int grid_bx = -1;
            int grid_by = -1;

            int offset_x = 0;
            int offset_y = 0;

            bool found = false;
            int max_region_area = 0;

            // try searching horizontally and vertically
            // then pick the result with the greatest area
            for (int test_orientation = 0; test_orientation < 2; test_orientation++)
            {
                bool temp_found = false;

                int temp_grid_tx = -1;
                int temp_grid_ty = -1;
                int temp_grid_bx = -1;
                int temp_grid_by = -1;

                int temp_offset_x = 0;
                int temp_offset_y = 0;

                switch (test_orientation)
                {
                    case 0:
                        {
                            while ((temp_offset_y < 5) && (!temp_found))
                            {
                                temp_offset_x = 0;
                                while ((temp_offset_x < 3) && (!temp_found))
                                {
                                    temp_grid_tx = temp_offset_x;
                                    temp_grid_ty = temp_offset_y;
                                    temp_grid_bx = grid.GetLength(0) - 1 - temp_offset_x;
                                    temp_grid_by = grid.GetLength(1) - 1 - temp_offset_y;

                                    if ((temp_grid_bx < grid.GetLength(0)) &&
                                        (temp_grid_tx < grid.GetLength(0)) &&
                                        (temp_grid_by < grid.GetLength(1)) &&
                                        (temp_grid_ty < grid.GetLength(1)) &&
                                        (temp_grid_ty >= 0) &&
                                        (temp_grid_by >= 0) &&
                                        (temp_grid_tx >= 0) &&
                                        (temp_grid_bx >= 0))
                                    {
                                        if ((grid[temp_grid_tx, temp_grid_ty] != null) &&
                                            (grid[temp_grid_bx, temp_grid_ty] != null) &&
                                            (grid[temp_grid_bx, temp_grid_by] != null) &&
                                            (grid[temp_grid_tx, temp_grid_by] != null))
                                        {
                                            temp_found = true;
                                        }
                                    }

                                    temp_offset_x++;
                                }
                                temp_offset_y++;
                            }
                            break;
                        }
                    case 1:
                        {
                            while ((temp_offset_x < 3) && (!temp_found))
                            {
                                temp_offset_y = 0;
                                while ((temp_offset_y < 5) && (!temp_found))
                                {
                                    temp_grid_tx = temp_offset_x;
                                    temp_grid_ty = temp_offset_y;
                                    temp_grid_bx = grid.GetLength(0) - 1 - temp_offset_x;
                                    temp_grid_by = grid.GetLength(1) - 1 - temp_offset_y;

                                    if ((temp_grid_bx < grid.GetLength(0)) &&
                                        (temp_grid_tx < grid.GetLength(0)) &&
                                        (temp_grid_by < grid.GetLength(1)) &&
                                        (temp_grid_ty < grid.GetLength(1)) &&
                                        (temp_grid_ty >= 0) &&
                                        (temp_grid_by >= 0) &&
                                        (temp_grid_tx >= 0) &&
                                        (temp_grid_bx >= 0))
                                    {
                                        if ((grid[temp_grid_tx, temp_grid_ty] != null) &&
                                            (grid[temp_grid_bx, temp_grid_ty] != null) &&
                                            (grid[temp_grid_bx, temp_grid_by] != null) &&
                                            (grid[temp_grid_tx, temp_grid_by] != null))
                                        {
                                            temp_found = true;
                                        }
                                    }

                                    temp_offset_y++;
                                }
                                temp_offset_x++;
                            }
                            break;
                        }
                }

                temp_offset_y = temp_grid_ty - 1;
                while (temp_offset_y >= 0)
                {
                    if ((temp_offset_y < grid.GetLength(1)) &&
                        (temp_offset_y >= 0))
                    {
                        if ((grid[temp_grid_tx, temp_offset_y] != null) &&
                            (grid[temp_grid_bx, temp_offset_y] != null))
                        {
                            temp_grid_ty = temp_offset_y;
                            temp_offset_y--;
                        }
                        else break;
                    }
                    else break;
                }

                temp_offset_y = temp_grid_by + 1;
                while (temp_offset_y < grid.GetLength(1))
                {
                    if ((temp_offset_y < grid.GetLength(1)) &&
                        (temp_offset_y >= 0))
                    {
                        if ((grid[temp_grid_tx, temp_offset_y] != null) &&
                            (grid[temp_grid_bx, temp_offset_y] != null))
                        {
                            temp_grid_by = temp_offset_y;
                            temp_offset_y++;
                        }
                        else break;
                    }
                    else break;
                }

                if (temp_found)
                {
                    int region_area = (temp_grid_bx - temp_grid_tx) * (temp_grid_by - temp_grid_ty);
                    if (region_area > max_region_area)
                    {
                        max_region_area = region_area;
                        found = true;

                        grid_tx = temp_grid_tx;
                        grid_ty = temp_grid_ty;
                        grid_bx = temp_grid_bx;
                        grid_by = temp_grid_by;

                        offset_x = temp_offset_x;
                        offset_y = temp_offset_y;
                    }
                }
            }

            if (found)
            {
                // record the positions of the corners
                corners.Add(grid[grid_tx, grid_ty]);
                corners.Add(grid[grid_bx, grid_ty]);
                corners.Add(grid[grid_bx, grid_by]);
                corners.Add(grid[grid_tx, grid_by]);

                double dx, dy;

                double x0 = grid[grid_tx, grid_ty].x;
                double y0 = grid[grid_tx, grid_ty].y;
                double x1 = grid[grid_bx, grid_ty].x;
                double y1 = grid[grid_bx, grid_ty].y;
                double x2 = grid[grid_tx, grid_by].x;
                double y2 = grid[grid_tx, grid_by].y;
                double x3 = grid[grid_bx, grid_by].x;
                double y3 = grid[grid_bx, grid_by].y;

                polygon2D perimeter = new polygon2D();
                perimeter.Add((float)x0, (float)y0);
                perimeter.Add((float)x1, (float)y1);
                perimeter.Add((float)x3, (float)y3);
                perimeter.Add((float)x2, (float)y2);

                int grid_width = grid_bx - grid_tx;
                int grid_height = grid_by - grid_ty;

                int min_hits = 0;
                double min_dx = 0, min_dy = 0;

                // try various perimeter sizes
                double min_dist = double.MaxValue;
                int max_perim_size_tries = 100;
                polygon2D best_perimeter = perimeter;
                MersenneTwister rnd = new MersenneTwister(random_seed);
                for (int perim_size = 0; perim_size < max_perim_size_tries; perim_size++)
                {
                    // try a small range of translations
                    for (int nudge_x = -10; nudge_x <= 10; nudge_x++)
                    {
                        for (int nudge_y = -5; nudge_y <= 5; nudge_y++)
                        {
                            // create a perimeter at this scale and translation
                            polygon2D temp_perimeter = perimeter.Scale(1.0f + (perim_size * 0.1f / max_perim_size_tries));
                            temp_perimeter = temp_perimeter.ScaleSideLength(0, 0.95f + ((float)rnd.NextDouble() * 0.1f));
                            temp_perimeter = temp_perimeter.ScaleSideLength(2, 0.95f + ((float)rnd.NextDouble() * 0.1f));
                            for (int i = 0; i < temp_perimeter.x_points.Count; i++)
                            {
                                temp_perimeter.x_points[i] += nudge_x;
                                temp_perimeter.y_points[i] += nudge_y;
                            }

                            // create a grid based upon the perimeter
                            grid2D temp_overlay_grid = new grid2D(grid_width, grid_height, temp_perimeter, 0, false);

                            // how closely does the grid fit the actual observations ?
                            double temp_min_dist = min_dist;
                            BestFit(grid_tx, grid_ty, grid,
                                    temp_overlay_grid, ref min_dist,
                                    ref min_dx, ref min_dy, ref min_hits,
                                    ref grid_offset_x, ref grid_offset_y);

                            // record the closest fit
                            if (temp_min_dist < min_dist)
                            {
                                best_perimeter = temp_perimeter;
                                overlay_grid = temp_overlay_grid;
                            }
                        }
                    }
                }

                if (min_hits > 0)
                {
                    dx = min_dx;
                    dy = min_dy;

                    Console.WriteLine("dx: " + dx.ToString());
                    Console.WriteLine("dy: " + dy.ToString());

                    x0 += dx;
                    y0 += dy;
                    x1 += dx;
                    y1 += dy;
                    x2 += dx;
                    y2 += dy;
                    x3 += dx;
                    y3 += dy;

                    perimeter = new polygon2D();
                    perimeter.Add((float)x0, (float)y0);
                    perimeter.Add((float)x1, (float)y1);
                    perimeter.Add((float)x3, (float)y3);
                    perimeter.Add((float)x2, (float)y2);
                    overlay_grid = new grid2D(grid_width, grid_height, perimeter, 0, false);
                }
            }

            return (overlay_grid);
        }
Пример #40
0
        /// <summary>
        /// fits a curve to the given grid using the given centre of distortion
        /// </summary>
        /// <param name="grid">detected grid dots</param>
        /// <param name="overlay_grid">overlayed ideal rectified grid</param>
        /// <param name="centre_of_distortion">centre of lens distortion</param>
        /// <param name="curve">curve to be fitted</param>
        private static void FitCurve(calibrationDot[,] grid,
                                     grid2D overlay_grid,
                                     calibrationDot centre_of_distortion,
                                     polynomial curve,
                                     double noise, MersenneTwister rnd,
                                     int grid_offset_x, int grid_offset_y)
        {
            double[] prev_col = new double[grid.GetLength(1) * 2];
            double[] col = new double[prev_col.Length];

            double half_noise = noise / 2;
            double rectified_x, rectified_y;

            for (int pass = 0; pass < 1; pass++)
            {
                // for every detected dot
                for (int grid_x = 0; grid_x < grid.GetLength(0); grid_x++)
                {
                    double prev_rectified_radial_dist = 0;
                    double prev_actual_radial_dist = 0;
                    int prev_grid_y = -1;
                    for (int grid_y = 0; grid_y < grid.GetLength(1); grid_y++)
                    {
                        if (grid[grid_x, grid_y] != null)
                        {
                            if ((grid_x + grid_offset_x < overlay_grid.line_intercepts.GetLength(0)) &&
                                (grid_y + grid_offset_y < overlay_grid.line_intercepts.GetLength(1)) &&
                                (grid_x + grid_offset_x >= 0) && (grid_y + grid_offset_y >= 0))
                            {
                                // find the rectified distance of the dot from the centre of distortion
                                rectified_x = overlay_grid.line_intercepts[grid_x + grid_offset_x, grid_y + grid_offset_y, 0];
                                rectified_y = overlay_grid.line_intercepts[grid_x + grid_offset_x, grid_y + grid_offset_y, 1];
                                if (pass > 0)
                                {
                                    rectified_x += (((rnd.NextDouble() * noise) - half_noise) * 0.1);
                                    rectified_y += (((rnd.NextDouble() * noise) - half_noise) * 0.1);
                                }

                                //double rectified_x = overlay_grid.line_intercepts[grid_x + grid_offset_x, grid_y + grid_offset_y, 0];
                                //double rectified_y = overlay_grid.line_intercepts[grid_x + grid_offset_x, grid_y + grid_offset_y, 1];
                                double rectified_dx = rectified_x - centre_of_distortion.x;
                                double rectified_dy = rectified_y - centre_of_distortion.y;
                                double rectified_radial_dist = Math.Sqrt(rectified_dx * rectified_dx + rectified_dy * rectified_dy);

                                // find the actual raw image distance of the dot from the centre of distortion
                                //double actual_x = grid[grid_x, grid_y].x + (((rnd.NextDouble() * noise) - half_noise) * 2);
                                //double actual_y = grid[grid_x, grid_y].y + (((rnd.NextDouble() * noise) - half_noise) * 2);
                                double actual_x = grid[grid_x, grid_y].x;
                                double actual_y = grid[grid_x, grid_y].y;
                                double actual_dx = actual_x - centre_of_distortion.x;
                                double actual_dy = actual_y - centre_of_distortion.y;
                                double actual_radial_dist = Math.Sqrt(actual_dx * actual_dx + actual_dy * actual_dy);

                                // plot
                                curve.AddPoint(rectified_radial_dist, actual_radial_dist);

                                col[(grid_y * 2)] = rectified_radial_dist;
                                col[(grid_y * 2) + 1] = actual_radial_dist;

                                prev_rectified_radial_dist = rectified_radial_dist;
                                prev_actual_radial_dist = actual_radial_dist;
                                prev_grid_y = grid_y;
                            }
                        }
                    }

                    for (int i = 0; i < col.Length; i++)
                        prev_col[i] = col[i];
                }
            }

            // find the best fit curve
            curve.Solve();
        }
Пример #41
0
        /// <summary>
        /// fits a curve to the given grid using the given centre of distortion
        /// </summary>
        /// <param name="image_width">width of the image in pixels</param>
        /// <param name="image_height">height of the image in pixels</param>
        /// <param name="grid">detected grid dots</param>
        /// <param name="overlay_grid">overlayed ideal rectified grid</param>
        /// <param name="centre_of_distortion">centre of lens distortion</param>
        /// <param name="centre_of_distortion_search_radius">search radius for the centre of distortion</param>
        /// <returns>fitted curve</returns>
        private static polynomial FitCurve(int image_width, int image_height,
                                           calibrationDot[,] grid,
                                           grid2D overlay_grid,
                                           calibrationDot centre_of_distortion,
                                           double centre_of_distortion_search_radius,
                                           int grid_offset_x, int grid_offset_y,
                                           List<List<double>> lines,
                                           ref double minimum_error,
                                           int random_seed)
        {   
            double overall_minimum_error = double.MaxValue;
            double centre_of_distortion_x=0, centre_of_distortion_y=0;
            polynomial overall_best_curve = null;
            polynomial best_curve = null;
        
            for (int rand_pass = random_seed; rand_pass < random_seed + 3; rand_pass++)
            {
                minimum_error = double.MaxValue;
                double search_min_error = minimum_error;

                int degrees = 3;
                int best_degrees = degrees;
                List<double> prev_minimum_error = new List<double>();
                prev_minimum_error.Add(minimum_error);
                double increment = 3.0f;
                double noise = increment / 2;
                best_curve = null;

                double search_radius = (float)centre_of_distortion_search_radius;
                double half_width = image_width / 2;
                double half_height = image_height / 2;
                double half_noise = noise / 2;
                double max_radius_sqr = centre_of_distortion_search_radius * centre_of_distortion_search_radius;
                int scaled_up = 0;

                List<double> result = new List<double>();
                double best_cx = half_width, best_cy = half_height;
            
                float maxerr = (image_width / 2) * (image_width / 2);
                MersenneTwister rnd = new MersenneTwister(rand_pass);
                
                int max_passes = 1000;
                for (int pass = 0; pass < max_passes; pass++)
                {
                    double centre_x = 0;
                    double centre_y = 0;
                    double mass = 0;

                    for (double cx = half_width - search_radius; cx < half_width + search_radius; cx += increment)
                    {
                        double dx = cx - half_width;
                        for (double cy = half_height - search_radius; cy < half_height + search_radius; cy += increment)
                        {
                            double dy = cy - half_height;
                            double dist = dx * dx + dy * dy;
                            if (dist < max_radius_sqr)
                            {
                                polynomial curve = new polynomial();
                                curve.SetDegree(degrees);

                                centre_of_distortion.x = cx + (rnd.NextDouble() * noise) - half_noise;
                                centre_of_distortion.y = cy + (rnd.NextDouble() * noise) - half_noise;
                                FitCurve(grid, overlay_grid, centre_of_distortion, curve, noise, rnd, grid_offset_x, grid_offset_y);

                                // do a sanity check on the curve
                                if (ValidCurve(curve, image_width))
                                {
                                    double error = curve.GetMeanError();
                                    error = error * error;

                                    if (error > 0.001)
                                    {
                                        error = maxerr - error;  // inverse
                                        if (error > 0)
                                        {
                                            centre_x += centre_of_distortion.x * error;
                                            centre_y += centre_of_distortion.y * error;
                                            mass += error;
                                        }
                                    }
                                }

                            }
                        }
                    }

                    if (mass > 0)
                    {
                        centre_x /= mass;
                        centre_y /= mass;

                        centre_of_distortion.x = centre_x;
                        centre_of_distortion.y = centre_y;

                        polynomial curve2 = new polynomial();
                        curve2.SetDegree(degrees);
                        FitCurve(grid, overlay_grid, centre_of_distortion, curve2, noise, rnd, grid_offset_x, grid_offset_y);

                        double mean_error = curve2.GetMeanError();

                        double scaledown = 0.99999999999999999;
                        if (mean_error < search_min_error)
                        {

                            search_min_error = mean_error;

                            // cool down
                            prev_minimum_error.Add(search_min_error);
                            search_radius *= scaledown;
                            increment *= scaledown;
                            noise = increment / 2;
                            half_noise = noise / 2;
                            half_width = centre_x;
                            half_height = centre_y;

                            if (mean_error < minimum_error)
                            {
                                best_cx = half_width;
                                best_cy = half_height;
                                minimum_error = mean_error;
                                Console.WriteLine("Cool " + pass.ToString() + ": " + mean_error.ToString());
                                if (max_passes - pass < 500) max_passes += 500;
                                best_degrees = degrees;
                                best_curve = curve2;
                            }

                            scaled_up = 0;
                        }
                        else
                        {
                            // heat up
                            double scaleup = 1.0 / scaledown;
                            search_radius /= scaledown;
                            increment /= scaledown;
                            noise = increment / 2;
                            half_noise = noise / 2;
                            scaled_up++;
                            half_width = best_cx + (rnd.NextDouble() * noise) - half_noise;
                            half_height = best_cy + (rnd.NextDouble() * noise) - half_noise;
                            if (prev_minimum_error.Count > 0)
                            {
                                minimum_error = prev_minimum_error[prev_minimum_error.Count - 1];
                                prev_minimum_error.RemoveAt(prev_minimum_error.Count - 1);
                            }
                        }

                        result.Add(mean_error);
                    }
                }
            
                minimum_error = Math.Sqrt(minimum_error);

                centre_of_distortion.x = best_cx;
                centre_of_distortion.y = best_cy;
                
                if (best_curve != null)
                    minimum_error = best_curve.GetMeanError();
                    
                if (minimum_error < overall_minimum_error)
                {
                    overall_minimum_error = minimum_error;
                    centre_of_distortion_x = best_cx;
                    centre_of_distortion_y = best_cy;
                    overall_best_curve = best_curve;
                }
            }
            overall_minimum_error = minimum_error;
            centre_of_distortion.x = centre_of_distortion_x;
            centre_of_distortion.y = centre_of_distortion_y;
            best_curve = overall_best_curve;
            return (best_curve);
        }
Пример #42
0
 private void UpdateRealizations() {
   var realizations = new ItemList<BoolArray>(RealizationsSize);
   var rand = new MersenneTwister();
   for (var i = 0; i < RealizationsSize; i++) {
     var newRealization = new BoolArray(Probabilities.Length);
     var countOnes = 0;
     do {
       countOnes = 0;
       for (var j = 0; j < Probabilities.Length; j++) {
         newRealization[j] = Probabilities[j] < rand.NextDouble();
         if (newRealization[j]) countOnes++;
       }
       // only generate realizations with at least 4 cities visited
     } while (countOnes < 4 && Probabilities.Length > 3);
     realizations.Add(newRealization);
   }
   Realizations = realizations;
 }
    void Sample()
    {
        Debug.Log("GENERATING RANDOM NUMBERS WITH SEED: " + seed);
        mrand = new MersenneTwister(seed);
        randomList = new ArrayList();
        for (int i = 0; i < samplig_size; i++) {

            double myval, rn;

            switch (op)
            {
                case MersenneWindowOptionsType.INT:
                    rn = mrand.Next();
                break;

                case MersenneWindowOptionsType.FLOAT:
                    rn = mrand.NextSingle(true);
                break;

                case MersenneWindowOptionsType.DOUBLE:
                    rn = mrand.NextDouble(true);
                break;

                default:
                    rn = mrand.Next();
                break;
            }

            if (normalizeToggle) {
                myval = UnityNormalDistribution.toNormalDistribution(rn, temperature);
            } else {
                myval = rn;
            }

            randomList.Add(myval);
        }
        randomList.Sort();
        this.Repaint();
    }
Пример #44
0
		public static void Test()
		{
			int i;

			MersenneTwister mt = new MersenneTwister();

			Console.WriteLine("1000 outputs of genrand_int32()");
			for (i = 0; i < 1000; i++)
			{
				Console.Write("{0} ", mt.NextUnsigned());
				if (i % 5 == 4) Console.WriteLine();
			}

			Console.ReadLine();
			Console.WriteLine("1000 outputs of genrand_real2");
			for (i = 0; i < 1000; i++)
			{
				Console.Write("{0} ", mt.NextDouble());
				if (i % 5 == 4) Console.WriteLine();
			}
		}