Пример #1
0
        public MotionSequence GenerateSynchronousSingleSequence(int dimention)
        {
            var uniform         = new ContinuousUniform(0, 1, _randomGenerator);
            var ValueRangeRatio = (float)uniform.Sample();
            var InitialForce    = (float)uniform.Sample();

            if (_numControlPoints != InitialTimes.Length)
            {
                throw new ArgumentException("コントロールポイント数が不一致");
            }

            // 位相にノイズを入れる
            var offset = Mathf.PI * (uniform.Sample() > 0.5 ? 1 : 0);

            var sequence = new MotionTarget[InitialTimes.Length];

            for (var i = 0; i < InitialTimes.Length; i++)
            {
                var values = new float[dimention];
                values[0] = InitialForce;
                for (var d = 1; d < dimention; d++)
                {
                    // control point value
                    var radian = InitialTimes[i] * 2f * Mathf.PI + offset;
                    values[d] = 0.5f + ValueRangeRatio * Mathf.Sin(radian) / 2f; // [0,1]に正規化;
                }

                sequence[i] = new MotionTarget(InitialTimes[i] * _timeRange, values);
            }

            return(new MotionSequence(sequence));
        }
Пример #2
0
        static void LoadXOR(out HashSet <TrainingData> data, int length, int nData)
        {
            data = new HashSet <TrainingData>();
            ContinuousUniform rand = new ContinuousUniform(0, 1);

            for (var i = 0; i < nData; i++)
            {
                TrainingData td = new TrainingData(1, 1);
                td[0] = new TrainingData.TrainingPair(DenseVector.Create(1, rand.Sample() > 0.5 ? 1 : 0), DenseVector.Create(1, 0.5));
                for (var j = 1; j < length; j++)
                {
                    TrainingData.TrainingPair p = new TrainingData.TrainingPair();
                    p.Data = DenseVector.Create(1, rand.Sample() > 0.5 ? 1 : 0);
                    if (td[j - 1].Data[0] == p.Data[0])
                    {
                        p.Response = DenseVector.Create(1, 0);
                    }
                    else
                    {
                        p.Response = DenseVector.Create(1, 1);
                    }
                    td[j] = p;
                }
                data.Add(td);
            }
        }
Пример #3
0
        public void Selection()
        {
            int randomIndividualsNumber = Mathf.RoundToInt(randomIndividualsRate * populationSize);
            int bestIndividualsNumber   = Mathf.RoundToInt(bestIndividualsRate * populationSize);


            for (int i = 0; i < bestIndividualsNumber; i++)
            {
                for (int j = 0; j < individualSize; j++)
                {
                    tmp[j, i] = bestIndividual[j];
                }
                //tmp.SetColumn(i, bestIndividual);
            }

            for (int i = bestIndividualsNumber; i < bestIndividualsNumber + randomIndividualsNumber; i++)
            {
                //tmp.SetColumn(i, Vector<float>.Build.Random(individualSize, distribution));
                for (int j = 0; j < individualSize; j++)
                {
                    tmp[j, i] = (float)distribution.Sample();
                }
                distEmpty = Combinatorics.GenerateCombination(individualSize, Mathf.RoundToInt(emptyRate * individualSize), rndGenerator);
                for (int j = 0; j < individualSize; j++)
                {
                    if (distEmpty[j])
                    {
                        population[j, i] = 0;
                    }
                }
            }

            for (int i = randomIndividualsNumber + bestIndividualsNumber; i < populationSize; i++)
            {
                int index = SelectionOneElementIndex();
                for (int j = 0; j < individualSize; j++)
                {
                    tmp[j, i] = population[j, index];
                }

                //tmp.SetColumn(i, SelectionOneElement());
            }

            //int[] p = Combinatorics.GeneratePermutation(populationSize);
            Combinatorics.SelectPermutationInplace(indexPermutation, rndGenerator);

            /*for (int i =0; i < populationSize; i++) {
             *  Debug.Log(indexPermutation[i]);
             * }*/
            Permutation p = new Permutation(indexPermutation);

            tmp.PermuteColumns(p);

            Matrix <float> refPop = population;

            population = tmp;
            tmp        = refPop;

            //tmp.CopyTo(population);
        }
        /// <summary>
        /// Build linear samples.
        /// </summary>
        /// <param name="x">X sample values.</param>
        /// <param name="y">Y samples values.</param>
        /// <param name="xtest">X test values.</param>
        /// <param name="ytest">Y test values.</param>
        /// <param name="samples">Sample values.</param>
        /// <param name="sampleOffset">Sample offset.</param>
        /// <param name="slope">Slope number.</param>
        /// <param name="intercept">Intercept criteria.</param>
        public static void Build(out double[] x, out double[] y, out double[] xtest, out double[] ytest, int samples = 3, double sampleOffset = -0.5, double slope = 2.0, double intercept = -1.0)
        {
            // Fixed-seed "random" distribution to ensure we always test with the same data
            var uniform = new ContinuousUniform(0.0, 1.0, new SystemRandomSource(42));

            // build linear samples
            x = new double[samples];
            y = new double[samples];
            for (int i = 0; i < x.Length; i++)
            {
                x[i] = i + sampleOffset;
                y[i] = (x[i] * slope) + intercept;
            }

            // build linear test vectors randomly between the sample points
            xtest = new double[samples + 1];
            ytest = new double[samples + 1];
            if (samples == 1)
            {
                // y = const
                xtest[0] = sampleOffset - uniform.Sample();
                xtest[1] = sampleOffset + uniform.Sample();
                ytest[0] = ytest[1] = (sampleOffset * slope) + intercept;
            }
            else
            {
                for (int i = 0; i < xtest.Length; i++)
                {
                    xtest[i] = (i - 1) + sampleOffset + uniform.Sample();
                    ytest[i] = (xtest[i] * slope) + intercept;
                }
            }
        }
        /// <summary>
        /// Build linear samples.
        /// </summary>
        /// <param name="x">X sample values.</param>
        /// <param name="y">Y samples values.</param>
        /// <param name="xtest">X test values.</param>
        /// <param name="ytest">Y test values.</param>
        /// <param name="samples">Sample values.</param>
        /// <param name="sampleOffset">Sample offset.</param>
        /// <param name="slope">Slope number.</param>
        /// <param name="intercept">Intercept criteria.</param>
        public static void Build(out double[] x, out double[] y, out double[] xtest, out double[] ytest, int samples = 3, double sampleOffset = -0.5, double slope = 2.0, double intercept = -1.0)
        {
            // Fixed-seed "random" distribution to ensure we always test with the same data
            var uniform = new ContinuousUniform(0.0, 1.0, new MersenneTwister(42));

            // build linear samples
            x = new double[samples];
            y = new double[samples];
            for (int i = 0; i < x.Length; i++)
            {
                x[i] = i + sampleOffset;
                y[i] = (x[i] * slope) + intercept;
            }

            // build linear test vectors randomly between the sample points
            xtest = new double[samples + 1];
            ytest = new double[samples + 1];
            if (samples == 1)
            {
                // y = const
                xtest[0] = sampleOffset - uniform.Sample();
                xtest[1] = sampleOffset + uniform.Sample();
                ytest[0] = ytest[1] = (sampleOffset * slope) + intercept;
            }
            else
            {
                for (int i = 0; i < xtest.Length; i++)
                {
                    xtest[i] = (i - 1) + sampleOffset + uniform.Sample();
                    ytest[i] = (xtest[i] * slope) + intercept;
                }
            }
        }
Пример #6
0
        public void Cudnn_UseCase_ForwardConvolution_Float()
        {
            CudnnContext.DefaultType         = CudnnType.Float;
            CudnnContext.DefaultTensorFormat = CudnnTensorFormat.MajorRow;

            using (var context = CudnnContext.Create())
            {
                // Set some options and tensor dimensions
                int nInput           = 100;
                int filtersIn        = 10;
                int filtersOut       = 8;
                int heightIn         = 20;
                int widthIn          = 20;
                int heightFilter     = 5;
                int widthFilter      = 5;
                int paddingHeight    = 4;
                int paddingWeight    = 4;
                int verticalStride   = 1;
                int horizontalStride = 1;
                int upscalex         = 1;
                int upscaley         = 1;

                var distribution = new ContinuousUniform(0, 1);

                // Input Tensor Data
                Vector <float> xDataVector = Vector <float> .Build.Dense(nInput *filtersIn *heightIn *widthIn);

                xDataVector.MapInplace(x => (float)distribution.Sample(), Zeros.Include);

                // Filter Tensor Data
                Vector <float> filterData = Vector <float> .Build.Dense(filtersOut *filtersIn *heightFilter *widthFilter);

                filterData.MapInplace(x => (float)distribution.Sample(), Zeros.Include);

                // Descriptor for input
                var xTensor = CudnnContext.CreateTensor(new CudnnTensorDescriptorParameters(nInput, filtersIn, heightFilter, widthFilter));

                // Filter descriptor
                var filter = CudnnContext.CreateFilter(new CudnnFilterDescriptorParameters(filtersOut, filtersIn, heightFilter, widthFilter));

                // Convolution descriptor
                var convolution = CudnnContext.CreateConvolution(new CudnnConvolutionDescriptorParameters(CudnnConvolutionMode.CrossCorrelation, xTensor, filter, paddingHeight, paddingWeight, verticalStride, horizontalStride, upscalex, upscaley));
                var output      = convolution.GetOutputTensor(CudnnConvolutionPath.Forward);

                // Output tensor
                var     yTensor = CudnnContext.CreateTensor(new CudnnTensorDescriptorParameters(nInput, filtersOut, output.Height, output.Width));
                float[] yData   = new float[nInput * filtersOut * output.Height * output.Width];

                // Perform convolution
                context.Forward(xTensor, xDataVector.ToArray(), filter, filterData.ToArray(), convolution, yTensor, yData, CudnnAccumulateResult.DoNotAccumulate);

                // Clean up
                xTensor.Dispose();
                yTensor.Dispose();
                filter.Dispose();
                convolution.Dispose();
            }
        }
Пример #7
0
        /// <summary>
        ///     BeInfluenced a beliefBit by doing
        ///     Random value is used to set the new value
        /// </summary>
        /// <param name="model"></param>
        /// <param name="beliefBit"></param>
        public void Learn(RandomGenerator model, byte beliefBit)
        {
            var bit = BeliefBits.GetBit(beliefBit);

            switch (model)
            {
            case RandomGenerator.RandomUniform:
                bit += ContinuousUniform.Sample(RangeMin, RangeMax);
                if (bit < RangeMin)
                {
                    bit = RangeMin;
                }

                if (bit > RangeMax)
                {
                    bit = RangeMax;
                }

                break;

            case RandomGenerator.RandomBinary:
                bit = DiscreteUniform.Sample(RangeMin, RangeMax);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(model), model, null);
            }

            BeliefBits.SetBit(beliefBit, bit);
        }
        public TestSimpleIdentification()
        {
            TestName     = "Простая модель с идентификацией";
            TestFileName = "TestSimpleIdentification";


            Vector <double> mW = Exts.Vector(0, 0); Matrix <double> dW = Exts.Diag(0, 1.0);
            Vector <double> mNu = Exts.Vector(0); Matrix <double> dNu = Exts.Diag(1.0);
            Vector <double> mEta = Exts.Vector(0, 0.0); Matrix <double> dEta = Exts.Diag(0.27, 0);
            Func <int, Vector <double>, Vector <double> > phi1 = (s, x) => Exts.Vector(x[0], x[0] * x[1]);
            Func <int, Vector <double>, Matrix <double> > phi2 = (s, x) => Exts.Diag(0.0, 1.0);
            Func <int, Vector <double>, Vector <double> > psi1 = (s, x) => Exts.Vector(x[1]);
            Func <int, Vector <double>, Matrix <double> > psi2 = (s, x) => Exts.Matrix(0.1);

            RandomVector <Normal> NormalW  = new RandomVector <Normal>(mW, dW);
            RandomVector <Normal> NormalNu = new RandomVector <Normal>(mNu, dNu);
            ContinuousUniform     UniformW = new ContinuousUniform(-0.9, 0.9);

            Phi1 = phi1;
            Phi2 = phi2;
            Psi1 = psi1;
            Psi2 = psi2;
            Xi   = (s, x) => phi1(s, x) + phi2(s, x) * mW;
            Zeta = (s, x, y, k) => y - psi1(s, x) - psi2(s, x) * mNu;


            W      = (s) => NormalW.Sample();
            Nu     = (s) => NormalNu.Sample();
            DW     = dW;
            DNu    = dNu;
            X0     = () => Exts.Vector(UniformW.Sample(), 0.0);
            X0Hat  = mEta;
            DX0Hat = dEta;
        }
Пример #9
0
    public void Reset(float initialValueWeights, bool firstReset, List <float[, ]> customWeights = null)
    {
        for (int i = 0; i < shapesSize - 1; i++)
        {
            for (int j = 0; j < weights[i].GetLength(0); j++)
            {
                for (int k = 0; k < weights[i].GetLength(1); k++)
                {
                    //Debug.Log("i, j , k " + i + " - "+j + " - " + k);
                    //Debug.Log("Lenght " + weights[i].GetLength(0) + "-" + weights[i].GetLength(1));
                    if (customWeights != null)
                    {
                        weights[i][j, k] = customWeights[i][j, k];
                    }
                    else
                    {
                        weights[i][j, k] = (float)ContinuousUniform.Sample(rndGenerator, -initialValueWeights, initialValueWeights);
                    }

                    dw[i][j, k] = 0.0f;
                }
            }
        }
        WriteListArray("Weights", "init", weights);
    }
    public static Twist Twist(Random rnd)
    {
        var twistX = ContinuousUniform.Sample(rnd, -1, 1);
        var twist  = new Twist((float)twistX);

        return(twist);
    }
Пример #11
0
        private void GetPlanetoidOrbitalRadiusAndAngle(ref List <Planetoid> lstPlanetoids, out int _intOrbitalRadius, out int _intAngleFromZero)
        {
            int  intOrbitRadius = (int)ContinuousUniform.Sample(100.0d, SystemRadius);
            bool blnGoodOrbit   = false;
            int  intReTryCount  = 0;

            _intAngleFromZero = (int)ContinuousUniform.Sample(0, 359);

            while (blnGoodOrbit == false)
            {
                if (!lstPlanetoids.Exists(plt => intOrbitRadius < plt.OrbitalRadius + 50 && intOrbitRadius > plt.OrbitalRadius - 50))
                {
                    blnGoodOrbit = true;
                }
                else
                {
                    intReTryCount++;
                    intOrbitRadius = (int)ContinuousUniform.Sample(100.0d, SystemRadius);
                }
                if (intReTryCount >= 10)
                {
                    _intOrbitalRadius = 0;
                    _intAngleFromZero = 0;
                    return;
                }
            }

            _intOrbitalRadius = intOrbitRadius;
        }
Пример #12
0
        public static void GenerateStars(GlobalConstants.GalaxySize GalaxySize, GlobalConstants.GalaxyType GalaxyType)
        {
            SizeEnum       = GalaxySize;
            GalaxyTypeEnum = GalaxyType;

            SetGalaxyRadiusAndStarCountByGalazySize(SizeEnum);

            Engine.Instance.WriteToConsole("Generating galaxy!");
            Engine.Instance.WriteToConsole("Galaxy size: " + SizeEnum + "; Galaxy type: " + GalaxyTypeEnum);
            Engine.Instance.WriteToConsole("Star count: " + StarCount.ToString());
            Engine.Instance.WriteToConsole("");

            List <Star>       arrStars      = new List <Star>();
            ContinuousUniform StarRadiusGen = new ContinuousUniform(2, 16.3);

            for (int i = 0; i < StarCount; i++)
            {
                float fltStarRad = (float)StarRadiusGen.Sample();

                bool     blnShouldCreateStar = true;
                Vector2f StarPosition        = new Vector2f(0, 0);

                if (GalaxyTypeEnum == GlobalConstants.GalaxyType.DISK)
                {
                    StarPosition = GetStarCoordinatesForElipticalGalaxy(ref arrStars, out blnShouldCreateStar);
                }
                else if (GalaxyTypeEnum == GlobalConstants.GalaxyType.RING)
                {
                    StarPosition = GetStarCoordinatesForRingGalaxy(ref arrStars, out blnShouldCreateStar);
                }
                else
                {
                    StarPosition = GetStarCoordinatesForElipticalGalaxy(ref arrStars, out blnShouldCreateStar);
                }

                if (blnShouldCreateStar && StarPosition.X != 0 && StarPosition.Y != 0)
                {
                    Star objStar = new Star(fltStarRad, StarPosition, 1);
                    arrStars.Add(objStar);
                }

                Engine.Instance.WriteToConsole("Stars generated: " + i.ToString(), true, false, false);
            }

            Stars         = arrStars.ToArray();
            HomeStarIndex = random.Next(0, Stars.Length - 1);

            while (Stars[HomeStarIndex].HasPanets == false)
            {
                if (Stars[HomeStarIndex].HasPanets == true)
                {
                    Stars[HomeStarIndex].Home      = true;
                    Stars[HomeStarIndex].HasPlayer = true;
                }
                else
                {
                    HomeStarIndex = random.Next(0, Stars.Length - 1);
                }
            }
        }
Пример #13
0
        private void AddNoise(ElementNode node, PerturbSetting perturbSetting)
        {
            if (s_integerValueTypeNames.Contains(node.InstanceType, StringComparer.InvariantCultureIgnoreCase))
            {
                perturbSetting.RoundTo = 0;
            }

            var originValue = decimal.Parse(node.Value.ToString());
            var span        = perturbSetting.Span;

            if (perturbSetting.RangeType == PerturbRangeType.Proportional)
            {
                span = (double)originValue * perturbSetting.Span;
            }

            var noise          = (decimal)ContinuousUniform.Sample(-1 * span / 2, span / 2);
            var perturbedValue = decimal.Round(originValue + noise, perturbSetting.RoundTo);

            if (perturbedValue <= 0 && string.Equals(FHIRAllTypes.PositiveInt.ToString(), node.InstanceType, StringComparison.InvariantCultureIgnoreCase))
            {
                perturbedValue = 1;
            }
            if (perturbedValue < 0 && string.Equals(FHIRAllTypes.UnsignedInt.ToString(), node.InstanceType, StringComparison.InvariantCultureIgnoreCase))
            {
                perturbedValue = 0;
            }
            node.Value = perturbedValue;
            return;
        }
Пример #14
0
        public static float GetMinFromBeliefLevel(BeliefLevel level)
        {
            switch (level)
            {
            case BeliefLevel.NoBelief:
                return(0);

            case BeliefLevel.StronglyDisagree:
                return(-1F);

            case BeliefLevel.Disagree:
                return(-0.75F);

            case BeliefLevel.NeitherAgreeNorDisagree:
                return(-0.25F);

            case BeliefLevel.Agree:
                return(0.25F);

            case BeliefLevel.StronglyAgree:
                return(0.75F);

            case BeliefLevel.Random:
                return(ContinuousUniform.Sample(0, 0.75F));

            default:
                throw new ArgumentOutOfRangeException(nameof(level), level, null);
            }
        }
    double cosine(double xMin, double xMax)
    {
        double a = 0.5 * (xMin + xMax);     // location parameter
        double b = (xMax - xMin) / Math.PI; // scale parameter

        return(a + b * Math.Asin(ContinuousUniform.Sample(-1, 1)));
    }
        public override void Fill(Tensor blob)
        {
            Guard.That(() => blob.Count).IsPositive();

            using (var @cpuBlob = blob.OnCpu())
            {
                var data = @cpuBlob.Data;

                var distribution = new ContinuousUniform(0, 1);
                data.MapInplace(x => distribution.Sample(), Zeros.Include);

                int dim = blob.Count / blob.Num;
                Guard.That(() => dim).IsPositive();

                for (int i = 0; i < blob.Num; i++)
                {
                    double sum = 0.0d;
                    for (int j = 0; j < dim; j++)
                    {
                        sum += data[i * dim + j];
                    }

                    for (int j = 0; j < dim; j++)
                    {
                        data[i * dim + j] /= sum;
                    }
                }
            }
        }
Пример #17
0
        public static float GetMinFromKnowledgeLevel(KnowledgeLevel level)
        {
            switch (level)
            {
            case KnowledgeLevel.NoKnowledge:
                return(0);

            case KnowledgeLevel.BasicKnowledge:
                return(0.2F);

            case KnowledgeLevel.Foundational:
                return(0.3F);

            case KnowledgeLevel.Intermediate:
                return(0.4F);

            case KnowledgeLevel.FullProficiency:
                return(0.5F);

            case KnowledgeLevel.Expert:
                return(0.6F);

            case KnowledgeLevel.FullKnowledge:
                return(1F);

            case KnowledgeLevel.Random:
                return(ContinuousUniform.Sample(0, 1F));

            default:
                throw new ArgumentOutOfRangeException(nameof(level), level, null);
            }
        }
Пример #18
0
    private double logarithmic(double xMin, double xMax)
    {
        double a = 0.5 * (xMin + xMax); // location parameter
        double b = xMax - xMin;         // scale parameter

        return(a + b * ContinuousUniform.Sample(0, 1) * ContinuousUniform.Sample(0, 1));
    }
Пример #19
0
        // RING GALAXY
        private static Vector2f GetStarCoordinatesForRingGalaxy(ref List <Star> arrStars, out bool blnShouldBuildStar)
        {
            int intOrbitRadius = (int)ContinuousUniform.Sample(GalaxyMinorRadius, GalaxyMajorRadius);
            int THETA          = (int)ContinuousUniform.Sample(0, 359);

            double XCartCoord = intOrbitRadius * Math.Cos(THETA);
            double YCartCoord = intOrbitRadius * Math.Sin(THETA);

            Vector2f StarCoordinate = new Vector2f((float)XCartCoord, (float)YCartCoord);

            for (int currStarIndex = 0; currStarIndex < arrStars.Count(); currStarIndex++)
            {
                if (arrStars[currStarIndex] != null)
                {
                    float DistBetweenStars = (float)Math.Sqrt(((StarCoordinate.X - arrStars[currStarIndex].Origin.X) * (StarCoordinate.X - arrStars[currStarIndex].Origin.X))
                                                              + ((StarCoordinate.Y - arrStars[currStarIndex].Origin.Y) * (StarCoordinate.Y - arrStars[currStarIndex].Origin.Y)));

                    if (DistBetweenStars < 50)
                    {
                        blnShouldBuildStar = false;
                        return(new Vector2f());
                    }
                }
            }

            blnShouldBuildStar = true;
            return(StarCoordinate);
        }
Пример #20
0
        public static double AutoCallable_smooth_pricer(double S0, double r, double b,
                                                        double vol, double[] fixings, double remained_T, double total_T, double ko_price, double coupon, double rebate, double funding,
                                                        double annpay, int nsims, int seed)
        {
            //annpay 0 stands for absolute,1 stands for annualized
            int             nsteps      = (int)Math.Round(remained_T * 252);
            Vector <double> payoff_vec1 = Vector <double> .Build.Dense(nsims, 0.0);

            Vector <double> payoff_vec2 = Vector <double> .Build.Dense(nsims, 0.0);

            double dt          = 1 / 252.0;
            double passed_time = total_T - remained_T;

            //check if the fixing days are valid
            if (!validate_fixing(fixings))
            {
                double error_result = double.NaN;
                return(error_result);
            }
            //get fixing days in days number
            int[]         fixing_ko_days = getFixingDays(fixings);
            System.Random rnd            = new System.Random(seed);
            for (int i = 0; i < nsims; i++)
            {
                double dW1, dW2;
                double s1 = S0;
                double s2 = S0;
                double p_not_out1, p_not_out2;
                double L1 = 1;
                double L2 = 1;
                double uniform_rand;
                foreach (int j in fixing_ko_days)
                {
                    //the day before ko observation day
                    dW1             = Normal.Sample(rnd, 0, 1);
                    dW2             = -dW1;
                    s1             *= Math.Exp((b - 0.5 * vol * vol) * dt * (j - 1) + vol * Math.Sqrt(dt * (j - 1)) * dW1);
                    s2             *= Math.Exp((b - 0.5 * vol * vol) * dt * (j - 1) + vol * Math.Sqrt(dt * (j - 1)) * dW2);
                    p_not_out1      = Normal.CDF(0, 1, (Math.Log(ko_price / s1) - (b - Math.Pow(vol, 2) / 2) * dt) / (vol * Math.Sqrt(dt)));
                    p_not_out2      = Normal.CDF(0, 1, (Math.Log(ko_price / s2) - (b - Math.Pow(vol, 2) / 2) * dt) / (vol * Math.Sqrt(dt)));
                    payoff_vec1[i] += (1 - p_not_out1) * L1 * (coupon * (Math.Pow(passed_time + j * dt, annpay)) - funding * (passed_time + j * dt))
                                      * Math.Exp(-r * j * dt);
                    payoff_vec2[i] += (1 - p_not_out2) * L2 * (coupon * (Math.Pow(passed_time + j * dt, annpay)) - funding * (passed_time + j * dt))
                                      * Math.Exp(-r * j * dt);
                    L1          *= p_not_out1;
                    L2          *= p_not_out2;
                    uniform_rand = ContinuousUniform.Sample(rnd, 0, 1);
                    dW1          = Normal.InvCDF(0, 1, p_not_out1 * uniform_rand);
                    dW2          = Normal.InvCDF(0, 1, p_not_out2 * (1 - uniform_rand));
                    s1          *= Math.Exp((b - 0.5 * vol * vol) * dt + vol * Math.Sqrt(dt) * dW1);
                    s2          *= Math.Exp((b - 0.5 * vol * vol) * dt + vol * Math.Sqrt(dt) * dW2);
                }
                payoff_vec1[i] += (rebate * Math.Pow(passed_time + fixings.Last(), annpay) * Math.Exp(-r * nsteps / 252.0) - funding * (passed_time + fixings.Last())
                                   * Math.Exp(-r * remained_T)) * L1;
                payoff_vec2[i] += (rebate * Math.Pow(passed_time + fixings.Last(), annpay) * Math.Exp(-r * nsteps / 252.0) - funding * (passed_time + fixings.Last())
                                   * Math.Exp(-r * remained_T)) * L2;
            }
            return(payoff_vec1.Average() / 2 + payoff_vec2.Average() / 2);
        }
        public static void OnUniformTestPassed(this ModelTime now, Action <ModelTime> action, double density)
        {
            var quantile = 1 - density;
            var test     = new Func <bool>(() =>
                                           ContinuousUniform.InvCDF(0, 1, ContinuousUniform.Sample()) >= quantile);

            OnContinuousDistributionTest(now, test, action, density);
        }
Пример #22
0
    public void CustomResetSpeedTest()
    {
        int   iter = 10000;
        float initialValueWeights = 1.0f;

        mlp.Reset(initialValueWeights, true);
        mlpMN.Reset(true);

        SystemRandomSource     rndGenerator = new SystemRandomSource(seed);
        List <Matrix <float> > weightsMN    = new List <Matrix <float> >();
        List <float[, ]>       weights      = new List <float[, ]>();

        for (int i = 0; i < shapes.Count - 1; i++)
        {
            weightsMN.Add(Matrix <float> .Build.Random(mlpMN.layers[i + 1].RowCount, mlpMN.layers[i].RowCount, new ContinuousUniform(-initialValueWeights, initialValueWeights, rndGenerator)));
        }

        for (int i = 0; i < shapes.Count - 1; i++)
        {
            weights.Add(new float[mlp.layers[i].GetLength(1), mlp.layers[i + 1].GetLength(1)]);
        }
        for (int i = 0; i < shapes.Count - 1; i++)
        {
            for (int j = 0; j < weights[i].GetLength(0); j++)
            {
                for (int k = 0; k < weights[i].GetLength(1); k++)
                {
                    weights[i][j, k] = (float)ContinuousUniform.Sample(rndGenerator, -initialValueWeights, initialValueWeights);
                }
            }
        }

        var watch = System.Diagnostics.Stopwatch.StartNew();

        for (int i = 0; i < iter; i++)
        {
            mlpMN.Reset(false, weightsMN);
        }
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;

        Debug.Log("Reset Time MathNet: " + elapsedMs);


        watch = System.Diagnostics.Stopwatch.StartNew();
        for (int i = 0; i < iter; i++)
        {
            mlp.Reset(initialValueWeights, false, weights);
        }
        watch.Stop();
        elapsedMs = watch.ElapsedMilliseconds;

        Debug.Log("Reset Time Array: " + elapsedMs);

        Assert.AreEqual(mlp.weights, weights);
        Assert.AreEqual(mlpMN.weights, weightsMN);
    }
Пример #23
0
        public static int GetPercentageWithRandomRounding(this int amount, double percentage)
        {
            var integerAmount   = (int)Math.Floor(amount * percentage);
            var mathExpectation = amount * percentage;
            var difference      = mathExpectation - integerAmount; // 0 <= difference < 1
            var roundedValue    = ContinuousUniform.Sample(0, 1) < difference ? 1 : 0;

            return(integerAmount + roundedValue);
        }
    public static Swing Swing(Random rnd)
    {
        var swingTheta     = ContinuousUniform.Sample(rnd, -PI, PI);
        var swingMagnitude = ContinuousUniform.Sample(rnd, 0, 1);
        var swingY         = swingMagnitude * Cos(swingTheta);
        var swingZ         = swingMagnitude * Sin(swingTheta);
        var swing          = new Swing((float)swingY, (float)swingZ);

        return(swing);
    }
Пример #25
0
        public override void Fill(Tensor blob)
        {
            using (var @cpuBlob = blob.OnCpu())
            {
                var data = @cpuBlob.Data;

                var distribution = new ContinuousUniform(this.Parameters.Min, this.Parameters.Max);
                data.MapInplace(x => distribution.Sample(), Zeros.Include);
            }
        }
Пример #26
0
        public static List <Particle> BuildSwarm(int numberOfParticles, params int[][] ranges)
        {
            return(Enumerable.Range(0, numberOfParticles).Select(_ =>
            {
                var randomParam = ranges.Select(__ => ContinuousUniform.Sample(__[0], __[1])).ToArray();


                return new Particle(randomParam.Length > 1?randomParam[1]:0, randomParam[0], 1d / numberOfParticles);
            }).ToList());
        }
Пример #27
0
        /// <summary>
        ///     Clone the Influentialness for a specific agent with a random value between [InfluentialnessRateMin,
        ///     InfluentialnessRateMax]
        /// </summary>
        /// <returns></returns>
        public static float NextInfluenceability(InternalCharacteristics internalCharacteristics)
        {
            if (internalCharacteristics == null)
            {
                throw new ArgumentNullException(nameof(internalCharacteristics));
            }

            return(ContinuousUniform.Sample(internalCharacteristics.InfluenceabilityRateMin,
                                            internalCharacteristics.InfluenceabilityRateMax));
        }
Пример #28
0
        /**
         * \brief Change an element with a probability of #mutationRate
         * \return A \e float representing the value of this element
         */

        public float MutationOneElement(float value)
        {
            float draw = (float)drawDistribution.Sample();

            if (draw <= mutationRate)
            {
                return((float)distribution.Sample());
            }
            return(value);
        }
        private double AddNoise(double value)
        {
            var span = _perturbSetting.Span;

            if (_perturbSetting.RangeType == PerturbRangeType.Proportional)
            {
                span = Math.Abs(value * _perturbSetting.Span);
            }

            double noise = _perturbSetting.NoiseFunction == null?ContinuousUniform.Sample(-1 *span / 2, span / 2) : _perturbSetting.NoiseFunction(-1 * span / 2, span / 2);

            return(Math.Round(value + noise, _perturbSetting.RoundTo));
        }
Пример #30
0
        private static double Noise(double value, PerturbSetting perturbSetting)
        {
            perturbSetting.Validation();

            var span = perturbSetting.Span;

            if (perturbSetting.RangeType == PerturbRangeType.Proportional)
            {
                span = Math.Abs(value * perturbSetting.Span);
            }

            return(perturbSetting.NoiseFunction == null?ContinuousUniform.Sample(-1 *span / 2, span / 2) : perturbSetting.NoiseFunction(span));
        }
Пример #31
0
 public static double ContinuousUniform(double lower, double upper, string sourceLocation)
 {
     try
     {
         ContinuousUniform continuousUniform = new ContinuousUniform(lower, upper, _randomSource);
         return(continuousUniform.Sample());
     }
     catch (Exception e)
     {
         Console.WriteLine($"\n{e.Message} {sourceLocation}");
         Environment.Exit(1);
         return(0);
     }
 }
 public void CanSample()
 {
     var n = new ContinuousUniform();
     var d = n.Sample();
 }