-
Notifications
You must be signed in to change notification settings - Fork 3
/
Bobyqa.cs
2580 lines (2310 loc) · 110 KB
/
Bobyqa.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* csbobyqa
*
* The MIT License
*
* Copyright (c) 2012 Anders Gustafsson, Cureos AB.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Remarks:
*
* The original Fortran 77 version of this code was developed by Michael Powell ([email protected]) and can be downloaded from this location:
* http://plato.asu.edu/ftp/other_software/bobyqa.zip
*/
using System;
using System.IO;
namespace Cureos.Numerics
{
/// <summary>
/// Representation of supported exit statuses from the Bobyqa algorithm.
/// </summary>
public enum BobyqaExitStatus
{
TooFewVariables,
VariableBoundsArrayTooShort,
InvalidBoundsSpecification,
Normal,
InvalidInterpolationConditionNumber,
BoundsRangeTooSmall,
DenominatorCancellation,
TrustRegionStepReductionFailure,
MaximumIterationsReached
}
/// <summary>
/// C# implementation of Powell’s nonlinear derivative–free bound constrained optimization that uses a quadratic
/// approximation approach. The algorithm applies a trust region method that forms quadratic models by interpolation.
/// There is usually some freedom in the interpolation conditions, which is taken up by minimizing the Frobenius norm
/// of the change to the second derivative of the model, beginning with the zero matrix.
/// The values of the variables are constrained by upper and lower bounds.
/// </summary>
public static class Bobyqa
{
#region FIELDS
private const double INF = 1.0e60;
private const double INFMIN = -1.0e60;
private const double ONEMIN = -1.0;
private const double ZERO = 0.0;
private const double TENTH = 0.1;
private const double HALF = 0.5;
private const double ONE = 1.0;
private const double TWO = 2.0;
private const double TEN = 10.0;
private static readonly string LF = Environment.NewLine;
private static readonly string InvalidNptText = LF + "Return from BOBYQA because NPT is not in the required interval";
private static readonly string TooSmallBoundRangeText = LF + "Return from BOBYQA because one of the differences XU[I]-XL[I] is less than 2*RHOBEG.";
private static readonly string DenominatorCancellationText = LF + "Return from BOBYQA because of much cancellation in a denominator.";
private static readonly string MaxIterationsText = LF + "Return from BOBYQA because CALFUN has been called MAXFUN times.";
private static readonly string TrustRegionStepFailureText = LF + "Return from BOBYQA because a trust region step has failed to reduce Q.";
private static readonly string IterationOutputFormat = LF + "Function number {0,6} F ={1,18:E10}" + LF + "The corresponding X is: {2}";
private static readonly string StageCompleteOutputFormat = LF + "Least value of F ={0,15:E9}" + LF + "The corresponding X is: {1}";
private static readonly string RhoUpdatedFormat = LF + "New RHO ={0,11:E4}" + LF + "Number of function values ={1,6}";
private static readonly string FinalNumberEvaluationsFormat = LF + "At the return from BOBYQA Number of function values = {0}";
#endregion
#region PUBLIC METHODS
/// <summary>
/// Find a (local) minimum of the objective function <paramref name="calfun"/>, potentially subject to variable
/// bounds <paramref name="xl"/> and <paramref name="xu"/>.
/// </summary>
/// <param name="calfun">Objective function subject to minimization.</param>
/// <param name="n">Number of optimization variables, must be at least two.</param>
/// <param name="x">On entry, initial estimates of the variables. On exit, optimized variable values corresponding
/// to the minimization of <paramref name="calfun"/>. The variable array is zero-based.</param>
/// <param name="xl">Lower bounds on the variables. Array is zero-based. If set to null, all variables
/// are treated as downwards unbounded.</param>
/// <param name="xu">Upper bounds on the variables. Array is zero-based. If set to null, all variables
/// are treated as upwards unbounded.</param>
/// <param name="npt">Number of interpolation conditions. Its value must be in the interval [N+2,(N+1)(N+2)/2].
/// Choices that exceed 2*N+1 are not recommended.</param>
/// <param name="rhobeg">Initial value of a trust region radius, must be positive and greater than <paramref name="rhoend"/>.
/// Typically, value should be about one tenth of the greatest expected change to a variable.</param>
/// <param name="rhoend">Final values of a trust region radius, must be positive and less than <paramref name="rhobeg"/>.
/// Indicate the accuracy that is required in the final values of the variables.</param>
/// <param name="iprint">Should be set to 0, 1, 2 or 3, to control the amount of printing. Specifically, there is
/// no output for 0 and there is output only at the return for 1. Otherwise, each new value of RHO is printed,
/// with the best vector of variables so far and the corresponding value of the objective function. Further, each new
/// value of the objective function with its variables are output for value 3.</param>
/// <param name="maxfun">Maximum number of objective function evaluations.</param>
/// <param name="logger">If defined, text writer to which log output should be directed.</param>
/// <returns>Exit status of the objective function minimization.</returns>
/// <remarks>The construction of quadratic models requires <paramref name="xl"/> to be strictly less than
/// <paramref name="xu"/> for each index I. Further, the contribution to a model from changes to the I-th variable is
/// damaged severely by rounding errors if difference between upper and lower bound is too small.</remarks>
public static BobyqaExitStatus FindMinimum(Func<int, double[], double> calfun, int n, double[] x, double[] xl = null,
double[] xu = null, int npt = -1, double rhobeg = -1.0, double rhoend = -1.0, int iprint = 1, int maxfun = 10000,
TextWriter logger = null)
{
// Verify that the number of variables is greater than 1; BOBYQA does not support 1-D optimization.
if (n < 2) return BobyqaExitStatus.TooFewVariables;
// Verify that the number of variables, and bounds if defined, in the respective array is sufficient.
if (x.Length < n || (xl != null && xl.Length < n) || (xu != null && xu.Length < n))
{
return BobyqaExitStatus.VariableBoundsArrayTooShort;
}
// C# arrays are zero-based, whereas BOBYQA methods expect one-based arrays. Therefore define internal matrices
// to be dispatched to the private BOBYQA methods.
var ix = new double[1 + n];
Array.Copy(x, 0, ix, 1, n);
// If xl and/or xu are null, this is interpreted as that the optimization variables are all unbounded downwards and/or upwards.
// In that case, assign artificial +/- infinity values to the bounds array(s).
var ixl = new double[1 + n];
if (xl == null)
for (var i = 1; i <= n; ++i) ixl[i] = INFMIN;
else
Array.Copy(xl, 0, ixl, 1, n);
var ixu = new double[1 + n];
if (xu == null)
for (var i = 1; i <= n; ++i) ixu[i] = INF;
else
Array.Copy(xu, 0, ixu, 1, n);
// Verify that all lower bounds are less than upper bounds.
// If any start value is outside bounds, adjust this value to be within bounds.
var rng = new double[1 + n];
var minrng = Double.MaxValue;
var maxabsx = 0.0;
for (var i = 1; i <= n; ++i)
{
if ((rng[i] = ixu[i] - ixl[i]) <= 0.0)
return BobyqaExitStatus.InvalidBoundsSpecification;
minrng = Math.Min(rng[i], minrng);
if (ix[i] < ixl[i]) ix[i] = ixl[i];
if (ix[i] > ixu[i]) ix[i] = ixu[i];
maxabsx = Math.Max(Math.Abs(ix[i]), maxabsx);
}
// If rhobeg is non-positive, set rhobeg based on the absolute values of the variables' start values,
// using same strategy as R-project BOBYQA wrapper.
if (rhobeg <= 0.0) rhobeg = maxabsx > 0.0 ? Math.Min(0.95, 0.2 * maxabsx) : 0.95;
// Required that rhobeg is less than half the minimum bounds range; adjust rhobeg if necessary.
if (rhobeg > 0.5 * minrng) rhobeg = 0.2 * minrng;
// If rhoend is non-negative, set rhoend to one millionth of the rhobeg value (R-project strategy).
if (rhoend <= 0.0) rhoend = 1.0e-6 * rhobeg;
// If npt is non-positive, apply default value 2 * n + 1.
var inpt = npt > 0 ? npt : 2 * n + 1;
// Define internal calfun to account for that the x vector in the function invocation is one-based.
var icalfun = new Func<int, double[], double>((nn, ixx) =>
{
var xx = new double[n];
Array.Copy(ixx, 1, xx, 0, n);
return calfun(nn, xx);
});
// Invoke optimization. After completed optimization, transfer the optimized internal variable array to the
// variable array in the method call.
var status = BOBYQA(icalfun, n, inpt, ix, ixl, ixu, rhobeg, rhoend, iprint, maxfun, logger);
Array.Copy(ix, 1, x, 0, n);
return status;
}
#endregion
#region PRIVATE BOBYQA ALGORITHM METHODS
private static BobyqaExitStatus BOBYQA(Func<int, double[], double> calfun, int n, int npt, double[] x,
double[] xl, double[] xu, double rhobeg, double rhoend, int iprint, int maxfun, TextWriter logger)
{
// This subroutine seeks the least value of a function of many variables,
// by applying a trust region method that forms quadratic models by
// interpolation. There is usually some freedom in the interpolation
// conditions, which is taken up by minimizing the Frobenius norm of
// the change to the second derivative of the model, beginning with the
// zero matrix. The values of the variables are constrained by upper and
// lower bounds. The arguments of the subroutine are as follows.
//
// N must be set to the number of variables and must be at least two.
// NPT is the number of interpolation conditions. Its value must be in
// the interval [N+2,(N+1)(N+2)/2]. Choices that exceed 2*N+1 are not
// recommended.
// Initial values of the variables must be set in X(1),X(2),...,X(N). They
// will be changed to the values that give the least calculated F.
// For I=1,2,...,N, XL[I] and XU[I] must provide the lower and upper
// bounds, respectively, on X[I]. The construction of quadratic models
// requires XL[I] to be strictly less than XU[I] for each I. Further,
// the contribution to a model from changes to the I-th variable is
// damaged severely by rounding errors if XU[I]-XL[I] is too small.
// RHOBEG and RHOEND must be set to the initial and final values of a trust
// region radius, so both must be positive with RHOEND no greater than
// RHOBEG. Typically, RHOBEG should be about one tenth of the greatest
// expected change to a variable, while RHOEND should indicate the
// accuracy that is required in the final values of the variables. An
// error return occurs if any of the differences XU[I]-XL[I], I=1,...,N,
// is less than 2*RHOBEG.
// The value of IPRINT should be set to 0, 1, 2 or 3, which controls the
// amount of printing. Specifically, there is no output if IPRINT=0 and
// there is output only at the return if IPRINT=1. Otherwise, each new
// value of RHO is printed, with the best vector of variables so far and
// the corresponding value of the objective function. Further, each new
// value of F with its variables are output if IPRINT=3.
// MAXFUN must be set to an upper bound on the number of calls of CALFUN.
//
// SUBROUTINE CALFUN (N,X,F) has to be provided by the user. It must set
// F to the value of the objective function for the current values of the
// variables X(1),X(2),...,X(N), which are generated automatically in a
// way that satisfies the bounds given in XL and XU.
// Return if the value of NPT is unacceptable.
var np = n + 1;
if (npt < n + 2 || npt > ((n + 2) * np) / 2)
{
if (logger != null) logger.WriteLine(InvalidNptText);
return BobyqaExitStatus.InvalidInterpolationConditionNumber;
}
var ndim = npt + n;
var sl = new double[1 + n];
var su = new double[1 + n];
// Return if there is insufficient space between the bounds. Modify the
// initial X if necessary in order to avoid conflicts between the bounds
// and the construction of the first quadratic model. The lower and upper
// bounds on moves from the updated X are set now, in the ISL and ISU
// partitions of W, in order to provide useful and exact information about
// components of X that become within distance RHOBEG from their bounds.
for (var j = 1; j <= n; ++j)
{
double temp = xu[j] - xl[j];
if (temp < rhobeg + rhobeg)
{
if (logger != null) logger.WriteLine(TooSmallBoundRangeText);
return BobyqaExitStatus.BoundsRangeTooSmall;
}
sl[j] = xl[j] - x[j];
su[j] = xu[j] - x[j];
if (sl[j] >= -rhobeg)
{
if (sl[j] >= ZERO)
{
x[j] = xl[j];
sl[j] = ZERO;
su[j] = temp;
}
else
{
x[j] = xl[j] + rhobeg;
sl[j] = -rhobeg;
su[j] = Math.Max(xu[j] - x[j], rhobeg);
}
}
else if (su[j] <= rhobeg)
{
if (su[j] <= ZERO)
{
x[j] = xu[j];
sl[j] = -temp;
su[j] = ZERO;
}
else
{
x[j] = xu[j] - rhobeg;
sl[j] = Math.Min(xl[j] - x[j], -rhobeg);
su[j] = rhobeg;
}
}
}
// Make the call of BOBYQB.
return BOBYQB(calfun, n, npt, x, xl, xu, rhobeg, rhoend, iprint, maxfun, ndim, sl, su, logger);
}
private static BobyqaExitStatus BOBYQB(Func<int, double[], double> calfun, int n, int npt, double[] x, double[] xl,
double[] xu, double rhobeg, double rhoend, int iprint, int maxfun, int ndim, double[] sl, double[] su,
TextWriter logger)
{
// The arguments N, NPT, X, XL, XU, RHOBEG, RHOEND, IPRINT and MAXFUN
// are identical to the corresponding arguments in SUBROUTINE BOBYQA.
// SL and SU hold the differences XL-XBASE and XU-XBASE, respectively.
// All the components of every XOPT are going to satisfy the bounds
// SL[I] .LEQ. XOPT[I] .LEQ. SU[I], with appropriate equalities when
// XOPT is on a constraint boundary.
// Set some constants.
var np = n + 1;
var nptm = npt - np;
var nh = (n * np) / 2;
// XBASE holds a shift of origin that should reduce the contributions
// from rounding errors to values of the model and Lagrange functions.
// XPT is a two-dimensional array that holds the coordinates of the
// interpolation points relative to XBASE.
// FVAL holds the values of F at the interpolation points.
// XOPT is set to the displacement from XBASE of the trust region centre.
// GOPT holds the gradient of the quadratic model at XBASE+XOPT.
// HQ holds the explicit second derivatives of the quadratic model.
// PQ contains the parameters of the implicit second derivatives of the
// quadratic model.
// BMAT holds the last N columns of H.
// ZMAT holds the factorization of the leading NPT by NPT submatrix of H,
// this factorization being ZMAT times ZMAT^T, which provides both the
// correct rank and positive semi-definiteness.
// NDIM is the first dimension of BMAT and has the value NPT+N.
// XNEW is chosen by SUBROUTINE TRSBOX or ALTMOV. Usually XBASE+XNEW is the
// vector of variables for the next call of CALFUN. XNEW also satisfies
// the SL and SU constraints in the way that has just been mentioned.
// XALT is an alternative to XNEW, chosen by ALTMOV, that may replace XNEW
// in order to increase the denominator in the updating of UPDATE.
// D is reserved for a trial step from XOPT, which is usually XNEW-XOPT.
// VLAG contains the values of the Lagrange functions at a new point X.
// They are part of a product that requires VLAG to be of length NDIM.
// W is a one-dimensional array that is used for working space. Its length
// must be at least 3*NDIM = 3*(NPT+N).
var xbase = new double[1 + n];
var xpt = new double[1 + npt,1 + n];
var fval = new double[1 + npt];
var xopt = new double[1 + n];
var gopt = new double[1 + n];
var hq = new double[1 + n * np / 2];
var pq = new double[1 + npt];
var bmat = new double[1 + ndim,1 + n];
var zmat = new double[1 + npt,1 + npt - np];
var xnew = new double[1 + n];
var xalt = new double[1 + n];
var d = new double[1 + n];
var vlag = new double[1 + ndim];
var wn = new double[1 + n];
var w2npt = new double[1 + 2 * npt];
var knew = 0;
var adelt = 0.0;
var alpha = 0.0;
var beta = 0.0;
var cauchy = 0.0;
var denom = 0.0;
var diffc = 0.0;
var ratio = 0.0;
var f = 0.0;
double distsq;
BobyqaExitStatus status;
// The call of PRELIM sets the elements of XBASE, XPT, FVAL, GOPT, HQ, PQ,
// BMAT and ZMAT for the first iteration, with the corresponding values of
// of NF and KOPT, which are the number of calls of CALFUN so far and the
// index of the interpolation point at the trust region centre. Then the
// initial XOPT is set too. The branch to label 720 occurs if MAXFUN is
// less than NPT. GOPT will be updated if KOPT is different from KBASE.
int nf, kopt;
PRELIM(calfun,n, npt, x, xl, xu, rhobeg, iprint, maxfun, xbase, xpt, fval, gopt, hq, pq, bmat, zmat, ndim, sl, su,
out nf, out kopt, logger);
var xoptsq = ZERO;
for (var i = 1; i <= n; ++i)
{
xopt[i] = xpt[kopt, i];
xoptsq += xopt[i] * xopt[i];
}
var fsave = fval[1];
if (nf < npt)
{
if (iprint > 0 && logger != null) logger.WriteLine(MaxIterationsText);
status = BobyqaExitStatus.MaximumIterationsReached;
goto L_720;
}
var kbase = 1;
// Complete the settings that are required for the iterative procedure.
var rho = rhobeg;
var delta = rho;
var nresc = nf;
var ntrits = 0;
var diffa = ZERO;
var diffb = ZERO;
var itest = 0;
var nfsav = nf;
// Update GOPT if necessary before the first iteration and after each
// call of RESCUE that makes a call of CALFUN.
L_20:
if (kopt != kbase)
{
var ih = 0;
for (var j = 1; j <= n; ++j)
{
for (var i = 1; i <= j; ++i)
{
ih = ih + 1;
if (i < j) gopt[j] += hq[ih] * xopt[i];
gopt[i] += hq[ih] * xopt[j];
}
}
if (nf > npt)
{
for (var k = 1; k <= npt; ++k)
{
var temp = ZERO;
for (var j = 1; j <= n; ++j) temp += xpt[k, j] * xopt[j];
temp *= pq[k];
for (var i = 1; i <= n; ++i) gopt[i] += temp * xpt[k, i];
}
}
}
// Generate the next point in the trust region that provides a small value
// of the quadratic model subject to the constraints on the variables.
// The integer NTRITS is set to the number "trust region" iterations that
// have occurred since the last "alternative" iteration. If the length
// of XNEW-XOPT is less than HALF*RHO, however, then there is a branch to
// label 650 or 680 with NTRITS=-1, instead of calculating F at XNEW.
L_60:
var gnew = new double[1 + n];
double dsq, crvmin;
TRSBOX(n, npt, xpt, xopt, gopt, hq, pq, sl, su, delta, xnew, d, gnew, out dsq, out crvmin);
var dnorm = Math.Min(delta, Math.Sqrt(dsq));
if (dnorm < HALF * rho)
{
ntrits = -1;
distsq = TEN * TEN * rho * rho;
if (nf <= nfsav + 2) goto L_650;
// The following choice between labels 650 and 680 depends on whether or
// not our work with the current RHO seems to be complete. Either RHO is
// decreased or termination occurs if the errors in the quadratic model at
// the last three interpolation points compare favourably with predictions
// of likely improvements to the model within distance HALF*RHO of XOPT.
var errbig = Math.Max(diffa, Math.Max(diffb, diffc));
var frhosq = 0.125 * rho * rho;
if (crvmin > ZERO && errbig > frhosq * crvmin) goto L_650;
var bdtol = errbig / rho;
for (var j = 1; j <= n; ++j)
{
var bdtest = bdtol;
if (xnew[j] == sl[j]) bdtest = gnew[j];
if (xnew[j] == su[j]) bdtest = -gnew[j];
if (bdtest < bdtol)
{
var curv = hq[(j + j * j) / 2];
for (var k = 1; k <= npt; ++k)
{
curv = curv + pq[k] * xpt[k, j] * xpt[k, j];
}
bdtest = bdtest + HALF * curv * rho;
if (bdtest < bdtol) goto L_650;
}
}
goto L_680;
}
++ntrits;
// Severe cancellation is likely to occur if XOPT is too far from XBASE.
// If the following test holds, then XBASE is shifted so that XOPT becomes
// zero. The appropriate changes are made to BMAT and to the second
// derivatives of the current model, beginning with the changes to BMAT
// that do not depend on ZMAT. VLAG is used temporarily for working space.
L_90:
if (dsq <= 1.0E-3 * xoptsq)
{
var fracsq = 0.25 * xoptsq;
var sumpq = ZERO;
for (var k = 1; k <= npt; ++k)
{
sumpq += pq[k];
var sum = -HALF * xoptsq;
for (var i = 1; i <= n; ++i) sum += xpt[k, i] * xopt[i];
w2npt[k] = sum;
var temp = fracsq - HALF * sum;
for (var i = 1; i <= n; ++i)
{
wn[i] = bmat[k, i];
vlag[i] = sum * xpt[k, i] + temp * xopt[i];
var ip = npt + i;
for (var j = 1; j <= i; ++j) bmat[ip, j] += wn[i] * vlag[j] + vlag[i] * wn[j];
}
}
// Then the revisions of BMAT that depend on ZMAT are calculated.
for (var jj = 1; jj <= nptm; ++jj)
{
var sumz = ZERO;
var sumw = ZERO;
for (var k = 1; k <= npt; ++k)
{
sumz += zmat[k, jj];
vlag[k] = w2npt[k] * zmat[k, jj];
sumw += vlag[k];
}
for (var j = 1; j <= n; ++j)
{
var sum = (fracsq * sumz - HALF * sumw) * xopt[j];
for (var k = 1; k <= npt; ++k) sum += vlag[k] * xpt[k, j];
wn[j] = sum;
for (var k = 1; k <= npt; ++k) bmat[k, j] += sum * zmat[k, jj];
}
for (var i = 1; i <= n; ++i)
{
var ip = i + npt;
var temp = wn[i];
for (var j = 1; j <= i; ++j) bmat[ip, j] += temp * wn[j];
}
}
// The following instructions complete the shift, including the changes
// to the second derivative parameters of the quadratic model.
var ih = 0;
for (var j = 1; j <= n; ++j)
{
wn[j] = -HALF * sumpq * xopt[j];
for (var k = 1; k <= npt; ++k)
{
wn[j] += pq[k] * xpt[k, j];
xpt[k, j] -= xopt[j];
}
for (var i = 1; i <= j; ++i)
{
hq[++ih] += wn[i] * xopt[j] + xopt[i] * wn[j];
bmat[npt + i, j] = bmat[npt + j, i];
}
}
for (var i = 1; i <= n; ++i)
{
xbase[i] += xopt[i];
xnew[i] -= xopt[i];
sl[i] -= xopt[i];
su[i] -= xopt[i];
xopt[i] = ZERO;
}
xoptsq = ZERO;
}
if (ntrits == 0) goto L_210;
goto L_230;
// XBASE is also moved to XOPT by a call of RESCUE. This calculation is
// more expensive than the previous shift, because new matrices BMAT and
// ZMAT are generated from scratch, which may include the replacement of
// interpolation points whose positions seem to be causing near linear
// dependence in the interpolation conditions. Therefore RESCUE is called
// only if rounding errors have reduced by at least a factor of two the
// denominator of the formula for updating the H matrix. It provides a
// useful safeguard, but is not invoked in most applications of BOBYQA.
L_190:
nfsav = nf;
kbase = kopt;
RESCUE(calfun, n, npt, xl, xu, iprint, maxfun, xbase, xpt, fval, xopt, gopt, hq, pq, bmat, zmat, ndim, sl,
su, ref nf, delta, ref kopt, vlag, logger);
// XOPT is updated now in case the branch below to label 720 is taken.
// Any updating of GOPT occurs after the branch below to label 20, which
// leads to a trust region iteration as does the branch to label 60.
xoptsq = ZERO;
if (kopt != kbase)
{
for (var i = 1; i <= n; ++i)
{
xopt[i] = xpt[kopt, i];
xoptsq = xoptsq + xopt[i] * xopt[i];
}
}
if (nf < 0)
{
nf = maxfun;
if (iprint > 0 && logger != null) logger.WriteLine(MaxIterationsText);
status = BobyqaExitStatus.MaximumIterationsReached;
goto L_720;
}
nresc = nf;
if (nfsav < nf)
{
nfsav = nf;
goto L_20;
}
if (ntrits > 0) goto L_60;
// Pick two alternative vectors of variables, relative to XBASE, that
// are suitable as new positions of the KNEW-th interpolation point.
// Firstly, XNEW is set to the point on a line through XOPT and another
// interpolation point that minimizes the predicted value of the next
// denominator, subject to ||XNEW - XOPT|| .LEQ. ADELT and to the SL
// and SU bounds. Secondly, XALT is set to the best feasible point on
// a constrained version of the Cauchy step of the KNEW-th Lagrange
// function, the corresponding value of the square of this function
// being returned in CAUCHY. The choice between these alternatives is
// going to be made when the denominator is calculated.
L_210:
ALTMOV(n, npt, xpt, xopt, bmat, zmat, sl, su, kopt, knew, adelt, xnew, xalt, out alpha, out cauchy);
for (var i = 1; i <= n; ++i) d[i] = xnew[i] - xopt[i];
// Calculate VLAG and BETA for the current choice of D. The scalar
// product of D with XPT(K,.) is going to be held in W(NPT+K) for
// use when VQUAD is calculated.
L_230:
for (var k = 1; k <= npt; ++k)
{
var suma = ZERO;
var sumb = ZERO;
var sum = ZERO;
for (var j = 1; j <= n; ++j)
{
suma += xpt[k, j] * d[j];
sumb += xpt[k, j] * xopt[j];
sum += bmat[k, j] * d[j];
}
w2npt[k] = suma * (HALF * suma + sumb);
vlag[k] = sum;
w2npt[npt + k] = suma;
}
beta = ZERO;
for (var jj = 1; jj <= nptm; ++jj)
{
var sum = ZERO;
for (var k = 1; k <= npt; ++k) sum += zmat[k, jj] * w2npt[k];
beta -= sum * sum;
for (var k = 1; k <= npt; ++k) vlag[k] += sum * zmat[k, jj];
}
dsq = ZERO;
var bsum = ZERO;
var dx = ZERO;
for (var j = 1; j <= n; ++j)
{
dsq = dsq + d[j] * d[j];
var sum = ZERO;
for (var k = 1; k <= npt; ++k) sum += w2npt[k] * bmat[k, j];
bsum += sum * d[j];
var jp = npt + j;
for (var i = 1; i <= n; ++i) sum += bmat[jp, i] * d[i];
vlag[jp] = sum;
bsum += sum * d[j];
dx += d[j] * xopt[j];
}
beta += dx * dx + dsq * (xoptsq + dx + dx + HALF * dsq) - bsum;
vlag[kopt] += ONE;
// If NTRITS is zero, the denominator may be increased by replacing
// the step D of ALTMOV by a Cauchy step. Then RESCUE may be called if
// rounding errors have damaged the chosen denominator.
if (ntrits == 0)
{
denom = vlag[knew] * vlag[knew] + alpha * beta;
if (denom < cauchy && cauchy > ZERO)
{
for (var i = 1; i <= n; ++i)
{
xnew[i] = xalt[i];
d[i] = xnew[i] - xopt[i];
}
cauchy = ZERO;
goto L_230;
}
if (denom <= HALF * vlag[knew] * vlag[knew])
{
if (nf > nresc) goto L_190;
if (iprint > 0 && logger != null) logger.WriteLine(DenominatorCancellationText);
status = BobyqaExitStatus.DenominatorCancellation;
goto L_720;
}
}
// Alternatively, if NTRITS is positive, then set KNEW to the index of
// the next interpolation point to be deleted to make room for a trust
// region step. Again RESCUE may be called if rounding errors have damaged
// the chosen denominator, which is the reason for attempting to select
// KNEW before calculating the next value of the objective function.
else
{
var delsq = delta * delta;
var scaden = ZERO;
var biglsq = ZERO;
knew = 0;
for (var k = 1; k <= npt; ++k)
{
if (k == kopt) continue;
var hdiag = ZERO;
for (var jj = 1; jj <= nptm; ++jj) hdiag += zmat[k, jj] * zmat[k, jj];
var den = beta * hdiag + vlag[k] * vlag[k];
distsq = ZERO;
for (var j = 1; j <= n; ++j) distsq += Math.Pow(xpt[k, j] - xopt[j], 2.0);
var temp = Math.Max(ONE, Math.Pow(distsq / delsq, 2.0));
if (temp * den > scaden)
{
scaden = temp * den;
knew = k;
denom = den;
}
biglsq = Math.Max(biglsq, temp * vlag[k] * vlag[k]);
}
if (scaden <= HALF * biglsq)
{
if (nf > nresc) goto L_190;
if (iprint > 0 && logger != null) logger.WriteLine(DenominatorCancellationText);
status = BobyqaExitStatus.DenominatorCancellation;
goto L_720;
}
}
// Put the variables for the next calculation of the objective function
// in XNEW, with any adjustments for the bounds.
// Calculate the value of the objective function at XBASE+XNEW, unless
// the limit on the number of calculations of F has been reached.
L_360:
for (var i = 1; i <= n; ++i)
{
x[i] = Math.Min(Math.Max(xl[i], xbase[i] + xnew[i]), xu[i]);
if (xnew[i] == sl[i]) x[i] = xl[i];
if (xnew[i] == su[i]) x[i] = xu[i];
}
if (nf >= maxfun)
{
if (iprint > 0 && logger != null) logger.WriteLine(MaxIterationsText);
status = BobyqaExitStatus.MaximumIterationsReached;
goto L_720;
}
++nf;
f = calfun(n, x);
if (iprint == 3 && logger != null) logger.WriteLine(IterationOutputFormat, nf, f, x.ToString(n));
if (ntrits == -1)
{
fsave = f;
status = BobyqaExitStatus.Normal;
goto L_720;
}
// Use the quadratic model to predict the change in F due to the step D,
// and set DIFF to the error of this prediction.
var fopt = fval[kopt];
var vquad = ZERO;
{
var ih = 0;
for (var j = 1; j <= n; ++j)
{
vquad += d[j] * gopt[j];
for (var i = 1; i <= j; ++i)
vquad += hq[++ih] * (i == j ? HALF : ONE) * d[i] * d[j];
}
}
for (var k = 1; k <= npt; ++k) vquad += HALF * pq[k] * w2npt[npt + k] * w2npt[npt + k];
var diff = f - fopt - vquad;
diffc = diffb;
diffb = diffa;
diffa = Math.Abs(diff);
if (dnorm > rho) nfsav = nf;
// Pick the next value of DELTA after a trust region step.
if (ntrits > 0)
{
if (vquad >= ZERO)
{
if (iprint > 0 && logger != null) logger.WriteLine(TrustRegionStepFailureText);
status = BobyqaExitStatus.TrustRegionStepReductionFailure;
goto L_720;
}
ratio = (f - fopt) / vquad;
if (ratio <= TENTH)
delta = Math.Min(HALF * delta, dnorm);
else if (ratio <= 0.7)
delta = Math.Max(HALF * delta, dnorm);
else
delta = Math.Max(HALF * delta, dnorm + dnorm);
if (delta <= 1.5 * rho) delta = rho;
// Recalculate KNEW and DENOM if the new F is less than FOPT.
if (f < fopt)
{
var ksav = knew;
var densav = denom;
var delsq = delta * delta;
var scaden = ZERO;
var biglsq = ZERO;
knew = 0;
for (var k = 1; k <= npt; ++k)
{
var hdiag = ZERO;
for (var jj = 1; jj <= nptm; ++jj) hdiag += zmat[k, jj] * zmat[k, jj];
var den = beta * hdiag + vlag[k] * vlag[k];
distsq = ZERO;
for (var j = 1; j <= n; ++j) distsq += Math.Pow(xpt[k, j] - xnew[j], 2.0);
var temp = Math.Max(ONE, Math.Pow(distsq / delsq, 2.0));
if (temp * den > scaden)
{
scaden = temp * den;
knew = k;
denom = den;
}
biglsq = Math.Max(biglsq, temp * vlag[k] * vlag[k]);
}
if (scaden <= HALF * biglsq)
{
knew = ksav;
denom = densav;
}
}
}
// Update BMAT and ZMAT, so that the KNEW-th interpolation point can be
// moved. Also update the second derivative terms of the model.
var w = new double[1 + ndim];
UPDATE(n, npt, bmat, zmat, ndim, vlag, beta, denom, knew, w);
var pqold = pq[knew];
pq[knew] = ZERO;
{
var ih = 0;
for (var i = 1; i <= n; ++i)
{
var temp = pqold * xpt[knew, i];
for (var j = 1; j <= i; ++j) hq[++ih] += temp * xpt[knew, j];
}
}
for (var jj = 1; jj <= nptm; ++jj)
{
var temp = diff * zmat[knew, jj];
for (var k = 1; k <= npt; ++k) pq[k] += temp * zmat[k, jj];
}
// Include the new interpolation point, and make the changes to GOPT at
// the old XOPT that are caused by the updating of the quadratic model.
fval[knew] = f;
for (var i = 1; i <= n; ++i)
{
xpt[knew, i] = xnew[i];
wn[i] = bmat[knew, i];
}
for (var k = 1; k <= npt; ++k)
{
var suma = ZERO;
for (var jj = 1; jj <= nptm; ++jj) suma += zmat[knew, jj] * zmat[k, jj];
var sumb = ZERO;
for (var j = 1; j <= n; ++j) sumb += xpt[k, j] * xopt[j];
var temp = suma * sumb;
for (var i = 1; i <= n; ++i) wn[i] += temp * xpt[k, i];
}
for (var i = 1; i <= n; ++i) gopt[i] += diff * wn[i];
// Update XOPT, GOPT and KOPT if the new calculated F is less than FOPT.
if (f < fopt)
{
kopt = knew;
xoptsq = ZERO;
var ih = 0;
for (var j = 1; j <= n; ++j)
{
xopt[j] = xnew[j];
xoptsq += xopt[j] * xopt[j];
for (var i = 1; i <= j; ++i)
{
++ih;
if (i < j) gopt[j] += +hq[ih] * d[i];
gopt[i] += hq[ih] * d[j];
}
}
for (var k = 1; k <= npt; ++k)
{
var temp = ZERO;
for (var j = 1; j <= n; ++j) temp += xpt[k, j] * d[j];
temp *= pq[k];
for (var i = 1; i <= n; ++i) gopt[i] += temp * xpt[k, i];
}
}
// Calculate the parameters of the least Frobenius norm interpolant to
// the current data, the gradient of this interpolant at XOPT being put
// into VLAG(NPT+I), I=1,2,...,N.
if (ntrits > 0)
{
for (var k = 1; k <= npt; ++k)
{
vlag[k] = fval[k] - fval[kopt];
w2npt[k] = ZERO;
}
for (var j = 1; j <= nptm; ++j)
{
var sum = ZERO;
for (var k = 1; k <= npt; ++k) sum += zmat[k, j] * vlag[k];
for (var k = 1; k <= npt; ++k) w2npt[k] = w2npt[k] + sum * zmat[k, j];
}
for (var k = 1; k <= npt; ++k)
{
var sum = ZERO;
for (var j = 1; j <= n; ++j) sum += xpt[k, j] * xopt[j];
w2npt[k + npt] = w2npt[k];
w2npt[k] *= sum;
}
var gqsq = ZERO;
var gisq = ZERO;
for (var i = 1; i <= n; ++i)
{
var sum = ZERO;
for (var k = 1; k <= npt; ++k) sum += bmat[k, i] * vlag[k] + xpt[k, i] * w2npt[k];
if (xopt[i] == sl[i])
{
gqsq += Math.Pow(Math.Min(ZERO, gopt[i]), 2.0);
gisq += Math.Pow(Math.Min(ZERO, sum), 2.0);
}
else if (xopt[i] == su[i])
{
gqsq += Math.Pow(Math.Max(ZERO, gopt[i]), 2.0);
gisq += Math.Pow(Math.Max(ZERO, sum), 2.0);
}
else
{
gqsq += gopt[i] * gopt[i];
gisq += sum * sum;
}
vlag[npt + i] = sum;
}
// Test whether to replace the new quadratic model by the least Frobenius
// norm interpolant, making the replacement if the test is satisfied.
++itest;
if (gqsq < TEN * gisq) itest = 0;
if (itest >= 3)
{
for (var i = 1; i <= Math.Max(npt, nh); ++i)
{
if (i <= n) gopt[i] = vlag[npt + i];
if (i <= npt) pq[i] = w2npt[npt + i];
if (i <= nh) hq[i] = ZERO;
itest = 0;
}
}
}
// If a trust region step has provided a sufficient decrease in F, then
// branch for another trust region calculation. The case NTRITS=0 occurs
// when the new interpolation point was reached by an alternative step.
if (ntrits == 0 || f <= fopt + TENTH * vquad) goto L_60;
// Alternatively, find out if the interpolation points are close enough
// to the best point so far.
distsq = Math.Max(TWO * TWO * delta * delta, TEN * TEN * rho * rho);
L_650: