function optimAntenna = optimizeAntennaSurrogate(designparams,analysisparams,constraints,optimizerparams)
% OPTIMIZEANTENNA optimizes the antenna using a global optimization
% function OPTIMANTENNA =
% OPTIMIZEANTENNA(DESIGNPARAMS,ANALYSISPARAMS,CONSTRAINTS,OPTIMIZERPARAMS)
% optimizes the antenna using the ANALYSISPARAMS specified to achieve
% impedance match as well as maximizing gain and minimizing backlobe
% radiation. The optimization function will search for a solution over the
% parameter ranges specified as upper and lower bounds in the DESIGNPARAMS
% structure constrained by the values provided for minimum S_1_1, F/B ratio
% and Directivity in CONSTRAINTS. Each global optimization function has
% specific set of options which can be set up in OPTIMIZERPARAMS.

% The OPTIMIZEANTENNA function is used for an internal example.
% Its behavior may change in subsequent releases, so it should not be
% relied upon for programming purposes.

% Copyright 2018 The MathWorks, Inc.

% Unpack inputs
ant = designparams.Antenna;
parameterBounds = designparams.Bounds;
freq = analysisparams.CenterFrequency;
BW = analysisparams.Bandwidth;
Z0 = analysisparams.ReferenceImpedance;
angles = [analysisparams.MainLobeDirection,analysisparams.BackLobeDirection];
optimizerOptions = optimizerparams;
initial_values = [ ant.ReflectorLength,                          ...
                   ant.ReflectorSpacing,                         ...
                   ant.DirectorSpacing];                 
LB = parameterBounds.LB;
UB = parameterBounds.UB;
if strcmpi(class(optimizerparams),'optim.options.PatternsearchOptions')
    [optimAntenna] = patternsearch(@(x) yagi_objective_function_surrogate(ant,x,freq,BW,...
                                        angles,Z0,constraints),initial_values,[],...
                                    [],[],[],LB,UB,[],optimizerOptions);
elseif strcmpi(class(optimizerparams),'optim.options.Surrogateopt')
    rng default % For reproducibility
    [optimAntenna] = surrogateopt(@(x) yagi_objective_function_surrogate(ant,x,freq,BW,...
                                    angles,Z0,constraints),LB,UB,optimizerOptions);
else
    error('Optimizer not supported');
end