function gd_3bus
% 'gd_3bus' uses gen_dispatch to check branch flow and generator capacity 
% limits.  The 'threebus.m' file with the PTDF and LODF matrices is also
% required.
% 
% This code checks for the existence of an alpha value (linear combination 
% coefficient) that satisfies the branch MWmax constraints and the generator 
% available capacity constraints.  If an alpha value can be found, then the 
% range of successful alphas will be returned by gen_dispatch, such that 
% Pg1 = alpha*TotalLoad and Pg2 = (1-alpha)*TotalLoad could supply the load 
% while satisfying the constraints.
% 
% After running this example, try modifying it.  For example, what happens 
% when the artificial branch capacity limit factor (br_lim_fact) is less than 
% 1.0?  Try the value of 0.579.  Note that artificially reducing the branch 
% capacity limits serves only to illustrate the impact of branch capacity 
% constraints on the generator dispatch and potential load curtailment.
% 
% In addition to modifying the branch MW limits and the generator available 
% capacities, it is possible to add a branch outage via the LODF matrix to see 
% the impact on the ability to find a dispatch that satisfies the generator 
% available capacity and transmission capacity constraints.

threebus % load threebus.m, which contains PTDF and LODF matrices

InsCap1 = 80; % 4 x 20 MW units installed
InsCap2 = 60; % 2 x 30 MW units installed

Pd = [0; 0; 110];
Ltotal = sum(Pd);

br_lim_fact=1.000; % explore reduced branch capacity impact on load curtailment
MWmax = [80; 100; 90]*br_lim_fact; % branch MWmax with limit factor

CapAva1 = InsCap1; % assume 0 MW capacity outage
CapAva2 = InsCap2; % assume 0 MW capacity outage

% assume all load supplied by G1, even if greater than CapAva1
Pg1 = [Ltotal; 0; 0;]; % ignoring MW losses
flow1 = PTDF*(Pg1-Pd); % Pinj must sum to zero
% assume all load supplied by G2, even if greater than CapAva2
Pg2 = [0; Ltotal; 0;]; % ignoring MW losses
flow2 = PTDF*(Pg2-Pd); % Pinj must sum to zero

[success, alphamn, alphamx] = gen_dispatch (Ltotal, flow1, flow2, ...
    CapAva1, CapAva2, MWmax);

fprintf('\nalphmn    Pgen1    Pgen2\n');
fprintf('%6.4f  %7.2f  %7.2f\n',...
    [alphamn, Ltotal*alphamn, Ltotal*(1-alphamn)]');

fprintf('alphmx    Pgen1    Pgen2\n');
fprintf('%6.4f  %7.2f  %7.2f\n',...
    [alphamx, Ltotal*alphamx, Ltotal*(1-alphamx)]');

if (~success),
   fprintf('Invalid gen dispatch: alphamn > alphamx\n');
end
