diff --git a/Spectral-FLIM GUI.zip b/Spectral-FLIM GUI.zip deleted file mode 100644 index 3872415..0000000 Binary files a/Spectral-FLIM GUI.zip and /dev/null differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/AddScans.fig b/Spectral-FLIM GUI/Spectral-FLIM GUI/AddScans.fig new file mode 100644 index 0000000..311b9c6 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/AddScans.fig differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/AddScans.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/AddScans.m new file mode 100644 index 0000000..5596a2a --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/AddScans.m @@ -0,0 +1,444 @@ +function varargout = AddScans(varargin) +% AddScans MATLAB code for AddScans.fig +% AddScans, by itself, creates a new AddScans or raises the existing +% singleton*. +% +% H = AddScans returns the handle to a new AddScans or the handle to +% the existing singleton*. +% +% AddScans('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in AddScans.M with the given input arguments. +% +% AddScans('Property','Value',...) creates a new AddScans or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before AddScans_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to AddScans_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 AddScans + +% Last Modified by GUIDE v2.5 18-Jun-2013 11:02:17 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @AddScans_OpeningFcn, ... + 'gui_OutputFcn', @AddScans_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 AddScans is made visible. +function AddScans_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 AddScans (see VARARGIN) + +% Choose default command line output for AddScans +handles.output = hObject; + +handles.par_file = {}; +handles.par_IRFfile = ''; +handles.filename = {}; + +set(handles.text2,'String','Ready'); + +wt = num2cell(25); +wt(1) = {548}; +wt(2) = {60}; +set(handles.uitable1,'ColumnWidth',wt); + +col_name = {'Files','weight'}; +set(handles.uitable1,'Data',handles.filename'); +set(handles.uitable1,'ColumnName',col_name); + +% Update handles structure +guidata(hObject, handles); + +% UIWAIT makes AddScans wait for user response (see UIRESUME) +% uiwait(handles.figure1); + + +% --- Outputs from this function are returned to the command line. +function varargout = AddScans_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; + + +% --- Executes on button press in Load_button. +function Load_button_Callback(hObject, eventdata, handles) +% hObject handle to Load_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +n = numel(handles.par_file); + +[FileName,PathName] = uigetfile({'*.ht3;*.pt3','t3r-files';'*.*','All Files' },'Select data files ...','MultiSelect', 'on'); + +if ~iscell(FileName) + if FileName ~= 0 + handles.par_file{n+1} = [PathName FileName]; + handles.filename{n+1} = FileName; + end +else + for k = 1:numel(FileName) + handles.par_file{n+k} = [PathName FileName{k}]; + handles.filename{n+k} = FileName{k}; + end +end +for n = 1:numel(handles.filename) + data{n,1} = handles.filename{n}; + data{n,2} = 1; + + handles.f_weight(n) = 1; + +end + +set(handles.uitable1,'Data',data); +guidata(hObject, handles); + + +% --- Executes on button press in SetParams_button. +function SetParams_button_Callback(hObject, eventdata, handles) +% hObject handle to SetParams_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(handles.figure1,'Visible','off'); +Set_Params; +set(handles.figure1,'Visible','on'); + + +% --- Executes on button press in Start_button. +function Start_button_Callback(hObject, eventdata, handles) +% hObject handle to Start_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +set(handles.text2,'String','Processing data...'); +k = numel(handles.par_file); + +for n = 1:k + + W = handles.par_file{n}; + s = sprintf('Processing file %s (%d of %d)...', handles.filename{n}, n, k); + + set(handles.text2,'String', s ); + + pause(0.2) + + N1 = [W(1:end-4) '_FLIM.mat']; + tmp = dir(N1); + + if (numel(tmp)==0) + Process_file(W, handles.par_IRFfile); + end + +end + +for n = 1:k + + W = handles.par_file{n}; + + load([W(1:end-4) '_DATA.mat'], 'head', 'tag', 'tcspc', 'IRF', 'AP', 'DC'); + + nx(n) = size(tag,1); + ny(n) = size(tag,2); + nch(n) = size(tcspc,1); + nbin(n) = size(tcspc,2); + num_PIE(n) = size(tcspc,3); + +end + +ind = (nx~=nx(1))|(ny~=ny(1)); +if sum(ind)==0 + ind = (nch~=nch(1))|(nbin~=nbin(1))|(num_PIE~=num_PIE(1)); + if sum(ind)==0 + nx = nx(1); + ny = ny(1); + nch = nch(1); + nbin = nbin(1); + num_PIE = num_PIE(1); + + numpix = nx*ny; + numbin = nch*nbin*num_PIE; + numimg = k; + + s = sprintf('Computation in progress...'); + + else + s = sprintf('TCSPC formats are not matching! Aborted.'); + end +else + s = sprintf('Image sizes are not matching! Aborted.'); +end + +set(handles.text2,'String', s ); +pause(0.2) + +p = handles.f_weight./sum(handles.f_weight); + +sname = []; + +raw_data = zeros(nx,ny,numbin,numimg); + +for n = 1:numimg + + W = handles.par_file{n}; + + load([W(1:end-4) '_FLIM.mat'], 'stim') + + stim = reshape(stim, [nx ny numbin]); % rearrange the data for convenience + raw_data(:,:,:,n) = stim; + clear stim; + + tmp = sprintf('%s (%5.2f%%) ',handles.filename{n}(1:end-4),100.*p(n)); + + sname = [sname tmp]; +end + +raw_data(raw_data<0) = 0; + +% p = round(squeeze(sum(raw_data,3)).*repmat(p,[nx ny 1])); + +stim = zeros(nx,ny,numbin); + +h = waitbar(0,'Progress:'); + +for n1 = 1:nx + + for n2 = 1:ny + + tcspc = zeros(1,numbin); + + for k = 1:numimg + + tmp = round(raw_data(n1,n2,:,k)); + + n_ph = sum(tmp); + + p_n = zeros(1,n_ph); + bin = 1:numbin; + bin(tmp==0) = []; + + a = 1; + for l = 1:numel(bin) + e = a+tmp(bin(l)); + p_n(a:e-1) = bin(l); + a = e; + end + + for j = 1:10 + p_n = p_n(randperm(n_ph)); + end + + for j = 1:round(n_ph*p(k)) + bin = p_n(ceil(n_ph.*rand(1))); + tcspc(bin) = tcspc(bin) +1; + end + end + stim(n1,n2,:) = tcspc; + end + waitbar(n1/nx,h); + drawnow +end +close(h); + +stim = reshape(stim, [nx ny nch nbin num_PIE]); +tcspc = shiftdim(sum(sum(stim,1),2),2); +tcspc = tcspc./repmat(head.tauw,[nch 1 num_PIE]); +tag = squeeze(sum(stim,4)); + +pathname = ''; +tmp = strfind(handles.par_file{numimg},'\'); +if ~isempty(tmp) + pathname = handles.par_file{numimg}(1:tmp(end)); +end + +head.CreatorName = sprintf('%-18s','AddScans'); +head.CreatorVersion = sprintf('%-12s','1.0.0.0'); +tmp = clock; +head.FileTime = sprintf('%02d/%02d/%02d %02d:%02d:%02d ',tmp(3),tmp(2),tmp(1)-2000,tmp(4),tmp(5),round(tmp(6))); + +save([pathname sname(1:end-1) '_DATA.mat'], 'head', 'tag', 'tcspc', 'IRF', 'AP', 'DC'); +save([pathname sname(1:end-1) '_FLIM.mat'], 'stim'); + +fid = fopen([pathname sname(1:end-1) '.pt3'],'w'); +fwrite(fid, sprintf('%-16s',head.Ident), 'char'); % Ident (1-..) 4 +fwrite(fid, head.FormatVersion, 'char'); % FormatVersion (1-..) 20 +fwrite(fid, head.CreatorName, 'char'); % CreatorName (1-18) 26 +fwrite(fid, head.CreatorVersion, 'char'); % CreatorVersion (1-7) 44 +fwrite(fid, head.FileTime, 'char'); % FileTime (1-17) 56 + +a = [13 10]; +fwrite(fid, a, 'char'); % 'CR/LF' 74 + +fwrite(fid, head.Comment, 'char'); % Comment (256) 76 + +fwrite(fid, head.NCurves, 'int32'); % NCurves (1) 332 +fwrite(fid, head.BitsPerRecord, 'int32'); % BitsPerRecord (1) 336 +fwrite(fid, head.RoutingChannels, 'int32'); % RoutingChannels (1) 340 +fwrite(fid, head.NumberOfBoards, 'int32'); % NumberOfBoards (1) 344 +fwrite(fid, head.ActiveCurve, 'int32'); % ActiveCurve (1) 348 +fwrite(fid, head.MeasMode, 'int32'); % MeasMode (1) 352 +fwrite(fid, head.SubMode, 'int32'); % SubMode (1) 356 +fwrite(fid, head.RangeNo, 'int32'); % RangeNo (1) 360 +fwrite(fid, head.Offset, 'int32'); % Offset (1) 364 +fwrite(fid, 0, 'int32'); % TAcq (1) 368 +fwrite(fid, head.StopAt, 'int32'); % StopAt (1) 372 +fwrite(fid, head.StopOnOvfl, 'int32'); % StopOnOvfl (1) 376 +fwrite(fid, head.Restart, 'int32'); % Restart (1) 380 +fwrite(fid, head.LinLog, 'int32'); % DisplayLinLog (1) 384 +fwrite(fid, head.MinAx, 'int32'); % DisplayTimeAxMin (1) 388 +fwrite(fid, head.MaxAx, 'int32'); % DisplayTimeAxMax (1) 392 +fwrite(fid, head.MinAxCnt, 'int32'); % DisplayCountAxMin (1) 396 +fwrite(fid, head.MaxAxCnt, 'int32'); % DisplayCountAxMax (1) 400 + +for x = 1:8 + fwrite(fid, head.DispCurves(2*x-1), 'int32'); % DisplayCurve[x].MapTo (8x1) 404 412 420 428 436 444 452 460 + fwrite(fid, head.DispCurves(2*x ), 'int32'); % DisplayCurve[x].Show (8x1) 408 416 424 432 440 448 456 464 +end; + +for x = 1:3 + fwrite(fid, head.Params(3*x-2), 'float'); % Param[x].Start (3x1) 468 480 492 + fwrite(fid, head.Params(3*x-1), 'float'); % Param[x].Step (3x1) 472 484 496 + fwrite(fid, head.Params(3*x ), 'float'); % Param[x].End (3x1) 476 488 500 +end; + +fwrite(fid, head.RepeatMode, 'int32'); % RepeatMode (1) 504 +fwrite(fid, head.RepeatsPerCurve, 'int32'); % RepeatsPerCurve (1) 508 +fwrite(fid, head.RepeatTime, 'int32'); % RepeatTime (1) 512 +fwrite(fid, head.RepeatWaitTime, 'int32'); % RepeatWaitTime (1) 516 + +fwrite(fid, head.ScriptName, 'char'); % ScriptName (1-13) 520 + +for x = 1:head.NumberOfBoards + fwrite(fid, head.BoardIdent(:,x), 'char'); % HardwareIdent (1-..) 540 + fwrite(fid, head.BoardVersion(:,x), 'char'); % HardwareIdent (1-..) 540 + fwrite(fid, head.BoardSerial(x), 'int32'); % BordSerial (1) 564 + fwrite(fid, head.SyncDiv(x), 'int32'); % SyncDivider 568 + fwrite(fid, head.CFDZeroCross0(x), 'int32'); % CFD_Zero 0 (1) 572 + fwrite(fid, head.CFDLevel0(x), 'int32'); % CFDLevel 0 (1) 576 + fwrite(fid, head.CFDZeroCross1(x), 'int32'); % CFD_Zero 1 (1) 580 + fwrite(fid, head.CFDLevel1(x), 'int32'); % CFDLevel 1 (1) 584 + fwrite(fid, head.Resolution(x), 'float'); % Resolution (1) 588 + fwrite(fid, head.RouterModel(x), 'int32'); + fwrite(fid, head.RouterEnabled(x), 'int32'); + + fwrite(fid, head.RtCh1_InputType(x), 'int32'); + fwrite(fid, head.RtCh1_InputLevel(x), 'int32'); + fwrite(fid, head.RtCh1_InputEdge(x), 'int32'); + fwrite(fid, head.RtCh1_CFDPresent(x), 'int32'); + fwrite(fid, head.RtCh1_CFDLevel(x), 'int32'); + fwrite(fid, head.RtCh1_CFDZeroCross(x), 'int32'); + fwrite(fid, head.RtCh2_InputType(x), 'int32'); + fwrite(fid, head.RtCh2_InputLevel(x), 'int32'); + fwrite(fid, head.RtCh2_InputEdge(x), 'int32'); + fwrite(fid, head.RtCh2_CFDPresent(x), 'int32'); + fwrite(fid, head.RtCh2_CFDLevel(x), 'int32'); + fwrite(fid, head.RtCh2_CFDZeroCross(x), 'int32'); + fwrite(fid, head.RtCh3_InputType(x), 'int32'); + fwrite(fid, head.RtCh3_InputLevel(x), 'int32'); + fwrite(fid, head.RtCh3_InputEdge(x), 'int32'); + fwrite(fid, head.RtCh3_CFDPresent(x), 'int32'); + fwrite(fid, head.RtCh3_CFDLevel(x), 'int32'); + fwrite(fid, head.RtCh3_CFDZeroCross(x), 'int32'); + fwrite(fid, head.RtCh4_InputType(x), 'int32'); + fwrite(fid, head.RtCh4_InputLevel(x), 'int32'); + fwrite(fid, head.RtCh4_InputEdge(x), 'int32'); + fwrite(fid, head.RtCh4_CFDPresent(x), 'int32'); + fwrite(fid, head.RtCh4_CFDLevel(x), 'int32'); + fwrite(fid, head.RtCh4_CFDZeroCross(x), 'int32'); +end + +fwrite(fid, head.ExternalDev, 'int32'); % External Devices (1) 592 +fwrite(fid, head.Reserved1, 'int32'); % Dummy (1) 596 +fwrite(fid, head.Reserved2, 'int32'); % Dummy (1) 600 + +fwrite(fid, 0, 'int32'); % Syncrate (1) 604 +fwrite(fid, 0, 'int32'); % Countrate (1) 608 +fwrite(fid, 0, 'int32'); % TTTRStopAfter (1) 612 +fwrite(fid, 0, 'int32'); % TTTRStopReason (1) 616 +fwrite(fid, 0, 'uint32'); % NCounts (1) 620 + +fwrite(fid, head.SpecHeaderLength, 'uint32'); % SpecHeaderLength (1) 624 +fwrite(fid, head.ImgHdr.Dimensions, 'int32'); % Dimensions (3=area) (1) 628 +fwrite(fid, head.ImgHdr.Ident, 'int32'); % Ident (1=E710) (1) 632 +fwrite(fid, 1+log2(head.ImgHdr.Frame), 'int32'); +fwrite(fid, 1+log2(head.ImgHdr.LineStart), 'int32'); +fwrite(fid, 1+log2(head.ImgHdr.LineStop), 'int32'); +fwrite(fid, head.ImgHdr.Pattern, 'int32'); +fwrite(fid, head.ImgHdr.PixX, 'int32'); +fwrite(fid, head.ImgHdr.PixY, 'int32'); + +fclose(fid); + +set(handles.text2,'String','Done'); + + +% --- Executes on button press in Quit_button. +function Quit_button_Callback(hObject, eventdata, handles) +% hObject handle to Quit_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +close + +% --- 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 +delete(hObject); + + +% --- Executes when entered data in editable cell(s) in uitable1. +function uitable1_CellEditCallback(hObject, eventdata, handles) +% hObject handle to uitable1 (see GCBO) +% eventdata structure with the following fields (see UITABLE) +% Indices: row and column indices of the cell(s) edited +% PreviousData: previous data for the cell(s) edited +% EditData: string(s) entered by the user +% NewData: EditData or its converted form set on the Data property. Empty if Data was not changed +% Error: error string when failed to convert EditData to appropriate value for Data +% handles structure with handles and user data (see GUIDATA) + +data = get(handles.uitable1,'Data'); +if eventdata.Indices(2) == 2 + if isnan(eventdata.NewData) + data{eventdata.Indices(1),2} = 0; + set(handles.uitable1,'Data',data); + end +end + +for k = 1:size(data,1) + handles.f_weight(k) = data{k,2}; +end + +guidata(hObject, handles); + + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Calc_mIRF.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Calc_mIRF.m new file mode 100644 index 0000000..5994ad8 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Calc_mIRF.m @@ -0,0 +1,86 @@ +function IRF = Calc_mIRF(head, tcspc) + +maxres = max([head.Resolution]); +Resolution = max([maxres 0.032]); +Pulse = 1e9/head.SyncRate; + +tau = Resolution.*((1:size(tcspc,2))-0.5)'; +IRF = zeros(size(tcspc)); +nex = 2; + +t0 = 1.5; +w1 = 0.5^2; % width of excitation peak +T1 = 0.10; % time constant of rise term in IRF +T2 = 0.10; % time constant of decay term in IRF +a = 0.1; % rel. amplitude of second peak in IRF +b = 0.1; % rel. amplitude of second peak in IRF +dt = 0.0; % time shift of second peak in IRF + +for PIE = 1:size(tcspc,3) + + p = [t0 w1 T1 T2 a b dt 1 3]'; + pl = [t0-1.0 1e-3 1e-4 1e-4 0 0 -0.3 0.5*ones(1, nex)]'; + pu = [t0+1.0 1e-1 1 1 1 1 0.5 5*ones(1, nex)]'; + + tc = squeeze(sum(tcspc(:,:,PIE),2)); + [tmp, ord] = sort(tc,'descend'); + + ch = 1; + ind = ord(ch); + y = squeeze(tcspc(ind,:,PIE)); + + err = zeros(1,10); + + for casc=1:10 + [ts, s] = min(err); + r0 = p(:, s); + for sub=1:10 + rf = r0.*[2.^(1.1*(rand(size(r0))-0.5)./casc)]; % randomize start values + rf = max([rf pl],[],2); + rf = min([rf pu],[],2); + p(:,sub) = Simplex('TCSPC_Fun',rf,pl,pu,[],[],tau, y); + err(sub) = TCSPC_Fun(p(:,sub), tau, y); + end + end + + err1 = min(err); + p1 = mean(p(:,err==err1),2); + [tmp, c1, bla1, tmp1] = TCSPC_Fun(p1, tau, y); + + IRF(ind,:,PIE) = IRF_Fun(p1(1:7),tau); + IRF(ind,:,PIE) = IRF(ind,:,PIE)./max(IRF(ind,:,PIE)); + + para = p1(2:7); + p = [p1(1); p1(8:end)]; + pl = [ 0.5; 0.5*ones(nex, 1)]; + pu = [ 3.0; 10*ones(nex, 1)]; + + for ch = 2:size(tcspc,1) + ind = ord(ch); + y = squeeze(tcspc(ind,:,PIE)); + + err = zeros(1,10); + + for casc=1:10 + [ts, s] = min(err); + r0 = p(:, s); + for sub=1:10 + rf = r0.*[2.^(1.05*(rand(size(r0))-0.5)./casc)]; % randomize start values + rf = max([rf pl],[],2); + rf = min([rf pu],[],2); + p(:,sub) = Simplex('TCSPC_Fun',rf,pl,pu,[],[],tau, y, para); + err(sub) = TCSPC_Fun(p(:,sub), tau, y, para); + end + end + + err1 = min(err); + p1 = mean(p(:,err==err1),2); + [tmp, c1, bla1, tmp1] = TCSPC_Fun(p1, tau, y, para); + + IRF(ind,:,PIE) = IRF_Fun([p1(1); para; p1(2:end)],tau); + IRF(ind,:,PIE) = IRF(ind,:,PIE)./max(IRF(ind,:,PIE)); + end; +end + +IRF(IRF<1e-4) = 0; +IRF = IRF./repmat(sum(IRF,2),[1 size(IRF,2) 1]); \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Convergence.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Convergence.m new file mode 100644 index 0000000..76c55d3 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Convergence.m @@ -0,0 +1,58 @@ +function [x_out,llh_out,n_iter,conv,b] = Convergence(I,K) +tic; +i_err = (min(K,[],2)>0); +K = K(i_err,:); +I = I(:,i_err); + +lI = log(I)-1; + +n = size(I,1); +k = size(K,2); + +hd = repmat(sum(K,1),[n 1]); + +X = repmat(sum(I,2),[1 k])./k/5; +Exitflag = false; + +me = zeros(1,20); +conv=[]; +n_iter=0; +update = 1.2; +while ~Exitflag + + rate = update; + + for sl = 1:20 + + Z = X*K'; + + + x = (X./hd).*((I./Z)*K); + dx = (x - X); + + X = X + rate.*dx; + + me(sl) = 25*max(sum(abs(dx),2)); + end + + if min(me) < 50 + update = 1.6; + end + + if min(me) < 1 + Exitflag = true; + else + Exitflag = false; + end + + n_iter=n_iter+20; + conv=[conv me]; %#ok + +end + +m = Z.*(log(Z)-lI); +llh = sum(m,2); +x_out = x; +llh_out = llh; +b=toc; +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Convol.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Convol.m new file mode 100644 index 0000000..7cadb44 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Convol.m @@ -0,0 +1,20 @@ +function y = Convol(irf, x) +% convol(irf, x) performs a convolution of the instrumental response +% function irf with the decay function x. Periodicity (=length(x)) is assumed. + +mm = mean(irf(end-10:end)); +if size(x,1)==1 || size(x,2)==1 + irf = irf(:); + x = x(:); +end +p = size(x,1); +n = numel(irf); +if p>n + irf = [irf; mm*ones(p-n,1)]; +else + irf = irf(1:p); +end +y = real(ifft((fft(irf)*ones(1,size(x,2))).*fft(x))); +t = rem(rem(0:n-1,p)+p,p)+1; +y = y(t,:); + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/DetectTimeGates.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/DetectTimeGates.m new file mode 100644 index 0000000..400b914 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/DetectTimeGates.m @@ -0,0 +1,161 @@ +function [timegate, Ngate, tcspc] = DetectTimeGates(tcspcdata, cnum, Resolution, pic) +%. +% +% DetectTimeGates divides the TCSPC histogramm into time-windows of the +% same length in order to separate the data from different excitation +% pulses. +% +% usage: [timegate, Ngate, tcspc] = DetectTimeGates(tcspcdata, cnum, Resolution, pic) +% +% tcspcdata : TCSPC histogram of a PIE experiment +% cnum : number of excitation pulses (default: 1) +% Resolution : bin-size of TSCPC data in ns (default: 0.002 ns) +% pic : flag to display aligned data +% +% DetectTimeGates returns the following data: +% +% timegate : array of the size [cnum*dnum, 4] containing the +% respective beginning and end of each time-window. +% +% The order of the list is +% +% timegate( 1 ,:): time-window for pulse 1 in detection channel 1 +% timegate( 1 ,:): time-window for pulse 1 in detection channel 2 +% ... timegate( n ,:): time-window for pulse 1 in detection channel n +% timegate( n+1 ,:): time-window for pulse 2 in detection channel 1 +% timegate( n+2 ,:): time-window for pulse 2 in detection channel 2 +% ... timegate( 2*n ,:): time-window for pulse 2 in detection channel n +% ... timegate(cnum*n,:): time-window for pulse cnum in detection channel n +% +% timegate(:, 1) : begin of time-window +% timegate(:, 2) : end of time-window +% timegate(:, 3) : if > 0: continuation of time-window +% timegate(:, 4) : if > 0: end of time-window +% +% Ngate : Number of bins in each time-window +% tcscpc : Sorted and aligned TCSPC histogram in the same order as the timegates +% +% ......................................................................................... + +if (nargin < 4)||isempty(pic) + pic = 0; +end +pic = (pic>0); + +if (nargin < 3)||isempty(Resolution) + Resolution = 0.002; +end + +if (nargin < 2)||isempty(cnum) + cnum = 1; +end + +NChannels = size(tcspcdata,1); +dnum = size(tcspcdata,2); +timegate = zeros(dnum*cnum,4); + +%% Determine maxima of all detectors + +tmpdata = zeros(size(tcspcdata)); + +for k = 1:dnum + tmpdata(:,k) = smooth(tcspcdata(:,k),ceil(0.1./Resolution)); +end + +irf_w = floor(1.5/Resolution); +win = floor(NChannels/cnum); % Max #channels / pulse; + +im = zeros(dnum, cnum); +m = zeros(dnum, cnum); +bg = zeros(dnum, cnum); + +[tpm,i1] = max(tmpdata); %#ok +off = floor(mod(i1,win)-irf_w); + +for l = 1:cnum + for k = 1:dnum + ind = off(k)+(l-1)*win+(1:win-2*irf_w); + ind(ind<1) = ind(ind<1) + NChannels; + ind(ind>NChannels) = ind(ind>NChannels) - NChannels; + [m(k,l),im(k,l)] = max(tmpdata(ind,k)); + im(k,l) = ind(im(k,l)); + bg(k,l) = mean(tmpdata(ind(2*irf_w:end),k)); + end +end + +ind = (m<3*bg)|(m<10); + +for l = 1:cnum + for k = 1:dnum + if ind(k,l) == 1 + mi = find(im(k,:) == i1(k)); + im(k,l) = im(k,mi)+floor((l-mi)*NChannels/cnum); + end + end +end + +%% Determine time-gates for photon assignment +if cnum>1 + Ngate = zeros(1,cnum); + for k = 1:cnum + p = k-1; + if p < 1 + p = cnum; + end + Ngate(k) = min([abs(im(:,k)-im(:,p)); NChannels-abs(im(:,p)-im(:,k))]); + end + Ngate = min(Ngate); +else + Ngate = NChannels; +end + +%% Define final windows for each pulse and detector + +g = zeros(cnum*dnum, 4); + +for k = 1:dnum + for l = 1:cnum + d = im(k,l)-irf_w; + if d > 0 + if d <= (NChannels - Ngate)+1 + g(k+(l-1)*dnum,1:2) = [d d+Ngate-1]; + else + g(k+(l-1)*dnum,:) = [d NChannels 1 d+Ngate-NChannels-1]; + end; + else + d = d + NChannels; + if d > NChannels - Ngate +1 + g(k+(l-1)*dnum,:) = [d NChannels 1 d+Ngate-NChannels-1]; + else + g(k+(l-1)*dnum,1:2) = [d d+Ngate-1]; + end; + end; + end +end + +%% Sort windows to according excitation pulse + +channels = repmat(1:dnum,[1 cnum]); + +for n = 1:cnum*dnum + mch = mod(mean(g(n,1):(g(n,2)+g(n,4))),NChannels); + pie = floor(mch/(NChannels/(cnum-0.5))); + timegate(channels(n)+pie*dnum,:) = g(n,:); +end + +tcspc = zeros(Ngate,cnum*dnum); + +for n = 1:cnum*dnum + if (timegate(n,3)==0) + tmp = tcspcdata(timegate(n,1):timegate(n,2),channels(n)); + else + tmp = [tcspcdata(timegate(n,1):timegate(n,2),channels(n)); tcspcdata(timegate(n,3):timegate(n,4),channels(n))]; + end + tcspc(:,n) = tmp; +end + +if pic + figure; + semilogy((1:Ngate), tcspc); +end + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/EFilter.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/EFilter.m new file mode 100644 index 0000000..ead0c00 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/EFilter.m @@ -0,0 +1,104 @@ +function varargout = EFilter(sze, cutoffM, cutoffm, n, varargin) + +% EFILTER constructs an elliptical lowpass filter Butterworth filter +% E = EFILTER(Size, cutoffM, cutoffm, n) designs an Nth order elliptical +% lowpass digital Butterworth filter where Size is a two element +% [rows, cols] vector specifying the size of the filter to construct, +% cutoffM and cutoffm, the cutoff freqency on the major and minor +% axes are 0 < cutoff <= 1. +% +% If E = EFilter(Size, cutoffM, cutoffm, n, alpha), where alpha is an angle +% in radians, it will return and plot an elliptical filter rotated +% counter-clockwise through alpha. +% +% If E = EFilter(Size, cutoffM, cutoffm, n, alpha, xoff, yoff), where xoff +% and yoff are offsets in the x and y direction, it will return and +% plot an eliptical filter which is offset by the specified amount. +% An offset of 0 corresponds to the center and an offset of 1 +% corresponds to the edge of the filter. A positive offset shifts the +% filter in the positive direction. +% +% Calling EFilter(...) without assigning the output variable +% plots the 3D surface described by the function. + +% Katie Streit kstreit@rice.edu +% ELEC 301 +% Rice University +% +% December 2001 + +% Much of this code was based on Peter Kovesi's (pk@cs.uwa.edu.au) +% Matlab function for a lowpass Butterworth filter. + +if nargin == 4 + alpha = 0; + offx = 0; + offy = 0; +elseif nargin == 5 + offx = 0; + offy = 0; + alpha = varargin{1}; +elseif nargin == 7 + alpha = varargin{1}; + offx = varargin{2}; + offy = varargin{3}; +else + error('Invalid number of input arguments'); +end + +if nargout > 1 + error('Invalid number of output arguments'); +end + +if cutoffM < 0 || cutoffM > 1 + error('cutoffM frequency must be between 0 and 1'); +end + +if cutoffm < 0 || cutoffm > 1 + error('cutoffm frequency must be between 0 and 1'); +end + +if rem(n,1) ~= 0 || n < 1 + error('n must be an integer >= 1'); +end + +% extract the sizes from sze + +rows = sze(1); +cols = sze(2); + +% x and y matrices normalized to +/-.5 and an offset of offx or offy + +x = ((((ones(rows,1) * [1:cols])-offx*rows/2) - (fix(cols/2)+1))/cols); +y = ((([1:rows]' * ones(1,cols))-offy*rows/2) - (fix(rows/2)+1))/rows; + +% apply a linear transformation to rotate through alpha. Note that it +% uses negative alpha, which is caused by x and y being independent matrices. + +x2 = (x*cos(alpha) - y*sin(-alpha)); +y2 = (x*sin(-alpha) + y*cos(alpha)); + +% constructs an elliptical cone (defined by a and b) of height r on each at +% each elliptical ring. (r is effectively the "radius") +% r = sqrt(((x2/a).^2 + (y2/b).^2)); + +% Designs the filter +% f = 1./(1.0 + (r./cutoff).^(2*n)); + +a = cutoffM/2; +b = cutoffm/2; + +f = 1./(1+((x2/(a)).^2 + (y2/(b)).^2).^n); + +if nargout > 0 + varargout{1} = f; +else + %Plots a normalized (+/- 1), interpolated 3D image of the filter + surf([-1:2/(cols-1):1],[-1:2/(rows-1):1], f); + shading interp; + title('Elliptical Butterworth filter'); + xlabel('x'); + ylabel('y'); + zlabel('intensity'); + grid on; +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/FastFLIM.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/FastFLIM.m new file mode 100644 index 0000000..62474d8 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/FastFLIM.m @@ -0,0 +1,220 @@ +function FastFLIM(fname) + +close all + +tmp = strfind(fname,'\'); +pathname = fname(1:tmp(end)); +filename = fname(tmp(end)+1:end); + +[head, tag, tcspc] = load_data([pathname filename]); + +load Get_Params; + +nx = head.ImgHdr.PixX; +ny = head.ImgHdr.PixY; +tx = floor(nx/binning); +ty = floor(ny/binning); +x = head.ImgHdr.X0+(1:binning:nx)*head.ImgHdr.PixelSize; +y = head.ImgHdr.Y0+(1:binning:ny)*head.ImgHdr.PixelSize; +nch = size(tcspc,1); +% nbin = size(tcspc,2); +num_PIE = size(tcspc,3); +tau = head.tau; + +load([pathname filename(1:end-4) '_Moments.mat'],'tav'); + +t_m = (tav(:,:,:,:,1)); + +clear tav; + +if binning > 1 + tmp = tag(1:binning*tx,:,:,:); + tmp = reshape(tmp, binning, tx, ny, nch, num_PIE); + tmp = shiftdim(sum(tmp,1),1); + tmp = tmp(:,1:binning*ty,:,:); + tmp = reshape(tmp, tx, binning, ty, nch, num_PIE); + tag = permute(sum(tmp,2), [1 3 4 5 2]); +end + +ind = (sum(tag,3)) < Threshold; +t_m(ind) = 0; + +ind = (tag >= Threshold); +t_m = squeeze(sum(ind.*t_m.*tag,3)./sum(ind.*tag,3)); +t_m(t_m<0) = 0; + + +intens = squeeze(sqrt(sum(ind.*tag,3))); +intens = intens./max(max(max(intens))); + +%save('updatefflim', 't_m', 'ntau', 'nbin', 'stim'); + +clear S1 S2 S3; + +xl = [399 440 485 540 580 610 630 699]; +yl = [[0 0 0]; [0 0 1]; [0 1 1]; [0 1 0]; [1 1 0]; [1 0.65 0]; [1 0 0]; [1 0 1]]; +lambda = 399:3:699; +spectrum = interp1(xl, yl, lambda); + +p1 = 0.06; +p2 = 0.555; +w = 0.435; + +for pulse = 1:num_PIE + + name = sprintf('FastFLIM %d', pulse); + + figure(figFLIM+pulse); + set(gcf,'Name',name,'NumberTitle','off'); + + S1 = subplot('Position', [p1 p2 w w]); + + tmp = repmat(intens(:,:,pulse)./max(max(intens(:,:,pulse))), [1 1 3]); + + lims = [tau_min tau_max]; + + val = reshape(t_m(:,:,pulse),size(t_m,1)*size(t_m,2),1); + + val(isnan(val)) = 0; + val(vallims(2)) = lims(2); + + k = 2 + round((val-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-2)); + k(k<2) = 1; + + im = spectrum(k,:); + im = reshape(im,size(tmp,1),size(tmp,2),3); + im = im.*tmp; + + image(x,y,im) + + colormap(spectrum) + + set(S1,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'CLim', lims, ... + 'color', [0 0 0]); + + xlabel('x (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('y (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + + tst = 2 + round(((lims(1):.5:lims(2))-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-3)); + n= 1; + for ttst = lims(1):0.5:lims(2) + stst(n) = cellstr(sprintf('%4.1f',ttst)); + n = n+1; + end + colorbar('CLim', lims, 'YTickMode','manual','XColor',[0 0 0],'YColor',[0 0 0],'Box','off','YTick', tst, ... + 'FontSize', 9,'TickDir','out', 'YTickLabel',stst); + +% save for fastflimgraph +% save([name '_graph1'], 'x', 'y'); + + S2 = subplot('Position', [p1 p1 w w]); + + W = tag(:,:,:,pulse); + W(Wlims(2)) = lims(2); + + k = 2 + round((val-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-3)); + k(k<2) = 1; + + im = spectrum(k,:); + im = reshape(im,size(tmp,1),size(tmp,2),3); + im = im.*tmp; + + image(x,y,im) + + set(S2,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'CLim', lims, ... + 'color', [0 0 0]); + + xlabel('x (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('y (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + tst = 2 + round(((440:40:680)-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-3)); + colorbar('CLim', lims, 'XColor',[0 0 0],'YColor',[0 0 0],'Box','off','YTick', tst, ... + 'FontSize',9, 'YTickLabel',{'440', '480', '520', '560', '600', '640', '680'},'TickDir','out'); + +% save for fastflimgraph +% save([name '_graph2'], 'x', 'y', 'im', 'spectrum', 'lims', 'tst') + + S3 = subplot('Position', [p2 p1 w w]); + + s = squeeze(sum(sum(W,2),1)); + lam = (lam_start+lam_step.*(-1:numel(s))); + ts = clam_min:clam_max; + if max(s)>0 + s = [0; s(:); 0]./max(s); + cs = interp1(lam, s, ts,'cubic'); + cs(tslam_start+lam_step.*nch) = 0; + else + cs = zeros(size(ts)); + end + + plot(ts, cs, '-','Color',[1 0 0]); + + set(S3,'FontSize',9,'color', [204 204 204]./255); + + % axis([10*floor(lam(1)/10) 10*ceil(lam(end)/10) 0 1.1]) + axis([clam_min clam_max 0 1.1]) + + xlabel('wavelength of \lambda_0 (nm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('rel. spectral irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +% save for fastflimgraph +% save([name '_graph3'],'ts', 'cs'); + + S4 = subplot('Position', [p2 p2 w w]); + + if nch == 1 + k_ind = floor(1+(numel(lambda)-1)); + else + k_ind = floor(1+((1:nch)-1).*(numel(lambda)-1)./(nch-1)); + end + + m = max(max(tcspc(:,:,pulse))); + tcspc(tcspc<=1) = 1e-4; + semilogy(tau,tcspc(1,:,pulse)./m,'-','Color',spectrum(k_ind(1),:),'LineWidth',2); + hold on; + for n = 2:size(tcspc,1) + semilogy(tau,tcspc(n,:,pulse)./m,'-','Color',spectrum(k_ind(n),:),'LineWidth',2); + end + + hold off + + set(S4,'FontSize',9,'color', [204 204 204]./255); + + axis([0 floor(tau(end)) 1e-4 1.1]) + + xlabel('time (ns)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('detection frequency','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +% save for fastflimgraph +% save([name '_graph4'],'tau', 'tcspc', 'm', 'k_ind') + +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Fluofit.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Fluofit.m new file mode 100644 index 0000000..e25cebb --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Fluofit.m @@ -0,0 +1,159 @@ +function [c, offset, A, tau, dc, dtau, irs, zz, t, chi] = Fluofit(irf, y, p, dt, tau, lim, init) +% The function FLUOFIT performs a fit of a multi-exponential decay curve. +% It is called by: +% [c, offset, A, tau, dc, doffset, dtau, irs, z, t, chi] = fluofit(irf, y, p, dt, tau, limits, init). +% The function arguments are: +% irf = Instrumental Response Function +% y = Fluorescence decay data +% p = Time between laser exciation pulses (in nanoseconds) +% dt = Time width of one TCSPC channel (in nanoseconds) +% tau = Initial guess times +% lim = limits for the lifetimes guess times +% init = Whether to use a initial guess routine or not +% +% The return parameters are: +% c = Color Shift (time shift of the IRF with respect to the fluorescence curve) +% offset = Offset +% A = Amplitudes of the different decay components +% tau = Decay times of the different decay components +% dc = Color shift error +% doffset = Offset error +% dtau = Decay times error +% irs = IRF, shifted by the value of the colorshift +% zz Fitted fluorecence component curves +% t = time axis +% chi = chi2 value +% +% The program needs the following m-files: simplex.m, lsfit.m, mlfit.m, and convol.m. +% (c) 1996 Jörg Enderlein + + +fitfun = 'lsfit'; + +close all +irf = irf(:); +offset = 0; +y = y(:); +n = length(irf); +if nargin>6 + if isempty(init) + init = 1; + end +elseif nargin>4 + init = 0; +else + init = 1; +end + +if init>0 + [cx, tau, c, c] = DistFluofit(irf, y, p, dt, [-3 3]); + cx = cx(:)'; + tmp = cx>0; + t = 1:length(tmp); + t1 = t(tmp(2:end)>tmp(1:end-1)) + 1; + t2 = t(tmp(1:end-1)>tmp(2:end)); + if length(t1)==length(t2)+1 + t1(end)=[]; + end + if length(t2)==length(t1)+1 + t2(1)=[]; + end + if t1(1)>t2(1) + t1(end)=[]; + t2(1)=[]; + end + tmp = []; + for j=1:length(t1) + tmp = [tmp cx(t1(j):t2(j))*tau(t1(j):t2(j))/sum(cx(t1(j):t2(j)))]; + end + tau = tmp; +else + c = 0; +end + +if (nargin<6)||isempty(lim) + lim = [zeros(1,length(tau)) 100.*ones(1,length(tau))]; +end; + +p = p/dt; +tp = (1:p)'; +tau = tau(:)'/dt; +lim_min = lim(1:numel(tau))./dt; +lim_max = lim(numel(tau)+1:end)./dt; +t = 1:length(y); +m = length(tau); +x = exp(-(tp-1)*(1./tau))*diag(1./(1-exp(-p./tau))); +irs = (1-c+floor(c))*irf(rem(rem(t-floor(c)-1, n)+n,n)+1) + (c-floor(c))*irf(rem(rem(t-ceil(c)-1, n)+n,n)+1); +z = convol(irs, x); +z = [ones(size(z,1),1) z]; +%A = z\y; +A = lsqnonneg(z,y); +z = z*A; +close all +if init<2 + disp('Fit = Parameters ='); + param = [c; tau']; + % Decay times and Offset are assumed to be positive. + paramin = [-1/dt lim_min]; + paramax = [ 1/dt lim_max]; + [param, dparam] = Simplex(fitfun, param, paramin, paramax, [], [], irf(:), y(:), p); + c = param(1); + dc = dparam(1); + tau = param(2:length(param))'; + dtau = dparam(2:length(param)); + x = exp(-(tp-1)*(1./tau))*diag(1./(1-exp(-p./tau))); + irs = (1-c+floor(c))*irf(rem(rem(t-floor(c)-1, n)+n,n)+1) + (c-floor(c))*irf(rem(rem(t-ceil(c)-1, n)+n,n)+1); + z = convol(irs, x); + z = [ones(size(z,1),1) z]; + z = z./(ones(n,1)*sum(z)); + %A = z\y; + A = lsqnonneg(z,y); + zz = z.*(ones(size(z,1),1)*A'); + z = z*A; + dtau = dtau; + dc = dt*dc; +else + dtau = 0; + dc = 0; +end +chi = sum((y-z).^2./abs(z))/(n-m); +t = dt*t; +tau = dt*tau'; +c = dt*c; +offset = zz(1,1); +A(1) = []; +if 1 + hold off + subplot('position',[0.1 0.4 0.8 0.5]) + plot(t,log10(y),t,log10(irs),t,log10(z)); + v = axis; + v(1) = min(t); + v(2) = max(t); + axis(v); + xlabel('Time / ns'); + ylabel('Log Count'); + s = sprintf('COF = %3.3f %3.3f', c, offset); + text(max(t)/2,v(4)-0.05*(v(4)-v(3)),s); + s = ['AMP = ']; + for i=1:length(A) + s = [s sprintf('%1.3f',A(i)/sum(A)) ' ']; + end + text(max(t)/2,v(4)-0.12*(v(4)-v(3)),s); + s = ['TAU = ']; + for i=1:length(tau) + s = [s sprintf('%3.3f',tau(i)) ' ']; + end + text(max(t)/2,v(4)-0.19*(v(4)-v(3)),s); + subplot('position',[0.1 0.1 0.8 0.2]) + plot(t,(y-z)./sqrt(abs(z))); + v = axis; + v(1) = min(t); + v(2) = max(t); + + axis(v); + xlabel('Time / ns'); + ylabel('Residue'); + s = sprintf('%3.3f', chi); + text(max(t)/2,v(4)-0.1*(v(4)-v(3)),['\chi^2 = ' s]); + set(gcf,'units','normalized','position',[0.01 0.05 0.98 0.83]) +end diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Fret_Series.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Fret_Series.m new file mode 100644 index 0000000..d06476e --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Fret_Series.m @@ -0,0 +1,75 @@ +clear all +close all + +load('F:\Messungen\SFLIM\data\FRET_GFP_and_mRFP_DATA.mat') +load('F:\Messungen\SFLIM\data\Donor.pat','-mat') +Donor = pat; + +load('F:\Messungen\SFLIM\data\FRET.pat','-mat') +Fret = pat; + +tau = head.tau; +w = head.tauw; +binw = floor(w./w(1)); +tr = 1e9/head.SyncRate; +Resolution = 0.032; + +decay = []; +fret = []; +irf = []; +for k = 1:numel(w) + irf = [irf repmat(IRF(k)/w(k),[1 binw(k)])]; + decay = [decay repmat(Donor(k)/w(k),[1 binw(k)])]; + fret = [fret repmat(Fret(k)/w(k),[1 binw(k)])]; +end + +tau_n = (1:numel(decay)).*Resolution; +tau_n = tau_n+(tau(1)-tau_n(1)); + +semilogy(tau_n,decay,'o',tau_n,irf,'x') + +[c, offset, A, tau, dc, dtau, irs, zz, t, chi] = Fluofit(irf, decay, tr, Resolution, [2 3], [0.5 0.5 10 10], 0); + +close; + +ind = find(A==max(A)); +t_D = tau(ind); + +t = 1:numel(fret); +p = tr/Resolution; +tp = (1:p)'; +n = numel(irf); +irs = (1-c+floor(c))*irf(rem(rem(t-floor(c)-1, n)+n,n)+1) + (c-floor(c))*irf(rem(rem(t-ceil(c)-1, n)+n,n)+1); + +E = (0:99)./100; +for k = 1:numel(E) + + t_F = t_D.*(1-E(k)); + + ttau = [t_F tau']/Resolution; + + m = numel(ttau); + + x = exp(-(tp-1)*(1./ttau))*diag(1./(1-exp(-p./ttau))); + z = convol(irs(:), x); + z = [ones(size(z,1),1) z]; + A = lsqnonneg(z,fret(:)); + z = z*A; + chi(k) = sum((fret(:)-z).^2./abs(fret(:)))/(n-m); +end + +[m, ind] = min(chi); + +t_F = t_D.*(1-E(ind)); + +ttau = [t_F tau']/Resolution; + +m = numel(tau); + +x = exp(-(tp-1)*(1./ttau))*diag(1./(1-exp(-p./ttau))); +z = convol(irs(:), x); +z = [ones(size(z,1),1) z]; +A = z\fret(:); % lsqnonneg(z,fret(:)); +z = z*A; + +semilogy(tau_n,fret,'x',tau_n,z) diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Get_Params.mat b/Spectral-FLIM GUI/Spectral-FLIM GUI/Get_Params.mat new file mode 100644 index 0000000..fecd925 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/Get_Params.mat differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/HT3_Read.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/HT3_Read.m new file mode 100644 index 0000000..0121fcd --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/HT3_Read.m @@ -0,0 +1,247 @@ +function [sync, tcspc, chan, special, num, loc, head] = HT3_Read(name, cnts) +% +% function [sync, tcspc, chan, special, num, head] = HT3_Read(name, cnts) +% +% This function reads single-photon data from the file 'name' +% +% If the argument parameter 'cnts' is missing, or has the value 0 it returns just the +% header of the file in the output variable 'sync'. +% +% If 'cnts' contains a number larger than 0, the routine reads 'cnts' +% records the data stream or up the end of the file. +% +% If 'cnts' contains two numbers [cnts(1) cnts(2)], the routine proceeds +% to the position cnts(1) before readinf the cnts(2) records of data. +% +% If 'cnts' contains three numbers [cnts(1) cnts(2) cnts(3)], the routine +% does not read the header, but jumps over the first cnts(3)-bytes that +% represent the length of the file-header. After that it procceds to the +% data position cnts(1) before reading the cnts(2) records of data. +% +% The output variables contain the followig data: +% sync : number of the sync events that preceeded this detection event +% tcspc : number of the tcspc-bin of the event +% chan : number of the input channel of the event (detector-number) +% special : indicator of the event-type (0: photon; else : virtual photon) +% num : counter of the records that were actually read +% loc : number of overcounts after last valid photon +% head : the file header +% + +if (nargin<2)||isempty(cnts) + cnts = [0 0 0]; +end; + +if numel(cnts)<2 + cnts = [0 cnts 0]; +end; + +if numel(cnts)<3 + cnts = [cnts 0]; +end; + + +if (nargin<1)||isempty(name) + fprintf(1,'\n\n You have to specify a valid file-name. Aborted.\n'); + return; +else + fid = fopen(name); + if fid<1 + fprintf(1,'\n\n Could not open <%s>. Aborted.\n', name); + return; + end +end + +% +% The following represents the readable ASCII file header portion +% + +if (nargout==7)||(cnts(3)==0) + + head = []; + + tmp = deblank(char(fread(fid, 16, 'char')')); + + if strcmp(tmp, 'HydraHarp') + + head.Ident = tmp; + head.FormatVersion = deblank(char(fread(fid, 6, 'char')')); + +% if not(strcmp(head.FormatVersion,'1.0')) +% fprintf(1,'\n\n Warning: This program is for version 1.0 only. Aborted.'); +% fclose(fid); +% return; +% end; + + head.CreatorName = deblank(char(fread(fid, 18, 'char')')); + head.CreatorVersion = deblank(char(fread(fid, 12, 'char')')); + head.FileTime = deblank(char(fread(fid, 18, 'char')')); + fread(fid, 2, 'char'); + head.CommentField = deblank(char(fread(fid, 256, 'char')')); + + % + % The following is binary file header information + % + + head.Curves = fread(fid, 1, 'int32'); + head.BitsPerRecord = fread(fid, 1, 'int32'); + head.ActiveCurve = fread(fid, 1, 'int32'); + head.MeasurementMode = fread(fid, 1, 'int32'); + head.SubMode = fread(fid, 1, 'int32'); + head.Binning = fread(fid, 1, 'int32'); + head.Resolution = fread(fid, 1, 'double')/1000; + head.Offset = fread(fid, 1, 'int32'); + head.AcquisitionTime = fread(fid, 1, 'int32'); + head.StopAt = fread(fid, 1, 'int32'); + head.StopOnOvfl = fread(fid, 1, 'int32'); + head.Restart = fread(fid, 1, 'int32'); + head.DispLinLog = fread(fid, 1, 'int32'); + head.DispTimeFrom = fread(fid, 1, 'int32'); + head.DispTimeTo = fread(fid, 1, 'int32'); + head.DispCountFrom = fread(fid, 1, 'int32'); + head.DispCountTo = fread(fid, 1, 'int32'); + + for i = 1:8 + head.DispCurveMapTo(i) = fread(fid, 1, 'int32'); + head.DispCurveShow(i) = fread(fid, 1, 'int32'); + end; + + for i = 1:3 + head.ParamStart(i) = fread(fid, 1, 'float'); + head.ParamStep(i) = fread(fid, 1, 'float'); + head.ParamEnd(i) = fread(fid, 1, 'float'); + end; + + head.RepeatMode = fread(fid, 1, 'int32'); + head.RepeatsPerCurve = fread(fid, 1, 'int32'); + head.RepeatTime = fread(fid, 1, 'int32'); + head.RepeatWait = fread(fid, 1, 'int32'); + head.ScriptName = deblank(char(fread(fid, 20, 'char')')); + + % + % The next is a board specific header + % + + head.HardwareIdent = deblank(char(fread(fid, 16, 'char')')); + head.HardwareVersion = deblank(char(fread(fid, 8, 'char')')); + head.HardwareSerial = fread(fid, 1, 'int32'); + head.NumModules = fread(fid, 1, 'int32'); + + for i = 1:10 + head.Module(i).Serial = fread(fid, 1, 'int32'); + head.Module(i).Version = fread(fid, 1, 'int32'); + end; + + head.BaseResolution = fread(fid, 1, 'double'); + head.InputsEnabled = fread(fid,1,'int64'); + head.InputsPresent = fread(fid,1,'int32'); + head.RefClock = fread(fid,1,'int32'); + head.ExtDevices = fread(fid,1,'int32'); + head.MarkerSettings = fread(fid,1,'int32'); + + head.SyncDivider = fread(fid, 1, 'int32'); + head.SyncCFDLevel = fread(fid, 1, 'int32'); + head.SyncCFDZeroCross = fread(fid, 1, 'int32'); + head.SyncOffset = fread(fid, 1, 'int32'); + + for i = 1:head.InputsPresent + head.InpChannel(i).ModuleIdx = fread(fid, 1, 'int32'); + head.InpChannel(i).CFDLevel = fread(fid, 1, 'int32'); + head.InpChannel(i).CFDZeroCross = fread(fid, 1, 'int32'); + head.InpChannel(i).Offset = fread(fid, 1, 'int32'); + end; + + for i = 1:head.InputsPresent + head.InpChannel(i).CntRate = fread(fid, 1, 'int32'); + end; + + % + % The next is a T3 mode specific header + % + + head.SyncRate = fread(fid, 1, 'int32'); + head.StopAfter = fread(fid, 1, 'int32'); + head.StopReason = fread(fid, 1, 'int32'); + head.ImgHdrSize = fread(fid, 1, 'int32'); + head.Records = fread(fid, 1, 'int64'); + + %Special header for imaging + + if head.ImgHdrSize > 0 + head.ImgHdr.Dimensions = fread(fid, 1, 'int32'); + head.ImgHdr.Ident = fread(fid, 1, 'int32'); + if head.ImgHdr.Ident == 1 + head.ImgHdr.PixelTime = 2e5*fread(fid, 1, 'int32'); + head.ImgHdr.Acceleration = fread(fid, 1, 'int32'); + head.ImgHdr.Pattern = fread(fid, 1, 'int32'); + fread(fid, 1, 'int32'); + head.ImgHdr.X0 = fread(fid, 1, 'float'); + head.ImgHdr.Y0 = fread(fid, 1, 'float'); + head.ImgHdr.PixX = fread(fid, 1, 'int32'); + head.ImgHdr.PixY = fread(fid, 1, 'int32'); + head.ImgHdr.PixelSize = fread(fid, 1, 'float'); + head.ImgHdr.TStartTo = fread(fid, 1, 'float'); + head.ImgHdr.TStopTo = fread(fid, 1, 'float'); + head.ImgHdr.TStartFro = fread(fid, 1, 'float'); + head.ImgHdr.TStopFro = fread(fid, 1, 'float'); + elseif head.ImgHdr.Ident == 16 + head.ImgHdr.PixelTime = 2e5*fread(fid, 1, 'int32'); + head.ImgHdr.Acceleration = fread(fid, 1, 'int32'); + head.ImgHdr.Pattern = fread(fid, 1, 'int32'); + head.ImgHdr.X0 = fread(fid, 1, 'int32')/1000; + head.ImgHdr.Y0 = fread(fid, 1, 'int32')/1000; + head.ImgHdr.Z0 = fread(fid, 1, 'int32')/1000; + head.ImgHdr.PixX = fread(fid, 1, 'int32'); + head.ImgHdr.PixY = fread(fid, 1, 'int32'); + head.ImgHdr.PixelSize = fread(fid, 1, 'float'); + head.ImgHdr.TStartTo = fread(fid, 1, 'float'); + head.ImgHdr.TStopTo = fread(fid, 1, 'float'); + head.ImgHdr.TStartFro = fread(fid, 1, 'float'); + head.ImgHdr.TStopFro = fread(fid, 1, 'float'); + + else + head.ImgHdr.data = fread(fid, head.ImgHdrSize-2, 'int32'); + end + end; + head.length = ftell(fid); + else + head.Resolution = 2e-3; % in nanoseconds + head.length = 0; + end +end + + +if cnts(2)>0 + + if cnts(3)>0 + fseek(fid, (cnts(3)), 'bof'); + end + if cnts(1)>1 + fseek(fid, 4*(cnts(1)-1), 'cof'); + end + + WRAPAROUND=1024; + + [T3Record num] = fread(fid, cnts(2), 'ubit32'); % all 32 bits: + special = bitand(T3Record,2147483648)>0; + chan = bitand(bitshift(T3Record,-25),63); + tcspc = bitand(bitshift(T3Record,-10),32767); + sync = bitand(T3Record,1023); + + ind = (special==1 & chan==63); + tmp = sync(ind==1); + tmp(tmp==0) = 1; + sync(ind) = tmp; + sync = sync + WRAPAROUND*cumsum(ind.*sync); + + sync(ind) = []; + tcspc(ind) = []; + special(ind) = []; + chan(ind) = []; + loc = num - find(ind==0,1,'last'); +else + sync = head; +end + +fclose(fid); + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/HT3_ScanRead.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/HT3_ScanRead.m new file mode 100644 index 0000000..54e23fa --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/HT3_ScanRead.m @@ -0,0 +1,265 @@ +function [head, im_tcspc, im_chan, im_line, im_col] = HT3_ScanRead(name, plt) + +if (nargin>1)&&~isempty(plt) + plt = 1; +else + plt = 0; +end; + +if strcmp(name(end-2:end),'ht3') + + head = HT3_Read(name); + + if ~isempty(head) + + nx = head.ImgHdr.PixX; + ny = head.ImgHdr.PixY; + dt = 1e-9*nx*head.ImgHdr.PixelTime*head.SyncRate; + + anzch = 32; + Resolution = max([head.Resolution]); + chDiv = Resolution/head.Resolution; + Ngate = ceil(1e9/head.SyncRate./Resolution)+1; + + y = []; + tmpx = []; + chan = []; + markers = []; + + im_tcspc = []; + im_chan = []; + im_line = []; + im_col = []; + Turns = []; + + cnt = 0; + tend = 0; + line = 1; + + h = waitbar(0,'Please wait ...'); + + fprintf('\n\n'); + + if head.ImgHdr.Pattern == 0 + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = HT3_Read(name, [cnt+1 5e6 head.length]); + + while (num>0) + + cnt = cnt + num; + if ~isempty(y) + tmpy = tmpy+tend; + end; + + ind = (tmpmarkers>0)|((tmpchan + tmpx = [tmpx; floor(tmptcspc(ind)./chDiv)+1;]; %#ok + chan = [chan; tmpchan(ind)+1]; %#ok + markers = [markers; tmpmarkers(ind)]; %#ok + + Turns = [Turns; y(markers==1 & chan==5)]; %#ok + ind = (markers~=0); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + markers(ind) = []; + + tend = y(end)+loc; + + if numel(Turns)>1 + for j=1:numel(Turns)-1 + + dT = (Turns(2)-Turns(1)); + t1 = Turns(1)+head.ImgHdr.TStartTo*dT; + t2 = Turns(1)+head.ImgHdr.TStopTo*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + + line = line +1; + waitbar(line/ny); + drawnow + + Turns(1) = []; + + end + end + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = HT3_Read(name, [cnt+1 5e6 head.length]); + + end; + + t1 = Turns(end)+head.ImgHdr.TStartTo*dT; + t2 = Turns(end)+head.ImgHdr.TStopTo*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; + + line = line +1; + waitbar(line/ny); + drawnow + + else % bidirectional scan + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = HT3_Read(name, [cnt+1 5e6 head.length]); + + while (num>0) + + cnt = cnt + num; + if ~isempty(y) + tmpy = tmpy+tend; + end; + + ind = (tmpmarkers>0)|((tmpchan + tmpx = [tmpx; floor(tmptcspc(ind)./chDiv)+1;]; %#ok + chan = [chan; tmpchan(ind)+1]; %#ok + markers = [markers; tmpmarkers(ind)]; %#ok + + Turns = [Turns; y(markers==1 & chan==2)]; %#ok + + ind = (markers~=0); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + markers(ind) = []; + + tend = y(end)+loc; + + if numel(Turns)>2 + for j=1:2:2*floor(numel(Turns)/2-1) + + dT = (Turns(2)-Turns(1)); + t1 = Turns(1)+head.ImgHdr.TStartTo*dT; + t2 = Turns(1)+head.ImgHdr.TStopTo*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + + line = line +1; + + t1 = Turns(1)+head.ImgHdr.TStartFro*dT; + t2 = Turns(1)+head.ImgHdr.TStopFro*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(nx - floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + + line = line +1; + waitbar(line/ny); + drawnow + + Turns(1:2) = []; + end + end + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = HT3_Read(name, [cnt+1 5e6 head.length]); + + end; + + if ~isempty(Turns) + t1 = Turns(end-1)+head.ImgHdr.TStartTo*dT; + t2 = Turns(end-1)+head.ImgHdr.TStopTo*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; + + line = line +1; + + t1 = Turns(end-1)+head.ImgHdr.TStartFro*dT; + t2 = Turns(end-1)+head.ImgHdr.TStopFro*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(nx - floor(nx.*(y(ind)-t1)./(t2-t1)))]; + + line = line +1; + waitbar(line/ny); + drawnow + end + end; + + close(h); + + end +end + + +if ~isempty(head)&&(plt==1) + + tag = zeros(nx,ny); + for y = 1:ny + ind = (im_line == y); + tmp1 = im_col(ind); + for x = 1:nx + tag(y,x) = sum(tmp1 == x); + end + end + + x = head.ImgHdr.X0+(1:nx)*head.ImgHdr.PixelSize; + y = head.ImgHdr.Y0+(1:ny)*head.ImgHdr.PixelSize; + imagesc(x,y,tag); + set(gca,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse'); + xlabel('x / µm'); + ylabel('y / µm'); +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/IRF_Fun.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/IRF_Fun.m new file mode 100644 index 0000000..e828a0a --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/IRF_Fun.m @@ -0,0 +1,43 @@ +function [z] = IRF_Fun(p, t, pic) + +% Computes the following model IRF +% +% IRF(t_0, w, a, dt, T1, T2, t) = +% 1/Q [ exp(- t'^2/(2 w^2) + +% a H(t') exp(- t'/T1) + +% b (1-H(t')) exp( t'/T2)) ] +% +% t' = t - t_0 + +t = t(:); +p = p'; + +t_0 = p(1); +w1 = p(2); +T1 = p(3); +T2 = p(4); +a = p(5); +b = p(6); + +t1 = t-t_0; + +H = ones(size(t)); +H(t<(t_0)) = 0; + +ind = [false(size(t1)) H==0 H==1]; + +IRF = [exp(- t1.^2/(2*w1)) exp(-t1./T1) exp(t1./T2)]; +IRF(ind) = 0; +IRF = IRF./(ones(size(t1))*sum(IRF,1)); +IRF = (ones(size(t1))*[1 a b]).*IRF; + +z = sum(IRF,2)./sum(sum(IRF)); + +if nargin>2 && ~isempty(pic) + if pic==1 + plot(t, z, 'r'); drawnow + else + semilogy(t, z); drawnow + end +end + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/IRF_Read.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/IRF_Read.m new file mode 100644 index 0000000..32bda2c --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/IRF_Read.m @@ -0,0 +1,19 @@ +function [tcspc, timegate] = IRF_Read(name, num_PIE) + +if (nargin<2)||isempty(num_PIE) + num_PIE = 1; +end; + +N1 = [name(1:end-4) '_DATA.mat']; + +tmp = dir(N1); + +if (numel(tmp)==0) + [head, tag, tcspc] = MT_ScanRead(name, num_PIE); + timegate = head.timegate; +else + load(N1,'KRF','head'); + tcspc = KRF; + timegate = head.timegate; +end + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/KLF.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/KLF.m new file mode 100644 index 0000000..4fcc4be --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/KLF.m @@ -0,0 +1,38 @@ +function [x] = KLF(pattern_data,image_data) + +% Y : (n x m) matrix containing image data with 'n' pixels and 'm' bins +% A : (m x k) matrix containing component data with 'm' bins for 'k' components +% x : (n x k) matrik containing the amplitudes of the components for each pixel + +A = pattern_data; % Pattern Data +Y = image_data; % Image Data with bins + +x = []; +llh = []; + +nx = sqrt(size(Y,1)); +ny = nx; + + + +[Num_workers, ~] = getWorkersAvailable(); +index_split = floor(linspace(0,nx*ny,Num_workers+1))'; +amplitude_out = []; + + +parfor labindex = 1:Num_workers + + I = Y; % temporary variables + split_index = index_split + [x_out,~,~,~,~] = Convergence(I(index_split(labindex)+1:split_index(labindex+1),:),A) + amplitude_out = [amplitude_out;x_out]; +end + +x = amplitude_out; + +delete(gcp('nocreate')); +msgbox('Linear Unmixing Done','sFLIM Results','warn'); + +end + + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/LMFsolve.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/LMFsolve.m new file mode 100644 index 0000000..203ca55 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/LMFsolve.m @@ -0,0 +1,293 @@ +function [xf, S, cnt] = LMFsolve(varargin) +% LMFSOLVE Solve a Set of Nonlinear Equations in Least-Squares Sense. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% A solution is obtained by a shortened Fletcher version of the +% Levenberg-Maquardt algoritm for minimization of a sum of squares +% of equation residuals. +% +% [Xf, Ssq, CNT] = LMFsolve(FUN,Xo,Options) +% FUN is a function handle or a function M-file name that evaluates +% m-vector of equation residuals, +% Xo is n-vector of initial guesses of solution, +% Options is an optional set of Name/Value pairs of control parameters +% of the algorithm. It may be also preset by calling: +% Options = LMFsolve('default'), or by a set of Name/Value pairs: +% Options = LMFsolve('Name',Value, ... ), or updating the Options +% set by calling +% Options = LMFsolve(Options,'Name',Value, ...). +% +% Name Values {default} Description +% 'Display' integer Display iteration information +% {0} no display +% k display initial and every k-th iteration; +% 'FunTol' {1e-7} norm(FUN(x),1) stopping tolerance; +% 'XTol' {1e-7} norm(x-xold,1) stopping tolerance; +% 'MaxIter' {100} Maximum number of iterations; +% 'ScaleD' Scale control: +% value D = eye(m)*value; +% vector D = diag(vector); +% {[]} D(k,k) = JJ(k,k) for JJ(k,k)>0, or +% = 1 otherwise, +% where JJ = J.'*J +% Not defined fields of the Options structure are filled by default values. +% +% Output Arguments: +% Xf final solution approximation +% Ssq sum of squares of residuals +% Cnt >0 count of iterations +% -MaxIter, did not converge in MaxIter iterations + +% Example: Rosenbrock valey inside circle with unit diameter +% R = @(x) sqrt(x'*x)-.5; % A distance from the radius r=0.5 +% ros= @(x) [ 10*(x(2)-x(1)^2); 1-x(1); (R(x)>0)*R(x)*1000]; +% [x,ssq,cnt]=LMFsolve(ros,[-1.2,1],'Display',1,'MaxIter',50) +% returns x = [0.4556; 0.2059], ssq = 0.2966, cnt = 18. +% +% Note: Users with old MATLAB versions (<7), which have no anonymous +% functions implemented, should call LMFsolve with named function for +% residuals. For above example it is +% [x,ssq,cnt]=LMFsolve('rosen',[-1.2,1]); +% where the function rosen.m is of the form +% function r = rosen(x) +%% Rosenbrock valey with a constraint +% R = sqrt(x(1)^2+x(2)^2)-.5; +%% Residuals: +% r = [ 10*(x(2)-x(1)^2) % first part +% 1-x(1) % second part +% (R>0)*R*1000. % penalty +% ]; + +% Reference: +% Fletcher, R., (1971): A Modified Marquardt Subroutine for Nonlinear Least +% Squares. Rpt. AERE-R 6799, Harwell + +% Miroslav Balda, +% balda AT cdm DOT cas DOT cz +% 2007-07-02 v 1.0 +% 2008-12-22 v 1.1 * Changed name of the function in LMFsolv +% * Removed part with wrong code for use of analytical +% form for assembling of Jacobian matrix +% 2009-01-08 v 1.2 * Changed subfunction printit.m for better one, and +% modified its calling from inside LMFsolve. +% * Repaired a bug, which caused an inclination to +% istability, in charge of slower convergence. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% OPTIONS + %%%%%%% +% Default Options +if nargin==1 && strcmpi('default',varargin(1)) + xf.Display = 0; % no print of iterations + xf.MaxIter = 100; % maximum number of iterations allowed + xf.ScaleD = []; % automatic scaling by D = diag(diag(J'*J)) + xf.FunTol = 1e-7; % tolerace for final function value + xf.XTol = 1e-4; % tolerance on difference of x-solutions + return + +% Updating Options +elseif isstruct(varargin{1}) % Options=LMFsolve(Options,'Name','Value',...) + if ~isfield(varargin{1},'Display') + error('Options Structure not correct for LMFsolve.') + end + xf=varargin{1}; % Options + for i=2:2:nargin-1 + name=varargin{i}; % Option to be updated + if ~ischar(name) + error('Parameter Names Must be Strings.') + end + name=lower(name(isletter(name))); + value=varargin{i+1}; % value of the option + if strncmp(name,'d',1), xf.Display = value; + elseif strncmp(name,'f',1), xf.FunTol = value(1); + elseif strncmp(name,'x',1), xf.XTol = value(1); + elseif strncmp(name,'m',1), xf.MaxIter = value(1); + elseif strncmp(name,'s',1), xf.ScaleD = value; + else disp(['Unknown Parameter Name --> ' name]) + end + end + return + +% Pairs of Options +elseif ischar(varargin{1}) % check for Options=LMFSOLVE('Name',Value,...) + Pnames=char('display','funtol','xtol','maxiter','scaled'); + if strncmpi(varargin{1},Pnames,length(varargin{1})) + xf=LMFsolve('default'); % get default values + xf=LMFsolve(xf,varargin{:}); + return + end +end + +% LMFSOLVE(FUN,Xo,Options) + %%%%%%%%%%%%%%%%%%%%%%%% + +FUN=varargin{1}; % function handle +if ~(isvarname(FUN) || isa(FUN,'function_handle')) + error('FUN Must be a Function Handle or M-file Name.') +end + +xc=varargin{2}; % Xo + +if nargin>2 % OPTIONS + if isstruct(varargin{3}) + options=varargin{3}; + else + if ~exist('options','var') + options = LMFsolve('default'); + end + for i=3:2:size(varargin,2)-1 + options=LMFsolve(options, varargin{i},varargin{i+1}); + end + end +else + if ~exist('options','var') + options = LMFsolve('default'); + end +end + +x = xc(:); +lx = length(x); + +r = feval(FUN,x); % Residuals at starting point +%~~~~~~~~~~~~~~~~~ +S = r'*r; +epsx = options.XTol(:); +epsf = options.FunTol(:); +if length(epsx)1 + D = diag(sqrt(abs(D(1:lx)))); % vector of individual scaling + else + D = sqrt(abs(D))*eye(lx); % scalar of unique scaling + end +end + +Rlo = 0.25; +Rhi = 0.75; +l=1; lc=.75; is=0; +cnt = 0; +ipr = options.Display; +printit(ipr,-1); % Table header +d = options.XTol; % vector for the first cycle +maxit = options.MaxIter; % maximum permitted number of iterations + +while cnt= epsx) && ... %%%%%%%%%%%%%%%%%%%% + any(abs(r) >= epsf) + d = (A+l*D)\v; % negative solution increment + xd = x-d; + rd = feval(FUN,xd); +% ~~~~~~~~~~~~~~~~~~~ + nfJ = nfJ+1; + Sd = rd.'*rd; + dS = d.'*(2*v-A*d); % predicted reduction + + R = (S-Sd)/dS; + if R>Rhi % halve lambda if R too high + l = l/2; + if l10 + nu = 10; + end + if l==0 + lc = 1/max(abs(diag(inv(A)))); + l = lc; + nu = nu/2; + end + l = nu*l; + end + + cnt = cnt+1; + if ipr~=0 && (rem(cnt,ipr)==0 || cnt==1) % print iteration? + printit(ipr,cnt,nfJ,S,x,d,l,lc) + end + + if Sd 0 print every (ipr)th iteration +% cnt = -1 print out the header +% 0 print out second row of results +% >0 print out first row of results +if ipr~=0 + if cnt<0 % table header + disp('') + disp(char('*'*ones(1,75))) + fprintf(' itr nfJ SUM(r^2) x dx'); + if ipr>0 + fprintf(' l lc'); + end + fprintf('\n'); + disp(char('*'*ones(1,75))) + disp('') + else % iteration output + if rem(cnt,ipr)==0 + f='%12.4e '; + if ipr>0 + fprintf(['%4.0f %4.0f ' f f f f f '\n'],... + cnt,res,SS, x(1),dx(1),l,lc); + else + fprintf(['%4.0f %4.0f ' f f f '\n'],... + cnt,res,SS, x(1),dx(1)); + end + for k=2:length(x) + fprintf([blanks(23) f f '\n'],x(k),dx(k)); + end + end + end +end diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/List.mat b/Spectral-FLIM GUI/Spectral-FLIM GUI/List.mat new file mode 100644 index 0000000..63404de Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/List.mat differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/MT_ScanRead.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/MT_ScanRead.m new file mode 100644 index 0000000..71890b4 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/MT_ScanRead.m @@ -0,0 +1,229 @@ +function [head, tag, tcspc, tcspc_x, tcspc_y, DC, AP] = MT_ScanRead(name, num_PIE, bg, timegate) + +if (nargin<4)||isempty(timegate) + timegate = []; +end + +if (nargin<3)||isempty(bg) + BG_AP = 0; +else + BG_AP = bg; +end + +if (nargin<2)||isempty(num_PIE) + num_PIE = 1; +end + +fname = [name(1:end-4) '_FLIM.dat']; + +if strcmp(name(end-2:end),'ht3') + + [head, im_tcspc, im_chan, im_line, im_col] = HT3_ScanRead(name); + +elseif strcmp(name(end-2:end),'pt3') + + [head, im_tcspc, im_chan, im_line, im_col] = PT3_ScanRead(name); + head.ImgHdr.PixX = head.ImgHdr.ScanWidthX; + head.ImgHdr.PixY = head.ImgHdr.ScanWidthY; + +elseif strcmp(name(end-2:end),'ptu') + + [head, im_tcspc, im_chan, im_line, im_col] = PTU_ScanRead(name); + head.ImgHdr.PixX = head.ImgHdr_PixX; + head.ImgHdr.PixY = head.ImgHdr_PixY; + head.ImgHdr.X0 = head.ImgHdr_X0; + head.ImgHdr.Y0 = head.ImgHdr_Y0; + head.ImgHdr.PixelSize = head.ImgHdr_PixResol; + head.ImgHdr.PixelTime = head.ImgHdr_PixelTime; + head.Resolution = 1e9*head.MeasDesc_Resolution; + head.SyncRate = 1./head.MeasDesc_GlobalResolution; +end + + +if ~isempty(head) + + nx = head.ImgHdr.PixX; + ny = head.ImgHdr.PixY; + + maxch = max(im_chan); + + maxres = max([head.Resolution]); + Resolution = max([maxres 0.032]); + chDiv = Resolution/maxres; + + im_tcspc = ceil(im_tcspc./chDiv); + Ngate = double(max(im_tcspc)); + + % to avoid late arriving markers in hydraharp + %Ngate = double(1563); + + tcspc = zeros(maxch, Ngate); + tcspc_x = zeros(nx, maxch, Ngate); + tcspc_y = zeros(ny, maxch, Ngate); + + for ch = 1:maxch + tcspc(ch,:) = mHist(double(im_tcspc(im_chan == ch)),1:Ngate); + end + + for y = 1:ny + ind = (im_line == y); + tmp1 = im_tcspc(ind); + tmp2 = im_chan(ind); + for ch = 1:maxch + tcspc_y(y,ch,:) = mHist(double(tmp1(tmp2 == ch)),1:Ngate); + end + end + + for x = 1:nx + ind = (im_col == x); + tmp1 = im_tcspc(ind); + tmp2 = im_chan(ind); + for ch = 1:maxch + tcspc_x(x,ch,:) = mHist(double(tmp1(tmp2 == ch)),1:Ngate); + end + end + + nch = 1:maxch; + chind = sum(tcspc,2)<=100; + nch(chind) = []; + tcspc(chind,:) = []; + tcspc_x(:,chind,:) = []; + tcspc_y(:,chind,:) = []; + + bin = 1:size(tcspc,2); + % ind = sum(tcspc,1)<=10; + % bin(ind) = []; + % tcspc(:,ind) = []; + % tcspc_x(:,:,ind) = []; + % tcspc_y(:,:,ind) = []; + + tau = ((1:size(tcspc,2))-0.5).*Resolution; + nbin = numel(tau); + anzch = numel(nch); + + % Estimate background in measurement + + c_t = [tcspc_x./ny; tcspc_y./nx]; + c_ts = sum(c_t,3); + nc = size(c_ts,1); + ind = (1:floor(nc/100):nc); + AP = zeros(anzch,1); + DC = zeros(anzch,1); + + for a = 1:anzch + [tmp, ord] = sort(c_ts(:,a),'descend'); + cnt = tmp(ind); + tmp = squeeze(c_t(ord(ind),a,:)); + tmp = sort(tmp,2,'ascend'); + b_g = mean(tmp(:,2:floor(0.25.*nbin)),2); + + if BG_AP == 0 + V = [ones(size(cnt)) cnt]; + p = lsqnonneg(V, b_g); + DC(a) = p(1); + AP(a) = p(2); + else + AP(a) = BG_AP; + DC(a) = mean(b_g-cnt.*BG_AP); + end + end + DC(DC<0) = 0; + AP(AP<0) = 0; + + % Determine time-gates for PIE + + if isempty(timegate) + [timegate, Ngate] = DetectTimeGates(tcspc', num_PIE, Resolution); + else + Ngate = 1 + timegate(1,2)+timegate(1,4)-timegate(1,1); + end + + timegate(timegate>0) = bin(timegate(timegate>0)); + + head.timegate = timegate; + + tcspc = zeros(anzch, Ngate, num_PIE); + tcspc_x = zeros(nx, anzch, Ngate, num_PIE); + tcspc_y = zeros(ny, anzch, Ngate, num_PIE); + tag = zeros(ny, nx,anzch, num_PIE); + +% M_avail = memory; +% +% if M_avail.MaxPossibleArrayBytes > nx*ny*anzch*Ngate*num_PIE*8 +% +% tim = zeros(ny, nx, anzch, Ngate, num_PIE); +% +% for a = 1:ny +% ind = (im_line == a); +% tmp1 = im_tcspc(ind); +% tmp2 = im_chan(ind); +% tmp3 = im_col(ind); +% +% for x = 1:nx +% ind = (tmp3 == x); +% tmp4 = double(tmp1(ind)); +% tmp5 = tmp2(ind); +% +% n = 0; +% for pulse = 1:num_PIE +% for ch = 1:anzch +% n = n+1; +% if (timegate(n,3)==0) +% tim(a,x,ch,:,pulse) = mHist(tmp4(tmp5==nch(ch)),timegate(n,1):timegate(n,2)); +% else +% tim(a,x,ch,:,pulse) = [mHist(tmp4(tmp5==nch(ch)),timegate(n,1):timegate(n,2)); mHist(tmp4(tmp5==nch(ch)),timegate(n,3):timegate(n,4))]; +% end +% end +% end +% end +% end +% +% tcspc = shiftdim(sum(sum(tim,1),2),2); +% tcspc_y = shiftdim(sum(tim,1),1); +% tcspc_x = permute(sum(tim,2),[1 3 4 5 2]); +% tag = permute(sum(tim,4),[1 2 3 5 4]); +% +% save([fname(1:end-4) '.mat'],'tim','-v7.3'); +% +% else + + fid = fopen(fname,'w'); + + for a = 1:ny + + tmp = zeros(nx, anzch, Ngate, num_PIE); + + ind = (im_line == a); + tmp1 = im_tcspc(ind); + tmp2 = im_chan(ind); + tmp3 = im_col(ind); + + for x = 1:nx + ind = (tmp3 == x); + tmp4 = double(tmp1(ind)); + tmp5 = tmp2(ind); + + n = 0; + for pulse = 1:num_PIE + for ch = 1:anzch + n = n+1; + if (timegate(n,3)==0) + tmp(x,ch,:,pulse) = mHist(tmp4(tmp5==nch(ch)),timegate(n,1):timegate(n,2)); + else + tmp(x,ch,:,pulse) = [mHist(tmp4(tmp5==nch(ch)),timegate(n,1):timegate(n,2)); mHist(tmp4(tmp5==nch(ch)),timegate(n,3):timegate(n,4))]; + end + end + end + end + + tcspc = tcspc + shiftdim(sum(tmp,1),1); + tcspc_x = tcspc_x + tmp; + tcspc_y(a,:,:,:) = shiftdim(sum(tmp,1),1); + tag(a,:,:,:) = permute(sum(tmp,3),[1 2 4 3]); + + fwrite(fid, uint16(tmp), 'uint16' ); + end + + fclose(fid); + clear tmp im_chan im_col im_line im_tcspc c_t c_ts; +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/MakeComposite.fig b/Spectral-FLIM GUI/Spectral-FLIM GUI/MakeComposite.fig new file mode 100644 index 0000000..8591e2e Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/MakeComposite.fig differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/MakeComposite.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/MakeComposite.m new file mode 100644 index 0000000..b10b87b --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/MakeComposite.m @@ -0,0 +1,427 @@ +function varargout = MakeComposite(varargin) +% MAKECOMPOSITE M-file for MakeComposite.fig +% MAKECOMPOSITE, by itself, creates a new MAKECOMPOSITE or raises the existing +% singleton*. +% +% H = MAKECOMPOSITE returns the handle to a new MAKECOMPOSITE or the handle to +% the existing singleton*. +% +% MAKECOMPOSITE('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in MAKECOMPOSITE.M with the given input arguments. +% +% MAKECOMPOSITE('Property','Value',...) creates a new MAKECOMPOSITE or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before MakeComposite_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to MakeComposite_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 MakeComposite + +% Last Modified by GUIDE v2.5 10-Oct-2013 11:26:13 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @MakeComposite_OpeningFcn, ... + 'gui_OutputFcn', @MakeComposite_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 MakeComposite is made visible. +function MakeComposite_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 MakeComposite (see VARARGIN) + +% Choose default command line output for MakeComposite + +data = []; +list = []; +nargin = length(varargin); + +if nargin < 2 + errordlg('No data given','Error') +else + ind = 1; + while ind < nargin + if strcmpi(varargin{ind},'data') + data = cell2mat(varargin(ind+1)); + end + if strcmpi(varargin{ind},'list') + list = varargin(ind+1); + list = list{:}; + end + ind = ind + 2; + end +end + + +if ~isempty(data) + + load Get_Params; + + handles.nx = size(data,1); + handles.ny = size(data,2); + handles.num_pat = size(data,3); + handles.Sat = zeros(handles.num_pat,1); + handles.selected = 1; + + data = (reshape(data, [handles.nx*handles.ny handles.num_pat])); + + handles.data0 = data; + + tmp = sort(reshape(data,[numel(data) 1])); + dmax = round(tmp(floor(0.9995.*numel(tmp)))); + + handles.data = data./(ones(size(data,1),handles.num_pat).*dmax); + handles.data(handles.data>1) = 1; + + s = {}; + for ind = 1:handles.num_pat + handles.ROIcolor(ind,:) = ROIcolor(mod(ind,size(ROIcolor,1)),:); %#ok + handles.spectrum(ind,:,:) = (0:0.002:1)'*handles.ROIcolor(ind,:); + s(ind) = {sprintf('data %d',ind)}; + end + if ~isempty(list) + ind = min([handles.num_pat numel(list)]); % ind = min([handles.num_pat numel(list{:})]); + s(1:ind) = list(1:ind); + end + set(handles.ROI_list,'Value',1); + set(handles.ROI_list,'String',s); + + guidata(hObject, handles); + update_plot(handles); +end + +handles.SelectedColor = [1,0,0]; % Currently selected color in the palette +handles.PalettePanel = uibuttongroup('Parent',handles.Color_panel, ... + 'Units', 'Pixels',... + 'Position',[0 0 1 1],... + 'Title',{''},... + 'BorderType', 'none',... + 'SelectionChangeFcn', @(hObject, eventdata)MakeComposite('PalettePanelSelectionChanged',hObject, eventdata, guidata(hObject))); + +handles.SelectedColorText = uicontrol('Parent',handles.Color_panel,... + 'Units', 'Pixels',... + 'Style', 'text'); +handles.MoreColorButton = uicontrol('Parent',handles.Color_panel,... + 'Units', 'Pixels',... + 'String', 'More Colors ...',... + 'Callback',@(hObject, eventdata)MakeComposite('MoreColorButton_Callback',hObject, eventdata, guidata(hObject))); +guidata(hObject, handles); + +% Dynamically create the color cells and palette tools and layout component +layoutComponent(handles); + +% initalized the displayed color information +localUpdateColor(hObject, handles); + +% Return user defined output if it is requested +% mOutputArgs{1} =@getImage; % (hObject)MakeComposite('getImage', guidata(hObject)); +% +% if nargout>0 +% [varargout{1:nargout}] = mOutputArgs{:}; +% end + +handles.output = []; + +% Update handles structure +guidata(hObject, handles); + +% UIWAIT makes MakeComposite wait for user response (see UIRESUME) +uiwait(handles.figure1); + + +% --- Outputs from this function are returned to the command line. +function varargout = MakeComposite_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} = update_plot(handles); +delete(hObject); + + +% --- Executes on button press in OK_button. +function OK_button_Callback(hObject, eventdata, handles) +% hObject handle to OK_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +uiresume(handles.figure1); + + +% --- Executes on selection change in ROI_list. +function ROI_list_Callback(hObject, eventdata, handles) +% hObject handle to ROI_list (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hints: contents = get(hObject,'String') returns ROI_list contents as cell array +% contents{get(hObject,'Value')} returns selected item from ROI_list + +tmp = get(hObject, 'Value'); +if numel(tmp)>0 + handles.selected = tmp(1); + set(hObject, 'Value', tmp(1)); +else + handles.selected = 1; + set(hObject, 'Value', 1); +end +set(handles.slider1,'Value',handles.Sat(handles.selected)); +handles.SelectedColor = handles.ROIcolor(handles.selected,:) ; %#ok +set(handles.SelectedColorText, 'BackgroundColor', handles.SelectedColor); +set(get(handles.PalettePanel,'SelectedObject'),'Value',0); +guidata(hObject, handles); + + +% --- Executes during object creation, after setting all properties. +function ROI_list_CreateFcn(hObject, eventdata, handles) +% hObject handle to ROI_list (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: popupmenu 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 slider movement. +function slider1_Callback(hObject, eventdata, handles) +% hObject handle to slider1 (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,'Value') returns position of slider +% get(hObject,'Min') and get(hObject,'Max') to determine range of slider +tmp = get(hObject, 'Value'); +handles.Sat(handles.selected) = tmp; +guidata(hObject, handles); +update_plot(handles); + + +% --- Executes during object creation, after setting all properties. +function slider1_CreateFcn(hObject, eventdata, handles) +% hObject handle to slider1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: slider controls usually have a light gray background. +if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor',[.9 .9 .9]); +end +set(hObject,'Min',-4,'Max',4,'Value',0); + +% --- Executes on slider movement. +function slider3_Callback(hObject, eventdata, handles) +% hObject handle to slider3 (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,'Value') returns position of slider +% get(hObject,'Min') and get(hObject,'Max') to determine range of slider + +sv = 1-get(hObject, 'Value')/100; +data = handles.data0; + +tmp = sort(reshape(data,[numel(data) 1])); +dmax = round(tmp(floor(sv.*numel(tmp)))); + +handles.data = data./(ones(size(data,1),handles.num_pat).*dmax); +handles.data(handles.data>1) = 1; +guidata(hObject, handles); +update_plot(handles); + +% --- Executes during object creation, after setting all properties. +function slider3_CreateFcn(hObject, eventdata, handles) +% hObject handle to slider3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: slider controls usually have a light gray background. +if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor',[.9 .9 .9]); +end +set(hObject,'Min',0,'Max',0.5,'Value',0.05); + + +function im = update_plot(handles) + +tmp = floor(500.*exp(repmat(handles.Sat',[handles.nx*handles.ny 1])).*handles.data)+1; +tmp(tmp>501) = 501; +tmp(tmp<1) = 1; + +ind = 1; +im = handles.spectrum(ind, tmp(:,ind), :); +while ind < handles.num_pat + ind = ind + 1; + im = im + handles.spectrum(ind, tmp(:,ind), :); +end + +im(im>1)=1; + +axes(handles.axes1) +hold on; +cla + +image(1:handles.nx,1:handles.ny,reshape(im,[handles.nx handles.ny 3])) + +set(handles.axes1,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'color', [0 0 0]); + +xlabel('x','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('y','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +hold off + + +% --- Executes on button press in Reset_button. +function Reset_button_Callback(hObject, eventdata, handles) +% hObject handle to Reset_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(handles.slider1,'Value',0); +handles.Sat = zeros(handles.num_pat,1); +guidata(hObject, handles); +update_plot(handles); + + +function MoreColorButton_Callback(hObject, eventdata, handles) +% Callback called when the more color button is pressed. + +color = handles.SelectedColor; +if isnan(color) + color =[0 0 0]; +end +color = uisetcolor(color); +if ~isequal(color, handles.SelectedColor) + handles.SelectedColor =color; + localUpdateColor(hObject, handles); +end + + +function PalettePanelSelectionChanged(hObject, eventdata, handles) +% Callback called when the selected color is changed in the colorPlatte + +selected = get(hObject,'SelectedObject'); +def = get(selected, 'UserData'); +if ~isempty(def) && isfield(def,'Callback') + def.Callback(selected, eventdata, handles); +end + + +function colorCell_Callback(hObject, eventdata, handles) +% Callback called when any color cell button is pressed + +handles.SelectedColor = get(hObject, 'BackgroundColor'); +localUpdateColor(hObject, handles) + + +function localUpdateColor(hObject, handles) +% function that updates the preview of the selected color +set(handles.SelectedColorText, 'BackgroundColor', handles.SelectedColor); +handles.ROIcolor(handles.selected,:) = handles.SelectedColor; %#ok +handles.spectrum(handles.selected,:,:) = (0:0.002:1)'*handles.SelectedColor; +guidata(hObject, handles); +update_plot(handles); + + +function layoutComponent(handles) +% helper function that dynamically creats all the tools and color cells +% in the palette. It also positions all other UI objects properly. +% get the definision of the layout + +mColorEntries= {struct('Color','red', 'Callback',@colorCell_Callback),... + struct('Color','green', 'Callback',@colorCell_Callback),... + struct('Color','blue', 'Callback',@colorCell_Callback),... + struct('Color','yellow', 'Callback',@colorCell_Callback),... + struct('Color','magenta', 'Callback',@colorCell_Callback),... + struct('Color','cyan', 'Callback',@colorCell_Callback),... + struct('Color','white', 'Callback',@colorCell_Callback),... + struct('Color',[0.5,0.5,0.5], 'Callback',@colorCell_Callback)}; + +mLayout.hgap = 5; +mLayout.vgap = 5; +mLayout.cellSize = 21; +mLayout.cellPerRow = 4; +mLayout.colorSampleSize = 21; +mLayout.moreColorButtonHeight = 30; + +% calculate the preferred width and height +width = max([2*mLayout.colorSampleSize,(mLayout.cellSize+mLayout.hgap)*mLayout.cellPerRow]); +mLayout.cellRowNumber = ceil(length(mColorEntries)/ceil(width/(mLayout.cellSize+mLayout.vgap))); +height = mLayout.cellRowNumber*(mLayout.cellSize+mLayout.vgap) ... + + mLayout.colorSampleSize + mLayout.moreColorButtonHeight; +mLayout.preferredWidth = mLayout.hgap+width; +mLayout.preferredHeight = 2*mLayout.vgap+height; + +% change the size of the color palette to the desired size, place +% the components, and then change size back. +setpixelposition(handles.PalettePanel, [0, 0, mLayout.preferredWidth, mLayout.preferredHeight]); + +startY = mLayout.preferredHeight - mLayout.colorSampleSize; +startX = mLayout.hgap; + +% place color sample +setpixelposition(handles.SelectedColorText, [startX, startY, ... + mLayout.preferredWidth-2*mLayout.hgap, ... + mLayout.colorSampleSize]); +% create color cells +for i=1:mLayout.cellRowNumber + startY = startY - (mLayout.cellSize+mLayout.hgap); + for j=1:mLayout.cellPerRow + if ((i-1)*mLayout.cellPerRow + j)>length(mColorEntries) + break; + end + color = mColorEntries{(i-1)*mLayout.cellPerRow + j}; + tooltip = mat2str(color.Color); + if isfield(color,'Name') + tooltip = color.Name; + end + control = uicontrol('Style','ToggleButton',... + 'TooltipString', tooltip,... + 'BackgroundColor',color.Color,... + 'Parent',handles.PalettePanel, ... + 'Units','Pixels',... + 'UserData',color,... + 'Position',[startX+(j-1)*(mLayout.cellSize+mLayout.hgap),... + startY, ... + mLayout.cellSize, mLayout.cellSize]); + end +end + +% place more color button +startY = startY - mLayout.moreColorButtonHeight - mLayout.vgap; +setpixelposition(handles.MoreColorButton,[startX, startY, ... + mLayout.preferredWidth - 2*mLayout.hgap,mLayout.moreColorButtonHeight]); + +% restore palette to the full size +set(handles.PalettePanel, 'units', 'normalized', 'Position', [0 0 1 1]); diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/MomentAnalysis.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/MomentAnalysis.m new file mode 100644 index 0000000..c648a2a --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/MomentAnalysis.m @@ -0,0 +1,84 @@ +function MomentAnalysis(file) + +tmp = strfind(file,'\'); +pathname = file(1:tmp(end)); +filename = file(tmp(end)+1:end); + +load Get_Params; + +[head, tag, tcspc, IRF, timname] = load_data([pathname filename]); + +nx = floor(head.ImgHdr.PixX); +ny = floor(head.ImgHdr.PixY); +tx = floor(nx/binning); +ty = floor(ny/binning); + +nch = size(tcspc,1); +nbin = size(tcspc,2); +num_PIE = size(tcspc,3); +tau = head.tau; + +load([pathname timname], 'stim'); + +if binning > 1 + tmp = stim(1:binning*tx,:,:,:,:); + tmp = reshape(tmp, binning, tx, ny, nch, nbin, num_PIE); + tmp = shiftdim(sum(tmp,1),1); + tmp = tmp(:,1:binning*ty,:,:); + tmp = reshape(tmp, tx, binning, ty, nch, nbin, num_PIE); + stim = permute(sum(tmp,2), [1 3 4 5 6 2]); +end + +tav = zeros(ty, tx, nch, num_PIE, 2); + +if numel(stim)<2^26 + + T = permute(repmat(tau(:), [1 ty tx nch num_PIE]),[2 3 4 1 5]); + + H(:,:,1) = permute(sum(repmat(ones(nch,1)*tau ,[1 1 num_PIE]).*IRF,2),[1 3 2])./permute(sum(IRF,2),[1 3 2]); + H(:,:,2) = permute(sum(repmat(ones(nch,1)*tau.^2,[1 1 num_PIE]).*IRF,2),[1 3 2])./permute(sum(IRF,2),[1 3 2]); + + H = shiftdim(repmat(H,[1 1 1 ty tx]), 3); + + F(:,:,:,:,1) = permute(sum(T .*stim,4),[1 2 3 5 4])./permute(sum(stim,4),[1 2 3 5 4]); + F(:,:,:,:,2) = permute(sum(T.^2.*stim,4),[1 2 3 5 4])./permute(sum(stim,4),[1 2 3 5 4]); + + F(isnan(F)) = 0; + + tav(:,:,:,:,1) = F(:,:,:,:,1) - H(:,:,:,:,1); + tav(:,:,:,:,2) = F(:,:,:,:,2)./2 - (H(:,:,:,:,2)/2 + H(:,:,:,:,1).*tav(:,:,:,:,1)); + +else + + T = permute(repmat(tau(:), [1 tx nch]),[4 2 3 1]); + + for P = 1:num_PIE + H = zeros(nch,2); + H(:,1) = permute(sum((ones(nch,1)*tau ).*IRF(:,:,P),2),[1 3 2])./permute(sum(IRF(:,:,P),2),[1 3 2]); + H(:,2) = permute(sum((ones(nch,1)*tau.^2).*IRF(:,:,P),2),[1 3 2])./permute(sum(IRF(:,:,P),2),[1 3 2]); + + H = shiftdim(repmat(H,[1 1 tx]), 2); + if (size(H,2)==1) + H = permute(H,[2 1 3]); + end + + + for yi = 1:ty + F(:,:,1) = permute(sum(T .*stim(yi,:,:,:,P),4),[1 2 3 5 4])./permute(sum(stim(yi,:,:,:,P),4),[1 2 3 5 4]); + F(:,:,2) = permute(sum(T.^2.*stim(yi,:,:,:,P),4),[1 2 3 5 4])./permute(sum(stim(yi,:,:,:,P),4),[1 2 3 5 4]); + + F(isnan(F)) = 0; + + tav(yi,:,:,P,1) = F(:,:,1) - H(:,:,1); + tav(yi,:,:,P,2) = F(:,:,2)./2 - (H(:,:,2)/2 + H(:,:,1).*squeeze(tav(yi,:,:,P,1))); + end + end + +end + +% tav(tav<0) = 0; +tav(:,:,:,:,2) = tav(:,:,:,:,2) - tav(:,:,:,:,1).^2; +tav(tav<0) = 0; +tav(:,:,:,:,2) = sqrt(tav(:,:,:,:,2)); +clear stim; +save([pathname filename(1:end-4) '_Moments.mat'], 'tav'); \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/PT3_Read.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/PT3_Read.m new file mode 100644 index 0000000..8f3be27 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/PT3_Read.m @@ -0,0 +1,236 @@ +function [sync, tcspc, chan, num, loc, head] = PT3_Read(name, cnts) +% +% function [sync, tcspc, chan, num, head] = PT3_Read(name, cnts) +% +% This function reads single-photon data from the file 'name' +% +% If the argument parameter 'cnts' is missing, or has the value 0 it returns just the +% header of the file in the output variable 'sync'. +% +% If 'cnts' contains a number larger than 0, the routine reads 'cnts' +% records the data stream or up the end of the file. +% +% If 'cnts' contains two numbers [cnts(1) cnts(2)], the routine proceeds +% to the position cnts(1) before readinf the cnts(2) records of data. +% +% If 'cnts' contains three numbers [cnts(1) cnts(2) cnts(3)], the routine +% does not read the header, but jumps over the first cnts(3)-bytes that +% represent the length of the file-header. After that it procceds to the +% data position cnts(1) before reading the cnts(2) records of data. +% +% The output variables contain the followig data: +% sync : number of the sync events that preceeded this detection event +% tcspc : number of the tcspc-bin of the event +% chan : number of the input channel of the event (detector-number) +% num : counter of the records that were actually read +% loc : number of overcounts after last valid photon +% head : the file header +% + +if (nargin<2)||isempty(cnts) + cnts = [0 0 0]; +end; + +if numel(cnts)<2 + cnts = [0 cnts 0]; +end; + +if numel(cnts)<3 + cnts = [cnts 0]; +end; + + +if (nargin<1)||isempty(name) + fprintf(1,'\n\n You have to specify a valid file-name. Aborted.\n'); + return; +else + fid = fopen(name); + if fid<1 + fprintf(1,'\n\n Could not open <%s>. Aborted.\n', name); + return; + end +end + +% +% The following represents the readable ASCII file header portion +% + +if (nargout==7)||(cnts(3)==0) + + head = []; + + HeaderLength = fread(fid, 1, 'int32'); + + if HeaderLength > 0 + fseek(fid,0,'bof'); + end; + + tmp = deblank(char(fread(fid, 16, 'char')')); + + if strcmp(tmp, 'PicoHarp 300') + + head.Ident = tmp; + head.FormatVersion = fread(fid, 6, '*char')'; + head.CreatorName = fread(fid, 18, '*char')'; + head.CreatorVersion = fread(fid, 12, '*char')'; + head.FileTime = fread(fid, 18, '*char')'; + fread(fid, 2, 'char'); + head.Comment = fread(fid, 256, '*char')'; + + head.NCurves = fread(fid, 1, 'int32'); + head.NChannels = 4096; + head.BitsPerRecord = fread(fid, 1, 'int32'); + head.RoutingChannels = fread(fid, 1, 'int32'); + head.NumberOfBoards = fread(fid, 1, 'int32'); + head.ActiveCurve = fread(fid, 1, 'int32'); + head.MeasMode = fread(fid, 1, 'int32'); + head.SubMode = fread(fid, 1, 'int32'); + head.RangeNo = fread(fid, 1, 'int32'); + head.Offset = fread(fid, 1, 'int32'); + head.TAcq = fread(fid, 1, 'int32'); + head.StopAt = fread(fid, 1, 'int32'); + head.StopOnOvfl = fread(fid, 1, 'int32'); + head.Restart = fread(fid, 1, 'int32'); + head.LinLog = fread(fid, 1, 'int32'); + head.MinAx = fread(fid, 1, 'int32'); + head.MaxAx = fread(fid, 1, 'int32'); + head.MinAxCnt = fread(fid, 1, 'int32'); + head.MaxAxCnt = fread(fid, 1, 'int32'); + head.DispCurves = fread(fid, 16, 'int32'); + head.Params = fread(fid, 9, 'int32'); + head.RepeatMode = fread(fid, 1, 'int32'); + head.RepeatsPerCurve = fread(fid, 1, 'int32'); + head.RepeatTime = fread(fid, 1, 'int32'); + head.RepeatWaitTime = fread(fid, 1, 'int32'); + + head.ScriptName = fread(fid, 20, '*char')'; + head.anzch = 0; + for n=(1:head.NumberOfBoards) + head.BoardIdent(:,n) = fread(fid, 16, '*char')'; + head.BoardVersion(:,n) = fread(fid, 8, '*char')'; + head.BoardSerial(n) = fread(fid, 1, 'int32'); + head.SyncDiv(n) = fread(fid, 1, 'int32'); + head.CFDZeroCross0(n) = fread(fid, 1, 'int32'); + head.CFDLevel0(n) = fread(fid, 1, 'int32'); + head.CFDZeroCross1(n) = fread(fid, 1, 'int32'); + head.CFDLevel1(n) = fread(fid, 1, 'int32'); + head.Resolution(n) = fread(fid, 1, 'float'); + + head.anzch = head.anzch + 1; + + if strcmp(head.FormatVersion(1:3),'2.0') + head.RouterModel(n) = fread(fid, 1, 'int32'); + head.RouterEnabled(n) = fread(fid, 1, 'int32'); + head.RtCh1_InputType(n) = fread(fid, 1, 'int32'); + head.RtCh1_InputLevel(n) = fread(fid, 1, 'int32'); + head.RtCh1_InputEdge(n) = fread(fid, 1, 'int32'); + head.RtCh1_CFDPresent(n) = fread(fid, 1, 'int32'); + head.RtCh1_CFDLevel(n) = fread(fid, 1, 'int32'); + head.RtCh1_CFDZeroCross(n) = fread(fid, 1, 'int32'); + head.RtCh2_InputType(n) = fread(fid, 1, 'int32'); + head.RtCh2_InputLevel(n) = fread(fid, 1, 'int32'); + head.RtCh2_InputEdge(n) = fread(fid, 1, 'int32'); + head.RtCh2_CFDPresent(n) = fread(fid, 1, 'int32'); + head.RtCh2_CFDLevel(n) = fread(fid, 1, 'int32'); + head.RtCh2_CFDZeroCross(n) = fread(fid, 1, 'int32'); + head.RtCh3_InputType(n) = fread(fid, 1, 'int32'); + head.RtCh3_InputLevel(n) = fread(fid, 1, 'int32'); + head.RtCh3_InputEdge(n) = fread(fid, 1, 'int32'); + head.RtCh3_CFDPresent(n) = fread(fid, 1, 'int32'); + head.RtCh3_CFDLevel(n) = fread(fid, 1, 'int32'); + head.RtCh3_CFDZeroCross(n) = fread(fid, 1, 'int32'); + head.RtCh4_InputType(n) = fread(fid, 1, 'int32'); + head.RtCh4_InputLevel(n) = fread(fid, 1, 'int32'); + head.RtCh4_InputEdge(n) = fread(fid, 1, 'int32'); + head.RtCh4_CFDPresent(n) = fread(fid, 1, 'int32'); + head.RtCh4_CFDLevel(n) = fread(fid, 1, 'int32'); + head.RtCh4_CFDZeroCross(n) = fread(fid, 1, 'int32'); + if head.RouterEnabled(n) == 1 + head.anzch = head.anzch + 3; + else + head.anzch = head.RoutingChannels; + end + else + head.anzch = head.RoutingChannels; + head.Resolution = head.Resolution.*ones(4,1); + end + end; + + head.ExternalDev = fread(fid, 1, 'int32'); + head.Reserved1 = fread(fid, 1, 'int32'); + head.Reserved2 = fread(fid, 1, 'int32'); + head.SyncRate = fread(fid, 1, 'int32'); + head.CntRate1 = fread(fid, 1, 'int32'); + head.StopAfter = fread(fid, 1, 'int32'); + head.StopReason = fread(fid, 1, 'int32'); + head.NCounts = fread(fid, 1, 'uint32'); + + head.SpecHeaderLength = fread(fid, 1, 'int32'); + + tmp = head.SpecHeaderLength/4; + + if head.SpecHeaderLength>0 + head.ImgHdr.Dimensions = fread(fid, 1, 'int32'); + head.ImgHdr.Ident = fread(fid, 1, 'int32'); + if head.ImgHdr.Ident==1 % PI E710 Scan Controller + head.ImgHdr.ScanTimePerPix = fread(fid, 1, 'int32'); + fread(fid, 1, 'int32'); + head.ImgHdr.ScanPattern = fread(fid, 1, 'int32'); + fread(fid, 1, 'int32'); + head.ImgHdr.ScanStartX = fread(fid, 1, 'float'); + head.ImgHdr.ScanStartY = fread(fid, 1, 'float'); + head.ImgHdr.ScanWidthX = fread(fid, 1, 'int32'); + head.ImgHdr.ScanWidthY = fread(fid, 1, 'int32'); + head.ImgHdr.ScanResolution = fread(fid, 1, 'float'); + head.ImgHdr.ScanTStartTo = fread(fid, 1, 'float'); + head.ImgHdr.ScanTStopTo = fread(fid, 1, 'float'); + head.ImgHdr.ScanTStartFro = fread(fid, 1, 'float'); + head.ImgHdr.ScanTStopFro = fread(fid, 1, 'float'); + end + + if head.ImgHdr.Ident==3 % LSM + head.ImgHdr.Frame = 2^(fread(fid, 1, 'int32')-1); + head.ImgHdr.LineStart = 2^(fread(fid, 1, 'int32')-1); + head.ImgHdr.LineStop = 2^(fread(fid, 1, 'int32')-1); + head.ImgHdr.Pattern = fread(fid, 1, 'int32'); + head.ImgHdr.ScanWidthX = fread(fid, 1, 'int32'); + head.ImgHdr.ScanWidthY = fread(fid, 1, 'int32'); + for n = 9:tmp + tmp = fread(fid, 1, 'uint32'); + end + end + end + head.length = ftell(fid); + end +end + + +if cnts(2)>0 + + if cnts(3)>0 + fseek(fid, (cnts(3)), 'bof'); + end + if cnts(1)>0 + fseek(fid, 4*(cnts(1)-1), 'cof'); + end + + WRAPAROUND=65536; + + [T3Record num] = fread(fid, cnts(2), 'ubit32'); % all 32 bits: + + chan = bitand(bitshift(T3Record,-28),15); + tcspc = bitand(bitshift(T3Record,-16),4095); + sync = bitand(T3Record,65535); + + ind = (tcspc==0 & chan==15); + sync = sync + WRAPAROUND*cumsum(ind); + + sync(ind) = []; + tcspc(ind) = []; + chan(ind) = []; + loc = num - find(ind==0,1,'last'); +else + sync = head; +end + +fclose(fid); diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/PT3_ScanRead.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/PT3_ScanRead.m new file mode 100644 index 0000000..d6a3024 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/PT3_ScanRead.m @@ -0,0 +1,411 @@ +function [head, im_tcspc, im_chan, im_line, im_col] = PT3_ScanRead(name, plt) + +if (nargin>1)&&~isempty(plt) + plt = 1; +else + plt = 0; +end; + +if strcmp(name(end-2:end),'pt3') + + head = PT3_Read(name); + + if ~isempty(head) + + nx = head.ImgHdr.ScanWidthX; + ny = head.ImgHdr.ScanWidthY; + + y = []; + tmpx = []; + chan = []; + + im_tcspc = []; + im_chan = []; + im_line = []; + im_col = []; + Turns = []; + + cnt = 0; + tend = 0; + line = 1; + + h = waitbar(0,'Please wait ...'); + + fprintf('\n\n'); + + if head.ImgHdr.Ident == 1 % E710 Piezo Scanner + + if head.ImgHdr.ScanPattern == 1 % unidirectional scan + + [tmpy, tmptcspc, tmpchan, num, loc] = PT3_Read(name, [cnt+1 5e6 head.length]); + + while (num>0) + + cnt = cnt + num; + + tmpy = tmpy+tend; + + y = [y; tmpy]; %#ok + tmpx = [tmpx; tmptcspc]; %#ok + chan = [chan; tmpchan]; %#ok + Turns = [Turns; y(chan==15 & tmpx==2)]; %#ok + + ind = (chan==15); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + + tend = y(end)+loc; + + if numel(Turns)>1 + for j=1:numel(Turns)-1 + + dT = (Turns(2)-Turns(1)); + t1 = Turns(1)+head.ImgHdr.TStartTo*dT; + t2 = Turns(1)+head.ImgHdr.TStopTo*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + + line = line +1; + waitbar(line/ny); + drawnow + + Turns(1) = []; + end + + end + + [tmpy, tmptcspc, tmpchan, num, loc] = PT3_Read(name, [cnt+1 5e6 head.length]); + + end; + + t1 = Turns(end)+head.ImgHdr.TStartTo*dT; + t2 = Turns(end)+head.ImgHdr.TStopTo*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; + + line = line +1; + waitbar(line/ny); + drawnow + + else % bidirectional scan + + [tmpy, tmptcspc, tmpchan, num, loc] = PT3_Read(name, [cnt+1 5e6 head.length]); + + while (num>0) + + cnt = cnt + num; + + tmpy = tmpy+tend; + + y = [y; tmpy]; %#ok + tmpx = [tmpx; tmptcspc]; %#ok + chan = [chan; tmpchan]; %#ok + + Turns = [Turns; y(chan==15 & tmpx==2)]; %#ok + + ind = (chan==15); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + + tend = y(end)+loc; + + if numel(Turns)>2 + for j=1:2:2*floor(numel(Turns)/2-1) + + dT = (Turns(2)-Turns(1)); + t1 = Turns(1)+head.ImgHdr.TStartTo*dT; + t2 = Turns(1)+head.ImgHdr.TStopTo*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + + line = line +1; + + t1 = Turns(1)+head.ImgHdr.TStartFro*dT; + t2 = Turns(1)+head.ImgHdr.TStopFro*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(nx - floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + + line = line +1; + waitbar(line/ny); + drawnow + + Turns(1:2) = []; + end + end + + [tmpy, tmptcspc, tmpchan, num, loc] = PT3_Read(name, [cnt+1 5e6 head.length]); + + end; + + t1 = Turns(end-1)+head.ImgHdr.TStartTo*dT; + t2 = Turns(end-1)+head.ImgHdr.TStopTo*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; + + line = line +1; + + t1 = Turns(end-1)+head.ImgHdr.TStartFro*dT; + t2 = Turns(end-1)+head.ImgHdr.TStopFro*dT; + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(nx - floor(nx.*(y(ind)-t1)./(t2-t1)))]; + + line = line +1; + waitbar(line/ny); + drawnow + end + + elseif head.ImgHdr.Ident == 3 % LSM + + head.ImgHdr.X0 = 0; + head.ImgHdr.Y0 = 0; + head.ImgHdr.PixX = nx; + head.ImgHdr.PixY = ny; + head.ImgHdr.PixelSize = 1; + + LineStart = head.ImgHdr.LineStart; + LineStop = head.ImgHdr.LineStop; + Frame = head.ImgHdr.Frame; + + if Frame < 1 + Frame = -1; + end + + in_frame = false; + + if Frame < 1 + in_frame = true; + end + + [tmpy, tmptcspc, tmpchan, num, loc] = PT3_Read(name, [cnt+1 1e6 head.length]); + + while (num>0) + + t_tcspc = []; + t_chan = []; + t_line = []; + t_col = []; + + cnt = cnt + num; + + waitbar(cnt/head.NCounts); + + tmpy = tmpy+tend; + + y = [y; tmpy]; %#ok + tmpx = [tmpx; tmptcspc]; %#ok + chan = [chan; tmpchan]; %#ok + tend = y(end)+loc; + + F = y(chan==15 & bitand(tmpx,Frame)>0); + + while ~isempty(F) + + if ~in_frame + ind = (y<=F(1)); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + line = 1; + in_frame = true; + F(1) = []; + end + + if ~isempty(F) + ind = y0); + L2 = f_y(f_ch==15 & bitand(f_x,LineStop)>0); + + ll = line + numel(L2)-1; % this will be the last complete line in the data stack + + if ll > ny + L1 = L1(1:ny-line+1); + L2 = L2(1:ny-line+1); + end + + if numel(L1)>1 + for j=1:numel(L2) + + ind = (f_y>L1(j))&(f_y + t_chan = [t_chan; uint8(f_ch(ind))]; %#ok + t_line = [t_line; uint16(line.*ones(sum(ind),1))]; %#ok + t_col = [t_col; uint16(1 + floor(nx.*(f_y(ind)-L1(j))./(L2(j)-L1(j))))]; %#ok + + line = line +1; + + end + end + + if line>ny + in_frame = false; + end + end + + im_tcspc = [im_tcspc; t_tcspc]; %#ok + im_chan = [im_chan; t_chan]; %#ok + im_line = [im_line; t_line]; %#ok + im_col = [im_col; t_col]; %#ok + + [tmpy, tmptcspc, tmpchan, num, loc] = PT3_Read(name, [cnt+1 1e6 head.length]); + + end; + + F = y(chan==15 & bitand(tmpx,Frame)>0); + + t_tcspc = []; + t_chan = []; + t_line = []; + t_col = []; + + if ~in_frame + if isempty(F) + y = []; + tmpx = []; + chan = []; + line = 1; + else + ind = (y<=F(1)); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + line = 1; + end + end + + f_y = y; + f_x = tmpx; + f_ch = chan; + + clear y tmpx chan; + + L1 = f_y(f_ch==15 & bitand(f_x,LineStart)>0); + L2 = f_y(f_ch==15 & bitand(f_x,LineStop)>0); + + ll = line + numel(L2)-1; % this will be the last complete line in the data stack + if ll > ny + L1 = L1(1:ny-line+1); + L2 = L2(1:ny-line+1); + end + + if numel(L1)>1 + for j=1:numel(L2) + ind = (f_y>L1(j))&(f_y + t_chan = [t_chan; uint8(f_ch(ind))]; %#ok + t_line = [t_line; uint16(line.*ones(sum(ind),1))]; %#ok + t_col = [t_col; uint16(1 + floor(nx.*(f_y(ind)-L1(j))./(L2(j)-L1(j))))]; %#ok + line = line +1; + end + end + + im_tcspc = [im_tcspc; t_tcspc]; + im_chan = [im_chan; t_chan]; + im_line = [im_line; t_line]; + im_col = [im_col; t_col]; + + end + end; + + close(h); + +end + + +if ~isempty(head)&&(plt==1) + + tag = zeros(nx,ny); + for y = 1:ny + ind = (im_line == y); + tmp1 = im_col(ind); + for x = 1:nx + ind = (tmp1 == x); + tag(x,y) = sum(ind); + end + end + + figure; + x = head.ImgHdr.X0+(1:nx)*head.ImgHdr.PixelSize; + y = head.ImgHdr.Y0+(1:ny)*head.ImgHdr.PixelSize; + + imagesc(x,y,sum(sum(tag,4),3)); + set(gca,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse'); + xlabel('x / µm'); + ylabel('y / µm'); +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_Read.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_Read.m new file mode 100644 index 0000000..e13c22b --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_Read.m @@ -0,0 +1,171 @@ +function [sync, tcspc, chan, special, num, loc, head] = PTU_Read(name, cnts, head) +% +% function [sync, tcspc, chan, special, num] = HT3_Read(name, cnts, head) +% +% This function reads single-photon data from the file 'name' +% +% If 'cnts' contains a number larger than 0, the routine reads 'cnts' +% records the data stream or up the end of the file. +% +% If 'cnts' contains two numbers [cnts(1) cnts(2)], the routine proceeds +% to the position cnts(1) before readinf the cnts(2) records of data. +% +% The output variables contain the followig data: +% sync : number of the sync events that preceeded this detection event +% tcspc : number of the tcspc-bin of the event +% chan : number of the input channel of the event (detector-number) +% special : indicator of the event-type (0: photon; else : virtual photon) +% num : counter of the records that were actually read +% loc : number of overcounts after last valid photon + +rtPicoHarpT3 = hex2dec('00010303');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $03 (PicoHarp) +rtPicoHarpT2 = hex2dec('00010203');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $03 (PicoHarp) +rtHydraHarpT3 = hex2dec('00010304');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $04 (HydraHarp) +rtHydraHarpT2 = hex2dec('00010204');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $04 (HydraHarp) +rtHydraHarp2T3 = hex2dec('01010304');% (SubID = $01 ,RecFmt: $01) (V2), T-Mode: $03 (T3), HW: $04 (HydraHarp) +rtHydraHarp2T2 = hex2dec('01010204');% (SubID = $01 ,RecFmt: $01) (V2), T-Mode: $02 (T2), HW: $04 (HydraHarp) +rtTimeHarp260NT3 = hex2dec('00010305');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $05 (TimeHarp260N) +rtTimeHarp260NT2 = hex2dec('00010205');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $05 (TimeHarp260N) +rtTimeHarp260PT3 = hex2dec('00010306');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $06 (TimeHarp260P) +rtTimeHarp260PT2 = hex2dec('00010206');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $06 (TimeHarp260P) +rtMultiHarpNT3 = hex2dec('00010307');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $07 (MultiHarp150N) +rtMultiHarpNT2 = hex2dec('00010207');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $07 (MultiHarp150N) + +if (nargin<3)||(isempty(head)) + head = PTU_Read_Head(name); +end + +if ~isempty(head) + + if (nargin<2)||isempty(cnts) + cnts = [0 0]; + end + + if numel(cnts)<2 + cnts = [0 cnts]; + end + + + if cnts(2)>0 + + fid = fopen(name); + + if fid<1 + fprintf(1,'\n\n Could not open <%s>. Aborted.\n', name); + + else + + fseek(fid, head.length, 'bof'); + + if cnts(1)>1 + fseek(fid, 4*(cnts(1)-1), 'cof'); + end + + [T3Record, num] = fread(fid, cnts(2), 'ubit32'); % all 32 bits: + + switch head.TTResultFormat_TTTRRecType + case rtPicoHarpT3 + + WRAPAROUND=65536; + + sync = bitand(T3Record,65535); % the lowest 16 bits: + chan = bitand(bitshift(T3Record,-28),15); % the upper 4 bits: + tcspc = bitand(bitshift(T3Record,-16),4095); + special = (chan==15).*bitand(tcspc,15); + + ind = ((chan==15) & bitand(tcspc,15)==0); + + + case rtPicoHarpT2 + + WRAPAROUND=210698240; + + sync = bitand(T3Record,268435455); %the lowest 28 bits + tcspc = bitand(T3Record,15); %the lowest 4 bits + chan = bitand(bitshift(T3Record,-28),15); %the next 4 bits + special = (chan==15).*bitand(tcspc,15); + + ind = ((chan==15) & bitand(tcspc,15)==0); + + case {rtHydraHarpT3, rtHydraHarp2T3, rtTimeHarp260NT3, rtTimeHarp260PT3,rtMultiHarpNT3} + + WRAPAROUND=1024; + + % +----------------------+ T3 32 bit record +---------------------+ + % |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| + % +-------------------------------+ +-------------------------------+ + sync = bitand(T3Record,1023); % the lowest 10 bits: + % +-------------------------------+ +-------------------------------+ + % | | | | | | | | | | | | | | | | | | | | | | | |x|x|x|x|x|x|x|x|x|x| + % +-------------------------------+ +-------------------------------+ + tcspc = bitand(bitshift(T3Record,-10),32767); % the next 15 bits: + % the dtime unit depends on "Resolution" that can be obtained from header + % +-------------------------------+ +-------------------------------+ + % | | | | | | | |x|x|x|x|x|x|x|x|x| |x|x|x|x|x|x| | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + chan = bitand(bitshift(T3Record,-25),63); % the next 6 bits: + % +-------------------------------+ +-------------------------------+ + % | |x|x|x|x|x|x| | | | | | | | | | | | | | | | | | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + special = bitand(T3Record,2147483648)>0; % the last bit: + % +-------------------------------+ +-------------------------------+ + % |x| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + + ind = (special==1 & chan==63); + + special = special.*chan; + + case rtHydraHarpT2 + + WRAPAROUND=33552000; + + sync = bitand(T3Record,33554431); % the last 25 bits + chan = bitand(bitshift(T3Record,-25),63); % the next 6 bits + tcspc = bitand(chan,15); + special = bitand(bitshift(T3Record,-31),1); % the last bit + + ind = (special==1 & chan==63); + + special = special.*chan; + + case {rtHydraHarp2T2, rtTimeHarp260NT2, rtTimeHarp260PT2,rtMultiHarpNT2} + + WRAPAROUND=33554432; + + sync = bitand(T3Record,33554431); % the last 25 bits + chan = bitand(bitshift(T3Record,-25),63); % the next 6 bits + tcspc = bitand(chan,15); + special = bitand(bitshift(T3Record,-31),1); % the last bit + + ind = (special==1 & chan==63); + + special = special.*chan; + + otherwise + error('Illegal RecordType!'); + end + + tmp = sync(ind==1); + tmp(tmp==0) = 1; + sync(ind) = tmp; + sync = sync + WRAPAROUND*cumsum(ind.*sync); + + sync(ind) = []; + tcspc(ind) = []; + special(ind) = []; + chan(ind) = []; + loc = num - find(ind==0,1,'last'); + + end + + fclose(fid); + +% else +% if (nargin<1)||isempty(name) +% fprintf(1,'\n\n You have to specify a valid file-name. Aborted.\n'); +% %else +% %fprintf(1,'\n\n Could not open <%s>. Aborted.\n', name); +% end + end +end diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_Read_Head.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_Read_Head.m new file mode 100644 index 0000000..33f2bf7 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_Read_Head.m @@ -0,0 +1,108 @@ +function [head] = PTU_Read_Head(name) + +% Read PicoQuant Unified TTTR Files + +head = []; +fid = fopen(name); +if fid<1 + %fprintf(1,'\n\n Could not open <%s>. Aborted.\n', name); +else + + tyEmpty8 = hex2dec('FFFF0008'); + tyBool8 = hex2dec('00000008'); + tyInt8 = hex2dec('10000008'); + tyBitSet64 = hex2dec('11000008'); + tyColor8 = hex2dec('12000008'); + tyFloat8 = hex2dec('20000008'); + tyTDateTime = hex2dec('21000008'); + tyFloat8Array = hex2dec('2001FFFF'); + tyAnsiString = hex2dec('4001FFFF'); + tyWideString = hex2dec('4002FFFF'); + tyBinaryBlob = hex2dec('FFFFFFFF'); + + head.Magic = deblank(char(fread(fid, 8, 'char')')); + if not(strcmp(head.Magic,'PQTTTR')) + error('Magic invalid, this is not an PTU file.'); + end + head.Version = deblank(char(fread(fid, 8, 'char')')); + + + TagIdent = deblank(char(fread(fid, 32, 'char')')); % TagHead.Ident + TagIdent = TagIdent(TagIdent ~= '$'); + TagIdx = fread(fid, 1, 'int32'); % TagHead.Idx + TagTyp = fread(fid, 1, 'uint32'); % TagHead.Typ + + while ~strcmp(TagIdent, 'Header_End') + + if TagIdx > -1 + EvalName = ['head.' TagIdent '(' int2str(TagIdx + 1) ')']; + else + EvalName = ['head.' TagIdent]; + end + + % check Typ of Header + + switch TagTyp + case tyEmpty8 + fread(fid, 1, 'int64'); + eval([EvalName '= [];']); + case tyBool8 + TagInt = fread(fid, 1, 'int64'); + if TagInt==0 + eval([EvalName '=false;']); + else + eval([EvalName '=true;']); + end + case tyInt8 + TagInt = fread(fid, 1, 'int64'); + eval([EvalName '=TagInt;']); + case tyBitSet64 + TagInt = fread(fid, 1, 'int64'); + eval([EvalName '=TagInt;']); + case tyColor8 + TagInt = fread(fid, 1, 'int64'); + eval([EvalName '=TagInt;']); + case tyFloat8 + TagFloat = fread(fid, 1, 'double'); + eval([EvalName '=TagFloat;']); + case tyFloat8Array + TagInt = floor(fread(fid, 1, 'int64')/8); + TagArray = fread(fid, TagInt, 'double'); + case tyTDateTime + TagFloat = fread(fid, 1, 'double'); + eval([EvalName '=datestr(693960+TagFloat);']); + case tyAnsiString + TagInt = fread(fid, 1, 'int64'); + TagString = deblank(char(fread(fid, TagInt, 'char'))'); + tmp = char(regexp(EvalName,'\([0-9]+\)','match')); + if ~isempty(tmp) + EvalName=strrep(EvalName,tmp,['{' tmp(2:end-1) '}']); + end + eval([EvalName '=TagString;']); + case tyWideString + % Matlab does not support Widestrings at all, just read and + % remove the 0's (up to current (2012)) + TagInt = fread(fid, 1, 'int64'); + TagString = fread(fid, TagInt, '*char'); + TagString = (TagString(TagString ~= 0))'; + fprintf(1, '%s', TagString); + if TagIdx > -1 + EvalName = [TagIdent '(' int2str(TagIdx + 1) ',:)']; + end; + eval([EvalName '=TagString;']); + case tyBinaryBlob + TagInt = floor(fread(fid, 1, 'int64')/8); + TagBytes = fread(fid, 1, 'uint64'); + otherwise + + end; + TagIdent = deblank(char(fread(fid, 32, 'char')')); % TagHead.Ident + TagIdent = TagIdent(TagIdent ~= '$'); + TagIdx = fread(fid, 1, 'int32'); % TagHead.Idx + TagTyp = fread(fid, 1, 'uint32'); % TagHead.Typ + end + + head.length = ftell(fid)+8; + fclose(fid); + +end diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_ScanRead.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_ScanRead.m new file mode 100644 index 0000000..8fd8c9a --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/PTU_ScanRead.m @@ -0,0 +1,517 @@ +function [head, im_tcspc, im_chan, im_line, im_col] = PTU_ScanRead(name, plt) + +if (nargin>1)&&~isempty(plt) + plt = 1; +else + plt = 0; +end + +head = PTU_Read_Head(name); +nphot = head.TTResult_NumberOfRecords; + +if strcmp(name(end-2:end),'ptu') + + head = PTU_Read_Head(name); + + if ~isempty(head) + + nx = head.ImgHdr_PixX; + ny = head.ImgHdr_PixY; + + if (head.ImgHdr_Ident == 1)||(head.ImgHdr_Ident == 6) + + anzch = 32; + Resolution = max([1e9*head.MeasDesc_Resolution]); + chDiv = 1e-9*Resolution/head.MeasDesc_Resolution; + Ngate = ceil(1e9*head.MeasDesc_GlobalResolution./Resolution)+1; + + LineStart = 4; + LineStop = 2; + + if isfield(head,'ImgHdr_LineStart') + LineStart = 2^(head.ImgHdr_LineStart-1); + end + if isfield(head,'ImgHdr_LineStop') + LineStop = 2^(head.ImgHdr_LineStop-1); + end + + y = []; + tmpx = []; + chan = []; + markers = []; + dt = zeros(ny,1); + + im_tcspc = []; + im_chan = []; + im_line = []; + im_col = []; + Turns1 = []; + Turns2 = []; + + cnt = 0; + tend = 0; + line = 1; + + h = waitbar(0,'Please wait ...'); + + fprintf('\n\n'); + + if head.ImgHdr_BiDirect == 0 + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = PTU_Read(name, [cnt+1 nphot], head); + + while (num>0) + + cnt = cnt + num; + if ~isempty(y) + tmpy = tmpy+tend; + end + + ind = (tmpmarkers>0)|((tmpchan + tmpx = [tmpx; floor(tmptcspc(ind)./chDiv)+1;]; %#ok + chan = [chan; tmpchan(ind)+1]; %#ok + markers = [markers; tmpmarkers(ind)]; %#ok + + if LineStart==LineStop + tmpturns = y(markers==LineStart); + if numel(Turns1)>numel(Turns2) % first turn is a LineStop + Turns1 = [Turns1; tmpturns(2:2:end)]; %#ok + Turns2 = [Turns2; tmpturns(1:2:end)]; %#ok + else + Turns1 = [Turns1; tmpturns(1:2:end)]; %#ok + Turns2 = [Turns2; tmpturns(2:2:end)]; %#ok + end + else + Turns1 = [Turns1; y(markers==LineStart)]; %#ok + Turns2 = [Turns2; y(markers==LineStop)]; %#ok + end + + ind = (markers~=0); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + markers(ind) = []; + + tend = y(end)+loc; + + if numel(Turns2)>1 + for j=1:numel(Turns2)-1 + + t1 = Turns1(1); + t2 = Turns2(1); + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + + dt(line) = t2-t1; + line = line +1; + waitbar(line/ny); + drawnow + + Turns1(1) = []; + Turns2(1) = []; + end + end + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = PTU_Read(name, [cnt+1 nphot], head); + + end + + t1 = Turns1(end); + t2 = Turns2(end); + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; + dt(line) = t2-t1; + + line = line +1; + waitbar(line/ny,h); + drawnow + + else % bidirectional scan + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = PTU_Read(name, [cnt+1 nphot], head); + + while (num>0) + + cnt = cnt + num; + if ~isempty(y) + tmpy = tmpy+tend; + end + + ind = ((tmpchan + tmpx = [tmpx; floor(tmptcspc(ind)./chDiv)+1;]; %#ok + chan = [chan; tmpchan(ind)+1]; %#ok + markers = [markers; tmpmarkers(ind)]; %#ok + + if LineStart==LineStop + tmpturns = y(markers==LineStart); + if numel(Turns1)>numel(Turns2) % first turn is a LineStop + Turns1 = [Turns1; tmpturns(2:2:end)]; %#ok + Turns2 = [Turns2; tmpturns(1:2:end)]; %#ok + else + Turns1 = [Turns1; tmpturns(1:2:end)]; %#ok + Turns2 = [Turns2; tmpturns(2:2:end)]; %#ok + end + else + Turns1 = [Turns1; y(markers==LineStart)]; %#ok + Turns2 = [Turns2; y(markers==LineStop)]; %#ok + end + + ind = (markers~=0); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + markers(ind) = []; + + tend = y(end)+loc; + + if numel(Turns2)>2 + for j=1:2:2*floor(numel(Turns2)/2-1) + + t1 = Turns1(1); + t2 = Turns2(1); + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + dt(line) = t2-t1; + + line = line +1; + + t1 = Turns1(2); + t2 = Turns2(2); + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; %#ok + im_chan = [im_chan; uint8(chan(ind))]; %#ok + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; %#ok + im_col = [im_col; uint16(nx - floor(nx.*(y(ind)-t1)./(t2-t1)))]; %#ok + dt(line) = t2-t1; + + line = line +1; + waitbar(line/ny,h); + drawnow + + Turns1(1:2) = []; + Turns2(1:2) = []; + end + end + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = PTU_Read(name, [cnt+1 nphot], head); + + end + + if ~isempty(Turns2) + t1 = Turns1(end-1); + t2 = Turns2(end-1); + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(1 + floor(nx.*(y(ind)-t1)./(t2-t1)))]; + dt(line) = t2-t1; + + line = line +1; + + t1 = Turns1(end); + t2 = Turns2(end); + + ind = (y=t1)&(y<=t2); + + im_tcspc = [im_tcspc; uint16(tmpx(ind))]; + im_chan = [im_chan; uint8(chan(ind))]; + im_line = [im_line; uint16(line.*ones(sum(ind),1))]; + im_col = [im_col; uint16(nx - floor(nx.*(y(ind)-t1)./(t2-t1)))]; + dt(line) = t2-t1; + + line = line +1; + waitbar(line/ny); + drawnow + end + end + + head.ImgHdr_PixelTime = 1e9.*mean(dt)/nx/head.TTResult_SyncRate; + + close(h); + + elseif (head.ImgHdr_Ident == 3)||(head.ImgHdr_Ident == 9) + + y = []; + tmpx = []; + chan = []; + marker = []; + + dt = zeros(ny,1); + im_tcspc = []; + im_chan = []; + im_line = []; + im_col = []; + + cnt = 0; + tend = 0; + line = 1; + n_frames = 0; + f_times = []; + + head.ImgHdr_X0 = 0; + head.ImgHdr_Y0 = 0; + head.ImgHdr_PixResol = 1; + + LineStart = 2^(head.ImgHdr_LineStart-1); + LineStop = 2^(head.ImgHdr_LineStop-1); + Frame = 2^(head.ImgHdr_Frame-1); + + h = waitbar(0, 'Please Wait...'); + + if Frame < 1 + Frame = -1; + end + + in_frame = false; + + if Frame < 1 + in_frame = true; + n_frames = n_frames + 1; + end + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = PTU_Read(name, [cnt+1 nphot], head); + + % Zeiss Scan Read + if isfield(head,'StartedByRemoteInterface') + cnt = cnt + num; + waitbar(cnt/head.TTResult_NumberOfRecords,h); + [head, im_tcspc, im_chan, im_line, im_col] = zeiss_ScanRead(tmpy, tmptcspc, tmpchan+1, tmpmarkers, head); + clear tmpy tmptcspc tmpchan tmpmarkers num loc; + else + while (num>0) + + t_tcspc = []; + t_chan = []; + t_line = []; + t_col = []; + + cnt = cnt + num; + + waitbar(cnt/head.TTResult_NumberOfRecords,h); + + tmpy = tmpy+tend; + + y = [y; tmpy]; %#ok + tmpx = [tmpx; tmptcspc]; %#ok + chan = [chan; tmpchan+1]; %#ok + marker = [marker; tmpmarkers]; %#ok + tend = y(end)+loc; + + F = y(bitand(marker,Frame)>0); + + while ~isempty(F) + + if ~in_frame + ind = (y<=F(1)); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + marker(ind) = []; + line = 1; + in_frame = true; + n_frames = n_frames + 1; + f_times = [f_times; F(1)]; + F(1) = []; + end + + if ~isempty(F) + ind = y0); + L2 = f_y(bitand(f_m,LineStop)>0); + + ll = line + numel(L2)-1; % this will be the last complete line in the data stack + + if ll > ny + L1 = L1(1:ny-line+1); + L2 = L2(1:ny-line+1); + end + + if numel(L1)>1 + for j=1:numel(L2) + + ind = (f_y>L1(j))&(f_y + t_chan = [t_chan; uint8(f_ch(ind))]; %#ok + t_line = [t_line; uint16(line.*ones(sum(ind),1))]; %#ok + t_col = [t_col; uint16(1 + floor(nx.*(f_y(ind)-L1(j))./(L2(j)-L1(j))))]; %#ok + dt(line) = dt(line) + (L2(j)-L1(j)); + line = line +1; + end + end + + if line>ny + in_frame = false; + end + end + + im_tcspc = [im_tcspc; t_tcspc]; %#ok + im_chan = [im_chan; t_chan]; %#ok + im_line = [im_line; t_line]; %#ok + im_col = [im_col; t_col]; %#ok + + [tmpy, tmptcspc, tmpchan, tmpmarkers, num, loc] = PTU_Read(name, [cnt+1 nphot], head); + + end + + F = y(bitand(marker,Frame)>0); + + t_tcspc = []; + t_chan = []; + t_line = []; + t_col = []; + + if ~in_frame + if isempty(F) + y = []; + tmpx = []; + chan = []; + marker = []; + line = 1; + else + ind = (y<=F(1)); + y(ind) = []; + tmpx(ind) = []; + chan(ind) = []; + marker(ind) = []; + line = 1; + n_frames = n_frames + 1; + f_times = [f_times; F(1)]; + end + end + + f_y = y; + f_x = tmpx; + f_ch = chan; + f_m = marker; + + clear y tmpx chan; + + L1 = f_y(bitand(f_m,LineStart)>0); + L2 = f_y(bitand(f_m,LineStop)>0); + + ll = line + numel(L2)-1; % this will be the last complete line in the data stack + if ll > ny + L1 = L1(1:ny-line+1); + L2 = L2(1:ny-line+1); + end + + if numel(L1)>1 + for j=1:numel(L2) + ind = (f_y>L1(j))&(f_y + t_chan = [t_chan; uint8(f_ch(ind))]; %#ok + t_line = [t_line; uint16(line.*ones(sum(ind),1))]; %#ok + t_col = [t_col; uint16(1 + floor(nx.*(f_y(ind)-L1(j))./(L2(j)-L1(j))))]; %#ok + dt(line) = dt(line) + (L2(j)-L1(j)); + line = line +1; + end + end + + im_tcspc = [im_tcspc; t_tcspc]; + im_chan = [im_chan; t_chan]; + im_line = [im_line; t_line]; + im_col = [im_col; t_col]; + end + + %head.ImgHdr_FrameTime = 1e9.*mean(diff(f_times))/head.TTResult_SyncRate; + head.ImgHdr_PixelTime = head.TimePerPixel; + %head.ImgHdr_DwellTime = head.ImgHdr_PixelTime./n_frames; + close(h); + end + + end +end + + +if ~isempty(head)&&(plt==1) + + tag = zeros(nx,ny); + for y = 1:ny + ind = (im_line == y); + tmp1 = im_col(ind); + for x = 1:nx + tag(y,x) = sum(tmp1 == x); + end + end + + x = head.ImgHdr_X0+(1:nx)*head.ImgHdr_PixResol; + y = head.ImgHdr_Y0+(1:ny)*head.ImgHdr_PixResol; + imagesc(x,y,tag); + set(gca,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse'); + xlabel('x / µm'); + ylabel('y / µm'); +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern.mat b/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern.mat new file mode 100644 index 0000000..041ec62 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern.mat differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern_Fit.fig b/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern_Fit.fig new file mode 100644 index 0000000..94b42b6 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern_Fit.fig differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern_Fit.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern_Fit.m new file mode 100644 index 0000000..8d4cc56 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Pattern_Fit.m @@ -0,0 +1,1945 @@ +function varargout = Pattern_Fit(varargin) +% PATTERN_FIT M-file for Pattern_Fit.fig +% PATTERN_FIT, by itself, creates a new PATTERN_FIT or raises the existing +% singleton*. +% +% H = PATTERN_FIT returns the handle to a new PATTERN_FIT or the handle to +% the existing singleton*. +% +% PATTERN_FIT('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in PATTERN_FIT.M with the given input arguments. +% +% PATTERN_FIT('Property','Value',...) creates a new PATTERN_FIT or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before Pattern_Fit_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to Pattern_Fit_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 Pattern_Fit + +% Last Modified by GUIDE v2.5 01-Sep-2011 17:04:03 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @Pattern_Fit_OpeningFcn, ... + 'gui_OutputFcn', @Pattern_Fit_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 Pattern_Fit is made visible. +function Pattern_Fit_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 Pattern_Fit (see VARARGIN) + +% Choose default command line output for Pattern_Fit +handles.output = hObject; + + +load Get_Params; +handles.par_lam_start = lam_start; +handles.par_lam_step = lam_step; +handles.par_clam_min = clam_min; +handles.par_clam_max = clam_max; +handles.par_num_PIE = num_PIE; +handles.ROIcolor = ROIcolor; +handles.lamPIE = lamPIE; + +handles.ROI = 1; +handles.channel = 1; +handles.fit = 1; +handles.pulse = 1; + +%if length(varargin) < 2 +% uiwait(errordlg('No pattern given','Data missing')) +%elseif (length(varargin) == 2 && strcmpi(varargin{1},'file')) +% handles.filename = cell2mat(varargin(3)); +% load(cell2mat(varargin(2)), 'pat', 'list', 'params'); +% handles.pat = pat; +% handles.List = list; +% handles.params = params; +%end + +load(cell2mat(varargin(2)), 'pat', 'list', 'params'); +handles.pat = pat; +handles.list = list; +%handles.params = params; +handles.filename = cell2mat(varargin(3)); + +tmp = strfind(handles.filename,'\'); +handles.pathname = handles.filename(1:tmp(end)); +handles.filename = handles.filename(tmp(end)+1:end); + +[handles.head, handles.tag, handles.tcspc, handles.IRF, handles.timname... + , handles.AP, handles.DC] = load_data([handles.pathname handles.filename]); + +handles.nch = size(handles.tcspc,1); +handles.binw = handles.head.tauw(:)./handles.head.tauw(1); +handles.taush = handles.head.tau; +handles.tau = handles.head.tau(:)*ones(1,handles.par_num_PIE); +handles.tmp = ones(size(handles.tau,1),1)*((0:handles.par_num_PIE-1).*handles.tau(end,1)); +handles.tau = reshape(handles.tau+handles.tmp, [numel(handles.tau) 1]); +handles.m0 = handles.head.m0; + +% Update handles structure + +guidata(hObject, handles); + +set(handles.search,'Value',1); +set(handles.select_chan,'Value',1); +set(handles.in_spec, 'Value',1); + + +set(handles.popupmenu1, 'String',list); +set(handles.popupmenu6, 'String',{'Lifetime', 'FLIM FRET const Int. ratio', 'FLIM FRET const Ampl. ratio'}) + + +tmp = {}; +lam = (handles.par_lam_start+handles.par_lam_step.*(0:(handles.nch))); +for n = 1 : size(handles.tcspc,1) + tmp(n) = {sprintf(' %s nm',num2str(lam(n)))}; +end +set(handles.popupmenu2, 'String',tmp); + +tmp = {}; +PIE = 1:num_PIE; +for n = 1 : size(PIE,2) + tmp(n) = {sprintf('Pulse %s',num2str(PIE(n)))}; +end +set(handles.popupmenu3, 'String',tmp); + + +set(handles.edit1,'String', '0.026'); +set(handles.edit2,'String', '6.1'); +set(handles.edit3,'String', '0.28'); +set(handles.edit4,'String', '1.8'); + +set(handles.wave1,'Enable', 'off') +set(handles.wave2,'Enable', 'off') +set(handles.wave3,'Enable', 'off') +set(handles.wave4,'Enable', 'off') +set(handles.pulse1,'Enable', 'off'); +set(handles.pulse2,'Enable', 'off'); +set(handles.pulse3,'Enable', 'off'); +set(handles.pulse4,'Enable', 'off'); + +for n = 1:num_PIE + eval(sprintf('set(handles.wave%d, \''Enable\'', \''on\'');', n)) + eval(sprintf('set(handles.pulse%d, \''Enable\'', \''on\'');', n)) + eval(sprintf('set(handles.wave%d, \''String\'', \''%d\'');', n, lamPIE(n))) +end + +set(handles.varycheck, 'Value', 0) +set(handles.vary1, 'Enable', 'off'); +set(handles.vary2, 'Enable', 'off'); +set(handles.no_of_pat, 'Enable', 'off'); +set(handles.from, 'Enable', 'off'); +set(handles.to, 'Enable', 'off'); +set(handles.popupmenu6, 'Enable', 'off') + +zoom on + +axes(handles.axes1) + +axis([0 floor(handles.taush(end)) -3 0.1]); +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +axes(handles.axes2) + +axis([0 floor(handles.taush(end)) 0 0.01]); +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +axes(handles.axes3) + +axis([handles.par_clam_min handles.par_clam_max 0 1.1]); +xlabel('wavelength of spectral mean / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('rel. spectral irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +axes(handles.axes4) + +axis([0 floor(handles.taush(end)) -3 0.1]); +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +axes(handles.axes5) + +%axis([0 floor(handles.tau(end)) -3 0.1]); +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +axes(handles.axes6) + +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + + +% UIWAIT makes Pattern_Fit wait for user response (see UIRESUME) +% uiwait(handles.figure1); + + +% --- Outputs from this function are returned to the command line. +function varargout = Pattern_Fit_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; + + +% --- Executes on button press in iPattern. +function iPattern_Callback(hObject, eventdata, handles) +% hObject handle to iPattern (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% argin +selected_ROI = handles.ROI; +binw = handles.binw; +tau = handles.tau; +taush = handles.taush; +nch = handles.nch; +par_num_PIE = handles.par_num_PIE; +pulse = handles.pulse; + +% Reads the Pattern of the selected ROI and adds zeros left and right to +% the channel dimension. +pat = handles.pat(selected_ROI,:,:,:); +pat0 = zeros(size(pat,1),1,size(pat,3),size(pat,4)); +pat = cat(2, pat0, pat, pat0); + +% ??? +decay = sum(pat,2)./permute(repmat(binw, [1 size(pat,1) 1 size(pat,4)]),[2 3 1 4]); +decay = squeeze(decay); +M = max(decay,[],1); +decay = decay./M(pulse); +decay(decay<=1e-3) = 1e-3; + +handles.decay = decay(:,pulse); + + +% ploting: overall ROI decay of the selected ROI +axes(handles.axes1) +hold on; +cla + +plot(taush,log10(decay(:,pulse)),'.','LineWidth',2,'Color',handles.ROIcolor(selected_ROI,:)); + +hold off; + +axis([0 floor(taush(end)) -3 0.1]) + +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + +% ploting: IRF of each channel +axes(handles.axes2); +cla; +hold on; +for n = 1:nch + plot(handles.taush, handles.IRF(n,:,pulse).*handles.head.tauw ); +end +hold off; + +axis auto + +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + +axes(handles.axes3) + +hold on; +cla +box on; + +spec = sum(pat(1,:,:,pulse),3); +lam = (handles.par_lam_start+handles.par_lam_step.*(-1:nch))'; +ts = handles.par_clam_min: 1: handles.par_clam_max; + +[M,I] = max(spec); + +handles.I = I; +spec = interp1(lam, spec./M, ts,'cubic'); +handles.spec = [ts;spec]'; + +plot(ts,spec,'-','LineWidth',2,... + 'Color',handles.ROIcolor(selected_ROI,:)); + +hold off + +axis([handles.par_clam_min handles.par_clam_max 0 1.1]) + +xlabel('wavelength of spectral mean / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('rel. spectral irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +% Update handles structure +guidata(hObject, handles); + + + +% --- Executes on button press in iIRF. +function iIRF_Callback(hObject, eventdata, handles) +% hObject handle to iIRF (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% argin +nch = size(handles.tcspc,1); +selected_ROI = handles.ROI; +pulse = handles.pulse; + +% ploting: IRF of each channel +axes(handles.axes2); +cla; +hold on; +for n = 1:nch + plot(handles.head.tau, handles.IRF(n,:,pulse).*handles.head.tauw ); +end +hold off; + +axis auto + +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + + + +% --- Executes on button press in iSpectrum. +function iSpectrum_Callback(hObject, eventdata, handles) +% hObject handle to iSpectrum (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(handles.in_spec,'Value') == 1 + + set(handles.specname,'BackgroundColor', [0.83 0.82 0.78]); + set(handles.specname,'String',''); + + % argin + selected_ROI = handles.ROI; + binw = handles.binw; + tau = handles.tau; + taush = handles.taush; + nch = handles.nch; + num_PIE = handles.par_num_PIE + pulse = handles.pulse; + + + % Reads the Pattern of the selected ROI and adds zeros left and right to + % the channel dimension. + pat = handles.pat(selected_ROI,:,:,:); + pat0 = zeros(size(pat,1),1,size(pat,3),size(pat,4)); + pat = cat(2, pat0, pat, pat0); + + absorb = squeeze(sum(sum(pat,2),3)); + absorb = absorb./max(absorb); + for i = 1:num_PIE + eval(sprintf('set(handles.pulse%d,\''String\'',absorb(%d))',i,i)); + end + + axes(handles.axes3) + + hold on; + cla + box on; + spec = sum(pat(1,:,:,pulse),3); + lam = (handles.par_lam_start+handles.par_lam_step.*(-1:nch))'; + ts = handles.par_clam_min: 1: handles.par_clam_max; + + [M,I] = max(spec); + + handles.I = I; + spec = interp1(lam, spec./M, ts,'cubic'); + handles.spec = [ts;spec]'; + + plot(ts,spec,'-','LineWidth',2,... + 'Color',handles.ROIcolor(selected_ROI,:)); + + hold off + + axis([handles.par_clam_min handles.par_clam_max 0 1.1]) + + xlabel('wavelength of spectral mean / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('rel. spectral irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +elseif get(handles.ex_spec,'Value') == 1 + + [FileName,PathName] = uigetfile({'*.txt','txt-files';'*.*','All Files' }); + fid = fopen(FileName,'r'); + InputText = textscan(fid,'%f','delimiter','\n'); + + set(handles.specname,'BackgroundColor', 'white'); + set(handles.specname,'String',FileName); + + spec = reshape(InputText{1},[2,length(InputText{1})/2])'; + handles.spec = [spec(:,1) spec(:,2)./max(spec(:,2))]; + fclose('all'); + + axes(handles.axes3); + hold on; + cla; + plot(spec(:,1),spec(:,2)./max(spec(:,2))) + hold off +end + +guidata(hObject,handles); + + +% --- Executes on button press in fit. +function fit_Callback(hObject, eventdata, handles) +% hObject handle to fit (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% argin +selected_ROI = handles.ROI; +selected_chan = handles.channel; +binw = handles.binw; +tau = handles.taush; +par_num_PIE = handles.par_num_PIE; +taulong = handles.tau; +pulse = handles.pulse; + +% Prepare Data + +pat = handles.pat(selected_ROI,:,:,:); + +if get(handles.select_chan,'Value') == 1 + + pat = pat./permute(repmat(binw,[1 size(pat,1) size(pat,2) size(pat,4)]),[2 3 1 4]); + pat = pat./max(max(max(pat))); + pat(pat<=1e-3) = 1e-3; + + mesu = shiftdim(pat(:,selected_chan,:,pulse),1); + irf = handles.IRF(selected_chan,:,pulse).*handles.binw'; + +elseif get(handles.select_chan,'Value') == 0 + + decay = sum(pat,2)./permute(repmat(binw, [1 size(pat,1) 1 size(pat,4)]),[2 3 1 4]); + decay = squeeze(decay); + M = max(decay,[],1); + decay = decay./M(pulse); + decay(decay<=1e-3) = 1e-3; + + mesu = decay(:,pulse)'; + + binw = repmat(handles.binw',[size(handles.IRF,1) 1],1); + irf = sum(handles.IRF(:,:,pulse).*... + repmat(handles.binw',[size(handles.IRF,1) 1],1))./selected_chan; + +end + + +handles.fit + +% Get Initial Values + +if handles.fit == 1 + + handles.fit = 0; + + tmp = log10(mesu); + tmp = (tmp - min(tmp)); + + [M,I1] = max(tmp); + tmp(1:I1) = []; + + for i = 1:length(tmp) + if tmp(i) <= 3*M/4 + I2= I1 + i; + tmp(1:i)=[]; + break + end + end + + for i = 1:length(tmp) + if tmp(i) <= M/4 + I3= I2 + i; + tmp(1:i)=[]; + break + end + end + + for i = 1:length(tmp) + if tmp(i) == min(tmp) + I4 = I3 + i; + break + end + end + + tau1 = (tau(I2)-tau(I1))/(log(mesu(I1))-log(mesu(I2))); + tau2 = (tau(I4)-tau(I3))/(log(mesu(I3))-log(mesu(I4))); + + A = max(mesu); + A1 = mesu(I1); + A2 = mesu(I2); + + setparams = [A1,tau1,A2,tau2]; + + A1 = str2double(get(handles.edit1,'String')); + tau1 = str2double(get(handles.edit2,'String')); + A2 = str2double(get(handles.edit3,'String')); + tau2 = str2double(get(handles.edit4,'String')); + getparams = [A1,tau1,A2,tau2]; + +elseif handles.fit == 0 + + A1 = str2double(get(handles.edit1,'String')); + tau1 = str2double(get(handles.edit2,'String')); + A2 = str2double(get(handles.edit3,'String')); + tau2 = str2double(get(handles.edit4,'String')); + setparams = [A1,tau1,A2,tau2]; + getparams = setparams; + +end + +% Choice of fixed parameters + +a1 = get(handles.checkbox2,'Value'); +t1 = get(handles.checkbox3,'Value'); +a2 = get(handles.checkbox4,'Value'); +t2 = get(handles.checkbox5,'Value'); + +fix = [a1,t1,a2,t2]; + +antifix = ones(1,length(fix))-fix; + +setparams = antifix.*setparams; +getparams = fix.*getparams; + +params = antifix.*setparams + fix.*getparams; + +% Interpolation of tau to an aquidistant time array + +t = tau; + +res = diff([0 t]); + +t = 0.0:min(res):max(t); + +ind = zeros(size(tau)); +for k = 1:length(t) + for i = 1:length(tau) + if round(t(k)*1000)==round(tau(i)*1000) + ind(1,i) = k; + end + end +end + +% Fit + +f = @(setparams)norm(log10(Faltung(antifix.*setparams' + getparams,... + irf, tau,t,ind))-log10(mesu)); +tic; +[setparams, Ssq, CNT] = LMFsolve(f,setparams); +toc; + +params = antifix.*setparams' + fix.*getparams; + +% Convolution + +C = Faltung(params, irf, tau,t,ind); + +% Plot and show results + +axes(handles.axes4); +hold on +cla; + +plot(tau,log10(C),'r') +%plot(tau,log10(handles.IRF(selected_chan,:)),'b') +plot(tau,log10(mesu),'.','LineWidth',2,'Color',... + handles.ROIcolor(selected_ROI,:)) + +hold off + +axis([0 floor(tau(end)) -3 0.1]) +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + +set(handles.edit1,'String',num2str(params(1))); +set(handles.edit2,'String',num2str(params(2))); +set(handles.edit3,'String',num2str(params(3))); +set(handles.edit4,'String',num2str(params(4))); +set(handles.text3,'String',num2str(params(1)/params(3))); +set(handles.text4,'String',num2str((params(1)*params(2))/(params(3)*params(4)))); + +'finito' + +axes(handles.axes6); + +hold on +cla; + +abw = log10(C)-log10(mesu); +plot(tau,abw); + +hold off + +chi = norm(abw); +set(handles.text23,'String',num2str(chi)) + +xlim([0 floor(tau(end))]) +ylim auto +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +guidata(hObject,handles); + + +% --- Executes on button press in plot_IV. +function plot_IV_Callback(hObject, eventdata, handles) +% hObject handle to plot_IV (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% argin +selected_ROI = handles.ROI; +selected_chan = handles.channel; +binw = handles.binw; +tau = handles.taush; +pulse = handles.pulse; + +A1 = str2double(get(handles.edit1,'String')); +tau1 = str2double(get(handles.edit2,'String')); +A2 = str2double(get(handles.edit3,'String')); +tau2 = str2double(get(handles.edit4,'String')); + +pat = handles.pat(selected_ROI,:,:,:); + +if get(handles.select_chan,'Value') == 1 + + pat = pat./permute(repmat(binw,[1 size(pat,1) size(pat,2) size(pat,4)]),[2 3 1 4]); + pat = pat./max(max(max(pat))); + pat(pat<=1e-3) = 1e-3; + + mesu = shiftdim(pat(:,selected_chan,:,pulse),1); + irf = handles.IRF(selected_chan,:,pulse).*handles.binw'; + +elseif get(handles.select_chan,'Value') == 0 + + mesu = handles.decay; + irf = sum(handles.IRF(:,:,pulse).*... + repmat(handles.binw',[size(handles.IRF,1) 1],1))./selected_chan; + +end + +params = [A1,tau1,A2, tau2]; + +% Interpolation of tau to an aquidistant time array +ind = []; + +t = tau; + +res = diff([0 t]); + +t = 0.0:min(res):max(t); + +ind = zeros(size(tau)); +for k = 1:length(t) + for i = 1:length(tau) + if round(t(k)*1000)==round(tau(i)*1000) + ind(1,i) = k; + end + end +end + +%ind = round(t.*1000) == round(tau.*1000); + +C = Faltung(params, irf, tau,t,ind); + +axes(handles.axes4); +hold on +cla; +%plot(tau,log10(handles.IRF(selected_chan,:)),'b') +plot(tau,log10(C),'r') +plot(tau,log10(mesu),'.','LineWidth',2,'Color',... + handles.ROIcolor(selected_ROI,:)) + +hold off + +axis([0 floor(tau(end)) -3 0.1]) +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +guidata(hObject,handles); + + +% --- Executes on button press in getIV. +function getIV_Callback(hObject, eventdata, handles) +% hObject handle to getIV (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% argin +selected_ROI = handles.ROI; +selected_chan = handles.channel; +binw = handles.binw; +tau = handles.taush; +pulse = handles.pulse; + +pat = handles.pat(selected_ROI,:,:,:); + +if get(handles.select_chan,'Value') == 1 + + pat = pat./permute(repmat(binw,[1 size(pat,1) size(pat,2) size(pat,4)]),[2 3 1 4]); + pat = pat./max(max(max(pat))); + pat(pat<=1e-3) = 1e-3; + + mesu = shiftdim(pat(:,selected_chan,:,pulse),1); + +elseif get(handles.select_chan,'Value') == 0 + + mesu = handles.decay; + +end + +irf = handles.IRF(selected_chan,:,pulse).*handles.binw'; + +% generate initial values + +tmp = log10(mesu); +tmp = (tmp - min(tmp)); + +[M,I1] = max(tmp); +tmp(1:I1) = []; + +for i = 1:length(tmp) + if tmp(i) <= 3*M/4 + I2= I1 + i; + tmp(1:i)=[]; + break + end +end + +for i = 1:length(tmp) + if tmp(i) <= M/4 + I3= I2 + i; + tmp(1:i)=[]; + break + end +end + +for i = 1:length(tmp) + if tmp(i) == min(tmp) + I4 = I3 + i; + break + end +end + +tau1 = (tau(I2)-tau(I1))/(log(mesu(I1))-log(mesu(I2))); +tau2 = (tau(I4)-tau(I3))/(log(mesu(I3))-log(mesu(I4))); + +A = max(mesu); + +params = [(mesu(I1)),tau1,(mesu(I2)),tau2]; + +% Interpolation of tau to an aquidistant time array + +t = tau; + +res = diff([0 t]); + +t = 0.0:min(res):max(t); + +ind = zeros(size(tau)); +for k = 1:length(t) + for i = 1:length(tau) + if round(t(k)*1000)==round(tau(i)*1000) + ind(1,i) = k; + end + end +end + +% Convolution + +C = Faltung(params, irf, tau,t,ind); + +% Plot results + +axes(handles.axes4); +hold on +cla; + +plot(tau,log10(mesu(I1)*exp(-(tau-tau(I1))./tau1))) +plot(tau,log10(mesu(I3)*exp(-(tau-tau(I3))./tau2))) + +plot(tau,log10(C),'r') +plot(tau,log10(mesu),'.','LineWidth',2,'Color',... + handles.ROIcolor(selected_ROI,:)) +plot(tau(I1:I2),log10(mesu(I1:I2)),'-','LineWidth',2,'Color',... + 'y') +plot(tau(I3:I4),log10(mesu(I3:I4)),'-','LineWidth',2,'Color',... + 'g') + +hold off + +axis([0 floor(tau(end)) -3 0.1]) +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + +set(handles.edit1,'String', num2str(params(1))) +set(handles.edit2,'String', num2str(params(2))) +set(handles.edit3,'String', num2str(params(3))) +set(handles.edit4,'String', num2str(params(4))) + +guidata(hObject,handles); + + +% --- Executes on button press in copy_par. +function copy_par_Callback(hObject, eventdata, handles) +% hObject handle to copy_par (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + + +set(handles.edit5,'String',get(handles.edit1,'String')) +set(handles.edit6,'String',get(handles.edit2,'String')) +set(handles.edit7,'String',get(handles.edit3,'String')) +set(handles.edit8,'String',get(handles.edit4,'String')) + + +% --- Executes on button press in save_spec. +function save_spec_Callback(hObject, eventdata, handles) +% hObject handle to save_spec (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +spec = handles.spec; + +[FileName,PathName] = uiputfile({'*.txt','txt-files';... + '*.*','All Files' },'Save spectrum',... + 'newspectrum.txt'); +if FileName ~= 0 + %spec = interp1(lam, spec./M, ts,'cubic'); + save([PathName FileName], 'spec','-ascii'); +end + +guidata(hObject, handles); + + +% --- Executes on button press in create_pat. +function create_pat_Callback(hObject, eventdata, handles) +% hObject handle to create_pat (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +%First part: reading the relative intensity from a imported emission +%spectrum for each channel + +nch = handles.nch; +spec = handles.spec; + +lam = (handles.par_lam_start+handles.par_lam_step.*(0:nch-1)); + +M = zeros(length(lam),1); +%chan = []; + +for j = 1:length(lam) + for i = 1:length(spec(:,1)) + if spec(i,1) == lam(j) + if spec(i,2) > 1e-3 + M(j) = spec(i,2); + end + end + end +end + +A1 = str2double(get(handles.edit5,'String')); +tau1 = str2double(get(handles.edit6,'String')); +A2 = str2double(get(handles.edit7,'String')); +tau2 = str2double(get(handles.edit8,'String')); + +% Second Part: creating the Pattern + +% argin +%selected_chan = handles.channel; +binw = handles.binw; +tau = handles.taush; +taul = handles.tau; +nch = handles.nch; +%selected_ROI = handles.ROI; +par_num_PIE = handles.par_num_PIE; + +% vector for relative absorption coefficient + +if par_num_PIE == 1 + + pulse1 = repmat(str2double(get(handles.pulse1,'String')),[nch,length(tau)]); + + relInt = pulse1./max(pulse1,2); + + +elseif par_num_PIE == 2 + + pulse1 = repmat(str2double(get(handles.pulse1,'String')),[nch,length(tau)]); + pulse2 = repmat(str2double(get(handles.pulse2,'String')),[nch,length(tau)]); + + relInt = cat(2,pulse1,pulse2); + +elseif par_num_PIE == 3 + + pulse1 = repmat(str2double(get(handles.pulse1,'String')),[nch,length(tau)]); + pulse2 = repmat(str2double(get(handles.pulse2,'String')),[nch,length(tau)]); + pulse3 = repmat(str2double(get(handles.pulse3,'String')),[nch,length(tau)]); + + relInt = cat(2,pulse1,pulse2,pulse3); + +elseif par_num_PIE == 4 + + pulse1 = repmat(str2double(get(handles.pulse1,'String')),[nch,length(tau)]); + pulse2 = repmat(str2double(get(handles.pulse2,'String')),[nch,length(tau)]); + pulse3 = repmat(str2double(get(handles.pulse3,'String')),[nch,length(tau)]); + pulse4 = repmat(str2double(get(handles.pulse4,'String')),[nch,length(tau)]); + + relInt = cat(2,pulse1,pulse2,pulse3,pulse4); +end + +relInt = relInt./max(max(relInt)); + +if any(isnan(relInt)) + uiwait(errordlg('Please insert absorbtion coefficients')) +end + +% Interpolation of tau to an aquidistant time array +t = tau; +res = diff([0 t]); +t = 0.0:min(res):max(t); + +ind = zeros(size(tau)); +for k = 1:length(t) + for i = 1:length(tau) + if round(t(k)*1000)==round(tau(i)*1000) + ind(1,i) = k; + end + end +end + +% Pattern creation +pat = []; +for k = 1:par_num_PIE + C2 = []; + for i = 1:nch + irf = handles.IRF(i,:,par_num_PIE).*binw'; + params = [A1,tau1,A2,tau2]; + C1 = Pattern_Faltung(params,irf,tau,t,ind); + C1 = M(i).*C1/sum(C1,2); + C2 = cat(1,C2,C1); + end + pat = cat(2,pat,C2); +end + +pat = pat.*relInt; + + +handles.C = pat; + +% generation of a set of patterns varying one tau value from 'mint' to +% 'maxt' in 'no' steps + +if get(handles.varycheck, 'Value') == 1 + + no = str2double(get(handles.no_of_pat,'String')); + mint = str2double(get(handles.from,'String')); + maxt = str2double(get(handles.to,'String')); + step = (maxt-mint)/no; + FRETAmp = repmat(A2, [1 no+1]); + + if handles.match == 1 + vPara = mint + (0:no).*step; + if get(handles.vary1,'Value') == 1 + tau1 = vPara; + tau2 = repmat(tau2, [1, length(tau1)]); + elseif get(handles.vary2,'Value') == 1 + tau2 = vPara; + tau1 = repmat(tau1, [1, length(tau2)]); + end + elseif handles.match == 2 || handles.match == 3 + const = tau1*A1/(tau2*A2); + vPara = mint + (0:no).*step; + + tau2 = tau2.*(1-(vPara./100)); + tau1 = repmat(tau1, [1, length(tau2)]); + + if handles.match == 2 + FRETAmp = tau1.*repmat(A1,[1 no+1])./(const*tau2); + end + end + + %tau1.*A1./(tau2.*FRETAmp); + + handles.patfam = cell(1,no+2); + handles.patfam{end} = vPara; + patplot = cell(1,no+1); + + for n = 1:no+1 + pat = []; + for k = 1:par_num_PIE + C2 = []; + for i = 1:nch + irf = handles.IRF(i,:,par_num_PIE).*binw'; + params = [A1,tau1(n),FRETAmp(n), tau2(n)]; + C1 = Pattern_Faltung(params,irf,tau,t,ind); + C1 = M(i).*C1/sum(C1,2); + C2 = cat(1,C2,C1); + end + pat = cat(2,pat,C2); + end + + pat = pat.*relInt; + patplot{n} = pat; + + pat = pat.*permute(repmat(handles.binw,[handles.par_num_PIE size(pat,1)]),[2 1]); + pat = reshape(pat,[handles.nch,length(handles.taush),handles.par_num_PIE]); + + handles.patfam{n} = pat; + end + + axes(handles.axes5); + hold on + cla; + + for i = 1:no + pat = patplot{i}; + [~,I] = max(max(pat,[],2)); + plot(taul,log10(pat(I,:)),'r'); + end + + hold off + + axis([0 floor(taul(end)) -3 0.1]) + xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +else + axes(handles.axes5); + hold on + cla; + + [~,I] = max(max(pat,[],2)); + plot(taul,log10(pat(I,:)),'r'); + + hold off + + axis([0 floor(taul(end)) -3 0.1]) + xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); +end + + +guidata(hObject,handles) + + + +% --- Executes on button press in save_pat. +function save_pat_Callback(hObject, eventdata, handles) +% hObject handle to save_pat (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +pat = handles.C; + + +[FileName,PathName] = uiputfile({'*.pat','Pattern';'*.vpat','variable Pattern';... + '*.*','All Files'},'Save pattern',... + 'newpattern'); +if FileName ~= 0 + pat = pat.*permute(repmat(handles.binw,[handles.par_num_PIE size(pat,1)]),[2 1]); + pat = reshape(pat,[handles.nch,length(handles.taush),handles.par_num_PIE]); + if get(handles.varycheck, 'Value') == 1 + pat = {pat, handles.patfam, handles.match}; + end + save([PathName FileName], 'pat'); +end + +guidata(hObject, handles); + + +function pulse1_Callback(hObject, eventdata, handles) +% hObject handle to pulse1 (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 pulse1 as text +% str2double(get(hObject,'String')) returns contents of pulse1 as a double + + +% --- Executes during object creation, after setting all properties. +function pulse1_CreateFcn(hObject, eventdata, handles) +% hObject handle to pulse1 (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 pulse2_Callback(hObject, eventdata, handles) +% hObject handle to pulse2 (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 pulse2 as text +% str2double(get(hObject,'String')) returns contents of pulse2 as a double + + +% --- Executes during object creation, after setting all properties. +function pulse2_CreateFcn(hObject, eventdata, handles) +% hObject handle to pulse2 (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 pulse3_Callback(hObject, eventdata, handles) +% hObject handle to pulse3 (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 pulse3 as text +% str2double(get(hObject,'String')) returns contents of pulse3 as a double + + +% --- Executes during object creation, after setting all properties. +function pulse3_CreateFcn(hObject, eventdata, handles) +% hObject handle to pulse3 (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 pulse4_Callback(hObject, eventdata, handles) +% hObject handle to pulse4 (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 pulse4 as text +% str2double(get(hObject,'String')) returns contents of pulse4 as a double + + +% --- Executes during object creation, after setting all properties. +function pulse4_CreateFcn(hObject, eventdata, handles) +% hObject handle to pulse4 (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 selection change in popupmenu1. +function popupmenu1_Callback(hObject, eventdata, handles) +% hObject handle to popupmenu1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(handles.search, 'Value') == 1 + handles.fit = 1; +end + +tmp = get(hObject,'Value'); +if tmp ~= handles.ROI + handles.ROI = tmp; +end; + +guidata(hObject, handles); + +% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array +% contents{get(hObject,'Value')} returns selected item from popupmenu1 + + +% --- Executes during object creation, after setting all properties. +function popupmenu1_CreateFcn(hObject, eventdata, handles) +% hObject handle to popupmenu1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: popupmenu 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 selection change in popupmenu2. +function popupmenu2_Callback(hObject, eventdata, handles) +% hObject handle to popupmenu2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(handles.search, 'Value') == 1 + handles.fit = 1; +end + +tmp = get(hObject,'Value'); +if tmp ~= handles.channel + handles.channel = tmp; +end; + +guidata(hObject, handles); + +% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array +% contents{get(hObject,'Value')} returns selected item from popupmenu2 + + +% --- Executes during object creation, after setting all properties. +function popupmenu2_CreateFcn(hObject, eventdata, handles) +% hObject handle to popupmenu2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: popupmenu 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 selection change in popupmenu3. +function popupmenu3_Callback(hObject, eventdata, handles) +% hObject handle to popupmenu3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +tmp = get(hObject,'Value'); +if tmp ~= handles.pulse + handles.pulse = tmp; +end; + +guidata(hObject, handles); + +% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu3 contents as cell array +% contents{get(hObject,'Value')} returns selected item from popupmenu3 + + +% --- Executes during object creation, after setting all properties. +function popupmenu3_CreateFcn(hObject, eventdata, handles) +% hObject handle to popupmenu3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: popupmenu 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 selection change in popupmenu6. +function popupmenu6_Callback(hObject, eventdata, handles) +% hObject handle to popupmenu6 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +handles.match = get(hObject, 'Value'); + +tmp = get(hObject,'Value'); +if tmp == 1 + set(handles.text47, 'String','no. of tau values') + set(handles.text49, 'String', 'ns to ') + set(handles.text50, 'String', 'ns') + set(handles.vary2, 'Enable', 'on') + set(handles.vary1, 'Enable', 'on') +else + set(handles.text47, 'String','no. of FRET Eff. values') + set(handles.text49, 'String', '% to ') + set(handles.text50, 'String', '%') + set(handles.from, 'String', '30') + set(handles.to, 'String', '80') + set(handles.vary2, 'Value', 1) + set(handles.vary2, 'Enable', 'off') + set(handles.vary1, 'Value', 0) + set(handles.vary1, 'Enable', 'off') +end + +guidata(hObject, handles); + +% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu6 contents as cell array +% contents{get(hObject,'Value')} returns selected item from popupmenu6 + + +% --- Executes during object creation, after setting all properties. +function popupmenu6_CreateFcn(hObject, eventdata, handles) +% hObject handle to popupmenu6 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: popupmenu 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 search. +function search_Callback(hObject, eventdata, handles) +% hObject handle to search (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(hObject,'Value') == 1 + handles.fit = 1; +elseif get(hObject,'Value') == 0 + handles.fit = 0; +end + +guidata(hObject, handles); + +% Hint: get(hObject,'Value') returns toggle state of search + + +% --- Executes on button press in select_chan. +function select_chan_Callback(hObject, eventdata, handles) +% hObject handle to select_chan (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +handles.fit = 1; + +if get(hObject,'Value') == 1 + set(handles.popupmenu2,'Enable', 'on') +elseif get(hObject,'Value') == 0 + set(handles.popupmenu2,'Enable','off') +end + +guidata(hObject,handles); +% Hint: get(hObject,'Value') returns toggle state of select_chan + + +% --- Executes on button press in checkbox2. +function checkbox2_Callback(hObject, eventdata, handles) +% hObject handle to checkbox2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox2 + + +% --- Executes on button press in checkbox3. +function checkbox3_Callback(hObject, eventdata, handles) +% hObject handle to checkbox3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox3 + + +% --- Executes on button press in checkbox4. +function checkbox4_Callback(hObject, eventdata, handles) +% hObject handle to checkbox4 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox4 + + +% --- Executes on button press in checkbox5. +function checkbox5_Callback(hObject, eventdata, handles) +% hObject handle to checkbox5 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox5 + + +function edit1_Callback(hObject, eventdata, handles) +% hObject handle to edit1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(handles.search, 'Value') == 1 + handles.fit = 1; +end + +guidata(hObject, handles); + +% Hints: get(hObject,'String') returns contents of edit1 as text +% str2double(get(hObject,'String')) returns contents of edit1 as a double + + +% --- Executes during object creation, after setting all properties. +function edit1_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit1 (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 edit2_Callback(hObject, eventdata, handles) +% hObject handle to edit2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(handles.search, 'Value') == 1 + handles.fit = 1; +end + +guidata(hObject, handles); + +% Hints: get(hObject,'String') returns contents of edit2 as text +% str2double(get(hObject,'String')) returns contents of edit2 as a double + + +% --- Executes during object creation, after setting all properties. +function edit2_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit2 (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 edit3_Callback(hObject, eventdata, handles) +% hObject handle to edit3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(handles.search, 'Value') == 1 + handles.fit = 1; +end + +guidata(hObject, handles); + +% Hints: get(hObject,'String') returns contents of edit3 as text +% str2double(get(hObject,'String')) returns contents of edit3 as a double + + +% --- Executes during object creation, after setting all properties. +function edit3_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit3 (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 edit4_Callback(hObject, eventdata, handles) +% hObject handle to edit4 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(handles.search, 'Value') == 1 + handles.fit = 1; +end + +guidata(hObject, handles); + +% Hints: get(hObject,'String') returns contents of edit4 as text +% str2double(get(hObject,'String')) returns contents of edit4 as a double + + +% --- Executes during object creation, after setting all properties. +function edit4_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit4 (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 edit5_Callback(hObject, eventdata, handles) +% hObject handle to edit5 (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 edit5 as text +% str2double(get(hObject,'String')) returns contents of edit5 as a double + + +% --- Executes during object creation, after setting all properties. +function edit5_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit5 (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 edit6_Callback(hObject, eventdata, handles) +% hObject handle to edit6 (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 edit6 as text +% str2double(get(hObject,'String')) returns contents of edit6 as a double + + +% --- Executes during object creation, after setting all properties. +function edit6_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit6 (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 edit7_Callback(hObject, eventdata, handles) +% hObject handle to edit7 (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 edit7 as text +% str2double(get(hObject,'String')) returns contents of edit7 as a double + + +% --- Executes during object creation, after setting all properties. +function edit7_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit7 (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 edit8_Callback(hObject, eventdata, handles) +% hObject handle to edit8 (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 edit8 as text +% str2double(get(hObject,'String')) returns contents of edit8 as a double + + +% --- Executes during object creation, after setting all properties. +function edit8_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit8 (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 varycheck. +function varycheck_Callback(hObject, eventdata, handles) +% hObject handle to varycheck (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if get(hObject, 'Value') == 1 + set(handles.vary1, 'Enable', 'on'); + set(handles.vary2, 'Enable', 'on'); + set(handles.no_of_pat, 'Enable', 'on'); + set(handles.from, 'Enable', 'on'); + set(handles.to, 'Enable', 'on'); + set(handles.popupmenu6, 'Enable', 'on') + handles.match = get(handles.popupmenu6, 'Value'); +elseif get (hObject, 'Value') == 0 + set(handles.vary1, 'Enable', 'off'); + set(handles.vary2, 'Enable', 'off'); + set(handles.no_of_pat, 'Enable', 'off'); + set(handles.from, 'Enable', 'off'); + set(handles.to, 'Enable', 'off'); + set(handles.popupmenu6, 'Enable', 'off') +end + +guidata(hObject, handles); + + +% Hint: get(hObject,'Value') returns toggle state of varycheck + + +% --- Executes on button press in checkbox7. +function checkbox7_Callback(hObject, eventdata, handles) +% hObject handle to checkbox7 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox7 + + +% --- Executes on button press in checkbox8. +function checkbox8_Callback(hObject, eventdata, handles) +% hObject handle to checkbox8 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox8 + + +% --- Executes on button press in checkbox9. +function checkbox9_Callback(hObject, eventdata, handles) +% hObject handle to checkbox9 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox9 + + +% --- Executes on button press in checkbox10. +function checkbox10_Callback(hObject, eventdata, handles) +% hObject handle to checkbox10 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of checkbox10 + + +% --- Executes on button press in in_spec. +function in_spec_Callback(hObject, eventdata, handles) +% hObject handle to in_spec (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of in_spec + + +% --- Executes on button press in ex_spec. +function ex_spec_Callback(hObject, eventdata, handles) +% hObject handle to ex_spec (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of ex_spec + +% --- Executes on button press in in_spec. +function vary1_Callback(hObject, eventdata, handles) +% hObject handle to in_spec (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of in_spec + + +% --- Executes on button press in ex_spec. +function vary2_Callback(hObject, eventdata, handles) +% hObject handle to ex_spec (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hint: get(hObject,'Value') returns toggle state of ex_spec + + +function wave1_Callback(hObject, eventdata, handles) +% hObject handle to wave1 (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 wave1 as text +% str2double(get(hObject,'String')) returns contents of wave1 as a double + + +% --- Executes during object creation, after setting all properties. +function wave1_CreateFcn(hObject, eventdata, handles) +% hObject handle to wave1 (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 wave2_Callback(hObject, eventdata, handles) +% hObject handle to wave2 (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 wave2 as text +% str2double(get(hObject,'String')) returns contents of wave2 as a double + + +% --- Executes during object creation, after setting all properties. +function wave2_CreateFcn(hObject, eventdata, handles) +% hObject handle to wave2 (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 wave3_Callback(hObject, eventdata, handles) +% hObject handle to wave3 (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 wave3 as text +% str2double(get(hObject,'String')) returns contents of wave3 as a double + + +% --- Executes during object creation, after setting all properties. +function wave3_CreateFcn(hObject, eventdata, handles) +% hObject handle to wave3 (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 wave4_Callback(hObject, eventdata, handles) +% hObject handle to wave4 (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 wave4 as text +% str2double(get(hObject,'String')) returns contents of wave4 as a double + + +% --- Executes during object creation, after setting all properties. +function wave4_CreateFcn(hObject, eventdata, handles) +% hObject handle to wave4 (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 no_of_pat_Callback(hObject, eventdata, handles) +% hObject handle to no_of_pat (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(hObject, 'String', num2str(round(str2num(get(hObject, 'String'))))); + +% Hints: get(hObject,'String') returns contents of no_of_pat as text +% str2double(get(hObject,'String')) returns contents of no_of_pat as a double + + +% --- Executes during object creation, after setting all properties. +function no_of_pat_CreateFcn(hObject, eventdata, handles) +% hObject handle to no_of_pat (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 from_Callback(hObject, eventdata, handles) +% hObject handle to from (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 from as text +% str2double(get(hObject,'String')) returns contents of from as a double + + +% --- Executes during object creation, after setting all properties. +function from_CreateFcn(hObject, eventdata, handles) +% hObject handle to from (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 to_Callback(hObject, eventdata, handles) +% hObject handle to to (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 to as text +% str2double(get(hObject,'String')) returns contents of to as a double + + +% --- Executes during object creation, after setting all properties. +function to_CreateFcn(hObject, eventdata, handles) +% hObject handle to to (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 + + + + +%% Convolution of IRF and a double exponential decay + +function [C] = Faltung(params, irf, tau, t, ind) + +A1 = params(1); +tau1 = params(2); +if tau1 == 0 + tau1 = 1; +end +A2 = params(3); +tau2 = params(4); +if tau2 == 0 + tau2 = 1; +end +% The IRF is interpolated and normalized + +tau(end+1) = 0; +tau = circshift(tau,1); +irf(end+1) = min(irf); +irf = circshift(irf,1); + +irf = interp1(tau,irf,t); +irf = irf./sum(irf); + +% Computes a exponential decay function. + +decay = A1*exp(-t./tau1) + A2*exp(-t./tau2); + +%max(decay) + +% Calculates the convolution of irf and decay adding an offset + +C = conv(irf, decay); + +%max(C) + +tmp = []; +for i = ind + tmp(end+1) = C(i); +end +C = tmp; + +%C = C*ind; +%C(0) = []; + +C(C<=1e-3) = 1e-3; % einziger Unterschied zu Pattern_Faltung + +%% Convolution of IRF and a double exponential decay + +function [C] = Pattern_Faltung(params, irf, tau, t, ind) + +A1 = params(1); +tau1 = params(2); +if tau1 == 0 + tau1 = 1; +end +A2 = params(3); +tau2 = params(4); +if tau2 == 0 + tau2 = 1; +end + +% The IRF is interpolated and normalized + +tau(end+1) = 0; +tau = circshift(tau,1); +irf(end+1) = min(irf); +irf = circshift(irf,1); + +irf = interp1(tau,irf,t); +irf = irf./sum(irf); + +% Computes a exponential decay function. + +decay = A1*exp(-t./tau1) + A2*exp(-t./tau2); +%max(decay) + +% Calculates the convolution of irf and decay adding an offset + +C = conv(irf, decay); +%max(C) + +tmp = []; +for i = ind + tmp(end+1) = C(i); +end +C = tmp; diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Patternfit.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Patternfit.m new file mode 100644 index 0000000..a66602d --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Patternfit.m @@ -0,0 +1,131 @@ +function [c, offset, A, tau, dc, dtau, irs, zz, t, chi] = Patternfit(irf, y, p, dt, tau, lim) +% The function PATTERNFIT performs a fit of a multi-exponential decay curve. +% It is called by: +% [c, offset, A, tau, dc, doffset, dtau, irs, z, t, chi] = Patternfit(irf, y, p, dt, tau, limits, init). +% The function arguments are: +% irf = Instrumental Response Function +% y = Fluorescence decay data +% p = Time between laser exciation pulses (in nanoseconds) +% dt = Time width of one TCSPC channel (in nanoseconds) +% tau = Initial guess times +% lim = limits for the lifetimes guess times +% +% The return parameters are: +% c = Color Shift (time shift of the IRF with respect to the fluorescence curve) +% offset = Offset +% A = Amplitudes of the different decay components +% tau = Decay times of the different decay components +% dc = Color shift error +% doffset = Offset error +% dtau = Decay times error +% irs = IRF, shifted by the value of the colorshift +% zz Fitted fluorecence component curves +% t = time axis +% chi = chi2 value +% +% The program needs the following m-files: simplex.m, lsfit.m, mlfit.m, and convol.m. +% (c) 1996 Jörg Enderlein + + +fitfun = 'lsfit'; + +close all +irf = irf(:); +offset = 0; +y = y(:); + +w = round(diff([0 dt])./(dt(2)-dt(1))); +t1 = find(diff(w)); +t2 = find(diff(t1)==1); +w(t1(t2)+1)= w(t1(t2)+2); + +dt = dt(:)-dt(1); + +if (nargin<6)||isempty(lim) + lim = [zeros(1,length(tau)) 6.*ones(1,length(tau))]; +end; + +timeunit = min(diff(dt)); + +p = round(p/timeunit); +tp = (dt./timeunit); +tpp = (0:p-1)'; +ind = 1+intersect(round(tpp),round(tp)); + +tau = tau(:)'/timeunit; +lim_min = lim(1:numel(tau))./timeunit; +lim_max = lim(numel(tau)+1:end)./timeunit; + +[err, A, z] = dlsfit([0 tau], tp, irf, y, p); + +close all + +param = [0; tau']; +paramin = [-1/timeunit lim_min]; +paramax = [ 1/timeunit lim_max]; + +tmp = param; +k = numel(param); +err = 0; + +for casc=1:10 + [ts, s] = min(err); + r0 = tmp(:, s); + dlsfit(r0, tp, irf, y, p, 1); + drawnow; + for sub=1:10 + rf = r0.*[(2.^(1.2*(rand(k,1)-0.5)./casc))]; % randomize start values + tmp(:,sub) = Simplex('dlsfit',rf,paramin,paramax,[],[], tp, irf, y, p); + err(sub) = dlsfit(tmp(:,sub), tp, irf, y, p); + end +end + +param = mean(tmp(:,err==min(err)),2); +[err, A, z] = dlsfit(param, tp, irf, y, p, 1); + +[param, dparam] = Simplex('dlsfit', param, paramin, paramax, [], [], tp, irf, y, p, 1); +c = param(1); +dc = dparam(1); +tau = param(2:length(param))'; +dtau = dparam(2:length(param)); + +chi = sum((y1-z).^2./abs(z))/(n-m); +t = timeunit*t; +tau = timeunit*tau'; +c = timeunit*c; +offset = zz(1,1); +A(1) = []; + +hold off +subplot('position',[0.1 0.4 0.8 0.5]) +plot(t,log10(y1),t,log10(irs),t,log10(z)); +v = axis; +v(1) = min(t); +v(2) = max(t); +axis(v); +xlabel('Time in ns'); +ylabel('Log Count'); +s = sprintf('COF = %3.3f %3.3f', c, offset); +text(max(t)/2,v(4)-0.05*(v(4)-v(3)),s); +s = ['AMP = ']; +for i=1:length(A) + s = [s sprintf('%1.3f',A(i)/sum(A)) ' ']; +end +text(max(t)/2,v(4)-0.12*(v(4)-v(3)),s); +s = ['TAU = ']; +for i=1:length(tau) + s = [s sprintf('%3.3f',tau(i)) ' ']; +end +text(max(t)/2,v(4)-0.19*(v(4)-v(3)),s); +subplot('position',[0.1 0.1 0.8 0.2]) +plot(t,(y1-z)./sqrt(abs(z))); +v = axis; +v(1) = min(t); +v(2) = max(t); + +axis(v); +xlabel('Time in ns'); +ylabel('Residue'); +s = sprintf('%3.3f', chi); +text(max(t)/2,v(4)-0.1*(v(4)-v(3)),['\chi^2 = ' s]); +set(gcf,'units','normalized','position',[0.01 0.05 0.98 0.83]) diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Plot_UnmixingResults.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Plot_UnmixingResults.m new file mode 100644 index 0000000..72a2079 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Plot_UnmixingResults.m @@ -0,0 +1,29 @@ +function [im] = Plot_UnmixingResults() +%% +% The function allows user to plot the results already availbale + +load('List.mat','list'); +[filename, pathname] = uigetfile({'*results.mat','Results File (*results.mat)'}, 'Pick a Results file'); +A = load([pathname filename]); +%% +num_pattern = size(A.results.amp,3) - 1; +num_px = size(A.results.amp,1); +num_py = size(A.results.amp,2); +%% Composite image with tools vary + +im = MakeComposite('data',A.results.amp(:,:,1:num_pattern)); +name = sprintf('Composite Image'); +figure_handle = figure; +set(figure_handle,'Name',name,'NumberTitle','off'); +hold on; +cla; + +image(num_px , num_py,reshape(im,[num_px num_py 3])); +title(name); +set(gca,'DataAspectRatio', [1,1,1],'PlotBoxAspectRatio',[1 1 1],'XDir','normal','YDir','reverse'); +xlabel('x (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('y (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); +hold off + + +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Process_file.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Process_file.m new file mode 100644 index 0000000..e6fd66a --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Process_file.m @@ -0,0 +1,355 @@ +function Process_file(name, IRFname) + +tmp = strfind(name,'\'); +pathname = name(1:tmp(end)); + +names = dir(name); + +for k = 1:numel(names) + + fname = names(k).name; + load('Get_Params.mat'); + + IRF = []; + timegate = []; + + if (nargin>1)&&(~isempty(IRFname)) + [IRF, timegate] = IRF_Read(IRFname, num_PIE); + end + + [head, tag, tcspc, tcspc_x, tcspc_y, DC, AP] = MT_ScanRead([pathname fname], num_PIE, BG_AP, timegate); + +% save([pathname fname(1:end-4) '_MT_ScanRead_output.mat'], 'tcspc','tag','tcspc_x','tcspc_y','DC','AP','-v7.3'); + + if (BG_corr == 0) % ignore bg + + DC = zeros(size(DC)); + AP = zeros(size(AP)); + + elseif (BG_corr == 1) % take bg data from specified file + + tmp = dir([BG_file(1:end-4) '_DATA.mat']); + + if (numel(tmp)==0) + [dummy, dummy, dummy, dummy, dummy, DC, AP] = MT_ScanRead(BG_file, num_PIE, BG_AP, timegate); + else + load([BG_file(1:end-4) '_DATA.mat'],'DC','AP'); + end + + end + + if ~isempty(head) + if isempty(IRF) + IRF = Calc_mIRF(head, tcspc); + end + + maxres = max([head.Resolution]); + Resolution = max([maxres 0.032]); + + nx = head.ImgHdr.PixX; + ny = head.ImgHdr.PixY; + nch = size(tcspc,1); + nbin = min([size(tcspc,2) size(IRF,2)]); + nPIE = size(tcspc,3); + + mp = ceil(1.05./Resolution); % Goal is to shift this maximum to 1.0 ns + + numch = zeros(nch, nPIE); + + for ch = 1:nch + tmp1 = shiftdim(IRF(ch, :, :)); + tmp2 = shiftdim(tcspc(ch, :, :)); + + for PIE = 1:nPIE + [m0,m0] = min(abs(cumsum(tmp1(:,PIE)) - sum(tmp1(:,PIE))/2)); + numch(ch, PIE) = mp-m0; + if numch(ch, PIE) > 0 % we need to add channels to the front + if PIE == 1 + IRF(ch,:,PIE) = [tmp1(end-numch(ch, PIE)+1:end,end ); tmp1(1:end-numch(ch, PIE),PIE)]; + tcspc(ch,:,PIE) = [tmp2(end-numch(ch, PIE)+1:end,end ); tmp2(1:end-numch(ch, PIE),PIE)]; + else + IRF(ch,:,PIE) = [tmp1(end-numch(ch, PIE)+1:end,PIE-1); tmp1(1:end-numch(ch, PIE),PIE)]; + tcspc(ch,:,PIE) = [tmp2(end-numch(ch, PIE)+1:end,PIE-1); tmp2(1:end-numch(ch, PIE),PIE)]; + end + else % we need to add channels to the back + if PIE == nPIE + IRF(ch,:,PIE) = [tmp1(abs(numch(ch, PIE))+1:end,PIE); tmp1(1:abs(numch(ch, PIE)),1)]; + tcspc(ch,:,PIE) = [tmp2(abs(numch(ch, PIE))+1:end,PIE); tmp2(1:abs(numch(ch, PIE)),1)]; + else + IRF(ch,:,PIE) = [tmp1(abs(numch(ch, PIE))+1:end,PIE); tmp1(1:abs(numch(ch, PIE)),PIE+1)]; + tcspc(ch,:,PIE) = [tmp2(abs(numch(ch, PIE))+1:end,PIE); tmp2(1:abs(numch(ch, PIE)),PIE+1)]; + end + end + + for rx = 1:nx + tmp3 = shiftdim(tcspc_x(rx,ch,:,:),2); + if numch(ch, PIE) > 0 % we need to add channels to the front + if PIE == 1 + tcspc_x(rx,ch,:,PIE) = [tmp3(end-numch(ch, PIE)+1:end,end ); tmp3(1:end-numch(ch, PIE),PIE)]; + else + tcspc_x(rx,ch,:,PIE) = [tmp3(end-numch(ch, PIE)+1:end,PIE-1); tmp3(1:end-numch(ch, PIE),PIE)]; + end + else % we need to add channels to the back + if PIE == nPIE + tcspc_x(rx,ch,:,PIE) = [tmp3(abs(numch(ch, PIE))+1:end,PIE); tmp3(1:abs(numch(ch, PIE)),1)]; + else + tcspc_x(rx,ch,:,PIE) = [tmp3(abs(numch(ch, PIE))+1:end,PIE); tmp3(1:abs(numch(ch, PIE)),PIE+1)]; + end + end + end + for ry = 1:ny + tmp3 = shiftdim(tcspc_y(ry,ch,:,:),2); + if numch(ch, PIE) > 0 % we need to add channels to the front + if PIE == 1 + tcspc_y(ry,ch,:,PIE) = [tmp3(end-numch(ch, PIE)+1:end,end ); tmp3(1:end-numch(ch, PIE),PIE)]; + else + tcspc_y(ry,ch,:,PIE) = [tmp3(end-numch(ch, PIE)+1:end,PIE-1); tmp3(1:end-numch(ch, PIE),PIE)]; + end + else % we need to add channels to the back + if PIE == nPIE + tcspc_y(ry,ch,:,PIE) = [tmp3(abs(numch(ch, PIE))+1:end,PIE); tmp3(1:abs(numch(ch, PIE)),1)]; + else + tcspc_y(ry,ch,:,PIE) = [tmp3(abs(numch(ch, PIE))+1:end,PIE); tmp3(1:abs(numch(ch, PIE)),PIE+1)]; + end + end + end + + end + end + + % for pulse = 1:num_PIE + % for ch = 1:nch + % IRF(ch,:,pulse) = IRF(ch,:,pulse) - mean(IRF(ch,1:(mp-10),pulse),2); + % end + % end + IRF(IRF<0) = 0; + IRF = IRF./repmat(sum(IRF,2),[1 size(IRF,2) 1]); + KRF = IRF; + + c_t = shiftdim(sum(permute(tcspc,[2 1 3]),1),1); % tcspc : [nch nbin num_PIE] + + aAP = 1+AP; + + BG = c_t - (c_t - repmat(DC(:).*nx.*ny, [1 num_PIE]))./repmat(aAP(:), [1 num_PIE]); + BG = permute(repmat(BG, [1 1 nbin]), [1 3 2]); + + tcspc = tcspc - BG; + tcspc(tcspc<=0) = 1e-5; + + % rebin the time axis to compress data + + t0 = 0.032; + tbin = round(t0/Resolution); + if tbin<1 + tbin = 1; + t0 = Resolution; + end + + m0 = mp; + m1 = 8+ceil(m0/tbin); + t1 = t0; + t2 = (1:m1).*t1; + + M0 = permute(IRF, [2 1 3]); + M1 = M0; + + if tbin>1 + ne = floor(nbin/tbin)*tbin; + M1 = reshape(M0(1:ne,:,:), tbin, ne/tbin, nch, nPIE); + M1 = shiftdim(mean(M1),1); + end + M0(1:m1,:,:,:) = M1(1:m1,:,:,:); + m2 = m1; + + while size(M1,1)>m2+1 + M1 = M1(m2+1:end,:,:,:); + ne = floor(size(M1,1)/2)*2; + M1 = reshape(M1(1:ne,:,:,:), 2, ne/2, nch, nPIE); + M1 = shiftdim(mean(M1,1),1); + + m2 = min([8 size(M1,1)]); + M0(m1+(1:m2),:,:,:) = M1(1:m2,:,:,:); + m1 = m1+m2; + t1 = t1*2; + t2 = [t2 t2(end)+(1:m2)*t1]; + end + + IRF = permute(M0(1:m1,:,:), [2 1 3]); + + clear M0 M1 + + M0 = permute(tcspc, [2 1 3]); + M1 = M0; + + m1 = 8+ceil(m0/tbin); + t1 = t0; + t2 = (1:m1).*t1; + + if tbin>1 + ne = floor(nbin/tbin)*tbin; + M1 = reshape(M0(1:ne,:,:), tbin, ne/tbin, nch, nPIE); + M1 = shiftdim(mean(M1),1); + end + M0(1:m1,:,:,:) = M1(1:m1,:,:,:); + m2 = m1; + + while size(M1,1)>m2+1 + M1 = M1(m2+1:end,:,:,:); + ne = floor(size(M1,1)/2)*2; + M1 = reshape(M1(1:ne,:,:,:), 2, ne/2, nch, nPIE); + M1 = shiftdim(mean(M1,1),1); + + m2 = min([8 size(M1,1)]); + M0(m1+(1:m2),:,:,:) = M1(1:m2,:,:,:); + m1 = m1+m2; + t1 = t1*2; + t2 = [t2 t2(end)+(1:m2)*t1]; + end + + tcspc = permute(M0(1:m1,:,:), [2 1 3]); + clear M0 M1 + + head.tauw = diff([0 t2]); + head.tau = t2 - diff([0 t2])/2; + head.m0 = m0; + + save([pathname fname(1:end-4) '_DATA.mat'], 'head', 'tag', 'tcspc', 'IRF', 'KRF', 'AP', 'DC'); + + if isempty(dir([pathname fname(1:end-4) '_FLIM.dat'])) + + load([pathname fname(1:end-4) '_FLIM.mat'],'tim') + + c_t = permute(sum(tim,4),[1 2 3 5 4]); % c_t : [ny nx nch num_PIE] + + BG = c_t - (c_t - permute(repmat(DC(:), [1 ny nx num_PIE]),[2 3 1 4]))./permute(repmat(aAP(:), [1 ny nx num_PIE]),[2 3 1 4]); + BG = permute(repmat(BG, [1 1 1 1 nbin]), [1 2 3 5 4]); + + tim = tim - BG; + + clear BG; + + tim(tim<0) = 0; + + tim = permute(tim, [4 1 2 3 5]); % M0 : nbin ny nx nch num_PIE + + for ch = 1:nch + tmp = squeeze(tim(:, :, :, ch, :)); + for PIE = 1:nPIE + if numch(ch, PIE) > 0 % we need to add channels to the front + if PIE == 1 + tim(:,:,:,ch,PIE) = [tmp(end-numch(ch, PIE)+1:end,:,:,end ); tmp(1:end-numch(ch, PIE),:,:,PIE)]; + else + tim(:,:,:,ch,PIE) = [tmp(end-numch(ch, PIE)+1:end,:,:,PIE-1); tmp(1:end-numch(ch, PIE),:,:,PIE)]; + end + else % we need to add channels to the back + if PIE == nPIE + tim(:,:,:,ch,PIE) = [tmp(abs(numch(ch, PIE))+1:end,:,:,PIE); tmp(1:abs(numch(ch, PIE)),:,:,1)]; + else + tim(:,:,:,ch,PIE) = [tmp(abs(numch(ch, PIE))+1:end,:,:,PIE); tmp(1:abs(numch(ch, PIE)),:,:,PIE+1)]; + end + end + end + end + + m1 = 8+ceil(m0/tbin); + + M1 = tim; + if tbin>1 + ne = floor(nbin/tbin)*tbin; + M1 = reshape(tim(1:ne,:,:,:), tbin, ne/tbin, nch, nPIE); + M1 = shiftdim(mean(M1)); + end + tim(1:m1,:,:,:,:) = M1(1:m1,:,:,:,:); + m2 = m1; + + while size(M1,1)>m2+1 + M1 = M1(m2+1:end,:,:,:,:); + ne = floor(size(M1,1)/2)*2; + M1 = reshape(M1(1:ne,:,:,:,:), 2, ne/2, ny, nx, nch, num_PIE); + M1 = shiftdim(sum(M1),1); + + m2 = min([8 size(M1,1)]); + tim(m1+(1:m2),:,:,:,:) = M1(1:m2,:,:,:,:); + m1 = m1+m2; + end + + stim = permute(tim(1:m1,:,:,:), [2 3 4 1 5]); % stim : ny nx nch nbin num_PIE + + clear tim M1 + + else + num = nx*nch*nbin*num_PIE; + + fid1 = fopen([pathname fname(1:end-4) '_FLIM.dat'],'r'); + + stim = zeros(ny, nx, nch, size(tcspc,2), num_PIE); + + for a = 1:ny + tim = fread(fid1, num, 'uint16'); + tim = reshape(tim, [nx nch nbin num_PIE]); + + c_t = shiftdim(sum(permute(tim,[3 1 2 4]),1)); % c_t : [nx nch num_PIE] + + BG = c_t - (c_t - permute(repmat(DC(:), [1 nx num_PIE]),[2 1 3]))./permute(repmat(aAP(:), [1 nx num_PIE]),[2 1 3]); + BG = permute(repmat(BG, [1 1 1 nbin]), [1 2 4 3]); + + tim = tim - BG; + tim(tim<0) = 0; + + M0 = permute(tim, [3 1 2 4]); % M0 : nbin nx nch num_PIE + + for ch = 1:nch + tmp = squeeze(M0(:, :, ch, :)); + for PIE = 1:nPIE + if numch(ch, PIE) > 0 % we need to add channels to the front + if PIE == 1 + M0(:,:,ch,PIE) = [tmp(end-numch(ch, PIE)+1:end,:,end ); tmp(1:end-numch(ch, PIE),:,PIE)]; + else + M0(:,:,ch,PIE) = [tmp(end-numch(ch, PIE)+1:end,:,PIE-1); tmp(1:end-numch(ch, PIE),:,PIE)]; + end + else % we need to add channels to the back + if PIE == nPIE + M0(:,:,ch,PIE) = [tmp(abs(numch(ch, PIE))+1:end,:,PIE); tmp(1:abs(numch(ch, PIE)),:,1)]; + else + M0(:,:,ch,PIE) = [tmp(abs(numch(ch, PIE))+1:end,:,PIE); tmp(1:abs(numch(ch, PIE)),:,PIE+1)]; + end + end + end + end + + m1 = 8+ceil(m0/tbin); + + M1 = M0; + if tbin>1 + ne = floor(nbin/tbin)*tbin; + M1 = reshape(M0(1:ne,:,:), tbin, ne/tbin, nch, nPIE); + M1 = shiftdim(mean(M1)); + end + M0(1:m1,:,:,:) = M1(1:m1,:,:,:); + m2 = m1; + + while size(M1,1)>m2+1 + M1 = M1(m2+1:end,:,:,:); + ne = floor(size(M1,1)/2)*2; + M1 = reshape(M1(1:ne,:,:,:), 2, ne/2, nx, nch, num_PIE); + M1 = shiftdim(sum(M1),1); + + m2 = min([8 size(M1,1)]); + M0(m1+(1:m2),:,:,:) = M1(1:m2,:,:,:); + m1 = m1+m2; + end + stim(a,:,:,:,:) = permute(M0(1:m1,:,:,:), [2 3 1 4]); % stim : nx nch nbin num_PIE + end + + fclose(fid1); + delete([pathname fname(1:end-4) '_FLIM.dat']); + end + + save([pathname fname(1:end-4) '_FLIM.mat'], 'stim', '-v7.3'); + + clear head tag tcspc IRF stim + + end +end + +clear all; diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Read_PTU_MultiHarp.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Read_PTU_MultiHarp.m new file mode 100644 index 0000000..c1e5760 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Read_PTU_MultiHarp.m @@ -0,0 +1,487 @@ +function Read_PTU % Read PicoQuant Unified TTTR Files +% This is demo code. Use at your own risk. No warranties. +% Marcus Sackrow, PicoQuant GmbH, December 2013 +% Peter Kapusta, PicoQuant GmbH, November 2016 +% Edited script: text output formatting changed by KAP. + +% Note that marker events have a lower time resolution and may therefore appear +% in the file slightly out of order with respect to regular (photon) event records. +% This is by design. Markers are designed only for relatively coarse +% synchronization requirements such as image scanning. + +% T Mode data are written to an output file [filename].out +% We do not keep it in memory because of the huge amout of memory +% this would take in case of large files. Of course you can change this, +% e.g. if your files are not too big. +% Otherwise it is best process the data on the fly and keep only the results. + +% All HeaderData are introduced as Variable to Matlab and can directly be +% used for further analysis + + clear all; + clc; + % some constants + tyEmpty8 = hex2dec('FFFF0008'); + tyBool8 = hex2dec('00000008'); + tyInt8 = hex2dec('10000008'); + tyBitSet64 = hex2dec('11000008'); + tyColor8 = hex2dec('12000008'); + tyFloat8 = hex2dec('20000008'); + tyTDateTime = hex2dec('21000008'); + tyFloat8Array = hex2dec('2001FFFF'); + tyAnsiString = hex2dec('4001FFFF'); + tyWideString = hex2dec('4002FFFF'); + tyBinaryBlob = hex2dec('FFFFFFFF'); + % RecordTypes + rtPicoHarpT3 = hex2dec('00010303');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $03 (PicoHarp) + rtPicoHarpT2 = hex2dec('00010203');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $03 (PicoHarp) + rtHydraHarpT3 = hex2dec('00010304');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $04 (HydraHarp) + rtHydraHarpT2 = hex2dec('00010204');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $04 (HydraHarp) + rtHydraHarp2T3 = hex2dec('01010304');% (SubID = $01 ,RecFmt: $01) (V2), T-Mode: $03 (T3), HW: $04 (HydraHarp) + rtHydraHarp2T2 = hex2dec('01010204');% (SubID = $01 ,RecFmt: $01) (V2), T-Mode: $02 (T2), HW: $04 (HydraHarp) + rtTimeHarp260NT3 = hex2dec('00010305');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $05 (TimeHarp260N) + rtTimeHarp260NT2 = hex2dec('00010205');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $05 (TimeHarp260N) + rtTimeHarp260PT3 = hex2dec('00010306');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $06 (TimeHarp260P) + rtTimeHarp260PT2 = hex2dec('00010206');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $06 (TimeHarp260P) + rtMultiHarpNT3 = hex2dec('00010307');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $03 (T3), HW: $07 (MultiHarp150N) + rtMultiHarpNT2 = hex2dec('00010207');% (SubID = $00 ,RecFmt: $01) (V1), T-Mode: $02 (T2), HW: $07 (MultiHarp150N) + + % Globals for subroutines + global fid + global TTResultFormat_TTTRRecType; + global TTResult_NumberOfRecords; % Number of TTTR Records in the File; + global MeasDesc_Resolution; % Resolution for the Dtime (T3 Only) + global MeasDesc_GlobalResolution; + + TTResultFormat_TTTRRecType = 0; + TTResult_NumberOfRecords = 0; + MeasDesc_Resolution = 0; + MeasDesc_GlobalResolution = 0; + + % start Main program + [filename, pathname]=uigetfile('*.ptu', 'T-Mode data:'); + fid=fopen([pathname filename]); + + fprintf(1,'\n'); + Magic = fread(fid, 8, '*char'); + if not(strcmp(Magic(Magic~=0)','PQTTTR')) + error('Magic invalid, this is not an PTU file.'); + end; + Version = fread(fid, 8, '*char'); + fprintf(1,'Tag Version: %s\n', Version); + + % there is no repeat.. until (or do..while) construct in matlab so we use + % while 1 ... if (expr) break; end; end; + while 1 + % read Tag Head + TagIdent = fread(fid, 32, '*char'); % TagHead.Ident + TagIdent = (TagIdent(TagIdent ~= 0))'; % remove #0 and more more readable + TagIdx = fread(fid, 1, 'int32'); % TagHead.Idx + TagTyp = fread(fid, 1, 'uint32'); % TagHead.Typ + % TagHead.Value will be read in the + % right type function + TagIdent = genvarname(TagIdent); % remove all illegal characters + if TagIdx > -1 + EvalName = [TagIdent '(' int2str(TagIdx + 1) ')']; + else + EvalName = TagIdent; + end + fprintf(1,'\n %-40s', EvalName); + % check Typ of Header + switch TagTyp + case tyEmpty8 + fread(fid, 1, 'int64'); + fprintf(1,''); + case tyBool8 + TagInt = fread(fid, 1, 'int64'); + if TagInt==0 + fprintf(1,'FALSE'); + eval([EvalName '=false;']); + else + fprintf(1,'TRUE'); + eval([EvalName '=true;']); + end + case tyInt8 + TagInt = fread(fid, 1, 'int64'); + fprintf(1,'%d', TagInt); + eval([EvalName '=TagInt;']); + case tyBitSet64 + TagInt = fread(fid, 1, 'int64'); + fprintf(1,'%X', TagInt); + eval([EvalName '=TagInt;']); + case tyColor8 + TagInt = fread(fid, 1, 'int64'); + fprintf(1,'%X', TagInt); + eval([EvalName '=TagInt;']); + case tyFloat8 + TagFloat = fread(fid, 1, 'double'); + fprintf(1, '%e', TagFloat); + eval([EvalName '=TagFloat;']); + case tyFloat8Array + TagInt = fread(fid, 1, 'int64'); + fprintf(1,'', TagInt / 8); + fseek(fid, TagInt, 'cof'); + case tyTDateTime + TagFloat = fread(fid, 1, 'double'); + fprintf(1, '%s', datestr(datenum(1899,12,30)+TagFloat)); % display as Matlab Date String + eval([EvalName '=datenum(1899,12,30)+TagFloat;']); % but keep in memory as Matlab Date Number + case tyAnsiString + TagInt = fread(fid, 1, 'int64'); + TagString = fread(fid, TagInt, '*char'); + TagString = (TagString(TagString ~= 0))'; + fprintf(1, '%s', TagString); + if TagIdx > -1 + EvalName = [TagIdent '{' int2str(TagIdx + 1) '}']; + end; + eval([EvalName '=[TagString];']); + case tyWideString + % Matlab does not support Widestrings at all, just read and + % remove the 0's (up to current (2012)) + TagInt = fread(fid, 1, 'int64'); + TagString = fread(fid, TagInt, '*char'); + TagString = (TagString(TagString ~= 0))'; + fprintf(1, '%s', TagString); + if TagIdx > -1 + EvalName = [TagIdent '{' int2str(TagIdx + 1) '}']; + end; + eval([EvalName '=[TagString];']); + case tyBinaryBlob + TagInt = fread(fid, 1, 'int64'); + fprintf(1,'', TagInt); + fseek(fid, TagInt, 'cof'); + otherwise + error('Illegal Type identifier found! Broken file?'); + end; + if strcmp(TagIdent, 'Header_End') + break + end + end + fprintf(1, '\n----------------------\n'); + outfile = [pathname filename(1:length(filename)-4) '.out']; + global fpout; + fpout = fopen(outfile,'W'); + % Check recordtype + global isT2; + switch TTResultFormat_TTTRRecType; + case rtPicoHarpT3 + isT2 = false; + fprintf(1,'PicoHarp T3 data\n'); + case rtPicoHarpT2 + isT2 = true; + fprintf(1,'PicoHarp T2 data\n'); + case rtHydraHarpT3 + isT2 = false; + fprintf(1,'HydraHarp V1 T3 data\n'); + case rtHydraHarpT2 + isT2 = true; + fprintf(1,'HydraHarp V1 T2 data\n'); + case rtHydraHarp2T3 + isT2 = false; + fprintf(1,'HydraHarp V2 T3 data\n'); + case rtHydraHarp2T2 + isT2 = true; + fprintf(1,'HydraHarp V2 T2 data\n'); + case rtTimeHarp260NT3 + isT2 = false; + fprintf(1,'TimeHarp260N T3 data\n'); + case rtTimeHarp260NT2 + isT2 = true; + fprintf(1,'TimeHarp260N T2 data\n'); + case rtTimeHarp260PT3 + isT2 = false; + fprintf(1,'TimeHarp260P T3 data\n'); + case rtTimeHarp260PT2 + isT2 = true; + fprintf(1,'TimeHarp260P T2 data\n'); + case rtMultiHarpNT3 + isT2 = false; + fprintf(1,'MultiHarp150N T3 data\n'); + case rtMultiHarpNT2 + isT2 = true; + fprintf(1,'MultiHarp150N T2 data\n'); + otherwise + error('Illegal RecordType!'); + end; + fprintf(1,'\nWriting data to %s', outfile); + fprintf(1,'\nThis may take a while...'); + % write Header + if (isT2) + fprintf(fpout, ' record# Type Ch TimeTag TrueTime/ps\n'); + else + fprintf(fpout, ' record# Type Ch TimeTag TrueTime/ns DTime\n'); + end; + global cnt_ph; + global cnt_ov; + global cnt_ma; + cnt_ph = 0; + cnt_ov = 0; + cnt_ma = 0; + % choose right decode function + switch TTResultFormat_TTTRRecType; + case rtPicoHarpT3 + ReadPT3; + case rtPicoHarpT2 + isT2 = true; + ReadPT2; + case rtHydraHarpT3 + ReadHT3(1); + case rtHydraHarpT2 + isT2 = true; + ReadHT2(1); + case {rtMultiHarpNT3, rtHydraHarp2T3, rtTimeHarp260NT3, rtTimeHarp260PT3} + isT2 = false; + ReadHT3(2); + case {rtMultiHarpNT2, rtHydraHarp2T2, rtTimeHarp260NT2, rtTimeHarp260PT2} + isT2 = true; + ReadHT2(2); + otherwise + error('Illegal RecordType!'); + end; + fclose(fid); + fclose(fpout); + fprintf(1,'Ready! \n\n'); + fprintf(1,'\nStatistics obtained from the data:\n'); + fprintf(1,'\n%i photons, %i overflows, %i markers.',cnt_ph, cnt_ov, cnt_ma); + + fprintf(1,'\n'); +end + +%% Got Photon +% TimeTag: Raw TimeTag from Record * Globalresolution = Real Time arrival of Photon +% DTime: Arrival time of Photon after last Sync event (T3 only) DTime * Resolution = Real time arrival of Photon after last Sync event +% Channel: Channel the Photon arrived (0 = Sync channel for T2 measurements) +function GotPhoton(TimeTag, Channel, DTime) + global isT2; + global fpout; + global RecNum; + global MeasDesc_GlobalResolution; + global cnt_ph; + cnt_ph = cnt_ph + 1; + if(isT2) + % Edited: formatting changed by PK + fprintf(fpout,'\n%10i CHN %i %18.0f (%0.1f ps)' , RecNum, Channel, TimeTag, (TimeTag * MeasDesc_GlobalResolution * 1e12)); + else + % Edited: formatting changed by PK + fprintf(fpout,'\n%10i CHN %i %18.0f (%0.1f ns) %ich', RecNum, Channel, TimeTag, (TimeTag * MeasDesc_GlobalResolution * 1e9), DTime); + end; +end + +%% Got Marker +% TimeTag: Raw TimeTag from Record * Globalresolution = Real Time arrival of Photon +% Markers: Bitfield of arrived Markers, different markers can arrive at same time (same record) +function GotMarker(TimeTag, Markers) + global fpout; + global RecNum; + global cnt_ma; + global MeasDesc_GlobalResolution; + cnt_ma = cnt_ma + 1; + % Edited: formatting changed by PK + fprintf(fpout,'\n%10i MAR %i %18.0f (%0.1f ns)', RecNum, Markers, TimeTag, (TimeTag * MeasDesc_GlobalResolution * 1e9)); +end + +%% Got Overflow +% Count: Some TCSPC provide Overflow compression = if no Photons between overflow you get one record for multiple Overflows +function GotOverflow(Count) + global fpout; + global RecNum; + global cnt_ov; + cnt_ov = cnt_ov + Count; + % Edited: formatting changed by PK + fprintf(fpout,'\n%10i OFL * %i', RecNum, Count); +end + +%% Decoder functions + +%% Read PicoHarp T3 +function ReadPT3 + global fid; + global fpout; + global RecNum; + global TTResult_NumberOfRecords; % Number of TTTR Records in the File; + ofltime = 0; + WRAPAROUND=65536; + + for i=1:TTResult_NumberOfRecords + RecNum = i; + T3Record = fread(fid, 1, 'ubit32'); % all 32 bits: + % +-------------------------------+ +-------------------------------+ + % |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| + % +-------------------------------+ +-------------------------------+ + nsync = bitand(T3Record,65535); % the lowest 16 bits: + % +-------------------------------+ +-------------------------------+ + % | | | | | | | | | | | | | | | | | |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| + % +-------------------------------+ +-------------------------------+ + chan = bitand(bitshift(T3Record,-28),15); % the upper 4 bits: + % +-------------------------------+ +-------------------------------+ + % |x|x|x|x| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + truensync = ofltime + nsync; + if (chan >= 1) && (chan <=4) + dtime = bitand(bitshift(T3Record,-16),4095); + GotPhoton(truensync, chan, dtime); % regular count at Ch1, Rt_Ch1 - Rt_Ch4 when the router is enabled + else + if chan == 15 % special record + markers = bitand(bitshift(T3Record,-16),15); % where these four bits are markers: + % +-------------------------------+ +-------------------------------+ + % | | | | | | | | | | | | |x|x|x|x| | | | | | | | | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + if markers == 0 % then this is an overflow record + ofltime = ofltime + WRAPAROUND; % and we unwrap the numsync (=time tag) overflow + GotOverflow(1); + else % if nonzero, then this is a true marker event + GotMarker(truensync, markers); + end; + else + fprintf(fpout,'Err '); + end; + end; + end; +end + +%% Read PicoHarp T2 +function ReadPT2 + global fid; + global fpout; + global RecNum; + global TTResult_NumberOfRecords; % Number of TTTR Records in the File; + ofltime = 0; + WRAPAROUND=210698240; + + for i=1:TTResult_NumberOfRecords + RecNum = i; + T2Record = fread(fid, 1, 'ubit32'); + T2time = bitand(T2Record,268435455); %the lowest 28 bits + chan = bitand(bitshift(T2Record,-28),15); %the next 4 bits + timetag = T2time + ofltime; + if (chan >= 0) && (chan <= 4) + GotPhoton(timetag, chan, 0); + else + if chan == 15 + markers = bitand(T2Record,15); % where the lowest 4 bits are marker bits + if markers==0 % then this is an overflow record + ofltime = ofltime + WRAPAROUND; % and we unwrap the time tag overflow + GotOverflow(1); + else % otherwise it is a true marker + GotMarker(timetag, markers); + end; + else + fprintf(fpout,'Err'); + end; + end; + % Strictly, in case of a marker, the lower 4 bits of time are invalid + % because they carry the marker bits. So one could zero them out. + % However, the marker resolution is only a few tens of nanoseconds anyway, + % so we can just ignore the few picoseconds of error. + end; +end + +%% Read HydraHarp/TimeHarp260 T3 +function ReadHT3(Version) + global fid; + global RecNum; + global TTResult_NumberOfRecords; % Number of TTTR Records in the File + OverflowCorrection = 0; + T3WRAPAROUND = 1024; + + for i = 1:TTResult_NumberOfRecords + RecNum = i; + T3Record = fread(fid, 1, 'ubit32'); % all 32 bits: + % +-------------------------------+ +-------------------------------+ + % |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| + % +-------------------------------+ +-------------------------------+ + nsync = bitand(T3Record,1023); % the lowest 10 bits: + % +-------------------------------+ +-------------------------------+ + % | | | | | | | | | | | | | | | | | | | | | | | |x|x|x|x|x|x|x|x|x|x| + % +-------------------------------+ +-------------------------------+ + dtime = bitand(bitshift(T3Record,-10),32767); % the next 15 bits: + % the dtime unit depends on "Resolution" that can be obtained from header + % +-------------------------------+ +-------------------------------+ + % | | | | | | | |x|x|x|x|x|x|x|x|x| |x|x|x|x|x|x| | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + channel = bitand(bitshift(T3Record,-25),63); % the next 6 bits: + % +-------------------------------+ +-------------------------------+ + % | |x|x|x|x|x|x| | | | | | | | | | | | | | | | | | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + special = bitand(bitshift(T3Record,-31),1); % the last bit: + % +-------------------------------+ +-------------------------------+ + % |x| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + if special == 0 % this means a regular input channel + true_nSync = OverflowCorrection + nsync; + % one nsync time unit equals to "syncperiod" which can be + % calculated from "SyncRate" + GotPhoton(true_nSync, channel, dtime); + else % this means we have a special record + if channel == 63 % overflow of nsync occured + if (nsync == 0) || (Version == 1) % if nsync is zero it is an old style single oferflow or old Version + OverflowCorrection = OverflowCorrection + T3WRAPAROUND; + GotOverflow(1); + else % otherwise nsync indicates the number of overflows - THIS IS NEW IN FORMAT V2.0 + OverflowCorrection = OverflowCorrection + T3WRAPAROUND * nsync; + GotOverflow(nsync); + end; + end; + if (channel >= 1) && (channel <= 15) % these are markers + true_nSync = OverflowCorrection + nsync; + GotMarker(true_nSync, channel); + end; + end; + end; +end + +%% Read HydraHarp/TimeHarp260 T2 +function ReadHT2(Version) + global fid; + global TTResult_NumberOfRecords; % Number of TTTR Records in the File; + global RecNum; + + OverflowCorrection = 0; + T2WRAPAROUND_V1=33552000; + T2WRAPAROUND_V2=33554432; % = 2^25 IMPORTANT! THIS IS NEW IN FORMAT V2.0 + + for i=1:TTResult_NumberOfRecords + RecNum = i; + T2Record = fread(fid, 1, 'ubit32'); % all 32 bits: + % +-------------------------------+ +-------------------------------+ + % |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| + % +-------------------------------+ +-------------------------------+ + dtime = bitand(T2Record,33554431); % the last 25 bits: + % +-------------------------------+ +-------------------------------+ + % | | | | | | | |x|x|x|x|x|x|x|x|x| |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x| + % +-------------------------------+ +-------------------------------+ + channel = bitand(bitshift(T2Record,-25),63); % the next 6 bits: + % +-------------------------------+ +-------------------------------+ + % | |x|x|x|x|x|x| | | | | | | | | | | | | | | | | | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + special = bitand(bitshift(T2Record,-31),1); % the last bit: + % +-------------------------------+ +-------------------------------+ + % |x| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | + % +-------------------------------+ +-------------------------------+ + % the resolution in T2 mode is 1 ps - IMPORTANT! THIS IS NEW IN FORMAT V2.0 + timetag = OverflowCorrection + dtime; + if special == 0 % this means a regular photon record + GotPhoton(timetag, channel + 1, 0) + else % this means we have a special record + if channel == 63 % overflow of dtime occured + if Version == 1 + OverflowCorrection = OverflowCorrection + T2WRAPAROUND_V1; + GotOverflow(1); + else + if(dtime == 0) % if dtime is zero it is an old style single oferflow + OverflowCorrection = OverflowCorrection + T2WRAPAROUND_V2; + GotOverflow(1); + else % otherwise dtime indicates the number of overflows - THIS IS NEW IN FORMAT V2.0 + OverflowCorrection = OverflowCorrection + T2WRAPAROUND_V2 * dtime; + GotOverflow(dtime); + end; + end; + end; + if channel == 0 % Sync event + GotPhoton(timetag, channel, 0); + end; + if (channel >= 1) && (channel <= 15) % these are markers + GotMarker(timetag, channel); + end; + end; + end; +end diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Results_4.fig b/Spectral-FLIM GUI/Spectral-FLIM GUI/Results_4.fig new file mode 100644 index 0000000..59e152a Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/Results_4.fig differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Results_4.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Results_4.m new file mode 100644 index 0000000..2859430 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Results_4.m @@ -0,0 +1,2943 @@ +function varargout = Results_4(varargin) +% RESULTS_4 M-file for Results_4.fig +% RESULTS_4, by itself, creates a new RESULTS_4 or raises the existing +% singleton*. +% +% H = RESULTS_4 returns the handle to a new RESULTS_4 or the handle to +% the existing singleton*. +% +% RESULTS_4('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in RESULTS_4.M with the given input arguments. +% +% RESULTS_4('Property','Value',...) creates a new RESULTS_1 or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before Results_1_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to Results_1_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 Results_4 + +% Last Modified by GUIDE v2.5 05-Aug-2019 09:53:44 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @Results_4_OpeningFcn, ... + 'gui_OutputFcn', @Results_4_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 Results_4 is made visible. +function Results_4_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 Results_4 (see VARARGIN) + +% Choose default command line output for Results_4 +handles.output = hObject; + +set(handles.Update_button,'Enable','off'); +set(handles.NewROI_button,'Enable','off'); +set(handles.popupmenu1,'Enable','off'); +set(handles.popupmenu2,'Enable','off'); +set(handles.ClearROI_button,'Enable','off'); +set(handles.SaveROI_button,'Enable','off'); +set(handles.SavePattern_button,'Enable','off'); +set(handles.ClearPattern_button,'Enable','off'); +set(handles.ShowPattern_button,'Enable','off'); +set(handles.FindAmplitudes_button,'Enable','off'); +set(handles.SaveResults_button,'Enable','off'); +set(handles.Merge_button,'Enable','off'); +set(handles.Intersect_button,'Enable','off'); +set(handles.Add_Similar_button,'Enable','off'); +set(handles.FitPattern_button,'Enable','off'); +set(handles.Plot_Results_button,'Enable','on'); + + +% Update handles structure +guidata(hObject, handles); + +if nargin < 2 + errordlg('No filename given','File Load Error') +elseif (length(varargin) == 2 && ... + strcmpi(varargin{1},'file') && ... + (2 == exist([varargin{2}(1:end-4) '_Moments.mat'],'file'))) + handles.filename = cell2mat(varargin(2)); +else + errordlg('File Not Found','File Load Error') +end + +tmp = strfind(handles.filename,'\'); +handles.pathname = handles.filename(1:tmp(end)); +handles.filename = handles.filename(tmp(end)+1:end); + +load Get_Params; +handles.par_lam_start = lam_start; +handles.par_lam_step = lam_step; +handles.par_tau_min = tau_min; +handles.par_tau_max = tau_max; +handles.par_cum2_min = cum2_min; +handles.par_cum2_max = cum2_max; +handles.par_clam_min = clam_min; +handles.par_clam_max = clam_max; +handles.par_wlam_min = wlam_min; +handles.par_wlam_max = wlam_max; +handles.par_num_PIE = num_PIE; +handles.par_lam_PIE = lamPIE; +handles.par_Threshold = Threshold; +handles.par_binning = binning; +handles.ROIcolor = ROIcolor; +handles.maxROI = maxROI; +handles.figFLIM = figFLIM; +handles.figMA = figMA; +handles.figPA = figPA; +handles.figfFLIM = figfFLIM; +handles.figone = figone; + +handles.pulse = 1; +handles.match = 0; +handles.ROIlist = zeros(maxROI, num_PIE); + +[handles.head, handles.tag, handles.tcspc, handles.IRF, handles.timname, handles.AP, handles.DC] = load_data([handles.pathname handles.filename]); + +nx = handles.head.ImgHdr.PixX; +ny = handles.head.ImgHdr.PixY; +tx = floor(nx/binning); +ty = floor(ny/binning); +nch = size(handles.tcspc,1); +nbin = size(handles.tcspc,2); +num_PIE = size(handles.tcspc,3); + +if binning > 1 + tmp = handles.tag(1:binning*tx,:,:,:); + tmp = reshape(tmp, binning, tx, ny, nch, num_PIE); + tmp = squeeze(mean(tmp,1)); + tmp = tmp(:,1:binning*ty,:,:); + tmp = reshape(tmp, tx, binning, ty, nch, num_PIE); + handles.tag = squeeze(mean(tmp,2)); +end + +if handles.head.ImgHdr.PixelSize ==0 + handles.head.ImgHdr.PixelSize = pixwidth; +end + +handles.plt_tau_min = tau_min; +handles.plt_tau_max = tau_max; +handles.plt_cum2_min = cum2_min; +handles.plt_cum2_max = cum2_max; +handles.plt_clam_min = clam_min; +handles.plt_clam_max = clam_max; +handles.plt_wlam_min = wlam_min; +handles.plt_wlam_max = wlam_max; +handles.plt_x_min = handles.head.ImgHdr.X0; +handles.plt_x_max = handles.head.ImgHdr.X0+handles.head.ImgHdr.PixX*handles.head.ImgHdr.PixelSize; +handles.plt_y_min = handles.head.ImgHdr.Y0; +handles.plt_y_max = handles.head.ImgHdr.Y0+handles.head.ImgHdr.PixY*handles.head.ImgHdr.PixelSize; + +handles.channel = zeros(handles.par_num_PIE, size(handles.tcspc,1)); + +load([handles.pathname handles.filename(1:end-4) '_Moments.mat'],'tav'); + +handles.tav = tav; +handles.pat = zeros(1, size(handles.tcspc,1), size(handles.tcspc,2), handles.par_num_PIE); + +handles.s_ind = uint16(zeros(size(handles.tag,1)*size(handles.tag,2),handles.par_num_PIE)); + +guidata(hObject, handles); + +load('c_map.mat','map'); +colormap(map); + +s = {}; + +set(handles.Pattern_List,'String',s); + +for n = 1:num_PIE + s(n) = {sprintf('pulse %d',n)}; +end + +set(handles.popupmenu1, 'String',s); + +lambda = (handles.par_lam_start+handles.par_lam_step.*(0:size(handles.tcspc,1)-1)); +tmp = repmat(handles.par_lam_PIE(1:handles.par_num_PIE)', [1 size(handles.tcspc,1)])+handles.par_lam_step; + +handles.channel = repmat(lambda,[handles.par_num_PIE 1])>tmp; + +s = {}; + +for n = 1:size(handles.tcspc,1); + if handles.channel(handles.pulse,n) + s(n) = {sprintf('[X] %03d nm',lambda(n))}; + else + s(n) = {sprintf('[ ] %03d nm',lambda(n))}; + end +end + +set(handles.popupmenu2, 'String',s); + +set(handles.axes4,'visible', 'on'); +set(handles.axes4, 'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); +ylabel(handles.axes4, '< \tau > / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +xlabel(handles.axes4, '\lambda_0 / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +axis(handles.axes4, [tau_min tau_max clam_min clam_max]); + +set(handles.axes1, 'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'FontSize',9,... + 'XDir','normal', ... + 'YDir','reverse'); +xlabel(handles.axes2, 'x / µm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel(handles.axes2, 'y / µm','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +set(handles.axes2, 'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); +xlabel(handles.axes2, '\Delta \lambda / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel(handles.axes2, '\lambda_0 / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +axis(handles.axes2, [wlam_min wlam_max clam_min clam_max]); + + +[handles.M_X, handles.M_Y, handles.Z, handles.ZZ] = compute_data(handles); +compute_fFLIM(handles); +guidata(hObject, handles); + +plot_graphs(handles) + +pause(0.05) +set(handles.Update_button,'Enable','on'); +set(handles.NewROI_button,'Enable','on'); +set(handles.LoadROI_button,'Enable','on'); +set(handles.LoadPattern_button,'Enable','on'); +set(handles.popupmenu1,'Enable','on'); +set(handles.popupmenu2,'Enable','on'); + + +% --- Outputs from this function are returned to the command line. +function varargout = Results_4_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; + + +% --- Executes during object creation, after setting all properties. +function popupmenu1_CreateFcn(hObject, eventdata, handles) +% hObject handle to popupmenu1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); +end + + +% --- Executes during object creation, after setting all properties. +function popupmenu2_CreateFcn(hObject, eventdata, handles) +% hObject handle to popupmenu2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: popupmenu 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 during object creation, after setting all properties. +function listbox2_CreateFcn(hObject, eventdata, handles) +% hObject handle to listbox2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) + set(hObject,'BackgroundColor','white'); + set(hObject,'String',{}); +end + + +% --- Executes during object creation, after setting all properties. +function Pattern_List_CreateFcn(hObject, eventdata, handles) +% hObject handle to Pattern_List (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + +% Hint: listbox 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'); + set(hObject,'String',{}); +end + + +% --- Executes on selection change in popupmenu1. +function popupmenu1_Callback(hObject, eventdata, handles) +% hObject handle to popupmenu1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +tmp = get(hObject,'Value'); +if tmp ~= handles.pulse + handles.pulse = tmp; + guidata(hObject, handles); +end + + +% --- Executes on selection change in popupmenu2. +function popupmenu2_Callback(hObject, eventdata, handles) +% hObject handle to popupmenu2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% Hints: contents = get(hObject,'String') returns popupmenu2 contents as cell array +% contents{get(hObject,'Value')} returns selected item from popupmenu2 + +lambda = (handles.par_lam_start+handles.par_lam_step.*(0:size(handles.tcspc,1)-1)); + +% for n = 1:size(handles.tcspc,1); +% s(n) = {sprintf('[X] %03d nm',lambda(n))}; +% end + +tmp = get(hObject,'Value'); +s = get(hObject, 'String'); + +handles.channel(handles.pulse,tmp) = ~handles.channel(handles.pulse,tmp); + +if handles.channel(handles.pulse,tmp) + s(tmp) = {sprintf('[X] %03d nm',lambda(tmp))}; +else + s(tmp) = {sprintf('[ ] %03d nm',lambda(tmp))}; +end +set(hObject, 'String',s); +guidata(hObject, handles); + + +% --- Executes on selection change in listbox2. +function listbox2_Callback(hObject, eventdata, handles) +% hObject handle to listbox2 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +index_selected = get(hObject, 'Value'); +if numel(index_selected)>1 + set(handles.Intersect_button,'Enable','on'); + set(handles.Merge_button,'Enable','on'); +else + set(handles.Intersect_button,'Enable','off'); + set(handles.Merge_button,'Enable','off'); +end + +if numel(index_selected)>0 + set(handles.ClearROI_button,'Enable','on'); + set(handles.SaveROI_button,'Enable','on'); + set(handles.UseROI_button,'Enable','on'); + set(handles.Add_Similar_button,'Enable','on'); +else + set(handles.ClearROI_button,'Enable','off'); + set(handles.SaveROI_button,'Enable','off'); + set(handles.UseROI_button,'Enable','off'); + set(handles.Add_Similar_button,'Enable','off'); +end +guidata(hObject, handles); + + +% --- Executes on selection change in Pattern_List. +function Pattern_List_Callback(hObject, eventdata, handles) +% hObject handle to Pattern_List (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +index_selected = get(hObject, 'Value'); +if numel(index_selected)>0 + set(handles.ClearPattern_button,'Enable','on'); + set(handles.SavePattern_button,'Enable','on'); + set(handles.ShowPattern_button,'Enable','on'); + set(handles.FindAmplitudes_button,'Enable','on'); + set(handles.FitPattern_button,'Enable','on'); +else + set(handles.ClearPattern_button,'Enable','off'); + set(handles.SavePattern_button,'Enable','off'); + set(handles.ShowPattern_button,'Enable','off'); + set(handles.FindAmplitudes_button,'Enable','off'); +end +guidata(hObject, handles); + + +% --- Executes on button press in Update_button. +function Update_button_Callback(hObject, eventdata, handles) +% hObject handle to Update_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(handles.Update_button,'String','Busy'); +set(handles.Update_button,'Enable','off'); +pause(0.05) +guidata(hObject, handles); +[handles.M_X, handles.M_Y, handles.Z, handles.ZZ] = compute_data(handles); +lambda = (handles.par_lam_start+handles.par_lam_step.*(0:size(handles.tcspc,1)-1)); +s = {}; +for n = 1:size(handles.tcspc,1); + if handles.channel(handles.pulse,n) + s(n) = {sprintf('[X] %03d nm',lambda(n))}; + else + s(n) = {sprintf('[ ] %03d nm',lambda(n))}; + end +end +set(handles.popupmenu2, 'String',s); + + +guidata(hObject, handles); +plot_graphs(handles) +s = {}; +set(handles.listbox2, 'Value',[]); +if sum(handles.ROIlist(:, handles.pulse))>0 + tst = 1; + for n = 1:handles.maxROI + if handles.ROIlist(n, handles.pulse)==1 + s(tst) = {sprintf('ROI %d_%d',n,handles.pulse)}; + tst = tst+1; + end + end + set(handles.listbox2,'String',s); + set(handles.listbox2,'Enable','on'); + set(handles.ClearROI_button,'Enable','on'); + + update_fFLIM(handles) +else + set(handles.listbox2,'String',s); + set(handles.listbox2,'Enable','off'); + set(handles.ClearROI_button,'Enable','off'); +end + +set(handles.Update_button,'String','Update'); +set(handles.Update_button,'Enable','on'); + +% --- Executes on button press in zoom_button. +function zoom_button_Callback(hObject, eventdata, handles) +% hObject handle to zoom_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +axes(handles.axes1); + +[xi,yi,button] = ginput(1); + +if button==1 + + pt1 = get(handles.axes1, 'CurrentPoint'); + pt2 = get(handles.axes2, 'CurrentPoint'); + pt3 = get(handles.axes3, 'CurrentPoint'); + pt4 = get(handles.axes4, 'CurrentPoint'); + + t1 = xi-[pt1(1,1) pt2(1,1) pt3(1,1) pt4(1,1)]; + t2 = yi-[pt1(1,2) pt2(1,2) pt3(1,2) pt4(1,2)]; + p = find((t1+t2)==0); + + if isempty(p) + p = abs(t1+t2); + p = find(p==min(p)); + end + + if p==1 + axes(handles.axes1); + elseif p==2 + axes(handles.axes2); + elseif p==3 + axes(handles.axes3); + else + axes(handles.axes4); + end + + hold on + + plot(xi,yi,'+','Color',[1 1 1]) + xy = [xi;yi]; + + [xi,yi,button] = ginput(1); + if button==1 + plot(xi,yi,'+','Color',[1 1 1]) + xy(:,2) = [xi;yi]; + hold off + + x_min = min(xy(1,:)); + x_max = max(xy(1,:)); + y_min = min(xy(2,:)); + y_max = max(xy(2,:)); + + if p==1 % Intensity image + handles.plt_x_min = x_min; + handles.plt_x_max = x_max; + handles.plt_y_min = y_min; + handles.plt_y_max = y_max; + elseif p==2 % wavelength diagram + handles.plt_wlam_min = x_min; + handles.plt_wlam_max = x_max; + handles.plt_clam_min = y_min; + handles.plt_clam_max = y_max; + elseif p==3 % moments plot + handles.plt_tau_min = x_min; + handles.plt_tau_max = x_max; + handles.plt_cum2_min = y_min; + handles.plt_cum2_max = y_max; + elseif p==4 % tau-wavelength diagram + handles.plt_tau_min = x_min; + handles.plt_tau_max = x_max; + handles.plt_clam_min = y_min; + handles.plt_clam_max = y_max; + end + else + if p==1 % Intensity image + handles.plt_x_min = handles.head.ImgHdr.X0; + handles.plt_x_max = handles.head.ImgHdr.X0+handles.head.ImgHdr.PixX*handles.head.ImgHdr.PixelSize; + handles.plt_y_min = handles.head.ImgHdr.Y0; + handles.plt_y_max = handles.head.ImgHdr.Y0+handles.head.ImgHdr.PixY*handles.head.ImgHdr.PixelSize; + elseif p==2 % wavelength diagram + handles.plt_wlam_min = handles.par_wlam_min; + handles.plt_wlam_max = handles.par_wlam_max; + handles.plt_clam_min = handles.par_clam_min; + handles.plt_clam_max = handles.par_clam_max; + elseif p==3 % moments plot + handles.plt_tau_min = handles.par_tau_min; + handles.plt_tau_max = handles.par_tau_max; + handles.plt_cum2_min = handles.par_cum2_min; + handles.plt_cum2_max = handles.par_cum2_max; + elseif p==4 % tau-wavelength diagram + handles.plt_tau_min = handles.par_tau_min; + handles.plt_tau_max = handles.par_tau_max; + handles.plt_clam_min = handles.par_clam_min; + handles.plt_clam_max = handles.par_clam_max; + end + end +else + handles.plt_tau_min = handles.par_tau_min; + handles.plt_tau_max = handles.par_tau_max; + handles.plt_cum2_min = handles.par_cum2_min; + handles.plt_cum2_max = handles.par_cum2_max; + handles.plt_clam_min = handles.par_clam_min; + handles.plt_clam_max = handles.par_clam_max; + handles.plt_wlam_min = handles.par_wlam_min; + handles.plt_wlam_max = handles.par_wlam_max; + handles.plt_x_min = handles.head.ImgHdr.X0; + handles.plt_x_max = handles.head.ImgHdr.X0+handles.head.ImgHdr.PixX*handles.head.ImgHdr.PixelSize; + handles.plt_y_min = handles.head.ImgHdr.Y0; + handles.plt_y_max = handles.head.ImgHdr.Y0+handles.head.ImgHdr.PixY*handles.head.ImgHdr.PixelSize; +end + +guidata(hObject, handles) +plot_graphs(handles); + +% --- Executes on button press in NewROI_button. +function NewROI_button_Callback(hObject, eventdata, handles) +% hObject handle to NewROI_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(handles.NewROI_button,'String','Click'); +set(handles.NewROI_button,'Enable','off'); +pause(0.05) + +tmp = 1; +while handles.ROIlist(tmp, handles.pulse)==1 + tmp = tmp +1; +end + +if tmp <= handles.maxROI + handles.ROIlist(tmp, handles.pulse) = 1; + + guidata(hObject, handles); + + handles.s_ind = select_data(handles, tmp); + guidata(hObject, handles); + + plot_graphs(handles) + + s = {}; + tst = 1; + for n = 1:handles.maxROI + if handles.ROIlist(n, handles.pulse)==1 + s(tst) = {sprintf('ROI %d_%d',n,handles.pulse)}; + tst = tst+1; + end + end + set(handles.listbox2,'String',s); + set(handles.listbox2,'Enable','on'); + set(handles.ClearROI_button,'Enable','on'); +end + +set(handles.NewROI_button,'String','new ROI'); +if tmp0 + set(handles.ClearROI_button,'String','Busy'); + set(handles.ClearROI_button,'Enable','off'); + pause(0.05); + + list_entries = get(handles.listbox2, 'String'); + index_selected = get(handles.listbox2, 'Value'); + pat_list_entries = get(handles.Pattern_List, 'String'); + + for n = 1:numel(index_selected) + + s = list_entries{index_selected(n)}; + ROI = str2double(s(end-2)); + + handles.s_ind(:,handles.pulse) = bitset(handles.s_ind(:,handles.pulse), ROI, 0); + handles.ROIlist(ROI, handles.pulse) = 0; + + tst = strcmp(pat_list_entries,s); + handles.pat(tst,:,:,:) = []; + pat_list_entries(tst) = []; + end + + set(handles.Pattern_List,'String',pat_list_entries); + + guidata(hObject, handles); + + s = {}; + + tst = 1; + for n = 1:handles.maxROI + if handles.ROIlist(n, handles.pulse)==1 + s(tst) = {sprintf('ROI %d_%d',n,handles.pulse)}; + tst = tst+1; + end + end + set(handles.listbox2,'Value',1); + set(handles.listbox2,'String',s); + listbox2_Callback(handles.listbox2, [], handles); + + plot_graphs(handles) + % update_fFLIM(handles) + + set(handles.ClearROI_button,'String','clear ROI'); + if tst>1 + set(handles.ClearROI_button,'Enable','on'); + end + if tst<=handles.maxROI + set(handles.NewROI_button,'Enable','on'); + end +end +guidata(hObject, handles); + + + +% --- Executes on button press in LoadROI_button. +function LoadROI_button_Callback(hObject, eventdata, handles) % Load ROI +% hObject handle to LoadROI_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(hObject,'Enable','off'); + +ROInum = 1; +while handles.ROIlist(ROInum, handles.pulse)==1 + ROInum = ROInum +1; +end + +if ROInum <= handles.maxROI + handles.ROIlist(ROInum, handles.pulse)=1; + [FileName,PathName,FilterIndex] = uigetfile({'*.roi','ROI Files';... + [handles.pathname '*.*'],'All Files'},'Load ROI', [handles.pathname 'newroi.roi']); + if FileName ~= 0 + load([PathName FileName],'ind', '-mat'); + + handles.s_ind(ind, handles.pulse) = bitset(handles.s_ind(ind, handles.pulse), ROInum,1); + + guidata(hObject, handles); + + s = {}; + tst = 1; + for n = 1:handles.maxROI + if handles.ROIlist(n, handles.pulse)==1 + s(tst) = {sprintf('ROI %d_%d',n,handles.pulse)}; + tst = tst+1; + end + end + set(handles.listbox2,'Value',1); + set(handles.listbox2,'String',s); + listbox2_Callback(handles.listbox2, [], handles); + + plot_graphs(handles) + % update_fFLIM(handles) + end +end + +set(hObject,'String','Load ROI'); +if ROInum>=handles.maxROI + set(handles.NewROI_button,'Enable','off'); +end +guidata(hObject, handles); + + +% --- Executes on button press in SaveROI_button. +function SaveROI_button_Callback(hObject, eventdata, handles) % Save ROI +% hObject handle to SaveROI_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(hObject,'Enable','off'); + +list_entries = get(handles.listbox2, 'String'); +index_selected = get(handles.listbox2, 'Value'); + +for n = 1:numel(index_selected) + + s = list_entries{index_selected(n)}; + ROI = str2double(s(end-2)); + + ind = bitget(handles.s_ind(:, handles.pulse), ROI) == 1; + + [FileName,PathName] = uiputfile({'*.roi','ROI Files';... + '*.*','All Files' },'Save ROI',... + [handles.pathname 'newroi.roi']); + if FileName ~= 0 + save([PathName FileName],'ind'); + end +end + + +% --- Executes on button press in Merge_button. +function Merge_button_Callback(hObject, eventdata, handles) +% hObject handle to Merge_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(hObject,'String','Busy'); +set(hObject,'Enable','off'); + +list_entries = get(handles.listbox2, 'String'); +index_selected = get(handles.listbox2, 'Value'); + +if numel(index_selected) > 1 + + s = list_entries{index_selected(1)}; + ROI = str2double(s(end-2)); + + for n = 2:numel(index_selected) + + s = list_entries{index_selected(n)}; + k = str2double(s(end-2)); + + handles.ROIlist(k, handles.pulse) = 0; + + ind = bitget(handles.s_ind(:, handles.pulse), k) == 1; + handles.s_ind(ind, handles.pulse) = bitset(handles.s_ind(ind, handles.pulse), k, 0); + handles.s_ind(ind, handles.pulse) = bitset(handles.s_ind(ind, handles.pulse), ROI, 1); + end + guidata(hObject, handles); +end + +s = {}; +tst = 1; +for n = 1:handles.maxROI + if handles.ROIlist(n, handles.pulse)==1 + s(tst) = {sprintf('ROI %d_%d',n,handles.pulse)}; + tst = tst+1; + end +end +set(handles.listbox2,'Value',1); +set(handles.listbox2,'String',s); +listbox2_Callback(handles.listbox2, [], handles); + +%plot_graphs(handles) +%update_fFLIM(handles) +set(hObject,'String','Merge ROIs'); + + +% --- Executes on button press in Intersect_button. +function Intersect_button_Callback(hObject, eventdata, handles) +% hObject handle to Intersect_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(hObject,'String','Busy'); +set(hObject,'Enable','off'); + +list_entries = get(handles.listbox2, 'String'); +index_selected = get(handles.listbox2, 'Value'); + +if numel(index_selected) > 1 + + s = list_entries{index_selected(1)}; + ROI = str2double(s(end-2)); + + ind = bitget(handles.s_ind(:, handles.pulse), ROI) == 1; + + handles.s_ind(:, handles.pulse) = bitset(handles.s_ind(:, handles.pulse), ROI, 0); + + for n = 2:numel(index_selected) + + s = list_entries{index_selected(n)}; + k = str2double(s(end-2)); + + ind = ind & bitget(handles.s_ind(:, handles.pulse), k) == 1; + + handles.s_ind(:, handles.pulse) = bitset(handles.s_ind(:, handles.pulse), k, 0); + handles.ROIlist(k, handles.pulse) = 0; + + end + + handles.s_ind(ind, handles.pulse) = bitset(handles.s_ind(ind, handles.pulse), ROI, 1); + + guidata(hObject, handles); +end + +s = {}; +tst = 1; +for n = 1:handles.maxROI + if handles.ROIlist(n, handles.pulse)==1 + s(tst) = {sprintf('ROI %d_%d',n,handles.pulse)}; + tst = tst+1; + end +end +set(handles.listbox2,'Value',1); +set(handles.listbox2,'String',s); +listbox2_Callback(handles.listbox2, [], handles); + +plot_graphs(handles) +update_fFLIM(handles) +set(hObject,'String','Intersection'); + + +% --- Executes on button press in Add_Similar_button. +function Add_Similar_button_Callback(hObject, eventdata, handles) +% hObject handle to Add_Similar_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(hObject,'String','Busy'); +set(hObject,'Enable','off'); + +list_entries = get(handles.listbox2, 'String'); +index_selected = get(handles.listbox2, 'Value'); + +if numel(index_selected) >= 1 + + ROInum = 1; + while handles.ROIlist(ROInum, handles.pulse)==1 + ROInum = ROInum +1; + end + + if ROInum <= handles.maxROI + + handles.ROIlist(ROInum, handles.pulse) = 1; + + s = list_entries{index_selected(1)}; + ROI = str2double(s(end-2)); + + ind = bitget(handles.s_ind(:, handles.pulse), ROI) == 1; + + ind = ind & ~isnan(handles.M_X) & ~isnan(handles.M_Y) & ~isnan(handles.Z) & ~isnan(handles.ZZ); + tmp = squeeze(reshape(handles.tag(:,:,:,handles.pulse),size(handles.tag,1)*size(handles.tag,2),1,size(handles.tag,3))); + + for n = 1:size(tmp,2) + tmp(:,n) = tmp(:,n).*handles.channel(n); + end + intens = sum(tmp,2); + + ind1 = handles.M_X >= min(handles.M_X(ind)) & handles.M_X <= max(handles.M_X(ind)) & ... + handles.M_Y >= min(handles.M_Y(ind)) & handles.M_Y <= max(handles.M_Y(ind)) & ... + handles.Z >= min(handles.Z(ind)) & handles.Z <= max(handles.Z(ind)) & ... + handles.ZZ >= min(handles.ZZ(ind)) & handles.ZZ <= max(handles.ZZ(ind)) & ... + intens >= min(intens(ind)) & intens <= max(intens(ind)); + + handles.s_ind(ind1, handles.pulse) = bitset(handles.s_ind(ind1, handles.pulse), ROInum, 1); + end + guidata(hObject, handles); +end + +s = {}; +tst = 1; +for n = 1:handles.maxROI + if handles.ROIlist(n, handles.pulse)==1 + s(tst) = {sprintf('ROI %d_%d',n,handles.pulse)}; + tst = tst+1; + end +end + +set(handles.listbox2,'Value',1); +set(handles.listbox2,'String',s); +listbox2_Callback(handles.listbox2, [], handles); + +plot_graphs(handles) +update_fFLIM(handles) +set(hObject,'String','Add similar'); + + +% --- Executes on button press in UseROI_button. +function UseROI_button_Callback(hObject, eventdata, handles) +% hObject handle to UseROI_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(handles.UseROI_button,'String','Busy'); +set(handles.UseROI_button,'Enable','off'); +pause(0.05); + +list_entries = get(handles.listbox2, 'String'); +index_selected = get(handles.listbox2, 'Value'); + +binning = handles.par_binning; +nx = handles.head.ImgHdr.PixX; +ny = handles.head.ImgHdr.PixY; +tx = floor(nx/binning); +ty = floor(ny/binning); +nch = size(handles.tcspc,1); +nbin = size(handles.tcspc,2); +num_PIE = size(handles.tcspc,3); + +load([handles.pathname handles.timname], 'stim') + +if binning > 1 + tmp = stim(1:binning*tx,:,:,:,:); + tmp = reshape(tmp, binning, tx, ny, nch, nbin, num_PIE); + tmp = squeeze(mean(tmp,1)); + tmp = tmp(:,1:binning*ty,:,:); + tmp = reshape(tmp, tx, binning, ty, nch, nbin, num_PIE); + stim = permute(mean(tmp,2), [1 3 4 5 6 2]); +end + +stim = reshape(stim, tx*ty,nch, nbin, handles.par_num_PIE); + +pat_list_entries = get(handles.Pattern_List, 'String'); + +for n = 1:numel(index_selected) + + s = cell2mat(list_entries(index_selected(n))); + ROI = str2double(s(end-2)); + if ROI == 0 + ROI = 10; + end + p = numel(pat_list_entries)+1 ; + for k = 1:numel(pat_list_entries) + if strcmp(pat_list_entries(k), s) + p = k; + end + end + pat_list_entries(p) = {s}; + + ind = bitget(handles.s_ind(:, handles.pulse), ROI) == 1; + + pat = squeeze(sum(stim(ind,:,:,:),1)); + handles.pat(p,:,:,:) = pat./sum(sum(sum(pat))); + +end + +set(handles.Pattern_List,'Value',1); +set(handles.Pattern_List,'String',pat_list_entries); +set(handles.UseROI_button,'String','Use ROI'); + +guidata(hObject, handles); + +pause(0.05); + + +% --- Executes on button press in LoadPattern_button. +function LoadPattern_button_Callback(hObject, eventdata, handles) +% hObject handle to LoadPattern_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +%set(hObject,'Enable','off'); + +[FileName,PathName] = uigetfile({'*.pat','Pattern';'*.*','All Files'}, ... + 'Load pattern',[handles.pathname 'new.pat'],'MultiSelect', 'on'); + +if ~iscell(FileName) + if FileName ~= 0 + pat = importdata([PathName FileName], 'pat'); + + if ~isempty(pat) + if strcmp(FileName(end-3:end),'.pat') + s = FileName(1:end-4); + end + pat_list_entries = get(handles.Pattern_List, 'String'); + p = numel(pat_list_entries)+1 ; + for n = 1:numel(pat_list_entries) + if strcmp(pat_list_entries(n), s) + p = n; + end + end + + tmp = size(handles.tcspc); + if prod(1.*(size(pat) == tmp)) + pat_list_entries(p) = {s}; + + handles.pat(p,:,:,:) = pat./sum(sum(sum(pat))); + + set(handles.Pattern_List,'Value',1); + set(handles.Pattern_List,'String',pat_list_entries); + elseif (tmp(1)==size(pat,1))&&(tmp(3)==size(pat,3)) + pat_list_entries(p) = {s}; + if tmp(2)3 + [X,Y] = meshgrid(tau, lam(2:end-1)+n*2); + sh = waterfall(X, Y, log10(shiftdim(pat(n,2:end-1,:),1))); + else + [X,Y] = meshgrid(tau, lam+n*2); + sh = waterfall(X, Y, log10(shiftdim(pat(n,:,:),1))); + end + set(sh,'LineWidth',3,'EdgeColor',[0.2 0.2 0.2],'FaceColor',handles.ROIcolor(n,:)); + set(sh,'FaceAlpha',0.5,'EdgeAlpha',0.5); +end +set(R3,'CameraPosition',[200 -300 4]); +set(R3,'Clipping','on'); +hold off + +set(R3,'FontSize',9,'color', [204 204 204]./255); +axis([0 floor(tau(end)) max([lam(1) handles.par_clam_min]) min([lam(end) handles.par_clam_max]) -3 0]) + +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('wavelength of spectral mean / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +zlabel('rel. irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + +set(handles.ShowPattern_button,'String','Show pattern'); +set(handles.Pattern_List,'Value',1); +pause(0.05); +guidata(hObject, handles); + + +% --- Executes on button press in FindAmplitudes_button. +function FindAmplitudes_button_Callback(hObject, eventdata, handles) +% hObject handle to FindAmplitudes_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + + +%set(handles.FindAmplitudes_button,'Enable','off'); + +list_entries = get(handles.Pattern_List, 'String'); +index_selected = get(handles.Pattern_List, 'Value'); + +if numel(index_selected) >= 1 + + pat = handles.pat(index_selected, :,:,:); + list = list_entries(index_selected); + params = zeros(numel(index_selected), 1); + + ind = true(size(params)); + for j=1:size(pat,1) + s = sum(sum(sum(pat(j,:,:,:),4),3),2); + if s > 0 + pat(j,:,:,:) = pat(j,:,:,:)/s; % normalization + else + ind(j) = false; + end + end + + pat = pat(ind,:,:,:); + list = list(ind); + params = params(ind); + + %% select options for analysis + + save('Pattern.mat', 'pat', 'list', 'params'); + s = sprintf('Set_PatternOptions(\''file\'',\''Pattern.mat\'',\''%s\'');',[handles.pathname handles.filename]); + + uiwait(eval(s)); + + load('Pattern.mat', 'params'); + + n1 = size(pat,2); + n2 = size(pat,3); + + handles.mode = sum(params(1,1:2).*[1 2],2); + guidata(hObject, handles); + + handles.ch_ind = params(:,2+(1:n1)) == 1; + handles.ch_ind = permute(repmat(handles.ch_ind,[1 1 n2]),[2 3 1]); + handles.de_ind = params(:,3+n1:end) == 1; + handles.de_ind = permute(repmat(handles.de_ind,[1 1 n1]),[3 2 1]); + + handles.ch_ind = (handles.ch_ind>0)&(handles.de_ind>0); + + e_ch = squeeze(sum(sum(handles.ch_ind,3),2)>0); + e_bin = squeeze(sum(sum(handles.ch_ind,3),1)>0); + e_pie = squeeze(sum(sum(handles.ch_ind,1),2)>0); + + if prod([handles.mode sum(e_ch) sum(e_bin) sum(e_pie)]) > 0 + +% handles.ch_ind = handles.ch_ind(:,e_ch,e_pie); +% handles.ch_ind = permute(repmat(handles.ch_ind, [1 1 1 size(pat,3)]), [1 2 4 3]); + + load([handles.pathname handles.timname], 'stim') + + % Save data pre-processing + + % save('Pre-processed_FRET Slide.mat','stim','pat','-v7.3'); fg; + + stim = stim(:,:,e_ch,e_bin,e_pie); + pat = pat(:,e_ch,e_bin,e_pie); + handles.ch_ind = handles.ch_ind(e_ch,e_bin,e_pie); + + binning = handles.par_binning; + nx = size(stim,1); + ny = size(stim,2); + tx = floor(nx/binning); + ty = floor(ny/binning); + + numpix = tx*ty; + nch = size(stim,3); + nbin = size(stim,4); + num_PIE = size(stim,5); + num_pat = size(pat,1); + + if binning > 1 + tmp = stim(1:binning*tx,:,:,:,:); + tmp = reshape(tmp, binning, tx, ny, nch, nbin, num_PIE); + tmp = squeeze(sum(tmp,1)); + tmp = tmp(:,1:binning*ty,:,:); + tmp = reshape(tmp, tx, binning, ty, nch, nbin, num_PIE); + stim = permute(sum(tmp,2), [1 3 4 5 6 2]); + end + + clear tmp; + + stim = reshape(stim, [numpix nch nbin num_PIE]); % rearrange the transformed signal for convenience + + M = pat; + M = reshape(M,[num_pat nch*nbin*num_PIE]); + handles.ch_ind = reshape(handles.ch_ind, [1 nch*nbin*num_PIE]); + M = M.*repmat(handles.ch_ind, [num_pat 1]); + + if handles.mode == 3 % use spectrum and decay + + tmp = reshape(stim,[numpix nch*nbin*num_PIE]); + tmp = tmp.*repmat(handles.ch_ind, [numpix 1]); + + tmp = reshape(tmp, [numpix nch nbin num_PIE]); + tmp = permute(tmp, [1 2 4 3]); + tmp = reshape(tmp,[numpix nch*num_PIE*nbin]); + + M = reshape(M, [num_pat nch nbin num_PIE]); + M = permute(M, [1 2 4 3]); + M = reshape(M, [num_pat nch*num_PIE*nbin]); + + ebin = nbin; + M(M<0) = 0; + TT = tmp; + TT(TT<0) = 0; + T = TT; + + elseif handles.mode == 1 % use decay only + + handles.ch_ind = reshape(handles.ch_ind, [1 nch nbin num_PIE]); + + tmp = sum(stim.*repmat(handles.ch_ind, [numpix 1]),2); + tmp = reshape(tmp,[numpix nbin*num_PIE]); + + M = reshape(M,[num_pat nch nbin num_PIE]); + M = sum(M,2); + M = reshape(M,[num_pat nbin*num_PIE]); + ebin = nbin; + %% + M(M<0) = 0; + TT = tmp; + TT(TT<0) = 0; + T = TT; + + else % use spectrum only + % handles.mode == 2 + handles.ch_ind = reshape(handles.ch_ind, [1 nch nbin num_PIE]); + + tmp = sum(stim.*repmat(handles.ch_ind, [numpix 1]),3); + tmp = reshape(tmp,[numpix nch*num_PIE]); + + M = reshape(M,[num_pat nch nbin num_PIE]); + M = sum(M,3); + M = reshape(M,[num_pat nch*num_PIE]); + ebin = 1; + %% + M(M<0) = 0; + TT = tmp; + TT(TT<0) = 0; + T = TT; + end + + clear stim TT; + +% reduce effective number of spectral channels only when all +% information is used + if handles.mode == 3 + + kkk = []; + + if handles.mode > 1 + + if handles.mode == 2 + M = reshape(M,[num_pat nch ebin num_PIE]); + MMM = sum(M,3); + MMM = reshape(MMM,[num_pat nch*num_PIE]); + M = permute(M, [1 2 4 3]); + M = reshape(M,[num_pat nch*num_PIE*ebin]); + else + MMM = M; + end + + + for pulse = 1:num_PIE + off = (pulse-1)*nch; + ind = (1:nch)+off; + + [dum,b] = sort(sum(MMM(:,ind),2),'descend'); + + mm = min([numel(b) 5]); + A = MMM(b(1:mm),ind); + + [dum, k] = sort(A,1,'descend'); + + kk = [0 nch]; + for nl = 1:mm + kk = [kk find(diff(k(nl,:))~=0)]; + end + kk = sort(unique(kk)); + + while numel(kk) < mm+1 + [dk, ok] = max(diff(kk)); + kk = sort([kk kk(ok)+round(dk/2)]); + end + kk = off + sort([kk kk(1:end-1)+round(diff(kk)./2)]); + kkk = [kkk kk]; + end + + kk = unique(kkk); + nk = numel(kk)-1; + + if nk>0 + MM = zeros(num_pat,nk*ebin); + TT = zeros(numpix,nk*ebin); + off = num_PIE*nch.*((1:ebin)-1); + for o = 1:numel(off) + for l = 1:nk + MM(:,(o-1)*nk+l) = sum( M(:,off(o)+((kk(l)+1):kk(l+1))),2); + TT(:,(o-1)*nk+l) = sum(tmp(:,off(o)+((kk(l)+1):kk(l+1))),2); + end + end + else + MM = M; + TT = tmp; + end + + MM = reshape(MM,[num_pat nk ebin]); + MM = permute(MM,[1 3 2]); + MM = reshape(MM,[num_pat ebin*nk]); + + TT = reshape(TT,[numpix nk ebin]); + TT = permute(TT,[1 3 2]); + TT = reshape(TT,[numpix ebin*nk]); + else + MM = M; + TT = tmp; + nk = num_PIE; + end + + clear tmp M MMM; + + if handles.mode ~=2 + + kkk = []; + + for chan = 1:nk + off = (chan-1)*ebin; + ind = (1:ebin)+off; + + [tmp, b] = sort(sum(MM(:,ind(32:end)),2),'descend'); + + mm = min([numel(b) 3]); + A = MM(b(1:mm),ind(32:end)); + + [tmp, k] = sort(A,1,'descend'); + + kk = [31 nbin]; + for nl = 1:mm + kk = [kk 32+find(diff(k(nl,:))~=0)]; + end + kk = sort(unique(kk)); + + while numel(kk) < 4 + [dk, ok] = max(diff(kk)); + kk = sort([kk kk(ok)+round(dk/2)]); + end + kk = off + sort([0 kk kk(1:end-1)+round(diff(kk)./3) kk(1:end-1)+round(2*diff(kk)./3)]); + kkk = [kkk kk]; + end + + kk = unique(kkk); + nk = numel(kk)-1; + + if nk>0 + M = zeros(num_pat,nk); + T = zeros(numpix,nk); + for l = 1:nk + M(:,l) = sum(MM(:,(kk(l)+1):kk(l+1)),2); + T(:,l) = sum(TT(:,(kk(l)+1):kk(l+1)),2); + end + else + M = MM; + T = TT; + end + + T(T<0)= 0; + + else + M = MM; + T = TT; + end + end + + nk = size(T,2); % number of bins in pattern data + + % do fourier transform + + ek1 = ceil(tx/2); + ek2 = ceil(ty/2); + + EF = EFilter([tx+2*ek1 ty+2*ek2], 0.80, 0.80, 9); % optional low-pass filter + + T(T<0)= 0; + + T = reshape(T,[tx ty nk]); % tx = ty = numPixX/numPixY + + ftmp = zeros(size(EF,1), size(EF,2), nk); + + for k = 1:nk + tmp = zeros(size(EF,1), size(EF,2)); + tmp(ek1+(1:tx),ek2+(1:ty)) = T(:,:,k); + tmp = EF.*(fftshift(fftshift(fft2(tmp),1),2)); % norm of 2D-fourier-transform of singal components + ftmp(:,:,k) = abs(ifft2(ifftshift(ifftshift(tmp,1),2))); + end + + T = ftmp(ek1+(1:tx),ek2+(1:ty),:); + T(T<0)= 0; + + otmp = sum(T,3); + + T = reshape(T,[numpix nk]); + MMM = M'; + + res = KLF(MMM,T); % Linear unmixing step + + res(res<0)= 0; + res = reshape(res,[tx ty num_pat]); + + res(:,:,num_pat+1) = otmp - sum(res,3); + + set(handles.SaveResults_button,'Enable','on'); + handles.results.pat = pat; + handles.results.params = params; + handles.results.amp = res; + end +end + +handles.res = res; +guidata(hObject, handles); + + + +% --- Executes on button press in MatchResults_button. +function MatchResults_button_Callback(hObject, eventdata, handles) +% hObject handle to MatchResults_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +Plot_Results(handles) + + + +% --- Executes on button press in FitPattern_button. +function FitPattern_button_Callback(hObject, eventdata, handles) +% hObject handle to FitPattern_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +%#function Pattern_Fit + +set(hObject,'Enable','off'); + +list_entries = get(handles.Pattern_List, 'String'); +index_selected = get(handles.Pattern_List, 'Value'); + +if numel(index_selected) >= 1 + + pat = handles.pat(index_selected, :,:,:); + list = list_entries(index_selected); + params = zeros(numel(index_selected), 1); + binw = handles.head.tauw./handles.head.tauw(1); + DC = handles.DC; + aAP = 1 + handles.AP; + + save('Pattern.mat', 'pat', 'list', 'params'); + + handles.filename; + + s = sprintf('Pattern_Fit(\''file\'',\''Pattern.mat\'',\''%s\'');',... + [handles.pathname handles.filename]); + + evalin('base', s); + +end + + +% --- Executes on button press in SaveResults_button. +function SaveResults_button_Callback(hObject, eventdata, handles) +% hObject handle to SaveResults_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +[FileName,PathName] = uiputfile({'*.mat','MatLab-data';... + '*.*','All Files' },'Save results',... + [handles.pathname handles.filename(1:end-4) '_results.mat']); + +results = handles.results; +results.x = handles.head.ImgHdr.X0+(1:handles.par_binning:handles.head.ImgHdr.PixX)*handles.head.ImgHdr.PixelSize; +results.y = handles.head.ImgHdr.Y0+(1:handles.par_binning:handles.head.ImgHdr.PixY)*handles.head.ImgHdr.PixelSize; +results.image = handles.tag; +results.tau = handles.head.tau; + +pat = handles.results.pat; +tcspc = handles.tcspc; +irf = handles.IRF; + +tmp = round(handles.head.tauw./handles.head.tauw(1)); +tau = handles.head.tau; +tau = tau(1) + (tau(2)-tau(1)).*(0:sum(tmp)-1); +ind = [0 cumsum(tmp)]; +for k = 1:numel(tmp) + tst_p(:,:,ind(k)+1:ind(k+1),:) = repmat(pat(:,:,k,:), [1 1 tmp(k) 1 1])./tmp(k); + tst_t(:,ind(k)+1:ind(k+1),:) = repmat(tcspc(:,k,:), [1 tmp(k) 1 1]);% ./tmp(k); + tst_i(:,ind(k)+1:ind(k+1),:) = repmat(irf(:,k,:), [1 tmp(k) 1 1]); % ./tmp(k); +end + +results.tau = tau; +results.pat = tst_p; +results.tcspc = tst_t; +results.IRF = tst_i; + +save([PathName FileName],'results'); + + + +% --- Executes on button press in PlotResults_button. +function PlotResults_button_Callback(hObject, eventdata, handles) +% hObject handle to PlotResults_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +load Get_Params; +scrsz = get(0,'ScreenSize'); + +fwidth = 1200; +fheight = round(2*fwidth/3); +fx = 0.5*(scrsz(3)-fwidth); +fy = 0.5*(scrsz(4)-fheight); + +py1 = 0.06; +py2 = 0.555; +wy = 0.435; +px1 = 0.06; +px2 = 0.39; +px3 = 0.72; +wx = 0.27; + +xl = [399 440 485 540 580 610 630 699]; +yl = [[0 0 0]; [0 0 1]; [0 1 1]; [0 1 0]; [1 1 0]; [1 0.65 0]; [1 0 0]; [1 0 1]]; +lambda = 399:3:699; +spectrum = interp1(xl, yl, lambda); + +d_lambda = (handles.par_lam_start+handles.par_lam_step.*(0:7)); +dl = abs(ones(size(lambda'))*d_lambda - lambda'*ones(size(d_lambda))); +k_ind = mod(find(dl==ones(size(lambda'))*min(dl)),numel(lambda)); + +ntau = handles.head.tau; + +set(handles.PlotResults_button,'String','Busy'); +% set(handles.PlotResults_button,'Enable','off'); +pause(0.05); + +nx = handles.head.ImgHdr.PixX; +ny = handles.head.ImgHdr.PixY; +tx = floor(nx/binning); +ty = floor(ny/binning); +nch = size(handles.tcspc,1); +nbin = size(handles.tcspc,2); + + +load([handles.pathname 'Moments.mat'],'rtau'); +load([handles.pathname handles.timname],'stim'); +load('c_map.mat','map'); + +stim = shiftdim(stim(:,:,:,:,handles.pulse),1); %#ok + +if binning > 1 + tmp = stim(1:binning*tx,:,:,:); + tmp = reshape(tmp, binning, tx, ny, nch, nbin); + tmp = squeeze(mean(tmp,1)); + tmp = tmp(:,1:binning*ty,:); + tmp = reshape(tmp, tx, binning, ty, nch, nbin); + stim = permute(mean(tmp,2), [1 3 4 5 6 2]); +end + +stim = reshape(stim, size(stim,1)*size(stim,2),size(stim,3),size(stim,4)); +rtau = reshape(rtau, size(rtau,1)*size(rtau,2),size(rtau,3),size(rtau,4),size(rtau,5)); + +list_entries = get(handles.listbox2, 'String'); + +for n = 1:numel(list_entries) + + s = list_entries{n}; + ROI = str2double(s(end-2)); + + name = sprintf('Results for ROI %d Excitation pulse %d', ROI, handles.pulse); + + figure(figone+n); + set(gcf,'Position',[fx fy fwidth fheight]); + set(gcf,'Name',name,'NumberTitle','off'); + + colormap(map); + + ind = bitget(handles.s_ind(:, handles.pulse), ROI) == 1; + + % num_pix = sum(ind); + data = reshape(handles.tag, size(handles.tag,1)*size(handles.tag,2),size(handles.tag,3),size(handles.tag,4)); + tavg = reshape(handles.tav, size(handles.tav,1)*size(handles.tav,2),size(handles.tav,3),size(handles.tav,4),size(handles.tav,5)); + + data = data(ind,:,handles.pulse); + tavg = squeeze(tavg(:,:,handles.pulse,:)); + tavg = tavg(ind,:,:); + atau = rtau(ind,:,:,handles.pulse); + + data(datalam(k-1))&(tmp10 + s = s./max(s); + else + s(:) = 0; + end + + ts = 400: 0.5: 700; + cs = interp1(lam, s, ts,'pchip'); + + plot(ts,cs,'-','Color',[1 0 0]); + hold off + + set(R2,'FontSize',9,'color', [204 204 204]./255); + + % axis([10*floor(lind(1)/10) 10*ceil(lind(end)/10) 0 1.1]) + axis([handles.par_clam_min handles.par_clam_max 0 1.1]) + + xlabel('wavelength of spectral mean / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('rel. spectral irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + + R3 = subplot('Position', [px3 py2 wx wy]); + + hold on; + cla + box on; + for ch = 1:size(tavg,2) + la = d_lambda(ch); + tmp = sort(tavg(:,ch,1)); + bw(1) = tmp(round(0.5*numel(tmp))); + bw(2) = tmp(round(0.25*numel(tmp))); + bw(3) = tmp(round(0.75*numel(tmp))); + bw(4) = max(tmp(tmp<(bw(1)+1.5*(bw(3)-bw(2))))); + bw(5) = min(tmp(tmp>(bw(1)-1.5*(bw(3)-bw(2))))); + + + line([la la],[bw(4) bw(5)],'LineWidth',5); + line([la-3 la+3],[bw(1) bw(1)],'Color',[0 0 1],'LineWidth',2); + line([la-3 la+3 la+3 la-3 la-3],[bw(2) bw(2) bw(3) bw(3) bw(2)],'Color',[0 0 1],'LineWidth',1); + end + hold off + + set(R3,'FontSize',9,'color', [204 204 204]./255); + + axis([10*floor(lam(1)/10) 10*ceil(lam(end)/10) handles.par_tau_min handles.par_tau_max]) + + xlabel('detector wavelength / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('mean fluorecence lifetime / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + R4 = subplot('Position', [px1 py1 wx wy]); + + cla + + M_X = data.*squeeze(tavg(:,:,1)); + M_X = squeeze(sum(M_X,2)./sum(data,2)); + + M_Y = data.*squeeze(tavg(:,:,2)); + M_Y = squeeze(sum(M_Y,2)./sum(data,2)); + + cscatter(gca, M_X, M_Y); + + set(R4,'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); + + axis([handles.par_tau_min handles.par_tau_max handles.par_cum2_min handles.par_cum2_max]); + xlabel('mean fluorecence lifetime / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('sqrt(2nd cumulant) / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + R5 = subplot('Position', [px2 py1 wx wy]); + + hold on + cla + box on + + M_X = data.*squeeze(atau(:,1,:)); + M_X = squeeze(sum(M_X,2)./sum(data,2)); + + M_Y = data.*squeeze(atau(:,2,:)); + M_Y = squeeze(sum(M_Y,2)); + + amax = max(M_Y); + + scatter(M_X, M_Y, 10, [1 0 0],'diamond','Clipping','on'); + + M_X = data.*squeeze(atau(:,3,:)); + M_X = squeeze(sum(M_X,2)./sum(data,2)); + + M_Y = data.*squeeze(atau(:,4,:)); + M_Y = squeeze(sum(M_Y,2)); + + amax = max([1 amax max(M_Y)]); + + scatter(M_X, M_Y, 10, [0 1 0],'diamond','Clipping','on'); + + set(R5,'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); + + axis([handles.par_tau_min 8*handles.par_tau_max 0 ceil(amax)]); + xlabel('fluorecence lifetime / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('Amplitude','FontWeight','bold','FontSize',10,'FontAngle','italic'); + hold off + + + R6 = subplot('Position', [px3 py1 wx wy]); + cla + + M_X = data.*squeeze(atau(:,1,:)); + M_X = squeeze(sum(M_X,2)./sum(data,2)); + + M_Y = data.*squeeze(atau(:,3,:)); + M_Y = squeeze(sum(M_Y,2)./sum(data,2)); + + cscatter(gca, M_X, M_Y); + + set(R6,'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); + + axis([handles.par_tau_min 8*handles.par_tau_max handles.par_tau_min 8*handles.par_tau_max]); + + xlabel('fluorescence lifetime 1 / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('fluorescence lifetime 2 / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +end + +set(handles.PlotResults_button,'String','Plot ROI results'); +set(handles.PlotResults_button,'Enable','on'); +pause(0.05); + + +function [M_X, M_Y, Z, ZZ] = compute_data(handles) + +tag = handles.tag(:,:,:,handles.pulse); +tav = handles.tav(:,:,:,handles.pulse,1:2); + +for n = 1:size(tag,3) + tag(:,:,n) = tag(:,:,n).*handles.channel(handles.pulse,n); +end + +W = tag; +W(W= handles.par_Threshold; +t_m = ind.*t_m; + +save([handles.pathname 'fFLIM.mat'], 't_m'); + + +%% plot_graphs + +function plot_graphs(handles) + +binning = handles.par_binning; + +x = handles.head.ImgHdr.X0+(1:binning:handles.head.ImgHdr.PixX)*handles.head.ImgHdr.PixelSize; +y = handles.head.ImgHdr.Y0+(1:binning:handles.head.ImgHdr.PixY)*handles.head.ImgHdr.PixelSize; + +ind_x = x >= handles.plt_x_min & x <= handles.plt_x_max; +ind_y = y >= handles.plt_y_min & y <= handles.plt_y_max; + +xl = [399 440 485 540 580 610 630 699]; +yl = [[0 0 0]; [0 0 1]; [0 1 1]; [0 1 0]; [1 1 0]; [1 0.65 0]; [1 0 0]; [1 0 1]]; +lambda = 399:3:699; +spectrum = interp1(xl, yl, lambda); + +lims = [handles.plt_tau_min handles.plt_tau_max]; + +val = squeeze(handles.tav(:,:,:,handles.pulse,1)); + +data = squeeze(handles.tag(:,:,:,handles.pulse)); +data = data.*(data >= handles.par_Threshold); + +for n = 1:size(data,3) + data(:,:,n) = data(:,:,n).*handles.channel(n); + val(:,:,n) = val(:,:,n).*handles.channel(n); +end + +val = sum(val.*data,3)./sum(data,3); + +data = squeeze(sqrt(sum(data,3))); +tmp = max(max(data)); +data = data./tmp; + +data(data<0)=0; +data = repmat(data, [1 1 3]); + +val = reshape(val,size(val,1)*size(val,2),1); + +val(isnan(val)) = 0; +val(vallims(2)) = lims(2); + +k = 2 + round((val-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-2)); +k(k<2) = 1; + +im = spectrum(k,:); +im = reshape(im,size(data,1),size(data,2),3); +im = im.*data; + +axes(handles.axes1) + +hold(handles.axes1,'off'); +imagesc(x(ind_x), y(ind_y), im(ind_y,ind_x,:)); % data(ind_y,ind_x,:)); +hold(handles.axes1,'on'); + +% colormap(spectrum) +alpha = zeros(size(handles.tag,1), size(handles.tag,2)); +ovl = zeros(numel(alpha),3); +for n = 1:handles.maxROI + if handles.ROIlist(n,handles.pulse) == 1 + tst = bitget(handles.s_ind(:,handles.pulse), n)==1; + alpha(tst==1) = 1; + for k = 1:3 + tc = repmat(handles.ROIcolor(n,k),[size(data,1) size(data,2) 1]); + ovl(tst,k) = tc(tst); + end + end +end +ovl = data.*reshape(ovl, size(data,1), size(data,2), 3); + +iim2 = image(x(ind_x),y(ind_y), ovl(ind_y,ind_x,:)); +set(iim2,'AlphaData',alpha(ind_y,ind_x)); + +set(handles.axes1, ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9, ... + 'PlotBoxAspectRatio',[1 1 1]); +xlabel(handles.axes1, 'x / µm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel(handles.axes1, 'y / µm','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +% axes(handles.axes3) + +ind = handles.M_X > handles.plt_tau_min & handles.M_X < handles.plt_tau_max & ... + handles.M_Y > handles.plt_cum2_min & handles.M_Y< handles.plt_cum2_max & ... + handles.Z > handles.plt_clam_min & handles.Z < handles.plt_clam_max &... + handles.ZZ > handles.plt_wlam_min & handles.ZZ < handles.plt_wlam_max; + + +set(handles.axes3,'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9, ... + 'Color',[50 50 50]./255); + +cscatter(handles.axes3, handles.M_X(ind), handles.M_Y(ind)); +hold(handles.axes3, 'on'); + +axis(handles.axes3, [handles.plt_tau_min handles.plt_tau_max handles.plt_cum2_min handles.plt_cum2_max]); + +set(handles.axes3,'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9, ... + 'Color',[50 50 50]./255); +xlabel(handles.axes3, '< \tau > / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel(handles.axes3, 'sqrt(2nd cumulant) / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +% for n = 1:handles.maxROI +% if handles.ROIlist(n,handles.pulse) == 1 +% ind_1 = ind & bitget(handles.s_ind(:,handles.pulse), n)==1; +% end +% end + +% axes(handles.axes2) + +cscatter(handles.axes2, handles.ZZ(ind), handles.Z(ind)); +hold(handles.axes2, 'on'); + +set(handles.axes2, 'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); + +xlabel(handles.axes2,'\Delta \lambda (nm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel(handles.axes2,'\lambda_0 (nm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); +axis(handles.axes2, [handles.plt_wlam_min handles.plt_wlam_max handles.plt_clam_min handles.plt_clam_max]); + +% for n = 1:handles.maxROI +% if handles.ROIlist(n,handles.pulse) == 1 +% ind_1 = ind & bitget(handles.s_ind(:,handles.pulse), n)==1; +% end +% %variables for onegraphs.m +% % N(n,:) = histc((lam_start+lam_step.*Z(bitget(s_ind(:,pulse), n)==1,pulse)),edges); +% % N(n,:) = N(n,:) / sum(N(n,:)); +% end + +% axes(handles.axes4) + +cscatter(handles.axes4,handles.M_X(ind),handles.Z(ind)); +hold(handles.axes4, 'on'); +set(handles.axes4,'PlotBoxAspectRatio',[1 1 1], ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); + +xlabel(handles.axes4, '< \tau > / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel(handles.axes4, '\lambda_0 / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +axis(handles.axes4, [handles.plt_tau_min handles.plt_tau_max handles.plt_clam_min handles.plt_clam_max]); + +for n = 1:handles.maxROI + if handles.ROIlist(n,handles.pulse) == 1 + ind_1 = ind & bitget(handles.s_ind(:,handles.pulse), n)==1; + scatter(handles.axes4,handles.M_X(ind_1), handles.Z(ind_1),10,handles.ROIcolor(n,:),'diamond','Clipping','on'); + scatter(handles.axes2,handles.ZZ(ind_1), handles.Z(ind_1),10,handles.ROIcolor(n,:),'diamond','Clipping','on'); + scatter(handles.axes3,handles.M_X(ind_1),handles.M_Y(ind_1),10,handles.ROIcolor(n,:),'diamond','Clipping','on'); + end + %variables for onegraphs.m + % N(n,:) = histc((lam_start+lam_step.*Z(bitget(s_ind(:,pulse), n)==1,pulse)),edges); + % N(n,:) = N(n,:) / sum(N(n,:)); +end + +hold(handles.axes1, 'off'); +hold(handles.axes2, 'off'); +hold(handles.axes3, 'off'); +hold(handles.axes4, 'off'); + + +%% select_data + +function [s_ind] = select_data(handles, ROInum) + +s_ind = handles.s_ind; + +axes(handles.axes1); + +[xi,yi] = ginput(1); +pt1 = get(handles.axes1, 'CurrentPoint'); +pt2 = get(handles.axes2, 'CurrentPoint'); +pt3 = get(handles.axes3, 'CurrentPoint'); +pt4 = get(handles.axes4, 'CurrentPoint'); + + +t1 = xi-[pt1(1,1) pt2(1,1) pt3(1,1) pt4(1,1)]; +t2 = yi-[pt1(1,2) pt2(1,2) pt3(1,2) pt4(1,2)]; +p = find((t1+t2)==0); + +if isempty(p) + p = abs(t1+t2); + p = find(p==min(p)); +end + +if p==1 + axes(handles.axes1); +elseif p==2 + axes(handles.axes2); +elseif p==3 + axes(handles.axes3); +else + axes(handles.axes4); +end + +hold on + +plot(xi,yi,'+','Color',handles.ROIcolor(ROInum,:)) +xy = [xi;yi]; +n = 1; +but = 1; +while but == 1 + [xi,yi,but] = ginput(1); + plot(xi,yi,'+','Color',handles.ROIcolor(ROInum,:)) + n = n+1; + xy(:,n) = [xi;yi]; +end +n = n+1; +xy(:,n) = xy(:,1); + +s1 = [xy(1,n-1)-xy(1,2); xy(2,n-1)-xy(2,2)]; + +xy = [-s1 xy -s1]; + +cs = spline(1:n, xy); +% Interpolate with a spline curve and finer spacing. +ts = 1: 0.1: n; +xys = ppval(cs,ts); + +% Plot the interpolated curve. +plot(xys(1,:),xys(2,:),'Color',handles.ROIcolor(ROInum,:)); +hold off + +if p==1 % Intensity image + + t_ind = reshape(s_ind(:,handles.pulse),size(handles.tag,1),size(handles.tag,2)); + + mx = round((xys(1,:)-handles.head.ImgHdr.X0)./handles.head.ImgHdr.PixelSize/handles.par_binning); + my = round((xys(2,:)-handles.head.ImgHdr.Y0)./handles.head.ImgHdr.PixelSize/handles.par_binning); + mx(mx<1) = 1; + my(my<1) = 1; + mx(mx>size(t_ind,2)) = size(t_ind,2); + my(my>size(t_ind,1)) = size(t_ind,1); + + dmx = abs(diff([0 mx])); + dmy = abs(diff([0 my])); + tmx = mx(1); + tmy = my(1); + for n = 2:numel(dmx)-1 + if (dmx(n)+dmy(n))~=0 + if (dmx(n)>1)||(dmy(n)>1) + if dmx(n)>dmy(n) + nx = mx(n-1):sign(mx(n)-mx(n-1)):mx(n); + nx = nx(2:end); + ny = round(interp1([mx(n-1) mx(n)],[my(n-1) my(n)], nx)); + tmx = [tmx nx]; + tmy = [tmy ny]; + else + ny = my(n-1):sign(my(n)-my(n-1)):my(n); + ny = ny(2:end); + nx = round(interp1([my(n-1) my(n)],[mx(n-1) mx(n)], ny)); + tmx = [tmx nx]; + tmy = [tmy ny]; + end + else + tmx = [tmx mx(n)]; + tmy = [tmy my(n)]; + end + end + end + + for n = 1:numel(tmx) + t_ind(tmy(n),tmx(n)) = bitset(t_ind(tmy(n),tmx(n)), ROInum); + end + y_min = min(tmy); + y_max = max(tmy); + x_min = min(tmx)+1; + x_max = max(tmx)-1; + for x = x_min:x_max + tmp = find(bitget(t_ind(y_min:y_max,x), ROInum)==1); + tmp(diff([tmp; 2*y_max])==1) = []; + if mod(numel(tmp),2)==0 + while numel(tmp)>1 + t_ind(y_min-1+(tmp(1)+1:tmp(2)-1),x) = bitset(t_ind(y_min-1+(tmp(1)+1:tmp(2)-1),x), ROInum); + tmp = tmp(3:end); + end + end + end + y_min = y_min+1; + y_max = y_max-1; + x_min = x_min-1; + x_max = x_max+1; + for y = y_min:y_max + tmp = find(bitget(t_ind(y,x_min:x_max), ROInum)==1); + tmp(diff([tmp 2*x_max])==1) = []; + if mod(numel(tmp),2)==0 + while numel(tmp)>1 + t_ind(y,x_min-1+(tmp(1)+1:tmp(2)-1)) = bitset(t_ind(y,x_min-1+(tmp(1)+1:tmp(2)-1)), ROInum); + tmp = tmp(3:end); + end + end + end + s_ind(:,handles.pulse) = reshape(t_ind, numel(t_ind),1); + +elseif p==2 % wavelength diagram + + mx = xys(1,:); + my = xys(2,:); + y_min = min(my); + y_max = max(my); + x_min = min(mx); + x_max = max(mx); + + for n=1:numel(handles.M_X) + if (handles.ZZ(n)>=x_min)&&(handles.ZZ(n)<=x_max)&&(handles.Z(n)>=y_min)&&(handles.Z(n)<=y_max) + tx = mx - handles.ZZ(n); + ty = my - handles.Z(n); + dx = find(diff(sign(tx))); + dy = find(diff(sign(ty))); + y = ty(dx) - tx(dx).*(ty(dx) - ty(dx+1))./(tx(dx)-tx(dx+1)); + x = tx(dy) - ty(dy).*(tx(dy) - tx(dy+1))./(ty(dy)-ty(dy+1)); + y = sign(y); + x = sign(x); + tmp = mod(numel(find(x<0)),2)+mod(numel(find(x>0)),2)+mod(numel(find(y<0)),2)+mod(numel(find(y>0)),2); + if tmp>2 + s_ind(n,handles.pulse) = bitset(s_ind(n,handles.pulse), ROInum); + elseif numel(find(x==0))||numel(find(y==0)) + s_ind(n,handles.pulse) = bitset(s_ind(n,handles.pulse), ROInum); + end + end + end + +elseif p==3 % moments plot + + mx = xys(1,:); + my = xys(2,:); + y_min = min(my); + y_max = max(my); + x_min = min(mx); + x_max = max(mx); + + for n=1:numel(handles.M_X) + if (handles.M_X(n)>=x_min)&&(handles.M_X(n)<=x_max)&&(handles.M_Y(n)>=y_min)&&(handles.M_Y(n)<=y_max) + tx = mx - handles.M_X(n); + ty = my - handles.M_Y(n); + dx = find(diff(sign(tx))); + dy = find(diff(sign(ty))); + y = ty(dx) - tx(dx).*(ty(dx) - ty(dx+1))./(tx(dx)-tx(dx+1)); + x = tx(dy) - ty(dy).*(tx(dy) - tx(dy+1))./(ty(dy)-ty(dy+1)); + y = sign(y); + x = sign(x); + tmp = mod(numel(find(x<0)),2)+mod(numel(find(x>0)),2)+mod(numel(find(y<0)),2)+mod(numel(find(y>0)),2); + if tmp>2 + s_ind(n,handles.pulse) = bitset(s_ind(n,handles.pulse), ROInum); + elseif numel(find(x==0))||numel(find(y==0)) + s_ind(n,handles.pulse) = bitset(s_ind(n,handles.pulse), ROInum); + end + end + end + +elseif p==4 % tau-wavelength diagram + + mx = xys(1,:); + my = xys(2,:); + y_min = min(my); + y_max = max(my); + x_min = min(mx); + x_max = max(mx); + + for n=1:numel(handles.M_X) + if (handles.M_X(n)>=x_min)&&(handles.M_X(n)<=x_max)&&(handles.Z(n)>=y_min)&&(handles.Z(n)<=y_max) + tx = mx - handles.M_X(n); + ty = my - handles.Z(n); + dx = find(diff(sign(tx))); + dy = find(diff(sign(ty))); + y = ty(dx) - tx(dx).*(ty(dx) - ty(dx+1))./(tx(dx)-tx(dx+1)); + x = tx(dy) - ty(dy).*(tx(dy) - tx(dy+1))./(ty(dy)-ty(dy+1)); + y = sign(y); + x = sign(x); + tmp = mod(numel(find(x<0)),2)+mod(numel(find(x>0)),2)+mod(numel(find(y<0)),2)+mod(numel(find(y>0)),2); + if tmp>2 + s_ind(n,handles.pulse) = bitset(s_ind(n,handles.pulse), ROInum); + elseif numel(find(x==0))||numel(find(y==0)) + s_ind(n,handles.pulse) = bitset(s_ind(n,handles.pulse), ROInum); + end + end + end + +end + + +%% update_fFLIM + +function update_fFLIM(handles) + +pulse = handles.pulse; +binning = handles.par_binning; +nx = handles.head.ImgHdr.PixX; +ny = handles.head.ImgHdr.PixY; +tx = floor(nx/binning); +ty = floor(ny/binning); +nch = size(handles.tcspc,1); +nbin = size(handles.tcspc,2); +num_PIE = size(handles.tcspc,3); +tau = handles.head.tau; +binw = handles.head.tauw./handles.head.tauw(1); + +x = handles.head.ImgHdr.X0+(1:binning:handles.head.ImgHdr.PixX)*handles.head.ImgHdr.PixelSize; +y = handles.head.ImgHdr.Y0+(1:binning:handles.head.ImgHdr.PixY)*handles.head.ImgHdr.PixelSize; + +xl = [399 440 485 540 580 610 630 699]; +yl = [[0 0 0]; [0 0 1]; [0 1 1]; [0 1 0]; [1 1 0]; [1 0.65 0]; [1 0 0]; [1 0 1]]; +lambda = 399:3:699; +spectrum = interp1(xl, yl, lambda); + +figure(handles.figMA+pulse); +name = sprintf('update FastFLIM %d', pulse); +set(gcf,'Name',name,'NumberTitle','off'); + +p1 = 0.06; +p2 = 0.555; +w = 0.435; + +load([handles.pathname handles.timname], 'stim'); + +if binning > 1 + tmp = stim(1:binning*tx,:,:,:,:); + tmp = reshape(tmp, binning, tx, ny, nch, nbin, num_PIE); + tmp = squeeze(mean(tmp,1)); + tmp = tmp(:,1:binning*ty,:,:); + tmp = reshape(tmp, tx, binning, ty, nch, nbin, num_PIE); + stim = permute(mean(tmp,2), [1 3 4 5 6 2]); +end + +t_m = squeeze(handles.tav(:,:,:,handles.pulse,1)); %#ok + +W = squeeze(handles.tag(:,:,:,handles.pulse)); +V = squeeze(stim(:,:,:,:,handles.pulse)); %#ok + +W(W1 + V = squeeze(sum(V,3)); +end + +lam = (handles.par_lam_start+handles.par_lam_step.*(-1:size(W,3))); +ts = handles.par_clam_min: 1: handles.par_clam_max; +tmp = reshape(W, size(W,1).*size(W,2), size(W,3)); + +S3 = subplot('Position', [p2 p1 w w]); + +hold on; +cla +box on; + +for l = 1:handles.maxROI + if handles.ROIlist(l,handles.pulse) == 1 + ind = bitget(handles.s_ind(:,pulse), l)==1; + if sum(ind)>0 + s = squeeze(sum(tmp(ind,:),1)); + s = [0; s(:); 0]./max(s); + plot(ts,interp1(lam, s, ts,'pchip'),'-','Color',handles.ROIcolor(l,:)); + end + end +end +hold off + +set(S3,'FontSize',9,'color', [204 204 204]./255); + +% axis([10*floor(lind(1)/10) 10*ceil(lind(end)/10) 0 1.1]) +axis([handles.par_clam_min handles.par_clam_max 0 1.1]) + +xlabel('wavelength of spectral mean / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('rel. spectral irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +S4 = subplot('Position', [p2 p2 w w]); + +hold on; +cla +box on; + +for n = 1:handles.maxROI + if handles.ROIlist(n,handles.pulse)==1 + tmp = reshape(V, numel(handles.s_ind(:,pulse)), nbin); + ind = bitget(handles.s_ind(:,pulse), n)==1; + tmp = squeeze(sum(tmp(ind,:),1)); + tmp = tmp./(ones(size(tmp,1))*handles.head.tauw); + tmp(tmp<0) = 1; + plot(tau,log10(tmp./max(tmp)),'-','Color',handles.ROIcolor(n,:)); + clear tmp; + end +end +hold off; + +set(S4,'FontSize',9,'color', [204 204 204]./255); + +axis([0 floor(tau(end)) -3 0.1]) + +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('log (rel. frequency)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + +S1 = subplot('Position', [p1 p2 w w]); + +data = squeeze(handles.tag(:,:,:,handles.pulse)); + +for n = 1:size(data,3) + data(:,:,n) = data(:,:,n).*handles.channel(n); +end + +data = squeeze(sqrt(sum(data,3))); +tmp = max(max(data)); +data = data./tmp; + +data(data<0)=0; + +tmp = repmat(data, [1 1 3]); + +lims = [handles.par_tau_min handles.par_tau_max]; + +val = reshape(t_m,numel(t_m),1); %#ok + +val(isnan(val)) = 0; +val(vallims(2)) = lims(2); + +k = 2 + round((val-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-2)); +k(k<2) = 1; + +im = spectrum(k,:); +im = reshape(im,size(tmp,1),size(tmp,2),3); +im = im.*tmp; + +alpha = zeros(size(handles.tag,1),size(handles.tag,2)); +ovl = zeros(numel(alpha),3); +for n = 1:handles.maxROI + if handles.ROIlist(n,handles.pulse) == 1 + tst = bitget(handles.s_ind(:,pulse), n)==1; + alpha(tst==1) = 1; + for k = 1:3 + tc = repmat(handles.ROIcolor(n,k),[size(im,1) size(im,2) 1]); + ovl(tst,k) = tc(tst); + end + end +end +ovl = tmp.*reshape(ovl, size(im,1), size(im,2), 3); + +image(x,y,im) +hold on; + +colormap(spectrum) + +set(S1,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'CLim', lims, ... + 'color', [0 0 0]); + +xlabel('x / µm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('y / µm','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +tst = 2 + round(((lims(1):.5:lims(2))-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-3)); +n= 1; +for ttst = lims(1):0.5:lims(2) + stst(n) = cellstr(sprintf('%4.1f',ttst)); + n = n+1; +end + +colorbar('CLim', lims, 'YTickMode','manual','XColor',[0 0 0],'YColor',[0 0 0],'Box','off','YTick', tst, ... + 'FontSize',9, 'YTickLabel',stst,'TickDir','out'); + +iim2 = image(x,y, ovl); +set(iim2,'AlphaData',alpha); + +hold off + +S2 = subplot('Position', [p1 p1 w w]); + +lims = [399 699]; + +K = 1:size(W,3); +K = repmat(reshape(K,[1 1 numel(K)]),[size(W,1) size(W,2) 1]); + +tZ = W.*K; +tZ = handles.par_lam_start + handles.par_lam_step.*(sum(tZ,3)./sum(W,3)-1.0); + +val = tZ; +val = reshape(val,size(val,1)*size(val,2),1); + +val(isnan(val)) = 0; +val(vallims(2)) = lims(2); + +k = 2 + round((val-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-3)); +k(k<2) = 1; + +im = spectrum(k,:); +im = reshape(im,size(tmp,1),size(tmp,2),3); +im = im.*tmp; + +image(x,y,im) +hold on; + +set(S2,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'CLim', lims, ... + 'color', [0 0 0]); +xlabel('x / µm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('y / µm','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +tst = 2 + round(((440:40:680)-lims(1))./(lims(2)-lims(1)).*(size(spectrum,1)-3)); +colorbar('CLim', lims, 'XColor',[0 0 0],'YColor',[0 0 0],'Box','off','YTick', tst, ... + 'FontSize',9, 'YTickLabel',{'440', '480', '520', '560', '600', '640', '680'},'TickDir','out'); + +iim3 = image(x,y, ovl); +set(iim3,'AlphaData',alpha); + +hold off + +%% + +function [] = Plot_Results(handles) + +list_entries = get(handles.Pattern_List, 'String'); +index_selected = get(handles.Pattern_List, 'Value'); +list = list_entries(index_selected); + +if isfield(handles, 'k') + k = handles.k; +end +res = handles.res; + +nx = size(res,1); +ny = size(res,2); +num_pat = size(res,3)-1; + +scrsz = get(0,'ScreenSize'); + +fwidth = 800; +fheight = round(2*fwidth/3); +fx = 0.5*(scrsz(3)-fwidth); +fy = 0.5*(scrsz(4)-fheight); + +py1 = 0.10; +px1 = 0.06; +wy = 0.88; +wx = 0.88; + +x = handles.head.ImgHdr.X0+(1:handles.par_binning:handles.head.ImgHdr.PixX)*handles.head.ImgHdr.PixelSize; +y = handles.head.ImgHdr.Y0+(1:handles.par_binning:handles.head.ImgHdr.PixY)*handles.head.ImgHdr.PixelSize; + +res = reshape(res,[nx*ny num_pat+1]); +lims = [0 max(max(res))]; +if lims(2) <= lims(1) + lims(2) = lims(1)+1; +end + +%map = [0 0 0; 0 0 1; 0 1 1; 0 1 0; 1 1 0; 1 0 0; 0.5 0 0]; +%map1 = interp1(linspace(0, 1, 7), map, linspace(0, 1, 256)); + +map1 = gray; + +res = reshape(res,[nx ny num_pat+1]); + +for n = 1:num_pat+1 + if n>num_pat + name = sprintf('Residuals'); + else + s = cell2mat(list(n,:)); + name = sprintf('Pattern: %s', s); + end + + figure(handles.figPA+n); + + set(gcf,'Position',[fx fy fwidth fheight]); + set(gcf,'Name',name,'NumberTitle','off'); + R1 = subplot('Position', [px1 py1 wx wy]); + colormap(map1); + hold on; + cla + imagesc(x,y,res(:,:,n)); +% imagesc(x,y,res(:,:,n).*lims(2)./max(max(res(:,:,n)))); + + set(R1,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'CLim', [0 max(max(res(:,:,n)))], ... % Change + 'color', [0 0 0]); + + xlabel('x (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('y (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + m = n; + + colorbar('YColor',[0 0 0]) +end + +if exist('k','var') + if handles.match == 1 + name = sprintf('%s: lifetime fit', cell2mat(list(k,:))); + elseif handles.match == 2 || handles.match ==3 + name = sprintf('FRET Efficiency'); + end + figure(handles.figPA+m+1); + + set(gcf,'Position',[fx fy fwidth fheight]); + set(gcf,'Name',name,'NumberTitle','off'); + R1 = subplot('Position', [px1 py1 wx wy]); + + xl = [399 460 550 640 699];% 699]; + yl = [[0 0 1]; [0 1 1]; [0 1 0]; [1 1 0]; [1 0 0]];%; [1 0 1]]; + lambda = 399:3:699; + spectrum = interp1(xl, yl, lambda); + + %intens = squeeze(sqrt(sum(handles.tag,3))); + intens = squeeze(squeeze(res(:,:,k))); + intens = intens./max(max(intens)); + + tmp = repmat(intens(:,:), [1 1 3]); + + tmp_lims = [min(handles.vParam) max(handles.vParam)]; + + val = handles.vParamDist; + + val(isnan(val)) = 0; + val(valtmp_lims(2)) = tmp_lims(2); + + g = 2 + round((val-tmp_lims(1))./(tmp_lims(2)-tmp_lims(1)).*(size(spectrum,1)-2)); + g(g<2) = 1; + + im = spectrum(g,:); + im = reshape(im,size(tmp,1),size(tmp,2),3); + im = im.*tmp; + + image(x,y,im) + + colormap(spectrum) + + set(R1,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'CLim', tmp_lims, ... + 'color', [0 0 0]); + + xlabel('x (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('y (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + if handles.match == 1 + tst = 2 + round(((tmp_lims(1):.5:tmp_lims(2))-tmp_lims(1))./(tmp_lims(2)-tmp_lims(1)).*(size(spectrum,1)-3)); + n= 1; + for ttst = tmp_lims(1):0.5:tmp_lims(2) + stst(n) = cellstr(sprintf('%4.1f',ttst)); + n = n+1; + end + colorbar('CLim', tmp_lims, 'YTickMode','manual','XColor',[0 0 0],'YColor',[0 0 0],'Box','off','YTick', tst, ... + 'FontSize', 9,'TickDir','out', 'YTickLabel',stst); + elseif handles.match == 2 || handles.match == 3 + tst = 2 + round(((tmp_lims(1):5:tmp_lims(2))-tmp_lims(1))./(tmp_lims(2)-tmp_lims(1)).*(size(spectrum,1)-3)); + n= 1; + for ttst = tmp_lims(1):5:tmp_lims(2) + stst(n) = cellstr(sprintf('%4.1f',ttst)); + n = n+1; + end + colorbar('CLim', tmp_lims, 'YTickMode','manual','XColor',[0 0 0],'YColor',[0 0 0],'Box','off','YTick', tst, ... + 'FontSize', 9,'TickDir','out', 'YTickLabel',stst); + end +end + + +if handles.match == 2 || handles.match == 3 + + Binding = 100.*res(:,:,1)./(res(:,:,1)+res(:,:,2)); + + name = sprintf('Binding %d', cell2mat(list(k,:))); + + figure(handles.figPA+m+2); + + set(gcf,'Position',[fx fy fwidth fheight]); + set(gcf,'Name',name,'NumberTitle','off'); + R1 = subplot('Position', [px1 py1 wx wy]); + + xl = [399 460 550 640 699];% 699]; + yl = [[0 0 1]; [0 1 1]; [0 1 0]; [1 1 0]; [1 0 0]];%; [1 0 1]]; + lambda = 399:3:699; + spectrum = interp1(xl, yl, lambda); + + %intens = squeeze(sqrt(sum(handles.tag,3))); + intens = squeeze(res(:,:,1)+res(:,:,2)); + intens = intens./max(max(intens)); + + tmp = repmat(intens(:,:), [1 1 3]); + + tmp_lims = [0 100]; + + Binding = squeeze(Binding); + Binding(isnan(Binding)) = tmp_lims(2); + Binding(Bindingtmp_lims(2)) = tmp_lims(2); + + g = 2 + round((Binding-tmp_lims(1))./(tmp_lims(2)-tmp_lims(1)).*(size(spectrum,1)-2)); + g(g<2) = 1; + + im = spectrum(g,:); + im = reshape(im,size(tmp,1),size(tmp,2),3); + im = im.*tmp; + + image(x,y,im) + + colormap(spectrum) + + set(R1,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'CLim', tmp_lims, ... + 'color', [0 0 0]); + + xlabel('x (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + ylabel('y (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + + + tst = 2 + round(((tmp_lims(1):10:tmp_lims(2))-tmp_lims(1))./(tmp_lims(2)-tmp_lims(1)).*(size(spectrum,1)-3)); + n= 1; + for ttst = tmp_lims(1):10:tmp_lims(2) + stst(n) = cellstr(sprintf('%4.1f',ttst)); + n = n+1; + end + colorbar('CLim', tmp_lims, 'YTickMode','manual','XColor',[0 0 0],'YColor',[0 0 0],'Box','off','YTick', tst, ... + 'FontSize', 9,'TickDir','out', 'YTickLabel',stst); +end + + + +name = sprintf('Composite'); + +im = MakeComposite('data',res(:,:,1:num_pat),'list',list); + +figure(handles.figPA+num_pat+3); + +set(gcf,'Position',[fx fy fwidth fheight]); +set(gcf,'Name',name,'NumberTitle','off'); +R1 = subplot('Position', [px1 py1 wx wy]); + +hold on; + +cla + +image(x,y,reshape(im,[nx ny 3])) + +set(R1,'DataAspectRatio', [1,1,1], ... + 'PlotBoxAspectRatio',[1 1 1], ... + 'XDir','normal', ... + 'YDir','reverse', ... + 'FontSize',9,... + 'CLim', lims, ... + 'color', [0 0 0]); + +xlabel('x (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('y (µm)','FontWeight','bold','FontSize',10,'FontAngle','italic'); + +hold off + +s = {}; +tst = 1; +for n = 1:handles.maxROI + if handles.ROIlist(n, handles.pulse)==1 + s(tst) = {sprintf('ROI %d_%d',n,handles.pulse)}; + tst = tst+1; + end +end +set(handles.listbox2,'Value',1); +set(handles.listbox2,'String',s); +listbox2_Callback(handles.listbox2, [], handles); + +plot_graphs(handles) + + +% --- Executes on button press in Plot_Results_button. +function Plot_Results_button_Callback(hObject, eventdata, handles) +% hObject handle to Plot_Results_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +im = Plot_UnmixingResults(); +handles.im =im; +guidata(hObject, handles); diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_Params.fig b/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_Params.fig new file mode 100644 index 0000000..86b4ba0 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_Params.fig differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_Params.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_Params.m new file mode 100644 index 0000000..b8d1314 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_Params.m @@ -0,0 +1,862 @@ +function varargout = Set_Params(varargin) +% SET_PARAMS M-file for Set_Params.fig +% SET_PARAMS, by itself, creates a new SET_PARAMS or raises the existing +% singleton*. +% +% H = SET_PARAMS returns the handle to a new SET_PARAMS or the handle to +% the existing singleton*. +% +% SET_PARAMS('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in SET_PARAMS.M with the given input arguments. +% +% SET_PARAMS('Property','Value',...) creates a new SET_PARAMS or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before Set_Params_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to Set_Params_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 Set_Params + +% Last Modified by GUIDE v2.5 06-Mar-2014 13:18:22 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @Set_Params_OpeningFcn, ... + 'gui_OutputFcn', @Set_Params_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 Set_Params is made visible. +function Set_Params_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 Set_Params (see VARARGIN) + +% Choose default command line output for Set_Params +handles.output = hObject; + +% Update handles structure + +lam_start = 490; +lam_step = 8; +tau_min = 1; +tau_max = 4; +cum2_min = -5; +cum2_max = 5; +clam_min = 490; +clam_max = 650; +wlam_min = 0; +wlam_max = 30; +num_PIE = 1; +Threshold = 30; +pixwidth = 0; +binning = 1; +BG_corr = 1; +BG_AP = 0.0; +lamPIE = [475 530 560 640]; + +load('Get_Params.mat'); + +handles.par_lam_start = lam_start; +handles.par_lam_step = lam_step; +handles.par_tau_min = tau_min; +handles.par_tau_max = tau_max; +handles.par_cum2_min = cum2_min; +handles.par_cum2_max = cum2_max; +handles.par_clam_min = clam_min; +handles.par_clam_max = clam_max; +handles.par_wlam_min = wlam_min; +handles.par_wlam_max = wlam_max; +handles.par_num_PIE = num_PIE; +handles.par_Threshold = Threshold; +handles.par_binning = binning; +handles.par_pixwidth = pixwidth; +handles.par_BG_corr = BG_corr; +handles.par_BG_AP = 100*BG_AP; +handles.par_lamPIE = lamPIE; + +guidata(hObject, handles); + +set(handles.edit1 ,'String',sprintf('%d',round(handles.par_lam_start))); +set(handles.edit2 ,'String',sprintf('%d',round(handles.par_lam_step))); +set(handles.edit3 ,'String',sprintf('%d',round(handles.par_num_PIE))); +set(handles.edit5 ,'String',sprintf('%d',round(handles.par_wlam_max))); +set(handles.edit6 ,'String',sprintf('%d',round(handles.par_wlam_min))); +set(handles.edit7 ,'String',sprintf('%4.1f',round(10*handles.par_tau_min)/10)); +set(handles.edit8 ,'String',sprintf('%4.1f',round(10*handles.par_tau_max)/10)); +set(handles.edit9 ,'String',sprintf('%d',round(handles.par_cum2_min))); +set(handles.edit10,'String',sprintf('%d',round(handles.par_clam_min))); +set(handles.edit11,'String',sprintf('%d',round(handles.par_clam_max))); +set(handles.edit12,'String',sprintf('%d',round(handles.par_cum2_max))); +set(handles.edit13,'String',sprintf('%d',round(handles.par_Threshold))); +set(handles.edit14,'String',sprintf('%4.2f',(handles.par_pixwidth))); +set(handles.edit21,'String',sprintf('%d',round(handles.par_binning))); +set(handles.edit15,'String',sprintf('%4.2f',handles.par_BG_AP)); +set(handles.edit16,'String',sprintf('%d',handles.par_lamPIE(1))); +set(handles.edit18,'String',sprintf('%d',handles.par_lamPIE(2))); +set(handles.edit19,'String',sprintf('%d',handles.par_lamPIE(4))); +set(handles.edit20,'String',sprintf('%d',handles.par_lamPIE(3))); +set(handles.checkbox1,'Value',(handles.par_BG_corr>0)); +if handles.par_BG_corr == 0 + set(handles.edit15,'Enable','off'); + set(handles.uipanel1,'Visible','off'); +else + set(handles.edit15,'Enable','on'); + set(handles.uipanel1,'Visible','on'); + if handles.par_BG_corr == 2 + set(handles.radiobutton3 ,'Value',1); + end +end +if handles.par_num_PIE == 4 + set(handles.edit19,'enable','on'); +end +if handles.par_num_PIE > 2 + set(handles.edit20,'enable','on'); +end +if handles.par_num_PIE > 1 + set(handles.edit18,'enable','on'); +end +% UIWAIT makes Set_Params wait for user response (see UIRESUME) +uiwait(handles.figure1); + + +% --- Outputs from this function are returned to the command line. +function varargout = Set_Params_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; +close; + + +function edit1_Callback(hObject, eventdata, handles) +% hObject handle to edit1 (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 edit1 as text +% str2double(get(hObject,'String')) returns contents of edit1 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([300 tmp]); +tmp = min([700 tmp]); +handles.par_lam_start = tmp; +guidata(hObject, handles); +set(hObject,'String',sprintf('%d',round(handles.par_lam_start))); + +% --- Executes during object creation, after setting all properties. +function edit1_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit1 (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 edit2_Callback(hObject, eventdata, handles) +% hObject handle to edit2 (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 edit2 as text +% str2double(get(hObject,'String')) returns contents of edit2 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([ 1 tmp]); +tmp = min([100 tmp]); +handles.par_lam_step = tmp; +guidata(hObject, handles); +set(hObject,'String',sprintf('%d',round(handles.par_lam_step))); + + +% --- Executes during object creation, after setting all properties. +function edit2_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit2 (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 edit3_Callback(hObject, eventdata, handles) +% hObject handle to edit3 (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 edit3 as text +% str2double(get(hObject,'String')) returns contents of edit3 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([ 1 tmp]); +tmp = min([ 4 tmp]); +handles.par_num_PIE = tmp; + +set(handles.edit18,'enable','off'); +set(handles.edit19,'enable','off'); +set(handles.edit20,'enable','off'); + +if tmp == 4 + set(handles.edit19,'enable','on'); +end +if tmp > 2 + set(handles.edit20,'enable','on'); +end +if tmp > 1 + set(handles.edit18,'enable','on'); +end + +guidata(hObject, handles); +set(hObject,'String',sprintf('%d',round(handles.par_num_PIE))); + + +% --- Executes during object creation, after setting all properties. +function edit3_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit3 (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 edit5_Callback(hObject, eventdata, handles) +% hObject handle to edit5 (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 edit5 as text +% str2double(get(hObject,'String')) returns contents of edit5 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([handles.par_wlam_min+1 tmp]); +tmp = min([100 tmp]); +handles.par_wlam_max = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_wlam_max))); + + +% --- Executes during object creation, after setting all properties. +function edit5_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit5 (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 edit6_Callback(hObject, eventdata, handles) +% hObject handle to edit6 (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 edit6 as text +% str2double(get(hObject,'String')) returns contents of edit6 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = min([handles.par_wlam_max-1 tmp]); +tmp = max([0 tmp]); +handles.par_wlam_min = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_wlam_min))); + + +% --- Executes during object creation, after setting all properties. +function edit6_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit6 (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 edit7_Callback(hObject, eventdata, handles) +% hObject handle to edit7 (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 edit7 as text +% str2double(get(hObject,'String')) returns contents of edit7 as a double +tmp = round(10*str2double(get(hObject,'String')))/10; +tmp = min([handles.par_tau_max-1 tmp]); +tmp = max([0 tmp]); +handles.par_tau_min = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%4.1f',(handles.par_tau_min))); + + +% --- Executes during object creation, after setting all properties. +function edit7_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit7 (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 edit8_Callback(hObject, eventdata, handles) +% hObject handle to edit8 (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 edit8 as text +% str2double(get(hObject,'String')) returns contents of edit8 as a double + +tmp = round(10*str2double(get(hObject,'String')))/10; +tmp = max([handles.par_tau_min+1 tmp]); +tmp = min([20 tmp]); +handles.par_tau_max = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%4.1f',(handles.par_tau_max))); + + +% --- Executes during object creation, after setting all properties. +function edit8_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit8 (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 edit9_Callback(hObject, eventdata, handles) +% hObject handle to edit9 (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 edit9 as text +% str2double(get(hObject,'String')) returns contents of edit9 as a double + +tmp = round(str2double(get(hObject,'String'))); +tmp = min([handles.par_cum2_max-3 tmp]); +tmp = max([0 tmp]); +handles.par_cum2_min = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_cum2_min))); + + +% --- Executes during object creation, after setting all properties. +function edit9_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit9 (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 edit10_Callback(hObject, eventdata, handles) +% hObject handle to edit10 (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 edit10 as text +% str2double(get(hObject,'String')) returns contents of edit10 as a double + +tmp = round(str2double(get(hObject,'String'))); +tmp = min([handles.par_clam_max-25 tmp]); +tmp = max([0 tmp]); +handles.par_clam_min = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_clam_min))); + + +% --- Executes during object creation, after setting all properties. +function edit10_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit10 (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 edit11_Callback(hObject, eventdata, handles) +% hObject handle to edit11 (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 edit11 as text +% str2double(get(hObject,'String')) returns contents of edit11 as a double + +tmp = round(str2double(get(hObject,'String'))); +tmp = max([handles.par_clam_min+25 tmp]); +tmp = min([900 tmp]); +handles.par_clam_max = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_clam_max))); + + +% --- Executes during object creation, after setting all properties. +function edit11_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit11 (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 edit12_Callback(hObject, eventdata, handles) +% hObject handle to edit12 (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 edit12 as text +% str2double(get(hObject,'String')) returns contents of edit12 as a double + +tmp = round(str2double(get(hObject,'String'))); +tmp = max([handles.par_cum2_min+3 tmp]); +tmp = min([500 tmp]); +handles.par_cum2_max = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_cum2_max))); + + +% --- Executes during object creation, after setting all properties. +function edit12_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit12 (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 edit13_Callback(hObject, eventdata, handles) +% hObject handle to edit13 (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 edit13 as text +% str2double(get(hObject,'String')) returns contents of edit13 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([0 tmp]); +tmp = min([500 tmp]); +handles.par_Threshold = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_Threshold))); + + +% --- Executes during object creation, after setting all properties. +function edit13_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit13 (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 edit14_Callback(hObject, eventdata, handles) +% hObject handle to edit14 (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 edit13 as text +% str2double(get(hObject,'String')) returns contents of edit13 as a double +tmp = round(str2double(get(hObject,'String'))*100)/100; +tmp = max([0.01 tmp]); +tmp = min([100 tmp]); +handles.par_pixwidth = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%4.2f',(handles.par_pixwidth))); + + +% --- Executes during object creation, after setting all properties. +function edit14_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit14 (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 edit21_Callback(hObject, eventdata, handles) +% hObject handle to edit21 (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 edit21 as text +% str2double(get(hObject,'String')) returns contents of edit21 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([1 tmp]); +tmp = min([10 tmp]); +handles.par_binning = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_binning))); + + +% --- Executes during object creation, after setting all properties. +function edit21_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit21 (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 edit15_Callback(hObject, eventdata, handles) +% hObject handle to edit15 (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 edit13 as text +% str2double(get(hObject,'String')) returns contents of edit13 as a double +tmp = round(100*str2double(get(hObject,'String')))/100; +tmp = max([0 tmp]); +tmp = min([10 tmp]); +handles.par_BG_AP = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%4.2f',handles.par_BG_AP)); + + +% --- Executes during object creation, after setting all properties. +function edit15_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit15 (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 checkbox1_Callback(hObject, eventdata, handles) +% hObject handle to checkbox1 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +tmp = get(hObject,'Value'); +tmp = max([0 tmp]); +tmp = min([1 tmp]); +guidata(hObject, handles); +if tmp == 0 + set(handles.edit15,'Enable','off'); + set(handles.uipanel1,'Visible','off'); +else + set(handles.edit15,'Enable','on'); + set(handles.uipanel1,'Visible','on'); +end +tmp1 = get(handles.uipanel1,'Children'); +k = 1; +while get(tmp1(k),'Value') == 0 + k = k+1; +end +if strcmp(get(tmp1(k),'String'),'Individual determination') + handles.par_BG_corr = tmp*2; +else + handles.par_BG_corr = tmp; +end +set(hObject,'Value',tmp); +guidata(hObject, handles); + +% --- Executes on button press in pushbutton3. +function pushbutton3_Callback(hObject, eventdata, handles) +% hObject handle to pushbutton3 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +uiresume(handles.figure1); + + + +% --- Executes on button press in pushbutton4. +function pushbutton4_Callback(hObject, eventdata, handles) +% hObject handle to pushbutton4 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +%delete('Get_Params.m'); + +%fid = fopen('Get_Params.m','w'); + +lam_start = handles.par_lam_start; +lam_step = handles.par_lam_step; + +tau_min = handles.par_tau_min; +tau_max = handles.par_tau_max; + +cum2_min = handles.par_cum2_min; +cum2_max = handles.par_cum2_max; + +clam_min = handles.par_clam_min; +clam_max = handles.par_clam_max; + +wlam_min = handles.par_wlam_min; +wlam_max = handles.par_wlam_max; + +num_PIE = handles.par_num_PIE; + +pixwidth = handles.par_pixwidth; + +Threshold = handles.par_Threshold; +binning = handles.par_binning; + +lamPIE = handles.par_lamPIE; + +maxROI = 16; +ROIcolor = [1 0 0; ... + 0 1 0; ... + 0 0 1; ... + 1 1 0; ... + 1 0 1; ... + 0 1 1; ... + 1 1 1; ... + 0 0.5 0; ... + 0.5 0.5 0; ... + 0.3 0.3 0.3; ... + 0.0 0.5 0.5; ... + 0.5 0.0 0.5; ... + 0.7 0.5 0.3; ... + 0.3 0.7 0.5; ... + 0.5 0.3 0.7; ... + 0.3 0.5 0.7]; + +ROIlist = zeros(16,1); + +BG_corr = handles.par_BG_corr; +BG_AP = handles.par_BG_AP/100; + +BG_file = ''; + +if BG_corr == 1 + + [FileName,PathName] = uigetfile({'*.ht3;*.pt3','t3r-files';'*.*','All Files'}, 'MultiSelect', 'off'); + + if ~isempty(FileName) + BG_file = [PathName FileName]; + else + warndlg('No file selected!') + BG_corr = 2; + end +end + +figFLIM = 10; +figMA = 20; +figfFLIM = 30; +figone = 40; +figPA = 50; + +save('Get_Params.mat','lam_start','lam_step', 'tau_max', 'tau_min', 'cum2_min', 'cum2_max', ... + 'clam_min', 'clam_max', 'wlam_min', 'wlam_max', 'num_PIE', ... + 'Threshold', 'binning', 'maxROI', 'ROIcolor', 'ROIlist', ... + 'pixwidth', 'BG_corr', 'BG_file', 'BG_AP', 'lamPIE', ... + 'figFLIM', 'figfFLIM', 'figMA', 'figone', 'figPA'); + +uiresume(handles.figure1); + + +function edit16_Callback(hObject, eventdata, handles) +% hObject handle to edit16 (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 edit16 as text +% str2double(get(hObject,'String')) returns contents of edit16 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([ 300 tmp]); +tmp = min([1000 tmp]); +handles.par_lamPIE(1) = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_lamPIE(1)))); + + +% --- Executes during object creation, after setting all properties. +function edit16_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit16 (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 edit18_Callback(hObject, eventdata, handles) +% hObject handle to edit18 (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 edit18 as text +% str2double(get(hObject,'String')) returns contents of edit18 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([ 300 tmp]); +tmp = min([1000 tmp]); +handles.par_lamPIE(2) = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_lamPIE(2)))); + + +% --- Executes during object creation, after setting all properties. +function edit18_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit18 (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 edit19_Callback(hObject, eventdata, handles) +% hObject handle to edit19 (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 edit19 as text +% str2double(get(hObject,'String')) returns contents of edit19 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([ 300 tmp]); +tmp = min([1000 tmp]); +handles.par_lamPIE(4) = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_lamPIE(4)))); + + +% --- Executes during object creation, after setting all properties. +function edit19_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit19 (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 edit20_Callback(hObject, eventdata, handles) +% hObject handle to edit20 (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 edit20 as text +% str2double(get(hObject,'String')) returns contents of edit20 as a double +tmp = round(str2double(get(hObject,'String'))); +tmp = max([ 300 tmp]); +tmp = min([1000 tmp]); +handles.par_lamPIE(3) = tmp; +guidata(hObject, handles); + +set(hObject,'String',sprintf('%d',round(handles.par_lamPIE(3)))); + + +% --- Executes during object creation, after setting all properties. +function edit20_CreateFcn(hObject, eventdata, handles) +% hObject handle to edit20 (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 when selected object is changed in uipanel1. +function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) +% hObject handle to the selected object in uipanel1 +% eventdata structure with the following fields (see UIBUTTONGROUP) +% EventName: string 'SelectionChanged' (read only) +% OldValue: handle of the previously selected object or empty if none was selected +% NewValue: handle of the currently selected object +% handles structure with handles and user data (see GUIDATA) + +if strcmp(get(eventdata.NewValue,'String'),'Individual determination') + handles.par_BG_corr = 2; +else + handles.par_BG_corr = 1; +end +guidata(hObject, handles); + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_PatternOptions.fig b/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_PatternOptions.fig new file mode 100644 index 0000000..c5b7888 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_PatternOptions.fig differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_PatternOptions.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_PatternOptions.m new file mode 100644 index 0000000..db60818 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Set_PatternOptions.m @@ -0,0 +1,443 @@ +function varargout = Set_PatternOptions(varargin) +% SET_PATTERNOPTIONS M-file for Set_PatternOptions.fig +% SET_PATTERNOPTIONS, by itself, creates a new SET_PATTERNOPTIONS or raises the existing +% singleton*. +% +% H = SET_PATTERNOPTIONS returns the handle to a new SET_PATTERNOPTIONS or the handle to +% the existing singleton*. +% +% SET_PATTERNOPTIONS('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in SET_PATTERNOPTIONS.M with the given input arguments. +% +% SET_PATTERNOPTIONS('Property','Value',...) creates a new SET_PATTERNOPTIONS or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before Set_PatternOptions_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to Set_PatternOptions_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 Set_PatternOptions + +% Last Modified by GUIDE v2.5 19-May-2014 21:40:09 + +% Begin initialization code - DO NOT EDIT + +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @Set_PatternOptions_OpeningFcn, ... + 'gui_OutputFcn', @Set_PatternOptions_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 Set_PatternOptions is made visible. +function Set_PatternOptions_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 Set_PatternOptions (see VARARGIN) + +% Choose default command line output for Set_PatternOptions +handles.output = hObject; + +load Get_Params; +handles.par_lam_start = lam_start; +handles.par_lam_step = lam_step; +handles.par_clam_min = clam_min; +handles.par_clam_max = clam_max; +handles.par_num_PIE = num_PIE; +handles.ROIcolor = ROIcolor; + +handles.channel = 1; + + +if length(varargin) < 3 + uiwait(errordlg('No pattern given','Data missing')) +elseif (length(varargin) == 3 && strcmpi(varargin{1},'file')) + handles.file = cell2mat(varargin(2)); + load(cell2mat(varargin(2)), 'pat', 'list', 'params'); + handles.pat = pat; + handles.List = list; + handles.params = params; + handles.filename = cell2mat(varargin(3)); + handles.match = 0; +elseif (length(varargin) == 4 && strcmpi(varargin{1},'file')) + handles.file = cell2mat(varargin(2)); + load(cell2mat(varargin(2)), 'pat', 'list', 'params'); + handles.pat = pat; + handles.List = list; + handles.params = params; + handles.filename = cell2mat(varargin(3)); + + patfam = varargin(4); + handles.vTau = cell2mat(patfam{1,1}{1,1}(end)); + tmp = patfam{1,1}{1,1}(1:end-1); + handles.fam = cat(4,tmp{1,1},tmp{1,2}); + for n = 1:size(tmp,2)-2 + handles.fam = cat(4,handles.fam,tmp{1,n+2}); + end + handles.fam = permute(handles.fam,[4,1,2,3]); + handles.match = 1; +end + +tmp = strfind(handles.filename,'\'); +handles.pathname = handles.filename(1:tmp(end)); +handles.filename = handles.filename(tmp(end)+1:end); +[handles.head, handles.tag, handles.tcspc, handles.IRF, handles.timname,... + handles.AP, handles.DC] = load_data([handles.pathname handles.filename]); + +handles.nch = size(handles.tcspc,1); +handles.binw = handles.head.tauw(:)./handles.head.tauw(1); +handles.binw = squeeze(repmat(handles.binw,[num_PIE 1])); +handles.taush = handles.head.tau; +handles.tau = handles.head.tau(:)*ones(1,handles.par_num_PIE); +handles.tmp = ones(size(handles.tau,1),1)*((0:handles.par_num_PIE-1).*handles.tau(end,1)); +handles.tau = reshape(handles.tau+handles.tmp, [numel(handles.tau) 1]); +handles.m0 = handles.head.m0; + + +% Update handles structure +guidata(hObject, handles); + +load Get_Params; + + +col_name(1,1) = {'spectrum'}; +col_name(1,2) = {'all'}; + +lambda = (lam_start+lam_step.*(0:size(handles.pat,2)-1)); + +for n = 1:size(handles.pat,2) + col_name(1,2+n) = {sprintf('%03d',lambda(n))}; +end + +for n = 1:num_PIE + row_name(1,n) = {sprintf(' Pulse %01d',n)}; +end + +data = ' [X]'; +data = repmat({data}, num_PIE, size(handles.pat,2)+2); + +lambda = repmat([inf inf lambda], num_PIE, 1); +tmp = repmat(lamPIE(1:num_PIE)', 1, size(handles.pat,2)+2)+lam_step; + +ind = lambda<=tmp; + +data(ind) = {' [ ]'}; + +set(handles.uitable1,'Data',data); +set(handles.uitable1,'RowName',row_name); +set(handles.uitable1,'ColumnName',col_name); +wt = num2cell(25.*ones(1,size(data,2))); +wt(1) = {60}; +wt(2) = {30}; +set(handles.uitable1,'ColumnWidth',wt); +set(handles.uitable1,'ColumnEditable',false(1, size(data,2))); + +for n = 1:size(handles.pat,3)-handles.head.m0+1 + col_name(1,2+n) = {sprintf('%02d',n)}; +end + +data = ' [X]'; +data = repmat({data}, num_PIE, size(handles.pat,3)-handles.head.m0+3); + +col_name(1,1) = {'decay'}; +set(handles.uitable2,'Data',data); +set(handles.uitable2,'RowName',row_name); +set(handles.uitable2,'ColumnName',col_name); +wt = num2cell(25.*ones(1,size(data,2))); +wt(1) = {50}; +wt(2) = {30}; +set(handles.uitable2,'ColumnWidth',wt); +set(handles.uitable2,'ColumnEditable',false(1, size(data,2))); + + +handles.ROIcolor = ROIcolor; + +axes(handles.axes1) +hold on; +cla +set(handles.axes1, ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); +xlabel('wavelength of spectral mean / nm','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('rel. spectral irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); +axis([clam_min clam_max 0 1.1]); + +s = squeeze(sum(sum(pat,4),3)); +s(isnan(s)) = 0; +lam = (lam_start+lam_step.*(-1:size(s,2))); +s = [zeros(size(s,1),1) s zeros(size(s,1),1)]; +ts = lam_start-lam_step: 1: lam_start+lam_step*(1+size(handles.pat,2)); +cs = interp1(lam(:), s', ts','pchip'); +for a = 1:size(s,1) + plot(ts,cs(:,a)./max(max(cs)),'Color',ROIcolor(1+mod(a-1,size(ROIcolor,1)),:),'LineWidth',3); %#ok +end +hold off + +handles.lam = lam; +handles.ts = ts; + + +axes(handles.axes2) +hold on; +cla +set(handles.axes2, ... + 'Box','on', ... + 'XDir','normal', ... + 'YDir','normal', ... + 'FontSize',9,... + 'Color',[50 50 50]./255); +xlabel('time / ns','FontWeight','bold','FontSize',10,'FontAngle','italic'); +ylabel('rel. irradiance','FontWeight','bold','FontSize',10,'FontAngle','italic'); +axis([0 ceil(handles.taush(end)) -4 0.1]); + +s = squeeze(sum(sum(pat,4),2)); +s = s./repmat(handles.head.tauw, [size(s,1) 1]); +s(isnan(s)) = 0; + +ts = handles.taush; +for a = 1:size(s,1) + plot(ts,log10(s(a,:)./max(max(s))),'Color',ROIcolor(1+mod(a-1,size(ROIcolor,1)),:),'LineWidth',3); %#ok +end +hold off + + +guidata(hObject, handles); + + +% col_name = list; +% row_name = {'rel. Intensity'}; +% set(handles.uitable2,'Data',squeeze(handles.res(:,1,1,1))'); +% set(handles.uitable2,'RowName',row_name); +% set(handles.uitable2,'ColumnName',col_name); + +guidata(hObject, handles); + + +% UIWAIT makes Set_PatternOptions wait for user response (see UIRESUME) +% uiwait(handles.figure1); + + +% --- Outputs from this function are returned to the command line. +function varargout = Set_PatternOptions_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; + + +% --- Executes on button press in Cancel_button. +function Cancel_button_Callback(hObject, eventdata, handles) +% hObject handle to Cancel_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +params = zeros(size(handles.pat,4), 2+size(handles.pat,2)+size(handles.pat,3)); + +save(handles.file, 'params', '-APPEND'); + +guidata(hObject, handles); +close + +% --- Executes on button press in OK_button. +function OK_button_Callback(hObject, eventdata, handles) +% hObject handle to OK_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +% load('Get_Params.mat'); + +data1 = get(handles.uitable1, 'Data'); +data2 = get(handles.uitable2, 'Data'); + +n1 = size(data1,2)-2; +n2 = size(data2,2)-2; + +params = zeros(size(handles.pat,4), 2+n1+size(handles.pat,3)); + +params(:,1) = strcmpi(data1(:,1),{' [X]'}); +params(:,2) = strcmpi(data2(:,1),{' [X]'}); +params(:,2+(1:n1)) = strcmpi(data1(:,3:end),{' [X]'}); +params(:,2+n1+(1:handles.head.m0-1)) = repmat(strcmpi(data2(:,3),{' [X]'}),[1 handles.head.m0-1]); +params(:,1+n1+handles.head.m0+(1:n2)) = strcmpi(data2(:,3:end),{' [X]'}); + +save(handles.file, 'params', '-APPEND'); +guidata(hObject, handles); +close + + +% --- Executes when selected cell(s) is changed in uitable1. +function uitable1_CellSelectionCallback(hObject, eventdata, handles) +% hObject handle to uitable1 (see GCBO) +% eventdata structure with the following fields (see UITABLE) +% Indices: row and column indices of the cell(s) currently selecteds +% handles structure with handles and user data (see GUIDATA) + +load Get_Params; + +data = get(hObject,'Data'); +data1 = get(handles.uitable2,'Data'); + +save('data','data') +if numel(eventdata.Indices)>0 + if strcmpi(data(eventdata.Indices(1),eventdata.Indices(2)),{' [X]'}) + if eventdata.Indices(2) == 1 + data(:,eventdata.Indices(2)) = {' [ ]'}; + data1(:,1) = {' [X]'}; + elseif eventdata.Indices(2) == 2 + data(eventdata.Indices(1),2:end) = {' [ ]'}; + else + data(eventdata.Indices(1),eventdata.Indices(2)) = {' [ ]'}; + end + else + if eventdata.Indices(2) < 2 + data(:,eventdata.Indices(2)) = {' [X]'}; + elseif eventdata.Indices(2) == 2 + data(eventdata.Indices(1),2:end) = {' [X]'}; + else + data(eventdata.Indices(1),eventdata.Indices(2)) = {' [X]'}; + end + end + set(hObject,'Selected','off'); + set(hObject,'Data',data); + set(handles.uitable2,'Data',data1); +end + +guidata(hObject, handles); +update_plot(handles) + + +% --- Executes when selected cell(s) is changed in uitable2. +function uitable2_CellSelectionCallback(hObject, eventdata, handles) +% hObject handle to uitable2 (see GCBO) +% eventdata structure with the following fields (see UITABLE) +% Indices: row and column indices of the cell(s) currently selecteds +% handles structure with handles and user data (see GUIDATA) +load Get_Params; + +data = get(hObject,'Data'); +data1 = get(handles.uitable1,'Data'); + +save('data','data') +if numel(eventdata.Indices)>0 + if strcmpi(data(eventdata.Indices(1),eventdata.Indices(2)),{' [X]'}) + if eventdata.Indices(2) == 1 + data(:,1) = {' [ ]'}; + data1(:,1) = {' [X]'}; + elseif eventdata.Indices(2) == 2 + data(eventdata.Indices(1),2:end) = {' [ ]'}; + else + data(eventdata.Indices(1),eventdata.Indices(2)) = {' [ ]'}; + end + else + if eventdata.Indices(2) < 2 + data(:,eventdata.Indices(2)) = {' [X]'}; + elseif eventdata.Indices(2) == 2 + data(eventdata.Indices(1),2:end) = {' [X]'}; + else + data(eventdata.Indices(1),eventdata.Indices(2)) = {' [X]'}; + end + end + set(hObject,'Selected','off'); + set(hObject,'Data',data); + set(handles.uitable1,'Data',data1); +end + +guidata(hObject, handles); +update_plot(handles) + + +function update_plot(handles) + +style = [{'-'};{'--'};{'-.'};{':'}]; + +num_Pat = size(handles.pat,1); +num_PIE = size(handles.pat,4); + +data1 = get(handles.uitable1,'Data'); +data2 = get(handles.uitable2,'Data'); + +use_spec = strcmpi(data1(:,1),{' [X]'}); +use_dec = strcmpi(data2(:,1),{' [X]'}); + +s = permute(sum(handles.pat,3),[1 2 4 3]); + +s = reshape(permute(s,[3 1 2]),[size(s,1)*size(s,3) size(s,2)]); +m = max(max(s)); +ind = repmat(strcmpi(data1(:,3:end),{' [X]'}),[size(handles.pat,1) 1]); +s = s.*ind; + +s = [zeros(size(s,1),1) s zeros(size(s,1),1)]; + +hold(handles.axes1,'on') +cla(handles.axes1) + +for a = 1:num_Pat + for b = 1:num_PIE + ind = (a-1)*num_PIE+b; + color = handles.ROIcolor(1+mod(a-1,size(handles.ROIcolor,1)),:); + if use_spec(b) + cs = interp1(handles.lam(:), s(ind,:)', handles.ts,'pchip'); + plot(handles.axes1,handles.ts,cs./m,'Color',color,'LineWidth',3,'LineStyle',cell2mat(style(b))); %#ok + else + bar(handles.axes1,handles.lam(:)+(a-1).*2, (s(ind,:)>0)*(5-b)./4 ,'BarWidth',0.2*b,'FaceColor','none','LineWidth',2,'EdgeColor',color); + end + end +end +hold(handles.axes1,'off') +axis([handles.par_clam_min handles.par_clam_max 0 1.1]); +% axis([handles.lam(2) handles.lam(end-1) 0 1]) + + +s = permute(sum(handles.pat,2),[1 3 4 2]); +if size(handles.pat,1) == 1 + s = shiftdim(s,-1); +end + +s = s./repmat(handles.head.tauw,[size(s,1) 1 size(s,3)]); +s = reshape(permute(s,[3 1 2]),[size(s,1)*size(s,3) size(s,2)]); +m = max(max(s)); +ind = strcmpi(data2(:,3:end),{' [X]'}); +ind = [repmat(ind(:,1),[1 handles.head.m0]) ind(:,2:end)]; +ind = repmat(ind,[size(handles.pat,1) 1]); +s = s.*ind; + +hold(handles.axes2,'on') +cla(handles.axes2) + +for a = 1:num_Pat + for b = 1:num_PIE + ind = (a-1)*num_PIE+b; + color = handles.ROIcolor(1+mod(a-1,size(handles.ROIcolor,1)),:); + if use_dec(b) + plot(handles.axes2,handles.taush,log10(s(ind,:)./m),'Color',color,'LineWidth',3,'LineStyle',cell2mat(style(b))); %#ok + else + bar(handles.axes2,handles.taush(:)+(a-1)/8, -(s(ind,:)>0).*4 ,'BarWidth',0.8*b,'FaceColor','none','LineWidth',2,'EdgeColor',color); + end + end +end +hold(handles.axes2,'off') +axis([0 ceil(handles.taush(end)) -4 0.1]); diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/Simplex.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/Simplex.m new file mode 100644 index 0000000..95bc2e9 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/Simplex.m @@ -0,0 +1,166 @@ +function [x, dx, steps] = Simplex(fname, x, xmin, xmax, tol, steps, varargin) + +% [x, dx, steps] = Simplex('F', X0, XMIN, XMAX, TOL, STEPS, VARARGIN) +% attempts to return a vector x and its error dx, so that x minimzes the +% function F(x) near the starting vector X0 under the conditions that +% xmin <= x <= xmax. +% TOL is the relative termination tolerance dF/F; (default = 1e-10) +% STEPS is the maximum number of steps; (default = 200*number of parameters). +% The returned value of STEPS is the actual number of performed steps. +% Simplex allows for up to 10 additional arguments for the function F. +% Simplex uses a Nelder-Mead simplex search method. + +%#function TCSPC_Fun IRF_Fun + +x = x(:); +if nargin<5 + tol = 1e-10; + if nargin<4 + xmax = Inf*ones(length(x),1); + if nargin<3 + xmin = -Inf*ones(length(x),1); + end + end +elseif isempty(tol) + tol = 1e-5; +end +if nargin<6 + steps = []; +end +if isempty(xmin) + xmin = -Inf*ones(size(x)); +end +if isempty(xmax) + xmax = Inf*ones(size(x)); +end +xmin = xmin(:); +xmax = xmax(:); +xmax(xmaxxmax) = xmax(x>xmax); +xfix = zeros(size(x)); +tmp = xmin==xmax; +xfix(tmp) = xmin(tmp); +mask = diag(~tmp); +mask(:, tmp) = []; +x(tmp) = []; +xmin(tmp) = []; +xmax(tmp) = []; + +if isa(fname,'function_handle') + fun = fname; + evalstr = 'fun'; +else + evalstr = fname; +end +evalstr = [evalstr, '(mask*x+xfix']; +if nargin>6 + evalstr = [evalstr, ',varargin{:}']; +end +evalstr = [evalstr, ')']; + +n = length(x); +if n==0 + x = xfix; + dx = zeros(size(xfix)); + steps = 0; + return +end +if isempty(steps) + steps = 200*n; +end + +xin = x(:); +%v = 0.9*xin; +v = xin; +v(vxmax) = xmax(v>xmax); +x(:) = v; fv = eval(evalstr); +for j = 1:n + y = xin; + if y(j) ~= 0 + y(j) = (1 +.2*rand)*y(j); + else + y(j) = 0.2; + end + if y(j)>=xmax(j) + y(j) = xmax(j); + end + if y(j)<=xmin(j) + y(j) = xmin(j); + end + v = [v y]; + x(:) = y; f = eval(evalstr); + fv = [fv f]; +end +[fv, j] = sort(fv); +v = v(:,j); +count = n+1; + +% Parameter settings for Nelder-Meade +alpha = 1; beta = 1/2; gamma = 2; + +% Begin of Nelder-Meade simplex algorithm +while count < steps + if 2*abs(fv(n+1)-fv(1))/(abs(fv(1))+abs(fv(n+1))) <= tol + break + end + + % Reflection: + vmean = mean(v(:, 1:n),2); + vr = (1 + alpha)*vmean - alpha*v(:, n+1); + x(:) = vr; + fr = eval(evalstr); + count = count + 1; + vk = vr; fk = fr; + + if fr < fv(1) && all(xmin<=vr) && all(vr<=xmax) + % Expansion: + ve = gamma*vr + (1-gamma)*vmean; + x(:) = ve; + fe = eval(evalstr); + count = count + 1; + if fe < fv(1) && all(xmin<=ve) && all(ve<=xmax) + vk = ve; fk = fe; + end + else + vtmp = v(:,n+1); ftmp = fv(n+1); + if fr < ftmp && all(xmin<=vr) && all(vr<=xmax) + vtmp = vr; ftmp = fr; + end + % Contraction: + vc = beta*vtmp + (1-beta)*vmean; + x(:) = vc; + fc = eval(evalstr); + count = count + 1; + if fc < fv(n) && all(xmin<=vc) && all(vc<=xmax) + vk = vc; fk = fc; + else + % Shrinkage: + for j = 2:n + v(:, j) = (v(:, 1) + v(:, j))/2; + x(:) = v(:, j); + fv(j) = eval(evalstr); + end + count = count + n-1; + vk = (v(:, 1) + v(:, n+1))/2; + x(:) = vk; + fk = eval(evalstr); + count = count + 1; + end + end + v(:, n+1) = vk; + fv(n+1) = fk; + [fv, j] = sort(fv); + v = v(:,j); +end + +x = v(:,1); +dx = abs(v(:,n+1)-v(:,1)); +x = mask*x + xfix; +dx = mask*dx; +if count>=steps + disp(['Warning: Maximum number of iterations (', num2str(steps,'%d'),') has been exceeded']); +else + steps = count; +end diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/TCSPC_Fun.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/TCSPC_Fun.m new file mode 100644 index 0000000..7e858fb --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/TCSPC_Fun.m @@ -0,0 +1,99 @@ +function [err, c, zz, z] = TCSPC_Fun(p, t, y, para) + +% Fits the following model function to TCSPC-Data +% +% TCSPC(N,{q_1},{tau_i},t_0, w, a, dt, T1, T2, bg, t) = +% bg + N/Q Sum[ q_i (sqrt(pi/2) w/tau_i exp(w^2/(2 tau_i^2) - t'/tau_i) Erfc((w^2- t' tau_i)/(sqrt(2)w tau_t)) + +% a P H(t')) (tau_i/(tau_i/T12 -1)/(tau_1/T1 -1)/T2 exp(-t''\tau_i) + +% 1/(tau_1/T12 -1) exp(-t''/T12) - +% 1/(tau_i/T1 -1) exp(-t''/T1) ) ] +% t' = t - t_0 +% t'' = t - t_0 - dt; +% Q = sqrt(2 pi w^2) + a T1(1+T1/T2)^{T2/T1} +% P = (1-T2/T1)(1+T1/T2)^{T2/T1} +% +% (see: Walther, K.A. et al, Mol. BioSyst. (2011) doi:10.1039/c0mb00132e) + +p = p(:); + +if (nargin>3)&&(~isempty(para)) + para = para(:); + n = numel(para); + if n > 6 + p = [para; p]; + else + p = [p(1:7-n); para; p(8-n:end)]; + end +end + +nex = numel(p) - 7; +tau = p(8:end); + +if length(t)0); + y = y(y>0); + + IRF = IRF_Fun(p(1:6), t); + + zz = zeros(numel(t),nex+2); + + zz(:,1) = ones(size(t)); + zz(:,2) = IRF; + + for k = 1:nex + tmp = Convol(IRF, exp(-t./tau(k))./tau(k)); + zz(:,2+k) = tmp(1:numel(t)); + end + + zz = zz./(ones(length(t),1)*sum(zz)); + + for j=1:n + c(:,j) = lsqnonneg(zz,y(:,j)); %% + z(:,j) = zz*c(:,j); + end + +% if nargin>4 && ~isempty(pic) +% if pic==1 +% plot(t, y, 'ob', t, z, 'r'); drawnow +% else +% semilogy(t, abs(y), 'o', t, abs(z)); drawnow +% end +% end + + err = sum((y-z).^2./abs(y)); +end + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/TheProcessor.fig b/Spectral-FLIM GUI/Spectral-FLIM GUI/TheProcessor.fig new file mode 100644 index 0000000..46a67ec Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/TheProcessor.fig differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/TheProcessor.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/TheProcessor.m new file mode 100644 index 0000000..1a42817 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/TheProcessor.m @@ -0,0 +1,193 @@ +function varargout = TheProcessor(varargin) +% THEPROCESSOR MATLAB code for TheProcessor.fig +% THEPROCESSOR, by itself, creates a new THEPROCESSOR or raises the existing +% singleton*. +% +% H = THEPROCESSOR returns the handle to a new THEPROCESSOR or the handle to +% the existing singleton*. +% +% THEPROCESSOR('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in THEPROCESSOR.M with the given input arguments. +% +% THEPROCESSOR('Property','Value',...) creates a new THEPROCESSOR or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before TheProcessor_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to TheProcessor_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 TheProcessor + +% Last Modified by GUIDE v2.5 07-Sep-2017 14:22:58 + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @TheProcessor_OpeningFcn, ... + 'gui_OutputFcn', @TheProcessor_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 TheProcessor is made visible. +function TheProcessor_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 TheProcessor (see VARARGIN) + +% Choose default command line output for TheProcessor +handles.output = hObject; + +handles.par_file = {}; +handles.par_IRFfile = ''; +handles.filename = {}; + +set(handles.text2,'String','Ready'); + +wt = num2cell(25); +wt(1) = {510}; +wt(2) = {0}; +set(handles.uitable1,'ColumnWidth',wt); + +col_name = {'Files'}; +set(handles.uitable1,'Data',handles.filename'); +set(handles.uitable1,'ColumnName',col_name); + +% Update handles structure +guidata(hObject, handles); + +% UIWAIT makes TheProcessor wait for user response (see UIRESUME) +% uiwait(handles.figure1); + + +% --- Outputs from this function are returned to the command line. +function varargout = TheProcessor_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; + + +% --- Executes on button press in Load_button. +function Load_button_Callback(hObject, eventdata, handles) +% hObject handle to Load_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +n = numel(handles.par_file); + +[FileName,PathName] = uigetfile({'*.ht3;*.pt3;*.ptu','t3r-files';'*.*','All Files' },'Select data files ...','MultiSelect', 'on'); + +if ~iscell(FileName) + if FileName ~= 0 + handles.par_file{n+1} = [PathName FileName]; + handles.filename{n+1} = FileName; + end +else + for k = 1:numel(FileName) + handles.par_file{n+k} = [PathName FileName{k}]; + handles.filename{n+k} = FileName{k}; + end +end +set(handles.uitable1,'Data',handles.filename'); +guidata(hObject, handles); + + +% --- Executes on button press in SetParams_button. +function SetParams_button_Callback(hObject, eventdata, handles) +% hObject handle to SetParams_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(handles.figure1,'Visible','off'); +Set_Params; +set(handles.figure1,'Visible','on'); + + +% --- Executes on button press in Start_button. +function Start_button_Callback(hObject, eventdata, handles) +% hObject handle to Start_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +set(handles.text2,'String','Processing data...'); +k = numel(handles.par_file); + +parfor n = 1:k + + W = handles.par_file{n}; + if isempty(handles.par_IRFfile) + s = sprintf('Processing file %s (%d of %d)...', handles.filename{n}, n, k); + else + s = sprintf('Processing file %s (%d of %d) using IRF "%s"...', handles.filename{n}, n, k, handles.par_IRFfile); + end + + set(handles.text2,'String', s ); + + pause(0.2) + + N1 = [W(1:end-4) '_DATA.mat']; + tmp = dir(N1); + + if (numel(tmp)==0) + Process_file(W, handles.par_IRFfile); + end + +end + +set(handles.text2,'String','Done'); + + +% --- Executes on button press in Quit_button. +function Quit_button_Callback(hObject, eventdata, handles) +% hObject handle to Quit_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +close + +% --- 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 +delete(hObject); + + +% --- Executes on button press in SelectIRF_button. +function SelectIRF_button_Callback(hObject, eventdata, handles) +% hObject handle to SelectIRF_button (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +handles.par_IRFfile = ''; +handles.IRFfile = ''; + +[FileName, PathName] = uigetfile({'*.ht3;*.pt3','t3r-files';'*.*','All Files' }); + +if FileName ~= 0 + handles.par_IRFfile = [PathName FileName]; + handles.IRFfile = FileName; +end +guidata(hObject, handles); diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/c_map.mat b/Spectral-FLIM GUI/Spectral-FLIM GUI/c_map.mat new file mode 100644 index 0000000..0665370 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/c_map.mat differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/colorPalette.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/colorPalette.m new file mode 100644 index 0000000..471045e --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/colorPalette.m @@ -0,0 +1,256 @@ +function varargout = colorPalette(varargin) +% COLORPALETTE GUI creation example +% COLORPALETTE is an example GUI for demonstrating how to creating +% GUIs using nested functions. It shows how to share data between two +% GUIs, support custom input property/value pairs with data +% validation, and output data to the caller. COLORPALETTE populate a +% color palette into a given figure or panel provided as an input +% parameter through custom property 'parent'. If user does not +% provide parent, GCF will be used. +% +% GETCOLORFCN = COLORPALETTE(...) runs the GUI. And return a function +% handle for getting the currently selected color in the color +% palette. The returned function handle can be used at any time +% before the color palette is destroyed. +% +% COLORPALETTE('Property','Value',...) runs the GUI. This GUI +% accepts property value pairs from the input arguments. Only the +% following custom properties are supported that can be used to +% initialize this GUI. The names are not case sensitive: +% 'parent' the parent figure or panel that holds the color palette +% Other unrecognized property name or invalid value is ignored. +% +% Examples: +% +% fhandle = colorPalette; +% color = fhandle(); +% +% panel = uipanel('title', 'Palette'); +% fhandle = colorPalette('parent', panel); +% color = fhandle(); + +% Copyright 1984-2006 The MathWorks, Inc. + +% Declare non-UI data so that they can be used in any functions in this GUI +% file, including functions triggered by creating the GUI layout below +mInputArgs = varargin; % Command line arguments when invoking the GUI +mOutputArgs = {}; % Variable for storing output when GUI returns +mSelectedColor = [0,0,0]; % Currently selected color in the palette +% Variables for supporting custom property/value pairs +mPropertyDefs = {... % The supported custom property/value pairs of this GUI + 'parent', @localValidateInput, 'mPaletteParent'}; +mPaletteParent = []; % Use input property 'parent' to initialize + +% Process the command line input arguments supplied when the GUI is +% invoked +processUserInputs(); + +% Declare and create all the UI objects in this GUI here so that they can +% be used in any functions +hPalettePanel = uibuttongroup('Parent',mPaletteParent, ... + 'Units', 'Pixels',... + 'Position',[0 0 1 1],... + 'Title',{''},... + 'BorderType', 'none',... + 'SelectionChangeFcn', @hPalettePanelSelectionChanged); +hSelectedColorText = uicontrol('Parent',hPalettePanel,... + 'Units', 'Pixels',... + 'Style', 'text'); +hMoreColorButton = uicontrol('Parent',hPalettePanel,... + 'Units', 'Pixels',... + 'String', 'More Colors ...',... + 'Callback',@hMoreColorButtonCallback); + +% Dynamically create the color cells and palette tools and layout component +layoutComponent(); + +% initalized the displayed color information +localUpdateColor(); + +% Return user defined output if it is requested +mOutputArgs{1} =@getSelectedColor; +if nargout>0 + [varargout{1:nargout}] = mOutputArgs{:}; +end + + %---------------------------------------------------------------------- + function color = getSelectedColor + % function returns the currently selected color in this colorPlatte + color = mSelectedColor; + end + + %---------------------------------------------------------------------- + function hPalettePanelSelectionChanged(hObject, eventdata) + % Callback called when the selected color is changed in the colorPlatte + selected = get(hPalettePanel,'SelectedObject'); + def = get(selected, 'UserData'); + if ~isempty(def) && isfield(def,'Callback') + def.Callback(selected, eventdata); + end + end + + %---------------------------------------------------------------------- + function hMoreColorButtonCallback(hObject, eventdata) + % Callback called when the more color button is pressed. + color = mSelectedColor; + if isnan(color) + color =[0 0 0]; + end + color = uisetcolor(color); + if ~isequal(color, mSelectedColor) + mSelectedColor =color; + localUpdateColor(); + end + end + + %---------------------------------------------------------------------- + function colorCellCallback(hObject, eventdata) + % Callback called when any color cell button is pressed + mSelectedColor = get(hObject, 'BackgroundColor'); + localUpdateColor(); + end + + %---------------------------------------------------------------------- + function localUpdateColor + % helper function that updates the preview of the selected color + set(hSelectedColorText, 'BackgroundColor', mSelectedColor); + end + + %---------------------------------------------------------------------- + function layoutComponent + % helper function that dynamically creats all the tools and color cells + % in the palette. It also positions all other UI objects properly. + % get the definision of the layout + [mLayout, mColorEntries] = localDefineLayout(); + + % change the size of the color palette to the desired size, place + % the components, and then change size back. + setpixelposition(hPalettePanel, [0, 0, mLayout.preferredWidth, mLayout.preferredHeight]); + + + startY = mLayout.preferredHeight - mLayout.colorSampleSize; + startX = mLayout.hgap; + + % place color sample + setpixelposition(hSelectedColorText, [startX, startY, ... + mLayout.preferredWidth-2*mLayout.hgap, ... + mLayout.colorSampleSize]); + % create color cells + for i=1:mLayout.cellRowNumber + startY = startY - (mLayout.cellSize+mLayout.hgap); + for j=1:mLayout.cellPerRow + if ((i-1)*mLayout.cellPerRow + j)>length(mColorEntries) + break; + end + color = mColorEntries{(i-1)*mLayout.cellPerRow + j}; + tooltip = mat2str(color.Color); + if isfield(color,'Name') + tooltip = color.Name; + end + control = uicontrol('Style','ToggleButton',... + 'TooltipString', tooltip,... + 'BackgroundColor',color.Color,... + 'Parent',hPalettePanel, ... + 'Units','Pixels',... + 'UserData',color,... + 'Position',[startX+(j-1)*(mLayout.cellSize+mLayout.hgap),... + startY, ... + mLayout.cellSize, mLayout.cellSize]); + end + end + + % place more color button + startY = startY - mLayout.moreColorButtonHeight - mLayout.vgap; + setpixelposition(hMoreColorButton,[startX, startY, ... + mLayout.preferredWidth - 2*mLayout.hgap,mLayout.moreColorButtonHeight]); + + % restore palette to the full size + set(hPalettePanel, 'units', 'normalized', 'Position', [0 0 1 1]); + + %---------------------------------------------------------------------- + function [layout, colors]=localDefineLayout + % helper functions that provides the data defining the color palette + colors = localDefineColors(); + + layout.hgap = 5; + layout.vgap = 5; + layout.cellSize = 21; + layout.cellPerRow = 4; + layout.colorSampleSize = 21; + layout.moreColorButtonHeight = 30; + + % calculate the preferred width and height + width = max([2*layout.colorSampleSize,(layout.cellSize+layout.hgap)*layout.cellPerRow]); + layout.cellRowNumber = ceil(length(colors)/ceil(width/(layout.cellSize+layout.vgap))); + height = layout.cellRowNumber*(layout.cellSize+layout.vgap) ... + + layout.colorSampleSize + layout.moreColorButtonHeight; + layout.preferredWidth = layout.hgap+width; + layout.preferredHeight = 2*layout.vgap+height; + end + + %-------------------------------------------------------------------------- + function colors = localDefineColors + % helper function that defines the colors shown in this color + % palette. The 'name' is used to show a tooltip of the color. If it + % is not provided, the color value is used as the tooltip. The + % 'callback' is used to provide the function called when the + % corresponding color is selected. You can change the color values + % or the number of colors. The palette will adapt to the changes + callback =@colorCellCallback; + colors= {struct('Color','red',... + 'Callback',callback),... + struct('Color','green',... + 'Callback',callback),... + struct('Color','blue',... + 'Callback',callback),... + struct('Color','yellow',... + 'Callback',callback),... + struct('Color','magenta',... + 'Callback',callback),... + struct('Color','cyan',... + 'Callback',callback),... + struct('Color','white',... + 'Callback',callback),... + struct('Color',[0.5,0.5,0.5],... + 'Callback',callback)}; + end + end + + + %---------------------------------------------------------------------- + function processUserInputs + % helper function that processes the input property/value pairs + % Apply recognizable custom parameter/value pairs + for index=1:2:length(mInputArgs) + if length(mInputArgs) < index+1 + break; + end + match = find(ismember({mPropertyDefs{:,1}},mInputArgs{index})); + if ~isempty(match) + % Validate input and assign it to a variable if given + if ~isempty(mPropertyDefs{match,3}) && mPropertyDefs{match,2}(mPropertyDefs{match,1}, mInputArgs{index+1}) + assignin('caller', mPropertyDefs{match,3}, mInputArgs{index+1}) + end + end + end + + if isempty(mPaletteParent) + mPaletteParent =gcf; + end + end + + %---------------------------------------------------------------------- + function isValid = localValidateInput(property, value) + % helper function that validates the user provided input property/value + % pairs. You can choose to show warnings or errors here. + isValid = false; + switch lower(property) + case 'parent' + if ishandle(value) + mPaletteParent = true; + isValid =true; + end + end + end +end % end of iconPalette + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/cscatter.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/cscatter.m new file mode 100644 index 0000000..fe9a272 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/cscatter.m @@ -0,0 +1,146 @@ +function cscatter(h,X,Y, varargin) +% CSCATTER creates a scatter plot coloured by density. +% +% CSCATTER(X,Y) creates a scatterplot of X and Y at the locations +% specified by the vectors X and Y (which must be the same size), colored +% by the density of the points. +% +% CSCATTER(...,'MARKER',M) allows you to set the marker for the +% scatter plot. Default is 's', square. +% +% CSCATTER(...,'MSIZE',MS) allows you to set the marker size for the +% scatter plot. Default is 10. +% +% CSCATTER(...,'FILLED',false) sets the markers in the scatter plot to be +% outline. The default is to use filled markers. +% +% CSCATTER(...,'BINS',[NX,NY]) allows you to set the number of bins used +% for the 2D histogram used to estimate the density. The default is to +% use the number of unique values in X and Y up to a maximum of 200. +% +% CSCATTER(...,'SMOOTHING',LAMBDA) allows you to set the smoothing factor +% used by the density estimator. The default value is 20 which roughly +% means that the smoothing is over 20 bins around a given point. +% +% CSCATTER(...,'LOGY',true) uses a log scale for the yaxis. +% +% Reference: +% Paul H. C. Eilers and Jelle J. Goeman +% Enhancing scatterplots with smoothed densities +% Bioinformatics, Mar 2004; 20: 623 - 628. + +lambda = []; +nbins = []; +msize = 10; +marker = 'diamond'; +logy = false; +filled = true; + +if nargin > 3 + if rem(nargin,2) == 0 + error('Incorrect number of arguments to %s.',mfilename); + end + okargs = {'smoothing','bins','logy','marker','msize','filled'}; + for j=1:2:nargin-3 + pname = varargin{j}; + pval = varargin{j+1}; + k = strmatch(lower(pname), okargs); %#ok + if isempty(k) + error('Unknown parameter name: %s.',pname); + elseif length(k)>1 + error('Ambiguous parameter name: %s.',pname); + else + switch(k) + case 1 % smoothing factor + if isnumeric(pval) + lambda = pval; + else + error('Invalid smoothing parameter.'); + end + case 2 + if isscalar(pval) + nbins = [pval pval]; + else + nbins = pval; + end + case 3 + logy = pval; + Y = log10(Y); + case 4 + marker = pval; + case 5 + msize = pval; + case 6 + filled = pval; + end + end + end +end + +ind = ~isnan(X); +X = X(ind); +Y = Y(ind); +ind = ~isnan(Y); +X = X(ind); +Y = Y(ind); + +if numel(X)>10 + minx = min(X,[],1); + maxx = max(X,[],1); + miny = min(Y,[],1); + maxy = max(Y,[],1); + + if isempty(nbins) + nbins = [min(numel(unique(X)),200) ,min(numel(unique(Y)),200) ]; + end + + if isempty(lambda) + lambda = 20; + end + + edges1 = linspace(minx, maxx, nbins(1)+1); + edges1 = [-Inf edges1(2:end-1) Inf]; + edges2 = linspace(miny, maxy, nbins(2)+1); + edges2 = [-Inf edges2(2:end-1) Inf]; + + n = size(X,1); + bin = zeros(n,2); + % Reverse the columns to put the first column of X along the horizontal + % axis, the second along the vertical. + [dum,bin(:,2)] = histc(X,edges1); + [dum,bin(:,1)] = histc(Y,edges2); + H = accumarray(bin,1,nbins([2 1])) ./ n; + G = smooth1D(H,nbins(2)/lambda); + F = smooth1D(G',nbins(1)/lambda)'; + + if logy + Y = 10.^Y; + end + + if numel(F)>0 + F = F./max(F(:)); + ind = sub2ind(size(F),bin(:,1),bin(:,2)); + col = F(ind); + if filled + h = scatter(h,X,Y,msize,col,marker,'filled'); + else + h = scatter(h,X,Y,msize,col,marker); + end + else + cla; + end +else + if filled + h = scatter(h,X,Y,msize,[0.5 0.3 0.5],marker,'filled'); + else + h = scatter(h,X,Y,msize,[0.5 0.3 0.5],marker); + end +end + + +%set(h,'yscale','log'); +%set(h,'xscale','log'); + +% if nargout > 0 +% hAxes = get(h,'parent'); +% end diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/data.mat b/Spectral-FLIM GUI/Spectral-FLIM GUI/data.mat new file mode 100644 index 0000000..b0d80a0 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/data.mat differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/dlsfit.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/dlsfit.m new file mode 100644 index 0000000..2c8c16d --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/dlsfit.m @@ -0,0 +1,51 @@ +function [err, A, z] = dlsfit(param, t, irf, y, p, pic) + +% DLSFIT(param, t, irf, y, p, pic) returns the Least-Squares deviation between the data y +% and the computed values. +% LSFIT assumes a function of the form: +% +% y = yoffset + A(1)*convol(irf,exp(-t/tau(1)/(1-exp(-p/tau(1)))) + ... +% +% param(1) is the color shift value between irf and y. +% param(2) is the irf offset. +% param(3:...) are the decay times. +% irf is the measured Instrumental Response Function. +% y is the measured fluorescence decay curve. +% p is the time between to laser excitations (in number of TCSPC channels). + +if (nargin==6)&&~isempty(pic) + pic = true; +else + pic = false; +end + +c = param(1); +tau = param(2:length(param)); +tau = tau(:)'; + +n = length(irf); +t = t(:); +tp = (0:p-1)'; + +ind = 1+intersect(round(t),round(tp)); + +irf1 = interp1(t,irf,tp,'pchip'); + +x = exp(-tp*(1./tau))*diag(1./(1-exp(-p./tau))); + +irs = (1-c+floor(c))*irf1(rem(rem(tp-floor(c), p)+p,p)+1) + ... + ( c-floor(c))*irf1(rem(rem(tp-ceil(c), p)+p,p)+1); + +z = convol(irs, x); +z = z(ind,:); + +z = [ones(size(z,1),1) z]; +A = z\y; %A = lsqnonneg(z,y); +z = z*A; + +if pic + semilogy(t, irf/max(irf)*max(y), t, y, 'bo', t, z); + drawnow +end +err = sum((z-y).^2./abs(z))/(n-length(tau)); + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/eval_results.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/eval_results.m new file mode 100644 index 0000000..af89264 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/eval_results.m @@ -0,0 +1,21 @@ +clear all + +name = 'test_results.mat'; + +load([name]); + +amp = results.amp; +amp = reshape(amp,[size(amp,1)*size(tmp,2) size(amp,3)]); + +m = max(max(amp)); +m = 100*ceil(m/100); +b = 10:5:m; +histo_1 = []; + +for a = 1:size(amp,3) + histo(:,a) = mHist(amp(:,a),b); + m1(a) = mean(amp(:,a)); + s1(a) = std(amp(:,a)); +end + +save([name(1:end-3) 'dat'],'histo','-ASCII') \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/getWorkersAvailable.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/getWorkersAvailable.m new file mode 100644 index 0000000..41dc2c8 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/getWorkersAvailable.m @@ -0,0 +1,30 @@ +function [num_workers, isexist_ParallelToolBox] = getWorkersAvailable() + +% First checks if Parallel Computing Toolbox exists and then +% Returns num of workers available for executing parallel computing +% + +available_toolboxes = ver; +isexist_ParallelToolBox = false; +num_workers = 0; % default is set to 0 = single core processing +index =1; + +while index < size(available_toolboxes,2) + + if (convertCharsToStrings(available_toolboxes(index).Name) == "Parallel Computing Toolbox") + isexist_ParallelToolBox = true; + break; + end + + index = index + 1; + +end + +% if Paralle Computing toolbox available then get num_workers/CPU cores +% available for batch processing +if isexist_ParallelToolBox + myCluster = parcluster('local'); + num_workers = myCluster.NumWorkers; +end + +end \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/load_data.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/load_data.m new file mode 100644 index 0000000..3adcbac --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/load_data.m @@ -0,0 +1,27 @@ +function [head, tag, tcspc, IRF, timname, AP, DC] = load_data(name) + +head = []; +tcspc = []; +IRF = []; +tag = []; +AP = []; +DC = []; +timname = ''; + +tmp = strfind(name,'\'); +pathname = name(1:tmp(end)); +filename = name(tmp(end)+1:end); +name1 = [filename(1:end-4) '_DATA.mat']; + +names1 = dir([pathname name1]); + +if (numel(names1)==1) + load([pathname name1], 'head', 'tag', 'tcspc', 'IRF', 'AP', 'DC'); + tag(tag<0)=0; + timname = [filename(1:end-4) '_FLIM.mat']; + +else + fprintf('\n Data-files were not found in current directory.'); + fprintf('\n Please call "Process_file" to create necessary files.'); +end + \ No newline at end of file diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/lsfit.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/lsfit.m new file mode 100644 index 0000000..2625beb --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/lsfit.m @@ -0,0 +1,33 @@ +function [err A z] = lsfit(param, irf, y, p) +% LSFIT(param, irf, y, p) returns the Least-Squares deviation between the data y +% and the computed values. +% LSFIT assumes a function of the form: +% +% y = yoffset + A(1)*convol(irf,exp(-t/tau(1)/(1-exp(-p/tau(1)))) + ... +% +% param(1) is the color shift value between irf and y. +% param(2) is the irf offset. +% param(3:...) are the decay times. +% irf is the measured Instrumental Response Function. +% y is the measured fluorescence decay curve. +% p is the time between to laser excitations (in number of TCSPC channels). + + +n = length(irf); +t = 1:n; +tp = (1:p)'; +c = param(1); +tau = param(2:length(param)); tau = tau(:)'; +x = exp(-(tp-1)*(1./tau))*diag(1./(1-exp(-p./tau))); +irs = (1-c+floor(c))*irf(rem(rem(t-floor(c)-1, n)+n,n)+1) + (c-floor(c))*irf(rem(rem(t-ceil(c)-1, n)+n,n)+1); +z = convol(irs, x); +z = [ones(size(z,1),1) z]; +A = z\y; +%A = lsqnonneg(z,y); +z = z*A; +if 1 + semilogy(t, irs/max(irs)*max(y), t, y, 'bo', t, z); + drawnow +end +err = sum((z-y).^2./abs(z))/(n-length(tau)) + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/mHist.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/mHist.m new file mode 100644 index 0000000..7d771be --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/mHist.m @@ -0,0 +1,48 @@ +function [z, xv] = mHist(x,xv) + +if size(x,1)==1 || size(x,2)==1 + x = x(:); + x(~isfinite(x)) = []; +end + +xdim = max([1 size(x,2)]); + +if nargin>1 && ~isempty(xv) + xmin = xv(1); + xmax = xv(end); + ind = x>xmax | x1 + dx = xv(2)-xv(1); + end + if dx ~=0 + x = round((x-xmin)/dx)+1; + xmax = round((xmax-xmin)/dx)+1; + else + x = round(x-xmin)+1; + xmax = 0; + end + else + x = round(interp1(xv,1:length(xv),x)); + xmax = round(interp1(xv,1:length(xv),xmax)); + end +end + +z = zeros(length(xv)*xdim,1); +if ~isempty(x) + num = sort(x+xmax*ones(size(x,1),1)*(0:xdim-1)); + num = num(:); + z(num) = 1; + tmp = diff(diff([0; num; 0])==0); + ind = (1:length(num))'; + z(num(tmp==1)) = z(num(tmp==1))-ind(tmp==1)+ind(tmp==-1); + z = reshape(z,length(xv),xdim); +end; + +if nargout==0 + bar(xv,z,1,'b'); + clear z xv +end diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/sFLIM.fig b/Spectral-FLIM GUI/Spectral-FLIM GUI/sFLIM.fig new file mode 100644 index 0000000..d1012a6 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/sFLIM.fig differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/sFLIM.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/sFLIM.m new file mode 100644 index 0000000..9e6cf14 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/sFLIM.m @@ -0,0 +1,410 @@ +function varargout = sFLIM(varargin) +% SFLIM M-file for sFLIM.fig +% SFLIM, by itself, creates a new SFLIM or raises the existing +% singleton*. +% +% H = SFLIM returns the handle to a new SFLIM or the handle to +% the existing singleton*. +% +% SFLIM('CALLBACK',hObject,eventData,handles,...) calls the local +% function named CALLBACK in SFLIM.M with the given input arguments. +% +% SFLIM('Property','Value',...) creates a new SFLIM or raises the +% existing singleton*. Starting from the left, property value pairs are +% applied to the GUI before sFLIM_OpeningFcn gets called. An +% unrecognized property name or invalid value makes property application +% stop. All inputs are passed to sFLIM_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 sFLIM + +% Last Modified by GUIDE v2.5 15-Sep-2011 09:35:37 +%#function Set_Params + +% Begin initialization code - DO NOT EDIT +gui_Singleton = 1; +gui_State = struct('gui_Name', mfilename, ... + 'gui_Singleton', gui_Singleton, ... + 'gui_OpeningFcn', @sFLIM_OpeningFcn, ... + 'gui_OutputFcn', @sFLIM_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 sFLIM is made visible. +function sFLIM_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 sFLIM (see VARARGIN) + +% Choose default command line output for sFLIM +handles.output = hObject; + +% Update handles structure +set(handles.text13,'String','Ready'); + +handles.par_file = ''; +handles.par_IRFfile = ''; + +guidata(hObject, handles); + + +% UIWAIT makes sFLIM wait for user response (see UIRESUME) +% uiwait(handles.figure1); + + +% --- Outputs from this function are returned to the command line. +function varargout = sFLIM_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; + + +% --- Executes during object creation, after setting all properties. +function input_filename_CreateFcn(hObject, eventdata, handles) +% hObject handle to input_filename (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 FastFLIM. +function FastFLIM_Callback(hObject, eventdata, handles) +% hObject handle to FastFLIM (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +%#function FastFLIM + +set(handles.text13,'String','Busy'); +pause(0.05) +evalin('base', 'clear all'); + +W = handles.par_file; +N1 = [W(1:end-4) '_Moments.mat']; + +tmp = dir(N1); + +if (numel(tmp)==0) + s = sprintf('MomentAnalysis(\''%s\'');', handles.par_file); + evalin('base', s); +end + +s = sprintf('FastFLIM(\''%s\'');', handles.par_file); +evalin('base', s); +set(handles.text13,'String','Ready'); + + +% --- Executes on button press in PatternAnalysis +function pushbutton30_Callback(hObject, eventdata, handles) +% hObject handle to pushbutton30 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +%#function MomentAnalysis Results_4 + +set(handles.text13,'String','Busy'); +pause(0.05) +W = handles.par_file; +N1 = [W(1:end-4) '_Moments.mat']; + +tmp = dir(N1); + +if (numel(tmp)==0) + s = sprintf('MomentAnalysis(\''%s\'');', handles.par_file); + evalin('base', s); +end + +s = sprintf('Results_4(\''file\'', \''%s\'');', handles.par_file); +evalin('base', s); +set(handles.text13,'String','Ready'); + + +% --- Executes on button press in Process_file. +function Process_file_Callback(hObject, eventdata, handles) +% hObject handle to Process_file (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if ~iscell(handles.par_file) + n = 1; + W = handles.par_file; + N1 = [W(1:end-4) '_DATA.mat']; + + tmp = dir(N1); + + if (numel(tmp)==0) + set(handles.text13,'String','Processing data...'); + pause(0.05) + Process_file(W, handles.par_IRFfile); + end +else + for n = 1:numel(handles.par_file) + W = handles.par_file{n}; + N1 = [W(1:end-4) '_DATA.mat']; + + tmp = dir(N1); + + if (numel(tmp)==0) + set(handles.text13,'String','Processing data...'); + pause(0.05) + Process_file(W, handles.par_IRFfile); + end + end +end + +if n>1 + tmp = questdlg([{'Please select recording scheme:'}, {'Same excitation, different emission channel.'}, {'Different excitaition, same emission channel.'}],'Combine images','Same excitation','Same emission','Cancel','Yes'); + if ~strcmp(tmp,'Cancel') + + FileName = get(handles.text10, 'string'); + FileName = [FileName(1:end-7) '_combined.ht3']; + set(handles.text10, 'string', FileName); + + W = handles.par_file{1}; + load([W(1:end-4) '_DATA.mat']); + + tmp_DC = DC; + tmp_AP = AP; + tmp_IRF = IRF; + tmp_tcspc = tcspc; + tmp_tag = tag; + + for n = 2:numel(handles.par_file) + W = handles.par_file{n}; + load([W(1:end-4) '_DATA.mat']); + if strcmp(tmp,'Same emission') + tmp_DC = cat(3, tmp_DC, DC); + tmp_AP = cat(3, tmp_AP, AP); + tmp_IRF = cat(3, tmp_IRF, IRF); + tmp_tcspc = cat(3, tmp_tcspc, tcspc); + tmp_tag = cat(4, tmp_tag, tag); + else + tmp_DC = cat(2, tmp_DC, DC); + tmp_AP = cat(2, tmp_AP, AP); + tmp_IRF = cat(1, tmp_IRF, IRF); + tmp_tcspc = cat(1, tmp_tcspc, tcspc); + tmp_tag = cat(3, tmp_tag, tag); + end + end + + DC = tmp_DC; + AP = tmp_AP; + IRF = tmp_IRF; + tcspc = tmp_tcspc; + tag = tmp_tag; + + save([handles.par_file{1}(1:end-4) '_combined_DATA.mat'], 'head', 'DC', 'AP', 'IRF', 'tcspc', 'tag'); + + clear('head', 'DC', 'AP', 'IRF', 'tcspc', 'tag', 'tmp_DC', 'tmp_AP', 'tmp_IRF', 'tmp_tcspc', 'tmp_tag'); + + load([handles.par_file{1}(1:end-4) '_FLIM.mat']); + + tmp_stim = stim; + for n = 2:numel(handles.par_file) + W = handles.par_file{n}; + load([W(1:end-4) '_FLIM.mat']); + if strcmp(tmp,'Same emission') + tmp_stim = cat(5, tmp_stim, stim); + else + tmp_stim = cat(3, tmp_stim, stim); + end + end + + stim = tmp_stim; + + save([handles.par_file{1}(1:end-4) '_combined_FLIM.mat'], 'stim'); + + clear('stim','tmp_stim'); + + handles.par_file = [handles.par_file{1}(1:end-4) '_combined.ht3']; + else + handles.par_file = handles.par_file{1}; + end +end + +set(handles.text13,'String','Ready'); +guidata(hObject, handles); + + +% --- Executes on button press in FLIM_graph. +function FLIM_graph_Callback(hObject, eventdata, handles) +evalin('base', 'fastflim_graph'); +% hObject handle to FLIM_graph (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + + +function input_filename_Callback(hObject, eventdata, handles) +% hObject handle to input_filename (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +name = get(hObject, 'String'); +% Hints: get(hObject,'String') returns contents of input_filename as text +% str2double(get(hObject,'String')) returns contents of input_filename as a double + + +% --- Executes on button press in Select_ht3file. +function Select_ht3file_Callback(hObject, eventdata, handles) +% hObject handle to Select_ht3file (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(handles.text10, 'string', ''); +handles.par_file = ''; + +[FileName,PathName] = uigetfile({'*.ht3;*.pt3;*.ptu','t3r-files';'*.*','All Files'}, 'MultiSelect', 'on'); + +if ~iscell(FileName) + set(handles.text10, 'string', FileName); + handles.par_file = [PathName FileName]; +elseif numel(FileName) > 1 + if strcmp(questdlg([{'You have selceted more than one file!'}, {'Processing will combine the data in one image. Continue?'}],'Confirm selection','Yes','No','No'),'Yes') + set(handles.text10, 'string', [FileName{1} '...']); + for n = 1:numel(FileName) + handles.par_file{n} = [PathName FileName{n}]; + end + end +else + warndlg('No files selected!') +end + +guidata(hObject, handles); + + +% --- Executes on button press in select_IRF_file. +function select_IRF_file_Callback(hObject, eventdata, handles) +% hObject handle to select_IRF_file (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +set(handles.text14, 'string', ''); +handles.par_IRFfile = ''; + +[FileName,PathName] = uigetfile({'*.ht3;*.pt3;*.ptu','tr3-files';'*.mat','mat-files' }); + +if isempty(FileName) + warndlg('No file selected!') +else + if ~iscell(FileName) + set(handles.text14, 'string', FileName); + handles.par_IRFfile = [PathName FileName]; + elseif numel(FileName) > 1 + set(handles.text14, 'string', FileName{1}); + handles.par_IRFfile = [PathName FileName{1}]; + end +end +guidata(hObject, handles); + + +% --- Executes on button press in Clear_files. +function Clear_files_Callback(hObject, eventdata, handles) +% hObject handle to Clear_files (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +if ~isempty(handles.par_file) + if strcmp(questdlg('This will delete all associated data files. Continue?','Confirm deletion','Yes','No','No'),'Yes') + delete([handles.par_file(1:end-4) '_*.*']); + end +else + helpdlg('Please select sFLIM data-file.','No data-file chosen'); +end + + +% --- 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) +close all + + +% --- Executes on button press in Set_Params. +function Set_Params_Callback(hObject, eventdata, handles) +% hObject handle to Set_Params (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) + +%#function Set_Params + +set(handles.figure1,'Visible','off'); + +%evalin('base', 'Set_Params') +Set_Params; +set(handles.figure1,'Visible','on'); + + +% --- Executes on button press in pushbutton27. +function pushbutton27_Callback(hObject, eventdata, handles) +% hObject handle to pushbutton27 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +evalin('base', 'clear all') + + +% --- Executes on button press in pushbutton28. +function pushbutton28_Callback(hObject, eventdata, handles) +% hObject handle to pushbutton28 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +set(handles.text13,'String','Bye'); +close; +delete(handles.figure1); + + +% --- Executes during object creation, after setting all properties. +function text13_CreateFcn(hObject, eventdata, handles) +% hObject handle to text13 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called + + +% --- Executes during object creation, after setting all properties. +function text10_CreateFcn(hObject, eventdata, handles) +% hObject handle to text10 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles empty - handles not created until after all CreateFcns called +set(hObject,'String','Please select PTU-file'); + +% --- Executes during object deletion, before destroying properties. +function text10_DeleteFcn(hObject, eventdata, handles) +% hObject handle to text10 (see GCBO) +% eventdata reserved - to be defined in a future version of MATLAB +% handles structure with handles and user data (see GUIDATA) +set(hObject,'String',''); + + +% --- 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 +delete(hObject); diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/smooth.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/smooth.m new file mode 100644 index 0000000..3ccafab --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/smooth.m @@ -0,0 +1,683 @@ +function [c,ww] = smooth(varargin) +%SMOOTH Smooth data. +% Z = SMOOTH(Y) smooths data Y using a 5-point moving average. +% +% Z = SMOOTH(Y,SPAN) smooths data Y using SPAN as the number of points used +% to compute each element of Z. +% +% Z = SMOOTH(Y,SPAN,METHOD) smooths data Y with specified METHOD. The +% available methods are: +% +% 'moving' - Moving average (default) +% 'lowess' - Lowess (linear fit) +% 'loess' - Loess (quadratic fit) +% 'sgolay' - Savitzky-Golay +% 'rlowess' - Robust Lowess (linear fit) +% 'rloess' - Robust Loess (quadratic fit) +% +% Z = SMOOTH(Y,METHOD) uses the default SPAN 5. +% +% Z = SMOOTH(Y,SPAN,'sgolay',DEGREE) and Z = SMOOTH(Y,'sgolay',DEGREE) +% additionally specify the degree of the polynomial to be used in the +% Savitzky-Golay method. The default DEGREE is 2. DEGREE must be smaller +% than SPAN. +% +% Z = SMOOTH(X,Y,...) additionally specifies the X coordinates. If X is +% not provided, methods that require X coordinates assume X = 1:N, where +% N is the length of Y. +% +% Notes: +% 1. When X is given and X is not uniformly distributed, the default method +% is 'lowess'. The 'moving' method is not recommended. +% +% 2. For the 'moving' and 'sgolay' methods, SPAN must be odd. +% If an even SPAN is specified, it is reduced by 1. +% +% 3. If SPAN is greater than the length of Y, it is reduced to the +% length of Y. +% +% 4. In the case of (robust) lowess and (robust) loess, it is also +% possible to specify the SPAN as a percentage of the total number +% of data points. When SPAN is less than or equal to 1, it is +% treated as a percentage. +% +% For example: +% +% Z = SMOOTH(Y) uses the moving average method with span 5 and +% X=1:length(Y). +% +% Z = SMOOTH(Y,7) uses the moving average method with span 7 and +% X=1:length(Y). +% +% Z = SMOOTH(Y,'sgolay') uses the Savitzky-Golay method with DEGREE=2, +% SPAN = 5, X = 1:length(Y). +% +% Z = SMOOTH(X,Y,'lowess') uses the lowess method with SPAN=5. +% +% Z = SMOOTH(X,Y,SPAN,'rloess') uses the robust loess method. +% +% Z = SMOOTH(X,Y) where X is unevenly distributed uses the +% 'lowess' method with span 5. +% +% Z = SMOOTH(X,Y,8,'sgolay') uses the Savitzky-Golay method with +% span 7 (8 is reduced by 1 to make it odd). +% +% Z = SMOOTH(X,Y,0.3,'loess') uses the loess method where span is +% 30% of the data, i.e. span = ceil(0.3*length(Y)). +% +% See also SPLINE. + +% Copyright 2001-2009 The MathWorks, Inc. +% $Revision: 1.17.4.14 $ $Date: 2009/12/02 06:41:43 $ + +if nargin < 1 + error('curvefit:smooth:needMoreArgs', ... + 'SMOOTH needs at least one argument.'); +end + +if nargout > 1 % Called from the GUI cftool + ws = warning('off', 'all'); % turn warning off and record the previous warning state. + [lw,lwid] = lastwarn; + lastwarn(''); +else + ws = warning('query','all'); % Leave warning state alone but save it so resets are no-ops. +end + +% is x given as the first argument? +if nargin==1 || ( nargin > 1 && (length(varargin{2})==1 || ischar(varargin{2})) ) + % smooth(Y) | smooth(Y,span,...) | smooth(Y,method,...) + is_x = 0; % x is not given + y = varargin{1}; + y = y(:); + x = (1:length(y))'; +else % smooth(X,Y,...) + is_x = 1; + y = varargin{2}; + x = varargin{1}; + y = y(:); + x = x(:); +end + +% is span given? +span = []; +if nargin == 1+is_x || ischar(varargin{2+is_x}) + % smooth(Y), smooth(X,Y) || smooth(X,Y,method,..), smooth(Y,method) + is_span = 0; +else + % smooth(...,SPAN,...) + is_span = 1; + span = varargin{2+is_x}; +end + +% is method given? +method = []; +if nargin >= 2+is_x+is_span + % smooth(...,Y,method,...) | smooth(...,Y,span,method,...) + method = varargin{2+is_x+is_span}; +end + +t = length(y); +if t == 0 + c = y; + ww = ''; + if nargout > 1 + ww = lastwarn; + lastwarn(lw,lwid); + warning(ws); % turn warning back to the previous state. + end + return +elseif length(x) ~= t + warning(ws); % reset warn state before erroring + error('curvefit:smooth:XYmustBeSameLength',... + 'X and Y must be the same length.'); +end + +if isempty(method) + diffx = diff(x); + if uniformx(diffx,x,y) + method = 'moving'; % uniformly distributed X. + else + method = 'lowess'; + end +end + +% realize span +if span <= 0 + warning(ws); % reset warn state before erroring + error('curvefit:smooth:spanMustBePositive', ... + 'SPAN must be positive.'); +end +if span < 1, span = ceil(span*t); end % percent convention +if isempty(span), span = 5; end % smooth(Y,[],method) + +idx = 1:t; + +sortx = any(diff(isnan(x))<0); % if NaNs not all at end +if sortx || any(diff(x)<0) % sort x + [x,idx] = sort(x); + y = y(idx); +end + +c = NaN(size(y)); +ok = ~isnan(x); +switch method + case 'moving' + c(ok) = moving(x(ok),y(ok),span); + case {'lowess','loess','rlowess','rloess'} + robust = 0; + iter = 5; + if method(1)=='r' + robust = 1; + method = method(2:end); + end + c(ok) = lowess(x(ok),y(ok),span, method,robust,iter); + case 'sgolay' + if nargin >= 3+is_x+is_span + degree = varargin{3+is_x+is_span}; + else + degree = 2; + end + if degree < 0 || degree ~= floor(degree) || degree >= span + warning(ws); % reset warn state before erroring + error('curvefit:smooth:invalidDegree', ... + 'Degree must be an integer between 0 and span-1.'); + end + c(ok) = sgolay(x(ok),y(ok),span,degree); + otherwise + warning(ws); % reset warn state before erroring + error('curvefit:smooth:unrecognizedMethod', ... + 'SMOOTH: Unrecognized method.'); +end + +c(idx) = c; + +if nargout > 1 + ww = lastwarn; + lastwarn(lw,lwid); + warning(ws); % turn warning back to the previous state. +end + +%-------------------------------------------------------------------- +function c = moving(x,y, span) +% moving average of the data. + +ynan = isnan(y); +span = floor(span); +n = length(y); +span = min(span,n); +width = span-1+mod(span,2); % force it to be odd +xreps = any(diff(x)==0); +if width==1 && ~xreps && ~any(ynan), c = y; return; end +if ~xreps && ~any(ynan) + % simplest method for most common case + c = filter(ones(width,1)/width,1,y); + cbegin = cumsum(y(1:width-2)); + cbegin = cbegin(1:2:end)./(1:2:(width-2))'; + cend = cumsum(y(n:-1:n-width+3)); + cend = cend(end:-2:1)./(width-2:-2:1)'; + c = [cbegin;c(width:end);cend]; +elseif ~xreps + % with no x repeats, can take ratio of two smoothed sequences + yy = y; + yy(ynan) = 0; + nn = double(~ynan); + ynum = moving(x,yy,span); + yden = moving(x,nn,span); + c = ynum ./ yden; +else + % with some x repeats, loop + notnan = ~ynan; + yy = y; + yy(ynan) = 0; + c = zeros(n,1); + for i=1:n + if i>1 && x(i)==x(i-1) + c(i) = c(i-1); + continue; + end + R = i; % find rightmost value with same x + while(R1 && x(L)==x(L-1)) + L = L-1; + end + R = R+hf; % find rightmost point needed + while(R There is no significant growth here + end + + v = weight(:,ones(1,size(v,2))).*v; + y1 = weight.*y1; + if size(v,1)==size(v,2) + % Square v may give infs in the \ solution, so force least squares + b = [v;zeros(1,size(v,2))]\[y1;0]; + else + b = v\y1; + end + c(i) = b(1); + end +end + +% now that we have a non-robust fit, we can compute the residual and do +% the robust fit if required +maxabsyXeps = max(abs(y))*eps; +if robust + for k = 1:iter + r = y-c; + + % Compute robust weights + rweight = iBisquareWeights( r, maxabsyXeps ); + + % Find new value for each point. + for i=1:n + if i>1 && x(i)==x(i-1) + c(i) = c(i-1); + continue; + end + if isnan(c(i)), + continue; + end + + idx = lbound(i):rbound(i); + if anyNans + idx = idx(~ynan(idx)); + end + % check robust weights for removed points + if any( rweight(idx) <= 0 ) + idx = iKNearestNeighbours( span, i, x, (rweight > 0) ); + end + + x1 = x(idx) - x(i); + d1 = abs(x1); + y1 = y(idx); + + weight = iTricubeWeights( d1 ); + if all(weight There is no significant growth here + end + + % Modify the weights based on x values by multiplying them by + % robust weights. + weight = weight.*rweight(idx); + + v = weight(:,ones(1,size(v,2))).*v; + y1 = weight.*y1; + if size(v,1)==size(v,2) + % Square v may give infs in the \ solution, so force least squares + b = [v;zeros(1,size(v,2))]\[y1;0]; + else + b = v\y1; + end + c(i) = b(1); + end + end +end + + +%-------------------------------------------------------------------- +function c=sgolay(x,y,f,k) +% savitziki-golay smooth +% (x,y) are given data. f is the frame length to be taken, should +% be an odd number. k is the degree of polynomial filter. It should +% be less than f. + +% Reference: Orfanidis, S.J., Introduction to Signal Processing, +% Prentice-Hall, Englewood Cliffs, NJ, 1996. + +n = length(x); +f = floor(f); +f = min(f,n); +f = f-mod(f-1,2); % will subtract 1 if frame is even. +diffx = diff(x); +notnan = ~isnan(y); +nomissing = all(notnan); +if f <= k && all(diffx>0) && nomissing, c = y; return; end +hf = (f-1)/2; % half frame length + +idx = 1:n; +if any(diffx<0) % make sure x is monotonically increasing + [x,idx]=sort(x); + y = y(idx); + notnan = notnan(idx); + diffx = diff(x); +end +% note that x is sorted so max(abs(x)) must be abs(x(1)) or abs(x(end)); +% already calculated diffx for monotonic case, so use it again. Only +% recalculate if we sort x. +if nomissing && uniformx(diffx,x,y) + v = ones(f,k+1); + t=(-hf:hf)'; + for i=1:k + v(:,i+1)=t.^i; + end + [q,tmp]=qr(v,0); + ymid = filter(q*q(hf+1,:)',1,y); + ybegin = q(1:hf,:)*q'*y(1:f); + yend = q((hf+2):end,:)*q'*y(n-f+1:n); + c = [ybegin;ymid(f:end);yend]; + return; +end + +% non-uniformly distributed data +c = y; + +% Turn off warnings when called from command line (already off if called from +% cftool). +ws = warning('off', 'all'); +[lastwarnmsg,lastwarnid]=lastwarn; + +for i = 1:n + if i>1 && x(i)==x(i-1) + c(i) = c(i-1); + continue + end + L = i; R = i; % find leftmost and rightmost values + while(R1 && x(L-1)==x(i)) + L = L-1; + end + HF = ceil(max(0,(f - (R-L+1))/2)); % need this many more on each side + + L = min(n-f+1,max(1,L-HF)); % find leftmost point needed + while(L>1 && x(L)==x(L-1)) + L = L-1; + end + R = min(n,max(R+HF,L+f-1)); % find rightmost point needed + while(R0); + ncols = min(k+1, vrank); + v = ones(length(q),ncols); + for j = 1:ncols-1 + v(:,j+1) = q.^j; + end + if size(v,1)==size(v,2) + % Square v may give infs in the \ solution, so force least squares + d = [v;zeros(1,size(v,2))]\[y(tidx);0]; + else + d = v\y(tidx); + end + c(i) = d(1); +end +c(idx) = c; + +lastwarn(lastwarnmsg,lastwarnid); +warning(ws); + +% -------------------------------------------- +function ys = unifloess(y,span,useLoess) +%UNIFLOESS Apply loess on uniformly spaced X values + +y = y(:); + +% Omit points at the extremes, which have zero weight +halfw = (span-1)/2; % halfwidth of entire span +d = abs((1-halfw:halfw-1)); % distances to pts with nonzero weight +dmax = halfw; % max distance for tri-cubic weight + +% Set up weighted Vandermonde matrix using equally spaced X values +x1 = (2:span-1)-(halfw+1); +weight = (1 - (d/dmax).^3).^1.5; % tri-cubic weight +v = [ones(length(x1),1) x1(:)]; +if useLoess + v = [v x1(:).^2]; +end +V = v .* repmat(weight',1,size(v,2)); + +% Do QR decomposition +[Q,tmp] = qr(V,0); + +% The projection matrix is Q*Q'. We want to project onto the middle +% point, so we can take just one row of the first factor. +alpha = Q(halfw,:)*Q'; + +% This alpha defines the linear combination of the weighted y values that +% yields the desired smooth values. Incorporate the weights into the +% coefficients of the linear combination, then apply filter. +alpha = alpha .* weight; +ys = filter(alpha,1,y); + +% We need to slide the values into the center of the array. +ys(halfw+1:end-halfw) = ys(span-1:end-1); + +% Now we have taken care of everything except the end effects. Loop over +% the points where we don't have a complete span. Now the Vandermonde +% matrix has span-1 points, because only 1 has zero weight. +x1 = 1:span-1; +v = [ones(length(x1),1) x1(:)]; +if useLoess + v = [v x1(:).^2]; +end +for j=1:halfw + % Compute weights based on deviations from the jth point, + % then compute weights and apply them as above. + d = abs((1:span-1) - j); + weight = (1 - (d/(span-j)).^3).^1.5; + V = v .* repmat(weight(:),1,size(v,2)); + [Q,tmp] = qr(V,0); + alpha = Q(j,:)*Q'; + alpha = alpha .* weight; + ys(j) = alpha * y(1:span-1); + + % These coefficients can be applied to the other end as well + ys(end+1-j) = alpha * y(end:-1:end-span+2); +end + +% ----------------------------------------- +function isuniform = uniformx(diffx,x,y) +%ISUNIFORM True if x is of the form a:b:c + +if any(isnan(y)) || any(isnan(x)) + isuniform = false; +else + isuniform = all(abs(diff(diffx)) <= eps*max(abs([x(1),x(end)]))); +end + + +%------------------------ +function idx = iKNearestNeighbours( k, i, x, in ) +% Find the k points from x(in) closest to x(i) + +if nnz( in ) <= k + % If we have k points or fewer, then return them all + idx = find( in ); +else + % Find the distance to the k closest point + d = abs( x - x(i) ); + ds = sort( d(in) ); + dk = ds(k); + + % Find all points that are as close as or closer than the k closest point + close = (d <= dk); + + % The required indices are those points that are both close and "in" + idx = find( close & in ); +end + +% ----------------------------------------- +% Bi-square (robust) weight function +function delta = iBisquareWeights( r, myeps ) +% Convert residuals to weights using the bi-square weight function. +% NOTE that this function returns the square root of the weights + +% Only use non-NaN residuals to compute median +idx = ~isnan( r ); +% And bound the median away from zero +s = max( 1e8 * myeps, median( abs( r(idx) ) ) ); +% Covert the residuals to weights +delta = iBisquare( r/(6*s) ); +% Everything with NaN residual should have zero weight +delta(~idx) = 0; + +function b = iBisquare( x ) +% This is this bi-square function defined at the top of the left hand +% column of page 831 in [C79] +% NOTE that this function returns the square root of the weights +b = zeros( size( x ) ); +idx = abs( x ) < 1; +b(idx) = abs( 1 - x(idx).^2 ); + + +%------------------------ +% Tri-cubic weight function +function w = iTricubeWeights( d ) +% Convert distances into weights using tri-cubic weight function. +% NOTE that this function returns the square-root of the weights. +% +% Protect against divide-by-zero. This can happen if more points than the span +% are coincident. +maxD = max( d ); +if maxD > 0 + d = d/max( d ); +end +w = (1 - d.^3).^1.5; diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/smooth1D.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/smooth1D.m new file mode 100644 index 0000000..d196687 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/smooth1D.m @@ -0,0 +1,12 @@ +function Z = smooth1D(Y,lambda) + +if size(Y,1)>1 + E = eye(size(Y,1)); + D1 = diff(E,1); + D2 = diff(D1,1); + P = lambda.^2 .* D2'*D2 + 2.*lambda .* D1'*D1; + Z = (E + P) \ Y; +else + Z = Y; +end; + diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Pattern_Analysis.PNG b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Pattern_Analysis.PNG new file mode 100644 index 0000000..b69c87e Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Pattern_Analysis.PNG differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM-FRET.pdf b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM-FRET.pdf new file mode 100644 index 0000000..59f903d Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM-FRET.pdf differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM-FRET.pptx b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM-FRET.pptx new file mode 100644 index 0000000..8e52814 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM-FRET.pptx differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide1.TIF b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide1.TIF new file mode 100644 index 0000000..2e72e93 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide1.TIF differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide2.TIF b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide2.TIF new file mode 100644 index 0000000..7008fc7 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide2.TIF differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide3.TIF b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide3.TIF new file mode 100644 index 0000000..be2e463 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide3.TIF differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide4.TIF b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide4.TIF new file mode 100644 index 0000000..9314cc5 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Spectral-FLIM_instructions Tifs/Slide4.TIF differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Unmixing_done_msg.PNG b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Unmixing_done_msg.PNG new file mode 100644 index 0000000..8fb27f3 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/Unmixing_done_msg.PNG differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/multi-core_unmixing.PNG b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/multi-core_unmixing.PNG new file mode 100644 index 0000000..2b85e22 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/multi-core_unmixing.PNG differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/sFLIM-FLIM-FRET.PNG b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/sFLIM-FLIM-FRET.PNG new file mode 100644 index 0000000..3c01f77 Binary files /dev/null and b/Spectral-FLIM GUI/Spectral-FLIM GUI/spectral-FLIM Software Usage Instructions/sFLIM-FLIM-FRET.PNG differ diff --git a/Spectral-FLIM GUI/Spectral-FLIM GUI/zeiss_ScanRead.m b/Spectral-FLIM GUI/Spectral-FLIM GUI/zeiss_ScanRead.m new file mode 100644 index 0000000..0c34331 --- /dev/null +++ b/Spectral-FLIM GUI/Spectral-FLIM GUI/zeiss_ScanRead.m @@ -0,0 +1,103 @@ +function [head, im_tcspc, im_chan, im_line, im_col] = zeiss_ScanRead(sync, tcspc, channel, special, head) + + +tcspc_bin_resolution = 1e9*head.MeasDesc_Resolution; % in Nanoseconds +sync_rate = ceil(head.MeasDesc_GlobalResolution*1e9); % in Nanoseconds +num_tcspc_channel = max(tcspc)+1; +%num_tcspc_channel = floor(sync_rate/tcspc_bin_resolution)+1; +num_pixel_X = head.ImgHdr_PixX; +num_pixel_Y = head.ImgHdr_PixY; +num_of_detectors = max(channel); + + +% Get Number of Frames +FrameSyncVal = sync(special == 4); +num_of_Frames = size(FrameSyncVal,1); +read_data_range = find(sync == FrameSyncVal(num_of_Frames)); + +% Markers necessary to make FLIM image stack +LineStartMarker = 2^(head.ImgHdr_LineStart-1); +LineStopMarker = 2^(head.ImgHdr_LineStop-1); +FrameMarker = 2^(head.ImgHdr_Frame-1); + +L1 = sync((special == 1)); +L2 = sync((special == 2)); + +% Get pixel dwell time values from header for PicoQuant_FLIMBee or Zeiss_LSM scanner +syncPulsesPerLine = floor(mean(L2(1:100,1)- L1(1:100,1))); + +% Initialize Variable +currentLine = 0; +currentSync = 0; +syncStart = 0; +currentPixel = 0; +countFrame = -1; +insideLine = false; +insideFrame = false; +isPhoton = false; + +im_tcspc = []; +im_chan = []; +im_line = []; +im_col = []; + +% Read each event separately, and build the image matrix as you go +for event = 1:read_data_range + + currentSync = sync(event); + special_event = special(event); + currentChannel = channel(event); + currentTcspc = tcspc(event); + + if special(event) == 0 + isPhoton = true; + else + isPhoton = false; + end + + if ~isPhoton + + if (special_event == FrameMarker) + + insideFrame = true; + countFrame = countFrame + 1; + currentLine = 1; + % + % % NEW ADDITION + % if countFrame == num_of_Frames + % insideFrame = false; + % end + end + + if (special_event == LineStartMarker)% && (insideFrame == true)) + + insideLine = true; + syncStart = currentSync; + + elseif special_event == LineStopMarker + + insideLine = false; + currentLine = currentLine + 1; + syncStart = 0; + if (currentLine > num_pixel_Y) + insideFrame = false; + currentLine = 1; + end + end + end + %update image_data matrix if it's a valid photon + if (isPhoton && insideLine && insideFrame) + + currentPixel = 1 + floor(num_pixel_X*((currentSync - syncStart)/syncPulsesPerLine)); + + if currentPixel <= num_pixel_X + im_tcspc = [im_tcspc; uint16(currentTcspc)]; %#ok + im_chan = [im_chan; uint8(currentChannel)]; %#ok + im_line = [im_line; uint16(currentLine)]; %#ok + im_col = [im_col; uint16(currentPixel)]; %#ok + end + end + + +end % end of looping for all events +end \ No newline at end of file