Beispiel #1
0
        //levy flight - refer to url: https://www.mathworks.com/matlabcentral/fileexchange/45112-flower-pollination-algorithm/content/fpa_demo.m
        public double[] LevyFlight(int subsetSize)
        {
            //levy exponent and coefficient. For more details see Chapter 11 of the following book:
            // Xin-She Yang, Nature-Inspired Optimization Algorithms, Elsevier, (2014).

            double beta  = 3 / 2;
            double A     = Gamma(1 + beta);
            double B     = Math.Sin(Math.PI * beta / 2);
            double C     = Gamma((1 + beta) / 2);
            double D     = (beta - 1) / 2;
            double E     = beta * Math.Pow(2, D);
            double F     = 1 / beta;
            double sigma = Math.Pow((A * B / (C * E)), F);

            double G, H, I, step;

            double[] levyF = new double[subsetSize];

            for (int i = 0; i < subsetSize; i++)
            {
                double randNum = SimpleRNG.GetNormal();//generate random number with normal distribution
                G        = sigma * randNum;
                H        = SimpleRNG.GetNormal();
                I        = Math.Abs(H);
                step     = G / Math.Pow(I, F);
                levyF[i] = 0.01 * step;
            }

            return(levyF);
        }
    void DoShoot(Weapon _weapon, GameObject _projectile)
    {
        var _deltaPos = Vector2.zero;

        if (!Mathf.Approximately(positionDeviation.x, 0))
        {
            _deltaPos.x = (float)SimpleRNG.GetNormal(0, positionDeviation.x);
        }

        if (!Mathf.Approximately(positionDeviation.y, 0))
        {
            _deltaPos.y = (float)SimpleRNG.GetNormal(0, positionDeviation.y);
        }

        _projectile.transform.Translate(_deltaPos);


        if (!Mathf.Approximately(directionDeviation, 0))
        {
            var _delta    = (float)SimpleRNG.GetNormal(0, directionDeviation);
            var _rotation = Quaternion.AngleAxis(_delta, Vector3.forward);
            var _velocity = _projectile.rigidbody2D.velocity;
            _velocity = _rotation * _velocity;
            _projectile.rigidbody2D.velocity = _velocity;
        }
    }
Beispiel #3
0
            public void RealCrossover(ref ScheduleGenome p2, ref ScheduleGenome o1)
            {
                switch (realCrossover)
                {
                case RealCrossoverOp.MeanWithNoise:
                    // Mean-with-noise Crossover:
                    for (int i = 0; i < _modesLength; i++)
                    {
                        double mean = TimeGenes[i] + p2.TimeGenes[i];
                        mean            = mean / 2.0;
                        o1.TimeGenes[i] = SimpleRNG.GetNormal(mean, 0.5);
                        if (o1.TimeGenes[i] < 0.0)
                        {
                            o1.TimeGenes[i] = 0.0;
                        }
                    }
                    break;

                case RealCrossoverOp.Uniform:
                    // Uniform Crossover:
                    int cutpoint = SimpleRNG.Next(0, _modesLength + 1);
                    for (int i = 0; i < cutpoint; i++)
                    {
                        o1.TimeGenes[i] = TimeGenes[i];
                    }
                    for (int i = cutpoint; i < _modesLength; i++)
                    {
                        o1.TimeGenes[i] = p2.TimeGenes[i];
                    }
                    break;
                }
            }
Beispiel #4
0
 public void Mutate()
 {
     for (int i = 0; i < _jobsLength; i++)
     {
         if (SimpleRNG.GetUniform() < _mutationRate)
         {
             int r    = SimpleRNG.Next(0, _jobsLength);
             int temp = JobGenes[i];
             JobGenes[i] = JobGenes[r];
             JobGenes[r] = temp;
             // Mutate the delay time
             r = SimpleRNG.Next(0, _modesLength);
             double mutatedDelay = 0;
             //mutatedDelay = SimpleRNG.GetExponential(_delayMean);
             mutatedDelay = SimpleRNG.GetNormal(TimeGenes[r], 1.0);
             //mutatedDelay = _rand.NextDouble() * _delayMean;
             if (mutatedDelay < 0.0)
             {
                 mutatedDelay = 0.0;
             }
             TimeGenes[r] = mutatedDelay;
         }
     }
     //Mutate the Mode vector:
     for (int i = 0; i < _modesLength; i++)
     {
         if (SimpleRNG.GetUniform() < _mutationRate)
         {
             ModeGenes[i] = SimpleRNG.Next(0, _numberOfModes);
         }
     }
 }
Beispiel #5
0
        public static void RandomizeResult(ref Game game)
        {
            //SimpleRNG.SetSeedFromSystemTime();
            var blackFavor      = (game.BlackPlayer.Rating - game.WhitePlayer.Rating) / 40;
            var simulatedResult = SimpleRNG.GetNormal(32, 7) + blackFavor;

            game.BlackResult = MakeProperResult(simulatedResult);
            game.WhiteResult = 64 - game.BlackResult;
        }
        private List <int> ShortenOperator(List <int> mutatedValues, int segmentPosition)
        {
            int prolongLength = (int)Math.Ceiling(Math.Abs(SimpleRNG.GetNormal())) + 1;
            int sign          = mutatedValues[segmentPosition] / Math.Abs(mutatedValues[segmentPosition]);

            // Operator can be applied with length less or equal to difference between
            // maximum length of segment and longest segment
            if (sign < 0)
            {
                int minimum = mutatedValues.Min();
                if (prolongLength > Math.Abs(-39 - minimum))
                {
                    prolongLength = Math.Abs(-39 - minimum);
                }
            }
            else
            {
                int maximum = mutatedValues.Max();
                if (prolongLength > 29 - maximum)
                {
                    prolongLength = 29 - maximum;
                }
            }
            if (prolongLength == 0)
            {
                return(mutatedValues);
            }

            // Maximum allowed value for shortening operator is the length of the segment
            if (prolongLength > Math.Abs(mutatedValues[segmentPosition]))
            {
                prolongLength = Math.Abs(mutatedValues[segmentPosition]);
            }

            mutatedValues[segmentPosition] = sign * (Math.Abs(mutatedValues[segmentPosition]) - prolongLength);
            if (mutatedValues[segmentPosition] == 0)
            {
                if (segmentPosition == 0 || segmentPosition == mutatedValues.Count - 1)
                {
                    mutatedValues.RemoveAt(segmentPosition);
                    segmentPosition = -1;
                }
                else
                {
                    mutatedValues[segmentPosition - 1] += mutatedValues[segmentPosition + 1];
                    mutatedValues.RemoveRange(segmentPosition, 2);
                    segmentPosition = -1;
                }
            }

            int randomParallelSegmentIndex = FindRandomParalellSegment(mutatedValues, segmentPosition, sign > 0);

            mutatedValues[randomParallelSegmentIndex] = sign * (Math.Abs(mutatedValues[randomParallelSegmentIndex]) + prolongLength);

            return(mutatedValues);
        }
Beispiel #7
0
        public override Vector3 ReadSensor()
        {
            float   distanceMod = System.Convert.ToSingle(SimpleRNG.GetNormal(DEFAULT_MEAN, standardDeviation));
            float   angleMod    = Random.Range(MIN_GEN_ANGLE, MAX_GEN_ANGLE);
            Vector3 modificator = CoordinatesConverter.PolarToCartesian(distanceMod, angleMod);
            Vector3 result      = transform.position + modificator;

            UpdateMarker(result);
            recorder.SetData(transform.position.x.ToString(), REC_X_TAG);
            recorder.SetData(transform.position.z.ToString(), REC_Z_TAG);
            return(result);
        }
        public void TestStandardDeviationForGame()
        {
            const int numSamples = 100000;
            var       rs         = new RunningStat();

            rs.Clear();
            var mean  = 32;
            var stdev = 7;

            for (int i = 0; i < numSamples; ++i)
            {
                rs.Push(SimpleRNG.GetNormal(mean, stdev));
            }
            PrintStatisticResults("normal", mean, stdev * stdev, rs.Mean(), rs.Variance(), rs.resultlist.Min(), rs.resultlist.Max());
            PrintGameResultStats(rs);
        }
Beispiel #9
0
        void    Reset()
        {
            m_StepCount = 0;

            int CellsCount = (int)Math.Sqrt(PARTICLES_COUNT);

            for (int i = 0; i < PARTICLES_COUNT; i++)
            {
                int CellY = (i / CellsCount) - CellsCount / 2;
                int CellX = (i % CellsCount) - CellsCount / 2;

//				Point2D	Pos = new Point2D( SIMULATION_SPACE_SIZE * (float) SimpleRNG.GetNormal(), SIMULATION_SPACE_SIZE * (float) SimpleRNG.GetNormal() );
                Point2D Pos = new Point2D(40.0f * (CellX + (float)SimpleRNG.GetNormal()), 40.0f * (CellY + (float)SimpleRNG.GetNormal()));

                m_Particles[0][i].P    = m_Particles[1][i].P = Pos;
                m_Particles[0][i].Size = m_Particles[1][i].Size = 0;
            }
        }
Beispiel #10
0
        public void InitializeWeightsAndBiases()
        {
            SimpleRNG.SetSeedFromSystemTime();

            for (int layer = 0; layer < neuralNetAccessor.NumberOfLayers; layer++)
            {
                for (int node = 0; node < neuralNetAccessor.NodesInLayer(layer); node++)
                {
                    var sigmoid = neuralNetAccessor.GetSigmoid(layer, node);
                    sigmoid.Bias = (float)SimpleRNG.GetNormal(0, 1);
                    float standardDeviation = 1.0f / Mathf.Sqrt(sigmoid.Weights.Length);
                    for (int i = 0; i < sigmoid.Weights.Length; i++)
                    {
                        sigmoid.Weights[i] = (float)SimpleRNG.GetNormal(0, standardDeviation);
                    }
                }
            }
        }
        private Individual MutateIndividual(Individual individual)
        {
            int mutationEffect = random.Next(0, 2);

            if (mutationEffect == 0)
            {
                double value = random.NextDouble();
                for (int i = 0; i < individual.References.Count; i++)
                {
                    double chance = random.NextDouble();

                    if (chance < value)
                    {
                        int xChange = (int)(SimpleRNG.GetNormal());
                        int yChange = (int)(SimpleRNG.GetNormal());
                        int xSign   = Math.Sign(SimpleRNG.GetNormal());
                        int ySign   = Math.Sign(SimpleRNG.GetNormal());

                        individual.References[i].X += xSign * xChange;
                        individual.References[i].Y += ySign * yChange;
                    }
                }
            }
            else
            {
                double value = random.NextDouble();
                for (int i = 0; i < individual.References.Count; i++)
                {
                    double chance = random.NextDouble();
                    if (chance < value)
                    {
                        int randX = random.Next(1, 33);
                        int randY = random.Next(6, 28);

                        individual.References[i].X = randX;
                        individual.References[i].Y = randY;
                    }
                }
            }

            return(individual);
        }
Beispiel #12
0
        public Action StartSparkline(IEnumerable <AddTimeValue> addTimeValues)
        {
            Func <int> tickTime = () => {
                // Convert.ToInt32(Math.Floor(SimpleRNG.GetUniform()*2000));
                return(1000 / 2);
            };

            Func <AddTimeValue, Action> tickGenerator = addTimeValue => {
                var x = 100.0;
                return(() => {
                    while (true)
                    {
                        var newx = x + SimpleRNG.GetNormal() * 2;
                        if (newx < 0.0)
                        {
                            newx = 0.0;
                        }
                        _dispatcher.BeginInvoke((Action)(() => {
                            var guid = addTimeValue(newx);
                            if (SimpleRNG.GetUniform() > 0.75)
                            {
                                ShowFlag(guid, newx);
                            }
                        }));
                        x = newx;
                        Thread.Sleep(tickTime());
                    }
                });
            };

            Func <Action, WaitCallback> toWaitCallback = gen => wc => gen();
            Action start = () => {
                var tickGenerators = addTimeValues.Select(tickGenerator).ToArray();
                foreach (var generateTicks in tickGenerators)
                {
                    ThreadPool.QueueUserWorkItem(toWaitCallback(generateTicks));
                }
            };

            return(start);
        }
Beispiel #13
0
        public Form1()
        {
            InitializeComponent();

            for (int x = 0; x <= 100; x++)
            {
                float  sigma     = Math.Max(1e-4f, GRAPH_WIDTH * x / 100);
                double avgNormal = 0.0f;
                for (int i = 0; i < 10000; i++)
                {
                    double rnd = SimpleRNG.GetNormal(0, sigma);

                    rnd = rnd % Math.PI;                                                // Simple wrapping (https://en.wikipedia.org/wiki/Wrapped_distribution)
//					rnd = rnd % (2.0*Math.PI);			// Simple wrapping (https://en.wikipedia.org/wiki/Wrapped_distribution)
                    avgNormal += Math.Cos(rnd);
                }
                avgNormal /= 10000;
                m_distribution.Add(new float2(sigma, (float)avgNormal));
            }
            panelOutput.UpdateBitmap();
        }
Beispiel #14
0
        private void InitialiseGraph()
        {
            float[] position  = new float[this.input_dim];
            float[] position2 = new float[this.input_dim];

            SimpleRNG r  = new SimpleRNG();
            double    r1 = SimpleRNG.GetNormal();
            double    r2 = SimpleRNG.GetNormal();

            double r3 = SimpleRNG.GetNormal();
            double r4 = SimpleRNG.GetNormal();

            position[0] = (float)r1;
            position[1] = (float)r2;

            position2[0] = (float)r3;
            position2[1] = (float)r4;

            this.graph.AddNode(position, tlen);
            this.graph.AddNode(position2, tlen);
        }
Beispiel #15
0
        private void panelOutputNormalDistribution_BitmapUpdating(int W, int H, Graphics G)
        {
            G.FillRectangle(Brushes.White, 0, 0, W, H);

            int[] Buckets = new int[128];
            int   Peak    = 0;

            for (int i = 0; i < 10000; i++)
            {
                float Random = (float)SimpleRNG.GetNormal(0.0, 4.0);

                int BucketIndex = (int)(64 * (1.0f + 0.05f * Random));
                BucketIndex = Math.Max(0, Math.Min(127, BucketIndex));
                Buckets[BucketIndex]++;
                Peak = Math.Max(Peak, Buckets[BucketIndex]);
            }

            for (int i = 0; i < 128; i++)
            {
                float h = H * Buckets[i] / (1.1f * Peak);
                G.FillRectangle(Brushes.Black, W * (i + 0) / 128.0f, H - h - 1, W / 128.0f, h);
            }
        }
Beispiel #16
0
        public Problem Bat(Problem prob)
        {
            //default parameters
            int    populationSize = 5; //number of bats in the population
            int    maxGeneration  = 100;
            int    subsetSize     = 200;
            double loudness       = 0.5;
            double pulseRate      = 0.5;
            int    totalInstances = prob.X.Count(); //problem size
            double frequencyMin   = 0;              //minimum frequency. Frequency range determine the scalings
            double frequencyMax   = 2;              //maximum frequency.
            int    lowerBound     = -2;             //set lower bound - lower boundary
            int    upperBound     = 2;              //set upper bound - upper boundary

            double[] batFitnessVal                = new double[populationSize];
            double[] newbatFitnessVal             = new double[populationSize];
            double   globalBest                   = double.MinValue;
            ObjectInstanceSelection globalBestBat = null;
            Random r = new Random();

            //initialize population
            List <ObjectInstanceSelection> bats    = InitializeBat(populationSize, subsetSize, totalInstances, prob);
            List <ObjectInstanceSelection> newBats = new List <ObjectInstanceSelection>(bats.Count); //create a clone of bats

            bats.ForEach((item) =>
            {
                newBats.Add(new ObjectInstanceSelection(item.__Attribute_Values, item.__Attribute_Values_Continuous, item.__Frequency, item.__Velocity, item.__Pointers, item.__Fitness)); //create a clone of flowers
            });

            batFitnessVal    = fi.EvaluateObjectiveFunction(bats, prob);                                                           //evaluate fitness value for all the bats
            newbatFitnessVal = fi.EvaluateObjectiveFunction(newBats, prob);                                                        //evaluate fitness value for new bats. Note: this will be the same for this function call, since pollination has not occur
            BatFitness(batFitnessVal, bats);                                                                                       //fitness value for each bats
            BatFitness(newbatFitnessVal, newBats);                                                                                 //fitness value for new bats
            globalBestBat = EvaluateSolution(batFitnessVal, newbatFitnessVal, globalBest, bats, newBats, globalBestBat, loudness); //get the global best flower
            globalBest    = globalBestBat.__Fitness;

            //start bat algorithm
            double rand = r.NextDouble(); //generate random number

            for (int i = 0; i < maxGeneration; i++)
            {
                //loop over all bats or solutions
                for (int j = 0; j < populationSize; j++)
                {
                    bats[j].__Frequency = frequencyMin + (frequencyMin - frequencyMax) * rand; //adjust frequency
                    for (int k = 0; k < subsetSize; k++)
                    {
                        double randNum = SimpleRNG.GetNormal();                                                                                                                             //generate random number with normal distribution
                        newBats[j].__Velocity[k] = bats[j].__Velocity[k] + (bats[j].__Attribute_Values_Continuous[k] - globalBestBat.Attribute_Values_Continuous[k]) * bats[j].__Frequency; //update velocity
                        newBats[j].__Attribute_Values_Continuous[k] = bats[j].__Attribute_Values_Continuous[k] + bats[j].__Velocity[k];                                                     //update bat position in continuous space
                        newBats[j].__Attribute_Values_Continuous[k] = SimpleBounds(newBats[j].__Attribute_Values_Continuous[k], lowerBound, upperBound);                                    //ensure that value does not go beyond defined boundary

                        if (rand > pulseRate)                                                                                                                                               //The factor 0.001 limits the step sizes of random walks
                        {
                            newBats[j].__Attribute_Values_Continuous[k] = globalBestBat.Attribute_Values_Continuous[k] + 0.001 * randNum;
                        }

                        newBats[j].__Attribute_Values[k] = fi.Binarize(newBats[j].__Attribute_Values_Continuous[k], r.NextDouble()); //convert to binary
                    }
                }

                //evaluate new solution
                newbatFitnessVal = fi.EvaluateObjectiveFunction(newBats, prob);                                                        //evaluate fitness value for all the bats
                BatFitness(newbatFitnessVal, newBats);                                                                                 //fitness value for new bats
                globalBestBat = EvaluateSolution(batFitnessVal, newbatFitnessVal, globalBest, bats, newBats, globalBestBat, loudness); //get the global best flower
                globalBest    = globalBestBat.__Fitness;
            }

            //ensure that at least, 40 instances is selected for classification
            int countSelected = globalBestBat.__Attribute_Values.Count(q => q == 1); //count the total number of selected instances
            int diff, c = 0, d = 0;
            int Min = 40;                                                            //minimum number of selected instances

            if (countSelected < Min)
            {
                //if there are less than N, add N instances, where N = the number of selected instances
                diff = Min - countSelected;
                while (c < diff)
                {
                    if (globalBestBat.__Attribute_Values[d++] == 1)
                    {
                        continue;
                    }
                    else
                    {
                        globalBestBat.__Attribute_Values[d++] = 1;
                        c++;
                    }
                }
            }

            Problem subBest = fi.buildModel(globalBestBat, prob); //build model for the best Instance Mast

            return(subBest);
        }
Beispiel #17
0
        //Binary Bat
        public Problem BinaryBat(Problem prob, out double storagePercentage)
        {
            //default parameters
            int    populationSize = 3; //number of bats in the population
            int    subsetSize     = 100;
            int    maxGeneration  = 3;
            double loudness       = 0.5;
            double pulseRate      = 0.5;
            int    totalInstances = prob.X.Count(); //problem size
            double frequencyMin   = 0;              //minimum frequency. Frequency range determine the scalings
            double frequencyMax   = 2;              //maximum frequency.
            int    lowerBound     = -2;             //set lower bound - lower boundary
            int    upperBound     = 2;              //set upper bound - upper boundary

            double[] batFitnessVal                = new double[populationSize];
            double[] newbatFitnessVal             = new double[populationSize];
            double   globalBest                   = double.MinValue;
            ObjectInstanceSelection globalBestBat = null;
            Random r = new Random();
            FlowerPollinationAlgorithm fpa = new FlowerPollinationAlgorithm();

            //initialize population
            List <ObjectInstanceSelection> bats    = InitializeBinaryBat(populationSize, subsetSize, totalInstances, prob);
            List <ObjectInstanceSelection> newBats = new List <ObjectInstanceSelection>(bats.Count); //create a clone of bats

            bats.ForEach((item) =>
            {
                newBats.Add(new ObjectInstanceSelection(item.Attribute_Values, item.Attribute_Values_Continuous, item.Frequency, item.Velocity, item.Pointers, item.Fitness)); //create a clone of flowers
            });

            batFitnessVal    = EvaluateObjectiveFunction(bats, prob);                                                              //evaluate fitness value for all the bats
            newbatFitnessVal = EvaluateObjectiveFunction(newBats, prob);                                                           //evaluate fitness value for new bats. Note: this will be the same for this function call, since pollination has not occur
            BatFitness(batFitnessVal, bats);                                                                                       //fitness value for each bats
            BatFitness(newbatFitnessVal, newBats);                                                                                 //fitness value for new bats
            globalBestBat = EvaluateSolution(batFitnessVal, newbatFitnessVal, globalBest, bats, newBats, globalBestBat, loudness); //get the global best flower
            globalBest    = globalBestBat.Fitness;

            //start bat algorithm
            double rand = r.NextDouble(); //generate random number

            for (int i = 0; i < maxGeneration; i++)
            {
                //loop over all bats or solutions
                for (int j = 0; j < populationSize; j++)
                {
                    for (int k = 0; k < subsetSize; k++)
                    {
                        bats[j].Frequency = frequencyMin + (frequencyMin - frequencyMax) * r.NextDouble();                                                       //Adjust frequency
                        double randNum = SimpleRNG.GetNormal();                                                                                                  //generate random number with normal distribution
                        newBats[j].Velocity[k] = newBats[j].Velocity[k] + (bats[j].Attribute_Values[k] - globalBestBat.Attribute_Values[k]) * bats[j].Frequency; //update velocity
                        //newBats[j].Attribute_Values[k] = fpa.ConvertToBinary(newBats[j].Velocity[k], newBats[j].Attribute_Values[k]); //update bat position in the binary space
                        newBats[j].Attribute_Values[k] = TransferFunction(newBats[j].Velocity[k], newBats[j].Attribute_Values[k]);                               //update bat position in the binary space

                        if (rand > pulseRate)
                        {
                            newBats[j].Attribute_Values[k] = globalBestBat.Attribute_Values[k]; //change some of the dimensions of the position vector with some dimension of global best. Refer to reference for more explaination
                        }
                    }
                }

                //Select best solutions from the original population and matured population for the next generation;
                fpa.SelectBestSolution(bats, newBats);

                //evaluate new solution
                newbatFitnessVal = EvaluateObjectiveFunction(newBats, prob);                                                           //evaluate fitness value for all the bats
                BatFitness(newbatFitnessVal, newBats);                                                                                 //fitness value for new bats
                globalBestBat = EvaluateSolution(batFitnessVal, newbatFitnessVal, globalBest, bats, newBats, globalBestBat, loudness); //get the global best flower
                globalBest    = globalBestBat.Fitness;

                //if solution has converged to a optimal user-defined point, stop search
                int Max = 60;          // maximum percentage reduction
                if (globalBest >= Max) //if the percentage reduction has approached 60%, stop search!
                {
                    break;
                }
            }

            //ensure that at least, N instances are selected for classification
            int min = 15; //minimum number of selected instances

            globalBestBat = fpa.AddInstances(globalBestBat, min);

            Problem subBest = fi.buildModelMultiClass(globalBestBat, prob); //build model for the best Instance Mast

            storagePercentage = Training.StoragePercentage(subBest, prob);  //calculate the percent of the original training set was retained by the reduction algorithm
            return(subBest);
        }
Beispiel #18
0
        private void Button1_Click(object sender, EventArgs e)
        {
            Random rand = new Random();

            if (type < 2)
            {
                double Q1 = 0, Q2 = 0, Q3 = 0, N = 0;
                try
                {
                    Q1 = Convert.ToDouble(Q1textBox.Text);
                    Q2 = Convert.ToDouble(Q2textBox.Text);
                    Q3 = Convert.ToDouble(Q3textBox.Text);
                    N  = Convert.ToDouble(NtextBox.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Невірні дані\n" + ex.Message, "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (type == 0)
                {
                    if (comboBox1.Text == Distributions.Normal)
                    {
                        for (int i = 0; i < N; i++)
                        {
                            RezDat.Add(SimpleRNG.GetNormal(Q1, Q2));
                        }
                    }
                    else if (comboBox1.Text == Distributions.Exp)
                    {
                        for (int i = 0; i < N; i++)
                        {
                            RezDat.Add(Math.Log(1.0 / (1 - rand.NextDouble())) / Q1);
                        }
                    }
                    else if (comboBox1.Text == Distributions.Line)
                    {
                        for (int i = 0; i < N; i++)
                        {
                            RezDat.Add((rand.NextDouble() * (Q2 - Q1) + Q1));
                        }
                    }
                }
                else if (type == 1)
                {
                    for (int i = 0; i < FirstData.Length; i++)
                    {
                        double dat = RegresType.Model(FirstData[i], new double[] { Q1, Q2, Q3 }, comboBox1.Text);
                        double eps = SimpleRNG.GetNormal(0, N);
                        if (double.IsInfinity(dat) || double.IsNaN(dat))
                        {
                            MessageBox.Show("Неможливо створити даний тип регресії\n", "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            RezDat.Clear();
                            return;
                        }
                        dat = dat + eps;
                        RezDat.Add(dat);
                    }
                }
            }
            else if (type == 2)
            {
                double   A0 = 0, N = 0;
                double[] A = new double[ISA.Count];
                try
                {
                    N  = Convert.ToDouble(NtextBox.Text);
                    A0 = Convert.ToDouble(Q2textBox.Text);
                    string[] As = Regex.Split(Q1textBox.Text, ";");
                    if (As.Length != A.Length)
                    {
                        throw new System.ArgumentException("Невірний вектор A", "Помилка");
                    }
                    for (int i = 0; i < As.Length && i < A.Length; i++)
                    {
                        A[i] = Convert.ToDouble(As[i]);
                    }
                }
                catch { goto error; }
                for (int i = 0; i < ISA[0].unsortl.Length; i++)
                {
                    double dat = 0;
                    for (int j = 0; j < A.Length; j++)
                    {
                        dat += A[j] * ISA[j].unsortl[i];
                    }
                    dat += A0;
                    double eps = SimpleRNG.GetNormal(0, N);
                    dat = dat + eps;
                    RezDat.Add(dat);
                }
            }
            this.DialogResult = DialogResult.OK;
            this.Close();
            return;

error:
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
Beispiel #19
0
    public void UpdateVegetationAtPatch(IntVector2 patchCoord, Transform patchHolder)
    {
        // reset SimpleRNG using tree seed
        SimpleRNG.SetSeed((uint)(treeNoiseSeed + patchCoord.x + patchCoord.y * terrainManager.worldPatchesX));
        // set RNG seed depending on tree seed, world seed, and patch coordinates
        treeRNG = new System.Random(treeNoiseSeed + patchCoord.x + patchCoord.y * terrainManager.worldPatchesX);

        if (treePrefabs.Length > 0)
        {
            // get the number of trees in the patch (vegetation density)
            int numberOftrees = 0;
            if (true)
            {
                numberOftrees = Mathf.RoundToInt(Mathf.Max(0f, (float)SimpleRNG.GetNormal(treeDensity, treeDensityStdev)));
            }
            else
            {
                numberOftrees = Mathf.RoundToInt(vegetationNoiseOutsideModel.FractalNoise2D(patchCoord.x, patchCoord.y, 4, treeNoiseFrequency, treeNoiseScale) * treeDensity);
            }

            // place trees
            for (int i = 0; i < numberOftrees; i++)
            {
                // scale x and z coordinates for placing prefab prototypes in terrain. Note that this is not needed when placing GameObjects
                //Vector3 point = terrainManager.GetRandomPointInPatchSurface(patchCoord, treeRNG, scaleToTerrain: true);
                Vector3 point = loadSceneryAndLore.GetValidRandomPositionInPatch(patchCoord, 1f, treeRNG);

                float slope = terrainManager.GetSlopeAtPoint(point.x, point.z);

                if (slope < 0.7f)
                { //make sure tree are not on cliffs
                    GameObject temp = Instantiate(treePrefabs[Random.Range(0, treePrefabs.Length)], point, Quaternion.identity);
                    //temp.transform.Translate(Vector3.down * 1f);
                    temp.transform.localScale = Vector3.one * (treeScale.min + (float)treeRNG.NextDouble() * (treeScale.max - treeScale.min));
                    temp.transform.Rotate(Vector3.up * Random.Range(0f, 360f));

                    temp.transform.parent = patchHolder.transform;
                    //					TreeInstance temp = new TreeInstance ();
                    //					temp.position = point;
                    //					temp.rotation = Random.Range (0f, 360f) * Mathf.Deg2Rad;
                    //					temp.prototypeIndex = Random.Range (0, treePrefabs.Length);
                    //					temp.color = Color.white;
                    //					temp.lightmapColor = Color.white;
                    //
                    //					actTerrain.AddTreeInstance (temp);
                }
            }
        }
        //Debug.Log (terrainData.treeInstanceCount);

        // reset SimpleRNG using cactus seed
        SimpleRNG.SetSeed((uint)(cactusNoiseSeed + patchCoord.x + patchCoord.y * terrainManager.worldPatchesX));
        // set RNG seed depending on cactus seed, world seed, and patch coordinates
        cactusRNG = new System.Random(cactusNoiseSeed + patchCoord.x + patchCoord.y * terrainManager.worldPatchesX);

        if (cactusPrefabs.Length > 0)
        {
            // get the number of cactus in the patch (vegetation density)
            int numberOfCactus = 0;
            if (true)
            {
                numberOfCactus = Mathf.RoundToInt(Mathf.Max((float)SimpleRNG.GetNormal(cactusDensity, cactusDensityStdev)));
            }
            else
            {
                numberOfCactus = Mathf.RoundToInt(vegetationNoiseOutsideModel.FractalNoise2D(patchCoord.x, patchCoord.y, 4, cactusNoiseFrequency, cactusNoiseScale) * cactusDensity);
            }

            // place trees
            for (int i = 0; i < numberOfCactus; i++)
            {
                //Debug.Log(patchCoord.ToString());
                // scale x and z coordinates for placing prefab prototypes in terrain. Note that this is not needed when placing GameObjects
                //Vector3 point = terrainManager.GetRandomPointInPatchSurface(patchCoord, cactusRNG, scaleToTerrain: true);
                Vector3 point = loadSceneryAndLore.GetValidRandomPositionInPatch(patchCoord, 1f, cactusRNG);

                // normal diffusion
                //point = new Vector3(point.x + (float)SimpleRNG.GetNormal(0, .01f), 0f, point.z + (float)SimpleRNG.GetNormal(0, 0.01f));

                float slope = terrainManager.GetSlopeAtPoint(point.x, point.z);

                if (slope < 0.7f)
                { //make sure cactus are not on cliffs
                    GameObject temp = Instantiate(cactusPrefabs[cactusRNG.Next(0, cactusPrefabs.Length)], point, Quaternion.identity);
                    //temp.transform.Translate(Vector3.down * 0.2f);
                    temp.transform.localScale = Vector3.one * (cactusScale.min + (float)cactusRNG.NextDouble() * (cactusScale.max - cactusScale.min));
                    temp.transform.Rotate(Vector3.up * Random.Range(0f, 360f));

                    temp.transform.parent = patchHolder.transform;
                    //TreeInstance temp = new TreeInstance();
                    //temp.position = point;
                    //temp.rotation = Random.Range(0f, 360f) * Mathf.Deg2Rad;
                    //temp.prototypeIndex = Random.Range(treePrefabs.Length, treePrefabs.Length + cactusPrefabs.Length);
                    //float randomScale = Random.Range(1f, cactusMaxScale);
                    //temp.widthScale = randomScale;
                    //temp.heightScale = randomScale;
                    //temp.color = Color.white;
                    //temp.lightmapColor = Color.white;
                    //actTerrain.AddTreeInstance(temp);
                }
            }
        }
    }
Beispiel #20
0
    protected override void OnDoWork(System.ComponentModel.DoWorkEventArgs e)
    {
        int    matrixHorizontalSize = 0;
        double currentHorizontalPos = 0;
        int    counter = 0;

        // Get Circle/Square fractions needed for round laser beam
        double[,] fractions = CalcCircleSquareAreaFractions();

        while (currentHorizontalPos < SampleSizeHor)
        {
            currentHorizontalPos = LaserBeamSize + (counter * ScanSpeed) / LaserFrequency;
            counter++;
        }

        int[,] SampleOriginal = new int[SampleMatrix.GetLength(0), SampleMatrix.GetLength(1)];
        SampleOriginal        = SampleMatrix;

        matrixHorizontalSize = counter;

        double[,] ablatedSampleMatrix = new double
                                        [(int)Math.Ceiling((double)SampleSizeVer / LineSpacing), // the vertical sample size divided by the LaserBeamSize
                                         matrixHorizontalSize                                    // the horizontal sample size divided by ScanSpeed and multiplied by LaserFrequency, to get the number of pulses in a line
                                        ];                                                       // ** removed, i can calculate time if i need it; 1 for the resulting sum, and 1 for time

        double horLocation      = 0;                                                             // the horizontal, x, location of the laser beam (within a line)
        int    verLocation      = 0;                                                             // the vertical, y, location of the laser beam (lines)
        int    laserPulseNumber = 0;                                                             // will be used to show which the current pulse is, within a single line scen
        int    lineNumber       = 0;                                                             // will be used to show which the current line is
        double localSum         = 0;                                                             // initiation and declaration

        // GasFlow * 0.01 is there because of 10 ms time precision
        double ratio = (double)GasFlow * 0.01 / (double)ChamberVolume;
        // now to sum up these exponential fall-out values in time, so we get a representation
        // of how the concentration of ablated material/element changes in the gas with time
        int maxTime = 0;
        //Determine the approxiate washout time of the model, so we don't waste calculations
        int washoutTime = (int)Math.Round(6.746 * Math.Pow(ratio * 100, -1.0661) * 100);

        // If ratio is for example 1, (meaning 1 ml chamber, 100 ml/s gas flow), to keep the AUC for
        // integrate A*e^((-t)*1) from 0 to (6.746*((1*100)^(-1.0661))*100)
        // A, ergo peak, should be the ablated matrix value.
        // If the ratio is 0.5, the peak should be twice the ablated matrix value.

        double peakHeightFactor = ratio * 100;

        double exp = Math.Exp(1);

        int timeInCentiseconds = (int)Math.Floor((double)SampleSizeHor * 100 / ScanSpeed);      // how much time it takes for one line to complete

        double[,] finalBackmixedMatrix = new double[ablatedSampleMatrix.GetLength(0),
                                                    timeInCentiseconds];



        // Calculate the number of required calculations, so we can display the percent done in the
        // progress bar.

        for (int i = 0; i < (ablatedSampleMatrix.GetLength(0)); i++)
        {
            for (int j = 0; j < (ablatedSampleMatrix.GetLength(1)); j++)
            {
                int offsetTime = (int)Math.Floor(((double)j / (double)LaserFrequency) * 100);
                if ((offsetTime + washoutTime) < timeInCentiseconds)
                {
                    maxTime = offsetTime + washoutTime;
                }
                else
                {
                    maxTime = timeInCentiseconds;
                }

                HowManyCalculations += maxTime - offsetTime;
            }
        }

        HowManyCalculations += ablatedSampleMatrix.GetLength(1) * ablatedSampleMatrix.GetLength(0);

        // Simulate ablation (without backmixing)

        //// Noise
        Random random = new Random();

        SimpleRNG.SetSeedFromSystemTime();

        RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider();

        byte[] randBytes = new byte[4];
        double RSD       = 3.009 * Math.Exp(-0.2293 * LaserBeamSize) + 0.0568;

        /* Derived from MATLAB function fitting
         * a =       3.009  (0.9428, 5.076)
         * b =      0.2293  (0.1363, 0.3223)
         * c =      0.0568  (0.00159, 0.112)
         */
        while ((verLocation + LaserBeamSize) <= SampleSizeVer)     // whole sample
        {
            if (CancellationPending)
            {
                e.Cancel = true;
                return;
            }
            else
            {
                while ((horLocation + LaserBeamSize) <= SampleSizeHor)     // one line
                {
                    localSum = 0;

                    // this double for loop sums up the values within LaserBeamSize (down and right) of horLocation and verLocation
                    int LBS = LaserBeamSize;
                    for (int i = 0; i < LBS; i++)
                    {
                        for (int j = 0; j < LBS; j++)
                        {
                            // Square beam
                            if (BeamShape == false)
                            {
                                // Summation of values in the area of the matrix, that the laser ablates
                                localSum = localSum + SampleMatrix[i + verLocation, j + (int)Math.Floor(horLocation)];

                                // Ablate the thin sample, so that nothing remains in the impact site
                                if (ThinSample)
                                {
                                    SampleMatrix[i + verLocation, j + (int)Math.Floor(horLocation)] = 0;
                                }
                                // Ablate a certain fraction
                                else if (!ThinSample && !ThickSample)
                                {
                                    SampleMatrix[i + verLocation, j + (int)Math.Floor(horLocation)] -= (int)Math.Round(SampleOriginal[i + verLocation, j + (int)Math.Floor(horLocation)] * (1 / (double)NumberOfShots));
                                }
                            }
                            // Round beam. Multiply border areas with calculated fractions.
                            else if (BeamShape == true)
                            {
                                // Summation of values in the area of the matrix, that the laser ablates
                                localSum = localSum + SampleMatrix[i + verLocation, j + (int)Math.Floor(horLocation)] * fractions[i, j];

                                // Ablate the thin sample, so that nothing remains in the impact site
                                if (ThinSample)
                                {
                                    SampleMatrix[i + verLocation, j + (int)Math.Floor(horLocation)] -= (int)Math.Round(SampleMatrix[i + verLocation, j + (int)Math.Floor(horLocation)] * fractions[i, j]);
                                }
                                else if (!ThinSample && !ThickSample)
                                {
                                    SampleMatrix[i + verLocation, j + (int)Math.Floor(horLocation)] -= (int)Math.Round(SampleOriginal[i + verLocation, j + (int)Math.Floor(horLocation)] * fractions[i, j] * (1 / (double)NumberOfShots));
                                }
                            }
                        }
                    }
                    // Introduce ablation noise

                    secureRandom.GetBytes(randBytes);
                    double currentRandom = Math.Abs((double)BitConverter.ToInt32(randBytes, 0));

                    double noise2 = 0;
                    double noise  = 0;
                    // noise = AblationNoise * localSum * ((random.NextDouble() - 0.5) * 2);
                    if (AblationNoise != 0)
                    {
                        noise  = localSum * SimpleRNG.GetNormal(0, AblationNoise);
                        noise2 = SimpleRNG.GetNormal(0, AblationNoise);
                    }
                    ablatedSampleMatrix[lineNumber, laserPulseNumber] = Math.Abs(noise2 + localSum);

                    // resultingMatrix[lineNumber, laserPulseNumber, 1] = (int)Math.Floor((double)laserPulseNumber * 100/ LaserFrequency); // time at which the laser beam pulse had happened (in 1/100 seconds)
                    laserPulseNumber++;

                    CurrentCalc++;

                    horLocation = ScanSpeed * laserPulseNumber * (1 / (double)LaserFrequency);
                    // the next horizontal location equals the current one + how much the laser moves in one pulse
                }
            }
            // the next vertical location is the current one + the width of the laser (LaserBeamSize); moves down one width to the next line
            ReportProgress((int)(CurrentCalc * 100 / HowManyCalculations), "Simulating ... (1/3 - Sample ablation)");


            lineNumber++;
            laserPulseNumber = 0;
            horLocation      = 0;
            verLocation      = verLocation + LineSpacing;
            //  progressBar.Value = (int)(100 * ((double)verLocation / (double)SampleSizeVer));
            //  progressBar.Update();
        }

        // commented because we are putting everything in a single function
        // return ablatedSampleMatrix;
        // }

        // this is an inherent physical property of the LA (and ICP-MS?) machine, not its technical function

        //   public double[,] SampleBackmix(ref double[,] ablatedSampleMatrix, ref System.Windows.Forms.ProgressBar progressBar, ref System.Windows.Forms.Label timeRemaining)
        //   {


        //Report second step - sample backmixing
        // progressReport.Text = "Simulating ... (2/3 - Sample backmixing)";
        // form.Refresh();



        for (int i = 0; i < (ablatedSampleMatrix.GetLength(0)); i++)
        {
            if (CancellationPending)
            {
                e.Cancel = true;
                return;
            }
            else
            {
                for (int j = 0; j < (ablatedSampleMatrix.GetLength(1)); j++)
                {
                    int offsetTime = (int)Math.Ceiling(((double)j / (double)LaserFrequency) * 100);
                    if ((offsetTime + washoutTime) < timeInCentiseconds)
                    {
                        maxTime = offsetTime + washoutTime;
                    }
                    else
                    {
                        maxTime = timeInCentiseconds;
                    }

                    for (int k = offsetTime; k < maxTime; k++)
                    {
                        // so it starts the curve at the right point,*100 time precision
                        double noise = 0;
                        noise = TransferNoise * ((random.NextDouble() - 0.5) * 2);
                        finalBackmixedMatrix[i, k] += Math.Abs(noise + (ablatedSampleMatrix[i, j] * peakHeightFactor * Math.Pow(exp, (-(k - offsetTime)) * ratio)));
                    }
                    CurrentCalc += maxTime - offsetTime;
                }
            }
            ReportProgress((int)(CurrentCalc * 100 / HowManyCalculations), "Simulating ... (2/3 - Sample backmixing)");
        }

        double[,] ICPMSMatrix = new double[finalBackmixedMatrix.GetLength(0),
                                           (int)Math.Ceiling(finalBackmixedMatrix.GetLength(1) / (AcqTime * 100))];   // time precision ( the * 100 part)

        // Detector Noise generation
        //          Random detectorNoise = new Random();
        //          double strength = AmountNoise * 1 / (AdvancedNoiseSettings[10] * AdvancedNoiseSettings[11]);

        // Complete noise generation
        Random holisticNoise = new Random();

        // ICP-MS Acquisition
        for (int i = 0; i < ICPMSMatrix.GetLength(0); i++)
        {
            int    j         = 0; // raw data counter
            int    k         = 0; // final data counter
            double localSum1 = 0;


            while (j < finalBackmixedMatrix.GetLength(1))
            {
                // adds up all the raw data within an acquisition time
                //  localSum1 += finalBackmixedMatrix[i, j] + strength*detectorNoise.NextDouble();

                // Trapezoidal rule of approximating integration
                if ((j + 1 < finalBackmixedMatrix.GetLength(1)) && ((j + 1) % (AcqTime * 100) != 0))
                {
                    localSum1 += ((finalBackmixedMatrix[i, j] + finalBackmixedMatrix[i, j + 1]) / 2) * 0.01;
                }
                else
                {
                    localSum1 += finalBackmixedMatrix[i, j] * 0.01;
                }
                j++;

                // writes the data to the final array
                if ((j % (AcqTime * 100) == 0) || j == finalBackmixedMatrix.GetLength(1))     // time precision (the * 100 part)
                {
                    double noise = DetectorNoise * ((random.NextDouble() - 0.5) * 2);
                    //ICPMSMatrix[i, k] = localSum1 + holisticNoise.NextDouble()*AmountNoise ;
                    //ICPMSMatrix[i, k] = localSum1;
                    ICPMSMatrix[i, k] = Math.Abs(noise + localSum1);
                    localSum1         = 0;
                    k++;
                }
            }
        }

        ReportProgress((int)(CurrentCalc * 100 / HowManyCalculations), "Simulating ... (3/3 - ICPMS acquisition)");

        e.Result = ICPMSMatrix;
    }
Beispiel #21
0
        static void doTileZeroSimulation()
        {
            string adaptID  = "Game difficulty - Player skill";
            string gameID   = "TileZeroSimul";
            string playerID = "EvolvingAI";

            // [SC] do not update xml files
            bool updateDatafiles = false;

            // [SC] to randomly decide which player moves first
            Random rnd = new Random();
            // [SC] creating a game object
            Game tzGame = new Game();

            // [SC] disable logging to speed-up simulation
            Cfg.enableLog(false);

            double numberOfSimulations = 10;
            double numberOfMatches     = 400; // [SC] the number of games to be played with each AI evolution
            int    playableTileCount   = 54;
            double minRT = 60000;

            double distMean   = 0.75;
            double distSD     = 0.1;
            double lowerLimit = 0.5;
            double upperLimit = 1.0;

            // [SC] a player is represented by an AI evolving from Very Easy AI to Very Hard AI
            string[] aiOneEvolution = { TileZero.Cfg.VERY_EASY_AI
                                        , TileZero.Cfg.EASY_AI
                                        , TileZero.Cfg.MEDIUM_COLOR_AI
                                        , TileZero.Cfg.MEDIUM_SHAPE_AI
                                        , TileZero.Cfg.HARD_AI
                                        , TileZero.Cfg.VERY_HARD_AI };

            // [SC] start simulations
            for (int simIndex = 0; simIndex < numberOfSimulations; simIndex++)
            {
                TwoA twoA = new TwoA(new MyBridge());
                twoA.SetTargetDistribution(distMean, distSD, lowerLimit, upperLimit);
                double avgAccuracy = 0;

                // [SC] start AI player evolution from easiest to hardest
                foreach (string aiOneID in aiOneEvolution)
                {
                    // [SC] play a number of games before eacg evolution
                    for (int matchIndex = 0; matchIndex < numberOfMatches; matchIndex++)
                    {
                        // [SC] get a recommended opponent AI from TwoA
                        string aiTwoID = null;

                        aiTwoID = twoA.TargetScenarioID(adaptID, gameID, playerID);

                        Cfg.clearLog();

                        // [SC] start one match simualtion
                        int startPlayerIndex = rnd.Next(2); // [SC] decide whether the player or the opponent moves first
                        tzGame.initNewGame(aiOneID, aiTwoID, playableTileCount, startPlayerIndex);
                        tzGame.startNewGame();

                        // [SC] simulate player's response time
                        SimpleRNG.SetSeedFromRandom();
                        double rt = SimpleRNG.GetNormal(120000, 10000); // [SC] max is 900000
                        if (rt < minRT)
                        {
                            rt = minRT;
                        }

                        // [SC] obtain player's accuracy
                        double correctAnswer = 0;
                        if (tzGame.getPlayerByIndex(0).WinFlag)
                        {
                            correctAnswer = 1;
                        }

                        avgAccuracy += correctAnswer;

                        printMsg("Counter: " + (matchIndex + 1) + "; Start index: " + startPlayerIndex);
                        //printMsg(TileZero.Cfg.getLog());

                        // [SC] update ratings
                        twoA.UpdateRatings(adaptID, gameID, playerID, aiTwoID, rt, correctAnswer, updateDatafiles);
                    }
                }

                printMsg(String.Format("Accurracy for simulation {0}: {1}", simIndex, avgAccuracy / (numberOfMatches * aiOneEvolution.Length)));

                // [SC] creating a file with final ratings
                using (StreamWriter ratingfile = new StreamWriter("S4/ratingfile" + simIndex + ".txt")) {
                    string line = ""
                                  + "\"ScenarioID\""
                                  + "\t" + "\"Rating\""
                                  + "\t" + "\"PlayCount\""
                                  + "\t" + "\"Uncertainty\"";

                    ratingfile.WriteLine(line);

                    foreach (string scenarioID in aiOneEvolution)
                    {
                        line = ""
                               + "\"" + scenarioID + "\""
                               + "\t" + "\"" + twoA.ScenarioRating(adaptID, gameID, scenarioID) + "\""
                               + "\t" + "\"" + twoA.ScenarioPlayCount(adaptID, gameID, scenarioID) + "\""
                               + "\t" + "\"" + twoA.ScenarioUncertainty(adaptID, gameID, scenarioID) + "\"";

                        ratingfile.WriteLine(line);
                    }
                }

                // [SC] creating a file with history of gameplays including player and scenario ratings
                using (StreamWriter datafile = new StreamWriter("S4/datafile" + simIndex + ".txt")) {
                    GameplaysData  gameplays = twoA.GameplaysData;
                    TwoAAdaptation adaptNode = gameplays.Adaptation.First(p => p.AdaptationID.Equals(adaptID));
                    TwoAGame       gameNode  = adaptNode.Game.First(p => p.GameID.Equals(gameID));

                    string line = ""
                                  + "\"ID\""
                                  + "\t" + "\"PlayerID\""
                                  + "\t" + "\"ScenarioID\""
                                  + "\t" + "\"Timestamp\""
                                  + "\t" + "\"RT\""
                                  + "\t" + "\"Accuracy\""
                                  + "\t" + "\"PlayerRating\""
                                  + "\t" + "\"ScenarioRating\"";

                    datafile.WriteLine(line);

                    int id = 1;
                    foreach (TwoAGameplay gp in gameNode.Gameplay)
                    {
                        line = ""
                               + "\"" + id++ + "\""
                               + "\t" + "\"" + gp.PlayerID + "\""
                               + "\t" + "\"" + gp.ScenarioID + "\""
                               + "\t" + "\"" + gp.Timestamp + "\""
                               + "\t" + "\"" + gp.RT + "\""
                               + "\t" + "\"" + gp.Accuracy + "\""
                               + "\t" + "\"" + gp.PlayerRating + "\""
                               + "\t" + "\"" + gp.ScenarioRating + "\"";

                        datafile.WriteLine(line);
                    }
                }
            }
        }
        private List <int> ProlongOperator(List <int> mutatedValues, int segmentPosition)
        {
            int prolongLength = (int)Math.Ceiling(Math.Abs(SimpleRNG.GetNormal())) + 1;
            int sign          = mutatedValues[segmentPosition] / Math.Abs(mutatedValues[segmentPosition]);

            // Prolonging operator may not be applicable in full length
            // If segment extends throughout the whole field, operator is not applicable at all
            if (sign < 0)
            {
                if (mutatedValues[segmentPosition] + sign * prolongLength < -39)
                {
                    prolongLength = Math.Abs(-39 - mutatedValues[segmentPosition]);
                }
            }
            else
            {
                if (mutatedValues[segmentPosition] + sign * prolongLength > 29)
                {
                    prolongLength = 29 - mutatedValues[segmentPosition];
                }
            }

            if (prolongLength == 0)
            {
                return(mutatedValues);
            }

            mutatedValues[segmentPosition] = sign * (Math.Abs(mutatedValues[segmentPosition]) + prolongLength);
            int toShorten = prolongLength;

            while (toShorten > 0)
            {
                int randomParallelSegmentIndex = FindRandomParalellSegment(mutatedValues, segmentPosition);
                if (Math.Abs(mutatedValues[randomParallelSegmentIndex]) > toShorten)
                {
                    mutatedValues[randomParallelSegmentIndex] =
                        sign * (Math.Abs(mutatedValues[randomParallelSegmentIndex]) - toShorten);
                    toShorten = 0;
                }
                else
                {
                    toShorten -= Math.Abs(mutatedValues[randomParallelSegmentIndex]);
                    if (randomParallelSegmentIndex > 0 & randomParallelSegmentIndex < mutatedValues.Count - 1)
                    {
                        mutatedValues[randomParallelSegmentIndex - 1] += mutatedValues[randomParallelSegmentIndex + 1];
                        mutatedValues.RemoveRange(randomParallelSegmentIndex, 2);

                        if (segmentPosition > randomParallelSegmentIndex)
                        {
                            segmentPosition -= 2;
                        }
                    }
                    else
                    {
                        mutatedValues.RemoveAt(randomParallelSegmentIndex);
                        if (randomParallelSegmentIndex == 0)
                        {
                            segmentPosition -= 1;
                        }
                    }
                }
            }

            return(mutatedValues);
        }
Beispiel #23
0
        public Problem CuckooSearch(Problem prob, out double storagePercentage)
        {
            int    nNests         = 5;    //number of nests, or number of solutions
            int    subsetSize     = 100;
            int    maxGen         = 5;    //maximum generation
            double discoveryRate  = 0.25; //discovery rate of alien eggs
            double tolerance      = Math.Exp(-5);
            int    lowerBound     = -5;
            int    upperBound     = 5;
            int    totalInstances = prob.X.Count(); //problem size

            double[] cuckooFitnessVal                = new double[nNests];
            double[] newCuckooFitnessVal             = new double[nNests];
            ObjectInstanceSelection globalBestCuckoo = null;
            double globalBest = double.MinValue;
            Random rand       = new Random();

            FlowerPollinationAlgorithm fpa = new FlowerPollinationAlgorithm();

            //initialize population
            List <ObjectInstanceSelection> cuckoos    = InitializeBinaryCuckoo(nNests, subsetSize, totalInstances, prob);
            List <ObjectInstanceSelection> newCuckoos = new List <ObjectInstanceSelection>(cuckoos.Count); //create a clone of bats

            cuckoos.ForEach((item) =>
            {
                newCuckoos.Add(new ObjectInstanceSelection(item.Attribute_Values, item.Attribute_Values_Continuous, item.Pointers, item.Fitness)); //create a clone of flowers
            });

            cuckooFitnessVal    = EvaluateObjectiveFunction(cuckoos, prob);                                                                //evaluate fitness value for all the bats
            newCuckooFitnessVal = EvaluateObjectiveFunction(newCuckoos, prob);                                                             //evaluate fitness value for new bats. Note: this will be the same for this function call, since pollination has not occur
            CuckooFitness(cuckooFitnessVal, cuckoos);                                                                                      //fitness value for each bats
            CuckooFitness(newCuckooFitnessVal, newCuckoos);                                                                                //fitness value for new bats
            globalBestCuckoo = EvaluateSolution(cuckooFitnessVal, newCuckooFitnessVal, globalBest, cuckoos, newCuckoos, globalBestCuckoo); //get the global best flower
            globalBest       = globalBestCuckoo.__Fitness;

            //generate new solutions
            double beta  = 3 / 2;
            double A     = fp.Gamma(1 + beta) * Math.Sin(Math.PI * (beta / 2));
            double B     = fp.Gamma((1 + beta) / 2) * beta;
            double C     = (beta - 1) / 2;
            double D     = Math.Pow(2, C);
            double E     = A / (B * D);
            double sigma = Math.Pow(E, (1 / beta));

            double F;
            double G;
            double step;
            double stepSize;
            int    x = 0;

            for (int i = 0; i <= maxGen; i++)
            {
                for (int j = 0; j < nNests; j++)
                {
                    for (int k = 0; k < subsetSize; k++)
                    {
                        F    = SimpleRNG.GetNormal() * sigma;
                        G    = SimpleRNG.GetNormal();
                        step = F / Math.Pow(Math.Abs(G), (1 / beta));

                        //In the next equation, the difference factor (s-best) means that when the solution is the best solution, it remains unchanged.
                        //Here the factor 0.01 comes from the fact that L/100 should the typical step size of walks/flights where L is the typical lenghtscale;
                        //otherwise, Levy flights may become too aggresive/efficient, which makes new solutions (even) jump out side of the design domain (and thus wasting evaluations).
                        stepSize = 0.01 * step * (cuckoos[j].Attribute_Values[k] - globalBestCuckoo.Attribute_Values[k]);

                        //Now the actual random walks or levyy flights
                        newCuckoos[j].Attribute_Values[k] = fi.Binarize((newCuckoos[j].Attribute_Values[k] + stepSize) * SimpleRNG.GetNormal(), rand.NextDouble());

                        if (cuckoos[j].Attribute_Values[k] == 1 && newCuckoos[j].Attribute_Values[k] == 0)
                        {
                            x++;
                        }
                    }
                }

                //discovery and randomization - replace some nest by constructing new solutions
                newCuckoos = EmptyNest(cuckoos, newCuckoos, discoveryRate, subsetSize, nNests);

                //Select best solutions from the original population and matured population for the next generation;
                fpa.SelectBestSolution(cuckoos, newCuckoos);

                //evaluate new solution
                newCuckooFitnessVal = EvaluateObjectiveFunction(newCuckoos, prob);                                                             //evaluate fitness value for all the bats
                CuckooFitness(newCuckooFitnessVal, newCuckoos);                                                                                //fitness value for new bats
                globalBestCuckoo = EvaluateSolution(cuckooFitnessVal, newCuckooFitnessVal, globalBest, cuckoos, newCuckoos, globalBestCuckoo); //get the global best flower
                globalBest       = globalBestCuckoo.Fitness;

                //if solution has converged to a optimal user-defined point, stop search
                int Max = 60;          // maximum percentage reduction
                if (globalBest >= Max) //if the percentage reduction has approached 60%, stop search!
                {
                    break;
                }
            }

            //ensure that at least, N instances are selected for classification
            int min = 40; //minimum number of selected instances

            globalBestCuckoo = fpa.AddInstances(globalBestCuckoo, min);

            Problem subBest = fi.buildModelMultiClass(globalBestCuckoo, prob); //build model for the best Instance Mast

            storagePercentage = Training.StoragePercentage(subBest, prob);     //calculate the percent of the original training set was retained by the reduction algorithm
            return(subBest);
        }
        private List <int> BreakOperator(List <int> mutatedValues, int segmentPosition)
        {
            // 1.) Choose random position in the selected segment
            int selectedPosition = random.Next(1, Math.Abs(mutatedValues[segmentPosition]));
            // 2.) Check if break operator can be applied
            int upMovements    = 0;
            int rightMovements = 0;

            for (int i = 0; i < segmentPosition; i++)
            {
                if (mutatedValues[i] < 0)
                {
                    rightMovements -= mutatedValues[i];
                }
                else
                {
                    upMovements += mutatedValues[i];
                }
            }
            // Operator can only be applied if segments don't have either X or Y coordinate at maximum possible value
            if (upMovements == 29 || rightMovements == 39)
            {
                return(mutatedValues);
            }
            // Operator cannot be applied to segments of length 1
            if (Math.Abs(mutatedValues[segmentPosition]) == 1)
            {
                return(mutatedValues);
            }

            // 3.) Generate length of breaking segment using normal distribution
            int breakLength = (int)Math.Abs(Math.Ceiling(SimpleRNG.GetNormal()));

            if (breakLength == 0)
            {
                return(mutatedValues);
            }
            // Shorten break length to maximum allowed value if needed
            if (mutatedValues[segmentPosition] < 0)
            {
                if (upMovements + breakLength > 30)
                {
                    breakLength = 30 - upMovements;
                }
            }
            else
            {
                if (rightMovements + breakLength > 40)
                {
                    breakLength = 40 - rightMovements;
                }
            }

            // 4.) Mutate parent
            int currentChangedSegmentPosition = segmentPosition + 1;
            int sign = mutatedValues[segmentPosition] / (Math.Abs(mutatedValues[segmentPosition]));
            // a) Shorten segment that is going to be broken
            int otherHalfOfBrokenSegment = sign * (Math.Abs(mutatedValues[segmentPosition]) - selectedPosition);

            mutatedValues[segmentPosition] = sign * selectedPosition;
            // b) Add perpendicular breaking segment
            mutatedValues.Insert(segmentPosition + 1, -1 * sign * breakLength);
            // c) Add remaining part of shortened segment to the path
            mutatedValues.Insert(segmentPosition + 2, otherHalfOfBrokenSegment);
            // d) Shorten next following segment parallel with the break segment
            int toShorten = breakLength;

            while (toShorten > 0)
            {
                int randomParallelSegmentIndex = FindRandomParalellSegment(mutatedValues, currentChangedSegmentPosition);
                if (Math.Abs(mutatedValues[randomParallelSegmentIndex]) > toShorten)
                {
                    mutatedValues[randomParallelSegmentIndex] =
                        sign * -1 * (Math.Abs(mutatedValues[randomParallelSegmentIndex]) - toShorten);
                    toShorten = 0;
                }
                else
                {
                    toShorten -= Math.Abs(mutatedValues[randomParallelSegmentIndex]);
                    if (randomParallelSegmentIndex > 0 & randomParallelSegmentIndex < mutatedValues.Count - 1)
                    {
                        mutatedValues[randomParallelSegmentIndex - 1] += mutatedValues[randomParallelSegmentIndex + 1];
                        mutatedValues.RemoveRange(randomParallelSegmentIndex, 2);

                        if (currentChangedSegmentPosition > randomParallelSegmentIndex)
                        {
                            currentChangedSegmentPosition -= 2;
                        }
                    }
                    else
                    {
                        mutatedValues.RemoveAt(randomParallelSegmentIndex);
                        if (randomParallelSegmentIndex == 0)
                        {
                            currentChangedSegmentPosition -= 1;
                        }
                    }
                }
            }

            return(mutatedValues);
        }