public void FindParabolaMinimumWithDerivative() { using (var solver = new NLoptSolver(NLoptAlgorithm.LD_AUGLAG, 1, 0.01, 100, NLoptAlgorithm.LN_NELDERMEAD)) { solver.SetLowerBounds(new[] { -10.0 }); solver.SetUpperBounds(new[] { 100.0 }); solver.AddLessOrEqualZeroConstraint((variables, gradient) => { if (gradient != null) { gradient[0] = 1.0; } return(variables[0] - 100.0); }); solver.SetMinObjective((variables, gradient) => { if (gradient != null) { gradient[0] = (variables[0] - 3.0) * 2.0; } return(Math.Pow(variables[0] - 3.0, 2.0) + 4.0); }); double?finalScore; var initialValue = new[] { 2.0 }; var result = solver.Optimize(initialValue, out finalScore); Assert.AreEqual(3.0, initialValue[0], 0.01); Assert.AreEqual(4.0, finalScore.GetValueOrDefault(), 0.01); } }
public void Opt(ref double[] q, ref List <Point3d> gp, ref List <Curve> tp, ref List <Curve> sp, ref List <int> lp, ref List <Vector3d> lv, ref double[] cs, ref double compliance, ref double[] rfload, ref int seed) { FDMinput.Input(ref gp, ref tp, ref sp, ref lp, ref lv, ref fix, ref free, ref Pfix, ref C, ref istart, ref iend, ref rfload); uint nm = (uint)tpinit.Count; //FDMfunc.Sens(ref q, ref gp, ref tp, ref lp, ref cs, ref compliance, ref rfload, ref fix, ref free, ref Pfix, ref C, ref istart, ref iend, ref scompliance, ref srfload); using (var solver = new NLoptSolver(NLoptAlgorithm.LD_SLSQP, nm, .1e-5, 100)) { var qmin = new double[nm]; for (int i = 0; i < nm; i++) { qmin[i] = q[i] - .1e3; } var qmax = new double[nm]; for (int i = 0; i < nm; i++) { qmax[i] = q[i] + .1e3; } solver.SetLowerBounds(qmin); solver.SetUpperBounds(qmax); solver.SetMinObjective(SObjFun); solver.AddEqualZeroConstraint(sConFun0, .1e-5); solver.AddEqualZeroConstraint(sConFun1, .1e-5); Random Random = new Random(seed); for (int i = 0; i < nm; i++) { q[i] += (Random.NextDouble() - 0.5) * 10; } double?finalScore = 0; var result = solver.Optimize(q, out finalScore); FDMfunc.Sens(ref q, ref gp, ref tp, ref lp, ref cs, ref compliance, ref rfload, ref fix, ref free, ref Pfix, ref C, ref istart, ref iend, ref scompliance, ref srfload); Console.WriteLine("============================================"); Console.WriteLine(result); for (int i = 0; i < nm; i++) { Console.WriteLine("q[{0}]={1}", i, q[i]); } Console.WriteLine("compliance={0}", compliance); Console.WriteLine("rfload[0]={0}", rfload[0]); Console.WriteLine("rfload[1]={0}", rfload[1]); } }
public void FindParabolaMinimum() { using (var solver = new NLoptSolver(NLoptAlgorithm.LN_COBYLA, 1, 0.001, 100)) { solver.SetLowerBounds(new[] { -10.0 }); solver.SetUpperBounds(new[] { 100.0 }); solver.SetMinObjective(variables => Math.Pow(variables[0] - 3.0, 2.0) + 4.0); double?finalScore; var initialValue = new[] { 2.0 }; var result = solver.Optimize(initialValue, out finalScore); Assert.AreEqual(NloptResult.XTOL_REACHED, result); Assert.AreEqual(3.0, initialValue[0], 0.1); Assert.AreEqual(4.0, finalScore.GetValueOrDefault(), 0.1); } }
public void TestBasicParabola() { for (int i = 0; i <= (int)NLoptAlgorithm.GN_ESCH; i++) { var algorithm = (NLoptAlgorithm)i; var algStr = algorithm.ToString(); if (algStr.Contains("AUGLAG") || algStr.Contains("MLSL")) { continue; } var sw = Stopwatch.StartNew(); int count = 0; using (var solver = new NLoptSolver(algorithm, 1, 0.0001, 2000)) { solver.SetLowerBounds(new[] { -10.0 }); solver.SetUpperBounds(new[] { 100.0 }); solver.SetMinObjective((variables, gradient) => { count++; if (gradient != null) { gradient[0] = (variables[0] - 3.0) * 2.0; } return(Math.Pow(variables[0] - 3.0, 2.0) + 4.0); }); double?final; var data = new[] { 2.0 }; var result = solver.Optimize(data, out final); //Assert.AreEqual(NloptResult.XTOL_REACHED, result); //if (result == NloptResult.MAXEVAL_REACHED || result == NloptResult.XTOL_REACHED) //Assert.AreEqual(4.0, final.Value, 0.1); // Assert.AreEqual(3.0, data[0], 0.01); Trace.WriteLine(string.Format("D:{0:F3}, R:{1:F3}, A:{2}, {3}", data[0], final.GetValueOrDefault(-1), algorithm, result)); } Trace.WriteLine("Elapsed: " + sw.ElapsedMilliseconds + "ms, Iterations: " + count); } }
public static Tuple <Date, double>[] Calibrate( string name, Date referenceDate, IMarketInstrument[] marketInstruments, BusinessDayConvention bda, IDayCount daycount, ICalendar calendar, Compound compound, Interpolation interpolation, YieldCurveTrait trait, CurrencyCode currency, Date[] knotPoints, out double fittingError, IMarketCondition baseMarket = null, Expression <Func <IMarketCondition, object> >[] expression = null, double initialValue = double.NaN, double initialGuess = 0.05, double xmin = -3, double xmax = 3.0 ) { var accuracy = 1.0e-13; if (marketInstruments.Any(x => !(x.Instrument is Bond))) { throw new PricingLibraryException("All instruments must be bond to build a bond curve!"); } var keyTs = knotPoints.Select(x => daycount.CalcDayCountFraction(referenceDate, x)).ToArray(); var len = keyTs.Length; baseMarket = baseMarket ?? new MarketCondition( x => x.ValuationDate.Value = referenceDate, x => x.DiscountCurve.Value = null, x => x.FixingCurve.Value = null, x => x.HistoricalIndexRates.Value = new Dictionary <IndexType, SortedDictionary <Date, double> >() ); var bondYieldPricer = new BondYieldPricer(); var bonds = marketInstruments.Select(x => x.Instrument as Bond); var bondCf = bonds.Select(x => x.GetCashflows(baseMarket, true)).ToList(); var bondPrices = bonds.Select( (x, i) => bondYieldPricer.FullPriceFromYield(bondCf[i], x.PaymentDayCount, x.PaymentFreq, x.StartDate, referenceDate, marketInstruments[i].TargetValue, x.BondTradeingMarket, x.IrregularPayment)).ToArray(); var rand = new Random(); // variables : alpha, b1, b2, b3, b4, b5 ... var numVars = 1 + 2 + len; var lowerBounds = new double[numVars]; var upperBounds = new double[numVars]; var initials = new double[numVars]; double?finalScore = double.NaN; for (var i = 0; i < numVars; ++i) { lowerBounds[i] = i == 0 ? 0.0 : xmin; upperBounds[i] = i == 0 ? 1.0 : xmax; initials[i] = rand.NextDouble() > 0 ? rand.NextDouble() : -rand.NextDouble(); } var globalSolver = new NLoptSolver(NLoptAlgorithm.GN_DIRECT, (ushort)numVars, accuracy, 100000, NLoptAlgorithm.LN_COBYLA); globalSolver.SetLowerBounds(lowerBounds); globalSolver.SetUpperBounds(upperBounds); globalSolver.SetMinObjective((variables, gradients) => { var error = bondCf.Select((cfs, i) => GetModelPrice(referenceDate, cfs, daycount, variables, keyTs) - bondPrices[i]).ToArray(); return(error.Sum(x => x * x)); }); double?globalFinalScore; var globalResult = globalSolver.Optimize(initials, out globalFinalScore); var localSolvers = new[] { NLoptAlgorithm.LN_BOBYQA, NLoptAlgorithm.LD_AUGLAG, NLoptAlgorithm.LN_COBYLA }; for (var k = 0; k < 3; ++k) { var localSolver = new NLoptSolver(localSolvers[k], (ushort)numVars, accuracy, 100000, NLoptAlgorithm.LN_COBYLA); localSolver.SetLowerBounds(lowerBounds); localSolver.SetUpperBounds(upperBounds); localSolver.SetMinObjective((variables, gradients) => { var error = bondCf.Select((cfs, i) => GetModelPrice(referenceDate, cfs, daycount, variables, keyTs) - bondPrices[i]).ToArray(); return(error.Sum(x => x * x)); }); var result = localSolver.Optimize(initials, out finalScore); } fittingError = finalScore.Value; var coeffes = new[] { Tuple.Create(referenceDate, initials[0]), Tuple.Create(referenceDate, -1.0 - initials[1] - initials[2] - initials.Skip(3).Sum() * 1 / 3.0), Tuple.Create(referenceDate, initials[1]), Tuple.Create(referenceDate, initials[2]), } .Union(knotPoints.Select((x, i) => Tuple.Create(x, initials[i + 3]))) .ToArray(); //var errors = bondCf.Select((cfs, i) => GetModelPrice(referenceDate, cfs, daycount, initials, keyTs)).ToArray(); //for (var i = 0; i < errors.Length; ++i) //{ // Console.WriteLine("{0},{1},{2}", errors[i], bondPrices[i], errors[i] - bondPrices[i]); //} return(coeffes); // Insert 0D point to avoid interpolation jump at the beginning }
} // relStopTO, neither should be made optional arguments public void SetBounds() { Solver.SetLowerBounds(Design.ActiveVariables.Select(x => x.Min).ToArray()); // should we do it only for active variables? Solver.SetUpperBounds(Design.ActiveVariables.Select(x => x.Max).ToArray()); }