function tir

% створюємо глобальну змінну TS, куди будуть записуватись дані
global TS; TS.index=0;
global TSTemp; TSTemp.index=0;
global Data_type; Data_type=1;
% визначаємо поточну розподільчу здатність, встановивши одиниці в PIXELS

set(0,'Units','pixels');
SCREEN_SIZE=get(0,'ScreenSize');
% SCREEN_SIZE = [left bottom width height]
SCRHeight=SCREEN_SIZE(1,4);

% створюємо фігуру розміром 100 x 600, що знаходиться у верхному лівому
% куті з відступом у 10 пікселів зверху та зліва
fg=figure('Position',[10,SCRHeight-760,350,710], 'Units','pixels', ...
          'HandleVisibility','on', 'MenuBar','none', 'Name','Time irreversibility research', ...
          'Resize','off', 'Tag','ApEn set properties figure', ...
          'NumberTitle','off', 'DeleteFcn',@DeleteFcn_Callback);
      
% записуємо handle фігури
handles.rootFigure=fg;

% створюємо меню користувача
menuRoot=uimenu('Parent',fg, 'Label','File', 'Tag', 'Menu File');
menuTemp=uimenu('Parent',menuRoot, 'Label','Read', 'Tag','Menu File Load', 'Callback',@MenuFileLoad_Callback);

% створюємо статичний текст 
uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[42,678,150,25], ...
          'String','Available data:', 'FontName','MS Sans Serif', ...
          'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'demi');

% створюємо ListBox
handles.ListBoxTS=uicontrol(fg, 'Style','listbox', 'Units','pixels', 'Position',[49,552,252,115], ...
          'String','', 'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'normal', ...
          'Tag', 'ListBoxTS', 'ListboxTop', 5, 'Callback', @Listbox_Callback);
      
handles.pushbutton3=uicontrol(fg, 'Style','pushbutton', 'Tag','pushbutton3', ...
          'Units','pixels', 'Position',[118,505,113,27], 'String','Plot', ...
          'FontName','MS Sans Serif', 'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi', ...
          'Callback',@pushbutton3_Callback);        
      
      
      %створюємо статичний текст 
uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[42,465,170,22], ...
          'String','Interval of calculation:','FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
 
    % створюємо фрейм    
uicontrol(fg, 'Style','frame', 'Tag','frame2', 'Units','pixels', 'Position',[59,394,232,60]);      

uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[68,435,88,17], ...
          'String','start', 'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
handles.edit3=uicontrol(fg, 'Style','Edit', 'Tag', 'edit3', ...
           'Units','pixels', 'Position',[75,405,70,25], ...
          'String','', 'FontName','Courier New', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'demi');
      
uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[200,435,88,17], ...
          'String','end', 'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
handles.edit4=uicontrol(fg, 'Style','Edit', 'Tag', 'edit4', ...
           'Units','pixels', 'Position',[205,405,70,25], ...
          'String','', 'FontName','Courier New', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'demi');
      

    %створюємо статичний текст 
uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[42,355,100,22], ...
          'String','Type of data:','FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
      
      % створюємо фрейм 
uicontrol(fg, 'Style','frame', 'Tag','frame2', 'Units','pixels', 'Position',[59,265,232,80]);

handles.radiobutton1=uicontrol(fg, 'Style','radiobutton', 'Tag','radiobutton1', 'Units','pixels', 'Position',[70,315,120,22], ...
          'String','price (index)','CallBack', @radiobutton1_Callback,'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi','Value',1);
 
handles.radiobutton2=uicontrol(fg, 'Style','radiobutton', 'Tag','radiobutton2', 'Units','pixels', 'Position',[70,295,120,22], ...
          'String','returns','CallBack',  @radiobutton2_Callback,'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi','Value',0);
      
handles.radiobutton3=uicontrol(fg, 'Style','radiobutton', 'Tag','radiobutton3', 'Units','pixels', 'Position',[70,275,120,22], ...
          'String','medicine','CallBack', @radiobutton3_Callback,'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi','Value',0);
          

 % створюємо кнопку для розрахунку Multiscale time asymmetry

      % створюємо статичний текст 
uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[28,232,304,20], ...
          'String','Multiscale time asymmetry at scale tau', 'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
 % створюємо статичний текст 
%uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[103,222,145,20], ...
 %         'String','at scale tau', 'FontName','MS Sans Serif', ...
  %        'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
   
 handles.pushbutton1=uicontrol(fg, 'Style','pushbutton', 'String',' Calculate','Tag','pushbutton1', ...
          'Units','pixels', 'Position',[108,184,146,34], ...
          'FontName','MS Sans Serif', 'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi', ...
          'Callback',@pushbutton1_Callback);
      
      
  % створюємо кнопку для розрахунку Dynamics of multiscale asymmetry index  
 
% створюємо статичний текст 
uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[26,146,281,22], ...
          'String','Dynamics of multiscale asymmetry index', 'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
% створюємо фрейм 
uicontrol(fg, 'Style','frame', 'Tag','frame3', 'Units','pixels', 'Position',[49,15,253,124]);

% створюємо статичний текст та edit для введення значення початкової ширини вікна
uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[106,101,88,17], ...
          'String','window size', 'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
handles.edit1=uicontrol(fg, 'Style','Edit', 'Tag', 'edit1', ...
           'Units','pixels', 'Position',[205,101,40,25], ...
          'String','100', 'FontName','Courier New', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'demi');
      
% створюємо статичний текст та edit для введення значення кроку вікна
uicontrol(fg, 'Style','text', 'Tag','', 'Units','pixels', 'Position',[151,69,43,18], ...
          'String','step', 'FontName','MS Sans Serif', ...
          'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi');
handles.edit2=uicontrol(fg, 'Style','Edit', 'Tag', 'edit1', ...
           'Units','pixels', 'Position',[206,69,38,24], ...
          'String','1', 'FontName','Courier New', 'FontSize', 12, 'FontAngle', 'normal', 'FontWeight', 'demi');

handles.pushbutton2=uicontrol(fg, 'Style','pushbutton', 'Tag','pushbutton2', ...
          'Units','pixels', 'Position',[118,25,113,32], 'String',' Calculate', ...
          'FontName','MS Sans Serif', 'FontSize', 10, 'FontAngle', 'normal', 'FontWeight', 'demi', ...
          'Callback',@pushbutton2_Callback);     
guidata(fg,handles);
%--------------------------------------------------------------------------

% Функція, що виконується при закритті фігури
function DeleteFcn_Callback(h,eventdata,handles)

% очищення пам"яті, що використовувалась для локальних змінних
clear global;


% =============================================================================================================================
% вибір пункту меню "Read"
function MenuFileLoad_Callback(h,eventdata,handles)
global TSTemp;
% читаємо ім"я файла
[FILENAME,PATHNAME,FILTERINDEX]=uigetfile( ...
    {'*.txt;*.dat', 'Файлы с данными (*.txt, *.dat)'; ...
     '*.txt',            'Текстовые файлы (*.txt)'; ...
     '*.dat',            'Текстовый файлы с данными (*.dat)'}, ...
     'Выберите файл с временным рядом');

if ((FILENAME(1,1)~=0) & (PATHNAME(1,1)~=0))
    % читаємо дані з вибраного файла
    [NAMES,DATAS,DATES]=loadTS(PATHNAME,FILENAME);

    
    
    % повідомляємо про прочитаний файл
    TSTemp.index=TSTemp.index+1;
    TSTemp.data{TSTemp.index}.datas=DATAS;
    TSTemp.data{TSTemp.index}.names=NAMES
    TSTemp.data{TSTemp.index}.dates=DATES
    
    % отримуємо handle ListBox
    handles=guidata(gcbo);
    ListBoxTS=handles.ListBoxTS;
    STRINGS=get(ListBoxTS,'String');
    STRINGS=appendString(STRINGS,FILENAME);
    set(ListBoxTS,'String',STRINGS);
    
end

index=get(handles.ListBoxTS,'Value');

if index>0
    X=TSTemp.data{index}.datas;
    %get(handles.edit3,'String'));
    set(handles.edit3,'String','1');
    set(handles.edit4,'String',length(X));
end

%--------------------------------------------------------------------------
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global TSTemp;
global Data_type;

handles=guidata(gcbo);

index=get(handles.ListBoxTS,'Value');
X=TSTemp.data{index}.datas;

f=figure('Name','Data','NumberTitle','off');

plot(X,'LineWidth',2)
grid on
xlim([1 length(X)]) 


%--------------------------------------------------------------------------
function Listbox_Callback(hObject, eventdata, handles)
global TSTemp;
global Data_type;

handles=guidata(gcbo);

index=get(handles.ListBoxTS,'Value');

if index>0
    X=TSTemp.data{index}.datas;
    %get(handles.edit3,'String'));
    set(handles.edit3,'String','1');
    set(handles.edit4,'String',length(X));
end
    
    
    

%-------------------------------------------------------------------------------------------------
%при натисненні на кнопку "Multiscale time asymmetry at scale tau"
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global TSTemp;
global Data_type;

handles=guidata(gcbo);

index=get(handles.ListBoxTS,'Value');
X=TSTemp.data{index}.datas;
first=str2num(get(handles.edit3,'String'));
last=str2num(get(handles.edit4,'String'));
X=X(:,first:last);


Data_type
if Data_type==1,
   % X1=X;
    X=price2ret(X);
    X=X/std(X);
elseif Data_type==2,
    X=X/std(X);
    %X1=X;
elseif Data_type==3,
    for ii=2:length(X)
        X1(ii-1,1)=X(ii)-X(ii-1);
    end
    
    X1=X1/std(X1);
    X=X1;
    X=X';
end

%X=price2ret(X);
%X=X/std(X);
y=X';
%d=10;
tau=35;
wind=length(y)-1;


[tau_plus,tau_minus,Ai,A_tau] = irrevers(y,tau,wind);


f=figure('Name','Multiscale time irreversibility (asymmetry) analysis ','NumberTitle','off');

subplot(3,1,1);
plot(y,'LineWidth',2)
xlim([1 length(y)])
grid on


subplot(3,1,2);
plot(tau_plus,'color','red','LineWidth', 2)
 hold on
 plot(tau_minus,'--','color','black','LineWidth',2)
 grid on
  h = legend('y\tau >0','y\tau <0',1); 
set(gca,'FontName','Times New Roman','FontSize',14)
 xlabel('Scale factor (\tau)','FontSize',16,'FontName','Times New Roman')
 ylabel('p ln p','FontSize',16,'FontName','Times New Roman')
 
xlim([1 tau]) 
 ylabel('p ln p','FontSize',16,'FontName','Times New Roman')
 subplot(3,1,3);
 plot(A_tau)
 grid on
 xlabel('Scale factor (\tau)','FontSize',16,'FontName','Times New Roman')
 ylabel('A(\tau)','FontSize',16,'FontName','Times New Roman')
 
  
       messageString=['____________Ai =' num2str(Ai,8),'____________'];
        msgbox(messageString,'multiscale asymmetry index:');
% очищуємо локальні змінні
clear index X;
% =============================================================================================================================


% --- при натисненні на кнопку "Calculate"
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global TSTemp;
global Data_type;
handles=guidata(gcbo);

index=get(handles.ListBoxTS,'Value');
X=TSTemp.data{index}.datas;
X=X';
first=str2num(get(handles.edit3,'String'));
last=str2num(get(handles.edit4,'String'));
X=X(first:last,:);
%X=X';



Data_type
if Data_type==1,
    X1=X;
    X=price2ret(X);
    X=X/std(X);
elseif Data_type==2,
    X=X/std(X);
    X1=X;
elseif Data_type==3,
    for ii=2:length(X)
        X1(ii-1,1)=X(ii)-X(ii-1);
    end
    
    X1=X1/std(X1);
    X=X1;
end

    
%d=10;
tau=25;

wind=str2num(get(handles.edit1,'String'));
Step=str2num(get(handles.edit2,'String'));
k=1;


for ii=1:Step:length(X)-wind
    y=X(ii:ii+wind,1);
    [tau_plus,tau_minus,Ai,A_tau,Ai_plus,Ai_minus] = irrevers(y,tau,wind);
    Ai_din(k,1)=Ai;
    Ai_din_plus(k,1)=Ai_plus;
    Ai_din_minus(k,1)=Ai_minus;
    
    k=k+1;
end


sum_irr(1,1)=Ai_din(1,1);

for ii=2:length(Ai_din)
  sum_irr(ii,1)=sum_irr(ii-1,1)+Ai_din(ii,1) ; 
end

sum_irr2(1,1)=Ai_din(1,1);
for ii=2:length(Ai_din)
  sum_irr2(ii,1)=sum_irr2(ii-1,1)+Ai_din(ii,1) ; 
 if abs(sum_irr2(ii,1))<abs(sum_irr2(ii-1,1))
     sum_irr2(ii)=0;
 end
end


%визначаємо координати розташуванн дат

wdata=TSTemp.data{index}.dates;
wdata=(wdata(:,first:last))';
if wdata(:,1)==wdata(:,2) graphtick=0; end
if wdata(:,1)<wdata(:,2) graphtick=1;   
xxt=num2str(wdata(:,1));
[rw,cw]=size(wdata);
jj=1;
    for ii=1:rw-1
         if strncmpi(xxt(ii,:),xxt(ii+1,:),4)==0 
         xxt1(jj,1:4)=xxt(ii+1,1:4);
         xxt2(jj)=((ii+1)-wind)/Step;
         jj=jj+1;
        end
    end
end








z=figure('Name','Cumulative multiscale time irreversibility','NumberTitle','off');
subplot(2,1,1); 


h = stem(sum_irr,'-sr','fill');

set(h,'Color','r','LineWidth',2) 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 if graphtick==1
set(gca,'XTick',xxt2)
set(gca,'XTickLabel',xxt1,'FontSize',14,'FontName','Times New Roman')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xlabel('Time, days','FontSize',14,'FontName','Times New Roman')


grid on
xlim([1 length(Ai_din)])
 MaxY=max(sum_irr); 
 MinY=min(sum_irr); 
 ylim([MinY MaxY])
  
 subplot(2,1,2); 
 
 plot(Ai_din_plus,'color','red','LineWidth', 2)
 grid on
 hold on
 plot(Ai_din_minus,'--','color','black','LineWidth',2)
 xlim([1 length(Ai_din)])
 MaxY=max(max(Ai_din_plus,Ai_din_minus)); 
 MinY=min(min(Ai_din_plus,Ai_din_minus)); 
 ylim([MinY MaxY])
 h = legend('\Sigma p ln p, if y\tau >0','\Sigma p ln p, if y\tau <0',1); 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 if graphtick==1
set(gca,'XTick',xxt2)
set(gca,'XTickLabel',xxt1,'FontSize',14,'FontName','Times New Roman')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xlabel('Time, days','FontSize',14,'FontName','Times New Roman')

 
p=figure('Name','Cumulative multiscale time irreversibility','NumberTitle','off');
subplot(2,1,1); 


h = stem(sum_irr2,'-sr','fill');

set(h,'Color','r','LineWidth',2) 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
set(gca,'XTick',xxt2)
set(gca,'XTickLabel',xxt1,'FontSize',14,'FontName','Times New Roman')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%stem(sum_irr,'color','red','LineWidth', 2)
grid on
xlim([1 length(Ai_din)])
 MaxY=max(sum_irr2); 
 MinY=min(sum_irr2); 
 ylim([MinY MaxY])
  
 subplot(2,1,2); 
 
 plot(Ai_din_plus,'color','red','LineWidth', 2)
 grid on
 hold on
 plot(Ai_din_minus,'--','color','black','LineWidth',2)
 xlim([1 length(Ai_din)])
 MaxY=max(max(Ai_din_plus,Ai_din_minus)); 
 MinY=min(min(Ai_din_plus,Ai_din_minus)); 
 ylim([MinY MaxY])
 h = legend('\Sigma p ln p, if y\tau >0','\Sigma p ln p, if y\tau <0',1); 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
set(gca,'XTick',xxt2)
set(gca,'XTickLabel',xxt1,'FontSize',14,'FontName','Times New Roman')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
 xlabel('Time, days','FontSize',14,'FontName','Times New Roman') 
     
f=figure('Name','Dynamic of сumulative multiscale time irreversibility','NumberTitle','off');
 
subplot(3,1,1); plot(X1(wind+1:length(X1),1),'color','black','LineWidth',2)
 grid on
 xlim([1 length(X1)-wind])
 ylim([min(X1) max(X1)])
  ylabel('Index','FontSize',14,'FontName','Times New Roman')


subplot(3,1,2); plot(sum_irr,'color','red','LineWidth', 2)
 grid on
grid on
xlim([1 length(Ai_din)])
 MaxY=max(sum_irr); 
 MinY=min(sum_irr); 
 ylim([MinY MaxY])
  
  %h = legend('y\tau >0','y\tau <0',1); 
 set(gca,'FontName','Times New Roman','FontSize',14)
 
 

 ylabel('Cumulative A_i','FontSize',14,'FontName','Times New Roman')

 subplot(3,1,3); 
 
 plot(Ai_din_plus,'color','red','LineWidth', 2)
 grid on
 hold on
 plot(Ai_din_minus,'--','color','black','LineWidth',2)
 xlim([1 length(Ai_din)])
 MaxY=max(max(Ai_din_plus,Ai_din_minus)); 
 MinY=min(min(Ai_din_plus,Ai_din_minus)); 
 ylim([MinY MaxY])
 h = legend('\Sigma p ln p, if y\tau >0','\Sigma p ln p, if y\tau <0',1); 
 set(gca,'FontName','Times New Roman','FontSize',14)
 xlabel('Time, days','FontSize',14,'FontName','Times New Roman')
 
v=figure('Name','Dynamic of multiscale time irreversibility','NumberTitle','off');
 
plot(Ai_din,'color','red','LineWidth', 2)
 grid on
  %h = legend('y\tau >0','y\tau <0',1); 
 set(gca,'FontName','Times New Roman','FontSize',14)
 
 ylim([-1 1]) 
 xlim([1 length(Ai_din)])

 ylabel('A_i','FontSize',14,'FontName','Times New Roman')

 %xlabel('Scale factor (\tau)','FontSize',16,'FontName','Times New Roman')
 %ylabel('p ln p','FontSize',16,'FontName','Times New Roman')

 %hold on
 %plot(y_tau_minus,'--','color','black','LineWidth',2)
 
 button = questdlg('Do you want to save Ai?',...
 'Continue Operation','Yes','No','No');
 if strcmp(button,'Yes')
   [filename,pathname,filterindex]=uiputfile(...
    {'*.txt','Текстовые файлы (*.txt)'}, ...
     'Выберите файл','');

    [m,n]=size(filename);
    if (n<4) || (~((filename(n-3)=='.') && (filename(n-2)=='t') && (filename(n-1)=='x') && (filename(n)=='t')))
    filename=[filename '.txt'];
    end
 
    f_hand=[Ai_din];
    NAME=[pathname filename];
    save (NAME,'f_hand','-ascii')
elseif strcmp(button,'No')
   close
end
% читаємо ім"я файла

function mutual_exclude(off)
set(off,'Value',0)

function radiobutton1_Callback(hObject, eventdata, handles)
global Data_type;
handles=guidata(gcbo);

off = [handles.radiobutton2,handles.radiobutton3];
mutual_exclude(off)
Data_type=1;

function radiobutton2_Callback(hObject, eventdata, handles)
global Data_type;
handles=guidata(gcbo);

off = [handles.radiobutton1,handles.radiobutton3];
mutual_exclude(off)
Data_type=2;

function radiobutton3_Callback(hObject, eventdata, handles)
global Data_type;
handles=guidata(gcbo);

off = [handles.radiobutton2,handles.radiobutton1];
mutual_exclude(off)
Data_type=3;




