You are on page 1of 19

Para baixar o código acesse: https://goo.

gl/znCEkr

Escola Politécnica da Universidade de São Paulo

Diego Varalda de Almeida, 10580379

Resolução da 3a lista de exercícios

PMR5215 - Otimização aplicada ao projeto


de sistemas mecânicos

Orientadores: Prof. Dr. Emílio Carlos Nelli


Silva ; Prof. Dr. Thiago Martins

Universidade de São Paulo


Programa de Pós-graduação

São Paulo
2018
EXERCÍCIO 1
Transformando as restrições na forma , obtemos:

syms x_1 x_2


% objective function
f = x_2^2 - x_1^2;
% constraints
g = [-x_2+3>=0, -x_1^2-x_2^2+25>=0];

Item a
Uma vez que o problema possui apenas duas coordenadas, é possível a representação no espaço
Cartesiano. A figura abaixo mostra o gráfico da função objetivo para um intervalo de .
Uma rotina em Matlab foi desenvolvida para se calcular o gradiente da função objetivo e plotar o campo
vetorial desse gradiente. Também foi inserido as regiões onde ambas restrições estão ativas (domínio
viável), como mostrado a seguir:

%% Item a: Plotting gradient


ffun = matlabFunction(x_2^2 - x_1^2);
% gradient
grad = matlabFunction(transpose(gradient(f, [x_1, x_2])));

[X_1, X_2] = meshgrid(-10 : 0.5 : 10);

G = grad(X_1, X_2); %matrix with the gradient values


Z = ffun(X_1, X_2);

figure; set(gcf,'color','white');
% -> plot vector field
quiver(X_1, X_2, G(:, 1:size(G, 2)/2), G(:,size(G, 2)/2 + 1:size(G, 2)));
xlabel('$x_1$', 'Interpreter','latex', 'FontSize',17);
ylabel('$x_2$', 'Interpreter','latex', 'FontSize',17);
title('Gradient and Constraint Plot');
hold on

% -> Plot contour


contour(X_1, X_2, Z, 'ShowText', 'on');
pbaspect([1 1 1]);

% -> Plotting Contraints


%make a finer grid for contraints
[X_1, X_2] = meshgrid(-10 : 0.2 : 10);
ineq1 = -X_2+3>=0;
ineq2 = -X_1.^2-X_2.^2+25>=0;
% intersection of the inequalities
both = double(ineq1 & ineq2);
% remove points where the constraints don't intersect
for i = 1:size(X_1, 1)
for j = 1:size(X_1, 2)
if both(i, j) ~= 1
X_1(i, j) = nan;
X_2(i, j) = nan;
end
end
end
% plot contraints
scatter(X_1(:),X_2(:),3,both(:),'filled');

% Plot surface
[X_1, X_2] = meshgrid(-10 : 0.5 : 10);
Z = ffun(X_1, X_2);
figure; set(gcf,'color','white');
surf(X_1, X_2, Z);
xlabel('$x_1$', 'Interpreter','latex', 'FontSize',17);
ylabel('$x_2$', 'Interpreter','latex', 'FontSize',17);
zlabel('$f(x_1, x_2)$', 'Interpreter','latex', 'FontSize',17);
title('Surface Plot of the objective function');
pbaspect([1 1 1]);

Item b
A função Lagrangiana para um sistema com restrições é definido pela expressão

a Lagrangiana para o problema proposto fica, portanto:


%% Item b: Lagrangian
l_multi = sym('lambda_', [1,length(g)]); %Lagrange multipliers

constraint_term = 0;
for i = 1 : length(g)
lhs_g = children(g(i)); %get the left hand side of the constraint inequality
constraint_term = constraint_term + (l_multi(i) * lhs_g(2));
end
L = f - constraint_term;
latex2(L);

Item c
A codição de estacionariedade é obtida diferenciando-se a função Lagrangiana com respeito às variáveis de
projeto, desta forma

A matriz hessiana da função Lagrangiana é dada por

Para cada possibilidade de valor para os multiplicadores de Lagrange

No primeiro caso, ambas as restrições estão inativas e obtemos .

O código abaixo calcula os multiplicadores de Lagrange para cada caso

%% Item c: Lagrange multipliers


hyp = []; %hypothesis about lambda
% assemble a matrix with all possible configurations for lambda
% (1 means different than zero and 0 means lambda is zero)
for i = 0:1
for j = 0:1
hyp = [hyp; [i, j]];
end

end
dLdx1 = diff(L, x_1) == 0;
dLdx2 = diff(L, x_2) == 0;

% Computes the Hessian matrix


H = hessian(L, [x_1, x_2]);
latex2(H);

% For each configuration of the Lagrange multipliers, solve the equations


% given by the stationary condition (dLdx1 and dLdx2)
X_sol = cell(2^size(g, 2), 1); %2^n is the number of possible scenarios
% for lagrange multipliers, where n is the number of constraints
for i = 1:size(hyp, 1)
disp(strcat('>>>> Case_', num2str(i)));
LS = [dLdx1; dLdx2];

for j = 1:size(hyp, 2)
if hyp(i,j) == 0
LS = subs(LS, l_multi(j), 0);
% H_num = subs(H_num, l_multi(j), 0);
else %add active constraint expression to the system of equations
lhs_g = children(g(j));
LS = [LS; lhs_g(2)==0];
end
end
LS_sol = solve(LS); %solve the system of equations

%displaying the results


sol_vars = fieldnames(LS_sol);
for ii = 1:size(sol_vars, 1)
disp(sol_vars(ii));
disp(getfield(LS_sol, sol_vars{ii}));
X_sol{i}(:, ii) = getfield(LS_sol, sol_vars{ii});
end

% Check the hessian matrix for every solution of a particular


% configuration of the Lagrange multipliers.
for iii = 1: size(getfield(LS_sol, sol_vars{1}), 1)
H_num = H; %Hessian matrix that will be solved using numeric values
for j = 1:size(sol_vars, 1)
sol_values = getfield(LS_sol, sol_vars{j});
H_num = subs(H_num, sol_vars(j), sol_values(iii));
end
disp('-> Hessian Matrix');
disp(H_num);
% using the Cholesky factorization to dermine if the matrix is positive
% definite (if p is zero the matrix is definite position, p~=0 the matrix
% is negative definite)
[~, p] = chol(H_num);
if p == 0

disp('H is positive definite')


else
disp('H is negative definite')
end
end
end

X_sol

Item d
Caso 1

Neste caso ambas as restrições estão inativas, o ponto em vermelho indica a solução das variáveis de
projeto, ou seja .

Caso 2

Neste caso apenas a segunda restrição está ativa (conforme tabela acima), pode-se notar pelo gráfico
abaixo que as soluções são os pontos extremos da circunferência
 

Caso 3

No caso três apenas a primeira restrição está ativa, logo a solução é o ponto no extremo do linha formada
pela expressão , sendo este um ponto de máximo
 

Caso 4

No quarto caso, ambas as restrições estão ativas, e portanto os pontos obtidos são os pontos de
intersecção das duas restrições.
 

Itens e, f
Os itens e e f estão incorporados no código mostrado no item c. A resposta retornada pelo código é
mostrada a seguir

>>>> Case_1
'x_1'

'x_2'

-> Hessian Matrix


[ 2*lambda_2 - 2, 0]
[ 0, 2*lambda_2 + 2]

H is negative definite
>>>> Case_2
'lambda_2'
1
1
-1
-1

'x_1'

-5
5
0
0

'x_2'

0
0
-5
5

-> Hessian Matrix


[ 0, 0]
[ 0, 4]

H is negative definite
-> Hessian Matrix
[ 0, 0]
[ 0, 4]

H is negative definite
-> Hessian Matrix
[ -4, 0]
[ 0, 0]

H is negative definite
-> Hessian Matrix
[ -4, 0]
[ 0, 0]

H is negative definite
>>>> Case_3
'lambda_1'

-6

'x_1'

'x_2'

3
-> Hessian Matrix
[ 2*lambda_2 - 2, 0]
[ 0, 2*lambda_2 + 2]

H is negative definite
>>>> Case_4
'lambda_1'

-12
-12

'lambda_2'

1
1

'x_1'

-4
4

'x_2'

3
3

-> Hessian Matrix


[ 0, 0]
[ 0, 4]

H is negative definite
-> Hessian Matrix
[ 0, 0]
[ 0, 4]

H is negative definite

X_sol =

[1x2 sym]
[4x3 sym]
[1x3 sym]
[2x4 sym]

>> X_sol{1}

ans =

[ 0, 0]

>> X_sol{2}

ans =
[ 1, -5, 0]
[ 1, 5, 0]
[ -1, 0, -5]
[ -1, 0, 5]

>> X_sol{3}

ans =

[ -6, 0, 3]

>> X_sol{4}

ans =

[ -12, 1, -4, 3]
[ -12, 1, 4, 3]

Exercício 2
O problema consiste em maximizar o momento em guinada a bombordo,

podemos converter o problema para um problema de minimização e reescrevermos as restrições para que
fique na forma , desta forma obtemos:

Item a
A função Lagrangiana é definida como

desta forma, para o problema proposto


Item b
Os multiplicadores de Lagrange são calculados a partir do seguinte problema de otimização

a matriz para as restrições dadas, quando ambas estão ativas é

e o gradiente de

b.1
 

Para o primerio ponto ( ), ambas as restrições estão ativas, logo

b.2
Para o segundo ponto ( ), devemos notar que , desta forma
ambas as restrições também estão ativas, sendo assim

b.3
Para o terceiro ponto ( ), fazemos a
verificação das restrições, para , temos

efetuando as operações necessárias

nota-se, contudo que , desta forma

logo esta restrição está ativa, de modo análogo, resolvemos para e notamos que de novo ambas estão
ativas, sendo assim, obtemos a seguinte matriz

e os multiplicadores de Lagrange são

b.4
Apenas os pontos 1 e 3 obedecem as condições KKT, uma vez que em ambos os casos . No ponto 2
fornecido, a matriz possui um deficiente e logo pode haver múltiplas soluções para a inversa de
, sendo assim não se pode calcular algébricamente os valores de para este ponto.

b.5
A matriz Hessiana do problema é

Percebe-se que a matriz é positiva semi-definida, logo o problema é convexo. Para o ponto três dado, a
matriz Hessiana é
que é positiva definida (assumindo que ), desta forma o ponto três é o ponto ótimo do
problema, máximo global. O código abaixo calcula os multiplicadores de Lagrange para cada ponto dado,
além de checar se as restrições estão ativas e calcular a matriz Hessiana.

function exe2()
%EXE2 Solution to exercise 2 (list 3)

% Author(s): Diego Varalda de Almeida


% Copyright (c) 2018, Diego ALMEIDA
% <diego.vda@usp.br>

% 01-Apr-2018 First version of EXE2.

% Inputs
% project variables
x = sym('x_', [1,2]);
y = sym('y_', [1,2]);
pvars = [x, y];
syms T_max L B

R = sqrt(L^2+B^2);

f = -L * (x(1)+x(2)) + B *(y(1)-y(2));

g = [-x(1)^2-y(1)^2+T_max^2 >= 0, -x(2)^2-y(2)^2+T_max^2 >=0];

points{1} = [x(1), 0;
x(2), 0;
y(1), -T_max;
y(2), T_max];

points{2} = [x(1), 0;
x(2), T_max;
y(1), 0;
y(2), 0];

points{3} = [x(1), T_max*L/R;


x(2), T_max*L/R;
y(1), -T_max*B/R;
y(2), T_max*B/R];

%%

lagrangian = computeLagrangian(f, g);


gradf = gradient(f, pvars);

% Computing N and the Lagrange multipliers for each point


for i = 1 : length(points)
disp(strcat('>>> Point__', num2str(i)));
isActive = checkActiveConstraint(g, points{i});
%copy to g_new only the active constraints (where isActive array have
%logical 1)
g_new = g(isActive);
N = computeN(g_new, pvars, transpose(points{i}(:, 2)));
disp('N matrix')
disp(N);
% latex2(N)

% computes Lagrange multipliers


lambda = computeLagrangeMultipliers(gradf, N);
disp(strcat('Lambda for point_', num2str(i)));
disp(lambda);
% latex2(lambda)

% computes Hessian matrix


% adding lambda to point data
l_multi = sym('lambda_', [length(g), 1]);
point = [points{i}; [l_multi, lambda]];
H = computeHessian(lagrangian, pvars, point);
disp('Hessian matrix')
disp(H);
latex2(arrange(H))
end
end

%%
function lagrangian = computeLagrangian(f, g)
l_multi = sym('lambda_', [1,length(g)]);
const_term = 0; %constraint term

lhs_g = children(g);
for i = 1 : length(g)
const_term = const_term + l_multi(i) * lhs_g{i}(2);
end

% Computing the Lagrangian function and the gradient of f


lagrangian = f - const_term;
end
%%
function isActive = checkActiveConstraint(g, x_vec)
% Check if a given constraint is either active or not for a given point
% Evaluate the constraint expression (g_i>=0) if the expression returns a
% logical 0 the point is not inside the constraint region
for j = 1 : size(x_vec, 1)
g = subs(g, x_vec(j, 1), x_vec(j, 2));
end
try
isActive = logical(g);
catch
assume(symvar(g) >0);
isActive = isAlways(g);
end
end

%%
function N = computeN(g, x, varargin)
% Computes N matrix (Jacobian matrix for the constraints). Takes the
% partial differentiation of the active constraint g_i with respect to the
% project variables;
% g is an array containing all r active constraints symbolic expressions,
% x is an array containing all n project variables (symbolic) x_num is a
% (1 x n) array containing numeric values for project variables, x and
% x_num must have the same size

% remove right hand side of inequality


cg = children(g);
for i = 1 : length(g)
g(i) = cg{i}(2);
end

N = transpose(jacobian(g, x));

% if an array with numeric values has been given, solve N numerically


if nargin>2
x_num = varargin{1};

% check if x and x_num have the same size


if (size(x) == size(x_num))
for i = 1:length(x)
N = subs(N, x(i), x_num(i));
end
end
end
end

%%
function lambda = computeLagrangeMultipliers(grad_f, N)
N_transp = transpose(N);
lambda = (N_transp*N) \ N_transp * grad_f;

end

%%
function H = computeHessian(L, x, varargin)
% Computes the hessian matrix of the lagrangian function

H = hessian(L, x);

% if an array with numeric values has been given, solve N numerically


if nargin>2
x_num = varargin{1};
% check if x and x_num have the same size
for i = 1:size(x_num, 1)
H = subs(H, x_num(i, 1), x_num(i, 2));
end
end
end

You might also like