/// <summary> /// Check if an inequality constaint can be applied on current algorithm. /// In NLopt, api/options.c has a function inequality_ok() which do the same verification. /// </summary> protected void CheckInequalityConstraintAvailability() { NLoptAlgorithm algorithm = Algorithm; switch (algorithm) { case NLoptAlgorithm.LD_MMA: case NLoptAlgorithm.LD_CCSAQ: case NLoptAlgorithm.LD_SLSQP: case NLoptAlgorithm.LN_COBYLA: case NLoptAlgorithm.GN_ISRES: case NLoptAlgorithm.GN_ORIG_DIRECT: case NLoptAlgorithm.GN_ORIG_DIRECT_L: case NLoptAlgorithm.AUGLAG: case NLoptAlgorithm.AUGLAG_EQ: case NLoptAlgorithm.LN_AUGLAG: case NLoptAlgorithm.LN_AUGLAG_EQ: case NLoptAlgorithm.LD_AUGLAG: case NLoptAlgorithm.LD_AUGLAG_EQ: break; default: throw new ArgumentException("Algorithm " + algorithm.ToString() + " does not support inequality constraint."); } }
public NLoptSolver(NLoptAlgorithm algorithm, uint numVariables, double relativeStoppingTolerance = 0.0001, int maximumIterations = 0, NLoptAlgorithm?childAlgorithm = null) { if (numVariables < 1) { throw new ArgumentOutOfRangeException("numVariables"); } _opt = nlopt_create(algorithm, numVariables); if (_opt == IntPtr.Zero) { throw new ArgumentException("Unable to initialize the algorithm.", "algorithm"); } if (relativeStoppingTolerance > 0.0) { var res = nlopt_set_xtol_rel(_opt, relativeStoppingTolerance); if (res != NloptResult.SUCCESS) { throw new ArgumentException("Unable to set primary tolerance. Result: " + res, "relativeStoppingTolerance"); } } if (maximumIterations > 0) { nlopt_set_maxeval(_opt, maximumIterations); } if (childAlgorithm != null) { var inner = nlopt_create(childAlgorithm.Value, numVariables); if (inner == IntPtr.Zero) { throw new ArgumentException("Unable to initialize the secondary algorithm.", "childAlgorithm"); } if (relativeStoppingTolerance > 0.0) { var res = nlopt_set_xtol_rel(inner, relativeStoppingTolerance); if (res != NloptResult.SUCCESS) { throw new ArgumentException("Unable to set secondary tolerance. Result: " + res, "relativeStoppingTolerance"); } } if (maximumIterations > 0) { nlopt_set_maxeval(inner, maximumIterations); } var ret = nlopt_set_local_optimizer(_opt, inner); nlopt_destroy(inner); if (ret != NloptResult.SUCCESS) { throw new ArgumentException("Unable to associate the child optimizer. Result: " + ret, "childAlgorithm"); } } }
public void NLoptTutorialExample_TestCaseNLoptConstraints_AnalyticSolution(NLoptAlgorithm nloptAlgorithm) { var multiDimOptimizer = new NLoptMultiDimOptimizer(NLoptAlgorithm.LN_COBYLA, NLoptAbortCondition.Create(relativeXTolerance: 1E-4)); var nloptBoxConstraint = multiDimOptimizer.Constraint.Create(MultiDimRegion.Interval.Create(dimension: 2, lowerBounds: new[] { Double.NegativeInfinity, 0.0 }, upperBounds: new[] { Double.PositiveInfinity, Double.PositiveInfinity })); double a1 = 2.0; double b1 = 0.0; double a2 = -1; double b2 = 1.0; /* this code uses NLopt specific constraints: */ var optimizer = multiDimOptimizer.Create(nloptBoxConstraint, multiDimOptimizer.Constraint.Create(2, (x, grad) => { if (grad != null) { grad[0] = 3.0 * a1 * (a1 * x[0] + b1) * (a1 * x[0] + b1); grad[1] = -1.0; } return((a1 * x[0] + b1) * (a1 * x[0] + b1) * (a1 * x[0] + b1) - x[1]); }), multiDimOptimizer.Constraint.Create(2, (x, grad) => { if (grad != null) { grad[0] = 3.0 * a2 * (a2 * x[0] + b2) * (a2 * x[0] + b2); grad[1] = -1.0; } return((a2 * x[0] + b2) * (a2 * x[0] + b2) * (a2 * x[0] + b2) - x[1]); } )); optimizer.Function = multiDimOptimizer.Function.Create(2, (x, grad) => { if (grad != null) { grad[0] = 0.0; grad[1] = 0.5 / Math.Sqrt(x[1]); } return(Math.Sqrt(x[1])); }); var actualArgMin = new[] { 1.234, 5.678 }; double actualMinimum; optimizer.FindMinimum(actualArgMin, out actualMinimum); double expectedMinimum = Math.Sqrt(8.0 / 27.0); double expectedArgMin0 = 1.0 / 3.0; double expectedArgMin1 = 8.0 / 27.0; Assert.That(actualMinimum, Is.EqualTo(expectedMinimum).Within(1E-3)); Assert.That(actualArgMin[0], Is.EqualTo(expectedArgMin0).Within(1E-3)); Assert.That(actualArgMin[1], Is.EqualTo(expectedArgMin1).Within(1E-3)); }
public void NLoptTutorialExample_TestCase_AnalyticSolution(NLoptAlgorithm nloptAlgorithm) { NLoptPtr ptr = new NLoptPtr(nloptAlgorithm, 2); /* add and create boundary and nonlinear constraints: */ ptr.SetLowerBounds(new[] { Double.NegativeInfinity, 0.0 }); double a1 = 2.0; double b1 = 0.0; ptr.AddInequalityConstraint((n, x, grad, data) => { if (grad != null) { grad[0] = 3.0 * a1 * (a1 * x[0] + b1) * (a1 * x[0] + b1); grad[1] = -1.0; } return((a1 * x[0] + b1) * (a1 * x[0] + b1) * (a1 * x[0] + b1) - x[1]); }, 1E-8); double a2 = -1; double b2 = 1.0; var code = ptr.AddInequalityConstraint((n, x, grad, data) => { if (grad != null) { grad[0] = 3.0 * a2 * (a2 * x[0] + b2) * (a2 * x[0] + b2); grad[1] = -1.0; } return((a2 * x[0] + b2) * (a2 * x[0] + b2) * (a2 * x[0] + b2) - x[1]); }, 1E-8); ptr.SetFunction((n, x, grad, data) => { if (grad != null) { grad[0] = 0.0; grad[1] = 0.5 / Math.Sqrt(x[1]); } return(Math.Sqrt(x[1])); }); ptr.TrySetRelativeXTolerance(1E-4); var actualArgMin = new[] { 1.234, 5.678 }; double actualMinimum; ptr.FindMinimum(actualArgMin, out actualMinimum); double expectedMinimum = Math.Sqrt(8.0 / 27.0); double expectedArgMin0 = 1.0 / 3.0; double expectedArgMin1 = 8.0 / 27.0; Assert.That(actualMinimum, Is.EqualTo(expectedMinimum).Within(1E-3)); Assert.That(actualArgMin[0], Is.EqualTo(expectedArgMin0).Within(1E-3)); Assert.That(actualArgMin[1], Is.EqualTo(expectedArgMin1).Within(1E-3)); }
/// <summary>Initializes a new instance of the <see cref="NLoptPtr"/> class. /// </summary> /// <param name="algorithm">The NLopt algorithm in its <see cref="NLoptAlgorithm"/> representation.</param> /// <param name="dimension">The dimension of the feasible region.</param> public NLoptPtr(NLoptAlgorithm algorithm, int dimension) { m_NLoptAlgorithm = algorithm; m_NLopPtr = nlopt_create(m_NLoptAlgorithm, dimension); if (m_NLopPtr == IntPtr.Zero) { throw new Exception(String.Format(ExceptionMessages.ObjectIsNotOperable, "NLopt[Ptr]")); } }
/// <summary> /// Check if an equality constaint can be applied on current algorithm. /// In NLopt, api/options.c has a function equality_ok() which do the same verification. /// </summary> protected void CheckEqualityConstraintAvailability() { NLoptAlgorithm algorithm = Algorithm; switch (algorithm) { case NLoptAlgorithm.LD_SLSQP: case NLoptAlgorithm.GN_ISRES: case NLoptAlgorithm.LN_COBYLA: break; default: throw new ArgumentException("Algorithm " + algorithm.ToString() + " does not support equality constraint."); } }
public bool DisablingAllowed; //if user want us to disable components that are not necessary in recomputation // CONSTRUCTOR FOR RADICAL public RadicalOptimizer(Design design, RadicalWindow radwindow) { this.Design = design; this.RadicalWindow = radwindow; this.RadicalVM = this.RadicalWindow.RadicalVM; this.MainAlg = this.RadicalVM.PrimaryAlgorithm; this.DisablingAllowed = !this.RadicalVM.DisablingNotAllowed; //this.SecondaryAlg = NLoptAlgorithm.LN_COBYLA; BuildWrapper(); SetBounds(); StoredMainValues = new ChartValues <double>(); StoredConstraintValues = new ChartValues <ChartValues <double> >(); if (this.DisablingAllowed) { FindWhichOnesToDisable(); } if (Design.Constraints != null) { foreach (Constraint c in Design.Constraints) { if (c.IsActive) { StoredConstraintValues.Add(new ChartValues <double>()); if (c.MyType == Constraint.ConstraintType.lessthan) { Solver.AddLessOrEqualZeroConstraint((x) => constraint(x, c)); } else if (c.MyType == Constraint.ConstraintType.morethan) { Solver.AddLessOrEqualZeroConstraint((x) => - constraint(x, c)); } else { Solver.AddEqualZeroConstraint((x) => constraint(x, c)); } } } } Solver.SetMinObjective((x) => Objective(x)); }
/// <summary>Initializes a new instance of the <see cref="NLoptMultiDimOptimizer" /> class. /// </summary> /// <param name="algorithm">A value indicating the specific NLopt algorithm.</param> /// <param name="abortCondition">The abort (stopping) condition of the NLopt algorithm.</param> /// <param name="nloptPtrAdjustment">An optional delegate which will be called in the <c>Create</c> methods for <see cref="IMultiDimOptimizerAlgorithm"/> objects that allows individual adjustments of the internal <see cref="NLoptPtr"/> representation.</param> /// <param name="loggerStreamFactory">A factory for <see cref="ILoggerStream"/> objects, i.e. for a logging. Each <see cref="IMultiDimOptimizerAlgorithm"/> object will track the function values in the specified logger.</param> /// <remarks>One can use <paramref name="nloptPtrAdjustment"/> to change the Initial step size, initial "population" of random points, set Local/subsidiary optimization algorithm etc. See /// the documentation of the NLopt library http://ab-initio.mit.edu/wiki/index.php/NLopt for further details.</remarks> public NLoptMultiDimOptimizer(NLoptAlgorithm algorithm, NLoptAbortCondition abortCondition, Action <NLoptPtr> nloptPtrAdjustment = null, Func <IMultiDimOptimizerAlgorithm, ILogger> loggerStreamFactory = null) { Algorithm = algorithm; Configuration = NLoptConfiguration.Create(algorithm); if (abortCondition == null) { throw new ArgumentNullException("abortCondition"); } AbortCondition = abortCondition; m_LongName = new IdentifierString(NLoptPtr.GetName(algorithm)); m_Name = new IdentifierString(algorithm.ToFormatString(EnumStringRepresentationUsage.StringAttribute)); Constraint = new NLoptConstraintFactory(this); Function = new NLoptFunctionFactory(this); m_nloptPtrAdjustment = nloptPtrAdjustment; m_LoggerStreamFactory = loggerStreamFactory; }
private static extern IntPtr nlopt_create(NLoptAlgorithm algorithm, uint n);
/// <summary>Creates the specified <see cref="NLoptConfiguration"/>. /// </summary> /// <param name="nloptAlgorithm">The NLopt algorithm in its <see cref="NLoptAlgorithm"/> representation.</param> /// <returns>The configuration of the specified NLopt algorithm in its <see cref="NLoptConfiguration"/> representation.</returns> public static NLoptConfiguration Create(NLoptAlgorithm nloptAlgorithm) { var attribute = EnumAttribute.Create <NLoptAlgorithmAttribute>(nloptAlgorithm); return(attribute.GetConfiguration()); }
/// <summary>Gets the name of a specific NLopt algorithm. /// </summary> /// <param name="nloptalgorithm">The NLopt algorithm in its <see cref="NLoptAlgorithm"/> representation.</param> /// <returns>The name of the specific NLopt algorithm in its <see cref="System.String"/> representation.</returns> public static string GetName(NLoptAlgorithm nloptalgorithm) { return(Marshal.PtrToStringAnsi(nlopt_AlgorithmName(nloptalgorithm))); }
private static extern IntPtr nlopt_AlgorithmName(NLoptAlgorithm algorithm);
/// <summary>Initializes a new instance of the <see cref="NLoptMultiDimOptimizer" /> class. /// </summary> /// <param name="algorithm">A value indicating the specific NLopt algorithm.</param> /// <param name="nloptPtrAdjustment">An optional delegate which will be called in the <c>Create</c> methods for <see cref="IMultiDimOptimizerAlgorithm"/> objects that allows individual adjustments of the internal <see cref="NLoptPtr"/> representation.</param> /// <param name="loggerStreamFactory">A factory for <see cref="ILoggerStream"/> objects, i.e. for a logging. Each <see cref="IMultiDimOptimizerAlgorithm"/> object will track the function values in the specified logger.</param> /// <remarks> /// <para>The <see cref="NLoptMultiDimOptimizer.StandardAbortCondition"/> is taken into account.</para> /// One can use <paramref name="nloptPtrAdjustment"/> to change the Initial step size, initial "population" of random points, set Local/subsidiary optimization algorithm etc. See /// the documentation of the NLopt library http://ab-initio.mit.edu/wiki/index.php/NLopt for further details.</remarks> public NLoptMultiDimOptimizer(NLoptAlgorithm algorithm, Action <NLoptPtr> nloptPtrAdjustment = null, Func <IMultiDimOptimizerAlgorithm, ILogger> loggerStreamFactory = null) : this(algorithm, StandardAbortCondition, nloptPtrAdjustment, loggerStreamFactory) { }
public void NLoptTutorialExample_TestCase_AnalyticSolution(NLoptAlgorithm nloptAlgorithm) { var multiDimOptimizer = new NLoptMultiDimOptimizer(nloptAlgorithm, NLoptAbortCondition.Create(relativeXTolerance: 1E-4)); var nloptBoxConstraint = multiDimOptimizer.Constraint.Create(MultiDimRegion.Interval.Create(dimension: 2, lowerBounds: new[] { Double.NegativeInfinity, 0.0 }, upperBounds: new[] { Double.PositiveInfinity, Double.PositiveInfinity })); double a1 = 2.0; double b1 = 0.0; /* This code uses generic constraints, i.e. polynomial constraints: */ /* The constraints in the Tutorial of the NLopt documentation can be re-written as polynomial in the following form: * * x_2 - a^3 * x_1^3 - 3*a^2*b*x_1^2 - 3*a*b^2 * x_1 >= b^3 */ var polynomialConstraint1 = MultiDimRegion.Polynomial.Create(2, b1 * b1 * b1, Double.PositiveInfinity, new[] { 1.0, -a1 * a1 * a1, -3.0 * a1 * a1 * b1, -3.0 * a1 * b1 * b1 }, MultiDimRegion.Polynomial.Monomial.Create(1, 1), MultiDimRegion.Polynomial.Monomial.Create(0, 3), MultiDimRegion.Polynomial.Monomial.Create(0, 2), MultiDimRegion.Polynomial.Monomial.Create(0, 1)); double a2 = -1; double b2 = 1.0; var polynomialConstraint2 = MultiDimRegion.Polynomial.Create(2, b2 * b2 * b2, Double.PositiveInfinity, new[] { 1.0, -a2 * a2 * a2, -3.0 * a2 * a2 * b2, -3.0 * a2 * b2 * b2 }, MultiDimRegion.Polynomial.Monomial.Create(1, 1), MultiDimRegion.Polynomial.Monomial.Create(0, 3), MultiDimRegion.Polynomial.Monomial.Create(0, 2), MultiDimRegion.Polynomial.Monomial.Create(0, 1)); var optimizer = multiDimOptimizer.Create(nloptBoxConstraint, multiDimOptimizer.Constraint.Create(polynomialConstraint1), multiDimOptimizer.Constraint.Create(polynomialConstraint2)); optimizer.Function = multiDimOptimizer.Function.Create(2, (x, grad) => { if (grad != null) { grad[0] = 0.0; grad[1] = 0.5 / Math.Sqrt(x[1]); } return(Math.Sqrt(x[1])); }); var actualArgMin = new[] { 1.234, 5.678 }; double actualMinimum; var state = optimizer.FindMinimum(actualArgMin, out actualMinimum); double expectedMinimum = Math.Sqrt(8.0 / 27.0); double expectedArgMin0 = 1.0 / 3.0; double expectedArgMin1 = 8.0 / 27.0; Assert.That(actualMinimum, Is.EqualTo(expectedMinimum).Within(1E-3), String.Format("<Minimum> State: {0}; Actual minimum: {1}; Expected minimum: {2}; Actual argMin: ({3}; {4}); Expected argMin: ({5}; {6})", state, actualMinimum, expectedMinimum, actualArgMin[0], actualArgMin[1], expectedArgMin0, expectedArgMin1)); Assert.That(actualArgMin[0], Is.EqualTo(expectedArgMin0).Within(1E-3), String.Format("<argMin[0]> State: {0}; Actual minimum: {1}; Expected minimum: {2}; Actual argMin: ({3}; {4}); Expected argMin: ({5}; {6})", state, actualMinimum, expectedMinimum, actualArgMin[0], actualArgMin[1], expectedArgMin0, expectedArgMin1)); Assert.That(actualArgMin[1], Is.EqualTo(expectedArgMin1).Within(1E-3), String.Format("<argMin[1]> State: {0}; Actual minimum: {1}; Expected minimum: {2}; Actual argMin: ({3}; {4}); Expected argMin: ({5}; {6})", state, actualMinimum, expectedMinimum, actualArgMin[0], actualArgMin[1], expectedArgMin0, expectedArgMin1)); }