summaryrefslogtreecommitdiffstats
path: root/templates/lqr_tuning.asv
blob: 71c92ef1dffc546ada53fd53579405034a74b06c (plain)
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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (c) 2023, Amon Lahr, Simon Muntwiler, Antoine Leeman & Fabian Flürenbrock Institute for Dynamic Systems and Control, ETH Zurich.
%
% All rights reserved.
%
% Please see the LICENSE file that has been included as part of this package.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [tuning_struct, i_opt] = lqr_tuning(x0,Q,params)
    % YOUR CODE HERE
    R = eye(params.model.nu);
    size_Q = size(Q);
    param_choices = size_Q(2);
    J_array = [];
    for i = 1:param_choices
        Q_mat = diag(Q(:,i));
        ctrl = LQR(Q_mat,R,params);
        [Xt, Ut, ctrl_info] = simulate(x0, ctrl, params);
        ctrl_feas_arr = [];
        for k = 1:params.model.HorizonLength
            ctrl_feas_arr = [ctrl_feas_arr,ctrl_info(k).ctrl_feas];
        end
%         display(ctrl_feas_arr);
        if all(ctrl_feas_arr)
            J = 0;
            for j = 1:params.model.HorizonLength
                J = J + Xt(:,j)'*Q_mat*Xt(:,j);
                J = J + Ut(:,j)'*R*Ut(:,j);
            end
            J = J + Xt(:,end)'*Q_mat*Xt(:,end);
            J_array = [J_array, J];
        end
    end
%     display(J_array)
    if isempty(J_array)
        i_opt = nan;
        tuning_struct.TrajFeasible = false;
    else
        [~, i_opt] = min(J_array);
    end
    tuning_struct.TrajFeasible = true;
    tuning_struct.InitialCondition = x0;
    tuning_struct.Qdiag = Q(:,i_opt);
    tuning_struct.MaxAbsPositionXZ = params.constraints.MaxAbsPositionXZ;
    tuning_struct.MaxAbsPositionY = params.constraints.MaxAbsPositionY;
    tuning_struct.MaxAbsThrust = params.constraints.MaxAbsThrust;
    tuning_struct.InputCost = J_
    tuning_struct.MaxFinalPosDiff = params.constraints.MaxFinalPosDiff;
    tuning_struct.MaxFinalVelDiff = params.constraints.MaxFinalVelDiff;
end