Example #1
0
        public void NextNumberSequenceUniform_LeapfrogEstimatedMean_ConvidenceInterval(int sampleSize, double a, double b, RandomNumberSequence.UniformGenerationMode generatorMode)
        {
            double expectedMean = (a + b) / 2.0;
            double expectedStandardDeviation = (b - a) / (2.0 * Math.Sqrt(3.0));

            IRandomNumberStream randomStream = GetRandomStream();

            Assume.That(randomStream.SplittingApproach.HasFlag(RandomNumberSequence.SplittingApproach.LeapFrog), String.Format("Random Number Generator {0} does not support Leapfrog approach.", randomStream.ToString()));

            int numberOfStreams = 5;  // use five sub-streams for Pseudo-Random-Number Generators

            if (randomStream.Generator is IQuasiRandomNumberGenerator)
            {
                numberOfStreams = (int)randomStream.Dimension;
            }
            var sample = new List <double>(sampleSize);

            for (int j = 0; j < numberOfStreams; j++)
            {
                var stream = randomStream.CreateLeapfrogStream(j, numberOfStreams);

                int subSampleSize = sampleSize / numberOfStreams;
                var subSample     = new double[subSampleSize];
                stream.NextNumberSequence.Uniform(subSampleSize, subSample, a, b, generatorMode);

                sample.AddRange(subSample);
            }
            /* compute estimated mean and standard deviation: */
            double estimatedMean = sample.Average();
            double estimatedStandardDeviation = GetEstimatedStandardDeviation(sample.ToArray(), sampleSize, estimatedMean);
            double epsilon = 2.0 * estimatedStandardDeviation / Math.Sqrt(sampleSize); // size of the confidence interval w.r.t. normal distribution N{-1}(0.975) \approx 1.96 \approx 2.0, i.e. \alpha/2 quantile with \alpha = 5%

            /* test whether E(X) \in [ estimatedMean - \epsilon, estimatedMean + \epsilon], where \epsilon = \sigma/\sqrt(n} */
            Assert.That((expectedMean >= estimatedMean - epsilon) && (expectedMean <= estimatedMean + epsilon), String.Format("a: {0}, b: {1}, Expectation: {2}, Standard deviation: {3}, estimated mean: {4}, estimated Standard Deviation: {5}, epsilon: {6}", a, b, expectedMean, expectedStandardDeviation, estimatedMean, estimatedStandardDeviation, epsilon));
        }
Example #2
0
        /// <summary>Overrides the stream state data of a specific stream object with the data of the current object.
        /// </summary>
        /// <param name="destinationStream">The destination random number stream.</param>
        /// <exception cref="ArgumentException">Thrown, if the stream of the current instance and the stream represented by <paramref name="destinationStream"/> are not compatible.</exception>
        /// <remarks>Stream state data are for example the dimension etc.</remarks>
        public void CopyStreamStateTo(IRandomNumberStream destinationStream)
        {
            AcmlRandomNumberStream acmlStream = (AcmlRandomNumberStream)destinationStream;

            if (acmlStream == null)
            {
                throw new ArgumentException(nameof(destinationStream));
            }
            acmlStream.m_State = m_State.ToArray();
        }
Example #3
0
        /// <summary>Initializes a new instance of the <see cref="SingleRandomNumberStream"/> class.
        /// </summary>
        /// <param name="randomNumberStream">The <see cref="IRandomNumberStream"/> object to encapsulate.</param>
        /// <param name="sequenceLength">The length of random number sequences to pull from <paramref name="randomNumberStream"/>.</param>
        public SingleRandomNumberStream(IRandomNumberStream randomNumberStream, int sequenceLength = 100)
        {
            if (randomNumberStream == null)
            {
                throw new ArgumentNullException("randomNumberStream");
            }
            m_SequenceLength     = sequenceLength;
            m_RandomNumberStream = randomNumberStream;

            m_Data         = new double[sequenceLength];
            m_CurrentIndex = -1;
        }
Example #4
0
        public void NextNumberSequenceGaussianMultivariate_EstimatedMean_ConvidenceInterval(int dimension, int sampleSize, double[] mu, double[] pseudoRootOfVarianceCovarianceMatrix, RandomNumberSequence.MultivariateMatrixStorageType matrixStorageType, RandomNumberSequence.GaussianGenerationMode generatorMode)
        {
            IRandomNumberStream randomStream = GetRandomStream();

            /* do not apply BoxMuller to Pseudo-Random Number Generator: */
            Assume.That(randomStream.Generator is IPseudoRandomNumberGenerator || (string)generatorMode.Name != "BoxMuller", "Box-Muller approach is for Pseudo-Random Number Generators not adequate.");

            var sample          = new double[sampleSize * dimension];
            int workspaceLength = randomStream.NextNumberSequence.GaussianMultivariateWorkspaceQuery(sampleSize, dimension, matrixStorageType, generatorMode);

            double[] workspace = null;
            if (workspaceLength > 0)
            {
                workspace = new double[workspaceLength];
            }
            var outputRepresentation = randomStream.NextNumberSequence.GaussianMultivariate(sampleSize, sample, dimension, matrixStorageType, mu, pseudoRootOfVarianceCovarianceMatrix, workspace, generatorMode);

            for (int j = 0; j < dimension; j++)
            {
                // check the mean of the j'te component etc.:
                double[] projectedSample = null;

                switch (outputRepresentation)
                {
                case Basics.BLAS.MatrixTransposeState.NoTranspose:
                    projectedSample = sample.Skip(j).Where((x, k) => k % dimension == 0).ToArray();      // the relevant sample, i.e. realisations of a normal-distributed random number
                    break;

                case Basics.BLAS.MatrixTransposeState.Transpose:
                case Basics.BLAS.MatrixTransposeState.Hermite:
                    projectedSample = sample.Skip(j * sampleSize).Where((x, k) => k < sampleSize).ToArray();
                    break;

                default:
                    throw new NotImplementedException();
                }
                Assert.That(projectedSample.Length >= sampleSize, String.Format("Length : {0}", projectedSample.Length));

                double expectedMean  = mu[j];
                double estimatedMean = projectedSample.Average();

                double estimatedStandardDeviation = GetEstimatedStandardDeviation(projectedSample, sampleSize, estimatedMean);
                double epsilon = 2.0 * estimatedStandardDeviation / Math.Sqrt(sampleSize); // size of the confidence interval w.r.t. normal distribution N{-1}(0.975) \approx 1.96 \approx 2.0

                /* test whether E(X) \in [ estimatedMean - \epsilon, estimatedMean + \epsilon], where \epsilon = \sigma/\sqrt(n} */
                Assert.That(estimatedMean + epsilon, Is.GreaterThanOrEqualTo(expectedMean), String.Format("Component: {0}; expected Mean: {1}; estimated Mean: {2}; lower Confidence Interval bound: {3}; upper Confidence Interval bound: {4}.", j, expectedMean, estimatedMean, estimatedMean - epsilon, estimatedMean + epsilon));
                Assert.That(estimatedMean - epsilon, Is.LessThanOrEqualTo(expectedMean), String.Format("Component: {0}; expected Mean: {1}; estimated Mean: {2}; lower Confidence Interval bound: {3}; upper Confidence Interval bound: {4}.", j, expectedMean, estimatedMean, estimatedMean - epsilon, estimatedMean + epsilon));
            }
        }
Example #5
0
        /// <summary>Initializes a new instance of the <see cref="OneDimSAOptimizer"/> class.
        /// </summary>
        /// <param name="randomNumberStream">The random number stream.</param>
        /// <param name="configuration">The configuration of the Simulated Annealing optimizer.</param>
        /// <param name="abortCondition">The abort (stopping) condition for the Simulated Annealing optimizer.</param>
        public OneDimSAOptimizer(IRandomNumberStream randomNumberStream, OneDimSAOptimizerConfiguration configuration, OneDimSAOptimizerAbortCondition abortCondition)
        {
            AbortCondition = abortCondition ?? throw new ArgumentNullException(nameof(abortCondition));
            Configuration  = configuration ?? throw new ArgumentNullException(nameof(configuration));

            if (randomNumberStream == null)
            {
                throw new ArgumentNullException(nameof(randomNumberStream));
            }
            m_SingleRandomNumberStream = new SingleRandomNumberStream(randomNumberStream, 250);

            m_Name = new IdentifierString(String.Format("1-dim Simulated Annealing; {0}", abortCondition.ToString()));
            m_ObjectiveFunctionFactory = new OneDimOptimizerFunctionFactory();
            m_ConstraintDescriptor     = new OneDimOptimizerConstraintFactory(OneDimOptimizerConstraintFactory.ConstraintType.BoundedInterval);
        }
Example #6
0
        /// <summary>Initializes a new instance of the <see cref="PraxisOptimizer"/> class.
        /// </summary>
        /// <param name="randomNumberStream">The random number stream.</param>
        /// <param name="abortCondition">The abort (stopping) condition for the Simulated Annealing optimizer.</param>
        /// <param name="constraintProvider">The constraint provider, i.e. transformation etc. for the support of specific constraints (the original algorithm does not support any constraints).</param>
        /// <param name="scalingFactor">A scaling parameter. If the scales for the different parameters are very different this value should be/ set to a value of about 10.0.</param>
        /// <param name="expectedDistanceToSolution">A step length parameter which should be set equal to the expected distance from the solution.</param>
        public PraxisOptimizer(IRandomNumberStream randomNumberStream, PraxisOptimizerAbortCondition abortCondition, MultiDimOptimizerConstraintProvider constraintProvider, double scalingFactor = 1.0, double expectedDistanceToSolution = 1.0)
        {
            if (randomNumberStream == null)
            {
                throw new ArgumentNullException(nameof(randomNumberStream));
            }
            m_SingleRandomNumberStream = new SingleRandomNumberStream(randomNumberStream, 250);
            AbortCondition             = abortCondition ?? throw new ArgumentNullException(nameof(abortCondition));
            m_ConstraintProvider       = constraintProvider ?? throw new ArgumentNullException(nameof(constraintProvider));

            ScalingFactor = scalingFactor;
            ExpectedDistanceToSolution = expectedDistanceToSolution;
            m_Name = new IdentifierString("PRAXIS optimizer");
            m_FunctionDescriptor   = new OrdinaryMultiDimOptimizerFunctionFactory();
            m_ConstraintDescriptor = new MultiDimOptimizerConstraintFactory(constraintProvider.SupportedConstraints);
        }
Example #7
0
        public void NextNumberSequenceUniform_EstimatedMean_ConvidenceInterval(int sampleSize, double a, double b, RandomNumberSequence.UniformGenerationMode generatorMode)
        {
            double expectedMean = (a + b) / 2.0;
            double expectedStandardDeviation = (b - a) / (2.0 * Math.Sqrt(3.0));

            var sample = new double[sampleSize];
            IRandomNumberStream randomStream = GetRandomStream();

            randomStream.NextNumberSequence.Uniform(sampleSize, sample, a, b, generatorMode);

            double estimatedMean = sample.Average();
            double estimatedStandardDeviation = GetEstimatedStandardDeviation(sample, sampleSize, estimatedMean);
            double epsilon = 2.0 * estimatedStandardDeviation / Math.Sqrt(sampleSize); // size of the confidence interval w.r.t. normal distribution N{-1}(0.975) \approx 1.96 \approx 2.0, i.e. \alpha/2 quantile with \alpha = 5%

            /* test whether E(X) \in [ estimatedMean - \epsilon, estimatedMean + \epsilon], where \epsilon = \sigma/\sqrt(n} */
            Assert.That((expectedMean >= estimatedMean - epsilon) && (expectedMean <= estimatedMean + epsilon), String.Format("a: {0}, b: {1}, Expectation: {2}, Standard deviation: {3}, estimated mean: {4}, estimated Standard Deviation: {5}, epsilon: {6}", a, b, expectedMean, expectedStandardDeviation, estimatedMean, estimatedStandardDeviation, epsilon));
        }
Example #8
0
        public void NextNumberSequenceGaussian_EstimatedMean_ConvidenceInterval(int sampleSize, double a, double sigma, RandomNumberSequence.GaussianGenerationMode generatorMode)
        {
            double expectedMean = a;

            var sample = new double[sampleSize];
            IRandomNumberStream randomStream = GetRandomStream();

            randomStream.NextNumberSequence.Gaussian(sampleSize, sample, a, sigma, generatorMode);

            double estimatedMean = sample.Average();
            double estimatedStandardDeviation = GetEstimatedStandardDeviation(sample, sampleSize, estimatedMean);
            double epsilon = 2.0 * estimatedStandardDeviation / Math.Sqrt(sampleSize); // size of the confidence interval w.r.t. normal distribution N{-1}(0.975) \approx 1.96 \approx 2.0

            /* test whether E(X) \in [ estimatedMean - \epsilon, estimatedMean + \epsilon], where \epsilon = \sigma/\sqrt(n} */
            Assert.That(estimatedMean - epsilon, Is.LessThanOrEqualTo(expectedMean), String.Format("a: {0}, sigma: {1}, estimated mean: {2}, estimated Standard Deviation: {3}, epsilon: {4}", a, sigma, estimatedMean, estimatedStandardDeviation, epsilon));
            Assert.That(estimatedMean + epsilon, Is.GreaterThanOrEqualTo(expectedMean), String.Format("a: {0}, sigma: {1}, estimated mean: {2}, estimated Standard Deviation: {3}, epsilon: {4}", a, sigma, estimatedMean, estimatedStandardDeviation, epsilon));
        }
Example #9
0
        public void NextNumberSequenceGaussian_EstimatedSecondMoment_ConvidenceInterval(int sampleSize, double a, double sigma, RandomNumberSequence.GaussianGenerationMode generatorMode)
        {
            double expectedSecondMoment = sigma * sigma + a * a;

            var sample = new double[sampleSize];
            IRandomNumberStream randomStream = GetRandomStream();

            randomStream.NextNumberSequence.Gaussian(sampleSize, sample, a, sigma, generatorMode);
            sample = sample.Select(x => x * x).ToArray();

            double estimatedSecondMoment      = sample.Average();
            double estimatedStandardDeviation = GetEstimatedStandardDeviation(sample, sampleSize, estimatedSecondMoment);
            double epsilon = 2.0 * estimatedStandardDeviation / Math.Sqrt(sampleSize); // size of the confidence interval w.r.t. normal distribution N{-1}(0.975) \approx 1.96 \approx 2.00

            /* test whether E(X^2) \in [ estimatedMoment - \epsilon, estimatedMoment + \epsilon], where \epsilon = \sigma/\sqrt(n} */
            Assert.That(estimatedSecondMoment - epsilon, Is.LessThanOrEqualTo(expectedSecondMoment), String.Format("a: {0}; sigma: {1}; 2nd Moment: {2}; estimated 2nd Moment: {3}; estimated Standard Deviation: {4}; epsilon: {5}", a, sigma, sigma * sigma + a * a, estimatedSecondMoment, estimatedStandardDeviation, epsilon));
            Assert.That(estimatedSecondMoment + epsilon, Is.GreaterThanOrEqualTo(expectedSecondMoment), String.Format("a: {0}; sigma: {1}; 2nd Moment: {2}; estimated 2nd Moment: {3}; estimated Standard Deviation: {4}; epsilon: {5}", a, sigma, sigma * sigma + a * a, estimatedSecondMoment, estimatedStandardDeviation, epsilon));
        }
Example #10
0
        public void NextNumberSequenceGaussian_EstimateVariance_ConvidenceInterval(int sampleSize, double a, double sigma, double lowerCriticalValueOfChiSquaredDistribution, double upperCriticalValueOfChiSquaredDistribution, RandomNumberSequence.GaussianGenerationMode generatorMode)
        {
            var sample = new double[sampleSize];
            IRandomNumberStream randomStream = GetRandomStream();

            randomStream.NextNumberSequence.Gaussian(sampleSize, sample, a, sigma, generatorMode);

            double estimatedMean     = sample.Average();
            double estimatedVariance = GetEstimatedVariance(sample, sampleSize, estimatedMean);

            /* check whether the (theoretical) variance is inside
             *
             * [ (n-1) * S^2 / \chi^2_{\alpha/2, n-1}, (n-1)*S^2 / \chi^2_{1.0 - \alpha/2, n-1} ],
             *
             * where \chi^2_{\alpha, n} is the quantile of the chi-square distribution with degree n and parameter \alpha.
             */
            double expectedVariance = sigma * sigma;

            Assert.That((sampleSize - 1) * estimatedVariance / upperCriticalValueOfChiSquaredDistribution, Is.GreaterThanOrEqualTo(expectedVariance), String.Format("a: {0}, sigma: {1}, sampleSize: {2}, theor. Variance: {3}, estimated mean: {4}, estimated Variance: {5}, upper-Chi Squared quantile: {6}", a, sigma, sampleSize, expectedVariance, estimatedMean, estimatedVariance, upperCriticalValueOfChiSquaredDistribution));
            Assert.That((sampleSize - 1) * estimatedVariance / lowerCriticalValueOfChiSquaredDistribution, Is.LessThanOrEqualTo(expectedVariance), String.Format("a: {0}, sigma: {1}, sampleSize: {2}, theor. Variance: {3}, estimated mean: {4}, estimated Variance: {5}, lower-Chi Squared quantile: {6}", a, sigma, sampleSize, expectedVariance, estimatedMean, estimatedVariance, lowerCriticalValueOfChiSquaredDistribution));
        }
Example #11
0
        /// <summary>Overrides the stream state data of a specific stream object with the data of the current object.
        /// </summary>
        /// <param name="destinationStream">The destination random number stream.</param>
        /// <exception cref="ArgumentException">Thrown, if the stream of the current instance and the stream represented by <paramref name="destinationStream"/> are not compatible.</exception>
        /// <remarks>Stream state data are for example the dimension etc.</remarks>
        public void CopyStreamStateTo(IRandomNumberStream destinationStream)
        {
            if (destinationStream == null)
            {
                throw new ArgumentNullException("destinationStream");
            }

            MklRandomNumberStream destinationVslRandomStream = destinationStream as MklRandomNumberStream;

            if (destinationVslRandomStream == null)
            {
                throw new ArgumentException("destinationStream");
            }

            int errorCode = vslCopyStreamState(destinationVslRandomStream.m_Handle, m_Handle);

            if (errorCode != 0) // execution is not successful
            {
                throw new ArgumentException("MKL: Return value " + errorCode + " in vslCopyStreamState.", "destinationStream");
            }
            destinationVslRandomStream.m_Dimension = m_Dimension;
            destinationVslRandomStream.m_Generator = m_Generator;
        }
Example #12
0
 /// <summary>Initializes a new instance of the <see cref="PraxisOptimizer"/> class.
 /// </summary>
 /// <param name="randomNumberStream">The random number stream.</param>
 /// <param name="scalingFactor">A scaling parameter. If the scales for the different parameters are very different this value should be/ set to a value of about 10.0.</param>
 /// <param name="expectedDistanceToSolution">A step length parameter which should be set equal to the expected distance from the solution.</param>
 /// <remarks>The <see cref="PraxisOptimizer.StandardAbortCondition"/> and <see cref="PraxisOptimizer.StandardConstraintProvider"/> are taken into account.</remarks>
 public PraxisOptimizer(IRandomNumberStream randomNumberStream, double scalingFactor = 1.0, double expectedDistanceToSolution = 1.0)
     : this(randomNumberStream, StandardAbortCondition, StandardConstraintProvider, scalingFactor, expectedDistanceToSolution)
 {
 }
Example #13
0
        public void NextNumberSequenceGaussianMultivariate_EstimatedVariance_ConvidenceInterval(int dimension, int sampleSize, double[] mu, double[] pseudoRootOfVarianceCovarianceMatrix, RandomNumberSequence.MultivariateMatrixStorageType matrixStorageType, double lowerCriticalValueOfChiSquaredDistribution, double upperCriticalValueOfChiSquaredDistribution, RandomNumberSequence.GaussianGenerationMode generatorMode)
        {
            IRandomNumberStream randomStream = GetRandomStream();

            /* do not apply BoxMuller to Pseudo-Random Number Generator: */
            Assume.That(randomStream.Generator is IPseudoRandomNumberGenerator || (string)generatorMode.Name != "BoxMuller", "Box-Muller approach is for Pseudo-Random Number Generators not adequate.");


            var sample          = new double[sampleSize * dimension];
            int workspaceLength = randomStream.NextNumberSequence.GaussianMultivariateWorkspaceQuery(sampleSize, dimension, matrixStorageType, generatorMode);

            double[] workspace = null;
            if (workspaceLength > 0)
            {
                workspace = new double[workspaceLength];
            }
            var outputRepresentation = randomStream.NextNumberSequence.GaussianMultivariate(sampleSize, sample, dimension, matrixStorageType, mu, pseudoRootOfVarianceCovarianceMatrix, workspace, generatorMode);

            int triangularPackagedMatrixStartIndex = 0;

            for (int j = 0; j < dimension; j++)
            {
                // check the variance of the j'te component
                double[] projectedSample = null;

                switch (outputRepresentation)
                {
                case Basics.BLAS.MatrixTransposeState.NoTranspose:
                    projectedSample = sample.Skip(j).Where((x, k) => k % dimension == 0).ToArray();      // the relevant sample, i.e. realisations of a normal-distributed random number
                    break;

                case Basics.BLAS.MatrixTransposeState.Transpose:
                case Basics.BLAS.MatrixTransposeState.Hermite:
                    projectedSample = sample.Skip(j * sampleSize).Where((x, k) => k < sampleSize).ToArray();
                    break;

                default:
                    throw new NotImplementedException();
                }
                Assert.That(projectedSample.Length >= sampleSize, String.Format("Length : {0}", projectedSample.Length));

                double expectedMean  = mu[j];
                double estimatedMean = projectedSample.Average();

                double estimatedVariance = GetEstimatedVariance(projectedSample, sampleSize, estimatedMean);

                double expectedVariance = 0.0;
                switch (matrixStorageType)
                {
                case RandomNumberSequence.MultivariateMatrixStorageType.Diagonal:
                    expectedVariance = pseudoRootOfVarianceCovarianceMatrix[j] * pseudoRootOfVarianceCovarianceMatrix[j];
                    break;

                case RandomNumberSequence.MultivariateMatrixStorageType.Full:

                    // compute [Q * Q']_{j,j], where Q' is one of the arguments
                    for (int k = 0; k < dimension; k++)
                    {
                        double temp = pseudoRootOfVarianceCovarianceMatrix[k + dimension * j];
                        expectedVariance += temp * temp;
                    }
                    break;

                case RandomNumberSequence.MultivariateMatrixStorageType.TriangularPackaged:

                    for (int k = 0; k <= j; k++)
                    {
                        double temp = pseudoRootOfVarianceCovarianceMatrix[triangularPackagedMatrixStartIndex + k];
                        expectedVariance += temp * temp;
                    }
                    triangularPackagedMatrixStartIndex += j + 1;
                    break;

                default:
                    throw new NotImplementedException();
                }

                /* check whether the (theoretical) variance is inside
                 *
                 * [ (n-1) * S^2 / \chi^2_{\alpha/2, n-1}, (n-1)*S^2 / \chi^2_{1.0 - \alpha/2, n-1} ],
                 *
                 * where \chi^2_{\alpha, n} is the quantile of the chi-square distribution with degree n and parameter \alpha.
                 */
                Assert.That(estimatedVariance * (sampleSize - 1) / upperCriticalValueOfChiSquaredDistribution, Is.GreaterThanOrEqualTo(expectedVariance), String.Format("Component: {0}; sampleSize: {1}, theor. Variance: {2}, estimated mean: {3}, estimated Variance: {4}, upper-Chi Squared quantile: {5}", j, sampleSize, expectedVariance, estimatedMean, estimatedVariance, upperCriticalValueOfChiSquaredDistribution));
                Assert.That(estimatedVariance * (sampleSize - 1) / lowerCriticalValueOfChiSquaredDistribution, Is.LessThanOrEqualTo(expectedVariance), String.Format("Component: {0}; sampleSize: {1}, theor. Variance: {2}, estimated mean: {3}, estimated Variance: {4}, upper-Chi Squared quantile: {5}", j, sampleSize, expectedVariance, estimatedMean, estimatedVariance, upperCriticalValueOfChiSquaredDistribution));
            }
        }
Example #14
0
        public void NextNumberSequenceUniform_SkipAheadEstimatedMean_ConvidenceInterval(int sampleSize, double a, double b, RandomNumberSequence.UniformGenerationMode generatorMode)
        {
            double expectedMean = (a + b) / 2.0;
            double expectedStandardDeviation = (b - a) / (2.0 * Math.Sqrt(3.0));

            IRandomNumberStream randomStream = GetRandomStream();

            Assume.That(randomStream.SplittingApproach.HasFlag(RandomNumberSequence.SplittingApproach.SkipAhead), String.Format("Random Number Generator {0} does not support Leapfrog approach.", randomStream.ToString()));

            var sample          = new List <double>();
            int numberOfStreams = 2;
            int nskip           = sampleSize * numberOfStreams;

            for (int j = 0; j < numberOfStreams; j++)
            {
                var stream = randomStream.CreateSkipAheadStream(j * nskip);

                int subSampleSize = sampleSize / numberOfStreams;
                var subSample     = new double[subSampleSize];
                stream.NextNumberSequence.Uniform(subSampleSize, subSample, a, b, generatorMode);

                sample.AddRange(subSample);
            }
            sampleSize = sample.Count;

            /* alternativly, use: */

            /*
             * var stream1 = randomStream.CreateSkipAheadStream(5);
             * var stream2 = stream1.CreateSkipAheadStream(5);
             * var stream3 = stream2.CreateSkipAheadStream(5);
             *
             * int subSampleSize = sampleSize / 3;
             * var sample1 = new double[subSampleSize];
             * stream1.NextNumberSequence.Uniform(subSampleSize, sample1, a, b, generatorMode);
             *
             * var sample2 = new double[subSampleSize];
             * stream2.NextNumberSequence.Uniform(subSampleSize, sample2, a, b, generatorMode);
             *
             * var sample3 = new double[subSampleSize];
             * stream3.NextNumberSequence.Uniform(subSampleSize, sample3, a, b, generatorMode);
             *
             * var sample = new List<double>();
             * sample.AddRange(sample1);
             * sample.AddRange(sample2);
             * sample.AddRange(sample3);
             */

            /* compute estimated mean and standard deviation: */
            double estimatedMean = sample.Average();
            double estimatedStandardDeviation = GetEstimatedStandardDeviation(sample.ToArray(), sampleSize, estimatedMean);
            double epsilon = 2.0 * estimatedStandardDeviation / Math.Sqrt(sampleSize); // size of the confidence interval w.r.t. normal distribution N{-1}(0.975) \approx 1.96 \approx 2.0, i.e. \alpha/2 quantile with \alpha = 5%

            /*
             * Even for a fixed seed the results of the random sampling are not identically (for Intel's MKL Library)!
             *
             * Therefore we enlarge the convidence interval - this unit test is not part of a test suite for Random Number Generators.
             * We focus on the integration with the native Dll.
             */
            epsilon *= 2.0;  // special adjustment, in most cases not necessary

            /* test whether E(X) \in [ estimatedMean - \epsilon, estimatedMean + \epsilon], where \epsilon = \sigma/\sqrt(n} */
            Assert.That(estimatedMean - epsilon, Is.LessThanOrEqualTo(expectedMean), String.Format("a: {0}, b: {1}, Expectation: {2}, Standard deviation: {3}, estimated mean: {4}, estimated Standard Deviation: {5}, epsilon: {6}", a, b, expectedMean, expectedStandardDeviation, estimatedMean, estimatedStandardDeviation, epsilon));
            Assert.That(estimatedMean + epsilon, Is.GreaterThanOrEqualTo(expectedMean), String.Format("a: {0}, b: {1}, Expectation: {2}, Standard deviation: {3}, estimated mean: {4}, estimated Standard Deviation: {5}, epsilon: {6}", a, b, expectedMean, expectedStandardDeviation, estimatedMean, estimatedStandardDeviation, epsilon));
        }
Example #15
0
 /// <summary>Initializes a new instance of the <see cref="OneDimSAOptimizer"/> class.
 /// </summary>
 /// <param name="randomNumberStream">The random number stream.</param>
 /// <remarks>The <see cref="OneDimSAOptimizer.StandardAbortCondition"/> and <see cref="OneDimSAOptimizer.StandardConfiguration"/> are taken into account.</remarks>
 public OneDimSAOptimizer(IRandomNumberStream randomNumberStream)
     : this(randomNumberStream, StandardConfiguration, StandardAbortCondition)
 {
 }