function varargout = Einzelkanalsim_V1(varargin)
% EINZELKANALSIM_V1 MATLAB code for Einzelkanalsim_V1.fig
%      EINZELKANALSIM_V1, by itself, creates a new EINZELKANALSIM_V1 or raises the existing
%      singleton*.
%
%      H = EINZELKANALSIM_V1 returns the handle to a new EINZELKANALSIM_V1 or the handle to
%      the existing singleton*.
%
%      EINZELKANALSIM_V1('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in EINZELKANALSIM_V1.M with the given input arguments.
%
%      EINZELKANALSIM_V1('Property','Value',...) creates a new EINZELKANALSIM_V1 or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Einzelkanalsim_V1_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Einzelkanalsim_V1_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Einzelkanalsim_V1

% Last Modified by GUIDE v2.5 31-Jul-2014 10:55:20

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Einzelkanalsim_V1_OpeningFcn, ...
                   'gui_OutputFcn',  @Einzelkanalsim_V1_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Einzelkanalsim_V1 is made visible.
function Einzelkanalsim_V1_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Einzelkanalsim_V1 (see VARARGIN)
set(handles.U,'String','100');
set(handles.C,'String','1');
set(handles.t,'String','1');
set(handles.tges,'String','1000');
% Choose default command line output for Einzelkanalsim_V1
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Einzelkanalsim_V1 wait for user response (see UIRESUME)
 uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Einzelkanalsim_V1_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;
delete(hObject); 

% --------------------------------------------------------------------
function Modell_laden_Callback(hObject, eventdata, handles)
% hObject    handle to Modell_laden (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Pulsdatei_laden_Callback(hObject, eventdata, handles)
% hObject    handle to Pulsdatei_laden (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Speichern_Callback(hObject, eventdata, handles)
% hObject    handle to Speichern (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)



function U_Callback(hObject, eventdata, handles)
% hObject    handle to U (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of U as text
%        str2double(get(hObject,'String')) returns contents of U as a double


% --- Executes during object creation, after setting all properties.
function U_CreateFcn(hObject, eventdata, handles)
% hObject    handle to U (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function C_Callback(hObject, eventdata, handles)
% hObject    handle to C (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of C as text
%        str2double(get(hObject,'String')) returns contents of C as a double


% --- Executes during object creation, after setting all properties.
function C_CreateFcn(hObject, eventdata, handles)
% hObject    handle to C (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function t_Callback(hObject, eventdata, handles)
% hObject    handle to t (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of t as text
%        str2double(get(hObject,'String')) returns contents of t as a double


% --- Executes during object creation, after setting all properties.
function t_CreateFcn(hObject, eventdata, handles)
% hObject    handle to t (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function tges_Callback(hObject, eventdata, handles)
% hObject    handle to tges (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of tges as text
%        str2double(get(hObject,'String')) returns contents of tges as a double


% --- Executes during object creation, after setting all properties.
function tges_CreateFcn(hObject, eventdata, handles)
% hObject    handle to tges (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in Start.
function Start_Callback(hObject, eventdata, handles)
% hObject    handle to Start (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
     
N_ch =1;        % number of channels in the patch
N_it =1;         % number of iterations

 Modellname=get(handles.Modellname, 'String');
 Modell=Modellname(1:end-2);
 
if get(handles.Pulsdatei_geladen,'Value')==true
 Pulsname=get(handles.Pulsname, 'String');
 Puls=Pulsname(1:end-2);
       
  if get(handles.Zeitschritt_fest,'Value')==true
       
        [MC,MK,uc,ub] = feval(Modell);  % Modelldaten einlesen
        [PP,dt] = feval(Puls);          % Pulsdaten einlesen       
        AnzMP =  PP(1,:)/dt;            % Anzahl Messpunkte in Pulsen
        AnzMPkum = cumsum(AnzMP);       % kumulative Summe
        np = length(PP(1,:));           % Anzahl Pulse
        ns = length(MC(1,:));           % Anzahl Zustände
        nMK = ones(ns,ns)- MK;          % Matrixwerte ohne Konzentrationen
        CC  = zeros(ns,ns,np);          % Besetzung des CC - Arrays
        ev3 = zeros(ns,ns,np);          % Besetzung des Eigenvektor-Arrays
        ew3 = zeros(ns,np);             % Besetzung des Eigenwerte -Arrays
        for k = 1:np
            konz = PP(3,k);             % Konzentration im Puls
            C = konz*MK.*MC+nMK.*MC;    % Multiplikation mit konz
            for i=1:ns                  % Hauptdiagonale von C berechnen
                C(i,i)=0;
                element=0;
                for j=1:ns
                    element=element-C(j,i);
                end
                C(i,i)=element;
            end
            CC(:,:,k) = C;              % alle C-Matrizen
            [ev,ew]   = eig(C);         % Eigenvektoren und Eigenwerte
            ev3(:,:,k)= ev;            % np Matrizen mit Eigenvektoren
            ew3(:,k)  = diag(ew);      % np Spalten mit Eigenwerten
        end
        GGWB1 = zeros(ns,1);
        CG = CC(:,:,1);
        CG(end,:) = 1;
        b = [zeros(ns-1,1);1];          % b-Vektor mit [0; 0; ...; 0; 1]
        GGWB1 = CG\b;                   % Zustandsvektor im GGW als Spaltenvektor
        E = eye(ns);         % Einheitsmatrix, Spaltenvektoren sind Anfangszustände
        D = triu(ones(ns));  % obere Dreiecksmatrix mit Einsen belegt
        B = [];              % sicherheitshalber;
        % Berechnet für jeden Puls und jeden möglichen Ausgangszustand (k)
        % die Matrix B.pmat
        for pu = 1:np
            EV = ev3(:,:,pu);    % Matrix der Eigenvektoren in Array
            EW = ew3(:,pu);      % Vektor der Eigenwerte in Matrix
            for k = 1:ns
                Anf_Besetzung = E(:,k);                      % nur Zustand k besetzt
                B(pu,k).pmat  = EV*(diag(EV\Anf_Besetzung)); % .pmat von typ und k
            end
        end
        % Berechnung u. Speicherung der Übergangswahrscheinlichkeitsmatrizen
        for pu =1:np    
           EW = ew3(:,pu);
           for k = 1:ns                      % k ist ein bestimmter Anfangszustand
             probl = B(pu,k).pmat*exp(EW*dt); % Wahrscheinlichkeiten nach dt
             TIS(pu).sprobl(:,k) = D*probl;   % summierte Wahrscheinlichkeiten 
           end
        end
       	% Speicherplatz reservieren
        SEc = zeros(AnzMPkum(np),1);	% Summe der einzelnen Simulationen
        SEb = SEc;                      % Summe der einzelnen Simulationen
           
         for m = 1:N_it
         
            zust_0 = zeros(ns,AnzMPkum(np));
            zust_s = zust_0;                    % Summe der Einzelströme
            for nr = 1:N_ch
                zust = zust_0;                  % Nullmatrix für Zustände  
                sBesetzung = D*GGWB1;     % summierte Besetzungswahrscheinlichkeiten
                a = rand(1,AnzMPkum(np)+1);             % Zufallszahl entscheidet Vor - Besetzung   
                rz = max(find(sBesetzung>a(end)));    % zufälliger Zustand in Vor-Besetzung
                j = 0;
                for pu = 1:np         
                   for i=1:AnzMP(pu)
                             j = j+1;
                             % a=rand;
                             sBesetzung = TIS(pu).sprobl(:,rz); 
                             rz = max(find(sBesetzung>a(j))); 
                             zust(:,j) = zust(:,j) + E(:,rz);
                   end
                end
                zust_s = zust_s + zust;
            end 
        
            zust = zust_s / N_ch;
            strom = uc*zust;
            fluor = ub*zust;
            SEc = SEc + strom'; 
            SEb = SEb + fluor';
            
            end
        
       
        % die Vektoren SQ und SE erhalten jetzt neue Bedeutungen, 
        % um nicht noch weiteren Speicherplatz zu "vergeuden"
        if N_it==1
            SEc = SEc/N_it;	
            SEb = SEb/N_it;
            
        else      
        SEc = SEc/N_it; % das sind jetzt die Mittelwerte Strom
        SEb = SEb/N_it;	% das sind jetzt die Mittelwerte Fluor
        end
         
       handles.SEc=SEc;
       handles.SEb=SEb;
   
       guidata(hObject, handles);
       
       t = dt*(1:length(strom));
       handles.t=t;

       plot(handles.axes1,t,SEc); % Mittelwert Strom
      
  end


% if get(handles.variabel,'Value')==true
     
 %end
 
%if get(handles.glatt,'Value')==true
 %[strom,s0,fluor,t]=simulator_G(Modell,Puls);
  %   handles.strom=strom;
   %  handles.fluor=fluor;
    % handles.t=t;

    %plot(handles.axes1,t,strom);
    
%end
end
 
 %if get(handles.automatisch,'Value')==true
%end   
% Die handles-struktur aktualisieren
guidata(hObject, handles);

% --- Executes on button press in close.
function close_Callback(hObject, eventdata, handles)
% hObject    handle to close (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

Abfrage = questdlg('Speichern?','title','Ja','Nein','default'); 
 if strcmp(Abfrage, 'Ja') 
    if get(handles.Vorgabe,'Value')==true   % wenn Vorgabe ausgewählt
   
     if get(handles.Zeitschritt_fest,'Value')==true 
     t  = (handles.t)';
    
     SEc= handles.SEc;

     A  = [t,SEc];
     DefaultName = ['Einzelkanal','.csv'];
     [FileName,PathName]=uiputfile('*.csv','ASCII-Datei speichern',DefaultName);
        if FileName~=0      % Nur wenn ein file ausgewählt wurde
            FilePath=fullfile(PathName,FileName);
            csvwrite(FilePath,A);
        end
     end
    end
    
    if get(handles.Pulsdatei_geladen,'Value')==true %wenn Pulsdatei gewählt wurde       
    if get(handles.Zeitschritt_fest,'Value')==true 
     t  = (handles.t)';
  
     SEc= handles.SEc;    
    
     A  = [t,SEc];
     DefaultName = ['Einzelkanal','.csv'];
     [FileName,PathName]=uiputfile('*.csv','ASCII-Datei speichern',DefaultName);
        if FileName~=0      % Nur wenn ein file ausgewählt wurde
            FilePath=fullfile(PathName,FileName);
            csvwrite(FilePath,A);
        end
 % if get(handles.variabel,'Value')==true   schon vorgesehen für die
                                              % anderen 2 Fälle
 % if get(handles.automatisch,'Value')==true  
    end
    end

 
end
close(handles.figure1);         %Fenster schließen

% --- Executes on button press in Histogramme.
function Histogramme_Callback(hObject, eventdata, handles)
% hObject    handle to Histogramme (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Pulsprotokoll_neu_laden_Callback(hObject, eventdata, handles)
% hObject    handle to Pulsprotokoll_neu_laden (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[FileNameP,PathNameP]=uigetfile('*.m');
    if FileNameP~=0      % Nur wenn ein file ausgewählt wurde
        FilePathP=fullfile(PathNameP,FileNameP);
        set(handles.Pulsname,'String',FileNameP);
    end
    % Die handles-struktur aktualisieren
guidata(hObject, handles);
% --------------------------------------------------------------------
function Modell_neu_laden_Callback(hObject, eventdata, handles)
% hObject    handle to Modell_neu_laden (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[FileNameM,PathNameM]=uigetfile('*.m');
    if FileNameM~=0      % Nur wenn ein file ausgewählt wurde
        FilePathM=fullfile(PathNameM,FileNameM);
        set(handles.Modellname,'String',FileNameM);
     end
    
    % Die handles-struktur aktualisieren
guidata(hObject, handles);


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
uiresume(handles.figure1);
