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


function [Cineq, Res] = HEN_Constraints_11_HXD_DJT2(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); 

% Parameters
w0 = par.w0; wh1 = par.wh1; wh2 = par.wh2;
Th1 = par.Th1; Th2 = par.Th2; T0 = par.T0;
UA1 = par.UA1; UA2 = par.UA2;
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 EQUAITONS
%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;
 
%Jaeschke Temperatures
 DJT1 = (T1-T0)^2/(Th1-T0);
 DJT2 = (T2-T0)^2/(Th2-T0);

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);
         
         % Jaeschke constraint
         DJT1 - DJT2];
    
     
end

