-
Notifications
You must be signed in to change notification settings - Fork 34
/
evalobj.m
53 lines (46 loc) · 1.92 KB
/
evalobj.m
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
function [f, succ] = evalobj(invoker, fun, x, funcmax)
%EVALOBJ evaluates an objective function `f = fun(x)`.
% In particular, it uses a 'moderated extreme barrier' to cope with 'hidden constraints' or
% evaluation failures.
succ = true;
try
f = fun(x);
catch exception
succ = false;
f = NaN;
wid = sprintf('%s:ObjectiveFailure', invoker);
if ~isempty(exception.identifier)
wmsg = sprintf('%s: Objective function fails with the following error:\n %s: %s\n Error occurred in %s, line %d', ...
invoker, exception.identifier, exception.message, exception.stack(1).file, exception.stack(1).line);
else
wmsg = sprintf('%s: Objective function fails with the following error:\n %s\n Error occurred in %s, line %d', ...
invoker, exception.message, exception.stack(1).file, exception.stack(1).line);
end
warning(wid, '%s', wmsg);
end
if numel(f) ~= 1
% succ = false; % Not needed if we raise an error.
% Public/normal error
error(sprintf('%s:ObjectiveNotScalar', invoker), '%s: objective function should return a scalar value.', invoker);
end
if ~isnumeric(f)
succ = false;
f = NaN;
end
% Use a 'moderated extreme barrier' to cope with 'hidden constraints' or evaluation failures.
if isnan(f) || ~isreal(f) || f > funcmax
wid = sprintf('%s:ObjectiveAbnormalReturn', invoker);
xstr = sprintf('%g ', x);
if ~isreal(f)
fstr = sprintf('%g%+gi', real(f), imag(f));
else
fstr = sprintf('%g', f);
end
wmsg = sprintf('%s: Objective function returns %s, which is replaced by funcmax = %g.\nThe value of x is:\n%s\n', invoker, fstr, funcmax, xstr);
warning(wid, '%s', wmsg);
%warnings = [warnings, wmsg]; % We do not record this warning in the output.
% Apply the moderated extreme barrier:
f = funcmax;
end
f = double(real(f)); % Some functions like 'asin' can return complex values even when it is not intended
return