% Optimize Unisim model "C3MR_Precooling.usc"
% Make sure this file is open in Unisim before proceeding.

% clc
clear all

global h
h=actxserver('UnisimDesign.Application');

load x0_precooling
load dist_precooling

x0 = x0_precool ;

lb = [12/3600 ; 60.5/3600 ; 1100 ; 420 ; 210 ; 105.0 ] ;
ub = [12.6/3600 ; 64/3600 ; 1300 ; 480 ; 250 ; 125 ] ;

%Scale limits and starting guess.

scale_x = diag(10.^(fix(log10(ub - lb)))) ;

x0 = scale_x\x0 ;
lb = scale_x\lb ;
ub = scale_x\ub ;

x0(1) = ub(1) ;
x0(3) = lb(3) ;
x0(4) = ub(4) ;
x0(6) = lb(6) ;

parameters.scale_x = scale_x ;
parameters.scale_c=diag([60 60 120 1 1]);
parameters.constraint = 'enthalpy' ;
%If changing disturbances, do it here.
d = d0 ; 


%'interior-point' 'active-set' ,'DiffMinChange',1e-6,'DiffMaxChange',1e-2
options = optimset('Display','iter','TolFun',1e-3,'TolCon',1e-1,'Algorithm','active-set','MaxFunEvals',1000,'MaxIter',100,'DiffMinChange',1e-4);
tic
% C = Precooling_constraints(x0,d,parameters)
[x_opt,J_opt,exitflag,output,lambda] = fmincon(@Precooling_obj,x0,[],[],[],[],lb,ub,@Precooling_constraints,options,d,parameters) ; 
C = Precooling_constraints(x_opt,d,parameters);
C = parameters.scale_c*C 
t1=toc ;

% gaoptions = gaoptimset('Display','iter','TolFun',1e-5,'TolCon',1e-2,'Generations',25,'PlotFcns',{@gaplotbestf @gaplotbestindiv @gaplotmaxconstr},'InitialPopulation',x0') ;
% tic
% x_opt_gen = ga(@(x) Precooling_obj(x,d,parameters),6,[],[],[],[],lb,ub,@(x) Precooling_constraints(x,d,parameters),gaoptions) ;
% x_opt_gen = x_opt_gen(:) ;
% t2 = toc ;


unitscale_x=diag([3600 3600 0.01 0.01 0.01 0.01]); % Turn flows into kmol/h and pressures into bar


% Reset_Precooling(x0_precool,d0,h) ; 