plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
mehta-lab/Instantaneous-PolScope-master
|
nucleiDetectionProcessGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/nucleiDetectionProcessGUI.m
| 7,045 |
utf_8
|
9739f37fd2f90691d1951528581099cd
|
function varargout = nucleiDetectionProcessGUI(varargin)
% nucleiDetectionProcessGUI M-file for nucleiDetectionProcessGUI.fig
% nucleiDetectionProcessGUI, by itself, creates a new nucleiDetectionProcessGUI or raises the existing
% singleton*.
%
% H = nucleiDetectionProcessGUI returns the handle to a new nucleiDetectionProcessGUI or the handle to
% the existing singleton*.
%
% nucleiDetectionProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in nucleiDetectionProcessGUI.M with the given input arguments.
%
% nucleiDetectionProcessGUI('Property','Value',...) creates a new nucleiDetectionProcessGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before nucleiDetectionProcessGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to nucleiDetectionProcessGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help nucleiDetectionProcessGUI
% Last Modified by GUIDE v2.5 21-Feb-2013 16:58:23
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @nucleiDetectionProcessGUI_OpeningFcn, ...
'gui_OutputFcn', @nucleiDetectionProcessGUI_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 nucleiDetectionProcessGUI is made visible.
function nucleiDetectionProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin)
processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1);
% ---------------------- Channel Setup -------------------------
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
funParams = userData.crtProc.funParams_;
% Set parameters
set(handles.edit_radius, 'String', funParams.radius);
set(handles.checkbox_confluent, 'Value', funParams.confluent);
set(handles.edit_firstFrame, 'String', funParams.firstFrame);
set(handles.edit_lastFrame, 'String', funParams.lastFrame);
set(handles.text_nFrames, 'String', ['(Totally ' num2str(userData.MD.nFrames_) ' frames in the movie)'])
% Update user data and GUI data
handles.output = hObject;
set(hObject, 'UserData', userData);
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = nucleiDetectionProcessGUI_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 pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
% Delete figure
delete(handles.figure1);
% --- Executes on button press in pushbutton_done.
function pushbutton_done_Callback(hObject, eventdata, handles)
% Call back function of 'Apply' button
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
% -------- Check user input --------
if isempty(get(handles.listbox_selectedChannels, 'String'))
errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal')
return;
end
channelIndex = get (handles.listbox_selectedChannels, 'Userdata');
funParams.ChannelIndex = channelIndex;
radius = str2double(get(handles.edit_radius, 'String'));
if isnan(radius) || radius <0
errordlg(['Please provide a valid value for ' get(handles.text_radius,'String')...
'.'],'Setting Error','modal')
return
end
funParams.radius = radius;
funParams.confluent = get(handles.checkbox_confluent, 'Value');
% Read frame range for detection
firstFrame=str2double(get(handles.edit_firstFrame, 'String'));
if isnan(firstFrame) || firstFrame<1 ||round(firstFrame)~=firstFrame
errordlg('Please provide a valid value for the frame range to analyze.','Setting Error','modal')
return
end
funParams.firstFrame=firstFrame;
lastFrame=str2double(get(handles.edit_lastFrame, 'String'));
if isnan(lastFrame) || lastFrame>userData.MD.nFrames_ ||...
lastFrame<firstFrame|| round(lastFrame)~=lastFrame
errordlg('Please provide a valid value for the frame range to analyze.','Setting Error','modal')
return
end
funParams.lastFrame=lastFrame;
if lastFrame == userData.MD.nFrames_
setLastFrame =@(x) parseProcessParams(x, struct('lastFrame',...
x.owner_.nFrames_));
else
setLastFrame =@(x) parseProcessParams(x, struct('lastFrame',...
min(x.funParams_.lastFrame,x.owner_.nFrames_)));
end
processGUI_ApplyFcn(hObject, eventdata, handles,funParams,{setLastFrame});
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
% Notify the package GUI that the setting panel is closed
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
if ishandle(userData.helpFig), delete(userData.helpFig); end
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
% --- Executes on key press with focus on pushbutton_done and none of its controls.
function pushbutton_done_KeyPressFcn(hObject, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(hObject, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
fitGaussians2D.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/fitGaussians2D.m
| 7,593 |
utf_8
|
513d8a065b094059546a78abd0fda5e7
|
% pStruct = fitGaussians2D(img, x, y, A, sigma, c, mode, varargin)
%
% Inputs: img : input image
% x : initial (or fixed) x-positions
% y : initial (or fixed) y-positions
% A : initial (or fixed) amplitudes
% s : initial (or fixed) Gaussian PSF standard deviations
% c : initial (or fixed) background intensities
%
% Options:
% mode : selector for optimization parameters, any of 'xyAsc'. Default: 'xyAc'
%
% Options ('specifier', value):
% 'Mask' : mask of spot locations
% 'ConfRadius' : Confinement radius for valid fits. Default: ceil(2*sigma)
% 'WindowSize' : Size of the support used for the fit, specified as half-width;
% i.e., for a window of 15x15, enter 7. Default: ceil(4*sigma)
%
% Output: pStruct: structure with fields:
% x : estimated x-positions
% y : estimated y-positions
% A : estimated amplitudes
% s : estimated standard deviations of the PSF
% c : estimated background intensities
%
% x_pstd : standard deviations, estimated by error propagation
% y_pstd : "
% A_pstd : "
% s_pstd : "
% c_pstd : "
% sigma_r : standard deviation of the background (residual)
% SE_sigma_r : standard error of sigma_r
% pval_Ar : p-value of an amplitude vs. background noise test (p < 0.05 -> significant amplitude)
%
%
% Usage for a single-channel image with mask and fixed sigma:
% fitGaussians2D(img, x, y, A, sigma, c, 'xyAc', 'mask', mask);
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Francois Aguet, March 28 2011 (last updated: Sep 30 2013)
function pStruct = fitGaussians2D(img, x, y, A, sigma, c, varargin)
% Parse inputs
ip = inputParser;
ip.CaseSensitive = false;
ip.addRequired('img', @isnumeric);
ip.addRequired('x');
ip.addRequired('y');
ip.addRequired('A');
ip.addRequired('sigma');
ip.addRequired('c');
ip.addOptional('mode', 'xyAc', @ischar);
ip.addParamValue('Alpha', 0.05, @isscalar);
ip.addParamValue('AlphaT', 0.05, @isscalar);
ip.addParamValue('Mask', [], @islogical);
ip.addParamValue('ConfRadius', []);
ip.addParamValue('WindowSize', []);
ip.parse(img, x, y, A, sigma, c, varargin{:});
np = length(x);
sigma = ip.Results.sigma;
if numel(sigma)==1
sigma = sigma*ones(1,np);
end
mode = ip.Results.mode;
if ~isempty(ip.Results.Mask)
labels = bwlabel(ip.Results.Mask);
else
labels = zeros(size(img));
end
pStruct = struct('x', [], 'y', [], 'A', [], 's', [], 'c', [],...
'x_pstd', [], 'y_pstd', [], 'A_pstd', [], 's_pstd', [], 'c_pstd', [],...
'x_init', [], 'y_init', [],...
'sigma_r', [], 'SE_sigma_r', [], 'RSS', [], 'pval_Ar', [], 'mask_Ar', [], 'hval_Ar', [], 'hval_AD', []);
xi = round(x);
yi = round(y);
[ny,nx] = size(img);
kLevel = norminv(1-ip.Results.Alpha/2.0, 0, 1); % ~2 std above background
iRange = [min(img(:)) max(img(:))];
estIdx = regexpi('xyAsc', ['[' mode ']']);
% initialize pStruct arrays
pStruct.x = NaN(1,np);
pStruct.y = NaN(1,np);
pStruct.A = NaN(1,np);
pStruct.s = NaN(1,np);
pStruct.c = NaN(1,np);
pStruct.x_pstd = NaN(1,np);
pStruct.y_pstd = NaN(1,np);
pStruct.A_pstd = NaN(1,np);
pStruct.s_pstd = NaN(1,np);
pStruct.c_pstd = NaN(1,np);
pStruct.x_init = reshape(xi, [1 np]);
pStruct.y_init = reshape(yi, [1 np]);
pStruct.sigma_r = NaN(1,np);
pStruct.SE_sigma_r = NaN(1,np);
pStruct.RSS = NaN(1,np);
pStruct.pval_Ar = NaN(1,np);
pStruct.mask_Ar = zeros(1,np);
pStruct.hval_AD = false(1,np);
pStruct.hval_Ar = false(1,np);
sigma_max = max(sigma);
w2 = ip.Results.ConfRadius;
if isempty(w2)
w2 = ceil(2*sigma_max);
end
w4 = ip.Results.WindowSize;
if isempty(w4)
w4 = ceil(4*sigma_max);
end
% for background estimation
if isempty(c)
% mask template: ring with inner radius w3, outer radius w4
[xm,ym] = meshgrid(-w4:w4);
r = sqrt(xm.^2+ym.^2);
annularMask = zeros(size(r));
annularMask(r<=ceil(4*sigma_max) & r>=ceil(3*sigma_max)) = 1;
end
g = exp(-(-w4:w4).^2/(2*sigma_max^2));
g = g'*g;
g = g(:);
T = zeros(1,np);
df2 = zeros(1,np);
for p = 1:np
% ignore points in border
if (xi(p)>w4 && xi(p)<=nx-w4 && yi(p)>w4 && yi(p)<=ny-w4)
% label mask
maskWindow = labels(yi(p)-w4:yi(p)+w4, xi(p)-w4:xi(p)+w4);
maskWindow(maskWindow==maskWindow(w4+1,w4+1)) = 0;
window = img(yi(p)-w4:yi(p)+w4, xi(p)-w4:xi(p)+w4);
% estimate background
if isempty(c)
cmask = annularMask;
cmask(maskWindow~=0) = 0;
c_init = mean(window(cmask==1));
else
c_init = c(p);
end
% set any other components to NaN
window(maskWindow~=0) = NaN;
npx = sum(isfinite(window(:)));
if npx >= 10 % only perform fit if window contains sufficient data points
% fit
if isempty(A)
A_init = max(window(:))-c_init;
else
A_init = A(p);
end
[prm, prmStd, ~, res] = fitGaussian2D(window, [x(p)-xi(p) y(p)-yi(p) A_init sigma(p) c_init], mode);
dx = prm(1);
dy = prm(2);
% exclude points where localization failed
if (dx > -w2 && dx < w2 && dy > -w2 && dy < w2 && prm(3)<2*diff(iRange))
pStruct.x(p) = xi(p) + dx;
pStruct.y(p) = yi(p) + dy;
pStruct.A(p) = prm(3);
pStruct.s(p) = prm(4);
pStruct.c(p) = prm(5);
stdVect = zeros(1,5);
stdVect(estIdx) = prmStd;
pStruct.x_pstd(p) = stdVect(1);
pStruct.y_pstd(p) = stdVect(2);
pStruct.A_pstd(p) = stdVect(3);
pStruct.s_pstd(p) = stdVect(4);
pStruct.c_pstd(p) = stdVect(5);
pStruct.sigma_r(p) = res.std;
pStruct.RSS(p) = res.RSS;
pStruct.SE_sigma_r(p) = res.std/sqrt(2*(npx-1));
SE_sigma_r = pStruct.SE_sigma_r(p) * kLevel;
pStruct.hval_AD(p) = res.hAD;
% H0: A <= k*sigma_r
% H1: A > k*sigma_r
sigma_A = stdVect(3);
A_est = prm(3);
df2(p) = (npx-1) * (sigma_A.^2 + SE_sigma_r.^2).^2 ./ (sigma_A.^4 + SE_sigma_r.^4);
scomb = sqrt((sigma_A.^2 + SE_sigma_r.^2)/npx);
T(p) = (A_est - res.std*kLevel) ./ scomb;
pStruct.mask_Ar(p) = sum(A_est*g>res.std*kLevel);
end
end
end
end
% 1-sided t-test: A_est must be greater than k*sigma_r
pStruct.pval_Ar = tcdf(-T, df2);
pStruct.hval_Ar = pStruct.pval_Ar < ip.Results.AlphaT;
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
plusTipGroupAnalysisGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/plusTipGroupAnalysisGUI.m
| 8,132 |
utf_8
|
40f61ae979266c3cb5c4afed08624583
|
function varargout = plusTipGroupAnalysisGUI(varargin)
% plusTipGroupAnalysisGUI M-file for plusTipGroupAnalysisGUI.fig
% plusTipGroupAnalysisGUI, by itself, creates a new plusTipGroupAnalysisGUI or raises the existing
% singleton*.
%
% H = plusTipGroupAnalysisGUI returns the handle to a new plusTipGroupAnalysisGUI or the handle to
% the existing singleton*.
%
% plusTipGroupAnalysisGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in plusTipGroupAnalysisGUI.M with the given input arguments.
%
% plusTipGroupAnalysisGUI('Property','Value',...) creates a new plusTipGroupAnalysisGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before plusTipGroupAnalysisGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to plusTipGroupAnalysisGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help plusTipGroupAnalysisGUI
% Last Modified by GUIDE v2.5 14-Apr-2014 13:02:10
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @plusTipGroupAnalysisGUI_OpeningFcn, ...
'gui_OutputFcn', @plusTipGroupAnalysisGUI_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 plusTipGroupAnalysisGUI is made visible.
function plusTipGroupAnalysisGUI_OpeningFcn(hObject, eventdata, handles, varargin)
set(handles.text_copyright, 'String', getLCCBCopyright())
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
% Get main figure handle and process id
ip = inputParser;
ip.addParamValue('mainFig', [], @isscalar)
ip.parse(varargin{:});
userData.mainFig = ip.Results.mainFig;
userData.handles_main = guidata(userData.mainFig);
% Get current package and process
userData_main = get(userData.mainFig, 'UserData');
userData.ML = userData_main.ML;
% Get icon infomation
userData.questIconData = userData_main.questIconData;
userData.colormap = userData_main.colormap;
% Set test values
testList = {'t-test of the means';'Wilcoxon ranksum test';'Kolmogorov-Smirnov test (K-S test)';...
'Mean substracted K-S test';'Median substracted K-S test';...
'Permutation t-test of the means';'Calibrated mean subtracted K-S test'};
testValues=[1 2 10 11 12 20 21];
test_handles = [handles.popupmenu_poolData_testID1...
handles.popupmenu_poolData_testID2...
handles.popupmenu_perCell_testID1...
handles.popupmenu_perCell_testID2];
set(test_handles, 'String', testList, 'UserData', testValues);
set(handles.popupmenu_poolData_testID1, 'Value', 6);
set(handles.popupmenu_poolData_testID2, 'Value', 7);
set(handles.popupmenu_perCell_testID1, 'Value', 1);
set(handles.popupmenu_perCell_testID2, 'Value', 6);
handles.output = hObject;
set(hObject, 'UserData', userData);
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = plusTipGroupAnalysisGUI_OutputFcn(~, ~, 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;
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
if isempty(userData.ML)
warndlg('At least one movie list is required to perform group analysis.',...
'Input error', 'modal');
close(handles.figure1);
return
end
% --- Executes on button press in pushbutton_cancel.
function pushbutton_cancel_Callback(~, ~, handles)
% Delete figure
delete(handles.figure1);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, ~, handles)
% Notify the package GUI that the setting panel is closed
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
if isfield(userData, 'helpFig') && ishandle(userData.helpFig)
delete(userData.helpFig)
end
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
% --- Executes on button press in pushbutton_run.
function pushbutton_run_Callback(hObject, eventdata, handles)
userData = get(handles.figure1,'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
% Load group data
remBegEnd = get(handles.checkbox_remBegEnd,'Value');
disp('Extracting group data');
userData.groupData = plusTipExtractGroupData(userData.ML, remBegEnd);
% Read common value for statistical tests
alpha =str2double(get(handles.edit_alpha, 'String'));
testValues = get(handles.popupmenu_poolData_testID1,'UserData');
% Run within group comparison
if get(handles.checkbox_doWtn,'Value')
disp('Running within group comparison');
for i = 1 : numel(userData.ML)
fprintf(1, 'Movie %g/%g\n', i, numel(userData.ML));
outputDir = fullfile(userData.ML(i).outputDirectory_,...
'withinGroupComparison');
plusTipWithinGroupComparison(userData.groupData, i, outputDir, 1);
end
end
% Run per-cell group analysis
if numel(userData.ML) > 1 && get(handles.checkbox_poolData,'Value')
disp('Running pooled data analysis');
outputDir = fullfile(userData.ML(1).outputDirectory_, 'pooledData');
plusTipPoolGroupData(userData.groupData, outputDir, 0, 1);
% Perform statistical tests if more than one list is passed
testID1 = testValues(get(handles.popupmenu_poolData_testID1,'Value'));
testID2 = testValues(get(handles.popupmenu_poolData_testID2,'Value'));
plusTipTestDistrib(userData.groupData, outputDir,...
alpha, testID1, testID2);
end
% Run pooled group analysis
if get(handles.checkbox_perCell,'Value')
disp('Running per cell analysis');
outputDir = fullfile(userData.ML(1).outputDirectory_, 'perCell');
testID1 = testValues(get(handles.popupmenu_perCell_testID1,'Value'));
testID2 = testValues(get(handles.popupmenu_perCell_testID2,'Value'));
plusTipGetHits(userData.groupData, outputDir, alpha, testID1, testID2);
end
arrayfun(@save, userData.ML)
% --- Executes on button press in checkbox_poolData.
function checkbox_poolData_Callback(hObject, eventdata, handles)
if get(hObject, 'Value')
set(get(handles.uipanel_poolData, 'Children'), 'Enable', 'on');
else
set(get(handles.uipanel_poolData, 'Children'), 'Enable', 'off');
end
% --- Executes on button press in checkbox_perCell.
function checkbox_perCell_Callback(hObject, eventdata, handles)
if get(hObject, 'Value')
set(get(handles.uipanel_perCell, 'Children'), 'Enable', 'on');
else
set(get(handles.uipanel_perCell, 'Children'), 'Enable', 'off');
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
userfcn_checkAllMovies.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/userfcn_checkAllMovies.m
| 2,874 |
utf_8
|
a98e78bc49340218e28cbdcf47bf4341
|
function userfcn_checkAllMovies(procID, value, handles)
if get(handles.checkbox_all, 'Value')
userData = get(handles.figure1, 'UserData');
for x = setdiff(1:length(userData.MD), userData.id)
% Recalls the userData that may have been updated by the
% checkAllMovies function
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
userData=get(handles.figure1, 'UserData');
userData.statusM(x).Checked(procID) = value;
set(handles.figure1, 'UserData', userData)
dfs_checkAllMovies(procID, value, handles, x)
end
end
function dfs_checkAllMovies(procID, value, handles, x)
userData = get(handles.figure1, 'UserData');
M = userData.dependM;
if value % If check
parentI = find(M(procID, :)==1);
parentI = parentI(:)';
if isempty(parentI)
return
else
for i = parentI
if userData.statusM(x).Checked(i) || ...
(~isempty(userData.package(x).processes_{i}) && ...
userData.package(x).processes_{i}.success_ )
continue
else
userData.statusM(x).Checked(i) = 1;
set(handles.figure1, 'UserData', userData)
dfs_checkAllMovies(i, value, handles, x)
end
end
end
else % If uncheck
childProcesses = find(M(:,procID));
childProcesses = childProcesses(:)';
if isempty(childProcesses) || ...
(~isempty(userData.package(x).processes_{procID}) ...
&& userData.package(x).processes_{procID}.success_)
return;
else
for i = childProcesses
if userData.statusM(x).Checked(i)
userData.statusM(x).Checked(i) = 0;
set(handles.figure1, 'UserData', userData)
dfs_checkAllMovies(i, value, handles, x)
end
end
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
movieSelectorGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/movieSelectorGUI.m
| 21,130 |
utf_8
|
d0588976a362aa866f6160327e354d6b
|
function varargout = movieSelectorGUI(varargin)
% MOVIESELECTORGUI M-file for movieSelectorGUI.fig
% MOVIESELECTORGUI, by itself, creates a new MOVIESELECTORGUI or raises the existing
% singleton*.
%
% H = MOVIESELECTORGUI returns the handle to a new MOVIESELECTORGUI or the handle to
% the existing singleton*.
%
% MOVIESELECTORGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MOVIESELECTORGUI.M with the given input arguments.
%
% MOVIESELECTORGUI('Property','Value',...) creates a new MOVIESELECTORGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before movieSelectorGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to movieSelectorGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help movieSelectorGUI
% Last Modified by GUIDE v2.5 21-Oct-2014 12:46:50
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @movieSelectorGUI_OpeningFcn, ...
'gui_OutputFcn', @movieSelectorGUI_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 movieSelectorGUI is made visible.
function movieSelectorGUI_OpeningFcn(hObject, eventdata, handles, varargin)
%
% Useful tools:
%
% User Data:
%
% userData.MD - new or loaded MovieData object
% userData.ML - newly saved or loaded MovieList object
%
% userData.userDir - default open directory
% userData.colormap - color map (used for )
% userData.questIconData - image data of question icon
%
% userData.packageGUI - the name of package GUI
%
% userData.newFig - handle of new movie set-up GUI
% userData.iconHelpFig - handle of help dialog
% userData.msgboxGUI - handle of message box GUI
ip = inputParser;
ip.addRequired('hObject',@ishandle);
ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x));
ip.addRequired('handles',@isstruct);
ip.addParamValue('packageName','',@ischar);
ip.addParamValue('MD', MovieData.empty(1,0) ,@(x) isempty(x) || isa(x,'MovieData'));
ip.addParamValue('ML', MovieList.empty(1,0), @(x) isempty(x) || isa(x,'MovieList'));
ip.parse(hObject,eventdata,handles,varargin{:});
set(handles.text_copyright, 'String', getLCCBCopyright())
userData = get(handles.figure1, 'UserData');
if isempty(userData), userData = struct(); end
% Choose default command line output for setupMovieDataGUI
handles.output = hObject;
% other user data set-up
userData.MD = MovieData.empty(1,0);
userData.ML = MovieList.empty(1,0);
userData.userDir = pwd;
userData.newFig=-1;
userData.msgboxGUI=-1;
userData.iconHelpFig =-1;
userData.omeroLoginFig = -1;
userData.omeroDataFig = -1;
% Load help icon from dialogicons.mat
userData = loadLCCBIcons(userData);
% Get concrete packages
packageList = getPackageList();
if isempty(packageList),
warndlg('No package found! Please make sure you properly added the installation directory to the path (see user''s manual).',...
'Movie Selector','modal');
end
packageNames = cellfun(@(x) eval([x '.getName']),packageList,'Unif',0);
[packageNames,index]=sort(packageNames);
packageList=packageList(index);
% Create radio controls for packages
nPackages=numel(packageList);
pos = get(handles.uipanel_packages,'Position');
for i=1:nPackages
uicontrol(handles.uipanel_packages,'Style','radio',...
'Position',[30 pos(4)-20-30*i pos(3)-35 20],'Tag',['radiobutton_package' num2str(i)],...
'String',[' ' packageNames{i}],'UserData',packageList{i},...
'Value',strcmp(packageList{i},ip.Results.packageName))
axes_handle = axes('Units','pixels',...
'Position',[10 pos(4)-20-30*i 20 20],'Tag',['axes_help_package' num2str(i)],...
'Parent',handles.uipanel_packages);
Img = image(userData.questIconData, 'UserData', struct('class', packageList{i}),...
'Parent', axes_handle);
set(axes_handle, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'), 'Visible','off');
set(Img,'ButtonDownFcn',@icon_ButtonDownFcn);
end
set(handles.uipanel_packages,'SelectionChangeFcn','');
% Populate movie list to analyze
if ~isempty(ip.Results.ML)
userData.ML=ip.Results.ML;
% Populate movies with the movie list components if no MD is passed
if isempty(ip.Results.MD)
MD = arrayfun(@(x) horzcat(x.getMovies{:}),userData.ML,'Unif',0);
userData.MD = horzcat(MD{:});
else
userData.MD = MovieData.empty(1,0);
end
end
% Populate movies to analyze
if ~isempty(ip.Results.MD)
userData.MD = horzcat(userData.MD,ip.Results.MD);
end
% Filter movies to get a unique list
[~,index] = unique(arrayfun(@getFullPath,userData.MD,'Unif',0));
userData.MD = userData.MD(sort(index));
% Filter movie lists to get a unique list
[~,index] = unique(arrayfun(@getFullPath,userData.ML,'Unif',0));
userData.ML = userData.ML(sort(index));
supermap(1,:) = get(hObject,'color');
userData.colormap = supermap;
set(handles.figure1,'CurrentAxes',handles.axes_help);
Img = image(userData.questIconData);
set(hObject,'colormap',supermap);
set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),...
'visible','off');
set(Img,'ButtonDownFcn',@icon_ButtonDownFcn,'UserData', struct('class',mfilename));
set(handles.figure1,'UserData',userData);
refreshDisplay(hObject,eventdata,handles);
% Save userdata
guidata(hObject, handles);
function packageList = getPackageList()
packageList = {'BiosensorsPackage';...
'FocalAdhesionPackage'
'FocalAdhesionSegmentationPackage'
'IntegratorPackage'
'QFSMPackage'
'SegmentationPackage'
'TFMPackage'
'TrackingPackage'
'ParkinTranslocationScoringPackage'
'WindowingPackage'
'ColocalizationPackage'
'FilamentAnalysisPackage'
'ScoreGemPackage'};
validPackage = cellfun(@(x) exist(x,'class')==8,packageList);
packageList = packageList(validPackage);
% --- Outputs from this function are returned to the command line.
function varargout = movieSelectorGUI_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 pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
delete(handles.figure1)
% --- Executes on button press in pushbutton_done.
function pushbutton_done_Callback(hObject, eventdata, handles)
% Check a package is selected
if isempty(get(handles.uipanel_packages, 'SelectedObject'))
warndlg('Please select a package to continue.', 'Movie Selector', 'modal')
return
end
% Retrieve the ID of the selected button and call the appropriate
userData = get(handles.figure1, 'UserData');
selectedPackage=get(get(handles.uipanel_packages, 'SelectedObject'),'UserData');
% Select movie or list depending on the package nature
class = eval([selectedPackage '.getMovieClass()']);
if strcmp(class, 'MovieList')
type = 'movie list';
field = 'ML';
else
type = 'movie';
field = 'MD';
end
if isempty(userData.(field))
warndlg(['Please load at least one ' type ' to continue.'], 'Movie Selector', 'modal')
return
end
close(handles.figure1);
packageGUI(selectedPackage,userData.(field),...
'MD', userData.MD, 'ML', userData.ML);
% --- Executes on selection change in listbox_movie.
function listbox_movie_Callback(hObject, eventdata, handles)
refreshDisplay(hObject, eventdata, handles)
% --- Executes on button press in pushbutton_new.
function pushbutton_new_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
% if movieDataGUI exist, delete it
if ishandle(userData.newFig), delete(userData.newFig); end
userData.newFig = movieDataGUI('mainFig',handles.figure1);
set(handles.figure1,'UserData',userData);
% --- Executes on button press in pushbutton_prepare.
function pushbutton_prepare_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
% if preparation GUI exist, delete it
if ishandle(userData.newFig), delete(userData.newFig); end
userData.newFig = dataPreparationGUI('mainFig',handles.figure1);
set(handles.figure1,'UserData',userData);
% --- Executes on button press in pushbutton_delete.
function pushbutton_delete_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'Userdata');
if isempty(userData.MD), return;end
% Delete channel object
num = get(handles.listbox_movie,'Value');
removedMovie=userData.MD(num);
userData.MD(num) = [];
% Test if movie does not share common ancestor
checkCommonAncestor= arrayfun(@(x) any(isequal(removedMovie.getAncestor,x.getAncestor)),userData.MD);
if ~any(checkCommonAncestor), delete(removedMovie); end
% Refresh listbox_channel
set(handles.figure1, 'Userdata', userData)
refreshDisplay(hObject,eventdata,handles);
guidata(hObject, handles);
% --- Executes on button press in pushbutton_detail.
function pushbutton_detail_Callback(hObject, eventdata, handles)
% Return if no movie
props=get(handles.listbox_movie, {'String','Value'});
if isempty(props{1}), return; end
userData = get(handles.figure1, 'UserData');
% if movieDataGUI exist, delete it
userData.newFig = movieDataGUI(userData.MD(props{2}));
set(handles.figure1,'UserData',userData);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if ishandle(userData.newFig), delete(userData.newFig); end
if ishandle(userData.iconHelpFig), delete(userData.iconHelpFig); end
if ishandle(userData.msgboxGUI), delete(userData.msgboxGUI); end
if ishandle(userData.omeroLoginFig), delete(userData.omeroLoginFig); end
if ishandle(userData.omeroDataFig), delete(userData.omeroDataFig); end
% --- Executes on button press in pushbutton_open.
function pushbutton_open_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
filespec = {'*.mat','MATLAB Files'};
[filename, pathname] = uigetfile(filespec,'Select a movie to load', ...
userData.userDir);
if ~any([filename pathname]), return; end
userData.userDir = pathname;
% Check if reselect the movie data that is already in the listbox
moviePaths = get(handles.listbox_movie, 'String');
if any(strcmp([pathname filename], moviePaths))
errordlg('This movie has already been selected.','Error','modal');
return
end
try
MD = MovieData.load([pathname filename]);
userData.MD = horzcat(userData.MD, MD);
catch ME
msg = sprintf('Movie: %s\n\nError: %s\n\nMovie is not successfully loaded. Please refer to movie detail and adjust your data.', [pathname filename],ME.message);
errordlg(msg, 'Movie error','modal');
return
end
% Refresh movie box in movie selector panel
set(handles.figure1, 'UserData', userData);
refreshDisplay(hObject,eventdata,handles);
% --- Executes on button press in pushbutton_openlist.
function pushbutton_openlist_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
filespec = {'*.mat','MATLAB Files'};
[filename, pathname] = uigetfile(filespec,'Select a movie list to load', ...
userData.userDir);
if ~any([filename pathname]), return; end
userData.userDir = pathname;
% Check if reselect the movie list that is already in the listbox
movieListPaths = get(handles.listbox_movieList, 'String');
if any(strcmp([pathname filename], movieListPaths))
errordlg('This movie list has already been opened.','Error','modal');
return
end
try
ML = MovieList.load([pathname filename]);
catch ME
msg = sprintf('Movie: %s\n\nError: %s\n\nMovie is not successfully loaded. Please refer to movie detail and adjust your data.', [pathname filename],ME.message);
errordlg(msg, 'Movie error','modal');
return
end
% Find duplicate movie data in list box
movieDataFile = ML.movieDataFile_;
index = 1: length(movieDataFile);
movieList=get(handles.listbox_movie,'String');
index = index(~ismember(movieDataFile,movieList));
if isempty(index)
msg = sprintf('All movies in movie list file %s have already been added to the list of movies.', ML.movieListFileName_);
warndlg(msg,'Warning','modal');
end
% Healthy movie list
userData.ML = horzcat(userData.ML, ML);
userData.MD = horzcat(userData.MD,ML.getMovies{index});
% Refresh movie list box in movie selector panel
set(handles.figure1, 'UserData', userData);
refreshDisplay(hObject,eventdata,handles);
function menu_about_Callback(hObject, eventdata, handles)
status = web(get(hObject,'UserData'), '-browser');
if status
switch status
case 1
msg = 'System default web browser is not found.';
case 2
msg = 'System default web browser is found but could not be launched.';
otherwise
msg = 'Fail to open browser for unknown reason.';
end
warndlg(msg,'Fail to open browser','modal');
end
% --------------------------------------------------------------------
function menu_file_quit_Callback(hObject, eventdata, handles)
delete(handles.figure1)
% --- Executes on button press in pushbutton_deleteall.
function pushbutton_deleteall_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'Userdata');
contentlist = get(handles.listbox_movie,'String');
% Return if list is empty
if isempty(contentlist), return; end
% Confirm deletion
user_response = questdlg(['Are you sure to delete all the '...
'movies and movie lists?'], ...
'Movie Listbox', 'Yes','No','Yes');
if strcmpi('no', user_response), return; end
% Delete movies and movie lists
userData.MD = MovieData.empty(1,0);
userData.ML = MovieList.empty(1,0);
set(handles.figure1, 'Userdata', userData)
refreshDisplay(hObject, eventdata, handles)
guidata(hObject, handles);
% --- Executes on button press in pushbutton_save.
function pushbutton_save_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if isempty(userData.MD)
warndlg('No movie selected. Please create new movie data or open existing movie data or movie list.', 'No Movie Selected', 'modal')
return
end
if isempty(userData.ML)
movieListPath = [userData.userDir filesep];
movieListFileName = 'movieList.mat';
else
movieListPath = userData.ML(end).movieListPath_;
movieListFileName = userData.ML(end).movieListFileName_;
end
% Ask user where to save the movie data file
[filename,path] = uiputfile('*.mat','Find a place to save your movie list',...
[movieListPath filesep movieListFileName]);
if ~any([filename,path]), return; end
listPaths = arrayfun(@getFullPath,userData.ML,'Unif',false);
if any(strcmp([path filename], listPaths))
user_response = questdlg(['Are you sure to want to overwrite the list '...
'with the current selection of movies? All analysis performed at the '...
'list level will be lost.'], ...
'Movie Listbox', 'Yes','No','Yes');
if strcmpi('no', user_response), return; end
iList = strcmp([path filename], listPaths);
outputDir = userData.ML(iList).outputDirectory_;
delete(userData.ML(iList));
userData.ML(iList) = [];
else
% Ask user where to select the output directory of the
outputDir = uigetdir(path,'Select a directory to store the list analysis output');
if isequal(outputDir,0), return; end
end
try
ML = MovieList(userData.MD, outputDir);
ML.setPath(path);
ML.setFilename(filename);
ML.sanityCheck;
catch ME
msg = sprintf('%s\n\nMovie list is not saved.', ME.message);
errordlg(msg, 'Movie List Error', 'modal')
return
end
userData.ML = horzcat(userData.ML, ML);
set(handles.figure1,'UserData',userData);
refreshDisplay(hObject, eventdata, handles)
% --------------------------------------------------------------------
function menu_tools_crop_Callback(hObject, eventdata, handles)
% Return if no movie
props=get(handles.listbox_movie, {'String','Value'});
if isempty(props{1}), return; end
userData = get(handles.figure1, 'UserData');
if ishandle(userData.newFig), delete(userData.newFig); end
userData.newFig = cropMovieGUI(userData.MD(props{2}),'mainFig',handles.figure1);
set(handles.figure1,'UserData',userData);
% --------------------------------------------------------------------
function menu_tools_addROI_Callback(hObject, eventdata, handles)
% Return if no movie
props=get(handles.listbox_movie, {'String','Value'});
if isempty(props{1}), return; end
userData = get(handles.figure1, 'UserData');
if ishandle(userData.newFig), delete(userData.newFig); end
userData.newFig = addMovieROIGUI(userData.MD(props{2}),'mainFig',handles.figure1);
set(handles.figure1,'UserData',userData);
% --- Executes on selection change in listbox_movie.
function refreshDisplay(hObject, eventdata, handles)
userData = get(handles.figure1,'UserData');
% Display Movie information
moviePaths = arrayfun(@getFullPath,userData.MD,'Unif',false);
nMovies= numel(userData.MD);
iMovie = get(handles.listbox_movie, 'Value');
if isempty(userData.MD),
iMovie=0;
else
iMovie=max(1,min(iMovie,nMovies));
end
set(handles.listbox_movie,'String',moviePaths,'Value',iMovie);
set(handles.text_movies, 'String', sprintf('%g/%g movie(s)',iMovie,nMovies))
% Display list information
listPaths = arrayfun(@getFullPath,userData.ML,'Unif',false);
nLists= numel(userData.ML);
iList = get(handles.listbox_movieList, 'Value');
if isempty(userData.ML),
iList=0;
else
iList=max(1,min(iList,nLists));
end
set(handles.listbox_movieList,'String',listPaths);
set(handles.text_movieList, 'String', sprintf('%g/%g movie list(s)',iList,nLists))
% --- Executes on button press in pushbutton_deletelist.
function pushbutton_deletelist_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'Userdata');
if isempty(userData.MD), return;end
% Delete channel object
iList = get(handles.listbox_movieList,'Value');
delete(userData.ML(iList));
userData.ML(iList) = [];
% Refresh listbox_channel
set(handles.figure1, 'Userdata', userData)
refreshDisplay(hObject,eventdata,handles);
guidata(hObject, handles);
% --------------------------------------------------------------------
function menu_omero_login_Callback(hObject, eventdata, handles)
% Ensure loadOmero is in the path
if isempty(which('loadOmero')),
errordlg(sprintf(['No OMERO.matlab toolbox found in the path.\n'...
'Please download the OMERO.matlab toolbox matching your '...
'your OMERO server.']),'Error','modal');
return
end
% Make sure OMERO is in the MATLAB and Java class path
loadOmero();
% Call the login interface
userData = get(handles.figure1, 'UserData');
userData.omeroLoginFig = omeroLoginGUI();
set(handles.figure1, 'UserData', userData);
% --------------------------------------------------------------------
function menu_omero_load_Callback(hObject, eventdata, handles)
global session
if isempty(session)
errordlg('Please log in to the OMERO server first.',...
'No session found', 'modal');
return
end
try
ctx = session.getAdminService().getEventContext();
catch ME
errordlg('OMERO connection lost or not initialized.',...
'Connection error', 'modal');
return
end
% Call the data selection interface
userData = get(handles.figure1, 'UserData');
userData.omeroDataFig = omeroDataSelectionGUI('mainFig',handles.figure1);
set(handles.figure1, 'UserData', userData);
function View_Callback(hObject, eventdata, handles)
% Return if no movie
props=get(handles.listbox_movie, {'String','Value'});
if isempty(props{1}), return; end
userData = get(handles.figure1, 'UserData');
movieViewer(userData.MD(props{2}));
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
omeroLoginGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/omeroLoginGUI.m
| 9,632 |
utf_8
|
c690ef742750cb9158a55665c3a013d0
|
function varargout = omeroLoginGUI(varargin)
% OMEROLOGINGUI MATLAB code for omeroLoginGUI.fig
% OMEROLOGINGUI, by itself, creates a new OMEROLOGINGUI or raises the existing
% singleton*.
%
% H = OMEROLOGINGUI returns the handle to a new OMEROLOGINGUI or the handle to
% the existing singleton*.
%
% OMEROLOGINGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in OMEROLOGINGUI.M with the given input arguments.
%
% OMEROLOGINGUI('Property','Value',...) creates a new OMEROLOGINGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before omeroLoginGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to omeroLoginGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help omeroLoginGUI
% Last Modified by GUIDE v2.5 31-Oct-2013 20:21:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @omeroLoginGUI_OpeningFcn, ...
'gui_OutputFcn', @omeroLoginGUI_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 omeroLoginGUI is made visible.
function omeroLoginGUI_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 omeroLoginGUI (see VARARGIN)
set(handles.text_copyright, 'String', getLCCBCopyright())
update_status(handles)
% Choose default command line output for omeroLoginGUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes omeroLoginGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = omeroLoginGUI_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 key press with focus on edit_password and none of its controls.
function edit_password_KeyPressFcn(hObject, eventdata, handles)
password = get(hObject, 'UserData');
key = eventdata.Key;
switch key
case 'backspace'
password = password(1:end-1); % Delete the last character in the password
case 'return' % This cannot be done through callback without making tab to the same thing
% do nothing
case 'shift'
% do nothing
otherwise
password = [password eventdata.Character];
end
asterisk = password;
asterisk(1:end) = '*'; % Create a string of asterisks the same size as the password
set(hObject, 'String', asterisk,'UserData', password);
guidata(hObject,handles);
% --- Executes on button press in pushbutton_login.
function pushbutton_login_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_login (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
server = get(handles.edit_server, 'String');
if isempty(server),
errordlg('Please enter a valid server name', 'Server error', 'modal');
return;
end
port = get(handles.edit_port, 'String');
if isempty(port) || isnan(str2double(port)),
errordlg('Please enter a valid port', 'Port error', 'modal');
return;
end
username = get(handles.edit_username, 'String');
if isempty(username),
errordlg('Please enter a valid username', 'Username error', 'modal');
return;
end
password = get(handles.edit_password, 'UserData');
if isempty(password),
errordlg('Please enter a valid password', 'Password error', 'modal');
return;
end
% Create properties object to initialize the connection
properties = java.util.Properties();
properties.setProperty('omero.host', server);
properties.setProperty('omero.user', username);
properties.setProperty('omero.pass', password);
properties.setProperty('omero.port', port);
properties.setProperty('omero.keep_alive', '60');
connect(handles, properties);
% --- Executes on button press in pushbutton_login_file.
function pushbutton_login_file_Callback(hObject, eventdata, handles)
[file, path] = uigetfile('*.config',...
'Select the configuration file to use to log in to the OMERO server');
if isequal(path, 0), return; end
connect(handles, [path file]);
function connect(handles, varargin)
global client
global session
try
[client, session] = connectOmero(varargin{:});
update_status(handles);
catch ME
if isa(ME.ExceptionObject, 'Ice.ConnectionRefusedException')
status = 'connection refused';
elseif isa(ME.ExceptionObject, 'Glacier2.PermissionDeniedException');
status = 'password check failed';
elseif isa(ME.ExceptionObject, 'Ice.DNSException');
status = 'server name could not be resolved';
else
status = ME.message;
end
set(handles.text_status, 'String', sprintf('Status: %s', status));
end
function update_status(handles)
global client
global session
if ~isempty(session)
try
% Retrieve server name
adminService = session.getAdminService();
servername = char(client.getProperty('omero.host'));
set(handles.edit_server, 'String', servername)
% Read username and group name
userName = char(adminService.getEventContext().userName);
groupName = char(adminService.getEventContext().groupName);
set(handles.edit_username, 'String', userName);
% Read group ID and retrieve experimenter
userId = adminService.getEventContext().userId;
groupId = adminService.getEventContext().groupId;
user = adminService.getExperimenter(userId);
% Populate drop-down menu for available groups
groupIds = toMatlabList(adminService.getMemberOfGroupIds(user));
systemGroupId = adminService.getSecurityRoles().systemGroupId;
userGroupId = adminService.getSecurityRoles().userGroupId;
try
guestGroupId = adminService.getSecurityRoles().guestGroupId;
catch
guestGroupId = -1;
end
% Filter out system groups
groupIds(ismember(groupIds,...
[systemGroupId userGroupId guestGroupId])) = [];
groupNames = arrayfun(@(x) char(adminService.getGroup(x).getName().getValue),...
groupIds, 'UniformOutput', false);
set(handles.popupmenu_group, 'String', groupNames, 'UserData', groupIds,...
'Value', find(groupId == groupIds));
% Update status
status = sprintf('connected as %s under group %s', userName, groupName);
connected = 1;
catch ME
if isa(ME.ExceptionObject, 'Ice.CommunicatorDestroyedException')
status = 'lost connection';
else
status = ME.message;
end
connected = 0;
end
else
status = 'not connected';
connected = 0;
end
set(handles.text_status, 'String', sprintf('Status: %s', status));
if connected
set([handles.pushbutton_login, handles.pushbutton_login_file],...
'Enable', 'off');
set([handles.pushbutton_logout handles.popupmenu_group],...
'Enable', 'on');
else
set([handles.pushbutton_login, handles.pushbutton_login_file],...
'Enable', 'on');
set([handles.pushbutton_logout handles.popupmenu_group],...
'Enable', 'off');
end
% --- Executes on button press in pushbutton_logout.
function pushbutton_logout_Callback(hObject, eventdata, handles)
global client
if ~isempty(client), client.closeSession(); end
update_status(handles)
% --- Executes on selection change in popupmenu_group.
function popupmenu_group_Callback(hObject, eventdata, handles)
global session
props = get(handles.popupmenu_group, {'UserData', 'Value'});
groupId = props{1}(props{2});
session.setSecurityContext(session.getAdminService().getGroup(groupId));
update_status(handles)
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
rotateXTickLabels.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/rotateXTickLabels.m
| 3,735 |
utf_8
|
4cb3ba94d05825020b320669d2b73f77
|
%ROTATEXTICKLABELS rotates the labels on the x-axis
%
% INPUTS: ha : axis handle of the plot to be modified
% 'Angle' : rotation in degrees. Default: 45
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Francois Aguet, 22 Feb 2011
% Last modified: 08/15/2012
function ht = rotateXTickLabels(varargin)
ip = inputParser;
ip.CaseSensitive = false;
ip.addOptional('ha', gca, @ishandle);
ip.addParamValue('Angle', 45, @(x) isscalar(x) && (0<=x && x<=90));
ip.addParamValue('Interpreter', 'tex', @(x) any(strcmpi(x, {'tex', 'latex', 'none'})));
ip.addParamValue('AdjustFigure', true, @islogical);
ip.parse(varargin{:});
ha = ip.Results.ha;
xa = get(ha, 'XTick');
xla = get(ha, 'XTickLabel');
if ischar(xla) % label is numerical
xla = arrayfun(@(i) num2str(str2double(xla(i,:))), 1:size(xla,1), 'UniformOutput', false);
end
axPos = get(ha, 'Position');
set(ha, 'XTickLabel', [], 'Position', axPos);
fontName = get(get(ha, 'ylabel'), 'FontName');
fontSize = get(get(ha, 'ylabel'), 'FontSize');
XLim = get(ha, 'XLim');
YLim = get(ha, 'Ylim');
width = diff(XLim);
height = diff(YLim);
% get height of default text bounding box
h = text(0, 0, ' ', 'FontName', fontName, 'FontSize', fontSize, 'Parent', ha);
extent = get(h, 'extent');
shift = extent(4)/height*width/axPos(3)*axPos(4) * sin(ip.Results.Angle*pi/180)/4;
height0 = extent(4);
delete(h);
% shift
tl = get(ha, 'TickLength');
ht = arrayfun(@(k) text(xa(k)-shift, YLim(1)-2*tl(1)*height, xla{k},...
'FontName', fontName, 'FontSize', fontSize,...
'VerticalAlignment', 'top', 'HorizontalAlignment', 'right',...
'Rotation', ip.Results.Angle, 'Interpreter', ip.Results.Interpreter, 'Parent', ha),...
1:length(xa));
% largest extent (relative to axes units)
extents = arrayfun(@(k) get(k, 'extent'), ht, 'UniformOutput', false);
extents = vertcat(extents{:});
maxHeight = max(extents(:,4));
lmargin = -min(extents(:,1))/width * axPos(3); % normalized units in fig. frame
hx = get(ha, 'XLabel');
xlheight = get(hx, 'Extent');
xlheight = xlheight(4);
if xlheight==0 % add default space for label: 1.5*height of labels
xlheight = height0;
end
bmargin = (maxHeight+xlheight)/height * axPos(4); % data units -> normalized
if ip.Results.AdjustFigure
hfig = get(ha, 'Parent');
fpos = get(hfig, 'Position');
% expand figure window
if lmargin > axPos(1)
fpos(3) = fpos(3) + lmargin-axPos(1);
axPos(1) = lmargin;
end
switch get(ha, 'Units')
case 'normalized'
cf = 1-axPos(2) + bmargin;
axPos(4) = axPos(4) / cf;
fpos(4) = fpos(4) * cf;
axPos(2) = bmargin / cf;
otherwise % assumes units are the same for figure and axes
% extend figure, add bottom offest
fpos(4) = fpos(4) - axPos(2) + bmargin;
axPos(2) = bmargin;
end
set(hfig, 'Position', fpos, 'PaperPositionMode', 'auto');
set(ha, 'Position', axPos);
end
% shift x-label
xPos = get(hx, 'Position');
xPos(2) = YLim(1)-maxHeight;
set(hx, 'Position', xPos, 'VerticalAlignment', 'middle');
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
costMatRandomDirectedSwitchingMotionLinkGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/costMatRandomDirectedSwitchingMotionLinkGUI.m
| 10,941 |
utf_8
|
5508ccd4d85addedfb517fcd5b4e97d5
|
function varargout = costMatRandomDirectedSwitchingMotionLinkGUI(varargin)
% COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI M-file for costMatRandomDirectedSwitchingMotionLinkGUI.fig
% COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI, by itself, creates a new COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI or raises the existing
% singleton*.
%
% H = COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI returns the handle to a new COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI or the handle to
% the existing singleton*.
%
% COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI.M with the given input arguments.
%
% COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI('Property','Value',...) creates a new COSTMATRANDOMDIRECTEDSWITCHINGMOTIONLINKGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before costMatRandomDirectedSwitchingMotionLinkGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to costMatRandomDirectedSwitchingMotionLinkGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help costMatRandomDirectedSwitchingMotionLinkGUI
% Last Modified by GUIDE v2.5 09-Dec-2011 16:19:54
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @costMatRandomDirectedSwitchingMotionLinkGUI_OpeningFcn, ...
'gui_OutputFcn', @costMatRandomDirectedSwitchingMotionLinkGUI_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 costMatRandomDirectedSwitchingMotionLinkGUI is made visible.
function costMatRandomDirectedSwitchingMotionLinkGUI_OpeningFcn(hObject, eventdata, handles, varargin)
costMat_OpeningFcn(hObject, eventdata, handles, varargin{:})
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
parameters = userData.parameters;
% Parameter Setup
set(handles.checkbox_linearMotion, 'Value', logical(parameters.linearMotion));
checkbox_linearMotion_Callback(hObject, eventdata, handles)
set(handles.checkbox_immediateDirectionReversal, 'Value', parameters.linearMotion==2);
set(handles.edit_lower, 'String', num2str(parameters.minSearchRadius))
set(handles.edit_upper, 'String', num2str(parameters.maxSearchRadius))
set(handles.edit_brownStdMult, 'String', num2str(parameters.brownStdMult))
set(handles.checkbox_useLocalDensity, 'Value', parameters.useLocalDensity)
set(handles.edit_nnWindow, 'String', num2str(parameters.nnWindow))
if isempty(parameters.diagnostics) || (length(parameters.diagnostics) == 1 && parameters.diagnostics == 0)
set(handles.checkbox_diagnostics, 'Value', 0);
set(get(handles.uipanel_diagnostics,'Children'),'Enable','off');
else
set(handles.checkbox_diagnostics, 'Value', 1);
for i = 1:min(3,length(parameters.diagnostics))
set(handles.(['edit_diag_' num2str(i)]),...
'String',num2str(parameters.diagnostics(i)));
end
end
% Update handles structure
handles.output = hObject;
guidata(hObject, handles);
% UIWAIT makes costMatRandomDirectedSwitchingMotionLinkGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = costMatRandomDirectedSwitchingMotionLinkGUI_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 pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_cancel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
delete(handles.figure1)
% --- Executes on button press in pushbutton_done.
function pushbutton_done_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
lower = str2double(get(handles.edit_lower, 'String'));
upper = str2double(get(handles.edit_upper, 'String'));
brownStdMult = str2double(get(handles.edit_brownStdMult, 'String'));
nnWindow = str2double(get(handles.edit_nnWindow, 'String'));
diagnostics{1} = get(handles.edit_diag_1, 'String');
diagnostics{2} = get(handles.edit_diag_2, 'String');
diagnostics{3} = get(handles.edit_diag_3, 'String');
% lower
isPosScalar = @(x) isscalar(x) && ~isnan(x) && x>=0;
if ~isPosScalar(lower)
errordlg('Please provide a valid value to parameter "Lower Bound".','Error','modal')
return
end
% Upper
if ~isPosScalar(upper)
errordlg('Please provide a valid value to parameter "Upper Bound".','Error','modal')
return
elseif upper < lower
errordlg('"Upper Bound" should be larger than "Lower Bound".','Error','modal')
return
end
% brownStdMult
if ~isPosScalar(brownStdMult)
errordlg('Please provide a valid value to parameter "Multiplication Factor for Search Radius Calculation".','Error','modal')
return
end
% nnWindow
if ~isPosScalar(nnWindow)
errordlg('Please provide a valid value to parameter "Number of Frames for Nearest Neighbor Distance Calculation".','Error','modal')
return
end
% Set Parameters
parameters = userData.parameters;
parameters.linearMotion = get(handles.checkbox_linearMotion, 'Value')+...
get(handles.checkbox_immediateDirectionReversal,'Value');
parameters.minSearchRadius = lower;
parameters.maxSearchRadius = upper;
parameters.brownStdMult = brownStdMult;
parameters.useLocalDensity = get(handles.checkbox_useLocalDensity, 'Value');
parameters.nnWindow = nnWindow;
% Set diagnostics parameters
if get(handles.checkbox_diagnostics, 'Value')
if all(cellfun(@isempty, diagnostics))
errordlg('Please provide 1 or more than 1 (maximum 3) "Frame Numbers to Plot Histograms" in the text boxes.','Error','modal')
return
end
validDiagnostics = str2double(diagnostics(~cellfun(@isempty, diagnostics)));
nFrames= userData.crtProc.owner_.nFrames_;
if any(isnan(validDiagnostics) | validDiagnostics<2 | validDiagnostics>nFrames-1)
errordlg('Please provide a valid value to parameter "Frame Numbers to Plot Histograms". Note: the first or last frame of a movie is invalid.','Error','modal')
return
end
parameters.diagnostics =validDiagnostics;
else
parameters.diagnostics = [];
end
u = get(userData.handles_main.popupmenu_linking, 'UserData');
u{userData.procID} = parameters;
set(userData.handles_main.popupmenu_linking, 'UserData', u)
% set linearMotion to gap closing cost function "costMatLinearMotionCloseGaps2"
u_gapclosing = get(userData.handles_main.popupmenu_gapclosing, 'UserData');
gapclosingParameters = u_gapclosing{userData.procID};
% Check consistency of search radius parameters with gap closing
checkMinSearchRadius=(gapclosingParameters.minSearchRadius~=lower);
checkMaxSearchRadius=(gapclosingParameters.maxSearchRadius~=upper);
if checkMinSearchRadius || checkMaxSearchRadius
modifyGapClosingParameters=questdlg('Do you want to use the search radius bounds for the gap closing?',...
'Modified search radius parameters','Yes','No','Yes');
if strcmp(modifyGapClosingParameters,'Yes')
gapclosingParameters.minSearchRadius=lower;
gapclosingParameters.maxSearchRadius=upper;
end
end
% Check consistency of search radius parameters with gap closing
checkNewLinearMotion=(gapclosingParameters.linearMotion~=parameters.linearMotion);
checkDirectedMotion = parameters.linearMotion~=0;
gapclosingParameters.linearMotion=parameters.linearMotion;
if checkNewLinearMotion && checkDirectedMotion
modifyGapClosingParameters=questdlg('Do you want to use the default directed motion parameters for the gap closing?',...
'Modified linear motion parameters','Yes','No','Yes');
if strcmp(modifyGapClosingParameters,'Yes')
if parameters.linearMotion==1
gapclosingParameters.linStdMult(1)=1;
gapclosingParameters.linScaling(1)=1;
else
gapclosingParameters.linStdMult(1)=3;
gapclosingParameters.linScaling(1)=.5;
end
end
end
u_gapclosing{userData.procID} = gapclosingParameters;
set(userData.handles_main.popupmenu_gapclosing, 'UserData', u_gapclosing)
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
delete(handles.figure1);
% --- Executes on button press in checkbox_diagnostics.
function checkbox_diagnostics_Callback(hObject, eventdata, handles)
if get(hObject, 'Value'),
set(get(handles.uipanel_diagnostics,'Children'),'Enable','on');
else
set(get(handles.uipanel_diagnostics,'Children'),'Enable','off');
end
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(hObject, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
% --- Executes on button press in checkbox_linearMotion.
function checkbox_linearMotion_Callback(hObject, eventdata, handles)
if get(handles.checkbox_linearMotion,'Value')
set(handles.checkbox_immediateDirectionReversal,'Enable','on');
else
set(handles.checkbox_immediateDirectionReversal,'Enable','off','Value',0);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
discriminationMatrix.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/discriminationMatrix.m
| 8,257 |
utf_8
|
cd1061252d13a1613adf40e4f2cad450
|
function compMatrices = discriminationMatrix(dataStructure,testStructure)
%DISCRIMINATIONMATRIX generates discriminationMatrices comparing means and distributions of lists of values in the input data structures
%
% SYNOPSIS compMatrices = discriminationMatrix(dataStructure)
%
% INPUT dataStructure : n-by-1 structure containing the lists of values
% that are to be compared
% Fieldnames can be arbitrary
% testStructure : (opt) 1-by-1 structure containing information on
% test to be used. Fieldnames have to be exactly
% the same as in dataStructure.
% The fields have to contain a vector of length
% two, specifying the tests to be used. The first
% entry specifies the test shown below the
% diagonal, the second entry specifies the test
% shown above the diagonal.
% 1 - t-test for means (default below diag.)
% 2 - Wilcoxon ranksum test for medians
% 10 - K-S test for distributions
% 11 - K-S test for distributions with subtracted
% mean (default for above diag.)
% 12 - K-S test for distributions with subtracted
% median
% 20 - permutation test for means
% 21 - distribution test - calibrated K-S test
% with mean subtraction
%
% OUTPUT compMatrices : Structure with fieldnames equal to the
% fieldnames of the data structure, containing
% n-by-n matrices with p-values for
% - below the diagonal: T-test for equality of means
% - above the diagonal: Kolmogorov-Smirnov test for
% equality of the distributions, shifted by their
% means.
% Values in the diagonal are 1.01
%
% c: jonas, 12/04
% kathryn, 10/09 - added permutation and distribution tests
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
%=====================
% TEST INPUT
%=====================
defaultTest = [1 11];
% tests:
% If you add tests, please don't forget to reference them here AND in the
% help AND add the entry to the testList. Don't change the default.
% 1 - t-test for means (default below diag.)
% 2 - Wilcoxon ranksum test for medians
% 10 - K-S test for distributions
% 11 - K-S test for distributions with subtracted
% mean (default for above diag.)
% 12 - K-S test for distributions with subtracted
% median
% 20 - permutation test for means
% 21 - distribution test - calibrated KS with mean subtraction
testList = [1 2 10 11 12 20 21];
% nargin
if nargin == 0 || isempty(dataStructure) || ~isstruct(dataStructure)
error('Please input a non-empty data structure in DISCRIMINATIONMATRIX')
end
if nargin < 2 || isempty(testStructure)
useDefaultTest = 1;
else
useDefaultTest = 0;
end
% length structure
nGroups = length(dataStructure);
if nGroups < 2
error('Please try to compare at least two sets of data!')
end
% number of data sets to compare
dataNames = fieldnames(dataStructure);
nData = length(dataNames);
% loop through all the data. Get means, medians and fill testStruct
% (check whether empty, too)
groupMeans = zeros(nGroups,nData,2);
for iData = 1:nData
for iGroup = 1:nGroups
if ~isempty(dataStructure(iGroup).(dataNames{iData}))
% subtract nanMean/nanMedian to make sure that we don't lose all data for
% one NaN
groupMeans(iGroup,iData,1) = ...
nanmean(dataStructure(iGroup).(dataNames{iData}));
groupMeans(iGroup,iData,2) = ...
nanmedian(dataStructure(iGroup).(dataNames{iData}));
else
error('no empty entries are allowed in the dataStructure')
end
end
% select tests
if useDefaultTest
testStructure.(dataNames{iData}) = defaultTest;
else
% first: make sure there is a field of the right name.
% Then make sure two tests are given.
% Finally, make sure they are on the testList
if isfield(testStructure,dataNames{iData})
if length(testStructure.(dataNames{iData}))==2 && ...
all(ismember(testStructure.(dataNames{iData}),testList))
% all is good.
else
error('You either didn''t specify two tests, or you specified an invalid test')
end
else
testStructure.(dataNames{iData}) = defaultTest;
end
end
end
%======================
%=====================
% TEST DATA
%=====================
% preassign output
rawMat = repmat(1.01,[nGroups,nGroups]);
% fore each data entry: Compare all the groups
for iData = 1:nData
% preassign output
compMatrices.(dataNames{iData}) = rawMat;
for gi = 1:nGroups
for gj = gi-1:-1:1
% test 1: below diagonal
try
pValue = test(dataStructure(gi).(dataNames{iData}),...
dataStructure(gj).(dataNames{iData}),...
testStructure.(dataNames{iData})(1),...
groupMeans([gi,gj],iData,:));
compMatrices.(dataNames{iData})(gi,gj) = pValue;
catch
warning('data sets %i and %i could not be compared %s',...
gi,gj,lasterr)
end
% test 2: above diagonal
try
pValue = test(dataStructure(gi).(dataNames{iData}),...
dataStructure(gj).(dataNames{iData}),...
testStructure.(dataNames{iData})(2),...
groupMeans([gi,gj],iData,:));
compMatrices.(dataNames{iData})(gj,gi) = pValue;
catch
warning('data sets %i and %i could not be compared %s',...
gi,gj,lasterr)
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% SUBFUNCTION TEST %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pValue = test(data1, data2, whichTest, groupMeans)
% groupMeans is 2-by-1-by-2; (:,:,1) is the mean, (:,:,2) is the median
switch whichTest
case 1
% compare mean: ttest. Below diagonal
[dummy,pValue] = ...
ttest2(data1, data2, 0.05,'both','unequal');
case 2
% compare median: Wilcoxon Mann Whitney ranksum test. Remove NaN
% first
pValue = ranksum(data1(~isnan(data1)), data2(~isnan(data2)));
case 10
% compare distributions: KS-test. No correction
[dummy,pValue] = ...
kstest2(data1, data2);
case 11
% compare distributions: KS-test. Subtract means
[dummy,pValue] = ...
kstest2(data1-groupMeans(1,1,1), data2-groupMeans(2,1,1));
case 12
% compare distributions: KS-test. Subtract medians
[dummy,pValue] = ...
kstest2(data1-groupMeans(1,1,2), data2-groupMeans(2,1,2));
case 20
% compare means: permutation test
[~,pValue] = permTest(data1, data2, 0.05, 'both');
case 21
% compare distributions: calibrated KS-test
pValue=distribTest(data1,data2); % here pValue is really the confidence value
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
cometDetectionProcessGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/cometDetectionProcessGUI.m
| 8,543 |
utf_8
|
3ef50498580c765caa0521bdab2239cb
|
function varargout = cometDetectionProcessGUI(varargin)
% cometDetectionProcessGUI M-file for cometDetectionProcessGUI.fig
% cometDetectionProcessGUI, by itself, creates a new cometDetectionProcessGUI or raises the existing
% singleton*.
%
% H = cometDetectionProcessGUI returns the handle to a new cometDetectionProcessGUI or the handle to
% the existing singleton*.
%
% cometDetectionProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in cometDetectionProcessGUI.M with the given input arguments.
%
% cometDetectionProcessGUI('Property','Value',...) creates a new cometDetectionProcessGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before cometDetectionProcessGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to cometDetectionProcessGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help cometDetectionProcessGUI
% Last Modified by GUIDE v2.5 09-Feb-2012 18:03:09
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @cometDetectionProcessGUI_OpeningFcn, ...
'gui_OutputFcn', @cometDetectionProcessGUI_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 cometDetectionProcessGUI is made visible.
function cometDetectionProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin)
processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1);
% ---------------------- Channel Setup -------------------------
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
funParams = userData.crtProc.funParams_;
maskProc = cellfun(@(x) isa(x,'MaskProcess'),userData.MD.processes_);
maskProcID=find(maskProc);
maskProcNames = cellfun(@(x) x.getName(),userData.MD.processes_(maskProc),'Unif',false);
maskProcString = vertcat('None',maskProcNames(:));
maskProcData=horzcat({[]},num2cell(maskProcID));
maskProcValue = find(cellfun(@(x) isequal(x,funParams.MaskProcessIndex),maskProcData));
if isempty(maskProcValue), maskProcValue = 1; end
set(handles.popupmenu_MaskProcess,'String',maskProcString,...
'UserData',maskProcData,'Value',maskProcValue,'Enable','on');
set(handles.edit_firstFrame,'String',funParams.firstFrame);
set(handles.edit_lastFrame,'String',funParams.lastFrame);
userData.numParams ={'sigma1','sigma2','multFactorThresh','multFactorStepSize'};
cellfun(@(x) set(handles.(['edit_' x]),'String',funParams.(x)),...
userData.numParams)
% Update GUI user data
handles.output = hObject;
set(hObject, 'UserData', userData);
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = cometDetectionProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel.
function pushbutton_cancel_Callback(~, ~, handles)
% Delete figure
delete(handles.figure1);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, ~, handles)
% Notify the package GUI that the setting panel is closed
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
if isfield(userData, 'helpFig') && ishandle(userData.helpFig)
delete(userData.helpFig)
end
if isfield(userData, 'previewFig') && ishandle(userData.previewFig)
delete(userData.previewFig)
end
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
% --- Executes on key press with focus on pushbutton_done and none of its controls.
function pushbutton_done_KeyPressFcn(~, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(~, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
% --- Executes on button press in pushbutton_done.
function pushbutton_done_Callback(hObject, eventdata, handles)
% Check user input
if isempty(get(handles.listbox_selectedChannels, 'String'))
errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal')
return;
end
funParams.ChannelIndex = get(handles.listbox_selectedChannels, 'Userdata');
% Get frame range
userData=get(handles.figure1,'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
firstFrame = str2double(get(handles.edit_firstFrame,'String'));
if ~userData.crtProc.checkFrameNum(firstFrame)
errordlg(['Please enter a valid ' get(handles.text_frameRange,'String') '.'],...
'Setting Error','modal')
return;
end
funParams.firstFrame=firstFrame;
% Get last range
lastFrame = str2double(get(handles.edit_lastFrame,'String'));
if ~userData.crtProc.checkFrameNum(lastFrame) || firstFrame > lastFrame
errordlg(['Please enter a valid ' get(handles.text_frameRange,'String') '.'],...
'Setting Error','modal')
return;
end
funParams.lastFrame=lastFrame;
% Retrieve detection parameters
for i=1:numel(userData.numParams)
value = str2double(get(handles.(['edit_' userData.numParams{i}]),'String'));
if isnan(value) || value < 0
errordlg(['Please enter a valid value for '...
get(handles.(['text_' userData.numParams{i}]),'String') '.'],...
'Setting Error','modal')
return;
end
funParams.(userData.numParams{i})=value;
end
% Retrieve numerical parameters
for i=1:numel(userData.numParams)
value = str2double(get(handles.(['edit_' userData.numParams{i}]),'String'));
if isnan(value) || value < 0
errordlg(['Please enter a valid value for '...
get(handles.(['text_' userData.numParams{i}]),'String') '.'],...
'Setting Error','modal')
return;
end
funParams.(userData.numParams{i})=value;
end
% Retrieve mask process index and class (for propagation)
props=get(handles.popupmenu_MaskProcess,{'UserData','Value'});
funParams.MaskProcessIndex = props{1}{props{2}};
if ~isempty(funParams.MaskProcessIndex)
maskProcessClass=class(userData.MD.processes_{funParams.MaskProcessIndex});
else
maskProcessClass = '';
end
% Set parameters
setMaskProcess = @(x) parseProcessParams(x, struct('MaskProcessIndex',...
x.owner_.getProcessIndex(maskProcessClass,1,false)));
settingFcn = {setMaskProcess};
% Handle multiple movies last frame setting
if lastFrame == userData.MD.nFrames_
setLastFrame =@(x) parseProcessParams(x,struct('lastFrame',...
min(x.owner_.nFrames_)));
settingFcn = {setMaskProcess, setLastFrame};
end
processGUI_ApplyFcn(hObject, eventdata, handles,funParams,settingFcn);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
plusTipCostMatLinearMotionLinkGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/plusTipCostMatLinearMotionLinkGUI.m
| 8,348 |
utf_8
|
ef058bad2e121077bd52e5d1262d257e
|
function varargout = plusTipCostMatLinearMotionLinkGUI(varargin)
% PLUSTIPCOSTMATLINEARMOTIONLINKGUI M-file for plusTipCostMatLinearMotionLinkGUI.fig
% PLUSTIPCOSTMATLINEARMOTIONLINKGUI, by itself, creates a new PLUSTIPCOSTMATLINEARMOTIONLINKGUI or raises the existing
% singleton*.
%
% H = PLUSTIPCOSTMATLINEARMOTIONLINKGUI returns the handle to a new PLUSTIPCOSTMATLINEARMOTIONLINKGUI or the handle to
% the existing singleton*.
%
% PLUSTIPCOSTMATLINEARMOTIONLINKGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in PLUSTIPCOSTMATLINEARMOTIONLINKGUI.M with the given input arguments.
%
% PLUSTIPCOSTMATLINEARMOTIONLINKGUI('Property','Value',...) creates a new PLUSTIPCOSTMATLINEARMOTIONLINKGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before plusTipCostMatLinearMotionLinkGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to plusTipCostMatLinearMotionLinkGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help plusTipCostMatLinearMotionLinkGUI
% Last Modified by GUIDE v2.5 14-Feb-2013 17:00:53
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @plusTipCostMatLinearMotionLinkGUI_OpeningFcn, ...
'gui_OutputFcn', @plusTipCostMatLinearMotionLinkGUI_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 plusTipCostMatLinearMotionLinkGUI is made visible.
function plusTipCostMatLinearMotionLinkGUI_OpeningFcn(hObject, eventdata, handles, varargin)
costMat_OpeningFcn(hObject, eventdata, handles, varargin{:})
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
parameters = userData.parameters;
% Parameter Setup
set(handles.edit_lower, 'String', num2str(parameters.minSearchRadius))
set(handles.edit_upper, 'String', num2str(parameters.maxSearchRadius))
set(handles.edit_brownStdMult, 'String', num2str(parameters.brownStdMult))
set(handles.checkbox_useLocalDensity, 'Value', parameters.useLocalDensity)
set(handles.edit_nnWindow, 'String', num2str(parameters.nnWindow))
if isempty(parameters.diagnostics) || (length(parameters.diagnostics) == 1 && parameters.diagnostics == 0)
set(handles.checkbox_diagnostics, 'Value', 0);
set(get(handles.uipanel_diagnostics,'Children'),'Enable','off');
else
set(handles.checkbox_diagnostics, 'Value', 1);
for i = 1:min(3,length(parameters.diagnostics))
set(handles.(['edit_diag_' num2str(i)]),...
'String',num2str(parameters.diagnostics(i)));
end
end
% Update handles structure
handles.output = hObject;
guidata(hObject, handles);
% UIWAIT makes plusTipCostMatLinearMotionLinkGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = plusTipCostMatLinearMotionLinkGUI_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 pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_cancel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
delete(handles.figure1)
% --- Executes on button press in pushbutton_done.
function pushbutton_done_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end; % 2014b Hackaton-fix PR
lower = str2double(get(handles.edit_lower, 'String'));
upper = str2double(get(handles.edit_upper, 'String'));
brownStdMult = str2double(get(handles.edit_brownStdMult, 'String'));
nnWindow = str2double(get(handles.edit_nnWindow, 'String'));
diagnostics{1} = get(handles.edit_diag_1, 'String');
diagnostics{2} = get(handles.edit_diag_2, 'String');
diagnostics{3} = get(handles.edit_diag_3, 'String');
% lower
isPosScalar = @(x) isscalar(x) && ~isnan(x) && x>=0;
if ~isPosScalar(lower)
errordlg('Please provide a valid value to parameter "Lower Bound".','Error','modal')
return
end
% Upper
if ~isPosScalar(upper)
errordlg('Please provide a valid value to parameter "Upper Bound".','Error','modal')
return
elseif upper < lower
errordlg('"Upper Bound" should be larger than "Lower Bound".','Error','modal')
return
end
% brownStdMult
if ~isPosScalar(brownStdMult)
errordlg('Please provide a valid value to parameter "Multiplication Factor for Search Radius Calculation".','Error','modal')
return
end
% nnWindow
if ~isPosScalar(nnWindow)
errordlg('Please provide a valid value to parameter "Number of Frames for Nearest Neighbor Distance Calculation".','Error','modal')
return
end
% Set Parameters
parameters = userData.parameters;
parameters.minSearchRadius = lower;
parameters.maxSearchRadius = upper;
parameters.brownStdMult = brownStdMult;
parameters.useLocalDensity = get(handles.checkbox_useLocalDensity, 'Value');
parameters.nnWindow = nnWindow;
% Set diagnostics parameters
if get(handles.checkbox_diagnostics, 'Value')
if all(cellfun(@isempty, diagnostics))
errordlg('Please provide 1 or more than 1 (maximum 3) "Frame Numbers to Plot Histograms" in the text boxes.','Error','modal')
return
end
validDiagnostics = str2double(diagnostics(~cellfun(@isempty, diagnostics)));
nFrames= userData.crtProc.owner_.nFrames_;
if any(isnan(validDiagnostics) | validDiagnostics<2 | validDiagnostics>nFrames-1)
errordlg('Please provide a valid value to parameter "Frame Numbers to Plot Histograms". Note: the first or last frame of a movie is invalid.','Error','modal')
return
end
parameters.diagnostics =validDiagnostics;
else
parameters.diagnostics = [];
end
u = get(userData.handles_main.popupmenu_linking, 'UserData');
u{userData.procID} = parameters;
set(userData.handles_main.popupmenu_linking, 'UserData', u)
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
delete(handles.figure1);
% --- Executes on button press in checkbox_diagnostics.
function checkbox_diagnostics_Callback(hObject, eventdata, handles)
if get(hObject, 'Value'),
set(get(handles.uipanel_diagnostics,'Children'),'Enable','on');
else
set(get(handles.uipanel_diagnostics,'Children'),'Enable','off');
end
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(hObject, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
trackMSSAnalysis.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/trackMSSAnalysis.m
| 107,740 |
utf_8
|
4ed3a94d70b08446a794a81bc358b8a9
|
function [trackClass,mssSlope,genDiffCoef,scalingPower,normDiffCoef] ...
= trackMSSAnalysis(tracks,probDim,momentOrders,alphaMSS)
%TRACKMSSANALYSIS classifies trajectories based on their moment scaling spectrum
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
%SYNPOSIS [trackClass,mssSlope,genDiffCoef,scalingPower,normDiffCoef] ...
% = trackMSSAnalysis(tracks,probDim,momentOrders,alphaMSS)
%
%INPUT tracks : Matrix indicating the positions and amplitudes of the
% tracked features. Number of rows = number of tracks,
% number of columns = 8*number of time points.
% Each row consists of
% [x1 y1 z1 a1 dx1 dy1 dz1 da1 x2 y2 z2 a2 dx2 dy2 dz2 da2 ...].
% NaN is used to indicate time points where the track
% does not exist.
% probDim : Problem dimensionality. Optional. Default: 2.
% momentOrders: Orders of moments to be calculated.
% Optional. Default: 0 through 6.
% alphaMSS : Alpha-value for classification. Can take the values
% 0.2, 0.1, 0.05 and 0.01. One can enter one value, in
% which case it will be used for both confined and
% directed, or two values, where the first will be used
% for confined and the second for directed.
% Optional. Default: 0.1 for both.
%
%OUTPUT trackClass : # tracks x 1 vector of track classification.
% Values mean the following ...
% 0 = stalled. (NOT IMPLEMENTED YET)
% 1 = confined Brownian.
% 2 = pure Brownian.
% 3 = Brownian with drift (directed).
% NaN = not classified.
% mssSlope : # tracks x 1 vector of each track's slope of the line
% representing moment scaling power vs. moment order.
% NaN indicates tracks that could not be analyzed.
% genDiffCoef : # tracks x # orders array of generalized diffusion
% coefficients for every moment order considered.
% NaN indicates tracks that could not be analyzed.
% scalingPower: # tracks x # orders array of powers with which moment
% values scale with time.
% NaN indicates tracks that could not be analyzed.
% normDiffCoef: # tracks x 1 vector of each track's "normal"
% diffusion coefficient.
% NaN indicates tracks that could not be analyzed.
%
%REMARKS
%(1) Algorithm is based on Ewers et al. 2005. PNAS 102: 15110-15115 and
%Ferrari et al. 2001. Physica D 154: 111-137.
%(2) Analysis assumes that there are no kinks in the moment scaling
%spectrum curve, i.e. that the motion is strongly self-similar. Weakly
%self-similar processes will generate an MSS which is piece-wise
%continuous, hence before fitting to estimate the slope the curve must be
%chopped into smaller straight-line pieces (but this is not done).
%(3)MSS slope thresholds corresponding to alphaMSS = 0.1, 0.05 and 0.01 in
%2D case are calculated using a smoothing spline fit to the corresponding
%percentiles, which were in turn derived from a sample of 35500
%simulations. For all other conditions, the threshold is calculating using
%simple piece-wise line fit to the corresponding percentiles which were
%derived from a sample of 2000 simulations.
%
%Khuloud Jaqaman, March 2008
%% input
if nargin < 1
disp('--trackMSSAnalysis: Please input tracks to analyze.');
return
end
if nargin < 2 || isempty(probDim)
probDim = 2;
end
if nargin < 3 || isempty(momentOrders)
momentOrders = 0 : 6;
end
numOrders = length(momentOrders);
if nargin < 4 || isempty(alphaMSS)
[alphaMSSConf,alphaMSSDir] = deal(0.1);
elseif length(alphaMSS) == 1
[alphaMSSConf,alphaMSSDir] = deal(alphaMSS);
elseif length(alphaMSS) == 2
alphaMSSConf = alphaMSS(1);
alphaMSSDir = alphaMSS(2);
end
%get number of tracks and frames
[numTracks,numFramesMovie] = size(tracks);
numFramesMovie = numFramesMovie / 8;
%find indices of tracks that are >= 20 frames long - do not attempt
%to calculate moments for shorter tracks
criteria.lifeTime.min = 20;
indx4diff = chooseTracks(tracks,criteria);
clear criteria
%% alpha-value for classification
%determine threshold based on alpha-value and dimensionality
switch probDim
case 1
switch alphaMSSConf
case 0.2 %10th percentile and 90th percentile
mssThreshNeg = threshMSS1D_p20(numFramesMovie);
case 0.1 %5th percentile and 95th percentile
mssThreshNeg = threshMSS1D_p10(numFramesMovie);
case 0.05 %2.5th percentile and 97.5th percentile
mssThreshNeg = threshMSS1D_p05(numFramesMovie);
case 0.01 %0.5th percentile and 99.5th percentile
mssThreshNeg = threshMSS1D_p01(numFramesMovie);
end
switch alphaMSSDir
case 0.2 %10th percentile and 90th percentile
[dummy,mssThreshPos] = threshMSS1D_p20(numFramesMovie);
case 0.1 %5th percentile and 95th percentile
[dummy,mssThreshPos] = threshMSS1D_p10(numFramesMovie);
case 0.05 %2.5th percentile and 97.5th percentile
[dummy,mssThreshPos] = threshMSS1D_p05(numFramesMovie);
case 0.01 %0.5th percentile and 99.5th percentile
[duumy,mssThreshPos] = threshMSS1D_p01(numFramesMovie);
end
case 2
switch alphaMSSConf
case 0.2 %10th percentile and 90th percentile
mssThreshNeg = threshMSS2D_p20(numFramesMovie);
case 0.1 %5th percentile and 95th percentile
mssThreshNeg = threshMSS2D_p10(numFramesMovie);
case 0.05 %2.5th percentile and 97.5th percentile
mssThreshNeg = threshMSS2D_p05(numFramesMovie);
case 0.01 %0.5th percentile and 99.5th percentile
mssThreshNeg = threshMSS2D_p01(numFramesMovie);
end
switch alphaMSSDir
case 0.2 %10th percentile and 90th percentile
[dummy,mssThreshPos] = threshMSS2D_p20(numFramesMovie);
case 0.1 %5th percentile and 95th percentile
[dummy,mssThreshPos] = threshMSS2D_p10(numFramesMovie);
case 0.05 %2.5th percentile and 97.5th percentile
[dummy,mssThreshPos] = threshMSS2D_p05(numFramesMovie);
case 0.01 %0.5th percentile and 99.5th percentile
[dummy,mssThreshPos] = threshMSS2D_p01(numFramesMovie);
end
case 3
switch alphaMSSConf
case 0.2 %10th percentile and 90th percentile
mssThreshNeg = threshMSS3D_p20(numFramesMovie);
case 0.1 %5th percentile and 95th percentile
mssThreshNeg = threshMSS3D_p10(numFramesMovie);
case 0.05 %2.5th percentile and 97.5th percentile
mssThreshNeg = threshMSS3D_p05(numFramesMovie);
case 0.01 %0.5th percentile and 99.5th percentile
mssThreshNeg = threshMSS3D_p01(numFramesMovie);
end
switch alphaMSSDir
case 0.2 %10th percentile and 90th percentile
[dummy,mssThreshPos] = threshMSS3D_p20(numFramesMovie);
case 0.1 %5th percentile and 95th percentile
[dummy,mssThreshPos] = threshMSS3D_p10(numFramesMovie);
case 0.05 %2.5th percentile and 97.5th percentile
[dummy,mssThreshPos] = threshMSS3D_p05(numFramesMovie);
case 0.01 %0.5th percentile and 99.5th percentile
[dummy,mssThreshPos] = threshMSS3D_p01(numFramesMovie);
end
end
%% memory for trajectory classification
%classification means ...
%0 = stalled
%1 = confined Brownian
%2 = pure Brownian
%3 = drift/directed
%NaN = unclassified
trackClass = NaN(numTracks,1);
mssSlope = NaN(numTracks,1);
genDiffCoef = NaN(numTracks,numOrders);
scalingPower = NaN(numTracks,numOrders);
normDiffCoef = NaN(numTracks,1);
%% moments and their scaling with time
for iTrack = indx4diff'
%get track start and end time
trackSEL = getTrackSEL(tracks(iTrack,:));
startTime = trackSEL(1);
endTime = trackSEL(2);
numTimePoints = trackSEL(3);
%extract track's coordinates and their standard deviations
coordinates = [tracks(iTrack,1:8:end)' tracks(iTrack,2:8:end)' tracks(iTrack,3:8:end)'];
coordinates = coordinates(startTime:endTime,:);
standardDevs = [tracks(iTrack,5:8:end)' tracks(iTrack,6:8:end)' tracks(iTrack,7:8:end)'];
standardDevs = standardDevs(startTime:endTime,:);
%define maximum time lag for moment calculation
maxLag = min(30,floor(numTimePoints/4));
%calculate track moments
trackMomentsT = calcTrackMoments(coordinates,standardDevs,momentOrders,maxLag);
trackMoments = [trackMomentsT.momentValues];
trackMoments = trackMoments(:,1:2:end);
%estimate the moment scaling spectrum (MSS),
%i.e. the scaling power for all moments
scalingPowerT = NaN(1,numOrders);
genDiffCoefT = NaN(1,numOrders);
for iOrder = 1 : length(momentOrders)
%caculate ln(lag) and ln(moment)
lnTime = log((1:maxLag)');
lnMoment = log(trackMoments(:,iOrder));
%remove any NaNs
indxGood = find(~isnan(lnMoment));
lnTime = lnTime(indxGood);
lnMoment = lnMoment(indxGood);
%if there are moments to fit ...
if length(lnMoment) > 1
%fit a straight line in the plot of lnMoment vs. lnTime
slParam = polyfit(lnTime,lnMoment,1);
%get scaling power and generalized diffusion coefficient
scalingPowerT(iOrder) = slParam(1);
genDiffCoefT(iOrder) = exp(slParam(2)) / 2 / probDim;
%if this is the 2nd moment, calculate the "normal" diffusion
%coefficient
if momentOrders(iOrder)==2
options = optimset('Display','off','Jacobian','on');
lnSlope = lsqcurvefit(@strLineFun2,1,lnTime(1:min(5,...
length(lnTime))),lnMoment(1:min(5,length(lnMoment))),...
[],[],options);
normDiffCoefT = exp(lnSlope) / 2 / probDim;
end
end
end
%keep only non-NaN scaling powers
indxGood = find(~isnan(scalingPowerT));
momentOrders4fit = momentOrders(indxGood);
scalingPowerT = scalingPowerT(indxGood);
genDiffCoefT = genDiffCoefT(indxGood);
%if there are non-NaN scaling powers
if ~isempty(scalingPowerT)
%fit a straight line to the MSS
slParam = polyfit(momentOrders4fit,scalingPowerT,1);
%get the slope of the line
mssSlopeT = slParam(1);
%classify track as ...
%1 = confined Brownian, if MSS slope < mssThreshNeg
%2 = pure Brownian, if mssThreshNeg <= MSS slope <= mssThreshPos
%3 = directed, if MSS slope > mssThreshPos
if ~isnan(mssSlopeT)
if mssSlopeT < mssThreshNeg(numTimePoints)
trackClass(iTrack) = 1;
elseif mssSlopeT > mssThreshPos(numTimePoints)
trackClass(iTrack) = 3;
else
trackClass(iTrack) = 2;
end
end
%save additional output information
mssSlope(iTrack) = mssSlopeT;
genDiffCoef(iTrack,:) = genDiffCoefT;
scalingPower(iTrack,:) = scalingPowerT;
normDiffCoef(iTrack) = normDiffCoefT;
end
end
%% subfunction 1
function [y,d] = strLineFun2(logSlope,x)
y = logSlope + x;
d = ones(size(x));
%% thresholds
function [mssThreshNeg,mssThreshPos] = threshMSS1D_p20(nTP)
%1D, alpha = 0.2
%threshold curve parameters
turnPointsM = [20 60 200 500];
turnPointsP = [20 60 100 500];
slopeM = [0.002434794446981 0.000542795021531 0.000165329365168 0];
slopeP = [-0.001541239220102 -0.00036860800289 -0.00002638219148 0];
interseptM = [0.130233710469096 0.243753675996077 0.319246807268674 0.40191148985285];
interseptP = [0.672499246818346 0.602141373785626 0.567918792644692 0.554727696904506];
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS1D_p10(nTP)
%1D, alpha = 0.1
%threshold curve parameters
turnPointsM = [20 50 200 500];
turnPointsP = [20 60 150 500];
slopeM = [0.00403865723972 0.00073054296121 0.000167789786604 0];
slopeP = [-0.001863373027824 -0.000207607837099 -0.000068295975124 0];
interseptM = [0.018637170190375 0.184042884115918 0.296593519037011 0.380488412339042];
interseptP = [0.727469044719516 0.628123133276013 0.607226353979748 0.5730783664177];
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS1D_p05(nTP)
%1D, alpha = 0.05
%threshold curve parameters
turnPointsM = [20 60 200 500];
turnPointsP = [20 50 200 500];
slopeM = [0.004221335524384 0.000794743062117 0.000192611669839 0];
slopeP = [-0.002478698219027 -0.000203422663306 -0.000101280672122 0];
interseptM = [-0.059561585354062 0.146033962381945 0.266460240837543 0.362766075757204];
interseptP = [0.772420366381382 0.658656588595335 0.638228190358568 0.587587854297634];
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS1D_p01(nTP)
%1D, alpha = 0.01
%threshold curve parameters
turnPointsM = [20 50 150 500];
turnPointsP = [20 45 100 500];
slopeM = [0.00748519566052008 0.00132812830129705 0.000291477165467116 0];
slopeP = [-0.00263804313196125 -0.000652822904393821 -0.000123920022338378 0];
interseptM = [-0.27508360480994 0.0327697631512118 0.188267433525701 0.334006016259259];
interseptP = [0.839817228313045 0.750482318072511 0.697592029866967 0.635632018697778];
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS2D_p20(nTP)
%2D, alpha = 0.2
%threshold curve parameters
turnPointsM = [20 50 200 500];
turnPointsP = [20 60 150 500];
slopeM = [0.002365010936411 0.000327173962804 0.000137961052668 0];
slopeP = [-0.001158501020215 -0.000170757301414 -0.000033415212947 0];
interseptM = [0.227688919307209 0.329580767987585 0.367423350014689 0.436403876348735];
interseptP = [0.634413262884249 0.575148639756167 0.554547326486174 0.537839720012491];
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS2D_p10(nTP)
%2D, alpha = 0.1
%NEW
mssThreshNeg = [...
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
0.22745412174663
0.233161658076958
0.238712335849316
0.243942595943949
0.248765797042666
0.25319606019234
0.257222712435148
0.260820097125929
0.264022922051307
0.266958704365908
0.269672315280133
0.272160518632548
0.274452617591953
0.276641195820616
0.278727477064239
0.280671923536532
0.28247532444392
0.284208829102268
0.285860941991394
0.287378057585524
0.288753002802575
0.290071283927206
0.291367428204686
0.292623598509624
0.293840775024627
0.295072879740121
0.296295727221108
0.297444504094809
0.298509395809849
0.299561725921043
0.30060498942953
0.30160296929942
0.302539697275081
0.30345230271871
0.304325700625445
0.305133593757577
0.305876861532026
0.306607773063942
0.307338820167741
0.308044876026691
0.308719468362311
0.30939888182498
0.310072992600017
0.310709988314711
0.311326320570336
0.311994633765683
0.312731698246595
0.313505449420241
0.314295810475204
0.315118913163757
0.315947218279532
0.316733511082753
0.317463410977594
0.31817306411387
0.318867078363294
0.319524117937474
0.320140509673117
0.320749108687508
0.321348933053907
0.321914030863819
0.32243530687815
0.322933580726169
0.323389130856063
0.323767172308512
0.324067984556657
0.324336673775683
0.324587993066945
0.324811724125205
0.32501270487864
0.325222413638182
0.325440555615016
0.32565239061206
0.325870736964501
0.32613917517856
0.326447877924341
0.3267545200733
0.327038798351875
0.32732180403296
0.327604253128306
0.32787086458923
0.328128885523064
0.328422364979933
0.328760995825149
0.329126521994235
0.329507449821629
0.329917763166535
0.330338236348803
0.330735410709573
0.331102609831489
0.331463675658305
0.331815107768013
0.332139086364455
0.332433929405062
0.332723852877751
0.333002266913764
0.333239771054926
0.333424148275459
0.333583456328585
0.33373100341678
0.333871173017673
0.334035432605662
0.33428127941858
0.334632903253784
0.335080076975016
0.33560316901398
0.336184256673208
0.336808209446308
0.337459442116977
0.338122660077784
0.338786872271129
0.339444818853822
0.340090606417223
0.340719439276555
0.341330072164072
0.341925717534233
0.342511442719755
0.343091088011455
0.343672288496437
0.344262857441147
0.344866889856187
0.345479535539688
0.346091444559155
0.346690433756783
0.347271075584896
0.34784415398524
0.348421271526866
0.349011618630643
0.349616811684455
0.350235527269212
0.350864336548045
0.351493821882612
0.352114709737342
0.352725274065241
0.353325695040802
0.353916152838517
0.354496827632879
0.355067899598381
0.355629548909516
0.356181955740775
0.356725300266653
0.357259762661642
0.357785523100233
0.358302761756921
0.358811658806198
0.359312394422556
0.359805148780489
0.360290102054488
0.360767434419048
0.361237326048659
0.361699957117816
0.362155507801011
0.362604158272736
0.363046088707484
0.363481479279749
0.363910510164022
0.364333361534797
0.364750213566565
0.365161246433821
0.365566640311056
0.365966575372764
0.366361231793436
0.366750789747566
0.367135429409647
0.367515330954171
0.367890674555631
0.368261640388519
0.368628408627329
0.368991159446552
0.369350073020683
0.369705329524212
0.370057109131635
0.370405592017441
0.370750958356126
0.371093388322181
0.371433062090099
0.371770159834373
0.372104861729495
0.372437347949958
0.372767798670255
0.373096394064879
0.373423314308323
0.373748707425412
0.374072592842313
0.374394957835524
0.374715789681543
0.37503507565687
0.375352803038005
0.375668959101444
0.375983531123689
0.376296506381236
0.376607872150587
0.376917615708238
0.37722572433069
0.377532185294442
0.377836985875991
0.378140113351838
0.37844155499848
0.378741298092418
0.37903932991015
0.379335637728174
0.379630208822991
0.379923030471098
0.380214089948994
0.38050337453318
0.380790871500152
0.381076568126412
0.381360451688456
0.381642509462785
0.381922728725897
0.382201096754292
0.382477600824468
0.382752228212923
0.383024966196158
0.38329580205067
0.38356472305296
0.383831716479525
0.384096769606865
0.384359869711479
0.384621004069865
0.384880159958523
0.385137324653951
0.385392485432649
0.385645629571115
0.385896744345848
0.386145817033347
0.386392834910112
0.386637785252641
0.386880655337432
0.387121432440986
0.3873601038398
0.387596656810374
0.387831087681762
0.388063428993232
0.38829372233661
0.388522009303719
0.388748331486384
0.38897273047643
0.38919524786568
0.38941592524596
0.389634804209093
0.389851926346903
0.390067333251215
0.390281066513854
0.390493167726643
0.390703678481408
0.390912640369971
0.391120094984158
0.391326083915793
0.391530648756701
0.391733831098705
0.391935672533629
0.3921362146533
0.392335499049539
0.392533567314173
0.392730461039024
0.392926221815918
0.39312089123668
0.393314510893132
0.3935071223771
0.393698767280407
0.393889487194879
0.394079323712339
0.394268318424612
0.394456512923522
0.394643948800894
0.394830667648551
0.395016711058318
0.39520212062202
0.395386937931481
0.395571204578524
0.395754962154976
0.395938252252658
0.396121116463397
0.396303596379016
0.39648573359134
0.396667569692193
0.3968491462734
0.397030504926783
0.397211687244169
0.397392734817382
0.397573689238245
0.397754579905936
0.397935387449051
0.398116080303536
0.39829662690534
0.398476995690409
0.398657155094692
0.398837073554137
0.399016719504692
0.399196061382304
0.39937506762292
0.39955370666249
0.39973194693696
0.399909756882278
0.400087104934393
0.400263959529251
0.400440289102801
0.400616062090991
0.400791246929767
0.400965812055079
0.401139725902874
0.401312956909099
0.401485473509703
0.401657244140633
0.401828237237836
0.401998421237262
0.402167764574857
0.402336235686569
0.402503803008346
0.402670434976136
0.402836100025887
0.403000766593546
0.403164403115061
0.403326978026381
0.403488459763451
0.403648816762222
0.40380801745864
0.403966030288653
0.404122823688209
0.404278366093255
0.40443262593974
0.404585571663611
0.404737171700816
0.404887394487303
0.405036208459019
0.405183582051913
0.405329483701932
0.405473881845024
0.405616744917136
0.405758041354217
0.405897739592214
0.406035820637939
0.406172315781653
0.406307268884482
0.406440723807553
0.40657272441199
0.406703314558921
0.40683253810947
0.406960438924763
0.407087060865925
0.407212447794084
0.407336643570364
0.407459692055891
0.407581637111791
0.40770252259919
0.407822392379213
0.407941290312986
0.408059260261635
0.408176346086286
0.408292591648064
0.408408040808095
0.408522737427504
0.408636725367419
0.408750048488963
0.408862750653263
0.408974875721446
0.409086467554636
0.409197570013958
0.40930822696054
0.409418482255507
0.409528379759984
0.409637963335097
0.409747276841972
0.409856364141735
0.409965269095511
0.410074035564427
0.410182707409607
0.410291328492178
0.410399942673265
0.410508593813994
0.410617325775491
0.410726182418881
0.410835207605291
0.410944445195846
0.411053939051672
0.411163733033894
0.411273871003638
0.411384396822031
0.411495354350197
0.411606787449263
0.411718739980353
0.411831243447033
0.411944279922618
0.41205781912286
0.412171830763515
0.412286284560336
0.412401150229077
0.41251639748549
0.412631996045331
0.412747915624353
0.412864125938309
0.412980596702954
0.41309729763404
0.413214198447322
0.413331268858554
0.413448478583489
0.413565797337881
0.413683194837483
0.41380064079805
0.413918104935335
0.414035556965092
0.414152966603074
0.414270303565036
0.414387537566731
0.414504638323913
0.414621575552335
0.414738318967752
0.414854838285916
0.414971103222582
0.415087083493504
0.415202748814435
0.415318068901129
0.415433013469339
0.41554755223482
0.415661654913325
0.415775291220608
0.415888430872423
0.416001043584523
0.416113099072661
0.416224567052593
0.416335417240071
0.41644561935085
0.416555143100682
0.416663958205323
0.416772034380524
0.416879341342041
0.416985848805627
0.417091526487036
0.41719634410202
0.417300271366335
0.417403277995734
0.417505341923076
0.417606473949638
0.417706693093804
0.417806018373958
0.417904468808482
0.41800206341576
0.418098821214175
0.418194761222111
0.41828990245795
0.418384263940076
0.418477864686872
0.418570723716721
0.418662860048007
0.418754292699113
0.418845040688422
0.418935123034317
0.419024558755181
0.419113366869399
0.419201566395352
0.419289176351425
0.419376215756001
0.419462703627462
0.419548658984192
0.419634100844575
0.419719048226993
0.41980352014983
0.419887535631469
0.419971113690293
0.420054273344686
0.42013703361303
0.42021941351371
0.420301432065108
0.420383108285607
0.420464461193592
0.420545509807444
0.420626273145547
0.420706770226285
0.420787020068041
0.420867041689198
0.420946854108139
0.421026476343248
0.421105927412907
0.421185226335501
0.421264392129411
0.421343443813023
0.421422400404718
0.42150128092288
0.421580104385892
0.421658889812138
0.42173765622];
mssThreshPos = [...
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
0.654314617903462
0.651121703618836
0.647869171910077
0.644520555133229
0.641137482542311
0.637903321457796
0.63492029309509
0.632207407161199
0.629758811559197
0.627586008463287
0.625643972537407
0.62385997115495
0.622186987322888
0.62061323579898
0.619105337803229
0.617629145177402
0.616182400201377
0.614796525678107
0.61347629909111
0.612215523478362
0.611019193702705
0.609905622420528
0.608874132727919
0.607903724208895
0.606975549542505
0.606083268235531
0.60521550511657
0.604362118530077
0.603528316670036
0.602730247051137
0.601975132813481
0.601262510443939
0.600594673453327
0.599978970639928
0.599409048563272
0.598874413679956
0.598367490414222
0.597883655563545
0.597417910899598
0.596964849071257
0.596519436650525
0.596083431316087
0.59565268357715
0.595229222868723
0.594820562846994
0.594437303746982
0.594079665805683
0.59373928477206
0.593413843784139
0.59311040674089
0.592830286005747
0.592568178223267
0.592309735010737
0.592049584671471
0.591790698081427
0.591537469821343
0.591288939181546
0.591041605238755
0.590790505128832
0.590526977772355
0.590248990681051
0.589962657416809
0.589668751396622
0.589361684433013
0.589045030039499
0.588735585436852
0.588449920113551
0.588198347328549
0.587982671329895
0.587794838407755
0.587622139378069
0.587454418510344
0.587288748340044
0.587127936425178
0.586978202975761
0.586849116596437
0.586747276738412
0.586670983610322
0.586611463626982
0.586554850240366
0.586486621815529
0.586395315721713
0.586276014920567
0.586130100920972
0.585961396464937
0.585771514557314
0.585569696748179
0.585370077291245
0.585183527014906
0.585017817944233
0.584873594723511
0.584745878540664
0.584626492095028
0.584507760057278
0.584382802217256
0.584246470584476
0.584094844369256
0.583931155748866
0.583763127784926
0.58360097165287
0.583458975575805
0.583347272688156
0.583265070129244
0.583199753243692
0.583134817848274
0.583060248646393
0.582971390924761
0.582865257600286
0.582739519936508
0.582592287198727
0.582426755743775
0.582248928173202
0.582066830245188
0.581888987689774
0.581720541653177
0.581563871053679
0.581418683198207
0.581285068998552
0.581160731795124
0.581041256783231
0.58092047367492
0.580794812277068
0.580664881909549
0.580532664465509
0.580398490404841
0.580262229510879
0.580123980772444
0.579985663304701
0.579849611235834
0.579716586842009
0.579586073057527
0.579456652329342
0.579327983972931
0.579200063914547
0.57907288808044
0.578946452396861
0.578820752790062
0.578695785186293
0.578571545511806
0.578448029692851
0.57832523365568
0.578203153326545
0.578081784631695
0.577961123497383
0.577841165849859
0.577721907615374
0.57760334472018
0.577485473090528
0.577368288652668
0.577251787332853
0.577135965057332
0.577020817752357
0.576906341344179
0.57679253175905
0.57667938492322
0.576566896762941
0.576455063204463
0.576343880174039
0.576233343597918
0.576123449402351
0.576014193513592
0.575905571857889
0.575797580361494
0.575690214950659
0.575583471551635
0.575477346090672
0.575371834494022
0.575266932687935
0.575162636598664
0.575058942152459
0.574955845275571
0.574853341894251
0.574751427934751
0.574650099323321
0.574549351986213
0.574449181849677
0.574349584839966
0.574250556883329
0.574152093906019
0.574054191834285
0.57395684659438
0.57386005432578
0.573763812020863
0.573668116885235
0.573572966124498
0.573478356944257
0.573384286550116
0.573290752147679
0.573197750942552
0.573105280140336
0.573013336946638
0.57292191856706
0.572831022207208
0.572740645072685
0.572650784369095
0.572561437302043
0.572472601077132
0.572384272899968
0.572296449976153
0.572209129511293
0.572122308710991
0.572035984780852
0.571950154926479
0.571864816353477
0.57177996626745
0.571695601874002
0.571611720378738
0.571528318987261
0.571445394905175
0.571362945338085
0.571280967491596
0.57119945857131
0.571118415782832
0.571037836331767
0.570957717423718
0.57087805626429
0.570798850059087
0.570720096013713
0.570641791333772
0.570563933224868
0.570486518892606
0.570409545542589
0.570333010380422
0.570256910611709
0.570181243442054
0.570106006077062
0.570031195722335
0.56995680958348
0.569882844866099
0.569809298775796
0.569736168518177
0.569663450408612
0.569591137201538
0.569519220761158
0.569447692951678
0.569376545637301
0.569305770682231
0.569235359950672
0.569165305306828
0.569095598614902
0.5690262317391
0.568957196543624
0.568888484892679
0.568820088650469
0.568751999681198
0.568684209849069
0.568616711018287
0.568549495053056
0.568482553817579
0.56841587917606
0.568349462992705
0.568283297131715
0.568217373457296
0.568151683833652
0.568086220124986
0.568020974195502
0.567955937909404
0.567891103130897
0.567826461724184
0.56776200555347
0.567697726482957
0.567633616376851
0.567569667099354
0.567505870514672
0.567442218487008
0.567378702880566
0.567315315559549
0.567252048388163
0.567188893230611
0.567125841951096
0.567062886413823
0.567000018482997
0.566937230022819
0.566874512897496
0.56681185897123
0.566749260108226
0.566686708172688
0.566624195028819
0.566561712540824
0.566499252572906
0.566436806989269
0.566374369471378
0.56631194096973
0.566249524252085
0.566187122086201
0.566124737239837
0.566062372480752
0.566000030576704
0.565937714295451
0.565875426404753
0.565813169672368
0.565750946866054
0.56568876075357
0.565626614102675
0.565564509681128
0.565502450256686
0.565440438597109
0.565378477470155
0.565316569643583
0.565254717885151
0.565192924962618
0.565131193643743
0.565069526696284
0.565007926887999
0.564946396986648
0.564884939759989
0.564823557975781
0.564762254401782
0.564701031805751
0.564639892955446
0.564578840618626
0.56451787756305
0.564457006556476
0.564396230366663
0.56433555176137
0.564274973508354
0.564214498375376
0.564154129130192
0.564093868540563
0.564033719374245
0.563973684398999
0.563913766382583
0.563853968092755
0.563794292297274
0.563734741763898
0.563675319260387
0.563616027554498
0.563556869413991
0.563497847606624
0.563438964900155
0.563380224062343
0.563321628193631
0.563263181725198
0.563204889420906
0.563146756044618
0.563088786360197
0.563030985131506
0.562973357122407
0.562915907096764
0.562858639818438
0.562801560051294
0.562744672559193
0.562687982105998
0.562631493455572
0.562575211371779
0.56251914061848
0.562463285959539
0.562407652158818
0.56235224398018
0.562297066187488
0.562242123544604
0.562187420815392
0.562132962763714
0.562078754153433
0.562024799748412
0.561971104312514
0.561917672609601
0.561864509403535
0.561811619458181
0.561759007537401
0.561706678405057
0.561654636825012
0.561602887561129
0.561551435377271
0.561500285037301
0.561449441305081
0.561398908944474
0.561348692719344
0.561298797393551
0.561249227730961
0.561199988495435
0.561151084450835
0.561102520361026
0.561054300989869
0.561006431101228
0.560958915458965
0.560911758826943
0.560864965969024
0.560818541649073
0.56077249063095
0.56072681767852
0.560681525359265
0.560636607455146
0.560592055551748
0.560547861234651
0.56050401608944
0.560460511701695
0.560417339656999
0.560374491540935
0.560331958939085
0.560289733437032
0.560247806620357
0.560206170074644
0.560164815385474
0.560123734138431
0.560082917919096
0.560042358313052
0.560002046905881
0.559961975283166
0.559922135030489
0.559882517733433
0.559843114977579
0.559803918348511
0.55976491943181
0.559726109813059
0.559687481077841
0.559649024811738
0.559610732600332
0.559572596029206
0.559534606683942
0.559496756150122
0.559459036013329
0.559421437859146
0.559383953273154
0.559346573840936
0.559309291148075
0.559272096780153
0.559234982322751
0.559197939361454
0.559160959481843
0.5591240342695
0.559087155310008
0.559050314188949
0.559013502491906
0.558976711804461
0.558939933712196
0.558903159800694
0.558866381655538
0.558829590862309
0.55879277900659
0.558755937673964
0.55871905997872
0.558682145149977
0.558645193945562
0.558608207123302
0.558571185441022
0.55853412965655
0.558497040527712
0.558459918812333
0.558422765268242
0.558385580653265
0.558348365725227
0.558311121241955
0.558273847961277
0.558236546641018
0.558199218039005
0.558161862913064
0.558124482021022
0.558087076120705
0.558049645969941
0.558012192326555
0.557974715948373
0.557937217593223
0.557899698018931
0.557862157983324
0.557824598244227
0.557787019559468
0.557749422686873
0.557711808384268
0.55767417740948
0.557636530520336
0.557598868474662
0.557561192030284
0.557523501945028
0.557485798976723
0.557448083883193
0.557410357422266
0.557372620351768
0.557334873429525
0.557297117413364
0.557259353061112
0.557221581130595
0.557183802379639
0.557146017566071
0.557108227447717
0.557070432782405
0.55703263432796
0.556994832842209
0.556957029082978
0.556919223808095
0.556881417775385];
mssThreshNeg = [mssThreshNeg(1:min(500,nTP)); mssThreshNeg(500)*ones(max(0,nTP-500),1)];
mssThreshPos = [mssThreshPos(1:min(500,nTP)); mssThreshPos(500)*ones(max(0,nTP-500),1)];
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS2D_p05(nTP)
%2D, alpha = 0.05
%NEW
mssThreshNeg = [...
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
0.181502318197934
0.18838154839312
0.195093150236193
0.201442121195694
0.207306808998423
0.212671284114308
0.217532557256877
0.221922548689565
0.225932950092577
0.229699916111634
0.233254869995021
0.236552670861111
0.239577858589862
0.242411883979074
0.245071420325144
0.24752759823054
0.249788728574198
0.251918804873189
0.253897354787951
0.255649897546368
0.257179156137925
0.258614575528493
0.260031836782165
0.261452589867952
0.262895955219871
0.264411374671013
0.265954267057598
0.267422783984008
0.268774834751154
0.27004432706212
0.271212742725752
0.27222691255208
0.273083282167612
0.273856763073577
0.274571478179446
0.275235026799138
0.275888246341044
0.276625829445396
0.277455885316465
0.278327934150515
0.279214852070928
0.280141531850763
0.281070372256589
0.28194568792854
0.282754176677657
0.283552543232945
0.284351822876984
0.285134951932275
0.285910522477779
0.286733405071101
0.287603074387924
0.28847846377164
0.289344518753971
0.290221884752678
0.291086096888505
0.291899333693971
0.292654765103181
0.293395567856581
0.294121038994455
0.294796425477663
0.295404928327597
0.295973031216056
0.296495243035509
0.296962554136571
0.297386091414761
0.297806251800542
0.298221785133029
0.298609627952852
0.298968848762741
0.299324796946564
0.299656009252775
0.299920405055219
0.300113936894473
0.300289897045359
0.300465642712047
0.300626347554218
0.300772734121281
0.300946839689796
0.301161105705468
0.301407626432376
0.301699293564754
0.302090771300807
0.302597620306922
0.303188096932729
0.303828706002585
0.304503647117815
0.305156782347571
0.305724734586455
0.306185632342498
0.30657911598172
0.306929385133769
0.307234447011637
0.30750320909756
0.307774567678586
0.308045026162675
0.308293662450211
0.308519494296455
0.308747270361001
0.308971869842679
0.309177841480646
0.309397032188751
0.309716334669726
0.310182234779652
0.310790790403923
0.311508527402952
0.312288439399305
0.313084740117098
0.313868425757027
0.314632283201258
0.31537604800628
0.316106106881946
0.316835567719803
0.317576740361338
0.31832627614131
0.319068027983544
0.319790445331619
0.320491848838877
0.321175898051449
0.321847797499791
0.322511776960654
0.323167535303506
0.32381425690187
0.32444734520928
0.3250569837267
0.325635209870627
0.326184914065035
0.326713069256028
0.327222064465545
0.32771389695669
0.328194976703951
0.328674256987075
0.329158154752876
0.329647656229768
0.330142502064348
0.33064243290321
0.331147189392948
0.331656512180156
0.332170141911429
0.332687819233362
0.333209284792549
0.333734279235584
0.334262543209063
0.334793817359579
0.335327842333727
0.335864358778102
0.336403107339297
0.336943828663909
0.33748626339853
0.338030152189756
0.338575235684181
0.3391212545284
0.339667949369007
0.340215060852596
0.340762329625763
0.341309496335101
0.341856301627205
0.34240248614867
0.34294779054609
0.34349195546606
0.344034721555173
0.344575829460026
0.345115019827211
0.345652033303324
0.346186610534959
0.346718492168711
0.347247418851174
0.347773131228943
0.348295369948611
0.348813875656775
0.349328389000027
0.349838650624963
0.350344401178178
0.350845381306264
0.351341331655818
0.351831992873434
0.352317105605706
0.352796410499229
0.353269648200596
0.353736559356404
0.354196884613245
0.354650364617715
0.355096803733521
0.355536261192821
0.355968859944884
0.356394722938982
0.356813973124385
0.357226733450362
0.357633126866185
0.358033276321124
0.358427304764448
0.35881533514543
0.359197490413338
0.359573893517444
0.359944667407017
0.360309935031328
0.360669819339648
0.361024443281247
0.361373929805394
0.361718401861362
0.362057982398419
0.362392794365836
0.362722960712884
0.363048604388834
0.363369848342954
0.363686815524517
0.363999628882791
0.364308411367048
0.364613285926558
0.364914375510592
0.365211803068419
0.36550569154931
0.365796163902535
0.366083343077365
0.366367352023071
0.366648313688922
0.366926351024189
0.367201586978142
0.367474144500052
0.367744146539188
0.368011716044823
0.368276975966225
0.368540049252665
0.368801058853414
0.369060127717742
0.369317378794919
0.369572935034215
0.369826919384902
0.370079454796249
0.370330664217527
0.370580670598006
0.370829596886957
0.371077545990059
0.371324540638632
0.371570583520403
0.371815677323101
0.372059824734454
0.37230302844219
0.372545291134039
0.372786615497727
0.373027004220985
0.373266459991538
0.373504985497117
0.37374258342545
0.373979256464264
0.374215007301289
0.374449838624251
0.374683753120881
0.374916753478905
0.375148842386053
0.375380022530053
0.375610296598632
0.37583966727952
0.376068137260445
0.376295709229134
0.376522385873317
0.376748169880722
0.376973063939076
0.377197070736108
0.377420192959548
0.377642433297122
0.377863794436559
0.378084279065588
0.378303889871937
0.378522629543333
0.378740500767507
0.378957506232185
0.379173648625096
0.379388930633969
0.379603354946531
0.379816924250512
0.380029641233639
0.380241508583641
0.380452528988246
0.380662705135182
0.380872039712178
0.381080535406962
0.381288194907262
0.381495020900807
0.381701016075325
0.381906183118544
0.382110524718193
0.382314041511462
0.382516725933393
0.38271856836849
0.382919559201255
0.383119688816193
0.383318947597807
0.3835173259306
0.383714814199078
0.383911402787743
0.384107082081098
0.384301842463648
0.384495674319897
0.384688568034347
0.384880513991502
0.385071502575867
0.385261524171945
0.385450569164239
0.385638627937254
0.385825690875492
0.386011748363457
0.386196790785654
0.386380808526586
0.386563791970756
0.386745731502668
0.386926617506826
0.387106440367734
0.387285190469894
0.387462858197811
0.387639433935989
0.387814908068931
0.38798927098114
0.388162513057121
0.388334624681377
0.388505596238412
0.388675418112729
0.388844080688832
0.389011574351225
0.389177889484411
0.389343016472895
0.389506945701178
0.389669667553767
0.389831172415163
0.389991450669871
0.390150492702394
0.390308288897236
0.390464829638901
0.390620105311892
0.390774106300713
0.390926822989868
0.39107824576386
0.391228371833239
0.391377225712739
0.391524838743139
0.391671242265219
0.391816467619758
0.391960546147538
0.392103509189336
0.392245388085933
0.392386214178109
0.392526018806644
0.392664833312316
0.392802689035906
0.392939617318193
0.393075649499958
0.393210816921979
0.393345150925037
0.393478682849911
0.393611444037382
0.393743465828227
0.393874779563229
0.394005416583165
0.394135408228816
0.394264785840962
0.394393580760382
0.394521824327855
0.394649547884163
0.394776782770084
0.394903560326398
0.395029911893884
0.395155868813323
0.395281462425494
0.395406724071177
0.395531685091152
0.395656376826198
0.395780830617095
0.395905077804623
0.396029149729561
0.396153077732689
0.396276893154787
0.396400627336635
0.396524311619012
0.396647977342697
0.396771655848472
0.396895378477115
0.397019176569406
0.397143081466124
0.397267124508051
0.397391337035964
0.397515750390644
0.397640395912871
0.397765295916105
0.397890436604526
0.398015795154997
0.39814134874438
0.398267074549535
0.398392949747324
0.39851895151461
0.398645057028253
0.398771243465115
0.398897488002058
0.399023767815944
0.399150060083633
0.399276341981989
0.399402590687871
0.399528783378143
0.399654897229665
0.3997809094193
0.399906797123908
0.400032537520351
0.400158107785491
0.40028348509619
0.40040864662931
0.400533569561711
0.400658231070255
0.400782608331805
0.400906678523221
0.401030418821365
0.4011538064031
0.401276818445286
0.401399432124785
0.401521624618459
0.401643373103169
0.401764654755777
0.401885446753144
0.402005726272133
0.402125470489605
0.402244656582421
0.402363261727443
0.402481263101533
0.402598637881552
0.402715363244362
0.402831416366824
0.402946774425801
0.403061414598153
0.403175314060743
0.403288449990431
0.40340079956408
0.403512339958552
0.403623048350707
0.403732901917407
0.403841884564866
0.403950007116704
0.404057287125893
0.404163742145404
0.40426938972821
0.404374247427282
0.404478332795592
0.404581663386113
0.404684256751815
0.404786130445671
0.404887302020653
0.404987789029732
0.40508760902588
0.405186779562069
0.405285318191272
0.40538324246646
0.405480569940604
0.405577318166677
0.40567350469765
0.405769147086496
0.405864262886186
0.405958869649692
0.406052984929986
0.40614662628004
0.406239811252825
0.406332557401314
0.406424882278478
0.40651680343729
0.40660833843072
0.406699504811742
0.406790320133326
0.406880801948445
0.406970967810071
0.407060835271175
0.407150421884729
0.407239745203705
0.407328822781075
0.407417672169811
0.407506310922885
0.407594756593268
0.407683026733933
0.407771138897851
0.407859110637994
0.407946959507334
0.408034703058843
0.408122358845493
0.408209944420255
0.408297477336101
0.408384975146004
0.408472455402935];
mssThreshPos = [...
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
0.688317643178081
0.684726982642884
0.68109891780178
0.677425966056172
0.673772923654433
0.670288565640082
0.667028329047343
0.663971485209905
0.661098796538868
0.658423236864972
0.655915783776832
0.653542912686538
0.651304724479748
0.649254881220427
0.647402722076526
0.64571892369454
0.644173861928544
0.642761044119332
0.641442764872315
0.640171172719201
0.638926424664184
0.637724234901367
0.636561063652285
0.635423767720294
0.634316560623178
0.633269160418724
0.632282509308338
0.631332603316206
0.630403937638469
0.629494519244589
0.628598325433644
0.627717703921463
0.626877206866974
0.626112399589143
0.625433382597822
0.624830074186726
0.624272663307602
0.623732990124725
0.623188654303903
0.622621882518039
0.622018409224427
0.621382154346502
0.620734159692872
0.620101273033383
0.619513606228945
0.619001390533913
0.618570172161691
0.618207471742387
0.61789543013713
0.617620008083951
0.617368819561361
0.617134673177448
0.616912162432114
0.61669548554837
0.616482633313128
0.61627408525523
0.616069495218099
0.61585972662781
0.615645374006389
0.615428467168467
0.615204001060492
0.614950113717697
0.614648007493866
0.614283787241613
0.613854907780228
0.613376822565723
0.61288079011633
0.612404917991244
0.611979710511832
0.611612841377266
0.611296763087735
0.611014387509404
0.610750623745419
0.610498967002745
0.610260704299795
0.610041184941574
0.609841195252448
0.609652559162008
0.60946936691501
0.609291220413442
0.609125401270486
0.60898090580048
0.60886056117208
0.608754670781189
0.608646662655495
0.608519212313296
0.608359580758184
0.608164909156993
0.607938762999321
0.607689273624184
0.607429855604158
0.607169871033368
0.606918580257458
0.606682763857289
0.606465265393582
0.606264217674601
0.606072732783467
0.605883775313072
0.605691920712663
0.605495671515588
0.605301720282764
0.605118361905657
0.604953104735767
0.604811833591361
0.604699271334609
0.604610098710317
0.604531919619297
0.604449657153941
0.604349371760523
0.604224907001748
0.604072736775639
0.603891192281183
0.603684263288198
0.603460619613105
0.603231458616728
0.60300509886874
0.60279081690687
0.60259239013901
0.602412497491601
0.602254141198669
0.602116774525276
0.601994020237082
0.601873106297988
0.601744314891167
0.601600986274804
0.601438352273111
0.601256835807114
0.6010618214076
0.600857272726772
0.600648222598096
0.600441127912726
0.600237228641353
0.600036435488577
0.599838696104781
0.599643958140351
0.59945216924567
0.599263277071123
0.599077229267095
0.598893973483968
0.598713457372128
0.598535628581959
0.598360434763844
0.598187823568169
0.598017742645318
0.597850139645674
0.597684962219622
0.597522158017546
0.597361674689831
0.597203459886861
0.59704746125902
0.596893626456692
0.596741903130262
0.596592238930113
0.59644458150663
0.596298878510197
0.5961550775912
0.59601312640002
0.595872972587044
0.595734563802655
0.595597847697237
0.595462771921176
0.595329284124854
0.595197331958656
0.595066863072967
0.594937825118171
0.594810165744652
0.594683832602793
0.594558773342981
0.594434935615598
0.594312267071029
0.594190715359658
0.59407022813187
0.593950753038048
0.593832237728578
0.593714629853843
0.593597877064227
0.593481927010115
0.59336672734189
0.593252225709939
0.593138369764643
0.593025107156388
0.592912392027208
0.592800204485731
0.592688531132239
0.592577358567011
0.592466673390325
0.592356462202461
0.5922467116037
0.592137408194319
0.5920285385746
0.591920089344821
0.591812047105262
0.591704398456202
0.591597129997921
0.591490228330699
0.591383680054814
0.591277471770546
0.591171590078175
0.591066021577981
0.590960752870242
0.590855770555238
0.590751061233249
0.590646611504555
0.590542407969434
0.590438437228166
0.590334685881031
0.590231140528308
0.590127787770276
0.590024614207216
0.589921606439406
0.589818751067127
0.589716034690657
0.589613443910276
0.589510965326264
0.5894085855389
0.589306291148464
0.589204068755234
0.589101904959491
0.588999786361514
0.588897699561582
0.588795631159976
0.588693567756974
0.588591495952856
0.588489402347901
0.588387273542389
0.5882850961366
0.588182856730813
0.588080541925307
0.587978138320362
0.587875632516257
0.587773011113272
0.587670265223054
0.587567404002717
0.587464441120744
0.587361390245618
0.58725826504582
0.587155079189832
0.587051846346137
0.586948580183218
0.586845294369556
0.586742002573634
0.586638718463934
0.586535455708938
0.586432227977129
0.586329048936988
0.586225932256999
0.586122891605642
0.586019940651402
0.585917093062759
0.585814362508197
0.585711762656197
0.585609307175242
0.585507009733813
0.585404884000394
0.585302943643466
0.585201202331512
0.585099673733014
0.584998371516454
0.584897309350315
0.584796500903079
0.584695959843227
0.584595699839243
0.584495734559609
0.584396077672806
0.584296742847318
0.584197743751626
0.584099094054212
0.58400080742356
0.583902897528151
0.583805378036467
0.583708262616991
0.583611564938205
0.583515298668591
0.583419477476631
0.583324115030809
0.583229224999606
0.583134821051503
0.583040916854985
0.582947526078532
0.582854662390628
0.582762339459753
0.582670569344341
0.582579357662615
0.582488708422753
0.582398625632927
0.582309113301314
0.582220175436088
0.582131816045425
0.582044039137498
0.581956848720483
0.581870248802555
0.581784243391889
0.581698836496659
0.581614032125041
0.58152983428521
0.58144624698534
0.581363274233606
0.581280920038183
0.581199188407247
0.581118083348971
0.581037608871532
0.580957768983103
0.58087856769186
0.580800009005978
0.580722096933631
0.580644835482995
0.580568228662244
0.580492280479554
0.580416994943099
0.580342376061053
0.580268427841593
0.580195154292893
0.580122559423128
0.580050647240473
0.579979421753102
0.579908886969191
0.579839046896914
0.579769905544447
0.579701466919964
0.57963373503164
0.57956671388765
0.57950040749617
0.579434819865373
0.579369955003435
0.579305816918531
0.579242409618836
0.579179737112525
0.579117803407771
0.579056612512752
0.57899616843564
0.578936475184612
0.57887753226413
0.578819321163809
0.57876181886955
0.578705002367256
0.57864884864283
0.578593334682173
0.578538437471188
0.578484133995778
0.578430401241845
0.57837721619529
0.578324555842016
0.578272397167927
0.578220717158923
0.578169492800907
0.578118701079782
0.57806831898145
0.578018323491813
0.577968691596773
0.577919400282233
0.577870426534095
0.577821747338262
0.577773339680635
0.577725180547118
0.577677246923611
0.577629515796019
0.577581964150242
0.577534568972184
0.577487307247746
0.577440155962831
0.577393092103341
0.577346092655179
0.577299134604247
0.577252194936447
0.577205250637681
0.577158278693852
0.577111256090863
0.577064159814614
0.57701696685101
0.576969654185951
0.576922198805341
0.576874577695081
0.576826767841075
0.576778746229223
0.576730489845429
0.576681975675596
0.576633180705624
0.576584081921417
0.576534656308877
0.576484880853906
0.576434732542406
0.576384193652116
0.576333267628115
0.57628196320732
0.576230289126646
0.57617825412301
0.576125866933326
0.576073136294511
0.576020070943481
0.575966679617151
0.575912971052437
0.575858953986256
0.575804637155522
0.575750029297153
0.575695139148063
0.575639975445168
0.575584546925385
0.575528862325629
0.575472930382816
0.575416759833862
0.575360359415682
0.575303737865193
0.57524690391931
0.57518986631495
0.575132633789027
0.575075215078458
0.575017618920159
0.574959854051046
0.574901929208033
0.574843853128038
0.574785634547976
0.574727282204763
0.574668804835314
0.574610211176546
0.574551509965375
0.574492709938715
0.574433819833484
0.574374848386596
0.574315804334968
0.574256696415516
0.574197533365154
0.574138323920801
0.57407907681937
0.574019800797778
0.57396050459294
0.573901196941774
0.573841886581193
0.573782582248115
0.573723292679455
0.573664026612129
0.573604792783052
0.573545598336405
0.573486444045419
0.573427329090593
0.573368252652422
0.573309213911404
0.573250212048034
0.573191246242811
0.573132315676229
0.573073419528787
0.57301455698098
0.572955727213306
0.572896929406261
0.572838162740342
0.572779426396045
0.572720719553867
0.572662041394306
0.572603391097857
0.572544767845017
0.572486170816283
0.572427599192152
0.57236905215312
0.572310528879684
0.572252028552341
0.572193550351587
0.572135093457919
0.572076657051834
0.572018240313829
0.5719598424244
0.571901462564043
0.571843099913256
0.571784753652535
0.571726422962378
0.571668107023279
0.571609805015737
0.571551516120248
0.571493239517309
0.571434974387416
0.571376719911066
0.571318475268756
0.571260239640982
0.571202012208242
0.571143792151031
0.571085578649847
0.571027370885185
0.570969168037544
0.570910969287419
0.570852773815308
0.570794580801706
0.570736389427111
0.57067819887202];
mssThreshNeg = [mssThreshNeg(1:min(500,nTP)); mssThreshNeg(500)*ones(max(0,nTP-500),1)];
mssThreshPos = [mssThreshPos(1:min(500,nTP)); mssThreshPos(500)*ones(max(0,nTP-500),1)];
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS2D_p01(nTP)
%2D, alpha = 0.01
mssThreshNeg = [...
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
0.0915486471971317
0.100671616999023
0.10955875894705
0.118011316449105
0.125887144108242
0.133131289897661
0.139737005238879
0.145705995027657
0.151112359984369
0.156116370113472
0.160762844472145
0.165040671537703
0.168986102045849
0.172745327012372
0.176396211132299
0.179890461183287
0.183179581516945
0.186324128001645
0.189312219341217
0.192057512725438
0.194543351409659
0.19686401647993
0.199027837443714
0.201007741228426
0.202815435121145
0.204569899703765
0.206285392283955
0.207922811901324
0.209488237078343
0.21106571111798
0.212656039210603
0.214201355442208
0.215664673494099
0.217100369103699
0.218518129108796
0.219842456946586
0.221042500405771
0.222194807337113
0.223323108866386
0.224392374718687
0.225378598561683
0.226312088482021
0.227196258649204
0.228021290134248
0.228795724532316
0.22956637008591
0.230333334413044
0.231051575162275
0.231718271951513
0.232411606349154
0.233167094538452
0.233969907270292
0.23479588018697
0.235654650167993
0.23650797621557
0.237283968701925
0.237939777825461
0.238514955122998
0.239019646431625
0.239455360292773
0.239859569531789
0.240339076079567
0.240962143803522
0.241736325218023
0.242646005137539
0.243673798661359
0.244705490801636
0.245582657313175
0.246225636624915
0.246662840085691
0.246937802051194
0.247087468664853
0.247185626269538
0.247345981475725
0.247611175374529
0.247967147763268
0.248420470864584
0.249039545486146
0.249836171851885
0.250761993534409
0.251753953378734
0.252764538789389
0.253707819505046
0.254510239535313
0.255160322959598
0.255686609596412
0.256097900337804
0.25638543292716
0.256570478785386
0.256721788766842
0.256879441756437
0.257065639645503
0.257316094144063
0.257670554948797
0.258118921083491
0.258619293978429
0.25913597887017
0.25966798909132
0.260202425460088
0.260726204395079
0.261244478486087
0.261789413423779
0.262370256151468
0.26298020787078
0.263605592409436
0.264243344259435
0.264898937926137
0.265578041020037
0.266287786325582
0.267045020853011
0.267867082118982
0.268758506631976
0.269717180148353
0.270718313478107
0.271719370284138
0.272685180432856
0.273603896855532
0.274477698940946
0.275311298454889
0.276115784214232
0.276894716268988
0.277653187680488
0.278404128778922
0.279161090188406
0.279924497201986
0.280700062659582
0.281506239802355
0.282349766064853
0.283227440466056
0.284124261058993
0.285024372076602
0.285912714842098
0.286786328624336
0.28764547314468
0.288490408124494
0.289321393285141
0.290138688347987
0.290942553034394
0.291733247065727
0.292511030163349
0.293276162048625
0.294028902442917
0.294769511067591
0.29549824764401
0.296215371893538
0.296921143537539
0.297615822297377
0.298299667894415
0.298972940050017
0.299635898485549
0.300288802922372
0.300931913081852
0.301565488685352
0.302189789454236
0.302805075109868
0.303411605373612
0.304009639966831
0.304599438610891
0.305181261027153
0.305755366936984
0.306322016061745
0.306881468122802
0.307433982841518
0.307979819939257
0.308519239137383
0.30905250015726
0.309579862720252
0.310101586547722
0.310617931361035
0.311129156881555
0.311635522830644
0.312137288929669
0.312634714899991
0.313128060462975
0.313617585339985
0.314103549252385
0.314586211921539
0.315065833068811
0.315542672415564
0.316016989683162
0.31648904459297
0.316959049690909
0.317427028821132
0.317892958652347
0.318356815853266
0.318818577092599
0.319278219039055
0.319735718361345
0.320191051728178
0.320644195808265
0.321095127270316
0.321543822783041
0.321990259015149
0.322434412635351
0.322876260312358
0.323315778714878
0.323752944511623
0.324187734371301
0.324620124962624
0.325050092954301
0.325477615015042
0.325902667813558
0.326325228018558
0.326745272298753
0.327162777322852
0.327577719759565
0.327990076277603
0.328399823545676
0.328806938232494
0.329211397006766
0.329613176537203
0.330012253492516
0.330408604541413
0.330802206352604
0.331193035594802
0.331581068936714
0.331966283047051
0.332348654594523
0.332728160247841
0.333104776675714
0.333478480546853
0.333849248529966
0.334217057293766
0.334581883506961
0.334943703838261
0.335302494956377
0.335658233530019
0.336010896227896
0.336360459718719
0.336706900671199
0.337050195754043
0.337390333782881
0.337727352161005
0.338061300438624
0.33839222816595
0.338720184893191
0.339045220170558
0.339367383548262
0.339686724576511
0.340003292805516
0.340317137785487
0.340628309066634
0.340936856199167
0.341242828733296
0.34154627621923
0.341847248207181
0.342145794247358
0.34244196388997
0.342735806685229
0.343027372183343
0.343316709934523
0.343603869488979
0.343888900396921
0.344171852208559
0.344452774474103
0.344731716743762
0.345008728567748
0.345283859496269
0.345557159079537
0.34582867686776
0.346098462411149
0.346366565259914
0.346633034964265
0.346897921074411
0.347161273140564
0.347423140712932
0.347683573341726
0.347942620577156
0.348200331969432
0.348456757068764
0.348711945425362
0.348965946589435
0.349218810111194
0.34947058554085
0.349721322428611
0.349971070324687
0.35021987877929
0.350467797342629
0.350714875564913
0.350961162996353
0.351206709187159
0.351451552286378
0.351695684838409
0.351939087986488
0.352181742873849
0.352423630643729
0.352664732439364
0.35290502940399
0.353144502680842
0.353383133413156
0.353620902744167
0.353857791817112
0.354093781775227
0.354328853761746
0.354562988919907
0.354796168392944
0.355028373324093
0.355259584856591
0.355489784133673
0.355718952298574
0.355947070494531
0.356174119864779
0.356400081552555
0.356624936701093
0.35684866645363
0.357071251953401
0.357292674343643
0.35751291476759
0.357731954368479
0.357949774289546
0.358166355674025
0.358381679665154
0.358595727406168
0.358808480040302
0.359019918710793
0.359230024560876
0.359438778733787
0.359646162372761
0.359852156621035
0.360056742621844
0.360259901518424
0.360461614454011
0.360661862571841
0.360860627015149
0.361057888927171
0.361253629451142
0.3614478297303
0.361640470907879
0.361831534127115
0.362021000531244
0.362208851263502
0.362395077878643
0.362579713577497
0.362762801972413
0.362944386675739
0.363124511299823
0.363303219457014
0.363480554759661
0.363656560820112
0.363831281250715
0.364004759663819
0.364177039671773
0.364348164886925
0.364518178921623
0.364687125388216
0.364855047899052
0.36502199006648
0.365187995502849
0.365353107820507
0.365517370631802
0.365680827549083
0.365843522184698
0.366005498150996
0.366166799060326
0.366327468525035
0.366487550157473
0.366647087569988
0.366806124374928
0.366964704184642
0.367122870611478
0.367280667267785
0.367438137765911
0.367595325718205
0.367752274737016
0.367909028434691
0.368065630423579
0.36822212431603
0.36837855372439
0.368534962261009
0.368691393538236
0.368847891168418
0.369004498763905
0.369161259937044
0.369318218300185
0.369475417465675
0.369632901045863
0.369790712653099
0.369948895899729
0.370107494398103
0.370266551760569
0.370426111599476
0.370586204357528
0.370746807798854
0.370907886517936
0.37106940510926
0.371231328167309
0.371393620286568
0.37155624606152
0.37171917008665
0.371882356956442
0.372045771265379
0.372209377607945
0.372373140578626
0.372537024771905
0.372700994782265
0.372865015204191
0.373029050632168
0.373193065660678
0.373357024884207
0.373520892897237
0.373684634294254
0.373848213669741
0.374011595618183
0.374174744734063
0.374337625611866
0.374500202846074
0.374662441031174
0.374824304761648
0.374985758631981
0.375146767236657
0.375307295170159
0.375467307026972
0.375626767401581
0.375785640888468
0.375943892082118
0.376101485577015
0.376258385967643
0.376414557848487
0.37656996581403
0.376724574458756
0.376878348377149
0.377031252163694
0.377183250412875
0.377334307719175
0.377484388677078
0.377633457881069
0.377781479925632
0.37792841940525
0.378074240914409
0.378218909047591
0.378362388399281
0.378504653545506
0.378645718988463
0.378785609211892
0.378924348699534
0.379061961935128
0.379198473402415
0.379333907585135
0.379468288967028
0.379601642031835
0.379733991263295
0.379865361145148
0.379995776161135
0.380125260794996
0.380253839530471
0.3803815368513
0.380508377241224
0.380634385183982
0.380759585163315
0.380884001662963
0.381007659166666
0.381130582158164
0.381252795121197
0.381374322539506
0.381495188896831
0.381615418676911
0.381735036363487
0.3818540664403
0.381972533391089
0.382090461699594
0.382207875849556
0.382324800324715
0.38244125960881
0.382557278185583
0.382672880538773
0.38278809115212
0.382902934509366
0.383017435094248
0.383131617390509
0.383245505881888
0.383359125052125
0.38347249938496
0.383585653364134
0.383698611473387
0.383811398196458
0.383924038017089
0.384036555419019
0.384148974885988
0.384261320901737
0.384373617950005
0.384485890514533];
mssThreshPos = [...
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
0.750265572468563
0.746217200245581
0.742117813924218
0.737971145291753
0.733868862858166
0.729990679197887
0.72642797020255
0.723151820426775
0.720100058054654
0.717243686891916
0.714539753569261
0.711942629982225
0.709437924910794
0.707063448960662
0.704827892167264
0.702742930416691
0.700809934456745
0.699002230389337
0.697251475783319
0.695506848752802
0.693755881259079
0.692005833213999
0.690250199400663
0.688488829435655
0.686749928971535
0.685094841765023
0.683543128639221
0.682076119929991
0.68068969839937
0.67939232180094
0.678169225133095
0.676997114155101
0.675870542406679
0.674798084022674
0.673787244132564
0.672840773668072
0.6719629173696
0.6711712197284
0.670481788364631
0.669888635448306
0.669352281682291
0.668821849278578
0.668272966170585
0.667694158042765
0.667080362161112
0.666443037485745
0.665806294582891
0.665191658158698
0.664605261628074
0.664038809345026
0.663475049814771
0.662891295378162
0.66227266327622
0.661602462278384
0.660878944212457
0.660119830056248
0.659361808983804
0.658654097553155
0.658023632321308
0.657479430340614
0.657022613472294
0.656639767181658
0.656311041066085
0.656003958270266
0.655679899899229
0.655305809459256
0.654863493266331
0.654356042971839
0.653810104486025
0.653268568000375
0.652770343902119
0.652330127806941
0.651938949223061
0.651572547174639
0.651209378257629
0.650831713846563
0.650431564273119
0.650015229474996
0.649592760916608
0.649176997882014
0.648775290746419
0.648385441168244
0.647996575812798
0.647606452025784
0.647227027965201
0.646880436291042
0.646585088989155
0.646345926231941
0.646159401222635
0.646013206093368
0.645893667166536
0.645787332011113
0.64568377692405
0.645585544725221
0.645512402866599
0.645481670944532
0.645497610094702
0.645551740336929
0.645642775059394
0.645756876297718
0.645865950633395
0.645926981080937
0.64591322017193
0.645833324540451
0.6457212646252
0.64560709332276
0.645503369754937
0.645403119626725
0.645289488284613
0.645151492243763
0.644985882199931
0.64479473590996
0.64458363298583
0.644346693193633
0.644070425128451
0.643748116315153
0.643382120158113
0.642982469896317
0.642566714319327
0.642152722007253
0.641756605306366
0.641392947963751
0.641076536621273
0.640818315156262
0.64061838927512
0.640466558943228
0.640345736458033
0.640235104749114
0.640121271598142
0.63999725911874
0.639860286735131
0.639714002494725
0.639559716993427
0.639397711794269
0.63922826846028
0.63905166855449
0.638868193639929
0.638678125279626
0.638481745036612
0.638279334473917
0.63807117515457
0.637857548641601
0.63763873649804
0.637415020286916
0.637186681571261
0.636954001914103
0.636717262878473
0.636476746027399
0.636232732923914
0.635985505131045
0.635735344211823
0.635482531729277
0.635227349246438
0.634970078326336
0.634711000532
0.63445039742646
0.634188550572747
0.633925741533889
0.633662251872917
0.63339836315286
0.633134356936749
0.632870514787613
0.632607118268483
0.632344448942388
0.632082788372357
0.631822418121421
0.63156361975261
0.631306674828953
0.631051864913481
0.630799471569223
0.630549776359209
0.630303060846469
0.630059606594032
0.62981969516493
0.629583608122191
0.629351627028845
0.629124033447922
0.628901108942453
0.628683135075466
0.628470393409992
0.628263165509061
0.628061661345803
0.627865804533751
0.62767544709654
0.627490441057802
0.627310638441172
0.627135891270282
0.626966051568769
0.626800971360264
0.626640502668401
0.626484497516815
0.626332807929139
0.626185285929007
0.626041783540053
0.62590215278591
0.625766245690212
0.625633914276593
0.625505010568687
0.625379386590128
0.625256894364548
0.625137385915583
0.625020713266865
0.624906728442029
0.624795283464708
0.624686230358536
0.624579421147147
0.624474707854175
0.624371942503253
0.624270977118015
0.624171663722095
0.624073854339126
0.623977400992743
0.623882155706579
0.623787970504268
0.623694697409444
0.62360218844574
0.62351029563679
0.623418871006228
0.623327766577688
0.623236834374803
0.623145926421208
0.623054894740535
0.622963591356419
0.622871868292494
0.622779577572393
0.622686571219751
0.6225927012582
0.622497819711374
0.622401778602908
0.622304429956435
0.622205625795589
0.622105251936466
0.622003329365013
0.62189991285964
0.621795057198756
0.621688817160771
0.621581247524094
0.621472403067135
0.621362338568304
0.621251108806009
0.621138768558661
0.621025372604668
0.620910975722441
0.62079563269039
0.620679398286922
0.620562327290449
0.620444474479379
0.620325894632123
0.620206642527089
0.620086772942687
0.619966340657327
0.619845400449419
0.619724007097371
0.619602215379593
0.619480080074496
0.619357655960488
0.619234997815978
0.619112160419378
0.618989198549095
0.618866166983539
0.618743120501121
0.61862011388025
0.618497201899334
0.618374439336784
0.61825188097101
0.61812958158042
0.618007595943424
0.617885978838433
0.617764785043854
0.617644069338099
0.617523886499575
0.617404291306694
0.617285338537864
0.617167082971495
0.617049579385997
0.616932882559779
0.61681704727125
0.616702128298821
0.6165881804209
0.616475258415897
0.616363417062222
0.616252695681619
0.616143071769166
0.616034507363278
0.61592696450237
0.615820405224854
0.615714791569145
0.615610085573656
0.615506249276802
0.615403244716996
0.615301033932652
0.615199578962184
0.615098841844006
0.614998784616532
0.614899369318175
0.61480055798735
0.61470231266247
0.61460459538195
0.614507368184203
0.614410593107643
0.614314232190684
0.614218247471739
0.614122600989223
0.61402725478155
0.613932170887133
0.613837311344387
0.613742638191724
0.61364811346756
0.613553699210308
0.613459357458381
0.613365050250194
0.613270739624161
0.613176387618695
0.613081956272211
0.612987407623121
0.612892703709841
0.612797806570784
0.612702678244363
0.612607280768993
0.612511576183088
0.612415526525061
0.612319093833326
0.612222240146298
0.61212492750239
0.612027117940016
0.611928773497589
0.611829856213525
0.611730328126235
0.611630151274136
0.611529287695639
0.61142769942916
0.611325359209217
0.611222282554745
0.611118495680787
0.611014024802383
0.610908896134574
0.610803135892401
0.610696770290905
0.610589825545126
0.610482327870107
0.610374303480889
0.610265778592511
0.610156779420015
0.610047332178442
0.609937463082833
0.60982719834823
0.609716564189672
0.609605586822201
0.609494292460858
0.609382707320685
0.609270857616721
0.609158769564008
0.609046469377587
0.6089339832725
0.608821337463786
0.608708558166487
0.608595671595644
0.608482703966298
0.60836968149349
0.608256630392261
0.608143576877652
0.608030547164704
0.607917567468457
0.607804664003954
0.607691862986234
0.60757919063034
0.607466673151311
0.607354336764189
0.607242207684016
0.607130312125831
0.607018676304676
0.606907326435591
0.606796288733619
0.606685589413799
0.606575254691174
0.606465310780783
0.606355783897668
0.60624670025687
0.60613808607343
0.606029967562388
0.605922370938787
0.605815318742873
0.605708818815719
0.605602875323605
0.60549749243281
0.605392674309615
0.605288425120299
0.605184749031141
0.605081650208421
0.604979132818419
0.604877201027414
0.604775859001685
0.604675110907513
0.604574960911177
0.604475413178957
0.604376471877132
0.604278141171981
0.604180425229785
0.604083328216823
0.603986854299374
0.603891007643718
0.603795792416136
0.603701212782905
0.603607272910306
0.603513976964619
0.603421329112123
0.603329333519098
0.603237994351823
0.603147315776578
0.603057301959643
0.602967957067296
0.602879285265819
0.602791290721489
0.602703977600587
0.602617350069393
0.602531412294186
0.602446168441246
0.602361622676852
0.602277779167284
0.602194642078821
0.602112215577743
0.60203050383033
0.601949511002861
0.601869241261616
0.601789698772874
0.601710887702916
0.60163281221802
0.601555476484466
0.601478884668534
0.601403040936504
0.601327949454654
0.601253611173497
0.601180014180471
0.601107143347248
0.601034983545497
0.600963519646891
0.600892736523098
0.600822619045791
0.600753152086641
0.600684320517317
0.600616109209491
0.600548503034833
0.600481486865014
0.600415045571706
0.600349164026578
0.600283827101303
0.600219019667549
0.600154726596989
0.600090932761293
0.600027623032131
0.599964782281175
0.599902395380095
0.599840447200563
0.599778922614249
0.599717806492823
0.599657083707957
0.599596739131321
0.599536757634586
0.599477124089423
0.599417823367502
0.599358840340496
0.599300159880073
0.599241766857905
0.599183646145664
0.599125782615018
0.59906816113764
0.599010766585201
0.59895358382937
0.598896597741819
0.598839793194219
0.59878315505824
0.598726668205553
0.598670317507829
0.598614087836739
0.598557964063953
0.598501931061143
0.598445973699978
0.59839007685213
0.59833422538927
0.598278404183069
0.598222598105197];
mssThreshNeg = [mssThreshNeg(1:min(500,nTP)); mssThreshNeg(500)*ones(max(0,nTP-500),1)];
mssThreshPos = [mssThreshPos(1:min(500,nTP)); mssThreshPos(500)*ones(max(0,nTP-500),1)];
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS3D_p20(nTP)
%3D, alpha = 0.2
%threshold curve parameters
turnPointsM = [20 60 200 500];
turnPointsP = [20 60 100 500];
slopeM = [0.001359327197525 0.000280732353905 0.000108640351462 0];
slopeP = [-0.000746906632969 -0.000348357342053 -0.000037074457479 0];
interseptM = [0.299405762325546 0.364121452942741 0.39853985343145 0.452860029162242];
interseptP = [0.609183824504497 0.585270867049586 0.554142578592106 0.535605349852791];
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS3D_p10(nTP)
%3D, alpha = 0.1
%threshold curve parameters
turnPointsM = [20 60 200 500];
turnPointsP = [20 50 100 500];
slopeM = [0.001587591010958 0.000334860802492 0.000129492806027 0];
slopeP = [-0.001033885285809 -0.000409579718459 -0.000060967307118 0];
interseptM = [0.258642983727984 0.333806796235989 0.374880395529001 0.439626798542322];
interseptP = [0.644618927677761 0.613403649310276 0.57854240817611 0.548058754617302];
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
%%%%%%%%%%%%%%%%%%%%%%%
function [mssThreshNeg,mssThreshPos] = threshMSS3D_p05(nTP)
%3D, alpha = 0.05
%threshold curve parameters
turnPointsM = [20 60 200 500];
turnPointsP = [20 50 80 500];
slopeM = [0.001897773535643 0.000390310143108 0.00014504631569 0];
slopeP = [-0.001281266825658 -0.000815336722161 -0.000079326637385 0];
interseptM = [0.217433363211081 0.307881166763189 0.356933932246803 0.429457090091877];
interseptP = [0.683369058696754 0.660072553521921 0.601191746739831 0.56152842804728];
% threshold curve evaluation
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
function [mssThreshNeg,mssThreshPos] = threshMSS3D_p01(nTP)
%3D, alpha = 0.01
%threshold curve parameters
turnPointsM = [20 50 200 500];
turnPointsP = [20 90 200 500];
slopeM = [0.00330864748993062 0.000607571513122873 0.000183704012624133 0];
slopeP = [-0.0011001388082068 -0.000401685416953439 -7.31736162754304e-05 0];
interseptM = [0.100955106735165 0.236008905575552 0.3207824056753 0.412634411987367];
interseptP = [0.747201850658008 0.684341045445206 0.618638685309604 0.582051877171889];
%threshold curve evaluation
[mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
slopeM,slopeP,interseptM,interseptP,nTP);
%%%%%%%%%%%%%%%%%%%%%%%
%% threshold curve evaluation subfunction
function [mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,...
turnPointsP,slopeM,slopeP,interseptM,interseptP,nTP)
%confined diffusion threshold
mssThreshNeg = NaN(1,turnPointsM(1)-1);
for i = 1 : length(turnPointsM)-1
x = turnPointsM(i) : turnPointsM(i+1)-1;
mssThreshNeg = [mssThreshNeg slopeM(i)*x+interseptM(i)]; %#ok<AGROW>
end
x = turnPointsM(end) : nTP;
mssThreshNeg = [mssThreshNeg slopeM(end)*x+interseptM(end)];
%directed diffusion threshold
mssThreshPos = NaN(1,turnPointsP(1)-1);
for i = 1 : length(turnPointsP)-1
x = turnPointsP(i) : turnPointsP(i+1)-1;
mssThreshPos = [mssThreshPos slopeP(i)*x+interseptP(i)]; %#ok<AGROW>
end
x = turnPointsP(end) : nTP;
mssThreshPos = [mssThreshPos slopeP(end)*x+interseptP(end)];
%% Old stuff
%alpha = 0.1
%NEW-OLD
%
% mssSlopeThreshM = [...
% 0.224574197458434
% 0.232559328197472
% 0.240357791324024
% 0.246731733302628
% 0.247450701750563
% 0.252840787466973
% 0.25825075827193
% 0.263944731727673
% 0.261076605760038
% 0.266197697287224
% 0.270178419497252
% 0.274606592489297
% 0.271376194203051
% 0.276085785031232
% 0.279378728963397
% 0.283219603898803
% 0.279654403572
% 0.283523320918118
% 0.286623354962519
% 0.290307212465952
% 0.286839418118361
% 0.288984857293021
% 0.291657181170727
% 0.294696186390912
% 0.291296036625286
% 0.294274998957638
% 0.297400403843315
% 0.300093544028548
% 0.296058303558528
% 0.298984599873247
% 0.300837413650959
% 0.30355875941062
% 0.300537241041706
% 0.303553899696145
% 0.304643574404516
% 0.306858640291308
% 0.304517227216722
% 0.305786651507545
% 0.307694416757531
% 0.309570228584845
% 0.307136751429856
% 0.308913831979711
% 0.311123413298387
% 0.312495448400378
% 0.309540038446651
% 0.310984660138447
% 0.312990691870498
% 0.31484605563284
% 0.312802168261889
% 0.314774386519118
% 0.316575956262911
% 0.318306178204258
% 0.31630405351131
% 0.317642463153647
% 0.319191262418683
% 0.320771521937496
% 0.318990933603294
% 0.320242585948214
% 0.321678022160499
% 0.323025857488633
% 0.321069206265912
% 0.32266446190648
% 0.32411447829162
% 0.325132246686479
% 0.322992583642119
% 0.323812952639433
% 0.32491153817459
% 0.325757675440457
% 0.323942358143971
% 0.324935715890395
% 0.326010916798555
% 0.32679931630416
% 0.324219560510537
% 0.325508461984927
% 0.326917158107201
% 0.328018604003
% 0.326232160746548
% 0.326961490754226
% 0.328028478958878
% 0.329102484331661
% 0.326973602201008
% 0.327895273457125
% 0.328838467242407
% 0.330114641324494
% 0.328381938906311
% 0.329645800011516
% 0.330929040311086
% 0.33169733354709
% 0.330143207685598
% 0.331222331707293
% 0.332107477065053
% 0.333050657036604
% 0.331447652894312
% 0.332245520588352
% 0.333301465387876
% 0.334480220741545
% 0.33275447586093
% 0.333340247514732
% 0.334356092454392
% 0.334701601312588
% 0.33305602342014
% 0.333571439651457
% 0.33452814107543
% 0.335136860203542
% 0.335675609552624
% 0.336156021072486
% 0.336796874380794
% 0.337566147391449
% 0.338197778725749
% 0.338805050847811
% 0.339452759437724
% 0.340165806025131
% 0.340815447803009
% 0.34137901878133
% 0.341845378660267
% 0.342643968821759
% 0.3430739292543
% 0.343628709867637
% 0.344030449547619
% 0.344820345837317
% 0.345385150217369
% 0.346192542181834
% 0.347150568143299
% 0.347177550210086
% 0.347851444610726
% 0.348210649507165
% 0.348983376323579
% 0.349605264937159
% 0.350069938939118
% 0.350855513247267
% 0.351711131132179
% 0.373419649246441
% 0.387597688801557
% 0.39757229927659
% 0.405899172670596
% 0.411717331218285
% 0.417404214745695
% 0.421737294870718];
%
% mssSlopeThreshP = [...
% 0.653147355047145
% 0.65132889440543
% 0.649679483704307
% 0.648255163538267
% 0.638266876704396
% 0.636400480426
% 0.634316151103251
% 0.633292570511596
% 0.628000687058611
% 0.627089206944701
% 0.62623067199019
% 0.624941557090645
% 0.621290363716996
% 0.620656480982382
% 0.619741271556897
% 0.618677674924027
% 0.615191927091456
% 0.614672321955848
% 0.613712500298175
% 0.612670790407075
% 0.610480153245027
% 0.609441707448592
% 0.608951952696789
% 0.608301812139239
% 0.606731156213953
% 0.606088800305914
% 0.605578390971856
% 0.604654925884508
% 0.603241283957719
% 0.602568191842692
% 0.602034107891529
% 0.601502966069536
% 0.600150178644757
% 0.599954439030026
% 0.599479698077799
% 0.598948995542751
% 0.598335083997344
% 0.597895946426736
% 0.597354513864994
% 0.597248773582739
% 0.596221321800998
% 0.596318548882293
% 0.595714725703501
% 0.595371138010948
% 0.594542730138966
% 0.59422339966226
% 0.594234483216372
% 0.594023321567637
% 0.59319228593867
% 0.593056926275941
% 0.59251157375923
% 0.592865374565399
% 0.592463004095721
% 0.592090365270891
% 0.591636608943834
% 0.59150254266524
% 0.591293152592306
% 0.590893017494081
% 0.5909590461544
% 0.590757060805986
% 0.59008876723898
% 0.589764691633642
% 0.589895615061654
% 0.589696629469499
% 0.588985888855342
% 0.588611243655994
% 0.588293218254769
% 0.587979469301641
% 0.58789107809767
% 0.587849365301885
% 0.587786718740068
% 0.587565596487811
% 0.587333249637887
% 0.587227795585252
% 0.586915982025173
% 0.586659657746996
% 0.586621219433631
% 0.58655825918332
% 0.586607820875872
% 0.586607465763016
% 0.58662852895352
% 0.586521269181149
% 0.586348328329744
% 0.585993194401089
% 0.58618479909948
% 0.585884464694563
% 0.585452261779234
% 0.585354836543565
% 0.585008661395476
% 0.58491999976014
% 0.584798659054402
% 0.584778811701729
% 0.584626919852783
% 0.584563759450215
% 0.584355849930455
% 0.584438181230103
% 0.584170392306253
% 0.583949214171273
% 0.583898991132972
% 0.583504243272866
% 0.583236345638302
% 0.583088957376113
% 0.583173276719509
% 0.583381836019792
% 0.583238013229126
% 0.583076490844526
% 0.582993336593433
% 0.582836284243519
% 0.582883399895619
% 0.582625669153702
% 0.582469259862584
% 0.582276169598837
% 0.581972357215994
% 0.581853795824746
% 0.581640888158356
% 0.581613113203099
% 0.581345099050163
% 0.581257980303522
% 0.581101202181861
% 0.581106338839736
% 0.581016085872333
% 0.580823745913101
% 0.580610008520541
% 0.580534960994928
% 0.580391660548403
% 0.58031338183263
% 0.580133695745293
% 0.579942962575481
% 0.579831508049998
% 0.579685855341995
% 0.579624446685547
% 0.573956870902088
% 0.569736067031574
% 0.566437014156808
% 0.563380261988323
% 0.560726567291193
% 0.558756111946602
% 0.556881403376681];
%
% %fit smoothing spline to threshold for confined, and interpolate
% splineFitM = csaps([20:150 200:50:500],mssSlopeThreshM,0.05);
% mssThreshNeg = [NaN(19,1); fnval(splineFitM,(20:min(500,nTP))')];
% mssThreshNeg = [mssThreshNeg; mssThreshNeg(end)*ones(max(0,nTP-500),1)];
%
% %fit smoothing spline to threshold for directed, and interpolate
% splineFitP = csaps([20:150 200:50:500],mssSlopeThreshP,0.05);
% mssThreshPos = [NaN(19,1); fnval(splineFitP,(20:min(500,nTP))')];
% mssThreshPos = [mssThreshPos; mssThreshPos(end)*ones(max(0,nTP-500),1)];
%
%OLD
% %threshold curve parameters
% turnPointsM = [20 50 200 500];
% turnPointsP = [20 50 100 500];
% slopeM = [0.002834926966999 0.00040315841383 0.000171843106892 0];
% slopeP = [-0.001737592454918 -0.000337743432604 -0.000073809631405 0];
% interseptM = [0.169732430047339 0.291320857705762 0.337583919093415 0.423505472539345];
% interseptP = [0.684919949284652 0.614927498168961 0.588534118049036 0.551629302346427];
%
% %threshold curve evaluation
% [mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
% slopeM,slopeP,interseptM,interseptP,nTP);
%alpha = 0.05
% %NEW-OLD
% mssSlopeThreshM = [...
% 0.17851880381419
% 0.1871730025546
% 0.196806677145191
% 0.204158488839211
% 0.206780204232365
% 0.21353652330535
% 0.218577893947974
% 0.223689904246123
% 0.222886969243971
% 0.228177104641715
% 0.233663785913629
% 0.239823425476981
% 0.237133768841959
% 0.241532853194731
% 0.245839766102515
% 0.24957179742297
% 0.247191406774247
% 0.25063478522449
% 0.255473793871516
% 0.25942938968348
% 0.254931053813695
% 0.257698407885778
% 0.259785064837744
% 0.263067478299164
% 0.260139812933828
% 0.263102433740553
% 0.26741770863631
% 0.269690336003608
% 0.26690500294172
% 0.269279550337408
% 0.272191467568818
% 0.274732878983067
% 0.271025801318721
% 0.273790820577884
% 0.275009039118091
% 0.27733986831005
% 0.273170815788627
% 0.27552019844457
% 0.277916692959511
% 0.280252910270569
% 0.276984038010674
% 0.280015495232136
% 0.281743742377518
% 0.284209925547003
% 0.281004644730678
% 0.283080116510187
% 0.28478778026557
% 0.286788305337569
% 0.284136898032984
% 0.285859418906338
% 0.288250931610169
% 0.289726410517383
% 0.287774661557119
% 0.290110792934316
% 0.291577670301109
% 0.29357715164282
% 0.291152695818162
% 0.292723741229145
% 0.294428705734903
% 0.296284348044087
% 0.294079793467697
% 0.296140523245772
% 0.29674929600504
% 0.298074416347853
% 0.296021373583597
% 0.297405492500614
% 0.298702824136024
% 0.299609274920867
% 0.29748524233694
% 0.298922935244787
% 0.300396681779992
% 0.301695357655895
% 0.298810183668257
% 0.29963335929538
% 0.300726622866354
% 0.302011538115881
% 0.299680870615641
% 0.300555178433349
% 0.301500035531218
% 0.302814475423732
% 0.300495033226206
% 0.301043161036347
% 0.302599629593006
% 0.304027996171868
% 0.30248430433422
% 0.30444287588424
% 0.305919003051943
% 0.307468262932956
% 0.305461650063214
% 0.305971272805794
% 0.307098804618111
% 0.308407242943892
% 0.306061329632763
% 0.307536501389644
% 0.308452662919498
% 0.309174325167614
% 0.307522529764362
% 0.30844934724475
% 0.309982854436816
% 0.310823818135481
% 0.308077360907993
% 0.308742662619394
% 0.309647805603832
% 0.310535528309306
% 0.311521329842896
% 0.312631583310933
% 0.313612564360577
% 0.31389812255908
% 0.314777820622545
% 0.315522433002325
% 0.316141244189818
% 0.316457655785337
% 0.317268181024399
% 0.31847940657704
% 0.319288068829374
% 0.319882469425602
% 0.320512345395368
% 0.321178015943994
% 0.321707707451331
% 0.322553495831334
% 0.323082097331497
% 0.323683265040748
% 0.324461676032448
% 0.32534199866625
% 0.325718062141354
% 0.326033897565515
% 0.326711715628724
% 0.327333834966668
% 0.327771217677864
% 0.328143860117064
% 0.328532260659434
% 0.354657628368557
% 0.370827311917658
% 0.382110290956925
% 0.391079023933105
% 0.397639366798427
% 0.403733669063502
% 0.40847212189647];
%
% mssSlopeThreshP = [...
% 0.687515318409466
% 0.685276840381168
% 0.682310561481955
% 0.680269322151898
% 0.670761438237813
% 0.668850618151345
% 0.667108714557779
% 0.665257873482051
% 0.659544959778331
% 0.658564624033264
% 0.656390823739982
% 0.655334669652393
% 0.649768630980414
% 0.648554688106195
% 0.64733206058663
% 0.646667472432749
% 0.643087317951418
% 0.64260041945609
% 0.642015155100117
% 0.641235202334666
% 0.638151435624193
% 0.637565208573271
% 0.636877368331779
% 0.636296240775795
% 0.633417881281766
% 0.632710957101116
% 0.632570137717717
% 0.631709198598634
% 0.630150270258322
% 0.629673211058848
% 0.629091453066231
% 0.628097808090468
% 0.626119162802377
% 0.625861483439657
% 0.624894318620891
% 0.624988101259194
% 0.62436785722323
% 0.623850770564247
% 0.623149817439354
% 0.623059336956896
% 0.622380571473926
% 0.621447945819085
% 0.620770711134517
% 0.620261382175091
% 0.618850229073762
% 0.618680695343894
% 0.618461413581746
% 0.618349907588212
% 0.617869911300813
% 0.617768116997836
% 0.617394090514407
% 0.617088958117533
% 0.617024690153813
% 0.616723442005675
% 0.616541996342523
% 0.61591454854244
% 0.616446171462252
% 0.615821903302535
% 0.615583614420069
% 0.614911353866245
% 0.615412525977224
% 0.61498245966794
% 0.614868983642384
% 0.614661432898643
% 0.614175193590041
% 0.613519810762257
% 0.612769342190297
% 0.61184095238639
% 0.611744329927023
% 0.611383112637346
% 0.611363426353595
% 0.611205148201553
% 0.610899733546305
% 0.610600033612161
% 0.610170428732971
% 0.609781040806253
% 0.609950334356465
% 0.609734506809841
% 0.609660766144285
% 0.609319162924641
% 0.609017707927956
% 0.608680454051921
% 0.60874235141495
% 0.608744169581691
% 0.608721091140155
% 0.608754744897785
% 0.608469360544911
% 0.608222630220981
% 0.608118605790019
% 0.607514470023567
% 0.607487244672096
% 0.607103519035866
% 0.606843905993827
% 0.606598992613698
% 0.606337998851331
% 0.606284692420762
% 0.606101286455309
% 0.605932723503751
% 0.605915261865577
% 0.605487021856316
% 0.605295643449468
% 0.605061653341967
% 0.605000933035169
% 0.604544765962621
% 0.604574912170413
% 0.604567842780715
% 0.604519690341924
% 0.604670488535696
% 0.604365550783769
% 0.60423921775345
% 0.604211047055473
% 0.603968717484945
% 0.60376937750576
% 0.603330777601416
% 0.603337530254406
% 0.602819862688282
% 0.602798789189528
% 0.602620510303525
% 0.60232890161527
% 0.602155822077865
% 0.601928969953038
% 0.602114550246144
% 0.601926971831044
% 0.601756943301308
% 0.601712245628021
% 0.601572471487258
% 0.601174723109729
% 0.601094172824707
% 0.600931866419486
% 0.600479838986798
% 0.600445339732039
% 0.593025847204398
% 0.587773525409125
% 0.582762155913914
% 0.578935961761433
% 0.576435335811663
% 0.573604611211088
% 0.570678214442582];
%
% %fit smoothing spline to threshold for confined, and interpolate
% splineFitM = csaps([20:150 200:50:500],mssSlopeThreshM,0.05);
% mssThreshNeg = [NaN(19,1); fnval(splineFitM,(20:min(500,nTP))')];
% mssThreshNeg = [mssThreshNeg; mssThreshNeg(end)*ones(max(0,nTP-500),1)];
%
% %fit smoothing spline to threshold for directed, and interpolate
% splineFitP = csaps([20:150 200:50:500],mssSlopeThreshP,0.05);
% mssThreshPos = [NaN(19,1); fnval(splineFitP,(20:min(500,nTP))')];
% mssThreshPos = [mssThreshPos; mssThreshPos(end)*ones(max(0,nTP-500),1)];
%
%OLD
% %threshold curve parameters
% turnPointsM = [20 60 200 500];
% turnPointsP = [20 50 100 500];
% slopeM = [0.002405756738527 0.000449948051639 0.000201793444222 0];
% slopeP = [-0.001937063703976 -0.00055853262239 -0.000095409685751 0];
% interseptM = [0.14034289465302 0.257691415866306 0.307322337349635 0.40821905946088];
% interseptP = [0.724427540398996 0.6555009863197 0.609188692655777 0.561483849780384];
%
% %threshold curve evaluation
% [mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
% slopeM,slopeP,interseptM,interseptP,nTP);
%alpha = 0.01
% %NEW
%
% mssSlopeThreshM = [...
% 0.0869293372917652
% 0.10150310109063
% 0.110458946420983
% 0.120032758710204
% 0.126841231786467
% 0.132788690031883
% 0.14111701308745
% 0.148781687505228
% 0.147252880610777
% 0.1553171871407
% 0.161442969632278
% 0.168518651326214
% 0.166927249661439
% 0.169713556194574
% 0.176200144207776
% 0.183683423129845
% 0.180635673565965
% 0.184448961101505
% 0.190868182290257
% 0.195653039305515
% 0.191252194839295
% 0.196634636222973
% 0.199200620916018
% 0.204966948598132
% 0.199034977778829
% 0.203794068441596
% 0.20708633211622
% 0.210645344880564
% 0.206685150305956
% 0.210066380391817
% 0.212767942989253
% 0.217133344918783
% 0.214240086206739
% 0.214772194218289
% 0.219544508270378
% 0.223154571256961
% 0.219011271077927
% 0.220986503689222
% 0.223488753108885
% 0.22619483084937
% 0.224194973560089
% 0.226178225803561
% 0.227406761136877
% 0.22940624261505
% 0.22740780991765
% 0.228409204872548
% 0.231202813362898
% 0.233544129082427
% 0.230112799676474
% 0.231477087623101
% 0.232771262427577
% 0.235423552060439
% 0.233230474179764
% 0.235004551394325
% 0.236837833499403
% 0.239925178524418
% 0.23643883383143
% 0.238525271507289
% 0.239494673183166
% 0.241644865269114
% 0.238530040907104
% 0.239074346365199
% 0.240429497038729
% 0.24249052420283
% 0.239960108432541
% 0.242624556563014
% 0.246548500562546
% 0.2482388052189
% 0.24607834810935
% 0.24631986902394
% 0.247705918615776
% 0.248557756204567
% 0.24508727005309
% 0.246167649594781
% 0.247958911621948
% 0.250106631141259
% 0.246563259798458
% 0.24787643982634
% 0.249487947306661
% 0.251642114429472
% 0.250353774128162
% 0.253105520989134
% 0.255154736842992
% 0.255458715941156
% 0.254481294256244
% 0.255204010387031
% 0.256705126931167
% 0.257862965000293
% 0.255465779313494
% 0.256394450063663
% 0.257255518773257
% 0.257428789612193
% 0.255947747739563
% 0.257097813890015
% 0.258153306063873
% 0.259761729031251
% 0.25848857662748
% 0.259757136368261
% 0.260472217040183
% 0.261636814313246
% 0.260411740732779
% 0.261597017320547
% 0.262143363765362
% 0.263296152893485
% 0.263778320432011
% 0.264210048669862
% 0.264881406247162
% 0.265848493156194
% 0.266330931199834
% 0.266657906952071
% 0.267913077915911
% 0.26820345160375
% 0.269306460578444
% 0.270893072017012
% 0.272270802899136
% 0.272963520827481
% 0.273538118818612
% 0.2747511616727
% 0.275010209388528
% 0.276188398325692
% 0.277080112179737
% 0.277732438576256
% 0.27797244279239
% 0.279312295496952
% 0.2803541422979
% 0.280282682708896
% 0.281410512555297
% 0.282017075629052
% 0.283308619337792
% 0.284034900517493
% 0.285391503662665
% 0.316483666592547
% 0.337051580502542
% 0.351205409454649
% 0.362210038176644
% 0.370424610260052
% 0.378363526295147
% 0.38448542532347];
%
% mssSlopeThreshP = [...
% 0.749099569987682
% 0.7473976079156
% 0.743637214208967
% 0.740737922870941
% 0.731319375604135
% 0.727351468795612
% 0.725821086646462
% 0.724427338813107
% 0.719386888932021
% 0.717229727042768
% 0.715003842279892
% 0.713661239816129
% 0.70805040499508
% 0.707575173780406
% 0.704508899778484
% 0.702332389387305
% 0.699574001331452
% 0.699606291151099
% 0.698068508021262
% 0.696006997617741
% 0.69318723992507
% 0.692211025007642
% 0.690722524577197
% 0.689626925037122
% 0.685502965263368
% 0.684181346563977
% 0.684085797605733
% 0.682477915849491
% 0.679973394790633
% 0.679208346225125
% 0.678649097784419
% 0.677296246097386
% 0.675792489830621
% 0.674689295772486
% 0.673758471165635
% 0.673234947975078
% 0.67193116470555
% 0.670740252773019
% 0.669718527533529
% 0.66955461847328
% 0.670152182453987
% 0.668977915409172
% 0.668319144494854
% 0.668084298910368
% 0.667357093497072
% 0.666388254370274
% 0.66545390766008
% 0.664901381763898
% 0.664473841187214
% 0.66383380074169
% 0.663806781930918
% 0.662659134136517
% 0.662663410366108
% 0.661975143813824
% 0.66121695408175
% 0.660557483414595
% 0.658701307455414
% 0.658318530191394
% 0.657983579766347
% 0.657075156133082
% 0.657022613723566
% 0.656310351440114
% 0.65618928817467
% 0.656120193055426
% 0.655970827393449
% 0.655720225002854
% 0.655341431833804
% 0.654715058668071
% 0.65374795119537
% 0.652704467781272
% 0.652328414113147
% 0.651964010931146
% 0.652102231331959
% 0.651595338799864
% 0.65138981440537
% 0.651197418745217
% 0.650417323616883
% 0.650134161247124
% 0.649449085923729
% 0.649007030471857
% 0.64851028166696
% 0.648626495681014
% 0.648281264406385
% 0.64784553574051
% 0.647145897739493
% 0.646541716627282
% 0.646485311136555
% 0.646116242821253
% 0.646179150612063
% 0.646008189636678
% 0.645919205713778
% 0.646035469268067
% 0.646143872962349
% 0.645460631374134
% 0.645272904691685
% 0.645075912479232
% 0.645907654922474
% 0.645137363484374
% 0.645459383449963
% 0.64527969781766
% 0.646256769526858
% 0.646695608933769
% 0.646483957551041
% 0.64566752089819
% 0.645367142013856
% 0.645195097085672
% 0.645278667798355
% 0.645587562820339
% 0.645445730695456
% 0.645223775994562
% 0.645147789749733
% 0.644474033445713
% 0.644398112861634
% 0.644541802659769
% 0.64424830538345
% 0.643874996092825
% 0.643572221938234
% 0.642951955763577
% 0.642535125193078
% 0.642109381986806
% 0.641787294207641
% 0.641336662383792
% 0.640832914882883
% 0.640613536204056
% 0.640506272345644
% 0.640334611469348
% 0.640560495345698
% 0.640354449811109
% 0.640160366304582
% 0.640200028639871
% 0.639742976987077
% 0.628255004260535
% 0.622209478136329
% 0.616361655002305
% 0.611428918785076
% 0.60592195201232
% 0.601327582857087
% 0.598222885543451];
%
% %fit smoothing spline to threshold for confined, and interpolate
% splineFitM = csaps([20:150 200:50:500],mssSlopeThreshM,0.05);
% mssThreshNeg = [NaN(19,1); fnval(splineFitM,(20:min(500,nTP))')];
% mssThreshNeg = [mssThreshNeg; mssThreshNeg(end)*ones(max(0,nTP-500),1)];
%
% %fit smoothing spline to threshold for directed, and interpolate
% splineFitP = csaps([20:150 200:50:500],mssSlopeThreshP,0.05);
% mssThreshPos = [NaN(19,1); fnval(splineFitP,(20:min(500,nTP))')];
% mssThreshPos = [mssThreshPos; mssThreshPos(end)*ones(max(0,nTP-500),1)];
%
%OLD
% %threshold curve parameters
% turnPointsM = [20 50 150 500];
% turnPointsP = [20 60 200 500];
% slopeM = [0.00435441385708182 0.000812259003939792 0.000273699080289468 0];
% slopeP = [-0.00172943051183377 -0.000284948443095389 -0.000153857046768591 0];
% interseptM = [-0.00562462883719271 0.171483113819909 0.252267102367457 0.389116642512191];
% interseptP = [0.779260212544801 0.692591288420498 0.666373009155138 0.589444485770843];
%
% %threshold curve evaluation
% [mssThreshNeg,mssThreshPos] = getThreshCurve(turnPointsM,turnPointsP,...
% slopeM,slopeP,interseptM,interseptP,nTP);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
movieViewer.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/movieViewer.m
| 54,923 |
utf_8
|
c1ba064b9ee8edd24181bce7b51e7b7a
|
function mainFig = movieViewer(MO,varargin)
%MOVIEVIEWER creates a graphical interface to display the analysis output of a MovieObject
%
% h = movieViewer(MD)
% movieViewer(MD, [1 2]);
% h = movieViewer(ML, 'movieIndex', 3);
%
% This function reads the components of a MovieObject including all
% drawable anlaysis results (determined by the getDrawableOutput method).
% It then generates a graphical interface allowing to switch between image
% results and toggle on/off overlay components. Additionally, two
% interfaces can be created: one to control movie display options (for the
% image and the various overlays) and one interface showing the different
% graph results (i.e. results displayed on separate figures).
%
% Input
%
% MO - the MovieObject to be displayed. If a MovieList is input, the main
% interface will have a popupmenu allowing to switch between the list and
% all the movie components.
%
% procId - Optional. An array containing the indices of the processes
% which output should be displayed by default. Default: empty.
%
% Optional parameters in param/value pairs
%
% movieIndex - Integer. For movie list input. If 0 display the movie list
% and its analysis. If non-zero, set the index of the movie to be
% displayed. Default: 0.
%
% Output:
%
% mainFig - the handle of the main control interface
%
% See also: graphViewer, movieViewerOptions
%
% Sebastien Besson, July 2012 (last modified Nov 2012)
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Check input
ip = inputParser;
ip.addRequired('MO',@(x) isa(x,'MovieObject'));
ip.addOptional('procId',[],@isnumeric);
ip.addOptional('refresher',[],@isstr);
ip.addParamValue('movieIndex',0,@isscalar);
ip.parse(MO,varargin{:});
if strcmp(ip.Results.refresher, '1') == 1
movieviewerRefresher(MO);
return
end
% Generate the main figure
mainFig=figure('Name','Viewer','Position',[0 0 200 200],...
'NumberTitle','off','Tag','figure1','Toolbar','none','MenuBar','none',...
'Color',get(0,'defaultUicontrolBackgroundColor'),'Resize','off',...
'DeleteFcn', @(h,event) deleteViewer());
userData=get(mainFig,'UserData');
set(mainFig, 'UserData', userData);
% Read the MovieObject and process index input
if isa(ip.Results.MO,'MovieList')
userData.ML=ip.Results.MO;
userData.movieIndex=ip.Results.movieIndex;
if userData.movieIndex~=0
userData.MO=ip.Results.MO.getMovies{userData.movieIndex};
else
userData.MO=ip.Results.MO;
end
userData.procId = ip.Results.procId;
if ~isempty(ip.Results.procId)
procId = userData.MO.getProcessIndex(class(userData.ML.processes_{ip.Results.procId}));
else
procId = ip.Results.procId;
end
else
userData.MO=ip.Results.MO;
procId=ip.Results.procId;
end
% Check existence of viewer interface
if isfield('MO', 'isMock') && ~MO.isMock()
h=findobj(0,'Name','Viewer');
h2 = findobj('Name', 'hcsview');
if ~isempty(h), delete(h); end
if ~isempty(h2), delete(h2); end
else
hPosition = 10;
end
% Read all drawable output
validProcId= find(cellfun(@(x) ismember('getDrawableOutput',methods(x)) &...
x.success_,userData.MO.processes_));
validProc=userData.MO.processes_(validProcId);
% Classify movieData processes by type (image, overlay or graph)
getOutputType = @(type) cellfun(@(x) any(~cellfun(@isempty,...
regexp({x.getDrawableOutput.type},type,'once','start'))), validProc);
isImageProc = getOutputType('image');
imageProc=validProc(isImageProc);
imageProcId = validProcId(isImageProc);
isOverlayProc = getOutputType('[oO]verlay');
overlayProc = validProc(isOverlayProc);
overlayProcId = validProcId(isOverlayProc);
isGraphProc =getOutputType('[gG]raph');
graphProc=validProc(isGraphProc);
graphProcId = validProcId(isGraphProc);
% Create series of anonymous function to generate process controls
createProcText= @(panel,i,j,pos,name) uicontrol(panel,'Style','text',...
'Position',[10 pos 250 20],'Tag',['text_process' num2str(i)],...
'String',name,'HorizontalAlignment','left','FontWeight','bold');
createOutputText= @(panel,i,j,pos,text) uicontrol(panel,'Style','text',...
'Position',[40 pos 200 20],'Tag',['text_process' num2str(i) '_output'...
num2str(j)],'String',text,'HorizontalAlignment','left');
createProcButton= @(panel,i,j,k,pos) uicontrol(panel,'Style','radio',...
'Position',[200+30*k pos 20 20],'Tag',['radiobutton_process' num2str(i) '_output'...
num2str(j) '_channel' num2str(k)]);
createChannelBox= @(panel,i,j,k,pos,varargin) uicontrol(panel,'Style','checkbox',...
'Position',[200+30*k pos 20 20],'Tag',['checkbox_process' num2str(i) '_output'...
num2str(j) '_channel' num2str(k)],varargin{:});
createMovieBox= @(panel,i,j,pos,name,varargin) uicontrol(panel,'Style','checkbox',...
'Position',[40 pos 200 25],'Tag',['checkbox_process' num2str(i) '_output'...
num2str(j)],'String',[' ' name],varargin{:});
%% Image panel creation
if isa(userData.MO,'MovieData')
imagePanel = uibuttongroup(mainFig,'Position',[0 0 1/2 1],...
'Title','Image','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),...
'Units','pixels','Tag','uipanel_image');
% Create controls for switching between process image output
hPosition=10;
nProc = numel(imageProc);
for iProc=nProc:-1:1;
output=imageProc{iProc}.getDrawableOutput;
validChan = imageProc{iProc}.checkChannelOutput;
validOutput = find(strcmp({output.type},'image'));
for iOutput=validOutput(end:-1:1)
createOutputText(imagePanel,imageProcId(iProc),iOutput,hPosition,output(iOutput).name);
arrayfun(@(x) createProcButton(imagePanel,imageProcId(iProc),iOutput,x,hPosition),...
find(validChan));
hPosition=hPosition+20;
end
createProcText(imagePanel,imageProcId(iProc),iOutput,hPosition,imageProc{iProc}.getName);
hPosition=hPosition+20;
end
% Create controls for selecting channels (raw image)
hPosition=hPosition+10;
uicontrol(imagePanel,'Style','radio','Position',[10 hPosition 200 20],...
'Tag','radiobutton_channels','String',' Raw image','Value',1,...
'HorizontalAlignment','left','FontWeight','bold');
arrayfun(@(i) uicontrol(imagePanel,'Style','checkbox',...
'Position',[200+30*i hPosition 20 20],...
'Tag',['checkbox_channel' num2str(i)],'Value',i<4,...
'Callback',@(h,event) redrawChannel(h,guidata(h))),...
1:numel(userData.MO.channels_));
hPosition=hPosition+20;
uicontrol(imagePanel,'Style','text','Position',[120 hPosition 100 20],...
'Tag','text_channels','String','Channels');
arrayfun(@(i) uicontrol(imagePanel,'Style','text',...
'Position',[200+30*i hPosition 20 20],...
'Tag',['text_channel' num2str(i)],'String',i),...
1:numel(userData.MO.channels_));
else
imagePanel=-1;
end
%% Overlay panel creation
if ~isempty(overlayProc)
overlayPanel = uipanel(mainFig,'Position',[1/2 0 1/2 1],...
'Title','Overlay','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),...
'Units','pixels','Tag','uipanel_overlay');
% Create overlay options
hPosition=10;
nProc = numel(overlayProc);
for iProc=nProc:-1:1;
output=overlayProc{iProc}.getDrawableOutput;
% Create checkboxes for movie overlays
validOutput = find(strcmp({output.type},'movieOverlay'));
for iOutput=validOutput(end:-1:1)
createMovieBox(overlayPanel,overlayProcId(iProc),iOutput,hPosition,output(iOutput).name,...
'Callback',@(h,event) redrawOverlay(h,guidata(h)));
hPosition=hPosition+20;
end
% Create checkboxes for channel-specific overlays
validOutput = find(strcmp({output.type},'overlay'));
for iOutput=validOutput(end:-1:1)
validChan = overlayProc{iProc}.checkChannelOutput;
createOutputText(overlayPanel,overlayProcId(iProc),iOutput,hPosition,output(iOutput).name);
arrayfun(@(x) createChannelBox(overlayPanel,overlayProcId(iProc),iOutput,x,hPosition,...
'Callback',@(h,event) redrawOverlay(h,guidata(h))),find(validChan));
hPosition=hPosition+20;
end
createProcText(overlayPanel,overlayProcId(iProc),iOutput,hPosition,overlayProc{iProc}.getName);
hPosition=hPosition+20;
end
if ~isempty(overlayProc)
uicontrol(overlayPanel,'Style','text','Position',[120 hPosition 100 20],...
'Tag','text_channels','String','Channels');
arrayfun(@(i) uicontrol(overlayPanel,'Style','text',...
'Position',[200+30*i hPosition 20 20],...
'Tag',['text_channel' num2str(i)],'String',i),...
1:numel(userData.MO.channels_));
end
else
overlayPanel=-1;
end
%% Get image/overlay panel size and resize them
imagePanelSize = getPanelSize(imagePanel);
overlayPanelSize = getPanelSize(overlayPanel);
panelsLength = max(500,imagePanelSize(1)+overlayPanelSize(1));
panelsHeight = max([imagePanelSize(2),overlayPanelSize(2)]);
% Resize panel
if ishandle(imagePanel)
set(imagePanel,'Position',[10 panelsHeight-imagePanelSize(2)+10 ...
imagePanelSize(1) imagePanelSize(2)],...
'SelectionChangeFcn',@(h,event) redrawImage(guidata(h)))
end
if ishandle(overlayPanel)
set(overlayPanel,'Position',[imagePanelSize(1)+10 panelsHeight-overlayPanelSize(2)+10 ...
overlayPanelSize(1) overlayPanelSize(2)]);
end
%% Create movie panel
moviePanel = uipanel(mainFig,...
'Title','','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),...
'Units','pixels','Tag','uipanel_movie','BorderType','none');
if isa(userData.MO,'MovieData')
hPosition=10;
% Create controls for scrollling through the movie if regular moviedata
MO = userData.MO;
if isa(MO,'MovieData') && ~MO.isHCS()
uicontrol(moviePanel, 'Style', 'togglebutton','String', 'Run movie',...
'Position', [10 hPosition 100 20],'Callback',@(h,event) runMovie(h,guidata(h)));
% Create control button for exporting figures and movie (cf Francois' GUI)
uicontrol(moviePanel, 'Style', 'checkbox','Tag','checkbox_saveFrames',...
'Value',0,'String', 'Save frames','Position', [150 hPosition 100 20]);
uicontrol(moviePanel, 'Style', 'checkbox','Tag','checkbox_saveMovie',...
'Value',0,'String', 'Save movie','Position', [250 hPosition 100 20]);
uicontrol(moviePanel, 'Style', 'popupmenu','Tag','popupmenu_movieFormat',...
'Value',1,'String', {'MOV';'AVI'},'Position', [350 hPosition 100 20]);
hPosition = hPosition+30;
uicontrol(moviePanel,'Style','text','Position',[10 hPosition 50 15],...
'String','Frame','Tag','text_frame','HorizontalAlignment','left');
uicontrol(moviePanel,'Style','edit','Position',[70 hPosition 30 20],...
'String','1','Tag','edit_frame','BackgroundColor','white',...
'HorizontalAlignment','left',...
'Callback',@(h,event) redrawScene(h,guidata(h)));
uicontrol(moviePanel,'Style','text','Position',[100 hPosition 40 15],...
'HorizontalAlignment','left',...
'String',['/' num2str(userData.MO.nFrames_)],'Tag','text_frameMax');
uicontrol(moviePanel,'Style','slider',...
'Position',[150 hPosition panelsLength-160 20],...
'Value',1,'Min',1,'Max',userData.MO.nFrames_,...
'SliderStep',[1/double(userData.MO.nFrames_) 5/double(userData.MO.nFrames_)],...
'Tag','slider_frame','BackgroundColor','white',...
'Callback',@(h,event) redrawScene(h,guidata(h)));
%%%% 3D slider starts %%%%
if MO.is3D()
hPosition = hPosition+30;
uicontrol(moviePanel, 'Style', 'togglebutton','String', 'Show in 3D',...
'Position', [10 hPosition 100 20],'Callback',@(h,event) render3DMovie(h,guidata(h)));
uicontrol(moviePanel, 'Style', 'checkbox','Tag','checkbox_saveplane',...
'Value',0,'String', 'Save plane','Position', [150 hPosition 100 20]);
uicontrol(moviePanel, 'Style', 'checkbox','Tag','checkbox_saveRender',...
'Value',0,'String', 'Save render','Position', [250 hPosition 100 20]);
uicontrol(moviePanel, 'Style', 'popupmenu','Tag','popupmenu_3DmovieFormat',...
'Value',1,'String', {'MOV';'AVI'},'Position', [350 hPosition 100 20]);
hPosition = hPosition+30;
uicontrol(moviePanel,'Style','text','Position',[10 hPosition 50 15],...
'String','Depth','Tag','text_depth','HorizontalAlignment','left');
uicontrol(moviePanel,'Style','edit','Position',[70 hPosition 30 20],...
'String','1','Tag','edit_depth','BackgroundColor','white',...
'HorizontalAlignment','left',...
'Callback',@(h,event) redrawScene(h,guidata(h)));
uicontrol(moviePanel,'Style','text','Position',[100 hPosition 40 15],...
'HorizontalAlignment','left',...
'String',['/' num2str(userData.MO.zSize_)],'Tag','text_frameMax');
uicontrol(moviePanel,'Style','slider',...
'Position',[150 hPosition panelsLength-160 20],...
'Value',1,'Min',1,'Max',userData.MO.zSize_,...
'SliderStep',[1/double(userData.MO.zSize_) 5/double(userData.MO.zSize_)],...
'Tag','slider_depth','BackgroundColor','white',...
'Callback',@(h,event) redrawScene(h,guidata(h)));
end
%%% 3D slider ends %%%%
hPosition = hPosition+30;
elseif isa(MO,'MovieData') && MO.isMock()
% shtext = uicontrol(moviePanel, 'Style', 'text', 'Position', [10 60 panelsLength-100 20], ...
% 'String', ['Preview for site ', MO.channels_(1,1).getGenericName(MO.channels_(1,1).hcsPlatestack_{1}, 'site_on')], ...
% 'HorizontalAlignment','left');
if size(MO.mockMD_.index,1) > 1
%hPosition = hPosition+20;
uicontrol(moviePanel,'Style','text','Position',[10 hPosition 50 15],...
'String','Frame','Tag','text_frame','HorizontalAlignment','left');
uicontrol(moviePanel,'Style','text','Position',[70 hPosition 80 15],...
'String','1','Tag','edit_frame','BackgroundColor','white',...
'HorizontalAlignment','left',...
'Callback',@(h,event) redrawScene(h,guidata(h)));
uicontrol(moviePanel,'Style','text','Position',[150 hPosition 40 15],...
'HorizontalAlignment','left',...
'String',['/' num2str(userData.MO.nFrames_)],'Tag','text_frameMax');
uicontrol(moviePanel,'Style','slider',...
'Position',[200 hPosition panelsLength-160 20],...
'Value',1,'Min',1,'Max',userData.MO.nFrames_,...
'SliderStep',[1/double(userData.MO.nFrames_) 5/double(userData.MO.nFrames_)],...
'Tag','slider_frame','BackgroundColor','white',...
'Callback',@(h,event) redrawScene(h,guidata(h)));
end
hPosition = hPosition+30;
else
hcshid = uicontrol('Parent', mainFig, 'Visible', 'off', 'Tag','slider_frame');
hcsview = figure('Name','hcsview','Position',[100 100 200 200],...
'NumberTitle','off','Tag','hcsview','Toolbar','none','MenuBar','none',...
'Color',get(0,'defaultUicontrolBackgroundColor'),'Resize','off',...
'DeleteFcn', @(h,event) deleteViewer());
hcsuserData.lastclick = '0';
hcsuserData.MO = MO;
set(hcsview, 'UserData', hcsuserData);
dcolor = get(0, 'DefaultUIControlBackgroundColor');
platestack = MO.channels_(1,1).hcsPlatestack_;
wellflag = MO.channels_(1,1).hcsFlags_.wellF;
% gui for a plate
% hp = uipanel('Parent', moviePanel,'Title','Plate Inspector','FontSize',10,...
% 'Position',[10 320 22*((size(wellflag,1)+2)) 22*((size(wellflag,2)+2))]);
hp = uipanel('Parent', hcsview,'Title','Plate Inspector','FontSize',10,...
'Position',[.04 .29 .9 .68]);
% gui for well
hpp = uipanel('Parent', hcsview,'Title','Well Inspector','FontSize',10,...
'Position',[.04 .04 .4 .24]);
pwgc = 0; % plate-well good count
for i2 = 1:size(wellflag,1)
for i3 = 1:size(wellflag,2)
if i2 == 1
hth = uicontrol('Parent', hp, 'Style', 'Text', 'Position', [i3*22+22,370, 22,22],...
'String', num2str(i3));
end
if i3 == 1
htv = uicontrol('Parent', hp, 'Style', 'Text', 'Position', [22,365-i2*22, 22,22],...
'String', char(i2-1+'A'));
end
if wellflag(i2, i3) == 0
hb = uicontrol('Parent', hp,'Style','pushbutton', 'Position', [i3*22+22,370-i2*22,22,22]...
,'Tag','slider_frame',...
'enable', 'off'); %
elseif wellflag(i2, i3) == 1
pwgc = pwgc + 1;
if pwgc == 1
ipr1 = i2; ipr2 = i3;
end
if ~isempty(platestack{i2-ipr1+1, i3-ipr2+1}{1,1})
wellname = MO.channels_(1,1).getGenericName(platestack{i2-ipr1+1, i3-ipr2+1}{1,1});
else
wellname = '';
end
hb = uicontrol('Parent', hp,'Style','pushbutton', 'Position', [i3*22+22,370-i2*22,22,22]...
,'TooltipString',[wellname, ...
',',num2str(length(platestack{i2-ipr1+1, i3-ipr2+1})), ...
' Sites'],'Tag', wellname,...
'UserData', dcolor, ...
'enable', 'on',...
'Callback', {@updatewellp, platestack, [i2-ipr1+1, i3-ipr2+1], hpp, mainFig, MO});
% setting the colors while building the plate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if MO.hasMock()
mMDsite_number = [];
for imMDt = 1:size(MO.mMDparent_,1)
if size(MO.mMDparent_{imMDt},1) > 1 % multi-frame mockMD
for imMD = 1:size(MO.mMDparent_{imMDt},1)
if i2-ipr1+1 == MO.mMDparent_{imMDt}(imMD, 1) && i3-ipr2+1 == MO.mMDparent_{imMDt}(imMD,2)
set(hb,'BackgroundColor','cyan');
set(hb,'UserData',[0 1 1]);
mMDsite_number = [mMDsite_number; MO.mMDparent_{imMDt}(imMD,3)];
set(hb, 'Callback', {@updatewellp, platestack, {i2-ipr1+1, i3-ipr2+1, mMDsite_number, 1, MO.mMDparent_{imMDt,2}}, hpp, mainFig, MO});
end
end
else
if i2-ipr1+1 == MO.mMDparent_{imMDt}(1) && i3-ipr2+1 == MO.mMDparent_{imMDt}(2)
set(hb,'BackgroundColor','green');
set(hb,'UserData',[0 1 0]);
mMDsite_number = [mMDsite_number; MO.mMDparent_{imMDt}(3)];
set(hb, 'Callback', {@updatewellp, platestack, {i2-ipr1+1, i3-ipr2+1, mMDsite_number, 0, MO.mMDparent_{imMDt,2}}, hpp, mainFig, MO});
end
end
end
end
end
end
end
uicontrol('Parent', hpp, 'Style', 'pushbutton', 'Position', [299 55 180 25], ...
'String', 'Preprocess Controls ', ...
'Callback', {@togglecontrol, MO});
if ~isempty(MO.mMDparent_)
uicontrol('Parent', hpp, 'Style', 'pushbutton', 'Position', [299 30 180 25], ...
'String', 'Flush Controls', ...
'Callback', {@flushcontrol, MO});
end
handles = guihandles(hcsview);
guidata(handles.hcsview, handles);
set(handles.hcsview,'UserData',hcsuserData);
end
end
% Create movie location edit box
uicontrol(moviePanel,'Style','text','Position',[10 hPosition 40 20],...
'String','Movie','Tag','text_movie');
% Create popupmenu if input is a MovieList, else list the movie path
if isa(ip.Results.MO,'MovieList')
moviePaths = cellfun(@getDisplayPath,userData.ML.getMovies,'UniformOutput',false);
movieIndex=0:numel(moviePaths);
uicontrol(moviePanel,'Style','popupmenu','Position',[60 hPosition panelsLength-110 20],...
'String',vertcat(getDisplayPath(ip.Results.MO),moviePaths(:)),'UserData',movieIndex,...
'Value',find(userData.movieIndex==movieIndex),...
'HorizontalAlignment','left','BackgroundColor','white','Tag','popup_movie',...
'Callback',@(h,event) switchMovie(h,guidata(h)));
if userData.movieIndex==0, set(findobj(moviePanel,'Tag','text_movie'),'String','List'); end
else
uicontrol(moviePanel,'Style','edit','Position',[60 hPosition panelsLength-110 20],...
'String',getDisplayPath(ip.Results.MO),...
'HorizontalAlignment','left','BackgroundColor','white','Tag','edit_movie');
end
% Add help button
set(0,'CurrentFigure',mainFig)
hAxes = axes('Units','pixels','Position',[panelsLength-50 hPosition 20 20],...
'Tag','axes_help', 'Parent', moviePanel);
icons = loadLCCBIcons();
Img = image(icons.questIconData);
set(hAxes, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'), 'visible','off','YDir','reverse');
set(Img,'ButtonDownFcn',@icon_ButtonDownFcn, 'UserData', struct('class','movieViewer'));
% Add copyrigth
hPosition = hPosition+30;
uicontrol(moviePanel,'Style','text','Position',[10 hPosition panelsLength-100 20],...
'String',getLCCBCopyright(),'Tag','text_copyright',...
'HorizontalAlignment','left');
% Get overlay panel size
moviePanelSize = getPanelSize(moviePanel);
moviePanelHeight =moviePanelSize(2);
if isa(MO, 'MovieData')
if ~isempty(MO.channels_(1,1).hcsFlags_)
if max(size(MO.channels_(1,1).hcsFlags_.wellF)) ~= 0
hcsl = 22*size(MO.channels_(1,1).hcsFlags_.wellF,2)+150;
hcsh = 22*size(MO.channels_(1,1).hcsFlags_.wellF,1)+250;
else
hcsl = 0;
hcsh = 0;
end
panelsLength = max(panelsLength, hcsl);
end
end
%% Resize panels and figure
sz=get(0,'ScreenSize');
maxWidth = panelsLength+20;
maxHeight = panelsHeight+moviePanelHeight;
if isa(MO, 'MovieData')
if MO.isMock()
maxHeight = 190;
end
if MO.isHCS() && ~MO.isMock()
set(hcsview,'Position',[sz(3)/50 sz(4)/2 maxWidth hcsh]);
end
end
set(mainFig,'Position',[sz(3)/50 sz(4)/3.8 maxWidth maxHeight]);
set(moviePanel,'Position',[10 panelsHeight+10 panelsLength moviePanelHeight]);
% Update handles structure and attach it to the main figure
handles = guihandles(mainFig);
guidata(handles.figure1, handles);
% Create redraw callbacks
userData.redrawImageFcn = @(varargin) redrawImage(handles, varargin{:});
userData.redrawOverlaysFcn = @(varargin) redrawOverlays(handles, varargin{:});
userData.getFigure = @(figName) getFigure(handles, figName);
set(handles.figure1,'UserData',userData);
% Create options figure
if isa(userData.MO, 'MovieData')
optionsFig = movieViewerOptions(mainFig);
set(optionsFig, 'Tag', 'optionsFig');
end
%% Add additional panel for independent graphs
if ~isempty(graphProc)
graphFig = graphViewer(mainFig, graphProc, graphProcId, intersect(graphProcId,procId));
set(graphFig, 'Tag', 'graphFig');
end
%% Set up default parameters
% Auto check input process
for i=intersect(procId,validProcId)
h=findobj(mainFig,'-regexp','Tag',['(\w)_process' num2str(i) '_output1.*'],...
'-not','Style','text');
set(h,'Value',1);
end
if isa(MO, 'MovieData')
if userData.MO.isMock()
redrawScene(handles.figure1, handles);
end
end
% Update the image and overlays
if isa(userData.MO,'MovieData') && ~userData.MO.isHCS()
redrawScene(handles.figure1, handles);
end
% function slider_callback(src,eventdata,panel)
% pos=get(panel,'Position');
% pos(2)=(1-pos(4))*get(src,'Value');
% set(panel,'Position',pos)
% uistack(panel,'top');
function displayPath= getDisplayPath(movie)
[~,endPath] = fileparts(movie.getPath);
displayPath = fullfile(endPath,movie.getFilename);
function switchMovie(hObject,handles)
userData=get(handles.figure1,'UserData');
props=get(hObject,{'UserData','Value'});
if isequal(props{1}(props{2}), userData.movieIndex),return;end
if isempty(userData.procId)
movieViewer(userData.ML,'movieIndex',props{1}(props{2}));
else
movieViewer(userData.ML,userData.procId,'movieIndex',props{1}(props{2}));
end
function size = getPanelSize(hPanel)
if ~ishandle(hPanel), size=[0 0]; return; end
a=get(get(hPanel,'Children'),'Position');
P=vertcat(a{:});
size = [max(P(:,1)+P(:,3))+10 max(P(:,2)+P(:,4))+20];
function runMovie(hObject,handles)
userData = get(handles.figure1, 'UserData');
nFrames = userData.MO.nFrames_;
startFrame = get(handles.slider_frame,'Value');
if startFrame == nFrames, startFrame =1; end;
if get(hObject,'Value')
action = 'Stop';
else action = 'Run';
end
set(hObject,'String',[action ' movie']);
% Get frame/movies export status
saveMovie = get(handles.checkbox_saveMovie,'Value');
saveFrames = get(handles.checkbox_saveFrames,'Value');
props = get(handles.popupmenu_movieFormat,{'String','Value'});
movieFormat = props{1}{props{2}};
if saveMovie,
moviePath = fullfile(userData.MO.outputDirectory_,['Movie.' lower(movieFormat)]);
end
% Initialize movie output
if saveMovie && strcmpi(movieFormat,'mov')
MakeQTMovie('start',moviePath);
MakeQTMovie('quality',.9)
end
if saveMovie && strcmpi(movieFormat,'avi')
movieFrames(1:nFrames) = struct('cdata', [],'colormap', []);
end
% Initialize frame output
if saveFrames;
fmt = ['%0' num2str(ceil(log10(nFrames))) 'd'];
frameName = @(frame) ['frame' num2str(frame, fmt) '.tif'];
fpath = [userData.MO.outputDirectory_ filesep 'Frames'];
mkClrDir(fpath);
fprintf('Generating movie frames: ');
end
for iFrame = startFrame : nFrames
if ~get(hObject,'Value'), return; end % Handle pushbutton press
set(handles.slider_frame, 'Value',iFrame);
redrawScene(hObject, handles);
drawnow;
% Get current frame for frame/movie export
hFig = getFigure(handles,'Movie');
if saveMovie && strcmpi(movieFormat,'mov'), MakeQTMovie('addfigure'); end
if saveMovie && strcmpi(movieFormat,'avi'), movieFrames(iFrame) = getframe(hFig); end
if saveFrames
print(hFig, '-dtiff', fullfile(fpath,frameName(iFrame)));
fprintf('\b\b\b\b%3d%%', round(100*iFrame/(nFrames)));
end
end
% Finish frame/movie creation
if saveFrames; fprintf('\n'); end
if saveMovie && strcmpi(movieFormat,'mov'), MakeQTMovie('finish'); end
if saveMovie && strcmpi(movieFormat,'avi'), movie2avi(movieFrames,moviePath); end
% Reset button
set(hObject,'String', 'Run movie', 'Value', 0);
function render3DMovie(hObject,handles)
userData = get(handles.figure1, 'UserData');
nPlane = userData.MO.zSize_;
startFrame = get(handles.slider_depth,'Value');
if startFrame == nPlane, startFrame =1; end;
if get(hObject,'Value')
action = 'Stop';
else action = 'Run';
end
set(hObject,'String',[action ' Rendering']);
% Get frame/movies export status
saveMovie = get(handles.checkbox_saveRender,'Value');
saveFrames = get(handles.checkbox_saveplane,'Value');
props = get(handles.popupmenu_3DmovieFormat,{'String','Value'});
movieFormat = props{1}{props{2}};
if saveMovie,
moviePath = fullfile(userData.MO.outputDirectory_,['Movie.' lower(movieFormat)]);
end
% Initialize movie output
if saveMovie && strcmpi(movieFormat,'mov')
MakeQTMovie('start',moviePath);
MakeQTMovie('quality',.9)
end
if saveMovie && strcmpi(movieFormat,'avi')
movieFrames(1:nPlane) = struct('cdata', [],'colormap', []);
end
% Initialize frame output
if saveFrames;
fmt = ['%0' num2str(ceil(log10(nPlane))) 'd'];
frameName = @(frame) ['depth' num2str(frame, fmt) '.tif'];
fpath = [userData.MO.outputDirectory_ filesep 'Depths'];
mkClrDir(fpath);
fprintf('Generating movie depth: ');
end
for iFrame = startFrame : nPlane
if ~get(hObject,'Value'), return; end % Handle pushbutton press
set(handles.slider_depth, 'Value',iFrame);
redrawScene(hObject, handles);
drawnow;
% Get current frame for frame/movie export
hFig = getFigure(handles,'Movie');
if saveMovie && strcmpi(movieFormat,'mov'), MakeQTMovie('addfigure'); end
if saveMovie && strcmpi(movieFormat,'avi'), movieFrames(iFrame) = getframe(hFig); end
if saveFrames
print(hFig, '-dtiff', fullfile(fpath,frameName(iFrame)));
fprintf('\b\b\b\b%3d%%', round(100*iFrame/(nPlane)));
end
end
% Finish frame/movie creation
if saveFrames; fprintf('\n'); end
if saveMovie && strcmpi(movieFormat,'mov'), MakeQTMovie('finish'); end
if saveMovie && strcmpi(movieFormat,'avi'), movie2avi(movieFrames,moviePath); end
% Reset button
set(hObject,'String', 'Show 3D', 'Value', 0);
function redrawScene(hObject, handles)
userData = get(handles.figure1, 'UserData');
% Retrieve the value of the selected image
if userData.MO.isHCS()
if userData.MO.isMock()
if size(userData.MO.mockMD_.index,1) == 1;
frameNumber = 1;
else
frameNumber = get(handles.slider_frame,'Value');
end
else
frameNumber = get(handles.slider_frame,'Value');
if max(size(frameNumber)) ~= 1
frameNumber = frameNumber{1};
if frameNumber == 0;
frameNumber = 1;
end
end
end
elseif strcmp(get(hObject,'Tag'),'edit_frame')
frameNumber = str2double(get(handles.edit_frame, 'String'));
else
frameNumber = get(handles.slider_frame, 'Value');
end
frameNumber=round(frameNumber);
frameNumber = min(max(frameNumber,1),userData.MO.nFrames_);
%3D depth aquisition
if userData.MO.is3D() && strcmp(get(hObject,'Tag'),'edit_depth')
ZNr = str2double(get(handles.edit_depth,'String'));
elseif userData.MO.is3D()
ZNr = round(get(handles.slider_depth,'Value'));
end
% Set the slider and editboxes values
if ~userData.MO.isHCS()
set(handles.edit_frame,'String',frameNumber);
set(handles.slider_frame,'Value',frameNumber);
if userData.MO.is3D()
set(handles.edit_depth,'String',ZNr);
set(handles.slider_depth,'Value',ZNr);
end
end
if userData.MO.isMock() && size(userData.MO.mockMD_.index,1) > 1
set(handles.slider_frame,'Value',frameNumber);
set(handles.edit_frame,'String',userData.MO.channels_(1,1).getGenericName(userData.MO.channels_(1,1).hcsPlatestack_{frameNumber}, 'site_on'));
if userData.MO.isMock() && size(userData.MO.mockMD_.index,1) == 1
set(handles.slider_frame,'Value',1);
end
end
% Update the image and overlays
redrawImage(handles);
redrawOverlays(handles);
function h= getFigure(handles,figName)
h = findobj(0,'-regexp','Name',['^' figName '$']);
if ~isempty(h), figure(h); return; end
%Create a figure
if strcmp(figName,'Movie')
userData = get(handles.figure1,'UserData');
sz=get(0,'ScreenSize');
nx=userData.MO.imSize_(2);
ny=userData.MO.imSize_(1);
sc = max(1, max(nx/(.9*sz(3)), ny/(.9*sz(4))));
h = figure('Position',[sz(3)*.2 sz(4)*.2 nx/sc ny/sc],...
'Name',figName,'NumberTitle','off','Tag','viewerFig',...
'UserData',handles.figure1);
% figure options for movie export
iptsetpref('ImShowBorder','tight');
set(h, 'InvertHardcopy', 'off');
set(h, 'PaperUnits', 'Points');
set(h, 'PaperSize', [nx ny]);
set(h, 'PaperPosition', [0 0 nx ny]); % very important
set(h, 'PaperPositionMode', 'auto');
% set(h,'DefaultLineLineSmoothing','on');
% set(h,'DefaultPatchLineSmoothing','on');
axes('Parent',h,'XLim',[0 userData.MO.imSize_(2)],...
'YLim',[0 userData.MO.imSize_(1)],'Position',[0.05 0.05 .9 .9]);
set(handles.figure1,'UserData',userData);
% Set the zoom properties
hZoom=zoom(h);
hPan=pan(h);
set(hZoom,'ActionPostCallback',@(h,event)panZoomCallback(h));
set(hPan,'ActionPostCallback',@(h,event)panZoomCallback(h));
else
h = figure('Name',figName,'NumberTitle','off','Tag','viewerFig');
end
function redrawChannel(hObject,handles)
% Callback for channels checkboxes to avoid 0 or more than 4 channels
channelBoxes = findobj(handles.figure1,'-regexp','Tag','checkbox_channel*');
nChan=numel(find(arrayfun(@(x)get(x,'Value'),channelBoxes)));
if nChan==0, set(hObject,'Value',1); elseif nChan>3, set(hObject,'Value',0); end
redrawImage(handles)
function redrawImage(handles,varargin)
imageTag = get(get(handles.uipanel_image,'SelectedObject'),'Tag');
% Get the figure handle
drawFig = getFigure(handles,'Movie');
userData=get(handles.figure1,'UserData');
if userData.MO.isMock() && size(userData.MO.mockMD_.index,1) == 1
frameNr = 1;
else
frameNr = get(handles.slider_frame,'Value');
end
if userData.MO.is3D()
ZNr = get(handles.slider_depth, 'Value');
else
ZNr = 1;
end
% Use corresponding method depending if input is channel or process output
channelBoxes = findobj(handles.figure1,'-regexp','Tag','checkbox_channel*');
[~,index]=sort(arrayfun(@(x) get(x,'Tag'),channelBoxes,'UniformOutput',false));
channelBoxes =channelBoxes(index);
if strcmp(imageTag,'radiobutton_channels')
set(channelBoxes,'Enable','on');
chanList=find(arrayfun(@(x)get(x,'Value'),channelBoxes));
userData.MO.channels_(chanList).draw(frameNr,ZNr,varargin{:});
displayMethod = userData.MO.channels_(chanList(1)).displayMethod_;
else
set(channelBoxes,'Enable','off');
% Retrieve the id, process nr and channel nr of the selected imageProc
tokens = regexp(imageTag,'radiobutton_process(\d+)_output(\d+)_channel(\d+)','tokens');
procId=str2double(tokens{1}{1});
outputList = userData.MO.processes_{procId}.getDrawableOutput;
iOutput = str2double(tokens{1}{2});
output = outputList(iOutput).var;
iChan = str2double(tokens{1}{3});
userData.MO.processes_{procId}.draw(iChan,frameNr,'output',output,varargin{:});
displayMethod = userData.MO.processes_{procId}.displayMethod_{iOutput,iChan};
end
optFig = findobj(0,'-regexp','Name','Movie options');
if ~isempty(optFig),
userData = get(optFig,'userData');
userData.setImageOptions(drawFig, displayMethod)
end
function panZoomCallback(varargin)
% Find if options figure exist
optionsFig = findobj(0,'-regexp','Tag', 'optionsFig');
if ~isempty(optionsFig)
% Reset the scaleBar
handles = guidata(optionsFig);
scalebarCallback = get(handles.edit_imageScaleBar,'Callback');
timeStampCallback = get(handles.checkbox_timeStamp,'Callback');
scalebarCallback(optionsFig);
timeStampCallback(optionsFig);
end
function redrawOverlays(handles)
if ~isfield(handles,'uipanel_overlay'), return; end
overlayBoxes = findobj(handles.uipanel_overlay,'-regexp','Tag','checkbox_process*');
checkedBoxes = logical(arrayfun(@(x) get(x,'Value'),overlayBoxes));
overlayTags=arrayfun(@(x) get(x,'Tag'),overlayBoxes(checkedBoxes),...
'UniformOutput',false);
for i=1:numel(overlayTags),
redrawOverlay(handles.(overlayTags{i}),handles)
end
function redrawOverlay(hObject,handles) %%%% need configuration for 3D.
userData=get(handles.figure1,'UserData');
if userData.MO.isMock()
if size(userData.MO.mockMD_.index,1) == 1;
frameNr = 1;
else
frameNr = get(handles.slider_frame,'Value');
end
else
frameNr = get(handles.slider_frame,'Value');
end
if max(size(frameNr)) > 1
frameNr = frameNr{1};
end
overlayTag = get(hObject,'Tag');
% Get figure handle or recreate figure
movieFig = findobj(0,'Name','Movie');
if isempty(movieFig), redrawScene(hObject, handles); return; end
figure(movieFig);
% Retrieve the id, process nr and channel nr of the selected imageProc
tokens = regexp(overlayTag,'^checkbox_process(\d+)_output(\d+)','tokens');
procId=str2double(tokens{1}{1});
outputList = userData.MO.processes_{procId}.getDrawableOutput;
iOutput = str2double(tokens{1}{2});
output = outputList(iOutput).var;
% Discriminate between channel-specific processes annd movie processes
tokens = regexp(overlayTag,'_channel(\d+)$','tokens');
if ~isempty(tokens)
iChan = str2double(tokens{1}{1});
inputArgs={iChan,frameNr};
graphicTag =['process' num2str(procId) '_channel'...
num2str(iChan) '_output' num2str(iOutput)];
else
iChan = [];
inputArgs={frameNr};
graphicTag = ['process' num2str(procId) '_output' num2str(iOutput)];
end
% Get options figure handle
optFig = findobj(0,'-regexp','Name','Movie options');
if ~isempty(optFig), userData = get(optFig, 'userData'); end
% Draw or delete the overlay depending on the checkbox value
if get(hObject,'Value')
if ~isempty(optFig),
options = userData.getOverlayOptions();
else
options = {};
end
if userData.MO.is3D() % && userData.MO.processes_{procId}.is3DP()
ZNr = get(handles.slider_depth,'Value');
userData.MO.processes_{procId}.draw(inputArgs{:},'output',output,... % draw method of process object modificiation for 3D!!!
options{:}, 'iZ',ZNr);
else
userData.MO.processes_{procId}.draw(inputArgs{:},'output',output,... % draw method of process object modificiation for 3D!!!
options{:});
end
else
h=findobj('Tag',graphicTag);
if ~isempty(h), delete(h); end
end
% Get display method and update option status
if isempty(iChan),
displayMethod = userData.MO.processes_{procId}.displayMethod_{iOutput};
else
displayMethod = userData.MO.processes_{procId}.displayMethod_{iOutput,iChan}; %% 3D depth specific process???
end
if ~isempty(optFig),
userData.setOverlayOptions(displayMethod)
end
function deleteViewer()
tags = {'viewerFig','optionsFig','graphFig'};
for i = 1:numel(tags)
h = findobj(0,'-regexp','Tag', tags{i});
if ~isempty(h), delete(h); end
end
function updatewellp(src, eventdata, platestack, indw, hpp, mainFig, MO)
dcolor = get(0, 'DefaultUIControlBackgroundColor');
siteflags = MO.channels_(1,1).hcsFlags_.siteF;
hcsview = findobj('Name', 'hcsview');
userData = get(hcsview, 'UserData');
userData = userData(1);
if strcmp(userData.lastclick, '0') ~= 1
lwell = findobj('Tag', userData.lastclick);
original_color = get(lwell, 'UserData'); % original color saved in each well's UserData
set(lwell, 'BackgroundColor', original_color);
end
if size(indw,2) == 2
indw = {indw(1), indw(2)};
end
pst = platestack{indw{1}, indw{2}};
cwell = findobj('Tag', MO.channels_(1,1).getGenericName(pst{1,1}));
% save last clicked well into userdata, in order to be refreshed.
userData.lastclick = MO.channels_(1,1).getGenericName(pst{1,1});
set(hcsview, 'UserData', userData);
current_well_type = get(cwell, 'UserData');
if sum(current_well_type - [0 1 0]) == 0
set(cwell, 'BackgroundColor', [0.5 1 0.5]);
elseif sum(current_well_type - [0 1 1]) == 0
set(cwell, 'BackgroundColor', [0.8 1 1]);
else
set(cwell, 'BackgroundColor', [1 1 1]);
end
i4 = 1;
for i1 = 1:size(siteflags,1)
for i2 = 1:size(siteflags,2)
if siteflags(i1, i2) == 0
hballsites = uicontrol('Parent', hpp, 'Style', 'pushbutton', 'Position', [i2*22 size(siteflags,1)*22-i1*22+10 22 22],...
'enable', 'off');
else
preprocess_flag{1} = 0;
sitestr = [MO.channels_(1,1).getGenericName(pst{1,1}),'S',num2str(i4)]; sstr = num2str(i4);
hbwp = uicontrol('Parent', hpp, 'Style', 'pushbutton', 'Position', [i2*22 size(siteflags,1)*22-i1*22+10 22 22],...
'Tag',['S', num2str(i4)], ...
'UserData', dcolor, ...
'FontWeight', 'normal', ...
'String',sstr,'Callback', {@viewsite, i4, indw, platestack, mainFig, hpp, sitestr, preprocess_flag});%@(hbwp,event) redrawScene(hbwp,guidata(hbwp)));%,...
current_well_type = get(cwell, 'UserData');
if sum(current_well_type - [0 1 0]) ~= 0 && sum(current_well_type - [0 1 1]) ~= 0
if i4 == 1
set(hbwp, 'BackgroundColor', [1 1 1]);
viewsite(src, eventdata, i4, indw, platestack, mainFig, hpp, sitestr, preprocess_flag);
end
end
%'Callback',{@view4ch, pst, i4,dirurl});
if size(indw, 2) >2
for isk = 1:length(indw{3})
if i4 == indw{3}(isk)
preprocess_flag{1} = 1;
if size(indw,2)>3
if indw{4} == 1
set(hbwp,'BackgroundColor','cyan');
set(hbwp,'UserData',[0 1 1]);
else
set(hbwp,'BackgroundColor','green');
set(hbwp,'UserData',[0 1 0]);
end
preprocess_flag{2} = indw{5};
end
set(hbwp, 'Callback', {@viewsite, i4, indw, platestack, mainFig, hpp, sitestr, preprocess_flag});
end
end
end
i4 = i4+1;
end
end
end
function viewsite(src, eventdata, inds, indw, platestack, mainFig, hpp, sitestr, preprocess_flag)
n_site = size(platestack{indw{1},indw{2}},2);
for id = 1:n_site
refreshsitestr = findobj(hpp, 'Tag', ['S', num2str(id)]);
if length(refreshsitestr) > 0
original_color = get(refreshsitestr(1), 'UserData');
set(refreshsitestr, 'BackgroundColor', original_color);
end
end
current_click = findobj('Tag', ['S', num2str(inds)]);
original_color = get(current_click(1), 'UserData');
if original_color == [0 1 0] % green
set(current_click, 'BackgroundColor', [0.5 1 0.5]); % lighter green
elseif original_color == [0 1 1] % cyan
set(current_click, 'BackgroundColor', [0.8 1 1]); % lighter cyan
else
set(current_click, 'BackgroundColor', [1 1 1]);
end
tni = 0;
for iv = 1:indw{1} %get number of rows
for ih = 1:size(platestack,2)%get number of columns
niw = size(platestack{iv,ih},2);%get number of sites within one well
% doing this loop instead of multiplication can
% avoid the case of inconsistent number of sites
% exists across wells.
if iv == indw{1} && ih == indw{2}
tni = tni + inds;
break;
else
tni = tni + niw;
end
end
end
if tni == 0
tni = 1;
end
handles = guihandles(mainFig);
set(handles.slider_frame, 'Value', tni);
userdata = get(handles.figure1, 'UserData');
MD = userdata.MO;
if MD.isMock()
load([MD.movieDataPath_ filesep MD.mockMD_.parent.movieDataFileName_]);
% Duplication of objects in matlab will link all the
% duplicated objects to be consistent. One solution to it is
% to have this object < matlab.mixin.copy, which is not
% desired. Therefore we need to load in the original
% MovieData if it has been changed during MD_mock
% loading original MD in this level of callback is to
% prevent MD_mock been wrapped recursively into itself.
end
userdata.MO = MD;
set(handles.figure1, 'UserData', userdata);
% Preprocess for mock_MD button
mockppb = uicontrol('Parent', hpp, 'Style', 'pushbutton', 'Position', [299 80 180 25], ...
'String', ['Process&View ',sitestr], 'Callback', {@mockMD_preprocess, tni, MD, preprocess_flag});
redrawScene(handles.figure1, handles);
%redrawScene(handles,guidata(mainFig));
function mockMD_preprocess(src, eventdata, tni, MD, preprocess_flag)
if MD.isMock()
load([MD.movieDataPath_ filesep MD.movieDataFileName_]);
% Duplication of objects in matlab will link all the
% duplicated objects to be consistent. One solution to it is
% to have this object < matlab.mixin.copy, which is not
% desired. Therefore we need to load in the original
% MovieData if it has been changed during MD_mock
% loading original MD in this level of callback is to
% prevent MD_mock been wrapped recursively into itself.
end
if preprocess_flag{1} == 0
MD_mock = mockMovieData(MD, tni);%tni is the single number index for the site. NOT [col# row# site#]
MD_mock.sanityCheck;
else
load(preprocess_flag{2});
ds = exist('obj', 'var');
if ds == 1
MD_mock = obj;
else
dsk = exist('MD', 'var');
if dsk == 1
MD_mock = MD;
end
end
end
fig = movieSelectorGUI;
handles = guihandles(fig);
userData = get(handles.figure1, 'UserData');
userData.MD = MD_mock;
pathname = MD_mock.movieDataPath_;
userData.userDir = pathname;
M = MD_mock;
set(handles.figure1, 'UserData', userData);
% Display Movie information
moviePaths = MD_mock.mockMD_.path;
nMovies= numel(userData.MD);
iMovie = get(handles.listbox_movie, 'Value');
if isempty(userData.MD),
iMovie=0;
else
iMovie=max(1,min(iMovie,nMovies));
end
set(handles.listbox_movie,'String',moviePaths,'Value',iMovie);
set(handles.text_movies, 'String', sprintf('%g/%g movie(s)',iMovie,nMovies))
% Display list information
listPaths = arrayfun(@getFullPath,userData.ML,'Unif',false);
nLists= numel(userData.ML);
iList = get(handles.listbox_movieList, 'Value');
if isempty(userData.ML),
iList=0;
else
iList=max(1,min(iList,nLists));
end
set(handles.listbox_movieList,'String',listPaths);
set(handles.text_movieList, 'String', sprintf('%g/%g movie list(s)',iList,nLists))
function togglecontrol(src, eventdata, MO)
pp = figure('Name','Viewer','Position',[0 0 700 530],...
'NumberTitle','off','Tag','tog','Toolbar','none','MenuBar','none',...
'Color',get(0,'defaultUicontrolBackgroundColor'),'Resize','off');
platestack = MO.channels_(1,1).hcsPlatestack_;
wellflag = MO.channels_(1,1).hcsFlags_.wellF;
hp = uipanel('Parent', pp,'Title','Select Wells as Controls','FontSize',10,...
'Position',[.05 .15 .9 .8]);
pwgc = 0; % plate-well good count
for i2 = 1:size(wellflag,1)
for i3 = 1:size(wellflag,2)
if i2 == 1
hth = uicontrol('Parent', hp, 'Style', 'Text', 'Position', [i3*22+22,380, 22,22],...
'String', num2str(i3));
end
if i3 == 1
htv = uicontrol('Parent', hp, 'Style', 'Text', 'Position', [22,375-i2*22, 22,22],...
'String', char(i2-1+'A'));
end
if wellflag(i2, i3) == 0
hb = uicontrol('Parent', hp,'Style','pushbutton', 'Position', [i3*22+22,380-i2*22,22,22]...
,'Tag','slider_frame',...
'enable', 'off'); %
elseif wellflag(i2, i3) == 1
pwgc = pwgc + 1;
if pwgc == 1
ipr1 = i2; ipr2 = i3;
end
indexvh = [i2-ipr1+1, i3-ipr2+1];
wellname = MO.channels_(1,1).getGenericName(platestack{i2-ipr1+1, i3-ipr2+1}{1,1});
hb(pwgc) = uicontrol('Parent', hp,'Style','togglebutton', 'Position', [i3*22+22,380-i2*22,22,22]...
,'TooltipString',[MO.channels_(1,1).getGenericName(platestack{i2-ipr1+1, i3-ipr2+1}{1,1}), ...% has to be named in the same way
',',num2str(length(platestack{i2-ipr1+1, i3-ipr2+1})), ...
' Sites'],'Tag',['T', wellname],...
'enable', 'on');%,'Callback', {@mockMDindex, indexvh, platestack, pp});
end
end
end
hbend = uicontrol('Parent', pp,'Style','pushbutton', 'Position', [450,20,180,30],...
'String', 'Submit as Controls',...
'enable', 'on','Callback', {@submittoggles, MO});
%
% function abs_inx = mockMDindex(src, eventdata, indexvh, platestack, pp)
% in = size(platestack{indexvh(1),indexvh(2)},2);
% for i = 1:in
% index3 = [indexvh, i];
% abs_inx(i) = indexing3to1(index3, platestack);
% end
% absi_list = get(pp, 'UserData');
% set(pp, 'UserData', [absi_list abs_inx]);
function submittoggles(src, eventdata, MD)
pt = findobj('Value', 1, 'Style', 'togglebutton');
selectedWell = get(pt, 'Tag');
findemptyh = sum(MD.channels_(1,1).hcsFlags_.wellF);
findemptyv = sum(MD.channels_(1,1).hcsFlags_.wellF');
e_c = find(findemptyh == 0);
e_r = find(findemptyv == 0);
if length(e_c) == 1
emptywellc = e_c;
elseif ~isempty(e_c)
for i1 = 2:length(e_c)
if e_c(i1)-e_c(i1-1) ~=1
emptywellc = e_c(i1-1);
end
end
else
emptywellc = 0;
end
if length(e_r) == 1
emptywellr = e_r;
elseif ~isempty(e_r)
for i3 = 2:length(e_r)
if e_r(i3)-e_r(i3-1) ~=1
emptywellr = e_r(i3-1);
end
end
else
emptywellr = 0;
end
tnit = [];
for i= 1:length(selectedWell)
wpv = double(selectedWell{i}(2))-64-emptywellc;
wph = str2double(selectedWell{i}(3:4))-emptywellr;
for i2 = 1:length(MD.channels_(1,1).hcsPlatestack_{1,1})
index3(i2,:) = [wpv, wph, i2];
tni(i2) = indexing3to1(index3(i2,:), MD.channels_(1,1).hcsPlatestack_);
end
tnit = [tnit tni];
end
tnit = sort(tnit);
mMD = mockMovieData(MD, tnit);
mMD.sanityCheck;
load([mMD.mockMD_.parent.movieDataPath_ filesep mMD.mockMD_.parent.movieDataFileName_]);
movieViewer(MD, 'refresher', '1');
hf = findobj(0, '-regexp', 'Tag', 'tog');
delete(hf)
function flushcontrol(src, eventdata, MD)
MD.mMDparent_ = [];
rmdir([MD.outputDirectory_ filesep 'controls'], 's');
parentMDpath = [MD.movieDataPath_ filesep MD.movieDataFileName_];
save(parentMDpath, 'MD');
movieViewer(MD);
function tni = indexing3to1(index3, platestack)
indw = {index3(1),index3(2)};
inds = index3(3);
tni = 0;
for iv = 1:indw{1} %get number of rows
for ih = 1:size(platestack,2)%get number of columns
niw = size(platestack{iv,ih},2);%get number of sites within one well
% doing this loop instead of multiplication can
% avoid the case of inconsistent number of sites
% exists across wells.
if iv == indw{1} && ih == indw{2}
tni = tni + inds;
return;
else
tni = tni + niw;
end
end
end
if tni == 0
tni = 1;
end
function movieviewerRefresher(MO)
hcsFig = findobj('Name', 'hcsview');
mainFig = findobj('Tag', 'figure1');
mainFig = mainFig(end);
userData = get(hcsFig, 'UserData');
userData.MO = MO;
set(hcsFig, 'UserData', userData);
hpp = findobj('Title','Well Inspector');
if MO.hasMock()
uicontrol('Parent', hpp, 'Style', 'pushbutton', 'Position', [299 30 180 25], ...
'String', 'Flush Controls', ...
'Callback', {@flushcontrol, MO});
end
if MO.hasMock()
mMDsite_number = [];
for imMDt = 1:size(MO.mMDparent_,1)
platestack = MO.channels_(1,1).hcsPlatestack_;
if size(MO.mMDparent_{imMDt},1) > 1
for imMD = 1:size(MO.mMDparent_{imMDt},1)
k1 = MO.mMDparent_{imMDt}(imMD, 1);
k2 = MO.mMDparent_{imMDt}(imMD,2);
wellname = MO.channels_(1,1).getGenericName(platestack{k1, k2}{1,1});
hb = findobj('Tag', wellname);
set(hb,'BackgroundColor','cyan');
set(hb,'UserData',[0 1 1]);
userData.lastclick = wellname;
set(hcsFig, 'UserData', userData);
mMDsite_number = [mMDsite_number; MO.mMDparent_{imMDt}(imMD,3)];
set(hb, 'Callback', {@updatewellp, platestack, {k1, k2, mMDsite_number, 1, MO.mMDparent_{imMDt,2}}, hpp, mainFig, MO});
end
else
k1 = MO.mMDparent_{imMDt}(1);
k2 = MO.mMDparent_{imMDt}(2);
wellname = MO.channels_(1,1).getGenericName(platestack{k1, k2}{1,1});
hb = findobj('Tag', wellname);
set(hb,'BackgroundColor','green');
set(hb,'UserData',[0 1 0]);
userData.lastclick = wellname;
set(hcsFig, 'UserData', userData);
mMDsite_number = MO.mMDparent_{imMDt}(3);
set(hb, 'Callback', {@updatewellp, platestack, {k1, k2, mMDsite_number, 0, MO.mMDparent_{imMDt,2}}, hpp, mainFig, MO});
end
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
extendedColors.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/extendedColors.m
| 6,641 |
utf_8
|
7c12bb63818f2066ec5edba247205fbf
|
function color = extendedColors(colorSwitch,drawTable,betaTable)
%extendedColors gives a more extensive set of possible colors than the normal color switch
%
%SYNOPSIS color = extendedColors(colorSwitch, drawTable, betaTable)
%
%INPUT colorSwitch: can be any char from list 'rgbymcadefhijlnpqstuvzkw' or a
% number from 1 to 24 (23 without white), or a vector,
% where the first entry designs the color and the second
% entry the brighness (>0 brighter, <0 darker)
% drawTable : if == 1, extendedColors draws the full color table
% betaTable : if the table is drawn, this gives the amount of
% increased/decreased brightness
%
%OUTPUT color : RGB-vector according to the colorswitch
%
%REMARKS Thanks to the creators of arrow3 for the typing!
%
% r red 1
% g green 2
% b blue 3
% y yellow 4
% m magenta 5
% c cyan 6
% a apple green 7
% d dark gray 8
% e evergreen 9
% f fuchsia 10
% h honey 11
% i indigo 12
% j jade 13
% l lilac 14
% n nutbrown 15
% p pink 16
% q kumquat 17
% s sky blue 18
% t tan 19
% u umber 20
% v violet 21
% z zinc 22
% k black 23
% w white -1
%
% c: 04-03 jonas
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
%init valid colors
valCol = 'rgbymcadefhijlnpqstuvzkw';
%----------parse input
if nargin == 0
error('not enough input arguments!');
end
%test colorSwitch
if nargin == 1 && ~isempty(colorSwitch)
if length(colorSwitch)>2
% recursively call extendedColors
nColors = length(colorSwitch);
color = zeros(nColors,3);
for i=1:nColors
color(i,:) = extendedColors(colorSwitch(i));
end
return
end
switch ischar(colorSwitch) + 2*isnumeric(colorSwitch)
case 1 %char
if ~strfind(valCol,colorSwitch) | length(colorSwitch)>1
error('unsupported colorString!');
else
colorNum = strfind(valCol,colorSwitch);
beta = 0;
end
case 2 %num
if length(colorSwitch) == 2
beta = colorSwitch(2);
else
beta = 0;
end
%take no chances with col num - make sure that there is no 0
if colorSwitch(1)>0
colorNum = round(abs(rem(colorSwitch(1)-1,23)))+1;
else
colorNum = -1;
end
end %colorSwitch switch
elseif nargin > 1 & isempty(colorSwitch)
colorNum = 1;
beta = 0;
else
error('insufficient input arguments');
end %colorSwitch if
if nargin > 3
error ('too many input arguments!');
end
%assign color
cn = LocalColorTable(0);
if colorNum > 0
color = cn(colorNum,:);
else
color = cn(24,:);
end
%brighten
if beta
color = LocalBrighten(color,beta);
end
%draw table
if nargin > 1 & ~isempty(drawTable) & drawTable ~=0
if nargin == 2 | isempty(betaTable)
betaTable = 0;
end
LocalColorTable(1,betaTable);
end
%==================================================================
function [cn]=LocalColorTable(n,beta)
vc='rgbymcadefhijlnpqstuvzkw'; % valid color codes
% r g b y
cn=[1.00,0.00,0.00; 0.00,1.00,0.00; 0.00,0.00,1.00; 1.00,1.00,0.00;
% m c a d
1.00,0.00,1.00; 0.00,1.00,1.00; 0.00,0.70,0.00; 0.40,0.40,0.40;
% e f h i
0.00,0.40,0.00; 0.90,0.00,0.40; 1.00,0.80,0.00; 0.00,0.00,0.70;
% j l n p
0.20,0.80,0.50; 0.80,0.40,0.80; 0.50,0.20,0.00; 1.00,0.40,0.60;
% q s t u
1.00,0.40,0.00; 0.00,0.80,1.00; 0.80,0.40,0.00; 0.70,0.00,0.00;
% v z k w
0.60,0.00,1.00; 0.60,0.60,0.60; 0.00,0.00,0.00; 1.00,1.00,1.00;];
if n % plot color table
figure;
name={'red','green','blue','yellow','magenta','cyan',...
'apple green',...
'dark gray','evergreen','fuchsia','honey',...
'indigo','jade','lilac','nutbrown',...
'pink','kumquat','sky blue','tan',...
'umber','violet','zinc','black','white'};
c=['yhtn';'gjae';'csbi';'plmv';'frqu';'wzdk'];
clf, set(gcf,'DefaultAxesXTick',[],'DefaultAxesYTick',[],...
'DefaultAxesXTickLabel',[],'DefaultAxesYTickLabel',[],...
'DefaultAxesXLim',[0,0.75],'DefaultAxesYLim',[0,0.75],...
'DefaultRectangleEdgeColor','none');
for i=1:24
subplot(4,6,i); j=find(vc==c(i)); title(name{j});
dark=LocalBrighten(cn(j,:),-beta);
light=LocalBrighten(cn(j,:),beta);
rectangle('Position',[0,0.00,0.75,0.25],'FaceColor',dark);
rectangle('Position',[0,0.25,0.75,0.25],'FaceColor',cn(j,:));
rectangle('Position',[0,0.50,0.75,0.25],'FaceColor',light);
rectangle('Position',[0,0.00,0.75,0.75],'EdgeColor','k');
if rem(i,6)==1
set(gca,'YTickLabel',{'dark','normal','light'},...
'YTick',[0.125,0.375,0.625]);
if i==19
text(0,-0.25,['{\bf\it extendedColors} Named Color Table ',...
'( \beta = ',num2str(beta),' )']);
end
end
end
end
%==========================================================================
% Brighten
function C=LocalBrighten(c,beta)
C=c.^((1-min(1-sqrt(eps),abs(beta)))^sign(beta));
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
kalmanInitializationGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/kalmanInitializationGUI.m
| 8,453 |
utf_8
|
e224b15b4633cb3c4ced2464d02f99cc
|
function varargout = kalmanInitializationGUI(varargin)
% KALMANINITIALIZATIONGUI M-file for kalmanInitializationGUI.fig
% KALMANINITIALIZATIONGUI, by itself, creates a new KALMANINITIALIZATIONGUI or raises the existing
% singleton*.
%
% H = KALMANINITIALIZATIONGUI returns the handle to a new KALMANINITIALIZATIONGUI or the handle to
% the existing singleton*.
%
% KALMANINITIALIZATIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in KALMANINITIALIZATIONGUI.M with the given input arguments.
%
% KALMANINITIALIZATIONGUI('Property','Value',...) creates a new KALMANINITIALIZATIONGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before kalmanInitializationGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to kalmanInitializationGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help kalmanInitializationGUI
% Last Modified by GUIDE v2.5 13-Dec-2011 17:07:36
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @kalmanInitializationGUI_OpeningFcn, ...
'gui_OutputFcn', @kalmanInitializationGUI_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 kalmanInitializationGUI is made visible.
function kalmanInitializationGUI_OpeningFcn(hObject, eventdata, handles, varargin)
costMat_OpeningFcn(hObject, eventdata, handles, varargin{:})
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
parameters = userData.parameters;
% mkitti 2014/11/28 Why do we do this again?
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
% Get main figure handle and process id
props = get(userData.handles_main.popupmenu_probDim, {'UserData','Value'});
userData.probDim=props{1}(props{2});
% Parameter Setup
set(handles.radiobutton_none,'Value',1);
if ~isempty(parameters)
if ~isempty(parameters.initVelocity)% Initial Valocity Estimate
for i=1:userData.probDim
set(handles.(['edit_v_' num2str(i)]), 'String', parameters.initVelocity(i));
end
set(handles.radiobutton_initVelocity, 'Value', 1);
end
if ~isempty(parameters.convergePoint) % Reference Point for Initial Estimate
for i=1:userData.probDim
set(handles.(['edit_' num2str(i)]), 'String', parameters.convergePoint(i));
end
set(handles.radiobutton_convergePoint, 'Value', 1);
end
set(handles.edit_radius, 'String', num2str(parameters.searchRadiusFirstIteration))
end
handles.output = hObject;
set(handles.figure1, 'UserData', userData)
uipanel5_SelectionChangeFcn(hObject,eventdata,handles);
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes kalmanInitializationGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = kalmanInitializationGUI_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 pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_cancel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
delete(handles.figure1)
% --- Executes on button press in pushbutton_done.
function pushbutton_done_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
parameters = userData.parameters;
initVelFlag=get(handles.radiobutton_initVelocity, 'Value');
dimensions=1:userData.probDim;
if initVelFlag
initVelocity=arrayfun(@(x) str2double(get(handles.(['edit_v_' num2str(x)]),'String')),dimensions);
if any(isnan(initVelocity)) || any(initVelocity<0)
errordlg(['Please provide a valid value to parameter' ...
get(handles.radiobutton_initVelocity,'String') '.'],'Error','modal')
return
end
else
initVelocity=[];
end
convPointFlag=get(handles.radiobutton_convergePoint, 'Value');
if convPointFlag
convergePoint=arrayfun(@(x) str2double(get(handles.(['edit_' num2str(x)]),'String')),dimensions);
if any(isnan(convergePoint)) || any(convergePoint<0)
errordlg(['Please provide a valid value to parameter' ...
get(handles.radiobutton_convergePoint,'String') '.'],'Error','modal')
return
end
else
convergePoint=[];
end
searchRadiusFlag=~isempty(get(handles.edit_radius, 'String'));
if searchRadiusFlag
searchRadiusFirstIteration=str2double(get(handles.edit_radius, 'String'));
if isnan(searchRadiusFirstIteration) || searchRadiusFirstIteration <0
errordlg('Please provide a valid value to parameter "Search Radius for Iteration".','Error','modal')
return
end
else
searchRadiusFirstIteration=[];
end
if ~initVelFlag && ~convPointFlag && ~searchRadiusFlag
parameters = [];
else
parameters.initVelocity = initVelocity;
parameters.convergePoint = convergePoint;
parameters.searchRadiusFirstIteration = searchRadiusFirstIteration;
end
u = get(userData.handles_main.popupmenu_kalmanFunctions, 'UserData');
u{userData.procID} = parameters;
set(userData.handles_main.popupmenu_kalmanFunctions, 'UserData', u)
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
delete(handles.figure1);
% --- Executes when selected object is changed in uipanel5.
function uipanel5_SelectionChangeFcn(hObject, eventdata, handles)
handles = guidata(hObject);
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
% Highlight the content under new radiobuttonfunction uipanel5_SelectionChangeFcn(hObject, eventdata, handles)
selectedButton = get(get(handles.uipanel5,'SelectedObject'),'Tag');
if strcmpi(selectedButton,'radiobutton_initVelocity');
child=get(handles.uipanel_initVelocity,'Children');
dim = cellfun(@(x)str2double(x(end)),get(child,'Tag'));
set(child(dim<=userData.probDim),'Enable','on');
set(child(dim>userData.probDim),'Enable','off');
else
set(get(handles.uipanel_initVelocity,'Children'),'Enable','off');
end
if strcmpi(selectedButton,'radiobutton_convergePoint');
child=get(handles.uipanel_convergePoint,'Children');
dim = cellfun(@(x)str2double(x(end)),get(child,'Tag'));
set(child(dim<=userData.probDim),'Enable','on');
set(child(dim>userData.probDim),'Enable','off');
else
set(get(handles.uipanel_convergePoint,'Children'),'Enable','off');
end
%updates the handles structure
guidata(hObject, handles);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
graphViewer.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/graphViewer.m
| 12,427 |
utf_8
|
95719cc6341e559b786efdbd1ba49c2b
|
function graphFig = graphViewer(mainFig, graphProc, graphProcId, checkedId)
%GRAPHVIEWER creates a graphical interface to display the graph output of a MovieObject
%
% This function creates a list of checkboxes for all graph processes which
% output can be displayed in a standalone figure. It is called by
% movieViewer.
%
% Input
%
% mainFig - the handle of the calling figure.
%
% graphProc - The cell array of processes that can be displaye.
%
% graphProcId - The array of processes indices that can be displayed.
%
% checkedId - The array of processes indices to display at creation.
%
% Output:
%
% graphFig - the handle of the graph control interface
%
% See also: graphViewer, movieViewerOptions
%
% Sebastien Besson, Nov 2012
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Check existence of viewer
h=findobj(0,'Name','Graphs');
if ~isempty(h), delete(h); end
graphFig=figure('Name','Graphs','Position',[0 0 200 200],...
'NumberTitle','off','Tag','figure1','Toolbar','none','MenuBar','none',...
'Color',get(0,'defaultUicontrolBackgroundColor'),'Resize','off',...
'DeleteFcn', @(h,event) deleteViewer());
userData = get(mainFig, 'UserData');
graphPanel = uipanel(graphFig,'Position',[0 0 1 1],...
'Title','Graph','BackgroundColor',get(0,'defaultUicontrolBackgroundColor'),...
'Units','pixels','Tag','uipanel_graph');
hPosition3=10;
% Create series of anonymous function to generate process controls
createProcText= @(panel,i,j,pos,name) uicontrol(panel,'Style','text',...
'Position',[10 pos 250 20],'Tag',['text_process' num2str(i)],...
'String',name,'HorizontalAlignment','left','FontWeight','bold');
createOutputText= @(panel,i,j,pos,text) uicontrol(panel,'Style','text',...
'Position',[40 pos 200 20],'Tag',['text_process' num2str(i) '_output'...
num2str(j)],'String',text,'HorizontalAlignment','left');
createChannelBox= @(panel,i,j,k,pos,varargin) uicontrol(panel,'Style','checkbox',...
'Position',[200+30*k pos 20 20],'Tag',['checkbox_process' num2str(i) '_output'...
num2str(j) '_channel' num2str(k)],varargin{:});
createMovieBox= @(panel,i,j,pos,name,varargin) uicontrol(panel,'Style','checkbox',...
'Position',[40 pos 200 25],'Tag',['checkbox_process' num2str(i) '_output'...
num2str(j)],'String',[' ' name],varargin{:});
createInputBox= @(panel,i,j,k,pos,name,varargin) uicontrol(panel,'Style','checkbox',...
'Position',[40 pos 200 25],'Tag',['checkbox_process' num2str(i) '_output'...
num2str(j) '_input' num2str(k)],'String',[' ' name],varargin{:});
createInputInputBox= @(panel,i,j,k,l,pos,varargin) uicontrol(panel,'Style','checkbox',...
'Position',[200+30*l pos 20 20],'Tag',['checkbox_process' num2str(i) '_output'...
num2str(j) '_input' num2str(k) '_input' num2str(l)],varargin{:});
hPosition3 = createScalarMapOptions(graphPanel,hPosition3);
hPosition3=hPosition3+50;
% Create controls for selecting all other graphs
nProc = numel(graphProc);
for iProc=nProc:-1:1;
output=graphProc{iProc}.getDrawableOutput;
if isa(graphProc{iProc},'SignalProcessingProcess');
input=graphProc{iProc}.getInput;
nInput=numel(input);
% Create set of boxes for correlation graphs (input/input)
validOutput = graphProc{iProc}.checkOutput;
for iOutput=size(validOutput,3):-1:1
for iInput=nInput:-1:1
createOutputText(graphPanel,graphProcId(iProc),iInput,hPosition3,input(iInput).name);
for jInput=1:iInput
if validOutput(iInput,jInput,iOutput)
createInputInputBox(graphPanel,graphProcId(iProc),iOutput,iInput,jInput,hPosition3,...
'Callback',@(h,event) redrawSignalGraph(h,guidata(h)));
end
end
hPosition3=hPosition3+20;
end
createProcText(graphPanel,graphProcId(iProc),iInput,hPosition3,output(iOutput).name);
hPosition3=hPosition3+20;
end
else
% Create boxes for movie -specific graphs
validOutput = find(strcmp({output.type},'movieGraph'));
for iOutput=validOutput(end:-1:1)
createMovieBox(graphPanel,graphProcId(iProc),iOutput,hPosition3,...
output(iOutput).name,'Callback',@(h,event) redrawGraph(h,guidata(h)));
hPosition3=hPosition3+20;
end
% Create boxes for channel-specific graphs
validOutput = find(strcmp({output.type},'graph'));
for iOutput=validOutput(end:-1:1)
validChan = graphProc{iProc}.checkChannelOutput();
createOutputText(graphPanel,graphProcId(iProc),iOutput,hPosition3,output(iOutput).name);
arrayfun(@(x) createChannelBox(graphPanel,graphProcId(iProc),iOutput,x,hPosition3,...
'Callback',@(h,event) redrawGraph(h,guidata(h))),find(validChan));
hPosition3=hPosition3+20;
end
% Create boxes for sampled graphs
validOutput = find(strcmp({output.type},'sampledGraph'));
for iOutput=validOutput(end:-1:1)
validChan = graphProc{iProc}.checkChannelOutput();
createOutputText(graphPanel,graphProcId(iProc),iOutput,hPosition3,output(iOutput).name);
arrayfun(@(x) createChannelBox(graphPanel,graphProcId(iProc),iOutput,x,hPosition3,...
'Callback',@(h,event) redrawGraph(h,guidata(h))),find(validChan(iOutput,:)));
hPosition3=hPosition3+20;
end
% Create boxes for sampled graphs
validOutput = find(strcmp({output.type},'signalGraph'));
for iOutput=validOutput(end:-1:1)
input=graphProc{iProc}.getInput;
validInput = find(graphProc{iProc}.checkOutput());
% createOutputText(graphPanel,graphProcId(iProc),iOutput,hPosition3,output(iOutput).name);
for iInput=fliplr(validInput)
createInputBox(graphPanel,graphProcId(iProc),iOutput,iInput,hPosition3,...
input(iInput).name,'Callback',@(h,event) redrawGraph(h,guidata(h)));
hPosition3=hPosition3+20;
end
end
createProcText(graphPanel,graphProcId(iProc),iOutput,hPosition3,graphProc{iProc}.getName);
hPosition3=hPosition3+20;
end
end
if ~isempty(graphProc) && isa(userData.MO,'MovieData')
uicontrol(graphPanel,'Style','text','Position',[120 hPosition3 100 20],...
'Tag','text_channels','String','Channels');
arrayfun(@(i) uicontrol(graphPanel,'Style','text',...
'Position',[200+30*i hPosition3 20 20],...
'Tag',['text_channel' num2str(i)],'String',i),...
1:numel(userData.MO.channels_));
end
%% Get image/overlay panel size and resize them
graphPanelSize = getPanelSize(graphPanel);
set(graphPanel,'Position',[10 10 graphPanelSize(1) graphPanelSize(2)])
%% Resize panels and figure
sz=get(0,'ScreenSize');
maxWidth = graphPanelSize(1)+20;
maxHeight = graphPanelSize(2)+20;
set(graphFig,'Position',[3*sz(3)/4 sz(4)/2 maxWidth maxHeight]);
% Update handles structure and attach it to the main figure
handles = guihandles(graphFig);
guidata(handles.figure1, handles);
% Create redraw callbacks
userData.mainFig = mainFig;
set(handles.figure1,'UserData',userData);
%% Set up default parameters
% Auto check input process
for i=checkedId
h=findobj(graphFig,'-regexp','Tag',['(\w)_process' num2str(i) '_output1.*'],...
'-not','Style','text');
set(h,'Value',1);
end
redrawGraphs(handles)
function hPosition=createScalarMapOptions(graphPanel,hPosition)
uicontrol(graphPanel,'Style','text',...
'Position',[20 hPosition 200 20],'Tag','text_UpSample',...
'String',' Upsampling Factor','HorizontalAlignment','left');
uicontrol(graphPanel,'Style','edit','Position',[220 hPosition 50 20],...
'String','1','BackgroundColor','white','Tag','edit_UpSample',...
'Callback',@(h,event) redrawGraphs(guidata(h)));
hPosition=hPosition+20;
uicontrol(graphPanel,'Style','text',...
'Position',[20 hPosition 200 20],'Tag','text_SmoothParam',...
'String',' Smoothing Parameter','HorizontalAlignment','left');
uicontrol(graphPanel,'Style','edit','Position',[220 hPosition 50 20],...
'String','.99','BackgroundColor','white','Tag','edit_SmoothParam',...
'Callback',@(h,event) redrawGraphs(guidata(h)));
hPosition=hPosition+20;
uicontrol(graphPanel,'Style','text',...
'Position',[10 hPosition 200 20],'Tag','text_scalarMapOptions',...
'String','Scalar Map options','HorizontalAlignment','left','FontWeight','bold');
function size = getPanelSize(hPanel)
if ~ishandle(hPanel), size=[0 0]; return; end
a=get(get(hPanel,'Children'),'Position');
P=vertcat(a{:});
size = [max(P(:,1)+P(:,3))+10 max(P(:,2)+P(:,4))+20];
function redrawGraphs(handles)
graphBoxes = findobj(handles.uipanel_graph,'-regexp','Tag','checkbox_process*');
checkedBoxes = logical(arrayfun(@(x) get(x,'Value'),graphBoxes));
graphTags=arrayfun(@(x) get(x,'Tag'),graphBoxes(checkedBoxes),...
'UniformOutput',false);
for i=1:numel(graphTags),
redrawGraph(handles.(graphTags{i}),handles)
end
function redrawGraph(hObject,handles)
graphTag = get(hObject,'Tag');
userData=get(handles.figure1,'UserData');
% Retrieve the id, process nr and channel nr of the selected graphProc
tokens = regexp(graphTag,'^checkbox_process(\d+)_output(\d+)','tokens');
procId=str2double(tokens{1}{1});
outputList = userData.MO.processes_{procId}.getDrawableOutput;
iOutput = str2double(tokens{1}{2});
output = outputList(iOutput).var;
% Discriminate between channel-specific and movie processes
tokens = regexp(graphTag,'_channel(\d+)$','tokens');
if ~isempty(tokens)
iChan = str2double(tokens{1}{1});
figName = [outputList(iOutput).name ' - Channel ' num2str(iChan)];
if strcmp({outputList(iOutput).type},'sampledGraph')
inputArgs={iChan,iOutput};
else
inputArgs={iChan};
end
else
tokens = regexp(graphTag,'_input(\d+)$','tokens');
if ~isempty(tokens)
iInput = str2double(tokens{1}{1});
figName = [outputList(iOutput).name ' - ' ...
userData.MO.processes_{procId}.getInput(iInput).name];
inputArgs={iInput};
else
inputArgs={};
figName = outputList(iOutput).name;
end
end
% Draw or delete the graph figure depending on the checkbox value
h = userData.getFigure(figName);
if ~get(hObject,'Value'),delete(h); return; end
set(h,'Tag','graphFig');
upSample = str2double(get(handles.edit_UpSample,'String'));
smoothParam = str2double(get(handles.edit_SmoothParam,'String'));
userData.MO.processes_{procId}.draw(inputArgs{:}, 'output', output,...
'UpSample', upSample,'SmoothParam', smoothParam);
set(h,'DeleteFcn',@(h,event)closeGraphFigure(hObject));
function redrawSignalGraph(hObject,handles)
graphTag = get(hObject,'Tag');
userData=get(handles.figure1,'UserData');
% Retrieve the id, process nr and channel nr of the selected graphProc
tokens = regexp(graphTag,'^checkbox_process(\d+)_output(\d+)_input(\d+)_input(\d+)','tokens');
procId=str2double(tokens{1}{1});
iOutput = str2double(tokens{1}{2});
iInput1 = str2double(tokens{1}{3});
iInput2 = str2double(tokens{1}{4});
signalProc = userData.MO.processes_{procId};
figName = signalProc.getOutputTitle(iInput1,iInput2,iOutput);
% Draw or delete the graph figure depending on the checkbox value
h = userData.getFigure(figName);
if ~get(hObject,'Value'),delete(h); return; end
set(h,'Tag','graphFig');
signalProc.draw(iInput1,iInput2,iOutput);
set(h,'DeleteFcn',@(h,event)closeGraphFigure(hObject));
function closeGraphFigure(hObject)
set(hObject,'Value',0);
function deleteViewer()
h = findobj(0,'-regexp','Tag','graphFig');
if ~isempty(h), delete(h); end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
plusTipCostMatCloseGaps.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/plusTipCostMatCloseGaps.m
| 37,213 |
utf_8
|
1c55797419c9da78410cc5ee7d41d19b
|
function [costMat,nonlinkMarker,indxMerge,numMerge,indxSplit,numSplit,...
errFlag] = plusTipCostMatCloseGaps(trackedFeatInfo,...
trackedFeatIndx,trackStartTime,trackEndTime,costMatParam,gapCloseParam,...
kalmanFilterInfo,nnDistLinkedFeat,probDim,movieInfo)
%COSTMATLINEARMOTIONCLOSEGAPS provides a cost matrix for closing gaps and capturing merges/splits using Kalman filter information
%
%SYNOPSIS [costMat,nonlinkMarker,indxMerge,numMerge,indxSplit,numSplit,...
% errFlag] = costMatLinearMotionCloseGaps(trackedFeatInfo,...
% trackedFeatIndx,trackStartTime,trackEndTime,costMatParam,gapCloseParam,...
% kalmanFilterInfo,nnDistLinkedFeat,probDim,movieInfo)
%
%INPUT trackedFeatInfo: The positions and amplitudes of the tracked
% features from linkFeaturesKalman.
% Number of rows = number of tracks.
% Number of columns = 8*number of frames.
% Each row consists of
% [x1 y1 z1 a1 dx1 dy1 dz1 da1 x2 y2 z2 a2 dx2 dy2 dz2 da2 ...]
% in image coordinate system (coordinates in
% pixels). NaN is used to indicate time points
% where the track does not exist.
% trackedFeatIndx: Connectivity matrix of features between frames.
% Rows indicate continuous tracks, while columns
% indicate frames. A track that ends before the
% last time point is followed by zeros, and a track
% that starts at a time after the first time point
% is preceded by zeros.
% trackStartTime : Starting time of all tracks.
% trackEndTime : Ending time of all tracks.
% costMatParam : Structure containing variables needed for cost
% calculation. Contains the fields:
% .fluctRad : Size in pixels of tube radius around track
% trajectory. The search region in the backward
% direction will expand out from the track at
% the final point. This value also determines
% the search radius around the final point
% wherein any candidates will be considered for
% forward linking, even if they fall slightly
% behind the point. This ensures that tracks
% starting from a fluctuation during a pause
% will still be picked up as candidates for
% pause.
% .maxFAngle : Max angle in degrees allowed between the end
% track's final velocity vector and the
% displacement vector between end and start.
% Also the max angle between the end and start
% tracks themselves.
% .maxBAngle : Angle in degrees used to expand backward
% search region, giving a distance-dependent
% criterion for how far a start track
% can be from the lattice to be considered a
% candidate for linking. THIS IS CURRENTLY A
% HARDWIRED PARAMETER
% .backVelMultFactor : Muliplication factor of max growth speed used
% to define candidate search area in the
% backward direction.
% gapCloseParam : Structure containing variables needed for gap closing.
% Contains the fields:
% .timeWindow : Largest time gap between the end of a track and the
% beginning of another that could be connected to
% it.
% .mergeSplit : Logical variable with value 1 if the merging
% and splitting of trajectories are to be consided;
% and 0 if merging and splitting are not allowed.
% For MT tracking, there are no merges/splits, so
% this should be 0.
% kalmanFilterInfo: Structure array with number of entries equal to
% number of frames in movie. Contains the fields:
% .stateVec : Kalman filter state vector for each
% feature in frame.
% .stateCov : Kalman filter state covariance matrix
% for each feature in frame.
% .noiseVar : Variance of state noise for each
% feature in frame.
% .stateNoise : Estimated state noise for each feature in
% frame.
% .scheme : 1st column: propagation scheme connecting
% feature to previous feature. 2nd column:
% propagation scheme connecting feature to
% next feature.
% nnDistLinkedFeat:Matrix indicating the nearest neighbor
% distances of features linked together within
% tracks.
% probDim : Problem dimensionality. 2 (for 2D) or 3 (for 3D).
% movieInfo : movieInfo as input to trackCloseGapsKalman. Not
% really used in this code, but needed for
% compatibility with other cost functions.
%
%OUTPUT costMat : Cost matrix.
% nonlinkMarker : Value indicating that a link is not allowed.
% indxMerge : Index of tracks that have possibly merged with
% tracks that end before the last time points.
% numMerge : Number of such tracks.
% indxSplit : Index of tracks from which tracks that begin after
% the first time point might have split.
% numSplit : Number of such tracks.
% errFlag : 0 if function executes normally, 1 otherwise.
%
%REMARKS
%
%Kathryn Applegate, 2009
%Adapted from costMatCloseGaps.m by Khuloud Jaqaman, April 2007
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
%% Output
costMat = [];
nonlinkMarker = [];
indxMerge = [];
numMerge = [];
indxSplit = [];
numSplit = [];
errFlag = [];
%% Input
%check whether correct number of input arguments was used
if nargin ~= nargin('plusTipCostMatCloseGaps')
disp('--plusTipCostMatCloseGaps: Incorrect number of input arguments!');
errFlag = 1;
return
end
doTest=0;
doPlot=0;
% get user-set parameters
fluctRad=costMatParam.fluctRad;
maxFAngle = costMatParam.maxFAngle*pi/180;
maxBAngle = costMatParam.maxBAngle*pi/180;
backVelMultFactor = costMatParam.backVelMultFactor;
tMax=gapCloseParam.timeWindow;
%find the number of tracks to be linked and the number of frames in the movie
[nTracks,nFrames] = size(trackedFeatInfo);
nFrames = nFrames / 8;
%list the tracks that start and end in each frame
tracksPerFrame = repmat(struct('starts',[],'ends',[]),nFrames,1);
for iFrame = 1 : nFrames
tracksPerFrame(iFrame).starts = find(trackStartTime == iFrame); %starts
tracksPerFrame(iFrame).ends = find(trackEndTime == iFrame); %ends
end
%% Gap closing
% extract feature positions and velocity components
px=trackedFeatInfo(:,1:8:end);
py=trackedFeatInfo(:,2:8:end);
vx=diff(px,1,2);
vy=diff(py,1,2);
% all the instantaneous velocities from all tracks in one vector
velInst=sqrt(vx.^2+vy.^2);
velInst=velInst(:);
velInst(isnan(velInst))=[];
% TRACK STARTS
trackStartPxyVxy = zeros(nTracks,4);
% x and y coordinates of the track's first point
trackStartPxyVxy(:,1)=cell2mat(arrayfun(@(i) px(i,find(~isnan(px(i,:)),1,'first')),[1:nTracks]','UniformOutput',0));
trackStartPxyVxy(:,2)=cell2mat(arrayfun(@(i) py(i,find(~isnan(py(i,:)),1,'first')),[1:nTracks]','UniformOutput',0));
% average of first three velocity vectors (made from last 4 points
% on track, if that many exist), x and y components
trackStartPxyVxy(:,3)=cell2mat(arrayfun(@(i) mean(vx(i,find(~isnan(vx(i,:)),3,'first'))),[1:nTracks]','UniformOutput',0));
trackStartPxyVxy(:,4)=cell2mat(arrayfun(@(i) mean(vy(i,find(~isnan(vy(i,:)),3,'first'))),[1:nTracks]','UniformOutput',0));
% TRACK ENDS
trackEndPxyVxy = zeros(nTracks,4);
% x and y coordinates of the track's last point
trackEndPxyVxy(:,1)=cell2mat(arrayfun(@(i) px(i,find(~isnan(px(i,:)),1,'last')),[1:nTracks]','UniformOutput',0));
trackEndPxyVxy(:,2)=cell2mat(arrayfun(@(i) py(i,find(~isnan(py(i,:)),1,'last')),[1:nTracks]','UniformOutput',0));
% average of last three velocity vectors (made from last 4 points
% on track, if that many exist), x and y components
trackEndPxyVxy(:,3)=cell2mat(arrayfun(@(i) mean(vx(i,find(~isnan(vx(i,:)),3,'last'))),[1:nTracks]','UniformOutput',0));
trackEndPxyVxy(:,4)=cell2mat(arrayfun(@(i) mean(vy(i,find(~isnan(vy(i,:)),3,'last'))),[1:nTracks]','UniformOutput',0));
% get velocity components for each track from kalman filter (very similar to trackEndVxy)
xyzVel=cell2mat(arrayfun(@(iTrack) kalmanFilterInfo(trackEndTime(iTrack))...
.stateVec(trackedFeatIndx(iTrack,trackEndTime(iTrack)),probDim+1:2*probDim),...
[1:nTracks]','UniformOutput',0));
trackEndSpeed=sqrt(sum(xyzVel.^2,2));
vMax=prctile(trackEndSpeed,95);
vMed=median(trackEndSpeed);
% get start and end frames for each track
sFrameAll=zeros(nTracks,1);
eFrameAll=zeros(nTracks,1);
for iFrame=1:nFrames
sFrameAll(tracksPerFrame(iFrame).starts)=iFrame;
eFrameAll(tracksPerFrame(iFrame).ends)=iFrame;
end
% initialize matrices for pair indices and cost components
indx1 = zeros(10*nTracks,1);
indx2 = zeros(10*nTracks,1);
costComponents = zeros(10*nTracks,5);
linkCount = 1;
for iFrame = 1:nFrames-1
%find tracks that end in this frame
endsToConsider = tracksPerFrame(iFrame).ends;
if isempty(endsToConsider)
continue
end
% these are the frames to consider for finding starts
jFrame=iFrame+1:min(iFrame+tMax,nFrames);
% find tracks that start in possible frame range
startsToConsider=arrayfun(@(x) tracksPerFrame(x).starts,jFrame,'uniformoutput',0);
% get number of starts in each frame
nStarts=cellfun(@(x) length(x),startsToConsider,'uniformoutput',0);
if isempty(startsToConsider)
continue
end
% n-vector of time gaps allowable
tGap = jFrame - iFrame;
% forward and backward cutoff distances - based on velocity and the
% current time gap
cutoffDistFwd = vMax*min(sqrt(tMax),tGap);
cutoffDistBwd = min(vMed*tMax,backVelMultFactor*vMax*tGap);
% plot the cutoff distances as a function of time gap
if doPlot==1 && iFrame==1
figure;
plot(cutoffDistFwd);
hold on;
plot(cutoffDistBwd,'r');
legend('forward links','backward links','location','best')
title('cutoff distance')
xlabel('time gap (frames)')
ylabel('cutoff distance (pixels)')
end
% make vectors containing forward/backward cutoffs for each start track candidate
cutFwdPerVec=cell2mat(arrayfun(@(i,j) repmat(i,[j,1]),cutoffDistFwd,cell2mat(nStarts),'uniformoutput',0)');
cutBwdPerVec=cell2mat(arrayfun(@(i,j) repmat(i,[j,1]),cutoffDistBwd,cell2mat(nStarts),'uniformoutput',0)');
startsToConsider=cell2mat(startsToConsider');
nStarts = length(startsToConsider);
nEnds = length(endsToConsider);
% end track last pt
epX=repmat(trackEndPxyVxy(endsToConsider,1),[1 nStarts]);
epY=repmat(trackEndPxyVxy(endsToConsider,2),[1 nStarts]);
% start track first pt
spX=repmat(trackStartPxyVxy(startsToConsider,1)',[nEnds 1]);
spY=repmat(trackStartPxyVxy(startsToConsider,2)',[nEnds 1]);
% nEnds x nStarts distance matrix containing displacement vector magnitude
dispMag=sqrt((epX-spX).^2+(epY-spY).^2);
% we will only consider end/start pairs where the distance from end to start is less than
% the max(forwardCutoff,backwardCutoff)
maxCut=max(repmat(cutFwdPerVec',[nEnds 1]),repmat(cutBwdPerVec',[nEnds 1]));
% initialize with larger-than-needed matrix
dPerp=zeros(nStarts*nEnds,1); % distance from start track's first point to end track's lattice
dPara=zeros(nStarts*nEnds,1); % distance from the dPerp point on end track lattice to end track's last point
evYc=zeros(nStarts*nEnds,1); % x component of end track's instantaneous velocity at dPerp point
evXc=zeros(nStarts*nEnds,1); % y component of end track's instantaneous velocity at dPerp point
endLinkIdx=zeros(nStarts*nEnds,1); % end track's index for candidate pair
startLinkIdx=zeros(nStarts*nEnds,1); % start track's index for candidate pair
sAll=zeros(nStarts*nEnds,1); % local start index that feeds into startCandidateIdx
sXall=zeros(nStarts*nEnds,1); % x-coordinates of all start tracks
sYall=zeros(nStarts*nEnds,1); % y-coordinates of all start tracks
endCounter=zeros(nStarts*nEnds,1); % keep track of the current iEnd loop index
if doTest==1
endRange=1:nEnds;
else
endRange=1:nEnds;
end
count=1;
for iEnd=endRange
% indices correspoinding to current set of starts and ends, respectively
startCandidateIdx=find(dispMag(iEnd,:)<maxCut(iEnd,:))';
endCandidateIdx=repmat(iEnd,[length(startCandidateIdx) 1]);
if isempty(startCandidateIdx)
continue
end
% coordinates of the first point in each startsToConsider track
sX=trackStartPxyVxy(startsToConsider(startCandidateIdx),1);
sY=trackStartPxyVxy(startsToConsider(startCandidateIdx),2);
if doTest==1
% re-assign points to be the current end track
xtemp=px(endsToConsider(iEnd),:)';
xtemp(isnan(xtemp))=[];
ytemp=py(endsToConsider(iEnd),:)';
ytemp(isnan(ytemp))=[];
% here only look at the end tracks >=10 frames long
if length(xtemp)<25
continue
end
% store track for later
xTemp{iEnd,1}=xtemp;
yTemp{iEnd,1}=ytemp;
% add fake points around the end track's last point at each
% pixel center +/- halfWidth pixels from this point
halfWidth=round(max([max(cutoffDistFwd); max(cutoffDistBwd)]));
[sX sY]= meshgrid([round(xtemp(end))-halfWidth:round(xtemp(end))+halfWidth],[round(ytemp(end))-halfWidth:round(ytemp(end))+halfWidth]);
sX=sX(:);
sY=sY(:);
negIdx=find(sX<=0 | sY<=0);
sX(negIdx)=[];
sY(negIdx)=[];
sXall(count:count+length(sX)-1)=sX;
sYall(count:count+length(sX)-1)=sY;
% assume all fake points are within the fwd and bwd cutoff distances
cutFwdPerVec(count:count+length(sX)-1)=max(cutoffDistFwd);
cutBwdPerVec(count:count+length(sX)-1)=max(cutoffDistBwd);
end
sXall(count:count+length(sX)-1)=sX;
sYall(count:count+length(sX)-1)=sY;
endCounter(count:count+length(sX)-1)=iEnd;
% call subfunction to calculate magnitude of the components of
% the vector pointing from end to start, as well as the components
% of the local velocity along the end track at its closest point to
% the start track
[dPerpTemp,dParaTemp,evYcTemp,evXcTemp]=pt2segDist...
([py(endsToConsider(iEnd),:)',px(endsToConsider(iEnd),:)'],...
trackStartPxyVxy(endsToConsider(iEnd),:),[sY,sX],cutoffDistBwd,0);
% dPerp is the component perpendicular to the end track
dPerp(count:count+length(sX)-1)=dPerpTemp;
% dPara is the component parallel to the end track
dPara(count:count+length(sX)-1)=dParaTemp;
% evX/Yc are the velocity components of the end track at
% the point closest (c) each startsToConsider track starts
evXc(count:count+length(sX)-1)=evXcTemp;
evYc(count:count+length(sX)-1)=evYcTemp;
if doTest==1
% redefine these based on test points
endCandidateIdx=repmat(iEnd,[length(sX) 1]);
endLinkIdx (count:count+length(sX)-1) = endsToConsider(endCandidateIdx);
startLinkIdx(count:count+length(sX)-1)=1:length(sX);
sAll(count:count+length(sX)-1)=1:length(sX);
else
% starts/endsToConsider indices of the ones checked
endLinkIdx (count:count+length(sX)-1) = endsToConsider(endCandidateIdx);
startLinkIdx(count:count+length(sX)-1) = startsToConsider(startCandidateIdx);
sAll(count:count+length(sX)-1)=startCandidateIdx;
end
count=count+length(sX);
end % end iterating thru track ends
if count==1
% there aren't any points to continue with
continue
end
% trim down the vectors
dPerp(count:end)=[];
dPara(count:end)=[];
evYc(count:end)=[];
evXc(count:end)=[];
endLinkIdx(count:end)=[];
startLinkIdx(count:end)=[];
sAll(count:end)=[];
% velocity at starts of startsToConsider tracks
if doTest==1
% for test, assume they all point in same direction as end track's last pt
svX = evXc; %trackEndPxyVxy(endLinkIdx,3);
svY = evYc; %trackEndPxyVxy(endLinkIdx,4);
else
svX = trackStartPxyVxy(startLinkIdx,3);
svY = trackStartPxyVxy(startLinkIdx,4);
end
svMag = sqrt(svX.^2 + svY.^2);
% cos of angle between start track beginning and direction of end
% track at closest point to start
evMagC=sqrt(evXc.^2+evYc.^2);
cosTheta = (evXc.*svX + evYc.*svY)./(evMagC.*svMag);
% velocity at final point (f) of endsToConsider tracks
evXf = trackEndPxyVxy(endLinkIdx,3);
evYf = trackEndPxyVxy(endLinkIdx,4);
evMagF = sqrt(evXf.^2 + evYf.^2);
% displacement vector (start minus end)
if doTest==1
dispX = sXall-trackEndPxyVxy(endLinkIdx,1);
dispY = sYall-trackEndPxyVxy(endLinkIdx,2);
else
dispX = trackStartPxyVxy(startLinkIdx,1)-trackEndPxyVxy(endLinkIdx,1);
dispY = trackStartPxyVxy(startLinkIdx,2)-trackEndPxyVxy(endLinkIdx,2);
end
dispMag = sqrt(dispX.^2 + dispY.^2);
% cos angle between end track's end and start track's start
cosEF_SF = (evXf.*svX + evYf.*svY)./(evMagF.*svMag); % cos(alpha)
% cos angle between end track's end and displacement vector
cosEF_D = (evXf.*dispX + evYf.*dispY)./(evMagF.*dispMag); % cos(beta)
% criteria for backward linking:
% perp dist (dPerp) must be smaller than user-set fluctRad
% nearest pt needs to not be the end of the endTrack and parallel dist
% should be smaller than backward cutoff
% angle between tracks should be less than max forward angle
bwdIdx=find(dPerp<=(fluctRad+dPara*tan(maxBAngle)) & (dPara>0 & dPara<=cutBwdPerVec(sAll)) & cosTheta>=cos(maxFAngle));
if ~isempty(bwdIdx)
% record indices and parts of cost for forward links
indx1(linkCount:linkCount+length(bwdIdx)-1) = endLinkIdx(bwdIdx);
indx2(linkCount:linkCount+length(bwdIdx)-1) = startLinkIdx(bwdIdx);
% cost - keep several pieces of data here for now
% [dPerp dPara cosTheta 2 (for backward)]
costComponents(linkCount:linkCount+length(bwdIdx)-1,1:4) = [dPerp(bwdIdx) dPara(bwdIdx) cosTheta(bwdIdx) 2*ones(length(bwdIdx),1)];
linkCount = linkCount+length(bwdIdx);
end
% criteria for forward linking:
% parallel dist (dPara) must be 0 (indicates closest pt is the end pt)
% end-start dist must be smaller than forward cutoff
% end-displacement angle must be smaller than max forward angle
% angle between tracks should be less than max forward angle
fwdIdx1=find(dPerp<=cutFwdPerVec(sAll) & dPara==0 & cosEF_D>=cos(maxFAngle) & cosTheta>=cos(maxFAngle));
% for forward links, currently cosTheta=cosEF_SF and dPerp=dispMag
% reassign dPerp and dPara with components of displacement vector
if ~isempty(fwdIdx1)
dPara(fwdIdx1)=dPerp(fwdIdx1).*cosEF_D(fwdIdx1);
dPerp(fwdIdx1)=sqrt(dPerp(fwdIdx1).^2-dPara(fwdIdx1).^2);
end
% but also count those tracks falling within fluctRad of the track
% end in the backward direction as forward links. here we calculate
% dispMagApparent, which is the hypotenuse length of the triangle
% formed by dPara and dPerp (as opposed to the Euclidean distance
% between them, which is captured by dispMag)
dispMagApparent = sqrt(dPara.^2+dPerp.^2);
fwdIdx2=setdiff(find(dispMagApparent<=fluctRad & cosTheta>=cos(maxFAngle)),fwdIdx1);
% combine them
fwdIdx=[fwdIdx1; fwdIdx2];
if ~isempty(fwdIdx)
% record indices and parts of cost for forward links
indx1(linkCount:linkCount+length(fwdIdx)-1) = endLinkIdx(fwdIdx);
indx2(linkCount:linkCount+length(fwdIdx)-1) = startLinkIdx(fwdIdx);
% cost - keep several pieces of data here for now
% [dPerp dPara cosTheta 1 (for forward)]
costComponents(linkCount:linkCount+length(fwdIdx)-1,1:4) = [dPerp(fwdIdx) dPara(fwdIdx) cosTheta(fwdIdx) ones(length(fwdIdx),1)];
linkCount = linkCount+length(fwdIdx);
end
% some candidates will be in both fwd and bwd lists because the bwd
% criterion specifies dPara>0, which includes some in the fluctation
% radius captured by the fwdIdx. we leave those in the fwdIdx list and
% get rid of them from the bwdIdx list.
bwdIdx=setdiff(bwdIdx,fwdIdx);
if doTest==1
for iEnd=endRange
% get only those indices corresponding to the current end
idxTemp=find(endCounter==iEnd);
% if there are some, make an image where the forward cone is
% green, the backward cone is red, and other pixels in blue
if ~isempty(idxTemp)
if isempty(intersect(idxTemp,fwdIdx)) && isempty(intersect(idxTemp,bwdIdx))
continue
end
img=zeros(max(sYall(idxTemp)),max(sXall(idxTemp)));
img(sub2ind(size(img),sYall(intersect(idxTemp,fwdIdx)),sXall(intersect(idxTemp,fwdIdx))))=1;
img(sub2ind(size(img),sYall(intersect(idxTemp,bwdIdx)),sXall(intersect(idxTemp,bwdIdx))))=2;
figure
imagesc(img);
hold on
x=xTemp{iEnd,1};
y=yTemp{iEnd,1};
plot(x,y,'linewidth',2)
axis equal
scatter(x,y,'b.')
scatter(x(end),y(end),'b*')
end
end
end
end
indx1(linkCount:end) =[];
indx2(linkCount:end) =[];
costComponents(linkCount:end,:)=[];
costComponents(:,5)=sFrameAll(indx2)-eFrameAll(indx1);
% type is 1 for forward, 2 for backward
type=costComponents(:,4);
% calculate the cost
costPerp = costComponents(:,1)./prctile(costComponents(:,1),99); % normalized dperp only
costPara = costComponents(:,2)./prctile(costComponents(:,2),99); % normalized dpara only
costAngle = 1-costComponents(:,3); % 1-cos(angle) only
costPerpParaAngle = costPerp + costPara + costAngle;
cost = 1.1.^costComponents(:,5).*costPerpParaAngle; % for now, this seems to be the best cost
% plot histograms of costs for forward and backward
doPlot=0;
if doPlot==1
% define populations for forward/backward linkings costs (all tracks)
pop1=cost(type==1); % forward
pop2=cost(type==2); % backward
% put them into a matrix
M=nan(max([length(pop1) length(pop2)]),2);
M(1:length(pop1),1)=pop1;
M(1:length(pop2),2)=pop2;
% create x-axis bins spanning all costs in sample
n=linspace(min([pop1;pop2]),max([pop1;pop2]),25);
% bin the samples
[x1,nbins1] = histc(pop1,n); % forward
[x2,nbins2] = histc(pop2,n); % backward
% make new matrix of binned samples
M=nan(max([length(x1) length(x2)]),2);
M(1:length(x1),1)=x1;
M(1:length(x2),2)=x2;
% make the plot
figure
bar(n,M,'stack')
colormap([1 0 0; 0 0 1])
legend('Forward Costs','Shrinkage Costs','Location','best')
title('Cost for all tracks')
xlabel('cost');
ylabel('number of track pairs');
hold on
deathCost=prctile(cost,90);
plot([deathCost;deathCost],[0,max([x1+x2])])
text(deathCost,max([x1+x2])/2,['\leftarrow ' 'death cost'])
%saveas(gcf,[histDir filesep 'allTracksCostStackedHist.fig'])
%saveas(gcf,[histDir filesep 'allTracksCostStackedHist.tif'])
% get indices from endsToConsider with only 1 potential start link
[num, u] = getMultiplicity(indx1);
only1 = u(num==1);
costSingles=cost(cell2mat(arrayfun(@(x) find(indx1==x),only1,'uniformoutput',0)));
typeSingles=type(cell2mat(arrayfun(@(x) find(indx1==x),only1,'uniformoutput',0)));
% define populations for forward/backward linkings costs (tracks with only one link)
pop1=costSingles(typeSingles==1); % forward
pop2=costSingles(typeSingles==2); % backward
% put them into a matrix
M=nan(max([length(pop1) length(pop2)]),2);
M(1:length(pop1),1)=pop1;
M(1:length(pop2),2)=pop2;
% create x-axis bins spanning all costs in sample
%n=linspace(min([pop1;pop2]),max([pop1;pop2]),25);
% here let's use the same span for all costs
% bin the samples
[x1,nbins1] = histc(pop1,n); % forward
[x2,nbins2] = histc(pop2,n); % backward
% make new matrix of binned samples
M=nan(max([length(x1) length(x2)]),2);
M(1:length(x1),1)=x1;
M(1:length(x2),2)=x2;
% make the plot
figure
bar(n,M,'stack')
colormap([1 0 0; 0 0 1])
legend('Forward Costs','Shrinkage Costs','Location','best')
title('Cost for tracks with only one potential link')
xlabel('cost');
ylabel('number of track pairs');
hold on
deathCost=prctile(cost,90);
plot([deathCost;deathCost],[0,max([x1+x2])])
text(deathCost,max([x1+x2])/2,['\leftarrow ' 'death cost'])
%saveas(gcf,[histDir filesep 'singleTracksCostStackedHist.fig'])
%saveas(gcf,[histDir filesep 'singleTracksCostStackedHist.tif'])
end
% plot those tracks with 3 potential connections and their costs
% doPlot=1;
if doPlot==1
figure
imagesc(.75*zeros(round(max(py(:))),round(max(px(:))))); colormap gray
hold on
[num, u] = getMultiplicity(indx1);
c = u(num==3);
for j=1:5 %length(c);
b=find(indx1==c(j));
[indx1(b) indx2(b) type(b) cost(b)]
for i=1:length(b)
idx=b(i);
%get current end track's coordinates
currentTrackE = [px(indx1(idx),:); py(indx1(idx),:)]';
currentTrackE = currentTrackE(trackStartTime(indx1(idx)):trackEndTime(indx1(idx)),:);
%get current start track's coordinates
currentTrackS = [px(indx2(idx),:); py(indx2(idx),:)]';
currentTrackS = currentTrackS(trackStartTime(indx2(idx)):trackEndTime(indx2(idx)),:);
% plot the tracks in blue
plot(currentTrackE(:,1),currentTrackE(:,2),'g')
plot(currentTrackS(:,1),currentTrackS(:,2),'r')
% plot points along tracks in red (ends) or green (starts)
scatter(currentTrackE(:,1),currentTrackE(:,2),'b.')
scatter(currentTrackS(:,1),currentTrackS(:,2),'b.')
% plot possible connections
if type(idx)==1
x=[currentTrackE(end,1);currentTrackS(1,1)];
y=[currentTrackE(end,2);currentTrackS(1,2)];
plot(x,y,'c')
text(mean(x),mean(y),[' \leftarrow ' sprintf('%3.2f',cost(idx))],'color','c');
else
x=[currentTrackE(end,1);currentTrackS(1,1)];
y=[currentTrackE(end,2);currentTrackS(1,2)];
plot(x,y,'y')
text(mean(x),mean(y),[sprintf('%3.2f',cost(idx)) '\rightarrow '],'color','y','horizontalAlignment','right');
end
% end track end vectors
%quiver(currentTrackE(end,1),currentTrackE(end,2),xyzVel(indx1(iEnd),1),xyzVel(indx1(iEnd),2),'r')
quiver(trackEndPxyVxy(indx1(idx),1),trackEndPxyVxy(indx1(idx),2),trackEndPxyVxy(indx1(idx),3),trackEndPxyVxy(indx1(idx),4),'b')
% start track end vectors
%quiver(currentTrackS(end,1),currentTrackS(end,2),xyzVel(indx2(iStart),1),xyzVel(indx2(iStart),2),'r')
quiver(trackEndPxyVxy(indx2(idx),1),trackEndPxyVxy(indx2(idx),2),trackEndPxyVxy(indx2(idx),3),trackEndPxyVxy(indx2(idx),4),'b')
end
end
axis equal
end
%% Merging and splitting
%define some merging and splitting variables
numMerge = 0; %index counting merging events
indxMerge = []; %vector storing merging track number
altCostMerge = []; %vector storing alternative costs of not merging
numSplit = 0; %index counting splitting events
indxSplit = []; %vector storing splitting track number
altCostSplit = []; %vector storing alternative costs of not splitting
%create cost matrix without births and deaths
numEndSplit = nTracks;
numStartMerge = nTracks;
costMat = sparse(indx1,indx2,cost,numEndSplit,numStartMerge);
%% Append cost matrix to allow births and deaths ...
%determine the cost of birth and death
costBD = prctile(cost,90);
%get the cost for the lower right block
costLR = min(min(min(costMat))-1,-1);
% create cost matrix that allows for births and deaths
costMat = [costMat ... %costs for links (gap closing + merge/split)
spdiags([costBD*ones(nTracks,1); altCostSplit],0,numEndSplit,numEndSplit); ... %costs for death
spdiags([costBD*ones(nTracks,1); altCostMerge],0,numStartMerge,numStartMerge) ... %costs for birth
sparse(indx2,indx1,costLR*ones(length(indx1),1),numStartMerge,numEndSplit)]; %dummy costs to complete the cost matrix
%determine the nonlinkMarker
nonlinkMarker = min(floor(full(min(min(costMat))))-5,-5);
%% ~~~ the end ~~~
function [dPerp,dPara,evY,evX]=pt2segDist(segYX,endTrackStartPxyVxy,ptYX,maxCutoff,doPlot)
% find nearest point on the directed segment B-C to point P
% see http://www.geometrictools.com/Documentation/DistancePointLine.pdf for
% inspiration
% the point of this subfunction is to find the perpendicular and parallel
% distances of one or more points (stored in ptYX), which represent a
% candidate track's starting position, to a line segment (segYX), which
% represents the end track itself. we also want to know the
% velocity components of the point on segment nearest the
% track start. because the MT tarck may not be straight, dPara, the
% component parallel to the track, is here the actual distance along the
% lattice, not the euclidean distance from track end to the candidate start.
% dPerp is perpendicular to the line segment unless of course
% the point of interest is nearest one of the two segment ends; then it is
% defined as the Euclidean distance. to avoid dPerp being zero in the
% backward direction (along the lattice), we add "phantom points" before
% the first point of segYX, extending the lattice backward in the direction
% of the end track's start velocity. this extrapolation is not implemented
% for the forward direction, as dPerp = 0 is one of the criterion for a
% point to be considered in the forward direction.
if doPlot==1
figure
end
segYXorig=segYX;
% find how many phantom pts are needed to extend bwd vector past max bwd cutoff
% endTrackStartPxyVxy is not the whole matrix - only for this particular end
% track
endMag=sqrt(sum(endTrackStartPxyVxy(1,3:4).^2));
nRepPhantom=ceil(max(maxCutoff)/endMag);
% create the phantom points extending back from end track's first pt,
% pointing towards it with the end track's starting velocity
phantomYX=repmat(endTrackStartPxyVxy(1,2:-1:1),[nRepPhantom,1])-...
repmat([nRepPhantom:-1:1]',[1,2]).*repmat(endTrackStartPxyVxy(1,4:-1:3),[nRepPhantom,1]);
segYX=[phantomYX; segYX];
% treat every consecutive pair of points in segYX as a line segment BC
bYX=segYX(1:end-1,:); % here's a vector containing the first pt of each line segment (B)
bcYX=diff(segYX); % velocity components
BC=sqrt(sum(bcYX.^2,2)); % BC length
% keep track of which entries don't exist
nanEntries=double(isnan(bcYX(:,1)));
nanEntries=swapMaskValues(nanEntries,[0,1],[1,nan]);
nPts=size(ptYX,1);
dPerp=zeros(nPts,1);
dPara=zeros(nPts,1);
evY=zeros(nPts,1);
evX=zeros(nPts,1);
for i=1:size(ptYX,1)
% velocity components for vectors from all points on seg BC to P
temp=repmat(ptYX(i,:),[size(segYX,1),1])-segYX;
bpYX=temp(1:end-1,:); % velocity components for P-B
BP=sqrt(sum(bpYX.^2,2)); % distance from P to B
cpYX=temp(2:end,:); % velocity components for P-C
CP=sqrt(sum(cpYX.^2,2)); % distance from P to C
% get fraction mag(vector from B to point on line closest to P)/mag(BC)
% if t0<0, closest to b; if t0>0 then closet to c
t0=(bcYX(:,1).*bpYX(:,1)+bcYX(:,2).*bpYX(:,2))./(BC.^2);
D=zeros(length(t0),1);
extraPt=zeros(length(t0),2);
% P falls outside segment and is closest to B
idx=find(t0<=0);
D(idx)=BP(idx);
extraPt(idx,:)=segYX(idx,:); % just duplicate the first point
% P falls outside segment and is closest to C
idx=find(t0>=1);
D(idx)=CP(idx);
extraPt(idx,:)=segYX(idx+1,:); % duplicate the last point
% P falls within BC segment
idx=find(t0>0 & t0<1);
pYX=repmat(ptYX(i,:),[length(idx),1]);
b_plus_t0M=bYX(idx,:)+repmat(t0(idx),[1 2]).*bcYX(idx,:); % location of perp point along segment
nearVec=pYX-b_plus_t0M;
D(idx)=sqrt(sum(nearVec.^2,2));
extraPt(idx,:)=b_plus_t0M; % we'll have to insert this point into the list of pts in segYX
% don't consider where track didn't exist
D=D.*nanEntries;
% this is the segment index with the lowest distance
d1Idx=find(D==nanmin(D),1,'first'); % this is where we will insert the extra point
dPerp(i)=D(d1Idx); % distance from P to nearest point on BC
% add in the extra point corresponding to where the dPerp vector falls on
% the BC line
temp=[segYX; 0 0];
temp(d1Idx+2:end,:)=temp(d1Idx+1:end-1,:);
temp(d1Idx+1,:)=extraPt(d1Idx,:);
% get local segment velocity at the extra point. do this by finding the
% pt behind up and the three pts ahead of the extra pt (closest pt on
% the line to the start pt of interest). since there is a duplicated
% pt, this could throw off the velocity calculation if we just did a
% mean of the differences between pts. instead, sum the differences and
% divide by the number of *segments* (nPts-1), minus 1 for the zero
% difference from one point to its duplicate. this should give a good
% local estimate of the instantaneous velocity
pts2getLocalVel = temp(max(1,d1Idx-1):min(size(temp,1),d1Idx+3),:);
pts2getLocalVel(isnan(pts2getLocalVel(:,1)),:)=[];
velYX=sum(diff(pts2getLocalVel))./(size(pts2getLocalVel,1)-2);
evY(i)=velYX(1);
evX(i)=velYX(2);
% calculate pt-to-pt displacements towards the track end and sum them
% this is the total shrinkage distance
% if dPara=0, P is nearest the track end (no shrinkage)
% if dPara=trackLength, P is nearest the track start (complete shrinkage)
dPara(i)=nansum(sqrt(sum(diff(temp(d1Idx+1:end,:)).^2,2)));
if doPlot==1
% show all the pts to check as blue dot
scatter(ptYX(:,2),ptYX(:,1),'.')
% plot end track as a blue line
plot(segYX(:,2),segYX(:,1))
plot(segYXorig(:,2),segYXorig(:,1),'LineWidth',2)
hold on;
% add blue dots for detection events
scatter(temp(:,2),temp(:,1),'b.')
% add magenta line showing start velocity vector
quiver(endTrackStartPxyVxy(1),endTrackStartPxyVxy(2),endTrackStartPxyVxy(3),endTrackStartPxyVxy(4),0,'m')
% plot candidate start point in red
scatter(ptYX(i,2),ptYX(i,1),'r.')
% show dPerp,dPara distances next to point
text(ptYX(i,2),ptYX(i,1),['\leftarrow ' sprintf('%3.2f',dPerp(i)) ', ' sprintf('%3.2f',dPara(i))])
% show newly-created extra pt as green circle
scatter(extraPt(d1Idx,2),extraPt(d1Idx,1),'g')
% show end-track calculated instantaneous velocity at new pt
quiver(extraPt(d1Idx,2),extraPt(d1Idx,1),velYX(2)+.1,velYX(1)+.1,0,'r')
% connect new pt to candidate start pt with green line
plot([ptYX(i,2); extraPt(d1Idx,2)],[ptYX(i,1); extraPt(d1Idx,1)],'g')
axis equal
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
dataPreparationGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/dataPreparationGUI.m
| 29,233 |
utf_8
|
9fc08eb42e3bf3903fbdb663bd993eed
|
function varargout = dataPreparationGUI(varargin)
% DATAPREPARATIONGUI M-file for dataPreparationGUI.fig
% DATAPREPARATIONGUI, by itself, creates a new DATAPREPARATIONGUI or raises the existing
% singleton*.
%
% H = DATAPREPARATIONGUI returns the handle to a new DATAPREPARATIONGUI or the handle to
% the existing singleton*.
%
% DATAPREPARATIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DATAPREPARATIONGUI.M with the given input arguments.
%
% DATAPREPARATIONGUI('Property','Value',...) creates a new DATAPREPARATIONGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before dataPreparationGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to dataPreparationGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help dataPreparationGUI
% Last Modified by GUIDE v2.5 10-Apr-2013 12:15:52
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @dataPreparationGUI_OpeningFcn, ...
'gui_OutputFcn', @dataPreparationGUI_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 dataPreparationGUI is made visible.
function dataPreparationGUI_OpeningFcn(hObject, ~, handles, varargin)
%
% dataPreparationGUI('mainFig', handles.figure1) - call from movieSelector
%
% Useful tools:
%
% User Data:
%
% userData.channels - array of Channel objects
% userData.mainFig - handle of movie selector GUI
% userData.handles_main - 'handles' of movie selector GUI
%
% userData.setChannelFig - handle of channel set-up figure
% userData.iconHelpFig - handle of help dialog
%
%
%
set(handles.text_copyright, 'String', getLCCBCopyright())
% Choose default command line output forfor i dataPreparationGUI
handles.output = hObject;
userData = get(handles.figure1, 'UserData');
if isempty(userData), userData = struct(); end
% Initialize the userData
userData.projectDir = pwd;
userData.outputDir = [];
userData.rawData =[];
userData.channels =[];
userData.movies=[];
% Load help icon from dialogicons.mat
userData = loadLCCBIcons(userData);
supermap(1,:) = get(hObject,'color');
userData.colormap = supermap;
axes(handles.axes_help);
Img = image(userData.questIconData);
set(hObject,'colormap',supermap);
set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),...
'visible','off');
set(Img,'ButtonDownFcn',@icon_ButtonDownFcn,...
'UserData', struct('class',mfilename));
% TestIif the dataPreparationGUI ewas called from the movieSelctorGUI
if nargin > 3
t = find(strcmp(varargin,'mainFig'));
if isempty(t)
error('User-defined: input error, correct statement: dataPreparationGUI(''mainFig'',handles.figure1)');
end
set(handles.checkbox_createMD,'Value',1);
% Save main figure handles
userData.mainFig = varargin{t+1};
userData.handles_main = guidata(userData.mainFig);
end
% Save data and update graphics
set(handles.figure1,'UserData',userData)
guidata(hObject, handles);
update_graphics(hObject,handles)
% UIWAIT makes dataPreparationGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = dataPreparationGUI_OutputFcn(~, ~, 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 pushbutton_cancel.
function pushbutton_cancel_Callback(~, ~, handles)
% handles structure with handles and user data (see GUIDATA)
delete(handles.figure1);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(~, ~, handles)
% handles structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
% Delete help window if existing
if isfield(userData, 'iconHelpFig') && ishandle(userData.iconHelpFig)
delete(userData.iconHelpFig)
end
% --- Executes on button press in pushbutton_delete_channel.
function pushbutton_delete_channel_Callback(hObject, ~, handles)
% hObject handle to pushbutton_delete_channel (see GCBO)
% handles structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
% Retrieve the selected channel id, remove it and update the selected channel
userData.selectedChannel=get(handles.listbox_channels,'Value');
userData.channels(userData.selectedChannel)=[];
userData.selectedChannel = max(userData.selectedChannel-1,1);
% Save data and update graphics
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
update_graphics(hObject,handles)
% --- Executes on button press in pushbutton_edit_channel.
function channelEdition_Callback(hObject, ~, handles)
% hObject handle to pushbutton_edit_channel (see GCBO)
% handles structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
% Retrieve the channel index in the case of channel edition
if strcmp(get(hObject,'Tag'),'pushbutton_edit_channel')
userData.selectedChannel = get(handles.listbox_channels,'Value');
if userData.selectedChannel> numel(userData.channels), return; end
newChannel=0;
else
newChannel=1;
end
% Launch a dialog window asking the user for the new channel directory name
propNames = {'excitationWavelength_','emissionWavelength_','exposureTime_'};
prompt = {'Enter the channel as it is encoded in the image names',...
'Enter the channel directory name - optional',...
'Enter the excitation wavelength (in nm) - optional',...
'Enter the emission wavelength (in nm) - optional',...
'Enter the exposure time (in s) - optional'};
num_lines = 1;
if newChannel
inputData=inputdlg(prompt,'Create new channel',num_lines);
else
dlg_title = ['Rename channel ' num2str(userData.selectedChannel)];
defaultValues={userData.channels(userData.selectedChannel).string,...
userData.channels(userData.selectedChannel).name,...
num2str(userData.channels(userData.selectedChannel).properties.excitationWavelength_),...
num2str(userData.channels(userData.selectedChannel).properties.emissionWavelength_),...
num2str(userData.channels(userData.selectedChannel).properties.exposureTime_)};
inputData=inputdlg(prompt,dlg_title,num_lines,defaultValues);
end
if isempty(inputData), return; end
% If no channel directory name is supplied, use the channel string name
if isempty(inputData{2}), inputData{2}=inputData{1}; end
% Update the channel string and
if newChannel
% Add a new channel structure and update the channel index
userData.channels(end+1).name=inputData{2};
userData.channels(end).exportMD = 1;
userData.channels(end).string='';
userData.channels(end).properties.excitationWavelength_=[];
userData.channels(end).properties.emissionWavelength_=[];
userData.channels(end).properties.exposureTime_=[];
userData.selectedChannel = numel(userData.channels);
else
userData.channels(userData.selectedChannel).name=inputData{2};
end
userData.channels(userData.selectedChannel).string=inputData{1};
% Manage input properties
propList=inputData(3:end);
if ~isempty(propList),
% Check for property values validity
propValues = cellfun(@str2num,propList','Unif',false);
validProperties = Channel.checkValue(propNames,propValues);
% Affect valid, non-multiple properties values
for i= find(validProperties)
userData.channels(userData.selectedChannel).properties.(propNames{i})=propValues{i};
end
end
% Save data and update graphics
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
update_graphics(hObject,handles)
% --- Executes on button press in pushbutton_select_projectDir.
function pushbutton_select_projectDir_Callback(hObject, ~, handles)
% hObject handle to pushbutton_select_projectDir (see GCBO)
% handles structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
pathname = uigetdir(userData.projectDir,'Select project folder');
% Test uigetdir output, reinitalize the movies if any, store the project
% directory and the output directory (project directory by default)
if isequal(pathname,0), return; end
userData.projectDir = pathname;
userData.outputDir = pathname;
userData.movies=[];
userData.rawData=[];
set(handles.edit_projectDir,'String',pathname);
set(handles.edit_outputDir,'String',pathname);
% List all subdirectories, including the project directory itself
allSub = dir(userData.projectDir);
allSub = allSub([allSub.isdir]' & ...
arrayfun(@(x)(~any(strcmp(x.name,{'..'}))),allSub));
nSub = numel(allSub);
for iSub = 1:nSub
% List all images of any extension in this directory
% Use the true returnAll option of imDir
imageFiles = imDir([userData.projectDir filesep allSub(iSub).name],true);
if ~isempty(imageFiles)
% If some image files are found, there are two behaviours
% 1- if the directory is the project directory, we will use it as
% it to create channel folders
% 2- for any other folder, add a new movie which name is set by the
% folder name
if ~strcmp(allSub(iSub).name,'.')
% Add movie with empty properties
userData.movies(end+1).name=allSub(iSub).name;
userData.movies(end).properties.pixelSize_=[];
userData.movies(end).properties.timeInterval_=[];
userData.movies(end).properties.numAperture_=[];
userData.movies(end).properties.camBitdepth_=[];
rawData.movieIndx = numel(userData.movies);
else
rawData.movieIndx=[];
end
% Get the unique bodyname of the image files
[~, imageBodyNames,~,imageExt]=cellfun(@getFilenameBody,{imageFiles.name},'Unif',false);
[imageBodyNames,uniqueIndx] = unique(imageBodyNames);
for iRawData=1:numel(imageBodyNames)
rawData.name = imageBodyNames{iRawData};
rawData.dir = allSub(iSub).name;
rawData.chanIndx=[];
rawData.ext=imageExt{uniqueIndx(iRawData)};
userData.rawData=vertcat(userData.rawData,rawData);
end
end
end
if isempty(userData.rawData)
errordlg('No images found in the main project folder or its sub-folders !!');
end
% Save data and update graphics
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
update_graphics(hObject,handles)
% --- Executes on button press in pushbutton_guess.
function pushbutton_guess_Callback(hObject, ~, handles)
% hObject handle to pushbutton_guess (see GCBO)
% handles structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
% Check all raw data components have been affected to a channel
checkChannels = any(cellfun(@isempty,{userData.rawData.chanIndx}));
if checkChannels,
errordlg('All components have not been affected to a channel','modal');
return;
end
% Guess the movie names from the raw data
% Use the part of the string to the left of the channel string
nRawData = numel(userData.rawData);
movieNames=cell(1,nRawData);
for i=1:nRawData
chanIndx = userData.rawData(i).chanIndx;
indx=regexp(userData.rawData(i).name,userData.channels(chanIndx).string,'start');
movieNames{i}=userData.rawData(i).name(1:indx-1);
end
% Find the unique movie names and store the correspondinx index for each
% raw data component
[uniqueMovieNames, ~, movieIndx]= unique(movieNames);
userData.movies = cell2struct(uniqueMovieNames,'name')';
initProperties.pixelSize_=[];
initProperties.timeInterval_=[];
initProperties.numAperture_=[];
initProperties.camBitdepth_=[];
[userData.movies(:).properties]=deal(initProperties);
for i=1:nRawData
userData.rawData(i).movieIndx=movieIndx(i);
end
% Save data and update graphics
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
update_graphics(hObject,handles)
% --- Executes on button press in checkbox_createMD.
function checkbox_createMD_Callback(hObject, ~, handles)
update_graphics(hObject,handles)
% --- Executes on button press in pushbutton_edit_movie.
function pushbutton_edit_movie_Callback(hObject, ~, handles)
% hObject handle to pushbutton_edit_movie (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
if isempty(userData), userData = struct(); end
% Retrieve the selected movie ID and launch a dialog box asking the user
% for the new movie name
selectedMovie = get(handles.listbox_movies,'Value');
propNames = {'pixelSize_','timeInterval_','numAperture_','camBitdepth_'};
% Input dialog common properties
dlg_title = 'Movie edition';
num_lines = 1;
prompt = {...
'Enter the movie directory name:',...
'Enter the pixel size (in nm) - optional',...
'Enter the time interval (in s) - optional',...
'Enter the numerical aperture - optional',...
'Enter the camera bit depth - optional',...
};
% Test for single or multiple selection
if numel(selectedMovie)==1
defaultValues={...
userData.movies(selectedMovie).name,...
num2str(userData.movies(selectedMovie).properties.pixelSize_),...
num2str(userData.movies(selectedMovie).properties.timeInterval_),...
num2str(userData.movies(selectedMovie).properties.numAperture_),...
num2str(userData.movies(selectedMovie).properties.camBitdepth_)};
inputData=inputdlg(prompt,dlg_title,num_lines,defaultValues);
% Update the movie name and store the list of properties in propList
userData.movies(selectedMovie).name=inputData{1};
propList=inputData(2:end);
else
% Initialize default values
nProps = numel(propNames);
defaultValues=cellfun(@num2str,cell(1,nProps),'Unif',false);
for i= 1:nProps
allPropValues=arrayfun(@(x) x.properties.(propNames{i}),userData.movies(selectedMovie),...
'UniformOutput',false);
uniquePropValues = unique([allPropValues{:}]);
emptyPropValues = find(cellfun(@isempty,allPropValues),1);
unicityTest = isempty(uniquePropValues) ||...
(numel(uniquePropValues)==1 && isempty(emptyPropValues));
if unicityTest
defaultValues{i} = num2str(uniquePropValues);
else
defaultValues{i}='(multiple)';
end
end
% Remove the movie name from the prompt list and store answer in
% propList
propList=inputdlg(prompt(2:end),dlg_title,num_lines,defaultValues);
end
if isempty(propList), return; end
% Check multiple properties
nonMultipleOutput=~strcmp(propList','(multiple)');
% Check for property values validity
propValues = cellfun(@str2num,propList','Unif',false);
validProperties = MovieData.checkValue(propNames,propValues);
% Affect valid, non-multiple properties values
for i= find(nonMultipleOutput & validProperties)
for j=selectedMovie
userData.movies(j).properties.(propNames{i})=propValues{i};
end
end
% Save data and update graphics
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
update_graphics(hObject,handles)
% --- Executes on selection change in listbox_channels.
function listbox_channels_Callback(hObject, ~, handles)
% hObject handle to listbox_channels (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Check if the user double clicked on the list box
if strcmp(get(handles.figure1,'SelectionType'),'open')
userData = get(handles.figure1, 'UserData');
% Modify the export status of the selected channel
userData.selectedChannel=get(handles.listbox_channels,'Value');
userData.channels(userData.selectedChannel).exportMD=~userData.channels(userData.selectedChannel).exportMD;
% Save data and update graphics
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
update_graphics(hObject,handles)
end
function update_graphics(hObject, handles)
userData = get(handles.figure1, 'UserData');
if ~isempty(userData.channels)
% Generate the channel list, put the channels to be exported in the
% MovieData in bold (using html block), update the channel listbox
channelList =arrayfun(@(x)[x.name ' (' x.string ')'],userData.channels,'UniformOutput',false);
if get(handles.checkbox_createMD,'Value')
exportMDChannels = logical([userData.channels.exportMD]);
channelList(exportMDChannels)=cellfun(@(x) ['<html><b>' x '</b></html>'],channelList(exportMDChannels),...
'UniformOutput',false);
end
set(handles.listbox_channels,'String',channelList,'Value',userData.selectedChannel);
else
set(handles.listbox_channels,'String',[]);
end
if ~isempty(userData.movies)
% Generate the movie list, update the movies listbox
set(handles.listbox_movies,'String',{userData.movies.name});
else
set(handles.listbox_movies,'String',[]);
end
if isempty(userData.rawData),
set(handles.listbox_rawData,'String',[]);
return;
end
nRawData = numel(userData.rawData);
% If raw data has been selected, find the match between each channel string
% with all the raw data components
nChannels = numel(userData.channels(:));
channelMatches=zeros(nChannels,nRawData);
for i=1:nChannels
findChannel = @(x) (~isempty(regexp(x,userData.channels(i).string,'ONCE')));
channelMatches(i,:) = cellfun(findChannel,{userData.rawData.name});
end
% Test the unique correspondance between each raw data component and a
% channel
for i=1:nRawData
chanIndx=find(channelMatches(:,i));
if numel(chanIndx)>1
errorMsg=sprintf('Multiple user-defined channels match the movie:\n %s',userData.rawData(i).name);
errordlg(errorMsg);
userData.rawData(i).chanIndx=[];
break
else
userData.rawData(i).chanIndx = chanIndx;
end
end
% Update the number of found chanels and put the matched raw data components
% associated with a channel in bold font.
channelMatch = ~cellfun(@isempty,{userData.rawData.chanIndx});
channelMatchText=['Matching channels: ' num2str(sum(channelMatch)) '/' num2str(nRawData)];
set(handles.text_channelMatch,'String',channelMatchText);
rawDataNames={userData.rawData.name};
rawDataNames(channelMatch)=cellfun(@(x) ['<html><b>' x '</b></html>'],rawDataNames(channelMatch),'UniformOutput',false);
set(handles.listbox_rawData,'String',rawDataNames);
% Update the number of found movies
movieMatch = ~cellfun(@isempty,{userData.rawData.movieIndx});
movieMatchText=['Matching movies: ' num2str(sum(movieMatch)) '/' num2str(nRawData)];
set(handles.text_movieMatch,'String',movieMatchText);
% Save data
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
% --- Executes on button press in pushbutton_select_outputDir.
function pushbutton_select_outputDir_Callback(hObject, ~, handles)
% hObject handle to pushbutton_select_outputDir (see GCBO)
% handles structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
pathname = uigetdir('Select output directory', userData.projectDir);
% Test uigetdir output and store its results
if isequal(pathname,0), return; end
userData.outputDir = pathname;
set(handles.edit_outputDir,'String',pathname);
% Save data
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
% --- Executes on button press in pushbutton_exclude_component.
function pushbutton_exclude_component_Callback(hObject, ~, handles)
% hObject handle to pushbutton_exclude_component (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
userData = get(handles.figure1, 'UserData');
% Retrieve the selected component id,
selectedComponents=get(handles.listbox_rawData,'Value');
% Find any movie associated with component to exclude
uniqueMovieIndx =unique([userData.rawData(selectedComponents).movieIndx]);
if ~isempty(uniqueMovieIndx),
% Loop backwards on found movies (for index renumbering)
for i=uniqueMovieIndx(end:-1:1)
% Find movies to remove, i.e. movies where all components are to be
% excluded
nMovieComponentsToExclude = sum([userData.rawData(selectedComponents).movieIndx]==i);
nMovieComponentsTotal = sum([userData.rawData(:).movieIndx]==i);
if nMovieComponentsToExclude~=nMovieComponentsTotal, continue; end
% Remove movie from the list
userData.movies(i)=[];
% Renumber movie index of remaining components
renumberIndx=([userData.rawData(:).movieIndx]>i);
% Lame for loop as I didn't find a way to avoid it
for rawDataIndx =find(renumberIndx)
userData.rawData(rawDataIndx).movieIndx=userData.rawData(rawDataIndx).movieIndx -1;
end
end
end
% Remove component and update the selected value
userData.rawData(selectedComponents)=[];
selectedComponents = max(min(selectedComponents)-1,1);
set(handles.listbox_rawData,'Value',selectedComponents);
% Save data and update graphics
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
update_graphics(hObject,handles)
% --- Executes on button press in pushbutton_done.
function pushbutton_done_Callback(~, eventdata, handles)
userData = get(handles.figure1, 'UserData');
% Check all movies and channels have been attributed
if isempty(userData.rawData), return; end
checkMovies = any(cellfun(@isempty,{userData.rawData.movieIndx}));
if checkMovies,
errordlg('All components have not been affected to a movie','modal');
return;
end
checkChannels = any(cellfun(@isempty,{userData.rawData.chanIndx}));
if checkChannels,
errordlg('All components have not been affected to a channel','modal');
return;
end
wtBar = waitbar(0,'Please wait, ...');
% Read checkbox values
createMD=get(handles.checkbox_createMD,'Value');
splitSTK=get(handles.checkbox_splitSTK,'Value');
% Retrieve main window userData if applicable
if isfield(userData,'mainFig')
userData_main = get(userData.mainFig, 'UserData');
contentlist = get(userData.handles_main.listbox_movie, 'String');
end
nMovies=numel(userData.movies);
for iMovie=1:nMovies
% Create the movie folder
movieFolder=[userData.outputDir filesep userData.movies(iMovie).name];
if ~isdir(movieFolder), mkdir(movieFolder); end
waitbar(iMovie/nMovies,wtBar,['Please wait, setting up movie ' num2str(iMovie) ' ...']);
% Initialize Channel array (to be fetched in the MovieData constructor)
if createMD, MDChannels=[]; end
% Find all raw data components associated with that movie
rawDataList=find([userData.rawData.movieIndx]==iMovie);
for nRawData=rawDataList
% Retrieve the channel index and create the channel folder
chanIndx = userData.rawData(nRawData).chanIndx;
channelFolder = [movieFolder filesep userData.channels(chanIndx).name];
if ~isdir(channelFolder), mkdir(channelFolder); end
% Retrieve original rawDatafolder and copy/move the file
rawDataFolder = [userData.projectDir filesep userData.rawData(nRawData).dir];
rawDataBodyName = userData.rawData(nRawData).name;
rawDataExt = userData.rawData(nRawData).ext;
rawDataFiles=[rawDataFolder filesep rawDataBodyName '*' rawDataExt];
if strcmpi(rawDataExt,'.stk') && splitSTK
% Split STK files
stkFiles=dir(rawDataFiles);
if numel(stkFiles)>1
errordlg('Found more than one STK file for the movie');
continue;
end
try
currIm = stackRead([rawDataFolder filesep stkFiles(1).name]);
catch errMess
disp(['stackRead.m failed: ' errMess.message ' Trying tif3Dread.m instead...'])
%Tif3Dread is slower, but can open some files which the
%current stackRead version fails to open
currIm = tif3Dread([rawDataFolder filesep stkFiles(1).name]);
end
nIm = size(currIm,3); %Check number of images
%Get number of digits for writing file names
nDig = floor(log10(nIm)+1);
%Make the string for formatting
fString = strcat('%0',num2str(nDig),'.f');
%Write them all to new dir
disp(['Splitting "' stkFiles(1).name '" into ' num2str(nIm) ' seperate files...'])
for k = 1:nIm
imwrite(squeeze(currIm(:,:,k)),[channelFolder filesep stkFiles(1).name(1:end-4) '_' num2str(k,fString) '.tif']);
end
else
if get(handles.checkbox_copy,'Value')
copyfile(rawDataFiles,channelFolder);
else
movefile(rawDataFiles,channelFolder);
end
end
% Create a Channel object, and append it to the existing Channel
% array if applicable
if createMD && userData.channels(chanIndx).exportMD
try
newChannel = Channel(channelFolder);
set(newChannel, userData.channels(chanIndx).properties);
catch ME
throw(ME);
end
MDChannels = horzcat(MDChannels, newChannel);
end
end
if createMD
% Check all required channels have been set up
nFoundChannels =numel(MDChannels);
nExpectedChannels = sum([userData.channels.exportMD]);
if nFoundChannels ~= nExpectedChannels
errordlg('Not all channels were found. Skipped Movie Data creation!');
continue
end
% Save Movie Data to disk
movieDataFile = 'movieData.mat';
% Launch the MovieData constructor
try
MD = MovieData(MDChannels, movieFolder);
catch ME
errormsg = sprintf([ME.message '.\n\nCreating movie data failed.']);
errordlg(errormsg, 'User Input Error','modal');
continue;
end
% Check the movieData sanity
try
MD.movieDataPath_=movieFolder;
MD.movieDataFileName_=movieDataFile;
set(MD,userData.movies(iMovie).properties);
MD.sanityCheck;
catch ME
delete(MD);
errormsg = sprintf('%s.\n\nPlease check your movie data. Movie data is not saved.',ME.message);
errordlg(errormsg,'Channel Error','modal');
continue;
end
% Save the movie data
MD.save;
% Update main window components and controls if applicable
if isfield(userData,'mainFig')
if any(strcmp([movieFolder filesep movieDataFile], contentlist))
errordlg('Cannot overwrite a movie data file which is already in the movie list. Please choose another file name or another path.','Error','modal');
return
end
% Append new ROI to movie selector panel
userData_main.MD = horzcat(userData_main.MD, MD);
set(userData.mainFig, 'UserData', userData_main)
movieSelectorGUI('refreshDisplay',userData.mainFig,...
eventdata,guidata(userData.mainFig));
end
end
end
close(wtBar)
% Update main window components and controls if applicable
if isfield(userData,'mainFig')% Save the data
set(userData.mainFig, 'UserData', userData_main)
end
% Delete current window
delete(handles.figure1)
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
progressText.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/progressText.m
| 5,109 |
utf_8
|
169b0a5dad48dba34c507abd1d6a74a3
|
function progressText(fractionDone,text)
%PROGRESSTEXT shows progress of a loop as text on the screen
%
% SYNOPSIS: progressText(fractionDone,text)
%
% INPUT fractionDone: fraction of loop done (0-1)
% text (opt): {yourTexthere} : XX% done xx:xx:xx remaining
% Note: text can be changed for every call
% OUTPUT none
%
% EXAMPLE
% n = 1000;
% progressText(0,'Test run') % Create text
% for i = 1:n
% pause(0.01) % Do something important
% progressText(i/n) % Update text
% end
%
% REMARKS progressText will set lastwarn to ''
%
% created with MATLAB ver.: 7.4.0.287 (R2007a) on Windows_NT
%
% created by: jdorn based on progressbar.m
% DATE: 29-Jun-2007
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
persistent starttime lastupdate clearText printText finalText warnText clearWarn
% constants
nCharsBase = 27; % change this if changing output format
% Test input
if nargin < 1 || isempty(fractionDone)
fractionDone = 0;
end
if nargin < 2 || isempty(text)
text = '';
else
text = [text,' : '];
end
if fractionDone == 0 || isempty(starttime)
% set up everything
% Set time of last update to ensure calculation
lastupdate = clock - 1;
% Task starting time reference
starttime = clock;
% create fprintf-expression
printText = sprintf('%s%%2d%%%% done %%s remaining',text);
initialText = sprintf('%s 0%%%% done xx:xx:xx remaining',text);
finalText = sprintf('%s100%%%% done %%s elapsed',text);
% get length of fprintf expression
nChars = nCharsBase + length(text);
clearText = repmat('\b',1,nChars);
% print initialText and return
fprintf(1,initialText);
% %fprintfExpression removes old expression before overwriting
% fprintfExpression = [clearText printText];
% fprintfExpressionFinal = [clearText, finalText];
% empty warning
lastwarn('');
warnText = '';
clearWarn = '';
return
elseif ~isempty(text)
% text has been changed. Create fprintfExpressions first, then update
% clearText
printText = sprintf('%s%%2d%%%% done %%s remaining',text);
finalText = sprintf('%s100%%%% done %%s elapsed',text);
fprintfExpression = [clearText clearWarn printText, warnText];
fprintfExpressionFinal = [clearText, clearWarn, finalText, warnText, '\n'];
nChars = nCharsBase + length(text);
clearText = repmat('\b',1,nChars);
elseif ~isempty(lastwarn)
% add warnings to the end of the progressText
% find warning
w = lastwarn;
lastwarn('')
nw = length(w);
% erase warning
fprintf(1,repmat('\b',1,11+nw)); %--- is this correct???
% create new warnText
w = regexprep(w,['(',char(10),'\s+)'],' - ');
warnTextNew = sprintf('\n Warning @%7.3f%%%% done : %s ',100*fractionDone,w);
warnLength = length(warnTextNew) - 1; % subtract 2 for %%-sign
warnText = [warnText,warnTextNew];
fprintfExpression = [clearText clearWarn printText, warnText];
fprintfExpressionFinal = [clearText, clearWarn, finalText, warnText, '\n'];
% prepare cleanWarn for next time
clearWarn = [clearWarn,repmat('\b',1,warnLength)];
else
% all is normal. Just generate output
fprintfExpression = [clearText clearWarn printText, warnText];
fprintfExpressionFinal = [clearText, clearWarn, finalText, warnText, '\n'];
end
% write progress
percentDone = floor(100*fractionDone);
% get elapsed time
runTime = etime(clock,starttime);
% check whether there has been a warning since last time
% if ~isempty(lastwarn)
% lastwarn('');
% fprintfExpression = regexprep(fprintfExpression,'(\\b)*','\\n');
% fprintfExpressionFinal = regexprep(fprintfExpressionFinal,'(\\b)*','\\b\\n');
% end
if percentDone == 100 % Task completed
fprintf(1,fprintfExpressionFinal,convertTime(runTime)); % finish up
clear starttime lastupdate clearText printText finalText % Clear persistent vars
return
end
% only update if significant time has passed
if etime(clock,lastupdate) < 0.3
return
end
% update
timeLeft = runTime/fractionDone - runTime;
fprintf(1,fprintfExpression,percentDone,convertTime(timeLeft));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% subfcn
function timeString = convertTime(time)
timeStruct = sec2struct(time);
if timeStruct.hour > 99
timeString = '99:59:59';
else
timeString = timeStruct.str(1:end-4);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
getMultiplicity.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/getMultiplicity.m
| 1,713 |
utf_8
|
1ff95e962c1943b3db814735b84e7a35
|
% [r, udata, sdata] = getMultiplicity(data) returns the occurrences/Multiplicity of the elements of 'data'
%
% Inputs:
% data : n-dimensional input array
%
% Outputs:
% rep : # of occurrences for each element of 'data'
% udata : sorted 1-D array of unique values in 'data'
% sdata : sorted 1-D array of values in 'data'
%
% Note: NaN/Inf elements in input data are ignored
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Francois Aguet, 03/02/2012 (modified on 10/29/2012)
% Mark Kittisopikul, calculate udata only when requested, 09/11/2014
function [rep, udata, sdata] = getMultiplicity(data)
% fail quickly if data is empty
if(isempty(data))
rep = [];
udata = data;
sdata = data;
return;
end
if(~isinteger(data))
data = data(isfinite(data));
end
% sort
sdata = sort(data(:));
% store as row vector
sdata = sdata(:)';
% find where the numbers change in the sorted array
isDiff = [diff(sdata)~=0 1];
idx = find(isDiff);
if(nargout > 1)
udata = sdata(idx);
end
% count occurrences
rep = diff([0 idx]);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
readIXMHTDFileM.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/readIXMHTDFileM.m
| 3,478 |
utf_8
|
27632e6a934397be1be7145c0c4a7d57
|
function [wellFlags,siteFlags,wavelengthNames,hcsPlatestack]=readIXMHTDFileM(inputPath)
% locate the HTD file
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
htdFileName=dir(fullfile(inputPath, '*.HTD'));
if min(size(htdFileName)) == 0
wellFlags = 0;
siteFlags = 0;
wavelengthNames = 0;
return;
end
htdFileName=htdFileName(1).name;
% read in HTD file
fid=fopen([inputPath, filesep, htdFileName]);
% skip 4 lines
for i=1:4
fgetl(fid);
end
% read in number of columns/rows
xWells=readLastNumberFromLineofText(fid);
yWells=readLastNumberFromLineofText(fid);
% read in well flags
wellFlags=false(yWells,xWells);
for y=1:yWells
tline=fgetl(fid);
indx=strfind(tline,',');
for x=1:xWells
flag=tline(indx(x)+2);
if strcmp(flag,'T')
wellFlags(y,x)=true;
end
end
end
% skip 1 line
fgetl(fid);
% read in x,y grid dimension for different sites within the same well
xSites=readLastNumberFromLineofText(fid);
ySites=readLastNumberFromLineofText(fid);
% read in site flags
siteFlags=false(ySites,xSites);
for y=1:ySites
tline=fgetl(fid);
indx=strfind(tline,',');
for x=1:xSites
flag=tline(indx(x)+2);
if strcmp(flag,'T')
siteFlags(y,x)=true;
end
end
end
% skip 1 line
fgetl(fid);
% read in number of channels
nWavelengths=readLastNumberFromLineofText(fid);
% read in wavelength names
wavelengthNames=cell(nWavelengths,1);
for i=1:nWavelengths
tline=fgetl(fid);
indx=strfind(tline,'"');
wavelengthNames{i}=tline(indx(3)+1:indx(4)-1);
end
hcsPlatestack = plategenerator(wellFlags, siteFlags, wavelengthNames, htdFileName);
end
function n=readLastNumberFromLineofText(fid)
tline=fgetl(fid);
indx=strfind(tline,',');
n=tline(indx+1:end);
n=str2double(n);
end
function hcsPlatestack = plategenerator(wellFlags, siteFlags, wavelengthNames, htdFileName)
ct = 0;
h = waitbar(0, 'Loading HCS Images');
for i4 = 1:length(wavelengthNames)
for i1 = 1:size(wellFlags,1)
for i2 = 1:size(wellFlags,2)
if wellFlags(i1,i2) == 1
inH = regexp(htdFileName, '.HTD');
if i2 > 9
wellnstr = num2str(i2);
else
wellnstr = strcat('0', num2str(i2));
end
for i3 = 1:sum(sum(siteFlags))
ct = ct + 1;
if ct == 1
wpvr = i1; wphr = i2;
end
hcsPlatestack{i4}{i1-wpvr+1, i2-wphr+1}{i3} = strcat(htdFileName(1:inH-1),'_',char(i1 -1 + 'A'), wellnstr, '_',...
's', num2str(i3),'_','w', num2str(i4), '.TIF');
end
end
end
end
waitbar(i4/(length(wavelengthNames)));
end
close(h);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
packageGUI_RunFcn.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/packageGUI_RunFcn.m
| 9,238 |
utf_8
|
a58d65798ec676fa520ea6512eb24195
|
function packageGUI_RunFcn(hObject,eventdata,handles)
% Run the selected processes in the packageGUI interface
%
% This is a common section of code called by pushbutton_run_Callback
% when user click the "Run" button on package control panels.
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Chuangang Ren 11/2010
% Sebastien Besson 5/2011 (last modified Oct 2011)
ip = inputParser;
ip.addRequired('hObject',@ishandle);
ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x) || isa(x, 'event.EventData'));
ip.addRequired('handles',@isstruct);
ip.parse(hObject,eventdata,handles);
%% Initialization
% Get check box status of current movie and update user data
userData = get(handles.figure1,'UserData');
userData.statusM(userData.id).Checked = userfcn_saveCheckbox(handles);
set(handles.figure1, 'UserData', userData)
% Determine the movie(s) to be processed
if ~isempty(userData.MD), field='MD'; else field = 'ML'; end
nMovies = length(userData.(field)); % number of movies
if get(handles.checkbox_runall, 'Value')
movieList = circshift(1:nMovies,[0 -(userData.id-1)]);
else
movieList=userData.id;
end
% Get the list of valid movies (with processes to run)
hasValidProc = arrayfun(@(x) any(userData.statusM(x).Checked),movieList);
movieRun=movieList(hasValidProc);
procCheck=cell(1,numel(nMovies));
procCheck(movieRun)=arrayfun(@(x) find(userData.statusM(x).Checked),movieRun,...
'UniformOutput',false);
% Throw warning dialog if no movie
if isempty(movieRun)
warndlg('No step is selected, please select a step to process.',...
'No Step Selected','modal');
return
end
%% Pre-processing examination
% movie exception (same length of movie data)
movieException = cell(1, nMovies);
procRun = cell(1, nMovies);% id of processes to run
% Find unset processes
isProcSet=@(x,y)~isempty(userData.package(x).processes_{y});
isMovieProcSet = @(x) all(arrayfun(@(y)isProcSet(x,y),procCheck{x}));
invalidMovies=movieRun(~arrayfun(isMovieProcSet,movieRun));
for i = invalidMovies
invalidProc = procCheck{i}(arrayfun(@(y)~isProcSet(i,y),procCheck{i}));
for j=invalidProc
ME = MException('lccb:run:setup', ['Step %d : %s is not set up yet.\n'...
'\nTip: when step is set up successfully, the step name becomes bold.'],j,...
eval([userData.package(i).getProcessClassNames{j} '.getName']));
movieException{i} = horzcat(movieException{i}, ME);
end
end
validMovies=movieRun(arrayfun(isMovieProcSet,movieRun));
for iMovie = validMovies
% Check if selected processes have alrady be successfully run
% If force run, re-run every process that is checked
if ~get(handles.checkbox_forcerun, 'Value')
k = true;
for i = procCheck{iMovie}
if ~( userData.package(iMovie).processes_{i}.success_ && ...
~userData.package(iMovie).processes_{i}.procChanged_ ) || ...
~userData.package(iMovie).processes_{i}.updated_
k = false;
procRun{iMovie} = horzcat(procRun{iMovie}, i);
end
end
if k
movieRun = setdiff(movieRun, iMovie);
continue
end
else
procRun{iMovie} = procCheck{iMovie};
end
% Package full sanity check. Sanitycheck every checked process
[status procEx] = userData.package(iMovie).sanityCheck(true, procRun{iMovie});
% Return user data !!!
set(handles.figure1, 'UserData', userData)
invalidProcEx = procRun{iMovie}(~cellfun(@isempty,procEx(procRun{iMovie})));
for i = invalidProcEx
% Check if there is fatal error in exception array
if strcmp(procEx{i}(1).identifier, 'lccb:set:fatal') || ...
strcmp(procEx{i}(1).identifier, 'lccb:input:fatal')
% Sanity check error - switch GUI to the x th movie
if iMovie ~= userData.id
set(handles.popupmenu_movie, 'Value', iMovie)
% Update the movie pop-up menu in the main package GUI
packageGUI('switchMovie_Callback',handles.popupmenu_movie, [], handles)
end
userfcn_drawIcon(handles,'error', i, procEx{i}(1).message, true);
ME = MException('lccb:run:sanitycheck','Step %d %s: \n%s',...
i,userData.package(iMovie).processes_{i}.getName, procEx{i}(1).message);
movieException{iMovie} = horzcat(movieException{iMovie}, ME);
end
end
% Refresh user data !!!
userData = get(handles.figure1, 'UserData');
end
%% Pre-processing exception report
if isempty(movieRun)
warndlg('All selected steps have been processed successfully. Please check the ''Force Run'' check box if you want to re-process the successful steps.','No Step Selected','modal');
return
end
status = generateReport(movieException,userData,'preprocessing');
if ~status, return; end
%% Start processing
if strcmp(get(handles.menu_debug_enter,'Checked'),'on'), dbstop if caught error; end
for i=1:length(movieRun)
iMovie = movieRun(i);
if iMovie ~= userData.id
% Update the movie pop-up menu in the main package GUI
set(handles.figure1, 'UserData', userData)
set(handles.popupmenu_movie, 'Value', iMovie)
% Update the movie pop-up menu in the main package GUI
packageGUI('switchMovie_Callback',handles.popupmenu_movie, [], handles)
userData = get(handles.figure1, 'UserData');
end
% Clear icons of selected processes
% Return user data !!!
set(handles.figure1, 'UserData', userData)
userfcn_drawIcon(handles,'clear',procRun{iMovie},'',true); % user data is retrieved, updated and submitted
% Refresh user data !!!
userData = get(handles.figure1, 'UserData');
set(handles.text_status, 'Visible', 'on')
% Run algorithms!
try
% Return user data !!!
set(handles.figure1, 'UserData', userData)
for procID = procRun{iMovie}
set(handles.text_status, 'String', ...
sprintf('Step %d - Processing %d of %d movies total ...', procID, i, length(movieRun)) )
userfcn_runProc_dfs(procID, procRun{iMovie}, handles); % user data is retrieved, updated and submitted
end
catch ME
% Save the error into movie Exception cell array
ME2 = MException('lccb:run:error','Step %d: %s',...
procID,userData.package(iMovie).processes_{procID}.getName);
movieException{iMovie} = horzcat(movieException{iMovie}, ME2);
movieException{iMovie}=movieException{iMovie}.addCause(ME);
procRun{iMovie} = procRun{iMovie}(procRun{iMovie} < procID);
% Refresh wall status
packageGUI_RefreshFcn(handles,'initialize');
end
% Refresh user data !!!
userData = get(handles.figure1, 'UserData');
set(handles.pushbutton_run, 'Enable', 'on')
set(handles.checkbox_forcerun, 'Enable', 'on')
set(handles.checkbox_runall, 'Enable', 'on')
set(handles.text_status, 'Visible', 'off')
% Return user data !!!
set(handles.figure1, 'UserData', userData)
end
if strcmp(get(handles.menu_debug_enter,'Checked'),'on'), dbclear if caught error; end
%% Post-processing exception report
status = generateReport(movieException,userData,'postprocessing');
if status
successMsg = 'Your movie(s) have been processed successfully.';
userData.iconHelpFig = helpdlg(successMsg, [userData.crtPackage.getName]);
set(handles.figure1, 'UserData', userData)
end
% Delete waitbars
hWaitbar = findall(0,'type','figure','tag','TMWWaitbar');
delete(hWaitbar);
end
function userfcn_runProc_dfs (procID, procRun, handles) % throws exception
% Set user Data
userData = get(handles.figure1, 'UserData');
parentRun = [];
parentID=userData.crtPackage.getParent(procID);
% if current process procID have dependency processes
for j = parentID
% if parent process is one of the processes need to be run
% if parent process has already run successfully
if any(j == procRun) && ~userData.crtPackage.processes_{j}.success_
parentRun = horzcat(parentRun,j); %#ok<AGROW>
end
end
% if above assumptions are yes, recursively run parent process' dfs fcn
for j = parentRun
userfcn_runProc_dfs (j, procRun, handles)
end
try
userData.crtPackage.processes_{procID}.run(); % throws exception
catch ME
rethrow(ME)
end
% Refresh wall status
packageGUI_RefreshFcn(handles,'initialize');
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
TracksDisplay.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/TracksDisplay.m
| 10,460 |
utf_8
|
6d2510617ad57c883a53ffbdabee9435
|
classdef TracksDisplay < MovieDataDisplay
%Conrete class for displaying flow
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
properties
Linestyle='-';
Linewidth=1;
GapLinestyle='--';
Color = 'r';
MergeColor = 'y';
MergeMarker = 's';
SplitColor = 'g';
SplitMarker = 's';
useDragtail=true;
dragtailLength=10;
showLabel=false;
markMergeSplit=false;
ButtonDownFcn=[];
end
methods
function obj=TracksDisplay(varargin)
nVarargin = numel(varargin);
if nVarargin > 1 && mod(nVarargin,2)==0
for i=1 : 2 : nVarargin-1
obj.(varargin{i}) = varargin{i+1};
end
end
end
function h=initDraw(obj, tracks, tag, varargin)
if isempty(tracks), h = -1; return; end
% Get track length and filter valid tracks
trackLengths = cellfun(@numel,{tracks.xCoord});
validTracks = find(trackLengths>0);
tracks = tracks(validTracks);
trackLengths = trackLengths(validTracks);
nTracks = numel(validTracks);
% Constraing the dragtail length between 2 and the maximum
% track length
if obj.useDragtail
dLength = max(2,min(obj.dragtailLength,max(trackLengths)));
else
dLength = max(trackLengths);
end
% Concatenate data in a matrix of size dragtailLength x nTracks
xData = NaN(dLength, nTracks);
yData = NaN(dLength, nTracks);
displayLength = trackLengths;
displayLength(trackLengths > dLength) = dLength;
for i = 1 : nTracks
xData(1:displayLength(i), i) = tracks(i).xCoord(end-displayLength(i)+1:end);
yData(1:displayLength(i), i) = tracks(i).yCoord(end-displayLength(i)+1:end);
end
% Initialize matrix for gaps
xGapData = NaN(size(xData));
yGapData = NaN(size(xData));
% Label gaps: series of NaNs not-connected to the border
I = isnan(xData);
I = [I; zeros(size(I))];
I = reshape(I, size(I,1)/2, size(I,2)*2);
I = [zeros(size(I,1), 1) I];
I = imclearborder(I);
I = bwlabel(I);
I = I(:, 2:2:end);
% Fill gaps x and y data
for i = unique(nonzeros(I))'
iFirst = find(I == i, 1, 'first')-1;
iLast = find(I == i, 1, 'last')+1;
xGapData(iFirst:iLast) = linspace(xData(iFirst), xData(iLast), iLast - iFirst +1);
yGapData(iFirst:iLast) = linspace(yData(iFirst), yData(iLast), iLast - iFirst +1);
end
% Initialize matrix for split events
if(isfield(tracks,'events'))
hasSplitEvents = arrayfun(@(x) ~isempty(strfind(x.events,'s')),tracks);
else
hasSplitEvents = false(size(tracks));
end
xSplitData = NaN(dLength, nTracks);
ySplitData = NaN(dLength, nTracks);
for i = find(hasSplitEvents)'
eventTimes = tracks(i).events == 's';
eventTimes = find([ eventTimes false ] | [false eventTimes]);
dragtailWindow = [trackLengths(i) - displayLength(i) + 1 trackLengths(i)];
eventTimes = eventTimes(eventTimes >= dragtailWindow(1) & eventTimes <= dragtailWindow(2));
xSplitData(eventTimes - dragtailWindow(1) +1, i) = tracks(i).xCoord(eventTimes);
ySplitData(eventTimes - dragtailWindow(1) +1, i) = tracks(i).yCoord(eventTimes);
end
% Initialize matrix for split events
if(isfield(tracks,'events'))
hasMergeEvents = arrayfun(@(x) ~isempty(strfind(x.events,'m')),tracks);
else
hasMergeEvents = false(size(tracks));
end
xMergeData = NaN(dLength, nTracks);
yMergeData = NaN(dLength, nTracks);
for i = find(hasMergeEvents)'
eventTimes = tracks(i).events == 'm';
eventTimes = find([ eventTimes false ] | [false eventTimes])-1;
dragtailWindow = [trackLengths(i) - displayLength(i) + 1 trackLengths(i)];
eventTimes = eventTimes(eventTimes >= dragtailWindow(1) & eventTimes <= dragtailWindow(2));
xMergeData(eventTimes - dragtailWindow(1) +1, i) = tracks(i).xCoord(eventTimes);
yMergeData(eventTimes - dragtailWindow(1) +1, i) = tracks(i).yCoord(eventTimes);
end
% Plot tracks
if isfield(tracks,'label') % If track is classified
nColors = size(obj.Color,1);
h = -ones(nColors,2);
for iColor = 1:nColors
iTracks = mod([tracks.label]-1, nColors) +1 == iColor;
h(iColor,1)=plotFast(h(iColor,1),xData(:,iTracks),yData(:,iTracks),'Linestyle',obj.Linestyle,...
'Linewidth', obj.Linewidth, 'Color',obj.Color(iColor,:),varargin{:});
h(iColor,2)=plotFast(h(iColor,2),xGapData(:,iTracks),yGapData(:,iTracks),'Linestyle',obj.GapLinestyle,...
'Linewidth', obj.Linewidth, 'Color', obj.Color(iColor,:),varargin{:});
end
else
% Plot links and gaps
h=-ones(4,1);
splitMarker = 'none';
mergeMarker = 'none';
if(obj.markMergeSplit)
splitMarker = obj.SplitMarker;
mergeMarker = obj.MergeMarker;
end
h(1) = plotFast(h(1),xData, yData, 'Linestyle', obj.Linestyle,...
'Linewidth', obj.Linewidth, 'Color',obj.Color,varargin{:});
h(2) = plotFast(h(2),xGapData, yGapData, 'Linestyle', obj.GapLinestyle',...
'Linewidth', obj.Linewidth, 'Color',[1 1 1] - obj.Color, varargin{:});
h(3) = plotFast(h(3),xSplitData, ySplitData, 'Linestyle', obj.Linestyle,...
'Linewidth', obj.Linewidth, 'Color', obj.SplitColor , 'Marker', splitMarker , varargin{:});
h(4) = plotFast(h(4),xMergeData, yMergeData, 'Linestyle', obj.Linestyle,...
'Linewidth', obj.Linewidth, 'Color', obj.MergeColor, 'Marker', mergeMarker , varargin{:});
end
% Display track numbers if option is selected
if obj.showLabel
hlabels = -ones(nTracks,1);
for i = find(~all(isnan(xData),1))
trackNr = num2str(tracks(i).number);
% Find last non-NaN coordinate
index = find(~isnan(xData(:,i)),1,'last');
if isfield(tracks,'label')
iColor = mod(tracks(i).label, nColors) + 1;
hlabels(i) = text(xData(index,i)+2, yData(index,i)+2, trackNr,...
'Color', obj.Color(iColor,:));
else
hlabels(i) = text(xData(index,i)+2, yData(index,i)+2, trackNr,...
'Color', obj.Color);
end
end
h = [h(:) ; hlabels ];
end
% Set tag
set(h(ishandle(h)), 'Tag', tag, 'ButtonDownFcn', obj.ButtonDownFcn);
end
function updateDraw(obj, h, data)
tag=get(h(1),'Tag');
delete(h);
obj.initDraw(data,tag);
return;
end
end
methods (Static)
function params=getParamValidators()
params(1).name='Color';
params(1).validator=@(x)ischar(x) ||isvector(x);
params(2).name='Linestyle';
params(2).validator=@ischar;
params(3).name='GapLinestyle';
params(3).validator=@ischar;
params(4).name='dragtailLength';
params(4).validator=@isscalar;
params(5).name='showLabel';
params(5).validator=@isscalar;
params(6).name='useDragtail';
params(6).validator=@islogical;
params(7).name='MergeColor';
params(7).validator=@(x)ischar(x) ||isvector(x);
params(8).name='SplitColor';
params(8).validator=@(x)ischar(x) ||isvector(x);
params(9).name='ButtonDownFcn';
params(9).validator=@(x) isempty(x) || isa(x, 'function_handle');
params(10).name='markMergeSplit';
params(10).validator=@isscalar;
end
function f=getDataValidator()
f=@isstruct;
end
end
end
function h = plotFast(h,xData,yData,varargin)
%plotFast Uses the low-level plotting function line to plot matrices by
%separate lines into a single line with gaps while also trying to avoid
%creating a new object.
%
% INPUT
% h - handle to update if valid
% xData - same as given to plot, can be a matrix where columns are separate
% lines
% yData - same as given to plot, can be a matrix where columns are separate
% lines
% varargin - passes through extra parameters to the line function
%
% OUTPUT
%
% h - handle to the line object created or used
%
% Mark Kittisopikul, 2014/11/24
xData(end+1,:) = NaN;
yData(end+1,:) = NaN;
if(ishandle(h))
set(h,'XData',xData(:),'YData',yData(:),varargin{:});
else
h = line(xData(:),yData(:),varargin{:});
if(isempty(h))
h = -1;
end
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
GaussFitND.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/GaussFitND.m
| 23,268 |
utf_8
|
16617d7108993175ed8823c81033305b
|
function [parameters,sigmaParameters,Q,chiSquared,degreesOfFreedom,...
residualImage,resAndGauss] = GaussFitND(intensities, coordList, ...
fitParameters, parameters, isNormed, fitOptions)
%GAUSSFITND fits one or several N-D Gaussians to an input intensity distribution
%
% SYNOPSIS: [parameters,sigmaParameters,Q,chiSquared,degreesOfFreedom,...
% residualImage,resAndGauss] = GaussFitND(intensities, coordList, ...
% fitParameters, parameters, isNormed, fitOptions)
%
% INPUT intensities: Vector with the image intensities. Alternatively, you
% can supply the n-d image directly.
% coordList: nCoord-by-nDims list of coordinates corresponding to
% every intensity in the image list. If you supplied the
% image directly, you can pass empty here and GaussFitND will
% calculate the coordinateList for you.
% fitParameters: Cell array of strings that lists the parameters that
% should be fitted
% -'X#' position in dimension #
% -'A' amplitude
% -'S#' sigma in dimension # (Sxy if S1 and S2 are identical)
% -'B' background (has to be the last parameter!)
% parameters: All the parameters (including initial guesses)
% necessary to describe the N-D Gaussian:
% [X1...n,A,S1...n,B]. If S1==S2, you specify SXY instead of
% S1 and S2 (will result in one parameter less).If you have
% no idea about the value of a specific parameter, supply
% NaN, and the code will estimate the parameter.
% If you want to jointly fit multiple kernels, supply
% multiple rows of parameters (the background is assumed to
% be constant, though) If you do so, you cannot enter
% NaNs as parameters, because the estimation will be
% meaningless.
% isNormed: (opt) Whether the Gaussian should be normed to an
% integral of 1. [{0}/1]. Only relevant for sigma-fitting,
% when the input is normed already, and thus the amplitude is
% not a fit-parameter.
% fitOptions: (opt) Options for lsqnonlin. It is not recommended
% that you set 'Jacobian' to 'off'
% Default options
% TolFun 1e-20
% TolX 1e-3
% Display 'off'
%
% OUTPUT parameters: Descriptors of the Gaussian(s) in the same order as
% the initialGuess
% sigmaParameters: uncertainty in the parameters
% sqrt(diag(Q)*chiSquared)
% Q : covariance matrix of the unknowns
% chiSquared : variance of the residuals
% degreesOfFreedom : degrees of freedom
% residualImage : n-d matrix of residuals (NaN where there is no
% intensity given)
%
%
% created with MATLAB ver.: 7.1.0.246 (R14) Service Pack 3 on Windows_NT
%
% created by: jdorn
% DATE: 04-Mar-2006
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
%============================
% TEST INPUT
%============================
% defaults
def_isNormed = 0;
def_fitOptions = optimset('Display','off','Jacobian','on','TolFun',1e-20,'TolX',1e-3);
verbose = 0; % displays parameters
noFit = 0; % if 1, only estimation is done, but not actual fitting
% nargin
% if nargin < 4 || isempty(fitParameters) || isempty(parameters) || isempty(coordList) || isempty(intensities)
if nargin < 4 || isempty(fitParameters) || isempty(parameters) || isempty(intensities)
error('not enough input arguments for GaussFitND!')
end
% check whether we have to create the coordList ourselves
if isempty(coordList)
sizeInt = size(intensities);
nd = length(sizeInt);
% check for vector
if nd == 2 && any(sizeInt == 1)
% for a vector, coordList is just 1:n
coordList = (1:length(intensities))';
else
% make coordList with eval to have n-dims
inputString = sprintf('1:%i,',sizeInt);
inputString = inputString(1:end-1);
eval(['[',sprintf('X%i ',1:nd),']=ndgrid(' inputString ');']);
eval(['coordList=[',sprintf('X%i(:) ',1:nd),'];']);
end
end
% make sure image is a list
intensities = intensities(:);
% get dimensionality
nDims = size(coordList,2);
nCoords = size(coordList,1);
if nCoords ~= length(intensities)
error('GaussFitND needs the coordinate of every pixel/voxel')
end
% check number of parameters. It can either be d+1+d+1 or d+1+(d-1)+1,
% depending on whether we have sxy or not
nParameters = size(parameters,2);
if nParameters == 2*nDims+2
isSxy = 0;
elseif nParameters == 2*nDims+1
isSxy = 1;
else
error('You have to specify all the parameters for the %i-d Gaussian!',nDims)
end
% get the number of kernels
nKernels = size(parameters,1);
% check the number of fitParameters
nFitParameters = length(fitParameters);
if ~iscell(fitParameters) || nFitParameters > nParameters
error(['FitParameters has to be a cell array of strings',...
'no longer than the number of parameters of the Gaussian!'])
end
% check optional input
if nargin < 5 || isempty(isNormed);
isNormed = def_isNormed;
end
if nargin < 6
fitOptions = def_fitOptions;
else
fitOptions = optimset(def_fitOptions,fitOptions);
end
% check nargout
if nargout > 1
doStatistics = 1;
else
doStatistics = 0;
end
%==========================
%==========================
% ESTIMATE PARAMETERS
%==========================
if verbose
for i=1:nKernels
disp(sprintf(['orig parms ',repmat('%1.4f ',1,nParameters)],parameters(i,:)))
end
end
if any(isnan(parameters))
% test whether we can estimate at all
if nKernels > 1 || nDims > 3
error('Parameter estimation has not been implemented for multiple kernels or more than 3 dimensions')
end
% make full image from coordList. Put NaN wherever there is nothing
% transform to 1:n
tmpCoordList = coordList;
minList = min(tmpCoordList,[],1);
tmpCoordList = tmpCoordList - repmat(minList,nCoords,1) + 1;
% minimum image size is the maximum coordinates
maxList = max(tmpCoordList,[],1);
fullImage = repmat(NaN,maxList);
% to assign values, coordinates must be indices, and sub2Ind doesn't accept
% a coordinate matrix
tmpCoordList = mat2cell(tmpCoordList,nCoords,ones(1,nDims));
tmpIdxList = sub2ind(maxList,tmpCoordList{:});
% assign intensities, have NaN otherwise
fullImage(tmpIdxList) = intensities;
% find parameters to estimate. Get NaN-indices so that we can
% (theoretically) have only some of the centers or sigmas estimated
centerIdx = find(isnan(parameters(1:nDims)));
backgroundIdx = find(isnan(parameters(end)));
amplitudeIdx = find(isnan(parameters(nDims+1)));
sigmaIdx = find(isnan(parameters(nDims+2:end-1)));
% do estimation only for up to 3D images, as I'm not going to write a
% n-d centroid code right now
% estimate center
if any(centerIdx)
% find centroid. Use exponent 10 to become a bit less sensitive to
% noise. - Unfortunately, this means being more sensitive to
% asymmetries, but that's why we do fitting
center = centroid3D(fullImage,10);
% transform center
center = center(1:nDims) + minList - 1;
% assign parameters
parameters(centerIdx) = center(centerIdx);
end
% read new center. Transform to fullImage coordinates
center = parameters(1:nDims) - minList + 1;
% estimate background
if any(backgroundIdx)
% background is taken as the median of all the border pixels. If all is
% NaN-masked, we might get only a few pixels to estimate the background
% from, but at least they will be fairly definite background pixels.
bgIdx = zeros(nCoords,nDims);
% get border pixels by finding min and max coordinates along everz
% dimension
for i=1:nDims
bgIdx(:,i) = tmpCoordList{i} == 1 | tmpCoordList{i} == maxList(i);
end
bgIdx = any(bgIdx,2);
parameters(end) = nanmedian(fullImage(tmpIdxList(bgIdx)));
end
% read background and subtract
background = parameters(end);
fullImage = fullImage - background;
if any(amplitudeIdx) && ~isNormed
% amplitude is the maximum of a 3^nDims pixel region around the center.
% Stamp3D is another of those functions that would have to be extended
% for N-D.
% if isNormed, there is no need for estimating amplitude
subImage = stamp3d(fullImage,repmat(3,[1,nDims]),floor(center));
parameters(nDims+1) = max(subImage(:));
end
% read amplitude, make image into 0/1
amplitude = parameters(nDims+1);
fullImage = fullImage./amplitude;
if any(sigmaIdx)
% for sigma: Threshold image at 1/sqrt(e) For a Gaussian, the width of
% the remaining image should be two sigma
fullImage = fullImage>exp(-0.5);
% find largest group in threshold
fullImage = bwlabeln(fullImage);
[number,entry] = getMultiplicity(fullImage(:));
[dummy,idx] = max(number(2:end));
% get indices of largest group
idx = find(fullImage == entry(idx+1));
% get coordinates of largest group. Limit to 3D
[cx,cy,cz] = ind2sub(maxList,idx);
coords = [cx,cy,cz];
minCoords = min(coords(:,1:nDims),[],1);
maxCoords = max(coords(:,1:nDims),[],1);
% sigma is half the extent of the thresholded region
sigma = (maxCoords-minCoords+1)/2;
% take care of Sxy
if isSxy
sigmaXY = mean(sigma(1:2));
sigma = [sigmaXY,sigma(3:end)];
end
parameters(nDims+1+sigmaIdx) = sigma(sigmaIdx);
end
% no need to read sigma here
if verbose
for i=1:nKernels
disp(sprintf(['est parms ',repmat('%1.4f ',1,nParameters)],parameters(i,:)))
end
end
end % if estimate
%==========================
if noFit
if nargout > 1
[Q,chiSquared,degreesOfFreedom]=deal([]);
end
return
end
%==========================
% FIT
%==========================
% Choose fitting scheme:
% a) if sigmas are fixed, do all at once
% b) if not, do iterative fitting
anyAmplitude = any(strncmpi('a',fitParameters,1));
bgIdx = find(strncmpi('b',fitParameters,1));
anyBackground = any(bgIdx);
if anyBackground && any(bgIdx < nFitParameters)
error('for fitting, background has to be at the last position in the fitParameters')
end
% In case we fit the amplitude: make amplitude comparable in magnitude to coordinates to
% avoid fitting problems. The amplitudes (max of image-background)
% are set to be roughly the average of the coordinates. Accordingly, the
% intensities and the background will have to be scaled, too!
if anyAmplitude || anyBackground
% yes, coordList is correct here!
%intensityScaling = mean(abs(coordList(:))) / max(intensities - parameters(1,end));
% when things didn't work as with the MMF, I tried the very simple 0..1
% norm from fitTest. Surprisingly, it works. In other words, the
% norming of the amplitude is something that should be investigated
% further - but I don't have the time right now.
intensityScaling = 1/max(intensities);
parameters(:,[nDims+1,end]) = ...
parameters(:,[nDims+1,end]) * intensityScaling;
intensities = intensities * intensityScaling;
end
% mask image
mask = zeros(size(intensities));
for k = 1:nKernels
dist = normList(coordList-repmat(parameters(k,1:nDims),nCoords,1));
% % mask = mask | dist < 3*parameters(k,nDims+2);
mask = mask | dist < 4*parameters(k,nDims+2); %--KJ (more reliable fit with bigger area)
end
intensities = intensities(mask);
coordList = coordList(mask,:);
nCoords = size(coordList,1);
%if fitSigma
% check for whether sigmas are to be fitted.
%fitSigma = any(strncmpi('s',fitParameters,1));
if 0
% % do iterative fitting
% % check for what we have to fit at all
% anyCenter = any(strncmpi('x',fitParameters,1));
%
% for i=1:3
% % fit center if necessary
% if anyCenter
% % create xIdx
% xIdx = (1:nKernels*nDims)';
% % define fitFcn
% fitFcn = @(x)(GaussFitND_lsqnonlinFitFcn(x,fitParameters,parameters,xIdx,intensities,coordList,isNormed));
% % fit
% x = lsqnonlin(...
% fitFcn,parameters(xIdx),[],[],fitOptions);
% % update parameters
% parameters(xIdx) = x;
% if verbose
% for i=1:nKernels
% disp(sprintf(['fitC parms ',repmat('%1.4f ',1,nParameters)],parameters(i,:)))
% end
% end
% end
%
% if anyAmplitude || anyBackground
% % create xIdx
% xIdx = zeros(nKernels*anyAmplitude + anyBackground,1);
% if anyAmplitude
% xIdx(1:nKernels) = nKernels*nDims+1 : nKernels*(nDims+1);
% end
% if anyBackground
% xIdx(end) = nParameters * nKernels;
% end
%
% % define fitFcn
% fitFcn = @(x)(GaussFitND_lsqnonlinFitFcn(...
% x,fitParameters,parameters,xIdx,intensities,coordList,isNormed));
% % fit
% x = lsqnonlin(...
% fitFcn,parameters(xIdx),[],[],fitOptions);
% % update parameters
% parameters(xIdx) = x;
% if verbose
% for i=1:nKernels
% disp(sprintf(['fitA parms ',repmat('%1.4f ',1,nParameters)],parameters(i,:)))
% end
% end
%
% end
%
% % fit sigma.
% % create xIdx
% xIdx = (nKernels*(nDims+1)+1:nKernels*(nDims*2+1-isSxy))';
% % define fitFcn
% fitFcn = @(x)(GaussFitND_lsqnonlinFitFcn(...
% x,fitParameters,parameters,xIdx,intensities,coordList,isNormed));
% % fit
% x = lsqnonlin(...
% fitFcn,parameters(xIdx),[],[],fitOptions);
% % update parameters
% parameters(xIdx) = x;
% if verbose
% for i=1:nKernels
% disp(sprintf(['fitS parms ',repmat('%1.4f ',1,nParameters)],parameters(i,:)))
% end
% end
% end % loop iterative fitting
%
%
% % undo intensity scaling
% if anyAmplitude || anyBackground
% parameters(:,[nDims+1,end]) = ...
% parameters(:,[nDims+1,end]) / intensityScaling;
% intensities = intensities / intensityScaling;
% end
%
% if doStatistics
%
% % get jacobian, residuals for statistics. Find xIdx again
% xIdx = [];
% if anyCenter
% xIdx = [xIdx;(1:nKernels*nDims)'];
% end
% if anyAmplitude || anyBackground
% % create xIdx
% tmp = zeros(nKernels*anyAmplitude + anyBackground,1);
% if anyAmplitude
% tmp(1:nKernels) = nKernels*nDims+1 : nKernels*(nDims+1);
% end
% if anyBackground
% tmp(end) = nParameters * nKernels;
% end
% xIdx = [xIdx;tmp];
% end
% % we'll always be fitting sigma
% xIdx = [xIdx;(nKernels*(nDims+1)+1:nKernels*(nDims*2+1-isSxy))'];
%
% % get residuals and jacobian
% [residuals, jacobian] = ...
% GaussFitND_lsqnonlinFitFcn(parameters(xIdx),...
% fitParameters,parameters,xIdx,intensities,coordList,isNormed);
% end
else
% do one-step fitting
% find the indices of the parameters that have to be fitted, and add to
% xIdx
xIdx = GaussFitND_xIdx(fitParameters,nFitParameters,nParameters,nKernels,nDims,isSxy);
% define fitFcn
fitFcn = @(x)(GaussFitND_lsqnonlinFitFcn(...
x,fitParameters,parameters,xIdx,intensities,coordList,isNormed,nDims,isSxy));
% fit
x = lsqnonlin(...
fitFcn,parameters(xIdx),[],[],fitOptions);
% update parameters
parameters(xIdx) = x;
parameters(:,end) = parameters(end);
% undo intensity scaling
if anyAmplitude || anyBackground
parameters(:,[nDims+1,end]) = ...
parameters(:,[nDims+1,end]) / intensityScaling;
intensities = intensities / intensityScaling;
end
if doStatistics
% get residuals and jacobian
[residuals, jacobian, gaussian] = ...
GaussFitND_lsqnonlinFitFcn(parameters(xIdx),...
fitParameters,parameters,xIdx,intensities,coordList,isNormed,nDims,isSxy);
end
end
if verbose
for i=1:nKernels
disp(sprintf(['end parms ',repmat('%1.4f ',1,nParameters)],parameters(i,:)))
end
end
%=======================
%=======================
% Calculate statistics
%=======================
if doStatistics
% calculate chi squared of fit, covarianceMatrix
degreesOfFreedom = (nCoords-nFitParameters);
chiSquared= sum(residuals.^2)/degreesOfFreedom;
Q=inv(jacobian'*jacobian);
sp = sqrt(chiSquared*diag(Q));
% reshape sigmaParameters so that it looks like parameters
sigmaParameters = repmat(NaN,size(parameters));
sigmaParameters(xIdx) = sp;
sigmaParameters(:,end) = sigmaParameters(end);
if nargout > 5
% make residual image
tmpCoordList = coordList;
minList = min(tmpCoordList,[],1);
tmpCoordList = tmpCoordList - repmat(minList,nCoords,1) + 1;
% minimum image size is the maximum coordinates
maxList = max(tmpCoordList,[],1);
residualImage = repmat(NaN,maxList);
% to assign values, coordinates must be indices, and sub2Ind doesn't accept
% a coordinate matrix
tmpCoordList = mat2cell(tmpCoordList,nCoords,ones(1,nDims));
tmpIdxList = sub2ind(maxList,tmpCoordList{:});
% assign intensities, have NaN otherwise
residualImage(tmpIdxList) = residuals;
if nargout > 6
resAndGauss = [residuals,gaussian];
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [residuals, jacobian, gaussian] = GaussFitND_lsqnonlinFitFcn(x,fitParameters,parameters,xIdx,intensities,coordList,isNormed,nDims,isSxy)
% GaussFitND_lsqnonlinFitFcn is the fit-routine in GaussFitND
% input: x: vector of unknowns.
% fitParameters: 'labels' of the unknowns.
% parameters: vector with all the data necessary to describe the
% Gaussian.
% xIdx: index to place the unknowns in the parameter array
% intensities : data to be fitted
% coordList : coordinate corresponding to the intensities
% isNormed : whether Gaussian is normed or not
% fill in parameters
parameters(xIdx) = x;
parameters(:,end) = parameters(end);
% check for amplitude norm - if normed, amplitude is a function of sigma.
% Fill it in.
if isNormed
% amplitude is 1/(2*pi)^(nDims/2)*1/(sx*sy*sz)
sigmas = parameters(:,end-(nDims-isSxy):end-1);
if isSxy
sigmas(:,1) = sigmas(:,1).^2;
end
parameters(:,nDims+1) = 1/(2*pi)^(nDims/2)*1./prod(sigmas,2);
end
% calculate gradient, Gaussian
[jacobian,gaussian] = ...
GaussFitND_gradient(fitParameters,parameters,coordList,isNormed);
% get residuals
residuals = gaussian - intensities;
% disp parameters, suggested step
% disp(sprintf(['parms ',repmat('%1.4f ',1,length(parameters))],parameters))
% step = jacobian \ residuals;
% disp(sprintf(['step ',repmat('%1.4f ',1,length(step))],step))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xIdx = GaussFitND_xIdx(fitParameters,nFitParameters,nParameters,nKernels,nDims,isSxy)
% GaussFitND_xIdx finds the incides of the parameters that have to be
% fitted.
% find the indices of the parameters that have to be fitted, and add to
% xIdx
% If we also fit the background, there will only be one index (the very
% last)
% xIdx should be in rows, i.e. if there are two kernels, there should first
% be all the indices to the first kernel, then all the indices to the
% second kernel etc.
fitBg = any(strncmpi('b',fitParameters,1));
% xIdx = zeros((nFitParameters - fitBg) * nKernels + fitBg,1);
% if fitBg
% xIdx(end) = nParameters * nKernels;
% end
xIdx = zeros(nFitParameters - fitBg,nKernels);
% we don't need to go over background (we force it to be at the end of the
% list earlier in the program)
for iParm = 1:nFitParameters - fitBg
currentParm = fitParameters{iParm};
switch currentParm(1)
case {'X','x'}
% read dimension
currentDim = str2double(currentParm(2:end));
% add index to xIdx
xIdx(iParm,:) = (currentDim-1) * nKernels + 1 : currentDim * nKernels;
case {'S','s'}
% take care of the special case sxy
if strcmpi(currentParm(2:end),'xy')
% use sx. Also correct for the fact that sigmas start
% after center and amplitude
currentDim = 1 + nDims + 1;
else
% get dimension. If there is a sxy, we lack S2. Also
% correct for the fact that sigmas start after center
% and amplitude
currentDim = str2double(currentParm(2:end)) - isSxy;
currentDim = currentDim + nDims + 1;
end
% add index to xIdx
xIdx(iParm,:) =...
(currentDim-1) * nKernels + 1 : currentDim * nKernels;
case {'A','a'}
% add index to xIdx
xIdx(iParm,:) = ...
nDims * nKernels + 1 : (nDims+1) * nKernels;
case {'B','b'}
% we've taken care of that already
otherwise
error('fitParameter ''%s'' not recognized!',currentParm)
end % switch fitParm
end % loop fitParm
% make xIdx into a vector, add background
if fitBg
xIdx = [xIdx(:);nKernels*nParameters];
else
xIdx = xIdx(:);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
fitGaussianMixtures2D.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/fitGaussianMixtures2D.m
| 9,530 |
utf_8
|
d8f05a5e90ee9768227c3838d6aed570
|
% pStruct = fitGaussianMixtures2D(img, x, y, A, sigma, c, mode, varargin)
%
% Inputs: img : input image
% x : initial (or fixed) x-positions
% y : initial (or fixed) y-positions
% A : initial (or fixed) amplitudes
% s : initial (or fixed) Gaussian PSF standard deviations
% c : initial (or fixed) background intensities
% mode : string selector for optimization parameters, any of 'xyAsc'
%
% Optional inputs : ('Mask', mask) pair with a mask of spot locations
%
%
% Output: pStruct: structure with fields:
% x : estimated x-positions
% y : estimated y-positions
% A : estimated amplitudes
% s : estimated standard deviations of the PSF
% c : estimated background intensities
%
% x_pstd : standard deviations, estimated by error propagation
% y_pstd :
% A_pstd :
% s_pstd :
% c_pstd :
% sigma_r : standard deviation of the background (residual)
% SE_sigma_r : standard error of sigma_r
% pval_Ar : p-value of an amplitude vs. background noise test (p > 0.05 -> significant amplitude)
%
%
% Usage for a single-channel img with mask and fixed sigma:
% fitGaussians2D(img, x_v, y_v, 'sigma', sigma_v, 'mask', mask);
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Francois Aguet, March 28 2011 (last modified: Feb 5 2013)
function pStruct = fitGaussianMixtures2D(img, x, y, A, sigma, c, varargin)
% Parse inputs
ip = inputParser;
ip.CaseSensitive = false;
ip.addRequired('img', @isnumeric);
ip.addRequired('x');
ip.addRequired('y');
ip.addRequired('A');
ip.addRequired('sigma');
ip.addRequired('c');
ip.addParamValue('Alpha', 0.05, @isscalar);
ip.addParamValue('AlphaT', 0.05, @isscalar);
ip.addParamValue('Mask', [], @islogical);
ip.addParamValue('maxM', 5, @isscalar);
ip.parse(img, x, y, A, sigma, c, varargin{:});
np = length(x);
sigma = ip.Results.sigma;
if numel(sigma)==1
sigma = sigma*ones(1,np);
end
if ~isempty(ip.Results.Mask)
labels = bwlabel(ip.Results.Mask);
else
labels = zeros(size(img));
end
pStruct = struct('x', [], 'y', [], 'A', [], 's', [], 'c', [],...
'x_pstd', [], 'y_pstd', [], 'A_pstd', [], 's_pstd', [], 'c_pstd', [],...
'x_init', [], 'y_init', [],...
'sigma_r', [], 'SE_sigma_r', [], 'RSS', [], 'pval_Ar', [], 'hval_Ar', [], 'hval_AD', []);
xi = round(x);
yi = round(y);
[ny,nx] = size(img);
kLevel = norminv(1-ip.Results.Alpha/2.0, 0, 1); % ~2 std above background
iRange = [squeeze(min(min(img))) squeeze(max(max(img)))];
% initialize pStruct arrays
pStruct.x = cell(1,np);
pStruct.y = cell(1,np);
pStruct.A = cell(1,np);
pStruct.s = cell(1,np);
pStruct.c = cell(1,np);
pStruct.x_pstd = cell(1,np);
pStruct.y_pstd = cell(1,np);
pStruct.A_pstd = cell(1,np);
pStruct.s_pstd = cell(1,np);
pStruct.c_pstd = cell(1,np);
pStruct.x_init = cell(1,np);
pStruct.y_init = cell(1,np);
pStruct.sigma_r = cell(1,np);
pStruct.SE_sigma_r = cell(1,np);
pStruct.RSS = cell(1,np);
pStruct.pval_Ar = cell(1,np);
pStruct.hval_AD = cell(1,np);
pStruct.hval_Ar = cell(1,np);
sigma_max = max(sigma);
w2 = ceil(2*sigma_max);
w3 = ceil(3*sigma_max);
w4 = ceil(4*sigma_max);
% mask template: ring with inner radius w3, outer radius w4
[xm,ym] = meshgrid(-w4:w4);
r = sqrt(xm.^2+ym.^2);
annularMask = zeros(size(r));
annularMask(r<=w4 & r>=w3) = 1;
mixtureIndex = 1;
% loop through initial points
for p = 1:np
% ignore points in image border
if (xi(p)>w4 && xi(p)<=nx-w4 && yi(p)>w4 && yi(p)<=ny-w4)
% label mask
maskWindow = labels(yi(p)-w4:yi(p)+w4, xi(p)-w4:xi(p)+w4);
maskWindow(maskWindow==maskWindow(w4+1,w4+1)) = 0;
% estimate background
cmask = annularMask;
cmask(maskWindow~=0) = 0;
window = img(yi(p)-w4:yi(p)+w4, xi(p)-w4:xi(p)+w4);
if isempty(c)
c0 = mean(window(cmask==1));
else
c0 = c(p);
end
% set any other components to NaN
window(maskWindow~=0) = NaN;
npx = sum(isfinite(window(:)));
% fit
if isempty(A)
A0 = max(window(:))-c0;
else
A0 = A(p);
end
% initial fit with a single Gaussian
% Notation: reduced model: '_r', full model: '_f'
[prm_f, prmStd_f, ~, res_f] = fitGaussian2D(window, [x(p)-xi(p) y(p)-yi(p) A0 sigma(p) c0], 'xyAc');
prmStd_f = [prmStd_f(1:3) 0 prmStd_f(4)]; % update standard deviations
RSS_r = res_f.RSS;
p_r = 4; % #parameters in the model (x,y,A,c)
i = 1; % iteration
pval = 0;
validBounds = true;
while i<ip.Results.maxM && pval<0.05 && validBounds % models are significantly different
i = i+1;
prm_r = prm_f;
prmStd_r = prmStd_f;
res_r = res_f;
% expanded model
% new component: initial values given by max. residual point
[y0, x0] = find(res_r.data==max(res_r.data(:)), 1, 'first');
% This initialization may work better in some cases:
%initV = [x0-w4-1 y0-w4-1 max(res_r.data(:)) prm_r];
%initV(3:3:end-2) = sum(prm_r(3:3:end-2))/i;
%[prm_f, prmStd_f, ~, res_f] = fitGaussianMixture2D(window, initV, 'xyAc');
[prm_f, prmStd_f, ~, res_f] = fitGaussianMixture2D(window, [x0-w4-1 y0-w4-1 max(res_r.data(:)) prm_r], 'xyAc');
RSS_f = res_f.RSS;
p_f = p_r + 3; % 3 parameters (x,y,A) added at every iteration
% test statistic (F-test)
T = (RSS_r-RSS_f)/RSS_f * (npx-p_f-1)/(p_f-p_r);
pval = 1-fcdf(T,p_f-p_r,npx-p_f-1);
% update reduced model
p_r = p_f;
RSS_r = RSS_f;
% restrict radius; otherwise neighboring signals are considered part of mixture
if min(prm_f(1:3:end-2))<-w2 || max(prm_f(1:3:end-2))>w2 ||...
min(prm_f(2:3:end-2))<-w2 || max(prm_f(2:3:end-2))>w2
validBounds = false;
end
end
ng = i-1; % # gaussians in final model
% sigma, c are the same for each mixture
x_est = prm_r(1:3:end-2);
y_est = prm_r(2:3:end-2);
A_est = prm_r(3:3:end-2);
% exclude points where localization failed
if ng>1 || (x_est > -w2 && x_est < w2 && y_est > -w2 && y_est < w2 && A_est<2*diff(iRange))
pStruct.x{p} = xi(p) + x_est;
pStruct.y{p} = yi(p) + y_est;
pStruct.A{p} = A_est;
% sigma and background offset are identical for all mixture components
pStruct.s{p} = repmat(prm_r(end-1), [1 ng]);
pStruct.c{p} = repmat(prm_r(end), [1 ng]);
pStruct.x_pstd{p} = prmStd_r(1:3:end-2);
pStruct.y_pstd{p} = prmStd_r(2:3:end-2);
pStruct.A_pstd{p} = prmStd_r(3:3:end-2);
pStruct.s_pstd{p} = repmat(prmStd_r(end-1), [1 ng]);
pStruct.c_pstd{p} = repmat(prmStd_r(end), [1 ng]);
pStruct.x_init{p} = repmat(xi(p), [1 ng]);
pStruct.y_init{p} = repmat(yi(p), [1 ng]);
pStruct.sigma_r{p} = repmat(res_r.std, [1 ng]);
pStruct.RSS{p} = repmat(res_r.RSS, [1 ng]);
SE_sigma_r = res_r.std/sqrt(2*(npx-1));
pStruct.SE_sigma_r{p} = repmat(SE_sigma_r, [1 ng]);
SE_sigma_r = SE_sigma_r * kLevel;
pStruct.hval_AD{p} = repmat(res_r.hAD, [1 ng]);
% H0: A <= k*sigma_r
% H1: A > k*sigma_r
for i = 1:ng
sigma_A = pStruct.A_pstd{p}(i);
A_est = pStruct.A{p}(i);
df2 = (npx-1) * (sigma_A.^2 + SE_sigma_r.^2).^2 ./ (sigma_A.^4 + SE_sigma_r.^4);
scomb = sqrt((sigma_A.^2 + SE_sigma_r.^2)/npx);
T = (A_est - res_r.std*kLevel) ./ scomb;
% 1-sided t-test: A_est must be greater than k*sigma_r
pStruct.pval_Ar{p}(i) = tcdf(-T, df2);
pStruct.hval_Ar{p}(i) = pStruct.pval_Ar{p}(i) < ip.Results.AlphaT;
%pStruct.mask_Ar{p}(i) = sum(A_est*g>res_r.std*kLevel); % # significant pixels
end
if ng>1
pStruct.mixtureIndex{p} = mixtureIndex*ones(1,ng);
mixtureIndex = mixtureIndex+1;
else
pStruct.mixtureIndex{p} = 0;
end
end
end
end
% concatenate cell arrays
fnames = fieldnames(pStruct);
for f = 1:numel(fnames)
pStruct.(fnames{f}) = [pStruct.(fnames{f}){:}];
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
abstractProcessGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/abstractProcessGUI.m
| 6,533 |
utf_8
|
bfb6f0a72786910f9b8d6fae847543b7
|
function varargout = abstractProcessGUI(varargin)
%ABSTRACTPROCESSGUI M-file for abstractProcessGUI.fig
% ABSTRACTPROCESSGUI, by itself, creates a new ABSTRACTPROCESSGUI or raises the existing
% singleton*.
%
% H = ABSTRACTPROCESSGUI returns the handle to a new ABSTRACTPROCESSGUI or the handle to
% the existing singleton*.
%
% ABSTRACTPROCESSGUI('Property','Value',...) creates a new ABSTRACTPROCESSGUI using the
% given property value pairs. Unrecognized properties are passed via
% varargin to abstractProcessGUI_OpeningFcn. This calling syntax produces a
% warning when there is an existing singleton*.
%
% ABSTRACTPROCESSGUI('CALLBACK') and ABSTRACTPROCESSGUI('CALLBACK',hObject,...) call the
% local function named CALLBACK in ABSTRACTPROCESSGUI.M with the given input
% arguments.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help abstractProcessGUI
% Last Modified by GUIDE v2.5 09-Jul-2012 10:49:16
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @abstractProcessGUI_OpeningFcn, ...
'gui_OutputFcn', @abstractProcessGUI_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 abstractProcessGUI is made visible.
function abstractProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin)
processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:})
% Get current package and process
userData = get(handles.figure1, 'UserData');
procName = eval([userData.crtProcClassName '.getName()']);
set(handles.uipanel_methods, 'Title', [procName ' methods']);
set(handles.text_methods, 'String', ['Choose a ' lower(procName) ' method']);
% Get current process constructer, set-up GUIs and mask refinement process
% constructor
userData.subProcClassNames = eval([userData.crtProcClassName '.getConcreteClasses()']);
isGraphicalProcess = @(x) Process.isProcess(x) && Process.hasGUI(x);
validClasses = cellfun(isGraphicalProcess, userData.subProcClassNames);
userData.subProcClassNames = userData.subProcClassNames(validClasses);
userData.subProcConstr = cellfun(@(x) str2func(x),userData.subProcClassNames,'Unif',0);
userData.subProcGUI = cellfun(@(x) eval([x '.GUI']),userData.subProcClassNames,'Unif',0);
subProcNames = cellfun(@(x) eval([x '.getName']),userData.subProcClassNames,'Unif',0);
popupMenuProcName = vertcat(subProcNames,{['Choose a ' lower(procName) ' method']});
% Set up input channel list box
if isempty(userData.crtProc)
value = numel(userData.subProcClassNames)+1;
set(handles.pushbutton_set, 'Enable', 'off');
else
value = find(strcmp(userData.crtProc.getName,subProcNames));
end
existSubProc = @(proc) any(cellfun(@(x) isa(x,proc),userData.MD.processes_));
for i=find(cellfun(existSubProc,userData.subProcClassNames'))
popupMenuProcName{i} = ['<html><b>' popupMenuProcName{i} '</b></html>'];
end
set(handles.popupmenu_methods, 'String', popupMenuProcName,...
'Value',value)
% Choose default command line output for abstractProcessGUI
handles.output = hObject;
% Update user data and GUI data
set(hObject, 'UserData', userData);
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = abstractProcessGUI_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 pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
% Delete figure
delete(handles.figure1);
% --- Executes on selection change in popupmenu_methods.
function popupmenu_methods_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_methods (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_methods contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_methods
content = get(hObject, 'string');
if get(hObject, 'Value') == length(content)
set(handles.pushbutton_set, 'Enable', 'off')
else
set(handles.pushbutton_set, 'Enable', 'on')
end
% --- Executes on button press in pushbutton_set.
function pushbutton_set_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
segProcID = get(handles.popupmenu_methods, 'Value');
subProcGUI =userData.subProcGUI{segProcID};
subProcGUI('mainFig',userData.mainFig,userData.procID,...
'procConstr',userData.subProcConstr{segProcID},...
'procClassName',userData.subProcClassNames{segProcID});
delete(handles.figure1);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if ~isempty(userData) %%%% check and see why
delete(userData.helpFig(ishandle(userData.helpFig)));
end
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
naFromLensID.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/naFromLensID.m
| 3,469 |
utf_8
|
2697834078098bf83f70f4ebdbbe386e
|
function [NA,mag] = naFromLensID(lensID,ask)
%NAFROMLENSID is a lookup table to find the NA for a given lensID
%
% SYNOPSIS [NA,mag] = naFromLensID(lensID,ask)
%
% INPUT lensID : ID of the lens according to deltaVision
% ask : Whether or not to ask for lensID if not found in list
% Default: 1
%
% OUTPUT NA : numerical aperture of the specified lens
% mag : magnification of the lens
%
% REMARKS After the program asks for a lensID, it will write it into the
% .m-file. Alternatively, you can write it into the list at the
% end of the code yourself.
%
% c: 8/05 jonas
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% TEST INPUT
if nargin == 0
error('not enough input arguments')
end
if nargin < 2 || isempty(ask)
ask = 1;
end
NA = NaN;
mag = NaN;
% LOOKUP LENSID
lensIDList = lookupLensIDs;
lensIdx = find(lensIDList(:,1) == lensID);
% assign NA and mag if possible
if ~isempty(lensIdx)
% use most recent version
NA = lensIDList(lensIdx(end),2);
mag = lensIDList(lensIdx(end),3);
end
% check whether we have all the output we need
if ~isnan(NA) && (~isnan(mag) || nargout < 2)
% all is fine
elseif ask
% if not good, check whether we can ask for input. Use what we have for
% defaults
answ = inputdlg(...
{sprintf('Please input NA of lens %i',lensID),...
sprintf('Please input magnification of lens %i',lensID)},...
'Manual NA',1,...
{num2str(NA),num2str(mag)});
if ~isempty(answ)
NA = str2double(answ{1});
mag = str2double(answ{2});
end
% write to file
file = which('naFromLensID.m');
mFile = textread(file,'%s',...
'delimiter','\n','whitespace','');
% now add a line just befor the last line
newLine = sprintf('%6i, %1.2f,%4i;...',lensID,NA,mag);
mFile{end+1} = mFile{end};
mFile{end-1} = newLine;
% finally, write the mFile
fid = fopen(file,'w');
for i=1:length(mFile)
fprintf(fid,'%s\n',mFile{i});
end
fclose(fid);
else
% simply return the default (NaN)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function lensID = lookupLensIDs
% add lensIDs, NAs and mags by adding a line like:
% '9999, 1.25, 60;...'
% into the table below. Do not add any lines after the
% closing of the table '];'
lensID = ...
[10002, 1.40, 100;...
10006, 1.40, 100;...
10612, 1.42, 60;...
12003, 1.40, 100;...
0, 1.40, NaN;...
10005, 1.35, NaN;...
10105, 1.40, NaN;...
10403, 1.35, NaN;...
10003, 1.35, NaN;...
12005, NaN, NaN;...
10007, 1.40, 100;...
99999, 1.4, 100;...
10211, 1.40, 100;...
10602, 1.40, 60;...
];
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
pointSourceDetectionProcessGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/pointSourceDetectionProcessGUI.m
| 28,298 |
utf_8
|
342372247e7d42dfc0ea2f0a7e5af5f5
|
function varargout = pointSourceDetectionProcessGUI(varargin)
% anisoGaussianDetectionProcessGUI M-file for anisoGaussianDetectionProcessGUI.fig
% anisoGaussianDetectionProcessGUI, by itself, creates a new anisoGaussianDetectionProcessGUI or raises the existing
% singleton*.
%
% H = anisoGaussianDetectionProcessGUI returns the handle to a new anisoGaussianDetectionProcessGUI or the handle to
% the existing singleton*.
%
% anisoGaussianDetectionProcessGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in anisoGaussianDetectionProcessGUI.M with the given input arguments.
%
% anisoGaussianDetectionProcessGUI('Property','Value',...) creates a new anisoGaussianDetectionProcessGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before anisoGaussianDetectionProcessGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to anisoGaussianDetectionProcessGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help anisoGaussianDetectionProcessGUI
% Last Modified by GUIDE v2.5 01-Oct-2013 19:23:29
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @pointSourceDetectionProcessGUI_OpeningFcn, ...
'gui_OutputFcn', @pointSourceDetectionProcessGUI_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 anisoGaussianDetectionProcessGUI is made visible.
function pointSourceDetectionProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin)
processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1);
% Set-up parameters
userData=get(handles.figure1,'UserData');
funParams = userData.crtProc.funParams_;
%Remove the output directory as we don't want to replicate it to other
%movies if the "apply to all movies" box is checked. Ideally we would
%explicitly only replicate the parameters we set in this GUI but this is a
%quick fix. - HLE
if isfield(funParams,'OutputDirectory')
funParams = rmfield(funParams,'OutputDirectory');
end
set(handles.popupmenu_CurrentChannel,'UserData',funParams);
iChan = get(handles.popupmenu_CurrentChannel,'Value');
if isempty(iChan)
iChan = 1;
set(handles.popupmenu_CurrentChannel,'Value',1);
end
% %Specify parameters
% userData.numParams = {'filterSigma', 'alpha','Mode','MaxMixtures','RedundancyRadius'};
% %Set the intersection checkbox
% userData.checkParams ={'FitMixtures'};
%
% for i =1 : numel(userData.numParams)
% paramName = userData.numParams{i};
% if any(strcmp(paramName,funParams.PerChannelParams))
% parVal = funParams.(paramName)(iChan);
% else
% parVal = funParams.(paramName);
% end
% set(handles.(['edit_' paramName]), 'String',parVal);
% end
%
%
%
% set(handles.edit_UseIntersection,,'Value',funParams.UseIntersection)
%
% for i =1 : numel(userData.checkParams)
% paramName = userData.checkParams{i};
% if any(strcmp(paramName,funParams.PerChannelParams))
% parVal = funParams.(paramName)(iChan);
% else
% parVal = funParams.(paramName);
% end
% set(handles.(['edit_' paramName]), 'Value',parVal);
% end
% Set up available mask channels
set(handles.listbox_availableMaskChannels,'String',userData.MD.getChannelPaths(), ...
'UserData',1:numel(userData.MD.channels_));
maskChannelIndex = funParams.MaskChannelIndex;
if ~isempty(maskChannelIndex)
maskChannelString = userData.MD.getChannelPaths(maskChannelIndex);
else
maskChannelString = {};
end
set(handles.listbox_selectedMaskChannels,'String',maskChannelString,...
'UserData',maskChannelIndex);
%Setup mask process list box
segProc = cellfun(@(x) isa(x,'MaskProcess'),userData.MD.processes_);
segProcID=find(segProc);
segProcNames = cellfun(@(x) x.getName(),userData.MD.processes_(segProc),'Unif',false);
segProcString = vertcat('Choose later',segProcNames(:));
segProcData=horzcat({[]},num2cell(segProcID));
segProcValue = find(cellfun(@(x) isequal(x,funParams.MaskProcessIndex),segProcData));
if isempty(segProcValue), segProcValue = 1; end
set(handles.popupmenu_SegProcessIndex,'String',segProcString,...
'UserData',segProcData,'Value',segProcValue);
% Update channels listboxes depending on the selected process
popupmenu_SegProcessIndex_Callback(hObject, eventdata, handles)
%Update channel parameter selection dropdown
popupmenu_CurrentChannel_Callback(hObject, eventdata, handles)
% Update GUI user data
set(handles.figure1, 'UserData', userData);
handles.output = hObject;
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = pointSourceDetectionProcessGUI_OutputFcn(~, ~, 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 pushbutton_cancel.
function pushbutton_cancel_Callback(~, ~, handles)
% Delete figure
delete(handles.figure1);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, ~, handles)
% Notify the package GUI that the setting panel is closed
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
if isfield(userData, 'helpFig') && ishandle(userData.helpFig)
delete(userData.helpFig)
end
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
% --- Executes on key press with focus on pushbutton_done and none of its controls.
function pushbutton_done_KeyPressFcn(~, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(~, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
% --- Executes on button press in pushbutton_done.
function pushbutton_done_Callback(hObject, eventdata, handles)
% -------- Check user input --------
if isempty(get(handles.listbox_selectedChannels, 'String'))
errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal')
return;
end
%Save the currently set per-channel parameters
pushbutton_saveChannelParams_Callback(hObject, eventdata, handles)
% Retrieve detection parameters
funParams = get(handles.popupmenu_CurrentChannel,'UserData');
% Retrieve GUI-defined non-channel specific parameters
%Get selected image channels
channelIndex = get(handles.listbox_selectedChannels, 'Userdata');
if isempty(channelIndex)
errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal')
return;
end
funParams.ChannelIndex = channelIndex;
%Get selected mask channels
maskChannelProps = get(handles.listbox_selectedMaskChannels, {'Userdata','String'});
if ~isempty(maskChannelProps{1}) && ( numel(maskChannelProps{1}) ~= numel(channelIndex))
errordlg('Please select either zero mask channels or the same number of mask channels as input channels.','Setting Error','modal')
return;
end
funParams.MaskChannelIndex = maskChannelProps{1};
% Retrieve mask process index and class (for propagation)
props=get(handles.popupmenu_SegProcessIndex,{'UserData','Value'});
funParams.MaskProcessIndex = props{1}{props{2}};
funParams.UseIntersection = get(handles.edit_UseIntersection,'Value') > 0;
% Add 64-bit warning
is64bit = ~isempty(regexp(computer ,'64$', 'once'));
if ~is64bit
warndlg(['Your Matlab version is not detected as 64-bit. Please note '....
'the point source detection uses compiled MEX files which '...
'are not provided for 32-bit.'],...
'Setting Error','modal');
end
processGUI_ApplyFcn(hObject, eventdata, handles,funParams);
function edit_Mode_Callback(hObject, eventdata, handles)
% hObject handle to edit_Mode (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 edit_Mode as text
% str2double(get(hObject,'String')) returns contents of edit_Mode as a double
% --- Executes during object creation, after setting all properties.
function edit_Mode_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_Mode (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 edit_FitMixtures.
function edit_FitMixtures_Callback(hObject, eventdata, handles)
% hObject handle to edit_FitMixtures (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 edit_FitMixtures
function edit_MaxMixtures_Callback(hObject, eventdata, handles)
% hObject handle to edit_MaxMixtures (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 edit_MaxMixtures as text
% str2double(get(hObject,'String')) returns contents of edit_MaxMixtures as a double
% --- Executes during object creation, after setting all properties.
function edit_MaxMixtures_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_MaxMixtures (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 edit_RedundancyRadius_Callback(hObject, eventdata, handles)
% hObject handle to edit_RedundancyRadius (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 edit_RedundancyRadius as text
% str2double(get(hObject,'String')) returns contents of edit_RedundancyRadius as a double
% --- Executes during object creation, after setting all properties.
function edit_RedundancyRadius_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_RedundancyRadius (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 listbox_availableMaskChannels.
function listbox_availableMaskChannels_Callback(hObject, eventdata, handles)
% hObject handle to listbox_availableMaskChannels (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox_availableMaskChannels contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox_availableMaskChannels
% --- Executes during object creation, after setting all properties.
function listbox_availableMaskChannels_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox_availableMaskChannels (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');
end
% --- Executes on button press in checkbox_mask_all.
function checkbox_mask_all_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_mask_all (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 checkbox_mask_all
contents1 = get(handles.listbox_availableMaskChannels, 'String');
chanIndex1 = get(handles.listbox_availableMaskChannels, 'Userdata');
chanIndex2 = get(handles.listbox_selectedMaskChannels, 'Userdata');
% Return if listbox1 is empty
if isempty(contents1)
return;
end
switch get(hObject,'Value')
case 1
set(handles.listbox_selectedMaskChannels, 'String', contents1);
chanIndex2 = chanIndex1;
case 0
set(handles.listbox_selectedMaskChannels, 'String', {}, 'Value',1);
chanIndex2 = [ ];
end
set(handles.listbox_selectedMaskChannels, 'UserData', chanIndex2);
% --- Executes on button press in pushbutton_mask_select.
function pushbutton_mask_select_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_mask_select (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
contents1 = get(handles.listbox_availableMaskChannels, 'String');
contents2 = get(handles.listbox_selectedMaskChannels, 'String');
id = get(handles.listbox_availableMaskChannels, 'Value');
% If channel has already been added, return;
chanIndex1 = get(handles.listbox_availableMaskChannels, 'Userdata');
chanIndex2 = get(handles.listbox_selectedMaskChannels, 'Userdata');
for i = id
contents2{end+1} = contents1{i};
chanIndex2 = cat(2, chanIndex2, chanIndex1(i));
end
set(handles.listbox_selectedMaskChannels, 'String', contents2, 'Userdata', chanIndex2);
% --- Executes on button press in pushbutton_mask_delete.
function pushbutton_mask_delete_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_mask_delete (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Call back function of 'delete' button
contents = get(handles.listbox_selectedMaskChannels,'String');
id = get(handles.listbox_selectedMaskChannels,'Value');
% Return if list is empty
if isempty(contents) || isempty(id)
return;
end
% Delete selected item
contents(id) = [ ];
% Delete userdata
chanIndex2 = get(handles.listbox_selectedMaskChannels, 'Userdata');
chanIndex2(id) = [ ];
set(handles.listbox_selectedMaskChannels, 'Userdata', chanIndex2);
% Point 'Value' to the second last item in the list once the
% last item has been deleted
if (id >length(contents) && id>1)
set(handles.listbox_selectedMaskChannels,'Value',length(contents));
end
% Refresh listbox
set(handles.listbox_selectedMaskChannels,'String',contents);
% --- Executes on selection change in listbox_selectedMaskChannels.
function listbox_selectedMaskChannels_Callback(hObject, eventdata, handles)
% hObject handle to listbox_selectedMaskChannels (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox_selectedMaskChannels contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox_selectedMaskChannels
% --- Executes during object creation, after setting all properties.
function listbox_selectedMaskChannels_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox_selectedMaskChannels (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');
end
% --- Executes on button press in pushbutton_up.
function pushbutton_up_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_up (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% call back of 'Up' button
id = get(handles.listbox_selectedMaskChannels,'Value');
contents = get(handles.listbox_selectedMaskChannels,'String');
% Return if list is empty
if isempty(contents) || isempty(id) || id == 1
return;
end
temp = contents{id};
contents{id} = contents{id-1};
contents{id-1} = temp;
chanIndex = get(handles.listbox_selectedMaskChannels, 'Userdata');
temp = chanIndex(id);
chanIndex(id) = chanIndex(id-1);
chanIndex(id-1) = temp;
set(handles.listbox_selectedMaskChannels, 'String', contents, 'Userdata', chanIndex);
set(handles.listbox_selectedMaskChannels, 'value', id-1);
% --- Executes on button press in pushbutton_down.
function pushbutton_down_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_down (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
id = get(handles.listbox_selectedMaskChannels,'Value');
contents = get(handles.listbox_selectedMaskChannels,'String');
% Return if list is empty
if isempty(contents) || isempty(id) || id == length(contents)
return;
end
temp = contents{id};
contents{id} = contents{id+1};
contents{id+1} = temp;
chanIndex = get(handles.listbox_selectedMaskChannels, 'Userdata');
temp = chanIndex(id);
chanIndex(id) = chanIndex(id+1);
chanIndex(id+1) = temp;
set(handles.listbox_selectedMaskChannels, 'string', contents, 'Userdata',chanIndex);
set(handles.listbox_selectedMaskChannels, 'value', id+1);
% --- Executes on selection change in popupmenu_SegProcessIndex.
function popupmenu_SegProcessIndex_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_SegProcessIndex (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_SegProcessIndex contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_SegProcessIndex
% Retrieve selected process ID
props= get(handles.popupmenu_SegProcessIndex,{'UserData','Value'});
procID = props{1}{props{2}};
% Read process and check available channels
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
if isempty(procID)
allChannelIndex=1:numel(userData.MD.channels_);
else
allChannelIndex = find(userData.MD.processes_{procID}.checkChannelOutput);
end
% Set up available channels listbox
if ~isempty(allChannelIndex)
if isempty(procID)
channelString = userData.MD.getChannelPaths(allChannelIndex);
else
channelString = userData.MD.processes_{procID}.outFilePaths_(1,allChannelIndex);
end
else
channelString = {};
end
set(handles.listbox_availableMaskChannels,'String',channelString,'UserData',allChannelIndex);
% Set up selected channels listbox
channelIndex = get(handles.listbox_selectedMaskChannels, 'UserData');
channelIndex(~ismember(channelIndex,allChannelIndex)) = [];%So that indices may repeat, and handles empty better than intersect
if ~isempty(channelIndex)
if isempty(procID)
channelString = userData.MD.getChannelPaths(channelIndex);
else
channelString = userData.MD.processes_{procID}.outFilePaths_(1,channelIndex);
end
else
channelString = {};
channelIndex = [];%Because the intersect command returns a 0x1 instead of 0x0 which causes concatenation errors
end
set(handles.listbox_selectedMaskChannels,'String',channelString,'UserData',channelIndex);
% --- Executes during object creation, after setting all properties.
function popupmenu_SegProcessIndex_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_SegProcessIndex (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 edit_UseIntersection.
function edit_UseIntersection_Callback(hObject, eventdata, handles)
% hObject handle to edit_UseIntersection (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 edit_UseIntersection
% --- Executes on selection change in popupmenu_CurrentChannel.
function popupmenu_CurrentChannel_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_CurrentChannel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_CurrentChannel contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_CurrentChannel
userData=get(handles.figure1,'UserData');
funParams = get(handles.popupmenu_CurrentChannel,'UserData');
selChan = 1:numel(userData.MD.channels_);%For now just let them set parameters for all channels.
%selChan = get(handles.listbox_selectedChannels,'UserData');
chanStr = arrayfun(@(x)(['Channel ' num2str(x)]),selChan,'Unif',0);
set(handles.popupmenu_CurrentChannel,'String',chanStr);
iChan = get(handles.popupmenu_CurrentChannel,'Value');
%set(handles.popupmenu_CurrentChannel,'UserData',iChan);
% Set-up parameters
for i =1 : numel(funParams.PerChannelParams)
paramName = funParams.PerChannelParams{i};
parVal = funParams.(paramName)(iChan);
if ~islogical(funParams.(paramName))
set(handles.(['edit_' paramName]), 'String',parVal);
else
set(handles.(['edit_' paramName]), 'Value',parVal);
end
end
% --- Executes during object creation, after setting all properties.
function popupmenu_CurrentChannel_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_CurrentChannel (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 pushbutton_saveChannelParams.
function pushbutton_saveChannelParams_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_saveChannelParams (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Get settings for the current channel before switching to another
iChan = get(handles.popupmenu_CurrentChannel,'Value');
%userData=get(handles.figure1,'UserData');
funParams = get(handles.popupmenu_CurrentChannel,'UserData');
for i =1 : numel(funParams.PerChannelParams)
paramName = funParams.PerChannelParams{i};
if islogical(funParams.(paramName))
parVal = get(handles.(['edit_' paramName]), 'Value');
funParams.(paramName)(iChan) = parVal;
elseif iscell(funParams.(paramName))
parVal = get(handles.(['edit_' paramName]), 'String');
funParams.(paramName)(iChan) = parVal;
else
parVal = get(handles.(['edit_' paramName]), 'String');
funParams.(paramName)(iChan) = str2double(parVal);
end
end
set(handles.popupmenu_CurrentChannel,'UserData',funParams);
% --- Executes on button press in edit_PreFilter.
function edit_PreFilter_Callback(hObject, eventdata, handles)
% hObject handle to edit_PreFilter (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 edit_PreFilter
function edit_ConfRadius_Callback(hObject, eventdata, handles)
% hObject handle to edit_ConfRadius (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 edit_ConfRadius as text
% str2double(get(hObject,'String')) returns contents of edit_ConfRadius as a double
% --- Executes during object creation, after setting all properties.
function edit_ConfRadius_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_ConfRadius (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 edit_WindowSize_Callback(hObject, eventdata, handles)
% hObject handle to edit_WindowSize (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 edit_WindowSize as text
% str2double(get(hObject,'String')) returns contents of edit_WindowSize as a double
% --- Executes during object creation, after setting all properties.
function edit_WindowSize_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_WindowSize (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
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
packageGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/packageGUI.m
| 10,583 |
utf_8
|
3d8400f8615c3cd846444d403f0378cb
|
function varargout = packageGUI(varargin)
% PACKAGEGUI M-file for packageGUI.fig
% PACKAGEGUI, by itself, creates a new PACKAGEGUI or raises the existing
% singleton*.
%
% H = PACKAGEGUI returns the handle to a new PACKAGEGUI or the handle to
% the existing singleton*.
%
% PACKAGEGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in PACKAGEGUI.M with the given input arguments.
%
% PACKAGEGUI('Property','Value',...) creates a new PACKAGEGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before packageGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to packageGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help packageGUI
% Last Modified by GUIDE v2.5 04-Jun-2013 14:06:35
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @packageGUI_OpeningFcn, ...
'gui_OutputFcn', @packageGUI_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
% --- Outputs from this function are returned to the command line.
function varargout = packageGUI_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;
% In case the package GUI has been called without argument
userData = get(handles.figure1, 'UserData');
if (isfield(userData,'startMovieSelectorGUI') && userData.startMovieSelectorGUI)
movieSelectorGUI('packageName',userData.packageName,'MD',userData.MD,...
'ML', userData.ML);
delete(handles.figure1)
end
% --- Executes on button press in pushbutton_status.
function pushbutton_status_Callback(~, ~, handles)
userData = get(handles.figure1, 'UserData');
% if movieDataGUI exist
if isfield(userData, 'overviewFig') && ishandle(userData.overviewFig)
delete(userData.overviewFig)
end
userData.overviewFig = movieDataGUI(userData.MD(userData.id));
set(handles.figure1, 'UserData', userData);
% --- Executes on Save button press or File>Save
function save_Callback(~, ~, handles)
userData = get(handles.figure1, 'UserData');
set(handles.text_saveStatus, 'Visible', 'on')
arrayfun(@save,userData.MD);
pause(.3)
set(handles.text_saveStatus, 'Visible', 'off')
function switchMovie_Callback(hObject, ~, handles)
userData = get(handles.figure1, 'UserData');
nMovies = length(userData.MD);
switch get(hObject,'Tag')
case 'pushbutton_left'
newMovieId = userData.id - 1;
case 'pushbutton_right'
newMovieId = userData.id + 1;
case 'popupmenu_movie'
newMovieId = get(hObject, 'Value');
otherwise
end
if (newMovieId==userData.id), return; end
% Save previous movie checkboxes
userData.statusM(userData.id).Checked = userfcn_saveCheckbox(handles);
% Set up new movie GUI parameters
userData.id = mod(newMovieId-1,nMovies)+1;
userData.crtPackage = userData.package(userData.id);
set(handles.figure1, 'UserData', userData)
set(handles.popupmenu_movie, 'Value', userData.id)
% Set up GUI
if userData.statusM(userData.id).Visited
packageGUI_RefreshFcn(handles, 'refresh')
else
packageGUI_RefreshFcn(handles, 'initialize')
end
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
userData = get(handles.figure1,'Userdata');
if isfield(userData, 'MD')
MD = userData.MD;
else
delete(handles.figure1);
return;
end
saveRes = questdlg('Do you want to save the current progress?', ...
'Package Control Panel');
if strcmpi(saveRes,'yes'), arrayfun(@save,userData.MD); end
if strcmpi(saveRes,'cancel'), return; end
delete(handles.figure1);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if ~isempty(userData.MD)
if userData.MD.isMock()
load([userData.MD.mockMD_.parent.movieDataPath_, filesep, userData.MD.mockMD_.parent.movieDataFileName_]);
movieViewer(MD, 'refresher', '1');
end
end
% Find all figures stored in userData and delete them
if isempty(userData), return; end
userDataFields=fieldnames(userData);
isFig = ~cellfun(@isempty,regexp(userDataFields,'Fig$'));
userDataFigs = userDataFields(isFig);
for i=1:numel(userDataFigs)
figHandles = userData.(userDataFigs{i});
validFigHandles = figHandles(ishandle(figHandles)&figHandles ~= 0);
delete(validFigHandles);
end
% msgboxGUI used for error reports
if isfield(userData, 'msgboxGUI') && ishandle(userData.msgboxGUI)
delete(userData.msgboxGUI)
end
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(hObject, eventdata, handles)
if strcmp(eventdata.Key, 'return')
exit_Callback(handles.pushbutton_exit, [], handles);
end
if strcmp(eventdata.Key, 'leftarrow')
switchMovie_Callback(handles.pushbutton_left, [], handles);
end
if strcmp(eventdata.Key, 'rightarrow')
switchMovie_Callback(handles.pushbutton_right, [], handles);
end
% --------------------------------------------------------------------
function menu_about_Callback(hObject, eventdata, handles)
status = web(get(hObject,'UserData'), '-browser');
if status
switch status
case 1
msg = 'System default web browser is not found.';
case 2
msg = 'System default web browser is found but could not be launched.';
otherwise
msg = 'Fail to open browser for unknown reason.';
end
warndlg(msg,'Fail to open browser','modal');
end
% --------------------------------------------------------------------
function menu_file_open_Callback(~, ~, handles)
% Call back function of 'New' in menu bar
userData = get(handles.figure1,'Userdata');
% if ~isempty(userData.MD), field = 'MD'; else field = 'ML'; end
% arrayfun(@(x) x.save,userData.(field));
movieSelectorGUI('packageName',userData.packageName,...
'MD', userData.MD, 'ML', userData.ML);
delete(handles.figure1)
% --------------------------------------------------------------------
function exit_Callback(~, ~, handles)
delete(handles.figure1);
% --- Executes on button press in pushbutton_show.
function pushbutton_show_Callback(hObject, ~, handles)
userData = get(handles.figure1, 'UserData');
prop=get(hObject,'Tag');
procID = str2double(prop(length('pushbutton_show_')+1:end));
if isfield(userData, 'resultFig') && ishandle(userData.resultFig)
delete(userData.resultFig)
end
userData.resultFig = userData.crtPackage.processes_{procID}.resultDisplay();
set(handles.figure1, 'UserData', userData);
% --- Executes on button press in pushbutton_set.
function pushbutton_set_Callback(hObject, ~, handles)
userData = get(handles.figure1, 'UserData');
prop=get(hObject,'Tag');
procID = str2double(prop(length('pushbutton_set_')+1:end));
% Read GUI handle from the associated process static method
crtProc=userData.crtPackage.getProcessClassNames{procID};
crtProcGUI =eval([crtProc '.GUI']);
userData.setFig(procID) = crtProcGUI('mainFig',handles.figure1,procID);
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
% --- Executes on button press in checkbox.
function checkbox_Callback(hObject, eventdata, handles)
props=get(hObject,{'Value','Tag'});
procStatus=props{1};
procID = str2double(props{2}(length('checkbox_')+1:end));
userData=get(handles.figure1, 'UserData');
userData.statusM(userData.id).Checked(procID) = procStatus;
set(handles.figure1, 'UserData', userData)
userfcn_checkAllMovies(procID, procStatus, handles);
userfcn_lampSwitch(procID, procStatus, handles);
% --------------------------------------------------------------------
function menu_debug_enter_Callback(hObject, eventdata, handles)
status = get(hObject,'Checked');
if strcmp(status,'on'),
newstatus = 'off';
dbclear if caught error;
else
newstatus='on';
end
set(hObject,'Checked',newstatus);
% --------------------------------------------------------------------
function menu_debug_batchMode_Callback(hObject, eventdata, handles)
status = get(hObject,'Checked');
if strcmp(status,'on'),
newstatus = 'off';
else
newstatus='on';
end
set(hObject,'Checked',newstatus);
% --- Executes on button press in pushbutton_open.
function pushbutton_open_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
prop=get(hObject,'Tag');
procID = str2double(prop(length('pushbutton_show_')+1:end));
% Use the OS-specific command to open result in exploration window
outputDir = userData.crtPackage.processes_{procID}.funParams_.OutputDirectory;
if ispc
winopen(outputDir);
elseif ismac
system(sprintf('open %s',regexptranslate('escape',outputDir)));
else
msgbox(sprintf('Results can be found under %s',regexptranslate('escape',outputDir)));
% SB: Following command not working under Ubuntu (as well as gnome-open
% & nautilus)
% system(sprintf('xdg-open %s',regexptranslate('escape',outputDir)));
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
getGaussianPSFsigma.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/getGaussianPSFsigma.m
| 3,287 |
utf_8
|
1bc6d7a33a0c071253b338643cab911f
|
%[sigma] = getGaussianPSFsigma(NA, M, pixelSize, lambda) returns the s.d. of the Gaussian PSF approximation
%
% Inputs NA : numerical aperture of the objective
% M : magnification of the objective
% pixelSize : physical pixel size of the CCD in [m]
% lambda : emission maximum wavelength of the fluorophore in [m]
% -or- fluorophore name (see getFluorPropStruct.m)
% {'Display'} : Display PSF and its Gaussian approximation. Optional, default: false.
%
% Ouputs
% sigma : standard deviation of the Gaussian PSF approximation, in pixels
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Francois Aguet, October 2010 (last modified 05/28/2013)
function sigma = getGaussianPSFsigma(NA, M, pixelSize, lambda, varargin)
if isnumeric(lambda)
lambda = num2cell(lambda);
end
if ischar(lambda)
lambda = {lambda};
end
ip = inputParser;
ip.CaseSensitive = false;
ip.addRequired('NA', @isscalar);
ip.addRequired('M', @isscalar);
ip.addRequired('pixelSize', @isscalar);
ip.addRequired('lambda', @(x) all(cellfun(@(i) ischar(i) || isscalar(i),x)));
ip.addParamValue('Display', false, @islogical);
ip.addParamValue('Mode', 'epi', @(x) any(strcmpi(x, {'epi', 'tirf', 'confocal'})));
ip.parse(NA, M, pixelSize, lambda, varargin{:});
idx = find(cellfun(@ischar, lambda));
for i = idx
lambda{i} = name2wavelength(lambda(i));
end
% Defaults use values corresponding to optimal imaging conditions
p.ti0 = 0; % working distance has no effect under ideal conditions
p.ni0 = 1.518;
p.ni = 1.518;
p.tg0 = 0.17e-3;
p.tg = 0.17e-3;
p.ng0 = 1.515;
p.ng = 1.515;
p.ns = 1.33;
p.lambda = [];
p.M = M;
p.NA = NA;
p.pixelSize = pixelSize;
p.sf = 1;
p.mode = 1;
ru = 8;
nl = numel(lambda);
sigma = zeros(1,nl);
for i = 1:nl
p.lambda = lambda{i};
psf = vectorialPSF([0 0 0], 0, (2*ru)-1, p);
if strcmpi(ip.Results.Mode, 'confocal')
% approximation: in theory this should be psf_ex.*psf_em
psf = psf.^2;
end
[pG, ~, ~, res] = fitGaussian2D(psf, [0 0 max(psf(:)) 1 0], 'As');
sigma(i) = pG(4);
% Display
if ip.Results.Display
xa = (-ru+1:ru-1)*p.pixelSize/p.M*1e9;
figure;
subplot(1,2,1);
imagesc(xa,xa,psf); colormap(gray(256)); axis image; colorbar;
title('PSF');
xlabel('x [nm]');
ylabel('y [nm]');
subplot(1,2,2);
imagesc(xa,xa, psf+res.data); colormap(gray(256)); axis image; colorbar;
title('Gaussian approximation');
xlabel('x [nm]');
ylabel('y [nm]');
linkaxes;
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
addMovieROIGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/addMovieROIGUI.m
| 11,173 |
utf_8
|
99046aa8e67f15ba9f3beb2966033c0e
|
function varargout = addMovieROIGUI(varargin)
% addMovieROIGUI M-file for addMovieROIGUI.fig
% addMovieROIGUI, by itself, creates a new addMovieROIGUI or raises the existing
% singleton*.
%
% H = addMovieROIGUI returns the handle to a new addMovieROIGUI or the handle to
% the existing singleton*.
%
% addMovieROIGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in addMovieROIGUI.M with the given input arguments.
%
% addMovieROIGUI('Property','Value',...) creates a new addMovieROIGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before addMovieROIGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to addMovieROIGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help addMovieROIGUI
% Last Modified by GUIDE v2.5 07-Feb-2012 15:54:14
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @addMovieROIGUI_OpeningFcn, ...
'gui_OutputFcn', @addMovieROIGUI_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 addMovieROIGUI is made visible.
function addMovieROIGUI_OpeningFcn(hObject,eventdata,handles,varargin)
% Check input
% The mainFig and procID should always be present
% procCOnstr and procName should only be present if the concrete process
% initation is delegated from an abstract class. Else the constructor will
% be directly read from the package constructor list.
ip = inputParser;
ip.addRequired('hObject',@ishandle);
ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x));
ip.addRequired('handles',@isstruct);
ip.addOptional('MD',[],@(x)isa(x,'MovieData'));
ip.addParamValue('mainFig',-1,@ishandle);
ip.parse(hObject,eventdata,handles,varargin{:});
userData.MD =ip.Results.MD;
userData.mainFig =ip.Results.mainFig;
% Set up copyright statement
set(handles.text_copyright, 'String', getLCCBCopyright());
% Set up available input channels
set(handles.listbox_selectedChannels,'String',userData.MD.getChannelPaths(), ...
'UserData',1:numel(userData.MD.channels_));
% Save the image directories and names (for cropping preview)
userData.nFrames = userData.MD.nFrames_;
userData.imPolyHandle.isvalid=0;
m=userData.MD.imSize_(2);
n=userData.MD.imSize_(1);
userData.ROI = [1 1; m 1; m n; 1 n;];
userData.previewFig=-1;
userData.helpFig=-1;
% Read the first image and update the sliders max value and steps
userData.chanIndex = 1;
set(handles.edit_frameNumber,'String',1);
set(handles.slider_frameNumber,'Min',1,'Value',1,'Max',userData.nFrames,...
'SliderStep',[1/max(1,double(userData.nFrames-1)) 10/max(1,double(userData.nFrames-1))]);
userData.imIndx=1;
userData.imData=mat2gray(userData.MD.channels_(userData.chanIndex).loadImage(userData.imIndx));
set(handles.listbox_selectedChannels,'Callback',@(h,event) update_data(h,event,guidata(h)));
% Choose default command line output for addMovieROIGUI
handles.output = hObject;
% Update user data and GUI data
set(hObject, 'UserData', userData);
guidata(hObject, handles);
update_data(hObject,eventdata,handles);
% --- Outputs from this function are returned to the command line.
function varargout = addMovieROIGUI_OutputFcn(~, ~, 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 pushbutton_cancel.
function pushbutton_cancel_Callback(~, ~, handles)
% Delete figure
delete(handles.figure1);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, ~, handles)
% Notify the package GUI that the setting panel is closed
userData = get(handles.figure1, 'UserData');
if ~isempty(userData)
if ishandle(userData.helpFig), delete(userData.helpFig); end
if ishandle(userData.previewFig), delete(userData.previewFig); end
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
end
% --- Executes on key press with focus on pushbutton_addROI and none of its controls.
function pushbutton_addROI_KeyPressFcn(~, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_addROI, [], handles);
end
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(~, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_addROI, [], handles);
end
% --- Executes on button press in checkbox_preview.
function update_data(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
% Retrieve the channel index
props=get(handles.listbox_selectedChannels,{'UserData','Value'});
chanIndex = props{1}(props{2});
imIndx = get(handles.slider_frameNumber,'Value');
% Load a new image if either the image number or the channel has been changed
if (chanIndex~=userData.chanIndex) || (imIndx~=userData.imIndx)
% Update image flag and dat
userData.imData=mat2gray(userData.MD.channels_(chanIndex).loadImage(imIndx));
userData.updateImage=1;
userData.chanIndex=chanIndex;
userData.imIndx=imIndx;
% Update roi
if userData.imPolyHandle.isvalid
userData.ROI=getPosition(userData.imPolyHandle);
end
else
userData.updateImage=0;
end
% Create figure if non-existing or closed
if ~isfield(userData, 'previewFig') || ~ishandle(userData.previewFig)
userData.previewFig = figure('NumberTitle','off','Name',...
'Select the region of interest','DeleteFcn',@close_previewFig,...
'UserData',handles.figure1);
axes('Position',[.05 .05 .9 .9]);
userData.newFigure = 1;
else
figure(userData.previewFig);
userData.newFigure = 0;
end
% Retrieve the image object handle
imHandle =findobj(userData.previewFig,'Type','image');
if userData.newFigure || userData.updateImage
if isempty(imHandle)
imHandle=imshow(userData.imData);
axis off;
else
set(imHandle,'CData',userData.imData);
end
end
if userData.imPolyHandle.isvalid
% Update the imPoly position
setPosition(userData.imPolyHandle,userData.ROI)
else
% Create a new imPoly object and store the handle
userData.imPolyHandle = impoly(get(imHandle,'Parent'),userData.ROI);
fcn = makeConstrainToRectFcn('impoly',get(imHandle,'XData'),get(imHandle,'YData'));
setPositionConstraintFcn(userData.imPolyHandle,fcn);
end
set(handles.figure1, 'UserData', userData);
guidata(hObject,handles);
function close_previewFig(hObject, eventdata)
handles = guidata(get(hObject,'UserData'));
userData=get(handles.figure1,'UserData');
userData.ROI=getPosition(userData.imPolyHandle);
set(handles.figure1,'UserData',userData);
update_data(hObject, eventdata, handles);
% --- Executes on slider movement.
function frameNumberEdition_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
% Retrieve the value of the selected image
if strcmp(get(hObject,'Tag'),'edit_frameNumber')
frameNumber = str2double(get(handles.edit_frameNumber, 'String'));
else
frameNumber = get(handles.slider_frameNumber, 'Value');
end
frameNumber=round(frameNumber);
% Check the validity of the frame values
if isnan(frameNumber)
warndlg('Please provide a valid frame value.','Setting Error','modal');
end
frameNumber = min(max(frameNumber,1),userData.nFrames);
% Store value
set(handles.slider_frameNumber,'Value',frameNumber);
set(handles.edit_frameNumber,'String',frameNumber);
% Save data and update graphics
set(handles.figure1, 'UserData', userData);
guidata(hObject, handles);
update_data(hObject,eventdata,handles);
% --- Executes on button press in pushbutton_outputDirectory.
function pushbutton_outputDirectory_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
pathname = uigetdir(userData.MD.movieDataPath_,'Select output directory');
% Test uigetdir output and store its results
if isequal(pathname,0), return; end
set(handles.edit_outputDirectory,'String',pathname);
% Save data
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
% --- Executes on button press in pushbutton_addROI.
function pushbutton_addROI_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
% Check valid output directory
outputDirectory = get(handles.edit_outputDirectory,'String');
if isempty(outputDirectory),
errordlg('Please select an output directory','Error','modal');
return;
end
% Read ROI if crop window is still visible
if userData.imPolyHandle.isvalid
userData.ROI=getPosition(userData.imPolyHandle);
set(handles.figure1,'UserData',userData);
end
update_data(hObject,eventdata,handles);
% Create ROI mask and save it in the outputDirectory
userData = get(handles.figure1, 'UserData');
mask=createMask(userData.imPolyHandle);
maskPath = fullfile(outputDirectory,'roiMask.tif');
imwrite(mask,maskPath);
% Create a new region of interest and save the object
userData.MD.addROI(maskPath,outputDirectory);
movieROI=userData.MD.rois_(end);
movieROI.save;
% If called from movieSelectorGUI
if userData.mainFig ~=-1,
% Retrieve main window userData
userData_main = get(userData.mainFig, 'UserData');
% Append new ROI to movie selector panel
userData_main.MD = horzcat(userData_main.MD, movieROI);
set(userData.mainFig, 'UserData', userData_main)
movieSelectorGUI('refreshDisplay',userData.mainFig,...
eventdata,guidata(userData.mainFig));
end
% Delete current window
delete(handles.figure1)
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
trackingProcessGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/trackingProcessGUI.m
| 16,305 |
utf_8
|
55317020c14298cee6e4d87fb6d56a40
|
function varargout = trackingProcessGUI(varargin)
% TRACKINGPROCESSGUI M-file for trackingProcessGUI.fig
% TRACKINGPROCESSGUI, by itself, creates a new TRACKINGPROCESSGUI or raises the existing
% singleton*.
%
% H = TRACKINGPROCESSGUI returns the handle to a new TRACKINGPROCESSGUI or the handle to
% the existing singleton*.
%
% TRACKINGPROCESSGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in TRACKINGPROCESSGUI.M with the given input arguments.
%
% TRACKINGPROCESSGUI('Property','Value',...) creates a new TRACKINGPROCESSGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before trackingProcessGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to trackingProcessGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help trackingProcessGUI
% Last Modified by GUIDE v2.5 05-Mar-2012 18:28:45
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @trackingProcessGUI_OpeningFcn, ...
'gui_OutputFcn', @trackingProcessGUI_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 trackingProcessGUI is made visible.
function trackingProcessGUI_OpeningFcn(hObject, eventdata, handles, varargin)
processGUI_OpeningFcn(hObject, eventdata, handles, varargin{:},'initChannel',1);
% Parameter Setup
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
funParams = userData.crtProc.funParams_;
set(handles.popupmenu_probDim,'String',{'2','3'},'UserData',[2 3],...
'Value',find(funParams.probDim==[2 3]));
set(handles.checkbox_verbose, 'Value', funParams.verbose)
% gapCloseParam
set(handles.edit_maxgap, 'String', num2str(funParams.gapCloseParam.timeWindow - 1))
set(handles.edit_minlength, 'String', num2str(funParams.gapCloseParam.minTrackLen))
set(handles.checkbox_histogram, 'Value', funParams.gapCloseParam.diagnostics)
set(handles.checkbox_merging, 'Value',ismember(funParams.gapCloseParam.mergeSplit,[1 2]));
set(handles.checkbox_splitting, 'Value',ismember(funParams.gapCloseParam.mergeSplit,[1 3]));
% Set cost matrics
defaultLinkingCostMat = userData.crtProc.getDefaultLinkingCostMatrices(userData.MD,funParams.gapCloseParam.timeWindow);
defaultGapClosingCostMat = userData.crtProc.getDefaultGapClosingCostMatrices(userData.MD,funParams.gapCloseParam.timeWindow);
userData.cost_linking = {defaultLinkingCostMat.funcName};
userData.cost_gapclosing = {defaultGapClosingCostMat.funcName};
userData.fun_cost_linking = {defaultLinkingCostMat.GUI};
userData.fun_cost_gap = {defaultGapClosingCostMat.GUI};
% Retrieve index of default cost matrices
i1 = find(strcmp(funParams.costMatrices(1).funcName, userData.cost_linking));
i2 = find(strcmp(funParams.costMatrices(2).funcName, userData.cost_gapclosing));
assert(isscalar(i1) && isscalar(i2),'User-defined: the length of matching methods must be 1.')
nLinking=numel(defaultLinkingCostMat);
nGapClosing=numel(defaultGapClosingCostMat);
u1 = cell(1,nLinking);
u2 = cell(1,nGapClosing);
u1{i1} = funParams.costMatrices(1).parameters;
u2{i2} = funParams.costMatrices(2).parameters;
for i=setdiff(1:nLinking,i1), u1{i}=defaultLinkingCostMat(i).parameters; end
for i=setdiff(1:nGapClosing,i1), u2{i}=defaultGapClosingCostMat(i).parameters; end
set(handles.popupmenu_linking, 'Value', i1, 'UserData', u1,...
'String',{defaultLinkingCostMat.name})
set(handles.popupmenu_gapclosing, 'Value', i2, 'UserData', u2,...
'String',{defaultGapClosingCostMat.name})
% Kalman functions
userData.kalmanFunctions = TrackingProcess.getKalmanFunctions;
nKalmanFunctions = numel(userData.kalmanFunctions);
kalmanFields = {'reserveMem','initialize','calcGain','timeReverse'};
index=true(1,nKalmanFunctions);
for i=1:numel(kalmanFields)
index=index & strcmp(funParams.kalmanFunctions.(kalmanFields{i}),...
{userData.kalmanFunctions.(kalmanFields{i})});
end
assert(sum(index)==1, 'Did not find a unique Kalman set.');
u2 = cell(1,nKalmanFunctions);
u2{index} = funParams.costMatrices(1).parameters.kalmanInitParam;
set(handles.popupmenu_kalmanFunctions,'UserData',u2,...
'String', {userData.kalmanFunctions.name}, 'Value', find(index))
set(handles.checkbox_export, 'Value', funParams.saveResults.export)
% Initialize children figure handles
userData.linkingFig=-1;
userData.gapclosingFig=-1;
userData.kalmanFig=-1;
% Choose default command line output for trackingProcessGUI
handles.output = hObject;
% Update user data and GUI data
set(hObject, 'UserData', userData);
uicontrol(handles.pushbutton_done);
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = trackingProcessGUI_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 pushbutton_done.
function pushbutton_done_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
% Check User Input
if isempty(get(handles.listbox_selectedChannels, 'String'))
errordlg('Please select at least one input channel from ''Available Channels''.','Setting Error','modal')
return;
end
props = get(handles.popupmenu_probDim, {'UserData','Value'});
probDim=props{1}(props{2});
timeWindow = str2double(get(handles.edit_maxgap, 'String'))+1;
if isnan(timeWindow) || timeWindow < 0 || floor(timeWindow) ~= ceil(timeWindow)
errordlg('Please provide a valid value to parameter "Maximum Gap to Close".','Error','modal')
return
end
minTrackLen = str2double(get(handles.edit_minlength, 'String'));
if isnan(minTrackLen) || minTrackLen < 0 || floor(minTrackLen) ~= ceil(minTrackLen)
errordlg('Please provide a valid value to parameter "Minimum Length of Track Segment from First Step to use in Second Step".','Error','modal')
return
end
% -------- Set parameter --------
channelIndex = get (handles.listbox_selectedChannels, 'Userdata');
funParams.ChannelIndex = channelIndex;
funParams.probDim = probDim;
funParams.verbose = get(handles.checkbox_verbose, 'Value');
funParams.gapCloseParam.timeWindow = timeWindow;
funParams.gapCloseParam.minTrackLen = minTrackLen;
funParams.gapCloseParam.diagnostics = get(handles.checkbox_histogram, 'Value');
if get(handles.checkbox_merging, 'Value') && get(handles.checkbox_splitting, 'Value')
funParams.gapCloseParam.mergeSplit = 1;
elseif get(handles.checkbox_merging, 'Value') && ~get(handles.checkbox_splitting, 'Value')
funParams.gapCloseParam.mergeSplit = 2;
elseif ~get(handles.checkbox_merging, 'Value') && get(handles.checkbox_splitting, 'Value')
funParams.gapCloseParam.mergeSplit = 3;
elseif ~get(handles.checkbox_merging, 'Value') && ~get(handles.checkbox_splitting, 'Value')
funParams.gapCloseParam.mergeSplit = 0;
end
funParams.saveResults.export = get(handles.checkbox_export, 'Value');
% Cost matrices
i_linking = get(handles.popupmenu_linking, 'Value');
i_gapclosing = get(handles.popupmenu_gapclosing, 'Value');
u_linking = get(handles.popupmenu_linking, 'UserData');
u_gapclosing = get(handles.popupmenu_gapclosing, 'UserData');
if isempty( u_linking{i_linking} )
errordlg('Plese set up the selected cost function for "Step 1: frame-to-frame linking".','Error','modal')
end
if isempty( u_gapclosing{i_gapclosing} )
errordlg('Plese set up the selected cost function for "Step 2: gap closing, mergin and splitting".','Error','modal')
end
funParams.costMatrices(1).funcName = userData.cost_linking{i_linking};
funParams.costMatrices(1).parameters = u_linking{i_linking};
funParams.costMatrices(2).funcName = userData.cost_gapclosing{i_gapclosing};
funParams.costMatrices(2).parameters = u_gapclosing{i_gapclosing};
% Get Kalman values
iKalman = get(handles.popupmenu_kalmanFunctions, 'Value');
kalmanFields = {'reserveMem','initialize','calcGain','timeReverse'};
for i=1:numel(kalmanFields)
funParams.kalmanFunctions.(kalmanFields{i})=userData.kalmanFunctions(iKalman).(kalmanFields{i});
end
kalmanData = get(handles.popupmenu_kalmanFunctions, 'UserData');
funParams.costMatrices(1).parameters.kalmanInitParam = kalmanData{iKalman};
% Set up parameters effected by funParams.gapCloseParam.timeWindow
if isfield(funParams.costMatrices(2).parameters,'brownStdMult'),
funParams.costMatrices(2).parameters.brownStdMult = funParams.costMatrices(2).parameters.brownStdMult(1) * ones(funParams.gapCloseParam.timeWindow,1);
end
if isfield(funParams.costMatrices(2).parameters,'linStdMult'),
funParams.costMatrices(2).parameters.linStdMult = funParams.costMatrices(2).parameters.linStdMult(1) * ones(funParams.gapCloseParam.timeWindow,1);
end
processGUI_ApplyFcn(hObject,eventdata,handles,funParams)
% --- Executes on button press in pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
delete(handles.figure1);
% --- Executes on button press in pushbutton_set_linking.
function pushbutton_set_linking_Callback(hObject, eventdata, handles)
% userData.linkingFig - the handle of setting panel for linking set-up
% userData.gapclosingFig - the handle of setting panel for gap closing set-up
% userData.kalmanFig
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
parent = handles.popupmenu_linking;
procID = get(parent, 'Value');
if procID > length(userData.fun_cost_linking)
warndlg('Please select a cost function for linking step.','Error','modal')
return
else
settingGUI = userData.fun_cost_linking{procID};
userData.linkingFig = settingGUI(parent, procID);
end
set(handles.figure1, 'UserData', userData);
% --- Executes on button press in pushbutton_set_gapclosing.
function pushbutton_set_gapclosing_Callback(hObject, eventdata, handles)
% userData.linkingFig - the handle of setting panel for linking set-up
% userData.gapclosingFig - the handle of setting panel for gap closing set-up
% userData.kalmanFig
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
parent = handles.popupmenu_gapclosing;
procID = get(parent, 'Value');
if procID > length(userData.fun_cost_gap)
warndlg('Please select a cost function for gap closing step.','Error','modal')
return
else
settingGUI = userData.fun_cost_gap{procID};
userData.gapclosingFig = settingGUI(parent, procID);
end
set(handles.figure1, 'UserData', userData);
function edit_maxgap_Callback(hObject, eventdata, handles)
maxgap = str2double(get(handles.edit_maxgap, 'String'));
if isnan(maxgap) || maxgap < 0 || floor(maxgap) ~= ceil(maxgap)
errordlg('Please provide a valid value to parameter "Maximum Gap to Close".','Warning','modal')
return;
end
timeWindow = maxgap + 1; % Retrieve the new value for the time window
% Retrieve the parameters of the linking and gap closing matrices
u_linking = get(handles.popupmenu_linking, 'UserData');
linkingID = get(handles.popupmenu_linking, 'Value');
linkingParameters = u_linking{linkingID};
u_gapclosing = get(handles.popupmenu_gapclosing, 'UserData');
gapclosingID = get(handles.popupmenu_gapclosing, 'Value');
gapclosingParameters = u_gapclosing{gapclosingID};
% Check for changes
linkingnnWindowChange=(linkingParameters.nnWindow~=timeWindow);
gapclosingnnWindowChange=isfield(gapclosingParameters,'nnWindow') && (gapclosingParameters.nnWindow~=timeWindow);
gapclosingtimeReachConfBChange=isfield(gapclosingParameters,'timeReachConfB') && (gapclosingParameters.timeReachConfB~=timeWindow);
gapclosingtimeReachConfLChange=isfield(gapclosingParameters,'timeReachConfL') &&(gapclosingParameters.timeReachConfL~=timeWindow);
if ~linkingnnWindowChange && ~gapclosingnnWindowChange && ...
~gapclosingtimeReachConfBChange && ~gapclosingtimeReachConfLChange,
return;
end
% Optional: asks the user if the time window value should be propagated
% to the linking and gap closing matrics
modifyParameters=questdlg('Do you want to propagate the changes in the maximum number of gaps to close?',...
'Parameters update','Yes','No','Yes');
if ~strcmp(modifyParameters,'Yes'), return; end
% Set new linking time window
if linkingnnWindowChange, linkingParameters.nnWindow=timeWindow; end
u_linking{linkingID} = linkingParameters;
set(handles.popupmenu_linking, 'UserData', u_linking)
% Set new gap closing time window
if gapclosingnnWindowChange, gapclosingParameters.nnWindow=timeWindow; end
if gapclosingtimeReachConfBChange, gapclosingParameters.timeReachConfB=timeWindow; end
if gapclosingtimeReachConfLChange, gapclosingParameters.timeReachConfL=timeWindow; end
u_gapclosing{gapclosingID} = gapclosingParameters;
set(handles.popupmenu_gapclosing, 'UserData', u_gapclosing)
guidata(hObject,handles);
% --- Executes on button press in pushbutton_kalman_initialize.
function pushbutton_kalman_initialize_Callback(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
parent = handles.popupmenu_kalmanFunctions;
id = get(parent, 'Value');
settingGUI = userData.kalmanFunctions(id).initializeGUI;
userData.kalmanFig = settingGUI(parent, id);
set(handles.figure1, 'UserData', userData);
% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(hObject, eventdata, handles)
if strcmp(eventdata.Key, 'return')
pushbutton_done_Callback(handles.pushbutton_done, [], handles);
end
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
userData = get(handles.figure1, 'UserData');
if(isempty(userData)), userData = struct(); end;
% Delete setting panels
if ishandle(userData.linkingFig), delete(userData.linkingFig);end
if ishandle(userData.gapclosingFig), delete(userData.gapclosingFig); end
if ishandle(userData.kalmanFig), delete(userData.kalmanFig); end
% --- Executes on button press in checkbox_export.
function checkbox_export_Callback(hObject, eventdata, handles)
if get(hObject,'Value')
exportMsg=sprintf('The output matrices resulting from this process might be very large. Be cautious if you have large movies');
if any([get(handles.checkbox_merging, 'Value') get(handles.checkbox_splitting, 'Value')])
exportMsg =[exportMsg sprintf('\n \nAny merging and splitting information will be lost in the exported format.')];
end
warndlg(exportMsg,'Warning','modal')
end
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
delete(hObject);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
packageGUI_OpeningFcn.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/packageGUI_OpeningFcn.m
| 14,244 |
utf_8
|
6220495595ec1b14ec4939661efd30d0
|
function packageGUI_OpeningFcn(hObject,eventdata,handles,packageName,varargin)
% Callback called at the opening of packageGUI
%
% packageGUI_OpeningFcn(packageName,MD) MD: MovieData object
%
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Useful tools
%
% User Data:
%
% userData.MD - array of MovieData object
% userData.MD - array of MovieList object
% userData.package - array of package (same length with userData.MD)
% userData.crtPackage - the package of current MD
% userData.id - the id of current MD on board
%
% userData.dependM - dependency matrix
% userdata.statusM - GUI status matrix
% userData.optProcID - optional process ID
% userData.applytoall - array of boolean for batch movie set up
%
% userData.passIconData - pass icon image data
% userData.errorIconData - error icon image data
% userData.warnIconData - warning icon image data
% userData.questIconData - help icon image data
% userData.colormap - color map
%
% userData.setFig - array of handles of (multiple) setting figures (may not exist)
% userData.resultFig - array of handles of (multiple) result figures (may not exist)
% userData.packageHelpFig - handle of (single) help figure (may not exist)
% userData.iconHelpFig - handle of (single) help figures (may not exist)
% userData.statusFig - handle of (multiple) status figures (may not exist)
% userData.processHelpFig - handle of (multiple) help figures (may not exist)
%
%
% NOTE:
%
% userData.statusM - 1 x m stucture array, m is the number of Movie Data
% this user data is used to save the status of movies
% when GUI is switching between different movie(s)
%
% fields: IconType - the type of status icons, 'pass', 'warn', 'error'
% Msg - the message displayed when clicking status icons
% Checked - 1 x n logical array, n is the number of processes
% used to save value of check box of each process
% Visited - logical true or false, if the movie has been
% loaded to GUI before
% Sebastien Besson May 2011 (last modified Sep 2011()
% Input check
ip = inputParser;
ip.addRequired('hObject',@ishandle);
ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x));
ip.addRequired('handles',@isstruct);
ip.addRequired('packageName',@ischar);
ip.addOptional('MO',[],@(x) isa(x,'MovieObject'));
ip.addParamValue('MD',[],@(x) isempty(x) || isa(x,'MovieData'));
ip.addParamValue('ML',[],@(x) isempty(x) || isa(x,'MovieList'));
ip.addParamValue('packageConstr','',@(x) isa(x,'function_handle'));
ip.parse(hObject,eventdata,handles,packageName,varargin{:});
% Read the package name
packageName = ip.Results.packageName;
assert(any(strcmp(superclasses(packageName),'Package')),...
sprintf('%s is not a valid Package',packageName));
handles.output = hObject;
userData = get(handles.figure1,'UserData');
if isempty(userData), userData = struct(); end
userData.packageName = packageName;
userData.MD = ip.Results.MD;
userData.ML = ip.Results.ML;
%If package GUI supplied without argument, saves a boolean which will be
%read by packageNameGUI_OutputFcn
if isempty(ip.Results.MO)
userData.startMovieSelectorGUI=true;
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
return
end
if isa(ip.Results.MO,'MovieList')
userData.ML = ip.Results.MO;
set(handles.pushbutton_status,'Enable','off');
else
userData.MD=ip.Results.MO;
end
% Call package GUI error
set(handles.text_copyright, 'String', getLCCBCopyright());
% Singleton control
try assert(~userData.init)
catch ME
if strcmpi(ME.identifier,'MATLAB:nonExistentField');
userData.init=true;
else
return
end
end
% ----------------------------- Load MovieData ----------------------------
nMovies = numel(ip.Results.MO);
packageIndx = cell(1, nMovies);
% I. Before loading MovieData, firstly check if the current package exists
for i = 1:nMovies
% Check for existing packages and create them if false
packageIndx{i} = ip.Results.MO(i).getPackageIndex(packageName,1,false);
end
for i = find(~cellfun(@isempty, packageIndx))
userData.package(i) = ip.Results.MO(i).packages_{packageIndx{i}};
end
if any(cellfun(@isempty, packageIndx))
% Get the adapted constructor
if ~isempty(ip.Results.packageConstr),
packageConstr = ip.Results.packageConstr;
elseif isConcreteClass(userData.packageName)
packageConstr = str2func(userData.packageName);
else
% Launch interface to determine constructor
concretePackages = eval([userData.packageName '.getConcretePackages()']);
[selection, status] = listdlg('Name','',...
'PromptString',{'Select the type of object';'you want to track:'},...
'ListString', {concretePackages.name},'SelectionMode','single');
if ~status,
userData.startMovieSelectorGUI=true;
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
return
end
packageConstr = concretePackages(selection).packageConstr;
end
% Add package to movie
for i = find(cellfun(@isempty, packageIndx))
ip.Results.MO(i).addPackage(packageConstr(ip.Results.MO(i),...
ip.Results.MO(i).outputDirectory_));
userData.package(i) = ip.Results.MO(i).packages_{end};
end
end
% Run sanity check to check basic dependencies are satisfied
movieExceptions = cell(nMovies, 1);
for i = 1:nMovies
try
userData.package(i).sanityCheck(true,'all');
catch ME
movieExceptions{i} = MException('lccb:initialization',...
'%s initialization',...
userData.package(i).getName);
movieExceptions{i} = movieExceptions{i}.addCause(ME);
end
end
if ~all(cellfun(@isempty, movieExceptions))
generateReport(movieExceptions, userData);
userData.startMovieSelectorGUI=true;
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
return
end
% ------------- Check if existing processes can be recycled ---------------
recyclableProc = cell(1, nMovies);
processClassNames = userData.package(1).getProcessClassNames;
% Multiple movies loop
for i = 1:nMovies
if isempty(packageIndx{i}) && ~isempty(ip.Results.MO(i).processes_)
recyclableProcIndx = cellfun(@(x) cellfun(@(y)isa(y,x),...
ip.Results.MO(i).processes_),processClassNames,'UniformOutput',false);
recyclableProc{i}=ip.Results.MO(i).processes_(any(vertcat(recyclableProcIndx{:}),1));
end
end
recyclableProcMovie = find(~cellfun(@isempty, recyclableProc));
if ~isempty(recyclableProcMovie)
% Ask user if to recycle
msg = ['Record indicates that existing processes are recyclable for %s package:'...
'\n\nDo you want to load and re-use these steps?'];
user_response = questdlg(sprintf(msg,userData.package(1).getName),...
'Recycle Existing Steps','No','Yes','Yes');
if strcmpi(user_response,'Yes')
for i = recyclableProcMovie
recycleProcessGUI(recyclableProc{i}, userData.package(i),'mainFig', handles.figure1)
end
end
end
% Initialize userdata
userData.id = 1;
userData.crtPackage = userData.package(userData.id);
userData.dependM = userData.package(userData.id).getDependencyMatrix;
userData.optProcID =find(sum(userData.dependM==2,1));
nProc = size(userData.dependM, 1);
userData.statusM = repmat( struct('IconType', {cell(1,nProc)}, 'Msg', {cell(1,nProc)}, 'Checked', zeros(1,nProc), 'Visited', false), 1, nMovies);
% -----------------------Load and set up icons----------------------------
% Load icon images from dialogicons.mat
userData = loadLCCBIcons(userData);
% Set figure colormap
supermap(1,:) = get(hObject,'color');
set(hObject,'colormap',supermap);
userData.colormap = supermap;
% Set up package help.
set(handles.figure1,'CurrentAxes',handles.axes_help);
Img = image(userData.questIconData);
set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),...
'visible','off','YDir','reverse');
set(Img,'ButtonDownFcn',@icon_ButtonDownFcn, 'UserData', struct('class', packageName))
% --------------------------Set up processes------------------------------
% List of template process uicontrols to expand
templateTag{1} = 'checkbox';
templateTag{2} = 'axes_icon';
templateTag{3} = 'pushbutton_show';
templateTag{4} = 'pushbutton_set';
templateTag{5} = 'axes_prochelp';
templateTag{6} = 'pushbutton_open';
set(handles.(templateTag{6}),'CData',userData.openIconData);
% templateTag{6} = 'pushbutton_clear'; To be implemented someday?
procTag=templateTag;
set(handles.figure1,'Position',...
get(handles.figure1,'Position')+(nProc-1)*[0 0 0 40])
set(handles.panel_movie,'Position',...
get(handles.panel_movie,'Position')+(nProc-1)*[0 40 0 0])
set(handles.panel_proc,'Position',...
get(handles.panel_proc,'Position')+(nProc-1)*[0 0 0 40])
set(handles.text_status, 'Position',...
get(handles.text_status,'Position')+(nProc-1)*[0 40 0 0])
% Replicate templates ui controls for each process
for i = 1 : nProc
for j = 1 : length(templateTag)
procTag{j}=[templateTag{j} '_' num2str(i)];
handles.(procTag{j}) = copyobj(handles.(templateTag{j}),handles.panel_proc);
set(handles.(procTag{j}),'Tag',procTag{j},'Position',...
get(handles.(templateTag{j}),'Position')+(nProc-i)*[0 40 0 0]);
if ~strcmp(templateTag{j}(1:4), 'axes')
% Make sure callbacks are copied - copyobj does not copy
% callbacks starting with R2014b
set(handles.(procTag{j}),'Callback',...
get(handles.(templateTag{j}),'Callback'));
end
end
% Set name of the process in the corresponding checkbox
processClassName = userData.crtPackage.getProcessClassNames{i};
processName=eval([processClassName '.getName']);
checkboxString = [' Step ' num2str(i) ': ' processName];
set(handles.(procTag{1}),'String',checkboxString)
% Setup help button
set(handles.figure1,'CurrentAxes',handles.(procTag{5}));
Img = image(userData.smallquestIconData);
set(gca, 'XLim',get(Img,'XData'),'YLim',get(Img,'YData'),...
'visible','off','YDir','reverse');
set(Img,'ButtonDownFcn',@icon_ButtonDownFcn,...
'UserData', struct('class', processClassName))
end
% Remove templates and remove from the handles structure
cellfun(@(x) delete(handles.(x)), templateTag)
handles = rmfield(handles,templateTag);
% Add text boxes for optional processes
optTag = 'text_optional';
for i = userData.optProcID
procOptTag=[optTag '_' num2str(i)];
handles.(procOptTag) = copyobj(handles.(optTag),handles.panel_proc);
set(handles.(procOptTag),'Tag',procOptTag,'Position',...
get(handles.(optTag),'Position')+(nProc-i)*[0 40 0 0]);
end
% Remove template optional text box
delete(handles.(optTag));
handles = rmfield(handles,optTag);
% --------------------------Create tools menu-----------------------------
if ~isempty(userData.crtPackage.getTools)
handles.menu_tools = uimenu(handles.figure1,'Label','Tools','Position',2);
for i=1:length(userData.crtPackage.getTools)
toolMenuTag=['menu_tools_' num2str(i)];
handles.(toolMenuTag) = uimenu(handles.menu_tools,...
'Label',userData.crtPackage.getTools(i).name,...
'Callback',@(h,event)menu_tools_Callback(h),'Tag',toolMenuTag);
end
end
% --------------------------Other GUI settings-----------------------------
% set titles
set(handles.figure1, 'Name',['Control Panel - ' userData.crtPackage.getName]);
set(handles.text_packageName,'String',userData.crtPackage.getName);
% Set movie explorer
msg = {};
if isa(ip.Results.MO,'MovieData'), movieType = 'Movie'; else movieType = 'Movie list'; end
for i = 1: length(ip.Results.MO)
msg = horzcat(msg, {sprintf(' %s %d of %d', movieType, i, length(ip.Results.MO))});
end
set(handles.popupmenu_movie, 'String', msg, 'Value', userData.id);
% Set option depen
if length(ip.Results.MO) == 1
set(handles.checkbox_runall, 'Visible', 'off')
set(handles.pushbutton_left, 'Enable', 'off')
set(handles.pushbutton_right, 'Enable', 'off')
set(handles.checkbox_all, 'Visible', 'off', 'Value', 0)
userData.applytoall=zeros(nProc,1);
else
set(handles.checkbox_runall, 'Visible', 'on')
userData.applytoall=ones(nProc,1);
end
set(handles.pushbutton_run, 'Callback', @(hObject,eventdata)packageGUI_RunFcn(hObject,eventdata,guidata(hObject)));
% Set web links in menu
set(handles.menu_about_gpl,'UserData','http://www.gnu.org/licenses/gpl.html')
set(handles.menu_about_lccb,'UserData','http://lccb.hms.harvard.edu/')
set(handles.menu_about_lccbsoftware,'UserData','http://lccb.hms.harvard.edu/software.html')
% Update handles structure
set(handles.figure1,'UserData',userData);
guidata(hObject, handles);
set(Img,'ButtonDownFcn',@icon_ButtonDownFcn);
packageGUI_RefreshFcn(handles, 'initialize')
end
% --------------------------------------------------------------------
function menu_tools_Callback(hObject)
handles =guidata(hObject);
userData = get(handles.figure1, 'UserData');
prop=get(hObject,'Tag');
toolID = str2double(prop(length('menu_tools_')+1:end));
toolHandle=userData.crtPackage.getTools(toolID).funHandle;
userData.toolFig(toolID) = toolHandle('mainFig',handles.figure1);
set(handles.figure1, 'UserData', userData);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
postProcessMovieComets.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/postProcessMovieComets.m
| 6,990 |
utf_8
|
0ac022ca6d0a09fb798c3f1ef7dab229
|
function postProcessMovieComets(movieData,varargin)
% Track features in a movie which has been processed by a detection method
%
% Sebastien Besson, Feb 2012
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
%% Input
%Check input
ip = inputParser;
ip.CaseSensitive = false;
ip.addRequired('movieData', @(x) isa(x,'MovieData'));
ip.addOptional('paramsIn',[], @isstruct);
ip.parse(movieData,varargin{:});
paramsIn=ip.Results.paramsIn;
%Get the indices of any previous tracking processes from this function
iProc = movieData.getProcessIndex('CometPostTrackingProcess',1,0);
%If the process doesn't exist, create it
if isempty(iProc)
iProc = numel(movieData.processes_)+1;
movieData.addProcess(CometPostTrackingProcess(movieData));
end
postProc = movieData.processes_{iProc};
%Parse input, store in parameter structure
p = parseProcessParams(postProc,paramsIn);
%% --------------- Initialization ---------------%%
errorMsg = @(metadata) ['Missing ' metadata '. Please in the movie''s '...
metadata ' before post-processing the tracks.'];
assert(~isempty(movieData.timeInterval_), errorMsg('time interval'));
assert(~isempty(movieData.pixelSize_), errorMsg('pixels size'));
% Check detection process first
iTrackProc =movieData.getProcessIndex('TrackingProcess',1,1);
assert(~isempty(iTrackProc),['Tracking has not been run! '...
'Please run tracking prior to post-processing!'])
trackProc = movieData.processes_{iTrackProc};
assert(all(trackProc.checkChannelOutput(p.ChannelIndex)),...
['Missing tracking output ! Please apply tracking before ' ...
'running post-processing!'])
iDetProc =movieData.getProcessIndex('DetectionProcess',1,1);
assert(~isempty(iDetProc),'Please run detection first');
detProc=movieData.processes_{iDetProc};
assert(all(detProc.checkChannelOutput(p.ChannelIndex)),...
['Missing detection output ! Please apply detection before ' ...
'running post-processing!']);
% Set up the input directories (input images)
inFilePaths = cell(2,numel(movieData.channels_));
for i = p.ChannelIndex
inFilePaths{1,i} = trackProc.outFilePaths_{1,i};
inFilePaths{2,i} = detProc.outFilePaths_{1,i};
end
postProc.setInFilePaths(inFilePaths);
% Set up the output file
outFilePaths = cell(2,numel(movieData.channels_));
for i = p.ChannelIndex
outFilePaths{1,i} = [p.OutputDirectory filesep 'channel_' num2str(i) '.mat'];
outFilePaths{2,i} = [p.OutputDirectory filesep 'channel_' num2str(i) '.txt'];
outFilePaths{3,i} = [p.OutputDirectory filesep 'channel_' num2str(i) '_stats.txt'];
outFilePaths{4,i} = [p.OutputDirectory filesep 'channel_' num2str(i) '_histograms'];
end
if isdir(p.OutputDirectory), rmdir(p.OutputDirectory, 's'); end
mkdir(p.OutputDirectory);
postProc.setOutFilePaths(outFilePaths);
%% --------------- Displacement field calculation ---------------%%%
disp('Starting post-processing...')
for i = p.ChannelIndex
movieInfo = detProc.loadChannelOutput(i);
tracksFinal = trackProc.loadChannelOutput(i);
projData.secPerFrame = movieData.timeInterval_;
projData.pixSizeNm = movieData.pixelSize_;
% figure out which frames were used in detection
detExists=find(arrayfun(@(x) ~isempty(x.xCoord),movieInfo));
sF=min(detExists); eF=max(detExists);
projData.detectionFrameRange=[sF eF];
% Read tracking parameters
gapCloseParam = trackProc.funParams_.gapCloseParam;
costMatrices = trackProc.funParams_.costMatrices;
projData.trackingParameters.maxGapLength=gapCloseParam.timeWindow;
projData.trackingParameters.minTrackLen=gapCloseParam.minTrackLen;
projData.trackingParameters.minSearchRadius=costMatrices(1,1).parameters.minSearchRadius;
projData.trackingParameters.maxSearchRadius=costMatrices(1,1).parameters.maxSearchRadius;
projData.trackingParameters.maxForwardAngle=costMatrices(1,2).parameters.maxFAngle;
projData.trackingParameters.maxBackwardAngle=costMatrices(1,2).parameters.maxBAngle;
projData.trackingParameters.backVelMultFactor=costMatrices(1,2).parameters.backVelMultFactor;
projData.trackingParameters.fluctRadius=costMatrices(1,2).parameters.fluctRad;
% Call main post-processing function
[projData,M]=postProcessMTTracks(projData, tracksFinal, movieInfo,...
[1 movieData.nFrames_],p.remBegEnd,...
'fgapReclassScheme',p.fgapReclassScheme,...
'bgapReclassScheme',p.bgapReclassScheme);
% save each projData in its own directory
save(outFilePaths{1,i},'projData')
% write out speed/lifetime/displacement distributions into a text file
dlmwrite(outFilePaths{2,i}, M,...
'precision', 3,'delimiter', '\t','newline', 'pc');
% Write stats results into a text file
statsFile = outFilePaths{3, i};
statsData= struct2cell(projData.stats);
statsName = fieldnames(projData.stats);
fid=fopen(statsFile,'w+');
for j=1:numel(statsName)
fprintf(fid,'%s\t%g\n',statsName{j},statsData{j});
end
fclose(fid);
if p.makeHist==1
plusTipMakeHistograms(M, outFilePaths{4, i});
if movieData.isOmero() && movieData.canUpload()
uploadHistograms(movieData, outFilePaths{4, i})
end
end
end
disp('Finished post-processing comet tracks!')
function uploadHistograms(movieData, directory)
disp('Uploading histograms to OMERO')
% Retrieve
files = dir(fullfile(directory, '*.eps'));
session = movieData.getOmeroSession();
id = movieData.getOmeroId();
namespace = [getLCCBOmeroNamespace() '.tracking'];
for i = 1 : numel(files),
[~, filename] = fileparts(files(i).name);
ns = [namespace '.' filename];
fas = getImageFileAnnotations(session, id, 'include', ns);
if ~isempty(fas)
% Read file of first found file annotation
fa = fas(1);
updateFileAnnotation(session, fa,...
fullfile(directory, files(i).name));
fprintf(1, 'Updating file annotation: %d\n', fa.getId().getValue());
else
fa = writeFileAnnotation(session,...
fullfile(directory, files(i).name),...
'description', 'Comet post-processing results', 'namespace', ns);
linkAnnotation(session, fa, 'image', id);
msg = 'Created file annotation %g and linked it to image %d\n';
fprintf(1, msg, fa.getId().getValue(), id);
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
omeroDataSelectionGUI.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/omeroDataSelectionGUI.m
| 13,227 |
utf_8
|
fc19b4145a74fe363555711ba2415a13
|
function varargout = omeroDataSelectionGUI(varargin)
% OMERODATASELECTIONGUI MATLAB code for omeroDataSelectionGUI.fig
% OMERODATASELECTIONGUI, by itself, creates a new OMERODATASELECTIONGUI or raises the existing
% singleton*.
%
% H = OMERODATASELECTIONGUI returns the handle to a new OMERODATASELECTIONGUI or the handle to
% the existing singleton*.
%
% OMERODATASELECTIONGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in OMERODATASELECTIONGUI.M with the given input arguments.
%
% OMERODATASELECTIONGUI('Property','Value',...) creates a new OMERODATASELECTIONGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before omeroDataSelectionGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to omeroDataSelectionGUI_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
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track. If not, see <http://www.gnu.org/licenses/>.
%
%
% Edit the above text to modify the response to help omeroDataSelectionGUI
% Last Modified by GUIDE v2.5 07-Apr-2014 11:18:10
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @omeroDataSelectionGUI_OpeningFcn, ...
'gui_OutputFcn', @omeroDataSelectionGUI_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 omeroDataSelectionGUI is made visible.
function omeroDataSelectionGUI_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 omeroDataSelectionGUI (see VARARGIN)
ip = inputParser;
ip.addRequired('hObject',@ishandle);
ip.addRequired('eventdata',@(x) isstruct(x) || isempty(x));
ip.addRequired('handles',@isstruct);
ip.addOptional('MD',[],@(x) isa(x,'MovieData'));
ip.addParamValue('mainFig', -1, @ishandle);
ip.parse(hObject,eventdata,handles,varargin{:})
% Store inpu
userData = get(handles.figure1, 'UserData');
if isempty(userData), userData = struct(); end
userData.mainFig=ip.Results.mainFig;
set(handles.text_copyright, 'String', getLCCBCopyright())
global session
% List users
groupId = session.getAdminService().getEventContext().groupId;
userId = session.getAdminService().getEventContext().userId;
group = session.getAdminService().getGroup(groupId);
userData.groupPermissions = group.getDetails().getPermissions();
if userData.groupPermissions.isGroupRead(),
map = toMatlabList(group.copyGroupExperimenterMap());
ids = arrayfun(@(x) x.getChild().getId().getValue(), map);
names = arrayfun(@(x) [char(x.getChild().getFirstName().getValue())...
' ' char(x.getChild().getLastName().getValue())...
' (' char(x.getChild().getOmeName().getValue()) ')'], map,...
'UniformOutput', false);
set(handles.popupmenu_user, 'Enable', 'on', 'String', names,...
'UserData', ids, 'Value', find(ids == userId));
else
experimenter = session.getAdminService().getExperimenter(userId);
name = [char(experimenter.getFirstName().getValue())...
' ' char(experimenter.getLastName().getValue())...
' (' char(experimenter.getOmeName().getValue()) ')'];
set(handles.popupmenu_user, 'Enable', 'off', 'String', name,...
'UserData', userId, 'Value', 1);
end
set(hObject, 'UserData', userData);
refreshDataList(hObject, [], handles);
% Choose default command line output for omeroDataSelectionGUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes omeroDataSelectionGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = omeroDataSelectionGUI_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 selection change in popupmenu_user.
function refreshDataList(hObject, eventdata, handles)
global session
props = get(handles.popupmenu_user, {'Value', 'UserData'});
userId = props{2}(props{1});
userData = get(handles.figure1, 'UserData');
if isempty(userData), userData = struct(); end
if userId ~= session.getAdminService.getEventContext().userId && ...
~userData.groupPermissions.isGroupAnnotate(),
set(handles.pushbutton_load_images, 'Enable', 'off');
set(handles.pushbutton_load_dataset, 'Enable', 'off');
else
set(handles.pushbutton_load_images, 'Enable', 'on');
set(handles.pushbutton_load_dataset, 'Enable', 'on');
end
% List projects and orphaned datasets
p = omero.sys.ParametersI();
p.exp(rlong(userId));
p.orphan();
proxy = session.getContainerService();
objectList = proxy.loadContainerHierarchy('omero.model.ProjectI', [], p);
orphanList = java.util.ArrayList();
for i = objectList.size() - 1 : -1 : 0,
if ~isa(objectList.get(i), 'omero.model.ProjectI');
orphanList.add(objectList.get(i));
objectList.remove(i);
end
end
projects = sortById(toMatlabList(objectList));
orphanedDatasets = sortById(toMatlabList(orphanList));
projectNames = arrayfun(@(x) char(x.getName().getValue()), projects,...
'UniformOutput', false);
projectNames = [{'none'}; projectNames];
set(handles.popupmenu_project, 'Value', 1, 'String', projectNames,...
'UserData', projects);
% Save orphaned datasets
userData = get(handles.figure1, 'UserData');
if isempty(userData), userData = struct(); end
userData.orphaned_datasets = orphanedDatasets;
set(handles.figure1, 'UserData', userData);
refreshDatasetList(hObject, [], handles);
function refreshImageList(handles)
global session
% Read image list from selected dataset
p_props = get(handles.popupmenu_project, {'Value', 'UserData'});
d_props = get(handles.popupmenu_dataset, {'Value', 'UserData'});
if d_props{1} == 1
images = [];
elseif p_props{1} == 1 && d_props{1} == numel(d_props{2}) + 2;
% Retrieve orphaned images
orphanQuery = ['select img from Image as img '...
'left outer join fetch img.details.owner '...
'left outer join fetch img.pixels as pix '...
'left outer join fetch pix.pixelsType as pt '...
'where not exists (select obl from '...'
'DatasetImageLink as obl where obl.child = img.id) '...
'and not exists (select ws from WellSample as '...
'ws where ws.image = img.id)'...
' and img.details.owner.id = :userID'];
parameters = omero.sys.ParametersI();
u_props = get(handles.popupmenu_user, {'Value', 'UserData'});
parameters.addLong('userID', u_props{2}(u_props{1}));
images = session.getQueryService.findAllByQuery(orphanQuery, parameters);
images = toMatlabList(images);
else
datasetId = d_props{2}(d_props{1}-1).getId.getValue;
images = getImages(session, 'dataset', datasetId);
end
% Update image list
images = sortById(images);
imageNames = arrayfun(@(x) char(x.getName().getValue()), images,...
'UniformOutput', false);
set(handles.listbox_images, 'Value', 1, 'String', imageNames,...
'UserData', images);
% --- Executes on selection change in popupmenu_project.
function refreshDatasetList(hObject, eventdata, handles)
% Read dataset list from selected project
props = get(handles.popupmenu_project, {'Value', 'UserData'});
if props{1} == 1,
userData = get(handles.figure1, 'UserData');
datasets = userData.orphaned_datasets;
else
datasets = toMatlabList(props{2}(props{1} - 1).linkedDatasetList);
datasets = sortById(datasets);
end
% Update datasets drop down menu list
datasetNames = arrayfun(@(x) char(x.getName().getValue()), datasets,...
'UniformOutput', false);
datasetNames = [{'none'}; datasetNames];
if props{1} == 1,
datasetNames = [datasetNames; {'Orphaned images'}];
end
set(handles.popupmenu_dataset, 'Value', 1, 'String', datasetNames,...
'UserData', datasets);
refreshImageList(handles)
% --- Executes on selection change in popupmenu_dataset.
function popupmenu_dataset_Callback(hObject, eventdata, handles)
refreshImageList(handles)
% --- Executes on button press in pushbutton_load_images.
function pushbutton_load_images_Callback(hObject, eventdata, handles)
props = get(handles.listbox_images, {'Value', 'UserData'});
if isempty(props{1}), return; end
imageIDs = arrayfun(@(x) x.getId().getValue(), props{2}(props{1}));
% If derivated from movie selection window, only load new movies
userData = get(handles.figure1, 'UserData');
if isempty(userData), userData = struct(); end
if ishandle(userData.mainFig),
userData=get(handles.figure1,'UserData');
userData_main = get(userData.mainFig, 'UserData');
omeroMovies = arrayfun(@isOmero, userData_main.MD);
existingIDs = arrayfun(@(x) x.getOmeroId(), userData_main.MD(omeroMovies));
imageIDs = setdiff(imageIDs, existingIDs);
end
% Return if empty list
if isempty(imageIDs),
errordlg('All selected images have already been loaded', 'Error', 'modal');
return
end
% Load images from OMERO
global session
MD = getOmeroMovies(session, imageIDs);
% Update movie selector interface
if ishandle(userData.mainFig),
% Append MovieData object to movie selector panel
userData_main.MD = horzcat(userData_main.MD, MD);
set(userData.mainFig, 'UserData', userData_main)
movieSelectorGUI('refreshDisplay', userData.mainFig,...
eventdata, guidata(userData.mainFig))
end
delete(handles.figure1);
% --- Executes on button press in pushbutton_cancel.
function pushbutton_cancel_Callback(hObject, eventdata, handles)
delete(handles.figure1);
% --- Executes on button press in pushbutton_load_dataset.
function pushbutton_load_dataset_Callback(hObject, eventdata, handles)
props = get(handles.popupmenu_dataset, {'Value', 'UserData'});
if props{1} == 1, return; end
datasetIDs = props{2}(props{1}-1).getId().getValue();
% If derivated from movie selection window, only load new movies
userData = get(handles.figure1, 'UserData');
if isempty(userData), userData = struct(); end
if ishandle(userData.mainFig),
userData=get(handles.figure1,'UserData');
userData_main = get(userData.mainFig, 'UserData');
omeroLists = arrayfun(@isOmero, userData_main.ML);
existingIDs = arrayfun(@(x) x.getOmeroId(), userData_main.ML(omeroLists));
datasetIDs = setdiff(datasetIDs, existingIDs);
end
% Return if empty list
if isempty(datasetIDs),
errordlg('All selected datasets have already been loaded', 'Error', 'modal');
return
end
% Load images from OMERO
global session
ML = getOmeroLists(session, datasetIDs);
% Update movie selector interface
if ishandle(userData.mainFig),
% Append MovieList object to movie selector panel
userData_main.ML = horzcat(userData_main.ML, ML);
% Append new MovieData objects to movie selector panel
movieList = arrayfun(@getFullPath, userData_main.MD, 'Unif', false);
if ~isempty(movieList),
index = cellfun(@(x) ~ismember(x.getFullPath(), movieList),...
ML.getMovies());
else
index = true(numel(ML.getMovies), 1);
end
if any(index)
newMovies = ML.getMovies();
newMovies = newMovies(index);
userData_main.MD = horzcat(userData_main.MD, newMovies{:});
else
warndlg('All images containedin dataset has already been loaded',...
'Warning','modal');
end
set(userData.mainFig, 'UserData', userData_main)
movieSelectorGUI('refreshDisplay', userData.mainFig,...
eventdata, guidata(userData.mainFig))
end
delete(handles.figure1);
function objects = sortById(objects)
objectIds = arrayfun(@(x) x.getId().getValue(), objects);
[~, sortindex] = sort(objectIds);
objects =objects(sortindex);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
bfCheckJavaPath.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/bioformats/bfCheckJavaPath.m
| 3,237 |
utf_8
|
a8204822a04672d090a16a10d4e3bf12
|
function [status, version] = bfCheckJavaPath(varargin)
% bfCheckJavaPath check Bio-Formats is included in the Java class path
%
% SYNOPSIS bfCheckJavaPath()
% status = bfCheckJavaPath(autoloadBioFormats)
% [status, version] = bfCheckJavaPath()
%
% Input
%
% autoloadBioFormats - Optional. A boolean specifying the action to take
% if no Bio-Formats JAR file is in the Java class path. If true, looks
% for and adds a Bio-Formats JAR file to the dynamic Java path.
% Default - true
%
% Output
%
% status - Boolean. True if a Bio-Formats JAR file is in the Java class
% path.
%
%
% version - String specifying the current version of Bio-Formats if
% a Bio-Formats JAR file is in the Java class path. Empty string else.
% OME Bio-Formats package for reading and converting biological file formats.
%
% Copyright (C) 2012 - 2014 Open Microscopy Environment:
% - Board of Regents of the University of Wisconsin-Madison
% - Glencoe Software, Inc.
% - University of Dundee
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as
% published by the Free Software Foundation, either version 2 of the
% License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License along
% with this program; if not, write to the Free Software Foundation, Inc.,
% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
% Input check
ip = inputParser;
ip.addOptional('autoloadBioFormats', true, @isscalar);
ip.parse(varargin{:});
% Check if a Bio-Formats JAR file is in the Java class path
% Can be in either static or dynamic Java class path
jPath = javaclasspath('-all');
bfJarFiles = {'bioformats_package.jar', 'loci_tools.jar'};
hasBFJar = false(numel(bfJarFiles), 1);
for i = 1: numel(bfJarFiles);
isBFJar = @(x) ~isempty(regexp(x, ['.*' bfJarFiles{i} '$'], 'once'));
hasBFJar(i) = any(cellfun(isBFJar, jPath));
end
% Check conflicting JARs are not loaded
status = any(hasBFJar);
if all(hasBFJar),
warning('bf:jarConflict', ['Multiple Bio-Formats JAR files found'...
'in the Java class path. Please check.'])
end
if ~status && ip.Results.autoloadBioFormats,
jarPath = getJarPath(bfJarFiles);
assert(~isempty(jarPath), 'bf:jarNotFound',...
'Cannot automatically locate a Bio-Formats JAR file');
% Add the Bio-Formats JAR file to dynamic Java class path
javaaddpath(jarPath);
status = true;
end
if status
% Read Bio-Formats version
version = char(loci.formats.FormatTools.VERSION);
else
version = '';
end
function path = getJarPath(files)
% Assume the jar is either in the Matlab path or under the same folder as
% this file
for i = 1 : numel(files)
path = which(files{i});
if isempty(path)
path = fullfile(fileparts(mfilename('fullpath')), files{i});
end
if ~isempty(path) && exist(path, 'file') == 2
return
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
createMinimalOMEXMLMetadata.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/bioformats/createMinimalOMEXMLMetadata.m
| 3,882 |
utf_8
|
5fca909f328b98da9546c3bbcb5eaefa
|
function metadata = createMinimalOMEXMLMetadata(I, varargin)
% CREATEMINIMALOMEXMLMETADATA Create an OME-XML metadata object from an input matrix
%
% createMinimalOMEXMLMetadata(I) creates an OME-XML metadata object from
% an input 5-D array. Minimal metadata information is stored such as the
% pixels dimensions, dimension order and type. The output object is a
% metadata object of type loci.formats.ome.OMEXMLMetadata.
%
% createMinimalOMEXMLMetadata(I, dimensionOrder) specifies the dimension
% order of the input matrix. Default valuse is XYZCT.
%
% Examples:
%
% metadata = createMinimalOMEXMLMetadata(zeros(100, 100));
% metadata = createMinimalOMEXMLMetadata(zeros(10, 10, 2), 'XYTZC');
%
% See also: BFSAVE
% OME Bio-Formats package for reading and converting biological file formats.
%
% Copyright (C) 2012 - 2014 Open Microscopy Environment:
% - Board of Regents of the University of Wisconsin-Madison
% - Glencoe Software, Inc.
% - University of Dundee
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as
% published by the Free Software Foundation, either version 2 of the
% License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License along
% with this program; if not, write to the Free Software Foundation, Inc.,
% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
% Not using the inputParser for first argument as it copies data
assert(isnumeric(I), 'First argument must be numeric');
% Input check
ip = inputParser;
ip.addOptional('dimensionOrder', 'XYZCT', @(x) ismember(x, getDimensionOrders()));
ip.parse(varargin{:});
% Create metadata
toInt = @(x) ome.xml.model.primitives.PositiveInteger(java.lang.Integer(x));
OMEXMLService = loci.formats.services.OMEXMLServiceImpl();
metadata = OMEXMLService.createOMEXMLMetadata();
metadata.createRoot();
metadata.setImageID('Image:0', 0);
metadata.setPixelsID('Pixels:0', 0);
metadata.setPixelsBinDataBigEndian(java.lang.Boolean.TRUE, 0, 0);
% Set dimension order
dimensionOrderEnumHandler = ome.xml.model.enums.handlers.DimensionOrderEnumHandler();
dimensionOrder = dimensionOrderEnumHandler.getEnumeration(ip.Results.dimensionOrder);
metadata.setPixelsDimensionOrder(dimensionOrder, 0);
% Set pixels type
pixelTypeEnumHandler = ome.xml.model.enums.handlers.PixelTypeEnumHandler();
if strcmp(class(I), 'single')
pixelsType = pixelTypeEnumHandler.getEnumeration('float');
else
pixelsType = pixelTypeEnumHandler.getEnumeration(class(I));
end
metadata.setPixelsType(pixelsType, 0);
% Read pixels size from image and set it to the metadat
sizeX = size(I, 2);
sizeY = size(I, 1);
sizeZ = size(I, find(ip.Results.dimensionOrder == 'Z'));
sizeC = size(I, find(ip.Results.dimensionOrder == 'C'));
sizeT = size(I, find(ip.Results.dimensionOrder == 'T'));
metadata.setPixelsSizeX(toInt(sizeX), 0);
metadata.setPixelsSizeY(toInt(sizeY), 0);
metadata.setPixelsSizeZ(toInt(sizeZ), 0);
metadata.setPixelsSizeC(toInt(sizeC), 0);
metadata.setPixelsSizeT(toInt(sizeT), 0);
% Set channels ID and samples per pixel
for i = 1: sizeC
metadata.setChannelID(['Channel:0:' num2str(i-1)], 0, i-1);
metadata.setChannelSamplesPerPixel(toInt(1), 0, i-1);
end
end
function dimensionOrders = getDimensionOrders()
% List all values of DimensionOrder
dimensionOrderValues = ome.xml.model.enums.DimensionOrder.values();
dimensionOrders = cell(numel(dimensionOrderValues), 1);
for i = 1 :numel(dimensionOrderValues),
dimensionOrders{i} = char(dimensionOrderValues(i).toString());
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
bfsave.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/u-track-2.1.3/software/bioformats/bfsave.m
| 4,860 |
utf_8
|
4a3e7594e4db8454876906cad376fb5d
|
function bfsave(I, outputPath, varargin)
% BFSAVE Save a 5D matrix into an OME-TIFF using Bio-Formats library
%
% bfsave(I, outputPath) writes the input 5D matrix into a new file
% specified by outputPath.
%
% bfsave(I, outputPath, dimensionOrder) specifies the dimension order of
% the input matrix. Default valuse is XYZCT.
%
% bfsave(I, outputPath, 'Compression', compression) specifies the
% compression to use when writing the OME-TIFF file.
%
% bfsave(I, outputPath, 'BigTiff', true) allows to save the file using
% 64-bit offsets
%
% bfsave(I, outputPath, 'metadata', metadata) allows to use a custom
% OME-XML metadata object when saving the file instead of creating a
% minimal OME-XML metadata object from the input 5D matrix.
%
% For more information, see https://www.openmicroscopy.org/site/support/bio-formats5/developers/matlab-dev.html
%
% Examples:
%
% bfsave(zeros(100, 100), outputPath)
% bfsave(zeros(100, 100, 2, 3, 4), outputPath)
% bfsave(zeros(100, 100, 20), outputPath, 'dimensionOrder', 'XYTZC')
% bfsave(zeros(100, 100), outputPath, 'Compression', 'LZW')
% bfsave(zeros(100, 100), outputPath, 'BigTiff', true)
% bfsave(zeros(100, 100), outputPath, 'metadata', metadata)
%
% See also: BFGETREADER, CREATEMINIMALOMEXMLMETADATA
% OME Bio-Formats package for reading and converting biological file formats.
%
% Copyright (C) 2012 - 2014 Open Microscopy Environment:
% - Board of Regents of the University of Wisconsin-Madison
% - Glencoe Software, Inc.
% - University of Dundee
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as
% published by the Free Software Foundation, either version 2 of the
% License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License along
% with this program; if not, write to the Free Software Foundation, Inc.,
% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
% verify that enough memory is allocated
bfCheckJavaMemory();
% Check for required jars in the Java path
bfCheckJavaPath();
% Not using the inputParser for first argument as it copies data
assert(isnumeric(I), 'First argument must be numeric');
% Input check
ip = inputParser;
ip.addRequired('outputPath', @ischar);
ip.addOptional('dimensionOrder', 'XYZCT', @(x) ismember(x, getDimensionOrders()));
ip.addParamValue('metadata', [], @(x) isa(x, 'loci.formats.ome.OMEXMLMetadata'));
ip.addParamValue('Compression', '', @(x) ismember(x, getCompressionTypes()));
ip.addParamValue('BigTiff', false , @islogical);
ip.parse(outputPath, varargin{:});
% Create metadata
if isempty(ip.Results.metadata)
metadata = createMinimalOMEXMLMetadata(I, ip.Results.dimensionOrder);
else
metadata = ip.Results.metadata;
end
% Create ImageWriter
writer = loci.formats.ImageWriter();
writer.setWriteSequentially(true);
writer.setMetadataRetrieve(metadata);
if ~isempty(ip.Results.Compression)
writer.setCompression(ip.Results.Compression)
end
if ip.Results.BigTiff
writer.getWriter(outputPath).setBigTiff(ip.Results.BigTiff)
end
writer.setId(outputPath);
% Load conversion tools for saving planes
switch class(I)
case {'int8', 'uint8'}
getBytes = @(x) x(:);
case {'uint16','int16'}
getBytes = @(x) loci.common.DataTools.shortsToBytes(x(:), 0);
case {'uint32','int32'}
getBytes = @(x) loci.common.DataTools.intsToBytes(x(:), 0);
case {'single'}
getBytes = @(x) loci.common.DataTools.floatsToBytes(x(:), 0);
case 'double'
getBytes = @(x) loci.common.DataTools.doublesToBytes(x(:), 0);
end
% Save planes to the writer
nPlanes = metadata.getPixelsSizeZ(0).getValue() *...
metadata.getPixelsSizeC(0).getValue() *...
metadata.getPixelsSizeT(0).getValue();
for index = 1 : nPlanes
[i, j, k] = ind2sub([size(I, 3) size(I, 4) size(I, 5)],index);
plane = I(:, :, i, j, k)';
writer.saveBytes(index-1, getBytes(plane));
end
writer.close();
end
function dimensionOrders = getDimensionOrders()
% List all values of DimensionOrder
dimensionOrderValues = ome.xml.model.enums.DimensionOrder.values();
dimensionOrders = cell(numel(dimensionOrderValues), 1);
for i = 1 :numel(dimensionOrderValues),
dimensionOrders{i} = char(dimensionOrderValues(i).toString());
end
end
function compressionTypes = getCompressionTypes()
% List all values of Compression
writer = loci.formats.ImageWriter();
compressionTypes = arrayfun(@char, writer.getCompressionTypes(),...
'UniformOutput', false);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
strsetmatch.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/strsetmatch.m
| 928 |
utf_8
|
73f5541ad337bbbc7179cf71004b7062
|
% Indicator of which elements of a universal set are in a particular set.
%
% Input arguments:
% strset:
% the particular set as a cell array of strings
% struniversal:
% the universal set as a cell array of strings, all elements in the
% particular set are expected to be in the universal set
%
% Output arguments:
% ind:
% a logical vector of which elements of the universal set are found in
% the particular set
% Copyright 2010 Levente Hunyadi
function ind = strsetmatch(strset, struniversal)
assert(iscellstr(strset), 'strsetmatch:ArgumentTypeMismatch', ...
'The particular set is expected to be a cell array of strings.');
assert(iscellstr(struniversal), 'strsetmatch:ArgumentTypeMismatch', ...
'The particular set is expected to be a cell array of strings.');
ind = false(size(struniversal));
for k = 1 : numel(struniversal)
ind(k) = ~isempty(strmatch(struniversal{k}, strset, 'exact'));
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
helptext.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/helptext.m
| 1,593 |
utf_8
|
bd49205fc50aeae5a909c8b58a47be6d
|
% Help text associated with a function, class, property or method.
% Spaces are removed as necessary.
%
% See also: helpdialog
% Copyright 2008-2010 Levente Hunyadi
function text = helptext(obj)
if ischar(obj)
text = gethelptext(obj);
else
text = gethelptext(class(obj));
end
text = texttrim(text);
function text = gethelptext(key)
persistent dict;
if isempty(dict) && usejava('jvm')
dict = java.util.Properties();
end
if ~isempty(dict)
text = char(dict.getProperty(key)); % look up key in cache
if ~isempty(text) % help text found in cache
return;
end
text = help(key);
if ~isempty(text) % help text returned by help call, save it into cache
dict.setProperty(key, text);
end
else
text = help(key);
end
function lines = texttrim(text)
% Trims leading and trailing whitespace characters from lines of text.
% The number of leading whitespace characters to trim is determined by
% inspecting all lines of text.
loc = strfind(text, sprintf('\n'));
n = numel(loc);
loc = [ 0 loc ];
lines = cell(n,1);
if ~isempty(loc)
for k = 1 : n
lines{k} = text(loc(k)+1 : loc(k+1));
end
end
lines = deblank(lines);
% determine maximum leading whitespace count
f = ~cellfun(@isempty, lines); % filter for non-empty lines
firstchar = cellfun(@(line) find(~isspace(line), 1), lines(f)); % index of first non-whitespace character
if isempty(firstchar)
indent = 1;
else
indent = min(firstchar);
end
% trim leading whitespace
lines(f) = cellfun(@(line) line(min(indent,numel(line)):end), lines(f), 'UniformOutput', false);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
javaclass.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/javaclass.m
| 3,635 |
utf_8
|
7165e1fd27bd4f5898132023dc04662b
|
% Return java.lang.Class instance for MatLab type.
%
% Input arguments:
% mtype:
% the MatLab name of the type for which to return the java.lang.Class
% instance
% ndims:
% the number of dimensions of the MatLab data type
%
% See also: class
% Copyright 2009-2010 Levente Hunyadi
function jclass = javaclass(mtype, ndims)
validateattributes(mtype, {'char'}, {'nonempty','row'});
if nargin < 2
ndims = 0;
else
validateattributes(ndims, {'numeric'}, {'nonnegative','integer','scalar'});
end
if ndims == 1 && strcmp(mtype, 'char'); % a character vector converts into a string
jclassname = 'java.lang.String';
elseif ndims > 0
jclassname = javaarrayclass(mtype, ndims);
else
% The static property .class applied to a Java type returns a string in
% MatLab rather than an instance of java.lang.Class. For this reason,
% use a string and java.lang.Class.forName to instantiate a
% java.lang.Class object; the syntax java.lang.Boolean.class will not
% do so.
switch mtype
case 'logical' % logical vaule (true or false)
jclassname = 'java.lang.Boolean';
case 'char' % a singe character
jclassname = 'java.lang.Character';
case {'int8','uint8'} % 8-bit signed and unsigned integer
jclassname = 'java.lang.Byte';
case {'int16','uint16'} % 16-bit signed and unsigned integer
jclassname = 'java.lang.Short';
case {'int32','uint32'} % 32-bit signed and unsigned integer
jclassname = 'java.lang.Integer';
case {'int64','uint64'} % 64-bit signed and unsigned integer
jclassname = 'java.lang.Long';
case 'single' % single-precision floating-point number
jclassname = 'java.lang.Float';
case 'double' % double-precision floating-point number
jclassname = 'java.lang.Double';
case 'cellstr' % a single cell or a character array
jclassname = 'java.lang.String';
otherwise
error('java:javaclass:InvalidArgumentValue', ...
'MatLab type "%s" is not recognized or supported in Java.', mtype);
end
end
% Note: When querying a java.lang.Class object by name with the method
% jclass = java.lang.Class.forName(jclassname);
% MatLab generates an error. For the Class.forName method to work, MatLab
% requires class loader to be specified explicitly.
jclass = java.lang.Class.forName(jclassname, true, java.lang.Thread.currentThread().getContextClassLoader());
function jclassname = javaarrayclass(mtype, ndims)
% Returns the type qualifier for a multidimensional Java array.
switch mtype
case 'logical' % logical array of true and false values
jclassid = 'Z';
case 'char' % character array
jclassid = 'C';
case {'int8','uint8'} % 8-bit signed and unsigned integer array
jclassid = 'B';
case {'int16','uint16'} % 16-bit signed and unsigned integer array
jclassid = 'S';
case {'int32','uint32'} % 32-bit signed and unsigned integer array
jclassid = 'I';
case {'int64','uint64'} % 64-bit signed and unsigned integer array
jclassid = 'J';
case 'single' % single-precision floating-point number array
jclassid = 'F';
case 'double' % double-precision floating-point number array
jclassid = 'D';
case 'cellstr' % cell array of strings
jclassid = 'Ljava.lang.String;';
otherwise
error('java:javaclass:InvalidArgumentValue', ...
'MatLab type "%s" is not recognized or supported in Java.', mtype);
end
jclassname = [repmat('[',1,ndims), jclassid];
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
helpdialog.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/helpdialog.m
| 3,397 |
utf_8
|
f16f23c1b608a247bc5298f5ebc6d321
|
% Displays a dialog to give help information on an object.
%
% Examples:
% helpdialog char
% gives information of character arrays
% helpdialog plot
% gives help on the plot command
% helpdialog(obj)
% gives help on the MatLab object obj
%
% See also: helptext, msgbox
% Copyright 2008-2010 Levente Hunyadi
function helpdialog(obj)
if nargin < 1
obj = 'helpdialog';
end
if ischar(obj)
key = obj;
else
key = class(obj);
end
title = [key ' - Quick help'];
text = helptext(key);
if isempty(text)
text = {'No help available.'};
end
if 0 % standard MatLab message dialog box
createmode = struct( ...
'WindowStyle', 'replace', ...
'Interpreter', 'none');
msgbox(text, title, 'help', createmode);
else
fig = figure( ...
'MenuBar', 'none', ...
'Name', title, ...
'NumberTitle', 'off', ...
'Position', [0 0 480 160], ...
'Toolbar', 'none', ...
'Visible', 'off', ...
'ResizeFcn', @helpdialog_resize);
% information icon
icons = load('dialogicons.mat');
icons.helpIconMap(256,:) = get(fig, 'Color');
iconaxes = axes( ...
'Parent', fig, ...
'Units', 'pixels', ...
'Tag', 'IconAxes');
try
iconimg = image('CData', icons.helpIconData, 'Parent', iconaxes);
set(fig, 'Colormap', icons.helpIconMap);
catch me
delete(fig);
rethrow(me)
end
if ~isempty(get(iconimg,'XData')) && ~isempty(get(iconimg,'YData'))
set(iconaxes, ...
'XLim', get(iconimg,'XData')+[-0.5 0.5], ...
'YLim', get(iconimg,'YData')+[-0.5 0.5]);
end
set(iconaxes, ...
'Visible', 'off', ...
'YDir', 'reverse');
% help text
rgb = get(fig, 'Color');
text = cellfun(@(line) helpdialog_html(line), text, 'UniformOutput', false);
html = ['<html>' strjoin(sprintf('\n'), text) '</html>'];
jtext = javax.swing.JLabel(html);
jcolor = java.awt.Color(rgb(1), rgb(2), rgb(3));
jtext.setBackground(jcolor);
jtext.setVerticalAlignment(1);
jscrollpane = javax.swing.JScrollPane(jtext, javax.swing.JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jscrollpane.getViewport().setBackground(jcolor);
jscrollpane.setBorder(javax.swing.border.EmptyBorder(0,0,0,0));
[jcontrol,jcontainer] = javacomponent(jscrollpane, [0 0 100 100]);
set(jcontainer, 'Tag', 'HelpText');
movegui(fig, 'center'); % center figure on screen
set(fig, 'Visible', 'on');
end
function helpdialog_resize(fig, event) %#ok<INUSD>
position = getpixelposition(fig);
width = position(3);
height = position(4);
iconaxes = findobj(fig, 'Tag', 'IconAxes');
helptext = findobj(fig, 'Tag', 'HelpText');
bottom = 7*height/12;
set(iconaxes, 'Position', [12 bottom 51 51]);
set(helptext, 'Position', [75 12 width-75-12 height-24]);
function html = helpdialog_html(line)
preline = deblank(line); % trailing spaces removed
line = strtrim(preline); % leading spaces removed
leadingspace = repmat(' ', 1, numel(preline)-numel(line)); % add leading spaces as non-breaking space
ix = strfind(line, 'See also');
if ~isempty(ix)
ix = ix(1) + numel('See also');
line = [ line(1:ix-1) regexprep(line(ix:end), '(\w[\d\w]+)', '<a href="matlab:helpdialog $1">$1</a>') ];
end
html = ['<p>' leadingspace line '</p>'];
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
getdependentproperties.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/getdependentproperties.m
| 907 |
utf_8
|
5f87bb7115d9bcacd8556d89a4492c44
|
% Publicly accessible dependent properties of an object.
%
% See also: meta.property
% Copyright 2010 Levente Hunyadi
function dependent = getdependentproperties(obj)
dependent = {};
if isstruct(obj) % structures have no dependent properties
return;
end
try
clazz = metaclass(obj);
catch %#ok<CTCH>
return; % old-style class (i.e. not defined with the classdef keyword) have no dependent properties
end
k = 0; % number of dependent properties found
n = numel(clazz.Properties); % maximum number of properties
dependent = cell(n, 1);
for i = 1 : n
property = clazz.Properties{i};
if property.Abstract || property.Hidden || ~strcmp(property.GetAccess, 'public') || ~property.Dependent
continue; % skip abstract, hidden, inaccessible and independent properties
end
k = k + 1;
dependent{k} = property.Name;
end
dependent(k+1:end) = []; % drop unused cells
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
strjoin.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/strjoin.m
| 938 |
utf_8
|
63425068d4fd2fd0543aa9e5b46eca84
|
% Concatenates a cell array of strings.
%
% Input arguments:
% adjoiner:
% string separating each neighboring element
% strings:
% a cell array of strings to join
%
% See also: strsplit, cell2mat
% Copyright 2008-2009 Levente Hunyadi
function string = strjoin(adjoiner, strings)
validateattributes(adjoiner, {'char'}, {'vector'});
validateattributes(strings, {'cell'}, {'vector'});
assert(iscellstr(strings), ...
'strjoin:ArgumentTypeMismatch', ...
'The elements to join should be stored in a cell vector of strings (character arrays).');
if isempty(strings)
string = '';
return;
end
% arrange substrings into cell array of strings
concat = cell(1, 2 * numel(strings) - 1); % must be row vector
j = 1;
concat{j} = strings{1};
for i = 2 : length(strings)
j = j + 1;
concat{j} = adjoiner;
j = j + 1;
concat{j} = strings{i};
end
% concatenate substrings preserving spaces
string = cell2mat(concat);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
strsplit.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/strsplit.m
| 553 |
utf_8
|
81fa1c544a57b6a796400f39aedf3d44
|
% Splits a string into a cell array of strings.
%
% Input arguments:
% string:
% a string to split into a cell array
% adjoiner:
% string separating each neighboring element
%
% See also: strjoin
% Copyright 2008-2009 Levente Hunyadi
function strings = strsplit(string, adjoiner)
if nargin < 2
adjoiner = sprintf('\n');
end
ix = strfind(string, adjoiner);
strings = cell(numel(ix)+1, 1);
ix = [0 ix numel(string)+1]; % place implicit adjoiners before and after string
for k = 2 : numel(ix)
strings{k-1} = string(ix(k-1)+1:ix(k)-1);
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
nestedfetch.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/nestedfetch.m
| 1,000 |
utf_8
|
1f3b58597c8ee6879bc2650defb0799d
|
% Fetches the value of the named property of an object or structure.
% This function can deal with nested properties.
%
% Input arguments:
% obj:
% the handle or value object the value should be assigned to
% name:
% a property name with dot (.) separating property names at
% different hierarchy levels
% value:
% the value to assign to the property at the deepest hierarchy
% level
%
% Example:
% obj = struct('surface', struct('nested', 23));
% value = nestedfetch(obj, 'surface.nested');
% disp(value); % prints 23
%
% See also: nestedassign
% Copyright 2010 Levente Hunyadi
function value = nestedfetch(obj, name)
if ~iscell(name)
nameparts = strsplit(name, '.');
else
nameparts = name;
end
value = nestedfetch_recurse(obj, nameparts);
end
function value = nestedfetch_recurse(obj, name)
if numel(name) > 1
value = nestedfetch_recurse(obj.(name{1}), name(2:end));
else
value = obj.(name{1});
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
findobjuser.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/findobjuser.m
| 1,186 |
utf_8
|
7bd275f50be4d4907288de44fab8fade
|
% Find handle graphics object with user data check.
% Retrieves those handle graphics objects (HGOs) that have the specified
% Tag property and whose UserData property satisfies the given predicate.
%
% Input arguments:
% fcn:
% a predicate (a function that returns a logical value) to test against
% the HGO's UserData property
% tag (optional):
% a string tag to restrict the set of controls to investigate
%
% See also: findobj
% Copyright 2010 Levente Hunyadi
function h = findobjuser(fcn, tag)
validateattributes(fcn, {'function_handle'}, {'scalar'});
if nargin < 2 || isempty(tag)
tag = '';
else
validateattributes(tag, {'char'}, {'row'});
end
%hh = get(0, 'ShowHiddenHandles');
%cleanup = onCleanup(@() set(0, 'ShowHiddenHandles', hh)); % restore visibility on exit or exception
if ~isempty(tag)
% look among all handles (incl. hidden handles) to help findobj locate the object it seeks
h = findobj(findall(0), '-property', 'UserData', '-and', 'Tag', tag); % more results if multiple matching HGOs exist
else
h = findobj(findall(0), '-property', 'UserData');
end
h = unique(h);
f = arrayfun(@(handle) fcn(get(handle, 'UserData')), h);
h = h(f);
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
javaStringArray.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/javaStringArray.m
| 628 |
utf_8
|
fe0389e3b0d1933d49c1a78c416a279c
|
% Converts a MatLab cell array of strings into a java.lang.String array.
%
% Input arguments:
% str:
% a cell array of strings (i.e. a cell array of char row vectors)
%
% Output arguments:
% arr:
% a java.lang.String array instance (i.e. java.lang.String[])
%
% See also: javaArray
% Copyright 2009-2010 Levente Hunyadi
function arr = javaStringArray(str)
assert(iscellstr(str) && isvector(str), ...
'java:StringArray:InvalidArgumentType', ...
'Cell row or column vector of strings expected.');
arr = javaArray('java.lang.String', length(str));
for k = 1 : numel(str);
arr(k) = java.lang.String(str{k});
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
var2str.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/var2str.m
| 441 |
utf_8
|
5588acb0d18dcfac8183caf10a3b5675
|
% Textual representation of any MatLab value.
% Copyright 2009 Levente Hunyadi
function s = var2str(value)
if islogical(value) || isnumeric(value)
s = num2str(value);
elseif ischar(value) && isvector(value)
s = reshape(value, 1, numel(value));
elseif isjava(value)
s = char(value); % calls java.lang.Object.toString()
else
try
s = char(value);
catch %#ok<CTCH>
s = '[no preview available]';
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
getclassfield.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/getclassfield.m
| 376 |
utf_8
|
e3b87866af8da4dd40243e750a7e53f6
|
% Field value of each object in an array or cell array.
%
% See also: getfield
% Copyright 2010 Levente Hunyadi
function values = getclassfield(objects, field)
values = cell(size(objects));
if iscell(objects)
for k = 1 : numel(values)
values{k} = objects{k}.(field);
end
else
for k = 1 : numel(values)
values{k} = objects(k).(field);
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
arrayfilter.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/arrayfilter.m
| 488 |
utf_8
|
a2649b876169e3d850372917e57a8b68
|
% Filter elements of array that meet a condition.
% Copyright 2010 Levente Hunyadi
function array = arrayfilter(fun, array)
validateattributes(fun, {'function_handle'}, {'scalar'});
if isobject(array)
filter = false(size(array));
for k = 1 : numel(filter)
filter(k) = fun(array(k));
end
else
filter = arrayfun(fun, array); % logical indicator array of elements that satisfy condition
end
array = array(filter); % array of elements that meet condition
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
constructor.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/constructor.m
| 2,078 |
utf_8
|
c67e647ec8055710896666c9e83b45e0
|
% Sets public properties of a MatLab object using a name-value list.
% Properties are traversed in the order they occur in the class definition.
% Copyright 2008-2009 Levente Hunyadi
function obj = constructor(obj, varargin)
assert(isobject(obj), ...
'Function operates on MatLab new-style objects only.');
if nargin <= 1
return;
end
if isa(obj, 'hgsetget')
set(obj, varargin{:});
return;
end
assert(is_name_value_list(varargin), ...
'constructor:ArgumentTypeMismatch', ...
'A list of property name--value pairs is expected.');
% instantiate input parser object
parser = inputParser;
% query class properties using meta-class facility
metaobj = metaclass(obj);
properties = metaobj.Properties;
for i = 1 : numel(properties)
property = properties{i};
if is_public_property(property)
parser.addParamValue(property.Name, obj.(property.Name));
end
end
% set property values according to name-value list
parser.parse(varargin{:});
for i = 1 : numel(properties)
property = properties{i};
if is_public_property(property) && ~is_string_in_vector(property.Name, parser.UsingDefaults) % do not set defaults
obj.(property.Name) = parser.Results.(property.Name);
end
end
function tf = is_name_value_list(list)
% True if the specified list is a name-value list.
%
% Input arguments:
% list:
% a name-value list as a cell array.
validateattributes(list, {'cell'}, {'vector'});
n = numel(list);
if mod(n, 2) ~= 0
% a name-value list has an even number of elements
tf = false;
else
for i = 1 : 2 : n
if ~ischar(list{i})
% each odd element in a name-value list must be a char array
tf = false;
return;
end
end
tf = true;
end
function tf = is_string_in_vector(str, vector)
tf = any(strcmp(str, vector));
function tf = is_public_property(property)
% True if the property designates a public, accessible property.
tf = ~property.Abstract && ~property.Hidden && strcmp(property.GetAccess, 'public') && strcmp(property.SetAccess, 'public');
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
nestedassign.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/nestedassign.m
| 1,457 |
utf_8
|
12d661bb4df3c64a0707a06f7e3e6afc
|
% Assigns the given value to the named property of an object or structure.
% This function can deal with nested properties.
%
% Input arguments:
% obj:
% the structure, handle or value object the value should be assigned to
% name:
% a property name with dot (.) separating property names at
% different hierarchy levels
% value:
% the value to assign to the property at the deepest hierarchy
% level
%
% Output arguments:
% obj:
% the updated object or structure, optional for handle objects
%
% Example:
% obj = struct('surface', struct('nested', 10));
% obj = nestedassign(obj, 'surface.nested', 23);
% disp(obj.surface.nested); % prints 23
%
% See also: nestedfetch
% Copyright 2010 Levente Hunyadi
function obj = nestedassign(obj, name, value)
if ~iscell(name)
nameparts = strsplit(name, '.');
else
nameparts = name;
end
obj = nestedassign_recurse(obj, nameparts, value);
end
function obj = nestedassign_recurse(obj, name, value)
% Assigns the given value to the named property of an object.
%
% Input arguments:
% obj:
% the handle or value object the value should be assigned to
% name:
% a cell array of the composite property name
% value:
% the value to assign to the property at the deepest hierarchy
% level
if numel(name) > 1
obj.(name{1}) = nestedassign_recurse(obj.(name{1}), name(2:end), value);
else
obj.(name{1}) = value;
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
javaArrayList.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/PropertyGrid/javaArrayList.m
| 647 |
utf_8
|
f2dfbe065497f86c285230bc35bf381c
|
% Converts a MatLab array into a java.util.ArrayList.
%
% Input arguments:
% array:
% a MatLab row or column vector (with elements of any type)
%
% Output arguments:
% list:
% a java.util.ArrayList instance
%
% See also: javaArray
% Copyright 2010 Levente Hunyadi
function list = javaArrayList(array)
assert(isvector(array), 'javaArrayList:DimensionMismatch', ...
'Row or column vector expected.');
list = java.util.ArrayList;
if iscell(array) % convert cell array into ArrayList
for k = 1 : numel(array)
list.add(array{k});
end
else % convert (numeric) array into ArrayList
for k = 1 : numel(array)
list.add(array(k));
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
tracking.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/GUI Layout Toolbox 2.3.1/layout/+uix/tracking.m
| 5,760 |
utf_8
|
0a5cc1ec12e0f3d0ff2fe76e2c686f9a
|
function varargout = tracking( varargin )
%tracking Track anonymized usage data
%
% tracking(p,v,id) tracks usage to the property p for the product version
% v and identifier id. No personally identifiable information is tracked.
%
% r = tracking(...) returns the server response r, for debugging purposes.
%
% tracking('on') turns tracking on. tracking('off') turns tracking off.
% tracking('query') returns the tracking state.
% tracking('spoof') sets the tracking settings -- domain, language,
% client, MATLAB version, operating system version -- to spoof values.
% tracking('reset') sets the tracking settings to normal values.
%
% [t,s] = tracking('query') returns the tracking state t and settings s.
% Copyright 2016 The MathWorks, Inc.
% $Revision: 1435 $ $Date: 2016-11-17 17:50:34 +0000 (Thu, 17 Nov 2016) $
persistent STATE USERNAME DOMAIN LANGUAGE CLIENT MATLAB OS
if isempty( STATE )
STATE = getpref( 'Tracking', 'State', 'on' );
if strcmp( STATE, 'snooze' ) % deprecated
setpref( 'Tracking', 'State', 'on' )
STATE = 'on';
end
if ispref( 'Tracking', 'Date' ) % deprecated
rmpref( 'Tracking', 'Date' )
end
USERNAME = getenv( 'USERNAME' );
reset()
end % initialize
switch nargin
case 1
switch varargin{1}
case {'on','off'}
STATE = varargin{1};
setpref( 'Tracking', 'State', varargin{1} ) % persist
case 'spoof'
spoof()
case 'reset'
reset()
case 'query'
varargout{1} = STATE;
varargout{2} = query();
otherwise
error( 'tracking:InvalidArgument', ...
'Valid options are ''on'', ''off'' and ''query''.' )
end
case 3
switch nargout
case 0
if strcmp( STATE, 'off' ), return, end
uri = 'https://www.google-analytics.com/collect';
track( uri, varargin{:} );
case 1
uri = 'https://www.google-analytics.com/debug/collect';
varargout{1} = track( uri, varargin{:} );
otherwise
nargoutchk( 0, 1 )
end
otherwise
narginchk( 3, 3 )
end % switch
function reset()
%reset Set normal settings
DOMAIN = lower( getenv( 'USERDOMAIN' ) );
LANGUAGE = char( java.util.Locale.getDefault() );
CLIENT = getpref( 'Tracking', 'Client', uuid() );
MATLAB = matlab();
OS = os();
end % reset
function spoof()
%spoof Set spoof settings
DOMAIN = randomDomain();
LANGUAGE = randomLanguage();
CLIENT = randomClient();
MATLAB = randomMatlab();
OS = randomOs();
end % spoof
function s = query()
%query Return settings
s.Username = USERNAME;
s.Domain = DOMAIN;
s.Language = LANGUAGE;
s.Client = CLIENT;
s.Matlab = MATLAB;
s.Os = OS;
end % query
function varargout = track( uri, p, v, s )
%track Do tracking
a = sprintf( '%s/%s (%s)', MATLAB, v, OS );
if isdeployed()
ds = 'deployed';
elseif strcmp( DOMAIN, 'mathworks' )
ds = DOMAIN;
else
ds = 'unknown';
end
pv = {'v', '1', 'tid', p, 'ua', escape( a ), 'ul', LANGUAGE, ...
'cid', CLIENT, 'ht', 'pageview', ...
'dp', sprintf( '/%s', s ), 'ds', ds};
[varargout{1:nargout}] = urlread( uri, 'Post', pv );
end % track
end % tracking
function s = randomDomain()
%randomDomain Random domain string
switch randi( 4 )
case 1
s = 'mathworks';
otherwise
s = hash( uuid() );
end
end % randomDomain
function s = randomLanguage()
%randomLanguage Random language string
lo = java.util.Locale.getAvailableLocales();
s = char( lo(randi( numel( lo ) )) );
end % randomLanguage
function s = randomClient()
%randomClient Random client identifier
s = uuid();
end % randomClient
function s = matlab()
%matlab MATLAB version string
v = ver( 'MATLAB' );
s = v.Release;
s(s=='('|s==')') = [];
end % matlab
function s = randomMatlab()
%randomMatlab Random MATLAB version string
releases = {'R2014b' 'R2015a' 'R2015b' 'R2016a' 'R2016b'};
s = releases{randi( numel( releases ) )};
end % randomMatlab
function s = os()
%os Operating system string
if ispc()
s = sprintf( 'Windows NT %s', ...
char( java.lang.System.getProperty( 'os.version' ) ) );
elseif isunix()
s = 'Linux x86_64';
elseif ismac()
s = sprintf( 'Macintosh; Intel OS X %s', ...
strrep( char( java.lang.System.getProperty( 'os.version' ) ), ' ', '_' ) );
else
s = 'unknown';
end
end % os
function s = randomOs()
%randomOs Random operating system string
switch randi( 3 )
case 1
versions = [5.1 5.2 6 6.1 6.2 6.3 10];
s = sprintf( 'Windows NT %.1f', ...
versions(randi( numel( versions ) )) );
case 2
s = 'Linux x86_64';
case 3
s = sprintf( 'Macintosh; Intel OS X 10_%d', ...
randi( [10 12] ) );
end
end % randomOs
function s = escape( s )
%escape Escape string
s = char( java.net.URLEncoder.encode( s, 'UTF-8' ) );
end % escape
function h = hash( s )
%hash Hash string
%
% See also: rptgen.hash
persistent MD5
if isempty( MD5 )
MD5 = java.security.MessageDigest.getInstance( 'MD5' );
end
MD5.update( uint8( s(:) ) );
h = typecast( MD5.digest, 'uint8' );
h = dec2hex( h )';
h = lower( h(:) )';
end % hash
function s = uuid()
%uuid Unique identifier
s = char( java.util.UUID.randomUUID() );
end % uuid
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
Text.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/GUI Layout Toolbox 2.3.1/layout/+uix/Text.m
| 14,906 |
utf_8
|
c37ac7f47e68e43733564dd25304a3dc
|
classdef Text < matlab.mixin.SetGet
%uix.Text Text control
%
% t = uix.Text(p1,v1,p2,v2,...) constructs a text control and sets
% parameter p1 to value v1, etc.
%
% A text control adds functionality to a uicontrol of Style text:
% * Set VerticalAlignment to 'top', 'middle' or 'bottom'
% * Fire a Callback when the user clicks on the text
%
% See also: uicontrol
% Copyright 2009-2015 The MathWorks, Inc.
% $Revision: 1435 $ $Date: 2016-11-17 17:50:34 +0000 (Thu, 17 Nov 2016) $
properties( Dependent )
BackgroundColor
end
properties( Dependent, SetAccess = private )
BeingDeleted
end
properties( Dependent )
Callback
DeleteFcn
Enable
end
properties( Dependent, SetAccess = private )
Extent
end
properties( Dependent )
FontAngle
FontName
FontSize
FontUnits
FontWeight
ForegroundColor
HandleVisibility
HorizontalAlignment
Parent
Position
String
Tag
TooltipString
end
properties( Dependent, SetAccess = private )
Type
end
properties( Dependent )
UIContextMenu
Units
UserData
VerticalAlignment
Visible
end
properties( Access = private )
Container % container
Checkbox % checkbox, used for label
Screen % text, used for covering checkbox
VerticalAlignment_ = 'top' % backing for VerticalAlignment
Dirty = false % flag
FigureObserver % observer
FigureListener % listener
end
properties( Constant, Access = private )
Margin = checkBoxLabelOffset() % checkbox size
end
methods
function obj = Text( varargin )
%uix.Text Text control
%
% t = uix.Text(p1,v1,p2,v2,...) constructs a text control and
% sets parameter p1 to value v1, etc.
% Create graphics
container = uicontainer( 'Parent', [], ...
'Units', get( 0, 'DefaultUicontrolUnits' ), ...
'Position', get( 0, 'DefaultUicontrolPosition' ), ...
'SizeChangedFcn', @obj.onResized );
checkbox = uicontrol( 'Parent', container, ...
'HandleVisibility', 'off', ...
'Style', 'checkbox', 'Units', 'pixels', ...
'HorizontalAlignment', 'center', ...
'Enable', 'inactive' );
screen = uicontrol( 'Parent', container, ...
'HandleVisibility', 'off', ...
'Style', 'text', 'Units', 'pixels' );
% Create observers and listeners
figureObserver = uix.FigureObserver( container );
figureListener = event.listener( figureObserver, ...
'FigureChanged', @obj.onFigureChanged );
% Store properties
obj.Container = container;
obj.Checkbox = checkbox;
obj.Screen = screen;
obj.FigureObserver = figureObserver;
obj.FigureListener = figureListener;
% Set properties
if nargin > 0
try
assert( rem( nargin, 2 ) == 0, 'uix:InvalidArgument', ...
'Parameters and values must be provided in pairs.' )
set( obj, varargin{:} )
catch e
delete( obj )
e.throwAsCaller()
end
end
end % constructor
function delete( obj )
%delete Destructor
delete( obj.Container )
end % destructor
end % structors
methods
function value = get.BackgroundColor( obj )
value = obj.Checkbox.BackgroundColor;
end % get.BackgroundColor
function set.BackgroundColor( obj, value )
obj.Container.BackgroundColor = value;
obj.Checkbox.BackgroundColor = value;
obj.Screen.BackgroundColor = value;
end % set.BackgroundColor
function value = get.BeingDeleted( obj )
value = obj.Checkbox.BeingDeleted;
end % get.BeingDeleted
function value = get.Callback( obj )
value = obj.Checkbox.Callback;
end % get.Callback
function set.Callback( obj, value )
obj.Checkbox.Callback = value;
end % set.Callback
function value = get.DeleteFcn( obj )
value = obj.Checkbox.DeleteFcn;
end % get.DeleteFcn
function set.DeleteFcn( obj, value )
obj.Checkbox.DeleteFcn = value;
end % set.DeleteFcn
function value = get.Enable( obj )
value = obj.Checkbox.Enable;
end % get.Enable
function set.Enable( obj, value )
obj.Checkbox.Enable = value;
end % set.Enable
function value = get.Extent( obj )
value = obj.Checkbox.Extent;
end % get.Extent
function value = get.FontAngle( obj )
value = obj.Checkbox.FontAngle;
end % get.FontAngle
function set.FontAngle( obj, value )
% Set
obj.Checkbox.FontAngle = value;
% Mark as dirty
obj.setDirty()
end % set.FontAngle
function value = get.FontName( obj )
value = obj.Checkbox.FontName;
end % get.FontName
function set.FontName( obj, value )
% Set
obj.Checkbox.FontName = value;
% Mark as dirty
obj.setDirty()
end % set.FontName
function value = get.FontSize( obj )
value = obj.Checkbox.FontSize;
end % get.FontSize
function set.FontSize( obj, value )
% Set
obj.Checkbox.FontSize = value;
% Mark as dirty
obj.setDirty()
end % set.FontSize
function value = get.FontUnits( obj )
value = obj.Checkbox.FontUnits;
end % get.FontUnits
function set.FontUnits( obj, value )
obj.Checkbox.FontUnits = value;
end % set.FontUnits
function value = get.FontWeight( obj )
value = obj.Checkbox.FontWeight;
end % get.FontWeight
function set.FontWeight( obj, value )
% Set
obj.Checkbox.FontWeight = value;
% Mark as dirty
obj.setDirty()
end % set.FontWeight
function value = get.ForegroundColor( obj )
value = obj.Checkbox.ForegroundColor;
end % get.ForegroundColor
function set.ForegroundColor( obj, value )
obj.Checkbox.ForegroundColor = value;
end % set.ForegroundColor
function value = get.HandleVisibility( obj )
value = obj.Container.HandleVisibility;
end % get.HandleVisibility
function set.HandleVisibility( obj, value )
obj.Container.HandleVisibility = value;
end % set.HandleVisibility
function value = get.HorizontalAlignment( obj )
value = obj.Checkbox.HorizontalAlignment;
end % get.HorizontalAlignment
function set.HorizontalAlignment( obj, value )
% Set
obj.Checkbox.HorizontalAlignment = value;
% Mark as dirty
obj.setDirty()
end % set.HorizontalAlignment
function value = get.Parent( obj )
value = obj.Container.Parent;
end % get.Parent
function set.Parent( obj, value )
obj.Container.Parent = value;
end % set.Parent
function value = get.Position( obj )
value = obj.Container.Position;
end % get.Position
function set.Position( obj, value )
obj.Container.Position = value;
end % set.Position
function value = get.String( obj )
value = obj.Checkbox.String;
end % get.String
function set.String( obj, value )
% Set
obj.Checkbox.String = value;
% Mark as dirty
obj.setDirty()
end % set.String
function value = get.Tag( obj )
value = obj.Checkbox.Tag;
end % get.Tag
function set.Tag( obj, value )
obj.Checkbox.Tag = value;
end % set.Tag
function value = get.TooltipString( obj )
value = obj.Checkbox.TooltipString;
end % get.TooltipString
function set.TooltipString( obj, value )
obj.Checkbox.TooltipString = value;
end % set.TooltipString
function value = get.Type( obj )
value = obj.Checkbox.Type;
end % get.Type
function value = get.UIContextMenu( obj )
value = obj.Checkbox.UIContextMenu;
end % get.UIContextMenu
function set.UIContextMenu( obj, value )
obj.Checkbox.UIContextMenu = value;
end % set.UIContextMenu
function value = get.Units( obj )
value = obj.Container.Units;
end % get.Units
function set.Units( obj, value )
obj.Container.Units = value;
end % set.Units
function value = get.UserData( obj )
value = obj.Checkbox.UserData;
end % get.UserData
function set.UserData( obj, value )
obj.Checkbox.UserData = value;
end % set.UserData
function value = get.VerticalAlignment( obj )
value = obj.VerticalAlignment_;
end % get.VerticalAlignment
function set.VerticalAlignment( obj, value )
% Check
assert( ischar( value ) && ...
any( strcmp( value, {'top','middle','bottom'} ) ), ...
'uix:InvalidPropertyValue', ...
'Property ''VerticalAlignment'' must be ''top'', ''middle'' or ''bottom''.' )
% Set
obj.VerticalAlignment_ = value;
% Mark as dirty
obj.setDirty()
end % set.VerticalAlignment
function value = get.Visible( obj )
value = obj.Container.Visible;
end % get.Visible
function set.Visible( obj, value )
obj.Container.Visible = value;
end % set.Visible
end % accessors
methods( Access = private )
function onResized( obj, ~, ~ )
%onResized Event handler
% Rooted, so redraw
obj.redraw()
end % onResized
function onFigureChanged( obj, ~, eventData )
% If rooted, redraw
if isempty( eventData.OldFigure ) && ...
~isempty( eventData.NewFigure ) && obj.Dirty
obj.redraw()
end
end % onFigureChanged
end % event handlers
methods( Access = private )
function setDirty( obj )
%setDirty Mark as dirty
%
% t.setDirty() marks the text control t as dirty. If the text
% control is rooted then it is redrawn immediately. If not
% then the redraw is queued for when it is next rooted.
if isempty( obj.FigureObserver.Figure )
obj.Dirty = true; % set flag
else
obj.Dirty = false; % unset flag
obj.redraw() % redraw
end
end % setDirty
function redraw( obj )
%redraw Redraw
%
% t.redraw() redraws the text control t. Note that this
% requires the text control to be rooted. Methods should
% request redraws using setDirty, rather than calling redraw
% directly.
c = obj.Container;
b = obj.Checkbox;
s = obj.Screen;
bo = hgconvertunits( ancestor( obj, 'figure' ), ...
[0 0 1 1], 'normalized', 'pixels', c ); % bounds
m = obj.Margin;
e = b.Extent;
switch b.HorizontalAlignment
case 'left'
x = 1 - m;
case 'center'
x = 1 + bo(3)/2 - e(3)/2 - m;
case 'right'
x = 1 + bo(3) - e(3) - m;
end
w = e(3) + m;
switch obj.VerticalAlignment_
case 'top'
y = 1 + bo(4) - e(4);
case 'middle'
y = 1 + bo(4)/2 - e(4)/2;
case 'bottom'
y = 1;
end
h = e(4);
b.Position = [x y w h];
s.Position = [x y m h];
end % redraw
end % helpers
end % classdef
function o = checkBoxLabelOffset()
%checkBoxLabelOffset Horizontal offset to checkbox label
if verLessThan( 'MATLAB', '8.6' ) % R2015b
o = 18;
else
o = 16;
end
end % margin
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
loadIcon.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/GUI Layout Toolbox 2.3.1/layout/+uix/loadIcon.m
| 3,127 |
utf_8
|
38f0cd83643a54e6cdfb1bf63a443c44
|
function cdata = loadIcon( filename, bgcol )
%loadIcon Load an icon and set the transparent color
%
% cdata = uix.loadIcon(filename) loads the icon from the specified
% filename. For PNG files with transparency, the transparent pixels are
% set to NaN. For other files, pixels that are pure green are set to
% transparent (i.e., "green screen"). The resulting cdata is an RGB
% double array.
%
% cdata = uix.loadIcon(filename,bgcol) tries to merge the color data with
% the specified background colour bgcol. Fully transparent pixels are
% still set to NaN, but partially transparent pixels are merged with the
% background.
%
% See also: imread
% Copyright 2009-2016 The MathWorks, Inc.
% $Revision: 1436 $ $Date: 2016-11-17 17:53:29 +0000 (Thu, 17 Nov 2016) $
% Check inputs
narginchk( 1, 2 )
if nargin < 2
bgcol = get( 0, 'DefaultUIControlBackgroundColor' );
end
% First try normally
thisDir = fileparts( mfilename( 'fullpath' ) );
iconDir = fullfile( thisDir, 'Resources' );
if exist( filename, 'file' )
[cdata, map, alpha] = imread( filename );
elseif exist( fullfile( iconDir, filename ), 'file' )
[cdata, map, alpha] = imread( fullfile( iconDir, filename ) );
else
error( 'uix:FileNotFound', 'Cannot open file ''%s''.', filename )
end
% Convert indexed images to RGB
if ~isempty( map )
cdata = ind2rgb( cdata, map );
end
% Convert to double before applying transparency
cdata = convertToDouble( cdata );
% Handle transparency
[rows, cols, ~] = size( cdata );
if ~isempty( alpha )
% Transparency specified
alpha = convertToDouble( alpha );
f = find( alpha==0 );
if ~isempty( f )
cdata(f) = NaN;
cdata(f + rows*cols) = NaN;
cdata(f + 2*rows*cols) = NaN;
end
% Now blend partial alphas
f = find( alpha(:)>0 & alpha(:)<1 );
if ~isempty(f)
cdata(f) = cdata(f).*alpha(f) + bgcol(1)*(1-alpha(f));
cdata(f + rows*cols) = cdata(f + rows*cols).*alpha(f) + bgcol(2)*(1-alpha(f));
cdata(f + 2*rows*cols) = cdata(f + 2*rows*cols).*alpha(f) + bgcol(3)*(1-alpha(f));
end
else
% Do a "green screen", treating anything pure-green as transparent
f = find( cdata(:,:,1)==0 & cdata(:,:,2)==1 & cdata(:,:,3)==0 );
cdata(f) = NaN;
cdata(f + rows*cols) = NaN;
cdata(f + 2*rows*cols) = NaN;
end
end % uix.loadIcon
% -------------------------------------------------------------------------
function cdata = convertToDouble( cdata )
%convertToDouble Convert image data to double in the range [0,1]
%
% cdata = convertToDouble(cData)
switch lower( class( cdata ) )
case 'double'
% do nothing
case 'single'
cdata = double( cdata );
case 'uint8'
cdata = double( cdata ) / 255;
case 'uint16'
cdata = double( cdata ) / 65535;
case 'int8'
cdata = ( double( cdata ) + 128 ) / 255;
case 'int16'
cdata = ( double( cdata ) + 32768 ) / 65535;
otherwise
error( 'uix:InvalidArgument', ...
'Image data of type ''%s'' is not supported.', class( cdata ) )
end
end % convertToDouble
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
ChildObserver.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/GUI Layout Toolbox 2.3.1/layout/+uix/ChildObserver.m
| 8,831 |
utf_8
|
cc3553df755d4fc3dd119136aa17fe95
|
classdef ( Hidden, Sealed ) ChildObserver < handle
%uix.ChildObserver Child observer
%
% co = uix.ChildObserver(o) creates a child observer for the graphics
% object o. A child observer raises events when objects are added to
% and removed from the property Children of o.
%
% See also: uix.Node
% Copyright 2009-2016 The MathWorks, Inc.
% $Revision: 1436 $ $Date: 2016-11-17 17:53:29 +0000 (Thu, 17 Nov 2016) $
properties( Access = private )
Root % root node
end
events( NotifyAccess = private )
ChildAdded % child added
ChildRemoved % child removed
end
methods
function obj = ChildObserver( oRoot )
%uix.ChildObserver Child observer
%
% co = uix.ChildObserver(o) creates a child observer for the
% graphics object o. A child observer raises events when
% objects are added to and removed from the property Children
% of o.
% Check
assert( iscontent( oRoot ) && ...
isequal( size( oRoot ), [1 1] ), 'uix.InvalidArgument', ...
'Object must be a graphics object.' )
% Create root node
nRoot = uix.Node( oRoot );
childAddedListener = event.listener( oRoot, ...
'ObjectChildAdded', ...
@(~,e)obj.addChild(nRoot,e.Child) );
childAddedListener.Recursive = true;
nRoot.addprop( 'ChildAddedListener' );
nRoot.ChildAddedListener = childAddedListener;
childRemovedListener = event.listener( oRoot, ...
'ObjectChildRemoved', ...
@(~,e)obj.removeChild(nRoot,e.Child) );
childRemovedListener.Recursive = true;
nRoot.addprop( 'ChildRemovedListener' );
nRoot.ChildRemovedListener = childRemovedListener;
% Add children
oChildren = hgGetTrueChildren( oRoot );
for ii = 1:numel( oChildren )
obj.addChild( nRoot, oChildren(ii) )
end
% Store properties
obj.Root = nRoot;
end % constructor
end % structors
methods( Access = private )
function addChild( obj, nParent, oChild )
%addChild Add child object to parent node
%
% co.addChild(np,oc) adds the child object oc to the parent
% node np, either as part of construction of the child
% observer co, or in response to an ObjectChildAdded event on
% an object of interest to co. This may lead to ChildAdded
% events being raised on co.
% Create child node
nChild = uix.Node( oChild );
nParent.addChild( nChild )
if iscontent( oChild )
% Add Internal PreSet property listener
internalPreSetListener = event.proplistener( oChild, ...
findprop( oChild, 'Internal' ), 'PreSet', ...
@(~,~)obj.preSetInternal(nChild) );
nChild.addprop( 'InternalPreSetListener' );
nChild.InternalPreSetListener = internalPreSetListener;
% Add Internal PostSet property listener
internalPostSetListener = event.proplistener( oChild, ...
findprop( oChild, 'Internal' ), 'PostSet', ...
@(~,~)obj.postSetInternal(nChild) );
nChild.addprop( 'InternalPostSetListener' );
nChild.InternalPostSetListener = internalPostSetListener;
else
% Add ObjectChildAdded listener
childAddedListener = event.listener( oChild, ...
'ObjectChildAdded', ...
@(~,e)obj.addChild(nChild,e.Child) );
nChild.addprop( 'ChildAddedListener' );
nChild.ChildAddedListener = childAddedListener;
% Add ObjectChildRemoved listener
childRemovedListener = event.listener( oChild, ...
'ObjectChildRemoved', ...
@(~,e)obj.removeChild(nChild,e.Child) );
nChild.addprop( 'ChildRemovedListener' );
nChild.ChildRemovedListener = childRemovedListener;
end
% Raise ChildAdded event
if iscontent( oChild ) && oChild.Internal == false
notify( obj, 'ChildAdded', uix.ChildEvent( oChild ) )
end
% Add grandchildren
if ~iscontent( oChild )
oGrandchildren = hgGetTrueChildren( oChild );
for ii = 1:numel( oGrandchildren )
obj.addChild( nChild, oGrandchildren(ii) )
end
end
end % addChild
function removeChild( obj, nParent, oChild )
%removeChild Remove child object from parent node
%
% co.removeChild(np,oc) removes the child object oc from the
% parent node np, in response to an ObjectChildRemoved event
% on an object of interest to co. This may lead to
% ChildRemoved events being raised on co.
% Get child node
nChildren = nParent.Children;
tf = oChild == [nChildren.Object];
nChild = nChildren(tf);
% Raise ChildRemoved event(s)
notifyChildRemoved( nChild )
% Delete child node
delete( nChild )
function notifyChildRemoved( nc )
% Process child nodes
ngc = nc.Children;
for ii = 1:numel( ngc )
notifyChildRemoved( ngc(ii) )
end
% Process this node
oc = nc.Object;
if iscontent( oc ) && oc.Internal == false
notify( obj, 'ChildRemoved', uix.ChildEvent( oc ) )
end
end % notifyChildRemoved
end % removeChild
function preSetInternal( ~, nChild )
%preSetInternal Perform property PreSet tasks
%
% co.preSetInternal(n) caches the previous value of the
% property Internal of the object referenced by the node n, to
% enable PostSet tasks to identify whether the value changed.
% This is necessary since Internal AbortSet is false.
oldInternal = nChild.Object.Internal;
nChild.addprop( 'OldInternal' );
nChild.OldInternal = oldInternal;
end % preSetInternal
function postSetInternal( obj, nChild )
%postSetInternal Perform property PostSet tasks
%
% co.postSetInternal(n) raises a ChildAdded or ChildRemoved
% event on the child observer co in response to a change of
% the value of the property Internal of the object referenced
% by the node n.
% Retrieve old and new values
oChild = nChild.Object;
newInternal = oChild.Internal;
oldInternal = nChild.OldInternal;
% Clean up node
delete( findprop( nChild, 'OldInternal' ) )
% Raise event
switch newInternal
case oldInternal % no change
% no event
case true % false to true
notify( obj, 'ChildRemoved', uix.ChildEvent( oChild ) )
case false % true to false
notify( obj, 'ChildAdded', uix.ChildEvent( oChild ) )
end
end % postSetInternal
end % event handlers
end % classdef
function tf = iscontent( o )
%iscontent True for graphics that can be Contents (and can be Children)
%
% uix.ChildObserver needs to determine which objects can be Contents,
% which is equivalent to can be Children if HandleVisibility is 'on' and
% Internal is false. Prior to R2016a, this condition could be checked
% using isgraphics. From R2016a, isgraphics returns true for a wider
% range of objects, including some that can never by Contents, e.g.,
% JavaCanvas. Therefore this function checks whether an object is of type
% matlab.graphics.internal.GraphicsBaseFunctions, which is what isgraphics
% did prior to R2016a.
tf = isa( o, 'matlab.graphics.internal.GraphicsBaseFunctions' ) &&...
isprop( o, 'Position' );
end % iscontent
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
Empty.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/GUI Layout Toolbox 2.3.1/layout/+uix/Empty.m
| 2,629 |
utf_8
|
baef0f4e364966ead829a37218b4ad5d
|
function obj = Empty( varargin )
%uix.Empty Create an empty space
%
% obj = uix.Empty() creates an empty space that can be used to add gaps
% between elements in layouts.
%
% obj = uix.Empty(param,value,...) also sets one or more property
% values.
%
% See the <a href="matlab:doc uix.Empty">documentation</a> for more detail and the list of properties.
%
% Examples:
% >> f = figure();
% >> box = uix.HBox( 'Parent', f );
% >> uicontrol( 'Parent', box, 'Background', 'r' )
% >> uix.Empty( 'Parent', box )
% >> uicontrol( 'Parent', box, 'Background', 'b' )
% Copyright 2009-2016 The MathWorks, Inc.
% $Revision: 1436 $ $Date: 2016-11-17 17:53:29 +0000 (Thu, 17 Nov 2016) $
% Create uicontainer
obj = matlab.ui.container.internal.UIContainer( 'Tag', 'empty', varargin{:} );
% Create property for Parent listener
p = addprop( obj, 'ParentListener' );
p.Hidden = true;
% Create Parent listener
obj.ParentListener = event.proplistener( obj, ...
findprop( obj, 'Parent' ), 'PostSet', @(~,~)onParentChanged(obj) );
% Create property for Parent color listener
p = addprop( obj, 'ParentColorListener' );
p.Hidden = true;
% Initialize color and listener
updateColor( obj )
updateListener( obj )
end % uix.Empty
function onParentChanged( obj )
%onParentColorChanged Event handler
% Update color and listener
updateColor( obj )
updateListener( obj )
end % onParentChanged
function onParentColorChanged( obj )
%onParentColorChanged Event handler
% Update color
updateColor( obj )
end % onParentColorChanged
function name = getColorProperty( obj )
%getColorProperty Get color property
names = {'Color','BackgroundColor'}; % possible names
for ii = 1:numel( names ) % loop over possible names
name = names{ii};
if isprop( obj, name )
return
end
end
error( 'Cannot find color property for %s.', class( obj ) )
end % getColorProperty
function updateColor( obj )
%updateColor Set uicontainer BackgroundColor to match Parent
parent = obj.Parent;
if isempty( parent ), return, end
property = getColorProperty( parent );
color = parent.( property );
try
obj.BackgroundColor = color;
catch e
warning( e.identifier, e.message ) % rethrow as warning
end
end % updateColor
function updateListener( obj )
%updateListener Create listener to parent color property
parent = obj.Parent;
if isempty( parent )
obj.ParentColorListener = [];
else
property = getColorProperty( parent );
obj.ParentColorListener = event.proplistener( parent, ...
findprop( parent, property ), 'PostSet', ...
@(~,~)onParentColorChanged(obj) );
end
end % updateListener
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
guideApp.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/GUI Layout Toolbox 2.3.1/layoutdoc/Examples/guideApp.m
| 4,073 |
utf_8
|
f1e03beaed00662522eda571d8c8f409
|
function varargout = guideApp(varargin)
% GUIDEAPP MATLAB code for guideApp.fig
% GUIDEAPP, by itself, creates a new GUIDEAPP or raises the existing
% singleton*.
%
% H = GUIDEAPP returns the handle to a new GUIDEAPP or the handle to
% the existing singleton*.
%
% GUIDEAPP('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUIDEAPP.M with the given input arguments.
%
% GUIDEAPP('Property','Value',...) creates a new GUIDEAPP or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before guideApp_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to guideApp_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
% Copyright 2009-2013 The MathWorks Ltd.
% Edit the above text to modify the response to help guideApp
% Last Modified by GUIDE v2.5 21-Jul-2010 07:36:25
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @guideApp_OpeningFcn, ...
'gui_OutputFcn', @guideApp_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 guideApp is made visible.
function guideApp_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 guideApp (see VARARGIN)
% Choose default command line output for guideApp
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% Put a layout in the panel
g = uix.GridFlex( 'Parent', handles.uipanel1, ...
'Units', 'Normalized', 'Position', [0 0 1 1], ...
'Spacing', 5 );
uix.BoxPanel( 'Parent', g, 'Title', 'Panel 1' );
uix.BoxPanel( 'Parent', g, 'Title', 'Panel 2' );
uix.BoxPanel( 'Parent', g, 'Title', 'Panel 3' );
uix.BoxPanel( 'Parent', g, 'Title', 'Panel 4' );
g.Heights = [-1 -1];
% UIWAIT makes guideApp wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = guideApp_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 pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- 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)
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
colorspace.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/colorspace/colorspace.m
| 16,178 |
utf_8
|
2ca0aee9ae4d0f5c12a7028c45ef2b8d
|
function varargout = colorspace(Conversion,varargin)
%COLORSPACE Transform a color image between color representations.
% B = COLORSPACE(S,A) transforms the color representation of image A
% where S is a string specifying the conversion. The input array A
% should be a real full double array of size Mx3 or MxNx3. The output B
% is the same size as A.
%
% S tells the source and destination color spaces, S = 'dest<-src', or
% alternatively, S = 'src->dest'. Supported color spaces are
%
% 'RGB' sRGB IEC 61966-2-1
% 'YCbCr' Luma + Chroma ("digitized" version of Y'PbPr)
% 'JPEG-YCbCr' Luma + Chroma space used in JFIF JPEG
% 'YDbDr' SECAM Y'DbDr Luma + Chroma
% 'YPbPr' Luma (ITU-R BT.601) + Chroma
% 'YUV' NTSC PAL Y'UV Luma + Chroma
% 'YIQ' NTSC Y'IQ Luma + Chroma
% 'HSV' or 'HSB' Hue Saturation Value/Brightness
% 'HSL' or 'HLS' Hue Saturation Luminance
% 'HSI' Hue Saturation Intensity
% 'XYZ' CIE 1931 XYZ
% 'Lab' CIE 1976 L*a*b* (CIELAB)
% 'Luv' CIE L*u*v* (CIELUV)
% 'LCH' CIE L*C*H* (CIELCH)
% 'CAT02 LMS' CIE CAT02 LMS
%
% All conversions assume 2 degree observer and D65 illuminant.
%
% Color space names are case insensitive and spaces are ignored. When
% sRGB is the source or destination, it can be omitted. For example
% 'yuv<-' is short for 'yuv<-rgb'.
%
% For sRGB, the values should be scaled between 0 and 1. Beware that
% transformations generally do not constrain colors to be "in gamut."
% Particularly, transforming from another space to sRGB may obtain
% R'G'B' values outside of the [0,1] range. So the result should be
% clamped to [0,1] before displaying:
% image(min(max(B,0),1)); % Clamp B to [0,1] and display
%
% sRGB (Red Green Blue) is the (ITU-R BT.709 gamma-corrected) standard
% red-green-blue representation of colors used in digital imaging. The
% components should be scaled between 0 and 1. The space can be
% visualized geometrically as a cube.
%
% Y'PbPr, Y'CbCr, Y'DbDr, Y'UV, and Y'IQ are related to sRGB by linear
% transformations. These spaces separate a color into a grayscale
% luminance component Y and two chroma components. The valid ranges of
% the components depends on the space.
%
% HSV (Hue Saturation Value) is related to sRGB by
% H = hexagonal hue angle (0 <= H < 360),
% S = C/V (0 <= S <= 1),
% V = max(R',G',B') (0 <= V <= 1),
% where C = max(R',G',B') - min(R',G',B'). The hue angle H is computed on
% a hexagon. The space is geometrically a hexagonal cone.
%
% HSL (Hue Saturation Lightness) is related to sRGB by
% H = hexagonal hue angle (0 <= H < 360),
% S = C/(1 - |2L-1|) (0 <= S <= 1),
% L = (max(R',G',B') + min(R',G',B'))/2 (0 <= L <= 1),
% where H and C are the same as in HSV. Geometrically, the space is a
% double hexagonal cone.
%
% HSI (Hue Saturation Intensity) is related to sRGB by
% H = polar hue angle (0 <= H < 360),
% S = 1 - min(R',G',B')/I (0 <= S <= 1),
% I = (R'+G'+B')/3 (0 <= I <= 1).
% Unlike HSV and HSL, the hue angle H is computed on a circle rather than
% a hexagon.
%
% CIE XYZ is related to sRGB by inverse gamma correction followed by a
% linear transform. Other CIE color spaces are defined relative to XYZ.
%
% CIE L*a*b*, L*u*v*, and L*C*H* are nonlinear functions of XYZ. The L*
% component is designed to match closely with human perception of
% lightness. The other two components describe the chroma.
%
% CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02
% chromatic adaptation matrix. The space is designed to model the
% response of the three types of cones in the human eye, where L, M, S,
% correspond respectively to red ("long"), green ("medium"), and blue
% ("short").
% Pascal Getreuer 2005-2010
%%% Input parsing %%%
if nargin < 2, error('Not enough input arguments.'); end
[SrcSpace,DestSpace] = parse(Conversion);
if nargin == 2
Image = varargin{1};
elseif nargin >= 3
Image = cat(3,varargin{:});
else
error('Invalid number of input arguments.');
end
FlipDims = (size(Image,3) == 1);
if FlipDims, Image = permute(Image,[1,3,2]); end
if ~isa(Image,'double'), Image = double(Image)/255; end
if size(Image,3) ~= 3, error('Invalid input size.'); end
SrcT = gettransform(SrcSpace);
DestT = gettransform(DestSpace);
if ~ischar(SrcT) && ~ischar(DestT)
% Both source and destination transforms are affine, so they
% can be composed into one affine operation
T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)];
Temp = zeros(size(Image));
Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
Image = Temp;
elseif ~ischar(DestT)
Image = rgb(Image,SrcSpace);
Temp = zeros(size(Image));
Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10);
Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11);
Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12);
Image = Temp;
else
Image = feval(DestT,Image,SrcSpace);
end
%%% Output format %%%
if nargout > 1
varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)};
else
if FlipDims, Image = permute(Image,[1,3,2]); end
varargout = {Image};
end
return;
function [SrcSpace,DestSpace] = parse(Str)
% Parse conversion argument
if ischar(Str)
Str = lower(strrep(strrep(Str,'-',''),'=',''));
k = find(Str == '>');
if length(k) == 1 % Interpret the form 'src->dest'
SrcSpace = Str(1:k-1);
DestSpace = Str(k+1:end);
else
k = find(Str == '<');
if length(k) == 1 % Interpret the form 'dest<-src'
DestSpace = Str(1:k-1);
SrcSpace = Str(k+1:end);
else
error(['Invalid conversion, ''',Str,'''.']);
end
end
SrcSpace = alias(SrcSpace);
DestSpace = alias(DestSpace);
else
SrcSpace = 1; % No source pre-transform
DestSpace = Conversion;
if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end
end
return;
function Space = alias(Space)
Space = strrep(strrep(Space,'cie',''),' ','');
if isempty(Space)
Space = 'rgb';
end
switch Space
case {'ycbcr','ycc'}
Space = 'ycbcr';
case {'hsv','hsb'}
Space = 'hsv';
case {'hsl','hsi','hls'}
Space = 'hsl';
case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'}
return;
end
return;
function T = gettransform(Space)
% Get a colorspace transform: either a matrix describing an affine transform,
% or a string referring to a conversion subroutine
switch Space
case 'ypbpr'
T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0];
case 'yuv'
% sRGB to NTSC/PAL YUV
% Wikipedia: http://en.wikipedia.org/wiki/YUV
T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0];
case 'ydbdr'
% sRGB to SECAM YDbDr
% Wikipedia: http://en.wikipedia.org/wiki/YDbDr
T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0];
case 'yiq'
% sRGB in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591];
% Wikipedia: http://en.wikipedia.org/wiki/YIQ
T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0];
case 'ycbcr'
% sRGB (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr
% Wikipedia: http://en.wikipedia.org/wiki/YCbCr
% Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion
T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128];
case 'jpegycbcr'
% Wikipedia: http://en.wikipedia.org/wiki/YCbCr
T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255;
case {'rgb','xyz','hsv','hsl','lab','luv','lch','cat02lms'}
T = Space;
otherwise
error(['Unknown color space, ''',Space,'''.']);
end
return;
function Image = rgb(Image,SrcSpace)
% Convert to sRGB from 'SrcSpace'
switch SrcSpace
case 'rgb'
return;
case 'hsv'
% Convert HSV to sRGB
Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1));
case 'hsl'
% Convert HSL to sRGB
L = Image(:,:,3);
Delta = Image(:,:,2).*min(L,1-L);
Image = huetorgb(L-Delta,L+Delta,Image(:,:,1));
case {'xyz','lab','luv','lch','cat02lms'}
% Convert to CIE XYZ
Image = xyz(Image,SrcSpace);
% Convert XYZ to RGB
T = [3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057];
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B
% Desaturate and rescale to constrain resulting RGB values to [0,1]
AddWhite = -min(min(min(R,G),B),0);
R = R + AddWhite;
G = G + AddWhite;
B = B + AddWhite;
% Apply gamma correction to convert linear RGB to sRGB
Image(:,:,1) = gammacorrection(R); % R'
Image(:,:,2) = gammacorrection(G); % G'
Image(:,:,3) = gammacorrection(B); % B'
otherwise % Conversion is through an affine transform
T = gettransform(SrcSpace);
temp = inv(T(:,1:3));
T = [temp,-temp*T(:,4)];
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
Image(:,:,1) = R;
Image(:,:,2) = G;
Image(:,:,3) = B;
end
% Clip to [0,1]
Image = min(max(Image,0),1);
return;
function Image = xyz(Image,SrcSpace)
% Convert to CIE XYZ from 'SrcSpace'
WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'xyz'
return;
case 'luv'
% Convert CIE L*uv to XYZ
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
L = Image(:,:,1);
Y = (L + 16)/116;
Y = invf(Y)*WhitePoint(2);
U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU;
V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV;
Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X
Image(:,:,2) = Y; % Y
Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z
case {'lab','lch'}
Image = lab(Image,SrcSpace);
% Convert CIE L*ab to XYZ
fY = (Image(:,:,1) + 16)/116;
fX = fY + Image(:,:,2)/500;
fZ = fY - Image(:,:,3)/200;
Image(:,:,1) = WhitePoint(1)*invf(fX); % X
Image(:,:,2) = WhitePoint(2)*invf(fY); % Y
Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z
case 'cat02lms'
% Convert CAT02 LMS to XYZ
T = inv([0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]);
L = Image(:,:,1);
M = Image(:,:,2);
S = Image(:,:,3);
Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X
Image(:,:,2) = T(2)*L + T(5)*M + T(8)*S; % Y
Image(:,:,3) = T(3)*L + T(6)*M + T(9)*S; % Z
otherwise % Convert from some gamma-corrected space
% Convert to sRGB
Image = rgb(Image,SrcSpace);
% Undo gamma correction
R = invgammacorrection(Image(:,:,1));
G = invgammacorrection(Image(:,:,2));
B = invgammacorrection(Image(:,:,3));
% Convert RGB to XYZ
T = inv([3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]);
Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X
Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y
Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z
end
return;
function Image = hsv(Image,SrcSpace)
% Convert to HSV
Image = rgb(Image,SrcSpace);
V = max(Image,[],3);
S = (V - min(Image,[],3))./(V + (V == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = V;
return;
function Image = hsl(Image,SrcSpace)
% Convert to HSL
switch SrcSpace
case 'hsv'
% Convert HSV to HSL
MaxVal = Image(:,:,3);
MinVal = (1 - Image(:,:,2)).*MaxVal;
L = 0.5*(MaxVal + MinVal);
temp = min(L,1-L);
Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
Image(:,:,3) = L;
otherwise
Image = rgb(Image,SrcSpace); % Convert to sRGB
% Convert sRGB to HSL
MinVal = min(Image,[],3);
MaxVal = max(Image,[],3);
L = 0.5*(MaxVal + MinVal);
temp = min(L,1-L);
S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = L;
end
return;
function Image = lab(Image,SrcSpace)
% Convert to CIE L*a*b* (CIELAB)
WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'lab'
return;
case 'lch'
% Convert CIE L*CH to CIE L*ab
C = Image(:,:,2);
Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a*
Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b*
otherwise
Image = xyz(Image,SrcSpace); % Convert to XYZ
% Convert XYZ to CIE L*a*b*
X = Image(:,:,1)/WhitePoint(1);
Y = Image(:,:,2)/WhitePoint(2);
Z = Image(:,:,3)/WhitePoint(3);
fX = f(X);
fY = f(Y);
fZ = f(Z);
Image(:,:,1) = 116*fY - 16; % L*
Image(:,:,2) = 500*(fX - fY); % a*
Image(:,:,3) = 200*(fY - fZ); % b*
end
return;
function Image = luv(Image,SrcSpace)
% Convert to CIE L*u*v* (CIELUV)
WhitePoint = [0.950456,1,1.088754];
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
Image = xyz(Image,SrcSpace); % Convert to XYZ
Denom = Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3);
U = (4*Image(:,:,1))./(Denom + (Denom == 0));
V = (9*Image(:,:,2))./(Denom + (Denom == 0));
Y = Image(:,:,2)/WhitePoint(2);
L = 116*f(Y) - 16;
Image(:,:,1) = L; % L*
Image(:,:,2) = 13*L.*(U - WhitePointU); % u*
Image(:,:,3) = 13*L.*(V - WhitePointV); % v*
return;
function Image = lch(Image,SrcSpace)
% Convert to CIE L*ch
Image = lab(Image,SrcSpace); % Convert to CIE L*ab
H = atan2(Image(:,:,3),Image(:,:,2));
H = H*180/pi + 360*(H < 0);
Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C
Image(:,:,3) = H; % H
return;
function Image = cat02lms(Image,SrcSpace)
% Convert to CAT02 LMS
Image = xyz(Image,SrcSpace);
T = [0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834];
X = Image(:,:,1);
Y = Image(:,:,2);
Z = Image(:,:,3);
Image(:,:,1) = T(1)*X + T(4)*Y + T(7)*Z; % L
Image(:,:,2) = T(2)*X + T(5)*Y + T(8)*Z; % M
Image(:,:,3) = T(3)*X + T(6)*Y + T(9)*Z; % S
return;
function Image = huetorgb(m0,m2,H)
% Convert HSV or HSL hue to RGB
N = size(H);
H = min(max(H(:),0),360)/60;
m0 = m0(:);
m2 = m2(:);
F = H - round(H/2)*2;
M = [m0, m0 + (m2-m0).*abs(F), m2];
Num = length(m0);
j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num;
k = floor(H) + 1;
Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]);
return;
function H = rgbtohue(Image)
% Convert RGB to HSV or HSL hue
[M,i] = sort(Image,3);
i = i(:,:,3);
Delta = M(:,:,3) - M(:,:,1);
Delta = Delta + (Delta == 0);
R = Image(:,:,1);
G = Image(:,:,2);
B = Image(:,:,3);
H = zeros(size(R));
k = (i == 1);
H(k) = (G(k) - B(k))./Delta(k);
k = (i == 2);
H(k) = 2 + (B(k) - R(k))./Delta(k);
k = (i == 3);
H(k) = 4 + (R(k) - G(k))./Delta(k);
H = 60*H + 360*(H < 0);
H(Delta == 0) = nan;
return;
function Rp = gammacorrection(R)
Rp = zeros(size(R));
i = (R <= 0.0031306684425005883);
Rp(i) = 12.92*R(i);
Rp(~i) = real(1.055*R(~i).^0.416666666666666667 - 0.055);
return;
function R = invgammacorrection(Rp)
R = zeros(size(Rp));
i = (Rp <= 0.0404482362771076);
R(i) = Rp(i)/12.92;
R(~i) = real(((Rp(~i) + 0.055)/1.055).^2.4);
return;
function fY = f(Y)
fY = real(Y.^(1/3));
i = (Y < 0.008856);
fY(i) = Y(i)*(841/108) + (4/29);
return;
function Y = invf(fY)
Y = fY.^3;
i = (Y < 0.008856);
Y(i) = (fY(i) - 4/29)*(108/841);
return;
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
display.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/panel_2.10/@panel/display.m
| 685 |
utf_8
|
d40ca5f83673dfa9d60822d651eca66f
|
function display(p)
% disp([10 'panel: (' num2str(p.fig) ', ' int2str(p.id) ')' 10])
disp([10 '(Panel Object)'])
if isnumeric(p.fig) && isscalar(p.fig) && ishandle(p.fig) && strcmp(get(p.fig,'type'), 'figure')
[P, panelroot] = getpanel(p);
sect('Figure Properties');
disp(panelroot)
sect('Panel Logical Properties');
disp(P.panel)
sect('Panel Render Properties (inherited)');
disp(P.render_inh)
sect('Panel Render Properties (not inherited)');
disp(P.render_notinh)
disp(' ')
else
warning('panel is not attached to an existing figure')
disp(' ')
end
function sect(msg)
disp(' ')
disp([msg ':'])
% disp('________________________________');
% disp(' ')
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
subrender.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/contrib/panel_2.10/@panel/private/subrender.m
| 7,009 |
utf_8
|
a6638f6f21594918bd93a00354a88a44
|
%% SUBRENDER
function subrender(p, P, renderer)
% get specific margin
if P.panel.axis
margin = subsref(p, 'axismargin');
else
margin = subsref(p, 'parentmargin');
end
% root has extra margin
if ~P.panel.parent
rootmargin = subsref(p, 'rootmargin');
margin = margin + rootmargin;
end
% get fractional margin
size_panel_mm = renderer.size_fig_mm .* renderer.into(3:4); % size in mm of the panel we're rendering into
margin_as_panel_frac = tofrac(margin, size_panel_mm, renderer.units);
% reduce "into" by margin
renderer.into(1:2) = renderer.into(1:2) ...
+ margin_as_panel_frac(1:2) .* renderer.into(3:4);
renderer.into(3:4) = renderer.into(3:4) ...
- margin_as_panel_frac(1:2) .* renderer.into(3:4) ...
- margin_as_panel_frac(3:4) .* renderer.into(3:4);
% handle separately parent panels and axis panels
if P.panel.axis
subrender_axis(p, P, renderer);
else
subrender_parent(p, P, renderer);
end
%% SUBRENDER_AXIS
%
% function returns the amount of space this axis needs
% on each side (in mm) to render all its parts (labels,
% etc.) in addition, it does all the layout for those
% labels. returns margin as [l b r t].
function margin = subrender_axis(p, P, renderer)
% metrics
label_c = 1; % fixed gap associated with title
label_m = 1.5;
% assume zero
margin = [0 0 0 0];
% font metrics
fontname = subsref(p, 'fontname');
fontsize = subsref(p, 'fontsize');
fontweight = subsref(p, 'fontweight');
set(P.panel.axis, 'fontname', fontname);
set(P.panel.axis, 'fontsize', fontsize);
set(P.panel.axis, 'fontweight', fontweight);
% title
title = P.render_notinh.title;
h = get(P.panel.axis, 'title');
set(h, 'FontName', fontname, ...
'FontSize', fontsize, ...
'FontWeight', fontweight, ...
'string', title);
% if ~isempty(title)
% margin(4) = margin(4) + fontsize * label_m / 72 * 25.4 + label_c;
% end
% render specials
for xy = 'xy'
suffix = P.render_notinh.([xy 'scale']);
tick = get(P.panel.axis, [xy 'tick']);
tickLabelSuffix = '';
if any(suffix == '$')
useSuffixOnTickLabels = true;
suffix = suffix(suffix ~= '$');
else
useSuffixOnTickLabels = false;
end
if isempty(suffix)
mult = 1;
else
if length(suffix) ~= 1
error(['error in scale argument "' suffix '"']);
end
suffixes = 'yzafpnum kMGTPEZY';
if suffix == '?'
% auto scale
m = floor(log10(max(abs(tick))) / 3);
m = m + 9;
if m < 1 m = 1; end
if m > length(suffixes) m = length(suffixes); end
suffix = suffixes(m);
end
i = find(suffixes == suffix);
if isempty(i)
error(['error in scale argument "' suffix '"']);
end
mult = 1000 ^ (i - 9);
if useSuffixOnTickLabels
tickLabelSuffix = suffix;
end
end
tick = tick / mult;
ticklabel = {};
longestticklabel = 0;
for n = 1:length(tick)
ticklabel{n} = [sprintf('%g', tick(n)) tickLabelSuffix];
if length(ticklabel{n}) > longestticklabel
longestticklabel = length(ticklabel{n});
end
end
set(P.panel.axis, [xy 'ticklabel'], ticklabel);
h = get(P.panel.axis, [xy 'label']);
label = subsref(p, [xy 'label']);
s = strfind(label, '$');
if ~isempty(s)
if suffix == 'u'
suffix = '\mu';
end
label = strrep(label, '$', suffix);
end
set(h, 'FontName', fontname, ...
'FontSize', fontsize, ...
'FontWeight', fontweight, ...
'string', label);
% if ~isempty(label)
% switch xy
% case 'x'
% ax = 2;
% case 'y'
% ax = 1;
% ticklabelspace = longestticklabel * fontsize * 0.4 * label_m / 72 * 25.4;
% labelspace = fontsize * label_m / 72 * 25.4 + label_c;
% margin(ax) = ticklabelspace + labelspace;
% end
% end
end
%%%% could return the margin at this point (end first pass)
%%%% so that caller could calculate margins across a whole
%%%% packed panel, and then call us back to do the second
%%%% pass, below:
% check we've space to render and do so
if renderer.into(1) >= 0 & renderer.into(1) < 1 & renderer.into(2) >= 0 & renderer.into(2) < 1 & renderer.into(3) > 0 & renderer.into(3) <= 1 & renderer.into(4) > 0 & renderer.into(4) <= 1
set(P.panel.axis, 'position', renderer.into);
else
disp('WARNING (panel): failed to render an axis due to size limitations')
end
%% SUBRENDER_PARENT
function subrender_parent(p, P, renderer)
% if any child uses absolute positioning, all must
used_abs = false;
used_rel = false;
N = length(P.panel.children);
c = p;
C = {};
for n = 1:N
c.id = P.panel.children(n);
C{n} = getpanel(c);
if isscalar(C{n}.panel.pack)
used_rel = true;
else
used_abs = true;
end
end
if used_rel && used_abs
error('cannot use relative and absolute positioning amongst the children of a single panel');
end
% assign space to each of its children
if used_abs
% do assignments
renderer2 = renderer;
for n = 1:N
pack = tofrac(C{n}.panel.pack, renderer.size_fig_mm, renderer.units); % convert percentage to fraction
packed = [];
packed(1:2) = renderer.into(1:2) + pack(1:2) .* renderer.into(3:4);
packed(3:4) = renderer.into(3:4) .* pack(3:4);
c.id = P.panel.children(n);
renderer2.into = packed;
subrender(c, C{n}, renderer2)
end
end
if used_rel
% convert edge to axis and end
edges = 'lbrt';
edge = find(P.render_inh.edge == edges);
if isempty(edge)
error(['unrecognised packing edge "' P.render_inh.edge '" (use l, r, t or b)']);
end
axs = [1 2 1 2];
ax = axs(edge);
eds = [1 1 2 2];
ed = eds(edge);
% % ask each axis child to render (first pass)
% % maximise margins that match up (if packing on top or
% % bottom edge, that's the left and right margins, and vice
% % versa).
% max_margin = [0 0];
% margins = {};
% match_indices = {[2 4] [1 3]};
% for n = 1:N
% if C{n}.panel.axis
% margin = subrender_axis_first(c, C{n});
% margins{n} = margin;
% match_margin = margin(match_indices{ax});
% max_margin = max(max_margin, match_margin);
% else
% margins{n} = [0 0 0 0];
% end
% end
% size in mm of the "into" space we're rendering into
size_into_mm = renderer.size_fig_mm .* renderer.into(3:4);
% assignments
assignments = zeros(1,N);
% assign to each child
for n = 1:N
pack = C{n}.panel.pack;
assignments(n) = tofrac(pack, renderer.size_fig_mm(ax), renderer.units);
end
% divvy up remaining space
n = find(assignments == 0);
if ~isempty(n)
S = sum(assignments);
M = length(n);
if S >= 1
warning('no space left to divvy up');
else
assignments(n) = (1 - S) / M;
end
end
% convert to scale of parent position
assignments = assignments * renderer.into(ax + 2);
% pack from near edge
if ed == 1
for n = 1:N
renderer.into(ax + 2) = assignments(n);
c.id = P.panel.children(n);
subrender(c, C{n}, renderer);
renderer.into(ax) = renderer.into(ax) + assignments(n);
end
end
% pack from far edge
if ed == 2
renderer.into(ax) = renderer.into(ax) + renderer.into(ax + 2);
for n = 1:N
renderer.into(ax) = renderer.into(ax) - assignments(n);
renderer.into(ax + 2) = assignments(n);
c.id = P.panel.children(n);
subrender(c, C{n},renderer);
end
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
overlayPositionOrientationV2.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/TrackingScripts/overlayPositionOrientationV2.m
| 9,961 |
utf_8
|
63d7fa169443d4cb324fd1510f2d5332
|
function [movOrient,LineXstart,LineYstart,LineXend,LineYend]=overlayPositionOrientationV2(xPart,yPart,anisoPart,orientPart,intPart,drawParticlesOn,varargin)
% [movOrient,hAxisOverlay,hAxisIntensity,xstart,ystart,xend,yend]=overlayPositionOrientation(xPart,yPart,anisoPart,orientPart,intPart,drawParticlesOn,varargin)
% Simpler version that just draws particles on specified axes. Useful when
% called from scripts.
% Function that overlays positon and orientation information on image.
arg.Parent=NaN;
arg.delay=0.01;
arg.glyphDiameter=6;
arg.lineLength=50; % Line-length corresponding to anisotropy of 1 when length is set proportional to anisotropy. If this is set to zero, no line is drawn.
arg.lineLengthProp=true;
arg.intensityRange=[0 0];
arg.anisotropyRange=[0 1];
arg.orientationRange=[0 180];
arg.excludeAboveOrientation=false;
arg.referenceOrientation=0;
arg.glyphColor='green';
arg.glyphLineWidth=2;
arg.roiX=0; % roiX is an array of X-coordinates that define polygon.
arg.roiY=0; % roiY is Y-coordinates of the polygon.
arg.zoomROI=false;
arg.scalePix=1/0.07;
arg.xdata=[1 size(drawParticlesOn,2)];
arg.ydata=[1 size(drawParticlesOn,1)];
arg.anisoScaleLocation=10;
arg.anisoScaleFont=20;
arg.clims=NaN; % display range for intensity image. Auto: NaN, RGB: 0, quantile of intensity data: [lowerfraction upperfraction], absolute intensity range: [lowerIntensity upperIntensity].
arg.exportMovie=true;
arg.simulatedData=false;
arg.trackLength=0; % If 0, no track is shown. If N, positions of particles over last N frames are plotted as tracks. If inf, all past positions
arg.trackColor='magenta';
arg.highlightTrack=NaN;
arg.frameRange=1:size(xPart,2);
arg.hAxisIntensity=NaN;
arg.cmap=gray(512);
arg=parsepropval(arg,varargin{:});
if( ishandle(arg.Parent) )
hAxisOverlay=arg.Parent;
else
hAxisOverlay=axes();
set(gcf,'color','w');
end
cla;
% Select particles based on intensity.
if all(arg.intensityRange)
intensityMask=intPart>arg.intensityRange(1) & intPart<arg.intensityRange(2);
else
intensityMask=~isnan(intPart); %NaNs in intPart matrix are excluded.
arg.intensityRange=[min(~isnan(intPart)) max(~isnan(intPart))];
end
% Select based on anisotropy.
anisotropyMask=(anisoPart >= arg.anisotropyRange(1) ) & ...
(anisoPart <= arg.anisotropyRange(2) );
% Select based on orientation.
% Convert to radians.
arg.orientationRange=arg.orientationRange*(pi/180);
orientPartFilter=mod(orientPart-arg.referenceOrientation,pi);
% The orientation w.r.t. reference is used to select what particles are
% drawn.
% But, the particle orientation must not be changed.
orientationMask= (orientPartFilter > arg.orientationRange(1)) & ...
(orientPartFilter < arg.orientationRange(2));
if(arg.excludeAboveOrientation) % Exclude above orientation.
orientationMask=~orientationMask;
end
if(all(arg.roiX) && all(arg.roiY))
roiMask=inpolygon(xPart,yPart,arg.roiX,arg.roiY);
else
roiMask=true(size(xPart));
end
%
useParticles=intensityMask & anisotropyMask & orientationMask & roiMask;
xPart(~useParticles)=NaN;
yPart(~useParticles)=NaN;
anisoPart(~useParticles)=NaN;
orientPart(~useParticles)=NaN;
if(isnan(arg.clims)) % determine the clims from data.
if(size(drawParticlesOn,3)==3)
warning('Assuming 3 frames and not a single RGB frame. If particles are to be drawn on RBG data, use ''clims'',0.');
end
clims=[quantile(drawParticlesOn(:),0.001) quantile(drawParticlesOn(:),0.9995)];
elseif(length(arg.clims)==2 && all(arg.clims<=1)) % clims are quantile range.
clims=[quantile(drawParticlesOn(:),arg.clims(1)) quantile(drawParticlesOn(:),arg.clims(2))];
else
clims=arg.clims;
end
for frameno=arg.frameRange
if(any(clims)) % gray image.
[xlims,ylims]=drawImage(arg.xdata,arg.ydata,drawParticlesOn(:,:,frameno),[hAxisOverlay arg.hAxisIntensity],arg.roiX,arg.roiY,clims,arg.scalePix,arg.zoomROI,arg.simulatedData,arg.cmap);
else %color image.
[xlims,ylims]=drawImage(arg.xdata,arg.ydata,drawParticlesOn(:,:,:,frameno),[hAxisOverlay arg.hAxisIntensity],arg.roiX,arg.roiY,clims,arg.scalePix,arg.zoomROI,arg.simulatedData,arg.cmap);
end
particlesToDraw=useParticles(:,frameno)';
xcen=xPart(:,frameno)'.*particlesToDraw;
ycen=yPart(:,frameno)'.*particlesToDraw;
orientcen=orientPart(:,frameno)'.*particlesToDraw;
% intead of (X-,Y-) to (X+,Y+) we need to do (X-,Y+), (X+,Y-), since Y
% axis runs from top to bottom, whereas we perceive and measure angle
% assuming Y running from bottom to top.
axes(hAxisOverlay); % Draw the particles on overlay axes.
hold on;
% Draw tracks.
if(arg.trackLength && frameno>2)
startTracks=frameno-arg.trackLength;
if(startTracks<1)
startTracks=1;
end
tracksX=xPart(particlesToDraw,startTracks:frameno)';
tracksY=yPart(particlesToDraw,startTracks:frameno)';
line (tracksX,tracksY,'color',arg.trackColor,'LineWidth',arg.glyphLineWidth);
% if(~isnan(arg.highlightTrack))
% tracksX=xPart(arg.highlightTrack,startTracks:frameno)';
% tracksY=yPart(arg.highlightTrack,startTracks:frameno)';
% line (tracksX,tracksY,'color',arg.trackColor,'LineWidth',2*arg.glyphLineWidth);
% end
end
% Draw particles and anisotropy lines.
if(arg.lineLength)
% since particles can have a wide range of intensities, it is not a
% good idea to scale line lengths with intensity.
lineL=0.5*arg.lineLength; % Half the line length;
if(arg.lineLengthProp)
lineLParticles=bsxfun(@times,lineL,anisoPart(:,frameno)');
end
LineXstart=xcen-lineLParticles.*cos(orientcen); LineXend=xcen+lineLParticles.*cos(orientcen);
if(arg.simulatedData) % For simulated data, images are plotted in XY grid and there is no need to flip the Y axis.
LineYstart=ycen-lineLParticles.*sin(orientcen); LineYend=ycen+lineLParticles.*sin(orientcen);
else % For experimental data, Y-axis runs from top to bottom, but we read orientaiton bottom to top. So flip the Y-axis when calculatint line.
LineYstart=ycen+lineLParticles.*sin(orientcen); LineYend=ycen-lineLParticles.*sin(orientcen);
end
%%quiver(xcen,ycen,cos(orientcen),sin(orientcen),0,'ShowArrowHead','off','AutoScale','on','Marker','o');
% if(isempty(arg.glyphColor))
% line([LineXstart;LineXend],[LineYstart;LineYend],'LineWidth',arg.glyphLineWidth); % Auto-color the lines.
% else
line([LineXstart;LineXend],[LineYstart;LineYend],'color',arg.glyphColor,'LineWidth',arg.glyphLineWidth);
% end
if(arg.anisoScaleLocation)
% line([2 2*lineL+2],[2 2],'color',arg.glyphColor,'LineWidth',4);
% text(2,-8,'polarization factor=1','FontSize',arg.anisoScaleFont);
line([xlims(1)+1 2*lineL+xlims(1)+1],[ylims(1)+arg.anisoScaleLocation ylims(1)+arg.anisoScaleLocation],'color',arg.glyphColor,'LineWidth',4);
end
end
plot(xcen,ycen,'.','MarkerEdgeColor',arg.glyphColor,'MarkerSize',arg.glyphDiameter,'LineWidth',arg.glyphLineWidth); %'LineWidth',arg.glyphLineWidth
if(~isnan(arg.highlightTrack))
plot(xcen(arg.highlightTrack),ycen(arg.highlightTrack),'*','MarkerEdgeColor',arg.glyphColor,'MarkerSize',2*arg.glyphDiameter,'LineWidth',arg.glyphLineWidth); %'LineWidth',arg.glyphLineWidth
end
% drawnow; % Make sure figure is updated, before taking a screenshot.
hold off;
if(arg.exportMovie && ishandle(arg.hAxisIntensity))
pause(arg.delay); % Delay so that figure is updated.
axes(hAxisOverlay);
frameOrient=frame2im(getframe(gca)); %getframe is better than screencapture, because it updates the figures before capture.
axes(arg.hAxisIntensity);
frameIntensity=frame2im(getframe(gca));
frameOrient=uint8(imresize(frameOrient,[600 NaN]));
frameIntensity=uint8(imresize(frameIntensity,[600 NaN]));
movOrient(:,:,:,frameno)=cat(2,frameIntensity,frameOrient);
%thisframe=frame2im(getframe(hfigOrient));
elseif(arg.exportMovie)
axes(hAxisOverlay);
frameOrient=frame2im(getframe(gca)); %getframe is better than screencapture, because it updates the figures before capture.
frameOrient=uint8(imresize(frameOrient,[600 NaN]));
movOrient(:,:,:,frameno)=frameOrient;
end
end
end
function [xlims,ylims]=drawImage(xdata,ydata,img,haxes,roiX,roiY,clims,scalePix,zoomROI,simulatedData,cmap,tStamp)
if(all(roiX) && all(roiY) && zoomROI)
xlims=[min(roiX) max(roiX)]; ylims=[min(roiY) max(roiY)];
else
xlims=xdata; ylims=ydata;
end
for idx=1:numel(haxes)
if(ishandle(haxes(idx)))
% imshow(squeeze(img),'XData',xdata,'YData',ydata,'Parent',haxes(idx),'InitialMagnification','fit');
% colormap(cmap);
imagesc(squeeze(img),'Parent',haxes(idx));
if(any(clims)) % For gray image.
set(haxes(idx),'CLim',clims);
end
if(simulatedData)
axis xy;
end
ylim([ydata(1)-20 ydata(end)]);
set(haxes(idx),'XTick',[],'YTick',[]);
hold on;
if(~zoomROI)
plot([roiX; roiX(1)],[roiY; roiY(1)],'--w','Linewidth',1.5);
end
xlim(xlims); ylim(ylims);
set(haxes(idx),'xlim',xlims,'ylim',ylims);
if(scalePix)
% line([xlims(1)+2 xlims(1)+2+scalePix],[ylims(2)-2 ylims(2)-2],'color','w','LineWidth',5,'Parent',haxes(idx));
addscalebar(1,scalePix,'Parent',haxes(idx));
end
hold off;
end
end
end
|
github
|
mehta-lab/Instantaneous-PolScope-master
|
checkRTFP.m
|
.m
|
Instantaneous-PolScope-master/MehtaetalPNAS2016/@instantPolGUI/checkRTFP.m
| 6,894 |
utf_8
|
b431e574bf27bbccf599756a0860707a
|
function checkRTFP(me,eventType,I0in,I45in,I90in,I135in,Anisotropyin,Orientationin,Averagein,varargin)
persistent I0 I45 I90 I135 Anisotropy Orientation Average;
% If error occurs in the very first call to the funciton (when file is selected), these persistent
% variables are not set.
% Also when this file is modified. Persistent variables are cleared.
% Choice of file/plotting of images appears to work. Focus on blinking analysis.
switch(eventType)
%% Store new data in persistent variables.
case 'newData'
I0=I0in;
I45=I45in;
I90=I90in;
I135=I135in;
Anisotropy=Anisotropyin;
Orientation=Orientationin;
Average=Averagein;
%% Respond to updates in the frame counters by drawing images or graphs.
case 'frameUpdate'
delete(get(me.hQuad.panelImgs,'Children'));
% Get the parameters.
frame=get(me.hQuad.frameNo,'Value');
frame=int16(frame);
if(~frame)
return;
end
if isfield(me.hQuad,'blinkRange') && ishandle(me.hQuad.blinkRange)
framerange=get(me.hQuad.blinkRange,'Value');
else
framerange=NaN;
end
% Parameters may be updated in GUI. Get the latest.
checkParams=me.hData.PGParams.GetPropertyValues();
if(checkParams.colorCeiling>checkParams.anisoCeiling)
checkParams.colorCeiling=checkParams.anisoCeiling;
me.hData.PGParams.UpdateFields({'colorCeiling'},{checkParams.anisoCeiling});
end
% Execute according to chosen analysis type.
switch(get(me.hQuad.selectAnalysis,'Value'))
case 1 %'ROI Histogram'
histFlag=get(me.hQuad.histMolecule,'value');
if(histFlag) % If molecular histogram is required, ROI needs to be selected.
set(me.hQuad.analyzeROI,'value',true);
end
roiFlag=get(me.hQuad.analyzeROI,'value');
if(histFlag)
statType='Molecule';
radialRange=NaN;
else
statType='PixelAnisotropy';
radialRange=[0 1];
end
hROI=interactivePolHist(I0(:,:,frame),I45(:,:,frame),I90(:,:,frame),I135(:,:,frame),...
Anisotropy(:,:,frame),Orientation(:,:,frame),Average(:,:,frame),...
'avgCeiling',checkParams.avgCeiling,'anisoCeiling',checkParams.colorCeiling,...
'Parent',me.hQuad.panelImgs,'analyzeROI',roiFlag,'Statistic',statType,...
'orientationRelativeToROI',get(me.hQuad.orientationRelativeToROI,'value'),'showColorbar',false);
case 2 %'Blinking'
% Once working, move the drawing of UI components to
% setupQuickCheckAnalysis so that these handles persist.
me.hQuad.axesImage=axes('Parent',me.hQuad.panelImgs,'Position',[0.02 0.02 0.45 0.95]);
me.hQuad.axesRaw=axes('Parent',me.hQuad.panelImgs,'Position',[0.5 0.5 0.42 0.4]);
me.hQuad.axesComputed=axes('Parent',me.hQuad.panelImgs,'Position',[0.5 0.05 0.42 0.4]);
maxframes=get(me.hQuad.frameNo,'Max');
I0blink=NaN(1,maxframes);
I45blink=NaN(1,maxframes);
I90blink=NaN(1,maxframes);
I135blink=NaN(1,maxframes);
Anisoblink=NaN(1,maxframes);
Orientblink=NaN(1,maxframes);
Iblink=NaN(1,maxframes);
% Identify the range to analyze.
startframe=frame-floor(0.5*framerange);
endframe=frame+floor(0.5*framerange);
if(startframe<1);
startframe=1;
end
if(endframe>maxframes)
endframe=maxframes;
end
ImBlink=Average(:,:,frame);
Ilims=[quantile(ImBlink(:),0.1) quantile(ImBlink(:),0.98)];
axes(me.hQuad.axesImage);
im=imagesc(ImBlink,Ilims);
axis equal; axis tight;
hold on;
resultsTable=table();
currentresult=table();
% Compute necessary variables and assign a call back for blink
% analysis to ButtonDownFcn.
[xx,yy]=meshgrid(1:size(Average,2),1:size(Average,1));
psfR=round((0.61*me.RTFP.Wavelength/me.RTFP.ObjectiveNA)/me.RTFP.PixSize);
set(im,'ButtonDownFcn',@doblinkAnalysis,'hittest','on');
end
end
function doblinkAnalysis(src,evt)
persistent hLine;
cp=get(me.hQuad.axesImage,'CurrentPoint');
xcen=round(cp(1,1));
ycen=round(cp(1,2));
set(get(me.hQuad.axesImage,'title'),'string',['(x,y)=' num2str([xcen ycen])]);
% Generate mask the size of PSF around chosen point.
particleMask=sqrt((xx-xcen).^2 + (yy-ycen).^2)<=psfR+0.5;
[maskY,maskX]=find(particleMask);
if(ishandle(hLine))
delete(hLine);
end
hLine=plot(maskX,maskY,'g.');
% Populate the raw intensities with results.
for frameno=startframe:endframe
I0frame=I0(:,:,frameno);
I135frame=I135(:,:,frameno);
I90frame=I90(:,:,frameno);
I45frame=I45(:,:,frameno);
I0blink(frameno)=sum(I0frame(particleMask));
I45blink(frameno)=sum(I45frame(particleMask));
I90blink(frameno)=sum(I90frame(particleMask));
I135blink(frameno)=sum(I135frame(particleMask));
end
% Compute anisotropy, orientation, and intensity accounting for
% calibration.
particleBG=numel(maskY)*checkParams.BGiso;
[Orientblink,Anisoblink,Iblink]=ComputeFluorAnisotropy(...
I0blink,I45blink,I90blink,I135blink,'anisotropy','BlackLevel',me.RTFP.BlackLevel,...
'BGiso',particleBG,'anisoCeiling',checkParams.anisoCeiling,...
'ItoSMatrix',me.RTFP.ItoSMatrix);
% Update the plots.
axes(me.hQuad.axesRaw);
plot(1:maxframes,cat(1,I0blink-I90blink,I45blink-I135blink),...,I90blink-particleBG,I135blink-particleBG),...
'LineWidth',2);
set(me.hQuad.axesRaw,'xlim',[startframe-1 endframe+1]);
%legend({'I0','I45','I90','I135'},'Location','NorthEast');
legend({'I0-I90','I45-I135'},'Location','NorthEast');
xlabel('frame #');
axes(me.hQuad.axesComputed);
anisoPlot=100*Anisoblink/checkParams.anisoCeiling;
orientPlot=(180/pi)*Orientblink;
plot(1:maxframes,cat(1,anisoPlot,orientPlot),'LineWidth',2);
set(me.hQuad.axesComputed,'xlim',[startframe-1 endframe+1],'ylim',[0 180]);
legend({'aniso*100','\phi (degree)'},'Location','NorthEast');
xlabel('frame #');
end
end
|
github
|
CheckPointSW/labeless-master
|
member_pointer_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/member_pointer_runme.m
| 922 |
utf_8
|
5d65cb03abdda4efc4dd89ee739e27b6
|
# Example using pointers to member functions
member_pointer
function check(what,expected,actual)
if (expected != actual)
error ("Failed: %s, Expected: %f, Actual: %f",what,expected,actual);
endif
end
# Get the pointers
area_pt = areapt;
perim_pt = perimeterpt;
# Create some objects
s = Square(10);
# Do some calculations
check ("Square area ", 100.0, do_op(s,area_pt));
check ("Square perim", 40.0, do_op(s,perim_pt));
memberPtr = cvar.areavar;
memberPtr = cvar.perimetervar;
# Try the variables
check ("Square area ", 100.0, do_op(s,cvar.areavar));
check ("Square perim", 40.0, do_op(s,cvar.perimetervar));
# Modify one of the variables
cvar.areavar = perim_pt;
check ("Square perimeter", 40.0, do_op(s,cvar.areavar));
# Try the constants
memberPtr = AREAPT;
memberPtr = PERIMPT;
memberPtr = NULLPT;
check ("Square area ", 100.0, do_op(s,AREAPT));
check ("Square perim", 40.0, do_op(s,PERIMPT));
|
github
|
CheckPointSW/labeless-master
|
director_basic_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/director_basic_runme.m
| 1,734 |
utf_8
|
b6b47f50cd7b79dce886ca9a71659d86
|
director_basic
function self=OctFoo()
global director_basic;
self=subclass(director_basic.Foo());
self.ping=@OctFoo_ping;
end
function string=OctFoo_ping(self)
string="OctFoo::ping()";
end
a = OctFoo();
if (!strcmp(a.ping(),"OctFoo::ping()"))
error(a.ping())
endif
if (!strcmp(a.pong(),"Foo::pong();OctFoo::ping()"))
error(a.pong())
endif
b = director_basic.Foo();
if (!strcmp(b.ping(),"Foo::ping()"))
error(b.ping())
endif
if (!strcmp(b.pong(),"Foo::pong();Foo::ping()"))
error(b.pong())
endif
a = director_basic.A1(1);
if (a.rg(2) != 2)
error
endif
function self=OctClass()
global director_basic;
self=subclass(director_basic.MyClass());
self.method=@OctClass_method;
self.vmethod=@OctClass_vmethod;
end
function OctClass_method(self,vptr)
self.cmethod = 7;
end
function out=OctClass_vmethod(self,b)
b.x = b.x + 31;
out=b;
end
b = director_basic.Bar(3);
d = director_basic.MyClass();
c = OctClass();
cc = director_basic.MyClass_get_self(c);
dd = director_basic.MyClass_get_self(d);
bc = cc.cmethod(b);
bd = dd.cmethod(b);
cc.method(b);
if (c.cmethod != 7)
error
endif
if (bc.x != 34)
error
endif
if (bd.x != 16)
error
endif
function self=OctMulti()
global director_basic;
self=subclass(director_basic.Foo(),director_basic.MyClass());
self.vmethod=@OctMulti_vmethod;
self.ping=@OctMulti_ping;
end
function out=OctMulti_vmethod(self,b)
b.x = b.x + 31;
out=b;
end
function out=OctMulti_ping(self)
out="OctFoo::ping()";
end
a = 0;
for i=0:100,
octmult = OctMulti();
octmult.pong();
clear octmult
endfor
octmult = OctMulti();
p1 = director_basic.Foo_get_self(octmult);
p2 = director_basic.MyClass_get_self(octmult);
p1.ping();
p2.vmethod(bc);
|
github
|
CheckPointSW/labeless-master
|
director_string_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/director_string_runme.m
| 456 |
utf_8
|
253061c50e9f69d1d7f90b0bf7c64b21
|
director_string
function out=get_first(self)
out = strcat(self.A.get_first()," world!");
end
function process_text(self,string)
self.A.process_text(string);
self.smem = "hello";
end
B=@(string) subclass(A(string),'get_first',@get_first,'process_text',@process_text);
b = B("hello");
b.get(0);
if (!strcmp(b.get_first(),"hello world!"))
error(b.get_first())
endif
b.call_process_func();
if (!strcmp(b.smem,"hello"))
error(b.smem)
endif
|
github
|
CheckPointSW/labeless-master
|
voidtest_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/voidtest_runme.m
| 489 |
utf_8
|
e8f18ed9dcf24d5fabce570c881dde59
|
voidtest
voidtest.globalfunc();
f = voidtest.Foo();
f.memberfunc();
voidtest.Foo_staticmemberfunc();
function fvoid()
end
try
a = f.memberfunc();
catch
end_try_catch
try
a = fvoid();
catch
end_try_catch
v1 = voidtest.vfunc1(f);
v2 = voidtest.vfunc2(f);
if (swig_this(v1) != swig_this(v2))
error
endif
v3 = voidtest.vfunc3(v1);
if (swig_this(v3) != swig_this(f))
error
endif
v4 = voidtest.vfunc1(f);
if (swig_this(v4) != swig_this(v1))
error
endif
v3.memberfunc();
|
github
|
CheckPointSW/labeless-master
|
director_detect_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/director_detect_runme.m
| 659 |
utf_8
|
ed20d6fcffc7c81a27de292afc945862
|
director_detect
global MyBar=@(val=2) \
subclass(director_detect.Bar(),'val',val,@get_value,@get_class,@just_do_it,@clone);
function val=get_value(self)
self.val = self.val + 1;
val = self.val;
end
function ptr=get_class(self)
global director_detect;
self.val = self.val + 1;
ptr=director_detect.A();
end
function just_do_it(self)
self.val = self.val + 1;
end
function ptr=clone(self)
global MyBar;
ptr=MyBar(self.val);
end
b = MyBar();
f = b.baseclass();
v = f.get_value();
a = f.get_class();
f.just_do_it();
c = b.clone();
vc = c.get_value();
if ((v != 3) || (b.val != 5) || (vc != 6))
error("Bad virtual detection")
endif
|
github
|
CheckPointSW/labeless-master
|
preproc_constants_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/preproc_constants_runme.m
| 533 |
utf_8
|
917a1bdadc03d5ce92d7468e9c4c81b2
|
preproc_constants
assert(CONST_INT1, 10)
assert(CONST_DOUBLE3, 12.3)
assert(CONST_BOOL1, true)
assert(CONST_CHAR, 'x')
assert(CONST_STRING1, "const string")
# Test global constants can be seen within functions
function test_global()
global CONST_INT1
global CONST_DOUBLE3
global CONST_BOOL1
global CONST_CHAR
global CONST_STRING1
assert(CONST_INT1, 10)
assert(CONST_DOUBLE3, 12.3)
assert(CONST_BOOL1, true)
assert(CONST_CHAR, 'x')
assert(CONST_STRING1, "const string")
endfunction
test_global
|
github
|
CheckPointSW/labeless-master
|
director_classic_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/director_classic_runme.m
| 2,411 |
utf_8
|
168e96aff7298695046a230adc01e911
|
director_classic
TargetLangPerson=@() subclass(Person(),'id',@(self) "TargetLangPerson");
TargetLangChild=@() subclass(Child(),'id',@(self) "TargetLangChild");
TargetLangGrandChild=@() subclass(GrandChild(),'id',@(self) "TargetLangGrandChild");
# Semis - don't override id() in target language
TargetLangSemiPerson=@() subclass(Person());
TargetLangSemiChild=@() subclass(Child());
TargetLangSemiGrandChild=@() subclass(GrandChild());
# Orphans - don't override id() in C++
TargetLangOrphanPerson=@() subclass(OrphanPerson(),'id',@(self) "TargetLangOrphanPerson");
TargetLangOrphanChild=@() subclass(OrphanChild(),'id',@(self) "TargetLangOrphanChild");
function check(person,expected)
global Caller;
# Normal target language polymorphic call
ret = person.id();
if (ret != expected)
raise ("Failed. Received: " + ret + " Expected: " + expected);
endif
# Polymorphic call from C++
caller = Caller();
caller.setCallback(person);
ret = caller.call();
if (ret != expected)
error ("Failed. Received: " + ret + " Expected: " + expected);
endif
# Polymorphic call of object created in target language and passed to C++ and back again
baseclass = caller.baseClass();
ret = baseclass.id();
if (ret != expected)
error ("Failed. Received: " + ret + " Expected: " + expected);
endif
caller.resetCallback();
end
person = Person();
check(person, "Person");
clear person;
person = Child();
check(person, "Child");
clear person;
person = GrandChild();
check(person, "GrandChild");
clear person;
person = TargetLangPerson();
check(person, "TargetLangPerson");
clear person;
person = TargetLangChild();
check(person, "TargetLangChild");
clear person;
person = TargetLangGrandChild();
check(person, "TargetLangGrandChild");
clear person;
# Semis - don't override id() in target language
person = TargetLangSemiPerson();
check(person, "Person");
clear person;
person = TargetLangSemiChild();
check(person, "Child");
clear person;
person = TargetLangSemiGrandChild();
check(person, "GrandChild");
clear person;
# Orphans - don't override id() in C++
person = OrphanPerson();
check(person, "Person");
clear person;
person = OrphanChild();
check(person, "Child");
clear person;
person = TargetLangOrphanPerson();
check(person, "TargetLangOrphanPerson");
clear person;
person = TargetLangOrphanChild();
check(person, "TargetLangOrphanChild");
clear person;
|
github
|
CheckPointSW/labeless-master
|
li_std_vector_enum_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/li_std_vector_enum_runme.m
| 376 |
utf_8
|
3915e1d2851c46706f5ee2878da627c4
|
li_std_vector_enum
function check(a, b)
if (a != b)
error("incorrect match");
endif
end
ev = EnumVector();
check(ev.nums(0), 10);
check(ev.nums(1), 20);
check(ev.nums(2), 30);
it = ev.nums.begin();
v = it.value();
check(v, 10);
it.next();
v = it.value();
check(v, 20);
#expected = 10
#ev.nums.each do|val|
# swig_assert(val == expected)
# expected += 10
#end
|
github
|
CheckPointSW/labeless-master
|
exception_order_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/exception_order_runme.m
| 898 |
utf_8
|
a9559c0998ed1178eef715d5314f32e1
|
exception_order
function check_lasterror(expected)
if (!strcmp(lasterror.message, expected))
# Take account of older versions prefixing with "error: " and adding a newline at the end
if (!strcmp(regexprep(lasterror.message, 'error: (.*)\n$', '$1'), expected))
error(["Bad exception order. Expected: \"", expected, "\" Got: \"", lasterror.message, "\""])
endif
endif
endfunction
a = A();
try
a.foo()
catch
check_lasterror("C++ side threw an exception of type E1")
end_try_catch
try
a.bar()
catch
check_lasterror("C++ side threw an exception of type E2")
end_try_catch
try
a.foobar()
catch
check_lasterror("postcatch unknown (SWIG_RuntimeError)")
end_try_catch
try
a.barfoo(1)
catch
check_lasterror("C++ side threw an exception of type E1")
end_try_catch
try
a.barfoo(2)
catch
check_lasterror("C++ side threw an exception of type E2 *")
end_try_catch
|
github
|
CheckPointSW/labeless-master
|
director_abstract_runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/test-suite/octave/director_abstract_runme.m
| 993 |
utf_8
|
010e2a8f3e12a660ec6f6b89f629f5fd
|
director_abstract
MyFoo=@() subclass(director_abstract.Foo(),@ping);
function out=ping(self)
out="MyFoo::ping()";
end
a = MyFoo();
if (!strcmp(a.ping(),"MyFoo::ping()"))
error(a.ping())
endif
if (!strcmp(a.pong(),"Foo::pong();MyFoo::ping()"))
error(a.pong())
endif
MyExample1=@() subclass(director_abstract.Example1(),'Color',@(self,r,g,b) r);
MyExample2=@(a,b) subclass(director_abstract.Example2(a,b),'Color',@(self,r,g,b) g);
MyExample3=@() subclass(director_abstract.Example3_i(),'Color',@(self,r,g,b) b);
me1 = MyExample1();
if (director_abstract.Example1.get_color(me1, 1,2,3) != 1)
error
endif
me2 = MyExample2(1,2);
if (me2.get_color(me2, 1,2,3) != 2)
error
endif
me3 = MyExample3();
if (me3.get_color(me3, 1,2,3) != 3)
error
endif
# don't check that we cannot construct abstract bases, since we have no
# way of disambiguating that with the normal construction case using
# subclass. furthermore, calling a pure virtual method will still generate
# an error.
|
github
|
CheckPointSW/labeless-master
|
runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/octave/class/runme.m
| 1,017 |
utf_8
|
402733d5ff5c5f0ec147a476914de00a
|
# file: runme.m
# This file illustrates the proxy class C++ interface generated
# by SWIG.
swigexample
# ----- Object creation -----
printf("Creating some objects:\n");
c = swigexample.Circle(10)
s = swigexample.Square(10)
# ----- Access a static member -----
printf("\nA total of %i shapes were created\n", swigexample.Shape.nshapes);
# ----- Member data access -----
# Set the location of the object
c.x = 20
c.y = 30
s.x = -10
s.y = 5
printf("\nHere is their current position:\n");
printf(" Circle = (%f, %f)\n",c.x,c.y);
printf(" Square = (%f, %f)\n",s.x,s.y);
# ----- Call some methods -----
printf("\nHere are some properties of the shapes:\n");
function print_shape(o)
o
printf(" area = %f\n", o.area());
printf(" perimeter = %f\n", o.perimeter());
end;
print_shape(c);
print_shape(s);
printf("\nGuess I'll clean up now\n");
# Note: this invokes the virtual destructor
clear c
clear s
printf("%i shapes remain\n", swigexample.Shape.nshapes);
printf("Goodbye\n");
|
github
|
CheckPointSW/labeless-master
|
runme.m
|
.m
|
labeless-master/3rdparty/swigwin-3.0.2/Examples/octave/module_load/runme.m
| 1,662 |
utf_8
|
383122eccc45eeee51c841b36eab5129
|
# file: runme_args.m
# load module
clear all;
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
clear all
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
clear all
# load module in a function globally before base context
clear all;
function testme
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
endfunction
testme
testme
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
clear all
function testme
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
endfunction
testme
testme
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
clear all
# load module in a function globally after base context
clear all;
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
function testme
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
endfunction
testme
testme
clear all
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
function testme
swigexample;
assert(cvar.ivar == ifunc);
assert(exist("swigexample","var"));
endfunction
testme
testme
clear all
# octave 3.0.5 randomly crashes on the remaining tests, so skip them
api_version = sscanf(octave_config_info("api_version"), "api-v%i");
if api_version < 37
exit
endif
# load module with no cvar
clear all;
swigexample2;
assert(swigexample2.ivar == ifunc);
assert(exist("swigexample2","var"));
assert(!isglobal("cvar"))
clear all
swigexample2;
assert(swigexample2.ivar == ifunc);
assert(exist("swigexample2","var"));
assert(!isglobal("cvar"))
clear all
|
github
|
fquitin/energy_detection_system-master
|
read_int_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/read_int_binary.m
| 1,206 |
utf_8
|
ad5f11d74e447e5a86fc682db3eba8f3
|
%
% Copyright 2001,2002 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function v = read_int_binary (filename, count)
%% usage: read_int_binary (filename, [count])
%%
%% open filename and return the contents, treating them as
%% signed integers
%%
m = nargchk (1,2,nargin);
if (m)
usage (m);
end
if (nargin < 2)
count = Inf;
end
f = fopen (filename, 'rb');
if (f < 0)
v = 0;
else
v = fread (f, count, 'uint32');
fclose (f);
end
end
|
github
|
fquitin/energy_detection_system-master
|
read_short_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/read_short_binary.m
| 1,203 |
utf_8
|
074f9adf08a57572fff63418fe78ee9b
|
%
% Copyright 2001 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function v = read_short_binary (filename, count)
%% usage: read_short_binary (filename, [count])
%%
%% open filename and return the contents, treating them as
%% signed short integers
%%
m = nargchk (1,2,nargin);
if (m)
usage (m);
end
if (nargin < 2)
count = Inf;
end
f = fopen (filename, 'rb');
if (f < 0)
v = 0;
else
v = fread (f, count, 'short');
fclose (f);
end
|
github
|
fquitin/energy_detection_system-master
|
write_char_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/write_char_binary.m
| 314 |
utf_8
|
7d86f60d5b9f759312a2bb9f087e02f4
|
%
%
% Adam Gannon - 2014
function v = write_char_binary (data, filename)
% usage: write_char_binary (data, filename)
%
% open filename and write data to it as 8 bit chars
%
f = fopen (filename, 'wb');
if (f < 0)
v = 0;
else
v = fwrite (f, data, 'char');
fclose (f);
end
end
|
github
|
fquitin/energy_detection_system-master
|
read_char_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/read_char_binary.m
| 1,193 |
utf_8
|
2533746db69e6dbbb238d70666393254
|
%
% Copyright 2001 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function v = read_char_binary (filename, count)
%% usage: read_char (filename, [count])
%%
%% open filename and return the contents, treating them as
%% signed short integers
%%
m = nargchk (1,2,nargin);
if (m)
usage (m);
end
if (nargin < 2)
count = Inf;
end
f = fopen (filename, 'rb');
if (f < 0)
v = 0;
else
v = fread (f, count, 'char');
fclose (f);
end
|
github
|
fquitin/energy_detection_system-master
|
read_byte_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/read_byte_binary.m
| 1,185 |
utf_8
|
e27639238ea59610b43bddd1a5800856
|
%
% Copyright 2001 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function v = read_char_binary (filename, count)
%% usage: read_char (filename, [count])
%%
%% open filename and return the contents, treating them as
%% signed short integers
%%
m = nargchk (1,2,nargin);
if (m)
usage (m);
end
if (nargin < 2)
count = Inf;
end
f = fopen (filename, 'rb');
if (f < 0)
v = 0;
else
v = fread (f, count);
fclose (f);
end
|
github
|
fquitin/energy_detection_system-master
|
write_int_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/write_int_binary.m
| 315 |
utf_8
|
f9d2275d36cf037a6885986b114b9f61
|
%
%
% Adam Gannon - 2014
function v = write_int_binary (data, filename)
% usage: write_int_binary (data, filename)
%
% open filename and write data to it as signed integers
%
f = fopen (filename, 'wb');
if (f < 0)
v = 0;
else
v = fwrite (f, data, 'int');
fclose (f);
end
end
|
github
|
fquitin/energy_detection_system-master
|
read_complex_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/read_complex_binary.m
| 1,304 |
utf_8
|
66da98f4761fa283039a67c2ce01c499
|
%
% Copyright 2001 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function v = read_complex_binary (filename, count)
% usage: read_complex_binary (filename, [count])
%
% open filename and return the contents as a column vector,
% treating them as 32 bit complex numbers
%
m = nargchk (1,2,nargin);
if (m)
usage (m);
end
if (nargin < 2)
count = Inf;
end
f = fopen (filename, 'rb');
if (f < 0)
v = 0;
else
t = fread (f, [2, count], 'float');
fclose (f);
v = t(1,:) + t(2,:)*i;
[r, c] = size (v);
v = reshape (v, c, r);
end
|
github
|
fquitin/energy_detection_system-master
|
write_short_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/write_short_binary.m
| 327 |
utf_8
|
45a92300b9500b033e43717fa3c83aa2
|
%
%
% Adam Gannon - 2014
function v = write_short_binary (data, filename)
% usage: write_short_binary (data, filename)
%
% open filename and write data to it as signed short integers
%
f = fopen (filename, 'wb');
if (f < 0)
v = 0;
else
v = fwrite (f, data, 'short');
fclose (f);
end
end
|
github
|
fquitin/energy_detection_system-master
|
write_float_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/write_float_binary.m
| 1,072 |
utf_8
|
e5192508304227befdf8383e37067596
|
%
% Copyright 2001 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function v = write_float_binary (data, filename)
% usage: write_float_binary (data, filename)
%
% open filename and write data to it as 32 bit floats
%
f = fopen (filename, 'wb');
if (f < 0)
v = 0;
else
v = fwrite (f, data, 'float');
fclose (f);
end
end
|
github
|
fquitin/energy_detection_system-master
|
write_complex_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/write_complex_binary.m
| 1,224 |
utf_8
|
644708692f6c221368c5bb62ca270819
|
%
% Copyright 2001 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function ret = write_complex_binary (data, filename)
% usage: write_complex_binary (data, filename)
%
% open filename and write the contents of a complex column vector
% 32 bit complex number
%
m = nargchk (2,2,nargin);
if (m)
usage (m);
end
f = fopen (filename, 'wb');
if (f < 0)
ret = -1;
else
I = real(data);
Q = imag(data);
fwrite (f, [I Q].', 'float');
ret = fclose (f);
end
|
github
|
fquitin/energy_detection_system-master
|
plotdat.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/plotdat.m
| 258 |
utf_8
|
9d31ac3cefebeb526ef71988ce083bbd
|
%
%
% Plot a complex vector versus its index (default is I vs Q)
function handle = plotdat(vec,plotIm)
if (nargin<2)
plotIm = false;
end
handle = figure;
if (plotIm)
plot(1:length(vec),imag(vec));
else
plot(1:length(vec),real(vec));
end
end
|
github
|
fquitin/energy_detection_system-master
|
read_float_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/read_float_binary.m
| 1,195 |
utf_8
|
5bd133b4dc06135dd9a04eeb712c75aa
|
%
% Copyright 2001 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function v = read_float_binary (filename, count)
%% usage: read_float_binary (filename, [count])
%%
%% open filename and return the contents, treating them as
%% 32 bit floats
%%
m = nargchk (1,2,nargin);
if (m)
usage (m);
end
if (nargin < 2)
count = Inf;
end
f = fopen (filename, 'rb');
if (f < 0)
v = 0;
else
v = fread (f, count, 'float');
fclose (f);
end
|
github
|
fquitin/energy_detection_system-master
|
read_complex_binary_2.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/read_complex_binary_2.m
| 1,306 |
utf_8
|
1c70e8baea6a2f3193e8337dccd3ea24
|
%
% Copyright 2001 Free Software Foundation, Inc.
%
% This file is part of GNU Radio
%
% GNU Radio is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3, or (at your option)
% any later version.
%
% GNU Radio is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with GNU Radio; see the file COPYING. If not, write to
% the Free Software Foundation, Inc., 51 Franklin Street,
% Boston, MA 02110-1301, USA.
%
function v = read_complex_binary_2 (filename, count)
% usage: read_complex_binary (filename, [count])
%
% open filename and return the contents as a column vector,
% treating them as 32 bit complex numbers
%
m = nargchk (1,2,nargin);
if (m)
usage (m);
end
if (nargin < 2)
count = Inf;
end
f = fopen (filename, 'rb');
if (f < 0)
v = 0;
else
t = fread (f, [2, count], 'int16');
fclose (f);
v = t(1,:) + t(2,:)*i;
[r, c] = size (v);
v = reshape (v, c, r);
end
|
github
|
fquitin/energy_detection_system-master
|
write_byte_binary.m
|
.m
|
energy_detection_system-master/Matlab/matlab_utils-master/write_byte_binary.m
| 314 |
utf_8
|
e0af62efb365031dec60b7b849b2675d
|
%
%
% Adam Gannon - 2014
function v = write_byte_binary (data, filename)
% usage: write_byte_binary (data, filename)
%
% open filename and write data to it as 8 bit unsigned ints
%
f = fopen (filename, 'wb');
if (f < 0)
v = 0;
else
v = fwrite (f, data);
fclose (f);
end
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
wrf_winds_transform.m
|
.m
|
WRF_Utils-master/wrf_winds_transform.m
| 2,001 |
utf_8
|
7b27a9803d7f086b8483ce948779a4b0
|
function [ Ue, Ve ] = wrf_winds_transform( U, V, COSALPHA, SINALPHA )
% WRF_WINDS_TRANSFORM Transform winds to earth-relative orientation
% Function that will correctly calculate U and V wind components of
% winds given the COSALPHA and SINALPHA variables from WRF output,
% handling the conversion from grid-relative winds to
% earth-relative winds. Normally there is very little difference
% between the two.
%
% Note that this will assume that COSALPHA and SINALPHA will be the
% same for each 2D slice of U and V and so will only use the first
% 2D slice of COSALPHA and SINALPHA. It will also unstagger U and
% V.
sz_U = size(U);
sz_V = size(V);
stag_U = zeros(size(sz_U));
stag_U(1) = 1;
stag_V = zeros(size(sz_V));
stag_V(2) = 1;
if ndims(U) ~= ndims(V) || (~all(size(U) == size(V)) && ~all(size(U)-stag_U == size(V) - stag_V))
E.badinput('U and V should be the same size (they may be left staggered).')
elseif ndims(COSALPHA) ~= ndims(SINALPHA) || ~all(size(COSALPHA) == size(SINALPHA))
E.badinput('COSALPHA and SINALPHA should be the same size')
end
% Unstagger if needed
if size(U,1)-1 == size(V,1)
U = unstagger(U,1);
end
if size(V,2)-1 == size(U,2)
V = unstagger(V,2);
end
% Warn if the alphas have dimensions that won't be used
if ndims(COSALPHA) > 2 || ndims(SINALPHA) > 2 %#ok<*ISMAT>
warning('Only the first 2D slice of COSALPHA and SINALPHA will be used - this is assumed to be unchanged for all the WRF output')
COSALPHA = COSALPHA(:,:,1);
SINALPHA = SINALPHA(:,:,1);
end
% Loop through and apply the transformation to each 2D slice of the
% wind
Ue = nan(size(U));
Ve = nan(size(V));
for a=1:prod(sz_U(3:end))
Ue(:,:,a) = U(:,:,a) .* COSALPHA - V(:,:,a) .* SINALPHA;
Ve(:,:,a) = V(:,:,a) .* COSALPHA + U(:,:,a) .* SINALPHA;
end
end
function M = unstagger(M, dim)
permvec = 1:ndims(M);
permvec(1) = dim;
permvec(dim) = 1;
M = permute(M,permvec);
M = (M(1:end-1,:,:,:,:) + M(2:end,:,:,:,:))/2;
M = permute(M, permvec);
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
compute_wrf_trop_columns.m
|
.m
|
WRF_Utils-master/compute_wrf_trop_columns.m
| 3,101 |
utf_8
|
117f2ba49b7a0816863ea741dce10310
|
function [ trop_no2 ] = compute_wrf_trop_columns( wrf_filename, integration_mode, tropopause )
%COMPUTE_WRF_TROP_COLUMNS Calculate WRF-Chem tropospheric NO2 columns
% TROP_NO2 = COMPUTE_WRF_TROP_COLUMNS( WRF_FILENAME ) calculates NO2
% tropospheric columns in molec./cm^3 for WRF_FILENAME (a path to a WRF
% file that has the variables no2_ndens and zlev - currently this
% restricts it to files preprocessed with slurmrun/run_wrf_output.sh in
% the WRF-nco-tools repo). Integrates up to the tropopause calculated by
% FIND_WRF_TROPOPAUSE().
%
% TROP_NO2 = COMPUTE_WRF_TROP_COLUMNS( WRF_FILENAME, INTEGRATION_MODE )
% controls whether the integration is done by assuming constant number
% density over each box ('box', default) or by mixing ratio over pressure
% using integPr2 from BEHR-core-utils ('mixing_ratio').
%
% TROP_NO2 = COMPUTE_WRF_TROP_COLUMNS( WRF_FILENAME, INTEGRATION_MODE, TROPOPAUSE )
% integrates up to TROPOPAUSE (given in hPa) instead.
E = JLLErrors;
allowed_int_modes = {'box', 'mixing_ratio'};
if ~exist('integration_mode','var') || isempty(integration_mode)
integration_mode = allowed_int_modes{1};
elseif ~ischar(integration_mode) || ~ismember(integration_mode, allowed_int_modes)
E.badinput('INTEGRATION_MODE must be one of: %s', strjoin(allowed_int_modes, ', '));
end
if ~exist('tropopause','var')
tropopause = NaN;
elseif ~isnumeric(tropopause) || ~isscalar(tropopause) || tropopause < 0
E.badinput('TROPOPAUSE must be a positive, scalar number')
end
wi = ncinfo(wrf_filename);
% Rely on error messages from NCREAD() if missing a variable.
wrf_vars = read_file_vars(wrf_filename, integration_mode);
if isnan(tropopause)
daily_tplev = find_wrf_tropopause(wi);
else
daily_tplev = find_fixed_tropopause(wrf_vars.pres, tropopause);
end
for a=1:size(wrf_vars.no2,1)
for b=1:size(wrf_vars.no2,2)
for t=1:size(wrf_vars.no2,4)
tp = daily_tplev(a,b,t);
if tp > 0 % tp is given -1 if the tropopause algorithm cannot find a tropopause
wrf_vars.no2(a,b,tp:end,t) = nan;
end
end
end
end
if strcmpi(integration_mode,'box')
trop_no2 = squeeze(nansum2(wrf_vars.no2 .* (wrf_vars.zlev*100), 3));
elseif strcmpi(integration_mode, 'mixing_ratio');
sz = size(wrf_vars.no2);
trop_no2 = nan(sz(1:2));
for a=1:sz(1)
for b=1:sz(2)
trop_no2(a,b) = integPr2(squeeze(wrf_vars.no2(a,b,:)), squeeze(wrf_vars.pres(a,b,:)), wrf_vars.pres(a,b,1));
end
end
end
end
function tplev = find_fixed_tropopause(pres, tropopause)
sz = size(pres);
tplev = nan(sz(1:2));
for a=1:sz(1)
for b=1:sz(2)
tplev(a,b) = find(pres(a,b,:) > tropopause, 1, 'last');
end
end
end
function vars = read_file_vars(wrf_file, int_mode)
if strcmpi(int_mode, 'box')
vars.no2 = read_wrf_preproc(wrf_file, 'no2_ndens');
[~, vars.zlev] = read_wrf_preproc(wrf_file, 'z');
else
vars.no2 = ncread(wrf_file, 'no2');
end
% Used if finding fixed tropopause, so always include this
vars.pres = read_wrf_preproc(wrf_file, 'pressure');
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
get_wrf_array_size.m
|
.m
|
WRF_Utils-master/get_wrf_array_size.m
| 1,452 |
utf_8
|
871dea0d25f6d15df728782fee8df7da
|
function [ sz ] = get_wrf_array_size( wrffile )
%GET_WRF_ARRAY_SIZE Gets unstaggered array sizes in WRF output file
% SZ = GET_WRF_ARRAY_SIZE( WRFFILE ) Returns a 1x4 vector SZ which
% contains the length of unstagger WRF arrays in the given file along the
% west_east, south_north, bottom_top, and Time dimensions. These will be
% the sizes for most arrays of physical variables; although some
% variables will be staggered. This function is intended for use when you
% want to get the size of the arrays without actually loading the arrays
% themselves.
ncid = netcdf.open(wrffile, 'NC_NOWRITE');
cleanupObj = onCleanup(@() thisCleanup(ncid));
dim_we = netcdf.inqDimID(ncid, 'west_east');
[~,sz_we] = netcdf.inqDim(ncid, dim_we);
dim_sn = netcdf.inqDimID(ncid, 'south_north');
[~,sz_sn] = netcdf.inqDim(ncid, dim_sn);
dim_bt = netcdf.inqDimID(ncid, 'bottom_top');
[~,sz_bt] = netcdf.inqDim(ncid, dim_bt);
try
dim_time = netcdf.inqDimID(ncid, 'Time');
[~,sz_time] = netcdf.inqDim(ncid, dim_time);
catch err
if strcmp(err.identifier, 'MATLAB:imagesci:netcdf:libraryFailure')
warning('wrf_size:no_time', 'No "Time" dimension, assuming length 1');
sz_time = 1;
else
rethrow(err)
end
end
sz = [sz_we, sz_sn, sz_bt, sz_time];
end
function thisCleanup(ncid)
% Ensure that the netCDF file ID is closed even if this function errors.
%fprintf('Closing ncid %d\n', ncid);
netcdf.close(ncid);
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
compare_wrfout.m
|
.m
|
WRF_Utils-master/compare_wrfout.m
| 7,250 |
utf_8
|
de7b66d8d6da0c7d432ea37eed66a9eb
|
function [ ] = compare_wrfout( old_dir, new_dir, varargin )
%COMPARE_WRFOUT Compare several variables from two sets of WRF-Chem output
% COMPARE_WRFOUT( OLD_DIR, NEW_DIR ) Reads wrfout_d* files from OLD_DIR
% and NEW_DIR and plots the average absolute and percent difference in
% no, no2, o3, U, and V across all files common to both directories. If
% "plot_slice_gui" exists on your Matlab path, then it will be used to
% allow you to examine each model level at your leisure. Otherwise,
% pcolor will be used to plot the top and bottom levels. A list of
% statistics will also be printed out.
%
% Additional parameters:
% 'files' - a cell array of strings listing individual files
% that you wish to load. If any are missing from either OLD_DIR or
% NEW_DIR, an error is thrown. By default all files in common between
% the two directories are loaded.
%
% 'vars' - a cell array of strings listing which variables you wish
% to compare. Default is {'no', 'no2', 'o3', 'U', 'V'}. Variables
% will automatically be unstagged.
%
% 'filestem' - the beginning of the WRF-Chem output file names, used
% to filter out unrelated files. Default is 'wrfout_d'.
%
% 'maxvargb' - the maximum size a single variable loaded from two
% files can have in gigabytes. Because WRF-Chem output can get crazy
% large, this function estimates how large each variable loaded will
% be and halts if it exceeds this value to prevent grinding your poor
% computer to a halt.
E = JLLErrors;
p = inputParser;
p.addParameter('files',[]);
p.addParameter('vars',{'no','no2','o3','U','V'});
p.addParameter('filestem','wrfout_d');
p.addParameter('maxvargb',2);
p.parse(varargin{:});
pout = p.Results;
files = pout.files;
vars = pout.vars;
filestem = strcat(pout.filestem,'*');
maxvarGB = pout.maxvargb;
if ~iscellstr(vars)
E.badinput('Parameter "vars" must be a cell array of strings')
elseif ~ischar(filestem)
E.badinput('Parameter "filestem" must be a string')
end
% If a list of files is NOT given, find all wrfout files common to both the
% old and new directories. Make sure that no date/time is repeated.
if isempty(files)
Fold = dir(fullfile(old_dir,filestem));
fold_names = {Fold.name};
Fnew = dir(fullfile(new_dir,filestem));
fnew_names = {Fnew.name};
xx = find_common_elements(fold_names, fnew_names, 'nodup');
files = fnew_names(xx);
elseif ~iscellstr(files)
E.badinput('The value for parameter "files" must be a cell array of strings')
else
missing_files_new = {};
missing_files_old = {};
for a=1:numel(files)
if ~exist(fullfile(new_dir,files{a}),'file')
missing_files_new{end+1} = files{a}; %#ok<AGROW>
end
if ~exist(fullfile(old_dir,files{a}),'file')
missing_files_old{end+1} = files{a}; %#ok<AGROW>
end
end
doerr = false;
if numel(missing_files_new) > 0
fprintf('The following files are missing from %s: \n\t%s\n', new_dir, strjoin(missing_files_new, '\n\t'));
doerr = true;
end
if numel(missing_files_old) > 0
fprintf('The following files are missing from %s: \n\t%s\n', old_dir, strjoin(missing_files_old, '\n\t'));
doerr = true;
end
if doerr
E.filenotfound('%s', 'Files specified by the parameter "files" were missing. See previous messages for a list.')
end
end
% Check the array size of the first file, use to issue a warning if too
% much data will be read in
wrf_sz = get_wrf_array_size(fullfile(old_dir, files{1}));
gigabytes = prod(wrf_sz) * 4 * numel(files) * 2 / 1e9; % read in as single precision (4 bytes/value) and each file name is loaded from 2 directories
if gigabytes > maxvarGB
E.callError('var_too_large','Loading just one variable for all files would require %.2f GB, > %.2f GB (you can change this limit with the "maxvargb" parameter', gigabytes, maxvarGB)
end
xlon = double(ncread(fullfile(old_dir, files{1}),'XLONG'));
xlat = double(ncread(fullfile(old_dir, files{1}),'XLAT'));
coast_dat = load('coast');
if exist('plot_slice_gui','file')
plot_fxn = @(del,tstr) plot_with_gui(del,tstr);
else
plot_fxn = @(del,tstr) plot_with_pcolor(del,tstr);
end
% Load each variable; calculate the difference between the old and new WRF
% runs, then plot (either using the plot slice gui or just pcolor)
substruct = struct('mean_diff_by_level',[],'sdev_diff_by_level',[],'mean_perdiff_by_level',[],'sddev_perdiff_by_level',[],...
'mean_absdiff_by_level',[],'sdev_absdiff_by_level',[],'mean_absperdiff_by_level',[],'sdev_absperdiff_by_level',[]);
stats = make_empty_struct_from_cell(vars,substruct);
for a=1:numel(vars)
this_var_old = read_wrf_vars(old_dir,files,vars(a),false,'visual');
this_var_new = read_wrf_vars(new_dir,files,vars(a),false,'visual');
stagger_id = ncreadatt(fullfile(old_dir,files{1}),vars{a},'stagger');
if ~isequal(size(this_var_new), size(this_var_old))
E.sizeMismatch('this_var_old',sprintf('this_var_new (%s arrays concatenated from all WRF files)',vars{a}))
end
del = this_var_new - this_var_old;
[this_mean, this_std] = diff_stats(del, stagger_id);
stats.(vars{a}).mean_diff_by_level = this_mean;
stats.(vars{a}).sdev_diff_by_level = this_std;
[this_mean, this_std] = diff_stats(abs(del), stagger_id);
stats.(vars{a}).mean_absdiff_by_level = this_mean;
stats.(vars{a}).sdev_absdiff_by_level = this_std;
plot_fxn(del,sprintf('Absolute difference %s',vars{a}));
del = reldiff(this_var_new, this_var_old)*100;
[this_mean, this_std] = diff_stats(del, stagger_id);
stats.(vars{a}).mean_perdiff_by_level = this_mean;
stats.(vars{a}).sdev_perdiff_by_level = this_std;
[this_mean, this_std] = diff_stats(abs(del), stagger_id);
stats.(vars{a}).mean_absperdiff_by_level = this_mean;
stats.(vars{a}).sdev_absperdiff_by_level = this_std;
plot_fxn(del,sprintf('Percent difference %s',vars{a}));
end
% Print the stats
for a=1:numel(vars)
fprintf('%s\n:',vars{a});
fns = fieldnames(stats.(vars{a}));
for b=1:numel(fns)
fprintf(' %s: %g\n', fns{b}, stats.(vars{a}).(fns{b}));
end
end
function plot_with_gui(del, tstr)
del = double(nanmean(del(:,:,:,:),4)); %average along all time dimensions
plot_slice_gui(del, xlon, xlat, coast_dat.long, coast_dat.lat, tstr);
end
function plot_with_pcolor(del,tstr)
del = double(nanmean(del(:,:,:,:),4)); %average along all time dimensions
figure;
pcolor(xlon, xlat, del(:,:,1));
line(coast_dat.long, coast_dat.lat,'color','k');
colorbar;
title(sprintf('%s - level 1',tstr));
figure;
pcolor(xlon, xlat, del(:,:,end));
line(coast_dat.long, coast_dat.lat,'color','k');
colorbar;
title(sprintf('%s - level %d',tstr,size(del,3)));
end
end
function [m,s] = diff_stats(del, unstagger_dim)
if ~isempty(unstagger_dim)
del = unstagger(del, unstagger_dim);
end
pvec = 1:ndims(del);
pvec(3) = [];
pvec = cat(2,3,pvec);
del = permute(del,pvec);
del = reshape(del,size(del,1),[]);
m = nanmean(del,2);
s = nanstd(del,0,2);
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
wrf_grid_area.m
|
.m
|
WRF_Utils-master/wrf_grid_area.m
| 2,725 |
utf_8
|
e6543109062ae647aa804ccab90b90f8
|
function [ grid_area ] = wrf_grid_area( xlon, xlat, varargin )
%WRF_GRID_AREA Estimates the area of each WRF grid cell
% GRID_AREA = WRF_GRID_AREA( XLON, XLAT ) takes the grid center longitude
% (XLON) and latitude (XLAT) and returns the areas of the grid cells in
% kilometers (GRID_AREA). This uses wrf_grid_corners to estimate the
% corner points, so it's not as accurate as it would be if it calculated
% them with knowledge of the map projection. The area is computed
% assuming the WGS84 ellipsoid.
E = JLLErrors;
%%%% INPUT CHECKING %%%%%
if ~ismatrix(xlon) || ~ismatrix(xlat)
E.badinput('XLON and XLAT should be 2D')
elseif ~isequal(size(xlon), size(xlat))
E.badinput('XLON and XLAT must be the same size');
end
write_nc = false;
if nargin > 2
write_nc = true;
ncfilename = varargin{1};
if ~ischar(ncfilename)
E.badinput('NCFILENAME must be a string');
end
if exist(ncfilename, 'file')
if nargin < 4 || ~varargin{2}
warning('%s exists, will not overwrite. Give true as the fourth argument to overwrite\n', ncfilename);
write_nc = false;
end
end
end
%%%%% MAIN FUNCTION %%%%%
grid_area = nan(size(xlon));
earth_ellip = referenceEllipsoid('wgs84','kilometer');
[xloncorn, xlatcorn] = wrf_grid_corners(xlon, xlat);
for a = 1:numel(xlon)
xall = xloncorn(:,a);
yall = xlatcorn(:,a);
[xall, yall] = poly2cw(xall, yall);
grid_area(a) = areaint(yall,xall,earth_ellip);
end
if write_nc
write_netcdf(ncfilename, xlon, xlat, grid_area);
end
end
function write_netcdf(file_name, wrf_lon, wrf_lat, wrf_area)
if exist(file_name, 'file')
delete(file_name);
end
nccreate(file_name, 'XLONG', 'Datatype', 'single','Dimensions',{'west_east',size(wrf_lon,1),'south_north',size(wrf_lon,2)});
ncwrite(file_name, 'XLONG', wrf_lon);
ncwriteatt(file_name, 'XLONG', 'description', 'LONGITUDE, WEST IS NEGATIVE');
ncwriteatt(file_name, 'XLONG', 'units', 'degree_east');
ncwriteatt(file_name, 'XLONG', 'stagger', '');
nccreate(file_name, 'XLAT', 'Datatype', 'single','Dimensions',{'west_east',size(wrf_lon,1),'south_north',size(wrf_lon,2)});
ncwrite(file_name, 'XLAT', wrf_lat);
ncwriteatt(file_name, 'XLAT', 'description', 'LATITUDE, SOUTH IS NEGATIVE');
ncwriteatt(file_name, 'XLAT', 'units', 'degree_north');
ncwriteatt(file_name, 'XLAT', 'stagger', '');
nccreate(file_name, 'AREA', 'Datatype', 'single','Dimensions',{'west_east',size(wrf_lon,1),'south_north',size(wrf_lon,2)});
ncwrite(file_name, 'AREA', wrf_area);
ncwriteatt(file_name, 'AREA', 'description', 'GRID CELL AREA, CALCULATED BY WRF_GRID_AREA.m');
ncwriteatt(file_name, 'AREA', 'units', 'km^2');
ncwriteatt(file_name, 'AREA', 'stagger', '');
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
wrf_grid_corners.m
|
.m
|
WRF_Utils-master/wrf_grid_corners.m
| 4,076 |
utf_8
|
f07b77d1d96566f77ba0e842912f5547
|
function [ xloncorn, xlatcorn ] = wrf_grid_corners( xlon, xlat )
%WRF_GRID_CORNERS Computes corners of WRF grid cells.
% [ XLONCORN, XLATCORN ] = WRF_GRID_CORNERS( XLON, XLAT )
% Takes as input the grid center points XLON and XLAT. Returns the
% 4-by-m-by-n arrays XLONCORN and XLATCORN where m and n are the
% first and second dimension lengths of XLON and XLAT.
xloncorn = nan([4, size(xlon)]);
xlatcorn = nan([4, size(xlat)]);
% The interior corners will be shared amongst neighbor points, so we only
% need to calculate them once.
interior_loncorn = (xlon(1:end-1,1:end-1)+xlon(2:end,1:end-1)+xlon(2:end,2:end)+xlon(1:end-1,2:end))/4;
interior_latcorn = (xlat(1:end-1,1:end-1)+xlat(2:end,1:end-1)+xlat(2:end,2:end)+xlat(1:end-1,2:end))/4;
xloncorn(1,2:end,2:end) = interior_loncorn;
xlatcorn(1,2:end,2:end) = interior_latcorn;
xloncorn(2,1:end-1,2:end) = interior_loncorn;
xlatcorn(2,1:end-1,2:end) = interior_latcorn;
xloncorn(3,1:end-1,1:end-1) = interior_loncorn;
xlatcorn(3,1:end-1,1:end-1) = interior_latcorn;
xloncorn(4,2:end,1:end-1) = interior_loncorn;
xlatcorn(4,2:end,1:end-1) = interior_latcorn;
% Now we do the edges, ignoring the extreme corners b/c we don't actually
% have enough information right now. Assume that the spacing between the
% first and second column is the same as between the second and third, and
% so on.
xloncorn(2,1:end-1,1) = compute_by_difference( xloncorn(2,1:end-1,2), xloncorn(2,1:end-1,3) );
xloncorn(1,2:end,1) = xloncorn(2,1:end-1,1);
xlatcorn(2,1:end-1,1) = compute_by_difference( xlatcorn(2,1:end-1,2), xlatcorn(2,1:end-1,3) );
xlatcorn(1,2:end,1) = xlatcorn(2,1:end-1,1);
xloncorn(3,1:end-1,end) = compute_by_difference( xloncorn(3,1:end-1,end-1), xloncorn(3,1:end-1,end-2) );
xloncorn(4,2:end,end) = xloncorn(3,1:end-1,end);
xlatcorn(3,1:end-1,end) = compute_by_difference( xlatcorn(3,1:end-1,end-1), xlatcorn(3,1:end-1,end-2) );
xlatcorn(4,2:end,end) = xlatcorn(3,1:end-1,end);
xloncorn(4,1,1:end-1) = compute_by_difference( xloncorn(4,2,1:end-1), xloncorn(4,3,1:end-1) );
xloncorn(1,1,2:end) = xloncorn(4,1,1:end-1);
xlatcorn(4,1,1:end-1) = compute_by_difference( xlatcorn(4,2,1:end-1), xlatcorn(4,3,1:end-1) );
xlatcorn(1,1,2:end) = xlatcorn(4,1,1:end-1);
xloncorn(3,end,1:end-1) = compute_by_difference( xloncorn(3,end-1,1:end-1), xloncorn(3,end-2,1:end-1) );
xloncorn(2,end,2:end) = xloncorn(3,end,1:end-1);
xlatcorn(3,end,1:end-1) = compute_by_difference( xlatcorn(3,end-2,1:end-1), xlatcorn(3,end-2,1:end-1) );
xlatcorn(2,end,2:end) = xlatcorn(3,end,1:end-1);
% Finally the four remaining corners, now that we've filled in the middles
% of the edges, we have what we need. We'll use the average from both
% directions to determine this.
xloncorn(1,1,1) = mean([compute_by_difference(xloncorn(1,2,1), xloncorn(1,3,1)), compute_by_difference(xloncorn(1,1,2), xloncorn(1,1,3))]);
xlatcorn(1,1,1) = mean([compute_by_difference(xlatcorn(1,2,1), xlatcorn(1,3,1)), compute_by_difference(xlatcorn(1,1,2), xlatcorn(1,1,3))]);
xloncorn(2,end,1) = mean([compute_by_difference(xloncorn(2,end-1,1), xloncorn(2,end-2,1)), compute_by_difference(xloncorn(2,end,2), xloncorn(2,end,3))]);
xlatcorn(2,end,1) = mean([compute_by_difference(xlatcorn(2,end-1,1), xlatcorn(2,end-2,1)), compute_by_difference(xlatcorn(2,end,2), xlatcorn(2,end,3))]);
xloncorn(3,end,end) = mean([compute_by_difference(xloncorn(3,end-1,end), xloncorn(3,end-2,end)), compute_by_difference(xloncorn(3,end,end-1), xloncorn(3,end,end-2))]);
xlatcorn(3,end,end) = mean([compute_by_difference(xlatcorn(3,end-1,end), xlatcorn(3,end-2,end)), compute_by_difference(xlatcorn(3,end,end-1), xlatcorn(3,end,end-2))]);
xloncorn(4,1,end) = mean([compute_by_difference(xloncorn(4,2,end), xloncorn(4,3,end)), compute_by_difference(xloncorn(4,1,end-1), xloncorn(4,1,end-2))]);
xlatcorn(4,1,end) = mean([compute_by_difference(xlatcorn(4,2,end), xlatcorn(4,3,end)), compute_by_difference(xlatcorn(4,1,end-1), xlatcorn(4,1,end-2))]);
end
function [ out ] = compute_by_difference(nearest, next_nearest)
out = nearest - (next_nearest - nearest);
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
match_wrf2aircraft.m
|
.m
|
WRF_Utils-master/ChemComparison/match_wrf2aircraft.m
| 15,900 |
utf_8
|
aa6bc3161ea89982262416c2dbb3ef0c
|
function [ Match ] = match_wrf2aircraft( Raw, wrf_dirs, wrf_prof_mode )
%MATCH_WRF2AIRCRAFT Generates a structure matching WRF output to aircraft data
% MATCH = MATCH_WRF2AIRCRAFT( RAW, WRF_DIRS ) Matches the aircraft data
% contained in RAW to the WRF data in wrfout_* files contained in
% WRF_DIRS. RAW must be a structure that contains the fields "lon",
% "lat", "pres", "dvec", and "campaign". "lon" and "lat" are the
% longitude and latitude of the aircraft data (longitude must be in
% degrees west is < 0). "pres" is the pressure of the aircraft
% measurements in hPa. "dvec" is a vector of Matlab date numbers giving
% the date and time of each aircraft measurement. "campaign" is a string
% that gives the campaign name (solely for record keeping - does not need
% to be any specific format). The other fields in RAW must have names
% that match the names of WRF-Chem variables you want to match with the
% aircraft data. For example, if you want to compare aircraft NO, NO2,
% and HNO3 data with WRF files that contain that data as variables no,
% no2, and hno3, RAW should have the aircraft data stored in fields no,
% no2, and hno3, respectively. WRF_DIRS must be a string giving single
% directory where all necessary WRF data can be found, or a cell array of
% those directories.
%
% MATCH = MATCH_WRF2AIRCRAFT( RAW, WRF_DIRS, 'monthly' ) tells this
% function to look for monthly averaged WRF files (following the naming
% convention WRF_BEHR_monthly_XX.nc) instead of time resolved output
% files, where XX is the 2-digit month number.
%
% MATCH = MATCH_WRF2AIRCRAFT( RAW, WRF_DIRS, 'v2' ) tells this to use
% BEHR v2 NO2 profiles that are stored in .mat files with names
% mXX_NO2_profile.mat Note that these files only contain NO2 data.
%
% The output structure has three primary fields: "data", "wrf", and
% "indicies". It is constructed such that all the subfields in "data" and
% most of the subfields in "wrf" are just vectors. In "data", the fields
% are just a concatenation in time of fields from the aircraft data for
% the campaign. In "wrf", the vector fields are just the WRF data that
% corresponds to the aircraft measurement; a whole series of aircraft
% measurements that falls in the same grid cell will correspond to the
% same WRF value.
%
% The "indicies" field allows you to map the data in the previous two
% fields to the WRF grid. The subfields give the index in the
% corresponding WRF dimension. The WRF xlon and xlat fields are provided
% as arrays, the WRF pressure for each grid cell is provided as a vector,
% the bottom_top index should just be taken as-is, that is a model layer
% index.
%
% The "time" index bears mention; since a large number of WRF files do
% not have any corresponding aircraft data, they are skipped entirely.
% The "datevec" subfield under "wrf" has the times of the files that had
% corresponding aircraft data, the time index is the index in this
% vector.
% History:
% 27 Oct 2017 - modified to (a) split out the matching code from the code
% that loads the aircraft data and (b) to let it read monthly and BEHR
% version 2 NO2 profiles. Verified that old functionality didn't change
% by running it with match_wrf2campaigns.dc3 using wrf_dirs =
% '/Volumes/share2/USERS/LaughnerJ/WRF/DC3/lnox_off-fixed_BCs' and
% comparing vs. '/Users/Josh/Documents/MATLAB/BEHR/Workspaces/WRF/Chem
% Comparison/DC3-Comparison-no_lnox-fixedBC-using_wrfgridcorners.mat'
E = JLLErrors;
%%%%%%%%%%%%%%%%%%
% INPUT CHECKING %
%%%%%%%%%%%%%%%%%%
req_fields = {'lon', 'lat', 'pres', 'dvec', 'campaign'};
if ~isstruct(Raw)
E.badinput('RAW must be a structure')
else
xx_fields = ~ismember(req_fields, fieldnames(Raw));
if any(xx_fields)
E.badinput('RAW must contain the fields %s at a minimum (missing: %s)', strjoin(req_fields, ', '), strjoin(req_fields(xx_fields), ', '));
end
end
if ischar(wrf_dirs)
wrf_dirs = {wrf_dirs};
elseif ~iscellstr(wrf_dirs)
E.badinput('WRF_DIRS must be a string or cell array or strings');
else
fprintf('match_wrf2aircraft: will look for WRF-Chem data in:\n\t%s\n\n', strjoin(wrf_dirs, '\n\t'));
end
xx_exist = cellfun(@(d) exist(d, 'dir'), wrf_dirs);
if ~all(xx_exist)
E.badinput('The following given WRF_DIRS do not exist: \n\t%s', strjoin(wrf_dirs(~xx_exist), '\n\t'));
end
allowed_prof_modes = {'daily', 'monthly', 'v2'};
if ~exist('wrf_prof_mode', 'var')
wrf_prof_mode = 'daily';
elseif ~ismember(wrf_prof_mode, allowed_prof_modes)
E.badinput('WRF_PROF_MODE "%s" is not one of the allowed values (%s)', wrf_prof_mode, strjoin(allowed_prof_modes, ', '));
end
% Get a unified date number vector containing the exact time of each
% measurement. UTC is in seconds after midnight for the given day
air_dvec = Raw.dvec;
[W, wrf_dvec, time_inds] = match_in_time(wrf_dirs, air_dvec, wrf_prof_mode);
% Next we need to bin the data in space. We'll do this in two steps. First,
% by lat/lon. Then, we'll go back through and assign each value to a
% pressure bin by finding the WRF pressure in that lat/lon coordinate
% closest to the aircraft pressure
% Try to find XLONG_U and XLAT_V in the wrfout files. If there, we can use
% them as grid cell edges. Otherwise, we'll have to estimate them from the
% regular XLONG and XLAT
[wrf_edge_lon, wrf_edge_lat, wrf_lon, wrf_lat] = wrf_edge_latlon(W(1).name, wrf_prof_mode);
% Loop through each cell in the west-east and south-north directions, find
% the data points that fall in the column of grid cells, then assign them a
% vertical position by which pressure level they are closest to.
%
% Need to load wrf pressures here, may as well load the other chemical
% fields too. Match any fields from the aircraft data possible, remember;
% the fields in Raw should match WRF variables if they are desired to be
% matched.
if strcmpi(wrf_prof_mode, 'v2')
wrf_vars = {'no2', 'pres'}; % not used in loading, but is used in assigning to the match structure
convert_pres = false;
else
wi = ncinfo(W(1).name);
all_wrf_vars = {wi.Variables.Name};
air_fns = fieldnames(Raw);
wrf_vars = air_fns(ismember(air_fns, all_wrf_vars));
convert_pres = false;
if ~ismember('pres', wrf_vars)
% "pres" is a variable calculated by some of my NCO scripts when
% subsetting WRF output. If it's not there (i.e. reading direct WRF
% output) we need to compute the grid cell pressure.
if ismember('pres', all_wrf_vars)
wrf_vars{end+1} = 'pres';
else
wrf_vars{end+1} = 'P';
wrf_vars{end+1} = 'PB';
convert_pres = true;
end
end
if ismember('lnox_total', all_wrf_vars)
wrf_vars{end+1} = 'lnox_total';
end
end
Match.campaign = Raw.campaign;
Match.data = Raw;
Match.data.datevec = air_dvec;
Match.wrf = make_empty_struct_from_cell(wrf_vars);
Match.wrf.xlon = wrf_lon;
Match.wrf.xlat = wrf_lat;
Match.wrf.time = wrf_dvec;
blank_vec = nan(size(Raw.lon));
Match.indicies = struct('west_east', blank_vec, 'south_north', blank_vec, 'bottom_top', blank_vec, 'time', time_inds);
if strcmpi(wrf_prof_mode, 'v2')
% Loading version 2 .mat files, can't use the netCDF tools. There are
% always 28 pressures, although that dimension isn't needed in the
% current implementation.
wrf_sz = [size(wrf_lon), 28];
else
wrf_sz = get_wrf_array_size(wi.Filename);
end
fprintf('Matching lat/lon\n');
for a=1:wrf_sz(1)
for b=1:wrf_sz(2)
% First check all data, if nothing falls in this cell, move on
xx = Raw.lon >= wrf_edge_lon(a,b) & Raw.lon <= wrf_edge_lon(a+1,b);
yy = Raw.lat >= wrf_edge_lat(a,b) & Raw.lat <= wrf_edge_lat(a,b+1);
if sum(xx & yy) > 0;
Match.indicies.west_east(xx & yy) = a;
Match.indicies.south_north(xx & yy) = b;
end
end
end
for d=1:numel(W)
fprintf('Loading WRF file %d of %d\n', d, numel(W));
[wrf_var_struct, wrf_pres] = load_one_wrf_file(W(d).name, wrf_vars, wrf_prof_mode, convert_pres);
tt = find(Match.indicies.time == d);
i_time = d;
% Now go through each data point from the aircraft and assign the vertical coordinate
for i=1:numel(tt)
i_we = Match.indicies.west_east(tt(i));
i_sn = Match.indicies.south_north(tt(i));
if any(isnan([i_we, i_sn, i_time]))
continue
end
wrf_pres_vec = squeeze(wrf_pres(i_we, i_sn, :));
[~, i_bt] = min(abs(Match.data.pres(tt(i)) - wrf_pres_vec));
Match.indicies.bottom_top(tt(i)) = i_bt;
% We can match the WRF data at the same time
for j=1:numel(wrf_vars)
Match.wrf.(wrf_vars{j})(tt(i)) = wrf_var_struct.(wrf_vars{j})(i_we, i_sn, i_bt);
end
end
end
Match.generation_date = datestr(now);
% Switch pressure back to total
if convert_pres
Match.wrf.pres = (Match.wrf.P + Match.wrf.PB)/100;
Match.wrf = rmfield(Match.wrf, 'P');
Match.wrf = rmfield(Match.wrf, 'PB');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TIME MATCHING SUBFUNCTION %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [W, wrf_dvec, time_inds] = match_in_time(wrf_dirs, air_dvec, wrf_prof_mode)
% Get the list of wrfout files available across all given directories, find
% the difference in time between each. The first step will be to bin the
% aircraft data by which wrfout file is closest in time.
if strcmpi(wrf_prof_mode, 'monthly') || strcmpi(wrf_prof_mode, 'v2')
[W, wrf_dvec, time_inds] = match_monthly_wrf_files(wrf_dirs, air_dvec, wrf_prof_mode);
else
[W, wrf_dvec, time_inds] = match_daily_wrf_files(wrf_dirs, air_dvec);
end
end
function [W, wrf_months, time_inds] = match_monthly_wrf_files(wrf_dirs, air_dvec, wrf_prof_mode)
E = JLLErrors;
W = [];
for a=1:numel(wrf_dirs)
if strcmpi(wrf_prof_mode, 'monthly')
W = veccat(dirff(fullfile(wrf_dirs{a}, 'WRF_BEHR_monthly*.nc')));
elseif strcmpi(wrf_prof_mode, 'v2')
W = veccat(dirff(fullfile(wrf_dirs{a}, 'm*_NO2_profile.mat')));
else
E.notimplemented('File search for wrf_prof_mode == %s not implemented', wrf_prof_mode);
end
end
wrf_months = nan(size(W));
for a=1:numel(W)
[~,filename] = fileparts(W(a).name);
wrf_month_str = regexp(filename, '\d\d', 'match', 'once');
if isempty(wrf_month_str)
E.callError('no_wrf_month', 'Cannot identify month in filename %s', filename);
end
wrf_months(a) = str2double(wrf_month_str);
end
% Now bin the aircraft data in time. We won't directly bin it, rather we
% assign each data point a time index that indicates which WRF file it goes
% with. We'll also keep track
time_inds = nan(size(air_dvec));
wrf_to_keep = false(size(W));
i_t = 1;
for a=1:numel(wrf_months)
xx = month(air_dvec) == wrf_months(a);
if sum(xx) > 0
wrf_to_keep(a) = true;
time_inds(xx) = i_t;
i_t = i_t + 1;
end
end
W(~wrf_to_keep) = [];
wrf_months(~wrf_to_keep) = [];
end
function [W, wrf_dvec, time_inds] = match_daily_wrf_files(wrf_dirs, air_dvec)
E = JLLErrors;
W = [];
for a=1:numel(wrf_dirs)
W = veccat(W, dirff(fullfile(wrf_dirs{a},'wrfout*')));
end
wrf_dvec = date_from_wrf_filenames(W);
% Compute the difference between files.
wrf_timediff = diff(wrf_dvec);
if numel(unique(wrf_timediff)) == 1
wrf_timediff = unique(wrf_timediff);
else
warning('Difference in time between output files varies, using average (std dev of time differences = %g)', std(wrf_timediff))
wrf_timediff = nanmean(wrf_timediff);
end
% Now bin the aircraft data in time. We won't directly bin it, rather we
% assign each data point a time index that indicates which WRF file it goes
% with.
time_inds = nan(size(air_dvec));
wrf_to_keep = false(size(W));
i_t = 1;
for a=1:numel(wrf_dvec)
min_time = wrf_dvec(a) - wrf_timediff/2;
max_time = wrf_dvec(a) + wrf_timediff/2;
xx = air_dvec >= min_time & air_dvec < max_time;
if sum(xx) > 0
% Double check that we haven't assigned this point yet
if any(~isnan(time_inds(xx)))
if sum(~isnan(time_inds(xx))) == 1
wi = ~isnan(time_inds) & xx;
warning('One of the aircraft data points (%s) is being assigned to multiple WRF files. This is probably on the edge between two WRF files.', datestr(air_dvec(wi)));
else
E.callError('time_assignment', 'Multiple aircraft data points are being assigned to multiple WRF files.');
end
end
% Only if there are any data points at this time will we keep it.
% WRF files with no corresponding aircraft data will be removed.
time_inds(xx) = i_t;
i_t = i_t + 1;
wrf_to_keep(a) = true;
end
end
W(~wrf_to_keep) = [];
wrf_dvec(~wrf_to_keep) = [];
end
%%%%%%%%%%%%%%%%%%%%%
% SPATIAL FUNCTIONS %
%%%%%%%%%%%%%%%%%%%%%
function [wrf_edge_lon, wrf_edge_lat, xlon, xlat] = wrf_edge_latlon(filename, wrf_prof_mode)
% wi should be a structure for one representative wrfout file returned by
% ncinfo
if strcmpi(wrf_prof_mode, 'v2')
% If loading version 2 profiles, they're in .mat files, so we can read
% any variables.
wrf_vars = {};
else
wi = ncinfo(filename);
wrf_vars = {wi.Variables.Name};
end
if ismember('XLONG_U', wrf_vars) && ismember('XLAT_V', wrf_vars)
wrf_edge_lon = ncread(wi.Filename, 'XLONG_U');
wrf_edge_lat = ncread(wi.Filename, 'XLAT_V');
xlon = ncread(wi.Filename, 'XLONG');
xlat = ncread(wi.Filename, 'XLAT');
else
if strcmpi(wrf_prof_mode, 'v2')
P = load(filename);
% Must transpose these b/c in normal WRF files the first dimension
% is west_east, but in the version 2 files, it's set up so that the
% first dimension is longitude. This matters when we're figuring
% out which grid cell each aircraft point is in.
xlon = P.PROFILE.Longitude';
xlat = P.PROFILE.Latitude';
else
warning('XLONG_U or XLAT_V not available, using wrf_grid_corners() instead')
xlon = ncread(wi.Filename, 'XLONG');
xlat = ncread(wi.Filename, 'XLAT');
end
[xloncorn, xlatcorn] = wrf_grid_corners(xlon, xlat);
% Average the north and south west corners to get the west midpoint; do
% a similar process for each of the other sides. In the end,
% wrf_edge_lon should be staggered in the first dimension and wrf_edge
% lat in the second.
wloncorn = squeeze(nanmean(xloncorn([1 4], :, :)));
eloncorn = squeeze(nanmean(xloncorn([2 3], :, :)));
slatcorn = squeeze(nanmean(xlatcorn(1:2, :, :)));
nlatcorn = squeeze(nanmean(xlatcorn(3:4, :, :)));
weloncorn = (eloncorn(2:end,:)+wloncorn(1:end-1,:))/2;
snlatcorn = (slatcorn(:,2:end)+nlatcorn(:,1:end-1))/2;
wrf_edge_lon = cat(1, wloncorn(1,:), weloncorn, eloncorn(end, :));
wrf_edge_lat = cat(2, slatcorn(:,1), snlatcorn, nlatcorn(:, end));
end
end
%%%%%%%%%%%%%%%%
% LOADING DATA %
%%%%%%%%%%%%%%%%
function [wrf_var_struct, wrf_pres] = load_one_wrf_file(wrf_file, wrf_vars, wrf_prof_mode, convert_pres)
if strcmpi(wrf_prof_mode, 'v2')
P = load(wrf_file);
PROFILE = P.PROFILE;
pres = reshape(PROFILE.Pressure,1,1,[]);
% As in wrf_edge_latlon, we need to reorder these so that the first
% dimension is west_east and the second is south_north
wrf_pres = repmat(pres, [size(PROFILE.Longitude'), 1]);
wrf_var_struct.no2 = permute(PROFILE.NO2_profile, [3 2 1]);
wrf_var_struct.pres = wrf_pres;
else
wrf_var_cell = cell(size(wrf_vars));
[wrf_var_cell{:}] = read_wrf_vars('', wrf_file, wrf_vars);
wrf_var_struct = cell2struct(wrf_var_cell(:), wrf_vars(:), 1);
if convert_pres
wrf_pres = (wrf_var_struct.P + wrf_var_struct.PB)/100; % convert from Pa to hPa
else
wrf_pres = wrf_var_struct.pres;
end
end
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
parse_noaa_isd.m
|
.m
|
WRF_Utils-master/MetComparison/parse_noaa_isd.m
| 4,301 |
utf_8
|
4c0940a33b30c3307a5c1c77e56f13f7
|
function [ Site ] = parse_noaa_isd( file, lonlim, latlim, datelim )
%PARSE_NOAA_ISD Parse a NOAA integrate surface database file
% PARSE_NOAA_ISD( FILE ) parses the NOAA ISD file at path FILE and
% returns a NOAAISDSite object.
%
% PARSE_NOAA_ISD( FILE, LONLIM, LATLIM ) will parse the file if the site
% falls within the longitude and latitude limits. Otherwise it returns
% the default NOAAISDSite object. You can test for this case if the
% usaf_id field is the same as the object returned by constructing a
% NOAAISDSite object with no arguments.
E = JLLErrors;
if ~ischar(file)
E.badinput('FILE must be a string')
elseif ~exist(file,'file')
E.filenotfound(file);
end
if ~exist('lonlim','var')
lonlim = [-180, 180];
elseif ~isnumeric(lonlim) || numel(lonlim) ~= 2
E.badinput('LONLIM must be a 2 element numeric vector');
end
if ~exist('latlim','var')
latlim = [-90, 90];
elseif ~isnumeric(latlim) || numel(latlim) ~= 2
E.badinput('LATLIM must be a 2 element numeric vector');
end
if ~exist('datelim','var')
datelim = [];
elseif ~isnumeric(datelim) || numel(datelim) ~= 2 || any(datelim < 0)
E.badinput('DATELIM must be a 2 element numeric vector with both elements >0');
end
% Best guess for the number of observations
init_obs_vec = nan(1,1e6);
init_obs_cell = cell(1,1e6);
dvec = init_obs_vec;
wind_dir = init_obs_vec;
wind_dir_qual = init_obs_cell;
wind_vel = init_obs_vec;
wind_vel_qual = init_obs_cell;
temperature = init_obs_vec;
temperature_qual = init_obs_cell;
fid = fopen(file);
cleanup_fxn = onCleanup(@() cleanup(fid));
tline = fgetl(fid);
% Initial checking; get the static fields and make sure that we are in in
% lat/lon domain
[usaf_id, wban_id, lon, lat, elev] = parse_line(tline);
if lon < min(lonlim) || lon > max(lonlim) || lat < min(latlim) || lat > max(latlim)
fprintf('Site outside specified longitude and latitude bounds\n')
Site = NOAAISDSite();
return
else
Site = NOAAISDSite(usaf_id, wban_id, lon, lat, elev);
end
i = 0;
while ischar(tline)
i = i + 1;
[~, ~, ~, ~, ~, dvec(i), wind_dir(i), wind_dir_qual{i}, wind_vel(i), wind_vel_qual{i}, temperature(i), temperature_qual{i}] = parse_line( tline );
tline = fgetl(fid);
end
dvec = dvec(1:i);
wind_dir = wind_dir(1:i);
wind_dir_qual = wind_dir_qual(1:i);
wind_vel = wind_vel(1:i);
wind_vel_qual = wind_vel_qual(1:i);
temperature = temperature(1:i);
temperature_qual = temperature_qual(1:i);
if ~isempty(datelim)
xx = dvec >= min(datelim) & dvec <= max(datelim);
end
if sum(xx) > 0
Site.set_dates(dvec(xx));
Site.set_wind_dir(wind_dir(xx), wind_dir_qual(xx));
Site.set_wind_vel(wind_vel(xx), wind_vel_qual(xx));
Site.set_temperature(temperature(xx), temperature_qual(xx));
else
Site = NOAAISDSite();
fprintf('Site %s has no data within dates specified\n', usaf_id);
end
end
function [usaf_id, wban_id, lon, lat, elev, dnum, wind_dir, wind_dir_quality, wind_vel, wind_vel_quality, temperature, temperature_quality] = parse_line( line_in )
E = JLLErrors;
if ~ischar(line_in)
E.badinput('LINE_IN must be a string')
end
wban_fill = 99999;
lon_fill = 999999;
lon_scale = 1000;
lat_fill = 99999;
lat_scale = 1000;
elevation_fill = 9999;
elevation_scale = 1;
wind_dir_fill = 999;
wind_dir_scale = 1;
wind_vel_fill = 9999;
wind_vel_scale = 10;
temperature_fill = 9999;
temperature_scale = 10;
usaf_id = line_in(5:10);
wban_id = convert_str_to_val(line_in(11:15), wban_fill, 1);
dnum = datenum(line_in(16:27),'yyyymmddHHMM');
lon = convert_str_to_val(line_in(35:41), lon_fill, lon_scale);
lat = convert_str_to_val(line_in(29:34), lat_fill, lat_scale);
elev = convert_str_to_val(line_in(47:51), elevation_fill, elevation_scale);
wind_dir = convert_str_to_val(line_in(61:63), wind_dir_fill, wind_dir_scale);
wind_dir_quality = line_in(64);
wind_vel = convert_str_to_val(line_in(66:69), wind_vel_fill, wind_vel_scale);
wind_vel_quality = line_in(70);
temperature = convert_str_to_val(line_in(88:92), temperature_fill, temperature_scale);
temperature_quality = line_in(93);
end
function val = convert_str_to_val(substr, fill, scale)
val = str2double(substr);
if val == fill
val = nan;
else
val = val ./ scale;
end
end
function cleanup(fid)
fprintf('Closing fid %d\n', fid);
fclose(fid);
end
|
github
|
CohenBerkeleyLab/WRF_Utils-master
|
wrf_met_comp_plots.m
|
.m
|
WRF_Utils-master/MetComparison/wrf_met_comp_plots.m
| 25,618 |
utf_8
|
12cd35eb0367d1da22ff22eb9ad01dd9
|
function [ varargout ] = wrf_met_comp_plots( plottype, varargin )
%WRF_MET_COMP_PLOTS Collection of plots for comparing WRF output meteorology against references.
E = JLLErrors;
noaa_match_dir = '/Users/Josh/Documents/MATLAB/BEHR/Workspaces/WRF/NOAA ISD Obs Comparison/';
switch lower(plottype)
case 'spatial'
case 'noaa-timeser-all'
all_noaa_timeseries();
case 'noaa-timeser'
noaa_error_timeseries();
case 'met-error'
met_error_plots();
case 'rmse-trend'
rmse_trend_from_fig(varargin{1});
% Functions below here aren't really meant to be called externally, but are
% available just the same
case 'match_wrf_met'
varargout{1} = match_wrf_met(varargin{:});
end
function plot_spatial_agreement()
% This function will make a plot showing the agreement between WRF
% variables and NOAA observations as a map. It can plot either
% winds or temperature and as RMSE or correlation
agreement_type = ask_multichoice('How to measure agreement?', {'RMSE','Correlation'},'list',true);
quantity = ask_multichoice('Which quantity to plot?', {'Winds', 'Temperature'}, 'list', true);
end
function all_noaa_timeseries()
quantity = ask_multichoice('Which quantity to plot?', {'Winds (U-V)','Winds (vel-dir)', 'Temperature'}, 'list', true);
% Load all matches
files = dir(fullfile(noaa_match_dir,'*Match*.mat'));
legstr = cell(size(files));
Matches = cell(size(files));
for a=1:numel(files)
M = load(fullfile(noaa_match_dir, files(a).name));
fns = fieldnames(M);
if numel(fns) > 1; warning('Only plotting first variable in %s', files(a).name); end
Matches{a} = M.(fns{1});
[~, legstr{a}] = fileparts(files(a).name);
end
if strcmpi(quantity, 'winds (vel-dir)')
rmses = cell(numel(Matches),2);
else
rmses = cell(numel(Matches),1);
end
xdates = cell(numel(Matches,1));
for a=1:numel(Matches)
[xdates{a}, rmses(a,:), ystr] = noaa_error_timeseries(Matches{a}, quantity);
end
for b=1:size(rmses,2)
figure;
hold on
for a=1:size(rmses,1)
plot(xdates{a}, rmses{a,b}, 'o-','linewidth',2)
end
datetick('x');
set(gca,'XTickLabelRotation',45);
set(gca,'FontSize',16);
ylabel(ystr{b});
legend(legstr{:});
end
end
function varargout = noaa_error_timeseries(Match, quantity)
% This function will make a time series plot showing the difference
% between WRF and observed quantities day by day. In theory, this
% agreement should get worse over time. If there is an output, it
% won't plot, but will return the datenums and errors (this way you
% can use it to create timeseries for multiple cases and plot them
% in another function).
% Currently unused
%agreement_type = ask_multichoice('How to measure agreement?', {'RMSE'},'list',true);
if ~exist('quantity','var')
quantity = ask_multichoice('Which quantity to plot?', {'Winds (U-V)','Winds (vel-dir)', 'Temperature'}, 'list', true);
end
if ~exist('Match','var')
% Load the Match object from match_wrf_noaa
files = dir(fullfile(noaa_match_dir,'*Match*.mat'));
files = {files.name};
match_file = ask_multichoice('Choose the match file to plot', files, 'list', true);
M = load(fullfile(noaa_match_dir,match_file));
fns = fieldnames(M);
if numel(fns) > 1; warning('Only plotting first variable in %s', match_file); end
Match = M.(fns{1}); clear M
end
ndays = size(Match.wrf_U,3);
switch lower(quantity)
case 'winds (u-v)'
rmse = cell(1,1);
rmse = wind_rmse(reshape(Match.wrf_U,[],ndays), reshape(Match.wrf_V, [], ndays), reshape(Match.noaa_U, [], ndays), reshape(Match.noaa_V, [], ndays));
ystr = {'RMSE winds (U+V, m/s)'};
case 'winds (vel-dir)'
rmse = cell(1,2);
[rmse{1}, rmse{2}] = wind_rmse_veldir(reshape(Match.wrf_U,[],ndays), reshape(Match.wrf_V, [], ndays), reshape(Match.noaa_U, [], ndays), reshape(Match.noaa_V, [], ndays));
ystr = {'RMSE velocity (m/s)', 'RMSE direction (deg)'};
case 'temperature'
rmse = cell(1,1);
rmse = temperature_rmse(reshape(Match.wrf_T,[],ndays), reshape(Match.noaa_T,[],ndays));
ystr = {'RMSE temperature (K)'};
otherwise
E.notimplemented(quantity);
end
% Get rid of hour, minute, second in the datenum
xdates = datenum(datestr(Match.dnums(1,:),'yyyy-mm-dd'));
if nargout == 3
varargout{1} = xdates;
varargout{2} = rmse;
varargout{3} = ystr;
else
for a=1:numel(rmse)
figure;
plot(xdates, rmse{a}, 'ko-');
datetick('x','mm/dd');
xlabel('Date')
set(gca,'xtickLabelRotation',45);
ylabel(ystr{a});
end
end
end
function met_error_plots(Match)
matchdir = '/Users/Josh/Documents/MATLAB/BEHR/Workspaces/WRF/NARR Comparison';
if ~exist('Match','var')
F=dir(fullfile(matchdir,'*.mat'));
opts = {F.name};
opts{end+1} = 'Gen new match file';
user_ans = ask_multiselect('Which match file to use?', opts);
if any(strcmpi(user_ans,'gen new match file'))
fprintf('To generate a new match file, use wrf_met_comp_plots(''match_wrf_met'') and save the structure in\n%s\n',matchdir);
return
else
Match = cell(1,numel(user_ans));
legstr = cell(1,numel(user_ans));
for a=1:numel(user_ans)
M = load(fullfile(matchdir, user_ans{a}),'Match');
Match{a} = M.Match;
legstr{a} = user_ans{a};
end
end
end
% Check if we're loading Match files with vertical information or
% not
d3_matches = false(size(Match));
for a=1:numel(d3_matches)
d3_matches(a) = ndims(Match{a}.wrf_U)>3;
end
if ~all(d3_matches) && ~all(~d3_matches)
E.callError('inconsistent_matches','Loaded Matches have inconsistent dimensions')
end
plot_types = {'time series','spatial','spatial slices'};
plt = ask_multichoice('Which type of plot to make?', plot_types, 'list', true');
allowed_quantities = {'winds (U+V)','winds (dir+vel)','temperature'};
quantity = ask_multichoice('Which quantity to plot?', allowed_quantities, 'list', true);
if all(d3_matches)
nlevels = size(Match{1}.wrf_U,3);
levels = ask_number('Enter what model levels to plot the RMSE for (separated by a space)','default',1,'testfxn',@(x) any(x >= 1 & x <= 29 & mod(x,1) == 0),'testmsg',...
sprintf('All values must be between 1 and %d and must be integers',29));
else
levels = 1;
end
switch lower(plt)
case 'time series'
met_error_timeseries(Match, quantity, legstr, levels);
case 'spatial'
if numel(Match) > 1
E.badinput('Plotting multiple matched runs is incompatible with a spatial plot')
elseif iscell(Match)
Match = Match{1};
end
met_error_spatial(Match, quantity);
case 'spatial slices'
met_error_slices(Match, quantity, {F.name});
otherwise
E.notimplemented(plt)
end
end
function met_error_slices(Match_in, quantity, matchnames)
% Call interactively from met_error_plots.
% First we need to find which Match object has the shortest date
% vector; we will restrict all others to that.
dvec = Match_in{1}.dvec;
for a=2:numel(Match_in)
if numel(Match_in{a}.dvec) < numel(dvec)
dvec = Match_in{a}.dvec;
end
end
[slon, slat] = state_outlines('not', 'ak', 'hi');
% Now get the difference of either wind speed or wind direction
for a=1:numel(Match_in)
Match = Match_in{a};
tt = ismember(Match.dvec, dvec);
if sum(tt) ~= numel(dvec)
E.callError('Not all dates in the smallest datevec are present in %s', matchnames{a});
end
if strcmpi(quantity, 'winds (dir+vel)')
wrf_vel = sqrt(Match.wrf_U(:,:,tt) .^ 2 + Match.wrf_V(:,:,tt) .^ 2);
met_vel = sqrt(Match.met_U(:,:,tt) .^ 2 + Match.met_V(:,:,tt) .^ 2);
diff_vel = wrf_vel - met_vel;
wrf_dir = atan2d(Match.wrf_V(:,:,tt), Match.wrf_U(:,:,tt));
met_dir = atan2d(Match.met_V(:,:,tt), Match.met_U(:,:,tt));
diff_dir = angle_diffd(wrf_dir, met_dir);
else
E.notimplemented(quantity)
end
plot_slice_gui(diff_vel, Match.lon, Match.lat, slon, slat, sprintf('%s - velocity', matchnames{a}));
plot_slice_gui(diff_dir, Match.lon, Match.lat, slon, slat, sprintf('%s - direction', matchnames{a}));
end
end
function met_error_spatial(Match, quantity)
% Call interactively from met_error_plots to load the match file
% and get the quantity to plot.
blank_mat = nan(size(Match.lon));
if strcmpi(quantity, 'winds (dir+vel)')
rmse = cell(1,2);
rmse(:) = {blank_mat};
else
rmse = {blank_mat};
end
for a=1:size(rmse{1},1)
for b=1:size(rmse{1},2)
if ~isempty(regexp(quantity,'winds','once'))
wrf_U_slice = squeeze(Match.wrf_U(a,b,:));
wrf_V_slice = squeeze(Match.wrf_V(a,b,:));
narr_U_slice = squeeze(Match.met_U(a,b,:));
narr_V_slice = squeeze(Match.met_V(a,b,:));
if strcmpi(quantity, 'winds (U+V)')
rmse{1}(a,b) = wind_rmse(wrf_U_slice, wrf_V_slice, narr_U_slice, narr_V_slice);
cblabel{1} = 'RMSE wind U+V (m/s)';
elseif strcmpi(quantity, 'winds (dir+vel)');
[rmse{1}(a,b), rmse{2}(a,b)] = wind_rmse_veldir(wrf_U_slice, wrf_V_slice, narr_U_slice, narr_V_slice);
cblabel{1} = 'RMSE wind speed (m/s)';
cblabel{2} = 'RMSE wind direction (deg)';
else
E.notimplemented(quantity)
end
elseif strcmpi(quantity, 'temperature')
wrf_T_slice = squeeze(Match.wrf_T(a,b,:));
narr_T_slice = squeeze(Match.met_T(a,b,:));
rmse{1}(a,b) = temperature_rmse(wrf_T_slice, narr_T_slice);
cblabel{1} = 'RMSE temperature (K)';
else
E.notimplemented(quantity)
end
end
end
for f=1:numel(rmse)
figure;
pcolor(Match.lon, Match.lat, rmse{f});
colormap jet
cb = colorbar;
cb.Label.String = cblabel{f};
shading flat
state_outlines('k','not','ak','hi');
set(gca,'fontsize',16)
end
end
function met_error_timeseries(Match, quantity, legstr, levels)
% Call interactively from met_error_plots to load the match file
% and get the quantity to plot.
if ~exist('levels','var')
levels = 1;
end
% Handle 3D (rather than 4D) match structures by creating a
% singleton dimension 3
for a=1:numel(Match)
fns = fieldnames(Match{a});
for f=1:numel(fns)
if ndims(Match{a}.(fns{f})) == 3
sz = size(Match{a}.(fns{f}));
Match{a}.(fns{f}) = reshape(Match{a}.(fns{f}), [sz(1:3),1,sz(3)]);
end
end
end
levels_inds = zeros(numel(Match), numel(levels));
for a=1:numel(Match)
if isfield(Match{a}, 'model_levels')
match_levels = Match{a}.model_levels;
else
match_levels = 1:size(Match{a}.wrf_U,3);
end
for b=1:numel(levels)
li = find(levels(b)==match_levels);
if ~isempty(li)
levels_inds(a,b) = li;
end
end
end
if strcmpi(quantity, 'winds (dir+vel)')
rmse = cell(numel(Match),numel(levels),2);
else
rmse = cell(numel(Match),numel(levels),1);
end
for a=1:numel(Match)
ndays = numel(Match{a}.dvec);
for b=1:numel(levels)
if levels_inds(a,b) > 0
l = levels_inds(a,b);
else
% Level not present in this Match object, skip
continue
end
switch lower(quantity)
case 'winds (u+v)'
rmse{a,b} = wind_rmse(reshape(Match{a}.wrf_U(:,:,l,:),[],ndays), reshape(Match{a}.wrf_V(:,:,l,:),[],ndays), reshape(Match{a}.met_U(:,:,l,:),[],ndays), reshape(Match{a}.met_V(:,:,l,:),[],ndays));
ystr = {'RMSE in winds (U+V, m/s)'};
case 'winds (dir+vel)'
[rmse{a,b,1}, rmse{a,b,2}] = wind_rmse_veldir(reshape(Match{a}.wrf_U(:,:,l,:),[],ndays), reshape(Match{a}.wrf_V(:,:,l,:),[],ndays), reshape(Match{a}.met_U(:,:,l,:),[],ndays), reshape(Match{a}.met_V(:,:,l,:),[],ndays));
ystr = {'RMSE in wind speed (m/s)', 'RMSE in wind direction (deg)'};
case 'temperature'
rmse{a,b} = temperature_rmse(reshape(Match{a}.wrf_T(:,:,l,:),[],ndays), reshape(Match{a}.met_T(:,:,l,:),[],ndays));
ystr = {'RMSE in temperature (K)'};
otherwise
E.notimplemented(quantity);
end
end
end
levels_sym = {'o','s','d','v'};
levels_lstyle = {'-','--',':','-.'};
starttime_colors = {'b','r',[0 0.5 0],'m'};
for i=1:size(rmse,3)
l = gobjects(size(rmse,1), size(rmse,2));
lstr = cell(size(l));
figure;
for b=1:size(rmse,2)
bmod = mod(b-1, numel(levels_sym))+1;
marker = levels_sym{bmod};
lstyle = levels_lstyle{bmod};
for a=1:size(rmse,1)
% You'll want to add more colors if you need to plot
% more starting times
sercol = starttime_colors{a};
l(a,b) = line(Match{a}.dvec, rmse{a,b,i}, 'linestyle',lstyle,'marker',marker,'color',sercol,'linewidth',2);
lstr{a,b} = sprintf('%s, level %d', legstr{a}, levels(b));
end
end
datetick('x');
set(gca,'XTickLabelRotation',45);
set(gca,'FontSize',16);
ylabel(ystr{i});
legend(l(:),lstr(:));
end
end
function rmse_trend_from_fig(axes)
ch = get(axes, 'children');
for a=1:numel(ch)
dvec = ch(a).XData;
x = dvec - floor(dvec(1));
rmse = ch(a).YData;
figure;
plot(x, rmse, 'ko');
% There is no uncertainty in the date, so use y-residual
% fitting
plot_fit_line(x, rmse, 'regression', 'y-resid', 'one2one', false);
set(gca,'fontsize', 16);
ylabel(axes.YLabel.String);
title(ch(a).DisplayName);
end
end
function Match = match_wrf_met(wrfdir, metdir, avgday)
% This function will compare WRF output meteorology to that
% contained in the met_em files that are derived from NARR
% directly.
sharedir='/Volumes/share2/USERS/LaughnerJ/WRF/NudgeTest-US/';
D = dir(sharedir);
D(1:2) = []; % remove the . and .. entries
if ~exist('wrfdir','var')
wrfdir = ask_multichoice('Choose the directory with the WRF output.', {D.name}, 'list', true);
wrfdir = fullfile(sharedir, wrfdir);
end
if ~exist('metdir','var')
metdir = ask_multichoice('Choose the directory with the met_em files or wrfinput_subset files.', {D.name}, 'list', true);
metdir = fullfile(sharedir, metdir);
end
if ~exist('surf_bool','var')
levels = ask_number('Enter the levels to include in the output, separated by space. Valid levels are 1-29', 'testfxn', @(x) all(x>=1 & x<=29), 'testmsg', 'All level indices must be between 1 and 29');
end
avgday = false;
% if ~exist('avgday','var')
% user_ans = ask_multichoice('Average all available hours in a day to a single value?', {'y','n'});
% avgday = strcmp(user_ans,'y');
% end
% if avgday
% E.notimplemented('averaging to one per day');
% end
% Met files are usually output every three hours, wrf files every
% hour to half hour. If we're supposed to be using WRF-BEHR files,
% the only overlap for each day will be 1800 and 2100 UTC.
% Otherwise, if we have the wrfout_subset files, they should be
% available every three hours
wrffiles = dir(fullfile(wrfdir, 'wrfout_*'));
if ~isempty(wrffiles)
all_hours = true;
else
wrffiles = dir(fullfile(wrfdir, 'WRF_BEHR*.nc'));
all_hours = false;
if isempty(wrffiles)
E.filenotfound('wrfout_* or WRF_BEHR*.nc')
end
end
metfiles = dir(fullfile(metdir, 'wrfinput_*'));
met_varnames.lon = 'XLONG';
met_varnames.lat = 'XLAT';
met_varnames.U = 'U';
met_varnames.V = 'V';
met_varnames.T = 'TT';
if isempty(metfiles)
metfiles = dir(fullfile(metdir, 'met_em*'));
met_varnames.lon = 'XLONG_M';
met_varnames.lat = 'XLAT_M';
met_varnames.U = 'UU';
met_varnames.V = 'VV';
met_varnames.T = 'TT';
if ~isempty(metfiles)
warning('Could not find wrfinput_subset files, using met_em files. These are not properly interpolated to WRF vertical coordinates, so the comparisons may have greater error than expected.');
else
E.filenotfound('wrfinput_* or met_em*');
end
end
if ~all_hours
metfiles = glob({metfiles.name}, '_(18|21)-00-00');
else
metfiles = {metfiles.name};
end
metinfo = ncinfo(fullfile(metdir, metfiles{1}));
metvars = {metinfo.Variables.Name};
is_met_tt = ismember('TT', metvars);
wrfinfo = ncinfo(fullfile(wrfdir, wrffiles(1).name));
wrfvars = {wrfinfo.Variables.Name};
is_wrf_tt = ismember('TT', wrfvars);
% Go ahead and load lat/lon, can use to get the size of array we
% need
xlon = ncread(fullfile(metdir, metfiles{1}),met_varnames.lon);
xlat = ncread(fullfile(metdir, metfiles{1}),met_varnames.lat);
wrf_size = get_wrf_array_size(fullfile(metdir, metfiles{1}));
blank_mat = nan([wrf_size(1:2), numel(levels), numel(metfiles)]);
wrf_U = blank_mat;
wrf_V = blank_mat;
wrf_T = blank_mat;
met_U = blank_mat;
met_V = blank_mat;
met_T = blank_mat;
dvec = nan(numel(metfiles),1);
% Loop through the met files. For each find the corresponding day's
% WRF_BEHR file.
last_wrf_file = '';
wrffiles = {wrffiles.name};
include_inds = true(numel(metfiles),1);
for a = 1:numel(metfiles)
dstr = regexp(metfiles{a}, '\d\d\d\d-\d\d-\d\d_\d\d-\d\d-\d\d', 'match', 'once');
dnum = datenum(dstr, 'yyyy-mm-dd_HH-MM-SS');
dvec(a) = dnum;
% Load met data
[met_U_a, met_V_a, met_cos, met_sin] = read_wrf_vars(metdir, metfiles(a), {met_varnames.U,met_varnames.V,'COSALPHA','SINALPHA'});
if is_met_tt
met_T_a = read_wrf_vars(metdir, metfiles{a}, met_varnames.T);
else
met_T_a = convert_wrf_temperature(fullfile(metdir, metfiles{a}));
end
[met_U_a, met_V_a] = wrf_winds_transform(met_U_a, met_V_a, met_cos, met_sin);
met_U(:,:,:,a) = met_U_a(:,:,levels);
met_V(:,:,:,a) = met_V_a(:,:,levels);
met_T(:,:,:,a) = met_T_a(:,:,levels);
if ~all_hours
this_wrf_file = glob(wrffiles, datestr(dnum, 'yyyy-mm-dd'));
else
this_wrf_file = glob(wrffiles, datestr(dnum, 'yyyy-mm-dd_HH[:-]MM[:-]SS'));
end
if isempty(this_wrf_file)
include_inds(a) = false;
continue
end
this_wrf_file = this_wrf_file{1};
if ~strcmp(this_wrf_file, last_wrf_file)
[wrf_U_a, wrf_V_a, wrf_cos, wrf_sin, wrf_times] = read_wrf_vars(wrfdir, {this_wrf_file}, {'U','V','COSALPHA','SINALPHA','Times'});
if is_wrf_tt
wrf_T_a = read_wrf_vars(wrfdir, {this_wrf_file}, 'TT');
else
wrf_T_a = convert_wrf_temperature(fullfile(wrfdir, this_wrf_file));
end
wrf_cos = wrf_cos(:,:,1);
wrf_sin = wrf_sin(:,:,1);
[wrf_U_a, wrf_V_a] = wrf_winds_transform(wrf_U_a, wrf_V_a, wrf_cos, wrf_sin);
wrf_times = wrf_times';
last_wrf_file = this_wrf_file;
end
% Put the proper slices of WRF data in the output
% arrays. Extraneous if using wrfout_subset files that only
% include a single time, but if multiple times included in the
% output, this is necessary.
xx = strcmp(cellstr(wrf_times), datestr(dnum,'yyyy-mm-dd_HH:MM:SS'));
if sum(xx) < 1
E.callError('time_not_found', 'Time %s not found in WRF output file %s', datestr(dnum, 'yyyy-mm-dd_HH:MM:SS'), this_wrf_file);
end
wrf_U(:,:,:,a) = wrf_U_a(:,:,levels,xx);
wrf_V(:,:,:,a) = wrf_V_a(:,:,levels,xx);
wrf_T(:,:,:,a) = wrf_T_a(:,:,levels,xx);
end
% If we want to average down to one value per day, then we need to
% identify which slices belong to the same day
if avgday
E.notimplemented('averaging to one per day');
%dvec_day = unique(floor(dvec));
%for d=1:numel(dvec_day)
% dd = floor(dvec) == dvec_day(d)
% ...
end
Match.lon = xlon;
Match.lat = xlat;
Match.dvec = dvec(include_inds);
Match.model_levels = levels;
Match.wrf_U = wrf_U(:,:,:,include_inds);
Match.wrf_V = wrf_V(:,:,:,include_inds);
Match.wrf_T = wrf_T(:,:,:,include_inds);
Match.met_U = met_U(:,:,:,include_inds);
Match.met_V = met_V(:,:,:,include_inds);
Match.met_T = met_T(:,:,:,include_inds);
end
end
function rmse = wind_rmse(wrf_U, wrf_V, true_U, true_V)
% Computes root mean squared error for the winds (as a sum of the errors in
% the winds). RMSE will be calculated for each column in the inputs.
del_u = wrf_U - true_U;
del_v = wrf_V - true_V;
sq_del = nansum2(del_u .^ 2 + del_v .^ 2, 1);
valid_obs = ~isnan(wrf_U) & ~isnan(wrf_V) & ~isnan(true_U) & ~isnan(true_V);
n_obs = nansum2(valid_obs,1);
rmse = sqrt ( sq_del ./ n_obs );
end
function [rmse_vel, rmse_dir] = wind_rmse_veldir(wrf_U, wrf_V, true_U, true_V)
wrf_vel = sqrt(wrf_U .^ 2 + wrf_V .^ 2);
wrf_dir = atan2d(wrf_V, wrf_U);
true_vel = sqrt(true_U .^ 2 + true_V .^ 2);
true_dir = atan2d(true_V, true_U);
del_vel = wrf_vel - true_vel;
del_dir = angle_diffd(wrf_dir, true_dir);
sq_delvel = nansum2( del_vel .^ 2, 1);
sq_deldir = nansum2( del_dir .^ 2, 1);
valid_obs = ~isnan(wrf_U) & ~isnan(wrf_V) & ~isnan(true_U) & ~isnan(true_V);
n_obs = nansum2(valid_obs,1);
rmse_vel = sqrt( sq_delvel ./ n_obs );
rmse_dir = sqrt( sq_deldir ./ n_obs );
end
function rmse = temperature_rmse(wrf_T, true_T)
% Computes root mean squared error for the temperatures. RMSE will be
% calculated for each column in the inputs.
del_t = wrf_T - true_T;
sq_del = nansum2( del_t .^ 2, 1);
valid_obs = ~isnan(wrf_T) & ~isnan(true_T);
n_obs = nansum2(valid_obs,1);
rmse = sqrt ( sq_del ./ n_obs );
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.