%Non-linear optimisation w. fmincon
%This optimisation routine grabs the open HYSYS file and applies the
%fmincon optimiser to the flowsheet
%In this case: Subset 1a Reaction Section

%Grabbing Hysys object
    global hy,global hycase
    hy=actxserver('Hysys.Application'); %Hysys handle w. actx
    hycase=hy.Activedocument;
%Initial inputs, u0 is vector containing initial HYSYS-inputs
    isprd=hyspread(hy,'Input'); 
   %u0=[CW-1,C1-RPM,Split VLV-2,HP-S,AC-1,CW-2,Purge]
    u0=hyvalue(hycell(isprd,{'D2','D3','D4','D5','D6','D7','D8','D9'}));
%Define bounds for input (for MATLAB optimization)
    global lb, global ub
    %Lower bounds
    lb=hyvalue(hycell(isprd,{'E2','E3','E4','E5','E6','E7','E8','E9'}));
    %Upper bounds
    ub=hyvalue(hycell(isprd,{'F2','F3','F4','F5','F6','F7','F8','F9'}));
%Nonlinear optimisation w. fmincon
    %Scale inputs to bounds
    u0s=uscale(u0,lb,ub);
    %Input bounds for optimization
    lbm=zeros(size(lb));
    ubm=ones(size(ub));
    opt=optimset('TolFun',9e-8,...
             	 'TolCon',1e-4,...
                 'Display','iter',...
                 'Algorithm','interior-point',...
                 'Diagnostics','on',...
                 'FinDiffType','central',...
                 'ScaleProblem','obj-and-constr',...
                 'FinDiffRelStep',1e-2);
             
             
             
             
    tic
    [x,fval,exitflag,output,lambda]=fmincon(@(u)objfunct(u),u0s,[],[],[]...
                                       ,[],lbm,ubm,@(u)constraints(u),opt);
    elapsed_time=toc;
         