Exemplo n.º 1
0
        public void TestGenerateMatrixWithSize1()
        {
            int[,] matrix = Matrica.GenerateMatrix(1);

            int[,] expectedResult = { { 1 } };
            for (int row = 0; row < matrix.GetLength(0); row++)
            {
                for (int col = 0; col < matrix.GetLength(1); col++)
                {
                    Assert.AreEqual(expectedResult[row, col], matrix[row, col]);
                }
            }
        }
        /// <summary>
        /// Checks if two points (old and new) are similar.
        /// </summary>
        /// <param name="xNew">New point.</param>
        /// <param name="xOld">Old point.</param>
        /// <param name="e">Precision.</param>
        /// <returns>True if they are similar, otherwise returns false.</returns>

        public static bool CheckIfPointsAreSimilar(Matrica xNew, Matrica xOld, double e)
        {
            Matrica xResult = xNew.SubtractMatrices(xOld);

            for (int i = 0; i < xResult.NoOfRows; i++)
            {
                if (Math.Abs(xResult.LoadedMatrix[i][0]) > e)
                {
                    return(false);
                }
            }

            return(true);
        }
        static void Main(string[] args)
        {
            if (File.Exists(CFr))
            {
                File.Delete(CFr);
            }

            Matrica Mtr = new Matrica();              // Ikonteineris su dvimačiu masyvu

            Skaityti(CFd, Mtr);
            Spausdinti(CFr, Mtr, " Pirma matrica");

            Matrica Mtr1 = new Matrica();              // II konteineris su dvimačiu masyvu

            Skaityti(CFd1, Mtr1);
            Spausdinti(CFr, Mtr1, " Antra matrica");

            int[] B  = new int[Mtr.N];
            int[] B1 = new int[Mtr1.N];

            // Atlikite visus nurodytus skaičiavimus.
            int mtrMax  = Mtr.Skaiciavimas();
            int mtr1Max = Mtr1.Skaiciavimas();

            Console.Write("Pirmos matricos pirmos srities maksimalus neigiamas: ");
            if (mtrMax == 0)
            {
                Console.WriteLine("nėra neigiamų.");
            }
            else
            {
                Console.WriteLine(mtrMax);
            }

            Console.Write("Antros matricos pirmos srities maksimalus neigiamas: ");
            if (mtr1Max == 0)
            {
                Console.WriteLine("nėra neigiamų.");
            }
            else
            {
                Console.WriteLine(mtr1Max);
            }

            AntrasDidziausias(Mtr, B);
            AntrasDidziausias(Mtr1, B1);

            Spausdinti1(CFr, B, Mtr.N, "Iš Pirmos matricos suformuotas masyvas");
            Spausdinti1(CFr, B1, Mtr1.N, "Iš Antros matricos suformuotas masyvas");
        }
Exemplo n.º 4
0
        /// <summary>
        /// Calculates simplex points using starting point.
        /// </summary>
        /// <param name="startingPoint">Starting point.</param>
        /// <param name="shift">Shift used for getting simplex points from starting point.</param>
        /// <returns>List of simplex points.</returns>

        public static List <double[]> GetSimplexPoints(double[] startingPoint, double shift)
        {
            List <double[]> simplexPoints = new List <double[]>();

            simplexPoints.Insert(0, startingPoint);
            for (int i = 0; i < startingPoint.Length; i++)
            {
                Matrica point = new Matrica();
                point.Equals(Matrica.ArrayToVector(startingPoint));
                point.LoadedMatrix[i][0] += shift;
                simplexPoints.Insert(i + 1, point.VectorToArray());
            }

            return(simplexPoints);
        }
        // Matricos konteinerio duomenų spausdinimas faile fv
        static void Spausdinti(string fv, Matrica A, string tekstas)
        {
            using (var fr = File.AppendText(fv))
            {
                fr.WriteLine();
                fr.WriteLine("      " + tekstas);

                for (int i = 0; i < A.N; i++)
                {
                    for (int j = 0; j < A.N; j++)
                    {
                        fr.Write("{0, 4:d}", A.Imti(i, j));
                    }
                    fr.WriteLine();
                }
            }
        }
        /// <summary>
        /// Finds minimum for function using Hooke-Jeeves Optimization algorithm.
        /// </summary>
        /// <param name="startingPoint">Starting point of algorithm.</param>
        /// <param name="function">Function used in algorithm.</param>
        /// <param name="e">Precision.</param>
        /// <param name="deltaX">Step used for calculating new points.</param>
        /// <returns>Minimum of function.</returns>

        public static Matrica FindMinimum(Matrica startingPoint, Function function, Matrica e, Matrica deltaX)
        {
            if (startingPoint.NoOfRows != e.NoOfRows || startingPoint.NoOfRows != deltaX.NoOfRows ||
                startingPoint.NoOfColumns != 1 || e.NoOfColumns != 1 || deltaX.NoOfColumns != 1)
            {
                throw new ArgumentException("Matrice koje ste poslali nisu odgovarajućih dimenzija za Hooke Jeeves metodu!");
            }
            Matrica xp = new Matrica();
            Matrica xb = new Matrica();

            xp.Equals(startingPoint);
            xb.Equals(startingPoint);
            //double[] xp = xpMatrix.VectorToArray();
            //double[] xb = xbMatrix.VectorToArray();
            double  xnFunctionValue, xbFunctionValue;
            Matrica assistingMatrix = new Matrica();

            do
            {
                double[] xn = Search(xp.VectorToArray(), function, deltaX);
                xnFunctionValue = function.CalculateValue(xn);
                function.IncreaseCounter(algorithmName);
                xbFunctionValue = function.CalculateValue(xb.VectorToArray());
                function.IncreaseCounter(algorithmName);
                WritePointsAndValuesInConsole(xb, xp, Matrica.ArrayToVector(xn), function);

                if (xnFunctionValue < xbFunctionValue)
                {
                    assistingMatrix.Equals(Matrica.ArrayToVector(xn));
                    assistingMatrix.MultiplyByScalar(2);
                    xp = assistingMatrix.SubtractMatrices(xb);
                    //xb = new Matrica();

                    xb.Equals(Matrica.ArrayToVector(xn));
                }
                else
                {
                    DecreaseDelta(deltaX);
                    xp.Equals(xb);
                }
            } while (IsTerminationCriteriaSatisfied(deltaX, e));

            return(xb);
        }
        /// <summary>
        /// Writes points and their function values in console.
        /// </summary>
        /// <param name="xb">Base point Xb.</param>
        /// <param name="xp">Starting search point Xp.</param>
        /// <param name="xn">Point obtained in search Xn.</param>
        /// <param name="function">Function used in algorithm.</param>

        public static void WritePointsAndValuesInConsole(Matrica xb, Matrica xp, Matrica xn, Function function)
        {
            Console.WriteLine("\nXb:");
            Console.WriteLine("=====");
            xb.WriteMatrixInConsole();
            Console.WriteLine("\nf(Xb) = " + function.CalculateValue(xb.VectorToArray()));

            Console.WriteLine("\nXp:");
            Console.WriteLine("=====");
            xp.WriteMatrixInConsole();
            Console.WriteLine("\nf(Xp) = " + function.CalculateValue(xp.VectorToArray()));

            Console.WriteLine("\nXn:");
            Console.WriteLine("=====");
            xn.WriteMatrixInConsole();
            Console.WriteLine("\nf(Xn) = " + function.CalculateValue(xn.VectorToArray()));

            Console.WriteLine("\n================");
        }
Exemplo n.º 8
0
        /// <summary>
        /// Calculates centroid point of given simplex.
        /// </summary>
        /// <param name="simplexPoints">Simplex points of Box algorithm.</param>
        /// <returns>Centroid point vector.</returns>

        public static Matrica GetCentroidPoint(List <Matrica> simplexPoints)
        {
            Matrica centroid = new Matrica();

            centroid.NoOfColumns = 1;
            centroid.NoOfRows    = simplexPoints[0].NoOfRows;
            for (int i = 0; i < centroid.NoOfRows; i++)
            {
                List <double> row = new List <double>();
                row.Insert(0, 0);
                centroid.LoadedMatrix.Add(i, row);
            }
            for (int i = 0; i < simplexPoints.Count; i++)
            {
                centroid.AddValue(simplexPoints[i]);
            }
            centroid.MultiplyByScalar(1.0 / simplexPoints.Count);
            return(centroid);
        }
        public static bool[][] CreateBinary2DArray(Matrica decimalValuePoint, int[] lengths, ExplicitRestriction[] explicitRestrictions)
        {
            int n = 0;

            for (int i = 0; i < lengths.Length; i++)
            {
                n += lengths[i];
            }
            int[]    decimalValues = DoubleToIntArray(decimalValuePoint.VectorToArray(), lengths, explicitRestrictions);
            bool[][] result        = new bool[decimalValues.Length][];

            for (int i = 0; i < decimalValues.Length; i++)
            {
                bool[] binaryValue = DecimalToBinary(decimalValues[i], lengths[i]);
                result[i] = binaryValue;
            }

            return(result);
        }
        public static Individual OnePointCrossoverFloatingPoint(List <Individual> selectedIndividuals, int[] lengths, ExplicitRestriction[] explicitRestrictions)
        {
            int index = r.Next(0, explicitRestrictions.Length - 1);

            double[] values = new double[explicitRestrictions.Length];

            for (int i = 0; i < values.Length; i++)
            {
                if (i <= index)
                {
                    values[i] = selectedIndividuals[0].DecimalValuePoint.LoadedMatrix[i][0];
                }
                else
                {
                    values[i] = selectedIndividuals[1].DecimalValuePoint.LoadedMatrix[i][0];
                }
            }
            return(new Individual(Matrica.ArrayToVector(values), lengths, explicitRestrictions));
        }
 public static Individual ParentRangeCrossover(List <Individual> selectedIndividuals, int[] lengths, ExplicitRestriction[] explicitRestrictions)
 {
     double[] values = new double[explicitRestrictions.Length];
     for (int i = 0; i < values.Length; i++)
     {
         if (selectedIndividuals[0].DecimalValuePoint.LoadedMatrix[i][0] >= selectedIndividuals[1].DecimalValuePoint.LoadedMatrix[i][0])
         {
             values[i] = r.NextDouble() * (selectedIndividuals[0].DecimalValuePoint.LoadedMatrix[i][0]
                                           - selectedIndividuals[1].DecimalValuePoint.LoadedMatrix[i][0])
                         + selectedIndividuals[1].DecimalValuePoint.LoadedMatrix[i][0];
         }
         else
         {
             values[i] = r.NextDouble() * (selectedIndividuals[1].DecimalValuePoint.LoadedMatrix[i][0]
                                           - selectedIndividuals[0].DecimalValuePoint.LoadedMatrix[i][0])
                         + selectedIndividuals[0].DecimalValuePoint.LoadedMatrix[i][0];
         }
     }
     return(new Individual(Matrica.ArrayToVector(values), lengths, explicitRestrictions));
 }
Exemplo n.º 12
0
        public void TestGenerateMatrixWithSize6()
        {
            int[,] matrix = Matrica.GenerateMatrix(6);

            int[,] expectedResult =
            {
                {  1, 16, 17, 18, 19, 20 },
                { 15,  2, 27, 28, 29, 21 },
                { 14, 31,  3, 26, 30, 22 },
                { 13, 36, 32,  4, 25, 23 },
                { 12, 35, 34, 33,  5, 24 },
                { 11, 10,  9,  8,  7,  6 }
            };

            for (int row = 0; row < matrix.GetLength(0); row++)
            {
                for (int col = 0; col < matrix.GetLength(1); col++)
                {
                    Assert.AreEqual(expectedResult[row, col], matrix[row, col]);
                }
            }
        }
Exemplo n.º 13
0
 static void Skaityti(string fv, Matrica A)
 {
     using (StreamReader reader = new StreamReader(fv))
     {
         int      skaicius;
         string   line     = reader.ReadLine();
         char[]   skyr     = { ' ' };
         string[] skaiciai = line.Split(skyr,
                                        StringSplitOptions.RemoveEmptyEntries);
         A.N = int.Parse(skaiciai[0]);
         for (int i = 0; i < A.N; i++)
         {
             line     = reader.ReadLine();
             skaiciai = line.Split(skyr,
                                   StringSplitOptions.RemoveEmptyEntries);
             for (int j = 0; j < A.N; j++)
             {
                 skaicius = int.Parse(skaiciai[j]);
                 A.Deti(i, j, skaicius);
             }
         }
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Calculates centroid point Xc.
        /// </summary>
        /// <param name="simplexPoints">Points of simplex.</param>
        /// <param name="h">Index of point Xh in simplex.</param>
        /// <returns></returns>

        public static double[] GetCentroidPoint(List <double[]> simplexPoints, int h)
        {
            Matrica centroid = new Matrica();

            centroid.NoOfColumns = 1;
            centroid.NoOfRows    = simplexPoints[0].Length;
            for (int i = 0; i < centroid.NoOfRows; i++)
            {
                List <double> row = new List <double>();
                row.Insert(0, 0);
                centroid.LoadedMatrix.Add(i, row);
            }
            for (int i = 0; i < simplexPoints.Count; i++)
            {
                if (i == h)
                {
                    continue;
                }
                centroid.AddValue(Matrica.ArrayToVector(simplexPoints[i]));
            }
            centroid.MultiplyByScalar(1.0 / (simplexPoints.Count - 1));
            return(centroid.VectorToArray());
        }
Exemplo n.º 15
0
 // Užrašykite metodą, kuris randa kiekvieno stulpelio antrą didžiausią elementą
 // ir jį įrašo į naują rinkinį.
 static void RastiAntraDidziausia(int[] naujas, Matrica m, ref int kiek)
 {
     for (int j = 0; j < m.N; j++)
     {
         //Console.WriteLine("-----------------------------------------");
         int pirmasDid = 0;
         int antrasDid = 0;
         if (m.Imti(0, j) > m.Imti(1, j))
         {
             pirmasDid = m.Imti(0, j);
             antrasDid = m.Imti(1, j);
         }
         else if (m.Imti(0, j) < m.Imti(1, j))
         {
             pirmasDid = m.Imti(1, j);
             antrasDid = m.Imti(0, j);
         }
         for (int i = 2; i < m.N; i++)
         {
             if (m.Imti(i, j) > pirmasDid && m.Imti(i, j) > antrasDid)
             {
                 //Console.WriteLine("!");
                 //Console.WriteLine(pirmasDid + " -> " + antrasDid + " -> " + m.Imti(i, j));
                 int temp = pirmasDid;
                 pirmasDid = m.Imti(i, j);
                 antrasDid = temp;
             }
             else if (m.Imti(i, j) < pirmasDid && m.Imti(i, j) > antrasDid)
             {
                 //Console.WriteLine("!!");
                 //Console.WriteLine(pirmasDid + " -> " + antrasDid + " -> " + m.Imti(i, j));
                 antrasDid = m.Imti(i, j);
             }
         }
         naujas[kiek++] = antrasDid;
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Finds minimum of function using Newton-Raphson algorithm.
        /// </summary>
        /// <param name="function">Function used in algorithm.</param>
        /// <param name="e">Precision</param>
        /// <param name="startingPoint">Starting point of algorithm.</param>
        /// <param name="usingGoldenSection">Flag used for tracking whether user wants to use Golden Section algorithm or not.</param>
        /// <returns>Minimum of function.</returns>

        public static Matrica FindMinimum(Function function, double e, Matrica startingPoint, bool usingGoldenSection)
        {
            Matrica x = new Matrica();

            x.Equals(startingPoint);
            function.SetParametersSize(x.NoOfRows);
            Matrica gradient      = new Matrica();
            Matrica hessianMatrix = new Matrica();
            int     brojac        = 0;
            Matrica xs            = new Matrica();

            if (usingGoldenSection == false)
            {
                do
                {
                    xs.Equals(x);
                    gradient = function.CalculateGradientValue(x.VectorToArray());
                    function.IncreaseCounterGradientValue(algorithmName);
                    hessianMatrix = function.CalculateHessianMatrix(x.VectorToArray());
                    function.IncreaseCounterHessian(algorithmName);
                    Matrica LU     = hessianMatrix.LUPDecomposition(e, gradient);
                    Matrica y      = Matrica.ForwardSubstitution(LU, gradient);
                    Matrica deltaX = Matrica.BackwardSubstitution(LU, gradient, e);
                    x.AddValue(deltaX);
                    brojac++;

                    function.IncreaseCounterValue(algorithmName);
                    function.IncreaseCounterValue(algorithmName);
                } while (brojac < 100);
            }
            else
            {
                do
                {
                    xs.Equals(x);
                    gradient = function.CalculateGradientValue(x.VectorToArray());
                    function.IncreaseCounterGradientValue(algorithmName);
                    hessianMatrix = function.CalculateHessianMatrix(x.VectorToArray());
                    function.IncreaseCounterHessian(algorithmName);
                    Matrica LU     = hessianMatrix.LUPDecomposition(e, gradient);
                    Matrica y      = Matrica.ForwardSubstitution(LU, gradient);
                    Matrica deltaX = Matrica.BackwardSubstitution(LU, gradient, e);
                    x.AddValue(deltaX);

                    for (int i = 0; i < x.NoOfRows; i++)
                    {
                        double     value       = x.LoadedMatrix[i][0];
                        double     vectorValue = deltaX.LoadedMatrix[i][0];
                        Expression expression  = lambda => value + lambda * vectorValue;
                        function.SetParameters(i, expression);
                    }

                    UnimodalInterval interval       = UnimodalInterval.FindUnimodalInterval(function, 0, 1, algorithmName);
                    UnimodalInterval lambdaInterval = GoldenSection.FindMinimum(function, interval.Minimum, interval.Maximum, e, algorithmName);

                    double lambdaMin = (lambdaInterval.Minimum + lambdaInterval.Maximum) / 2;
                    deltaX.MultiplyByScalar(lambdaMin);
                    x.AddValue(deltaX);

                    function.IncreaseCounterValue(algorithmName);
                    function.IncreaseCounterValue(algorithmName);
                } while (function.GetGradientNorm() >= e);
            }

            function.DeleteParameters();
            return(x);
        }
        /// <summary>
        /// Checks if explicit restrictions are met.
        /// </summary>
        /// <param name="explicitRestriction">List of explicit restrictions.</param>
        /// <param name="point">Point for which the explicit restriction are checked.</param>
        /// <returns>True if the explicit restrictions are met, otherwise returns false.</returns>

        public static bool CheckIfExplicitConstraintsAreMet(ExplicitRestriction explicitRestriction, Matrica point)
        {
            return(explicitRestriction.IsExplicitRestrictionMet(point));
        }
Exemplo n.º 18
0
        public static Matrica SolveEquation(Matrica A, Matrica B, Matrica x0, Interval interval, double T, int loggingStep, string destPath)
        {
            Matrica result = new Matrica();

            result.Equals(x0);
            List <string> lines      = new List <string>();
            int           linesIndex = 0;
            string        line       = "";

            Matrica U  = Matrica.GenerateIdentityMatrix(A.NoOfRows);
            Matrica AT = A.MultiplyByScalar2(T / 2);
            Matrica R  = new Matrica();
            Matrica S  = new Matrica();

            try
            {
                R = (U.SubtractMatrices(AT)).FindInverse().MultiplyMatrices(U.AddMatrices(AT));
                S = (U.SubtractMatrices(AT)).FindInverse().MultiplyByScalar2(T / 2).MultiplyMatrices(B);
            }
            catch (OperationCanceledException e)
            {
                throw new ArgumentException("Nije moguće naći inverz matrice jer je matrica singularna!");
            }

            int noOfIterations = (int)(Math.Round(interval.Maximum - interval.Minimum) / T);

            line += "t      ";
            for (int i = 0; i < x0.NoOfRows; i++)
            {
                line += "  x" + (i + 1) + "      ";
            }
            Console.WriteLine(line);
            lines.Insert(linesIndex++, line);
            line = "";

            line += String.Format("{0:0.00000}", interval.Minimum);
            for (int j = 0; j < result.NoOfRows; j++)
            {
                line += String.Format("  {0:0.00000}", result.LoadedMatrix[j][0]);
            }
            Console.WriteLine(line);
            lines.Insert(linesIndex++, line);
            line = "";

            for (int i = 0; i < noOfIterations; i++)
            {
                result = R.MultiplyMatrices(result).AddMatrices(S);

                if (i % loggingStep == 0)
                {
                    line += String.Format("{0:0.00000}", interval.Minimum + T * (i + 1));
                    for (int j = 0; j < result.NoOfRows; j++)
                    {
                        line += String.Format("  {0:0.00000}", result.LoadedMatrix[j][0]);
                    }
                    Console.WriteLine(line);
                    lines.Insert(linesIndex++, line);
                    line = "";
                }
            }

            System.IO.File.WriteAllLines(destPath, lines.ToArray());

            return(result);
        }
        /// <summary>
        /// Checks if implicit restrictions are met.
        /// </summary>
        /// <param name="implicitRestrictions">List of implicit restrictions.</param>
        /// <param name="point">Point for which the implicit restriction are checked.</param>
        /// <returns>True if the implicit restrictions are met, otherwise returns false.</returns>

        public static bool CheckIfImplicitConstraintsAreMet(List <RestrictionExpression> implicitRestrictions, Matrica point)
        {
            bool result;

            double[] coordinates = point.VectorToArray();
            foreach (var ir in implicitRestrictions)
            {
                if (result = ir.CheckIfMet(coordinates) == false)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Finds minimum for function using Nelder-Mead Simplex Optimization algorithm.
        /// </summary>
        /// <param name="startingPoint">Starting point of algorithm.</param>
        /// <param name="shift">Shift used in calculating points of simplex.</param>
        /// <param name="function">Function used in algorithm.</param>
        /// <param name="alfa">Constant used for calculating point of reflection.</param>
        /// <param name="beta">Constant used for calcualating point of contraction.</param>
        /// <param name="gamma">Constant used for calculating point of expansion.</param>
        /// <param name="e">Precision.</param>
        /// <param name="sigma">Constant used for moving points of simplex closer to minimal value.</param>
        /// <returns>Minimum of function.</returns>

        public static Matrica FindMinimum(Matrica startingPoint, double shift, Function function, double alfa, double beta, double gamma, double e, double sigma)
        {
            double[]        startPoint     = startingPoint.VectorToArray();
            List <double[]> simplexPoints  = GetSimplexPoints(startPoint, shift);
            List <double>   functionValues = new List <double>();

            double[] xc;
            int      h, l;

            do
            {
                functionValues = GetSimplexPointsFunctionValues(simplexPoints, function);
                l  = functionValues.IndexOf(functionValues.Min());
                h  = functionValues.IndexOf(functionValues.Max());
                xc = GetCentroidPoint(simplexPoints, h);
                Console.WriteLine("\nCentroid Xc:");
                Console.WriteLine("================");
                Matrica.ArrayToVector(xc).WriteMatrixInConsole();
                Console.WriteLine("\nf(Xc) = " + function.CalculateValue(xc));
                function.IncreaseCounter(algorithmName);
                double[] xr = Reflection(xc, simplexPoints[h], alfa);

                double xrFunctionValue = function.CalculateValue(xr);
                function.IncreaseCounter(algorithmName);

                if (xrFunctionValue < functionValues[l])
                {
                    double[] xe = Expansion(xc, xr, gamma);
                    double   xeFunctionValue = function.CalculateValue(xe);
                    function.IncreaseCounter(algorithmName);

                    if (xeFunctionValue < functionValues[l])
                    {
                        simplexPoints[h]  = xe;
                        functionValues[h] = xeFunctionValue;
                    }
                    else
                    {
                        simplexPoints[h]  = xr;
                        functionValues[h] = xrFunctionValue;
                    }
                }
                else
                {
                    if (CheckIfReflectionGreaterThanSimplexPoints(xr, simplexPoints, function, h))
                    {
                        if (xrFunctionValue < functionValues[h])
                        {
                            simplexPoints[h]  = xr;
                            functionValues[h] = xrFunctionValue;
                        }
                        double[] xk = Contraction(xc, simplexPoints[h], beta);
                        double   xkFunctionValue = function.CalculateValue(xk);
                        function.IncreaseCounter(algorithmName);

                        if (xkFunctionValue < functionValues[h])
                        {
                            simplexPoints[h]  = xk;
                            functionValues[h] = xkFunctionValue;
                        }
                        else
                        {
                            for (int j = 0; j < simplexPoints.Count; j++)
                            {
                                if (j != l)
                                {
                                    MovePointCloserToMinValue(simplexPoints, l, j, sigma);
                                }
                            }
                            functionValues = GetSimplexPointsFunctionValues(simplexPoints, function);
                        }
                    }
                    else
                    {
                        simplexPoints[h]  = xr;
                        functionValues[h] = xrFunctionValue;
                    }
                }
            } while (!IsTerminationCriteriaSatisfied(simplexPoints, xc, function, e));

            return(Matrica.ArrayToVector(simplexPoints[functionValues.IndexOf(functionValues.Min())]));
        }
 public Individual(Matrica point, int[] lengths, ExplicitRestriction[] explicitRestrictions)
 {
     DecimalValuePoint = point;
     BinaryValuePoint  = CreateBinary2DArray(DecimalValuePoint, lengths, explicitRestrictions);
     OneLineBinary     = GetOneLineBinary(BinaryValuePoint);
 }
Exemplo n.º 22
0
        /// <summary>
        /// Finds minimum of function using Box optimization method.
        /// </summary>
        /// <param name="function">Function used to optimize.</param>
        /// <param name="implicitRestrictions">List of implicit restrictions used in Box method.</param>
        /// <param name="explicitRestriction">List of explicit restrictions used in Box method.</param>
        /// <param name="startingPoint">Starting point of algorithm.</param>
        /// <param name="alfa">Constant alpha used in algorithm.</param>
        /// <param name="iterations">Number of iterations of algorithm.</param>
        /// <returns></returns>

        public static Matrica FindMinimum(Function function, List <RestrictionExpression> implicitRestrictions, ExplicitRestriction explicitRestriction, Matrica startingPoint, double alfa, int iterations)
        {
            if (OptimizationUtils.CheckIfExplicitConstraintsAreMet(explicitRestriction, startingPoint) == false ||
                OptimizationUtils.CheckIfImplicitConstraintsAreMet(implicitRestrictions, startingPoint) == false)
            {
                throw new ArgumentException("Starting point does not meet explicit and/or implicit conditions!");
            }

            int iter = 0;

            function.SetParametersSize(startingPoint.NoOfRows);
            Matrica centroid = new Matrica();

            centroid.Equals(startingPoint);
            int              n      = startingPoint.NoOfRows;
            Random           random = new Random();
            double           R;
            List <Matrica>   simplex  = new List <Matrica>();
            UnimodalInterval interval = explicitRestriction.GetInterval();

            for (int t = 0; t < 2 * n; t++)
            {
                double[] point = new double[n];
                for (int i = 0; i < n; i++)
                {
                    R        = random.NextDouble() * (maximumForRandom - minimumForRandom) + minimumForRandom;
                    point[i] = interval.Minimum + R * (interval.Maximum - interval.Minimum);
                }

                simplex.Insert(t, Matrica.ArrayToVector(point));

                bool[] simplexPointMeetsImplicitRestrictions = new bool[implicitRestrictions.Count];
                for (int i = 0; i < implicitRestrictions.Count; i++)
                {
                    simplexPointMeetsImplicitRestrictions[i] = false;
                }

                while (true)
                {
                    for (int i = 0; i < implicitRestrictions.Count; i++)
                    {
                        simplexPointMeetsImplicitRestrictions[i] = implicitRestrictions[i].CheckIfMet(simplex[t].VectorToArray());
                        if (simplexPointMeetsImplicitRestrictions[i] == false)
                        {
                            simplex[t].AddValue(centroid);
                            simplex[t].MultiplyByScalar(1.0 / 2);
                            break;
                        }
                    }

                    if (!simplexPointMeetsImplicitRestrictions.Contains(false))
                    {
                        break;
                    }
                }

                centroid = GetCentroidPoint(simplex);
            }

            List <double> functionValues = GetSimplexPointsFunctionValues(simplex, function);
            Matrica       xr             = new Matrica();

            do
            {
                int h  = GetIndexOfWorstPoint(functionValues);
                int h2 = GetIndexOfSecondWorstPoint(functionValues, h);
                centroid = GetCentroidPoint(simplex, h);
                xr       = Reflection(centroid, simplex[h], alfa);

                for (int i = 0; i < xr.NoOfRows; i++)
                {
                    if (xr.LoadedMatrix[i][0] < interval.Minimum)
                    {
                        xr.LoadedMatrix[i][0] = interval.Minimum;
                    }
                    else if (xr.LoadedMatrix[i][0] > interval.Maximum)
                    {
                        xr.LoadedMatrix[i][0] = interval.Maximum;
                    }
                }

                bool[] reflectionMeetsImplicitRestrictions = new bool[implicitRestrictions.Count];
                for (int i = 0; i < implicitRestrictions.Count; i++)
                {
                    reflectionMeetsImplicitRestrictions[i] = false;
                }

                while (true)
                {
                    for (int i = 0; i < implicitRestrictions.Count; i++)
                    {
                        reflectionMeetsImplicitRestrictions[i] = implicitRestrictions[i].CheckIfMet(xr.VectorToArray());
                        if (reflectionMeetsImplicitRestrictions[i] == false)
                        {
                            xr.AddValue(centroid);
                            xr.MultiplyByScalar(1.0 / 2);
                            break;
                        }
                    }

                    if (!reflectionMeetsImplicitRestrictions.Contains(false))
                    {
                        break;
                    }
                }

                double xrFunctionValue = function.CalculateValue(xr.VectorToArray());
                function.IncreaseCounterValue(algorithmName);
                if (xrFunctionValue > functionValues[h2])
                {
                    xr.AddValue(centroid);
                    xr.MultiplyByScalar(1.0 / 2);
                }

                simplex[h]        = xr;
                functionValues[h] = xrFunctionValue;
                iter++;
            } while (iter < iterations);

            function.DeleteParameters();
            return(simplex.ElementAt(functionValues.IndexOf(functionValues.Min())));
        }
Exemplo n.º 23
0
        /// <summary>
        /// Finds minimum of functions by transforming it to form solvable by Hooke-Jeeves algorithm.
        /// </summary>
        /// <param name="implicitRestrictions">List of implicit restrictions.</param>
        /// <param name="function">Function used in algorithm.</param>
        /// <param name="t">Parameter of transformation.</param>
        /// <param name="e">Precision.</param>
        /// <param name="startingPoint">Starting point of algorithm.</param>
        /// <param name="epsilon">Precision used in Hooke-Jeeves method.</param>
        /// <param name="deltaX">Step used for calculating new point.</param>
        /// <param name="iterations">Number of iterations of algorithm.</param>
        /// <returns>Minimum of function.</returns>

        public static Matrica FindMinimum(List <RestrictionExpression> implicitRestrictions, Function function, double t, double e, Matrica startingPoint, Matrica epsilon, Matrica deltaX, int iterations)
        {
            Matrica x = new Matrica();

            x.Equals(startingPoint);
            int counter = 0;

            while (true)
            {
                Matrica dx = new Matrica();
                dx.Equals(deltaX);
                TransformedFunction transformedFunction = new TransformedFunction(function, implicitRestrictions, t);
                Matrica             xs = new Matrica();
                xs.Equals(x);
                x  = HookeJeevesMethod.FindMinimum(xs, transformedFunction, epsilon, dx, algorithmName);
                t *= 10;
                counter++;

                if (OptimizationUtils.CheckIfPointsAreSimilar(x, xs, e) || counter > iterations)
                {
                    break;
                }
            }

            function.DeleteParameters();
            return(x);
        }