% m file for optimizing the Unisim model MCHE_tempspecs.usc

clear all
clc

load x0
load ua
load disturbances

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

%Define x0, upper and lower bounds:
x0 = x0_temp ;
lb = [4240 ; 490 ; 100/3600 ; -100; -100 ; -100 ; -158.15 ; -159.15 ; 40/3600 ; 0/3600 ;  6/3600] ;
ub = [4440 ; 537 ; 104/3600 ;  -85;  -85 ;  -85 ; -156.15 ; -156.15 ; 45/3600 ; 4/3600 ; 10/3600] ;

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 ;
parameters.ua = ua ;

options = optimset('Display','iter','TolFun',1e-5,'TolCon',1e-5,'Algorithm','active-set','DiffMinChange',1e-4);

dist=linspace(d(3)*0.95,d(3)*1.05,11);
exitflags = zeros(1,11) ;

for i=1:11
    d(3) = dist(i) ;
%     init_temp % Run the script which gives us a new x0
    disp(['Starting optimization number ' num2str(i)])
    [x_opt,fval,exitflag,output,lambda] = fmincon(@MCHE_obj_temp,x0,[],[],[],[],lb,ub,@MCHE_constraints_temp,options,d,parameters);
    exitflags(i) = exitflag ;
    if exitflag > 0
        disp([num2str(i) '. optimization successful'])
    else
        disp([num2str(i) '. optimization failed'])
    end
end

disp('Resetting Unisim model')
Reset_MCHE_temp(x0_temp,d,h) ; %Reset Unisim model to default values!