public void AddAllInvestedConstraint()
        {
            var universe = from instrument in this
                           select instrument.ID;

            Constraints.Add(LinearConstraint.Create(universe, Relational.Equal, 1));
        }
        public void TestGradientWithoutIndices()
        {
            // Arrange1
            double[] combinedAs1 = { 2, 3, 4, 5, 6 };
            double[] combinedAs2 = { 9, 5, 1, 5, 8 };
            double[] x           = Vector.Random(5);

            var linearConstraint = new LinearConstraint(combinedAs1)
            {
                ShouldBe = ConstraintType.EqualTo,
                Value    = 42
            };

            // Act1
            double[] gradient = linearConstraint.Gradient(x);

            // Assert1
            Assert.True(gradient.IsEqual(combinedAs1));

            // Arrange2
            linearConstraint.CombinedAs = combinedAs2;

            // Act2
            double[] gradient2 = linearConstraint.Gradient(x);

            // Assert2
            Assert.True(gradient2.IsEqual(combinedAs2));
        }
        private void setTargetReturnConstraints(double targetReturn)
        {
            // Sum of all weighted returns should be equal to the target return
            var instList = from mr in _samplePortfolio
                           select new KeyValuePair <string, double>(mr.ID, mr.Mean);

            _samplePortfolio.Constraints.Add(LinearConstraint.Create(instList.ToDictionary(a => a.Key, b => b.Value), Relational.Equal, targetReturn));
        }
 public void AddLongOnlyConstraint()
 {
     foreach (var instrument in this)
     {
         // No short positions allowed -> min = 0
         Constraints.Add(LinearConstraint.Create(instrument.ID, Relational.Larger, 0));
     }
 }
 public void AddBoxConstraints(HashSet <string> assets, double lowerlimit, double upperlimit)
 {
     // check if asset in portfolio
     foreach (var asset in assets)
     {
         Constraints.Add(LinearConstraint.Create(asset, Relational.Smaller, upperlimit));
         Constraints.Add(LinearConstraint.Create(asset, Relational.Larger, lowerlimit));
     }
 }
Beispiel #6
0
        public void Test_10P1EqualP2()
        {
            int count = 8;

            double[] Ii = { 1, 1, 1, 1, 1, 1, 1, 1 };
            double[] w  = { 0.2, 0.121, 0.683, 0.04, 0.102, 0.081, 0.02, 0.667 };
            double[] d  =
            {
                10.0054919341489,
                3.03265795024749,
                6.83122010827837,
                1.98478460320379,
                5.09293357450987,
                4.05721328676762,
                0.991215230484718,
                6.66666666666666
            };
            double[]   b = { 0, 0, 0 };
            double[][] A =
            {
                new double[] { 1, -1, -1,  0,  0,  0,  0, 0 },
                new double[] { 0,  0,  1, -1, -1,  0,  0, 0 },
                new double[] { 0,  0,  0,  0,  1, -1, -1, 1 }
            };

            LinearConstraint linear = new LinearConstraint(numberOfVariables: 2)
            {
                VariablesAtIndices = new int[] { 0, 1 },
                CombinedAs         = new double[] { 1, -10 },
                ShouldBe           = ConstraintType.EqualTo,
                Value = 0
            };

            Calculator calculator = new Calculator();

            double[] res   = calculator.Solving(count, Ii, w, d, b, A, linear);
            bool     check = true;

            for (int i = 0; i < 3; i++)
            {
                double resultForCheck = 0;
                for (int j = 0; j < count; j++)
                {
                    resultForCheck += res[j] * A[i][j];
                }
                if (Math.Round(resultForCheck) != 0)
                {
                    check = false; break;
                }
            }

            Assert.AreEqual(true, check);
        }
        public void TestGradientWithIndices()
        {
            // Arrange1
            int[]    indices1    = { 2, 4, 6 };
            int[]    indices2    = { 0, 4, 6 };
            double[] combinedAs1 = { 2, 3, 4 };
            double[] combinedAs2 = { 9, 5, 1 };
            double[] x           = Vector.Random(8);
            double[] expected1   = { 0, 0, 2, 0, 3, 0, 4, 0 };
            double[] expected2   = { 0, 0, 9, 0, 5, 0, 1, 0 };
            double[] expected3   = { 9, 0, 0, 0, 5, 0, 1, 0 };

            var linearConstraint = new LinearConstraint(indices1.Length)
            {
                CombinedAs         = combinedAs1,
                VariablesAtIndices = indices1,
                ShouldBe           = ConstraintType.EqualTo,
                Value = 42
            };

            // Act1
            double[] gradient = linearConstraint.Gradient(x);

            // Assert1
            Assert.True(gradient.IsEqual(expected1));

            // Arrange2
            linearConstraint.CombinedAs = combinedAs2;

            // Act2
            double[] gradient2 = linearConstraint.Gradient(x);

            // Assert2
            Assert.True(gradient2.IsEqual(expected2));

            // Arrange3
            linearConstraint.VariablesAtIndices = indices2;

            // Act3
            double[] gradient3 = linearConstraint.Gradient(x);

            // Assert3
            Assert.True(gradient3.IsEqual(expected3));
        }
        public double[] Solve([FromBody] ForSolver data)
        {
            LinearConstraint linear = null;

            if (data.extra != null)
            {
                linear = new LinearConstraint(numberOfVariables: 2)
                {
                    VariablesAtIndices = new int[] { 0, 1 },
                    CombinedAs         = data.extra,
                    ShouldBe           = ConstraintType.EqualTo,
                    Value = 0
                };
            }
            Calculator calculator = new Calculator();

            double[] res = calculator.Solving(data.count, data.Ii, data.w, data.d, data.b, data.A, linear);
            return(res);
        }
        public void DocumentationTest()
        {
            #region doc_example
            // Linear constraints are common in numerical optimization.
            // Constraints can be defined using strings, expressions or
            // vectors. Suppose we have a quadratic objective function:
            var f = new QuadraticObjectiveFunction("2x² + 4y² - 2xy + 6");

            // Then the following three are all equivalent:
            var lc1 = new LinearConstraint(f, "3*x + 5*y <= 7");

            double x = 0, y = 0; // Define some dummy variables
            var    lc2 = new LinearConstraint(f, () => 3 * x + 5 * y <= 7);

            var lc3 = new LinearConstraint(numberOfVariables: 2)
            {
                CombinedAs = new double[] { 3, 5 },
                ShouldBe   = ConstraintType.LesserThanOrEqualTo,
                Value      = 7
            };

            // Then, we can check whether a constraint is violated and, if so,
            // by how much.
            double[] vector = { -2, 3 };

            if (lc1.IsViolated(vector))
            {
                // act on violation...
            }

            double violation = lc2.GetViolation(vector); // negative if violated

            #endregion

            double expected = -2;
            double v1       = lc1.GetViolation(vector);
            double v2       = lc2.GetViolation(vector);
            double v3       = lc3.GetViolation(vector);

            Assert.AreEqual(expected, v1);
            Assert.AreEqual(expected, v2);
            Assert.AreEqual(expected, v3);
        }
Beispiel #10
0
        public static Constraint[] GetConstraints(this Solution solution, ExperimentParameters experimentParameters)
        {
            var numberOfConstraintCoefficients = experimentParameters.NumberOfDimensions + 1;
            var numberOfConstraints            = experimentParameters.NumberOfConstraints;
            var limiter     = numberOfConstraintCoefficients * numberOfConstraints;
            var constraints = new Constraint[numberOfConstraints];
            var j           = 0;

            for (var i = 0; i < limiter; i += numberOfConstraintCoefficients)
            {
                var constraintLimitingValue = solution.ObjectCoefficients[i + numberOfConstraintCoefficients - 1];
                var constraintCoefficients  = new double[numberOfConstraintCoefficients - 1];

                Array.Copy(solution.ObjectCoefficients, i, constraintCoefficients, 0, numberOfConstraintCoefficients - 1);

                constraints[j++] = new LinearConstraint(constraintCoefficients, constraintLimitingValue);
            }

            return(constraints);
        }
Beispiel #11
0
        public static IEnumerable <LinearConstraint> GenerateInitialConstraints(Cluster cluster)
        {
            for (var i = 0; i < cluster.Dimensions; i++)
            {
                var minConstraint = new LinearConstraint(new Dictionary <int, double>()
                {
                    { i, 1.0 }
                }, cluster.Dimensions, cluster.Minimums[i])
                {
                    Sign = Inequality.GreaterThanOrEqual
                };

                yield return(minConstraint);

                var maxConstraint = new LinearConstraint(new Dictionary <int, double>()
                {
                    { i, 1.0 }
                }, cluster.Dimensions, cluster.Maximums[i]);

                yield return(maxConstraint);
            }
        }
Beispiel #12
0
        public ConstraintsBuilder(Constraint[] referenceConstraints, ExperimentParameters experimentParameters)
        {
            var singleReferenceConstraint = referenceConstraints.First();

            _constraintsModel = new Constraint[experimentParameters.MaximumNumberOfConstraints];

            if (experimentParameters.TypeOfBenchmark == BenchmarkType.Balln && experimentParameters.AllowQuadraticTerms)
            {
                for (var i = 0; i < _constraintsModel.Length; i++)
                {
                    _constraintsModel[i] = new QuadraticConstraint(singleReferenceConstraint.Terms.DeepCopyByExpressionTree(), 0);
                }
            }
            else
            {
                var terms = singleReferenceConstraint.Terms.Where(term => term.Type == TermType.Linear).ToArray();

                for (var i = 0; i < _constraintsModel.Length; i++)
                {
                    _constraintsModel[i] = new LinearConstraint(terms.DeepCopyByExpressionTree(), 0);
                }
            }
        }
Beispiel #13
0
        public double[] Solving(int count, double[] Ii, double[] w, double[] d, double[] b, double[][] A, LinearConstraint newConstraints = null)
        {
            double[,] I = new double[count, count];
            double[,] W = new double[count, count];
            for (int i = 0; i < w.Length; i++)
            {
                for (int j = 0; j < w.Length; j++)
                {
                    if (j == i)
                    {
                        W[i, j] = 1 / (w[i] * w[i]);
                        I[i, j] = Ii[i];
                    }
                    else
                    {
                        W[i, j] = 0;
                        I[i, j] = 0;
                    }
                }
            }
            double[,] Q = Accord.Math.Matrix.Dot(W, I);

            double[] D = new double[count];
            int[]    VariablesAtIndices = new int[count];
            for (int i = 0; i < count; i++)
            {
                D[i] = -1 * d[i] * Q[i, i];
                VariablesAtIndices[i] = i;
            }

            List <double[]> combinedAs = new List <double[]>();

            for (int i = 0; i < A.Length; i++)
            {
                double[] a = new double[A[i].Length];
                for (int j = 0; j < A[i].Length; j++)
                {
                    a[j] = A[i][j];
                }
                combinedAs.Add(a);
            }

            List <LinearConstraint> constraints = new List <LinearConstraint>();

            for (int i = 0; i < 3; i++)
            {
                LinearConstraint linear = new LinearConstraint(numberOfVariables: count)
                {
                    VariablesAtIndices = VariablesAtIndices,
                    CombinedAs         = combinedAs[i],
                    ShouldBe           = ConstraintType.EqualTo,
                    Value = b[i]
                };
                constraints.Add(linear);
            }

            if (newConstraints != null)
            {
                constraints.Add(newConstraints);
            }

            var solver = new GoldfarbIdnani(
                function: new QuadraticObjectiveFunction(Q, D),
                constraints: constraints);

            bool success = solver.Minimize();

            double[] solution = solver.Solution;
            return(solution);
        }
Beispiel #14
0
        /// <summary>
        ///   Computes the optimization algorithm when the user
        ///   presses the "Compute" button in the main interface.
        /// </summary>
        ///
        private void btnCompute_Click(object sender, EventArgs e)
        {
            // First, get what the user entered on screen:
            String strObjective = tbObjective.Text;

            String[] strConstraints = tbConstraints.Lines;

            // Check if this is a minimization or maximization task
            bool minimize = (string)comboBox1.SelectedItem == "min";

            // Now we can start creating our function:
            QuadraticObjectiveFunction function;

            LinearConstraint[] constraints = new LinearConstraint[strConstraints.Length];


            // Attempt to parse the string and create the objective function
            if (!QuadraticObjectiveFunction.TryParse(strObjective, out function))
            {
                tbSolution.Text = "Invalid objective function.";
                return;
            }

            // Create list of constraints
            for (int i = 0; i < constraints.Length; i++)
            {
                if (!LinearConstraint.TryParse(strConstraints[i], function, out constraints[i]))
                {
                    tbSolution.Text = "Invalid constraint at line " + i + ".";
                    return;
                }
            }


            // After the text has been parsed, create the solver
            var solver = new GoldfarbIdnani(function, constraints);


            // Solve the optimization problem:
            if (minimize)
            {
                solver.Minimize(); // the user wants to minimize it
            }
            else
            {
                solver.Maximize();   // the user wants to maximize it
            }
            if (solver.Status == GoldfarbIdnaniStatus.NonPositiveDefinite)
            {
                tbSolution.Text = "Function is not positive definite.";
                return;
            }
            else if (solver.Status == GoldfarbIdnaniStatus.NoPossibleSolution)
            {
                tbSolution.Text = "No possible solution could be attained.";
                return;
            }


            // Retrieve the computed solution
            double[] solution = solver.Solution;

            // And let's format and display it:
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("Solution:");
            sb.AppendLine();
            sb.AppendLine(" " + strObjective + " = " + solver.Value);
            sb.AppendLine();

            for (int i = 0; i < solution.Length; i++)
            {
                string variableName = function.Indices[i];
                sb.AppendLine(" " + variableName + " = " + solution[i]);
            }

            tbSolution.Text = sb.ToString();
        }
Beispiel #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            String objectiveString = tbObjective.Text;

            String[] constraintStrings = tbConstraints.Lines;
            bool     minimize          = (string)comboBox1.SelectedItem == "min";

            QuadraticObjectiveFunction function;

            LinearConstraint[] constraints = new LinearConstraint[constraintStrings.Length];

            try
            {
                // Create objective function
                function = new QuadraticObjectiveFunction(objectiveString);
            }
            catch (FormatException)
            {
                tbSolution.Text = "Invalid objective function.";
                return;
            }

            // Create list of constraints
            for (int i = 0; i < constraints.Length; i++)
            {
                try
                {
                    constraints[i] = new LinearConstraint(function, constraintStrings[i]);
                }
                catch (FormatException)
                {
                    tbSolution.Text = "Invalid constraint at line " + i + ".";
                    return;
                }
            }

            // Create solver
            var solver = new GoldfarbIdnaniQuadraticSolver(function.NumberOfVariables, constraints);

            try
            {
                // Solve the minimization or maximization problem
                double value = (minimize) ? solver.Minimize(function) : solver.Maximize(function);

                // Grab the solution found
                double[] solution = solver.Solution;

                // Format and display solution
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("Solution:");
                sb.AppendLine();
                sb.AppendLine(" " + objectiveString + " = " + value);
                sb.AppendLine();
                for (int i = 0; i < solution.Length; i++)
                {
                    string variableName = function.Indices[i];
                    sb.AppendLine(" " + variableName + " = " + solution[i]);
                }

                tbSolution.Text = sb.ToString();
            }
            catch (NonPositiveDefiniteMatrixException)
            {
                tbSolution.Text = "Function is not positive definite.";
            }
            catch (ConvergenceException)
            {
                tbSolution.Text = "No possible solution could be attained.";
            }
        }
Beispiel #16
0
        // Unterteilt das jetzige Ergebnic c in Unterzweigen
        // Fuer die Variablen, die nicht ganzzahlig sind
        private void SolveOne(Node c, CancellationToken cancelToken)
        {
            if (cancelToken.IsCancellationRequested)
            {
                IsCompleted = false;
                return;
            }
            if (!c.IsInfeasible)
            {
                // Falls das jetzige Ergebis schlechter als die Untergrenze,
                // dann muss es nicht in Unterzweigen mehr geteilt werden
                if (globalLowerBound > c.Upperbound)
                {
                    return;
                }
                // Falls das Lowerbound des jetizgen Ergebnises besser
                // als das Gespeicherte, dann ersetz das Gespeicherte
                // durch das Jetzige
                if (globalLowerBound < c.Lowerbound)
                {
                    globalLowerBound = c.Lowerbound;
                    // Und update das jetizge beste Loesung
                    CurrentSolution = new Dictionary <string, rat>();
                    foreach (var kvp in c.Answer)
                    {
                        CurrentSolution.Add(kvp.Key, kvp.Value.WholePart);
                        CurrentSolution["P"] = c.Lowerbound;
                    }
                }

                // Falls eine ganzzahlige Loesung (alle Variablen ganzzahlig) gefunden
                // dann kann man die ganze Suchreihe loeschen
                // denn dort wird die Ergebnis nach Upperbound sortiert
                // d.h. dieses Ergebnis 'c' hat den hoechstwahrscheinlichen Wert
                // innerhalb aller Moeglichkeiten
                if (c.Lowerbound.Equal(c.Upperbound))
                {
                    toSearch.Clear();
                    // Die endgueltige Loesung
                    BestSolution = new Dictionary <string, rat>();
                    foreach (var kvp in c.Answer)
                    {
                        BestSolution.Add(kvp.Key, kvp.Value.CanonicalForm);
                    }
                    return;
                }

                // Falls das jetizge Ergebnis nicht-ganzzahlige Variablen enthaelt
                // werden jede nicht-ganzzahlige Variable in zwei Zweigen unterteilt
                // naemlich x_i = 0 oder x_i = 1
                foreach (var pair in c.Answer)
                {
                    // der Zielwert 'P' kann uebersprungen werden
                    if (pair.Key.Equals(objective.LHSVariableNames[0]))
                    {
                        continue;
                    }
                    if (!(pair.Value.FractionPart == 0))
                    {
                        LinearConstraint zero = new LinearConstraint(new string[] { pair.Key }, new rat[] { 1 }, 0, LinearConstraint.InequalityType.SmallerOrEqualTo);
                        toSearch.Add(new Node(c.Tableau, zero, objective, cancelToken));
                        LinearConstraint one = new LinearConstraint(new string[] { pair.Key }, new rat[] { -1 }, -1, LinearConstraint.InequalityType.SmallerOrEqualTo);
                        toSearch.Add(new Node(c.Tableau, one, objective, cancelToken));
                    }
                }
            }
        }
 public void AddBoxConstraint(string asset, double lowerlimit, double upperlimit)
 {
     // check if asset in portfolio
     Constraints.Add(LinearConstraint.Create(asset, Relational.Smaller, upperlimit));
     Constraints.Add(LinearConstraint.Create(asset, Relational.Larger, lowerlimit));
 }
 public void AddGroupConstraints(HashSet <string> assets, double lowerlimit, double upperlimit)
 {
     Constraints.Add(LinearConstraint.Create(assets, Relational.Smaller, upperlimit));
     Constraints.Add(LinearConstraint.Create(assets, Relational.Larger, lowerlimit));
 }
 private double ConstraintFunctionValue(LinearConstraint constraint, double x) =>
 (-constraint[XIndex] * x + constraint.AbsoluteTerm) / constraint[YIndex];