% m file for optimizing the Unisim model MCHE_areaspecs.usc

clear all
clc

load x0
load ua
load disturbances



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

%Define x0, upper and lower bounds:
x0 = x0_area ;
lb = [4240 ; 500 ; 101/3600 ; 40/3600 ; 0/3600 ;  6/3600 ; -158.15 ; -100 ] ;
ub = [4440 ; 537 ; 103/3600 ; 45/3600 ; 4/3600 ; 10/3600 ; -156.15 ;  -80 ] ;

scale_x = diag(2.^(fix(log2(ub - lb)))) ;

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

parameters.scale_x = scale_x ;

%Now define whether recycles should be handled by Unisim or by matlab:
parameters.recycles = 'matlab' ;
% parameters.recycles = 'unisim' ;

switch parameters.recycles
    case('matlab')
        parameters.scale_ceq = eye(3) ;
    case('unisim') % If Unisim solves recycles we don't need the last two elements of x.
        parameters.scale_ceq = 1 ;
        x0 = x0(1:6);
        parameters.scale_x = scale_x(1:6,1:6) ;
        lb = lb(1:6);
        ub = ub(1:6);
end


options = optimset('Display','iter','TolFun',1e-5,'TolCon',1e-3,'Algorithm','active-set','MaxIter',50);
x_opt = fmincon(@MCHE_obj_area,x0,[],[],[],[],lb,ub,@MCHE_constraints_area,options,d,parameters);

disp('Resetting Unisim model')
Reset_MCHE_area(x0_area,d,h) ;