コード例 #1
0
        // sensor reading
        public void get_corrupted_accelerations(ref Vector <float> xdotdot_bf_corrupted, Vector <float> xdotdot_ideal, Vector <float> attitude_ideal)
        {
            // The accelerations in the earth frame are perfectly known from the differential equation.
            // But the accelerometer returns the accelerations in the body frame, therefore a transformation is needed.
            // R is a transformation matrix from the body to the earth frame, so R.inverse() transforms from earth to body frame.
            Matrix <float> R = Matrix <float> .Build.Dense(3, 3, 0);

            rotation(ref R, attitude_ideal);
            xdotdot_bf_corrupted = R.Inverse() * xdotdot_ideal;


            // If there is no acceleration in the earth frame (xdotdot_ideal = 0), the accelerometer would still measure the gravity acceleration.
            // Therefore the gravity vector has to be added.
            float[] gravity = { 0, 0, GRAVITY };
            xdotdot_bf_corrupted = xdotdot_bf_corrupted + R.Inverse() * Vector <float> .Build.DenseOfArray(gravity);

            // add chip tilt
            rotation(ref R, chip_tilt);
            xdotdot_bf_corrupted = R.Inverse() * xdotdot_bf_corrupted;

            MathNet.Numerics.Distributions.Normal distribution = new MathNet.Numerics.Distributions.Normal(0.0, 1.0); //using standard normal distribution

            // add noise and an offset
            xdotdot_bf_corrupted[0] += (float)distribution.Sample() * ACCELEROMETER_STANDEV_X + ACCELEROMETER_OFFSET_X;
            xdotdot_bf_corrupted[1] += (float)distribution.Sample() * ACCELEROMETER_STANDEV_Y + ACCELEROMETER_OFFSET_Y;
            xdotdot_bf_corrupted[2] += (float)distribution.Sample() * ACCELEROMETER_STANDEV_Z + ACCELEROMETER_OFFSET_Z;

            // remove the offset from the calibration
            xdotdot_bf_corrupted -= calibrated_offsets;
        }
コード例 #2
0
        /// <summary>
        /// Produce a vector of curves where the element at index i is a realization of a simulation at
        /// simulationDates i.  If you require the rates directly use <see cref="GetSimulatedRates(Date[])"/>
        /// </summary>
        /// <param name="simulationDates">Dates on which the simulation is run.  Must all be greater than the
        /// anchor date.</param>
        /// <returns></returns>
        public ICurve[] GetSimulatedCurves(Date[] simulationDates, Currency curveCcy = null)
        {
            if (curveCcy == null)
            {
                curveCcy = Currency.ANY;
            }
            var results      = new ICurve[simulationDates.Length];
            var dist         = new Normal();
            var previousDate = anchorDate;

            var previousRates = initialRates.Clone() as double[];
            var currentRates  = new double[initialRates.Length];

            // Iterate through the simulation dates
            for (var simCounter = 0; simCounter < simulationDates.Length; simCounter++)
            {
                var currentDate = simulationDates[simCounter];
                var dt          = (currentDate - previousDate) / 365.0;
                var sdt         = Math.Sqrt(dt);
                var curveDates  = new Date[initialRates.Length];

                // Random realizations to be used in simulation.
                var eps1 = dist.Sample();
                var eps2 = dist.Sample();
                var eps3 = dist.Sample();

                // Iterate thrrough the dates on the curve
                for (var i = 0; i < initialRates.Length; i++)
                {
                    curveDates[i] = simulationDates[simCounter].AddTenor(tenors[i]);
                    if (useRelative)
                    {
                        //TODO: add mean correction.
                        var exponent = components[0, i] * vols[0] * sdt * eps1 +
                                       components[1, i] * vols[1] * sdt * eps2 +
                                       components[2, i] * vols[2] * sdt * eps3;
                        currentRates[i] = previousRates[i] * Math.Exp(exponent);
                    }
                    else
                    {
                        var change = components[0, i] * vols[0] * sdt * eps1 + components[1, i] * vols[1] * sdt * eps2 +
                                     components[2, i] * vols[2] * sdt * eps3;
                        currentRates[i] = previousRates[i] + change;
                        if (floorAtZero)
                        {
                            currentRates[i] = Math.Max(0.0, currentRates[i]);
                        }
                    }
                }

                currentRates        = currentRates.Multiply(multiplier);
                results[simCounter] = new DatesAndRates(curveCcy, simulationDates[simCounter], curveDates, currentRates,
                                                        simulationDates[simCounter].AddMonths(360));
                previousRates = currentRates.Clone() as double[];
                previousDate  = new Date(currentDate);
            }

            return(results);
        }
コード例 #3
0
        private void SetNextOrderAmount()
        {
            switch (OptionA)
            {
            case EnumTypes.BuyerAOptions.Static:
                NextOrderAmount = this.Amount;
                break;

            case EnumTypes.BuyerAOptions.Random:
                Random rnd  = new Random();
                int    rand = rnd.Next(Convert.ToInt32(this.MinAmount), Convert.ToInt32(this.MaxAmount) + 1);
                NextOrderAmount = rand;
                break;

            case EnumTypes.BuyerAOptions.Poisson:
                MathNet.Numerics.Distributions.Poisson poisson = new MathNet.Numerics.Distributions.Poisson(this.Lambda);
                NextOrderAmount = poisson.Sample();
                break;

            case EnumTypes.BuyerAOptions.Gauss:
                MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(this.MeanOptionA, this.DeviationOptionA);
                NextOrderAmount = normal.Sample();
                break;
            }
        }
コード例 #4
0
        //method for performing gaussian distribution mutation
        public List <Offspring> gaussian_mutaion(List <Offspring> offspring, int offspring_size, double mutation_rate, int number_genes, Random random, MathNet.Numerics.Distributions.Normal normalDist, double lower_range, double higher_range)
        {
            for (int i = 0; i < offspring_size; i++)
            {
                for (int j = 0; j < number_genes; j++)
                {
                    this.generated_number = random.NextDouble();

                    //perform mutation if generated number is less than or equal to mutation rate
                    if (this.generated_number <= mutation_rate)
                    {
                        //calculate new gene value
                        this.gene_value = offspring[i].genes[j] + normalDist.Sample();

                        //update gene value only if it is withing the function upper and lower bounds
                        if (this.gene_value <= higher_range && this.gene_value >= lower_range)
                        {
                            offspring[i].genes[j] = this.gene_value;
                        }
                        //offspring[i].genes[j] = offspring[i].genes[j] + normalDist.Sample();
                    }
                }
            }

            return(offspring);
        }//end of method
コード例 #5
0
    public int Next()
    {
        int next;

        do
        {
            next = (int)_dist.Sample();
        } while (next < _min || next > _max);
        return(next);
    }
コード例 #6
0
        public void get_corrupted_height(ref float height_corrupted, float height_ideal)
        {
            MathNet.Numerics.Distributions.Normal distribution = new MathNet.Numerics.Distributions.Normal(0.0, 1.0);

            // add noise and an offset
            height_corrupted = height_ideal + (float)distribution.Sample() * BAROMETER_STANDEV + BAROMETER_OFFSET;

            // remove the offset from the calibration
            height_corrupted -= calibrated_offset;
        }
コード例 #7
0
        public void get_corrupted_MagneticVectorBodyFrame(ref Vector <float> magField_bf_corrupted, Vector <float> attitude_ideal)
        {
            Matrix <float> R = Matrix <float> .Build.Dense(3, 3, 0);

            rotation(ref R, attitude_ideal);

            // from earth to body frame
            magField_bf_corrupted = R.Inverse() * magneticEarthFieldVector;

            // add chip tilt
            rotation(ref R, chip_tilt);
            magField_bf_corrupted = R.Inverse() * (magField_bf_corrupted);

            MathNet.Numerics.Distributions.Normal distribution = new MathNet.Numerics.Distributions.Normal(0.0, 1.0);

            magField_bf_corrupted[0] += (float)distribution.Sample() * MAGNETOMETER_OFFSET_X + MAGNETOMETER_STANDEV_X;
            magField_bf_corrupted[1] += (float)distribution.Sample() * MAGNETOMETER_OFFSET_Y + MAGNETOMETER_STANDEV_Y;
            magField_bf_corrupted[2] += (float)distribution.Sample() * MAGNETOMETER_OFFSET_Z + MAGNETOMETER_STANDEV_Z;
        }
コード例 #8
0
        public void Attack(Character character)
        {
            int    previousHP = character.Health;
            double sample     = rnd.Sample();

            character.TakeDamage((int)(AttackPower * sample));
            Screen.MessageConsole.PrintMessageWithTimeout(
                Name + " dealt " + (previousHP - character.Health) + " damage to " + character.Name,
                TimeoutMessage.SHORT_TIMEOUT);
        }
コード例 #9
0
        public void get_corrupted_angveloc(ref Vector <float> thetadot_bf_corrupted, Vector <float> thetadot_ideal, Vector <float> attitude_ideal)
        {
            // The angular velocities in the earth frame are perfectly known from the differential equation.
            // But the gyroscope returns angular accelerations in the body frame, therefore a transformation is needed.
            // The easiest way is to use the functions for the differential equations.
            thetadot2omega(ref thetadot_bf_corrupted, thetadot_ideal, attitude_ideal);

            // add chip tilt
            thetadot2omega(ref thetadot_bf_corrupted, thetadot_bf_corrupted, chip_tilt);

            MathNet.Numerics.Distributions.Normal distribution = new MathNet.Numerics.Distributions.Normal(0.0, 1.0);

            // add noise and an offset
            thetadot_bf_corrupted[0] += (float)distribution.Sample() * DEG2RAD(GYROSCOPE_STANDEV_R) + DEG2RAD(GYROSCOPE_OFFSET_R);
            thetadot_bf_corrupted[1] += (float)distribution.Sample() * DEG2RAD(GYROSCOPE_STANDEV_P) + DEG2RAD(GYROSCOPE_OFFSET_P);
            thetadot_bf_corrupted[2] += (float)distribution.Sample() * DEG2RAD(GYROSCOPE_STANDEV_Y) + DEG2RAD(GYROSCOPE_OFFSET_Y);

            // remove the offset from the calibration
            thetadot_bf_corrupted -= calibrated_offsets;
        }
コード例 #10
0
        private Tuple <Genome, Genome> Crossover(Genome genome1, Genome genome2)
        {
            MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(0, GASettings.MutStdDev);
            double[] one = new double[genome1.ann.Weights.Length], two = new double[genome2.ann.Weights.Length];
            for (int i = 0; i < one.Length; i++)
            {
                if (Rand.NextDouble() < GASettings.CrossProb)
                {
                    one[i] = genome1.ann.Weights[i];
                    two[i] = genome2.ann.Weights[i];
                }
                else
                {
                    one[i] = genome2.ann.Weights[i];
                    two[i] = genome1.ann.Weights[i];
                }

                if (Rand.NextDouble() < GASettings.MutProb)
                {
                    one[i] += normal.Sample();
                    one[i]  = one[i] > ANNSettings.MaxBoundary ? ANNSettings.MaxBoundary : one[i];
                    one[i]  = one[i] < ANNSettings.MinBoundary ? ANNSettings.MinBoundary : one[i];
                }
                if (Rand.NextDouble() < GASettings.MutProb)
                {
                    two[i] += normal.Sample();
                    two[i]  = two[i] > ANNSettings.MaxBoundary ? ANNSettings.MaxBoundary : two[i];
                    two[i]  = two[i] < ANNSettings.MinBoundary ? ANNSettings.MinBoundary : two[i];
                }
            }
            Genome genome3 = null, genome4 = null;

            Parallel.Invoke(() => {
                genome3 = new Genome(one);
            }, () => {
                genome4 = new Genome(two);
            });
            return(Tuple.Create(genome3, genome4));
        }
コード例 #11
0
ファイル: Animal.cs プロジェクト: Wisetorsk/BioSimCSharp
        public Carnivore(Random rng, Position pos = null, IAnimalParams customParameters = null) : base(rng, pos)
        {
            if (customParameters is null)
            {
                Params = new CarnivoreParams();
            }
            else
            {
                Params = customParameters;
            }
            var norm = new MathNet.Numerics.Distributions.Normal(Params.BirthWeight, Params.BirthSigma);

            Weight = norm.Sample();
        }
コード例 #12
0
ファイル: Neuron.cs プロジェクト: alexfcoding/NeuralLibrary
        public void GenerateWeights(int weightCount, Random randomWeight)
        {
            Weights = new double[weightCount];

            WeightErrorDistribution = new double[weightCount];

            for (int i = 0; i < weightCount; i++)
            {
                double mean   = 0;
                double stdDev = 0.3;
                MathNet.Numerics.Distributions.Normal normalDist = new MathNet.Numerics.Distributions.Normal(mean, stdDev);
                double randomGaussianValue = normalDist.Sample();
                //randomGaussianValue = randomWeight.NextDouble() - 0.5;
                //randomGaussianValue = 1;
                Weights[i] = randomGaussianValue;
                bias       = randomGaussianValue;
            }
        }
コード例 #13
0
        public void SetNextOrderIfNeeded(DateTime currentTime)
        {
            if (NextOrderTime == new DateTime() || NextOrderTime <= currentTime)
            {
                switch (OptionB)
                {
                case EnumTypes.BuyerBOptions.Static:
                    NextOrderTime = currentTime.AddMinutes(this.Minutes);
                    break;

                case EnumTypes.BuyerBOptions.Gauss:
                    MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(this.MeanOptionB, this.DeviationOptionB);
                    NextOrderTime = currentTime.AddMinutes(normal.Sample());
                    break;
                }

                SetNextOrderAmount();
            }
        }
コード例 #14
0
            public Func <double> CreateRandomFunc()
            {
                var random = this.Seed == 0 ? DefaultRandom.Value : new Random(this.Seed);

                switch (this.Distribution)
                {
                case Distribution.Triangular:
                    return(() =>
                    {
                        double p = random.NextDouble();
                        return p < (this.Average - this.Minimum) / (this.Maximum - this.Minimum)
                                           ? this.Minimum
                        + Math.Sqrt(
                            p * (this.Maximum - this.Minimum) * (this.Average - this.Minimum))
                                           : this.Maximum
                        - Math.Sqrt(
                            (1 - p) * (this.Maximum - this.Minimum) * (this.Maximum - this.Average));
                    });

                case Distribution.Normal:
                {
                    var normal = new MathNet.Numerics.Distributions.Normal(
                        this.Average,
                        this.StandardDeviation,
                        random);
                    return(() => normal.Sample());
                }

                case Distribution.LogNormal:
                {
                    var logNormal = new MathNet.Numerics.Distributions.LogNormal(
                        this.Average,
                        this.StandardDeviation,
                        random);
                    return(() => logNormal.Sample());
                }

                case Distribution.Uniform:
                    return(() => random.NextDouble() * (this.Maximum - this.Minimum) + this.Minimum);
                }

                return(() => double.NaN);
            }
コード例 #15
0
        //generate ransdom number based off if gaussian or not
        static double generateRandom(int numMems, Random rnd)
        {
            double random = rnd.Next(0, numMems);

            if (USING_GUASSIAN)
            {
                double stdDev;

                if (numMems > 2)
                {
                    stdDev = numMems / (numMems * 3);
                }
                else
                {
                    stdDev = 0;
                }

                var normalDist = new MathNet.Numerics.Distributions.Normal(random, stdDev);
                random = Math.Abs(normalDist.Sample());
            }
            return(random);
        }
コード例 #16
0
        /// <summary>
        /// Gets a new Decision Vector, based on the PCX logic.
        /// </summary>
        /// <param name="parents">A list of parent <see cref="DecisionVector"/>s.</param>
        /// <returns>A new <see cref="DecisionVector"/>.</returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown if:
        /// - there are less than two parents; or
        /// - the parents have different length or zero length decision vectors; or
        /// - any of the parents have non-continuous Decision Vector elements.
        /// </exception>
        public DecisionVector Operate(params DecisionVector[] parents)
        {
            if (parents.Length < 2)
            {
                throw new ArgumentOutOfRangeException(nameof(parents),
                                                      "There must be at least two parents.");
            }

            // TODO: These calls to .Any() are slow - can we remove the error checking?
            if (parents.Any(p => p.GetContinuousElements().Count == 0))
            {
                throw new ArgumentOutOfRangeException(nameof(parents),
                                                      "Parents must have non-zero length decision vectors.");
            }

            if (parents.Any(p => p.GetContinuousElements().Count != parents.First().Count))
            {
                throw new ArgumentOutOfRangeException(nameof(parents),
                                                      "Parents must have the same length and fully continuous decision vectors.");
            }

            // 1: Pre-process
            var parentDVs = Matrix <double> .Build.DenseOfColumns(parents.Select(dv => dv.Select(d => (double)d)));

            var motherDV = Vector <double> .Build.DenseOfArray(parents.ElementAt(0).Select(d => (double)d).ToArray());

            // 1a: centroid of all parents
            var centroid = parentDVs.RowSums().Divide(parents.Count());

            // 1b: vector distance from centroid to mother (following Deb's C code, not paper)
            var motherCentroidVectorDistance   = centroid - motherDV;
            var motherCentroidAbsoluteDistance = motherCentroidVectorDistance.L2Norm();

            if (motherCentroidAbsoluteDistance < 1e-20)
            {
                return(DecisionVector.CreateForEmpty());
            }

            // 1c: vector distance from other parents to mother
            var otherParentDVs = parentDVs.RemoveColumn(0);
            var parentMotherVectorDistances = otherParentDVs.EnumerateColumns()
                                              .Select(v => v - motherDV).ToArray();
            var parentMotherAbsoluteDistances = parentMotherVectorDistances.Select(v => v.L2Norm()).ToArray();

            if (parentMotherAbsoluteDistances.Any(d => d < 1e-20))
            {
                return(DecisionVector.CreateForEmpty());
            }

            // 1d: perpendicular distances from other parents to centroid-mother vector
            var orthogonalDistances = parentMotherVectorDistances
                                      .Select((v, i) => parentMotherAbsoluteDistances.ElementAt(i) *
                                              Math.Sqrt(1.0 - Math.Pow(
                                                            v.DotProduct(motherCentroidVectorDistance) /
                                                            (parentMotherAbsoluteDistances.ElementAt(i) * motherCentroidAbsoluteDistance),
                                                            2.0)));
            var meanOrthogonalDistance = orthogonalDistances.Mean();

            // 2: Now create a new individual
            var normRnd    = new MathNet.Numerics.Distributions.Normal(rngManager.Rng);
            var samplesEta = new double[motherDV.Count];

            normRnd.Samples(samplesEta);

            var newRandomDv = Vector <double> .Build.DenseOfArray(samplesEta)
                              .Multiply(sigmaEta * meanOrthogonalDistance);

            //Remove component of randomness in direction of ?
            var offset1 = motherCentroidVectorDistance
                          .Multiply(newRandomDv.DotProduct(motherCentroidVectorDistance))
                          .Divide(Math.Pow(motherCentroidAbsoluteDistance, 2.0));

            newRandomDv -= offset1;

            var offset2 = motherCentroidVectorDistance
                          .Multiply(sigmaZeta * normRnd.Sample());

            newRandomDv += offset2;

            // Modification of Deb2002 which should maintain stability.
            var finalDv = motherDV +
                          newRandomDv.Divide(Math.Sqrt(motherDV.Count));

            return(DecisionVector.CreateFromArray(parents.First().GetDecisionSpace(), finalDv.ToArray()));
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: mszanetti/NETGen
        static void Main(string[] args)
        {
            double bias;
            try{
                    // The neighbor selection bias is given as command line argument
                    bias1 = double.Parse(args[0]);
                    bias2 = double.Parse(args[1]);
            }
            catch(Exception)
            {
                Console.WriteLine("Usage: mono ./DemoSimulation.exe [initial_bias] [secondary_bias]");
                return;
            }

            // The number of clusters (c) and the nodes within a cluster (Nc)
            int c = 20;
            int Nc = 20;

            // The number of desired edges
            int m = 6 * c * Nc;

            // In order to yield a connected network, at least ...
            double inter_thresh = 3d * ((c * Math.Log(c)) / 2d);
                // ... edges between communities are required

            // So the maximum number of edges within communities we s create is ...
            double intra_edges = m - inter_thresh;

            Console.WriteLine("Number of intra_edge pairs = " + c * Combinatorics.Combinations(Nc, 2));
            Console.WriteLine("Number of inter_edge pairs = " + (Combinatorics.Combinations(c * Nc, 2) - (c * Combinatorics.Combinations(Nc, 2))));

            // Calculate the p_i necessary to yield the desired number of intra_edges
            double pi =  intra_edges / (c * Combinatorics.Combinations(Nc, 2));

            // From this we can compute p_e ...
            double p_e = (m - c * MathNet.Numerics.Combinatorics.Combinations(Nc, 2) * pi) / (Combinatorics.Combinations(c * Nc, 2) - c * MathNet.Numerics.Combinatorics.Combinations(Nc, 2));
            Console.WriteLine("Generating cluster network with p_i = {0:0.0000}, p_e = {1:0.0000}", pi, p_e);

            // Create the network ...
            network = new NETGen.NetworkModels.Cluster.ClusterNetwork(c, Nc, pi, p_e);

            // ... and reduce it to the GCC
            network.ReduceToLargestConnectedComponent();

            Console.WriteLine("Created network has {0} vertices and {1} edges. Modularity = {2:0.00}", network.VertexCount, network.EdgeCount, network.NewmanModularity);

            // Run the OopenGL visualization
            NetworkColorizer colorizer = new NetworkColorizer();
            NetworkVisualizer.Start(network, new FruchtermanReingoldLayout(15), colorizer);

            currentBias = bias1;

            // Setup the synchronization simulation, passing the bias strategy as a lambda expression
            sync = new EpidemicSynchronization(
                network,
                colorizer,
                v => {
                    Vertex neighbor = v.RandomNeighbor;
                    double r = network.NextRandomDouble();

                    // classify neighbors
                    List<Vertex> intraNeighbors = new List<Vertex>();
                    List<Vertex> interNeighbors = new List<Vertex>();
                    ClassifyNeighbors(network, v, intraNeighbors, interNeighbors);

                    neighbor = intraNeighbors.ElementAt(network.NextRandom(intraNeighbors.Count));

                    // biasing strategy ...
                    if (r <= currentBias && interNeighbors.Count > 0)
                        neighbor = interNeighbors.ElementAt(network.NextRandom(interNeighbors.Count));

                    return neighbor;
                },
                0.9d);

            Dictionary<int, double> _groupMus = new Dictionary<int, double>();
            Dictionary<int, double> _groupSigmas = new Dictionary<int, double>();

            MathNet.Numerics.Distributions.Normal avgs_normal = new MathNet.Numerics.Distributions.Normal(300d, 50d);
            MathNet.Numerics.Distributions.Normal devs_normal = new MathNet.Numerics.Distributions.Normal(20d, 5d);

            for(int i=0; i<c; i++)
            {
                double groupAvg = avgs_normal.Sample();
                double groupStdDev = devs_normal.Sample();

                foreach(Vertex v in network.GetNodesInCluster(i))
                {
                    sync._MuPeriods[v] = groupAvg;
                    sync._SigmaPeriods[v] = groupStdDev;
                }
            }

            sync.OnStep+=new EpidemicSynchronization.StepHandler(collectLocalOrder);

            // Run the simulation synchronously
            sync.Run();

            Console.ReadKey();

            // Collect and print the results
            SyncResults res = sync.Collect();
               	Console.WriteLine("Order {0:0.00} reached after {1} rounds", res.order, res.time);
        }
コード例 #18
0
ファイル: MathUtility.cs プロジェクト: azabrod1/BoxingGame
 public static double Gauss2(double μ = 0.5, double σ = 0.5)
 {
     MathNet.Numerics.Distributions.Normal normalDist = new MathNet.Numerics.Distributions.Normal(0.5, 3);
     return(normalDist.Sample());
 }
コード例 #19
0
 public override dynamic getRandom()
 {
     // Implementation Uses C#MathNet.Numerics Normal Distribution Sampling
     return(normal.Sample());
 }
コード例 #20
0
ファイル: Program.cs プロジェクト: mszanetti/NETGen
        private static AggregationResult RunAggregation(ClusterNetwork net, double bias)
        {
            Dictionary<Vertex, double> _attributes = new Dictionary<Vertex, double>();
            Dictionary<Vertex, double> _aggregates = new Dictionary<Vertex, double>();

            MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(0d, 5d);

            AggregationResult result = new AggregationResult();

            result.Modularity = net.NewmanModularity;

            double average = 0d;

            foreach (Vertex v in net.Vertices)
            {
                _attributes[v] = normal.Sample();
                _aggregates[v] = _attributes[v];
                average += _attributes[v];
            }
            average /= (double)net.VertexCount;

            double avgEstimate = double.MaxValue;

            result.FinalVariance = double.MaxValue;
            result.FinalOffset = 0d;

            for (int k = 0; k < Properties.Settings.Default.ConsensusRounds; k++)
            {
                foreach (Vertex v in net.Vertices.ToArray())
                {
                    Vertex w = v.RandomNeighbor;
                    List<Vertex> intraNeighbors = new List<Vertex>();
                    List<Vertex> interNeighbors = new List<Vertex>();
                    ClassifyNeighbors(net, v, intraNeighbors, interNeighbors);

                    double r = net.NextRandomDouble();
                    if (r <= bias && interNeighbors.Count > 0)
                        w = interNeighbors.ElementAt(net.NextRandom(interNeighbors.Count));

                    _aggregates[v] = aggregate(_aggregates[v], _aggregates[w]);
                    _aggregates[w] = aggregate(_aggregates[v], _aggregates[w]);
                }

                avgEstimate = 0d;
                foreach (Vertex v in net.Vertices.ToArray())
                    avgEstimate += _aggregates[v];
                avgEstimate /= (double)net.VertexCount;

                result.FinalVariance = 0d;
                foreach (Vertex v in net.Vertices.ToArray())
                    result.FinalVariance += Math.Pow(_aggregates[v] - avgEstimate, 2d);
                result.FinalVariance /= (double)net.VertexCount;

                double intraVar = 0d;
                foreach (int c in net.ClusterIDs)
                {
                    double localavg = 0d;
                    double localvar = 0d;

                    foreach (Vertex v in net.GetNodesInCluster(c))
                        localavg += _aggregates[v];
                    localavg /= net.GetClusterSize(c);

                    foreach (Vertex v in net.GetNodesInCluster(c))
                        localvar += Math.Pow(_aggregates[v] - localavg, 2d);
                    localvar /= net.GetClusterSize(c);

                    intraVar += localvar;
                }
                intraVar /= 50d;

                //Console.WriteLine("i = {0:0000}, Avg = {1:0.000}, Estimate = {2:0.000}, Intra-Var = {3:0.000}, Total Var = {4:0.000}", result.iterations, average, avgEstimate, intraVar, totalVar);
            }
            result.FinalOffset = average - avgEstimate;

            return result;
        }
コード例 #21
0
 public override dynamic GetRandom()
 {
     return(normal.Sample());
 }
コード例 #22
0
ファイル: AnalysisClass.cs プロジェクト: Tarahtelka/-
        public static double[] generateValues(string typeScale, string typeDistr, int size)
        {
            List <double> sample = new List <double>(size);

            if (typeScale.Equals("дихотомическая"))
            {
                for (int i = 0; i < size; i++)
                {
                    sample.Add(rnd.Next(2));
                }
            }
            else if (typeScale.Equals("ранговая"))
            {
                if (typeDistr.Equals("нормальное"))
                {
                    //MathNet.Numerics.Distributions.Normal nDistr = new MathNet.Numerics.Distributions.Normal(0, 5);
                    rnd.Next(7);
                    List <double> smp = new List <double>(size);

                    for (int i = 0; i < size; i++)
                    {
                        smp.Add(rnd.Next(7));
                    }

                    MathNet.Numerics.Distributions.Normal nDistr = new MathNet.Numerics.Distributions.Normal(0, 1);

                    for (int i = 0; i < size; i++)
                    {
                        sample.Add(Math.Ceiling(nDistr.Sample()));
                    }
                }
                else
                {
                    for (int i = 0; i < size; i++)
                    {
                        sample.Add(rnd.Next(7));
                    }
                }
            }
            else if (typeScale.Equals("количественная"))
            {
                if (typeDistr.Equals("нормальное"))
                {
                    MathNet.Numerics.Distributions.Normal nDistr = new MathNet.Numerics.Distributions.Normal(0, 2);
                    double[] arr = new double[size];
                    for (int i = 0; i < size; i++)
                    {
                        MathNet.Numerics.Distributions.Normal.Samples(arr, 0, 1);
                        sample = arr.ToList();
                    }
                }
                else
                {
                    for (int i = 0; i < size; i++)
                    {
                        sample.Add(rnd.NextDouble() * 10);
                    }
                }
            }
            return(sample.ToArray());
        }