Problem: Ant Lion Optimizer Implementation in MATLAB

The problem involves implementing MATLAB functions for objective functions (F1-F23), helpers (initialization, RouletteWheelSelection, Random_walk_around_antlion), a function details getter, and the Ant Lion Optimizer (ALO) algorithm to find optimal solutions.


Input/Output: The problem receives function specifications (names, signatures, algorithm steps, test cases) for Ufun, F1-F23, Get_Functions_details, initialization, RouletteWheelSelection, Random_walk_around_antlion, and ALO. It produces MATLAB code for each function that implements the specified logic, follows the given signatures, and passes the provided test cases.

Required dependencies:

Sub-steps:
step_number: 1
step_description_prompt: Please write a MATLAB function named Ufun that implements an element-wise piecewise function calculation. The function is defined as function o = Ufun(x, a, k, m). Compute the output o using element-wise operations: o equals k multiplied by (x - a) raised to the power of m, multiplied by the logical array (x > a), plus k multiplied by (-x - a) raised to the power of m, multiplied by the logical array (x < -a). For positions where neither x > a nor x < -a is true, the corresponding values in o will be 0 since logical conditions in MATLAB evaluate to 0 when false.
function_header: function o=Ufun(x,a,k,m)

end
test_cases: clear; clc;
rng(42);
correct = 32.0000;
x = [-3, -1, 0, 1, 3];
a = 1;
k = 2;
m = 3;
result = Ufun(x, a, k, m);
val = sum(result);
if val~=correct
    error('Wrong')
end
correct = 500.0000;
x = [-4, -6, 2, 3, 5];
a = 2;
k = 5;
m = 3;
result = Ufun(x, a, k, m);
val = sum(result);
if val~=correct
    error('Wrong')
end
correct = 1302.00000;
x = [-1, -2, 5, 6, 4];
a = 1;
k = 6;
m = 3;
result = Ufun(x, a, k, m);
val = sum(result);
if val~=correct
    error('Wrong')
end
disp('Completely right!')

step_number: 2
step_description_prompt: Please write MATLAB code to generate a function named F1 that implements the sum of the squares of the input vector elements. The function definition is function o = F1(x). The algorithm flow is: Compute the sum of the element-wise square of x using sum(x.^2) and assign the result to o.

Please write MATLAB code to generate a function named F2 that implements the sum of absolute values of the input vector plus the product of absolute values of the input vector. The function definition is function o = F2(x). The algorithm flow is: Calculate sum(abs(x)) and prod(abs(x)), then add these two results together and assign to o.

Please write MATLAB code to generate a function named F3 that implements the sum of the squares of cumulative sums of the input vector. The function definition is function o = F3(x). The algorithm flow is: First, get the number of columns of x as dim = size(x, 2). Initialize o to 0. Then loop from i = 1 to dim: for each i, compute the cumulative sum of the first i elements of x using sum(x(1:i)), square this cumulative sum, and add it to o.

Please write MATLAB code to generate a function named F4 that implements the maximum absolute value of the input vector. The function definition is function o = F4(x). The algorithm flow is: Compute the absolute values of all elements in x using abs(x), then find the maximum value among these absolute values using max() and assign to o.

Please write MATLAB code to generate a function named F5 that implements the Rosenbrock function for the input vector. The function definition is function o = F5(x). The algorithm flow is: First, get the number of columns of x as dim = size(x, 2). Then compute the sum of 100*(x(2:dim) - x(1:dim-1).^2).^2 + (x(1:dim-1) - 1).^2 using sum() and assign to o.

Please write MATLAB code to generate a function named F6 that implements the sum of the squares of absolute values of (input elements plus 0.5). The function definition is function o = F6(x). The algorithm flow is: For each element in x, compute (x + 0.5) element-wise, take the absolute value using abs(), square the result element-wise, then sum all these values using sum() and assign to o.

Please write MATLAB code to generate a function named F7 that implements the sum of (element indices multiplied by the fourth power of input elements) plus a random number between 0 and 1. The function definition is function o = F7(x). The algorithm flow is: First, get the number of columns of x as dim = size(x, 2). Create a vector of indices from 1 to dim as idx = [1:dim]. Compute the element-wise fourth power of x using x.^4, multiply by idx element-wise (idx .* x.^4), sum these products using sum(), then add a random number generated by rand() (which is in [0,1]) and assign the total to o.

Please write MATLAB code to generate a function named F8 that implements the sum of (-input elements multiplied by the sine of the square root of absolute input elements). The function definition is function o = F8(x). The algorithm flow is: For each element in x, compute the absolute value using abs(), take the square root using sqrt(), compute the sine using sin(), multiply by -x element-wise, then sum all these values using sum() and assign to o.
test_cases: clear; clc;
rng(42);
correct = 6659.399639;
x = [1.2, -0.5, 2.3, -1.8, 0.7];
val = F1(x) + F2(x) + F3(x) + F4(x) + F5(x) + F6(x) + F7(x) + F8(x);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong')
end
correct = 116785.710695;
x = [1.6, -0.3, 5.6, -1.7, 0.9];
val = F1(x) + F2(x) + F3(x) + F4(x) + F5(x) + F6(x) + F7(x) + F8(x);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong')
end
correct = 24863.690416;
x = [2.5, -1.6, 2.6, -3.2, 1.3];
val = F1(x) + F2(x) + F3(x) + F4(x) + F5(x) + F6(x) + F7(x) + F8(x);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong')
end
disp('Completely right!')

step_number: 3
step_description_prompt: Please write MATLAB code to generate functions named F9, F10, F11, F12, F13, F14, F15, F16, F17 that implement the following functions respectively. Assume any called functions (like Ufun) are already defined and do not need to be reimplemented.

1. Function F9:
   - Input: Vector x (real numbers).
   - Steps:
     a. Compute dim = size(x,2).
     b. Compute the sum of (x(i)^2 - 10*cos(2*pi*x(i))) for all elements in x.
     c. Compute o = (result from step b) + 10*dim.
   - Output: o.

2. Function F10:
   - Input: Vector x (real numbers).
   - Steps:
     a. Compute dim = size(x,2).
     b. Compute term1 = -20 * exp(-0.2 * sqrt(sum(x.^2)/dim)).
     c. Compute term2 = -exp(sum(cos(2*pi*x))/dim).
     d. Compute o = term1 + term2 + 20 + exp(1).
   - Output: o.

3. Function F11:
   - Input: Vector x (real numbers).
   - Steps:
     a. Compute dim = size(x,2).
     b. Compute term1 = sum(x.^2)/4000.
     c. Compute term2 = prod(cos(x./sqrt(1:dim))).
     d. Compute o = term1 - term2 + 1.
   - Output: o.

4. Function F12:
   - Input: Vector x (real numbers).
   - Steps:
     a. Compute dim = size(x,2).
     b. Compute term1 = 10 * (sin(pi*(1 + (x(1)+1)/4)))^2.
     c. Compute term2 = sum( ((x(1:dim-1)+1)/4).^2 .* (1 + 10*(sin(pi*(1 + (x(2:dim)+1)/4))).^2 ) ).
     d. Compute term3 = ((x(dim)+1)/4)^2.
     e. Compute term4 = (pi/dim) * (term1 + term2 + term3).
     f. Compute term5 = sum(Ufun(x,10,100,4)).
     g. Compute o = term4 + term5.
   - Output: o.

5. Function F13:
   - Input: Vector x (real numbers).
   - Steps:
     a. Compute dim = size(x,2).
     b. Compute term1 = (sin(3*pi*x(1)))^2.
     c. Compute term2 = sum( (x(1:dim-1)-1).^2 .* (1 + (sin(3*pi*x(2:dim))).^2 ) ).
     d. Compute term3 = (x(dim)-1)^2 * (1 + (sin(2*pi*x(dim))).^2 ).
     e. Compute term4 = 0.1 * (term1 + term2 + term3).
     f. Compute term5 = sum(Ufun(x,5,100,4)).
     g. Compute o = term4 + term5.
   - Output: o.

6. Function F14:
   - Input: Vector x (real numbers).
   - Predefined: aS = [-32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32; -32 -32 -32 -32 -32 -16 -16 -16 -16 -16 0 0 0 0 0 16 16 16 16 16 32 32 32 32 32].
   - Steps:
     a. Initialize bS as a 1x25 vector.
     b. For j=1:25, compute bS(j) = sum( (x' - aS(:,j)).^6 ).
     c. Compute sum_term = sum(1./([1:25] + bS)).
     d. Compute o = (1/500 + sum_term)^(-1).
   - Output: o.

7. Function F15:
   - Input: Vector x (real numbers, length 4).
   - Predefined: aK = [0.1957 0.1947 0.1735 0.16 0.0844 0.0627 0.0456 0.0342 0.0323 0.0235 0.0246]; bK = 1./[0.25 0.5 1 2 4 6 8 10 12 14 16].
   - Steps:
     a. Compute the sum of (aK(j) - (x(1)*(bK(j)^2 + x(2)*bK(j)))/(bK(j)^2 + x(3)*bK(j) + x(4)))^2 for j=1 to 11.
     b. Set o as the result from step a.
   - Output: o.

8. Function F16:
   - Input: Vector x (real numbers, length 2).
   - Steps:
     a. Compute o = 4*x(1)^2 - 2.1*x(1)^4 + (x(1)^6)/3 + x(1)*x(2) - 4*x(2)^2 + 4*x(2)^4.
   - Output: o.

9. Function F17:
   - Input: Vector x (real numbers, length 2).
   - Steps:
     a. Compute term1 = (x(2) - (x(1)^2)*5.1/(4*pi^2) + (5/pi)*x(1) - 6)^2.
     b. Compute term2 = 10*(1 - 1/(8*pi))*cos(x(1)).
     c. Compute o = term1 + term2 + 10.
   - Output: o.

Each function must use the exact name specified, follow the steps precisely, and return the correct output as described.
test_cases: clear; clc;
rng(42);
correct = 143.557619;
x5 = [0.5, 1.2, 0.3, 1.5, 0.8];
x2 = [0.5, 1.2];
x4 = [0.3, 0.7, 1.5, 2.1];
val = F9(x5) + F10(x5) + F11(x5) + F12(x5) + F13(x5) + F14(x2) + F15(x4) + F16(x2) + F17(x2);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
correct = 148.143694;
x5 = [0.6, 2.2, 2.2, 1.6, 0.9];
x2 = [0.1, 1.2];
x4 = [0.3, 0.2, 2.3, 1.1];
val = F9(x5) + F10(x5) + F11(x5) + F12(x5) + F13(x5) + F14(x2) + F15(x4) + F16(x2) + F17(x2);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
correct = 131.306685;
x5 = [0.8, 1.4, 0.3, 1.2, 0.8];
x2 = [0.2, 1.1];
x4 = [0.4, 0.3, 1.1, 2.1];
val = F9(x5) + F10(x5) + F11(x5) + F12(x5) + F13(x5) + F14(x2) + F15(x4) + F16(x2) + F17(x2);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 4
step_description_prompt: Please write MATLAB functions with the exact names F18, F19, F20, F21, F22, F23. Each function takes a vector x as input and returns a scalar o.

1. For function F18:
- Function definition: function o = F18(x)
- Compute o as the product of two terms. The first term is 1 + ((x(1) + x(2) + 1)^2) * (19 - 14*x(1) + 3*(x(1)^2) - 14*x(2) + 6*x(1)*x(2) + 3*(x(2)^2)). The second term is 30 + ((2*x(1) - 3*x(2))^2) * (18 - 32*x(1) + 12*(x(1)^2) + 48*x(2) - 36*x(1)*x(2) + 27*(x(2)^2)). Multiply these two terms to get o.

2. For function F19:
- Function definition: function o = F19(x)
- Define matrices: aH = [3 10 30; .1 10 35; 3 10 30; .1 10 35], cH = [1 1.2 3 3.2], pH = [.3689 .117 .2673; .4699 .4387 .747; .1091 .8732 .5547; .03815 .5743 .8828]. Initialize o to 0. Loop i from 1 to 4: o = o - cH(i) * exp(-sum(aH(i,:) .* ((x - pH(i,:)) .^ 2))).

3. For function F20:
- Function definition: function o = F20(x)
- Define matrices: aH = [10 3 17 3.5 1.7 8; .05 10 17 .1 8 14; 3 3.5 1.7 10 17 8; 17 8 .05 10 .1 14], cH = [1 1.2 3 3.2], pH = [.1312 .1696 .5569 .0124 .8283 .5886; .2329 .4135 .8307 .3736 .1004 .9991; .2348 .1415 .3522 .2883 .3047 .6650; .4047 .8828 .8732 .5743 .1091 .0381]. Initialize o to 0. Loop i from 1 to 4: o = o - cH(i) * exp(-sum(aH(i,:) .* ((x - pH(i,:)) .^ 2))).

4. For function F21:
- Function definition: function o = F21(x)
- Define matrices: aSH = [4 4 4 4; 1 1 1 1; 8 8 8 8; 6 6 6 6; 3 7 3 7; 2 9 2 9; 5 5 3 3; 8 1 8 1; 6 2 6 2; 7 3.6 7 3.6], cSH = [.1 .2 .2 .4 .4 .6 .3 .7 .5 .5]. Initialize o to 0. Loop i from 1 to 5: o = o - ((x - aSH(i,:)) * (x - aSH(i,:))' + cSH(i)) ^ (-1).

5. For function F22:
- Function definition: function o = F22(x)
- Use the same aSH and cSH as F21. Initialize o to 0. Loop i from 1 to 7: o = o - ((x - aSH(i,:)) * (x - aSH(i,:))' + cSH(i)) ^ (-1).

6. For function F23:
- Function definition: function o = F23(x)
- Use the same aSH and cSH as F21. Initialize o to 0. Loop i from 1 to 10: o = o - ((x - aSH(i,:)) * (x - aSH(i,:))' + cSH(i)) ^ (-1).

All functions take a vector x as input. Ensure the matrices aH, cH, pH, aSH, cSH are defined exactly as given inside each function. The loops and calculations must follow the described steps precisely.
test_cases: clear; clc;
rng(42);
correct = 16649.063712;
x2 = [0.5, 1.2];  
x3 = [0.3, 0.7, 1.5]; 
x4 = [0.3, 0.7, 1.5, 2.1];
x6 = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2]; 
val = F18(x2) + F19(x3) + F20(x6) + F21(x4) + F22(x4) + F23(x4);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

correct = 17899.312189;
x2 = [0.6, 1.3];  
x3 = [0.5, 1.7, 1.2]; 
x4 = [0.1, 1.5, 1.6, 2.1];
x6 = [0.5, 0.2, 1.6, 0.8, 1.1, 1.2]; 
val = F18(x2) + F19(x3) + F20(x6) + F21(x4) + F22(x4) + F23(x4);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

correct = 42552.178761;
x2 = [0.2, 1.3];  
x3 = [1.3, 0.7, 1.3]; 
x4 = [2.2, 0.6, 1.2, 0.5];
x6 = [0.2, 0.1, 0.7, 0.2, 1.0, 1.1]; 
val = F18(x2) + F19(x3) + F20(x6) + F21(x4) + F22(x4) + F23(x4);
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 5
step_description_prompt: Please write a MATLAB function named Get_Functions_details that takes a string input F (representing a function identifier) and returns four outputs: lb (lower bound of the optimization problem), ub (upper bound), dim (problem dimension), and fobj (a handle to the corresponding objective function). The function maps each valid F (from 'F1' to 'F23') to predefined values for lb, ub, dim, and the handle of the corresponding pre-defined function (F1 to F23 are assumed to exist and do not need to be implemented here).
The function must have the exact signature: [lb, ub, dim, fobj] = Get_Functions_details(F).
Implement the function using a switch-case structure where each case corresponds to a function identifier (e.g., 'F1', 'F2', ..., 'F23'). For each case, assign the corresponding values as follows:
- Case 'F1': fobj = @F1; lb = -100; ub = 100; dim = 10;
- Case 'F2': fobj = @F2; lb = -10; ub = 10; dim = 10;
- Case 'F3': fobj = @F3; lb = -100; ub = 100; dim = 10;
- Case 'F4': fobj = @F4; lb = -100; ub = 100; dim = 10;
- Case 'F5': fobj = @F5; lb = -30; ub = 30; dim = 10;
- Case 'F6': fobj = @F6; lb = -100; ub = 100; dim = 10;
- Case 'F7': fobj = @F7; lb = -1.28; ub = 1.28; dim = 10;
- Case 'F8': fobj = @F8; lb = -500; ub = 500; dim = 10;
- Case 'F9': fobj = @F9; lb = -5.12; ub = 5.12; dim = 10;
- Case 'F10': fobj = @F10; lb = -32; ub = 32; dim = 10;
- Case 'F11': fobj = @F11; lb = -600; ub = 600; dim = 10;
- Case 'F12': fobj = @F12; lb = -50; ub = 50; dim = 10;
- Case 'F13': fobj = @F13; lb = -50; ub = 50; dim = 10;
- Case 'F14': fobj = @F14; lb = -65.536; ub = 65.536; dim = 2;
- Case 'F15': fobj = @F15; lb = -5; ub = 5; dim = 4;
- Case 'F16': fobj = @F16; lb = -5; ub = 5; dim = 2;
- Case 'F17': fobj = @F17; lb = [-5, 0]; ub = [10, 15]; dim = 2;
- Case 'F18': fobj = @F18; lb = -2; ub = 2; dim = 2;
- Case 'F19': fobj = @F19; lb = 0; ub = 1; dim = 3;
- Case 'F20': fobj = @F20; lb = 0; ub = 1; dim = 6;
- Case 'F21': fobj = @F21; lb = 0; ub = 10; dim = 4;
- Case 'F22': fobj = @F22; lb = 0; ub = 10; dim = 4;
- Case 'F23': fobj = @F23; lb = 0; ub = 10; dim = 4;
function_header: function [lb,ub,dim,fobj] = Get_Functions_details(F)

end
test_cases: clear; clc;
rng(42);
test_funcs = {'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', ...
              'F11', 'F12', 'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', ...
              'F20', 'F21', 'F22', 'F23'};
total = 0;
correct = 864.188863;
for i = 1:length(test_funcs)
    [lb, ub, dim, fobj] = Get_Functions_details(test_funcs{i});
    if isscalar(lb) && isscalar(ub)
        x = (lb + ub) / 2 * ones(1, dim);
    else
        x = (lb + ub) / 2;
    end
    fval = fobj(x);
    total = total + sum(lb(:)) + sum(ub(:)) + dim + fval;
end
tol = abs(total-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 6
step_description_prompt: Please write a MATLAB function named initialization that creates the first random population. The function is defined as function X=initialization(SearchAgents_no,dim,ub,lb). First, calculate Boundary_no as the number of columns of ub using size(ub,2). If Boundary_no == 1 (this means the boundaries of all variables are equal and the user entered a single number for both ub and lb), generate X as an SearchAgents_no-by-dim matrix where each element is computed by rand(SearchAgents_no,dim).*(ub-lb)+lb. If Boundary_no > 1 (this means each variable has a different lb and ub), loop over each dimension i from 1 to dim: get the upper bound ub_i for the i-th dimension as ub(i), get the lower bound lb_i for the i-th dimension as lb(i), then assign X(:,i) (the i-th column of X) as a column vector generated by rand(SearchAgents_no,1).*(ub_i-lb_i)+lb_i. Other functions called in the code are assumed to be already defined.
function_header: function X=initialization(SearchAgents_no,dim,ub,lb)

end
test_cases: clear; clc;
rng(42);

correct = 85.422048;
X1 = initialization(5, 3, 10, -5);
X2 = initialization(4, 3, [5,10,15], [-2,0,3]);
X3 = initialization(3, 2, 0, 0);
val = sum(X1(:)) + sum(X2(:)) + sum(X3(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

correct = 94.834255;
X1 = initialization(2, 5, 10, -7);
X2 = initialization(4, 3, [5,8,12], [-1,1,3]);
X3 = initialization(2, 2, 1, 4);
val = sum(X1(:)) + sum(X2(:)) + sum(X3(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

correct = 59.955864;
X1 = initialization(6, 2, 8, -8);
X2 = initialization(4, 3, [2,10,12], [-2,2,6]);
X3 = initialization(3, 4, 0, 1);
val = sum(X1(:)) + sum(X2(:)) + sum(X3(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 7
step_description_prompt: Please use MATLAB code to generate a function named RouletteWheelSelection that implements the Roulette Wheel Selection Algorithm. This function takes a set of weights (a vector) representing the probability of selection for each individual in a group of choices and returns the 1-based index of the chosen individual.
Function Definition: function choice = RouletteWheelSelection(weights)
Algorithm Flow: 1. Compute the cumulative sum of the input weights using cumsum(weights) and store the result in a variable named 'accumulation'. 2. Generate a random number 'p' by multiplying a uniformly distributed random number between 0 and 1 (generated by rand()) with the last element of 'accumulation' (which is the total sum of the weights). 3. Initialize a variable 'chosen_index' to -1. 4. Use a for loop to iterate over each index from 1 to the length of 'accumulation'. For each index, check if accumulation(index) is greater than 'p'. If this condition is true, set 'chosen_index' to the current index and break out of the loop immediately. 5. Assign the value of 'chosen_index' to the output variable 'choice'.
Note: The functions cumsum and rand called in the code are assumed to be already defined and do not need to be redefined.
function_header: function choice = RouletteWheelSelection(weights)

end
test_cases: clear; clc;
rng(42);

w1 = [1, 1, 1, 1];
w2 = [1, 2, 3, 4];
w3 = [1];
w4 = [5, 3, 1];

c1 = RouletteWheelSelection(w1);
c2 = RouletteWheelSelection(w2);
c3 = RouletteWheelSelection(w3);
c4 = RouletteWheelSelection(w4);

correct=2;
if c1~=correct
    error('Wrong')
end
correct=4;
if c2~=correct
    error('Wrong')
end
correct=1;
if c3~=correct
    error('Wrong')
end
correct=2;
if c4~=correct
    error('Wrong')
end
disp('Completely right!')

step_number: 8
step_description_prompt: Please use MATLAB code to create a function named Random_walk_around_antlion that generates random walks around an antlion by adjusting boundaries based on iteration progress and normalizing random paths. The function takes dimensions (Dim), maximum iterations (max_iter), lower bound (lb), upper bound (ub), antlion position (antlion), and current iteration (current_iter) as inputs, and returns the generated random walks (RWs).

Function definition: function [RWs] = Random_walk_around_antlion(Dim, max_iter, lb, ub, antlion, current_iter)

1. If lb or ub are scalars (size(lb,1) == 1 && size(lb,2) == 1), expand them to 1×Dim vectors using ones(1,Dim)*lb and ones(1,Dim)*ub respectively.
2. If lb is a column vector (size(lb,1) > size(lb,2)), transpose lb and ub to row vectors.
3. Initialize ratio I to 1. Update I with conditional checks in order: if current_iter > max_iter/10, set I = 1 + 100*(current_iter/max_iter); if current_iter > max_iter/2, set I = 1 + 1000*(current_iter/max_iter); if current_iter > max_iter*(3/4), set I = 1 + 10000*(current_iter/max_iter); if current_iter > max_iter*0.9, set I = 1 + 100000*(current_iter/max_iter); if current_iter > max_iter*0.95, set I = 1 + 1000000*(current_iter/max_iter).
4. Adjust lb and ub by dividing each by I (Equations 2.10 and 2.11).
5. Shift lb around antlion: if rand() < 0.5, lb = lb + antlion; else, lb = -lb + antlion (Equation 2.8). Shift ub around antlion: if rand() >= 0.5, ub = ub + antlion; else, ub = -ub + antlion (Equation 2.9).
6. For each dimension i from 1 to Dim:
   a. Generate random walk path X as [0, cumsum(2*(rand(max_iter,1) > 0.5) - 1)] (Equation 2.1).
   b. Compute a = min(X), b = max(X), c = lb(i), d = ub(i).
   c. Normalize X to [c, d] using X_norm = ((X - a) .* (d - c)) / (b - a) + c (Equation 2.7).
   d. Assign X_norm to RWs(:,i).

Ensure the function name is exactly Random_walk_around_antlion. Assume all built-in MATLAB functions are pre-defined.
function_header: function [RWs]=Random_walk_around_antlion(Dim,max_iter,lb, ub,antlion,current_iter)

end
test_cases: clear; clc;
rng(42);

Dim = 2;
max_iter = 100;
lb = -5;
ub = 5;
antlion = [1, 2];
current_iter = 10;
RWs1 = Random_walk_around_antlion(Dim, max_iter, lb, ub, antlion, current_iter);
correct=113.727273;
val = sum(RWs1(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
current_iter2 = 90;
RWs2 = Random_walk_around_antlion(3, 100, -2, 2, [0.5, 0.5, 0.5], current_iter2);
correct=151.497482;
val = sum(RWs2(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
current_iter3 = 60;
RWs3 = Random_walk_around_antlion(3, 80, -10, 10, [0.5, 0.5, 0.5], current_iter3);
correct=121.772657;
val = sum(RWs3(:));
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 9
step_description_prompt: Please write a MATLAB function named ALO that implements the Ant Lion Optimizer algorithm. The function returns the fitness and position of the elite antlion (the best solution found) and the convergence curve recording the elite fitness at each iteration.

Function definition: [Elite_antlion_fitness,Elite_antlion_position,Convergence_curve] = ALO(N, Max_iter, lb, ub, dim, fobj) where N is the number of antlions and ants, Max_iter is the maximum number of iterations, lb is the lower bound of the search space, ub is the upper bound, dim is the dimension of the search space, and fobj is the objective function to minimize.

Algorithm flow:
1. Initialize the positions of antlions and ants using the `initialization` function: `antlion_position = initialization(N, dim, ub, lb); ant_position = initialization(N, dim, ub, lb);`.
2. Initialize variables: `Sorted_antlions = zeros(N, dim); Elite_antlion_position = zeros(1, dim); Elite_antlion_fitness = inf; Convergence_curve = zeros(1, Max_iter); antlions_fitness = zeros(1, N); ants_fitness = zeros(1, N);`.
3. Calculate the fitness of initial antlions with `fobj`, sort `antlions_fitness` to get `sorted_antlion_fitness` and `sorted_indexes`, then assign `Sorted_antlions` using `sorted_indexes` and set `Elite_antlion_position` and `Elite_antlion_fitness` to the first element of `Sorted_antlions` and `sorted_antlion_fitness` respectively.
4. Start the main loop from `Current_iter = 2` to `Max_iter`:
   a. For each ant (from 1 to size(ant_position,1)):
      i. Select an antlion index via `RouletteWheelSelection(1./sorted_antlion_fitness)`; if `Rolette_index == -1`, set it to 1.
      ii. Generate random walk `RA` around the selected antlion using `Random_walk_around_antlion(dim, Max_iter, lb, ub, Sorted_antlions(Rolette_index,:), Current_iter)`.
      iii. Generate random walk `RE` around the elite antlion using `Random_walk_around_antlion(dim, Max_iter, lb, ub, Elite_antlion_position(1,:), Current_iter)`.
      iv. Update ant position as `(RA(Current_iter,:) + RE(Current_iter,:))/2`.
   b. For each ant, perform boundary checking: if `ant_position(i,:)` exceeds `ub` or is below `lb`, clamp it to `ub` or `lb` respectively using logical indexing.
   c. Calculate the fitness of ants using `fobj` and assign to `ants_fitness`.
   d. Merge antlion and ant populations into `double_population = [Sorted_antlions; ant_position]` and merge fitnesses into `double_fitness = [sorted_antlion_fitness ants_fitness]`.
   e. Sort `double_fitness` to get `double_fitness_sorted` and `I`, then assign `double_sorted_population = double_population(I,:)`.
   f. Keep the top N elements of `double_fitness_sorted` as `antlions_fitness` and top N elements of `double_sorted_population` as `Sorted_antlions`.
   g. If the first element of `antlions_fitness` is less than `Elite_antlion_fitness`, update `Elite_antlion_position` and `Elite_antlion_fitness` to the first element of `Sorted_antlions` and `antlions_fitness` respectively.
   h. Set the first element of `Sorted_antlions` to `Elite_antlion_position` and first element of `antlions_fitness` to `Elite_antlion_fitness` to keep the elite in the population.
   i. Update `Convergence_curve(Current_iter)` with `Elite_antlion_fitness`.
   j. Every 50 iterations (when `mod(Current_iter,50) == 0`), display the iteration number and elite fitness using `display(['At iteration ', num2str(Current_iter), ' the elite fitness is ', num2str(Elite_antlion_fitness)])`.
   k. Increment `Current_iter` by 1.
5. End the loop and return `Elite_antlion_fitness`, `Elite_antlion_position`, and `Convergence_curve`.

The functions `initialization`, `RouletteWheelSelection`, and `Random_walk_around_antlion` are assumed to be pre-defined and do not need to be reimplemented.
function_header: function [Elite_antlion_fitness,Elite_antlion_position,Convergence_curve]=ALO(N,Max_iter,lb,ub,dim,fobj)

end
test_cases: clear; clc;
rng(42);

Max_iteration = 5;
SearchAgents_no=20;
Function_name='F1';
[lb,ub,dim,fobj]=Get_Functions_details(Function_name);
[Best_score,Best_pos,cg_curve]=ALO(SearchAgents_no,Max_iteration,lb,ub,dim,fobj);
val = Best_score + sum(Best_pos) + sum(cg_curve);
correct = 18769.841788;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

Max_iteration = 20;
SearchAgents_no=30;
Function_name='F5';
[lb,ub,dim,fobj]=Get_Functions_details(Function_name);
[Best_score,Best_pos,cg_curve]=ALO(SearchAgents_no,Max_iteration,lb,ub,dim,fobj);
val = Best_score + sum(Best_pos) + sum(cg_curve);
correct = 19749189.085070;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end

Max_iteration = 10;
SearchAgents_no=8;
Function_name='F9';
[lb,ub,dim,fobj]=Get_Functions_details(Function_name);
[Best_score,Best_pos,cg_curve]=ALO(SearchAgents_no,Max_iteration,lb,ub,dim,fobj);
val = Best_score + sum(Best_pos) + sum(cg_curve);
correct = 704.363471;
tol = abs(val-correct);
if tol>1e-4
    error('Wrong!')
end
disp('Completely right!')

step_number: 10
step_description_prompt: Please write a MATLAB function named func_plot that draws benchmark functions. The function takes a single string input func_name which specifies the benchmark function to plot, and has no output. Note that the function Get_Functions_details(func_name) (which returns four outputs: lb, ub, dim, fobj) is assumed to be pre-defined and does not need to be reimplemented.

The function must follow this exact流程:
1. Call [lb, ub, dim, fobj] = Get_Functions_details(func_name); to retrieve the benchmark function details.
2. Use a switch-case structure on func_name to set the x and y vectors (with identical ranges and step sizes for x and y):
   - case 'F1': x = -100:2:100; y = x;
   - case 'F2': x = -100:2:100; y = x;
   - case 'F3': x = -100:2:100; y = x;
   - case 'F4': x = -100:2:100; y = x;
   - case 'F5': x = -200:2:200; y = x;
   - case 'F6': x = -100:2:100; y = x;
   - case 'F7': x = -1:0.03:1; y = x;
   - case 'F8': x = -500:10:500; y = x;
   - case 'F9': x = -5:0.1:5; y = x;
   - case 'F10': x = -20:0.5:20; y = x;
   - case 'F11': x = -500:10:500; y = x;
   - case 'F12': x = -10:0.1:10; y = x;
   - case 'F13': x = -5:0.08:5; y = x;
   - case 'F14': x = -100:2:100; y = x;
   - case 'F15': x = -5:0.1:5; y = x;
   - case 'F16': x = -1:0.01:1; y = x;
   - case 'F17': x = -5:0.1:5; y = x;
   - case 'F18': x = -5:0.06:5; y = x;
   - case 'F19': x = -5:0.1:5; y = x;
   - case 'F20': x = -5:0.1:5; y = x;
   - case 'F21': x = -5:0.1:5; y = x;
   - case 'F22': x = -5:0.1:5; y = x;
   - case 'F23': x = -5:0.1:5; y = x;
3. Calculate L = length(x) and initialize an empty array f.
4. Use nested for loops (i from 1 to L, j from 1 to L) to compute f(i,j):
   - If func_name is NOT 'F15', 'F19', 'F20', 'F21', 'F22', or 'F23', set f(i,j) = fobj([x(i), y(j)]).
   - If func_name is 'F15', set f(i,j) = fobj([x(i), y(j), 0, 0]).
   - If func_name is 'F19', set f(i,j) = fobj([x(i), y(j), 0]).
   - If func_name is 'F20', 'F21', 'F22', or 'F23', set f(i,j) = fobj([x(i), y(j), 0, 0]).
5. Plot the surface with surfc(x, y, f, 'LineStyle', 'none').

Ensure the function strictly matches the original logic, including exact x/y ranges, step sizes, loop conditions, and the surfc plot configuration.
ground_truth_code: % This function draws the benchmark functions

function func_plot(func_name)

[lb,ub,dim,fobj]=Get_Functions_details(func_name);

switch func_name 
    case 'F1' 
        x=-100:2:100; y=x; %[-100,100]
        
    case 'F2' 
        x=-100:2:100; y=x; %[-10,10]
        
    case 'F3' 
        x=-100:2:100; y=x; %[-100,100]
        
    case 'F4' 
        x=-100:2:100; y=x; %[-100,100]
    case 'F5' 
        x=-200:2:200; y=x; %[-5,5]
    case 'F6' 
        x=-100:2:100; y=x; %[-100,100]
    case 'F7' 
        x=-1:0.03:1;  y=x  %[-1,1]
    case 'F8' 
        x=-500:10:500;y=x; %[-500,500]
    case 'F9' 
        x=-5:0.1:5;   y=x; %[-5,5]    
    case 'F10' 
        x=-20:0.5:20; y=x;%[-500,500]
    case 'F11' 
        x=-500:10:500; y=x;%[-0.5,0.5]
    case 'F12' 
        x=-10:0.1:10; y=x;%[-pi,pi]
    case 'F13' 
        x=-5:0.08:5; y=x;%[-3,1]
    case 'F14' 
        x=-100:2:100; y=x;%[-100,100]
    case 'F15' 
        x=-5:0.1:5; y=x;%[-5,5]
    case 'F16' 
        x=-1:0.01:1; y=x;%[-5,5]
    case 'F17' 
        x=-5:0.1:5; y=x;%[-5,5]
    case 'F18' 
        x=-5:0.06:5; y=x;%[-5,5]
    case 'F19' 
        x=-5:0.1:5; y=x;%[-5,5]
    case 'F20' 
        x=-5:0.1:5; y=x;%[-5,5]        
    case 'F21' 
        x=-5:0.1:5; y=x;%[-5,5]
    case 'F22' 
        x=-5:0.1:5; y=x;%[-5,5]     
    case 'F23' 
        x=-5:0.1:5; y=x;%[-5,5]  
end    

    

L=length(x);
f=[];

for i=1:L
    for j=1:L
        if strcmp(func_name,'F15')==0 && strcmp(func_name,'F19')==0 && strcmp(func_name,'F20')==0 && strcmp(func_name,'F21')==0 && strcmp(func_name,'F22')==0 && strcmp(func_name,'F23')==0
            f(i,j)=fobj([x(i),y(j)]);
        end
        if strcmp(func_name,'F15')==1
            f(i,j)=fobj([x(i),y(j),0,0]);
        end
        if strcmp(func_name,'F19')==1
            f(i,j)=fobj([x(i),y(j),0]);
        end
        if strcmp(func_name,'F20')==1
            f(i,j)=fobj([x(i),y(j),0,0,0,0]);
        end       
        if strcmp(func_name,'F21')==1 || strcmp(func_name,'F22')==1 ||strcmp(func_name,'F23')==1
            f(i,j)=fobj([x(i),y(j),0,0]);
        end          
    end
end

surfc(x,y,f,'LineStyle','none');

end
function_header: function func_plot(func_name)

end

step_number: 11
step_description_prompt: Please use MATLAB code to create a script that calls the pre-defined function named ALO to implement the African Lion Optimization algorithm for optimizing a benchmark test function, obtaining the optimal solution, optimal objective value, and convergence curve, then visualizing the results.

The ALO function is defined as function [Best_score, Best_pos, cg_curve] = ALO(SearchAgents_no, Max_iteration, lb, ub, dim, fobj), where SearchAgents_no is the number of search agents, Max_iteration is the maximum number of iterations, lb is the lower bound of variables (can be a scalar or vector), ub is the upper bound of variables (can be a scalar or vector), dim is the number of variables, and fobj is the handle to the objective function to be minimized.

The script flow is as follows:
1. Clear the workspace and command window using clear all and clc.
2. Set the number of search agents: SearchAgents_no = 40.
3. Set the name of the benchmark test function (from F1 to F23): Function_name = 'F1'.
4. Set the maximum number of iterations: Max_iteration = 500.
5. Load the details of the selected test function (lb, ub, dim, fobj) using the pre-defined Get_Functions_details function with Function_name as input.
6. Call the ALO function with SearchAgents_no, Max_iteration, lb, ub, dim, fobj to get Best_score (best optimal value of the objective function), Best_pos (best solution vector), and cg_curve (convergence curve recording the best score at each iteration).
7. Create a figure window with position [500 500 660 290] using figure('Position', [500 500 660 290]).
8. Create the first subplot (1 row, 2 columns, 1st position) to visualize the search space of the test function:
   - Use the pre-defined func_plot function with Function_name as input: func_plot(Function_name).
   - Set the title to 'Test function' using title('Test function').
   - Set the x-axis label to 'x_1' using xlabel('x_1').
   - Set the y-axis label to 'x_2' using ylabel('x_2').
   - Set the z-axis label to [Function_name, '( x_1 , x_2 )'] using zlabel([Function_name,'( x_1 , x_2 )']).
   - Turn off the grid using grid off.
9. Create the second subplot (1 row, 2 columns, 2nd position) to visualize the convergence curve:
   - Plot the convergence curve using semilogy(cg_curve, 'Color', 'r').
   - Set the title to 'Convergence curve' using title('Convergence curve').
   - Set the x-axis label to 'Iteration' using xlabel('Iteration').
   - Set the y-axis label to 'Best score obtained so far' using ylabel('Best score obtained so far').
   - Tighten the axis limits using axis tight.
   - Turn off the grid using grid off.
   - Add a box around the plot using box on.
   - Add a legend with 'ALO' using legend('ALO').
10. Display the best solution obtained by ALO using display(['The best solution obtained by ALO is : ', num2str(Best_pos)]).
11. Display the best optimal value of the objective function using display(['The best optimal value of the objective funciton found by ALO is : ', num2str(Best_score)]).

The functions Get_Functions_details, func_plot, and ALO are pre-defined and do not need to be redefined.
ground_truth_code: % You can simply define your cost in a seperate file and load its handle to fobj 
% The initial parameters that you need are:

% fobj = @YourCostFunction
% dim = number of your variables
% Max_iteration = maximum number of generations
% SearchAgents_no = number of search agents
% lb=[lb1,lb2,...,lbn] where lbn is the lower bound of variable n
% ub=[ub1,ub2,...,ubn] where ubn is the upper bound of variable n
% If all the variables have equal lower bound you can just
% define lb and ub as two single number numbers
% To run ALO: [Best_score,Best_pos,cg_curve]=ALO(SearchAgents_no,Max_iteration,lb,ub,dim,fobj)

clear all 
clc

SearchAgents_no=40; % Number of search agents

Function_name='F1'; % Name of the test function that can be from F1 to F23 (Table 1,2,3 in the paper)

Max_iteration=500; % Maximum numbef of iterations

% Load details of the selected benchmark function
[lb,ub,dim,fobj]=Get_Functions_details(Function_name);

[Best_score,Best_pos,cg_curve]=ALO(SearchAgents_no,Max_iteration,lb,ub,dim,fobj);

figure('Position',[500 500 660 290])
%Draw search space
subplot(1,2,1);
func_plot(Function_name);
title('Test function')
xlabel('x_1');
ylabel('x_2');
zlabel([Function_name,'( x_1 , x_2 )'])
grid off

%Draw objective space
subplot(1,2,2);
semilogy(cg_curve,'Color','r')
title('Convergence curve')
xlabel('Iteration');
ylabel('Best score obtained so far');

axis tight
grid off
box on
legend('ALO')

display(['The best solution obtained by ALO is : ', num2str(Best_pos)]);
display(['The best optimal value of the objective funciton found by ALO is : ', num2str(Best_score)]);

General solution:

General tests: