close all;
clear all;
clc;

format shortE

% % % x = [9.5d-06, 3.d-03, 7.5d-09, 7.d-08];
x=[1.1676e-04   6.5485e-04   1.0233e-10   1.5080e-03]; %%% Ktheta = 1.8991e-03

x = [9.976238e-05, 9.473171e-04, 9.257424e-13, 2.299841e-03];

x0 = x;

    y = [1.0352d+02, 7.9071d-02, 9.4886d-02, -5.1277d-01, 4.0099d-02, 1.8228d+00; .....
         2.8634d+02, 5.7697d-02, 8.2231d-02, -5.1332d-01, 5.9229d-02, 2.1112d+00; .....
         2.6601d+02, 8.8987d-02, 5.7826d-02, -5.2279d-01, 4.1180d-02, 2.3182d+00; .....
         5.7211d+02, 8.6020d-03, 1.3256d-01, -5.9245d-01, 3.9716d-02, 2.4200d+00; .....
         1.8587d+03, -2.2881d-01, 1.8505d-01, -5.9238d-01, 9.9792d-02, 3.1086d+00; .....
         4.5732d+06, -2.4999d+00, 6.0861d-01, -4.3516d-01, 4.1953d-02, 3.2112d+00];
     
title1 = ['ThetaG_Lv_FI_T2_D1_R1.csv';'ThetaG_Lv_FI_T2_D1_R2.csv';'ThetaG_Lv_FI_T2_D1_R3.csv';'ThetaG_Lv_FI_T2_D2_R1.csv';'ThetaG_Lv_FI_T2_D2_R2.csv';'ThetaG_Lv_FI_T2_D2_R3.csv'];
n = 6;

 options = optimoptions('fmincon','Display','iter','Algorithm','interior-point','TypicalX',x,'FinDiffRelStep',[1e-2,1e-2,1e-2,1e-2],'TolFun',1e-9);
 A = [];
 b=[];
 Aeq=[];
 beq=[];
lb = [1.121409e-06   6.075168e-06   9.209827e-13   1.5e-03];
ub = [1.121409e-02   6.075168e-02   9.209827e-09   2.5e-03];

 nonlcon=[];
   
 fun=@(x) Myobjective(x,y,title1,n);
    
 [x, fval] = fmincon(fun,x,A,b,Aeq,beq,lb,ub,nonlcon,options);
 
extx = '.txt';
title_filex = 'Parameters';
title_case = strcat(title_filex,extx);

fileID = fopen(title_case,'w');
fprintf(fileID,'%6s %6.6e\n','kE =',x(1));
fprintf(fileID,'%6s %6.6e\n','kT =',x(2));
fprintf(fileID,'%6s %6.6e\n','kV =',x(3));
fprintf(fileID,'%6s %6.6e\n','Ktheta =',x(4));
% % % % fprintf(fileID,'%6s %6.6e\n','SCO2,0 =',x(5));
fclose(fileID);
