% HEN_Constraints function
% Nonlinear constraints for optimizing a HEN
% Includes mass, energy and steady state balances

function [Cineq, Res] = HEN_Constraints_11_HXD(x,par)
x=x.*par.sc.x; % Unscale variables

% States
Tend = x(1); T1 = x(2); T2 = x(3); Th1out = x(4); Th2out = x(5);
w1 = x(6); w2 = x(7); Q1 = x(8); Q2 = x(9); UA1 = x(10); UA2 = x(11);

% Parameters
w0 = par.w0; wh1 = par.wh1; wh2 = par.wh2;
Th1 = par.Th1; Th2 = par.Th2; T0 = par.T0;
DeltaTmin = par.DeltaTmin;

%% INEQUALITY CONSTRAINTS
%%HX 1
 Cineq1 = -(Th1-T1-DeltaTmin);      % HOT SIDE HX1
 Cineq2 = -(Th1out-T0-DeltaTmin);   % COLD SIDE HX1
    
%%HX 2
 Cineq3 = -(Th2-T2-DeltaTmin);      % HOT SIDE HX2
 Cineq4 = -(Th2out-T0-DeltaTmin);   % COLD SIDE HX2
 
Cineq = [Cineq1;Cineq2;Cineq3;Cineq4];

%% MODEL EQUATIONS

%AMTD Approximation
% DeltaT1 = 0.5*((Th1out-T0)+(Th1-T1));
% DeltaT2 = 0.5*((Th2out-T0)+(Th2-T2));

%Underwood Approximation
 DeltaT1 = ((((Th1out-T0)^1/3)+((Th1-T1)^1/3))/2)^3;
 DeltaT2 = ((((Th2out-T0)^1/3)+((Th2-T2)^1/3))/2)^3;

Res = [ % Upper path, 1st HX
         Q1-(w1*(T1-T0));                % Cold Stream, w1
         Q1+(par.wh1*(Th1out-Th1));      % Hot Stream, wh1   
         Q1-(UA1*DeltaT1);               % HX Design Equation
        
        % Lower path, 2nd HX
         Q2-(w2*(T2-T0));                % Cold Stream, w2
         Q2+(par.wh2*(Th2out-Th2));      % Hot Stream, wh2
         Q2-(UA2*DeltaT2);               % HX Design Equation
        
        % Mass balance
         w1+w2-w0;

        % Energy balance
         (w0*Tend)-(w1*T1)-(w2*T2)];
      
      
end

