Creating a custom problem

Now that we have that out of the way, let's create a custom problem based upon our base problem class. The code will look like the following example.

The following is the two-dimensional Rosenbrock problem with some example constraints; its optimal feasible solution seems to be as follows:

<summary>
a ~ 1.5937
b ~ 2.5416
</summary>
Class CustomProblem :Problem
{
public double GetA(double[] parameters)
{
return parameters[0];
}
public double GetB(double[] parameters)
{
return parameters[1];
}

Here, the base-class overrides the name of the optimizer, as follows:

public override string Name => "CustomProblem";

The dimensionality of the problem is as follows:

public override int Dimensionality => 2;
double[] _lowerBound = { -100, -100 };

 The following is the lower search-space boundary:

public override double[] LowerBound => _lowerBound;
double[] _upperBound = { 100, 100 };

The following is the upper search-space boundary:

public override double[] UpperBound => _upperBound;

The lower initialization boundary is as follows:

public override double[] LowerInit => LowerBound;

The upper initialization boundary is as follows:

public override double[] UpperInit => UpperBound;

The minimum possible fitness for this problem is worked out using the following line:

public override double MinFitness => 0;

 The acceptable fitness threshold is as follows:

public override double AcceptableFitness => 0.4;
string[] _parameterName = { "a", "b" };

The names of the parameters for the problem are as follows:

public override string[] ParameterName => _parameterName;

To compute and return fitness for the given parameters, use the following code:

public override double Fitness(double[] x)
{
Debug.Assert(x != null && x.Length == Dimensionality);
double a = GetA(x);
double b = GetB(x);
double t1 = 1 - a;
double t2 = b - a * a;
return t1 * t1 + 100 * t2 * t2;
}

To enforce and evaluate constraints, use the following code:

public override bool EnforceConstraints(ref double[] x)
{
// Enforce boundaries.
SwarmOps.Tools.Bound(ref x, LowerBound, UpperBound);
return Feasible(x);
}
// Evaluate constraints.
public override bool Feasible(double[] x)
{
Debug.Assert(x != null && x.Length == Dimensionality);
double a = GetA(x);
double b = GetB(x);
// Radius.
double r = Math.Sqrt(a * a + b * b);
return ((r < 0.7) || ((r > 3) && (r < 5))) && (a < b * b);
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset