#region Copyright Vanderlande Industries B.V. 2011 // // Copyright (c) 2011 Vanderlande Industries. // All rights reserved. // // @file: AlglibQPSolverTest.cs // @version: %version: 1 % // %date_created: vrijdag 31 augustus 2012 12:29:03 % // // The copyright to the computer program(s) herein is the property of // Vanderlande Industries. The program(s) may be used and/or copied // only with the written permission of the owner or in accordance with // the terms and conditions stipulated in the contract under which the // program(s) have been supplied. // #endregion using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Vanderlande.LFL.DetermineOrderStacks.UnitTest.Optimization { [TestFixture] public class AlglibQPSolverTest { public double[] Solve(int[,] variables, int[,] qObjective, int[] lObjective, int[,] constraints) { var nrVars = variables.GetLength(1); var nrCons = constraints.GetLength(0); var input = new double[nrVars]; var lbounds = new double[nrVars]; var ubounds = new double[nrVars]; for(var i = 0; i < nrVars; i++) { lbounds[i] = variables[i, 0]; input[i] = variables[i, 1]; ubounds[i] = variables[i, 2]; } alglib.minqpstate state; alglib.minqpreport report; double[] output; alglib.minqpcreate (nrVars, out state); alglib.minqpsetquadraticterm (state, Convert(qObjective)); alglib.minqpsetlinearterm (state, Convert(lObjective)); alglib.minqpsetbc (state, lbounds, ubounds); alglib.minqpsetlc (state, Convert(constraints), Enumerable.Repeat(-1, nrCons).ToArray()); alglib.minqpsetstartingpoint (state, input); // <--- Commenting this in/out changes the outcome of the solver alglib.minqpoptimize (state); alglib.minqpresults (state, out output, out report); return output; } [Test] public void AlglibQPSolver_Test1() { var result = Solve( variables: new [,]{ { 0, 0, 100 } , { 0, 100, 100 } , { 0, 0, 150 } }, qObjective: new [,]{ { 1, 0, 0 } , { 0, 1, 0 } , { 0, 0, 1 } }, lObjective: new [] { -50, -50, -75 } , constraints: new [,]{ { 1, -1, 0, -100 }, { 1, 0, -1, 0 }, { -1, 0, 1, 50 }}); Assert.AreEqual(new[] {0.0, 100.0, 50.0}, result.Select(d => Math.Round(d)).ToArray()); } [Test] public void AlglibQPSolver_Test2() { var result = Solve( variables: new [,]{ { 0, 0, 100 } , { 0, 100, 100 } , { 0, 150, 150 } }, qObjective: new [,]{ { 1, 0, 0 } , { 0, 1, 0 } , { 0, 0, 1 } }, lObjective: new [] { -50, -50, -75 } , constraints: new [,]{ { 1, -1, 0, -100 }, { 0, 1, -1, 0 }, { 0, -1, 1, 50 }}); Assert.AreEqual(new[] {0.0, 100.0, 100.0}, result.Select(d => Math.Round(d)).ToArray()); } private static double[] Convert(IEnumerable array) { return array.Select(i => (double) i).ToArray(); } private static double[,] Convert(int[,] array) { var result = new double[array.GetLength(0),array.GetLength(1)]; for(var i = 0; i < array.GetLength(0); i++) for(var j = 0; j < array.GetLength(1); j++) result[i, j] = array[i, j]; return result; } } }