I am attempting to use Accord.NET Cobyla to optimize a constrained problem with a black-box target function which is computationally expensive to run. Because of that, I want to control convergence myself, so the function being optimized should check how close the target is to the expected minimum, and terminate optimization as soon as it is within an acceptable error margin, or alternatively run to the MaxIterations limit and then terminate.
According to the Accord.NET Cobyla docs, termination can be scheduled with the CancellationToken. However, CancellationTokenSource is not provided, so I created a new one and injected it into cobyla
object, but for some reason that doesn’t cancel anything even when it is set before cobyla.Minimize()
is executed.
To investigate this, I decompiled Cobyla and BaseOptimizationMethod classes, and found the Token property, but as far as I can tell – it isn’t used anywhere, which is probably why it’s not working. I am not sure if this is developer oversight or if I’m missing something. Below is my code of this attempt to test cancellation. Am I doing it wrong?
using Accord.Math.Optimization;
using System.Diagnostics;
double BlackBoxFunction(double[] x)
{
return 10 * Math.Pow(x[0] + 1, 2) + Math.Pow(x[1], 2); //placeholder
}
var function = new NonlinearObjectiveFunction(2, BlackBoxFunction);
var constraints = new[]
{
new NonlinearConstraint(2, x => x[1] - x[0] * x[0] >= 0),
new NonlinearConstraint(2, x => 1 - x[0] * x[0] - x[1] * x[1] >= 0),
};
var cobyla = new Cobyla(function, constraints);
CancellationTokenSource source = new();
cobyla.Token = source.Token;
source.Cancel();
bool success = cobyla.Minimize();
double minimum = cobyla.Value;
double[] solution = cobyla.Solution;
int iterations = cobyla.Iterations;