%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                       %
%      UNISIM COMMUNICATION                                             %
%      AUTHOR: DANIEL GREINER EDVARDSEN                                 %
%      DATE: DECEMBER 5, 2010                                           %
%      PLACE: DEPARTMENT OF CHEMICAL ENGINEERING, NTNU, TRONDHEIM       %
%                                                                       %
%                               CASE III                                %
%                                                                       %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% This m-file accesses the mymodel.usc model in UniSim Design and provides
% all communication in between MATLAB and the UniSim software.

clc;
clear all;

% Establishing access to the UniSim Design Server and mymodel.usc
h = actxserver('UnisimDesign.Application');
hyCase = h.Activedocument ;
solv = hyCase.Solver ;
f = hyCase.Flowsheet ;      
m = f.MaterialStreams ;

%Initital values
x0 = 1.0e+003 * [

    1.5650
    0.8000
    0.0240
    0.0158
    0.0080
    0.0081
    0.0081
   -0.0145
   -0.0145
   -0.0500
   -0.0500
      ];

%Scaling
global scale1;
scale1 = [500 500 2 2 2 5 5 5 5 5 5]'; 

u0 = x0./scale1;
u0 = u0(:,1);

N = size(x0);

%Lower bounds
lb = [1500
    700
    23.8
    15.7
    7.9
    7
    7
    -15
    -15
    -51
    -51] ;

%Upper bounds
ub = [1600
    900
    24.1
    15.9
    8.1
    9
    9
    -14
    -14
    -49
    -49] ;

lb=lb./scale1;
ub=ub./scale1;

options = optimset('Display','iter', 'Diagnostics', 'on', 'TolFun', 1e-12, 'PlotFcns', ...
    @optimplotfirstorderopt, 'DiffMinChange', 1e-5, 'TolX', 1e-4, 'MaxFunEvals', 100*N(1), 'Algorithm', 'interior-point');

%Optimization
[u,fval,exitflag,output,lambda,grad,hessian] = fmincon(@myfun,u0,[],[],[],[],lb,ub,@mycon,options);
