%% Constrain Weighted Gain Evaluated with a Loop Opening
% Create a requirement that constrains the gain of the outer loop of the following control system, evaluated with the inner loop open.
%
% Create a model of the system. To do so, specify and connect the numeric plant models, G1 and G2, the tunable controllers C1 and C2. Also, create and connect the AnalysisPoint blocks that mark points of interest for analysis or tuning, AP1 and AP2.

G1 = tf(10,[1 10]);
G2 = tf([1 2],[1 0.2 10]);
C1 = tunablePID('C','pi');
C2 = tunableGain('G',1);
AP1 = AnalysisPoint('AP1');
AP2 = AnalysisPoint('AP2');
T = feedback(G1*feedback(G2*C2,AP2)*C1,AP1);  
T.InputName = 'r';
T.OutputName = 'y';

%
% Create a tuning requirement that constrains the gain of this system from r to y. Weight the gain at the output by s/(s + 0.5).

WL = tf([1 0],[1 0.5]);
Req = TuningGoal.WeightedGain('r','y',WL,[]);

% This requirement is equivalent to Req = TuningGoal.Gain('r','y',1/WL). However, for MIMO systems, you can use TuningGoal.WeightedGain to create channel-specific weightings that cannot be expressed as TuningGoal.Gain requirements.
%
% Specify that the transfer function from r to y be evaluated with the outer loop open for the purpose of tuning to this constraint.

Req.Openings = 'AP1';

%
% By default, tuning using TuningGoal.WeightedGain imposes a stability requirement as well as the gain requirement. Practically, in some control systems it is not possible to achieve a stable inner loop. When this occurs, remove the stability requirement for the inner loop by setting the Stabilize property to false.

Req.Stabilize = false;

% The tuning algorithm still imposes a stability requirement on the overall tuned control system, but not on the inner loop alone.
% Use systune to tune the free parameters of T to meet the tuning requirement specified by Req. You can then validate the tuned control system against the requirement using the command viewGoal(Req,T).
% Copyright 2012 The MathWorks, Inc.