
%%%%% load data from real test result
% [file,path] = uigetfile('*.xlsx','Select field data');
% if file~=0
%     A = xlsread([path file]);
% %     Q_0=A(:,1);
% %     Ca_0=A(:,2);
% %     Cb_0=A(:,3);
% %     Cc_0=A(:,4);
% end
%%%%% load data from field test result


%%%%%%%%%%%%%%%%%%%%%%% load data from simulated result
% [file,path] = uigetfile('*.txt','Select training data for production time');
% if file~=0
%     t_0 = dlmread([path file]);
% end
% [file,path] = uigetfile('*.txt','Select training data for Ca');
% if file~=0
%     Ca_0 = dlmread([path file]);
% end
% 
% 
% [file,path] = uigetfile('*.txt','Select training data for Cb');
% if file~=0
%     Cb_0 = dlmread([path file]);
% end
% 
% 
% [file,path] = uigetfile('*.txt','Select training data for Cc');
% if file~=0
%     Cc_0 = dlmread([path file]);
% end
% %%%%%%%%%%%%%%%%%%%%%%% load data from simulated result



A=[t_0 Ca0 Cb0 Cc0];
Q=[1000 1500 2000]; %%%%volumetric rate of injection step1, injection step 2 and production
q=[200 800];  %%%%. Volume of injection step 1 and step 2 in barrels
Ts=3;  %%% well shut in duration in days
constant=[4.6 32 0.25 Ts 100000];   
%% partition coefficient of tracer A, formation thickness in ft, porosity, injected concentration of tracer A in ppm



funObj = @(tuning)target_function(tuning,Q,q,constant,A);



%%%% define optional parameters for optimization
option=[];
option.numDiff=1;
option.maxIter=2000;
option.method='bfgs';
option.damped=1; 
option.optTol=1e-8;

%%%%%provide initial guess of fitting parameters
Sor=0.6;
k=0.05;
alpha=1.1;

f1=0.8;
f2=0.8;
%%%%%provide initial guess of fitting parameters




isRunning=1;
count=1;


while isRunning==1

    
   clc
   disp(['Round ' num2str(count) ':Fitting partitioning tracer...\n'])
   
    
   %%%%%fit tracer A and C with alpha, f1, f2 
   
   
   index=1;  %%% tell the funObj which are tunning parameters
   tuning2=[Sor,k]; 
   LB = [0;0.5;0.5];
   UB = [5;1;1];
  
   funObj = @(tuning)target_function(tuning,tuning2,Q,q,constant,A,index);
   w = minConf_TMP(funObj,[alpha;f1;f2],LB,UB,option);
   

   alpha_temp=w(1);
   f1_temp=w(2);
   f2_temp=w(3);
   
   if abs(alpha_temp-alpha)<0.001*alpha && abs(f1_temp-f1)<0.001*f1 && ...
           (f2_temp-f2)<0.001*f2 && count>1
       alpha=alpha_temp;
       f1=f1_temp;
       f2=f2_temp;
       break;
   end    
   
   alpha=alpha_temp;
   f1=f1_temp;
   f2=f2_temp;
   
   clc;
   
   %%%%%fit partitioining tracer with alpha, f1, f2 
  
   disp(['Round ' num2str(count) ':Fitting n-nopartitioning tracer...\n'])
   index=2;
   tuning2=[alpha,f1,f2];
   LB = [0;0];
   UB = [1;1];
   funObj = @(tuning)target_function(tuning,tuning2,Q,q,constant,A,index);
   w = minConf_TMP(funObj,[Sor;k],LB,UB,option);
   Sor_temp=w(1);
   k_temp=w(2);
   
   
   if abs(Sor_temp-Sor)<0.001*Sor && abs(k_temp-k)<0.001*k && count>1
       Sor=Sor_temp;
       k=k_temp;
       break;
   end
   
   Sor=Sor_temp;
   k=k_temp;
   
   count=count+1;

end



