% PROGRAM:        T2ED  
% VERSION:         [Interactive Standalone Version] V_1.8
% COMPATIBLE with Matlab version 2017b or later
% TOOLBOX: "Clustering/Transformation to ED Toolbox" within SERA Project
% DOCUMENT: "READ_ME_App_1A_v1_Description_T2ED.docx"
% --------------------------------------------------------------------------------------------------------------------
% Transformation of multiple parameters into Equavalent Dimensions:
% --------------------------------------------------------------------------------------------------------------------
% INPUT:
% !!! ----------------------------  INPUT DATA REQUIREMENTS ----------------------------- !!!
% the program works with ASCII input data files (e.g. *.txt). The files needed are:
% >   File(s) with the parameters of seismic and/or production data
% >   Files(s) with the fields description of the corresponding parameters
%                within the seismic and/or production data files
% FOR DETAILS on data requirements please refer to the document:
%                            "READ_ME_App_1A_v1_Description_T2ED.docx"
% --------------------------------------------------------------------------------------------------------------------
% OVEIRVIEW: THE PROGRAM takes as input a Seismic or/and a Production data parameters and 
%  transforms them into their Equivalent Dimensions (ED) following the Lasocki (2014) methodology 
% --------------------------------------------------------------------------------------------------------------------
% AUTHORS: K. Leptokaropoulos and P. Urban, 
% Last Updated: 03/2019, within SERA PROJECT, EU Horizon 2020 R&I 
% programme under grant agreement No.730900
% CURRENT VERSION: v1.8        ****    [INTERACTIVE STANDALONE VERSION!!]
%% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% PLEASE refer to the accompanying document:
%                                                              "READ_ME_App_1A_v1_Description_T2ED.docx" 
% for description of the Application and its requirements.
%% -----------------------------------------------------------------------------------------------------------------------
% DESCRIPTION: the code includes several functions performed step-
% by-step for data selection, filtering and preparation in order to apply
% the Transformation to Equivalent Dimensions. This latter process is 
% adequately described in Lasocki [2014] and comments in the EQ_DIM
% function. A brief description of the preparation process is given here:
% (please see in the script for more comments and details for each STEP)
% STEP_1. MODE SELECTION: Selection of Input Data Type(s)
% STEP_2. DATA SELECTION & FILTERING: this step includes:
%                - Selection of Data set(s)
%                - Selection of parameters from the data set(s)
%                - Graphical Selection of Mc (from a specified M scale)
%                - Selection of ED_DIM Parameters
% STEP_3. SELECT BACKGROUND Sample and TESTING Data: 
%                  starting and ending time or event to define the backgound 
%                  sample and the testing data (either by typing events/dates
%                  or by graphically selected from a plot).
% STEP_4: RUN EQ_DIM PROGRAM: for all the selected parameters
% STEP_5: DISPLAY AND SAVE OUTPUTS:
% 
% ---------------------------------------------------------------------------------------------------------------------
% INPUT:   All input data are sufficiently explained in the script as well as 
%               while running the code (interaction with the user). NOTE that
%               the catalog (seismic), as well as the production data must be 
%               in ASCII format (i.e. *.txt). 
%               Please refer to the APPLICATION DOCUMENTATION for further 
%               instructions and input data requirement specifications:  "READ_ME_App_1A_v1_Description_T2ED.docx"
% ----------------------------------------------------------------------------------------------------------------------
% OUTPUT:
%                 <> Output Report with data and parameters used 
%                 <> Output Matlab Structure with input (Original) and output (Transformed) data. 
%                                 Structure fields are:
%                    - xt               : vector with a transformed testing data of a parameter
%                    - xBG          : vector with a transformed background sample of a parameter
%                    - ierr            : h-convergence indicator (See EQ_DIM for details)
%                    - h                : kernel smoothing factor
%                    - xx*            : vector with the background sample considered for transformation
%                    - ambd*      : weigthing factors for the adaptive kernel
%                    - field          : [string] indicating the corresponding field (transformed parameter)
%           - index_Testing   : [vector] Index indicator of Testing Data from the original Dataset 
%                                           (‘origval_all’ field) which were transformed   
%      - index_Background: [vector] Index indicator of Background Sample from the original 
%                                           Dataset (‘origval_all’ field) which were transformed   
%                    - all+            : vector with size of the original parameter vector including the
%                                           transformed parameters and NaNs
%                    - origval       : vector with the original parameters that were transformed
%                 - origval_all+ : original input vector with the parameters that were transformed 
%                                           and NaN's 
% -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
% * can be doubled or tripled according to the selected “sampl_mult” value
% +NaNs may be included in some of these vectors
% -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
%                <> Output Figures: histograms with original and transformed background &
%                                                 full samples as well as adaptive kernel weighting factors 
%                <>  Output ASCII Files: For convenience of the User, three additional ASCII 
%                                                 files are produced with the main results of the Application:
%                      - Data_Original.txt        : File containing the Original parameters of Seismic 
%                                                                and Production data selected for the Analysis. Each 
%                                                                column corresponds to the values of one parameter, 
%                                                                which is defined in ‘Data_Fields.txt’ output file.   
%                      - Data_Transformed.txt : File containing Transformed parameters of Seismic 
%                                                                 and Production data derived by the Analysis. Each 
%                                                                 column corresponds to the values of one parameter, 
%                                                                 which is defined in ‘Data_Fields.txt’ output file.
%                      - Data_Fields.txt          : File containing the labels (Fileds )of each column of the 
%                                                              previously described output (ASCII) files.
% ---------------------------------------------------------------------------------------------------------------------
% REFERENCES:
% Lasocki S. (2014) GJI. 197(2), 1224-1235, doi:10.1093/gji/ggu062
% ---------------------------------------------------------------------------------------------------------------------
% LICENSE 
%     This is free software: you can redistribute it and/or modify it under 
%     the terms of the GNU General Public License as published by the
%     Free Software Foundation, either version 3 of the License, or 
%     (at your option) any later version.
% 
%     This program is distributed in the hope that it will be useful, but 
%     WITHOUT ANY WARRANTY; without even the implied warranty 
%     of MERCHANTABILITY or FITNESS FOR A PARTICULAR
%     PURPOSE. See the GNU General Public License for more details.
% -------------------------------------------------------------------------------------------------------------------


clear;clc
mkdir Outputs_ED

% ***********        STEP_1: DATA and MODE SELECTION        **************
[Catalog,PROD_Data,Mode1,dstr1,dstr2,s,s1,ss,s2]=Data_Hand_A2M;


% ********   STEP_2: DATA SELECTION & FILTERING   ********** 
% if Mode 1, or 3 is selected, filtering for M>=Mc is also performed 
% Modes Application, Upload Data 
switch Mode1

    case 1
  % Select Mc and filter parameters for M>=Mc 
  [Ctime,Cmag,Data,Mc]=FiltMc(Catalog,s1);
  PROD_time=[];Data2=[];s2=[];Description=[];           % empty incative parameters and structures
  ss=[];FieldDescription=[];                                            % empty incative parameters and structures
  %Select Parameters for T2ED
  [randmode,sample_mult,DT]=ED_params(Mode1);

  
    case 2
  [id] = findfield(PROD_Data,'Production_Time');
  PROD_time=PROD_Data(id).val;
   [Data2]=NonS_Data(PROD_Data,s2);
  
  Ctime=[];s=[];s1=[];Catalog=[];Mc=[];                    % empty incative parameters and structures
  %Select Parameters for T2ED
  [randmode,sample_mult,DT]=ED_params(Mode1);
  
    case 3
   [Ctime,Cmag,Data,Mc]=FiltMc(Catalog,s1);       % seismic data
 
   [id] = findfield(PROD_Data,'Production_Time');              % Production (non-seismic) data
   PROD_time=PROD_Data(id).val;
   [Data2]=NonS_Data(PROD_Data,s2);     
        
   [randmode,sample_mult,DT]=ED_params(Mode1); 
   %MergeData (Seismic/ Non-Seismic)

   [Data,Data3]=MergeSNSdata(PROD_time,Ctime,DT,Data,Data2);
end



% ********    STEP_3: SELECT BACKGROUND SAMPLE   ********
disp(' '),disp(' '),disp(' ')
disp('Select Starting and Ending Point for Background And Testing Data');
if Mode1==2;disp('"1" -  for typing observations');else;disp('"1" -  for typing events');end
disp('"2" -  for typing time');
disp('"3" -  for selecting from plot');
disp('"0" -  for using the entire data as background sample');
BGD=input(' ');

[option,P1,P2,t1,t2]=BcGround_Sample(BGD,Mode1,Ctime,PROD_time,Data2,s2,1);
[option,Pt1,Pt2,tt1,tt2]=BcGround_Sample(BGD,Mode1,Ctime,PROD_time,Data2,s2,2);

% DISPLAY parameters report in the screen
parameters_report(Mode1,dstr1,dstr2,s,ss,s1,s2,Catalog,PROD_Data,randmode,sample_mult,Mc,DT,t1,t2,tt1,tt2);

% **********     STEP_4: RUN EQ_DIM PROGRAM    **********
% Run T2ED in loop
if Mode1==2;D=Data2;t=PROD_time;else;D=Data;t=Ctime;end
nn1=length(D);
for i=1:nn1
x=D(i).val;
[xt,xBG,ierr,h,xx,ambd,IX1,IX2]=T2ED_Wrapper_MODE1(option,P1,P2,Pt1,Pt2,x,randmode,sample_mult,D(i),t(D(i).index),D,i);
Tdata(i).xt=xt;
Tdata(i).xBG=xBG;
Tdata(i).ierr=ierr;
Tdata(i).h=h;
Tdata(i).xx=xx;
Tdata(i).ambd=ambd;
Tdata(i).field=(['Transformed_',D(i).field]);
Tdata(i).index_Testing=IX1;
Tdata(i).index_Background=IX2;
Tdata(i).all=nan(size(D(i).index));Tdata(i).all(IX1)=xt;Tdata(i).all(IX2)=xBG;
Tdata(i).origval=x;
Tdata(i).origval_all=D(i).all;
% save figures
cd Outputs_ED;saveas(gcf,[D(i).field,'.jpg']);cd ../
%clearvars xt ierr h xx ambdb
end

% *********   STEP_5: DISPLAY AND SAVE OUTPUTS   ********
% Save Outputs
SaveOuts(Mode1,dstr1,dstr2,s,ss,s1,s2,Catalog,PROD_Data,randmode,sample_mult,Mc,DT,t1,t2,tt1,tt2,Tdata)
close all
disp(' ')
disp('Please Find the Results in Folder: "Outputs_ED" ')

%% ASCII OUTPUT FILE
cd Outputs_ED\
fid=fopen('Data_Original.txt','w');
fid1=fopen('Data_Transformed.txt','w');
fid2=fopen('Data_fields.txt','w');
for i=1:size(Tdata,2)
D_O(:,i)=Tdata(i).origval_all;
D_T(:,i)=Tdata(i).all;
D_F{i}=Tdata(i).field;
fprintf(fid2,'%s    ',D_F{i});
end
fprintf(fid,[repmat('%32.16f      ',[1,size(D_O,2)]),'\n'],D_O');
fprintf(fid1,[repmat('%12.10f    ',[1,size(D_T,2)]),'\n'],D_T');
fclose(fid);fclose(fid1);fclose(fid2);cd ../



%% *************************** FUNCTIONS ***************************
% ****-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-****
%% --------------------------------------------------------------------------------------
    %Select Seismic Catalog and the parameters the user wishes to study
function [s,ss1]=SeisDatLoad(dstr)        
% Select Seismic Catalog
[s,ok]=listdlg('PromptString','Select Seismic Catalog:',...
    'SelectionMode','single',...
    'ListString',dstr);
if ok; load(dstr{s});end

%Select Parameters from Seismic Catalog
[s1,ok]=listdlg('PromptString','Select field(s):',...
    'ListString',{Catalog.field});
for i=1:length(s1)
    ss1=s1(isnan(s1)==0);
end

end

%% -------------------------------------------------------------------------------------
%Select Non-Seismic Data Source (PRODuction File) and the parameters the user wishes to study
function [ss,s2,Fields]=NonSeisDatLoad(dstr)
% Select Production Date File
[ss,ok]=listdlg('PromptString','Select Production Dataset:',...
    'SelectionMode','single',...
    'ListString',dstr);
if ok; load(dstr{ss});end     

for j=1:size(FieldType,1);
    Fields{j}=FieldType{j};
end

%Select Parameters from Production Date File            
[s2,ok]=listdlg('PromptString','Select field(s):',...
    'ListString',Fields);
end    

%% --------------------------------------------------------------------------------------
% Select Mc and filter parameters for M>=Mc
function [Ctime,Cmag,Data,Mc]=FiltMc(Catalog,s1)
clc
id_time=findfield(Catalog,'Occurrence_Time');
opts.Interpreter='tex';opts.Default='Yes';
quest='Do you wish to filter Data for Mc?';
answer=questdlg(quest,'Data Completeness','Yes','No',opts);

if strcmp(answer,'Yes')
cou=1;
for i=1:length(Catalog)
    if strcmp(Catalog(i).fieldType,'Magnitude')==1
        C(cou).field=Catalog(i).field;cou=cou+1;
end
end

% Check for no magnitude
if cou==1;error('MyComponent:incorrectType',...
'No magnitude column detected!! Please check: Magnitude fields must be noted as one of the following:\nM  ,  Mw  ,  ML  ,  Ms  ,  mb  ,  Md\n or select the entire sample for analysis');end

%Select Parameters from Seismic Catalog
[ss1,ok]=listdlg('PromptString','Please Select M scale:',...
    'ListString',{C.field}, 'SelectionMode','single');

 id=findfield(Catalog,C(ss1).field);
  Mtype=Catalog(id).field;

Ctime=Catalog(id_time).val;
id_M=findfield(Catalog,Mtype);
Cmag=Catalog(id_M).val;

ar=min(Cmag):0.1:max(Cmag);
fig_Mc=figure;histogram(Cmag,length(ar));set(gca,'YScale','log')
title('Please Select M_C','FontSize',14);xlabel('M','FontSize',14),ylabel('Log_1_0N','FontSize',14)
% Select events above Mc
[Mc,N]=ginput(1);Mc=floor(10*Mc)/10;close(fig_Mc);

Ctime=Ctime(Cmag>=Mc);
disp(['Mc: ',num2str(Mc)])

elseif strcmp(answer,'No')
Ctime=Catalog(id_time).val;Cmag=Ctime;Mc=-20;
end

cou=1;
for i=1:length(s1)
    x=Catalog(s1(i)).val;x=x(Cmag>=Mc);
    index=isnan(x)==0;
    x=x(isnan(x)==0);
    Data(cou).val=x;
    Data(cou).field=Catalog(s1(i)).field;
    Data(cou).index=index;
    Data(cou).all=nan(size(Data(cou).index)); Data(cou).all(index)=x;
    cou=cou+1;
end
n=length(Ctime);
disp(['number of events: ',num2str(n)]) 

end

%% -------------------------------------------------------------------------------------
%Treat Production Data to be used further in the script
function [Data2]=NonS_Data(PROD_Data,s2)
cou=1;
for i=1:length(s2)
    x=PROD_Data(i).val;
    index=isnan(x)==0;
    x=x(isnan(x)==0);
    Data2(cou).val=x;
    Data2(cou).field=PROD_Data(i).field;
    Data2(cou).index=index;
    Data2(cou).all=nan(size(Data2(cou).index)); Data2(cou).all(index)=x;
    cou=cou+1;
end

end

%% --------------------------------------------------------------------------------------
% finds a field defined by a certain (string) name
function [id] = findfield( catalog,field )
id=0;
j=1;
while j <= size(catalog,2) && id==0
        if (strcmp(catalog(j).field,field)==1)
        id=j;
        end
        j=j+1;
end
end

%% --------------------------------------------------------------------------------------
%Select Parameters for T2ED
function [randmode,sample_mult,DT]=ED_params(Mode1)

if Mode1==1 || Mode1==2
 prompt={'\fontsize{12} Please enter randomization mode \color{red} "exp","norm","uni",no":','\fontsize{12} Please enter the sample multiplication mode \color{red} "no","left","right","both":'};
 name='Parameters Selection';
 numlines=1;
 defaultanswer={'exp','both'};
 opts.Interpreter='tex';
 answer=inputdlg(prompt,name,numlines,defaultanswer,opts);
 randmode=answer(1);sample_mult=answer(2);DT=[];
elseif Mode1==3
 prompt={'\fontsize{12} Please enter randomization mode \color{red} "exp","norm","uni",no":','\fontsize{12} Please enter the sample multiplication mode \color{red} "no","left","right","both":','\fontsize{12} Please enter the time lag in days (>=0):'};
 name='Parameters Selection';
 numlines=1;
 defaultanswer={'exp','both','0'};
 opts.Interpreter='tex';
 answer=inputdlg(prompt,name,numlines,defaultanswer,opts);
 randmode=answer(1);sample_mult=answer(2);DT=answer(3);DT=str2double(char(DT));
end
end

%% --------------------------------------------------------------------------------------
% Set Background Sample
function [option,P1,P2,t1,t2]=BcGround_Sample(BGD,Mode1,Ctime,PROD_time,Data2,s2,cout)
Y=[];
if cout==1;
    disp('  ')
    disp('---- For the Background Sample ----')
    disp('  ')
elseif cout==2;
    disp('  ')
    disp('  ')
    disp('------- For the Testing Sample -------')
    disp('  ')
end


switch BGD
    case 1
option='1';
if Mode1==2
P1=input('Please type starting observation: ');t1=PROD_time(P1);
P2=input('Please type ending observation: ');t2=PROD_time(P2);
else
P1=input('Please type starting event: ');t1=Ctime(P1);
P2=input('Please type ending event: ');t2=Ctime(P2);
end
   
    case 2
option='2';
disp('e.g."01-Jan-2014 00:00:01" ');
P1=input('Please type starting date: ');P1=datenum(P1);t1=P1;
P2=input('Please type ending date: ');P2=datenum(P2);t2=P2;

   case 3
option='2';
if Mode1==1
 fig1=figure('Position',[300 100 1600 500]);
 plot(Ctime,1:length(Ctime),'LineWidth',1);datetick('x',26);
 xlabel('Date','FontSize',16);ylabel('Cumulative events count','FontSize',16);
xcoo=Ctime(1);ycoo=length(Ctime);
yyaxis left;
if cout==1
text(xcoo,ycoo,'BackGround Data','FontSize',18,'Color','red');
elseif cout==2
text(xcoo,ycoo,'Testing Data','FontSize',18,'Color','red');
end
[t1,p1]=ginput(1);[t2,p2]=ginput(1); P1=t1;P2=t2; close(fig1);
%if isempty(t1);P1=Ctime(1);P2=Ctime(n);end


elseif Mode1==2
 fig1=figure('Position',[300 100 1600 500]);hold on;
 for i=1:length(s2);
     if strcmp(Data2(i).field,'Production_Time')==0
 plot(PROD_time,Data2(i).all,'LineWidth',1);datetick('x',26);
Y=[Y;Data2(i).all];
     end
 end
 xlabel('Date','FontSize',16);ylabel('Operational Parameter','FontSize',16);
% title({Description},'FontSize',12);
 xcoo=PROD_time(1);ycoo=max(Y);   
yyaxis left;
if cout==1
text(xcoo,ycoo,'BackGround Data','FontSize',18,'Color','red');
elseif cout==2
text(xcoo,ycoo,'Testing Data','FontSize',18,'Color','red');
end
[t1,p1]=ginput(1);[t2,p2]=ginput(1); P1=t1;P2=t2; close(fig1);


elseif Mode1==3
   fig1=figure('Position',[300 100 1600 500]);
   hold on
yyaxis left
plot(Ctime,1:length(Ctime),'LineWidth',1);ylabel('Cumulative events count','FontSize',16);
for i=1:length(s2)
     if strcmp(Data2(i).field,'Production_Time')==0
yyaxis right
plot(PROD_time,Data2(i).all,'-','LineWidth',1);
     end
xcoo=min(Ctime(1),Ctime(1));ycoo=length(Ctime);     
end
ylabel('Operational Parameter','FontSize',16);
datetick('x',26);

xlabel('Date','FontSize',16);ylabel('Operational Parameter','FontSize',16);

yyaxis left;
if cout==1
text(xcoo,ycoo,'BackGround Data','FontSize',18,'Color','red');
elseif cout==2
text(xcoo,ycoo,'Testing Data','FontSize',18,'Color','red');
end

[t1,p1]=ginput(1);[t2,p2]=ginput(1); P1=t1;P2=t2; close(fig1);

end

    case 0
if Mode1==2
        n=length(PROD_time);
        option='1';P1=1;P2=n;t1=PROD_time(1);t2=PROD_time(n);
else
        n=length(Ctime);
        option='1';P1=1;P2=n;t1=Ctime(1);t2=Ctime(n);        
end
end

end

%% --------------------------------------------------------------------------------------
% parameters report in the screen
function []=parameters_report(Mode1,dstr1,dstr2,s,ss,s1,s2,Catalog,PROD_Data,randmode,sample_mult,Mc,DT,t1,t2,tt1,tt2)
clc
disp('SELECTED DATA & PARAMETERS REPORT')
disp('----------------------------------------------------')
if Mode1==1
disp(['<Catalog                                                     >: ' dstr1{s}]);
elseif Mode1==2
disp(['<Production Data File                              >: ' dstr2{ss}]);
elseif Mode1==3
disp(['<Catalog                                                     >: ' dstr1{s}]);
disp(['<Production Data File                              >: ' dstr2{ss}]);
end

if Mode1==1
disp(['<Catalog Columns                                    >:'])
for i=1:length(s1)
    disp(['                                                                         -  ',Catalog(s1(i)).field]);
end
elseif Mode1==2
disp(['<Production Data Columns                     >:']);
for i=1:length(s2)
    disp(['                                                                         -  ',PROD_Data(s2(i)).field]);
end
elseif Mode1==3
disp(['<Catalog Columns                                    >:'])
for i=1:length(s1)
    disp(['                                                                         -  ',Catalog(s1(i)).field]);
end
disp(['<Production Data Columns                    >:']);
for i=1:length(s2)
    disp(['                                                                         -  ',PROD_Data(s2(i)).field]);
end
end

if Mode1~=2
    if Mc>-20
disp(['<Completeness Magnitude                       >: ', num2str(Mc,'%3.1f')]);
    else 
disp(['<Completeness Magnitude                       >: ', num2str('All magnitudes included')]);end
    end
if Mode1==3
disp(['<Time Delay (Operations-Seismicity)    >: ', num2str(DT),' days']);
end
disp(['<Randomization Mode                            >: ', char(randmode)]);
disp(['<Sample Multiplication Mode                 >: ', char(sample_mult)]);
disp(['<Starting Poing for background data      >: ', datestr(t1)]);
disp(['<Ending Poing for background data       >: ', datestr(t2)]);
disp(['<Starting Poing for testing data               >: ', datestr(tt1)]);
disp(['<Ending Poing for testing data                >: ', datestr(tt2)]);
disp([' '])
disp(['-------> Press any key to continue ......'])
pause

end

%% --------------------------------------------------------------------------------------
% Merge Seismic. Non-Seismic Data
function [Data,Data2]=MergeSNSdata(PROD_time,Ctime,DT,Data,Data2)
% TRANSFORM TIME to adjust to EQ Occurrence 
N1=size(Data,2);N2=size(Data2,2);

TT=PROD_time+DT;
T=RandomizeT(TT);
cou=1;
for i=1:N2
    Data2(i).all=interp1(T,Data2(i).all,Ctime);
    x=Data2(i).all;
    index=isnan(x)==0;
    x=x(isnan(x)==0);
    Data2(cou).index=index;
    Data2(cou).Tval=x;
    Data2(cou).Tval_all=nan(size(Data2(cou).index)); Data2(cou).Tval_all(index)=x;
    cou=cou+1;
end


% Merge Seismic and Non-Seismic Parameters

for i=1:N2
    Data(N1+i).field=Data2(i).field;
    Data(N1+i).index=Data2(i).index;
    Data(N1+i).all=Data2(i).Tval_all;                   %watch out for the inversed parameters!!!!  - Switch to Data2(i).val for primary original parameters
    Data(N1+i).val=Data2(i).Tval;                %watch out for the inversed parameters!!!!
end

end

%% --------------------------------------------------------------------------------------
% integer time points randomization to float
% For interpolation to occur, randomization of grid vector is necessary
% Uniform distribution is used for randomization within eps/10 accuracy
function [T]=RandomizeT(T1)

dT1=T1(2:length(T1))-T1(1:length(T1)-1);dT1=sort(dT1);
DT1=dT1(dT1>0);eps=min(DT1)/10;
ra=rand(length(T1),1);
T=T1-0.5*eps+eps.*ra;

end

%% --------------------------------------------------------------------------------------
function [xt,xBG,ierr,h,xx,ambd,IX1,IX2]=T2ED_Wrapper_MODE1(option,P1,P2,Pt1,Pt2,x,randmode,sample_mult,Data,t,D,i)

% STEP 1 & STEP 2 - MODE SELECTION & DATA PREPARATION

% STEP 3 - PARAMETERS SELECTION 
% A) BACKGROUND DATA OPTIONS:
% 'Points' - Option='1'
% 'Time' - 'Option='2'

%B)  -------------------------------- Parameters Value List --------------------------------  
% B1)  randmode - string determining the mode of data randomization (3rd input): 
%           'no'   - no randomization, 
%           'exp'  - exponential randomization, 
%           'norm' - Gaussian randomization,
%           'uni'  - uniform randomization
% B2) sample_mult - string determining the way of sample multiplication (4th input): 
%           'no'   - no multiplication, 
%           'left' - dubbling from the left hand side, 
%           'right - doubbling from the right hand side, 
%           'both' - trippling from both sides.

dix=find(Data.index==1);

switch option
    
    case  '1'
 n1=(dix<P1);n1=sum(n1)+1;    
 n2=(dix<=P2);n2=sum(n2);
 nt1=(dix<Pt1);nt1=sum(nt1)+1;    
 nt2=(dix<=Pt2);nt2=sum(nt2);
%if n2>length(x);n2=length(x);end   
    
    case '2'
        
 T1=P1;
 T2=P2; 
 p1=T1-t;p2=T2-t;
 n1=find(p1<0);n2=find(p2>0);
 n1=min(n1);n2=max(n2);

 Tt1=Pt1;
 Tt2=Pt2; 
 pt1=Tt1-t;pt2=Tt2-t;
 nt1=find(pt1<0);nt2=find(pt2>0);
 nt1=min(nt1);nt2=max(nt2);
 
end

IX1=dix(nt1:nt2);
IX2=dix(n1:n2);

%%%% ERROR HANDLING

%if n2>length(x); error(['Please select n2 smaller than ',num2str(length(x)),' events']);
%elseif isempty(x(n1:n2)); error('No events detected! Please select other period');end

if isempty(x(n1:n2)); warning('No events detected! Please select other period');
    xt=nan;xBG=nan;ierr=nan;h=nan;xx=nan;ambd=nan;
elseif isempty(x(nt1:nt2)); warning('No events detected! Please select other period');
   xt=nan;xBG=nan;ierr=nan;h=nan;xx=nan;ambd=nan;
else 
% STEP 4 - RUN T2ED PROGRAM
[xt,xBG,ierr,h,xx,ambd]=EQ_DIMv_2_0(x,n1,n2,nt1,nt2,randmode,sample_mult);
%[yt,ierry,hy,xxy,ambdy]=EQ_DIM(M,n1,n2,randmode,sample_mult);

%dealing with sample multiplication
if strcmp(sample_mult,'left')==1;N=length(xBG);xBG=xBG(N/2+1:N);
elseif strcmp(sample_mult,'right')==1;N=length(xBG);xBG=xBG(N/2+1:N);
elseif strcmp(sample_mult,'both')==1;N=length(xBG);xBG=xBG(N/3+1:2*N/3);end

%round values out of bounds
 xBG(xBG>1)=1;xt(xt>1)=1;
 xBG(xBG<0)=0;xt(xt<0)=0;

% STEP 5 - DISPLAY OUTPUT WARNING 
% Output  Warning: for h-convergence indicator.
if ierr==0; warning('Process has converged') 
elseif ierr==1; warning('Multiple h were encountered - largest h is accepted')
elseif ierr==2; warning('Process did not converge - approximate h value is taken')
end
end

% STEP 6 - STORE OUTPUT PARAMETERS 
% see doc for details:
% xt, ierrx, hx,xxx,ambdx

% STEP 7 - OUTPUT VISUALIZATIONS 
% see doc for details:

% STEP 8 - REPEAT PROCESS FOR THE OTHER PARAMETERS (VECTORS) 
% see doc for details:
% optional plot for check - please comment next line to disable plotting
%% ------------------------------------   PLOTTING  -------------------------------------
%-------------------------------------------------------------------------------------------------------------------------------------------
% plotHists Script:
figure('Position',[200 100 800 900]);
set(gcf, 'PaperSize', [6 4]);
if isempty(IX1) || isempty(IX2)
title(['Original Dimension - ',D(i).field],'Interpreter','none')
text(0.14,0.75,'No events detected!!','FontSize',26,'Color',[0.9 0.10 0.05])
text(0.21,0.6,'Please select another','FontSize',20)
text(0.06,0.5,'backgound or/and testing period','FontSize',20)
else
st=range(x)/25;
xtest=x(nt1:nt2);
xb=x(n1:n2);
a=(min([x;xb]):st:max([x;xb]));a10=0:0.1:1.0;if isempty(a);a=[min(x)/2 3*min(x)/2];end   %control empty(a)
%min(x),max(x)
subplot(3,1,1);histogram(xb,a,'FaceColor',[0.20 0.25 0.90]);hold on;histogram(xtest,a,'FaceColor',[0.70 0.65 0.80]);
lgd1=legend('Background Sample','Testing Data','Location','northeast');
title(['Original Dimension - ',D(i).field],'Interpreter','none')
if strcmp(D(i).field,'Occurrence_Time') | strcmp(D(i).field,'Production_Time');datetick('x',20,'keeplimits');end
xlabel([D(i).field],'FontSize',14,'Interpreter','none')
xlim([min(x) max(x)]);

subplot(3,1,2);histogram(xBG,a10,'FaceColor',[0.20 0.25 0.90]);hold on;
histogram(xt,a10,'FaceColor',[0.70 0.65 0.80]);title('Equivalent Dimension')

subplot(3,1,3);plot(xx,ambd,'o');title('adaptive kernel');lgd2=legend('weighting factors','Location','best');
if strcmp(D(i).field,'Occurrence_Time') | strcmp(D(i).field,'Production_Time');datetick('x',20,'keeplimits');end
xlabel([D(i).field],'FontSize',14,'Interpreter','none')
xlim([min(x) max(x)]);


lgd1.FontSize=12;lgd2.FontSize=12;
end
% ----------------------------------------------------------------------------------------------------------------------------------------------------
% for testing 
%[num2str(x,'%10.5f\a')   num2str(xt,'% 10.5f\a') num2str(M,'% 3.1f\a') datestr(t)]
%plot(xt,yt,'o'),[r p]=corr(xt,yt)
end

%% --------------------------------------------------------------------------------------
% Save Outputs
function SaveOuts(Mode1,dstr1,dstr2,s,ss,s1,s2,Catalog,PROD_Data,randmode,sample_mult,Mc,DT,t1,t2,tt1,tt2,Tdata)
% ---- Save *.txt file with Parameters Report ----
cd Outputs_ED/
fid=fopen('OUTPUT_REPORT.txt','w');
fprintf(fid,['SELECTED DATA & PARAMETERS REPORT (created on ', datestr(now),')\n']);
fprintf(fid,'-----------------------------------------------------------------\n');
if Mode1==1
fprintf(fid,['<Catalog                  >: ' dstr1{s},'\n']);
elseif Mode1==2
fprintf(fid,['<Production Data File     >: ' dstr2{ss},'\n']);
elseif Mode1==3
fprintf(fid,['<Catalog                  >: ' dstr1{s},'\n']);
fprintf(fid,['<Production Data File     >: ' dstr2{ss},'\n']);
end
if Mode1==1
fprintf(fid,['<Catalog Columns          >:\n']);
for i=1:length(s1)
    fprintf(fid,['                            -  ',Catalog(s1(i)).field,'\n']);
end
elseif Mode1==2
fprintf(fid,['<Production Data Columns  >:','\n']);
for i=1:length(s2)
    fprintf(fid,['                            -  ',PROD_Data(s2(i)).field,'\n']);
end
elseif Mode1==3
    fprintf(fid,['<Catalog Columns          >:\n']);
for i=1:length(s1)
    fprintf(fid,['                            -  ',Catalog(s1(i)).field,'\n']);
end
fprintf(fid,['<Production Data Columns  >:','\n']);
for i=1:length(s2)
    fprintf(fid,['                            -  ',PROD_Data(s2(i)).field,'\n']);
end
end
if Mode1~=2
    if Mc>-20
fprintf(fid,['<Completeness Magnitude               >: ',num2str(Mc,'%3.1f'),'\n']);
    else 
fprintf(fid,['<Completeness Magnitude               >: ',num2str('All magnitudes included'),'\n']);end
    end
if Mode1==3
fprintf(fid,['<Time Delay (Operations-Seismicity)   >: ', num2str(DT),' days','\n']);
end
fprintf(fid,['<Randomization Mode                   >: ', char(randmode),'\n']);
fprintf(fid,['<Sample Multiplication Mode           >: ', char(sample_mult),'\n']);
fprintf(fid,['<Starting Poing for background data   >: ', datestr(t1),'\n']);
fprintf(fid,['<Ending Poing for background data     >: ', datestr(t2),'\n']);
fprintf(fid,['<Starting Poing for testing data      >: ', datestr(tt1),'\n']);
fprintf(fid,['<Ending Poing for testing data        >: ', datestr(tt2),'\n']);
fclose(fid);

% Save Output Structure
 prompt={'\fontsize{12} Please enter output file name:'};
 name='Extract Output Structure';
    numlines=1;
    defaultanswer={'Tdata.mat'};
  opts.Interpreter='tex';
  answer=inputdlg(prompt,name,numlines,defaultanswer,opts);
save(char(answer),'Tdata')
cd ../

end

%% ------------------------- DATA HANDLING FUNCTION   -------------------------

function [Catalog,PROD_data,Mode1,dstr1,dstr2,s,ss1,ss,ss2]=Data_Hand_A2M
clc

disp('please select mode:');
disp(' "1" - For Seismic Data');
disp(' "2" - For Production Data');
disp(' "3" - For both Seismic and Production Data');
Mode1=input('mode:  ');

switch Mode1
    
    case 1
%% SEISMIC DATA
cd CATALOGS\
d=dir;dstr1={d.name};
[SData,SFields,s,s1]=DatLoad(dstr1,1);
cd ../

Na=length(SFields);if SFields(Na)~=' ';SFields(Na+1)=' ';end
[cou,c,Datime,Catalog]=Fields_dat(SData,SFields,1);
 ss1=SetParams(Catalog);%Catalog=Catalog(ss1);
PROD_data=[];ss=[];s2=[];ss2=[];dstr2=[];
    case 2
%% --------------------------------------------------------------------------------------------------------------
% NON-SEISMIC DATA
cd PRODUCTION_DATA\
d=dir;dstr2={d.name};
[OData,OFields,ss,s2]=DatLoad(dstr2,2);
cd ../

Na1=length(OFields);if OFields(Na1)~=' ';OFields(Na1+1)=' ';end
[cou1,c1,Datime1,PROD_data]=Fields_dat(OData,OFields,2);
ss2=SetParams(PROD_data);%PROD_data=PROD_data(ss2);
Catalog=[];s=[];s1=[];ss1=[];dstr1=[];

    case 3
%% ------------------------------------------------------------------------------------------------------------------------------------
% BOTH -SEISMIC and PRODUCTION DATA

cd CATALOGS\                                             %Seismic Data
d=dir;dstr1={d.name};
[SData,SFields,s,s1]=DatLoad(dstr1,1);
cd ../

Na=length(SFields);if SFields(Na)~=' ';SFields(Na+1)=' ';end
[cou,c,Datime,Catalog]=Fields_dat(SData,SFields,1);
 ss1=SetParams(Catalog);%Catalog=Catalog(ss1);
 
cd PRODUCTION_DATA\                         % Production (non-Seismic) Data
d=dir;dstr2={d.name};
[OData,OFields,ss,s2]=DatLoad(dstr2,2);
cd ../

Na1=length(OFields);if OFields(Na1)~=' ';OFields(Na1+1)=' ';end
[cou1,c1,Datime1,PROD_data]=Fields_dat(OData,OFields,2);
ss2=SetParams(PROD_data);%PROD_data=PROD_data(ss2);

end
 % save('Catalog_ST2_Test','Catalog')


%% -----------------------------------------    F U N C T I O N S    -----------------------------------------
function [cou,c,Datime,OUT]=Fields_dat(indata,infields,iop)

Datime=datenum(indata(:,1),indata(:,2),indata(:,3),indata(:,4),indata(:,5),indata(:,6));       % Convert time to matlab format

% Define Fields
c=1;
for i=1:length(infields)-1
if strcmp(infields(i),' ')==1;cou(i)=0;
else cou(i)=c;end
if strcmp(infields(i),' ')==0 & strcmp(infields(i+1),' ')==1;c=c+1;end
end

if iop==1
OUT(1).field='Occurrence_Time';OUT(1).val=Datime;
elseif iop==2
OUT(1).field='Production_Time';OUT(1).val=Datime;
end

for i=2:c-1
OUT(i).field=infields(cou==i);    
OUT(i).val=indata(:,i+5);
end

%Set Field Type for Magnitude Recognition
for i=1:size(OUT,2)
    if strcmp(OUT(i).field,'ML') || strcmp(OUT(i).field,'Mw') || strcmp(OUT(i).field,'M') ...
   || strcmp(OUT(i).field,'Ms') || strcmp(OUT(i).field,'mb') || strcmp(OUT(i).field,'Md')
         OUT(i).fieldType='Magnitude';
    else
    OUT(i).fieldType=[];
    end
end

end

%% -----------------------------------------------------------------------------------------------------------

function [Data,Fields,s,f]=DatLoad(dstr,da)        
% Select Seismic Catalog
if da==1;dlabel1='Select Seismic Catalog:';dlabel2='Select Catalog FIELDS file:';
elseif da==2;dlabel1='Select Production Data file:';dlabel2='Select Production FIELDS file:';end

[s,ok]=listdlg('PromptString',dlabel1,...
    'SelectionMode','single',...
    'ListString',dstr);
if ok; Data=load(dstr{s});end

[f,ok]=listdlg('PromptString',dlabel2,...
    'SelectionMode','single',...
    'ListString',dstr);
if ok; Fields=fileread(dstr{f});end

end


%%---------------------------------------------------------------------------------------------------------------
function ss1=SetParams(Data)
%Select Parameters from Seismic Catalog
[s1,ok]=listdlg('PromptString','Select field(s):',...
    'ListString',{Data.field});
for i=1:length(s1)
    ss1=s1(isnan(s1)==0);
end

end
% ----------------------------------------------------------------------------------------------------------------


end

%% --------------------- TRANSFORMATION TO ED MAIN FUNCTION ---------------------
function [u,uBG,ierr,h,xx,ambd]=EQ_DIMv_2_0(x,n1,n2,n3,n4,randmode,sample_mult)

%   [u,uBG,ierr,h,xx,ambd]=EQ_DIMv_2_0(x,n1,n2,n3,n4,randmode,sample_mult)
%
% TRANSFORMS PARAMETER SAMPLE DATA x TO ITS EQUIVALENT DIMENSION
%
% AUTHOR: S. Lasocki 06/2014 within IS-EPOS project.
%
% DESCRIPTION: An equivalent dimension u of a parameter x is u=FX^(–1)(x), 
%where FX^(–1)(X) is the inverse cumulative distribution function of X. 
% The distribution function of the parameter x, FX(x), is estimated by 
% means of the non-parametric, kernel estimation method. The background
% sample for the estimation can be either the whole vactor x or its user 
% determined part from n1 to n2. The smoothing factor of the kernel 
% estimator of F(x), h, is estimated using the least-squares 
% cross-validation for the Gaussian kernel function. The final form of the 
% kernel is the adaptive kernel.
% The kernel estimation cannot use samples with repeated values. When 
% needed the sample data are randomized within their round-off interval. 
% The round-off interval length - eps is the least non-zero difference 
% between sample data. Three randomization models are supported:
% (1) exponential distribution of x in [x0-eps/2, x0+eps/2], where x0
% is the sample data point and eps is the length of roud-off inteval. The 
% shape parameter of the exponential distribution is estimated from the 
% whole data sample assuming the exponential distribution. (2) normal 
% distribution N(x,eps) of x in [x0-eps/2, x0+eps/2]. (3) uniform 
% distribution of x in [x0-eps/2, x0+eps/2]. 
% Upon user's request the background sample - xx comprises the randomized 
% values of x trippled symmetrically with respect to the values min(x) and
% max(x),or doubled synetrically with respect to the value min(x) or
% max(x). Trippling/doubling should be carried out if the sample values are
% distinctly truncated from both/one side so that the assumption that the
% Weigthing factors row vector for the adaptive kernel is of the same size 
% as xx. 
% See: the references below for a more comprehensive description.
% 
% This is a beta version of the program. Further developments may appear.
%
% REFERENCES:
%Lasocki S. (2014) Geophys J Int. 197(2), 1224-1235, doi:10.1093/gji/ggu062
%Silverman B.W. (1986) Density Estimation for Statistics and Data Analysis, 
%   Chapman and Hall, London 
%Kijko A., Lasocki S., Graham G. (2001) Pure appl. geophys. 158, 1655-1665
%
% INPUT:
%   x - vector of earthquake parameter values
%   n1 - number of the first point defining the background sample
%   n2 - number of the last point defining the background sample
%   n3 - number of the first point defining the testing sample
%   n4 - number of the last point defining the testing sample
%   randmode - string determining the mode of data randomization: 
%           'no'   - no randomization, 
%           'exp'  - exponential randomization, 
%           'norm' - Gaussian randomization,
%           'uni'  - uniform randomization
%   sample_mult - string determining the way of sample multiplication: 
%           'no'   - no multiplication, 
%           'left' - dubbling from the left hand side, 
%           'right - doubbling from the right hand side, 
%           'both' - trippling from both sides.
%
% OUTPUT
%   u - vector of the transformed parameter values (testing sample)
%   uBG - vector of the transformed parameter values (background sample)
%   ierr - h-convergence indicator. ierr=0 if the estimation procedure of 
%       the optimal smoothing factor has converged (the zero of the h 
%       functional has been found, ierr=1 when multiple zeros of h 
%       functional were encountered - the largest h is accepted, ierr = 2 
%       when h functional did not zeroe - the approximate h value is taken.
%   h - kernel smoothing factor.
%   xx - the background sample for the transformation
%   ambd - the weigthing factors for the adaptive kernel
%
% LICENSE
%     This file is a part of the IS-EPOS e-PLATFORM.
%
%     This is free software: you can redistribute it and/or modify it under 
%     the terms of the GNU General Public License as published by the Free 
%     Software Foundation, either version 3 of the License, or 
%     (at your option) any later version.
% 
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
%     See the GNU General Public License for more details.
% 
% ------------------------------------------------------------------------------------------------------------------------
% EXAMPLE TO RUN:
% x=exprnd(1,1000,1);
% [u,uBG,ierr,h,xx,ambd]=EQ_DIMv_2_0(x,1,1000,100,300,'no','no')
% ------------------------------------------------------------------------------------------------------------------------

% xx=x(n1:n2);                                                           %K16JUN2015

if ~strcmp(randmode,'no')
    eps=magn_accur(x);
%  xx=rand_sampl(xx,eps,randmode);
     x=rand_sampl(x,eps,randmode);                      %K16JUN2015

end
   xx=x(n1:n2);                                                             %K16JUN2015
   xt=x(n3:n4);                                                             %K24JAN2019
   
if strcmp(sample_mult,'both')
    x1=min(x);
    x2=max(x);
    xx = potrajanie(xx,x1,x2);
    [h,ierr]=hopt(xx);
    [ambd]=scaling(xx,h);
    [u] = EQ_DIM_trans_x1_x2(xt,xx,ambd,h,x1,x2);
    [uBG] = EQ_DIM_trans_x1_x2(xx,xx,ambd,h,x1,x2);         %K24JAN2019
end
    
if strcmp(sample_mult,'right')
    x0=max(x);
    xx = podwajanie(xx,x0);
    [h,ierr]=hopt(xx);
    [ambd]=scaling(xx,h);
    [u] = EQ_DIM_trans_inf_x2(xt,xx,ambd,h,x0);
    [uBG] = EQ_DIM_trans_inf_x2(xx,xx,ambd,h,x0);             %K24JAN2019
end
    
if strcmp(sample_mult,'left')
    x0=min(x);
    xx = podwajanie(xx,x0);
    [h,ierr]=hopt(xx);
    [ambd]=scaling(xx,h);
    [u] = EQ_DIM_trans_x1_inf(xt,xx,ambd,h,x0);
    [uBG] = EQ_DIM_trans_x1_inf(xx,xx,ambd,h,x0);               %K24JAN2019
end

if strcmp(sample_mult,'no')
    [h,ierr]=hopt(xx);
    [ambd]=scaling(xx,h);
    [u] = EQ_DIM_trans_inf_inf(xt,xx,ambd,h);
    [uBG] = EQ_DIM_trans_inf_inf(xx,xx,ambd,h);                  %K24JAN2019
end
end
    
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --------------------------- FUNCTIONS ----------------------------%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% EPS
function [eps]=magn_accur(M)
x=sort(M);
d=x(2:length(x))-x(1:length(x)-1);
eps=min(d(d>0));
end

%% Sample multiplication
function x3 = potrajanie(x,x1,x2)
% Triples a sample 
%   If the sample x(i) is truncated from both sides in the interval 
%   [x1,x2] then the trippled sample is [-x(i)+2x1,x(i),-x(i)+2x2]
% x - is the column data vector
% x3 - is the column vector of data doubled and sorted in the ascending
% order
x3=[-x+2*x1
    x
    -x+2*x2];
%x3=sort(x3);                                                    % K31JAN2019 - deactivate ascending sorting
end

function x2 = podwajanie(x,x0)
% Doubles a sample
%   If the sample x(i) is is truncated from the left hand side and belongs 
% to the interval [x0,inf) or it is truncated from the right hand side and
% belongs to the interval (-inf,x0]
%   then the doubled sample is [-x(i)+2x0,x(i)]
% x - is the column data vector
% x2 - is the column vector of data doubled and sorted in the ascending
% order
x2=[-x+2*x0
    x];
%x2=sort(x2);                                                       % K31JAN2019 - deactivate ascending sorting
end


%% HOPT
function [h,ierr]=hopt(x)

%Estimation of the optimal smoothing factor by means of the least squares
%method
% x - column data vector
% The result is an optimal smoothing factor
% ierr=0 - convergence, ierr=1 - multiple h, ierr=2 - approximate h is used 
% The function calls the procedure FZERO for the function 'funct'
% NEW VERSION 2 - without a square matrix. Also equipped with extra zeros
% search

% MODIFIED JUNE 2014

ierr=0;
n=length(x);
x=sort(x);
interval=[0.000001 2*std(x)/n^0.2];
x1=funct(interval(1),x);
x2=funct(interval(2),x);
if x1*x2<0
    fun = @(t) funct(t,x);                                         % For Octave
    x0=interval;                                                      % ForOctave
    [hh(1),fval,exitflag]=fzero(fun,x0);                     % ForOctave

% Extra zeros search
    jj=1;
    for kk=2:7
        interval(1)=1.1*hh(jj);
        interval(2)=interval(1)+(kk-1)*hh(jj);
        x1=funct(interval(1),x);
        x2=funct(interval(2),x);
        if x1*x2<0
            jj=jj+1;
            fun=@(t) funct(t,x);                                   % ForOctave
            x0=interval;                                              % ForOctave
            [hh(jj),fval,exitflag]=fzero(fun,x0);             % ForOctave
        end
    end
    if jj>1;ierr=1;end
    h=max(hh);

   if exitflag==1;return;end

end
h=0.891836*(mean(x)-x(1))/(n^0.2);
ierr=2;
end

function [fct]=funct(t,x)
p2=1.41421356;
n=length(x);
yy=zeros(size(x));
for i=1:n,
   xij=(x-x(i)).^2/t^2;
   y=exp(-xij/4).*((xij/2-1)/p2)-2*exp(-xij/2).*(xij-1);
   yy(i)=sum(y);
end;
fct=sum(yy)-2*n;
clear xij y yy;
end

%% SCALING
function [ambd]=scaling(x,h)

% EVALUATES A VECTOR OF SCALING FACTORS FOR THE NONPARAMETRIC ADAPTATIVE
% ESTIMATION

% x - the n dimensional column vector of data values sorted in the ascending
% order
% h - the optimal smoothing factor
% ambd - the resultant n dimensional row vector of local scaling factors 

n=length(x);
c=sqrt(2*pi);
gau=zeros(1,n);
for i=1:n,
   gau(i)=sum(exp(-0.5*((x(i)-x)/h).^2))/c/n/h;
end
g=exp(mean(log(gau)));
ambd=sqrt(g./gau);
end


%% TRANS_EQ_DIM
function [x_tr] = EQ_DIM_trans_x1_x2(x,x_s,ambd,h,x1,x2)
%Transformation of the variable truncated within the interval [x1,x2]
%   x - the sample to be transformed
%   x_s - the background sample already trippled
%   ambd - weighting factors of adaptive kernel [1:length(x_s)]
%   h - optimal scaling factor for x_s
%   x_tr - the sample after transformation [1:length(x)]
%   x1 - left hand side truncation
%   x2 - right hand side truncation

n=length(x_s);
for i=1:length(x);
    if x(i)<x1; x_tr(i)=0;elseif x(i)>x2; x_tr(i)=1;
    else
       x_tr(i)=3*(Dystr_npr(x(i),x_s,ambd,h,n)-Dystr_npr(x1,x_s,ambd,h,n));    
    end
end
x_tr=x_tr';
end

function [x_tr] = EQ_DIM_trans_inf_inf(x,x_s,ambd,h)
%Transformation of the variable from (-inf,inf)
%   x - the sample to be transformed
%   x_s - the background sample already trippled
%   ambd - weighting factors of adaptive kernel [1:length(x_s)]
%   h - optimal scaling factor for x_s
%   x_tr - the sample after transformation [1:length(x)]

for i=1:length(x);
    x_tr(i)=Dystr_npr(x(i),x_s,ambd,h,length(x_s));                                
end
x_tr=x_tr';
end


function [x_tr] = EQ_DIM_trans_inf_x2(x,x_s,ambd,h,x2)
%Transformation of the variable from (-inf, x2]
%   x - the sample to be transformed
%   x_s - the background sample already trippled
%   ambd - weighting factors of adaptive kernel [1:length(x_s)]
%   h - optimal scaling factor for x_s
%   x_tr - the sample after transformation [1:length(x)]
%   x2 - right hand side truncation

for i=1:length(x);
    x_tr(i)=1.0;
    if x(i)<=x2
        x_tr(i)=2*Dystr_npr(x(i),x_s,ambd,h,length(x_s));                          % 
    end
end
x_tr=x_tr';
end

function [x_tr] = EQ_DIM_trans_x1_inf(x,x_s,ambd,h,x1)
%Transformation of the variable from [x1,inf)
%   x - the sample to be transformed
%   x_s - the background sample already trippled
%   ambd - weighting factors of adaptive kernel [1:length(x_s)]
%   h - optimal scaling factor for x_s
%   x_tr - the sample after transformation [1:length(x)]
%   x1 - left hand side truncation

n=length(x_s);
for i=1:length(x);
    x_tr(i)=0;
    if x(i)>=x1
        x_tr(i)=2*(Dystr_npr(x(i),x_s,ambd,h,n)-Dystr_npr(x1,x_s,ambd,h,n));                
    end
end
x_tr=x_tr';
end


%% Non-parameteric Adaptive cdf. random variables from (-inf,inf)
function [Fgau]=Dystr_npr(y,x,ambd,h,n)
   Fgau=sum(normcdf(((y-x)./ambd')./h))/n;
end

%% RAND_SAMPLE
function [x_corr]=rand_sampl(x,eps,randmode)

if strcmp(randmode,'exp')
    muhat = expfit(x-min(x));
    F1=1-exp(-(x-min(x)-0.5*eps)/muhat);
    F2=1-exp(-(x-min(x)+0.5*eps)/muhat);
    u=rand(size(x));
    w=u.*(F2-F1)+F1;
    x_corr=min(x)-log(1-w).*muhat;
end

if strcmp(randmode,'norm')
    F1=normcdf(x-0.5*eps,x,eps);
    F2=normcdf(x+0.5*eps,x,eps);
    u=rand(size(x));
    w=u.*(F2-F1)+F1;
    x_corr=norminv(w,x,eps);
end

if strcmp(randmode,'uni')
    r=rand(length(x),1);
    x_corr=x-0.5*eps+eps.*r;
end

end




