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
|
BottjerLab/Acoustic_Similarity-master
|
teststat.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/teststat.m
| 20,496 |
utf_8
|
d2bfb11cf5e6a0d7221866a5ff6cd823
|
% teststat - EEGLAB statistical testing function
%
% Statistics are critical for inference testing in Science. It is thus
% primordial to make sure than all the statistics implemented are
% robust and at least bug free. Statistical function using complex
% formulas are inherently prone to bugs. EEGLAB functions are all the
% more prone to bugs given that they only use complex Matlab code to
% avoid loops and speed up computation.
%
% This test function does not garantee that EEGLAB statistical functions
% are bug free. It does assure though that bugs are unlikely and minor
% if they are present.
%
% This function test 3 things.
%
% * First, it checks that for vector inputs the EEGLAB functions return
% the same output as other reference functions from the Matlab statistical
% toolbox or from other packages tested against the SPSS software for
% repeated measure ANOVA (rm_anova2 function).
%
% * Second, it checks that array inputs with different number of dimensions
% (from 1 to 3) the EEGLAB function return the same output.
%
% * Third, it checks that the permutation and bootstrap methods shuffle
% the data properly by running multiple tests.
function teststat;
% testing paired t-test
% ---------------------
a = { rand(1,10) rand(1,10)+0.5 };
[t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[h p tmp stats] = ttest(a{1}, a{2});
fprintf('Statistics paired statcond t-value %2.2f df=%d p=%0.4f\n', t, df, pvals);
fprintf('Statistics paired ttest func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p);
assertsame([t stats.tstat], [df stats.df], [pvals p]);
disp('--------------------');
% testing unpaired t-test
% -----------------------
[t df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[h p tmp stats] = ttest2(a{1}, a{2});
fprintf('Statistics paired statcond t-value %2.2f df=%d p=%0.4f\n', t, df, pvals);
fprintf('Statistics paired ttest2 func. t-value %2.2f df=%d p=%0.4f\n', stats.tstat, stats.df, p);
assertsame([t stats.tstat], [df stats.df], [pvals p]);
disp('--------------------');
% testing paired 1-way ANOVA
% --------------------------
a = { rand(1,10) rand(1,10) rand(1,10)+0.2; rand(1,10) rand(1,10)+0.2 rand(1,10) };
[F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
stats = rm_anova2( [ a{1,1}';a{1,2}';a{1,3}'], repmat([1:10]', [3 1]), [o;o;o], [z;o;t], {'a','b'});
fprintf('Statistics 1-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals);
fprintf('Statistics 1-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{3,5}, stats{3,3}, stats{6,3}, stats{3,6});
assertsame([F stats{3,5}], [df(1) stats{3,3}], [df(2) stats{6,3}], [pvals stats{3,6}]);
disp('--------------------');
% testing paired 2-way ANOVA
% --------------------------
[F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
z = zeros(10,1); o = ones(10,1); t = ones(10,1)*2;
stats = rm_anova2( [ a{1,1}';a{1,2}';a{1,3}';a{2,1}';a{2,2}';a{2,3}' ], ...
repmat([1:10]', [6 1]), [o;o;o;z;z;z], [z;o;t;z;o;t], {'a','b'});
fprintf('Statistics 2-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3});
fprintf('Statistics 2-way paired rm_avova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{7,3}, stats{4,6});
assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{7,3}], [pvals{3} stats{4,6}]);
disp('--------------------');
% testing 1-way unpaired ANOVA
% ----------------------------
[F df pvals surog] = statcond(a(1,:), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[p stats] = anova1( [ a{1,1}' a{1,2}' a{1,3}' ],{}, 'off');
fprintf('Statistics 1-way unpaired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F, df(1), df(2), pvals);
fprintf('Statistics 1-way unpaired anova1 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{2,5}, stats{2,3}, stats{3,3}, stats{2,6});
assertsame([F stats{2,5}], [df(1) stats{2,3}], [df(2) stats{3,3}], [pvals stats{2,6}]);
disp('--------------------');
% testing 2-way unpaired ANOVA
% ----------------------------
[F df pvals surog] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[p stats] = anova2( [ a{1,1}' a{1,2}' a{1,3}'; a{2,1}' a{2,2}' a{2,3}' ], 10, 'off');
fprintf('Statistics 2-way paired statcond F-value %2.2f df1=%d df2=%d p=%0.4f\n', F{3}, df{3}(1), df{3}(2), pvals{3});
fprintf('Statistics 1-way unpaired anova2 func. F-value %2.2f df1=%d df2=%d p=%0.4f\n', stats{4,5}, stats{4,3}, stats{5,3}, stats{4,6});
assertsame([F{3} stats{4,5}], [df{3}(1) stats{4,3}], [df{3}(2) stats{5,3}], [pvals{3} stats{4,6}]);
disp('--------------------');
% testing different dimensions in statcond
% ----------------------------------------
a = { rand(1,10) rand(1,10)+0.5 rand(1,10)};
b = { rand(10,10) rand(10,10)+0.5 rand(10,10)}; b{1}(4,:) = a{1}; b{2}(4,:) = a{2}; b{3}(4,:) = a{3};
c = { rand(5,10,10) rand(5,10,10)+0.5 rand(5,10,10)}; c{1}(2,4,:) = a{1}; c{2}(2,4,:) = a{2}; c{3}(2,4,:) = a{3};
d = { rand(2,5,10,10) rand(2,5,10,10)+0.5 rand(2,5,10,10)}; d{1}(1,2,4,:) = a{1}; d{2}(1,2,4,:) = a{2}; d{3}(1,2,4,:) = a{3};
[t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1);
fprintf('Statistics paired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4));
fprintf('Statistics paired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4));
fprintf('Statistics paired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d(1:2), 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond t-test dim1 t-value %2.2f df=%d p=%0.4f\n', t1, df1, pvals1);
fprintf('Statistics unpaired statcond t-test dim2 t-value %2.2f df=%d p=%0.4f\n', t2(4), df2, pvals2(4));
fprintf('Statistics unpaired statcond t-test dim3 t-value %2.2f df=%d p=%0.4f\n', t3(2,4), df3, pvals3(2,4));
fprintf('Statistics unpaired statcond t-test dim4 t-value %2.2f df=%d p=%0.4f\n', t4(1,2,4), df4, pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1);
fprintf('Statistics paired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4));
fprintf('Statistics paired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4));
fprintf('Statistics paired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond anova 1-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1, df1(1), df1(2), pvals1);
fprintf('Statistics unpaired statcond anova 1-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2(4), df2(1), df2(2), pvals2(4));
fprintf('Statistics unpaired statcond anova 1-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3(2,4), df3(1), df3(2), pvals3(2,4));
fprintf('Statistics unpaired statcond anova 1-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4(1,2,4), df4(1), df4(2), pvals4(1,2,4));
assertsame([t1 t2(4) t3(2,4) t4(1,2,4)], [df1 df2 df3 df4], [pvals1 pvals2(4) pvals3(2,4) pvals4(1,2,4)]);
disp('--------------------');
a(2,:) = a; a{1} = a{1}/2;
b(2,:) = b; b{1} = b{1}/2;
c(2,:) = c; c{1} = c{1}/2;
d(2,:) = d; d{1} = d{1}/2;
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'on');
fprintf('Statistics paired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3});
fprintf('Statistics paired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4));
fprintf('Statistics paired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4));
fprintf('Statistics paired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4));
assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]);
disp('--------------------');
[t1 df1 pvals1] = statcond(a, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t2 df2 pvals2] = statcond(b, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t3 df3 pvals3] = statcond(c, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
[t4 df4 pvals4] = statcond(d, 'mode', 'param', 'verbose', 'off', 'paired', 'off');
fprintf('Statistics unpaired statcond anova 2-way dim1 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t1{3}, df1{3}(1), df1{3}(2), pvals1{3});
fprintf('Statistics unpaired statcond anova 2-way dim2 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t2{3}(4), df2{3}(1), df2{3}(2), pvals2{3}(4));
fprintf('Statistics unpaired statcond anova 2-way dim3 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t3{3}(2,4), df3{3}(1), df3{3}(2), pvals3{3}(2,4));
fprintf('Statistics unpaired statcond anova 2-way dim4 t-value %2.2f df1=%d df2=%d p=%0.4f\n', t4{3}(1,2,4), df4{3}(1), df4{3}(2), pvals4{3}(1,2,4));
assertsame([t1{3} t2{3}(4) t3{3}(2,4) t4{3}(1,2,4)], [df1{3}(1) df2{3}(1) df3{3}(1) df4{3}(1)], [df1{3}(2) df2{3}(2) df3{3}(2) df4{3}(2)], [pvals1{3} pvals2{3}(4) pvals3{3}(2,4) pvals4{3}(1,2,4)]);
disp('--------------------');
% testing shuffling and permutation for bootstrap
% -----------------------------------------------
clear a;
m1 = [1:10];
m2 = [1:10]+100;
m3 = [1:10]+1000;
a{1} = { m1 m2 };
a{2} = { m1 m2 m3 };
a{3} = { [ zeros(9,10); m1] [ zeros(9,10); m2] };
a{4} = { [ zeros(9,10); m1] [ zeros(9,10); m2] [ zeros(9,10); m3] };
tmpa = zeros(9,8,10); tmpa(end,end,:) = m1;
tmpb = zeros(9,8,10); tmpb(end,end,:) = m2;
tmpc = zeros(9,8,10); tmpc(end,end,:) = m3;
a{5} = { tmpa tmpb };
a{6} = { tmpa tmpb tmpc };
for method = 1:2
if method == 2, opt = {'arraycomp', 'off'}; else opt = {}; end;
for dim = 1:length(a)
[sa1] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'on', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
[sa2] = statcond(a{dim}, 'mode', 'perm' , 'verbose', 'off', 'paired', 'on', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
[sa3] = statcond(a{dim}, 'mode', 'bootstrap', 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
[sa4] = statcond(a{dim}, 'mode', 'perm' , 'verbose', 'off', 'paired', 'off', 'returnresamplingarray', 'on', opt{:}, 'naccu', 10);
% select data
nd = ndims(sa1{1});
if nd == 2 && size(sa1{1},2) > 1
for t=1:length(sa1),
sa1{t} = sa1{t}(end,:);
sa2{t} = sa2{t}(end,:);
sa3{t} = sa3{t}(end,:);
sa4{t} = sa4{t}(end,:);
end;
elseif nd == 3
for t=1:length(sa1),
sa1{t} = squeeze(sa1{t}(end,end,:));
sa2{t} = squeeze(sa2{t}(end,end,:));
sa3{t} = squeeze(sa3{t}(end,end,:));
sa4{t} = squeeze(sa4{t}(end,end,:));
end;
elseif nd == 4
for t=1:length(sa1),
sa1{t} = squeeze(sa1{t}(end,end,end,:));
sa2{t} = squeeze(sa2{t}(end,end,end,:));
sa3{t} = squeeze(sa3{t}(end,end,end,:));
sa4{t} = squeeze(sa4{t}(end,end,end,:));
end;
end;
% for paired bootstrap, we make sure that the resampling has only shuffled between conditions
% for instance [101 2 1003 104 ...] is an acceptable sequence
if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0])
fprintf('Bootstrap paired dim%d resampling method %d Pass\n', dim, method);
else error('Bootstrap paired resampling Error');
end;
% for paired permutation, in addition, we make sure that the sum accross condition is constant
% which is not true for bootstrap
msa = meansa(sa2); msa = msa(:)-msa(1);
if all(rem(sa1{1}(:)',10) == [1:9 0]) && all(rem(sa1{2}(:)',10) == [1:9 0]) && ...
all(round(msa) == [0:9]') && length(unique(sa2{1})) == 10 && length(unique(sa2{2})) == 10
fprintf('Permutation paired dim%d resampling method %d Pass\n', dim, method);
else error('Permutation paired resampling Error');
end;
% for unpaired bootstrap, only make sure there are enough unique
% values
if length(unique(sa3{1})) > 3 && length(unique(sa3{2})) > 3
fprintf('Bootstrap unpaired dim%d reampling method %d Pass\n', dim, method);
else error('Bootstrap unpaired reampling Error');
end;
% for unpaired permutation, the number of unique values must be 10
% and the sum must be constant (not true for bootstrap)
if length(unique(sa4{1})) == 10 && length(unique(sa4{2})) == 10 && ( floor(mean(meansa(sa4))) == 55 || floor(mean(meansa(sa4))) == 372 )
fprintf('Permutation unpaired dim%d reampling method %d Pass\n', dim, method);
else error('Permutation unpaired reampling Error');
end;
disp('------------------------');
end;
end;
% function to check
function assertsame(varargin)
for ind = 1:length(varargin)
if length(varargin{1}) > 2
for tmpi = 1:length(varargin{1})-1
assertsame(varargin{1}(tmpi:tmpi+1));
end;
return;
else
if (varargin{ind}(1)-varargin{ind}(2)) > abs(mean(varargin{ind}))*0.01
error('Test failed');
end;
end;
end;
disp('Test pass');
function [meanmat] = meansa(mat)
meanmat = zeros(size(mat{1}));
for index = 1:length(mat)
meanmat = meanmat+mat{index}/length(mat);
end;
function stats = rm_anova2(Y,S,F1,F2,FACTNAMES)
%
% function stats = rm_anova2(Y,S,F1,F2,FACTNAMES)
%
% Two-factor, within-subject repeated measures ANOVA.
% For designs with two within-subject factors.
%
% Parameters:
% Y dependent variable (numeric) in a column vector
% S grouping variable for SUBJECT
% F1 grouping variable for factor #1
% F2 grouping variable for factor #2
% F1name name (character array) of factor #1
% F2name name (character array) of factor #2
%
% Y should be a 1-d column vector with all of your data (numeric).
% The grouping variables should also be 1-d numeric, each with same
% length as Y. Each entry in each of the grouping vectors indicates the
% level # (or subject #) of the corresponding entry in Y.
%
% Returns:
% stats is a cell array with the usual ANOVA table:
% Source / ss / df / ms / F / p
%
% Notes:
% Program does not do any input validation, so it is up to you to make
% sure that you have passed in the parameters in the correct form:
%
% Y, S, F1, and F2 must be numeric vectors all of the same length.
%
% There must be at least one value in Y for each possible combination
% of S, F1, and F2 (i.e. there must be at least one measurement per
% subject per condition).
%
% If there is more than one measurement per subject X condition, then
% the program will take the mean of those measurements.
%
% Aaron Schurger (2005.02.04)
% Derived from Keppel & Wickens (2004) "Design and Analysis" ch. 18
%
%
% Revision history...
%
% 11 December 2009 (Aaron Schurger)
%
% Fixed error under "bracket terms"
% was: expY = sum(Y.^2);
% now: expY = sum(sum(sum(MEANS.^2)));
%
stats = cell(4,5);
F1_lvls = unique(F1);
F2_lvls = unique(F2);
Subjs = unique(S);
a = length(F1_lvls); % # of levels in factor 1
b = length(F2_lvls); % # of levels in factor 2
n = length(Subjs); % # of subjects
INDS = cell(a,b,n); % this will hold arrays of indices
CELLS = cell(a,b,n); % this will hold the data for each subject X condition
MEANS = zeros(a,b,n); % this will hold the means for each subj X condition
% Calculate means for each subject X condition.
% Keep data in CELLS, because in future we may want to allow options for
% how to compute the means (e.g. leaving out outliers > 3stdev, etc...).
for i=1:a % F1
for j=1:b % F2
for k=1:n % Subjs
INDS{i,j,k} = find(F1==F1_lvls(i) & F2==F2_lvls(j) & S==Subjs(k));
CELLS{i,j,k} = Y(INDS{i,j,k});
MEANS(i,j,k) = mean(CELLS{i,j,k});
end
end
end
% make tables (see table 18.1, p. 402)
AB = reshape(sum(MEANS,3),a,b); % across subjects
AS = reshape(sum(MEANS,2),a,n); % across factor 2
BS = reshape(sum(MEANS,1),b,n); % across factor 1
A = sum(AB,2); % sum across columns, so result is ax1 column vector
B = sum(AB,1); % sum across rows, so result is 1xb row vector
S = sum(AS,1); % sum across columns, so result is 1xs row vector
T = sum(sum(A)); % could sum either A or B or S, choice is arbitrary
% degrees of freedom
dfA = a-1;
dfB = b-1;
dfAB = (a-1)*(b-1);
dfS = n-1;
dfAS = (a-1)*(n-1);
dfBS = (b-1)*(n-1);
dfABS = (a-1)*(b-1)*(n-1);
% bracket terms (expected value)
expA = sum(A.^2)./(b*n);
expB = sum(B.^2)./(a*n);
expAB = sum(sum(AB.^2))./n;
expS = sum(S.^2)./(a*b);
expAS = sum(sum(AS.^2))./b;
expBS = sum(sum(BS.^2))./a;
expY = sum(sum(sum(MEANS.^2))); %sum(Y.^2);
expT = T^2 / (a*b*n);
% sums of squares
ssA = expA - expT;
ssB = expB - expT;
ssAB = expAB - expA - expB + expT;
ssS = expS - expT;
ssAS = expAS - expA - expS + expT;
ssBS = expBS - expB - expS + expT;
ssABS = expY - expAB - expAS - expBS + expA + expB + expS - expT;
ssTot = expY - expT;
% mean squares
msA = ssA / dfA;
msB = ssB / dfB;
msAB = ssAB / dfAB;
msS = ssS / dfS;
msAS = ssAS / dfAS;
msBS = ssBS / dfBS;
msABS = ssABS / dfABS;
% f statistic
fA = msA / msAS;
fB = msB / msBS;
fAB = msAB / msABS;
% p values
pA = 1-fcdf(fA,dfA,dfAS);
pB = 1-fcdf(fB,dfB,dfBS);
pAB = 1-fcdf(fAB,dfAB,dfABS);
% return values
stats = {'Source','SS','df','MS','F','p';...
FACTNAMES{1}, ssA, dfA, msA, fA, pA;...
FACTNAMES{2}, ssB, dfB, msB, fB, pB;...
[FACTNAMES{1} ' x ' FACTNAMES{2}], ssAB, dfAB, msAB, fAB, pAB;...
[FACTNAMES{1} ' x Subj'], ssAS, dfAS, msAS, [], [];...
[FACTNAMES{1} ' x Subj'], ssBS, dfBS, msBS, [], [];...
[FACTNAMES{1} ' x ' FACTNAMES{2} ' x Subj'], ssABS, dfABS, msABS, [], []};
return
|
github
|
BottjerLab/Acoustic_Similarity-master
|
ttest2_cell.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/ttest2_cell.m
| 4,634 |
utf_8
|
cb20a27eff3e4cd6eb3c9ae82e863eed
|
% ttest2_cell() - compute unpaired t-test. Allow fast computation of
% multiple t-test using matrix manipulation.
%
% Usage:
% >> [F df] = ttest2_cell( { a b } );
% >> [F df] = ttest2_cell(a, b);
% >> [F df] = ttest2_cell(a, b, 'inhomogenous');
%
% Inputs:
% a,b = data consisting of UNPAIRED arrays to be compared. The last
% dimension of the data array is used to compute the t-test.
% 'inhomogenous' = use computation for the degree of freedom using
% inhomogenous variance. By default the computation of
% the degree of freedom is done with homogenous
% variances.
%
% Outputs:
% T - T-value
% df - degree of freedom (array)
%
% Example:
% a = { rand(1,10) rand(1,10)+0.5 }
% [T df] = ttest2_cell(a)
% signif = 2*tcdf(-abs(T), df(1))
%
% % for comparison, the same using the Matlab t-test function
% [h p ci stats] = ttest2(a{1}', a{2}');
% [ stats.tstat' p]
%
% % fast computation (fMRI scanner volume 100x100x100 and 10 control
% % subjects and 12 test subjects). The computation itself takes 0.5
% % seconds instead of half an hour using the standard approach (1000000
% % loops and Matlab t-test function)
% a = rand(100,100,100,10); b = rand(100,100,100,10);
% [F df] = ttest_cell({ a b });
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
% (thank you to G. Rousselet for providing the formula for
% inhomogenous variances).
%
% Reference:
% Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.
% Howel, Statistical Methods for Psychology. 2009. Wadsworth Publishing.
% Copyright (C) Arnaud Delorme
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [tval, df] = ttest2_cell(a,b,c) % assumes equal variances
if nargin < 1
help ttest2_cell;
return;
end;
homogenous = 'homogenous';
if nargin > 1 && isstr(b)
homogenous = b;
end;
if nargin > 2 && isstr(c)
homogenous = c;
end;
if iscell(a),
b = a{2};
a = a{1};
end;
if ~strcmpi(homogenous, 'inhomogenous') && ~strcmpi(homogenous, 'homogenous')
error('Value for homogenous parameter can only be ''homogenous'' or ''inhomogenous''');
end;
nd = myndims(a);
na = size(a, nd);
nb = size(b, nd);
meana = mymean(a, nd);
meanb = mymean(b, nd);
if strcmpi(homogenous, 'inhomogenous')
% inhomogenous variance from Howel, 2009, "Statistical Methods for Psychology"
% thank you to G. Rousselet for providing these formulas
m = meana - meanb;
s1 = var(a,0,nd) ./ na;
s2 = var(b,0,nd) ./ nb;
se = sqrt(s1 + s2);
sd = sqrt([s1.*na, s2.*nb]);
tval = m ./ se;
df = ((s1 + s2).^2) ./ ((s1.^2 ./ (na-1) + s2.^2 ./ (nb-1)));
else
sda = mystd(a, [], nd);
sdb = mystd(b, [], nd);
sp = sqrt(((na-1)*sda.^2+(nb-1)*sdb.^2)/(na+nb-2));
tval = (meana-meanb)./sp/sqrt(1/na+1/nb);
df = na+nb-2;
end;
% check values againg Matlab statistics toolbox
% [h p ci stats] = ttest2(a', b');
% [ tval stats.tstat' ]
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function res = mymean( data, varargin) % deal with complex numbers
res = mean( data, varargin{:});
if ~isreal(data)
res = abs( res );
end;
function res = mystd( data, varargin) % deal with complex numbers
if ~isreal(data)
res = std( abs(data), varargin{:});
else
res = sqrt(sum( bsxfun(@minus, data, mean( data, varargin{2})).^2, varargin{2})/(size(data,varargin{2})-1)); % 8 percent speedup
%res = std( data, varargin{:});
end;
|
github
|
BottjerLab/Acoustic_Similarity-master
|
concatdata.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/concatdata.m
| 3,384 |
utf_8
|
3637abb212e22ffda6377169e5e9f80a
|
% concatdata - concatenate data stored into a cell array into a single
% array. only concatenate along the last dimension
% Usage:
% [dataarray len dims] = concatata(cellarraydata);
%
% Input:
% cellarraydata - cell array containing data
%
% Output:
% dataarray - single array containing all data
% len - limits of each array
% dim - dimension of the orginal array
%
% Example:
% a = rand(3, 4, 3, 10);
% b = rand(3, 4, 3, 4);
% c = rand(3, 4, 3, 3);
% [ alldata len ] = concatdata({ a b c});
% % alldata is size [ 3 4 3 17 ]
% % len contains [ 0 10 14 17 ]
% % to access array number i, type "alldata(len(i)+1:len(i+1))
%
% Author: Arnaud Delorme, CERCO/CNRS & SCCN/INC/UCSD, 2009-
% Copyright (C) Arnaud Delorme
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ datac, alllen, dims ] = concatdata(data);
alllen = cellfun('size', data, myndims(data{1}) ); % by chance, pick up the last dimension
dims = size(data);
alllen = [ 0 alllen(:)' ];
switch myndims(data{1})
case 1,
datac = zeros(sum(alllen),1, 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(alllen(i)+1:alllen(i+1)) = data{i};
end;
case 2,
datac = zeros(size(data{1},1), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,alllen(i)+1:alllen(i+1)) = data{i};
end;
case 3,
datac = zeros(size(data{1},1), size(data{1},2), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,:,alllen(i)+1:alllen(i+1)) = data{i};
end;
case 4,
datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,:,:,alllen(i)+1:alllen(i+1)) = data{i};
end;
case 5,
datac = zeros(size(data{1},1), size(data{1},2), size(data{1},3), size(data{1},4), sum(alllen), 'single');
for i = 1:prod(dims)
alllen(i+1) = alllen(i+1) + alllen(i);
datac(:,:,:,:,alllen(i)+1:alllen(i+1)) = data{i};
end;
end;
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
BottjerLab/Acoustic_Similarity-master
|
ttest_cell.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/ttest_cell.m
| 3,107 |
utf_8
|
a669e2ffb5b0d990717a40eda3db4a2f
|
% ttest_cell() - compute paired t-test. Allow fast computation of
% multiple t-test using matrix manipulation.
%
% Usage:
% >> [F df] = ttest_cell( { a b } );
% >> [F df] = ttest_cell(a, b);
%
% Inputs:
% a,b = data consisting of PAIRED arrays to be compared. The last
% dimension of the data array is used to compute the t-test.
% Outputs:
% T - T-value
% df - degree of freedom (array)
%
% Example:
% a = { rand(1,10) rand(1,10)+0.5 }
% [T df] = ttest_cell(a)
% signif = 1-tcdf(T, df(1))
%
% % for comparison, the same using the Matlab t-test function
% [h p ci stats] = ttest(a{1}', b{1}');
% [ stats.tstat' p]
%
% % fast computation (fMRI scanner volume 100x100x100 and 10 subjects in
% % two conditions). The computation itself takes 0.5 seconds instead of
% % half an hour using the standard approach (1000000 loops and Matlab
% % t-test function)
% a = rand(100,100,100,10); b = rand(100,100,100,10);
% [F df] = ttest_cell({ a b });
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
%
% Reference:
% Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.
% Copyright (C) Arnaud Delorme
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [tval, df] = ttest_cell(a,b)
if nargin < 1
help ttest_cell;
return;
end;
if iscell(a), b = a{2}; a = a{1}; end;
tmpdiff = a-b;
diff = mymean(tmpdiff, myndims(a));
sd = mystd( tmpdiff,[], myndims(a));
tval = diff./sd*sqrt(size(a, myndims(a)));
df = size(a, myndims(a))-1;
% check values againg Matlab statistics toolbox
%[h p ci stats] = ttest(a', b');
% [ tval stats.tstat' ]
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function res = mymean( data, varargin) % deal with complex numbers
res = mean( data, varargin{:});
if ~isreal(data)
res = abs( res );
end;
function res = mystd( data, varargin) % deal with complex numbers
if ~isreal(data)
res = std( abs(data), varargin{:});
else
res = sqrt(sum( bsxfun(@minus, data, mean( data, varargin{2})).^2, varargin{2})/(size(data,varargin{2})-1)); % 8 percent speedup
%res = std( data, varargin{:});
end;
|
github
|
BottjerLab/Acoustic_Similarity-master
|
corrcoef_cell.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/corrcoef_cell.m
| 2,948 |
utf_8
|
da74fe42ac5921d717809eedaccd7f21
|
% corrcoef_cell() - compute pairwise correlations using arrays and
% cell array inputs.
%
% Usage:
% >> c = corrcoef_cell( data );
% >> c = corrcoef_cell( data );
%
% Inputs:
% data - [cell array] data consisting of PAIRED arrays to be compared.
% The last dimension of embeded data arrays is used to compute
% correlation (see examples).
% Outputs:
% c - Correlation values. Same size as data without the last dimension.
%
% Note: the main advantage over the corrcoef Matlab function is the
% capacity to compute millions of pairwise correlations per second.
%
% Example:
% a = { rand(1,10) rand(1,10) };
% c1 = corrcoef_cell(a);
% c2 = corrcoef(a{1}, a{2});
% % in this case, c1 is equal to c2(2)
%
% a = { rand(200,300,100) rand(200,300,100) };
% c = corrcoef_cell(a);
% % the call above would require 200 x 300 calls to the corrcoef function
% % and be about 1000 times slower
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2010
% Copyright (C) Arnaud Delorme
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function c = corrcoef_cell(a,b);
if nargin < 1
help corrcoef_cell;
return;
end;
if nargin < 2
b = a{2};
a = a{1};
end;
nd = myndims(a);
if nd == 1
aa = a-mean(a);
bb = b-mean(b);
cv = aa'*bb/(10-1);
cva = aa'*aa/(10-1);
cvb = bb'*bb/(10-1);
c = cv/sqrt(cva*cvb);
elseif nd == 2
aa = a-repmat(mean(a,2),[1 size(a,2)]);
bb = b-repmat(mean(b,2),[1 size(a,2)]);
cv = sum(aa.*bb,2);
cva = sum(aa.*aa,2);
cvb = sum(bb.*bb,2);
c = cv./sqrt(cva.*cvb);
elseif nd == 3
aa = a-repmat(mean(a,3),[1 1 size(a,3)]);
bb = b-repmat(mean(b,3),[1 1 size(a,3)]);
cv = sum(aa.*bb,3);
cva = sum(aa.*aa,3);
cvb = sum(bb.*bb,3);
c = cv./sqrt(cva.*cvb);
elseif nd == 4
aa = a-repmat(mean(a,4),[1 1 1 size(a,4)]);
bb = b-repmat(mean(b,4),[1 1 1 size(a,4)]);
cv = sum(aa.*bb,4);
cva = sum(aa.*aa,4);
cvb = sum(bb.*bb,4);
c = cv./sqrt(cva.*cvb);
end;
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
|
github
|
BottjerLab/Acoustic_Similarity-master
|
anova1_cell.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/anova1_cell.m
| 4,420 |
utf_8
|
1013b1b3f49e9b71df057025fdf4f1d8
|
% anova1_cell() - compute F-values in cell array using ANOVA.
%
% Usage:
% >> [F df] = anova1_cell( data );
%
% Inputs:
% data = data consisting of PAIRED arrays to be compared. The last
% dimension of the data array is used to compute ANOVA.
% Outputs:
% F - F-value
% df - degree of freedom (array)
%
% Note: the advantage over the ANOVA1 function of Matlab statistical
% toolbox is that this function works on arrays (see examples). Note
% also that you still need the statistical toolbox to assess
% significance using the fcdf() function. The other advantage is that
% this function will work with complex numbers.
%
% Example:
% a = { rand(1,10) rand(1,10) rand(1,10) }
% [F df] = anova1_cell(a)
% signif = 1-fcdf(F, df(1), df(2))
%
% % for comparison
% anova1( [ a{1,1}' a{1,2}' a{1,3}' ]) % look in the graph for the F value
%
% b = { [ a{1,1}; a{1,1} ] [ a{1,2}; a{1,2} ] [ a{1,3}; a{1,3} ] }
% [F df] = anova1_cell(b)
%
% c{1,1} = reshape(repmat(b{1,1}, [2 1]),2,2,10);
% c{1,2} = reshape(repmat(b{1,2}, [2 1]),2,2,10);
% c{1,3} = reshape(repmat(b{1,3}, [2 1]),2,2,10);
% [F df] = anova1_cell(c)
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
%
% Reference:
% Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.
% Copyright (C) Arnaud Delorme
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [F, df] = anova1_cell(data)
% This function does not return
% correct values (see bug 336)
% It should be fixed with Schaum's outlines p363
% but requires some work. It now calls
% anova2_cell which returns correct values
warning off;
[ F tmp tmp2 df] = anova2_cell(data);
warning on;
return;
% compute all means and all std
% -----------------------------
nd = myndims( data{1} );
if nd == 1
for i = 1:length(data)
n( i) = length(data{i});
m( i) = mymean( data{i});
sd(i) = mystd( data{i});
end;
nt = sum(n);
n = n';
m = m';
sd = sd';
elseif nd == 2
for i = 1:length(data)
n( :,i) = ones(size(data{i},1),1) * size(data{i},2, 'single');
m( :,i) = mymean( data{i},2);
sd(:,i) = mystd( data{i},[],2);
end;
nt = sum(n(1,:));
elseif nd == 3
for i = 1:length(data)
n( :,:,i) = ones(size(data{i},1),size(data{i},2)) * size(data{i},3, 'single');
m( :,:,i) = mymean( data{i},3);
sd(:,:,i) = mystd( data{i},[],3);
end;
nt = sum(n(1,1,:));
else
for i = 1:length(data)
n( :,:,:,i) = ones(size(data{i},1),size(data{i},2), size(data{i},3)) * size(data{i},4, 'single');
m( :,:,:,i) = mymean( data{i},4);
sd(:,:,:,i) = mystd( data{i},[],4);
end;
nt = sum(n(1,1,1,:));
end;
mt = mean(m,nd);
ng = length(data); % number of conditions
VinterG = ( sum( n.*(m.^2), nd ) - nt*mt.^2 )/(ng-1);
VwithinG = sum( (n-1).*(sd.^2), nd )/(nt-ng);
F = VinterG./VwithinG;
df = [ ng-1 ng*(size(data{1},nd)-1) ];
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function res = mymean( data, varargin) % deal with complex numbers
res = mean( data, varargin{:});
if ~isreal(data)
res = abs( res );
end;
function res = mystd( data, varargin) % deal with complex numbers
res = std( abs(data), varargin{:});
|
github
|
BottjerLab/Acoustic_Similarity-master
|
fdr.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/fdr.m
| 2,273 |
utf_8
|
0339630d5b76067fde504d464d26a9bf
|
% fdr() - compute false detection rate mask
%
% Usage:
% >> [p_fdr, p_masked] = fdr( pvals, alpha);
%
% Inputs:
% pvals - vector or array of p-values
% alpha - threshold value (non-corrected). If no alpha is given
% each p-value is used as its own alpha and FDR corrected
% array is returned.
% fdrtype - ['parametric'|'nonParametric'] FDR type. Default is
% 'parametric'.
%
% Outputs:
% p_fdr - pvalue used for threshold (based on independence
% or positive dependence of measurements)
% p_masked - p-value thresholded. Same size as pvals.
%
% Author: Arnaud Delorme, SCCN, 2008-
% Based on a function by Tom Nichols
%
% Reference: Bejamini & Yekutieli (2001) The Annals of Statistics
% Copyright (C) 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [pID, p_masked] = fdr(pvals, q, fdrType);
if nargin < 3, fdrType = 'parametric'; end;
if isempty(pvals), pID = []; return; end;
p = sort(pvals(:));
V = length(p);
I = (1:V)';
cVID = 1;
cVN = sum(1./(1:V));
if nargin < 2
pID = ones(size(pvals));
thresholds = exp(linspace(log(0.1),log(0.000001), 100));
for index = 1:length(thresholds)
[tmp p_masked] = fdr(pvals, thresholds(index));
pID(p_masked) = thresholds(index);
end;
else
if strcmpi(fdrType, 'parametric')
pID = p(max(find(p<=I/V*q/cVID))); % standard FDR
else
pID = p(max(find(p<=I/V*q/cVN))); % non-parametric FDR
end;
end;
if isempty(pID), pID = 0; end;
if nargout > 1
p_masked = pvals<=pID;
end;
|
github
|
BottjerLab/Acoustic_Similarity-master
|
anova2_cell.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/resampling_statistical_toolkit/statistics/anova2_cell.m
| 6,961 |
utf_8
|
0dbba037045407d82eca356a53792acf
|
% anova2_cell() - compute F-values in cell array using ANOVA.
%
% Usage:
% >> [FC FR FI dfc dfr dfi] = anova2_cell( data );
%
% Inputs:
% data = data consisting of PAIRED arrays to be compared. The last
% dimension of the data array is used to compute ANOVA.
% Outputs:
% FC - F-value for columns.
% FR - F-value for rows.
% FI - F-value for interaction.
% dfc - degree of freedom for columns.
% dfr - degree of freedom for rows.
% dfi - degree of freedom for interaction.
%
% Note: the advantage over the ANOVA2 function of Matlab statistical
% toolbox is that this function works on arrays (see examples). Note
% also that you still need the statistical toolbox to assess
% significance using the fcdf() function. The other advantage is that
% this function will work with complex numbers.
%
% Example:
% a = { rand(1,10) rand(1,10) rand(1,10); rand(1,10) rand(1,10) rand(1,10) }
% [FC FR FI dfc dfr dfi] = anova2_cell(a)
% signifC = 1-fcdf(FC, dfc(1), dfc(2))
% signifR = 1-fcdf(FR, dfr(1), dfr(2))
% signifI = 1-fcdf(FI, dfi(1), dfi(2))
%
% % for comparison
% anova2( [ a{1,1}' a{1,2}' a{1,3}'; a{2,1}' a{2,2}' a{2,3}' ], 10)
%
% b = { [ a{1,1}; a{1,1} ] [ a{1,2}; a{1,2} ] [ a{1,3}; a{1,3} ];
% [ a{2,1}; a{2,1} ] [ a{2,2}; a{2,2} ] [ a{2,3}; a{2,3} ] }
% [FC FR FI dfc dfr dfi] = anova2_cell(b)
%
% c{1,1} = reshape(repmat(b{1,1}, [2 1]),2,2,10);
% c{1,2} = reshape(repmat(b{1,2}, [2 1]),2,2,10);
% c{1,3} = reshape(repmat(b{1,3}, [2 1]),2,2,10);
% c{2,3} = reshape(repmat(b{2,3}, [2 1]),2,2,10);
% c{2,2} = reshape(repmat(b{2,2}, [2 1]),2,2,10);
% c{2,1} = reshape(repmat(b{2,1}, [2 1]),2,2,10)
% [FC FR FI dfc dfr dfi] = anova2_cell(c)
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, 2005
%
% Reference:
% Schaum's outlines in statistics (3rd edition). 1999. Mc Graw-Hill.
% Copyright (C) Arnaud Delorme
%
% 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [FC, FR, FI, freeC, freeR, freeI] = anova2_cell(data)
% compute all means and all std
% -----------------------------
a = size(data,1);
b = size(data,2);
nd = myndims( data{1} );
c = size(data{1}, nd);
% dataabs if for complex data only
% --------------------------------
dataabs = data;
if ~isreal(data{1})
for i = 1:a
for ii = 1:b
dataabs{i,ii} = abs(data{i,ii});
end;
end;
end;
if nd == 1
VE = 0;
m = zeros( size(data), 'single' );
for i = 1:a
for ii = 1:b
m(i,ii) = mymean(data{i,ii});
VE = VE+sum( (dataabs{i,ii}-m(i,ii)).^2 );
end;
end;
X = mean(mean(m));
Xj = mean(m,2);
Xk = mean(m,1);
VR = b*c*sum( (Xj-X).^2 );
VC = a*c*sum( (Xk-X).^2 );
Xj = repmat(Xj, [1 size(m,2) ]);
Xk = repmat(Xk, [size(m,1) 1]);
VI = c*sum( sum( ( m - Xj - Xk + X ).^2 ) );
elseif nd == 2
VE = zeros( size(data{1},1),1, 'single');
m = zeros( [ size(data{1},1) size(data) ], 'single' );
for i = 1:a
for ii = 1:b
tmpm = mymean(data{i,ii}, 2);
m(:,i,ii) = tmpm;
VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 size(data{i,ii},2)])).^2, 2);
end;
end;
X = mean(mean(m,3),2);
Xj = mean(m,3);
Xk = mean(m,2);
VR = b*c*sum( (Xj-repmat(X, [1 size(Xj,2)])).^2, 2 );
VC = a*c*sum( (Xk-repmat(X, [1 1 size(Xk,3)])).^2, 3 );
Xj = repmat(Xj, [1 1 size(m,3) ]);
Xk = repmat(Xk, [1 size(m,2) 1]);
VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 size(m,2) size(m,3)]) ).^2, 3), 2 );
elseif nd == 3
VE = zeros( size(data{1},1), size(data{1},2), 'single' );
m = zeros( [ size(data{1},1) size(data{1},2) size(data) ], 'single' );
for i = 1:a
for ii = 1:b
tmpm = mymean(data{i,ii}, 3);
m(:,:,i,ii) = tmpm;
VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 1 size(data{i,ii},3)])).^2, 3);
end;
end;
X = mean(mean(m,4),3);
Xj = mean(m,4);
Xk = mean(m,3);
VR = b*c*sum( (Xj-repmat(X, [1 1 size(Xj,3) ])).^2, 3 );
VC = a*c*sum( (Xk-repmat(X, [1 1 1 size(Xk,4)])).^2, 4 );
Xj = repmat(Xj, [1 1 1 size(m,4) ]);
Xk = repmat(Xk, [1 1 size(m,3) 1]);
VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 1 size(m,3) size(m,4)]) ).^2, 4 ), 3 );
else % nd == 4
VE = zeros( size(data{1},1), size(data{1},2), size(data{1},3), 'single' );
m = zeros( [ size(data{1},1) size(data{1},2) size(data{1},3) size(data) ], 'single' );
for i = 1:a
for ii = 1:b
tmpm = mymean(data{i,ii}, 4);
m(:,:,:,i,ii) = tmpm;
VE = VE+sum( (dataabs{i,ii}-repmat(tmpm, [1 1 1 size(data{i,ii},4)])).^2, 4);
end;
end;
X = mean(mean(m,5),4);
Xj = mean(m,5);
Xk = mean(m,4);
VR = b*c*sum( (Xj-repmat(X, [1 1 1 size(Xj,4) ])).^2, 4 );
VC = a*c*sum( (Xk-repmat(X, [1 1 1 1 size(Xk,5)])).^2, 5 );
Xj = repmat(Xj, [1 1 1 1 size(m,5) ]);
Xk = repmat(Xk, [1 1 1 size(m,4) 1]);
VI = c*sum( sum( ( m - Xj - Xk + repmat(X, [1 1 1 size(m,4) size(m,5)]) ).^2, 5 ), 4 );
end;
SR2 = VR/(a-1);
SC2 = VC/(b-1);
SI2 = VI/(a-1)/(b-1);
SE2 = VE/(a*b*(c-1));
FR = SR2./SE2; % rows
FC = SC2./SE2; % columns
FI = SI2./SE2; % interaction
freeR = [ a-1 a*b*(c-1) ];
freeC = [ b-1 a*b*(c-1) ];
freeI = [ (a-1)*(b-1) a*b*(c-1) ];
function val = myndims(a)
if ndims(a) > 2
val = ndims(a);
else
if size(a,1) == 1,
val = 2;
elseif size(a,2) == 1,
val = 1;
else
val = 2;
end;
end;
function res = mymean( data, varargin) % deal with complex numbers
res = mean( data, varargin{:});
if ~isreal(data)
res = abs( res );
end;
|
github
|
BottjerLab/Acoustic_Similarity-master
|
searchST.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/ukkonen/searchST.m
| 2,048 |
utf_8
|
0282dd1c42a6ee3b55906d7c341749ab
|
function indices = searchST(T,Str,Qry)
%searchST checks if a string is in a suffix tree and returns occurrence indices
% suffix tree root: T
% original string : Str
% query string : Qry
if ~isempty(T.transitions)
curr_state = T; % store current state for the iterative approach
qrylen = length(Qry); % store query length
indices=[]; % initialize the indices array
i = 1; % position variable
while i<=qrylen
% get array index of next transition by checking the character
if ~curr_state.isLeaf,
pos = regexp(char(curr_state.transitions.litera)', Qry(i), 'once');
else
pos = [];
end
% if( state.transition(X).litera != Qry(i) ) -> break -> no match
if isempty(pos),
break;
end
trans = curr_state.transitions(pos); % get current transition
strlen = trans.right-trans.left+1; % and its label length
if length(Qry(i:end))<=strlen
% compare the substring and the query
result = strcmp( Qry(i:end), Str( trans.left:trans.left+length(Qry(i:end))-1) );
% if query was found -> get the occurrence indices
if result
if trans.state.isLeaf
% next state is a leaf -> only one occurrence
% compute the occurrence index
indices = trans.left + length(Qry(i:end)) - qrylen;
else
% next state is not a leaf -> multiple occurrences
% need to traverse the subtree:
indices = getIndices( trans.state );
end
end
break; % break the loop
else
% query string longer than edge string:
% update the current state for next iteration step
curr_state = trans.state;
% update the index i
i = i+strlen;
end
end
end
end
% traverse the subtree (from state "state") in order to compute occurrence indices
function indices = getIndices(state)
indices = [];
for j=1:length(state.transitions)
if state.transitions(j).state.isLeaf
indices = [ indices state.transitions(j).state.index ];
else
indices = [ indices getIndices(state.transitions(j).state) ];
end
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
create_generalized_suffix_tree.m
|
.m
|
Acoustic_Similarity-master/code/fileExchange/ukkonen/create_generalized_suffix_tree.m
| 1,270 |
utf_8
|
634a95f2eb19b9d3e6ed8b110e6ad7a8
|
function [root, sfstring] = create_generalized_suffix_tree(varargin)
% CREATE_GENERALIZED_SUFFIX_TREE produces a generalized suffix tree
% for multiple strings using the CREATE_SUFFIX_TREE function
% (Ukkonen '95)
%
% string terminators to separate multiple strings
terminators = '!§$%&/()=?';
% check how many strings have been submitted (currently 10 string at most)
if nargin>length(terminators)
disp(['can only handle ' num2str(length(terminators)) ' strings!']);
disp('exiting!');
return;
end
% concatenate the strings using these terminators
sfstring = '';
if nargin==1 && varargin{1}(end) == '!'
sfstring = varargin{1};
else
for i=1:nargin,
sfstring = [sfstring char(varargin{i}) char(terminators(i))];
end
end
% create a suffix tree with the produced string
root = create_suffix_tree(sfstring);
% fix suffixes to produce the "real" generalized suffix tree output
if nargin>1,
fixSuffixes(root,sfstring);
end
end
function fixSuffixes(T,Txt)
len = length(T.transitions);
if len>0
for i=1:len
trans=T.transitions(i);
term = regexpi(Txt(trans.left:trans.right), '[!§$%&/()=?]');
if ~isempty(term)
trans.right=trans.left+term(1)-1;
end
fixSuffixes(T.transitions(i).state,Txt);
end
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
initEvents.m
|
.m
|
Acoustic_Similarity-master/code/eventUtil/initEvents.m
| 1,331 |
utf_8
|
77ca6c2126f8465349decd5e0fd1de34
|
function events = initEvents(N, exampleEvent)
% function EVENTS = INITEVENTS(N)
%
% initialize sparse coding of status, using events, which will be a struct
% array
%
% all events have the following fields:
% type: a label
% start: the start of the clip (in seconds)
% stop: the end of the clip (in seconds)
% idxStart: the start of the clip (in terms of the index in the waveform)
% idxStop: the end of the clip (in terms of the index in the waveform)
% 'start' and 'stop' should be proportional to their index counterparts,
% and the ratio should be 1/fs, where fs is the sampling rates.
if nargin == 0
N = 0;
end
if nargin < 2
fields = {'type','start','stop','idxStart','idxStop'};
elseif isstruct(exampleEvent)
fields = fieldnames(exampleEvent);
else
fields = exampleEvent;
end
events = initEmptyStructArray(fields);
if nargin == 1 && N>0
events(N) = initEvent;
for ii = 1:numel(fields)
events(N).(fields{ii}) = [];
end
end
function events = initEvent
% flag: isn't that helpful, should be replaced/obsoleted
% initialize sparse coding of status, using events, which will be a struct
% array
innerFields = {'type','start','stop','idxStart','idxStop'};
% fun with cell arrays
foo = cell(2,numel(innerFields));
[foo{1,:}] = innerFields{:};
[foo{2,:}] = deal(NaN);
events = struct(foo{:});
|
github
|
BottjerLab/Acoustic_Similarity-master
|
trainSongRecognizer.m
|
.m
|
Acoustic_Similarity-master/code/recognition/trainSongRecognizer.m
| 6,684 |
utf_8
|
cd95cb2e3cf8275eed3f6e494ee0ed56
|
function [prototypeSong, syllableFxns] = trainSongRecognizer(songStruct, alignedSongs, songSylls, params, varargin)
if nargin < 4
params = defaultParams;
end;
params = processArgs(params, varargin{:});
fs = 1/songStruct.interval;
% apply pre/postroll to all songs first
nSongs = numel(alignedSongs);
for ii = 1:nSongs
alignedSongs(ii) = addPrePost(alignedSongs(ii),params);
end
% given a set of aligned songs and borders,
% define the intervals for a typical song, and a
nTotalSylls = numel(songSylls);
%% first vote on the syllable boundaries
songStartVotes = zeros(1,nTotalSylls);
songStopVotes = zeros(1,nTotalSylls);
for ii = 1:nSongs
[theseSubSylls, theseIdxs] = getSubEvents(alignedSongs(ii),songSylls);
zeroAdjustedSylls = adjustTimeStamps(theseSubSylls, -alignedSongs(ii).start);
songStartVotes(theseIdxs) = [zeroAdjustedSylls.start];
songStopVotes(theseIdxs)= [zeroAdjustedSylls.stop];
end
% how much variance is there in syllable onsets?
kernelWidth = 0.005; %s
% time resolution parameter
widthRes = 5e-4; %s
songLen = alignedSongs(1).stop - alignedSongs(1).start;
songIdxLen = alignedSongs(1).idxStop - alignedSongs(1).idxStart + 1;
timeEv = 0:widthRes:songLen;
%% estimate the start/stop positions of each event,
% renormalizing so that each syllable has unit 'vote' at its location
kernelParams = {'width',kernelWidth,'kernel','epanechnikov'};
% instead of doing the math, we just find the height empirically
unnormedHeight = max(ksdensity((1:nTotalSylls) * 15 * kernelWidth,timeEv,kernelParams{:}));
startPeakVote = ksdensity(songStartVotes,timeEv,kernelParams{:}) / unnormedHeight;
stopPeakVote = ksdensity(songStopVotes,timeEv,kernelParams{:}) / unnormedHeight;
%% display
% get average clip for display purposes
clipAvg = averageWaveform(songStruct,alignedSongs,songIdxLen);
subplot(2,1,1);
plot((1:songIdxLen)/fs, clipAvg, 'b-');
title('Average Waveform');
xlim([0 songIdxLen/fs]);
subplot(2,1,2);
plot(timeEv, startPeakVote,'c-', timeEv, stopPeakVote,'m-' )
title('Finding boundaries for songs');
xlim([0 timeEv(end)]);
%% here we use thresholds on the vote to segment syllables
% what percent needs to vote on a syllable?
voteFraction = 0.35;
voteThresh = voteFraction * nSongs;
peakDist = kernelWidth / widthRes;
peakParams = {'minPeakHeight', voteThresh,'minPeakDistance', peakDist};
[startY, stdSyllStarts] = findpeaks(startPeakVote, peakParams{:});
[stopY , stdSyllStops ] = findpeaks(stopPeakVote , peakParams{:});
nStandardSylls = numel(stdSyllStarts);
stdSyllStarts = timeEv(stdSyllStarts);
stdSyllStops = timeEv(stdSyllStops );
stdSyllLengths = stopY - startY;
%% check (a) are these syllables interwoven at the right intervals?
if all(stdSyllLengths > 0) && all(stopY(1:end-1) - startY(2:end) > 0)
error('BadIntervals','Intervals are not correct'); % needs to be fixed
end
%% (b) are they symbols representative of real syllables?
% find if any syllables actually match these syllables
sylMatchIndex = NaN(1,nTotalSylls);
for ii = 1:nSongs
[theseSubSylls, theseIdxs] = getSubEvents(alignedSongs(ii),songSylls);
zeroAdjustedSylls = adjustTimeStamps(theseSubSylls, -alignedSongs(ii).start);
theseStarts = [zeroAdjustedSylls.start];
theseStops = [zeroAdjustedSylls.stop ];
for jj = 1:numel(theseIdxs)
matchSyll = abs(theseStarts(jj) - stdSyllStarts) < 2 * kernelWidth & ...
abs(theseStops(jj) - stdSyllStops) < 2 * kernelWidth;
if sum(matchSyll) == 1
sylMatchIndex(theseIdxs(jj)) = find(matchSyll);
elseif sum(matchSyll) > 1
warning('matchTooLoose','match criteria are too loose');
end
end
end
hold on;
plot(stdSyllStarts, startY, 'c^', 'markerfacecolor', [0 0 1]);
plot(stdSyllStops , stopY , 'm^', 'markerfacecolor', [1 0 0]);
hold off;
%% (c) are the syllables they model similar?
if params.plot
for ii = 1:nStandardSylls
theseSylls = songSylls(ii == sylMatchIndex);
nTheseSylls = numel(theseSylls);
hl=figure(); clf
fprintf('Showing spectrograms for syllable #%d/%d (%d)...\n',ii,nStandardSylls,nTheseSylls);
subplot(ceil(nTheseSylls/4),4,1);
progressbar(0);
for jj = 1:nTheseSylls
figure(hl);
subplot(ceil(nTheseSylls/4),4,jj);
waveform = getClip(theseSylls(jj), songStruct);
if params.playsample && jj == nTheseSylls, playSound(waveform,fs,true); end;
plotWaveform(waveform,fs);
set(gca,'XTick',0:0.01:max(get(gca,'XLim')));
%params.fine.fs = fs;
%spec = getMTSpectrumStats(waveform,params.fine);
%plotDerivGram(spec);
%ylabel(''); set(gca,'YTick',[]); xlabel(''); set(gca,'XTick',[]);
progressbar(jj/nTheseSylls);
if jj == 1; title(sprintf('Syllable #%d (%d)',ii,nTheseSylls)); end;
end
colormap(gray)
set(hl,'visible','on');
saveCurrFigure(sprintf('figures/stdSylls-%02d.tif',ii));
end
end
%% prepare output
prototypeSong = initEvents(nStandardSylls);
foo = num2cell(1:nStandardSylls); [prototypeSong.type] = foo{:};
foo = num2cell(stdSyllStarts - params.preroll/1000); [prototypeSong.start] = foo{:};
foo = num2cell(stdSyllStops - params.preroll/1000); [prototypeSong.stop ] = foo{:};
foo = num2cell(floor(fs * (stdSyllStarts - params.preroll/1000))); [prototypeSong.idxStart] = foo{:};
foo = num2cell(floor(fs * (stdSyllStops - params.preroll/1000))); [prototypeSong.idxStop ] = foo{:};
% now train the classifiers to recognize these syllables
% start by extracting all the features
if nargout == 2
progressbar('extracting features');
for ii = nTotalSylls:-1:1 % loop run backward so that preallocation happens
params.fine.fs = fs;
clip = getClip(songStruct, songSylls(ii));
featureReduction(ii) = extractFeatures(getMTSpectrumStats(clip, params.fine));
progressbar(1-(ii-1)/nTotalSylls);
end
for ii = 1:nStandardSylls
isThisSyll = (ii == sylMatchIndex);
fprintf('Training classifier on syllable #%d (%d)...\n',ii,sum(isThisSyll));
classer{ii} = trainClassifier(songStruct,songSylls,featureReduction, isThisSyll);
syllableFxns{ii} = @(feature) testClass(classer{ii}, feature);
end
end
end
function ret = averageWaveform(songStruct, clips, clipLen)
if nargin < 3,
clipLen = NaN([clips.idxStop] - [clips.idxStart]);
end
allClips = zeros(numel(clips), clipLen);
for ii = 1:numel(clips)
songLen = clips(ii).idxStop - clips(ii).idxStart + 1;
allClips(ii,1:songLen) = getClip(songStruct, clips(ii))';
end;
ret = nanmean(allClips,1);
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
specscope.m
|
.m
|
Acoustic_Similarity-master/code/chronux/spectral_analysis/specscope/specscope.m
| 18,968 |
utf_8
|
b67aa0a85101a9f8f5061995b2d4dcb9
|
function outdata=specscope(indata)
% record and plot audio spectrogram
%
% Usage: outdata=specscope(indata)
%
% Input: indata (optional)
% Displays a recorded piece of data, if an argument is passed
% Otherwise displays audio data from an attached microphone
%
% Output: outdata (optional)
% If present, will return up to 10 minutes
% of captured audio data.
%
% Note: Parameters such as sampling frequency, number of tapers
% and display refresh rate may be set below if desired.
% You can also acquire data from a national instruments card.
%
close all;
%=======================================================================
% Check toolboxes
%=======================================================================
% Check for toolboxes
if not(exist('analoginput','file'));
fprintf('You need to install the DAQ toolbox first\n');
return
end
if not(exist('mtspecgramc','file'));
fprintf('You need to install the Chronux toolbox first from http://chronux.org/\n');
return
end
%=======================================================================
% Set parameters
%=======================================================================
global acq;
% Set defaults
acq.params.Fs = 44100;
acq.pause = 0;
acq.skips = 0;
acq.stop = 0;
acq.restart = 0;
acq.plot_frequency = 10;
acq.samples_acquired = 0;
acq.spectra = [];
acq.times = [];
defaults
audio_instr;
fig=create_ui;
%=======================================================================
% Check arguments, start DAQ
%=======================================================================
if nargout
% save up to ten minutes data, preallocated...
fprintf('Pre-allocating memory for data save - please be patient.\n');
outdata=zeros( (acq.params.Fs * 60 * 10), 1 );
end
if nargin == 1;
acq.indata = indata;
acq.live = 0;
else
% Create and set up and start analog input daq
input=1;
if input==1;
acq.ai = analoginput('winsound');
addchannel( acq.ai, 1 );
else
acq.ai = analoginput('nidaq', 1);
addchannel(acq.ai, 0);
set(acq.ai,'InputType','SingleEnded')
set(acq.ai,'TransferMode','Interrupts')
set(acq.ai,'TriggerType','Manual');
end
set( acq.ai, 'SampleRate', acq.params.Fs )
acq.params.Fs = get( acq.ai, 'SampleRate' );
set( acq.ai, 'SamplesPerTrigger', inf )
start(acq.ai)
acq.live = 1;
if input==2;
trigger(acq.ai);
end
end
acq.samples_per_frame = acq.params.Fs / acq.plot_frequency;
%=======================================================================
% The scope main loop
%=======================================================================
acq.t0=clock;
acq.tn=clock;
% Loop over frames to acquire and display
while 1;
% Check for quit signal
if acq.stop;
break;
end
% Calculate times
calctime = acq.samples_acquired / acq.params.Fs;
acq.samples_acquired = acq.samples_acquired + acq.samples_per_frame;
acq.t1 = clock;
elapsed = etime(acq.t1,acq.t0);
% Get a small snippet of data
if ( acq.live )
data = getdata( acq.ai, acq.samples_per_frame );
else
while elapsed < acq.samples_acquired / acq.params.Fs
pause( acq.samples_acquired / (acq.params.Fs) - elapsed );
acq.t1=clock;
elapsed = etime(acq.t1,acq.t0);
end
if acq.samples_acquired + 2 * acq.samples_per_frame >= length( acq.indata )
acq.stop=1;
end
data = acq.indata(floor(acq.samples_acquired+1):floor(acq.samples_per_frame+acq.samples_acquired));
end
if nargout
outdata(floor(acq.samples_acquired+1):floor(acq.samples_acquired+length(data))) = data(:);
end
if acq.restart;
acq.restart = 0;
acq.spectra = [];
acq.times = [];
end
% Calculate spectrogram of data snippet
if acq.deriv
[s, t, f] = mtspecgramc(diff(data), acq.moving_window, acq.params );
else
[s, t, f] = mtspecgramc(data, acq.moving_window, acq.params );
end
% Add new spectra to that already calculated
acq.times = [acq.times t+calctime];
if acq.log
acq.spectra = [acq.spectra log(s')];
else
acq.spectra = [acq.spectra s'];
end
% Remove old spectra once window reaches desired size
while acq.times(1,end) - acq.times(1,1) > acq.display_size;
% Ring buffer!
y = length(t);
acq.times(:,1:y) = [];
acq.spectra(:,1:y) = [];
end
% Only plot if display is keeping up with real time and not paused
show_plot=1;
if nargin==0
if get(acq.ai, 'SamplesAvailable' ) > 10 * acq.samples_per_frame && acq.pause==0
show_plot=0;
end
else
if elapsed > calctime + 0.5
show_plot=0;
end
end
if acq.pause
show_plot=0;
end
if show_plot
if acq.bgsub
acq.mean_spectra = mean( acq.spectra, 2 );
end
% Normalize until full screen passes by if requested
if acq.normalize>=1;
if acq.normalize==1
acq.tn=clock;
acq.normalize=2;
end
if etime(clock,acq.tn)>1.25*acq.display_size
acq.normalize=0;
end
mins = min(min(acq.spectra));
maxs = max(max(acq.spectra));
end
% Scale the spectra based upon current offset and scale
if acq.bgsub
scaled_spectra = acq.offset + ( acq.scale ) * ( acq.spectra - repmat( acq.mean_spectra, [1,size(acq.spectra,2)]) ) / ( maxs - mins );
else
scaled_spectra = acq.offset + acq.scale * ( acq.spectra - mins ) / ( maxs - mins );
end
% Draw the image to the display
image( acq.times, f, scaled_spectra ); axis xy;
drawnow;
else
% Keep track of skipped displays
acq.skips = acq.skips + 1;
end
end
%=======================================================================
% Clean up
%=======================================================================
acq.t1=clock;
elapsed = etime(acq.t1,acq.t0);
fprintf( 'Elapsed time %f seconds\n', elapsed );
% Warn if many skips were encountered
if acq.skips > 5;
fprintf( '\nWARNING:\nThis program skipped plotting %d times to keep pace.\n', acq.skips )
fprintf( 'Run again without keyboard interaction or changing the figure size.\n' )
fprintf( 'If this message reappears you should reduce the plot frequency parameter.\n\n' );
end
% Clean up the analoginput object
if acq.live
stop(acq.ai);delete( acq.ai );clear acq.ai;
end
% Clean up the figure
delete(fig);
delete(gcf);
if nargout
% save up to ten minutes data, preallocated...
fprintf('Saving output data\n');
outdata=outdata(1:floor(acq.samples_acquired));
end
return;
%
%
%=======================================================================
% Functions called
%=======================================================================
%
%
%=======================================================================
% Handle Keypresses
%=======================================================================
% Handle figure window keypress events
function keypress(varargin)
global acq;
keypressed=get(gcf,'CurrentCharacter');
% ignore raw control, shift, alt keys
if keypressed;
% Save current frame as gif
if strcmp( keypressed, 'g');
saveas( acq.fig, sprintf( 'frame%d.png',acq.times(length(acq.times)) ) )
end
% Offset changes
increment=1;
if strcmp( keypressed, 'l');
acq.offset = acq.offset - increment;
elseif strcmp( keypressed, 'o');
acq.offset = acq.offset + increment;
% Scale changes
elseif strcmp( keypressed, 'x');
acq.scale = acq.scale - increment;
elseif strcmp( keypressed, 's');
acq.scale = acq.scale + increment;
% Reset defaults
elseif strcmp( keypressed, 'd');
defaults
acq.restart=1;
% Normalize spectra
elseif strcmp( keypressed, 'n');
request_normalize
% Quit
elseif strcmp( keypressed, 'q');
request_quit
% Pause
elseif strcmp( keypressed, 'p');
request_pause
% Help
elseif strcmp( keypressed, 'h');
audio_instr
% Change colormaps for 0-9,a-c
elseif strcmp( keypressed, '0' );
colormap( 'jet' );
elseif strcmp( keypressed, '1' );
colormap( 'bone' );
elseif strcmp( keypressed, '2' );
colormap( 'colorcube' );
elseif strcmp( keypressed, '3' );
colormap( 'cool' );
elseif strcmp( keypressed, '4' );
colormap( 'copper' );
elseif strcmp( keypressed, '5' );
colormap( 'gray' );
elseif strcmp( keypressed, '6' );
colormap( 'hot' );
elseif strcmp( keypressed, '7' );
colormap( 'hsv' );
elseif strcmp( keypressed, '8' );
colormap( 'autumn' );
elseif strcmp( keypressed, '9' );
colormap( 'pink' );
elseif strcmp( keypressed, 'a' );
colormap( 'spring' );
elseif strcmp( keypressed, 'b' );
colormap( 'summer' );
elseif strcmp( keypressed, 'c' );
colormap( 'winter' );
end
update_display
end
return
%=======================================================================
% Defaults
%=======================================================================
% Reset defaults
function defaults()
global acq;
acq.params.raw_tapers = [2 3];
acq.moving_window = [0.02 0.02];
acq.params.tapers=dpsschk(acq.params.raw_tapers,round(acq.params.Fs*acq.moving_window(1)),acq.params.Fs);
acq.offset = 0;
acq.scale = 64;
acq.display_size = 3;
acq.params.fpass = [50 8000];
acq.deriv=1;
acq.log=1;
acq.bgsub = 1;
acq.params.pad= 0;
acq.normalize = 2;
return
function update_display()
global acq;
set(acq.tapers_ui,'String',sprintf( '%.0f %.0f', acq.params.raw_tapers(1), acq.params.raw_tapers(2) ));
set(acq.window_ui,'String',sprintf( '%.2f %.2f', acq.moving_window(1), acq.moving_window(2) ));
set(acq.offset_ui,'String',sprintf( '%d', acq.offset ));
set(acq.scale_ui,'String',sprintf( '%d', acq.scale ));
set(acq.display_size_ui,'String',sprintf( '%.1f', acq.display_size ));
set(acq.frequency_ui,'String',sprintf( '%.1f %.1f', acq.params.fpass(1), acq.params.fpass(2) ))
set(acq.derivative_ui,'Value',acq.deriv);
set(acq.log_ui,'Value',acq.log);
set(acq.bgsub_ui,'Value',acq.bgsub);
return
%=======================================================================
% Update ui controls
%=======================================================================
function request_quit(varargin)
global acq;
acq.stop=1;
return
function request_pause(varargin)
global acq;
acq.pause = not( acq.pause );
return
function request_normalize(varargin)
global acq;
acq.normalize = 2;
return
function update_defaults(varargin)
global acq;
defaults
update_display
acq.restart=1;
return
function update_tapers(varargin)
global acq;
acq.params.raw_tapers = sscanf(get( gco, 'string' ),'%f %d')';
acq.params.tapers=dpsschk(acq.params.raw_tapers,round(acq.params.Fs*acq.moving_window(1)),acq.params.Fs); % check tapers
return
function update_window(varargin)
global acq;
acq.moving_window = sscanf(get( gco, 'string' ),'%f %f');
acq.params.tapers=dpsschk(acq.params.raw_tapers,round(acq.params.Fs*acq.moving_window(1)),acq.params.Fs);
acq.restart = 1;
return
function update_offset(varargin)
global acq;
acq.offset = sscanf(get( gco, 'string' ),'%f');
return
function update_scale(varargin)
global acq;
acq.scale = sscanf(get( gco, 'string' ),'%f');
return
function update_display_size(varargin)
global acq;
acq.display_size = sscanf(get( gco, 'string' ),'%f');
return
function update_fpass(varargin)
global acq;
acq.params.fpass = sscanf(get( gco, 'string' ),'%f %f');
acq.restart = 1;
return
function update_deriv(varargin)
global acq;
acq.deriv=get( gco, 'Value' );
acq.normalize=1;
return
function update_log(varargin)
global acq;
acq.log=get( gco, 'Value' );
acq.normalize=1;
return
function update_bgsub(varargin)
global acq;
acq.bgsub=get( gco, 'Value' );
return
%=======================================================================
% UI display
%=======================================================================
function fig=create_ui()
global acq;
bgcolor = [1 1 1]; % .7 .7 .7
% ===Create main figure==========================
fig = figure('Position',centerfig(800,600),...
'NumberTitle','off',...
'Name','Real-time spectrogram',...
'doublebuffer','on',...
'HandleVisibility','on',...
'Renderer', 'openGL', ...
'KeyPressFcn', @keypress, ...
'Color',bgcolor);
acq.fig = fig;
offset = 80;
% ===text==========
uicontrol(gcf,'Style','text',...
'String', 'tapers',...
'Position',[offset+225 20 45 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'moving win',...
'Position',[offset+300 20 70 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'offset',...
'Position',[offset+375 20 30 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'scale',...
'Position',[offset+410 20 30 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 't axis',...
'Position',[offset+445 20 30 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'f axis',...
'Position',[offset+480 20 40 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'deriv',...
'Position',[offset+550 20 35 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'log',...
'Position',[offset+580 20 35 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'bgsub',...
'Position',[offset+610 20 35 20],...
'BackgroundColor',bgcolor);
% ===The quit button===============================
uicontrol('Style','pushbutton',...
'Position',[offset+5 5 45 20],...
'String','Quit',...
'Interruptible','off',...
'BusyAction','cancel',...
'Callback',@request_quit);
% ===The pause button===============================
uicontrol('Style','pushbutton',...
'Position',[offset+55 5 45 20],...
'String','Pause',...
'Interruptible','off',...
'BusyAction','cancel',...
'Callback',@request_pause);
% ===The defaults button===============================
uicontrol('Style','pushbutton',...
'Position',[offset+105 5 50 20],...
'String','Defaults',...
'Interruptible','off',...
'BusyAction','cancel',...
'Callback',@update_defaults);
% ===The normalize button===============================
uicontrol('Style','pushbutton',...
'Position',[offset+160 5 60 20],...
'String','Normalize',...
'Interruptible','off',...
'BusyAction','cancel',...
'Callback',@request_normalize );
% ===Tapers============================================
acq.tapers_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.0f %.0f', acq.params.raw_tapers(1), acq.params.raw_tapers(2) ),...
'Position',[offset+225 5 70 20],...
'CallBack', @update_tapers);
% ===Window============================================
acq.window_ui=uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.2f %.2f', acq.moving_window(1), acq.moving_window(2) ),...
'Position',[offset+300 5 70 20],...
'CallBack', @update_window);
% ===Offset============================================
acq.offset_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%d', acq.offset ),...
'Position',[offset+375 5 30 20],...
'CallBack', @update_offset);
% ===Scale============================================
acq.scale_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%d', acq.scale ),...
'Position',[offset+410 5 30 20],...
'CallBack', @update_scale);
% ===display size======================================
acq.display_size_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.1f', acq.display_size ),...
'Position',[offset+445 5 30 20],...
'CallBack', @update_display_size);
% ===frequency axis=====================================
acq.frequency_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.1f %.1f', acq.params.fpass(1), acq.params.fpass(2) ),...
'Position',[offset+480 5 80 20],...
'CallBack', @update_fpass);
% ===derivative=====================================
acq.derivative_ui = uicontrol(gcf,'Style','checkbox',...
'Value',acq.deriv,...
'Position',[offset+565 5 20 20],...
'CallBack', @update_deriv);
% ===log=====================================
acq.log_ui = uicontrol(gcf,'Style','checkbox',...
'Value',acq.log,...
'Position',[offset+590 5 20 20],...
'CallBack', @update_log);
% ===bgsub=====================================
acq.bgsub_ui = uicontrol(gcf,'Style','checkbox',...
'Value',acq.bgsub,...
'Position',[offset+615 5 20 20],...
'CallBack', @update_bgsub);
return
%=======================================================================
% Assorted functions
%=======================================================================
function pos = centerfig(width,height)
% Find the screen size in pixels
screen_s = get(0,'ScreenSize');
pos = [screen_s(3)/2 - width/2, screen_s(4)/2 - height/2, width, height];
return
function audio_instr()
% Show instructions
fprintf('INSTRUCTIONS:\n');
fprintf('Click on figure window first to activate controls.\n')
fprintf('Adjust tapers, windows, scales, offsets and axes using the gui\n');
fprintf('The deriv checkbox toggles derivative of the data\n');
fprintf('The log checkbox toggles a log of the spectrum\n');
fprintf('Press d or use defaults button to reset most parameters to defaults.\n')
fprintf('Press n or use normalize button to normalize spectra based upon values in current display.\n')
fprintf('Press 0-9,a-c to choose a colormap (default 0).\n')
fprintf('Press p to pause and unpause display.\n')
fprintf('Press o and l to adjust offset, or use offset textbox on gui.\n');
fprintf('Press s and x to adjust scale, or use scale textbox on gui.\n');
fprintf('Press h for this message.\n')
fprintf('Press q to quit, or use quit button on gui.\n\n')
return
|
github
|
BottjerLab/Acoustic_Similarity-master
|
rtf.m
|
.m
|
Acoustic_Similarity-master/code/chronux/spectral_analysis/specscope/rtf.m
| 4,927 |
utf_8
|
643598d912d578b46cdc9aa085fa78f8
|
function rtf(plot_frq,flag_save)
close all
evalin('base','stop=0;');
%=========SET THE BASIC FIGURE=================
fig = figure('Position',[500,500,800,600],...
'NumberTitle','off',...
'Name','Scope',...
'doublebuffer','on',...
'HandleVisibility','on',...
'KeyPressFcn', @keypress, ...
'Renderer', 'openGL');
%=============================================
%=============OPEN THE DEVICE FOR RECORD======
sample_frequency = 44100;
samples_per_frame = 1024;
%plot_frq=10;
record_time=600;
samples_to_acquire = record_time * sample_frequency;
%PREPARE THE DEVICE
ai = analoginput('winsound');
chan = addchannel( ai, 1 );
set( ai, 'SampleRate', sample_frequency )
set( ai, 'SamplesPerTrigger', samples_to_acquire )
set(ai, 'StopFcn', @stop_dev)
sample_frequency = get( ai, 'SampleRate' );
%SETTING CALL BACK FUNCTIONS:
%The first for capture the
%second for display
set(ai, 'SamplesAcquiredFcnCount',samples_per_frame);
set(ai, 'SamplesAcquiredFcn',@flag);
set(ai, 'TimerPeriod',(1/plot_frq));
set(ai, 'TimerFcn',@disply);
%=============SAVE THE CONFIGURATION======
plot_ref=plot(zeros(10,1));
fid=-1;
%SAVE THE CURRENT PARAMETERS:
name_of_file=sprintf('%s-%d','real-anal',(round(sample_frequency/samples_per_frame)));
remark={1,...
zeros(samples_per_frame*20,1)',...
0,...
plot_ref,...
plot_frq,...
cputime,...
flag_save,...
-1,...
name_of_file
};
set(ai, 'UserData',remark)
%=============START TO RECORD================
fprintf ('To stop the program set <stop=1> or press q in the figure window\n');
start (ai)
%=============================================
%=========THE MAIN PROGRAM====================
%=============================================
% *
% ***
% *****
% ***
% ***
% ***
% ***
% ***
% *****
% ***
% *
%=============================================
%==========CALLBACK FUNCTIONS=================
%=============================================
%=========Keypress callback===========
function keypress(src, e)
keypressed=get(gcf,'CurrentCharacter');
% ignore raw control, shift, alt keys
if keypressed
% Quit
if strcmp( keypressed, 'q')
evalin('base','stop=1;');
end
end
return
%============FLAG FUNCTION===================
%This function activated when we capture
%certain amount of samples
function flag(obj,event)
% CHECK FOR STOP SIGNAL
if evalin('base','stop')
stop(obj)
end
% GET THE OLD DATA
remark=get(obj,'UserData');
flag_write=remark{1}; %Do I have to
buffer=remark{3}; %What is the old picture
flag_save=remark{7}; %Are we in saving mode?
fid=remark{8}; %What file descriptor to save
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%IN CASE - DELETE/SAVE THE OLD DATA
if flag_write>20
% IN CASE WE HAVE TO SAVE - CLOSE THE OLD FILE AND MAKE A NEW
if flag_save>0
fclose(fid);
name_of_data=sprintf('%s-%d.dat','dat',(round(cputime*1000)));
fid=fopen(name_of_data,'w');
end
%DELETE OLD DATA
flag_write=1;
buffer=[];
remark{1}=flag_write; % SET THE POSITION OF THE READING SHIFT
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TAKE THE NEW DATA
samples_per_frame=get(obj,'SamplesAcquiredFcnCount');
data=(getdata(obj,samples_per_frame))';
% IN CASE - WRITE THE DATA
if flag_save>0
if fid==-1
name_of_data=sprintf('%s-%d.dat','dat',(round(cputime*1000)));
fid=fopen(name_of_data,'w');
end
fwrite(fid,(data*10000),'short');
remark{8}=fid;
end
% Add to buffer
buffer=[buffer data];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
remark{3}=buffer;
set(obj,'UserData',remark);
return
function stop_dev(obj,event)
remark=get(obj,'UserData');
if (remark{8}>0) %FID>0 == There is open file
fclose (remark{8});
end
close all
fprintf('\n\nThanks for using Erlich Real-Time scope\n');
save (remark{9},'remark');
delete(obj)
clear obj
return
function disply(obj,event)
sample_frequency=get(obj,'SampleRate');
remark=get(obj,'UserData');
refresh_frq=remark{5};
read_shift=remark{1};
ring=remark{2};
buffer=remark{3};
end_shift=min((read_shift+round(sample_frequency/refresh_frq)),length(buffer));
new_data=buffer(read_shift:end_shift);
ring=[ring new_data];
ring(1:length(new_data))=[];
remark{1}=end_shift;
remark{2}=ring;
start_display(ring,remark{4})
set(obj,'UserData',remark);
return
|
github
|
BottjerLab/Acoustic_Similarity-master
|
specscopepp.m
|
.m
|
Acoustic_Similarity-master/code/chronux/spectral_analysis/specscope/specscopepp.m
| 19,677 |
utf_8
|
36533b75a54fc2d7689db8409d0d285c
|
function outdata=specscopepp(indata)
global acq;
h=hamming(5);
mins=5e-008;
maxs=1e-004;
% record and plot audio spectrogram
%
% Usage: outdata=specscope(indata)
%
% Input: indata (optional)
% Displays a recorded piece of data, if an argument is passed
% Otherwise displays audio data from an attached microphone
%
% Output: outdata (optional)
% If present, will return up to 10 minutes
% of captured audio data.
%
% Note: Parameters such as sampling frequency, number of tapers
% and display refresh rate may be set below if desired.
% You can also acquire data from a national instruments card.
%
close all;
%=======================================================================
% Check toolboxes
%=======================================================================
% Check for toolboxes
if not(exist('analoginput','file'));
fprintf('You need to install the DAQ toolbox first\n');
return
end
if not(exist('mtspecgramc','file'));
fprintf('You need to install the Chronux toolbox first from http://chronux.org/\n');
return
end
%=======================================================================
% Set parameters
%=======================================================================
% Set defaults
acq.params.Fs = 44100;
acq.pause = 0;
acq.skips = 0;
acq.stop = 0;
acq.restart = 0;
acq.plot_frequency = 20;
acq.samples_acquired = 0;
acq.spectra = [];
acq.times = [];
defaults
audio_instr;
fig=create_ui;
%=======================================================================
% Check arguments, start DAQ
%=======================================================================
if nargout
% save up to ten minutes data, preallocated...
fprintf('Pre-allocating memory for data save - please be patient.\n');
outdata=zeros( (acq.params.Fs * 60 * 10), 1 );
end
if nargin == 1;
acq.indata = indata;
acq.live = 0;
else
% Create and set up and start analog input daq
input=1;
if input==1;
acq.ai = analoginput('winsound');
addchannel( acq.ai, 1 );
else
acq.ai = analoginput('nidaq', 1);
addchannel(acq.ai, 0);
set(acq.ai,'InputType','SingleEnded')
set(acq.ai,'TransferMode','Interrupts')
set(acq.ai,'TriggerType','Manual');
end
set( acq.ai, 'SampleRate', acq.params.Fs )
acq.params.Fs = get( acq.ai, 'SampleRate' );
acq.samples_per_frame = acq.params.Fs / acq.plot_frequency;
set( acq.ai, 'SamplesPerTrigger', inf )
start(acq.ai)
acq.live = 1;
if input==2;
trigger(acq.ai);
end
end
%=======================================================================
% The scope main loop
%=======================================================================
acq.t0=clock;
acq.tn=clock;
% Loop over frames to acquire and display
while 1;
% Check for quit signal
if acq.stop;
break;
end
% Calculate times
calctime = acq.samples_acquired / acq.params.Fs;
acq.samples_acquired = acq.samples_acquired + acq.samples_per_frame;
acq.t1 = clock;
elapsed = etime(acq.t1,acq.t0);
% Get a small snippet of data
if ( acq.live )
data = getdata( acq.ai, acq.samples_per_frame );
else
while elapsed < acq.samples_acquired / acq.params.Fs
pause( acq.samples_acquired / (acq.params.Fs) - elapsed );
acq.t1=clock;
elapsed = etime(acq.t1,acq.t0);
end
if acq.samples_acquired + 2 * acq.samples_per_frame >= length( acq.indata )
acq.stop=1;
end
data = acq.indata(floor(acq.samples_acquired+1):floor(acq.samples_per_frame+acq.samples_acquired));
end
if nargout
outdata(floor(acq.samples_acquired+1):floor(acq.samples_acquired+length(data))) = data(:);
end
if acq.restart;
acq.restart = 0;
acq.spectra = [];
acq.times = [];
end
data=conv(h,data);
data=sign(data-acq.threshold);
% Calculate spectrogram of data snippet
if acq.deriv
[s, t, f] = mtspecgramc(abs(diff(data)), acq.moving_window, acq.params );
else
[s, t, f] = mtspecgramc(diff(data), acq.moving_window, acq.params );
end
% Add new spectra to that already calculated
acq.times = [acq.times t+calctime];
if acq.log
acq.spectra = [acq.spectra log(s')];
else
acq.spectra = [acq.spectra s'];
end
% Remove old spectra once window reaches desired size
while acq.times(1,end) - acq.times(1,1) > acq.display_size;
% Ring buffer!
y = length(t);
acq.times(:,1:y) = [];
acq.spectra(:,1:y) = [];
end
% Only plot if display is keeping up with real time and not paused
show_plot=1;
if nargin==0
if get(acq.ai, 'SamplesAvailable' ) > 10 * acq.samples_per_frame && acq.pause==0
show_plot=0;
end
else
if elapsed > calctime + 0.5
show_plot=0;
end
end
if acq.pause
show_plot=0;
end
if show_plot
if acq.bgsub
acq.mean_spectra = mean( acq.spectra, 2 );
end
% Normalize until full screen passes by if requested
if acq.normalize>=1;
if acq.normalize==1
acq.tn=clock;
acq.normalize=2;
end
if etime(clock,acq.tn)>1.25*acq.display_size
acq.normalize=0;
end
mins = min(min(acq.spectra));
maxs = max(max(acq.spectra));
end
% Scale the spectra based upon current offset and scale
if acq.bgsub
scaled_spectra = acq.offset + ( acq.scale ) * ( acq.spectra - repmat( acq.mean_spectra, [1,size(acq.spectra,2)]) ) / ( maxs - mins );
else
scaled_spectra = acq.offset + acq.scale * ( acq.spectra - mins ) / ( maxs - mins );
end
% Draw the image to the display
image( acq.times, f, scaled_spectra, 'parent', acq.ax1 ); axis([acq.ax1],'xy');
drawnow;
else
% Keep track of skipped displays
acq.skips = acq.skips + 1;
end
end
%=======================================================================
% Clean up
%=======================================================================
acq.t1=clock;
elapsed = etime(acq.t1,acq.t0);
fprintf( 'Elapsed time %f seconds\n', elapsed );
% Warn if many skips were encountered
if acq.skips > 5;
fprintf( '\nWARNING:\nThis program skipped plotting %d times to keep pace.\n', acq.skips )
fprintf( 'Run again without keyboard interaction or changing the figure size.\n' )
fprintf( 'If this message reappears you should reduce the plot frequency parameter.\n\n' );
end
% Clean up the analoginput object
if acq.live
stop(acq.ai);delete( acq.ai );clear acq.ai;
end
% Clean up the figure
delete(fig);
delete(gcf);
if nargout
% save up to ten minutes data, preallocated...
fprintf('Saving output data\n');
outdata=outdata(1:floor(acq.samples_acquired));
end
return;
%
%
%=======================================================================
% Functions called
%=======================================================================
%
%
%=======================================================================
% Handle Keypresses
%=======================================================================
% Handle figure window keypress events
function keypress(varargin)
global acq;
keypressed=get(gcf,'CurrentCharacter');
% ignore raw control, shift, alt keys
if keypressed;
% Offset changes
increment=1;
if strcmp( keypressed, 'l');
acq.offset = acq.offset - increment;
elseif strcmp( keypressed, 'o');
acq.offset = acq.offset + increment;
% Scale changes
elseif strcmp( keypressed, 'x');
acq.scale = acq.scale - increment;
elseif strcmp( keypressed, 's');
acq.scale = acq.scale + increment;
% Reset defaults
elseif strcmp( keypressed, 'd');
defaults
acq.restart=1;
% Normalize spectra
elseif strcmp( keypressed, 'n');
request_normalize
% Quit
elseif strcmp( keypressed, 'q');
request_quit
% Pause
elseif strcmp( keypressed, 'p');
request_pause
% Help
elseif strcmp( keypressed, 'h');
audio_instr
elseif strcmp( keypressed, 't');
acq.threshold = acq.threshold + 0.01;
elseif strcmp( keypressed, 'g');
acq.threshold = acq.threshold - 0.01;
% Change colormaps for 0-9,a-c
elseif strcmp( keypressed, '0' );
colormap( 'jet' );
elseif strcmp( keypressed, '1' );
colormap( 'bone' );
elseif strcmp( keypressed, '2' );
colormap( 'colorcube' );
elseif strcmp( keypressed, '3' );
colormap( 'cool' );
elseif strcmp( keypressed, '4' );
colormap( 'copper' );
elseif strcmp( keypressed, '5' );
colormap( 'gray' );
elseif strcmp( keypressed, '6' );
colormap( 'hot' );
elseif strcmp( keypressed, '7' );
colormap( 'hsv' );
elseif strcmp( keypressed, '8' );
colormap( 'autumn' );
elseif strcmp( keypressed, '9' );
colormap( 'pink' );
elseif strcmp( keypressed, 'a' );
colormap( 'spring' );
elseif strcmp( keypressed, 'b' );
colormap( 'summer' );
elseif strcmp( keypressed, 'c' );
colormap( 'winter' );
end
update_display
end
return
%=======================================================================
% Defaults
%=======================================================================
% Reset defaults
function defaults()
global acq;
acq.params.raw_tapers = [3 5];
acq.moving_window = [0.02 0.01];
acq.params.tapers=dpsschk(acq.params.raw_tapers,round(acq.params.Fs*acq.moving_window(1)),acq.params.Fs);
acq.offset = 0;
acq.scale = 500;
acq.display_size = 3;
acq.params.fpass = [50 20000];
acq.deriv=1;
acq.log=0;
acq.bgsub = 1;
acq.params.pad= 0;
acq.normalize = 0;
acq.threshold=0;
return
function update_display()
global acq;
set(acq.tapers_ui,'String',sprintf( '%.0f %.0f', acq.params.raw_tapers(1), acq.params.raw_tapers(2) ));
set(acq.window_ui,'String',sprintf( '%.2f %.2f', acq.moving_window(1), acq.moving_window(2) ));
set(acq.offset_ui,'String',sprintf( '%d', acq.offset ));
set(acq.scale_ui,'String',sprintf( '%d', acq.scale ));
set(acq.display_size_ui,'String',sprintf( '%.1f', acq.display_size ));
set(acq.frequency_ui,'String',sprintf( '%.1f %.1f', acq.params.fpass(1), acq.params.fpass(2) ))
set(acq.derivative_ui,'Value',acq.deriv);
set(acq.log_ui,'Value',acq.log);
set(acq.bgsub_ui,'Value',acq.bgsub);
set(acq.threshold_ui,'String',sprintf( '%.2f', acq.threshold ));
return
%=======================================================================
% Update ui controls
%=======================================================================
function request_quit(varargin)
global acq;
acq.stop=1;
return
function request_pause(varargin)
global acq;
acq.pause = not( acq.pause );
return
function request_normalize(varargin)
global acq;
acq.normalize = 2;
return
function update_defaults(varargin)
global acq;
defaults
update_display
acq.restart=1;
return
function update_tapers(varargin)
global acq;
acq.params.raw_tapers = sscanf(get( gco, 'string' ),'%f %d')';
acq.params.tapers=dpsschk(acq.params.raw_tapers,round(acq.params.Fs*acq.moving_window(1)),acq.params.Fs); % check tapers
return
function update_window(varargin)
global acq;
acq.moving_window = sscanf(get( gco, 'string' ),'%f %f');
acq.params.tapers=dpsschk(acq.params.raw_tapers,round(acq.params.Fs*acq.moving_window(1)),acq.params.Fs);
acq.restart = 1;
return
function update_offset(varargin)
global acq;
acq.offset = sscanf(get( gco, 'string' ),'%f');
return
function update_scale(varargin)
global acq;
acq.scale = sscanf(get( gco, 'string' ),'%f');
return
function update_display_size(varargin)
global acq;
acq.display_size = sscanf(get( gco, 'string' ),'%f');
return
function update_fpass(varargin)
global acq;
acq.params.fpass = sscanf(get( gco, 'string' ),'%f %f');
acq.restart = 1;
return
function update_deriv(varargin)
global acq;
acq.deriv=get( gco, 'Value' );
acq.normalize=1;
return
function update_log(varargin)
global acq;
acq.log=get( gco, 'Value' );
acq.normalize=1;
return
function update_bgsub(varargin)
global acq;
acq.bgsub=get( gco, 'Value' );
return
function update_threshold(varargin)
global acq;
acq.threshold = sscanf(get( gco, 'string' ),'%f');
return
%=======================================================================
% UI display
%=======================================================================
function fig=create_ui()
global acq;
bgcolor = [.7 .7 .7];
% ===Create main figure==========================
fig = figure('Position',centerfig(800,600),...
'NumberTitle','off',...
'Name','Real-time spectrogram',...
'doublebuffer','on',...
'HandleVisibility','on',...
'Renderer', 'openGL', ...
'KeyPressFcn', @keypress, ...
'Color',bgcolor);
acq.ax1 = axes('position', [0.05,0.1,0.9,0.85]);
colormap( 'autumn' );
% ===text==========
uicontrol(gcf,'Style','text',...
'String', 'tapers',...
'Position',[225 20 45 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'moving win',...
'Position',[300 20 70 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'offset',...
'Position',[375 20 30 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'scale',...
'Position',[410 20 30 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 't axis',...
'Position',[445 20 30 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'f axis',...
'Position',[480 20 40 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'abs',...
'Position',[550 20 35 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'log',...
'Position',[580 20 35 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'bgsub',...
'Position',[610 20 35 20],...
'BackgroundColor',bgcolor);
uicontrol(gcf,'Style','text',...
'String', 'thresh',...
'Position',[645 20 35 20],...
'BackgroundColor',bgcolor);
% ===The quit button===============================
uicontrol('Style','pushbutton',...
'Position',[5 5 45 20],...
'String','Quit',...
'Interruptible','off',...
'BusyAction','cancel',...
'Callback',@request_quit);
% ===The pause button===============================
uicontrol('Style','pushbutton',...
'Position',[55 5 45 20],...
'String','Pause',...
'Interruptible','off',...
'BusyAction','cancel',...
'Callback',@request_pause);
% ===The defaults button===============================
uicontrol('Style','pushbutton',...
'Position',[105 5 50 20],...
'String','Defaults',...
'Interruptible','off',...
'BusyAction','cancel',...
'Callback',@update_defaults);
% ===The normalize button===============================
uicontrol('Style','pushbutton',...
'Position',[160 5 60 20],...
'String','Normalize',...
'Interruptible','off',...
'BusyAction','cancel',...
'Callback',@request_normalize );
% ===Tapers============================================
acq.tapers_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.0f %.0f', acq.params.raw_tapers(1), acq.params.raw_tapers(2) ),...
'Position',[225 5 70 20],...
'CallBack', @update_tapers);
% ===Window============================================
acq.window_ui=uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.2f %.2f', acq.moving_window(1), acq.moving_window(2) ),...
'Position',[300 5 70 20],...
'CallBack', @update_window);
% ===Offset============================================
acq.offset_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%d', acq.offset ),...
'Position',[375 5 30 20],...
'CallBack', @update_offset);
% ===Scale============================================
acq.scale_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%d', acq.scale ),...
'Position',[410 5 30 20],...
'CallBack', @update_scale);
% ===display size======================================
acq.display_size_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.1f', acq.display_size ),...
'Position',[445 5 30 20],...
'CallBack', @update_display_size);
% ===frequency axis=====================================
acq.frequency_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.1f %.1f', acq.params.fpass(1), acq.params.fpass(2) ),...
'Position',[480 5 80 20],...
'CallBack', @update_fpass);
% ===derivative=====================================
acq.derivative_ui = uicontrol(gcf,'Style','checkbox',...
'Value',acq.deriv,...
'Position',[565 5 20 20],...
'CallBack', @update_deriv);
% ===log=====================================
acq.log_ui = uicontrol(gcf,'Style','checkbox',...
'Value',acq.log,...
'Position',[590 5 20 20],...
'CallBack', @update_log);
% ===bgsub=====================================
acq.bgsub_ui = uicontrol(gcf,'Style','checkbox',...
'Value',acq.bgsub,...
'Position',[615 5 20 20],...
'CallBack', @update_bgsub);
% ===threshold======================================
acq.threshold_ui = uicontrol(gcf,'Style','edit',...
'String', sprintf( '%.2f', acq.threshold ),...
'Position',[640 5 40 20],...
'CallBack', @update_threshold);
return
%=======================================================================
% Assorted functions
%=======================================================================
function pos = centerfig(width,height)
% Find the screen size in pixels
screen_s = get(0,'ScreenSize');
pos = [screen_s(3)/2 - width/2, screen_s(4)/2 - height/2, width, height];
return
function audio_instr()
% Show instructions
fprintf('INSTRUCTIONS:\n');
fprintf('Click on figure window first to activate controls.\n')
fprintf('Adjust tapers, windows, scales, offsets and axes using the gui\n');
fprintf('The abs checkbox toggles abs of the data\n');
fprintf('The log checkbox toggles a log of the spectrum\n');
fprintf('Press d or use defaults button to reset most parameters to defaults.\n')
fprintf('Press n or use normalize button to normalize spectra based upon values in current display.\n')
fprintf('Press 0-9,a-c to choose a colormap (default 0).\n')
fprintf('Press p to pause and unpause display.\n')
fprintf('Press t and g to adjust threshold, or use offset textbox on gui.\n');
fprintf('Press o and l to adjust offset, or use offset textbox on gui.\n');
fprintf('Press s and x to adjust scale, or use scale textbox on gui.\n');
fprintf('Press h for this message.\n')
fprintf('Press q to quit, or use quit button on gui.\n\n')
return
|
github
|
BottjerLab/Acoustic_Similarity-master
|
lfgui.m
|
.m
|
Acoustic_Similarity-master/code/chronux/locfit/m/lfgui.m
| 4,018 |
utf_8
|
3b6eace9dc5a0057fb2c8b221751aa6d
|
function varargout = lfgui(varargin)
% LFGUI M-file for lfgui.fig
% LFGUI, by itself, creates a new LFGUI or raises the existing
% singleton*.
%
% H = LFGUI returns the handle to a new LFGUI or the handle to
% the existing singleton*.
%
% LFGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in LFGUI.M with the given input arguments.
%
% LFGUI('Property','Value',...) creates a new LFGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before lfgui_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to lfgui_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 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help lfgui
% Last Modified by GUIDE v2.5 27-Dec-2005 18:56:48
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @lfgui_OpeningFcn, ...
'gui_OutputFcn', @lfgui_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 lfgui is made visible.
function lfgui_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 lfgui (see VARARGIN)
fit = locfit(varargin{:});
lfplot(fit);
handles.lfargs = varargin;
% Choose default command line output for lfgui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes lfgui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = lfgui_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 slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
n = get(hObject,'Value');
n0 = get(hObject,'Min');
n1 = get(hObject,'Max');
nn = 0.1+(n-n0)/(n1-n0);
fit = locfit(handles.lfargs{:},'nn',nn);
lfplot(fit);
% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background, change
% 'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
set(hObject,'BackgroundColor',[.9 .9 .9]);
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
auto_classify.m
|
.m
|
Acoustic_Similarity-master/code/chronux/wave_browser/auto_classify.m
| 24,375 |
utf_8
|
d6715f4c02b4802b386ebbbb058fed4c
|
function varargout = auto_classify(varargin)
% AUTO_CLASSIFY M-file for auto_classify.fig
% AUTO_CLASSIFY, by itself, creates a new AUTO_CLASSIFY or raises the existing
% singleton*.
%
% H = AUTO_CLASSIFY returns the handle to a new AUTO_CLASSIFY or the handle to
% the existing singleton*.
%
% AUTO_CLASSIFY('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in AUTO_CLASSIFY.M with the given input arguments.
%
% AUTO_CLASSIFY('Property','Value',...) creates a new AUTO_CLASSIFY or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before auto_classify_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to auto_classify_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 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help auto_classify
% Last Modified by GUIDE v2.5 21-Jun-2006 00:34:13
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @auto_classify_OpeningFcn, ...
'gui_OutputFcn', @auto_classify_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 auto_classify is made visible.
function auto_classify_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 auto_classify (see VARARGIN)
% input parameters
if isempty(varargin)
handles.matrix2classify = [];
handles.ncepstral = 5;
else
handles.matrix2classify = varargin{1};
handles.ncepstral = varargin{2};
end
handles.distancemeasure = 'sqEuclidean';
handles.cluster_method = 'kmeans';
set(handles.CepstralPopupMenu,'String',num2str([0:handles.ncepstral]'));
set(handles.CepstralPopupMenu,'Value',handles.ncepstral); %handles.ncepstral +1 );
% set(handles.CepstralPopupMenu,'Value',handles.ncepstral-1);
% Choose default command line output for auto_classify
% handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes auto_classify wait for user response (see UIRESUME)
% uiwait(handles.figure1);
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = auto_classify_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
close;
function clusters = clusterdata(X,k,dmeasure)
% A wrapper function for clustering
try
clusters = kmeans(X,k,'distance',dmeasure,'EmptyAction','singleton','replicates',30);
catch
clusters = k;
end
% --- Executes on button press in AutoClassifyButton.
function AutoClassifyButton_Callback(hObject, eventdata, handles)
% hObject handle to AutoClassifyButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.AcceptButton,'Enable','off');
guidata(gcbo,handles);
cncepstral = get(handles.CepstralPopupMenu,'Value');
matrix2classify = handles.matrix2classify;
matrix2classify = madnormalize(matrix2classify,1); % normalize the columns
matrix2classify = matrix2classify(:,1:cncepstral+1); % include the cepstral coefficients that you want
if length(matrix2classify(1,:)) > 3
matrix2classify = matrix2classify(:,[1,3:cncepstral+1]); % exclude the first cepestral coefficient
end
try
segweight = str2num(get(handles.SegLenWeight,'String'));
catch
segweight = 1;
set(handles.SegLenWeight,'String','1');
end
% Weight the segment lengths by square root of the weight
matrix2classify(:,1) = matrix2classify(:,1)*sqrt(segweight);
% Other weightings can be added here but the cepestral coefficients have a
% natural exponential decline which acts a weighting
%Handle transformations to segment length
contents = get(handles.TransformPopupMenu,'String');
value = get(handles.TransformPopupMenu,'Value');
switch contents{value}
case 'None'
matrix2classify = matrix2classify;
case 'Exclude'
matrix2classify = matrix2classify(:,2:length(matrix2classify(1,:)));
case 'Log'
matrix2classify(:,1) = log(matrix2classify(:,1));
case 'Exp'
matrix2classify(:,1) = exp(matrix2classify(:,1));
end
if length(matrix2classify(1,:)) == 0 % matrix to classify has no information
return
end
rangestate = get(handles.RangeSpecify,'Value');
diagnosticstate = get(handles.DiagnosticCheckbox,'Value');
if strcmp(handles.cluster_method,'hierarchical')
handles.classification = cluster_hierarchical(matrix2classify);
nclusters = length(unique(handles.classification)) - 1;
set(handles.KClasses,'String',nclusters);
if diagnosticstate
pcaplot(matrix2classify,handles.classification);
end
else if strcmp(handles.cluster_method, 'kmeans')
if not(rangestate)
kclassstr = get(handles.KClasses,'String');
if not(isempty(kclassstr))
try
nclasses = str2num(kclassstr);
catch
return;
end
classification = clusterdata(matrix2classify,nclasses,handles.distancemeasure);% this can be changed to a different clustering algorithm
% clusterdata shows how a clustering algorithm can be hooked in where the number of
% classes need to be assigned.
if length(classification) == 1
msgbox('Error in clustering. Try changing the number of target clusters or rerunning.');
else
if diagnosticstate
figure();
[silh h] = silhouette(matrix2classify,classification);
pcaplot(matrix2classify,classification);
end
handles.classification = classification;
end
else
return;
end
else
try
minclust = str2num(get(handles.MinClusters,'String'));
catch
return;
end
try
maxclust = str2num(get(handles.MaxClusters,'String'));
catch
return;
end
resultsclust = cell((1+ maxclust)-minclust,1);
hw = waitbar(0,'Clustering data set ');
for i = 1:(1+maxclust)-minclust
resultsclust{i} = clusterdata(matrix2classify,minclust + (i-1),handles.distancemeasure);
if length(resultsclust{i}) == 1
msgbox(['Clustering failed at ' num2str(resultsclust{i}) ' clusters. Try changing the range of clusters or rerunning.']);
return;
end
waitbar(i/(1+maxclust-minclust));
end
close(hw);
silhmean = zeros((1+ maxclust)-minclust,1);
for i = 1:1+(maxclust)-minclust
if diagnosticstate
figure();
[silh h] = silhouette(matrix2classify,resultsclust{i});
pcaplot(matrix2classify,resultsclust{i});
else
silh = silhouette(matrix2classify,resultsclust{i});
end
silhmean(i) = mean(silh);
end
[x I] = max(silhmean);
handles.classification = resultsclust{I(1)};
set(handles.KClasses,'String',num2str(minclust + (I(1)-1)));
end
end
end
set(handles.AcceptButton,'Enable','on');
guidata(gcbo,handles);
% --- Executes on button press in CancelButton.
function CancelButton_Callback(hObject, eventdata, handles)
% hObject handle to CancelButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = 0;
guidata(hObject,handles);
uiresume(handles.figure1);
% --- Executes on button press in AcceptButton.
function AcceptButton_Callback(hObject, eventdata, handles)
% hObject handle to AcceptButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = handles.classification;
guidata(hObject,handles);
uiresume(handles.figure1);
function CepstralEdit_Callback(hObject, eventdata, handles)
% hObject handle to CepstralEdit (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 CepstralEdit as text
% str2double(get(hObject,'String')) returns contents of CepstralEdit as a double
% --- Executes during object creation, after setting all properties.
function CepstralEdit_CreateFcn(hObject, eventdata, handles)
% hObject handle to CepstralEdit (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function MinClusters_Callback(hObject, eventdata, handles)
% hObject handle to MinClusters (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 MinClusters as text
% str2double(get(hObject,'String')) returns contents of MinClusters as a double
% --- Executes during object creation, after setting all properties.
function MinClusters_CreateFcn(hObject, eventdata, handles)
% hObject handle to MinClusters (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function MaxClusters_Callback(hObject, eventdata, handles)
% hObject handle to MaxClusters (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 MaxClusters as text
% str2double(get(hObject,'String')) returns contents of MaxClusters as a double
% --- Executes during object creation, after setting all properties.
function MaxClusters_CreateFcn(hObject, eventdata, handles)
% hObject handle to MaxClusters (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in TransformPopupMenu.
function TransformPopupMenu_Callback(hObject, eventdata, handles)
% hObject handle to TransformPopupMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns TransformPopupMenu contents as cell array
% contents{get(hObject,'Value')} returns selected item from TransformPopupMenu
% value = get(hObject,'Value');
%
% if value == 2
% handles.matrix2classify(:,1) = log(handles.matrix2classify(:,1));
% else
% handles.matrix2classify(:,1) = exp(handles.matrix2classify(:,1));
% end
% --- Executes during object creation, after setting all properties.
function TransformPopupMenu_CreateFcn(hObject, eventdata, handles)
% hObject handle to TransformPopupMenu (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function KClasses_Callback(hObject, eventdata, handles)
% hObject handle to KClasses (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 KClasses as text
% str2double(get(hObject,'String')) returns contents of KClasses as a double
% --- Executes during object creation, after setting all properties.
function KClasses_CreateFcn(hObject, eventdata, handles)
% hObject handle to KClasses (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in CepstralPopupMenu.
function CepstralPopupMenu_Callback(hObject, eventdata, handles)
% hObject handle to CepstralPopupMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns CepstralPopupMenu contents as cell array
% contents{get(hObject,'Value')} returns selected item from CepstralPopupMenu
% --- Executes during object creation, after setting all properties.
function CepstralPopupMenu_CreateFcn(hObject, eventdata, handles)
% hObject handle to CepstralPopupMenu (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in RangeSpecify.
function RangeSpecify_Callback(hObject, eventdata, handles)
% hObject handle to RangeSpecify (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 RangeSpecify
state = get(hObject,'Value');
if state
set(handles.KClasses,'Enable','off');
set(handles.text3,'Visible','on');
set(handles.MinClusters,'Visible','on');
set(handles.text4,'Visible','on');
set(handles.MaxClusters,'Visible','on');
else
set(handles.KClasses,'Enable','on');
set(handles.text3,'Visible','off');
set(handles.MinClusters,'Visible','off');
set(handles.text4,'Visible','off');
set(handles.MaxClusters,'Visible','off');
end
% --- Executes on selection change in DistancePopupMenu.
function DistancePopupMenu_Callback(hObject, eventdata, handles)
% hObject handle to DistancePopupMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns DistancePopupMenu contents as cell array
% contents{get(hObject,'Value')} returns selected item from DistancePopupMenu
contents = get(hObject,'String');
dstring = contents{get(hObject,'Value')};
switch dstring
case 'Squared Euclidean'
handles.distancemeasure = 'sqEuclidean'
case 'City Block (L1)'
handles.distancemeasure = 'cityblock'
case 'Cosine'
handles.distancemeasure = 'cosine'
case 'Correlation'
handles.distancemeasure = 'correlation'
end
guidata(gcbo,handles);
% --- Executes during object creation, after setting all properties.
function DistancePopupMenu_CreateFcn(hObject, eventdata, handles)
% hObject handle to DistancePopupMenu (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
handles.distancemeasure = 'sqEuclidean';
guidata(gcbo,handles);
% --- Executes on button press in DiagnosticCheckbox.
function DiagnosticCheckbox_Callback(hObject, eventdata, handles)
% hObject handle to DiagnosticCheckbox (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 DiagnosticCheckbox
function pcaplot(matrix2classify,classification)
% Plots the first two principal components uses different shapes selected
% randomly and different colors selected randomly to show classes.
nclusters = length(unique(classification));
if not(isempty(find(classification == 0)))
nclusters = nclusters -1;
end
colors = rand(nclusters,3);
mark = mod(1:nclusters,13)+1;
[coef, score] = princomp(matrix2classify);
figure();
for i = 1:length(classification)
h = line(score(i,1),score(i,2));
markers = set(h,'Marker');
if classification(i) == 0 % For segments which are not classified
set(h,'Marker',markers{4});
set(h,'Color',[0 0 0]);
else
set(h,'Marker',markers{mark(classification(i))});
set(h,'Color',colors(classification(i),:));
end
end
xlabel('PCA 1');
ylabel('PCA 2');
function classifymatrix = madnormalize(classifymatrix, cols2normalize)
for i = cols2normalize
classifymatrix(:,i) = (classifymatrix(:,i) - median(classifymatrix(:,i))) / mad(classifymatrix(:,i));
end
% This code is modified from http://phys.columbia.edu/~aylin/clustering
function c=cluster_aylin(p1,p2);
%enter the p1,p2 found from hneighbors.m and get the struct array c.
%c(i).c will contain the indices of the objects that is in cluster i.
%c(1).c will be the cluster that has the maximum number of objects.
nn=size(p1,2);
p=std(p1);g=p(p2);p=p';
z=zeros(nn,1);zz=zeros(nn,1);
n=zeros(1,nn);
for i=1:nn
n(i)=max(max(p1(:,p2(:,i))));
end
gg=[1:nn; max(g); n]';n=find(n<1);
[q1,q1]=sort(gg(n,2)');
g=gg(n(q1),1);
t=cputime;
j=1;m=1
for i=1:length(n)
ii=g(i);b=p2(:,ii);a=b;aa=a(find(gg(a,2)<1));
if length([0; unique(z(aa))])<=2;a1=1;a2=0;
while a1~=a2;a1=length(aa);
a=unique(p2(:,a));a=a(find(gg(a,2)<1));
a=unique(a(find(gg(a,2)<=mean(gg(aa,2))+std(gg(aa,2)))));
a=a(find(ismember(a,aa)==0));
if ~isempty(a);aa=[aa;a];
jj=aa(find(z(aa)));
if ~isempty(jj);;
u=unique(z(jj));
if length(u)==1;
zz(aa(find(~z(aa))))=m;z(aa)=u;m=m+1;
end
break;
end
end;a2=length(aa);
end;a=aa;
jj=a(find(z(a)));
if isempty(jj);
z(a)=j;j=j+1;
zz(a)=m;zz(b)=m-.1;zz(ii)=m-.2;m=m+1;
end
end
end
u=unique(z)
u=u(find(u));v=length(u);vv=floor(1/v);if vv;vv=' is';else vv='s are';end
fprintf([int2str(v) ' cluster' vv ' found in ' num2str(cputime-t) 'sec\n\n'])
q0=[];for i=1:v;qq=find(z==u(i));q0=[q0 length(qq)];end;
[q1,q2]=sort(q0);%q2=q2(find(100*q1/nn>1));v=length(q2);
c=[];for i=1:v;qq=find(z==u(q2(i)));[j,j]=sort(zz(qq));c(v-i+1).c=qq(j);end;
if isempty(c);fprintf('\tNo cluster was found. \n \tscale the data (step size must be 1)\n');end
function [p1,p2]=hneighbors(e);
% this function finds the neighbors of each object in 'e' within a unit hypercube
% and returns the sorted object distances to q.q1 and their identities to q.q2 , 'e' is a
% matrix where i th row and j th column represents the j th component of the i th object.
s='find(';i='abs(e(:,%d)-e(i,%d))<1&';
% assuming that the data is given scaled and the characteristic step size is 1, variable s
% keeps a script to find the objects that lie within a unit hypercube around the i th object.
for j=1:size(e,2);
s=[s sprintf(i,j,j)];
end;s([end end+1])=');';
% runs the script s for each of the objects and stores the sorted distances
% from the i th object in q(i).q1 and their indentities in q(i).q2
nn=size(e,1);m=ceil(nn^(1/4));p1=ones(m,nn);p2=kron(ones(m,1),1:nn);
for i=1:nn;
j=eval(s);
[q,qq]=sort(sqrt(sum((e(j,:)-kron(ones(length(j),1),e(i,:)))'.^2)));q=q(find(q<1));mm=length(q);
qq=j(qq(1:mm))';mn=min([m mm]);
p1(1:mn,i)=q(1:mn)';
p2(1:mn,i)=qq(1:mn)';
end
function classification = cluster_hierarchical(matrix2classify)
[p1,p2] = hneighbors(matrix2classify);
c = cluster_aylin(p1,p2);
nclusters = size(c,2);
total_classified = 0
nsegments = size(matrix2classify,1);
classification = zeros(nsegments,1);
for i = 1:nclusters
for j = 1:length(c(i).c)
classification(c(i).c(j)) = i;
end
end
;
% --- Executes on button press in HierarchicalRadioButton.
function HierarchicalRadioButton_Callback(hObject, eventdata, handles)
% hObject handle to HierarchicalRadioButton (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 HierarchicalRadioButton
selected = get(hObject,'Value');
if selected
handles.cluster_method = 'hierarchical';
end
guidata(gcbo,handles);
% --- Executes on button press in KmeansRadioButton.
function KmeansRadioButton_Callback(hObject, eventdata, handles)
% hObject handle to KmeansRadioButton (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 KmeansRadioButton
selected = get(hObject,'Value');
if selected
handles.cluster_method = 'kmeans';
end
guidata(gcbo,handles);
function SegLenWeight_Callback(hObject, eventdata, handles)
% hObject handle to SegLenWeight (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 SegLenWeight as text
% str2double(get(hObject,'String')) returns contents of SegLenWeight as a double
% --- Executes during object creation, after setting all properties.
function SegLenWeight_CreateFcn(hObject, eventdata, handles)
% hObject handle to SegLenWeight (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
wave_browser.m
|
.m
|
Acoustic_Similarity-master/code/chronux/wave_browser/wave_browser.m
| 55,349 |
utf_8
|
31e3e1f789441ceb592f2d267f9bbcfc
|
function varargout = wave_browser(varargin)
% WAVE_BROWSER M-file for wave_browser.fig
% WAVE_BROWSER, by itself, creates a new WAVE_BROWSER or raises the existing
% singleton*.
%
% H = WAVE_BROWSER returns the handle to a new WAVE_BROWSER or the handle to
% the existing singleton*.
%
% WAVE_BROWSER('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in WAVE_BROWSER.M with the given input arguments.
%
% WAVE_BROWSER('Property','Value',...) creates a new WAVE_BROWSER or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before wave_browser_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to wave_browser_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 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help wave_browser
% Last Modified by GUIDE v2.5 29-May-2007 16:30:52
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @wave_browser_OpeningFcn, ...
'gui_OutputFcn', @wave_browser_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 wave_browser is made visible.
function wave_browser_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 wave_browser (see VARARGIN)
handles.firsttime = 0; % indicates the firsttime that segment has been precomputed
handles.precomputed_spec = 0; % indicates that the spectra has not been precomputed
handles.longfile = 0; % indicates whether the file is a long file
handles.maxwavsize = 10 * 44100; % I will have to explore what number works best here
handles.maxspec_t = 30; % duration of the max size of a spectra
handles.Fs = 44100; % default size to start with
handles.segments = []; % holds regular segments in the current chunk
handles.allsegments = []; % holds segments across the maximum wave size
handles.loadedsegment = 0; % indicates no segments have been loaded
handles.lastmarkerstart = 1; % largest segment
handles.segmentmode = 0; % by default start off with segmenting turned off
handles.dontcutsegments = 0; % by default do not adapt to segments
handles.automethod = 'threshold'; % use threshold or ratiof method
handles.indexthresh = 10; % for ration method the threshold which to cut the curve off
handles.lower_range = [10 10000]; % the numerator in the ratio
handles.upper_range = [15000 20000]; % the denomitor in the ratio
handles.nsmooth = 0; % moving average parameter for the thresholds curves
positionP = get(handles.OptionsUiPanel,'Position');
positionF = get(gcf,'Position');
positionF(3) = positionF(3) - positionP(3);
% set(gcf,'Position',positionF); % untested
% Choose default command line output for wave_browser
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes wave_browser wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = wave_browser_OutputFcn(hObject, eventdata, handles)
% Get default command line output from handles structure
varargout{1} = handles.output;
function Frequency_Callback(hObject, eventdata, handles)
handles.Fs = eval(get(hObject,'String'));
guidata(gcbo,handles);
function Frequency_CreateFcn(hObject, eventdata, handles)
set(hObject,'String', '44100');
handles.Fs = 44100;
guidata(gcbo,handles);
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in LoadFile.
function LoadFile_Callback(hObject, eventdata, handles)
[fname pname]=uigetfile({'*.wav';'*.*'},'Load Time Series');
if fname == 0
return
end
set(handles.FileNameString, 'String',fname);
handles.filename = [pname fname];
[path] = cell2mat(regexp( handles.filename, '^.*\', 'match' ));
[extension] = cell2mat(regexp( handles.filename, '\w+$', 'match' ));
set(handles.Path,'String',path);
% set(handles.Extensions,'String',extension);
handles.segments = [];
handles.allsegments = [];
handles = loadfile(hObject, eventdata, handles);
guidata(hObject,handles);
function [wavesize channels] = wavsizeget(filename);
% Provides usable information about a file
wavesize = 0;
[filestatus info] = wavfinfo(filename);
info = regexp(info,'[0-9]+','match');
channels = str2num(info{2});
wavesize = str2num(info{1});
function handles = loadfile(hObject, eventdata, handles, varargin)
% Function for loading a file or using the optional varargin to load a
% specified position and size in the file
% contents=get(handles.endian,'String');
% precision=contents{get(handles.endian,'Value')};
[datasize channels] = wavsizeget(handles.filename);
handles.wavsize = datasize; % total number of samples in the files
try
handles.maxwavsize = round(handles.Fs * str2num(get(handles.MaximumWavSize,'String')));
catch
handles.maxwavsize = 20;
set(handles.MaximumWavSize,'String',num2str(handles.maxwavsize));
handles.maxwavsize = handles.maxwavsize * handles.Fs;
end
if isempty(varargin)
handles.markerstart = 1;
if datasize > handles.maxwavsize
handles.markerend = handles.maxwavsize;
handles.longfile = 1; % indicates that the file is long and will be loaded in chunks
else
handles.markerend = datasize;
end
else % passed in optional parameter
handles.markervec = varargin{1};
handles.markerstart = handles.markervec(1);
handles.markerend = handles.markervec(2);
end
if handles.markerstart <= 1 % make sure the range is possible
handles.markerstart = 1;
set(handles.PreviousChunk,'Enable','off');
else
set(handles.PreviousChunk,'Enable','on');
end
if handles.markerend >= handles.wavsize
handles.markerend = handles.wavsize;
set(handles.NextChunk,'Enable','off');
else
set(handles.NextChunk,'Enable','on');
end
if handles.maxwavsize < handles.wavsize
total_chunk = ceil(handles.wavsize / handles.maxwavsize);
i = 1;
while (i < total_chunk) && (handles.markerend >= (handles.maxwavsize * i))
i = i + 1;
end
current_chunk = i-1;
if handles.markerend == handles.wavsize
current_chunk = total_chunk;
end
set(handles.ChunkText,'String',['Chunk ' num2str(current_chunk) '/' num2str(total_chunk)]);
end
try
handles.maxseglength = round(handles.Fs * str2num(get(handles.MaxSegLength,'String')));
catch
handles.maxseglength = handles.Fs * 1;
end
set(handles.RealDuration,'String',num2str(handles.wavsize/handles.Fs,'%.1f'));
if handles.segmentmode % only if in segment mode make sure segments are not cut
if (handles.markerstart - handles.lastmarkerstart > 0) % only do this in terms of forward movement
if handles.dontcutsegments % this code is added so segments are not cut off when segmenting
if not(isempty(handles.segments)) % at least one segment has been defined previously
maxsegend = handles.segments(1).end; % find last defined segment in previous view
for i = 2:length(handles.segments)
if handles.segments(i).end > maxsegend
maxsegend = handles.segments(i).end;
end
end
maxsegend = round(maxsegend * handles.Fs);
if (handles.lastmarkerend - maxsegend) < (handles.lastmarkerend - handles.maxseglength)
handles.markerstart = (handles.lastmarkerstart + maxsegend) + 1; % defined segment is closer to the end
else
handles.markerstart = handles.lastmarkerend - handles.maxseglength;
end
else
handles.markerstart = handles.lastmarkerend - handles.maxseglength;
end
handles.markerend = handles.markerstart + handles.maxwavsize - 1;
if handles.markerend > handles.wavsize
handles.markerend = handles.wavsize;
end
end
end
end
hw=waitbar(0,'Loading ...'); waitbar(0.5,hw); drawnow;
[handles.markerstart handles.markerend]/handles.Fs
[handles.ts,handles.Fs] = wavread(handles.filename, [handles.markerstart handles.markerend]);
channel = str2double(get(handles.channel,'String'));
handles.ts = handles.ts(:,channel);
count = length(handles.ts);
handles.ts = handles.ts/std(handles.ts); % variance normalisation
set(handles.Frequency,'String', num2str(handles.Fs));
set( handles.Duration, 'String', count/handles.Fs );
Tim=eval(get(handles.DisplayWindow,'String'));
display_frac = 1;%max(1,Tim*handles.Fs/count);
set( handles.slider1, 'Value', 0 );
set( handles.SegmentButton, 'Enable', 'on' );
if handles.longfile
set(handles.SeekButton,'Enable', 'on');
end
set(handles.LoadNext, 'Enable', 'on' );
set(handles.PlayAll, 'Enable', 'on' );
set(handles.PlayWindow, 'Enable', 'on' );
set(handles.Plot, 'Enable', 'on' );
set(handles.PlotAllButton, 'Enable', 'on');
set(handles.Precompute, 'Enable','on');
set(handles.Jump,'Enable','on');
set(handles.JumpBack,'Enable','on');
handles.segments = []; % remove the current segments
handles.segments = filtersegments(handles,handles.allsegments);
set(handles.Precompute,'Value',1); % Set into precompute mode
Precompute_Callback(handles.Precompute, eventdata, handles);
handles = guidata(gcbo);
% set(handles.Precompute,'Value',1);
handles.precomputed_spec = 1;
handles.dontcutsegments = 1; % make sure segments are not cut off
handles.lastmarkerstart = handles.markerstart;
handles.lastmarkerend = handles.markerend;
close(hw);
% guidata(gcbo,handles);
% Plot_Callback(hObject, eventdata, handles);
% --- Executes on selection change in endian.
function endian_Callback(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function endian_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function edit2_Callback(hObject, eventdata, handles)
function edit2_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function FileNameString_Callback(hObject, eventdata, handles)
function FileNameString_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function WinSize_Callback(hObject, eventdata, handles)
function WinSize_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
function slider1_CreateFcn(hObject, eventdata, handles)
usewhitebg = 1;
if usewhitebg
set(hObject,'BackgroundColor',[.9 .9 .9]);
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function StepSize_Callback(hObject, eventdata, handles)
function StepSize_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function TW_Callback(hObject, eventdata, handles)
function TW_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function DisplayWindow_Callback(hObject, eventdata, handles)
function DisplayWindow_CreateFcn(hObject, eventdata, handles)
set(hObject, 'String', '4');
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
%function axes2ButtonDownCallback(hObject, eventdata, handles)
%h=handles.axesS; P=get(h,'CurrentPoint');
%fprintf( 'worked %f %f!\n', P(1),P(2));
function indexinS = getindexpre_c(t,timestart,timeend)
% A function for indexing correctly in time to a spectra stored in memory
tlen = length(t);
i=1;
while (i <= tlen) && (t(i) < timestart)
i = i + 1;
end
firstindex = i;
while (i <= tlen) && (t(i) < timeend)
i = i + 1;
end
secondindex = i;
indexinS = [firstindex secondindex];
% --- Executes on button press in Plot.
function Plot_Callback(hObject, eventdata, handles)
hw=waitbar(0.5,'Spectrogram calculation');drawnow
params.Fs=handles.Fs;
window=eval(get(handles.WinSize,'String'));
winstep=eval(get(handles.StepSize,'String'));
movingwin=[window winstep]*0.001;
fmin=eval(get(handles.MinFreq,'String'));
fmax=eval(get(handles.MaxFreq,'String'));
params.fpass=[fmin fmax];
p=eval(get(handles.TW,'String'));
params.tapers=[p floor(2*p-1)];
params.pad=1;
Tslider=get(handles.slider1,'Value');
Tim=eval(get(handles.DisplayWindow,'String'));
NT=min(round(Tim*handles.Fs),length(handles.ts));
handles.Tmin=1+floor(Tslider*length(handles.ts));
handles.Tmax=min(handles.Tmin+NT,length(handles.ts));
if handles.Tmax < length(handles.ts)
set( handles.Jump, 'Enable', 'on' );
else
set( handles.Jump, 'Enable', 'off' );
end
if handles.Tmin > 1
set( handles.JumpBack, 'Enable', 'on' );
else
set( handles.JumpBack, 'Enable', 'off' );
end
data=handles.ts(handles.Tmin:handles.Tmax);data=data(:);
handles.upper_range = eval(get(handles.RatioLower,'String'));
handles.lower_range = eval(get(handles.RatioUpper,'String'));
handles.indexthresh = eval(get(handles.RatioThresh,'String'));
handles.nsmooth = eval(get(handles.SmoothFactor,'String'));
% determine spectrum type
contents=get(handles.SpectrumType,'String');
stype=contents{get(handles.SpectrumType,'Value')};
axes(handles.axesW); plot(((handles.markerstart - 1)/handles.Fs) + [handles.Tmin:handles.Tmax]/handles.Fs,handles.ts(handles.Tmin:handles.Tmax)); axis tight;
switch stype
case 'Original'
if not(handles.precomputed_spec) || handles.firsttime
[S,t,f]=mtspecgramc(diff(data),movingwin,params);
timeax=(handles.Tmin/handles.Fs)+t;
else
indexinS = getindexpre_c(handles.t,(handles.Tmin-1)/handles.Fs,(handles.Tmax-1)/handles.Fs);
% indexinS = round(([handles.Tmin-1, handles.Tmax-1]/handles.Fs)/movingwin(2))+1;
if indexinS(1) < 1
indexinS(1) = 1;
end
SLen = length(handles.S(:,1));
if indexinS(2) > SLen
indexinS(2) = SLen;
end
f = handles.f;
t = handles.t(indexinS(1):indexinS(2));
S = handles.S(indexinS(1):indexinS(2),:);
timeax=t;
end
cmap='default';
th=eval(get(handles.AmpThresh,'String'));
% This sets up the automatic segmenting algorithm
if strcmp(handles.automethod,'threshold')
[Stot boxcurve] = compute_threshold_free(S,th,handles.nsmooth);
axes(handles.axesP);
semilogy(timeax,Stot);
axis tight;
elseif strcmp(handles.automethod,'ratiof')
[ratiof boxcurve] = compute_index(S,handles.lower_range,handles.upper_range,fmin,fmax,handles.indexthresh,handles.nsmooth);
axes(handles.axesP);
semilogy(timeax,ratiof);
axis tight;
end
hold on; semilogy(timeax,boxcurve,'r'); hold off;
axes(handles.axesS);
imagesc(timeax,f,log(S)'); axis xy; colormap(cmap);
%imagesc(t,f,log(S)'); axis xy; colormap(cmap);
% set(h,'ButtonDownFcn',axes2ButtonDownCallback);
case 'Time Derivative'
if not(handles.precomputed_spec) || handles.firsttime
[S,t,f]=mtdspecgramc(diff(data),movingwin,0,params);S = S';
timeax=handles.Tmin/handles.Fs+t;
else
indexinS = getindexpre_c(handles.t,(handles.Tmin-1)/handles.Fs,(handles.Tmax-1)/handles.Fs);
% indexinS = round(([handles.Tmin-1, handles.Tmax-1]/handles.Fs)/movingwin(2))+1;
if indexinS(1) < 1
indexinS(1) = 1;
end
SLen = length(handles.S(1,:));
if indexinS(2) > SLen
indexinS(2) = SLen;
end
f = handles.f;
t = handles.t(indexinS(1):indexinS(2));
S = handles.S(:,indexinS(1):indexinS(2));
timeax = t;
end
cmap='gray';
th=eval(get(handles.TDerThresh,'String'));
if strcmp(handles.automethod,'threshold')
[Stot boxcurve] = compute_threshold_free(abs(S'),th.handles.nsmooth);
axes(handles.axesP);
semilogy(timeax,Stot);
axis tight;
elseif strcmp(handles.automethod,'ratiof')
[ratiof boxcurve] = compute_index(abs(S)',handles.lower_range,handles.upper_range,fmin,fmax,handles.indexthresh,handles.nsmooth);
axes(handles.axesP);
semilogy(timeax,ratiof);
axis tight;
end
hold on; semilogy(timeax,boxcurve,'r'); hold off;
axes(handles.axesS);
imagesc(timeax,f,S); axis xy; colormap(cmap);
cmin=0.02*min(min(S)); cmax=0.02*max(max(S)); caxis([cmin cmax]);
case 'Frequency Derivative'
if not(handles.precomputed_spec) || handles.firsttime
[S,t,f]=mtdspecgramc(diff(data),movingwin,pi/2,params);S=S';
timeax=handles.Tmin/handles.Fs+t;
else
indexinS = getindexpre_c(handles.t,(handles.Tmin-1)/handles.Fs,(handles.Tmax-1)/handles.Fs);
if indexinS(1) < 1
indexinS(1) = 1;
end
SLen = length(handles.S(1,:));
if indexinS(2) > SLen
indexinS(2) = SLen;
end
f = handles.f;
t = handles.t(indexinS(1):indexinS(2));
S = handles.S(:,indexinS(1):indexinS(2));
timeax = t;
end
cmap='gray';
th=eval(get(handles.TDerThresh,'String'));
if strcmp(handles.automethod,'threshold')
[Stot boxcurve] = compute_threshold_free(abs(S'),th,handles.nsmooth);
axes(handles.axesP);
semilogy(timeax,Stot);
axis tight;
elseif strcmp(handles.automethod,'ratiof')
[ratiof boxcurve] = compute_index(abs(S)',handles.lower_range,handles.upper_range,fmin,fmax,handles.indexthresh,handles.nsmooth);
axes(handles.axesP);
semilogy(timeax,ratiof);
axis tight;
end
hold on; semilogy(timeax,boxcurve,'r'); hold off;
axes(handles.axesS);
imagesc(timeax,f,S); axis xy; colormap(cmap);
cmin=0.02*min(min(S)); cmax=0.02*max(max(S)); caxis([cmin cmax]);
end;
if handles.firsttime % first time precomputing the spectra
handles.S = S;
handles.t = t;
handles.f = f;
handles.precomputed_spec = 1;
handles.firstime = 0;
end
% S = log(S)';
% Smax = max(max(S));
% Smin = min(min(S));
% Ssmall = uint8(round(((S - Smin)/(Smax-Smin))*255));
%
% save('uint8_test.mat','Ssmall','-mat');
% save('full_rest.mat','S','-mat');
handles.times=timeax(:);
handles.transition=[diff(boxcurve(:)); 0];
set( handles.axesS, 'XTick', [] );
set( handles.axesP, 'XTick', [] );
if exist('handles.datacursor')
delete( handles.datacursor );
delete( handles.segmentLineP );
delete( handles.segmentLineS );
delete( handles.segmentLineW );
end
handles.datacursor=datacursormode(handles.figure1);
axes(handles.axesP);
handles.segmentLineP = line('Visible','off');
axes(handles.axesS);
handles.segmentLineS = line('Visible','off');
axes(handles.axesW);
handles.segmentLineW = line('Visible','off');
if get( handles.SegmentButton, 'Value' )
set(handles.datacursor,'Enable','on','DisplayStyle','datatip','SnapToDataVertex','off','UpdateFcn',@datacursorfunc);
end
guidata(gcbo,handles);
close(hw);
handles = draw_segments(handles);
function [Stot boxcurve] = compute_threshold_free(S,th,n)
% Computes the threshold based on a floating percentage of the maximum
% summed intensity
Stot=sum(S,2);
boxcurve=Stot;
smax=max(Stot);
Stot = smooth_curve(Stot',n); % for removing extremes
boxcurve(find(Stot<th*smax))= smax*th;
boxcurve(find(Stot>th*smax))= smax;
function [ratiof boxcurve] = compute_index(S,lower_range,upper_range,lowerfreq,upperfreq,indexthresh,n)
% This algorithm is based on the method described in Aylin's
% dissertation.
S = S';
nfreqs = length(S(:,1));
freqspern = (upperfreq - lowerfreq) / nfreqs;
indexinlower = fliplr(nfreqs - round((lower_range - lowerfreq)/freqspern));
indexinupper = fliplr(nfreqs - round((upper_range - lowerfreq)/freqspern)) + 1;
nrangelower = indexinlower(2)-indexinlower(1);
nrangeupper = indexinupper(2)-indexinupper(1);
ratiof = ( sum(S(indexinupper(1) : indexinupper(2),:)) / nrangeupper )...
./ ( sum(S( indexinlower(1) : indexinlower(2),:)) / nrangelower );
ratiof = smooth_curve(ratiof,n); % for smoothing the curve
maxrf = max(ratiof);
boxcurve = ratiof;
boxcurve(find(ratiof<indexthresh))= indexthresh;
boxcurve(find(ratiof>=indexthresh))= maxrf;
function smoothedcurve = smooth_curve(curve2smooth,n);
% Computes the moving average of the curve where n is an integer
% for example n = 1 averages the current point with the point before and afterwards
m = length(curve2smooth);
if m > 0
curve2smooth = [repmat(curve2smooth(1),1,n) curve2smooth repmat(curve2smooth(m),1,n)];
smoothedcurve = zeros(m,1);
for i = 1:m
smoothedcurve(i) = sum(curve2smooth(i:i + 2 * n)) / (2 * n + 1);
end
else % just to save computation time
smoothed_curve = curve2smooth;
end
function MinFreq_Callback(hObject, eventdata, handles)
function MinFreq_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function MaxFreq_Callback(hObject, eventdata, handles)
function MaxFreq_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in SpectrumType.
function SpectrumType_Callback(hObject, eventdata, handles)
function SpectrumType_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function AmpThresh_Callback(hObject, eventdata, handles)
function AmpThresh_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function TDerThresh_Callback(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function TDerThresh_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in PlayAll.
function PlayAll_Callback(hObject, eventdata, handles)
wavplay(handles.ts,handles.Fs);
% --- Executes on button press in PlayWindow.
function PlayWindow_Callback(hObject, eventdata, handles)
wavplay(handles.ts(handles.Tmin:handles.Tmax),handles.Fs,'async');
%h=handles.axesP; axes(h); semilogy(timeax,Stot); axis tight;
function txt = datacursorfunc(empt,event_obj)
pos = get(event_obj,'Position');
handles=guidata(get(event_obj,'Target'));
set(handles.segmentLineP,'Xdata',[pos(1) pos(1)],'Ydata',[0.00000000000001*pos(2) 1000000000000*pos(2)],'Visible','on' );
set(handles.segmentLineS,'Xdata',[pos(1) pos(1)],'Ydata',[0.00000000000001*pos(2) 1000000000000*pos(2)],'Visible','on' );
set(handles.segmentLineW,'Xdata',[pos(1) pos(1)],'Ydata',[-100000000000*pos(2) 1000000000000*pos(2)],'Visible','on' );
if handles.start_stop_enable == 1
set( handles.SegStartButton, 'Enable', 'on' );
else
set( handles.SegEndButton, 'Enable', 'on' );
end
txt = {[num2str(pos(1))]};
guidata(gcbo,handles);
function handles = draw_segments( handles )
n = 1;
while n <= length( handles.segments )
handles.segments(n).lines=[];
handles.segments(n) = draw_all_x( handles, handles.segments(n) );
n = n + 1;
end
guidata(gcbo,handles);
% --- Executes on button press in SegmentButton.
function SegmentButton_Callback(hObject, eventdata, handles)
toggled = get( handles.SegmentButton, 'Value' );
if toggled
handles.segments = [];
handles.segmentmode = 1;
set( handles.SegmentButton, 'String', 'Segment On' );
set( handles.SegmentButton, 'Enable', 'off' );
if not(exist([handles.filename '.seg.txt']));
set( handles.LoadSegments, 'Enable', 'off' );
else
set( handles.LoadSegments, 'Enable', 'on' );
end
set( handles.AutoSegmentFile, 'Enable','on');
set( handles.AutoSegButton, 'Enable', 'on' );
set( handles.SegmentLengthEdit, 'Enable', 'on' );
set( handles.SegmentLengthText, 'Enable', 'on ' );
set( handles.SaveSegments, 'Enable', 'on' );
set( handles.DeleteSegment, 'Enable', 'on' );
set( handles.DeleteAllButton, 'Enable', 'on' );
set( handles.SegCancel, 'Enable', 'on' );
set( handles.PlotSegments, 'Enable', 'on' );
set( handles.LoadFile, 'Enable', 'off' );
set( handles.LoadNext, 'Enable', 'off' );
handles.start_stop_enable = 1;
set(handles.datacursor,'Enable','on','DisplayStyle','datatip','SnapToDataVertex','off','UpdateFcn',@datacursorfunc);
fprintf( 'Segment mode on!\n' );
else
handles.segmentmode = 0;
set( handles.SegmentButton, 'String', 'Segment Off' );
set( handles.AutoSegButton, 'Enable', 'off' );
set( handles.AutoSegmentFile, 'Enable','off');
set( handles.SegmentLengthEdit, 'Enable', 'off' );
set( handles.SegmentLengthText, 'Enable', 'off' );
set( handles.LoadSegments, 'Enable', 'off' );
set( handles.SaveSegments, 'Enable', 'off' );
set( handles.SegStartButton, 'Enable', 'off' );
set( handles.SegEndButton, 'Enable', 'off' );
set( handles.DeleteSegment, 'Enable', 'off' );
set( handles.DeleteAllButton, 'Enable', 'off' );
set( handles.SegCancel, 'Enable', 'off' );
set( handles.PlotSegments, 'Enable', 'off' );
set( handles.LoadFile, 'Enable', 'on' );
set( handles.LoadNext, 'Enable', 'on' );
set(handles.datacursor,'Enable','off')
fprintf( 'Segment mode off!\n' );
end
guidata(gcbo,handles);
% --- Executes on button press in SegStartButton.
function SegStartButton_Callback(hObject, eventdata, handles)
set( handles.LoadSegments, 'Enable', 'off' );
set( handles.SegStartButton, 'Enable', 'off' );
handles.start_stop_enable = 0;
xy=get(handles.segmentLineP,'Xdata');
handles.segment.start=xy(1);
handles.segment.lines=[];
axes(handles.axesP);
set(handles.segmentLineP,'LineWidth',3);
handles.segment.lines(1) = handles.segmentLineP;
handles.segmentLineP = line('Visible','off');
axes(handles.axesS);
set(handles.segmentLineS,'LineWidth',3);
handles.segment.lines(2) = handles.segmentLineS;
handles.segmentLineS = line('Visible','off');
axes(handles.axesW);
set(handles.segmentLineW,'LineWidth',3);
handles.segment.lines(3) = handles.segmentLineW;
handles.segmentLineW = line('Visible','off');
guidata(gcbo,handles);
% --- Executes on button press in SegEndButton.
function SegEndButton_Callback(hObject, eventdata, handles)
set( handles.SegEndButton, 'Enable', 'off' );
handles.start_stop_enable = 1;
xy=get(handles.segmentLineP,'Xdata');
handles.segment.end=xy(1);
handles.segment=draw_all_x( handles, handles.segment );
handles.segments = [handles.segments handles.segment];
guidata(gcbo,handles);
function out=draw_all_x( handles, segment )
segment=draw_x( handles.axesP, segment );
segment=draw_x( handles.axesS, segment );
segment=draw_x( handles.axesW, segment );
out=segment;
function out=draw_x( theaxes, segment )
axes(theaxes);
ylim = get(theaxes,'YLim');
segment.lines = [segment.lines line('Xdata',[segment.start segment.start],'Ydata',ylim,'LineWidth',3)];
segment.lines = [segment.lines line('Xdata',[segment.end segment.end],'Ydata',ylim,'LineWidth',3)];
segment.lines = [segment.lines line('Xdata',[segment.start segment.end],'Ydata',ylim,'LineWidth',3)];
segment.lines = [segment.lines line('Xdata',[segment.start segment.end],'Ydata',[ylim(2) ylim(1)],'LineWidth',3)];
out=segment;
% --- Executes on button press in JumpBack.
function JumpBack_Callback(hObject, eventdata, handles)
Jump_shared(hObject, eventdata, handles, -1 )
% --- Executes on button press in Jump.
function Jump_Callback(hObject, eventdata, handles)
Jump_shared(hObject, eventdata, handles, 1 )
function Jump_shared(hObject, eventdata, handles, jump_dir )
Tim=eval(get(handles.DisplayWindow,'String'));
tDuration = str2num(get(handles.Duration,'String'));
maxTslider = (tDuration - Tim)/tDuration;
NT=min(round(Tim*handles.Fs),length(handles.ts));
Tslider=get(handles.slider1,'Value');
Tslider = Tslider + jump_dir * Tim * handles.Fs / length(handles.ts);
if Tim > tDuration
set(handles.DisplayWindow,'String',num2str(tDuration));
Tslider = 0;
end
if jump_dir == 1 % jumping forward
if Tslider > maxTslider
Tslider = maxTslider;
end
end
if jump_dir == -1 % jumping backwards
if Tslider < 0
Tslider = 0
end
end
% if Tslider > 1
% Tslider = ( length(handles.ts) - NT ) / length(handles.ts);
% end
% if Tslider < 0
% Tslider = 0
% end
set(handles.slider1,'Value',Tslider);
guidata(gcbo,handles);
Plot_Callback(hObject, eventdata, handles)
function LoadNext_Callback(hObject, eventdata, handles)
% Get filename, extension. Look for next file with same extension, no seg
% file associated
exclude_name = [handles.filename, get(handles.ExcludeExt,'String')];
if not(exist(exclude_name))
fid=fopen( exclude_name, 'w' );
fclose( fid);
end
[path] = cell2mat(regexp( handles.filename, '^.*\', 'match' ));
[extension] = cell2mat(regexp( handles.filename, '\w+$', 'match' ));
dirlist = dir( [path '*' extension] );
ndir = length(dirlist);
n = 1;
while n <= ndir
file = dirlist(n).name;
if not(exist([path file get(handles.ExcludeExt,'String')]))
break;
end
n = n + 1;
end
if n <= ndir
set( handles.FileNameString, 'String',file);
handles.filename = [path file];
guidata(gcbo,handles);
handles = loadfile(hObject, eventdata, handles);
else
error('No more files found matching desired pattern');
end
% --- Executes on button press in Precompute.
function Precompute_Callback(hObject, eventdata, handles)
% handles = guidata(gcbo);
toggled = get( hObject, 'Value' );
if toggled
% Disable spectra configuration parameters
% set(handles.DisplayWindow, 'Enable', 'off');
set(handles.WinSize, 'Enable', 'off');
set(handles.StepSize, 'Enable', 'off');
set(handles.TW, 'Enable', 'off');
set(handles.MinFreq, 'Enable', 'off');
set(handles.MaxFreq, 'Enable', 'off');
set(handles.SpectrumType, 'Enable', 'off');
% set(handles.AmpThresh, 'Enable', 'off');
% set(handles.TDerThresh, 'Enable', 'off');
set(handles.LoadNext, 'Enable','off');
% set(handles.LoadFile, 'Enable','off');
valueTslider = get(handles.slider1,'Value');
set(handles.slider1,'Value',0);
strDuration = get(handles.Duration,'String');
strWindow = get(handles.DisplayWindow,'String');
handles.firsttime = 1; % indicates that the spectra need to be calculated
if str2num(strDuration) > handles.maxspec_t
strDuration = num2str(handles.maxspec_t);
end
set(handles.DisplayWindow,'String',strDuration);
Plot_Callback(handles.Plot, eventdata, handles);
handles = guidata(hObject);
handles.firsttime = 0;
handles.precomputed_spec = 1;
set(handles.DisplayWindow,'String',strWindow);
set(handles.slider1,'Value',valueTslider);
Plot_Callback(handles.Plot, eventdata, handles);
handles = guidata(hObject);
handles.precomputed_spec = 1;
else
handles.precomputed_spec = 0;
% Enable spectra configuration parameters
handles.S = []; % release memory
handles.t = [];
handles.f = [];
set(handles.WinSize, 'Enable', 'on');
set(handles.StepSize, 'Enable', 'on');
set(handles.TW, 'Enable', 'on');
set(handles.MinFreq, 'Enable', 'on');
set(handles.MaxFreq, 'Enable', 'on');
set(handles.SpectrumType, 'Enable', 'on');
% set(handles.AmpThresh, 'Enable', 'on');
set(handles.TDerThresh, 'Enable', 'on');
set(handles.LoadNext, 'Enable','on');
set(handles.LoadFile, 'Enable','on');
end
guidata(hObject,handles);
function Precompute_CreateFcn(hObject, eventdata, handles)
function Path_Callback(hObject, eventdata, handles)
path=get(hObject,'String')
function Path_CreateFcn(hObject, eventdata, handles)
set(hObject,'String',pwd);
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function Extensions_Callback(hObject, eventdata, handles)
function Extensions_CreateFcn(hObject, eventdata, handles)
set(hObject,'String','wav');
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function Duration_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function LoadSegments_Callback(hObject, eventdata, handles)
handles = load_segment(handles, [handles.filename '.seg.txt'] );
set( handles.LoadSegments, 'Enable', 'off' );
handles = draw_segments( handles );
guidata(gcbo,handles);
function handles=load_segment(handles,filename)
fid=fopen( filename, 'r' );
segments = [];
scanned=fscanf( fid, '%g %g',[2 inf] );
n = 1;
while n <= size(scanned, 2)
segment.start = scanned(1,n);
segment.end = scanned(2,n);
segment.lines = [];
segments = [ segments segment ];
n = n + 1;
end
handles.allsegments = segments; % all segments holds all segments for the file
handles.segments = filtersegments(handles,handles.allsegments); % get segments for the current chunk
handles.loadedsegment = 1; % indicates segments have been filtered
guidata(gcf,handles);
function filteredsegments = filtersegments(handles,segments)
% Returns segments which are in the current defined view. Returns segments
% which are not cut off.
realstart = handles.markerstart / handles.Fs;
realend = handles.markerend / handles.Fs;
filteredsegments = [];
for i = 1:length(segments) % no garuantee segments are in the same order
if (segments(i).start >= realstart) && (segments(i).end <= realend)
filteredsegments = [filteredsegments segments(i)];
end
end
for i=1:length(filteredsegments)
filteredsegments(i).start = filteredsegments(i).start - realstart;
filteredsegments(i).end = filteredsegments(i).end - realstart;
end
function ExcludeExt_Callback(hObject, eventdata, handles)
% Hints: get(hObject,'String') returns contents of ExcludeExt as text
% str2double(get(hObject,'String')) returns contents of ExcludeExt as a double
function ExcludeExt_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function DeleteSegment_Callback(hObject, eventdata, handles)
pos=get(handles.segmentLineP,'Xdata');
n = 1;
while n <= length( handles.segments )
if pos(1) >= handles.segments(n).start && pos(1) <= handles.segments(n).end
handles=delete_segment( handles, n );
else
n = n + 1;
end
end
drawnow;
guidata(gcbo,handles);
function handles=delete_segment( handles, n )
nl = 1;
while nl <= length( handles.segments(n).lines )
set( handles.segments(n).lines(nl), 'Visible', 'off');
nl = nl + 1;
end
handles.segments(n) = [];
fprintf('deleted!\n');
function SaveSegments_Callback(hObject, eventdata, handles)
% For the currently defined segments append to the segment list
handles = savesegments2mem(handles);
segment_file = fopen( [handles.filename '.seg.txt'], 'wt' );
n = 1;
while n <= size(handles.allsegments, 2)
fprintf( segment_file, '%f %f\n', handles.allsegments(n).start, handles.allsegments(n).end );
n = n + 1;
end
fclose(segment_file);
set( handles.SegmentButton, 'Enable', 'on' );
guidata(gcbo,handles);
function handles=savesegments2mem(handles)
% Updates the handles allsegments in memory
% first remove in all segments all segments which are in the current chunk
oldsegments = [];
realstart = handles.markerstart / handles.Fs; % readjust time
realend = handles.markerend / handles.Fs; % readjust time
for i = 1:length(handles.allsegments)
if not((handles.allsegments(i).start) >= realstart && (handles.allsegments(i).end <= realend))
oldsegments = [oldsegments handles.allsegments(i)];
end
end
% now put in the new segments
newsegments = [];
for i = 1:length(handles.segments)
segment = handles.segments(i);
segment.start = segment.start + realstart;
segment.end = segment.end + realstart;
newsegments = [newsegments segment];
end
handles.allsegments = [oldsegments newsegments];
function SegCancel_Callback(hObject, eventdata, handles)
set( handles.SegmentButton, 'Enable', 'on' );
guidata(gcbo,handles);
function PlotSegments_Callback(hObject, eventdata, handles)
% Load Segments in directory
[path] = cell2mat(regexp( handles.filename, '^.*\', 'match' ));
[extension] = cell2mat(regexp( handles.filename, '\w+$', 'match' ));
path=get(handles.Path,'String');
extension=get(handles.Extensions,'String');
dirlist = dir( [path '\*' extension '.seg.txt'] );
ndir = length(dirlist);
n = 1;
all_segments = [];
while n <= ndir
file = dirlist(n).name;
segments = load_segment([path '\' file]);
all_segments = [all_segments segments];
n = n + 1;
end
% Plot info
if length(all_segments) > 2
figure();
axes();
nbin= max(length([all_segments.end])/5,10);
syllable_lengths=[all_segments.end]-[all_segments.start];
hi=hist( syllable_lengths ,nbin);
tl=min( syllable_lengths );
th=max( syllable_lengths );
times=tl:((th-tl)/(nbin-1)):th;
plot(times,hi);
xlabel('Segment Length (s)');
ylabel('N');
title(['All segments in ' path]);
else
error('too few segments to plot');
end
guidata(gcbo,handles);
function AutoSegButton_Callback(hObject, eventdata, handles)
n = 1;
segments = [];
segment.start = 0;
segment.end = 0;
segment.lines = [];
minlen = eval(get( handles.SegmentLengthEdit, 'String' ));
while n < length( handles.times )
if ( handles.transition(n) > 0 )
segment.start = handles.times(n);
end
if ( handles.transition(n) < 0 )
segment.end = handles.times(n);
end
if (segment.start > 0) && (segment.end) > 0 && (segment.end - segment.start) > minlen
segments = [ segments segment ];
segment.start = 0;
segment.end = 0;
end
n = n + 1;
end
handles.segments = [handles.segments segments];
handles = draw_segments( handles );
guidata(gcbo,handles);
function DeleteAllButton_Callback(hObject, eventdata, handles)
while length( handles.segments )
handles = delete_segment( handles, 1 );
end
guidata(gcf,handles);
% --- Executes on button press in PlotAllButton.
function PlotAllButton_Callback(hObject, eventdata, handles)
% hObject handle to PlotAllButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.slider1,'Value',0);
strDuration = get(handles.Duration,'String');
if str2num(strDuration) > handles.maxspec_t
strDuration = num2str(handles.maxspec_t);
end
set(handles.DisplayWindow,'String',strDuration);
Plot_Callback(hObject, eventdata, handles);
% --- Executes on button press in PreviousChunk.
function PreviousChunk_Callback(hObject, eventdata, handles)
% hObject handle to PreviousChunk (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% [handles.markerstart handles.markerend]
handles = savesegments2mem(handles);
handles = loadfile(hObject, eventdata, handles,[handles.markerstart-handles.maxwavsize-1,handles.markerstart-1]);
% [handles.markerstart handles.markerend]
;
guidata(gcf,handles);
% --- Executes on button press in NextChunk.
function NextChunk_Callback(hObject, eventdata, handles)
% hObject handle to NextChunk (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = savesegments2mem(handles);
handles = loadfile(hObject, eventdata, handles, [handles.markerend+1,handles.markerend+1+handles.maxwavsize]);
guidata(gcf,handles);
% --- Executes on button press in AutoSegmentFile.
function AutoSegmentFile_Callback(hObject, eventdata, handles)
% hObject handle to AutoSegmentFile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
while (handles.markerend < handles.wavsize)
PlotAllButton_Callback(hObject, eventdata, handles);
handles = guidata(gcbo);
AutoSegButton_Callback(hObject, eventdata, handles);
handles = guidata(gcbo);
NextChunk_Callback(hObject, eventdata, handles);
handles = guidata(gcbo);
end
PlotAllButton_Callback(hObject, eventdata, handles);
handles = guidata(gcbo);
AutoSegButton_Callback(hObject, eventdata, handles);
handles = guidata(gcbo);
guidata(gcbo,handles);
function MaxSegLength_Callback(hObject, eventdata, handles)
% hObject handle to MaxSegLength (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 MaxSegLength as text
% str2double(get(hObject,'String')) returns contents of MaxSegLength as a double
% --- Executes during object creation, after setting all properties.
function MaxSegLength_CreateFcn(hObject, eventdata, handles)
% hObject handle to MaxSegLength (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function MaximumWavSize_Callback(hObject, eventdata, handles)
% hObject handle to MaximumWavSize (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 MaximumWavSize as text
% str2double(get(hObject,'String')) returns contents of MaximumWavSize as a double
% --- Executes during object creation, after setting all properties.
function MaximumWavSize_CreateFcn(hObject, eventdata, handles)
% hObject handle to MaximumWavSize (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in SeekButton.
function SeekButton_Callback(hObject, eventdata, handles)
% hObject handle to SeekButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Seek anywhere in a long file
handles = savesegments2mem(handles);
try
timetoseek = str2num(get(handles.SeektoEdit,'String'));
catch
timetoseek = 0;
set(handles.SeektoEdit,'String','0');
end
if timetoseek < 0
timetoseek = 0;
set(handles.SeektoEdit,'String','0');
end
timetoseek = round(timetoseek * handles.Fs);
if timetoseek >= handles.wavsize
timetoseek = timetoseek - handles.maxwavsize;
end
timetoseek = timetoseek + 1;
timetoseekend = timetoseek + handles.maxwavsize;
if timetoseekend > handles.wavsize
timetoseekend = handles.wavsize;
end
oldstate = handles.dontcutsegments;
handles.dontcutsegments = 0;
handles = loadfile(hObject,eventdata,handles,[timetoseek timetoseekend]);
handles.dontcutsegments = oldstate;
guidata(gcbo,handles);
function SeektoEdit_Callback(hObject, eventdata, handles)
% hObject handle to SeektoEdit (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 SeektoEdit as text
% str2double(get(hObject,'String')) returns contents of SeektoEdit as a double
% --- Executes during object creation, after setting all properties.
function SeektoEdit_CreateFcn(hObject, eventdata, handles)
% hObject handle to SeektoEdit (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function RealDuration_Callback(hObject, eventdata, handles)
% hObject handle to RealDuration (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 RealDuration as text
% str2double(get(hObject,'String')) returns contents of RealDuration as a double
% --- Executes during object creation, after setting all properties.
function RealDuration_CreateFcn(hObject, eventdata, handles)
% hObject handle to RealDuration (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in AutoMethodPopupMenu.
function AutoMethodPopupMenu_Callback(hObject, eventdata, handles)
% hObject handle to AutoMethodPopupMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns AutoMethodPopupMenu contents as cell array
% contents{get(hObject,'Value')} returns selected item from AutoMethodPopupMenu
contents = get(hObject,'String');
method = contents{get(hObject,'Value')}
if strcmp(method,'Summed intensity')
handles.automethod = 'threshold';
set(handles.AmpThresh,'Visible','on');
set(handles.RatioThresh,'Visible','off');
elseif strcmp(method,'Ratio')
handles.automethod = 'ratiof';
set(handles.AmpThresh,'Visible','off');
set(handles.RatioThresh,'Visible','on');
end
guidata(gcbo,handles);
% --- Executes during object creation, after setting all properties.
function AutoMethodPopupMenu_CreateFcn(hObject, eventdata, handles)
% hObject handle to AutoMethodPopupMenu (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function RatioThresh_Callback(hObject, eventdata, handles)
% hObject handle to RatioThresh (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 RatioThresh as text
% str2double(get(hObject,'String')) returns contents of RatioThresh as a double
% --- Executes during object creation, after setting all properties.
function RatioThresh_CreateFcn(hObject, eventdata, handles)
% hObject handle to RatioThresh (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function RatioLower_Callback(hObject, eventdata, handles)
% hObject handle to RatioLower (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 RatioLower as text
% str2double(get(hObject,'String')) returns contents of RatioLower as a double
% --- Executes during object creation, after setting all properties.
function RatioLower_CreateFcn(hObject, eventdata, handles)
% hObject handle to RatioLower (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function RatioUpper_Callback(hObject, eventdata, handles)
% hObject handle to RatioUpper (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 RatioUpper as text
% str2double(get(hObject,'String')) returns contents of RatioUpper as a double
% --- Executes during object creation, after setting all properties.
function RatioUpper_CreateFcn(hObject, eventdata, handles)
% hObject handle to RatioUpper (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in OptionsDisplay.
function OptionsDisplay_Callback(hObject, eventdata, handles)
% hObject handle to OptionsDisplay (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 OptionsDisplay
% positionP = get(handles.OptionsUiPanel,'Position');
% positionF = get(gcf,'Position');
state = get(hObject,'Value');
if state
set(handles.OptionsUiPanel,'Visible','on');
% positionF(3) = positionF(3) + positionP(3);
else
set(handles.OptionsUiPanel,'Visible','off');
% positionF(3) = positionF(3) - positionP(3);
end
% set(gcf,'Position',positionF); % untested
guidata(gcbo,handles)
function Duration_Callback(hObject, eventdata, handles)
% hObject handle to Duration (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 Duration as text
% str2double(get(hObject,'String')) returns contents of Duration as a double
function SmoothFactor_Callback(hObject, eventdata, handles)
% hObject handle to SmoothFactor (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 SmoothFactor as text
% str2double(get(hObject,'String')) returns contents of SmoothFactor as a double
% --- Executes during object creation, after setting all properties.
function SmoothFactor_CreateFcn(hObject, eventdata, handles)
% hObject handle to SmoothFactor (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function channel_Callback(hObject, eventdata, handles)
% hObject handle to channel (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 channel as text
% str2double(get(hObject,'String')) returns contents of channel as a double
% --- Executes during object creation, after setting all properties.
function channel_CreateFcn(hObject, eventdata, handles)
% hObject handle to channel (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
|
BottjerLab/Acoustic_Similarity-master
|
classify_spectra.m
|
.m
|
Acoustic_Similarity-master/code/chronux/wave_browser/classify_spectra.m
| 108,297 |
utf_8
|
93fe2f22d145ba63cb667b18b3b33d0d
|
function varargout = classify_spectra(varargin)
% CLASSIFY_SPECTRA M-file for classify_spectra.fig
% CLASSIFY_SPECTRA, by itself, creates a new CLASSIFY_SPECTRA or raises the existing
% singleton*.
%
% H = CLASSIFY_SPECTRA returns the handle to a new CLASSIFY_SPECTRA or
% the handle to
% the existing singleton*.
%
% CLASSIFY_SPECTRA('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CLASSIFY_SPECTRA.M with the given input arguments.
%
% CLASSIFY_SPECTRA('Property','Value',...) creates a new CLASSIFY_SPECTRA or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before classify_spectra_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to classify_spectra_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help classify_spectra
% Last Modified by GUIDE v2.5 26-Jun-2006 23:19:22
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @classify_spectra_OpeningFcn, ...
'gui_OutputFcn', @classify_spectra_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(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 classify_spectra is made visible.
function classify_spectra_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 classify_spectra (see VARARGIN)
% Choose default command line output for classify_spectra
handles.output = hObject;
% Set defaults
handles.recompute = logical(1); % Whether to recompute a spectra
handles.cwavfile = ''; % The current wave file
handles.directory = pwd;
handles.Fs = 44100; % Frequency of audio sampling per second
handles.movingwin=[0.01 0.002]; % Size of the moving window in seconds; the first number is the window size and the second is the step size
handles.tapers=[3 5];
handles.pad=1;
handles.fpass=[0 20000]; % Range of frequency sampling
handles.nsegments = 0; % total number of segments
handles.NextIndex = 1; % the index for segments
handles.maxseglength = 0; % set in seconds
% ClassifyAxes handles
handles.classified_height = 560 ; % the height of the image in the classified axes
handles.classified_width = 450; % the width of the image in the classified axes
%
handles.plotmode = 'spectra'; % The main spectra plot mode can also be
% see plot modes
handles.plotmodes = {'spectra' 'waveform' 'spectra_dt' 'spectra_df' };
handles.plotmodevalue = 1;
% set up a density measurement which will allow scaling
classaxpos = get(handles.ClassifiedAxes,'Position');
handles.classified_height_density = handles.classified_height / classaxpos(4);
handles.classified_width_density = handles.classified_width / classaxpos(3);
handles.ispecheight = 100; % fixed height of the iconized spectogram
handles.ismaxwidth = SmallAxes_width(handles);
handles.specpad = 0.02; % pad in image sizes
handles.xspacer = 5; % fixed space between the images in the horizontal direction
handles.yspacer = 10; % fixed space between the row of the images
handles.xpsacer_density = handles.xspacer / classaxpos(3);
handles.ypsacer_density = handles.yspacer / classaxpos(4);
handles.image_list = {}; % holds an array of the specicons
handles.positions = []; % holds the position of images on infinitely long canvas
handles.images_dim = []; % holds the size of the images
handles.mapindex = []; % holds the position number for the segment
handles.nimages = 0; % total number of images or spectra
handles.number_rows = floor(handles.classified_height/(handles.yspacer + handles.ispecheight)); % the number of rows allowed on a page
handles.cnrows = 0; % current number of rows
handles.startpage = 1; % an index for the first image on the page
handles.endpage = 1; % an index for the last image on the page
handles.startx = 1; % for the classified axes holds the start position for the image
handles.endx = handles.classified_width; % for the classified axes holds the end position for the image
handles.mode = 'browse'; % A string representing the current major mode which is either
% 'browse','classify','class-view','class-members'
handles.submode = 'select'; %A string representing the minor mode which is either
% 'select','select-class','remove-class', 'compare',
% 'typify'
handles.quickmode = logical(0); % Quick mode allows quick classification with minimum
% work for the user. By default this is set
% off
handles.lastsegment = 1; % The last segment classified
handles.sortclass = 'length'; % Tells how classes are to be ordered in the ClassifiedAxes
% 'original' is the order the classes were created or loaded from
% 'popularity' sort the classes with most popular first
% 'length' sort the classes by longest
% class first
set(handles.SortPopupMenu,'Value',3);
handles.lastclass = 0;
handles.lowerfreq = 0; % Lower frequency for zooming
handles.upperfreq = 7500; % Upper frequency for zooming
handles.rezoom = logical(1);
handles.IconListf = {};
handles.baseclassname = 'mockingbird'; % This string should be set by the user
% used as the base class name
handles.nclasses = 0; % total number of syllable classes
handles.classes = []; % structure for holding class information
handles.current_class = 0; % used by compare to go through classes
handles.configschanged = logical(0); % indicates whether the configs for spectra has changed
handles.precomputed = logical(0);
handles.configfile = 'class_spec.conf';
handles.originalsize = [0 0 170 44]; % original position of the form
handles.originalaxessize = [80.5 6.375 86.167 34.438];
handles.blank = logical(1); % indicate that the ClassifiedAxes is blank
handles.prevsize = handles.originalsize;
handles.fixed = logical(1); % Whether to use fixed scaling when resizing the form
% initially set to true so not to call the repositioning algorithm when the
% form is blank
handles.nfeatures = 10;
handles.ncepestral = 10; % Number of cepestral coefficients to include
set(gcf, 'ResizeFcn', {@ResizeFcn});
%classify_spectra('ResizeFcn',gcbo,[],guidata(gcbo))
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes classify_spectra wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = classify_spectra_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;
function DirectoryEditBox_Callback(hObject, eventdata, handles)
handles.directory = get(hObject,'String');
function DirectoryEditBox_CreateFcn(hObject, eventdata, handles)
set(hObject,'string',pwd);
guidata(gcbo,handles);
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for loading segments %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function segments=LoadSegmentsFromDirectory(directory)
segfilelist = dir( [directory '\*' '.seg.txt'] );
%segfilelist;
nsegfile = length(segfilelist);
segments = [];
n = 1;
while n <= nsegfile
segfilename = segfilelist(n).name;
fid=fopen( segfilename, 'rt' );
if fid ~= -1 % if there is a seg file
scanned=fscanf( fid, '%g %g',[2 inf] );
fclose(fid);
%fprintf( 'File %d of %d has %d segments: %s\n', n, nsegfile, size(scanned,2),segfilename );
wavfile = segfilename(1:(length(segfilename)-8)); % can this be made more general
i = 1;
while i <= size(scanned, 2) % Load the start and stop of segments
segment.wavfile = wavfile;
segment.class = ''; % Loaded segments start out unclassified
segment.features = [];
segment.start = scanned(1,i);
segment.end = scanned(2,i);
segment.specfilename = [segment.wavfile '.' num2str(segment.start) '-' num2str(segment.end) '.spec'];
segments = [ segments segment];
i = i + 1;
end
end
n = n + 1;
end
function handles=Load_InitialSegments(hObject,handles)
%handles.directory = pwd;
handles.segments = LoadSegmentsFromDirectory(handles.directory);
handles.nsegments = length(handles.segments);
guidata(hObject, handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for handling syllable classes %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = cindex2imagelist(handles)
% Takes a cindex and generates a a list of images
handles.image_list = {};
%load('-mat','specicons');
for i = 1:length(handles.mapindex)
handles.image_list{i} = handles.classes( handles.mapindex(i) ).iconS;
end
function mapindex = sortindexbypop(handles)
% Takes a cindex and sorts by the class popularity
nindexes = length(handles.mapindex);
mapindex = [];
for i = 1:nindexes
mapindex(i,1:2) = [handles.mapindex(i) handles.classes(handles.mapindex(i)).nmembers];
end
mapindex = sortrows(mapindex, 2);
mapindex = flipud(mapindex(:,1));
function mapindex = sortindexbylength(handles)
% Takes a cindex and sorts by the class popularity
nindexes = length(handles.mapindex);
mapindex = [];
for i = 1:nindexes
mapindex(i,1:2) = [handles.mapindex(i) handles.classes(handles.mapindex(i)).length];
end
mapindex = sortrows(mapindex, 2);
mapindex = flipud(mapindex(:,1));
function class_string = newclassname(handles)
% Generates a new name for the class string using the baseclassname
% variable. Classes are numbered sequentially from the class with the largest number.
nbaseclass = length(handles.baseclassname);
classnum = 0;
for i = 1:handles.nclasses % make sure the largest class number is gotten
classname = handles.classes(i).name;
curr_classnum = str2num(classname(nbaseclass + 1:length(classname)));
if curr_classnum > classnum
classnum = curr_classnum;
end
end
class_string = strcat(handles.baseclassname,num2str(classnum + 1));
;
function cindex = returnclassindex(handles,classname)
% Return the index to the class
cindex = 0;
i = 1;
while (i <= handles.nclasses) && not(strcmp(classname,handles.classes(i).name))
i = i + 1;
end
cindex = i;
;
function handles = add_new_class(handles,segment)
% Segment is the class that will be used to typify the class
handles.nclasses = length(handles.classes);
class.name = newclassname(handles);
class.nmembers = 1; % the number of segments which are members of this class
class.specfilename = segment.specfilename; % specfilename will be used as a unique identifier
class.index = handles.NextIndex;
%load('-mat',class.specfilename);
class.iconS = handles.IconList{handles.NextIndex}; % this is the icon which typifies the class
class.length = segment.end - segment.start; % used to hold the lengt of the length
handles.classes = [handles.classes class];
handles.nclasses = handles.nclasses + 1;
%guidata(gcbo,handles);
;
function handles=ConfigureClassSegment(handles)
% Handles the gui configuration of the class information when navigating
segment = handles.segments(handles.NextIndex);
if strcmp(segment.class,'') % Unclassified segment
set(handles.ClassifyButton,'String','Classify');
set(handles.ClassifyButton,'Enable','on');
else % Classified segment
set(handles.ClassifyButton,'String','Declassify');
set(handles.ClassifyButton,'Enable','on');
end
%guidata(gcbo,handles);
function handles = blankaxes(handles)
set(handles.NextRowButton,'Enable','off');
set(handles.PreviousRowButton,'Enable','off');
axes(handles.ClassifiedAxes);
handles.hiclass = image(uint8(zeros(handles.classified_height,handles.classified_width)));
set(handles.ClassifiedAxes,'Xtick',[]);
set(handles.ClassifiedAxes,'Ytick',[]);
handles.blank = logical(1);
% --- Executes on button press in ClassifyButton.
function ClassifyButton_Callback(hObject, eventdata, handles)
% hObject handle to ClassifyButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
status = get(handles.ClassifyButton,'String');
set(handles.TypifyClassButton,'Visible', 'off');
set(handles.RemoveClassButton, 'Visible', 'off');
set(handles.NextClassButton,'Visible','off');
% set(handles.CompareToggleButton,'Visible','off');
set(handles.RenameClassButton,'Visible','off');
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
if strcmp(status,'Classify')
set_status(handles,'');
set(handles.ModePopupMenu,'Enable','off');
set(handles.NextSpectraButton,'Enable','off');
set(handles.PreviousSpectraButton,'Enable','off');
set(handles.ClassifyButton,'Enable','off');
set(handles.CompareToggleButton,'Enable','off');
set(handles.QuickModeButton,'Enable','off');
set(handles.AutoClassifyButton,'Enable','off');
set(handles.NewClassButton,'Visible','on');
if handles.nclasses > 0 % Make sure there is at least one class
if strcmp(handles.mode,'comparison') % if you are in comparison mode
set(handles.NewClassButton,'Visible','off');
handles.segments(handles.NextIndex).class = handles.classes(handles.lastclass).name;
set(handles.ModePopupMenu,'Enable','on');
set(handles.ClassifyButton,'String','Declassify');
set(handles.ClassifyButton,'Enable','on');
set(handles.CompareToggleButton,'value',0);
set(handles.CompareToggleButton,'Enable','on');
handles = configureclassview(handles,'select-class');
set_status(handles, ['Viewing all ', num2str(handles.nclasses),' classes']);
set(handles.RemoveClassButton,'Enable','on');
set(handles.RemoveClassButton,'Visible','on');
set(handles.QuickModeButton,'Enable','on');
set(handles.AutoClassifyButton,'Enable','on');
setnavigationbuttons(handles);
else % regular mode
set(handles.SortText,'Visible','on');
set(handles.SortPopupMenu,'Visible','on');
handles = configureclassview(handles,'select-class');
set_status(handles, ['Select a class']);
end
else % draw a blank image
handles = blankaxes(handles);
handles.mode = 'class-view';
handles.submode = 'select-class';
set(handles.hiclass,'ButtonDownFcn',{@DummyClassifyAxesClickCallBack,handles});
end
% configure the remaining gui
handles = SetModePopupMenu(handles,'class view');
elseif strcmp(status,'Declassify')
cindex = returnclassindex(handles,handles.segments(handles.NextIndex).class);
if handles.classes(cindex).nmembers == 1 % Only one member left of that class
if length(handles.classes) == 1 % Only one class remaining
axes(handles.ClassifiedAxes);
handles.classes = [];
handles.nclasses = 0;
handles = blankaxes(handles);
else % remove the class
handles.classes = [handles.classes(1:cindex-1) handles.classes(cindex + 1:length(handles.classes))];
handles.nclasses = handles.nclasses - 1;
end
else
if strcmp(handles.classes(cindex).specfilename,handles.segments(handles.NextIndex).specfilename)
i = 1; %Test if the class you are removing the type class
segs = [ handles.segments(1:(handles.NextIndex - 1)) handles.segments((handles.NextIndex + 1) : handles.nclasses)];
while (i <= length(segs)) && strcmp(segs(i).class,handles.classes(cindex).name)
i = i + 1;
end
handles.classes(cindex).specfilename = handles.segments(i).specfilename;
handles.classes(cindex).length = handles.segments(i).end - handles.segments(i).start;
handles.iconS = handles.IconList{i};
end
handles.classes(cindex).nmembers = handles.classes(cindex).nmembers - 1;
end
handles.segments(handles.NextIndex).class = ''; % Remove class information
if handles.nclasses >= 1 % Redraw axes
if strcmp(handles.mode,'class-view')
handles = configureclassview(handles,'select');
set_status(handles,['Viewing all ' num2str(handles.nclasses) ' classes']);
elseif strcmp(handles.mode,'class-members')
handles = configureclassmembers(handles,handles.classes(cindex).name);
set_status(handles,['Viewing ' num2str(handles.classes(cindex).nmembers) ' members of ' num2str(handles.classes(cindex).name)]);
elseif strcmp(handles.mode,'browse')
; % do nothing
end
end
set(handles.ClassifyButton,'String','Classify');
setnavigationbuttons(handles);
end
guidata(gcbo,handles);
% --- Executes on button press in NewClassButton.
function NewClassButton_Callback(hObject, eventdata, handles)
% hObject handle to NewClassButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
handles = add_new_class(handles,handles.segments(handles.NextIndex));
handles.segments(handles.NextIndex).class = handles.classes(handles.nclasses).name;
set(handles.SortText,'Visible','off');
set(handles.SortPopupMenu,'Visible','off');
set(handles.ClassifyButton,'Enable','on');
set(handles.ClassifyButton,'String','Declassify');
set(handles.NewClassButton,'Visible','off');
set(handles.ModePopupMenu,'Enable','on');
set(handles.NextSpectraButton,'Enable','on');
set(handles.CompareToggleButton,'Enable','on');
set(handles.QuickModeButton,'Enable','on');
set(handles.AutoClassifyButton,'Enable','on');
set(handles.PreviousSpectraButton,'Enable','on');
handles = configureclassview(handles,'xxx');
setnavigationbuttons(handles);
set_status(handles,'');
handles = SetModePopupMenu(handles,'class view');
guidata(gcbo,handles);
;
% --- Executes on button press in RemoveClassButton.
function RemoveClassButton_Callback(hObject, eventdata, handles)
% hObject handle to RemoveClassButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%set(handles.TypifyClassButton,'Enable','on');
set(handles.RemoveClassButton,'Enable','off');
handles.mode = 'class-view';
handles.submode = 'remove-class';
set_status(handles,'Select a class to remove');
guidata(gcbo,handles);
% --- Executes on button press in TypifyClassButton.
function TypifyClassButton_Callback(hObject, eventdata, handles)
% hObject handle to TypifyClassButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.TypifyClassButton,'Enable','off');
%set(handles.RemoveClassButton,'Enable','on');
handles.mode = 'class-members';
handles.submode = 'typify';
set_status(handles,'Select an icon to change the type');
guidata(gcbo,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for computing the spectra %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function segment=precompute_spectra(handles, segment)
% This function will do the precomputing of the spectragram
spec_ipad = round(handles.specpad * handles.Fs);
spec_istart = round(segment.start * handles.Fs);
spec_iend = round(segment.end * handles.Fs);
% This is to catch an over and under run errors in the wav file because of the padding
try
[data] = wavread(segment.wavfile, [spec_istart - spec_ipad, spec_iend + spec_ipad]);
catch
errmsg = lasterr;
if strfind(errmsg, 'Sample limits out of range')
if (segment.start - handles.specpad) < 0 % Make sure the starting point is not negative
[data] = wavread(segment.wavfile, [1 spec_iend + spec_ipad]);
else % over run of the buffer
[data] = wavread(segment.wavfile);
[data] = data((spec_istart - spec_ipad):length(data));
end
end
end
[Sfull tfull f] = compute_spectra(data,handles.tapers,handles.Fs,handles.fpass,handles.movingwin); % precompute the portion
wavlength = length(data);
Ssize = size(Sfull);
Slength = Ssize(2);
RatioWS = Slength / (wavlength / handles.Fs); % this allows us to index by time through spec file
Sstart = round(RatioWS * segment.start);
Send = round(RatioWS * segment.end);
Spad = round(RatioWS * handles.specpad);
Spre = Sfull(:,1:Spad);
S = Sfull(:,Spad+1:Spad + Send-Sstart);
Spost = Sfull(:,Spad + (Send-Sstart)+1:Slength);
t=[segment.start, segment.end];
iconS = iconify_spec(S,handles.ispecheight);
save(segment.specfilename,'S','t','f','Spre','Spost','RatioWS','tfull','iconS','-mat');
fprintf('Saving %s file\n',segment.specfilename);
function handles = precompute_AllSpectra(handles)
% This function precomputes all the spectra in a directory
hw = waitbar(0,'Precomputing spectra. . .');
if handles.nsegments >= 1
for i = 1:handles.nsegments
precompute_spectra(handles,handles.segments(i));
waitbar(i/handles.nsegments);
end
end
close(hw);
handles.IconList = get_SpecIcons(handles);
;
function [S t f]=compute_spectra(data,tapers,Fs,fpass,movingwin)
data = data / std(data); % normalize the variance of the spectra
params.tapers=tapers; params.Fs=Fs; params.fpass=fpass;
[S t f] = mtspecgramc( diff(data), movingwin, params );
S = log(S)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for plotting the spectragram %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles=get_and_plot(handles, segment)
load('-mat',segment.specfilename);
axes(handles.ToClassifyAxes);
% RatioWS
cmap = jet(256);
if strcmp(handles.plotmode,'spectra')
SFull = cat(2,Spre,S,Spost);
elseif strcmp(handles.plotmode,'spectra_dt') || strcmp(handles.plotmode,'spectra_df') || strcmp(handles.plotmode,'waveform')
wav_ipad = round(handles.specpad * handles.Fs);
wav_istart = round(segment.start * handles.Fs);
wav_iend = round(segment.end * handles.Fs);
% This is to catch an over and under run errors in the wav file because of the padding
try
[data] = wavread(segment.wavfile, [wav_istart - wav_ipad, wav_iend + wav_ipad]);
catch
errmsg = lasterr;
if strfind(errmsg, 'Sample limits out of range')
if (segment.start - handles.specpad) < 0 % Make sure the starting point is not negative
[data] = wavread(segment.wavfile, [1 wav_iend + wav_ipad]);
else % over run of the buffer
[data] = wavread(segment.wavfile);
[data] = data((wav_istart - wav_ipad):length(data));
end
end
end
data = data / std(data);
params.Fs=handles.Fs;
params.tapers = handles.tapers;
params.fpass=handles.fpass;
params.pad = 1;
if strcmp(handles.plotmode,'spectra_dt')
cmap = gray(256);
[SFull t f]= mtdspecgramc(diff(data),handles.movingwin,0,params); SFull=SFull';
elseif strcmp(handles.plotmode,'spectra_df')
cmap = gray(256);
[SFull t f]= mtdspecgramc(diff(data),handles.movingwin,pi/2,params); SFull=SFull';
end
end
if strcmp(handles.plotmode,'spectra') || strcmp(handles.plotmode,'spectra_dt') || strcmp(handles.plotmode,'spectra_df')
cmap(1,:) = [1, 1, 1];
colormap(cmap);
SFmin = min(min(SFull));
SFmax = max(max(SFull));
SFull = uint8(1 + round(255 * (SFull-SFmin) / (SFmax-SFmin)));
hi = image(tfull + segment.start - handles.specpad,f,SFull);
set(hi,'ButtonDownFcn',{@PlotModeCallBack});
axis xy;
hline1 = line([segment.start segment.start],[f(1) max(f)],'Color',[0 0 0],'LineWidth',3);
hline2 = line([segment.end segment.end],[f(1),max(f)],'Color',[0 0 0],'LineWidth',3);
else
% xlim([tfull(1) tfull(length(tfull))] + segment.start - handles.specpad);
hp = plot(segment.start - handles.specpad + [0:length(data)-1] / handles.Fs, data);
set(handles.ToClassifyAxes,'YLim',[-5 5]);
set(hp,'ButtonDownFcn',{@PlotModeCallBack});
axis tight;
dataspan = [min(data) max(data)];
hline1 = line([segment.start segment.start],dataspan,'Color',[0 0 0],'LineWidth',3);
hline2 = line([segment.end segment.end],dataspan,'Color',[0 0 0],'LineWidth',3);
end
axes(handles.ToClassifySmallAxes);
ispecFull = uint8(zeros(handles.ispecheight,handles.ismaxwidth));
ispecFull = copy_into(ispecFull,handles.IconList{handles.NextIndex},1,1);
if length(ispecFull(1,:)) > handles.ismaxwidth
ispecFull = ispecFull(:,1:handles.ismaxwidth);
end
if strcmp(get(handles.ZoomButton,'String'),'Zoom out')
f = [handles.lowerfreq handles.upperfreq];
end
tsmall = [handles.movingwin(1),handles.ismaxwidth * handles.movingwin(2) - handles.movingwin(1)];
%
% cmap = jet(256);
% cmap(1,:) = [1, 1, 1];
%
% colormap(cmap);
% [0 (handles.ismaxwidth * (segment.end - segment.start))/length(iconS(1,:))]
ih = image(tsmall,f,flipud(ispecFull));
axis xy;
;
function PlotModeCallBack(src,eventdata)
% A Function for handling clicks to the axes
handles = guidata(gcbo);
handles.plotmodevalue = handles.plotmodevalue + 1;
if handles.plotmodevalue > length(handles.plotmodes)
handles.plotmodevalue = 1;
end
handles.plotmode = handles.plotmodes{handles.plotmodevalue};
handles=get_and_plot(handles, handles.segments(handles.NextIndex));
guidata(gcf,handles);
function handles=ConfigureSpecPlot(handles)
% Handles the gui configuration of the plotting
segment = handles.segments(handles.NextIndex);
if not(exist(segment.specfilename)) || handles.recompute
precompute_spectra(handles,segment);
end
set(handles.ToClassifyPanel,'Title',['Segment ' num2str(handles.NextIndex) '/' num2str(handles.nsegments)])
segmentstatus = ['File: "' segment.wavfile '"; Segment length ' num2str(segment.end - segment.start,3)];
set(handles.SegmentText,'String',segmentstatus);
handles = get_and_plot(handles, segment);
guidata(gcbo,handles);
;
function NextSpectraButton_Callback(hObject, eventdata, handles)
% Moves the segment viewer forward one segment
handles.NextIndex = handles.NextIndex + 1;
if handles.NextIndex == handles.nsegments
set(handles.NextSpectraButton,'Enable','off');
end
if handles.NextIndex > 1
set(handles.PreviousSpectraButton,'Enable','on');
end
handles=ConfigureClassSegment(handles);
handles=ConfigureSpecPlot(handles);
guidata(gcbo,handles);
;
function PreviousSpectraButton_Callback(hObject, eventdata, handles)
% Moves the segment viewer backwards one segment
handles.NextIndex = handles.NextIndex - 1;
if handles.NextIndex == 1
set(handles.PreviousSpectraButton,'Enable','off');
set(handles.NextSpectraButton,'Enable','on');
end
if handles.NextIndex < handles.nsegments
set(handles.NextSpectraButton,'Enable','on');
end
handles=ConfigureClassSegment(handles);
handles=ConfigureSpecPlot(handles);
set(handles.NextSpectraButton,'Enable','off');
set(handles.NextSpectraButton,'Enable','on');
guidata(gcbo,handles);
;
function PrecomputeButton_Callback(hObject, eventdata, handles)
% Call back for the precompute button. This acts to load the file from the directory
handles.directory = get(handles.DirectoryEditBox,'String');
% fprintf('creating syllable list\n');
%handles.segments = segments;
handles.classes = [];
set(handles.PrecomputeButton, 'Enable', 'off' );
handles.NextIndex = 1;
handles = Load_InitialSegments(hObject,handles);
handles.recompute = logical(0);
if handles.nsegments >= 1
handles=ConfigureClassSegment(handles);
handles = load_configuration(handles,handles.configfile);
if exist([handles.baseclassname '.dat']) && not(handles.configschanged)
load('-mat','specicons');
handles.IconList = IconList;
data = read_syllable_database(handles);
handles = merge_syllable_database(handles,data);
else
handles = precompute_AllSpectra(handles);
end
%set(handles.ConfigureButton, 'Enable','off');
handles=ConfigureSpecPlot(handles);
handles=BrowseDirectory(handles);
handles.precomputed = logical(1);
set(handles.PlaySegmentButton, 'Enable', 'on' );
set(handles.NextSpectraButton, 'Enable', 'on' );
set(handles.ModePopupMenu,'Enable','on');
set(handles.SaveButton,'Enable','on');
set(handles.SaveItem,'Enable','on');
set(handles.PrecomputeButton, 'Enable', 'off' );
set(handles.CleanDirectoryItem, 'Enable', 'off' );
set(handles.LoadDirectoryButton,'Enable','off');
set(handles.LoadItem,'Enable','off');
set(handles.ZoomButton,'Enable','on');
set(handles.QuickModeButton,'Enable','on');
set(handles.CompareToggleButton,'Enable','on');
set(handles.ConfigureButton,'Enable','on');
set(handles.ConfigureItem,'Enable','on');
set(handles.AutoClassifyButton,'Enable','on');
handles.fixed = logical(0); % turn off fixed scaling
if not(strcmp(handles.segments(handles.NextIndex).class,'')) % Set the classification status
set(handles.ClassifyButton,'String','Declassify');
end
else
set(handles.PrecomputeButton, 'Enable', 'on' );
end
guidata(gcbo,handles);
;
% --- Executes on button press in PlaySegmentButton.
function PlaySegmentButton_Callback(hObject, eventdata, handles)
% Plays the current segment in the segment viewer
% hObject handle to PlaySegmentButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
segment = handles.segments(handles.NextIndex);
data = wavread(segment.wavfile,[round(handles.Fs * segment.start),round(handles.Fs * segment.end)]);
wavplay(data,handles.Fs,'async');
function CurrentFilenameEdit_Callback(hObject, eventdata, handles)
function CurrentFilenameEdit_CreateFcn(hObject, eventdata, handles)
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for viewing spectra icon %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function newwidth = SmallAxes_width(handles)
position1 = get(handles.ToClassifySmallAxes,'Position');
position2 = get(handles.ClassifiedAxes,'Position');
newwidth = round(position1(3) *(handles.classified_width / position2(3)));
function iconS = iconify_spec(S,height)
% Take a large spectra with high frequency bandwidth and reduce the height
% by pixel averaging
Ssize = size(S);
iconS = zeros(height,Ssize(2));
% averaging of values to reduce size
rf = floor(Ssize(1)/height);
for i = 1:(height-1)
for j = 1 : Ssize(2)
iconS(i,j) = sum(S(((i-1)*rf)+1:i*rf,j))/rf;
end
end
for j = 1 : Ssize(2) % take care of the last row by also pixel averaging
iconS(height,j) = mean(S(rf*(height-1) : Ssize(1),j));
end
iconS = flipud(iconS);
% Rescaling of values
maxintense = max(max(iconS));
minintense = min(min(iconS));
iconS=uint8(1 + round(255 * (iconS-minintense)/(maxintense-minintense)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for loading in images %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function destination = copy_into(destination,source,r,c)
% This copies an image into another image
% Two problems: one it can be optimized by removing the nested for loops
% two there is an indexing bug which returns a one pixel larger image
sized = size(destination);
sizes = size(source);
destination(r:r+sizes(1)-1,c:c+sizes(2)-1) = source(:,:);
% for i = 1:sizes(1)
% for j = 1:sizes(2)
% destination(r+i,c+j) = source(i,j);
% end
% end
% ;
function positions = position_images(height,width,images_dim,xspacer,yspacer)
% This function returns a matrix consisting of two rows with the xy
% position for images.
% The function also assumes that the image's height is not restricted this
% allows for easier scrolling
% The function assumes that all images are of the same height
% height in pixels of the original
% width in pixels of the original
% images
% xspacer in pixels for the horizontal space between images
% yspacer is the next height of the image
% image height is the fixed height of the images
number_images = length(images_dim(:,1));
imageheight = images_dim(1);
currentx = xspacer;
currenty = yspacer;
positions = zeros(number_images,2);
for i = 1:number_images
if (currentx + images_dim(i,2) + xspacer) > width % start a new row
currentx = xspacer;
currenty = currenty + imageheight + yspacer;
positions(i,:) = [currenty currentx];
currentx = currentx + images_dim(i,2) + xspacer;
else
positions(i,:) = [currenty currentx];
currentx = currentx + images_dim(i,2) + xspacer;
end
%positions(i,:) = [currenty currentx];
end
% function image_matrix = place_images_into(image_matrix, image_list, position_list)
% % Place images into a matrix
% number_images = length(image_list);
%
% for i = 1:number_images
% theimage = image_list{i};
% image_matrix = copy_into(image_matrix, theimage, position_list(i,1), position_list(i,2));
% end
% ;
function image_dim = get_image_sizes(images)
% Returns an array of image sizes
number_images = length(images);
image_dim = zeros(number_images,2);
for i = 1:number_images
image_dim(i,:) = size(images{i});
end
;
function image_matrix = place_images_into(image_matrix, image_list, position_list)
% Place images into a matrix
number_images = length(image_list);
for i = 1:number_images
theimage = image_list{i};
image_matrix = copy_into(image_matrix, theimage, position_list(i,1), position_list(i,2));
end
;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for manipulating and plotting spectra icons %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function IconList=get_SpecIcons(handles)
IconList = {};
status = 0;
for i = 1:handles.nsegments
load('-mat',handles.segments(i).specfilename);
IconList{i} = iconS;
end
save('specicons','IconList','-mat'); % temp code for saving
function handles = plot_classified_axes(handles, image_list, position_list)
% Low level drawing of the classified axes
handles.blank = logical(0);
handles.classmatrix = uint8(zeros(handles.classified_height,handles.classified_width));
axes(handles.ClassifiedAxes);
handles.classmatrix = place_images_into(handles.classmatrix,image_list,position_list);
set(handles.ClassifiedAxes,'XTick',[]);
set(handles.ClassifiedAxes,'YTick',[]);
handles.max_width = length(handles.classmatrix(1,:));
if handles.max_width > handles.classified_width
set(handles.SliderClassified,'Min',0);
set(handles.SliderClassified,'Max',handles.max_width - handles.classified_width);
set(handles.SliderClassified,'enable','on');
handles.endx = handles.classified_width;
else
set(handles.SliderClassified,'enable','off')
handles.startx = 1;
handles.endx = handles.classified_width;
end
classview = handles.classmatrix(:,handles.startx:handles.endx); % will cut overhang
handles.hiclass = image(classview);
set(handles.hiclass,'ButtonDownFcn',{@ClassifyAxesClickCallBack});
set(handles.ClassifiedAxes,'XTick',[]);
set(handles.ClassifiedAxes,'YTick',[]);
setrowbuttons(handles);
function handles = reposition_images(handles, image_list)
% this is a lower level function which is called to reposition the images.
% this would be called from higher level functions when images are added,
% deleted, or a new list of images needs to be loaded.
% initialize the handles for the images
handles.nimages = length(image_list);
handles.images_dim = get_image_sizes(image_list);
handles.positions = position_images(handles.classified_height,handles.classified_width,handles.images_dim,handles.xspacer,handles.yspacer);
handles.cnrows = length(unique(handles.positions(:,1)));
% Setup the first page view
handles.number_rows = floor(handles.classified_height / (handles.ispecheight + handles.yspacer));
handles.startpage = 1;
handles.endpage = 0;
for i = 1 : handles.number_rows
handles.endpage = next_row_end(handles.positions,handles.endpage);
end
%guidata(gcbo,handles);
;
function nrow = which_row(positions,index)
nrow = 1;
i = 2;
while i <= index
if not(positions(i,1) == positions(i-1,1))
nrow = nrow + 1;
end
i = i + 1;
end
function cpositions = get_curr_position(handles)
% Setups the current view of the positions
cpositions = handles.positions(handles.startpage:handles.endpage,:); % get the current view
cpositions(:,1) = cpositions(:,1) - cpositions(1,1) + handles.yspacer;
cpositions(:,2) = cpositions(:,2) - (handles.startx - 1);
;
function cposition = next_row_start(positions,cposition)
% Computes the position of the next row if the row based on the positions matrix
% it computes the position where the row starts
npos = length(positions);
i = cposition;
while (i <= npos) && positions(i,1) == positions(cposition,1)
i = i + 1;
end
if i < npos % make sure the row numbers match
cposition = i;
end
;
function cposition = next_row_end(positions,cposition)
% Computes the position of the next row if the row based on the positions matrix
% it computes the last position before a new row starts
npos = length(positions(:,1));
if cposition < npos % not at the last row
i = cposition + 1;
while (i < npos) && (positions(i,1) == positions(cposition+1,1))
i = i + 1;
end
if (positions(cposition + 1) == positions(npos))
cposition = npos; % handle the condition that you are now at the last row
else
cposition = i - 1; % make sure the row numbers match
end
else % handles the condition you are already at the last row
cposition = npos;
end
;
function handles = row_forward(handles)
% Moves the row forward in the classifiedaxes/browser view
startpage = next_row_start(handles.positions,handles.startpage);
endpage = next_row_end(handles.positions,handles.endpage);
if not(endpage == handles.endpage) % indicates you are not at the last page
handles.startpage = startpage;
handles.endpage = endpage;
end
% guidata(gcbo,handles);
;
function cposition = previous_row_start(positions,cposition)
% Computes the position of the previous row if the row based on the positions matrix
% it computes the position where the row starts
npos = length(positions(:,1));
if cposition > 1
i = cposition - 1;
while (i > 1) && (positions(i,1) == positions(cposition-1,1))
i = i - 1;
end
if (i > 1) && (cposition ~= 2)
cposition = i + 1;
else
cposition = 1;
end
else
cposition = 1; % in case things get missed up and neg index
end
;
function cposition = previous_row_end(positions,cposition)
npos = length(positions(:,1));
if cposition > 1
i = cposition;
while (i > 1) && (positions(i,1) == positions(cposition,1))
i = i - 1;
end
if i > 1;
cposition = i;
else
cposition = 1;
end
else
cposition = 1;
end
;
function nrows = number_of_rows(handles)
% Computes the number of rows in the current view
nrows = length(unique(handles.positions(handles.startpage:handles.endpage,1)));
function handles = row_backward(handles)
% Moves the row backwards in the classifiedaxes/browser view
startpage = previous_row_start(handles.positions,handles.startpage);
endpage = previous_row_end(handles.positions,handles.endpage);
if number_of_rows(handles) < handles.number_rows % indicates you are not at the last page
handles.startpage = startpage;
handles.endpage = length(handles.positions(:,1));
elseif handles.startpage == 1;
handles.startpage = 1;
handles.endpage = handles.endpage;
else
handles.startpage = startpage;
handles.endpage = endpage;
end
% guidata(gcbo,handles);
;
function handles = BrowseDirectory(handles)
% This function should be called only after precompute has been called
% it relies on their being a specicon file in the directory
%
% The function takes the current segments in the directory and loads their specicons
% into memory because the segments and icons are created in their order the
% order matches. This will need to be worked out better for the
% classification algorithms.
%load('-mat', 'specicons');
set_status(handles, ['Viewing all ', num2str(handles.nsegments),' segments']);
handles.mapindex = [1:handles.nsegments];
handles.image_list = handles.IconList;
handles = reposition_images(handles, handles.image_list);
handles.cpositions = get_curr_position(handles);
handles = plot_classified_axes(handles, handles.image_list(handles.startpage:handles.endpage), handles.cpositions);
handles.mode='browse';
%guidata(gcbo,handles);
% --- Executes on button press in NextRowButton.
function NextRowButton_Callback(hObject, eventdata, handles)
% hObject handle to NextRowButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if handles.cnrows > 1
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified, 'Value',0);
handles = row_forward(handles);
handles.cpositions = get_curr_position(handles);
handles = plot_classified_axes(handles, handles.image_list(handles.startpage:handles.endpage), handles.cpositions);
end
guidata(gcbo,handles);
% --- Executes on button press in PreviousRowButton.
function PreviousRowButton_Callback(hObject, eventdata, handles)
% hObject handle to PreviousRowButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if handles.cnrows > 1
handles.startx = 1;
handles.endx = handles.classified_width;
set(handles.SliderClassified, 'Value',0);
handles = row_backward(handles);
handles.cpositions = get_curr_position(handles);
handles = plot_classified_axes(handles, handles.image_list(handles.startpage:handles.endpage), handles.cpositions);
end
guidata(gcbo,handles);
% --- Executes on button press in LoadDirectoryButton.
function LoadDirectoryButton_Callback(hObject, eventdata, handles)
% hObject handle to LoadDirectoryButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%directoryname = uigetdir('./','Change directory');
directoryname = uigetdir;
if not(directoryname == 0)
handles.directory = directoryname;
set(handles.DirectoryEditBox, 'String',directoryname);
cd(handles.directory); % this we will need to change
end
guidata(gcbo,handles);
;
function im_index = coordinate2index(handles,xpos,ypos)
% For the current images displayed tests if pointer position is in an image
% returns the index for that image based on a left to right ordering on
% that page
% First check if the coordinate is totally out of the range
if (xpos < 0) || (ypos < 0) || (ypos > handles.classified_height) || (xpos > handles.classified_width)
im_index = 0;
else
im_index = 0;
npos = length(handles.cpositions(:,1));
i = 1;
while (i <= npos) && (im_index < 1)
if (xpos >= handles.cpositions(i,2)) && (xpos <= (handles.cpositions(i,2) + handles.images_dim(handles.startpage + (i-1), 2)))
if (ypos >= handles.cpositions(i,1)) && (ypos <= (handles.cpositions(i,1) + handles.images_dim(handles.startpage + (i-1),1)))
im_index = i;
end
end
i = i+1;
end
end
;
function setnavigationbuttons(handles)
% Sets the navigation buttons based on where the pointer is
if not(handles.quickmode)
if handles.NextIndex == handles.nsegments
set(handles.PreviousSpectraButton,'Enable','off');
set(handles.NextSpectraButton,'Enable','off');
elseif handles.NextIndex == handles.nsegments
set(handles.NextSpectraButton,'Enable','off');
set(handles.PreviousSpectraButton,'Enable','on');
elseif handles.NextIndex == 1
set(handles.PreviousSpectraButton,'Enable','off');
set(handles.NextSpectraButton,'Enable','on');
elseif (handles.NextIndex > 1) && (handles.NextIndex < handles.nsegments)
set(handles.PreviousSpectraButton,'Enable','on');
set(handles.NextSpectraButton,'Enable','on');
end
end
function setrowbuttons(handles)
if handles.startpage == 1
set(handles.PreviousRowButton,'Enable','off');
elseif handles.startpage > 1
set(handles.PreviousRowButton,'Enable','on');
end
if handles.endpage == length(handles.positions) % You are the last row
set(handles.NextRowButton,'Enable','off');
elseif handles.cnrows <= handles.number_rows
set(handles.NextRowButton,'Enable','off');
elseif handles.endpage < length(handles.positions)
set(handles.NextRowButton,'Enable','on');
end
function DummyClassifyAxesClickCallBack(src,eventdata,handles)
% When the image is blank this allow you to select out of the class view
set(handles.ClassifyButton,'Enable','on');
set(handles.NewClassButton,'Visible','off');
set(handles.NextSpectraButton,'Enable','on');
set(handles.PreviousSpectraButton,'Enable','on');
set(handles.ModePopupMenu,'Enable','on');
set(handles.AutoClassifyButton,'Enable','on');
set(handles.QuickModeButton,'Enable','on');
set(handles.CompareToggleButton,'Enable','on');
handles.submode = 'select';
setnavigationbuttons(handles);
guidata(gcbo,handles);
function ClassifyAxesClickCallBack(src,eventdata)
% A Function for handling clicks to the axes
handles = guidata(gcbo);
% handles.mode
%handles.submode
%fprintf('\n');
pos = get(handles.ClassifiedAxes,'CurrentPoint');
cposition = coordinate2index(handles,pos(1,1),pos(1,2));
if handles.quickmode
if cposition == 0 % Selecting in the outside takes you out of classification mode
set_status(handles,'');
else % You have selected an icon
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
class = handles.classes(handles.mapindex(cposition + (handles.startpage - 1)));
handles.segments(handles.NextIndex).class = class.name;
handles.classes(handles.mapindex(cposition + (handles.startpage - 1))).nmembers = handles.classes(handles.mapindex(cposition + (handles.startpage - 1))).nmembers + 1;
handles = jump_to_unclassified(handles);
handles = configureclassview(handles,'select-class');
if handles.lastsegment == handles.NextIndex % no more unclassified segments
handles = quick_mode_exit(handles);
set(handles.QuickModeButton,'Value',0);
handles.quickmode = not(handles.quickmode);
end
end
else % quick classify mode is off
if strcmp(handles.mode,'browse') && (cposition > 0)
handles.NextIndex = handles.mapindex((cposition - 1) + handles.startpage);
handles=ConfigureClassSegment(handles);
handles=ConfigureSpecPlot(handles);
else
%fprintf('%i\n', coordinate2index(handles,pos(1,1),pos(1,2)));
%fprintf('%i, %i\n\n', pos(1,1),pos(1,2));
;
end
if strcmp('class-members',handles.mode) && strcmp('select',handles.submode) && (cposition > 0)
handles.NextIndex = handles.mapindex((cposition - 1) + handles.startpage);
handles=ConfigureClassSegment(handles);
handles=ConfigureSpecPlot(handles);
end
%Show all members of a specific class
if strcmp('class-view',handles.mode) && strcmp('select',handles.submode) && (cposition > 0)
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
% set(handles.CompareToggleButton,'Visible','off');
cindex = handles.mapindex(cposition + (handles.startpage - 1));
class = handles.classes(cindex);
handles.lastclass = cindex;
handles = configureclassmembers(handles,class.name);
handles.mode = 'class-members';
handles.submode = 'select';
handles = SetModePopupMenu(handles,'class members');
set(handles.TypifyClassButton,'Visible','on');
set(handles.RemoveClassButton,'Visible','off');
set(handles.NextClassButton,'Visible','on');
set(handles.RenameClassButton,'Visible','on');
set_status(handles, ['Viewing ' num2str(length(handles.mapindex)),' members of ' class.name]);
end
if strcmp('class-view',handles.mode) && strcmp('select-class',handles.submode)
if cposition == 0 % Selecting in the outside takes you out of classification mode
set(handles.ClassifyButton,'Enable','on');
set(handles.NewClassButton,'Visible','off');
set_status(handles, ['Viewing all ', num2str(handles.nclasses),' classes']);
else % You have selected an icon
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
class = handles.classes(handles.mapindex(cposition + (handles.startpage - 1)));
handles.segments(handles.NextIndex).class = class.name;
handles.classes(handles.mapindex(cposition + (handles.startpage - 1))).nmembers = handles.classes(handles.mapindex(cposition + (handles.startpage - 1))).nmembers + 1;
set(handles.ClassifyButton,'String','Declassify');
handles = SetModePopupMenu(handles,'class members');
handles = configureclassmembers(handles,class.name);
handles.mode = 'class-members';
handles.submode = 'select';
set_status(handles,['Classified segment as ' class.name]);
end
set(handles.CompareToggleButton,'Enable','on');
set(handles.QuickModeButton,'Enable','on');
set(handles.AutoClassifyButton,'Enable','on');
set(handles.ClassifyButton,'Enable','on');
set(handles.NewClassButton,'Visible','off');
set(handles.NextSpectraButton,'Enable','on');
set(handles.PreviousSpectraButton,'Enable','on');
set(handles.ModePopupMenu,'Enable','on');
set(handles.SortText,'Visible','off');
set(handles.SortPopupMenu,'Visible','off');
handles.submode = 'select';
end
if strcmp(handles.mode,'class-members') && strcmp(handles.submode,'typify')
if cposition == 0
set(handles.TypifyClassButton, 'Enable','on');
else
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
sindex = handles.mapindex(cposition + (handles.startpage - 1));
cindex = returnclassindex(handles,handles.segments(sindex).class);
handles.classes(cindex).specfilename = handles.segments(sindex).specfilename;
handles.classes(cindex).length = handles.segments(sindex).end - handles.segments(sindex).start;
handles.classes(cindex).index = sindex;
%load('-mat','specicons');
handles.classes(cindex).iconS = handles.IconList{sindex};
handles.subclass = 'xxx';
set(handles.TypifyClassButton, 'Enable','on');
set_status(handles,'');
end
end
if strcmp('class-view', handles.mode) && strcmp('compare',handles.submode)
if cposition == 0
handles.mode = 'class-view';
handles.submode = 'select';
set(handles.CompareToggleButton,'Enable','on');
set(handles.RemoveClassButton,'Enable','on');
set(handles.NextSpectraButton,'Enable','on');
set(handles.PreviousSpectraButton,'Enable','on');
%set(handles.ModePopupMenu,'Enable','on');
else
handles.mode = 'comparison';
if strcmp(handles.segments(handles.NextIndex).class,'')
set(handles.ClassifyButton,'Enable','on');
end
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
cindex = handles.mapindex(cposition + (handles.startpage - 1));
handles.image_list = {};
handles.lastclass = cindex;
handles.image_list{2} = handles.classes(cindex).iconS;
%load('-mat','specicons');
handles.image_list{1} = handles.IconList{handles.NextIndex};
set_status(handles,['Comparing to ' handles.classes(cindex).name]);
handles = reposition_images(handles, handles.image_list);
handles.cpositions = get_curr_position(handles);
handles = plot_classified_axes(handles, handles.image_list(handles.startpage:handles.endpage), handles.cpositions);
handles.submode = 'xxx';
end
end
if strcmp(handles.mode,'class-view') && strcmp(handles.submode,'remove-class')
if cposition == 0
handles.submode = 'select';
set(handles.RemoveClassButton, 'Enable','on');
set_status(handles, ['Viewing all ', num2str(handles.nclasses),' classes']);
else
cindex = handles.mapindex(cposition + (handles.startpage - 1));
classname = handles.classes(cindex).name;
answer = questdlg(['Remove class ' classname]);
if strcmp(answer,'Yes')
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
for i = 1:handles.nsegments
if strcmp(classname,handles.segments(i).class)
handles.segments(i).class = '';
end
end
if handles.nclasses > 1
handles.classes = [handles.classes(1:(cindex-1)) handles.classes((cindex+1):handles.nclasses)];
handles.nclasses = handles.nclasses - 1;
handles = configureclassview(handles,'select');
set_status(handles, ['Viewing all ', num2str(handles.nclasses),' classes']);
else
handles.classes = [];
handles.nclasses = 0;
handles.image_list = {};
set_status(handles,'');
set(handles.RemoveClassButton,'Visible','off');
handles.submode = 'xxx';
handles = blankaxes(handles);
end
if strcmp(handles.segments(handles.NextIndex).class,'')
set(handles.ClassifyButton,'String','Classify');
end
set(handles.RemoveClassButton, 'Enable','on');
else
handles.submode = 'select';
set(handles.RemoveClassButton, 'Enable','on');
set_status(handles, ['Viewing all ', num2str(handles.nclasses),' classes']);
end
end
end
end
if not(strcmp(handles.mode,'comparison'))
setnavigationbuttons(handles);
end
% handles.mode
% handles.submode
guidata(gcf,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for setting up the classview %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = configureclassview(handles,submode)
% Configures the class-view for selecting classes
handles.mode = 'class-view';
handles.submode = submode;
% if not(handles.quickmode)
% set_status(handles, ['Select a class']);
% end
handles.mapindex = [1 : handles.nclasses];
if strcmp(handles.sortclass, 'popularity')
handles.mapindex = sortindexbypop(handles);
elseif strcmp(handles.sortclass,'length');
handles.mapindex = sortindexbylength(handles);
else
handles.mapindex = [1 : handles.nclasses];
end
handles = cindex2imagelist(handles);
handles = reposition_images(handles, handles.image_list);
if (strcmp(handles.sortclass,'length') && strcmp(handles.submode,'select-class')) || (strcmp(handles.sortclass,'length') && strcmp(handles.submode,'compare'))
% jump to the segment with the closest size match
i = 1;
while (i <= handles.nclasses) && (handles.classes(handles.mapindex(i)).length >= (handles.segments(handles.NextIndex).end - handles.segments(handles.NextIndex).start))
i = i + 1;
end
cnrow = which_row(handles.positions,i-1); % get the current row
if cnrow > handles.number_rows % The closes size segment is not in view
for i = 1:(cnrow - handles.number_rows) % matching size row is last
handles = row_forward(handles);
end
if not(handles.endpage == length(handles.positions)) % if not at the last row position so that larger and smaller rows match
nrows = floor(handles.number_rows / 2);
for i = 1:nrows
handles = row_forward(handles);
end
end
end
end
handles.cpositions = get_curr_position(handles);
handles = plot_classified_axes(handles, handles.image_list(handles.startpage:handles.endpage), handles.cpositions);
%guidata(gcbo,handles);
;
function handles = SetModePopupMenu(handles,viewstring)
popmodes = get(handles.ModePopupMenu,'String');
find_index = 0;
i = 1;
while (i <= length(popmodes)) && not(strcmp(popmodes(i),viewstring))
i = i + 1;
end
if i <= length(popmodes) % Don't do anything if the string cannot be found
set(handles.ModePopupMenu,'Value',[i]);
end
% --- Executes on selection change in ModePopupMenu.
function ModePopupMenu_Callback(hObject, eventdata, handles)
% Configure call back
% hObject handle to ModePopupMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns ModePopupMenu contents as cell array
% contents{get(hObject,'Value')} returns selected item from ModePopupMenu
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified,'Value',0);
%set(handles.CompareToggleButton,'Visible','off');
set(handles.RenameClassButton, 'Visible', 'off');
nmode = get(hObject,'Value');
modeview = get(hObject,'String');
if strcmp(modeview(nmode),'all')
handles.mode = 'browse';
handles.submode = 'select';
handles=BrowseDirectory(handles);
set(handles.RemoveClassButton,'Visible','off');
set(handles.TypifyClassButton, 'Visible', 'off');
set(handles.NextClassButton,'Visible','off');
elseif strcmp(modeview(nmode),'class view')
set(handles.NextClassButton,'Visible','off');
if handles.nclasses >= 1
handles = configureclassview(handles,'select');
handles.mode = 'class-view';
handles.submode = 'select';
set(handles.RemoveClassButton,'Visible','on');
set(handles.RemoveClassButton,'Enable','on');
set(handles.CompareToggleButton,'Visible','on');
set(handles.CompareToggleButton,'Enable','on');
set(handles.TypifyClassButton, 'Visible', 'off');
set_status(handles,['Viewing all ' num2str(handles.nclasses) ' classes'])
else % empty axes
handles = blankaxes(handles);
handles.mode = 'class-view';
handles.submode = 'xxx';
set_status(handles,'');
end
elseif strcmp(modeview(nmode),'unclassified') || (strcmp(handles.segments(handles.NextIndex).class,'') && strcmp(modeview(nmode),'class members'))
handles = configureclassmembers(handles,'');
set_status(handles,['A total of ' num2str(length(handles.mapindex)) ' unclassified segments ']);
handles = SetModePopupMenu(handles,'unclassified');
handles.mode = 'browse';
handles.submode = 'select';
set(handles.RemoveClassButton, 'Visible', 'off');
set(handles.TypifyClassButton,'Visible','off');
set(handles.NextClassButton,'Visible','off');
elseif strcmp(modeview(nmode),'class members')
handles = configureclassmembers(handles,handles.segments(handles.NextIndex).class);
set_status(handles,['Viewing ' num2str(length(handles.mapindex)) ' members of ' handles.segments(handles.NextIndex).class]);
handles.mode = 'class-members';
handles.submode = 'select';
handles.lastclass = get_class_index(handles,handles.segments(handles.NextIndex).class);
set(handles.TypifyClassButton,'Visible', 'on');
set(handles.RemoveClassButton, 'Visible', 'off');
set(handles.RenameClassButton,'Visible','on');
set(handles.NextClassButton,'Visible','on');
end
guidata(gcbo,handles);
% --- Executes during object creation, after setting all properties.
function ModePopupMenu_CreateFcn(hObject, eventdata, handles)
% hObject handle to ModePopupMenu (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function set_status(handles, statusstring)
set(handles.SegInfoText,'String',statusstring);
set(handles.SegInfoText,'Visible','on');
;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for filtering by class type %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = configureclassmembers(handles,classname)
handles.mapindex = select_class(handles,handles.segments,classname);
if length(handles.mapindex) > 0
handles.image_list = {};
%load('-mat','specicons');
for i = 1:length(handles.mapindex)
handles.image_list(i) = handles.IconList(handles.mapindex(i));
end
handles = reposition_images(handles, handles.image_list);
handles.cpositions = get_curr_position(handles);
%
%handles.mode = 'class-members';
handles = plot_classified_axes(handles, handles.image_list(handles.startpage:handles.endpage), handles.cpositions);
%handles = SetModePopupMenu(handles,'class members');
else
handles = blankaxes(handles);
%handles.mode = 'class-view';
%handles.submode = 'select';
set_status(handles,'');
end
;
function indexfilter = select_class(handles,segments,classname)
% Returns an index array of original addresses of segments which are members of a
% specified class
indexfilter = [];
nclassmembers = 0;
for i = 1:handles.nsegments
if strcmp(segments(i).class,classname)
nclassmembers = nclassmembers + 1;
indexfilter(nclassmembers) = i;
end
end
function cindex = get_class_index(handles,classname);
cindex = 0;
i = 1;
while (i <= handles.nclasses) && not(strcmp(handles.classes(i).name,classname))
i = i + 1;
end
cindex = i;
function value = mapind(index)
% Map the index value back to its original value
value = handles.mapindex(index);
%%&& not(strcmp(segments(i).class,''));
function write_syllable_database(handles)
filename = [handles.baseclassname '.dat'];
fid = fopen(filename,'wt');
classes = handles.classes;
if fid > -1
for i = 1:handles.nsegments
segment = handles.segments(i);
wavfile = segment.wavfile;
specfilename = segment.specfilename;
seg = [ num2str(segment.start) '\t' num2str(segment.end)];
classname = [ segment.class ];
typify = '';
nclasses = length(classes);
j = 1;
while (nclasses > 0) && (j <= nclasses) && not(strcmp(segment.specfilename,classes(j).specfilename))
j = j + 1;
end
if j <= length(classes) % found a match
classes = [classes(1:j-1) classes(j+1:nclasses)]; % shorten the classes
typify = '*'; % indicates that this is typological class
end
fprintf(fid,[specfilename '\t' wavfile '\t' seg '\t' classname '\t' typify '\n']);
end
fclose(fid);
end
;
function data = read_syllable_database(handles)
filename = [handles.baseclassname '.dat'];
fid = fopen(filename,'rt');
data = textscan(fid,'%s %s %n %n %s %s', 'delimiter','\t');
data = [data(1), data(5), data(6)]; % throw out extra stuff which will be useful for external analysis
fclose(fid);
;
function handles = merge_syllable_database(handles,data)
% Merge the syllable list with the loaded database
%load('-mat','specicons');
specfilenames = data{1};
classnames = data{2};
typifies = data{3};
ndata = length(specfilenames);
%classnum = 1;
handles.classes = [];
handles.nclasses = 0;
for i = 1:ndata
j=1; % allow for no matches and allow for
while (j < handles.nsegments) && not(strcmp(specfilenames(i),handles.segments(j).specfilename))
j = j + 1;
end
if j <= handles.nsegments
handles.segments(j).class = classnames{i};
if strcmp(typifies(i),'*') % this is the type class
%classnum = classnum + 1;
class.specfilename = specfilenames{i};
class.name = classnames{i};
class.index = j;
class.length = handles.segments(j).end - handles.segments(j).start;
class.iconS = handles.IconList{j};
class.nmembers = 0; % will update shortly
handles.nclasses = handles.nclasses + 1;
handles.classes = [handles.classes class];
end
end
end
% Now that we have the classes defined update the number of members
for i = 1:handles.nclasses
for j = 1 : handles.nsegments
if strcmp(handles.classes(i).name,handles.segments(j).class)
handles.classes(i).nmembers = handles.classes(i).nmembers + 1;
end
end
end
% --- Executes on button press in SaveButton.
function SaveButton_Callback(hObject, eventdata, handles)
% hObject handle to SaveButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
write_syllable_database(handles); % save the database
save_configuration(handles,handles.configfile); % save the current configuration
% --- Executes on slider movement.
function SliderClassified_Callback(hObject, eventdata, handles)
% hObject handle to SliderClassified (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
xposition = round(get(hObject,'Value'));
%xposition
handles.startx = 1 + xposition;
handles.endx = xposition + handles.classified_width;
handles.cpositions = get_curr_position(handles);
classview = handles.classmatrix(:,handles.startx:handles.endx); % will cut overhang
axes(handles.ClassifiedAxes);
handles.hiclass = image(classview);
set(handles.hiclass,'ButtonDownFcn',{@ClassifyAxesClickCallBack});
set(handles.ClassifiedAxes,'XTick',[]);
set(handles.ClassifiedAxes,'YTick',[]);
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function SliderClassified_CreateFcn(hObject, eventdata, handles)
% hObject handle to SliderClassified (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background, change
% 'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
set(hObject,'BackgroundColor',[.9 .9 .9]);
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on selection change in SortPopupMenu.
function SortPopupMenu_Callback(hObject, eventdata, handles)
% hObject handle to SortPopupMenu (see GCBO) eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns SortPopupMenu contents as cell array
% contents{get(hObject,'Value')} returns selected item from SortPopupMenu
sortlist = get(hObject,'String');
sortn = get(hObject,'Value');
sortby = sortlist(sortn);
if strcmp(sortby,'original')
handles.sortclass = 'original';
elseif strcmp(sortby,'by length')
handles.sortclass = 'length';
elseif strcmp(sortby,'by popularity')
handles.sortclass = 'popularity';
end
handles = configureclassview(handles,handles.submode);
guidata(gcbo,handles);
% --- Executes during object creation, after setting all properties.
function SortPopupMenu_CreateFcn(hObject, eventdata, handles)
% hObject handle to SortPopupMenu (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function segments = rename_segments(segments,oldname,newname)
nsegments = length(segments);
for i = 1 : nsegments
if strcmp(segments(i).class,oldname)
segments(i).class = newname;
end
end
function cln = doesclassexist(classname,classes)
% tests whether the current class name already exists if does not exist
% returns 1 if it does exist returns 0
i = 1;
nclasses = length(classes);
while (i <= nclasses) && (strcmp(classname,classes(i).name))
i = i + 1;
end
if i <= nclasses
cln = i;
else
cln = 0;
end
% --- Executes on button press in RenameClassButton.
function RenameClassButton_Callback(hObject, eventdata, handles)
% hObject handle to RenameClassButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
class = handles.classes(handles.lastclass);
answer = inputdlg({'Class name'},'Edit class name',1,{class.name});
% check the answer
sizeanswer = size(answer);
secondanswer = '';
if sizeanswer(1)
if not(strcmp(class.name,answer{1}))
classnexists = doesclassexist(answer{1},handles.classes);
if classnexists
secondanswer = questdlg('Class name already exists. Do you want to merge the two classes.')
end
if strcmp(secondanswer,'Yes') || strcmp(secondanswer,'')
segments = rename_segments(handles.segments,class.name,answer{1});
class.name = answer{1};
cindex = handles.lastclass;
handles.classes(cindex) = class;
handles.segments = segments;
if strcmp(secondanswer,'Yes') % functionality for merging two classes
handles.classes(classnexists).nmembers = handles.classes(classnexists).nmembers + handles.classes(cindex).nmembers;
handles.classes = [handles.classes(1:(cindex-1)) handles.classes((cindex+1):handles.nclasses)];
handles.nclasses = handles.nclasses - 1;
class.nmembers = handles.classes(classnexists).nmembers; % this is parasitic code
end
end
handles = configureclassmembers(handles,class.name);
set_status(handles, ['Viewing ' num2str(class.nmembers),' members of ' class.name]);
end
end
guidata(gcbo,handles);
function spectras = subsamplespectra(spectra,lowerfreq,upperfreq,freqrange)
% Returns a subsampled frequency of the spectra
freqsamples = length(spectra(:,1));
freqratio = freqsamples / (freqrange(2) - freqrange(1));
lowerfreqsamp = round(lowerfreq * freqratio) + 1;
upperfreqsamp = round(upperfreq * freqratio) + 1;
if lowerfreqsamp < 1 % make sure we are not out of range
lowerfreqsamp = 1;
end
if upperfreq > freqsamples
upperfeqsamp = freqsamples;
end
spectras = spectra(lowerfreqsamp:upperfreqsamp,:);
function handles = generate_subsamples_icons(handles)
segments = handles.segments;
IconListf = {};
hw = waitbar(0,'Zooming spectra. . .');
for i = 1:handles.nsegments
load('-mat',segments(i).specfilename);
Ssub = subsamplespectra(S,handles.lowerfreq,handles.upperfreq,handles.fpass);
IconListf{i} = iconify_spec(Ssub,handles.ispecheight);
waitbar(i/handles.nsegments);
end
close(hw);
handles.IconListf = IconListf;
function handles = ZoomSpectra(handles,status)
if strcmp(status,'Zoom in')
if (length(handles.IconListf) == 0) || (handles.rezoom)
handles = generate_subsamples_icons(handles);
handles.rezoom = logical(0);
end
handles.FullIconList = handles.IconList;
set(handles.ZoomButton,'String','Zoom out');
handles.IconList = handles.IconListf;
elseif strcmp(status,'Zoom out');
if handles.rezoom
handles = generate_subsamples_icons(handles);
handles.rezoom = logical(0);
set(handles.ZoomButton,'String','Zoom out');
handles.IconList = handles.IconListf;
else
handles.IconList = handles.FullIconList;
set(handles.ZoomButton,'String','Zoom in');
end
end
for j = 1:handles.nclasses % switch over class icons
handles.classes(j).iconS = handles.IconList{handles.classes(j).index};
end
nimages = length(handles.mapindex);
% this is kind of ugly
if not(strcmp(handles.mode,'class-view')) && not(strcmp(handles.mode,'comparison')) % update images
for i = 1:nimages
handles.image_list{i} = handles.IconList{handles.mapindex(i)};
end
elseif strcmp(handles.mode,'comparison')
handles.image_list{1} = handles.IconList{handles.NextIndex};
handles.image_list{2} = handles.IconList{handles.classes(handles.lastclass).index};
else
for i = 1:nimages
handles.image_list{i} = handles.IconList{handles.classes(handles.mapindex(i)).index};
end
end
handles=get_and_plot(handles,handles.segments(handles.NextIndex));
handles = plot_classified_axes(handles, handles.image_list(handles.startpage:handles.endpage), handles.cpositions);
% --- Executes on button press in ZoomButton.
function ZoomButton_Callback(hObject, eventdata, handles)
% hObject handle to ZoomButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
status = get(handles.ZoomButton,'String');
handles = ZoomSpectra(handles,status);
guidata(gcbo,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for computing class statistics %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [meanl sdl] = stat_lengths(handles)
lengthsarray = [];
for i = 1:length(handles.mapindex)
lengthsarray(i) = handles.segments(i).end - handles.segments(i).start;
end
meanl = mean(lengthsarray);
sdl = sd(lengthsarray);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Functions for quick classify mode %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = quick_mode_exit(handles)
set(handles.SkipButton,'Visible','off');
set(handles.UndoButton,'Visible','off');
set(handles.NewQuickButton,'Visible','off');
set(handles.ViewText,'Visible','on');
set(handles.ModePopupMenu,'Visible','on');
set(handles.SegInfoText,'Visible','on');
set(handles.ClassifyButton,'Enable','on');
set(handles.RemoveClassButton,'Enable','on');
set(handles.RemoveClassButton,'Visible','on');
set(handles.CompareToggleButton,'Enable','on');
set(handles.AutoClassifyButton,'Enable','on');
set(handles.SortPopupMenu,'Visible','off');
set(handles.ModePopupMenu,'Value',3);
handles.submode='select';
set_status(handles,['Viewing all ' num2str(handles.nclasses) ' classes']);
setnavigationbuttons(handles);
% --- Executes on button press in QuickModeButton.
function QuickModeButton_Callback(hObject, eventdata, handles)
% hObject handle to QuickModeButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if not(handles.quickmode) % turn on quick mode
handles.quickmode = 1;
% Turn off top header
set(handles.ViewText,'Visible','off');
set(handles.ModePopupMenu,'Visible','off');
set(handles.SegInfoText,'Visible','off');
% Make visible quick mode buttons
set(handles.SkipButton,'Visible','on');
set(handles.SkipButton,'Enable','on');
set(handles.UndoButton,'Visible','on');
set(handles.UndoButton,'Enable','on');
set(handles.NewQuickButton,'Visible','on');
set(handles.NewQuickButton,'Visible','on');
set(handles.SortPopupMenu,'Visible','on');
% Disable regular mode functions
set(handles.RemoveClassButton,'Visible','off');
set(handles.NextClassButton,'Visible','off');
set(handles.NextSpectraButton,'Enable','off');
set(handles.PreviousSpectraButton,'Enable','off');
set(handles.ClassifyButton,'Enable','off');
set(handles.TypifyClassButton,'Visible','off');
set(handles.RenameClassButton,'Visible','off');
set(handles.CompareToggleButton,'Enable','off');
set(handles.AutoClassifyButton,'Enable','off');
% Will need to disable buttons underneath classified axes
if not(strcmp(handles.segments(handles.NextIndex).class,''))
handles = jump_to_unclassified(handles);
handles.lastsegment = handles.NextIndex;
end
if handles.nclasses >= 1
handles = configureclassview(handles,'select-class');
handles.mode = 'class-view';
handles.submode = 'select-class';
else % empty axes
handles = blankaxes(handles);
handles.mode = 'class-view';
handles.submode = 'xxx';
end
else
handles.quickmode = 0;
handles = quick_mode_exit(handles);
% Will need to intellegently enable buttons underneath classified axes
end
guidata(gcbo,handles);
function handles=jump_to_unclassified(handles)
% Jumps to the next unclassified segment
currindex = handles.NextIndex;
i = currindex;
while (mod(i,handles.nsegments)+1 ~= currindex) && not(strcmp(handles.segments(mod(i,handles.nsegments) + 1).class,''))
i = i + 1;
end
if not(mod(i,handles.nsegments)+1 == currindex) % there are some unclassified segments
handles.NextIndex = mod(i,handles.nsegments) + 1;
handles=ConfigureClassSegment(handles);
handles=ConfigureSpecPlot(handles);
set(handles.ClassifyButton,'Enable','off');
end
%get(handles.QuickModeButton,'Value')
handles.lastsegment = currindex;
% --- Executes on button press in SkipButton.
function SkipButton_Callback(hObject, eventdata, handles)
% hObject handle to SkipButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = jump_to_unclassified(handles);
if handles.lastsegment == handles.NextIndex % no more unclassified segments
handles = quick_mode_exit(handles);
set(handles.QuickModeButton,'Value',0);
handles.quickmode = not(handles.quickmode);
end
handles = configureclassview(handles,'select-class');
guidata(gcbo,handles);
% --- Executes on button press in UndoButton.
function UndoButton_Callback(hObject, eventdata, handles)
% hObject handle to UndoButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.NextIndex = handles.lastsegment;
handles=ConfigureClassSegment(handles);
handles=ConfigureSpecPlot(handles);
handles = quick_mode_exit(handles);
set(handles.QuickModeButton,'Value',0);
handles.quickmode = not(handles.quickmode);
guidata(gcbo,handles);
% --- Executes on button press in NewQuickButton.
function NewQuickButton_Callback(hObject, eventdata, handles)
% hObject handle to NewQuickButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = add_new_class(handles,handles.segments(handles.NextIndex));
handles.segments(handles.NextIndex).class = handles.classes(handles.nclasses).name;
set(handles.ClassifyButton,'Enable','off');
handles = jump_to_unclassified(handles);
handles = configureclassview(handles,'select-class');
if handles.lastsegment == handles.NextIndex % no more unclassified segments
handles = quick_mode_exit(handles)
set(handles.QuickModeButton,'Value',0);
handles.quickmode = not(handles.quickmode);
end
guidata(gcbo,handles);
% --- Executes on button press in CompareToggleButton.
function CompareToggleButton_Callback(hObject, eventdata, handles)
% hObject handle to CompareToggleButton (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 CompareToggleButton
state = get(hObject,'Value');
if handles.nclasses > 0
if state % enter compare mode
handles.mode = 'class-view';
set(handles.RemoveClassButton,'Enable','off');
set(handles.RenameClassButton,'Visible','off');
set(handles.NextClassButton,'Visible','off');
set(handles.ModePopupMenu,'Enable','off');
set(handles.ClassifyButton,'Enable','off');
set(handles.QuickModeButton,'Enable','off');
set_status(handles,'Select a class to compare segment against');
set(handles.NextSpectraButton,'Enable','off');
set(handles.PreviousSpectraButton,'Enable','off');
set(handles.TypifyClassButton, 'Visible', 'off');
set(handles.AutoClassifyButton,'Enable','off');
handles = configureclassview(handles,'compare');
else
if strcmp(handles.mode,'comparison') % go back to the class view
set(hObject,'Value',1);
handles.startx = 1; % if you have been scrolling reset to defaults
handles.endx = handles.classified_width;
set(handles.SliderClassified, 'Value',0);
handles = configureclassview(handles,'compare');
handles.mode = 'class-view';
set_status(handles,'Select a class to compare segment against');
elseif strcmp(handles.mode,'class-view') % exit the compare mode entirely
set_status(handles, ['Viewing all ', num2str(handles.nclasses),' classes']);
set(handles.ModePopupMenu,'Enable','on');
set(handles.QuickModeButton,'Enable','on');
setnavigationbuttons(handles);
SetModePopupMenu(handles,'class view');
set(handles.RemoveClassButton,'Enable','on');
set(handles.RemoveClassButton,'Visible','on');
set(handles.ClassifyButton,'Enable','on');
set(handles.AutoClassifyButton,'Enable','on');
handles.submode = 'select';
end
end
else
set(hObject,'Value',0);
end
guidata(hObject, handles);
function handles = recompute_classifiedaxes(handles)
% Recomputes the width and height based on a new size for the classified
% axes
classaxpos=get(handles.ClassifiedAxes,'Position');
set(handles.SliderClassified,'Value',0);
handles.startx = 1;
handles.classified_width = round(handles.classified_width_density * classaxpos(3));
handles.classified_height = round(handles.classified_height_density * classaxpos(4));
oldpos = handles.startpage;
handles = reposition_images(handles, handles.image_list); % try to keep rows matched
cnrow = which_row(handles.positions,oldpos);
for i = 1:(cnrow-1)
handles = row_forward(handles);
end
handles.cpositions = get_curr_position(handles);
handles = plot_classified_axes(handles, handles.image_list(handles.startpage:handles.endpage), handles.cpositions);
function reposy(guielement,deltay)
oldpos = get(guielement,'Position');
set(guielement,'Position',[oldpos(1), oldpos(2) + deltay, oldpos(3), oldpos(4)]);
function reposelementsy(handles,deltay)
reposy(handles.PrecomputeButton,deltay);
reposy(handles.DirectoryEditBox,deltay);
reposy(handles.LoadDirectoryButton,deltay);
reposy(handles.SaveButton,deltay);
reposy(handles.ConfigureButton,deltay);
reposy(handles.ViewText,deltay);
reposy(handles.ModePopupMenu,deltay);
reposy(handles.SegInfoText,deltay);
reposy(handles.ToClassifyPanel,deltay);
reposy(handles.NewQuickButton,deltay);
reposy(handles.UndoButton,deltay);
reposy(handles.SkipButton,deltay);
reposy(handles.SortText,deltay);
reposy(handles.SortPopupMenu,deltay);
reposy(handles.NextClassButton,deltay);
function ResizeFcn(h, eventdata, handles, varargin)
handles = guidata(gcbo);
originalsize = handles.originalsize;
newsize = get(h,'Position');
classaxpos = get(handles.ClassifiedAxes,'Position');
if handles.originalsize(3) > newsize(3) % if form has smaller width bounce back
newsize(3) = originalsize(3);
classaxpos(3) = handles.originalaxessize(3);
sliderpos = get(handles.SliderClassified,'Position'); % Update the slider
sliderpos(3) = classaxpos(3);
set(handles.SliderClassified,'Position',sliderpos);
else % form is larger
deltax = newsize(3) - handles.prevsize(3);
classaxpos(3) = classaxpos(3) + deltax; % update width of the axes
sliderpos = get(handles.SliderClassified,'Position'); % Update the slider
sliderpos(3) = sliderpos(3) + deltax;
set(handles.SliderClassified,'Position',sliderpos);
end
if originalsize(4) > newsize(4) % if form has a smaller height bounce back
newsize(2) = newsize(2) + newsize(4) - originalsize(4);
deltay = originalsize(4) - handles.prevsize(4);
newsize(4) = originalsize(4);
classaxpos(4) = classaxpos(4) + newsize(4) - handles.prevsize(4);
reposelementsy(handles,deltay);
else % form is larger we need to reposition elements
deltay = newsize(4) - handles.prevsize(4);
reposelementsy(handles,deltay);
classaxpos(4) = classaxpos(4) + newsize(4) - handles.prevsize(4);
end
set(h,'Position',newsize);
set(handles.ClassifiedAxes,'Position',classaxpos);
if handles.fixed || handles.blank % allow fixed resizing
% do nothing except update the density measurements
handles.classified_width_density = handles.classified_width / classaxpos(3);
handles.classified_height_density = handles.classified_height / classaxpos(4);
else % reposition images
handles = recompute_classifiedaxes(handles);
end
handles.prevsize = newsize;
guidata(gcbo,handles);
function truth = truthrange(range)
truth = range(1) && range (2);
% --- Executes on button press in ConfigureButton.
function ConfigureButton_Callback(hObject, eventdata, handles)
% hObject handle to ConfigureButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handlenb vcccs structure with handles and user data (see GUIDATA)
configs = configure_classify(handles.lowerfreq,handles.upperfreq,handles.classified_height,handles.classified_width,handles.Fs,handles.movingwin,handles.tapers,handles.fpass,handles.fixed);
if not(isempty(configs) || length(configs) == 1) % if okay is pressed
lowerfreq= configs{1};
upperfreq= configs{2};
classified_height= configs{3};
classified_width= configs{4};
Fs=configs{5};
movingwin= configs{6};
tapers= configs{7};
fpass = configs{8};
rezoom = 0;
if not(handles.lowerfreq == lowerfreq)
handles.lowerfreq = lowerfreq;
rezoom = 1;
end
if not(handles.upperfreq==upperfreq)
handles.upperfreq=upperfreq;
rezoom=1;
end
redraw = 0;
if not(handles.classified_height==classified_height)
handles.classified_height=classified_height;
redraw = 1;
end
if not(handles.classified_width==classified_width)
handles.classified_width=classified_height;
redraw = 1;
end
recompute = 0; % check to see if the spectra needs to be recomputed
if not(handles.Fs==Fs)
handles.Fs = Fs;
recompute = 1;
end
if not(truthrange(handles.movingwin == movingwin))
handles.movingwin = movingwin;
recompute = 1;
end
if not(truthrange(handles.tapers==tapers))
handles.tapers=tapers;
recompute = 1;
end
if not(truthrange(handles.fpass==fpass))
handles.fpass=fpass;
recompute = 1;
end
if recompute % The spectra need to be recomputed
status = questdlg('Recompute spectra with changed parameters');
if not(isempty(status))
if strcmp(status,'Yes')
handles = precompute_AllSpectra(handles);
save_configuration(handles,handles.configfile); % Save configuration no matter what
handles=ConfigureSpecPlot(handles); % automatically force into browse mode
set(handles.RemoveClassButton,'Visible','off');
set(handles.TypifyClassButton, 'Visible', 'off');
set(handles.NextClassButton,'Visible','off');
handles=BrowseDirectory(handles);
set(handles.ModePopupMenu,'Value',1);
if handles.nclasses >= 1 % sync changes to the classview
for j = 1:handles.nclasses
handles.classes(j).iconS = handles.IconList{handles.classes(j).index};
end
end
set(handles.RemoveClassButton,'Visible','off'); % update buttons
set(handles.TypifyClassButton, 'Visible', 'off');
set(handles.NextClassButton,'Visible','off');
redraw = logical(1);
end
end
end
if rezoom
if strcmp(get(handles.ZoomButton,'String'),'Zoom out')
handles.rezoom = logical(1);
handles = ZoomSpectra(handles,'Zoom out');
else
handles.rezoom = logical(1); % Otherwise wait to user hits the rezoom button
end
end
if not(handles.configschanged) % handles the case were the configurations were changed already
if not(recompute)
handles.configschanged = logical(1);
end
end
if redraw % Redraw the axes
classaxpos = get(handles.ClassifiedAxes,'Position');
handles.classified_width_density = handles.classified_width / classaxpos(3);
handles.classified_height_density = handles.classified_height / classaxpos(4);
handles = recompute_classifiedaxes(handles);
end
handles.fixed = configs{9};
end
guidata(gcbo,handles);
function status = save_configuration(handles,filename)
Fs = handles.Fs;
movingwin = handles.movingwin;
tapers = handles.tapers;
fpass = handles.fpass;
try
save(filename,'Fs','movingwin','tapers','fpass','-mat');
catch
status = 1;
end
function handles = load_configuration(handles,filename)
try
load('-mat',filename)
if handles.Fs == Fs || handles.movingwin == movingwin || handles.tapers == tapers || handles.fpass == fpass
handles.configshavechanged = logical(1);
end
handles.Fs = Fs;
handles.movingwin = movingwin;
handles.tapers = tapers;
handles.fpass = fpass;
catch
handles = handles;
end
% --- Executes on button press in NextClassButton.
function NextClassButton_Callback(hObject, eventdata, handles)
% hObject handle to NextClassButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.lastclass = handles.lastclass + 1;
if handles.lastclass > handles.nclasses
handles.lastclass = 1;
end
class = handles.classes(handles.lastclass);
handles = configureclassmembers(handles,class.name);
set_status(handles,['Viewing ' num2str(length(handles.mapindex)) ' members of ' class.name]);
handles.mode = 'class-members';
handles.submode = 'select';
guidata(gcbo,handles);
function handles = features_segments(handles)
h=waitbar(0,'Computing Data Features. . . ');
for i = 1:handles.nsegments
startf = handles.segments(i).start;
endf = handles.segments(i).end;
cepestral = cepsfromspectra(handles.segments(i).specfilename,handles.ncepestral);
% Below shows how additional data features can be included in the
% exporting and classifying using the software
% The commented code shows how the wave file can be read in to
% calculate additional data features
% segment = handles.segments(i);
% data = wavread(segment.wavfile,round(handles.Fs * [segment.start segment.end]));
waitbar(i/handles.nsegments);
handles.segments(i).features = cepestral';
% Three additional data features can be added for example as following
%
% additional_features = compute_features(data,3);
% handles.nfeatures = handles.nfeatures + 3;
% handles.segments(i).features = [handles.segments(i).features additional_features'];
end
close(h);
function coefs = cepsfromspectra(specfilename,ncepestral)
load('-mat',specfilename);
sbase = (mean(min(exp(Spre))) + mean(min(exp(Spost)))) / 2; % might not be a good
% baseline because of
% the intensity of the
% sound around the syllable that
% is why I took the average
% minimum value
%Sdiff = S - sbase;
Sdiff = exp(S) - sbase; % arithmetic average
spectra = log(mean(Sdiff')); % average across time to generate spectra
%spectra=mean(Sdiff');
cepstrum = real(ifft(spectra));
% alternative methods for computing the cepstrum
%real(fft(hamming(length(spectra) .* spectra )));
%cepstrum = real(fft(spectra))
coefs = cepstrum(1:ncepestral); % this I understand is the
% correct way
function classifymatrix = generate_classify_mat(handles)
classifymatrix = zeros(handles.nsegments,handles.nfeatures+1);
for i = 1:handles.nsegments
seglength = handles.segments(i).end - handles.segments(i).start;
classifymatrix(i,1:1+handles.nfeatures) = [seglength handles.segments(i).features(1:handles.nfeatures)'];
end
;
function handles = generate_classes_auto(handles,classification)
nclasses = length(unique(classification));
classesfound = zeros(nclasses,1); % used to check which classes exist
handles.classes = [];
handles.nclasses = 0;
j = 1;
for i = 1:handles.nsegments
if classification(i) == 0 % segment has not been classified
handles.segments(i).class = '';
else
if isempty(classesfound(find(classesfound == classification(i)))) % a new class is found
class.specfilename = handles.segments(i).specfilename;
class.name = newclassname(handles);
class.index = i;
class.length = handles.segments(i).end - handles.segments(i).start;
class.iconS = handles.IconList{i};
class.nmembers = 1;
handles.segments(i).class = class.name;
handles.classes = [handles.classes class];
classesfound(j) = classification(i);
j = j + 1;
handles.nclasses = handles.nclasses + 1;
else % segment belongs to a class that already exists
classindex = find(classification(i) == classesfound);
handles.segments(i).class = handles.classes(classindex).name;
handles.classes(classindex).nmembers = handles.classes(classindex).nmembers + 1;
end
end
end
;
% --- Executes on button press in AutoClassifyButton.
function AutoClassifyButton_Callback(hObject, eventdata, handles)
% hObject handle to AutoClassifyButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if length(handles.segments(1).features) == 0; % compute cepestral coefficients if not computed before
handles = features_segments(handles);
end
matrix2classify = generate_classify_mat(handles);
classification = auto_classify(matrix2classify,handles.nfeatures);
if length(classification) > 1 %&& not(classification == 0)
if not(isempty(handles.classes))
answer = questdlg('A classification already exists. Do you want to replace the current classification?');
if strcmp(answer,'Yes')
handles = generate_classes_auto(handles,classification);
end
else
handles = generate_classes_auto(handles,classification);
end
handles=configureclassview(handles,'select');
set(handles.ClassifyButton,'String','Declassify'); % all classes are now classified
set(handles.RemoveClassButton,'Visible','on');
set(handles.RemoveClassButton,'Enable','on');
set(handles.CompareToggleButton,'Visible','on');
set(handles.CompareToggleButton,'Enable','on');
set(handles.TypifyClassButton, 'Visible', 'off');
set_status(handles,['Viewing all ' num2str(handles.nclasses) ' classes'])
%
% set(handles.ModePopupMenu,'Value',3);
%
% ModePopupMenu_Callback(handles.ModePopupMenu,eventdata, handles);
% handles.mode = 'class-view';
% handles.submode = 'select';
end
guidata(gcbo,handles);
% --------------------------------------------------------------------
function FileMenu_Callback(hObject, eventdata, handles)
% hObject handle to FileMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function SaveItem_Callback(hObject, eventdata, handles)
% hObject handle to SaveItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SaveButton_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function LoadItem_Callback(hObject, eventdata, handles)
% hObject handle to LoadItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
PrecomputeButton_Callback(hObject, eventdata, handles)
%guidata(gcbo,handles)
% --------------------------------------------------------------------
function HelpMenu_Callback(hObject, eventdata, handles)
% hObject handle to HelpMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function HelpItem_Callback(hObject, eventdata, handles)
% hObject handle to HelpItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
web('classify_spectra_help.html');
% --------------------------------------------------------------------
function AboutItem_Callback(hObject, eventdata, handles)
% hObject handle to AboutItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
msgbox('Classify_spectra (version 0.2) is being developed by the Mitra Lab at the Cold Spring Harbor Laboratory.','About classify_spectra');
% --------------------------------------------------------------------
function ConfigureItem_Callback(hObject, eventdata, handles)
% hObject handle to ConfigureItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
ConfigureButton_Callback(hObject, eventdata, handles)
function coefs = cepcoefs(data,p)
% Computes the cepstral coefficients from the data returns p coefficients
coefs = [];
if p > 0
y = fft(hamming(length(data)) .* data);
coefs = aryule(ifft(log(abs(y))),p);
end
function generate_output(handles,absolutetime,filename);
filebasetosave = filename(1:length(filename)-4);
matrixoutput = cell(handles.nsegments,1);
for i = 1:handles.nsegments
segment = handles.segments(i);
if absolutetime
dstr = regexp(segment.wavfile,'[0-9]+\-[0-9]+\-[0-9]+','match');
dstr = dstr{1}; % take first match only
tstr = regexp(segment.wavfile,'[0-9][0-9][0-9][0-9][0-9][0-9]','match');
tstr = tstr{1};
tstr = [tstr(1:2) ':' tstr(3:4) ':' tstr(5:6)];
segmentstart = datenum([dstr ' ' tstr]) + segment.start;
segmentstart = datevec(segmentstart);
else
segmentstart = segment.start;
end
matrixoutput{i} = {segment.wavfile,segment.class,segmentstart,segment.end - segment.start,segment.features};
end
save([filebasetosave '.mat'],'-mat','matrixoutput','-mat');
delimiter = '\t';
fp = fopen([filebasetosave '.txt'],'wt');
% Generate header for file
fprintf(fp,'filename');fprintf(fp,delimiter);
fprintf(fp,'class');fprintf(fp,delimiter);
if absolutetime
fprintf(fp,'year');fprintf(fp,delimiter);
fprintf(fp,'month');fprintf(fp,delimiter);
fprintf(fp,'day');fprintf(fp,delimiter);
fprintf(fp,'hour');fprintf(fp,delimiter);
fprintf(fp,'minute');fprintf(fp,delimiter);
fprintf(fp,'second');fprintf(fp,delimiter);
else
fprintf(fp,'start');fprintf(fp,delimiter);
end
fprintf(fp,'length');fprintf(fp,delimiter);
for i = 1:handles.nfeatures
fprintf(fp,['d' num2str(i)]);
if i < handles.nfeatures;
fprintf(fp,delimiter);
else
fprintf(fp,'\n');
end
end
% Generate main data
for i = 1:handles.nsegments
segment = handles.segments(i);
fprintf(fp,['"' segment.wavfile '"']);fprintf(fp,delimiter);
fprintf(fp,['"' segment.class '"']);fprintf(fp,delimiter);
if absolutetime
time = matrixoutput{i}{3};
fprintf(fp,num2str(time(1)));fprintf(fp,delimiter);
fprintf(fp,num2str(time(2)));fprintf(fp,delimiter);
fprintf(fp,num2str(time(3)));fprintf(fp,delimiter);
fprintf(fp,num2str(time(4)));fprintf(fp,delimiter);
fprintf(fp,num2str(time(5)));fprintf(fp,delimiter);
fprintf(fp,num2str(time(6)));
else
fprintf(fp,num2str(segment.start));
end
fprintf(fp,delimiter);
fprintf(fp,num2str(segment.end-segment.start));fprintf(fp,delimiter);
for j = 1:handles.nfeatures
fprintf(fp,num2str(segment.features(j)));
if j < handles.nfeatures % handle eol formatting
fprintf(fp,delimiter);
else
if i < handles.nsegments % handle eof formatting
fprintf(fp,'\n');
end
end
end
end
fclose(fp);
% --------------------------------------------------------------------
function ExportDataItem_Callback(hObject, eventdata, handles)
% hObject handle to ExportDataItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filename = uiputfile('*.txt','File to write exported data to');
if not(filename == 0)
if length(handles.segments(1).features) == 0
handles = features_segments(handles);
end
generate_output(handles,1,filename);
end
% --------------------------------------------------------------------
function CleanDirectoryItem_Callback(hObject, eventdata, handles)
% hObject handle to CleanDirectoryItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
answer = questdlg('Clean the current directory. This will remove all files generated by classify_spectra including the file which includes the classification');
if strcmp(answer,'Yes');
specfiles = dir('*.spec');
for i = 1:length(specfiles)
delete(specfiles(i).name);
end
if exist('class_spec.conf')
delete('class_spec.conf');
end
if exist([handles.baseclassname '.dat'])
delete([handles.baseclassname '.dat']);
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
configure_classify.m
|
.m
|
Acoustic_Similarity-master/code/chronux/wave_browser/configure_classify.m
| 17,395 |
utf_8
|
081c0712e35fc389b4df1270cb307bb7
|
function varargout = configure_classify(varargin)
% CONFIGURE_CLASSIFY M-file for configure_classify.fig
% CONFIGURE_CLASSIFY, by itself, creates a new CONFIGURE_CLASSIFY or raises the existing
% singleton*.
%
% H = CONFIGURE_CLASSIFY returns the handle to a new CONFIGURE_CLASSIFY or the handle to
% the existing singleton*.
%
% CONFIGURE_CLASSIFY('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CONFIGURE_CLASSIFY.M with the given input arguments.
%
% CONFIGURE_CLASSIFY('Property','Value',...) creates a new CONFIGURE_CLASSIFY or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before configure_classify_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to configure_classify_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 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help configure_classify
% Last Modified by GUIDE v2.5 01-May-2006 23:22:44
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @configure_classify_OpeningFcn, ...
'gui_OutputFcn', @configure_classify_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 configure_classify is made visible.
function configure_classify_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 configure_classify (see VARARGIN)
% Choose default command line output for configure_classify
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes configure_classify wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% configure_classify(0,7500,400,500,44100,[0.01 0.001],[3 5],[0 20000])
handles.lowerfreq = varargin{1}; % Lower frequency for zooming
handles.upperfreq = varargin{2}; % Upper frequency for zooming
handles.classified_height = varargin{3} ; % the height of the image in the classified axes
handles.classified_width = varargin{4}; % the width of the image in the classified axes
handles.Fs = varargin{5}; % Frequency of audio sampling per second
handles.movingwin = varargin{6}; % Size of the moving window in seconds; the first number is the window size and the second is the step size
handles.tapers = varargin{7}; % Tapers for smoothing
handles.fpass = varargin{8}; % Range of frequency sampling
handles.fixed = varargin{9}; % Fixed scaling of the classified axes
set(handles.ZoomLowerFreq,'String',num2str(handles.lowerfreq));
set(handles.ZoomUpperFreq,'String',num2str(handles.upperfreq));
set(handles.ClassifiedWidth,'String',num2str(handles.classified_width));
set(handles.ClassifiedHeight,'String',num2str(handles.classified_height));
set(handles.Frequency,'String',num2str(handles.Fs));
set(handles.WinSize,'String',num2str(handles.movingwin(1) * 1000));
set(handles.StepSize,'String',num2str(handles.movingwin(2) * 1000));
set(handles.TW,'String',num2str(handles.tapers(1)));
set(handles.MinFreq,'String',num2str(handles.fpass(1)));
set(handles.MaxFreq,'String',num2str(handles.fpass(2)));
set(handles.FixedCheckbox,'Value',handles.fixed);
% set(handles.ZoomLowerFreq,'Enable','off');
% set(handles.ZoomUpperFreq,'Enable','off');
% set(handles.ClassifiedWidth,'Enable','off');
% set(handles.ClassifiedHeight,'Enable','off');
% set(handles.Frequency,'Enable','off');
% set(handles.WinSize,'Enable','off');
% set(handles.StepSize,'Enable','off');
% set(handles.TW,'Enable','off');
% set(handles.MinFreq,'Enable','off');
% set(handles.MaxFreq,'Enable','off');
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = configure_classify_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
close;
function WinSize_Callback(hObject, eventdata, handles)
% hObject handle to WinSize (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 WinSize as text
% str2double(get(hObject,'String')) returns contents of WinSize as a double
% --- Executes during object creation, after setting all properties.
function WinSize_CreateFcn(hObject, eventdata, handles)
% hObject handle to WinSize (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in OKButton.
function OKButton_Callback(hObject, eventdata, handles)
% hObject handle to OKButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
lowerfreq = str2num(get(handles.ZoomLowerFreq,'String')); % Lower frequency for zooming
upperfreq = str2num(get(handles.ZoomUpperFreq,'String')); % Upper frequency for zooming
classified_height = str2num(get(handles.ClassifiedHeight,'String')); % the height of the image in the classified axes
classified_width = str2num(get(handles.ClassifiedWidth,'String')); % the width of the image in the classified axes
Fs = str2num(get(handles.Frequency,'String')); % Frequency of audio sampling per second
winsizeS = str2num(get(handles.WinSize,'String')) / 1000;
stepS = str2num(get(handles.StepSize,'String')) / 1000;
movingwin = [winsizeS stepS]; % Size of the moving window in seconds; the first number is the window size and the second is the step size
tw = str2num(get(handles.TW,'String'));
fpasslower = str2num(get(handles.MinFreq,'String')); % Range of frequency sampling
fpassupper = str2num(get(handles.MaxFreq,'String'));
fpass = [fpasslower fpassupper];
ierror = 1; % Indicates no errors encountered
if isempty(classified_height) || (classified_height < 1)
ierror = 0;
end
if isempty(tw) || tw < 0
ierror = 0;
end
if isempty(lowerfreq) || lowerfreq < 0
ierror = 0;
end
if isempty(fpasslower) || fpasslower < 0
ierror = 0;
end
if isempty(fpassupper) || fpassupper < fpasslower
ierror = 0;
end
if isempty(upperfreq) || lowerfreq > upperfreq
ierror = 0;
end
if isempty(winsizeS) || winsizeS < 0
ierror = 0;
end
if isempty(stepS) || stepS < 0
ierror = 0
end
if isempty(tw) || tw < 0
ierror = 0
else
tapers = [tw,floor(2*tw-1)]; % Tapers for smoothing
end
fixed = get(handles.FixedCheckbox,'Value');
if ierror == 0
;
else
handles.output = {lowerfreq,upperfreq,classified_height,classified_width,Fs,movingwin,tapers,fpass,fixed};
guidata(hObject,handles);
uiresume(handles.figure1);
end
%uiresume;
%close;
% --- Executes on button press in CancelButton.
function CancelButton_Callback(hObject, eventdata, handles)
% hObject handle to CancelButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.output = 0;
guidata(hObject,handles);
uiresume(handles.figure1);
function StepSize_Callback(hObject, eventdata, handles)
% hObject handle to StepSize (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 StepSize as text
% str2double(get(hObject,'String')) returns contents of StepSize as a double
% --- Executes during object creation, after setting all properties.
function StepSize_CreateFcn(hObject, eventdata, handles)
% hObject handle to StepSize (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function TW_Callback(hObject, eventdata, handles)
% hObject handle to TW (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 TW as text
% str2double(get(hObject,'String')) returns contents of TW as a double
% --- Executes during object creation, after setting all properties.
function TW_CreateFcn(hObject, eventdata, handles)
% hObject handle to TW (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function MinFreq_Callback(hObject, eventdata, handles)
% hObject handle to MinFreq (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 MinFreq as text
% str2double(get(hObject,'String')) returns contents of MinFreq as a double
% --- Executes during object creation, after setting all properties.
function MinFreq_CreateFcn(hObject, eventdata, handles)
% hObject handle to MinFreq (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function MaxFreq_Callback(hObject, eventdata, handles)
% hObject handle to MaxFreq (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 MaxFreq as text
% str2double(get(hObject,'String')) returns contents of MaxFreq as a double
% --- Executes during object creation, after setting all properties.
function MaxFreq_CreateFcn(hObject, eventdata, handles)
% hObject handle to MaxFreq (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function ZoomLowerFreq_Callback(hObject, eventdata, handles)
% hObject handle to ZoomLowerFreq (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 ZoomLowerFreq as text
% str2double(get(hObject,'String')) returns contents of ZoomLowerFreq as a double
% --- Executes during object creation, after setting all properties.
function ZoomLowerFreq_CreateFcn(hObject, eventdata, handles)
% hObject handle to ZoomLowerFreq (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function ZoomUpperFreq_Callback(hObject, eventdata, handles)
% hObject handle to ZoomUpperFreq (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 ZoomUpperFreq as text
% str2double(get(hObject,'String')) returns contents of ZoomUpperFreq as a double
% --- Executes during object creation, after setting all properties.
function ZoomUpperFreq_CreateFcn(hObject, eventdata, handles)
% hObject handle to ZoomUpperFreq (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function ClassifiedWidth_Callback(hObject, eventdata, handles)
% hObject handle to ClassifiedWidth (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 ClassifiedWidth as text
% str2double(get(hObject,'String')) returns contents of ClassifiedWidth as a double
% --- Executes during object creation, after setting all properties.
function ClassifiedWidth_CreateFcn(hObject, eventdata, handles)
% hObject handle to ClassifiedWidth (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function ClassifiedHeight_Callback(hObject, eventdata, handles)
% hObject handle to ClassifiedHeight (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 ClassifiedHeight as text
% str2double(get(hObject,'String')) returns contents of ClassifiedHeight as a double
% --- Executes during object creation, after setting all properties.
function ClassifiedHeight_CreateFcn(hObject, eventdata, handles)
% hObject handle to ClassifiedHeight (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function Frequency_Callback(hObject, eventdata, handles)
% hObject handle to Frequency (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 Frequency as text
% str2double(get(hObject,'String')) returns contents of Frequency as a double
% --- Executes during object creation, after setting all properties.
function Frequency_CreateFcn(hObject, eventdata, handles)
% hObject handle to Frequency (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes on button press in FixedCheckbox.
function FixedCheckbox_Callback(hObject, eventdata, handles)
% hObject handle to FixedCheckbox (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 FixedCheckbox
handles.fixed = get(hObject,'Value');
guidata(gcbo,handles);
|
github
|
BottjerLab/Acoustic_Similarity-master
|
FAnalyze.m
|
.m
|
Acoustic_Similarity-master/code/chronux/fly_track/FAnalyze/functions/FAnalyze.m
| 27,521 |
utf_8
|
3a1409d90fce239af9d011484fe9c3f7
|
function varargout = FAnalyze(varargin)
% FANALYZE
% For all your trajectory analysis needs! . See documentation for usage details.
%Written by Dan Valente
%November 2007
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @FAnalyze_OpeningFcn, ...
'gui_OutputFcn', @FAnalyze_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 FAnalyze is made visible.
function FAnalyze_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 FAnalyze (see VARARGIN)
% Choose default command line output for FAnalyze
handles.output = hObject;
handles.called = 0;
disp('Welcome to FAnalyze!')
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes FAnalyze wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = FAnalyze_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 ws_vars.
function ws_vars_Callback(hObject, eventdata, handles)
% hObject handle to ws_vars (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns ws_vars contents as cell array
% contents{get(hObject,'Value')} returns selected item from ws_vars
% --- Executes during object creation, after setting all properties.
function ws_vars_CreateFcn(hObject, eventdata, handles)
% hObject handle to ws_vars (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
function bins_Callback(hObject, eventdata, handles)
% hObject handle to bins (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 bins as text
% str2double(get(hObject,'String')) returns contents of bins as a double
% --- Executes during object creation, after setting all properties.
function bins_CreateFcn(hObject, eventdata, handles)
% hObject handle to bins (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 view_dist.
function view_dist_Callback(hObject, eventdata, handles)
% hObject handle to view_dist (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.called = handles.called+1;
index_selected = get(handles.ws_vars,'Value');
bins = get(handles.bins,'String');
phase_opt = get(get(handles.phase_space,'SelectedObject'), 'Tag');
if (length(index_selected) == 1)
var1 = get_var_names(handles);
u = strfind(var1,'_');
cur_zone1 = var1(u(1)+1:u(2)-1);
cur_zone1 = strmatch(cur_zone1, handles.zone_names,'exact');
cur_seg1 = var1(u(2)+1:end);
cur_seg1 = strmatch(cur_seg1, handles.zone{cur_zone1}.seg_label,'exact');
cur_var1 = var1(1:strfind(var1,'_')-1);
if strcmp(phase_opt,'phase1D')
P.label = var1;
P.phase_opt = phase_opt;
[P.data P.bins] = eval(['ProbDist1D(handles.zone{' num2str(cur_zone1) '}.' cur_var1 ...
'{' num2str(cur_seg1) '}.data ,' bins ')']);
elseif strcmp(phase_opt,'phase2D')
P.label = var1;
P.phase_opt = phase_opt;
[P.data P.bins] = eval(['ProbDist2D(handles.zone{' num2str(cur_zone1) '}.' cur_var1...
'{' num2str(cur_seg1) '}.data ,' bins ')']);
end
%plot the distribution
figure
plot(P.bins,P.data)
elseif (length(index_selected) == 2)
% should only look at joint distribution for same speed segments in
% same zones right now. The JointDist command expects equal length
% vectors. The following variables are just calculated in case we
% modify JointDist down the road to handle vectors of different
% lengths.
if numel(str2num(bins)) == 2 | numel(str2num(bins))== 0
[var1 var2] = get_var_names(handles);
u1 = strfind(var1,'_');
u2 = strfind(var2,'_');
cur_zone1 = var1(u1(1)+1:u1(2)-1);
cur_zone1 = strmatch(cur_zone1, handles.zone_names,'exact');
cur_zone2 = var2(u2(1)+1:u2(2)-1);
cur_zone2 = strmatch(cur_zone2, handles.zone_names,'exact');
cur_seg1 = var1(u1(2)+1:end);
cur_seg1 = strmatch(cur_seg1, handles.zone{cur_zone1}.seg_label,'exact');
cur_seg2 = var2(u2(2)+1:end);
cur_seg2 = strmatch(cur_seg2, handles.zone{cur_zone2}.seg_label,'exact');
cur_var1 = var1(1:strfind(var1,'_')-1);
cur_var2 = var2(1:strfind(var2,'_')-1);
P.label = [var1 '_' var2];
P.phase_opt = 'N/A';
[P.data P.bins] = eval(['JointDist(handles.zone{' num2str(cur_zone1) '}.' cur_var1...
'{' num2str(cur_seg1) '}.data , handles.zone{' num2str(cur_zone2) '}.' cur_var2...
'{' num2str(cur_seg2) '}.data ,' bins ')']);
figure
imagesc(P.bins{2},P.bins{1},log(P.data))
else
errordlg('For a joint distribution, you must define bins or number of bins for BOTH directions!','Missing Bin Parameter')
return;
end
elseif length(index_selected) > 2
errordlg('You must select only one or two variables, no more than two!!!',...
'Incorrect Selection','modal')
end
if exist('P')
handles.P{handles.called} = P;
else
handles.P{handles.called} = [];
end
guidata(gcbo,handles);
% --- Executes on button press in segment_speed.
function segment_speed_Callback(hObject, eventdata, handles)
% hObject handle to segment_speed (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
noise_thresh = str2num(get(handles.noise_thresh,'String'));
NumZones = length(handles.zone_names);
list1 = {'x','y','r','theta','vx','vy','v','vtheta','tau','kappa','beta'};
fps = handles.fps;
disp('Segmenting speed. Input parameters and wait...')
%based on how many spatial zones, ask how we want to segment speed.
%Remember that first zone is always the full arena.
n=0;
for i=1:NumZones
prompt1 = {['How many speed segments in ' handles.zone{i}.zone_label{1}]};
dlg_title1 = 'Segment Speed';
num_lines1 = 1;
def1 = {'2'};
num_segs = str2double(inputdlg(prompt1,dlg_title1,num_lines1,def1));
nameB4 = 'dummy';
seg_names = [];
speed_thresh = noise_thresh;
for j=1:num_segs-1;
prompt2 = {['Threshold between Segments ' num2str(j), ' and ' num2str(j+1) '.'],...
'Names for these zones:', ' '};
dlg_title2 = 'Please Input Speed Segmentation Data';
num_lines2 = 1;
def2 = {'0.75','NZS','FSS'};
answer = inputdlg(prompt2,dlg_title2,num_lines2,def2);
speed_thresh = [speed_thresh str2double(answer(1))];
nameA = answer(2);
nameB = answer(3);
check = strcmp(nameA,nameB4);
if (j~=1 & ~check)
errordlg([handles.zone{i}.zone_label{1} ' Segment ' num2str(j)...
' name must be same as previous ' handles.zone{i}.zone_label{1} ' Segment '...
num2str(j) ' name! Rename!'])
return;
else
seg_names = [seg_names nameA nameB];
end
nameB4 = nameB;
end
if (num_segs == 1 | num_segs == 2)
seg_names = seg_names;
elseif (num_segs== 3)
seg_names = [seg_names(1:2) seg_names(end)];
else
seg_names = [seg_names(1:2) seg_names(end-1:end)];
end
%check speed thresholds in that zone
[s indx] = sort(speed_thresh,'ascend');
if (indx ~= [1:length(speed_thresh)])
errordlg(['Speed thresholds for successive segments should be larger than previous segments. Try Again!'])
return;
elseif (~isempty(find(s < noise_thresh)))
errordlg(['None of the thresholds are permitted to be below the noise threshold. Try Again!'])
return;
end
seg_names = [{'all'} {'stops'} seg_names];
for q=1:length(seg_names)
for j=1:length(list1)
if (strcmp(seg_names{q},'all') & strcmp(list1{j},'kappa')) | ...
(strcmp(seg_names{q},'all') & strcmp(list1{j},'tau'))
temp_list{j,q+n*length(seg_names)} = [];
elseif (strcmp(seg_names{q},'stops') & strcmp(list1{j},'kappa')) | ...
(strcmp(seg_names{q},'stops') & strcmp(list1{j},'beta'))
temp_list{j,q+n*length(seg_names)} = [];
elseif ~strcmp(seg_names{q},'all') & strcmp(list1{j},'beta')
temp_list{j,q+n*length(seg_names)} = [];
else
temp_list{j,q+n*length(seg_names)} = [list1{j} '_' handles.zone{i}.zone_label{1} '_' seg_names{q}];
end
end
end
%calculate stuff for this particular zone
t = handles.zone{i}.t{1}.data;
x = handles.zone{i}.x{1}.data;
y = handles.zone{i}.y{1}.data;
r = handles.zone{i}.r{1}.data;
theta = handles.zone{i}.theta{1}.data;
vx = handles.zone{i}.vx{1}.data;
vy = handles.zone{i}.vy{1}.data;
v = handles.zone{i}.v{1}.data;
vtheta =handles.zone{i}.vtheta{1}.data;
stops_indx = find(v < speed_thresh(1));
moves_indx = find(v >= speed_thresh(1));
v(stops_indx) = 0; vx(stops_indx) = 0; vy(stops_indx) = 0; vtheta = atan2(vy,vx);
handles.zone{i}.seg_label = seg_names;
handles.zone{i}.t{2}.data = t(stops_indx);
handles.zone{i}.x{2}.data = x(stops_indx);
handles.zone{i}.y{2}.data = y(stops_indx);
handles.zone{i}.r{2}.data = r(stops_indx);
handles.zone{i}.theta{2}.data = theta(stops_indx);
handles.zone{i}.vx{2}.data = vx(stops_indx);
handles.zone{i}.vy{2}.data = vy(stops_indx);
handles.zone{i}.v{2}.data = v(stops_indx);
handles.zone{i}.vtheta{2}.data = vtheta(stops_indx);
handles.zone{i}.tau{2}.data = FindDuration(stops_indx);
handles.zone{i}.kappa{2}.data = 'N/A';
for j=2:length(speed_thresh)
indxA = find(v >= speed_thresh(j-1) & v < speed_thresh(j));
indxB = find(v >= speed_thresh(j));
handles.zone{i}.t{j+1}.data = t(indxA);
handles.zone{i}.x{j+1}.data = x(indxA);
handles.zone{i}.y{j+1}.data = y(indxA);
handles.zone{i}.r{j+1}.data = r(indxA);
handles.zone{i}.theta{j+1}.data = theta(indxA);
handles.zone{i}.vx{j+1}.data = vx(indxA);
handles.zone{i}.vy{j+1}.data = vy(indxA);
handles.zone{i}.v{j+1}.data = v(indxA);
handles.zone{i}.vtheta{j+1}.data = vtheta(indxA);
handles.zone{i}.tau{j+1}.data = FindDuration(indxA);
handles.zone{i}.kappa{j+1}.data = CalcCurvature(v, vtheta, indxA, 1/fps);
handles.zone{i}.t{j+2}.data = t(indxB);
handles.zone{i}.x{j+2}.data = x(indxB);
handles.zone{i}.y{j+2}.data = y(indxB);
handles.zone{i}.r{j+2}.data = r(indxB);
handles.zone{i}.theta{j+2}.data = theta(indxB);
handles.zone{i}.vx{j+2}.data = vx(indxB);
handles.zone{i}.vy{j+2}.data = vy(indxB);
handles.zone{i}.v{j+2}.data = v(indxB);
handles.zone{i}.vtheta{j+2}.data = vtheta(indxB);
handles.zone{i}.tau{j+2}.data = FindDuration(indxB);
handles.zone{i}.kappa{j+2}.data = CalcCurvature(v, vtheta, indxB, 1/fps);
end
handles.zone{i}.beta{1}.data = CalcReorientAngle(vtheta, moves_indx);
n=n+1;
end
temp3 = {};
sz = size(temp_list);
for q=1:sz(2)
temp3 = [temp3 temp_list{:,q}];
end
disp('Speed has been segmented.')
update_listbox(handles, temp3)
guidata(gcbo,handles);
% --- Executes on button press in load_traj.
function load_traj_Callback(hObject, eventdata, handles)
% hObject handle to load_traj (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile({'*.mat'}, 'Select the .mat file containing the trajectory', 'MultiSelect','off');
if isequal(filename,0) || isequal(pathname,0)
disp('File select canceled')
return;
else
disp(['File selected: ', fullfile(pathname, filename)])
load(fullfile(pathname,filename));
handles.filename = fullfile(pathname, filename);
end
handles.zone{1}.t{1}.data = t;
handles.fps = 1/(t(2)-t(1));
handles.zone{1}.x{1}.data = x;
handles.zone{1}.y{1}.data = y;
guidata(gcbo,handles);
% --- Executes on button press in smooth.
function smooth_Callback(hObject, eventdata, handles)
% hObject handle to smooth (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%grab data
t = handles.zone{1}.t{1}.data;
fps = handles.fps;
x = handles.zone{1}.x{1}.data;
y = handles.zone{1}.y{1}.data;
handles.P = [];
%grab smoothing parameters as input by the user
n = str2double(get(handles.n,'String'));
dn = str2double(get(handles.dn,'String'));
disp('Smoothing data. Please wait...')
%smooth using runline
x = runline(x, n, dn);
y = runline(y, n, dn);
%Calculate polar coords and velocity.
r = sqrt(x.^2+y.^2);
theta = atan2(y,x);
vx = fps*gradient(x);
vy = fps*gradient(y);
v = sqrt(vx.^2+vy.^2);
vtheta = atan2(vy,vx);
clear handles.x;
clear handles.y;
%save smooth data to handles to be used by other GUI functions
handles.zone_names{1} = 'Full Arena';
handles.zone{1}.zone_label = {'Full Arena'};
handles.zone{1}.seg_label = {'all'};
handles.zone{1}.t{1}.data = t;
handles.zone{1}.x{1}.data = x;
handles.zone{1}.y{1}.data = y;
handles.zone{1}.r{1}.data = r;
handles.zone{1}.theta{1}.data = theta;
handles.zone{1}.vx{1}.data = vx;
handles.zone{1}.vy{1}.data = vy;
handles.zone{1}.v{1}.data = v;
handles.zone{1}.vtheta{1}.data = vtheta;
handles.zone{1}.tau{1}.data = 'N/A';
handles.zone{1}.kappa{1}.data = 'N/A';
disp('Trajectory has been smoothed.')
update_listbox(handles, {'x_Full Arena_all','y_Full Arena_all','r_Full Arena_all','theta_Full Arena_all',...
'vx_Full Arena_all','vy_Full Arena_all','v_Full Arena_all','vtheta_Full Arena_all'});
guidata(gcbo,handles);
function n_Callback(hObject, eventdata, handles)
% hObject handle to n (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 n as text
% str2double(get(hObject,'String')) returns contents of n as a double
% --- Executes during object creation, after setting all properties.
function n_CreateFcn(hObject, eventdata, handles)
% hObject handle to n (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 dn_Callback(hObject, eventdata, handles)
% hObject handle to dn (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 dn as text
% str2double(get(hObject,'String')) returns contents of dn as a double
% --- Executes during object creation, after setting all properties.
function dn_CreateFcn(hObject, eventdata, handles)
% hObject handle to dn (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 view_traj.
function view_traj_Callback(hObject, eventdata, handles)
% hObject handle to view_traj (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
t = handles.zone{1}.t{1}.data;
x = handles.zone{1}.x{1}.data;
y = handles.zone{1}.y{1}.data;
tmp = getfield(handles, 'zone');
if (isfield(tmp{1},'r'))
r = handles.zone{1}.r{1}.data;
theta = handles.zone{1}.theta{1}.data;
vx = handles.zone{1}.vx{1}.data;
vy = handles.zone{1}.vy{1}.data;
v = handles.zone{1}.v{1}.data;
vtheta =handles.zone{1}.vtheta{1}.data;
end
str = get(handles.variables, 'String');
val = get(handles.variables, 'Value');
% Set current data to the selected data set.
if strcmp(str(val),'(x,y)')
figure
plot(x,y)
xlabel('x-position')
ylabel('y-position')
title('Trajectory')
if (~isfield(tmp{1},'r'))
disp('You can view your trajectory, but you MUST smooth your data before proceeding with any calculations!')
end
else
var1 = 't';
if exist(str{val})
figure
var2 = str{val};
eval(['plot(' var1 ',' var2 ')'])
xlabel('Time')
ylabel(var2)
xlim([0 t(end)])
else
errordlg('Can"t view this variable unless data is smoothed','Non-existant Variable')
return;
end
end
% --- Executes on selection change in variables.
function variables_Callback(hObject, eventdata, handles)
% hObject handle to variables (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns variables contents as cell array
% contents{get(hObject,'Value')} returns selected item from variables
set(hObject,'String',{'(x,y)','x','y','r','theta','vx','vy','v','vtheta'})
guidata(gcbo,handles);
% --- Executes during object creation, after setting all properties.
function variables_CreateFcn(hObject, eventdata, handles)
% hObject handle to variables (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
set(hObject,'String',{'(x,y)','x','y','r','theta','vx','vy','v','vtheta'})
guidata(gcbo,handles);
% --- Executes on button press in segment_space.
function segment_space_Callback(hObject, eventdata, handles)
% hObject handle to segment_space (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
NumZones = str2double(get(handles.num_zones,'String'));
if NumZones < 2
errordlg('Must have at least 2 zones','Too few zones')
return;
end
zone_indx = 1:NumZones;
list1 = {'x','y','r','theta','vx','vy','v','vtheta','tau','kappa'};
zone_names = handles.zone_names;
handles.zone_names = {};
handles.zone_names{1} = 'Full Arena';
t = handles.zone{1}.t{1}.data;
dt = t(2)-t(1);
x = handles.zone{1}.x{1}.data;
y = handles.zone{1}.y{1}.data;
r = handles.zone{1}.r{1}.data;
theta = handles.zone{1}.theta{1}.data;
vx = handles.zone{1}.vx{1}.data;
vy = handles.zone{1}.vy{1}.data;
v = handles.zone{1}.v{1}.data;
vtheta =handles.zone{1}.vtheta{1}.data;
disp('Segmenting Space. Input parameters and wait...')
thresh(1) = 0;
for i=1:NumZones-1
prompt = {['Threshold between Zones ' num2str(zone_indx(i)), ' and ' num2str(zone_indx(i+1)) '.'],...
'Names for these zones:', ' '};
dlg_title = 'Please Input Spatial Zone Data';
num_lines = 1;
def = {'7.3','CZ','RZ'};
answer{i} = inputdlg(prompt,dlg_title,num_lines,def);
thresh(i+1) = str2double(answer{i}(1));
end
zone_names = [zone_names answer{1}(2)];
for i=1:NumZones-2
nameA = answer{i}(2);
nameB = answer{i}(3);
nameC = answer{i+1}(2);
if (~strcmp(nameB,nameC))
errordlg(['Zone ' num2str(i+1) ' name must be same as previous Zone ' num2str(i+1) ' name! Rename!'])
else
zone_names = [zone_names nameB];
end
end
zone_names = [zone_names answer{NumZones-1}(3)];
for i=1:length(zone_names)
for j=1:length(list1)
if strcmp(zone_names{i},'Full Arena') & (strcmp(list1{j},'kappa') | strcmp(list1{j},'tau'))
temp_list{j,i} = [];
elseif strcmp(list1{j},'kappa')
temp_list{j,i} = [];
else
temp_list{j,i} = [list1{j} '_' zone_names{i} '_all'];
end
end
end
temp3 = {};
for i=1:NumZones+1
temp3 = [temp3 temp_list{:,i}];
end
handles.zone_names = zone_names;
%Now using thresholds, divvy up space
for i = 2:length(thresh)
% Can only do radial zones in this version of FAnalyze
indxA = find(r >= thresh(i-1) & r < thresh(i));
indxB = find(r >= thresh(i));
handles.zone{i}.zone_label = zone_names(i);
handles.zone{i}.seg_label = {'all'};
handles.zone{i}.t{1}.data = t(indxA);
handles.zone{i}.x{1}.data = x(indxA);
handles.zone{i}.y{1}.data = y(indxA);
handles.zone{i}.r{1}.data = r(indxA);
handles.zone{i}.theta{1}.data = theta(indxA);
handles.zone{i}.vx{1}.data = vx(indxA);
handles.zone{i}.vy{1}.data = vy(indxA);
handles.zone{i}.v{1}.data = v(indxA);
handles.zone{i}.vtheta{1}.data = vtheta(indxA);
handles.zone{i}.tau{1}.data = FindDuration(indxA);
handles.zone{i}.kappa{1}.data = CalcCurvature(v, vtheta, indxA, dt);
handles.zone{i+1}.zone_label = zone_names(i+1);
handles.zone{i+1}.seg_label = {'all'};
handles.zone{i+1}.t{1}.data = t(indxB);
handles.zone{i+1}.x{1}.data = x(indxB);
handles.zone{i+1}.y{1}.data = y(indxB);
handles.zone{i+1}.r{1}.data = r(indxB);
handles.zone{i+1}.theta{1}.data = theta(indxB);
handles.zone{i+1}.vx{1}.data = vx(indxB);
handles.zone{i+1}.vy{1}.data = vy(indxB);
handles.zone{i+1}.v{1}.data = v(indxB);
handles.zone{i+1}.vtheta{1}.data = vtheta(indxB);
handles.zone{i+1}.tau{1}.data = FindDuration(indxB);
handles.zone{i+1}.kappa{1}.data = CalcCurvature(v, vtheta, indxB, dt);
end
update_listbox(handles, temp3)
disp('Space has been segmented.')
guidata(gcbo,handles);
% --- Executes on button press in save_ws.
function save_ws_Callback(hObject, eventdata, handles)
% hObject handle to save_ws (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% %This whole function just defines variables and saves the workspace as a
% %.mat file.
[filename, pathname] = uiputfile('*.mat', 'Pick a MAT file to save to');
traj = handles.zone;
P = handles.P;
fps = handles.fps;
save(fullfile(pathname, filename),'traj','P')
disp(['Data has been saved to ' fullfile(pathname, filename)])
function update_listbox(handles, vars)
% this function updates the message center at the bottom of the GUI
% adapted from Mike Rieser's PControl GUI.
set(handles.ws_vars, 'String', vars);
%%%%%%%%%%%%%%%%
function varargout = get_var_names(handles)
list_entries = get(handles.ws_vars,'String');
index_selected = get(handles.ws_vars,'Value');
varargout = list_entries(index_selected);
function num_zones_Callback(hObject, eventdata, handles)
% hObject handle to num_zones (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 num_zones as text
% str2double(get(hObject,'String')) returns contents of num_zones as a double
% --- Executes during object creation, after setting all properties.
function num_zones_CreateFcn(hObject, eventdata, handles)
% hObject handle to num_zones (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 noise_thresh_Callback(hObject, eventdata, handles)
% hObject handle to noise_thresh (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 noise_thresh as text
% str2double(get(hObject,'String')) returns contents of noise_thresh as a double
% --- Executes during object creation, after setting all properties.
function noise_thresh_CreateFcn(hObject, eventdata, handles)
% hObject handle to noise_thresh (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
|
BottjerLab/Acoustic_Similarity-master
|
videoReader.m
|
.m
|
Acoustic_Similarity-master/code/chronux/fly_track/videoIO/videoIO_2006b/@videoReader/videoReader.m
| 5,622 |
utf_8
|
ae0c7daa1ec7e2618347338bff619af5
|
function vr = videoReader(url, varargin)
% videoReader class constructor
% Creates a object that reads video streams. We use a plugin
% architecture in the backend to do the actual reading. For example,
% on Windows, DirectShow will typically be used and on Linux, the
% ffmpeg library is often used.
%
% vr = videoReader(url)
% Opens the given video file for reading using the default plugin.
% On Windows, 'DirectShow' is used by default and on Linux,
% 'ffmpegPopen2' is used by default. For most plugins, the url will
% really be a filename.
%
% vr = videoReader(url, ..., 'plugin',pluginName, ...)
% vr = videoReader(url,pluginName, ...)
% Opens the file using the manually specified plugin implementation.
% Available plugins include:
%
% 'DirectShow': preferred method on Windows
% - Only available on Windows
% - See INSTALL.dshow.txt for installation instructions
% - Can load virtually any video file that can be played in
% Microsoft's Windows Media Player. Note that the correct codec
% must be installed to read a file. For example, to read
% tests/numbers.3ivx.avi, the user must have installed an MPEG4
% codec such as 3ivx (www.3ivx.com), DivX (www.divx.com), or XviD
% (www.xvid.org).
% - The URL parameter should be a filename.
% - As a convenience, all forward slashes ('/') are automatically
% converted to backslashes ('\')
%
% 'ffmpegPopen2': safe method on Linux
% - Only supported on GNU/Linux (might work on BSD systems too like Mac
% OS X, but this is untested)
% - See INSTALL.ffmpeg.txt for installation instructions
% - Creates a separate server process to communicate with the
% ffmpeg libraries.
% - Works when the system's version of GCC is very different from
% the one that MathWorks used to compile Matlab.
% - Isolates ffmpeg errors so they typically cannot crash
% Matlab.
% - May allow for more flexible distribution terms for your code
% when it uses videoIO (ffmpeg may be compiled with either
% the LGPL or GPL license).
%
% 'ffmpegDirect': low-overhead method on Linux
% - same as ffmpegPopen2, but the ffmpeg libraries are loaded
% directly by the MEX file.
% - May not work if MathWorks' and your version of GCC are
% incompatible.
% - Slightly faster than ffmpegPopen2 since there is no
% interprocess communication overhead.
%
% vr = videoReader(url, ..., param,arg,...)
% Allows the user to pass extra configuration arguments to plugin.
% Currently no plugin arguments are supported right now. In the
% future, we may allow the user to do things like have DirectShow
% automatically convert to grayscale, or give options to trade off
% speed with seeking precision.
%
% Once you have created a videoReader object, you must next call NEXT,
% SEEK, or STEP at least once so that it will read some frame from disk.
% *After* calling one of these methods, you may call GETFRAME as many
% times as you would like and it will decode and return the current frame
% (without advancing to a different frame). GETINFO may be called at any
% time (even before NEXT, SEEK, or STEP). It returns basic information
% about the video stream. Once you are done using the videoReader, make
% sure you call CLOSE so that any system resources allocated by the plugin
% may be released. Here's a simple example of how you might use
% videoReader:
%
% % take us to the videoReader directory since we know there's a video
% % file there.
% chdir(fileparts(which('videoReaderWrapper.cpp')));
%
% % Construct a videoReader object
% vr = videoReader('tests/numbers.uncompressed.avi');
%
% % Do some processing on the video and display the results
% avgIntensity = [];
% i = 1;
% figure;
% while (next(vr))
% img = getframe(vr);
% avgIntensity(i) = mean(img(:));
% subplot(121); imshow(img); title('current frame');
% subplot(122); plot(avgIntensity); title('avg. intensity vs. frame');
% drawnow; pause(0.1); i = i+1;
% end
% vr = close(vr);
%
% SEE ALSO:
% buildVideoMex
% videoReader/close
% videoReader/getframe
% videoReader/getinfo
% videoReader/getnext
% videoReader/next
% videoReader/seek
% videoReader/step
% videoWriter
%
%Copyright (c) 2006 Gerald Dalley
%See "MIT.txt" in the installation directory for licensing details (especially
%when using this library on GNU/Linux).
if (mod(length(varargin),2) == 0)
plugin = defaultVideoIOPlugin;
pluginArgs = varargin;
else
plugin = varargin{1};
pluginArgs = {varargin{2:end}};
end
[plugin,pluginArgs] = parsePlugin(plugin, pluginArgs);
vr = struct('plugin',mexName(plugin), 'handle',int32(-1));
vr = class(vr, 'videoReader');
[pathstr, name, ext, versn] = fileparts(url);
strArgs = cell(size(pluginArgs));
for i=1:numel(pluginArgs), strArgs{i} = num2str(pluginArgs{i}); end
vr.handle = feval(vr.plugin, 'open', vr.handle, ...
fullfile(pathstr,[name ext versn]), strArgs{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n = mexName(plugin)
n = ['videoReader_' plugin];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [plugin,pluginArgs] = parsePlugin(plugin, pluginArgs)
if (length(pluginArgs) > 0)
[pluginSpecified,idx] = ismember('plugin', {pluginArgs{1:2:end}});
if pluginSpecified
plugin = pluginArgs{idx*2};
pluginArgs = { pluginArgs{1:idx*2-2}, pluginArgs{idx*2+1:end} };
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
videoWriter.m
|
.m
|
Acoustic_Similarity-master/code/chronux/fly_track/videoIO/videoIO_2006b/@videoWriter/videoWriter.m
| 11,246 |
utf_8
|
a6a2b6d2d9552d4c6e352fc015b8e3dd
|
function vw = videoWriter(url, varargin)
% videoWriter class constructor
% Creates a object that writes video files. We use a plugin
% architecture in the backend to do the actual writing. For example,
% on Windows, DirectShow will typically be used and on Linux, the
% ffmpeg library is often used.
%
% vw = videoWriter(url)
% Opens the given video file for writing using the default plugin.
% On Windows, 'DirectShow' is used by default and on Linux,
% 'ffmpegPopen2' is used by default. For most plugins, the url will
% really be a filename.
%
% vw = videoWriter(url,..., 'plugin',pluginName, ...)
% vw = videoWriter(url,pluginName)
% Opens the file using the specified plugin implementation.
% Available plugins include:
%
% 'DirectShow': preferred method on Windows
% - Only available on Windows
% - See INSTALL.dshow.txt for installation instructions
% - The URL parameter should be a filename.
% - As a convenience, all forward slashes ('/') are automatically
% converted to backslashes ('\')
%
% 'ffmpegPopen2': safe method on Linux
% - Only supported on GNU/Linux (might work on BSD systems too like Mac
% OS X, but this is untested)
% - See INSTALL.ffmpeg.txt for installation instructions
% - Creates a separate server process to communicate with the
% ffmpeg libraries.
% - Works when the system's version of GCC is very different from
% the one that MathWorks used to compile Matlab.
% - Isolates ffmpeg errors so they typically cannot crash
% Matlab.
% - May allow for more flexible distribution terms for your code
% when it uses videoIO (ffmpeg may be compiled with either
% the LGPL or GPL license).
%
% 'ffmpegDirect': low-overhead method on Linux
% - same as ffmpegPopen2, but the ffmpeg libraries are loaded
% directly by the MEX file.
% - May not work if MathWorks' and your version of GCC are
% incompatible.
% - Slightly faster than ffmpegPopen2 since there is no
% interprocess communication overhead.
%
% vw = videoWriter(url, ..., param,arg,...)
% Allows the user to pass extra configuration arguments to plugin.
% At present, all parameter names are case sensitive (but in the
% future they may become case-insensitive).
%
% The following parameters are supported by current plugins:
%
% Plugin
% Parameter ffmpeg* DShow Implementation Notes
% --------- ------- ----- -----------------------------
% width X X Width of the encoded video. Most
% codecs require width to be divisible
% by 2, 4, or 8. Most users will want
% to explicitly pass this parameter.
% The addframe method will
% automatically resize any images
% according to the value chosen here
% (or a default value if none is
% specified here).
%
% height X X Height of the encoded video. Most
% codecs require height to be divisible
% by 2, 4, or 8. Most users will want
% to explicitly pass this parameter.
% The addframe method will
% automatically resize any images
% according to the value chosen here
% (or a default value if none is
% specified here).
%
% codec X X A string specifying the encoder to
% use. The exact set of possible
% codecs is highly system-dependent.
% Most users will want to explicitly
% pass this parameter. To see a list
% of available codecs on a specific
% machine, run:
% codecs = videoWriter([],'codecs');
%
% fourcc X For the DirectShow plugin, this is a
% synonym for 'codec'.
%
% fps X X Frame rate of the recorded video.
% Note that some codecs only work with
% some frame rates. 15, 24, 25, 29.97,
% and 30 should work with most codecs.
%
% framesPerSecond X X An alias for fps.
%
% fpsNum, fpsDenom X X This pair of parameters allows frames
% per second to be specified as a
% rational number. Either both or
% neither parameter must be given.
%
% framesPerSecond_num Alias for fpsNum, fpsDenom pair.
% framesPerSecond_denom
% X X
%
% bitRateTolerance X For supporting codecs, the actual
% bit rate is allowed to vary by +/-
% this value.
%
% showCompressionDialog X If true (a non-zero number), a dialog
% box is presented to the user allowing
% precise manual selection of the codec
% and its parameters. Note: sometimes
% the dialog does not received focus
% automatically so you'll need to
% ALT-TAB to get to it.
%
% codecParams X A MIME Base64-encoded string describing
% the codec setup parameters for a
% DirectShow codec. The contents of this
% string are very codec-specific. Often,
% The best ways to come up with a string
% like this are to first create a
% videoWriter with the
% 'showCompressionDialog' option enabled,
% choose the desired settings, then use
% the GETINFO method to extract the
% 'codecParams' value. Note that this
% representation is the same as used by
% VirtualDub 1.6 and 1.7 in its Sylia
% Script files. Nearly all useful
% DirectShow codecs can only be
% configured with 'codecParams' and they
% ignore the separate 'bitRate' and
% 'gopSize' parameters given below.
%
% bitRate X x Target bits/sec of the encoded video.
% Supported by most ffmpeg codecs.
% To see whether a particular codec uses
% the bitRate parameter, run the
% testBitRate function in the tests/
% subdirectory (NOTE: very few DirectShow
% codecs support it).
%
% gopSize X x Maximum period between keyframes. GOP
% stands for "group of pictures" in MPEG
% lingo. Supported by most ffmpeg
% codecs. To see whether a particular
% codec uses the gopSize parameter, run
% the testGopSize function in the tests/
% subdirectory (NOTE: very few DirectShow
% codecs support it).
%
% maxBFrames X For MPEG codecs, gives the max
% number of bidirectional frames in a
% group of pictures (GOP).
%
% codecs = videoWriter([],'codecs')
% codecs = videoWriter([],pluginName,'codecs')
% codecs = videoWriter([],'codecs','plugin',pluginName)
% Queries the backend for a list of the valid codecs that may be used
% with the 'codec' plugin parameter.
%
% Once you are done using the videoWriter, make sure you call CLOSE so
% that any system resources allocated by the plugin may be released.
% Here's a simple example of how you might use videoWriter to create
% a video of continually adding more motion blur to an image:
%
% % Construct a videoWriter object
% vw = videoWriter('writertest.avi', ...
% 'width',320, 'height',240, 'codec','xvid');
% img = imread('peppers.png');
% h = fspecial('motion',10,5);
% for i=1:100
% addframe(vw, img);
% img = imfilter(img, h);
% end
% vw=close(vw);
%
% SEE ALSO:
% buildVideoMex
% videoWriter/addframe
% videoWriter/close
% videoReader
%
%Copyright (c) 2006 Gerald Dalley
%See "MIT.txt" in the installation directory for licensing details (especially
%when using this library on GNU/Linux).
if (numel(url)==0)
% static method call
if (mod(length(varargin),2) == 0)
plugin = varargin{1};
staticMethod = varargin{2};
methodArgs = {varargin{3:end}};
else
plugin = defaultVideoIOPlugin;
staticMethod = varargin{1};
methodArgs = {varargin{2:end}};
end
[plugin,methodArgs] = parsePlugin(plugin, methodArgs);
vw = feval(mexName(plugin), staticMethod, int32(-1), methodArgs{:});
else
% constructor call
if (mod(length(varargin),2) == 0)
plugin = defaultVideoIOPlugin;
pluginArgs = varargin;
else
plugin = varargin{1};
pluginArgs = {varargin{2:end}};
end
plugin = parsePlugin(plugin, pluginArgs);
vw = struct('plugin',mexName(plugin), 'handle',int32(-1), ...
'w',int32(-1), 'h',int32(-1));
vw = class(vw, 'videoWriter');
[pathstr, name, ext, versn] = fileparts(url);
strArgs = cell(size(pluginArgs));
for i=1:numel(pluginArgs), strArgs{i} = num2str(pluginArgs{i}); end
[vw.handle,vw.w,vw.h] = feval(vw.plugin, 'open', vw.handle, ...
fullfile(pathstr,[name ext versn]), ...
strArgs{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n = mexName(plugin)
n = ['videoWriter_' plugin];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [plugin,pluginArgs] = parsePlugin(plugin, pluginArgs)
if (length(pluginArgs) > 0)
[pluginSpecified,idx] = ismember('plugin', {pluginArgs{1:2:end}});
if pluginSpecified
plugin = pluginArgs{idx*2};
pluginArgs = { pluginArgs{1:idx*2-2}, pluginArgs{idx*2+1:end} };
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
videoReader.m
|
.m
|
Acoustic_Similarity-master/code/chronux/fly_track/videoIO/videoIO_2006a/@videoReader/videoReader.m
| 5,622 |
utf_8
|
ae0c7daa1ec7e2618347338bff619af5
|
function vr = videoReader(url, varargin)
% videoReader class constructor
% Creates a object that reads video streams. We use a plugin
% architecture in the backend to do the actual reading. For example,
% on Windows, DirectShow will typically be used and on Linux, the
% ffmpeg library is often used.
%
% vr = videoReader(url)
% Opens the given video file for reading using the default plugin.
% On Windows, 'DirectShow' is used by default and on Linux,
% 'ffmpegPopen2' is used by default. For most plugins, the url will
% really be a filename.
%
% vr = videoReader(url, ..., 'plugin',pluginName, ...)
% vr = videoReader(url,pluginName, ...)
% Opens the file using the manually specified plugin implementation.
% Available plugins include:
%
% 'DirectShow': preferred method on Windows
% - Only available on Windows
% - See INSTALL.dshow.txt for installation instructions
% - Can load virtually any video file that can be played in
% Microsoft's Windows Media Player. Note that the correct codec
% must be installed to read a file. For example, to read
% tests/numbers.3ivx.avi, the user must have installed an MPEG4
% codec such as 3ivx (www.3ivx.com), DivX (www.divx.com), or XviD
% (www.xvid.org).
% - The URL parameter should be a filename.
% - As a convenience, all forward slashes ('/') are automatically
% converted to backslashes ('\')
%
% 'ffmpegPopen2': safe method on Linux
% - Only supported on GNU/Linux (might work on BSD systems too like Mac
% OS X, but this is untested)
% - See INSTALL.ffmpeg.txt for installation instructions
% - Creates a separate server process to communicate with the
% ffmpeg libraries.
% - Works when the system's version of GCC is very different from
% the one that MathWorks used to compile Matlab.
% - Isolates ffmpeg errors so they typically cannot crash
% Matlab.
% - May allow for more flexible distribution terms for your code
% when it uses videoIO (ffmpeg may be compiled with either
% the LGPL or GPL license).
%
% 'ffmpegDirect': low-overhead method on Linux
% - same as ffmpegPopen2, but the ffmpeg libraries are loaded
% directly by the MEX file.
% - May not work if MathWorks' and your version of GCC are
% incompatible.
% - Slightly faster than ffmpegPopen2 since there is no
% interprocess communication overhead.
%
% vr = videoReader(url, ..., param,arg,...)
% Allows the user to pass extra configuration arguments to plugin.
% Currently no plugin arguments are supported right now. In the
% future, we may allow the user to do things like have DirectShow
% automatically convert to grayscale, or give options to trade off
% speed with seeking precision.
%
% Once you have created a videoReader object, you must next call NEXT,
% SEEK, or STEP at least once so that it will read some frame from disk.
% *After* calling one of these methods, you may call GETFRAME as many
% times as you would like and it will decode and return the current frame
% (without advancing to a different frame). GETINFO may be called at any
% time (even before NEXT, SEEK, or STEP). It returns basic information
% about the video stream. Once you are done using the videoReader, make
% sure you call CLOSE so that any system resources allocated by the plugin
% may be released. Here's a simple example of how you might use
% videoReader:
%
% % take us to the videoReader directory since we know there's a video
% % file there.
% chdir(fileparts(which('videoReaderWrapper.cpp')));
%
% % Construct a videoReader object
% vr = videoReader('tests/numbers.uncompressed.avi');
%
% % Do some processing on the video and display the results
% avgIntensity = [];
% i = 1;
% figure;
% while (next(vr))
% img = getframe(vr);
% avgIntensity(i) = mean(img(:));
% subplot(121); imshow(img); title('current frame');
% subplot(122); plot(avgIntensity); title('avg. intensity vs. frame');
% drawnow; pause(0.1); i = i+1;
% end
% vr = close(vr);
%
% SEE ALSO:
% buildVideoMex
% videoReader/close
% videoReader/getframe
% videoReader/getinfo
% videoReader/getnext
% videoReader/next
% videoReader/seek
% videoReader/step
% videoWriter
%
%Copyright (c) 2006 Gerald Dalley
%See "MIT.txt" in the installation directory for licensing details (especially
%when using this library on GNU/Linux).
if (mod(length(varargin),2) == 0)
plugin = defaultVideoIOPlugin;
pluginArgs = varargin;
else
plugin = varargin{1};
pluginArgs = {varargin{2:end}};
end
[plugin,pluginArgs] = parsePlugin(plugin, pluginArgs);
vr = struct('plugin',mexName(plugin), 'handle',int32(-1));
vr = class(vr, 'videoReader');
[pathstr, name, ext, versn] = fileparts(url);
strArgs = cell(size(pluginArgs));
for i=1:numel(pluginArgs), strArgs{i} = num2str(pluginArgs{i}); end
vr.handle = feval(vr.plugin, 'open', vr.handle, ...
fullfile(pathstr,[name ext versn]), strArgs{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n = mexName(plugin)
n = ['videoReader_' plugin];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [plugin,pluginArgs] = parsePlugin(plugin, pluginArgs)
if (length(pluginArgs) > 0)
[pluginSpecified,idx] = ismember('plugin', {pluginArgs{1:2:end}});
if pluginSpecified
plugin = pluginArgs{idx*2};
pluginArgs = { pluginArgs{1:idx*2-2}, pluginArgs{idx*2+1:end} };
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
videoWriter.m
|
.m
|
Acoustic_Similarity-master/code/chronux/fly_track/videoIO/videoIO_2006a/@videoWriter/videoWriter.m
| 11,246 |
utf_8
|
a6a2b6d2d9552d4c6e352fc015b8e3dd
|
function vw = videoWriter(url, varargin)
% videoWriter class constructor
% Creates a object that writes video files. We use a plugin
% architecture in the backend to do the actual writing. For example,
% on Windows, DirectShow will typically be used and on Linux, the
% ffmpeg library is often used.
%
% vw = videoWriter(url)
% Opens the given video file for writing using the default plugin.
% On Windows, 'DirectShow' is used by default and on Linux,
% 'ffmpegPopen2' is used by default. For most plugins, the url will
% really be a filename.
%
% vw = videoWriter(url,..., 'plugin',pluginName, ...)
% vw = videoWriter(url,pluginName)
% Opens the file using the specified plugin implementation.
% Available plugins include:
%
% 'DirectShow': preferred method on Windows
% - Only available on Windows
% - See INSTALL.dshow.txt for installation instructions
% - The URL parameter should be a filename.
% - As a convenience, all forward slashes ('/') are automatically
% converted to backslashes ('\')
%
% 'ffmpegPopen2': safe method on Linux
% - Only supported on GNU/Linux (might work on BSD systems too like Mac
% OS X, but this is untested)
% - See INSTALL.ffmpeg.txt for installation instructions
% - Creates a separate server process to communicate with the
% ffmpeg libraries.
% - Works when the system's version of GCC is very different from
% the one that MathWorks used to compile Matlab.
% - Isolates ffmpeg errors so they typically cannot crash
% Matlab.
% - May allow for more flexible distribution terms for your code
% when it uses videoIO (ffmpeg may be compiled with either
% the LGPL or GPL license).
%
% 'ffmpegDirect': low-overhead method on Linux
% - same as ffmpegPopen2, but the ffmpeg libraries are loaded
% directly by the MEX file.
% - May not work if MathWorks' and your version of GCC are
% incompatible.
% - Slightly faster than ffmpegPopen2 since there is no
% interprocess communication overhead.
%
% vw = videoWriter(url, ..., param,arg,...)
% Allows the user to pass extra configuration arguments to plugin.
% At present, all parameter names are case sensitive (but in the
% future they may become case-insensitive).
%
% The following parameters are supported by current plugins:
%
% Plugin
% Parameter ffmpeg* DShow Implementation Notes
% --------- ------- ----- -----------------------------
% width X X Width of the encoded video. Most
% codecs require width to be divisible
% by 2, 4, or 8. Most users will want
% to explicitly pass this parameter.
% The addframe method will
% automatically resize any images
% according to the value chosen here
% (or a default value if none is
% specified here).
%
% height X X Height of the encoded video. Most
% codecs require height to be divisible
% by 2, 4, or 8. Most users will want
% to explicitly pass this parameter.
% The addframe method will
% automatically resize any images
% according to the value chosen here
% (or a default value if none is
% specified here).
%
% codec X X A string specifying the encoder to
% use. The exact set of possible
% codecs is highly system-dependent.
% Most users will want to explicitly
% pass this parameter. To see a list
% of available codecs on a specific
% machine, run:
% codecs = videoWriter([],'codecs');
%
% fourcc X For the DirectShow plugin, this is a
% synonym for 'codec'.
%
% fps X X Frame rate of the recorded video.
% Note that some codecs only work with
% some frame rates. 15, 24, 25, 29.97,
% and 30 should work with most codecs.
%
% framesPerSecond X X An alias for fps.
%
% fpsNum, fpsDenom X X This pair of parameters allows frames
% per second to be specified as a
% rational number. Either both or
% neither parameter must be given.
%
% framesPerSecond_num Alias for fpsNum, fpsDenom pair.
% framesPerSecond_denom
% X X
%
% bitRateTolerance X For supporting codecs, the actual
% bit rate is allowed to vary by +/-
% this value.
%
% showCompressionDialog X If true (a non-zero number), a dialog
% box is presented to the user allowing
% precise manual selection of the codec
% and its parameters. Note: sometimes
% the dialog does not received focus
% automatically so you'll need to
% ALT-TAB to get to it.
%
% codecParams X A MIME Base64-encoded string describing
% the codec setup parameters for a
% DirectShow codec. The contents of this
% string are very codec-specific. Often,
% The best ways to come up with a string
% like this are to first create a
% videoWriter with the
% 'showCompressionDialog' option enabled,
% choose the desired settings, then use
% the GETINFO method to extract the
% 'codecParams' value. Note that this
% representation is the same as used by
% VirtualDub 1.6 and 1.7 in its Sylia
% Script files. Nearly all useful
% DirectShow codecs can only be
% configured with 'codecParams' and they
% ignore the separate 'bitRate' and
% 'gopSize' parameters given below.
%
% bitRate X x Target bits/sec of the encoded video.
% Supported by most ffmpeg codecs.
% To see whether a particular codec uses
% the bitRate parameter, run the
% testBitRate function in the tests/
% subdirectory (NOTE: very few DirectShow
% codecs support it).
%
% gopSize X x Maximum period between keyframes. GOP
% stands for "group of pictures" in MPEG
% lingo. Supported by most ffmpeg
% codecs. To see whether a particular
% codec uses the gopSize parameter, run
% the testGopSize function in the tests/
% subdirectory (NOTE: very few DirectShow
% codecs support it).
%
% maxBFrames X For MPEG codecs, gives the max
% number of bidirectional frames in a
% group of pictures (GOP).
%
% codecs = videoWriter([],'codecs')
% codecs = videoWriter([],pluginName,'codecs')
% codecs = videoWriter([],'codecs','plugin',pluginName)
% Queries the backend for a list of the valid codecs that may be used
% with the 'codec' plugin parameter.
%
% Once you are done using the videoWriter, make sure you call CLOSE so
% that any system resources allocated by the plugin may be released.
% Here's a simple example of how you might use videoWriter to create
% a video of continually adding more motion blur to an image:
%
% % Construct a videoWriter object
% vw = videoWriter('writertest.avi', ...
% 'width',320, 'height',240, 'codec','xvid');
% img = imread('peppers.png');
% h = fspecial('motion',10,5);
% for i=1:100
% addframe(vw, img);
% img = imfilter(img, h);
% end
% vw=close(vw);
%
% SEE ALSO:
% buildVideoMex
% videoWriter/addframe
% videoWriter/close
% videoReader
%
%Copyright (c) 2006 Gerald Dalley
%See "MIT.txt" in the installation directory for licensing details (especially
%when using this library on GNU/Linux).
if (numel(url)==0)
% static method call
if (mod(length(varargin),2) == 0)
plugin = varargin{1};
staticMethod = varargin{2};
methodArgs = {varargin{3:end}};
else
plugin = defaultVideoIOPlugin;
staticMethod = varargin{1};
methodArgs = {varargin{2:end}};
end
[plugin,methodArgs] = parsePlugin(plugin, methodArgs);
vw = feval(mexName(plugin), staticMethod, int32(-1), methodArgs{:});
else
% constructor call
if (mod(length(varargin),2) == 0)
plugin = defaultVideoIOPlugin;
pluginArgs = varargin;
else
plugin = varargin{1};
pluginArgs = {varargin{2:end}};
end
plugin = parsePlugin(plugin, pluginArgs);
vw = struct('plugin',mexName(plugin), 'handle',int32(-1), ...
'w',int32(-1), 'h',int32(-1));
vw = class(vw, 'videoWriter');
[pathstr, name, ext, versn] = fileparts(url);
strArgs = cell(size(pluginArgs));
for i=1:numel(pluginArgs), strArgs{i} = num2str(pluginArgs{i}); end
[vw.handle,vw.w,vw.h] = feval(vw.plugin, 'open', vw.handle, ...
fullfile(pathstr,[name ext versn]), ...
strArgs{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n = mexName(plugin)
n = ['videoWriter_' plugin];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [plugin,pluginArgs] = parsePlugin(plugin, pluginArgs)
if (length(pluginArgs) > 0)
[pluginSpecified,idx] = ismember('plugin', {pluginArgs{1:2:end}});
if pluginSpecified
plugin = pluginArgs{idx*2};
pluginArgs = { pluginArgs{1:idx*2-2}, pluginArgs{idx*2+1:end} };
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
videoReader.m
|
.m
|
Acoustic_Similarity-master/code/chronux/fly_track/videoIO/videoIO_2007a/@videoReader/videoReader.m
| 5,622 |
utf_8
|
ae0c7daa1ec7e2618347338bff619af5
|
function vr = videoReader(url, varargin)
% videoReader class constructor
% Creates a object that reads video streams. We use a plugin
% architecture in the backend to do the actual reading. For example,
% on Windows, DirectShow will typically be used and on Linux, the
% ffmpeg library is often used.
%
% vr = videoReader(url)
% Opens the given video file for reading using the default plugin.
% On Windows, 'DirectShow' is used by default and on Linux,
% 'ffmpegPopen2' is used by default. For most plugins, the url will
% really be a filename.
%
% vr = videoReader(url, ..., 'plugin',pluginName, ...)
% vr = videoReader(url,pluginName, ...)
% Opens the file using the manually specified plugin implementation.
% Available plugins include:
%
% 'DirectShow': preferred method on Windows
% - Only available on Windows
% - See INSTALL.dshow.txt for installation instructions
% - Can load virtually any video file that can be played in
% Microsoft's Windows Media Player. Note that the correct codec
% must be installed to read a file. For example, to read
% tests/numbers.3ivx.avi, the user must have installed an MPEG4
% codec such as 3ivx (www.3ivx.com), DivX (www.divx.com), or XviD
% (www.xvid.org).
% - The URL parameter should be a filename.
% - As a convenience, all forward slashes ('/') are automatically
% converted to backslashes ('\')
%
% 'ffmpegPopen2': safe method on Linux
% - Only supported on GNU/Linux (might work on BSD systems too like Mac
% OS X, but this is untested)
% - See INSTALL.ffmpeg.txt for installation instructions
% - Creates a separate server process to communicate with the
% ffmpeg libraries.
% - Works when the system's version of GCC is very different from
% the one that MathWorks used to compile Matlab.
% - Isolates ffmpeg errors so they typically cannot crash
% Matlab.
% - May allow for more flexible distribution terms for your code
% when it uses videoIO (ffmpeg may be compiled with either
% the LGPL or GPL license).
%
% 'ffmpegDirect': low-overhead method on Linux
% - same as ffmpegPopen2, but the ffmpeg libraries are loaded
% directly by the MEX file.
% - May not work if MathWorks' and your version of GCC are
% incompatible.
% - Slightly faster than ffmpegPopen2 since there is no
% interprocess communication overhead.
%
% vr = videoReader(url, ..., param,arg,...)
% Allows the user to pass extra configuration arguments to plugin.
% Currently no plugin arguments are supported right now. In the
% future, we may allow the user to do things like have DirectShow
% automatically convert to grayscale, or give options to trade off
% speed with seeking precision.
%
% Once you have created a videoReader object, you must next call NEXT,
% SEEK, or STEP at least once so that it will read some frame from disk.
% *After* calling one of these methods, you may call GETFRAME as many
% times as you would like and it will decode and return the current frame
% (without advancing to a different frame). GETINFO may be called at any
% time (even before NEXT, SEEK, or STEP). It returns basic information
% about the video stream. Once you are done using the videoReader, make
% sure you call CLOSE so that any system resources allocated by the plugin
% may be released. Here's a simple example of how you might use
% videoReader:
%
% % take us to the videoReader directory since we know there's a video
% % file there.
% chdir(fileparts(which('videoReaderWrapper.cpp')));
%
% % Construct a videoReader object
% vr = videoReader('tests/numbers.uncompressed.avi');
%
% % Do some processing on the video and display the results
% avgIntensity = [];
% i = 1;
% figure;
% while (next(vr))
% img = getframe(vr);
% avgIntensity(i) = mean(img(:));
% subplot(121); imshow(img); title('current frame');
% subplot(122); plot(avgIntensity); title('avg. intensity vs. frame');
% drawnow; pause(0.1); i = i+1;
% end
% vr = close(vr);
%
% SEE ALSO:
% buildVideoMex
% videoReader/close
% videoReader/getframe
% videoReader/getinfo
% videoReader/getnext
% videoReader/next
% videoReader/seek
% videoReader/step
% videoWriter
%
%Copyright (c) 2006 Gerald Dalley
%See "MIT.txt" in the installation directory for licensing details (especially
%when using this library on GNU/Linux).
if (mod(length(varargin),2) == 0)
plugin = defaultVideoIOPlugin;
pluginArgs = varargin;
else
plugin = varargin{1};
pluginArgs = {varargin{2:end}};
end
[plugin,pluginArgs] = parsePlugin(plugin, pluginArgs);
vr = struct('plugin',mexName(plugin), 'handle',int32(-1));
vr = class(vr, 'videoReader');
[pathstr, name, ext, versn] = fileparts(url);
strArgs = cell(size(pluginArgs));
for i=1:numel(pluginArgs), strArgs{i} = num2str(pluginArgs{i}); end
vr.handle = feval(vr.plugin, 'open', vr.handle, ...
fullfile(pathstr,[name ext versn]), strArgs{:});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n = mexName(plugin)
n = ['videoReader_' plugin];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [plugin,pluginArgs] = parsePlugin(plugin, pluginArgs)
if (length(pluginArgs) > 0)
[pluginSpecified,idx] = ismember('plugin', {pluginArgs{1:2:end}});
if pluginSpecified
plugin = pluginArgs{idx*2};
pluginArgs = { pluginArgs{1:idx*2-2}, pluginArgs{idx*2+1:end} };
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
videoWriter.m
|
.m
|
Acoustic_Similarity-master/code/chronux/fly_track/videoIO/videoIO_2007a/@videoWriter/videoWriter.m
| 11,246 |
utf_8
|
a6a2b6d2d9552d4c6e352fc015b8e3dd
|
function vw = videoWriter(url, varargin)
% videoWriter class constructor
% Creates a object that writes video files. We use a plugin
% architecture in the backend to do the actual writing. For example,
% on Windows, DirectShow will typically be used and on Linux, the
% ffmpeg library is often used.
%
% vw = videoWriter(url)
% Opens the given video file for writing using the default plugin.
% On Windows, 'DirectShow' is used by default and on Linux,
% 'ffmpegPopen2' is used by default. For most plugins, the url will
% really be a filename.
%
% vw = videoWriter(url,..., 'plugin',pluginName, ...)
% vw = videoWriter(url,pluginName)
% Opens the file using the specified plugin implementation.
% Available plugins include:
%
% 'DirectShow': preferred method on Windows
% - Only available on Windows
% - See INSTALL.dshow.txt for installation instructions
% - The URL parameter should be a filename.
% - As a convenience, all forward slashes ('/') are automatically
% converted to backslashes ('\')
%
% 'ffmpegPopen2': safe method on Linux
% - Only supported on GNU/Linux (might work on BSD systems too like Mac
% OS X, but this is untested)
% - See INSTALL.ffmpeg.txt for installation instructions
% - Creates a separate server process to communicate with the
% ffmpeg libraries.
% - Works when the system's version of GCC is very different from
% the one that MathWorks used to compile Matlab.
% - Isolates ffmpeg errors so they typically cannot crash
% Matlab.
% - May allow for more flexible distribution terms for your code
% when it uses videoIO (ffmpeg may be compiled with either
% the LGPL or GPL license).
%
% 'ffmpegDirect': low-overhead method on Linux
% - same as ffmpegPopen2, but the ffmpeg libraries are loaded
% directly by the MEX file.
% - May not work if MathWorks' and your version of GCC are
% incompatible.
% - Slightly faster than ffmpegPopen2 since there is no
% interprocess communication overhead.
%
% vw = videoWriter(url, ..., param,arg,...)
% Allows the user to pass extra configuration arguments to plugin.
% At present, all parameter names are case sensitive (but in the
% future they may become case-insensitive).
%
% The following parameters are supported by current plugins:
%
% Plugin
% Parameter ffmpeg* DShow Implementation Notes
% --------- ------- ----- -----------------------------
% width X X Width of the encoded video. Most
% codecs require width to be divisible
% by 2, 4, or 8. Most users will want
% to explicitly pass this parameter.
% The addframe method will
% automatically resize any images
% according to the value chosen here
% (or a default value if none is
% specified here).
%
% height X X Height of the encoded video. Most
% codecs require height to be divisible
% by 2, 4, or 8. Most users will want
% to explicitly pass this parameter.
% The addframe method will
% automatically resize any images
% according to the value chosen here
% (or a default value if none is
% specified here).
%
% codec X X A string specifying the encoder to
% use. The exact set of possible
% codecs is highly system-dependent.
% Most users will want to explicitly
% pass this parameter. To see a list
% of available codecs on a specific
% machine, run:
% codecs = videoWriter([],'codecs');
%
% fourcc X For the DirectShow plugin, this is a
% synonym for 'codec'.
%
% fps X X Frame rate of the recorded video.
% Note that some codecs only work with
% some frame rates. 15, 24, 25, 29.97,
% and 30 should work with most codecs.
%
% framesPerSecond X X An alias for fps.
%
% fpsNum, fpsDenom X X This pair of parameters allows frames
% per second to be specified as a
% rational number. Either both or
% neither parameter must be given.
%
% framesPerSecond_num Alias for fpsNum, fpsDenom pair.
% framesPerSecond_denom
% X X
%
% bitRateTolerance X For supporting codecs, the actual
% bit rate is allowed to vary by +/-
% this value.
%
% showCompressionDialog X If true (a non-zero number), a dialog
% box is presented to the user allowing
% precise manual selection of the codec
% and its parameters. Note: sometimes
% the dialog does not received focus
% automatically so you'll need to
% ALT-TAB to get to it.
%
% codecParams X A MIME Base64-encoded string describing
% the codec setup parameters for a
% DirectShow codec. The contents of this
% string are very codec-specific. Often,
% The best ways to come up with a string
% like this are to first create a
% videoWriter with the
% 'showCompressionDialog' option enabled,
% choose the desired settings, then use
% the GETINFO method to extract the
% 'codecParams' value. Note that this
% representation is the same as used by
% VirtualDub 1.6 and 1.7 in its Sylia
% Script files. Nearly all useful
% DirectShow codecs can only be
% configured with 'codecParams' and they
% ignore the separate 'bitRate' and
% 'gopSize' parameters given below.
%
% bitRate X x Target bits/sec of the encoded video.
% Supported by most ffmpeg codecs.
% To see whether a particular codec uses
% the bitRate parameter, run the
% testBitRate function in the tests/
% subdirectory (NOTE: very few DirectShow
% codecs support it).
%
% gopSize X x Maximum period between keyframes. GOP
% stands for "group of pictures" in MPEG
% lingo. Supported by most ffmpeg
% codecs. To see whether a particular
% codec uses the gopSize parameter, run
% the testGopSize function in the tests/
% subdirectory (NOTE: very few DirectShow
% codecs support it).
%
% maxBFrames X For MPEG codecs, gives the max
% number of bidirectional frames in a
% group of pictures (GOP).
%
% codecs = videoWriter([],'codecs')
% codecs = videoWriter([],pluginName,'codecs')
% codecs = videoWriter([],'codecs','plugin',pluginName)
% Queries the backend for a list of the valid codecs that may be used
% with the 'codec' plugin parameter.
%
% Once you are done using the videoWriter, make sure you call CLOSE so
% that any system resources allocated by the plugin may be released.
% Here's a simple example of how you might use videoWriter to create
% a video of continually adding more motion blur to an image:
%
% % Construct a videoWriter object
% vw = videoWriter('writertest.avi', ...
% 'width',320, 'height',240, 'codec','xvid');
% img = imread('peppers.png');
% h = fspecial('motion',10,5);
% for i=1:100
% addframe(vw, img);
% img = imfilter(img, h);
% end
% vw=close(vw);
%
% SEE ALSO:
% buildVideoMex
% videoWriter/addframe
% videoWriter/close
% videoReader
%
%Copyright (c) 2006 Gerald Dalley
%See "MIT.txt" in the installation directory for licensing details (especially
%when using this library on GNU/Linux).
if (numel(url)==0)
% static method call
if (mod(length(varargin),2) == 0)
plugin = varargin{1};
staticMethod = varargin{2};
methodArgs = {varargin{3:end}};
else
plugin = defaultVideoIOPlugin;
staticMethod = varargin{1};
methodArgs = {varargin{2:end}};
end
[plugin,methodArgs] = parsePlugin(plugin, methodArgs);
vw = feval(mexName(plugin), staticMethod, int32(-1), methodArgs{:});
else
% constructor call
if (mod(length(varargin),2) == 0)
plugin = defaultVideoIOPlugin;
pluginArgs = varargin;
else
plugin = varargin{1};
pluginArgs = {varargin{2:end}};
end
plugin = parsePlugin(plugin, pluginArgs);
vw = struct('plugin',mexName(plugin), 'handle',int32(-1), ...
'w',int32(-1), 'h',int32(-1));
vw = class(vw, 'videoWriter');
[pathstr, name, ext, versn] = fileparts(url);
strArgs = cell(size(pluginArgs));
for i=1:numel(pluginArgs), strArgs{i} = num2str(pluginArgs{i}); end
[vw.handle,vw.w,vw.h] = feval(vw.plugin, 'open', vw.handle, ...
fullfile(pathstr,[name ext versn]), ...
strArgs{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n = mexName(plugin)
n = ['videoWriter_' plugin];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [plugin,pluginArgs] = parsePlugin(plugin, pluginArgs)
if (length(pluginArgs) > 0)
[pluginSpecified,idx] = ismember('plugin', {pluginArgs{1:2:end}});
if pluginSpecified
plugin = pluginArgs{idx*2};
pluginArgs = { pluginArgs{1:idx*2-2}, pluginArgs{idx*2+1:end} };
end
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
FTrack.m
|
.m
|
Acoustic_Similarity-master/code/chronux/fly_track/FTrack/functions/FTrack.m
| 19,662 |
utf_8
|
29bb346b9fcedc49122cc6f916b3f783
|
function varargout = FTrack(varargin)
% FTRACK
% For all your fly-tracking needs! . See documentation for usage details.
% Last Modified by GUIDE v2.5 26-Nov-2007 18:07:29
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @FTrack_OpeningFcn, ...
'gui_OutputFcn', @FTrack_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 FTrack is made visible.
function FTrack_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 FTrack (see VARARGIN)
% Choose default command line output for FTrack
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
disp('Welcome to FTrack!')
warning off all
% UIWAIT makes FTrack wait for user response (see UIRESUME)
% uiwait(handles.figure1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Outputs from this function are returned to the command line.
function varargout = FTrack_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in load_video.
function load_video_Callback(hObject, eventdata, handles)
% hObject handle to load_video (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA
%The following allows the user to select multiple videos to be tracked.
%The videos will be tracked sequentially, not in parallel. The filenames
%will be displayed in the message center.
[filename, pathname] = uigetfile({'*.avi;*.mpg;*.mp2','Video Files (*.avi,*.mpg,*.mp2)'}, 'Pick a video', 'MultiSelect','on');
if iscell(filename)
NFiles = length(filename);
else
NFiles = 1;
filename = {filename};
end
if isequal(filename,0) || isequal(pathname,0)
disp('File select canceled')
else
for i = 1:NFiles
disp(['Video selected: ', fullfile(pathname, filename{i})])
handles.filename{i} = fullfile(pathname, filename{i});
end
end
guidata(gcbo,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in viewframe.
function viewframe_Callback(hObject, eventdata, handles)
% hObject handle to viewframe (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%This is the single frame viewer. It simply gives the user some info about
%the video (displayed in the message center), and also shows the user a
%single frame of the movie so that they can make sure it looks correct and
%they can get some parameters off of the frame if need be (such as fly size
%or a pixel/cm calilbration).
filename = handles.filename;
if iscell(filename)
NFiles = length(filename);
else
NFiles = 1;
filename = {filename};
end
for i = 1:NFiles
video = videoReader(filename{i});
seek(video,1);
info = getinfo(video);
img = getframe(video);
figure
imagesc(img)
title(filename{i})
disp(['Video name:',filename{i}])
disp(['Video dimensions [Width, Height]: [', num2str(info.width),' , ' num2str(info.height),']'])
disp(['Number of frames: ',num2str(info.numFrames)])
disp(['Frame rate: ',num2str(info.fps),' frames/s'])
handles.VideoInfo(i) = info;
end
disp('Frame Viewer Finished')
guidata(gcbo, handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in arena_dims.
function arena_dims_Callback(hObject, eventdata, handles)
% hObject handle to arena_dims (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filename = handles.filename;
if iscell(filename)
NFiles = length(filename);
else
NFiles = 1;
filename = {filename};
end
p = [];
q = [];
for i = 1:NFiles
video = videoReader(filename{i});
info = getinfo(video);
seek(video,1);
img = getframe(video);
sz = size(img);
figure
colormap gray
imagesc(img)
axis image
title({filename{i}; 'Left click to select points on boundary of arena. Press return when done.'})
% Choose points on arena boundary
[p q] = ginput;
%Find center and radius of arena
ellipse = fit_ellipse(p',q','y');
semiminor = min(ellipse.a,ellipse.b);
semimajor = max(ellipse.a,ellipse.b);
ellipse.epsilon = sqrt(1-semiminor^2/semimajor^2);
ellipse.psi = asin(ellipse.epsilon);
ellipse.semiminor = semiminor;
ellipse.semimajor = semimajor;
rotated_ellipse = ellipse.rotated_ellipse;
ellipse.points_selected = [p q];
title('Arena w/ Boundary')
ellipse.boundaries = [ rotated_ellipse(1,:)', info.height-rotated_ellipse(2,:)'];
info = handles.VideoInfo(i);
figure
title('Masking arena. Please wait...')
drawnow
disp('Masking arena...')
mask = zeros(info.height, info.width);
for k=1:info.height
for j=1:info.width
rot = inv(ellipse.R)*[j;k];
testpoint = (rot(1)-ellipse.X0).^2/(ellipse.a).^2+(rot(2)-ellipse.Y0).^2/(ellipse.b).^2;
if (testpoint <= 1.01) %giving a little lee-way near boundary
mask(k,j) = 1;
end
end
end
ellipse.mask = double(mask);
handles.arena{i} = ellipse;
imagesc(double(img(:,:,1)).*double(mask))
axis image
colormap gray
title('Portion to be tracked')
end
%setting things up to only consider pixels within selected arena...
disp('Arena Dimensions Calculated')
disp(ellipse)
guidata(gcbo, handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in input_params.
function input_params_Callback(hObject, eventdata, handles)
% hObject handle to input_params (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Opens up a dialog box so that the user can input relevant parameters for
%each video that is being tracked. A separate box will open for each
%video.
filename = handles.filename;
if iscell(filename)
NFiles = length(filename);
else
Nfiles = 1;
filename = {filename};
end
UserIn = [];
for i = 1:NFiles
first = strvcat(filename{i}, ' ','Output directory');
prompt = {first,'Start Frame (Remember that first frame is indexed 0)','End Frame:', 'Initial background size:', 'Arena radius (cm)', 'Bounding box half-size (in pixels)','Background weight (0.9 < a < 1)'};
dlg_title = ['Input Paramters'];
num_lines = 1;
defaults = {'C:\Documents and Settings\liam\My Documents\LabVIEW Data\FTrack output','0','999', '100','7.5','10','0.9'};
options.Resize='on';
options.WindowStyle='normal';
answer = inputdlg(prompt,dlg_title,num_lines,defaults, options);
UserIn = [UserIn answer];
disp(['Input parameters have been entered for ', filename{i}])
InputData(i).OutputPath = UserIn{1,i};
InputData(i).StartFrame = str2double(UserIn(2,i));
InputData(i).EndFrame = str2double(UserIn(3,i));
InputData(i).NBackFrames = str2double(UserIn(4,i));
InputData(i).ArenaRadius = str2double(UserIn(5,i));
InputData(i).sqrsize = str2double(UserIn(6,i));
InputData(i).alpha = str2double(UserIn(7,i));
end
handles.InputData = InputData;
guidata(gcbo, handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Radio Buttons to select fly finding option
% --- Executes during object creation, after setting all properties.
function find_opt_CreateFcn(hObject, eventdata, handles)
% hObject handle to find_opt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --------------------------------------------------------------------
function find_opt_SelectionChangeFcn(hObject, eventdata, handles)
% hObject handle to find_opt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Radio buttons to select whether fly is white on black or black on white
% --- Executes during object creation, after setting all properties.
function neg_opt_CreateFcn(hObject, eventdata, handles)
% hObject handle to neg_opt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --------------------------------------------------------------------
function neg_opt_SelectionChangeFcn(hObject, eventdata, handles)
% hObject handle to neg_opt (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 TrackStart.
function TrackStart_Callback(hObject, eventdata, handles)
% hObject handle to TrackStart (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%This part of the calls FlyTracker to do the actual tracking.
%grab the filename and user input parameters
filename = handles.filename;
InputData = handles.InputData;
if iscell(filename)
NVideos = length(filename);
else
NVideos = 1;
filename = {filename};
end
neg_opt = get(get(handles.neg_opt,'SelectedObject'), 'Tag');
% Call FlyTracker
for i=1:NVideos
%video parameters, just because...
info = handles.VideoInfo(i);
FrameRate = info.fps;
FrameRange = [InputData(i).StartFrame:InputData(i).EndFrame];
%Track the fly!
[x, y, orientation] = FlyTracker(filename{i}, FrameRange,...
InputData(i).NBackFrames, neg_opt, InputData(i).sqrsize,...
InputData(i).alpha, handles.arena{i});
%Time vector
if (info.numFrames == InputData(i).EndFrame)
InputData(i).EndFrame = InputData(i).EndFrame-1;
elseif (info.numFrames < InputData(i).EndFrame)
InputData(i).EndFrame = info.numFrames-1;
end
t = [InputData(i).StartFrame:InputData.EndFrame(i)]/FrameRate;
%Save data to handles so the rest of the GUI can access it.
handles.x = x;
handles.y = y;
handles.orientation = orientation;
handles.t = t;
guidata(gcbo, handles);
%Also, save variables as a .mat file so that the user will be able to
%load in the tracked data later on.
out = SaveFiles(i,handles);
end
disp('Tracking Complete.')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in view_traj.
function view_traj_Callback(hObject, eventdata, handles)
% hObject handle to view_traj (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = ...
uigetfile({'*.mat'},'Select Raw Trajectory Data');
if isequal(filename,0) || isequal(pathname,0)
disp('File select canceled')
return;
else
fullname = fullfile(pathname, filename);
end
load(fullname)
figure
set(gcf,'Name',fullname)
subplot(2,2,1)
plot(t,x)
xlim([0 t(end)])
xlabel('Time (s)')
ylabel('cm')
title('Raw x data')
subplot(2,2,3)
plot(t,y)
xlim([0 t(end)])
xlabel('Time (s)')
ylabel('cm')
title('Raw y data')
subplot(2,2,[2 4])
plot(x,y)
xlabel('x position (cm)')
ylabel('y position (cm)')
title('Raw Trajectory')
axis equal
handles.filename = filename;
handles.x = x;
handles.y = y;
handles.orientation = orientation;
handles.t = t;
handles.VideoInfo = VideoInfo;
handles.InputData = InputData;
handles.arena{1} = arena;
guidata(gcbo, handles);
% --- Executes on button press in clean_x.
function clean_x_Callback(hObject, eventdata, handles)
% hObject handle to clean_x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
x = handles.x;
filename = handles.filename;
%open up plot to examine data
figure
plot(x)
title('Zoom in if necessary. Press any key to continue.')
xlabel('Frame')
ylabel('cm')
pause
% This loop runs until the user hits return to exit. We wait for the user
% to click four points on the graph, and then run the CleanData function on
% the region defined by those four points.
while(1)
title('Define region of data to clean: left, right, baseline, threshold. Hit Return to exit.')
[p q] = ginput(4);
if isempty(p)
close;
disp('X data has been cleaned.')
out = SaveFiles(1,handles);
return;
else
rnge = floor(p(1)):floor(p(2));
end
if (q(3) > q(4))
choice = 'below';
elseif (q(3) < q(4));
choice = 'above';
end
epsilon = q(4);
x = CleanData(x, rnge, choice, epsilon);
handles.x = x;
guidata(gcbo, handles)
ax = gca;
xlim_temp = get(ax, 'XLim');
ylim_temp = get(ax, 'YLim');
%Show plot of clean data
figure
plot(x)
xlim(xlim_temp);
ylim(ylim_temp);
xlabel('Frame')
ylabel('cm')
title('Zoom in if necessary. Press any key to continue.')
pause
end
% --- Executes on button press in clean_y.
function clean_y_Callback(hObject, eventdata, handles)
% hObject handle to clean_y (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
y = handles.y;
filename = handles.filename;
%open up plot to examine data
figure(2)
plot(y)
xlabel('Frame')
ylabel('cm')
title('Zoom in if necessary. Press any key to continue.')
pause
% This loop runs until the user hits return to exit. We wait for the user
% to click four points on the graph, and then run the CleanData function on
% the region defined by those four points.
while(1)
title('Define region of data to clean: left, right, baseline, threshold. Hit Return to exit.')
[p q] = ginput(4);
if isempty(p)
close;
disp('Y data has been cleaned.')
out = SaveFiles(1,handles);
return;
else
rnge = floor(p(1)):floor(p(2));
end
if (q(3) > q(4))
choice = 'below';
elseif (q(3) < q(4));
choice = 'above';
end
epsilon = q(4);
y = CleanData(y, rnge, choice, epsilon);
handles.y = y;
guidata(gcbo, handles)
ax = gca;
xlim_temp = get(ax, 'XLim');
ylim_temp = get(ax, 'YLim');
%Show plot of clean data
figure(2)
plot(y)
xlim(xlim_temp);
ylim(ylim_temp);
xlabel('Frame')
ylabel('cm')
title('Zoom in if necessary. Press any key to continue.')
pause
end
return;
function out = SaveFiles(i,handles)
if iscell(handles.filename)
filename = handles.filename{i};
else
filename = handles.filename;
end
OutputPath = handles.InputData(i).OutputPath;
x = handles.x;
y = handles.y;
t = handles.t;
orientation = handles.orientation;
InputData = handles.InputData(i);
VideoInfo = handles.VideoInfo(i);
arena = handles.arena{i};
[temp, name, ext, versn] = fileparts(filename);
name_mat = strcat(name,'.mat');
name_xy=strcat(name,'.xy');
name_ori=strcat(name,'.ori');
save_filename = fullfile(OutputPath,name);
save_filename_xy = fullfile(OutputPath,name_xy);
save_filename_ori = fullfile(OutputPath,name_ori);
ori=handles.orientation(1,:)';
xy=[handles.x' handles.y'];
save(save_filename,'x','y','t','orientation','InputData', 'VideoInfo','arena')
disp(['Saved ',save_filename])
save(save_filename_xy,'xy','-ascii','-tabs');
disp(['Saved ',save_filename_xy])
save(save_filename_ori,'ori','-ascii','-tabs');
disp(['Saved ',save_filename_ori])
out = 1;
return;
% --- Executes on button press in tilt_correct.
function tilt_correct_Callback(hObject, eventdata, handles)
% hObject handle to tilt_correct (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Note. This is a slightly different version of tilt correction than
%described in the PLoS paper. I think this is more robust and general.
x = handles.x;
y = handles.y;
t = handles.t;
ellipse = handles.arena{1};
radius_in_cm = handles.InputData.ArenaRadius;
video = videoReader(handles.VideoInfo.url);
info = getinfo(video);
height = info.height;
psi = ellipse.psi;
phi = ellipse.phi;
%redefining coordinate system so center of arena is at (0,0)
rotated_ellipse(:,1) = ellipse.boundaries(:,1)-ellipse.X0_in;
rotated_ellipse(:,2) = ellipse.boundaries(:,2)-(height-ellipse.Y0_in);
M = [cos(phi) sin(phi);-sin(phi) cos(phi)]; %rotation matrix.
%stretch ellipse only in shortest dimension to length of longest.
if (ellipse.a > ellipse.b)
L = [1 0; 0 ellipse.a/ellipse.b];
else
L = [ellipse.b/ellipse.a 0; 0 1];
end
T = L*M; %transformation matrix. A rotation and a stretch to turn an ellipse into a circle.
disp('Correcting for camera tilt. This may take a few minutes, so be patient!')
z = zeros(1,length(rotated_ellipse(:,1)));
%Transform boundary line
for j = 1:length(rotated_ellipse(:,1))
temp = T*[rotated_ellipse(j,1); rotated_ellipse(j,2)];
xe(j) = temp(1);
ye(j) = temp(2);
end
%fit new ellipse
z = zeros(1,length(x));
new_ellipse = fit_ellipse(xe',ye','n');
semiminor = min(new_ellipse.a,new_ellipse.b);
semimajor = max(new_ellipse.a,new_ellipse.b);
new_ellipse.epsilon = sqrt(1-semiminor^2/semimajor^2);
new_ellipse.psi = asin(new_ellipse.epsilon);
new_ellipse.semiminor = semiminor;
new_ellipse.semimajor = semimajor;
new_ellipse.boundaries = [xe' ye'];
%Now transform trajectory
for j = 1:length(x)
temp = T*[x(j)-ellipse.X0_in; y(j)-(height-ellipse.Y0_in)];
xp(j) = temp(1);
yp(j) = temp(2);
end
if (abs(new_ellipse.b-new_ellipse.a) <= 2) %2 pixel accuracy seems adequate
disp('Tilt corrected')
pixels_in_cm = semimajor/radius_in_cm;
x = (xp)/pixels_in_cm;
y = (yp)/pixels_in_cm;
figure
plot(x,y,new_ellipse.boundaries(:,1)/pixels_in_cm,new_ellipse.boundaries(:,2)/pixels_in_cm,'r')
title('Transformed trajectory with boundary')
handles.arena{1}=new_ellipse;
handles.x = x;
handles.y = y;
handles.InputData.pixels_in_cm = pixels_in_cm;
out = SaveFiles(1,handles);
else
disp('Something went wrong. Arena is still an ellipse. ')
end
guidata(gcbo, handles)
|
github
|
BottjerLab/Acoustic_Similarity-master
|
mostCommonSubstring.m
|
.m
|
Acoustic_Similarity-master/code/grammar/mostCommonSubstring.m
| 1,220 |
utf_8
|
f0f718d8b632979dea5c98a57c2a1d1b
|
function [subStrSorted, countsSorted, locations] = mostCommonSubstring(string,N, M)
% returns the most common substrings of length N, with more than M
% occurrences
if nargin < 3
M = 1;
end
[subStr, counts, locations] = n_gram(string, N);
[countsSorted, sortIdx] = sort(counts, 'descend');
subStrSorted = subStr(sortIdx);
subStrSorted = subStrSorted(countsSorted > M)';
countsSorted = countsSorted(countsSorted > M)';
rIdx = zeros(1,numel(sortIdx));
rIdx(sortIdx) = 1:numel(sortIdx);
locations = rIdx(locations);
end
function [subStrings, counts, index] = n_gram(fullString, N)
if (N == 1)
[subStrings, rIdx, index] = unique(cellstr(fullString.')); %.'# Simple case
subStrings{cellfun('isempty',subStrings)} = ' ';
else
nString = numel(fullString);
index = hankel(1:(nString-N+1), (nString-N+1):nString);
[subStrings, rIdx, index] = unique(cellstr(fullString(index)));
% make sure substrings have trailing spaces
for ii = 1:numel(subStrings)
if numel(subStrings{ii}) ~= N
subStrings{ii} = [subStrings{ii} ' ']; %assume only single spaces exist
end
end
end
counts = accumarray(index, 1);
end
|
github
|
BottjerLab/Acoustic_Similarity-master
|
extract_features.m
|
.m
|
Acoustic_Similarity-master/code/features/extract_features.m
| 14,572 |
utf_8
|
ad19fddda62ac137339201446c681e36
|
%function [m_spec_deriv , m_AM, m_FM ,m_Entropy , m_amplitude ,gravity_center, m_PitchGoodness , m_Pitch , Pitch_chose , Pitch_weight , m_amplitude_band_1 , m_Entropy_band_1 , m_amplitude_band_3 , m_Entropy_band_2 , m_amplitude_band_3 , m_Entropy_band_3]=deriv(TS,fs);
function [m_spec_deriv , m_AM, m_FM ,m_Entropy , m_amplitude ,gravity_center, m_PitchGoodness , m_Pitch , Pitch_chose , Pitch_weight ]=extract_features(TS,fs);
% NOTE: This function is only a model
% global S_f,S_t;
% DERIV [S, S_f, S_t]=DERIV(TS,NW,K,PAD,WINDOW,WINSTEP)
% uses the derivative estimates to calculate the spectrum's frequency
% and time derivatives
%
% S: estimated spectrum; S_f: estimated frequency derivative;
% S_t: estimated time derivative
% NW: time bandwidth parameter (e.g. 3)
% K : number of tapers kept, approx. 2*NW-1
% pad: length to which data will be padded (preferably power of 2
% window: time window size
% winstep: distance between centers of adjacent time windows
% Written by Sigal Saar August 08 2005
TS=filter_sound_sam(TS);
load('Parameters');
E=taper_read();
N=length(TS);
%if N>300000
% TS_all=TS;
TSM=runing_windows(TS',param.window, param.winstep);
%TSM=runing_windows(TS',param.window, 44.1);
S=0;
SF=0;
if floor(param.winstep)~=param.winstep
E=[E ; [0 0]];
end
J1=(fft(TSM(:,:).*(ones(size(TSM,1),1)*(E(:,1))'),param.pad,2));
J1=J1(:,1:param.spectrum_range)* ( 27539);
J2=(fft(TSM(:,:).*(ones(size(TSM,1),1)*(E(:,2))'),param.pad,2));
J2=J2(:,1:param.spectrum_range)* ( 27539);
%==============Power spectrum=============
m_powSpec=real(J1).^2+real(J2).^2+imag(J1).^2+imag(J2).^2;
m_time_deriv=-1*(real(J1).*real(J2)+imag(J1).*imag(J2));
m_freq_deriv=((imag(J1).*real(J2)-real(J1).*imag(J2)));
m_time_deriv_max=max(m_time_deriv.^2,[],2);
m_freq_deriv_max=max(m_freq_deriv.^2,[],2);
%===
freq_winer_ampl_index=[param.min_freq_winer_ampl:param.max_freq_winer_ampl];
m_amplitude=sum(m_powSpec(:,freq_winer_ampl_index),2);
log_power=m_time_deriv(:,freq_winer_ampl_index).^2+m_freq_deriv(:,freq_winer_ampl_index).^2;
m_SumLog=sum(log(m_powSpec(:,freq_winer_ampl_index)+eps),2);
m_LogSum=(sum(m_powSpec(:,freq_winer_ampl_index),2));
gravity_center=sum((ones(size(log_power,1),1)*(freq_winer_ampl_index)).*log_power,2);
gc_base=sum(log_power,2);
m_AM=sum(m_time_deriv(:,freq_winer_ampl_index),2);
gravity_center=gravity_center./max(gc_base,1)*fs/param.pad;
m_AM=m_AM./(m_amplitude+eps);
m_amplitude=log10(m_amplitude+1)*10-70; %units in Db
%===========Wiener entropy==================
m_LogSum(find(m_LogSum==0))=length(freq_winer_ampl_index);
m_LogSum=log(m_LogSum/length(freq_winer_ampl_index)); %divide by the number of frequencies
m_Entropy=(m_SumLog/length(freq_winer_ampl_index))-m_LogSum;
m_Entropy(find(m_LogSum==0))=0;
%============FM===================
m_FM=atan(m_time_deriv_max./(m_freq_deriv_max+eps));
%m_FM(find(m_freq_deriv_max==0))=0;
%%%%%%%%%%%%%%%%%%%%%%%%
%==========Directional Spectral derivatives=================
cFM=cos(m_FM);
sFM=sin(m_FM);
%==The image==
m_spec_deriv=m_time_deriv(:,3:255).*(sFM*ones(1,255-3+1))+m_freq_deriv(:,3:255).*(cFM*ones(1,255-3+1));
Cepstrum=(fft(m_spec_deriv./(m_powSpec(:,3:255)+eps),512,2))*( 1/2);
x=(real(Cepstrum(:,param.up_pitch:param.low_pitch))).^2+(imag(Cepstrum(:,param.up_pitch:param.low_pitch))).^2;
[m_PitchGoodness,m_Pitch]=sort(x,2);
m_PitchGoodness=m_PitchGoodness(:,end);
m_Pitch=m_Pitch(:,end);
m_Pitch(find(m_PitchGoodness<1))=1;
m_PitchGoodness=max(m_PitchGoodness,1);
m_Pitch=m_Pitch+3;
Pitch_chose= 22050./m_Pitch ; %1./(m_Pitch/1024*fs*512);
index_m_freq=find(Pitch_chose>param.pitch_HoP & (m_PitchGoodness<param.gdn_HoP | m_Entropy>param.up_wiener));
%smoothing algorithm - not debugged and not used
%diff_index_m_freq=(diff(index_m_freq));%smothing algorithm
%bad_chose1=find(diff_index_m_freq(1:end-4)==1 & diff_index_m_freq(2:end-3)==1 & diff_index_m_freq(3:end-2)==2 & diff_index_m_freq(4:end-1)==1 & diff_index_m_freq(5:end)==1);
%bad_chose2=find(diff_index_m_freq(1:end-1)>2 & diff_index_m_freq(2:end)>2);
%index_m_freq=[index_m_freq ; (bad_chose1+3)];
%index_m_freq(bad_chose2+1)=[];
Pitch_chose(index_m_freq)=gravity_center(index_m_freq);
Pitch_weight=Pitch_chose.*m_PitchGoodness./sum(m_PitchGoodness);
m_FM=m_FM*180/pi;
%save features.mat m_amplitude m_amplitude_band_1 m_amplitude_band_2 m_amplitude_band_3 m_Entropy m_Entropy_band_1 m_Entropy_band_2 m_Entropy_band_3
%m_amplitude=m_amplitude_band_3;
%m_Entropy=m_Entropy_band_3;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function E=taper_read()
E=[0.10082636 0.488103509
0.105322801 0.500162601
0.109902844 0.512267828
0.114566609 0.52441597
0.119314209 0.536603808
0.124145724 0.548828006
0.129061237 0.561085165
0.13406077 0.573371947
0.139144346 0.585684955
0.144311979 0.598020673
0.149563625 0.610375643
0.15489924 0.622746408
0.160318747 0.635129333
0.165822059 0.647520959
0.17140907 0.659917593
0.177079603 0.672315657
0.182833508 0.684711576
0.188670605 0.697101533
0.194590658 0.709481955
0.200593442 0.721849024
0.206678703 0.734199166
0.21284613 0.746528447
0.219095424 0.75883323
0.225426242 0.7711097
0.231838226 0.783353984
0.238331005 0.795562387
0.244904146 0.807730973
0.251557231 0.819855988
0.258289784 0.831933498
0.265101343 0.843959749
0.271991402 0.855930805
0.278959394 0.867842793
0.286004782 0.879691899
0.293127 0.891474187
0.300325394 0.903185785
0.307599366 0.914822817
0.314948261 0.926381409
0.322371393 0.937857628
0.329868048 0.949247718
0.337437481 0.960547745
0.345078975 0.971753776
0.352791727 0.982862055
0.360574961 0.993868709
0.368427813 1.004769802
0.376349419 1.0155617
0.384338975 1.026240349
0.392395496 1.036802173
0.400518119 1.047243237
0.40870589 1.057559848
0.416957796 1.067748189
0.425272882 1.077804685
0.433650136 1.087725401
0.442088515 1.097506762
0.450586915 1.107145071
0.459144324 1.116636872
0.467759579 1.125978231
0.476431549 1.135165811
0.485159129 1.144196033
0.493941098 1.153065205
0.502776325 1.161769986
0.511663496 1.170306802
0.520601451 1.178672433
0.529588878 1.186863184
0.538624585 1.194875956
0.5477072 1.20270741
0.556835413 1.21035409
0.566007853 1.217812896
0.575223267 1.225080609
0.584480166 1.232154131
0.593777239 1.239030242
0.603113055 1.245705962
0.612486124 1.252178192
0.621895015 1.258444071
0.631338298 1.264500499
0.640814483 1.270344853
0.65032202 1.275974274
0.659859419 1.281385779
0.66942513 1.286576867
0.679017663 1.291544795
0.688635349 1.296286941
0.698276699 1.3008008
0.707940042 1.30508399
0.71762383 1.309133887
0.727326393 1.312948227
0.737046123 1.316524744
0.746781349 1.319861054
0.756530404 1.322955132
0.766291559 1.32580471
0.776063263 1.328407884
0.78584367 1.330762625
0.79563117 1.332866907
0.805423975 1.334718943
0.815220356 1.336316943
0.825018644 1.33765924
0.834816992 1.338744044
0.844613671 1.339569926
0.854406953 1.340135336
0.864194989 1.340438843
0.873976052 1.340479016
0.883748353 1.340254664
0.893510044 1.339764476
0.903259337 1.339007378
0.912994385 1.337982178
0.922713459 1.336688161
0.932414711 1.335124135
0.942096293 1.333289266
0.951756358 1.331183076
0.961393118 1.328804493
0.971004725 1.326153278
0.98058933 1.323228598
0.990145147 1.320030212
0.999670267 1.316557646
1.009162784 1.312810659
1.018621087 1.308789015
1.028043151 1.304492474
1.037427068 1.299921274
1.046771288 1.295075178
1.056073666 1.289954305
1.065332532 1.284559011
1.074546099 1.278889418
1.083712459 1.272946
1.092829704 1.266728997
1.101896167 1.260239124
1.110909939 1.253476977
1.119869232 1.246443033
1.128772378 1.239138246
1.13761735 1.231563449
1.146402478 1.223719358
1.155125856 1.215607166
1.163785934 1.207227945
1.172380805 1.198582649
1.180908799 1.189672828
1.18936801 1.180499554
1.197756886 1.171064377
1.206073523 1.161368728
1.214316368 1.151414156
1.222483516 1.141202331
1.230573535 1.130734921
1.238584518 1.120013714
1.246514797 1.109040618
1.254362941 1.097817659
1.262127161 1.086346745
1.269805789 1.074629903
1.277397275 1.062669516
1.28489995 1.05046773
1.292312384 1.03802681
1.299632907 1.025349379
1.30685997 1.012437582
1.313992023 0.999294221
1.321027637 0.98592186
1.32796526 0.97232312
1.334803343 0.958500803
1.341540575 0.94445771
1.348175406 0.930196762
1.354706526 0.91572094
1.361132383 0.901033223
1.367451787 0.886136711
1.373663187 0.871034622
1.379765391 0.855730176
1.385756969 0.84022665
1.391636729 0.824527323
1.39740324 0.808635712
1.403055549 0.792555213
1.408592105 0.776289403
1.414011955 0.759841859
1.419313788 0.743216217
1.424496531 0.726416171
1.429558992 0.709445536
1.434500098 0.692308068
1.439318776 0.675007641
1.444013953 0.657548249
1.448584676 0.639933705
1.453029752 0.622168124
1.457348466 0.604255557
1.461539626 0.586200118
1.465602517 0.568005979
1.469536185 0.549677253
1.473339677 0.53121829
1.477012277 0.512633264
1.48055315 0.493926555
1.483961463 0.475102544
1.487236381 0.456165582
1.490377426 0.43712011
1.493383765 0.417970628
1.496254683 0.398721576
1.498989701 0.379377574
1.501588106 0.359943092
1.504049301 0.340422779
1.506372809 0.320821226
1.508558035 0.30114311
1.51060462 0.281393051
1.512511969 0.261575758
1.514279842 0.24169597
1.515907645 0.221758381
1.517395139 0.201767772
1.518741965 0.181728885
1.519947767 0.16164653
1.521012425 0.141525477
1.521935582 0.121370547
1.522717118 0.101186559
1.523356676 0.080978341
1.523854375 0.060750734
1.524209857 0.040508576
1.524423242 0.020256713
1.52449429 -2.11E-09
1.524423242 -0.020256717
1.524209857 -0.040508579
1.523854375 -0.060750738
1.523356676 -0.080978349
1.522717118 -0.101186566
1.521935582 -0.121370554
1.521012425 -0.141525477
1.519947767 -0.16164653
1.518741965 -0.181728899
1.517395139 -0.201767772
1.515907645 -0.221758395
1.514279842 -0.24169597
1.512511969 -0.261575758
1.51060462 -0.281393051
1.508558035 -0.30114311
1.506372809 -0.320821226
1.504049301 -0.340422779
1.501588106 -0.359943092
1.498989701 -0.379377574
1.496254683 -0.398721606
1.493383765 -0.417970628
1.490377426 -0.43712011
1.487236381 -0.456165582
1.483961463 -0.475102544
1.48055315 -0.493926555
1.477012277 -0.512633264
1.473339677 -0.53121829
1.469536185 -0.549677253
1.465602517 -0.568005979
1.461539626 -0.586200118
1.457348466 -0.604255617
1.453029752 -0.622168124
1.448584676 -0.639933705
1.444013953 -0.657548249
1.439318776 -0.675007701
1.434500098 -0.692308068
1.429558992 -0.709445536
1.424496531 -0.726416171
1.419313788 -0.743216217
1.414011955 -0.759841859
1.408592105 -0.776289403
1.403055549 -0.792555213
1.39740324 -0.808635712
1.391636729 -0.824527323
1.385756969 -0.84022665
1.379765391 -0.855730176
1.373663187 -0.871034682
1.367451787 -0.88613677
1.361132383 -0.901033223
1.354706526 -0.91572094
1.348175406 -0.930196762
1.341540575 -0.94445771
1.334803343 -0.958500803
1.32796526 -0.97232312
1.321027637 -0.98592186
1.313992023 -0.999294281
1.30685997 -1.012437582
1.299632907 -1.025349379
1.292312384 -1.03802681
1.28489995 -1.05046773
1.277397275 -1.062669516
1.269805789 -1.074629903
1.262127161 -1.086346745
1.254362941 -1.097817659
1.246514797 -1.109040618
1.238584518 -1.120013714
1.230573535 -1.130734921
1.222483516 -1.141202331
1.214316368 -1.151414156
1.206073523 -1.161368728
1.197756886 -1.171064377
1.18936801 -1.180499554
1.180908799 -1.189672828
1.172380805 -1.198582649
1.163785934 -1.207227945
1.155125856 -1.215607166
1.146402478 -1.223719358
1.13761735 -1.231563449
1.128772378 -1.239138246
1.119869232 -1.246443033
1.110909939 -1.253476977
1.101896167 -1.260239124
1.092829704 -1.266728997
1.083712459 -1.272946
1.074546099 -1.278889418
1.065332532 -1.284559011
1.056073666 -1.289954305
1.046771288 -1.295075178
1.037427068 -1.299921274
1.028043151 -1.304492474
1.018621087 -1.308789015
1.009162784 -1.312810659
0.999670208 -1.316557646
0.990145147 -1.320030212
0.98058933 -1.323228598
0.971004725 -1.326153278
0.961393118 -1.328804493
0.951756358 -1.331183076
0.942096293 -1.333289266
0.932414711 -1.335124135
0.922713459 -1.336688161
0.912994385 -1.337982178
0.903259337 -1.339007378
0.893510044 -1.339764476
0.883748353 -1.340254664
0.873976052 -1.340479016
0.864194989 -1.340438843
0.854406953 -1.340135336
0.844613671 -1.339569926
0.834816992 -1.338744044
0.825018644 -1.33765924
0.815220356 -1.336316943
0.805423975 -1.334718943
0.79563117 -1.332866907
0.78584367 -1.330762625
0.776063263 -1.328407884
0.766291559 -1.32580471
0.756530404 -1.322955132
0.746781349 -1.319861054
0.737046123 -1.316524744
0.727326393 -1.312948227
0.71762383 -1.309133887
0.707940042 -1.30508399
0.698276699 -1.3008008
0.688635349 -1.296286941
0.679017663 -1.291544795
0.66942513 -1.286576867
0.659859419 -1.281385779
0.65032202 -1.275974274
0.640814483 -1.270344853
0.631338298 -1.264500499
0.621895015 -1.258444071
0.612486124 -1.252178192
0.603113055 -1.245705962
0.593777239 -1.239030242
0.584480166 -1.232154131
0.575223267 -1.225080609
0.566007853 -1.217812896
0.556835413 -1.21035409
0.5477072 -1.20270741
0.538624585 -1.194875956
0.529588878 -1.186863184
0.520601451 -1.178672433
0.511663496 -1.170306802
0.502776325 -1.161769986
0.493941098 -1.153065205
0.485159129 -1.144196033
0.476431549 -1.135165811
0.467759579 -1.125978231
0.459144324 -1.116636872
0.450586915 -1.107145071
0.442088515 -1.097506762
0.433650136 -1.087725401
0.425272882 -1.077804685
0.416957796 -1.067748189
0.40870586 -1.057559848
0.400518119 -1.047243237
0.392395496 -1.036802173
0.384338945 -1.026240349
0.376349419 -1.0155617
0.368427813 -1.004769802
0.360574961 -0.993868709
0.352791727 -0.982862055
0.345078975 -0.971753776
0.337437481 -0.960547745
0.329868048 -0.949247718
0.322371393 -0.937857628
0.314948261 -0.926381409
0.307599366 -0.914822817
0.300325394 -0.903185785
0.293126971 -0.891474187
0.286004782 -0.879691899
0.278959394 -0.867842793
0.271991402 -0.855930805
0.265101343 -0.843959749
0.258289784 -0.831933498
0.251557231 -0.819855988
0.244904146 -0.807730973
0.238331005 -0.795562387
0.231838226 -0.783353984
0.225426242 -0.7711097
0.219095424 -0.75883323
0.21284613 -0.746528447
0.206678703 -0.734199166
0.200593442 -0.721849024
0.194590658 -0.709481955
0.188670605 -0.697101533
0.182833508 -0.684711576
0.177079603 -0.672315657
0.171409056 -0.659917593
0.165822059 -0.647520959
0.160318747 -0.635129333
0.15489924 -0.622746408
0.149563611 -0.610375643
0.144311965 -0.598020673
0.139144346 -0.585684955
0.134060755 -0.573371947
0.129061222 -0.561085165
0.124145724 -0.548828006
0.119314201 -0.536603808
0.114566602 -0.52441597
0.109902844 -0.512267828
0.105322801 -0.500162601
0.100826353 -0.488103509];
|
github
|
BottjerLab/Acoustic_Similarity-master
|
multLinearRegress.m
|
.m
|
Acoustic_Similarity-master/code/features/multLinearRegress.m
| 2,052 |
utf_8
|
d36768199d2c90c52ddff3138a4e2fe3
|
function [corrSig, sigLevel, corrSigP]=multLinearRegress(xStruct, yStruct, varargin)
% remove
% convert xStruct to column data
[X, xNames] = structArrayToColumn(xStruct);
% convert yStruct to column data
[allY, yNames] = structArrayToColumn(yStruct);
% clean zeroed data (is this an exact match?)
Xclean = X;
Xclean(:,any(X==0,1)) = [];
xNames(any(X==0,1)) = [];
%keyboard
% significance levels
sig(1) = 0.05;
sig(2) = sig(1) / numel(xNames);
sig(3) = sig(2) / numel(yNames);
% run the linear regression
for ii = 1:numel(yNames)
[b,dev,stats]=glmfit(Xclean,allY(:,ii));
posFiring = (0 < allY(:,ii));
[bP, devP, statsP] = glmfit(Xclean(posFiring,:),allY(posFiring,ii));
corrSig.constant(ii) = stats.p(1);
corrSigP.constant(ii) = statsP.p(1);
for jj = 1:numel(xNames)
corrSig.(xNames{jj})(ii) = stats.p(jj+1);
corrSigP.(xNames{jj})(ii) = statsP.p(jj+1);
sigLevel.(xNames{jj})(ii) = 0;
for kk = 1:numel(sig)
sigLevel.(xNames{jj})(ii) = sigLevel.(xNames{jj})(ii) + [stats.p(jj+1) < sig(kk)];
end
if sigLevel.(xNames{jj})(ii) == numel(sig) % unquestionably significant after mult. t-tests
figure; plot(Xclean(:,jj), allY(:,ii),'r.');
xlabel(sprintf('Similarity to feature %s', nos(xNames{jj})));
ylabel(sprintf('Firing rate within syllable (Hz), %s',nos(yNames{ii})));
fprintf('With zero firing rate, p = %f, without, p = %f\n',...
corrSig.(xNames{jj})(ii), corrSigP.(xNames{jj})(ii))
title(sprintf('With zero firing rate, p = %f, without, p = %f',...
corrSig.(xNames{jj})(ii), corrSigP.(xNames{jj})(ii)));
drawnow;
pause;
end
end
end
end
function str = nos(str)
str = strrep(str,'_', ' ');
end
function [colArray, names] = structArrayToColumn(structArray)
names = fieldnames(structArray);
colArray = zeros(numel(structArray), numel(names));
for kk = 1:numel(names)
colArray(:,kk) = [structArray.(names{kk})];
end
end
|
github
|
jamesjun/vistrack-master
|
poolTrials_location.m
|
.m
|
vistrack-master/poolTrials_location.m
| 2,704 |
utf_8
|
73ca9c9380e5c9950acc7d7647326faf
|
function S = poolTrials_location(vsTrial, iAnimal)
%Distance to landmark and IPI
pixpercm = 1053.28/(sqrt(2)*100);
%landmark locations
xy0 = vsTrial(1).xy0;
xyf = [789, 681]; rf = 1; %cm, radius
xy1 = [966, 418]; r1 = 2.216*2.54/2; %*1.1222; %cm, radius
xy2 = [975, 790]; r2 = 3.545*2.54/2; %*1.1222; %cm, radius
xy3 = [604, 799]; r3 = 4*2.54/2; %cm, radius
xy4 = [600, 428]; r4 = 3*2.54/2; %cm, radius
if nargin >= 2 && ~isempty(iAnimal)
viAnimal = poolVecFromStruct(vsTrial, 'iAnimal');
vsTrial = vsTrial(viAnimal == iAnimal);
end
calcD0 = @(x,y)sqrt((x-xy0(1)).^2 + (y-xy0(2)).^2) / pixpercm;
calcD1 = @(x,y)dist2square((x-xy1(1))/pixpercm, (y-xy1(2))/pixpercm, r1);
calcD2 = @(x,y)dist2square((x-xy2(1))/pixpercm, (y-xy2(2))/pixpercm, r2);
calcD3 = @(x,y)sqrt((x-xy3(1)).^2 + (y-xy3(2)).^2) / pixpercm - r3;
calcD4 = @(x,y)sqrt((x-xy4(1)).^2 + (y-xy4(2)).^2) / pixpercm - r4;
calcDf = @(x,y)sqrt((x-xyf(1)).^2 + (y-xyf(2)).^2) / pixpercm - rf;
S.vrX = [];
S.vrY = [];
S.vrV = [];
S.vrR = [];
S.vrA = [];
S.vrAV = [];
S.vrD0 = []; %dist from centre
S.vrD1 = []; %dist to LM1 (cm)
S.vrD2 = []; %dist to LM2 (cm)
S.vrD3 = []; %dist to LM3 (cm)
S.vrD4 = []; %dist to LM4 (cm)
S.vrDf = []; %dist to Food (cm)
S.vlZone = []; %active zone
S.img0 = vsTrial(1).img0;
S.xy0 = vsTrial(1).xy0;
for iTrial=1:numel(vsTrial)
Strial = vsTrial(iTrial);
vrX = poolVecFromStruct(Strial, 'vrX');
vrY = poolVecFromStruct(Strial, 'vrY');
vrV = poolVecFromStruct(Strial, 'VEL');
vrR = poolVecFromStruct(Strial, 'EODR');
vrA = poolVecFromStruct(Strial, 'ANG');
vrAV = poolVecFromStruct(Strial, 'AVEL');
vrD0 = calcD0(vrX, vrY);
vrD1 = calcD1(vrX, vrY);
vrD2 = calcD2(vrX, vrY);
vrD3 = calcD3(vrX, vrY);
vrD4 = calcD4(vrX, vrY);
vrDf = calcDf(vrX, vrY);
vlZone = isZone(Strial);
S.vrX = [S.vrX; vrX(:)];
S.vrY = [S.vrY; vrY(:)];
S.vrV = [S.vrV; vrV(:)];
S.vrR = [S.vrR; vrR(:)];
S.vrA = [S.vrA; vrA(:)];
S.vrAV = [S.vrAV; vrAV(:)];
S.vrD0 = [S.vrD0; vrD0(:)];
S.vrD1 = [S.vrD1; vrD1(:)];
S.vrD2 = [S.vrD2; vrD2(:)];
S.vrD3 = [S.vrD3; vrD3(:)];
S.vrD4 = [S.vrD4; vrD4(:)];
S.vrDf = [S.vrDf; vrDf(:)];
S.vlZone = [S.vlZone; vlZone(:)];
end
S.vlZone = logical(S.vlZone);
end
function vl = isZone(S)
angRot = -1.1590; %deg
rectCrop = [493 1083 312 902];
% rotational correction
rotMat = rotz(angRot); rotMat = rotMat(1:2, 1:2);
mrXY = [S.vrX(:) - S.xy0(1), S.vrY(:) - S.xy0(2)] * rotMat;
vrX = mrXY(:,1) + S.xy0(1);
vrY = mrXY(:,2) + S.xy0(2);
vl = vrX >= rectCrop(1) & vrX < rectCrop(2) ...
& vrY >= rectCrop(3) & vrY < rectCrop(4);
end
|
github
|
jamesjun/vistrack-master
|
struct_fun.m
|
.m
|
vistrack-master/struct_fun.m
| 318 |
utf_8
|
6748d64bc402276e82165758b57b288a
|
% 7/20/2018
% James Jun
function varargout = struct_fun(varargin)
% S_save = struct_copy_(handles, csField)
if nargin==0
vcCmd = 'help';
else
vcCmd = varargin{1};
end
switch vcCmd
case 'help', help_();
case 'copy', copy_();
case 'get', get_();
case 'set', set_();
end %switch
end %func
|
github
|
jamesjun/vistrack-master
|
prctile_.m
|
.m
|
vistrack-master/prctile_.m
| 6,604 |
utf_8
|
2cb0ab8814ae7c82533f03c822732cbe
|
function y = prctile_(x,p,dim)
%PRCTILE Percentiles of a sample.
% Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar
% or a vector of percent values. When X is a vector, Y is the same size
% as P, and Y(i) contains the P(i)-th percentile. When X is a matrix,
% the i-th row of Y contains the P(i)-th percentiles of each column of X.
% For N-D arrays, PRCTILE operates along the first non-singleton
% dimension.
%
% Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The
% DIM'th dimension of Y has length LENGTH(P).
%
% Percentiles are specified using percentages, from 0 to 100. For an N
% element vector X, PRCTILE computes percentiles as follows:
% 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N),
% ..., 100*((N-0.5)/N) percentiles.
% 2) Linear interpolation is used to compute percentiles for percent
% values between 100*(0.5/N) and 100*((N-0.5)/N)
% 3) The minimum or maximum values in X are assigned to percentiles
% for percent values outside that range.
%
% PRCTILE treats NaNs as missing values, and removes them.
%
% Examples:
% y = prctile(x,50); % the median of x
% y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x
%
% See also IQR, MEDIAN, NANMEDIAN, QUANTILE.
% Copyright 1993-2017 The MathWorks, Inc.
if ~isvector(p) || numel(p) == 0 || any(p < 0 | p > 100) || ~isreal(p)
error(message('stats:prctile:BadPercents'));
end
% Make sure we are working in floating point to avoid rounding errors.
if isfloat(x)
castOutput = false;
elseif isinteger(x)
% integer types are up-cast to either double or single and the result
% is down-cast back to the input type
castOutput = true;
outType = internal.stats.typeof(x);
if ismember(outType, ["int8" "uint8" "int16" "uint16"])
% single precision is enough
x = single(x);
else
% Needs double precision
x = double(x);
end
else
% All other types (e.g. char, logical) are cast to double and the result is
% double
castOutput = false;
x = double(x);
end
% Figure out which dimension prctile will work along.
sz = size(x);
if nargin < 3
dim = find(sz ~= 1,1);
if isempty(dim)
dim = 1;
end
dimArgGiven = false;
else
% Permute the array so that the requested dimension is the first dim.
nDimsX = ndims(x);
perm = [dim:max(nDimsX,dim) 1:dim-1];
x = permute(x,perm);
% Pad with ones if dim > ndims.
if dim > nDimsX
sz = [sz ones(1,dim-nDimsX)];
end
sz = sz(perm);
dim = 1;
dimArgGiven = true;
end
% If X is empty, return all NaNs.
if isempty(x)
if isequal(x,[]) && ~dimArgGiven
y = nan(size(p),'like',x);
else
szout = sz; szout(dim) = numel(p);
y = nan(szout,'like',x);
end
else
% Drop X's leading singleton dims, and combine its trailing dims. This
% leaves a matrix, and we can work along columns.
nrows = sz(dim);
ncols = numel(x) ./ nrows;
x = reshape(x, nrows, ncols);
x = sort(x,1);
n = sum(~isnan(x), 1); % Number of non-NaN values in each column
% For columns with no valid data, set n=1 to get nan in the result
n(n==0) = 1;
% If the number of non-nans in each column is the same, do all cols at once.
if all(n == n(1))
n = n(1);
if isequal(p,50) % make the median fast
if rem(n,2) % n is odd
y = x((n+1)/2,:);
else % n is even
y = (x(n/2,:) + x(n/2+1,:))/2;
end
else
y = interpColsSame(x,p,n);
end
else
% Get percentiles of the non-NaN values in each column.
y = interpColsDiffer(x,p,n);
end
% Reshape Y to conform to X's original shape and size.
szout = sz; szout(dim) = numel(p);
y = reshape(y,szout);
end
% undo the DIM permutation
if dimArgGiven
y = ipermute(y,perm);
end
% If X is a vector, the shape of Y should follow that of P, unless an
% explicit DIM arg was given.
if ~dimArgGiven && isvector(x)
y = reshape(y,size(p));
end
if castOutput
y = cast(y, outType);
end
function y = interpColsSame(x, p, n)
%INTERPCOLSSAME An aternative approach of 1-D linear interpolation which is
% faster than using INTERP1Q and can deal with invalid data so long as
% all columns have the same number of valid entries (scalar n).
% Make p a column vector. Note that n is assumed to be scalar.
if isrow(p)
p = p';
end
% Form the vector of index values (numel(p) x 1)
r = (p/100)*n;
k = floor(r+0.5); % K gives the index for the row just before r
kp1 = k + 1; % K+1 gives the index for the row just after r
r = r - k; % R is the ratio between the K and K+1 rows
% Find indices that are out of the range 1 to n and cap them
k(k<1 | isnan(k)) = 1;
kp1 = bsxfun( @min, kp1, n );
% Use simple linear interpolation for the valid percentages
y = (0.5+r).*x(kp1,:)+(0.5-r).*x(k,:);
% Make sure that values we hit exactly are copied rather than interpolated
exact = (r==-0.5);
if any(exact)
y(exact,:) = x(k(exact),:);
end
% Make sure that identical values are copied rather than interpolated
same = (x(k,:)==x(kp1,:));
if any(same(:))
x = x(k,:); % expand x
y(same) = x(same);
end
function y = interpColsDiffer(x, p, n)
%INTERPCOLSDIFFER A simple 1-D linear interpolation of columns that can
%deal with columns with differing numbers of valid entries (vector n).
[nrows, ncols] = size(x);
% Make p a column vector. n is already a row vector with ncols columns.
if isrow(p)
p = p';
end
% Form the grid of index values (numel(p) x numel(n))
r = (p/100)*n;
k = floor(r+0.5); % K gives the index for the row just before r
kp1 = k + 1; % K+1 gives the index for the row just after r
r = r - k; % R is the ratio between the K and K+1 rows
% Find indices that are out of the range 1 to n and cap them
k(k<1 | isnan(k)) = 1;
kp1 = bsxfun( @min, kp1, n );
% Convert K and Kp1 into linear indices
offset = nrows*(0:ncols-1);
k = bsxfun( @plus, k, offset );
kp1 = bsxfun( @plus, kp1, offset );
% Use simple linear interpolation for the valid percentages.
% Note that NaNs in r produce NaN rows.
y = (0.5-r).*x(k) + (0.5+r).*x(kp1);
% Make sure that values we hit exactly are copied rather than interpolated
exact = (r==-0.5);
if any(exact(:))
y(exact) = x(k(exact));
end
% Make sure that identical values are copied rather than interpolated
same = (x(k)==x(kp1));
if any(same(:))
x = x(k); % expand x
y(same) = x(same);
end
|
github
|
jamesjun/vistrack-master
|
plotAnimals_EODA.m
|
.m
|
vistrack-master/plotAnimals_EODA.m
| 1,656 |
utf_8
|
284d489e6f8e2cd7bb9a3ba663351686
|
function plotAnimals_EODA(vsTrialPool_E, vsTrialPool_L, vsTrialPool_P, strVar, fun1)
% plot correlatoin coefficient
csPhase = {'E', 'L', 'P'};
csAnimal = {'A', 'B', 'C', 'D', 'All'};
csZone = {'AZ', 'LM', 'NF', 'F'};
cvLM = cell(4,3);
mrLM = zeros(4,3);
figure;
% suptitle([strVar ', ' func2str(fun1)]);
%-------------------
% Plot per animal stats
for iAnimal = 1:numel(csAnimal)
subplot(1,5,iAnimal);
for iZone = 1:numel(csZone);
for iPhase = 1:numel(csPhase)
eval(sprintf('vsTrialPool = vsTrialPool_%s;', csPhase{iPhase}));
% S = poolTrials_location(vsTrialPool, iAnimal);
if iAnimal <= 4
S = poolTrials_IPI(vsTrialPool, iAnimal);
else
S = poolTrials_IPI(vsTrialPool, []);
end
[vlZone, strZone] = getZone(S, iZone);
eval(sprintf('vrZ = %s;', strVar));
mrLM(iZone, iPhase) = fun1(vrZ(vlZone));
end
end
h = bar(mrLM);
set(gca, 'XTickLabel', csZone);
set(h(1), 'FaceColor', 'r');
set(h(2), 'FaceColor', 'b');
set(h(3), 'FaceColor', 'g');
title(csAnimal{iAnimal});
end %for
end %func
function [vlZone, strZone] = getZone(S, iZone)
switch (iZone)
case 1 %all
vlZone = S.vlZone;
strZone = 'AZ';
case 2 %LM
vlZone = S.vrD1 <= 3 | S.vrD2 <= 3 | S.vrD3 <= 3 | S.vrD4 <= 3; %within landmark detection zone
strZone = 'LM<3';
case 3 %Fc<15
vlZone = S.vrDf < 14 & S.vrDf >= 3;
strZone = 'Fc4~15';
case 4 %F<3
vlZone = S.vrDf < 3;
strZone = 'F<3';
end
end %func
|
github
|
jamesjun/vistrack-master
|
calcGridStats.m
|
.m
|
vistrack-master/calcGridStats.m
| 1,787 |
utf_8
|
8e774ca996f9f96d64df19dded24592b
|
function [mnVisit, mnVisit1] = calcGridStats(vsTrialPool, img0, varname, fun2, mlMask)
% pixpercm = 1053.28/(sqrt(2)*100);
% nGrid = 20; %2.6854cm/grid
nGrid = 25; %3.3567cm/grid
% nGrid = 25;
% nTime = 1; %20 msec
fEODAs = 0;
vrX = poolVecFromStruct(vsTrialPool, 'vrX');
vrY = poolVecFromStruct(vsTrialPool, 'vrY');
switch upper(varname)
case 'EODAS'
vrZ = poolVecFromStruct(vsTrialPool, 'EODA');
fEODAs = 1;
fun1 = @(x)calcDistAsym(x);
otherwise
vrZ = poolVecFromStruct(vsTrialPool, varname);
fun1 = @(x)mean(x);
end
if nargin >= 4
fun1 = @(x)fun2(x);
end
%Averaging
% mnVisit = ...
% calcGrid(vrX, vrY, vrZ, fun1, img0, nGrid, [0, 0]) * 1/3 + ...
% (calcGrid(vrX, vrY, vrZ, fun1, img0, nGrid, [nGrid, 0]/2) + ...
% calcGrid(vrX, vrY, vrZ, fun1, img0, nGrid, [-nGrid, 0]/2) + ...
% calcGrid(vrX, vrY, vrZ, fun1, img0, nGrid, [0, nGrid]/2) + ...
% calcGrid(vrX, vrY, vrZ, fun1, img0, nGrid, [0, -nGrid]/2))/6;
mnVisit = calcGrid(vrX, vrY, vrZ, fun1, img0, nGrid, [0, 0]);
mnVisit1 = imresize(mnVisit, nGrid, 'nearest');
% maxVal = nanstd(mnVisit1(~isinf(mnVisit1)))*2;
maxVal = 2;
disp(maxVal);
% maxVal = 10;
if nargout == 0
mnVisit1(~mlMask) = 0;
mrVisit = uint8(mnVisit1 / maxVal * 255);
figure;
if nargin >= 5
imshow(rgbmix(img0, mrVisit, mlMask));
else
imshow(rgbmix(img0, mrVisit));
end
end
end
function mnVisit = calcGrid(vrX, vrY, vrZ, fun1, img0, nGrid, xy0)
vrX = vrX + xy0(1);
vrY = vrY + xy0(2);
viX = ceil(vrX/nGrid);
viY = ceil(vrY/nGrid);
[h, w] = size(img0);
h = h / nGrid;
w = w / nGrid;
mnVisit = zeros(h, w);
for iy=1:h
vlY = (viY == iy);
for ix=1:w
mnVisit(iy,ix) = fun1(vrZ(vlY & (viX == ix)));
end
end
end
|
github
|
jamesjun/vistrack-master
|
wef.m
|
.m
|
vistrack-master/wef.m
| 18,409 |
utf_8
|
a6aa27254651d2be7199663247ca0c36
|
function varargout = wef(vcCommand, arg1, arg2, arg3, arg4)
% wef command
if nargin<1, vcCommand='help'; end
if nargin<2, arg1=''; end
if nargin<3, arg2=''; end
if nargin<4, arg3=''; end
if nargin<5, arg4=''; end
switch vcCommand
case 'help'
help_();
case {'traj', 'trajectory'}
traj_(arg1);
case 'info-set'
info_set_(arg1, arg2);
case 'make-set' %collect trials
make_set_(arg1);
case 'plot-lc' %plot learning curve
plot_lc_(arg1, arg2);
case 'plot-probe' %plot probe
plot_probe_(arg1, arg2, arg3);
case 'test'
varargout{1} = test_(arg1, arg2, arg3, arg4);
end %switch
end %func
%--------------------------------------------------------------------------
function traj_(vcFile_prm)
S_mat = load_prm_(vcFile_prm);
mnImg = S_mat.P.I0;
mlMask = S_mat.P.MASK;
mnImg(~mlMask) = mnImg(~mlMask)/4;
figure; imshow(mnImg); hold on;
plot(S_mat.HEADXY(1,:), S_mat.HEADXY(2,:));
plot(S_mat.P.CENTERPOS(1), S_mat.P.CENTERPOS(2), 'r*');
plot(S_mat.P.CENTERPOS(1), S_mat.P.CENTERPOS(2), 'r*');
set(gcf,'Name', S_mat.EODTTL);
end %func
%--------------------------------------------------------------------------
function S_mat = load_prm_(vcFile_prm)
eval(sprintf('%s;', strrep(vcFile_prm, '.m', '')));
vcFile_mat = fullfile(vcDir, vcFile);
S_mat = load(vcFile_mat);
end %func
%--------------------------------------------------------------------------
function help_()
end %func
%--------------------------------------------------------------------------
function sync_()
end %func
%--------------------------------------------------------------------------
function plot_lc_(vcSet, vcAnimals)
% collect file names
[S_dataset, P] = load_set_(vcSet, vcAnimals);
if isempty(S_dataset), return; end
csAnimals = S_dataset.csAnimals;
mrPath_meter = pool_pathlen_(S_dataset, csAnimals, P) / 100;
mrPath_iqr = quantile(mrPath_meter, [.25,.5,.75])';
assignWorkspace_(mrPath_meter, mrPath_iqr);
figure;
errorbar_jjj([], mrPath_iqr); xlabel('Session #'); ylabel('Dist (m)');
grid on;
set(gcf,'Name',vcSet,'Color','w');
end %func
%--------------------------------------------------------------------------
function cs = vc2cs_(vc)
cs = arrayfun(@(x)x, vc, 'UniformOutput', 0);
end %func
%--------------------------------------------------------------------------
function mrPath = pool_pathlen_(S_dataset, csAnimals, P)
nTrialsPerSession = get_set_(P, 'nTrialsPerSession', 4);
cvrPath = cell(numel(csAnimals), 1);
for iAnimal = 1:numel(csAnimals)
% S_dataset.vsTrial_A
csTrial_ = getfield(S_dataset, sprintf('vsTrial_%s', csAnimals{iAnimal}));
% csTrials_ = reshape_(getfield(S_dataset, vcName_), nTrialsPerSession);
cvrPath{iAnimal} = reshape_(get_(csTrial_, 'pathLen_cm'), nTrialsPerSession);
end
nSessions = min(cellfun(@(x)size(x,2), cvrPath));
cvrPath = cellfun(@(x)x(:,1:nSessions), cvrPath, 'UniformOutput', 0);
mrPath = cell2mat(cvrPath);
end %func
%--------------------------------------------------------------------------
function ccPath = pool_(S_dataset, csAnimals, vcName)
ccPath = cell(numel(csAnimals), 1);
for iAnimal = 1:numel(csAnimals)
csTrial_ = getfield(S_dataset, sprintf('vsTrial_%s', csAnimals{iAnimal}));
ccPath{iAnimal} = cellstruct_get_(csTrial_, vcName);
end
end %func
%--------------------------------------------------------------------------
% create a dataset
function S = make_set_(vcSet)
[S_dataset, P] = load_set_(vcSet);
csAnimals = S_dataset.csAnimals;
% collect file names
% vcFile_trial_ = csFiles_trial{1};
% S_calib = calibrate_(vcFile_trial_); % correction factor for loading trial
% filter animals
S_set = struct();
for iAnimal = 1:numel(csAnimals) % go by animals and call importTrial
vcAnimal_ = csAnimals{iAnimal};
vcTrial_ = sprintf('vsTrial_%s', vcAnimal_);
vcProbe_ = sprintf('vsProbe_%s', vcAnimal_);
[S_set.(vcTrial_), S_set.(vcProbe_)] = import_trials_(csFiles_trial, vcAnimal_);
end
% write to file set
struct_save_(S_set, S_dataset.vcDataset);
end %func
%--------------------------------------------------------------------------
function P = mfile2struct_(vcFile_input_exclude_later_m)
% James Jun 2017 May 23
% Run a text file as .m script and result saved to a struct P
% _prm and _prb can now be called .prm and .prb files
eval(sprintf('%s;', strrep(vcFile_input_exclude_later_m, '.m', '')));
S_ws = whos();
csVars = {S_ws.name};
csVars = setdiff(csVars, 'vcFile_input_exclude_later_m');
P = struct();
for iVar=1:numel(csVars)
try
vcVar_ = csVars{iVar};
eval(sprintf('P.(''%s'') = %s;', vcVar_, vcVar_));
catch
disperr_();
end
end
end %func
%--------------------------------------------------------------------------
% function disperr_()
% Display error message and the error stack
function disperr_(vcMsg)
% ask user to email [email protected] ? for the error ticket?
dbstack('-completenames'); % display an error stack
vcErr = lasterr();
if nargin==0
fprintf(2, '%s\n', vcErr);
else
fprintf(2, '%s:\n\t%s\n', vcMsg, vcErr);
end
try gpuDevice(1); disp('GPU device reset'); catch, end
end %func
%--------------------------------------------------------------------------
% 7/31/17 JJJ: Documentation and added test ouput
function S_out = test_(vcFunc, cell_Input, nOutput, fVerbose)
% S_out = test_(vcFunc, {input1, input2, ...}, nOutput)
if nargin<2, cell_Input = {}; end
if nargin<3, nOutput = []; end
if nargin<4, fVerbose = ''; end
if isempty(nOutput), nOutput = 1; end
if ~iscell(cell_Input), cell_Input = {cell_Input}; end
if isempty(fVerbose), fVerbose = 1; end
delete_empty_files_(); % delete empty files
try
switch nOutput
case 0
feval(vcFunc, cell_Input{:});
S_out = [];
case 1
[out1] = feval(vcFunc, cell_Input{:});
S_out = makeStruct_(out1);
case 2
[out1, out2] = feval(vcFunc, cell_Input{:});
S_out = makeStruct_(out1, out2);
case 3
[out1, out2, out3] = feval(vcFunc, cell_Input{:});
S_out = makeStruct_(out1, out2, out3);
case 4
[out1, out2, out3, out4] = feval(vcFunc, cell_Input{:});
S_out = makeStruct_(out1, out2, out3, out4);
end %switch
if fVerbose
if nOutput>=1, fprintf('[%s: out1]\n', vcFunc); disp(S_out.out1); end
if nOutput>=2, fprintf('[%s: out2]\n', vcFunc); disp(S_out.out2); end
if nOutput>=3, fprintf('[%s: out3]\n', vcFunc); disp(S_out.out3); end
if nOutput>=4, fprintf('[%s: out4]\n', vcFunc); disp(S_out.out4); end
end
catch
disperr_();
S_out = [];
end
end %func
%--------------------------------------------------------------------------
% 7/31/17 JJJ: Documentation and test
function delete_empty_files_(vcDir)
if nargin<1, vcDir=[]; end
delete_files_(find_empty_files_(vcDir));
end %func
%--------------------------------------------------------------------------
% 7/31/17 JJJ: Documentation and test
function delete_files_(csFiles, fVerbose)
% Delete list of files
% delete_files_(vcFile)
% delete_files_(csFiles)
% delete_files_(csFiles, fVerbose)
if nargin<2, fVerbose = 1; end
if ischar(csFiles), csFiles = {csFiles}; end
for iFile = 1:numel(csFiles)
try
if exist(csFiles{iFile}, 'file')
delete(csFiles{iFile});
if fVerbose
fprintf('\tdeleted %s.\n', csFiles{iFile});
end
end
catch
disperr_();
end
end
end %func
%--------------------------------------------------------------------------
% 7/31/17 JJJ: Documentation and testing
function csFiles = find_empty_files_(vcDir)
% find files with 0 bytes
if nargin==0, vcDir = []; end
if isempty(vcDir), vcDir = pwd(); end
vS_dir = dir(vcDir);
viFile = find([vS_dir.bytes] == 0 & ~[vS_dir.isdir]);
csFiles = {vS_dir(viFile).name};
csFiles = cellfun(@(vc)[vcDir, filesep(), vc], csFiles, 'UniformOutput', 0);
end %func
%--------------------------------------------------------------------------
function S = makeStruct_(varargin)
%MAKESTRUCT all the inputs must be a variable.
%don't pass function of variables. ie: abs(X)
%instead create a var AbsX an dpass that name
S=[];
for i=1:nargin
S = setfield(S, inputname(i), varargin{i});
end
end %func
%--------------------------------------------------------------------------
function [csFiles_full, csFiles] = dir_(vcFilter, csExcl)
% return name of files full path, exclude files
if nargin>=2
if ischar(csExcl), csExcl = {csExcl}; end
csExcl = union(csExcl, {'.', '..'});
else
csExcl = [];
end
csFiles = dir(vcFilter);
csFiles = {csFiles.('name')};
csFiles = setdiff(csFiles, csExcl);
[vcDir, ~, ~] = fileparts(vcFilter);
if isempty(vcDir), vcDir='.'; end
csFiles_full = cellfun(@(vc)[vcDir, filesep(), vc], csFiles, 'UniformOutput', 0);
end %func
%--------------------------------------------------------------------------
function struct_save_(S, vcFile, fVerbose)
% 7/13/17 JJJ: Version check routine
if nargin<3, fVerbose = 0; end
if fVerbose
fprintf('Saving a struct to %s...\n', vcFile); t1=tic;
end
version_year = version('-release');
version_year = str2double(version_year(1:end-1));
if version_year >= 2017
save(vcFile, '-struct', 'S', '-v7.3', '-nocompression'); %faster
else
% disp('Saving with -nocompression flag failed. Trying without compression');
save(vcFile, '-struct', 'S', '-v7.3');
end
if fVerbose
fprintf('\ttook %0.1fs.\n', toc(t1));
end
end %func
%--------------------------------------------------------------------------
function S_calib = calibrate_(vcFile_trial)
% determine rotation and center
S = load(vcFile_trial);
hFig = figure;
imshow(imadjust(S.img0));
title('click (-50,0), (+50,0)cm');
set(gcf, 'Position', get(0, 'ScreenSize'));
[vrX, vrY] = ginput(2);
xy0 = [mean(vrX), mean(vrY)];
angXaxis = rad2deg(cart2pol(diff(vrX), diff(vrY))); %in rad
pixpercm = sqrt(diff(vrX)^2 + diff(vrY)^2) / 100;
hold on;
plot(vrX, vrY, 'r.');
plot(xy0(1), xy0(2), 'r.');
plot(S.xy0(1), S.xy0(2), 'go');
vcDisp = sprintf('%s, ang: %0.3f deg, pixpercm: %0.3f, x0: %0.1f, y0: %0.1f', ...
vcFile_trial, angXaxis, pixpercm, xy0(1), xy0(2));
disp(vcDisp);
title(vcDisp);
uiwait(msgbox('press okay to continue'));
close(hFig); drawnow;
S_calib = makeStruct_(angXaxis, pixpercm, xy0);
end %func
%--------------------------------------------------------------------------
function [csTrial, csProbe] = import_trials_(csFiles, vcAnimal)
[csTrial, csProbe] = deal({});
warning off;
for iFile = 1:numel(csFiles)
vcFile_ = csFiles{iFile};
try
[fAnimal, fProbe] = checkFile_(vcFile_, vcAnimal);
if ~fAnimal, continue; end
if fProbe
csProbe{end+1} = importTrial(vcFile_);
else
csTrial{end+1} = importTrial(vcFile_);
end
fprintf('%d/%d: %s\n', iFile, numel(csFiles), vcFile_);
catch
disperr_(vcFile_);
end
end
end %func
%--------------------------------------------------------------------------
function [fAnimal, fProbe] = checkFile_(vcFile, vcAnimal)
% returns if the animal name matches and whether probe or not
% file name takes "%##%#'
[~, vcDataId, ~] = fileparts(vcFile);
vcDataId = strrep(vcDataId, '_Track', '');
fAnimal = upper(vcDataId(4)) == upper(vcAnimal);
fProbe = numel(vcDataId) > 5;
end %func
%--------------------------------------------------------------------------
function val = get_set_(S, vcName, def_val)
% set a value if field does not exist (empty)
if isempty(S), val = def_val; return; end
if ~isstruct(S)
val = [];
fprintf(2, 'get_set_: %s be a struct\n', inputname(1));
return;
end
val = get_(S, vcName);
if isempty(val), val = def_val; end
end %func
%--------------------------------------------------------------------------
function cs = cellstruct_get_(cS, vcName)
% return cell of info
cs = cell(size(cS));
for i=1:numel(cs)
try
cs{i} = cS{i}.(vcName);
catch
;
end
end
end %func
%--------------------------------------------------------------------------
function varargout = get_(varargin)
% retrieve a field. if not exist then return empty
% [val1, val2] = get_(S, field1, field2, ...)
if nargin==0, varargout{1} = []; return; end
S = varargin{1};
if isempty(S), varargout{1} = []; return; end
if iscell(S)
out1 = [];
for i=1:numel(S)
try
out1(end+1) = S{i}.(varargin{2});
catch
;
end
end
varargout{1} = out1;
return;
end
for i=2:nargin
vcField = varargin{i};
try
varargout{i-1} = S.(vcField);
catch
varargout{i-1} = [];
end
end
end %func
%--------------------------------------------------------------------------
function mr = reshape_(vr, nwin)
nbins = floor(numel(vr)/nwin);
mr = reshape(vr(1:nbins*nwin), nwin, nbins);
end %func
%--------------------------------------------------------------------------
% 8/2/17 JJJ: Test and documentation
function assignWorkspace_(varargin)
% Assign variables to the Workspace
for i=1:numel(varargin)
if ~isempty(varargin{i})
assignin('base', inputname(i), varargin{i});
fprintf('assigned ''%s'' to workspace\n', inputname(i));
end
end
end %func
%--------------------------------------------------------------------------
function plot_probe_(vcSet, vcAnimals, vcProbe)
[S_dataset, P] = load_probe_(vcSet, vcAnimals, vcProbe);
csAnimals = S_dataset.csAnimals;
img0 = vsTrialPool_P{1}.img0;
mrImg_P = calcVisitCount(vsTrialPool_P, img0);
mlMask = getImageMask(img0, [0 60], 'CENTRE');
figure;
imshow(rgbmix(imadjust(img0), mrImg_P, mlMask));
title(sprintf('%s: %s', vcSet, sprintf('%s, ', csAnimals{:})));
grid on;
set(gcf,'Name',vcSet,'Color','w');
disp(cellstruct_get_(vsTrialPool_P, 'dataID')');
end %func
%--------------------------------------------------------------------------
function info_set_(vcSet, vcAnimals)
% vcSet: {'rand', 'randwide', 'none', 'cue', 'stable', 'shuffle'}
P = mfile2struct_('settings_wef.m');
if isempty(vcSet)
fprintf(2, 'Specify set name:\n\t%s\n', sprintf('%s, ', P.csNames_set{:}));
return;
end
vcSet = lower(vcSet);
eval(sprintf('vcDir = P.vcDir_%s;', vcSet));
eval(sprintf('vcDataset = P.vcDataset_%s;', vcSet));
eval(sprintf('csAnimals = P.csAnimals_%s;', vcSet));
if ~isempty(vcAnimals), csAnimals = vc2cs_(vcAnimals); end
% Show files in the set. trial duration and day
S_dataset = load(vcDataset);
ccDataId = pool_(S_dataset, csAnimals, 'dataID');
ccvtEod = pool_(S_dataset, csAnimals, 'TEOD');
csLine = {'b.-', 'r.-', 'g.-', 'k.-'};
figure; hold on;
for iAnimal = 1:numel(ccDataId)
csDataId_ = ccDataId{iAnimal};
viSession_ = cellfun(@(x)str2double(x([2,3,5])), csDataId_);
vt_dur_ = cellfun(@(x)diff(x([1,end])), ccvtEod{iAnimal});
plot(viSession_, vt_dur_, csLine{iAnimal});
end
legend(csAnimals);
end %func
%--------------------------------------------------------------------------
function [cvtDur, cviSession, csAnimals] = pool_duration_(S_dataset, csAnimals)
if nargin<2, csAnimals = {'A', 'B', 'C', 'D'}; end
ccDataId = pool_(S_dataset, csAnimals, 'dataID');
ccvtEod = pool_(S_dataset, csAnimals, 'TEOD');
for iAnimal = 1:numel(ccDataId)
cvtDur{iAnimal} = cellfun(@(x)diff(x([1,end])), ccvtEod{iAnimal});
cviSession{iAnimal} = cellfun(@(x)str2double(x([2,3,5])), ccDataId{iAnimal});
end
end %func
%--------------------------------------------------------------------------
function S_dataset = filter_duration_(S_dataset, maxDur)
[cvtDur, cviSession, csAnimals] = pool_duration_(S_dataset);
for iAnimal = 1:numel(cvtDur)
vcField_ = sprintf('vsTrial_%s', csAnimals{iAnimal});
csTrial_ = getfield(S_dataset, vcField_);
S_dataset.(vcField_) = csTrial_(cvtDur{iAnimal} < maxDur);
end
end %func
%--------------------------------------------------------------------------
function S_dataset = filter_valid_(S_dataset, csAnimals)
for iAnimal = 1:numel(csAnimals)
vcField_ = sprintf('vsTrial_%s', csAnimals{iAnimal});
csTrial_ = getfield(S_dataset, vcField_);
vl_ = cellfun(@(x)isfield(x, 'TEOD'), csTrial_);
S_dataset.(vcField_) = csTrial_(vl_);
end
end %func
%--------------------------------------------------------------------------
function [S_dataset, P] = load_set_(vcSet, vcAnimals)
% vcSet: {'rand', 'randwide', 'none', 'cue', 'stable', 'shuffle'}
if nargin<2, vcAnimals = ''; end
[S_dataset, P] = deal([]);
P = mfile2struct_('settings_wef.m');
if isempty(vcSet)
fprintf(2, 'Specify set name:\n\t%s\n', sprintf('%s, ', P.csNames_set{:}));
return;
end
vcSet = lower(vcSet);
eval(sprintf('vcDir = P.vcDir_%s;', vcSet)); % not needed
eval(sprintf('vcDataset = P.vcDataset_%s;', vcSet));
if ~isempty(vcAnimals)
csAnimals = vc2cs_(vcAnimals);
else
eval(sprintf('csAnimals = P.csAnimals_%s;', vcSet));
end
S_dataset = load(vcDataset);
S_dataset = filter_valid_(S_dataset, P.csAnimals);
S_dataset = filter_duration_(S_dataset, P.maxDur);
if vcDir(end) ~= filesep(), vcDir(end+1) = filesep(); end
csFiles_trial = dir_(sprintf('%s*_Track.mat', vcDir));
% add to the struct
S_dataset.csFiles_trial = csFiles_trial;
S_dataset.vcDataset = vcDataset;
S_dataset.csAnimals = csAnimals;
end %func
%--------------------------------------------------------------------------
function [csTrials_probe, P] = load_probe_(vcSet, vcAnimals, vcProbe)
% vcSet: {'rand', 'randwide', 'none', 'cue', 'stable', 'shuffle'}
if isempty(vcProbe), vcProbe = 'probe'; end
[csTrials_probe, P] = deal([]);
P = mfile2struct_('settings_wef.m');
if isempty(vcSet)
fprintf(2, 'Specify set name:\n\t%s\n', sprintf('%s, ', P.csNames_set{:}));
return;
end
vcSet = lower(vcSet);
eval(sprintf('vcDir = P.vcDir_%s;', vcSet)); % not needed
eval(sprintf('vcDataset = P.vcDataset_%s;', vcSet));
if ~isempty(vcAnimals)
csAnimals = vc2cs_(vcAnimals);
else
eval(sprintf('csAnimals = P.csAnimals_%s;', vcSet));
end
% collect trials directly
vcDir_relearn
S_dataset = load(vcDataset);
S_dataset = filter_valid_(S_dataset, P.csAnimals);
S_dataset = filter_duration_(S_dataset, P.maxDur);
if vcDir(end) ~= filesep(), vcDir(end+1) = filesep(); end
csFiles_trial = dir_(sprintf('%s*_Track.mat', vcDir));
% add to the struct
S_dataset.csFiles_trial = csFiles_trial;
S_dataset.vcDataset = vcDataset;
S_dataset.csAnimals = csAnimals;
end %func
|
github
|
jamesjun/vistrack-master
|
resize_figure.m
|
.m
|
vistrack-master/resize_figure.m
| 764 |
utf_8
|
bd43731bf60d356799068cb14e203419
|
%--------------------------------------------------------------------------
function hFig = resize_figure(hFig, posvec0, fRefocus)
if nargin<3, fRefocus = 1; end
height_taskbar = 40;
pos0 = get(groot, 'ScreenSize');
width = pos0(3);
height = pos0(4) - height_taskbar;
% width = width;
% height = height - 132; %width offset
% width = width - 32;
posvec = [0 0 0 0];
posvec(1) = max(round(posvec0(1)*width),1);
posvec(2) = max(round(posvec0(2)*height),1) + height_taskbar;
posvec(3) = min(round(posvec0(3)*width), width);
posvec(4) = min(round(posvec0(4)*height), height);
% drawnow;
if isempty(hFig)
hFig = figure; %create a figure
else
hFig = figure(hFig);
end
drawnow;
set(hFig, 'OuterPosition', posvec, 'Color', 'w', 'NumberTitle', 'off');
end %func
|
github
|
jamesjun/vistrack-master
|
plotAnimals_var.m
|
.m
|
vistrack-master/plotAnimals_var.m
| 2,069 |
utf_8
|
0f41a69599533668ddc4b5c75ad48ebc
|
function plotAnimals_var(vsTrialPool_E, vsTrialPool_L, vsTrialPool_P, strVar, fun1)
% plot correlatoin coefficient
vsPhase = {'E', 'L', 'P'};
cvLM = cell(4,3);
mrLM = zeros(4,3);
figure;
suptitle([strVar ', ' func2str(fun1)]);
%-------------------
% Plot per animal stats
for iZone = 1:4
subplot(3,2,iZone);
for iAnimal = 1:4
for iPhase = 1:3
eval(sprintf('vsTrialPool = vsTrialPool_%s;', vsPhase{iPhase}));
% S = poolTrials_location(vsTrialPool, iAnimal);
S = poolTrials_IPI(vsTrialPool, iAnimal);
[vlZone, strZone] = getZone(S, iZone);
eval(sprintf('vrZ = S.%s;', strVar));
mrLM(iAnimal, iPhase) = fun1(vrZ(vlZone));
end
end
h = bar(mrLM);
set(h(1), 'FaceColor', 'r');
set(h(2), 'FaceColor', 'b');
set(h(3), 'FaceColor', 'g');
set(gca, 'XTickLabel', {'A', 'B', 'C', 'D'});
title(strZone);
end %for
%-------------------
% Plot per loc stats
subplot(3,2,5);
mrLM = zeros(4,3);
for iZone = 1:4
for iPhase = 1:3
eval(sprintf('vsTrialPool = vsTrialPool_%s;', vsPhase{iPhase}));
% S = poolTrials_location(vsTrialPool, iAnimal);
S = poolTrials_IPI(vsTrialPool, iAnimal);
[vlZone, strZone] = getZone(S, iZone);
eval(sprintf('vrZ = S.%s;', strVar));
mrLM(iZone, iPhase) = fun1(vrZ(vlZone));
end
end %for
h = bar(mrLM);
title('All animals');
set(h(1), 'FaceColor', 'r');
set(h(2), 'FaceColor', 'b');
set(h(3), 'FaceColor', 'g');
set(gca, 'XTickLabel', {'AZ', 'LM<3', 'Fc<15', 'F<3'});
end %func
function [vlZone, strZone] = getZone(S, iZone)
switch (iZone)
case 1 %all
vlZone = S.vlZone;
strZone = 'AZ';
case 2 %LM
vlZone = S.vrD1 <= 3 | S.vrD2 <= 3 | S.vrD3 <= 3 | S.vrD4 <= 3; %within landmark detection zone
strZone = 'LM<3';
case 3 %Fc<15
vlZone = S.vrDf < 14 & S.vrDf >= 3;
strZone = 'Fc4~15';
case 4 %F<3
vlZone = S.vrDf < 3;
strZone = 'F<3';
end
end %func
|
github
|
jamesjun/vistrack-master
|
detectBlink.m
|
.m
|
vistrack-master/detectBlink.m
| 2,789 |
utf_8
|
4d77e592274809685aebd0257f16fd1f
|
function [iFrame, xyLED] = detectBlink(handles, mode, fAsk)
% Returns the absolute frame
if nargin<3, fAsk = 1; end
mode = lower(mode);
vidobj = handles.vidobj;
switch mode
case 'first'
FLIM1 = [1, 300];
FLIM1(2) = min(FLIM1(2), vidobj.NumberOfFrames);
xyLED = []; % auto-detect
case 'last'
FLIM1 = [-300, -1] + vidobj.NumberOfFrames + 1;
FLIM1(1) = max(FLIM1(1), 1);
xyLED = handles.xyLed;
otherwise
if isnumeric(mode)
FLIM1 = [-75, 75] + mode;
FLIM1 = min(max(FLIM1, 1), vidobj.NumberOfFrames);
mode = 'first';
else
error(sprintf('detectBlink-Unsupported mode-%s', mode));
end
end
h=msgbox('Loading... (this will close automatically)', 'detect LED blink'); drawnow;
% trImg = read(handles.vidobj, FLIM1);
% trImg = squeeze(trImg(:,:,1,:));
trImg = vid_read(handles.vidobj, FLIM1(1):FLIM1(2));
try close(h); catch, end;
if isempty(xyLED), xyLED = find_mov_max_(trImg); end
yRange = xyLED(2)+(-5:5);
xRange = xyLED(1)+(-5:5);
yRange1 = xyLED(2)+(-15:15);
xRange1 = xyLED(1)+(-15:15);
trInt = trImg(yRange, xRange,:);
trInt = mean(mean(trInt,1),2);
vrInt = trInt(:);
[vMax,iFrame] = max(vrInt);
[vMin,iFrameMin] = min(vrInt);
thresh = (vMax+vMin)/2; %vMax*.9 previously
iFrame = find(diff(vrInt>thresh)>0, 1, mode)+1;
if iFrame > 1 && iFrame < size(trImg,3)
hfig = figure;
subplot 231; imshow(trImg(yRange1,xRange1,iFrame-1));
title(num2str(iFrame-1));
subplot 232; imshow(trImg(yRange1,xRange1,iFrame));
title(num2str(iFrame));
subplot 233; imshow(trImg(yRange1,xRange1,iFrame+1));
title(num2str(iFrame+1));
subplot(2,3,4:6); bar(1:(diff(FLIM1)+1), vrInt); hold on;
plot(iFrame*[1 1]+.5, get(gca, 'YLim'), 'r-');
xlabel('Frame #'); ylabel('Intensity'); axis tight;
set(gcf,'Name',handles.vidFname);
button = questdlg('Is the blink detection correct?',handles.vidFname,'Yes','No','Yes');
if strcmp(button, 'Yes')
fAskUser = 0;
else
fAskUser = 1;
iFrame = nan;
end
try close(hfig), catch, end;
else
fAskUser = 1;
end
if fAskUser && fAsk
implay(trImg);
vcMsg = sprintf('Find the %s brightest blink, and close the movie', mode);
uiwait(msgbox({vcMsg, handles.vidFname}));
ans = inputdlg('Frame Number', 'First frame',1,{num2str(iFrame)});
iFrame = str2num(ans{1});
fprintf('Frame %d selected.\n', iFrame);
end
if ~isnan(iFrame)
iFrame = iFrame + FLIM1(1) - 1;
end
end %func
%--------------------------------------------------------------------------
function xyLed = find_mov_max_(trImg)
img_pp = (max(trImg,[],3) - min(trImg,[],3));
[~,imax_pp] = max(img_pp(:));
[yLed, xLed] = ind2sub(size(img_pp), imax_pp);
xyLed = [xLed, yLed];
end %func
|
github
|
jamesjun/vistrack-master
|
keyFcnPreview.m
|
.m
|
vistrack-master/keyFcnPreview.m
| 3,585 |
utf_8
|
33c946fb326af699a27132c483b27ed4
|
function keyFcnPreview(hFig, event)
% ensure the figure is still valid
if ~ishandle(hFig), return; end
timer1 = get(hFig, 'UserData');
S = get(timer1, 'UserData');
fRunning = strcmpi(timer1.Running, 'on');
handles = guidata(S.hObject);
nFrames = size(handles.MOV,3);
[~, vcDataID, ~] = fileparts(handles.vidFname);
[iFrame, hObject] = deal(S.iFrame, S.hObject);
switch lower(event.Key)
case 'h' %help
csHelp = { ...
'----Playback----',
'[SPACE]: start and stop video',
'(Shift) + LEFT/RIGHT: backward/forward (Shift: 4x)',
'[UP/DOWN]: Speed up/down',
'[HOME/END]: Go to start/end',
'[G]oto: Go to a specific frame}',
'----EDIT----',
'[F]lip head/tail',
'[C]ut: Trim video up to the current frame'};
msgbox(csHelp);
case 'space' % toggle start and stop
if fRunning, stop(timer1);
else start(timer1); end
case {'leftarrow', 'rightarrow', 'f', 'home', 'end', 'g'}
%'f' for flip, 'left' for back, 'right' for forward
if fRunning, stop(timer1); end
switch event.Key
case {'leftarrow', 'rightarrow'}
nStep = S.REPLAY_STEP * ifeq_(key_modifier_(event, 'shift'), 4, 1);
nStep = nStep * ifeq_(strcmpi(event.Key, 'leftarrow'), -1, 1);
S.iFrame = min(max(1, S.iFrame + nStep), nFrames);
case 'home', S.iFrame = 1;
case 'end', S.iFrame = nFrames;
case 'f', GUI_FLIP; %flip orientation
case 'g' % go to frame
S.iFrame = uigetnum(sprintf('Go to Frame (choose from 1-%d)', nFrames), S.iFrame);
if isempty(S.iFrame), return; end
if (S.iFrame < 1 || S.iFrame > nFrames), S.iFrame = nan; end
if isnan(S.iFrame), msgbox('Cancelled'); return; end
end
set(S.hImg, 'CData', imadjust(handles.MOV(:,:,S.iFrame)));
%annotate iamge
handles = guidata(S.hObject);
mrXC = bsxfun(@minus, handles.XC, handles.XC_off);
mrYC = bsxfun(@minus, handles.YC, handles.YC_off);
XC = mrXC(S.iFrame,:);
YC = mrYC(S.iFrame,:);
nxy = numel(XC);
X1 = interp1(2:nxy, XC(2:end), 2:.1:nxy, 'spline');
Y1 = interp1(2:nxy, YC(2:end), 2:.1:nxy, 'spline');
set(S.hPlot(1), 'XData', XC(2), 'YData', YC(2));
set(S.hPlot(2), 'XData', XC(3:end), 'YData', YC(3:end));
set(S.hPlot(3), 'XData', X1, 'YData', Y1);
set(S.hPlot(4), 'XData', XC(1), 'YData', YC(1));
case 'uparrow' %speed up
S.REPLAY_STEP = min(S.REPLAY_STEP+1, 30);
case 'downarrow' %speed up
S.REPLAY_STEP = max(S.REPLAY_STEP-1, 1);
case 'c' % cut up to here
if fRunning, stop(timer1); end
GUI_CUT;
end %switch
set(S.hTitle, 'String', ...
sprintf('F1: %d; T1: %0.3f s, Step: %d (%s)', ...
S.iFrame, S.TC1(S.iFrame), S.REPLAY_STEP, vcDataID));
set(timer1, 'UserData', S);
end %func
%--------------------------------------------------------------------------
% 7/24/2018: Copied from jrc3.m
function flag = key_modifier_(event, vcKey)
% Check for shift, alt, ctrl press
try
flag = any(strcmpi(event.Modifier, vcKey));
catch
flag = 0;
end
end %func
%--------------------------------------------------------------------------
% 7/24/2018: Copied from jrc3.m
function out = ifeq_(if_, true_, false_)
if (if_)
out = true_;
else
out = false_;
end
end %func
|
github
|
jamesjun/vistrack-master
|
untitled.m
|
.m
|
vistrack-master/untitled.m
| 3,151 |
utf_8
|
4e530a31eed8acf850dfab148815a7bb
|
function varargout = untitled(varargin)
% UNTITLED MATLAB code for untitled.fig
% UNTITLED, by itself, creates a new UNTITLED or raises the existing
% singleton*.
%
% H = UNTITLED returns the handle to a new UNTITLED or the handle to
% the existing singleton*.
%
% UNTITLED('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in UNTITLED.M with the given input arguments.
%
% UNTITLED('Property','Value',...) creates a new UNTITLED or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before untitled_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to untitled_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help untitled
% Last Modified by GUIDE v2.5 30-May-2013 08:54:16
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @untitled_OpeningFcn, ...
'gui_OutputFcn', @untitled_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 untitled is made visible.
function untitled_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 untitled (see VARARGIN)
% Choose default command line output for untitled
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes untitled wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = untitled_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 when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: delete(hObject) closes the figure
delete(hObject);
|
github
|
jamesjun/vistrack-master
|
imCorr.m
|
.m
|
vistrack-master/imCorr.m
| 1,331 |
utf_8
|
460780e6a045f95e65824afb696993ff
|
function mrC = imCorr(mrA, mrB)
% dimension of mrA, mrB must the same
nwin = 21;
nwinh = (nwin-1)/2;
h = size(mrA, 1);
w = size(mrA, 2);
mrA1 = zeros([h+nwinh*2, w+nwinh*2], class(mrA));
mrB1 = zeros([h+nwinh*2, w+nwinh*2], class(mrB));
mrA1(nwinh+1:end-nwinh, nwinh+1:end-nwinh) = mrA;
mrB1(nwinh+1:end-nwinh, nwinh+1:end-nwinh) = mrB;
mlMask = false(h+nwinh*2, nwin); %pad
mrA2 = zeros(nwin^2, h*w);
mrB2 = zeros(nwin^2, h*w);
i=1;
mrC = zeros(h, w);
for ic=(1+nwinh):w-nwinh
mrA1c = double(mrA1(:, ic-nwinh:ic+nwinh));
mrB1c = double(mrB1(:, ic-nwinh:ic+nwinh));
for ir=(1+nwinh):h-nwinh
mlMask1 = mlMask;
mlMask1(ir-nwinh:ir+nwinh, :) = 1;
mrC(ir-1, ic-1) = cov2(mrA1c(mlMask1), mrB1c(mlMask1));
% mrA2(:,i) = mrA1c(mlMask1);
% mrB2(:,i) = mrB1c(mlMask1);
% i=i+1;
% if ic==nwin && ir==nwin
% disp('debug');
% end
end
end
mrC(isnan(mrC)) = 1;
% mrC = reshape(corrMat(mrA2, mrB2, 1), [h, w]);
end %func
function c = cov2(a,b)
c = mean((a-mean(a)) .* (b-mean(b))) / var(a);
end
function [vrCorr, vrCov] = corrMat(M1, M2, dimm)
if nargin < 3
dimm = 1;
end
vrCov = mean(M1 .* M2, dimm) - mean(M1,dimm) .* mean(M2,dimm);
vrCorr = vrCov ./ (nanstd(M1,1,dimm) .* nanstd(M2,1,dimm));
vrCorr(isnan(vrCorr)) = 1;
end
|
github
|
jamesjun/vistrack-master
|
rgbmix.m
|
.m
|
vistrack-master/rgbmix.m
| 1,572 |
utf_8
|
284be1bb60a191cfe2408ae5f2ac0186
|
% mix the RGB to RGBbk in the masked area
function RGB = rgbmix(RGBbk, RGB, MASK, mode, mixRatio)
% RGB = rgbmix(RGBbk, RGB, MASK, 'mix', mixRatio)
% RGB = rgbmix(RGBbk, RGB, [], 'transparent', mixRatio)
if nargin<3, MASK = []; end
if nargin<4, mode = ''; end
if nargin<5, mixRatio = []; end
if isempty(mixRatio), mixRatio = .25; end
if isempty(mode)
if ~isempty(MASK)
mode = 'mix';
else
mode = 'transparent';
end
end
if numel(size(RGBbk)) == 2 %gray scale
if isa(RGBbk, 'double')
RGBbk = uint8(RGBbk/max(RGBbk(:)));
end
RGBbk = imgray2rgb(RGBbk, [0 255], 'gray');
end
if numel(size(RGB)) == 2 %gray scale
if ~isempty(MASK)
RGB(~MASK) = 0;
end
if isa(RGB, 'double')
RGB = uint8(RGB/max(RGB(:))*255);
end
RGB = imgray2rgb(RGB, [0 255], 'jet');
end
% R = RGBbk(:,:,1);
% G = RGBbk(:,:,1);
% B = RGBbk(:,:,1);
switch mode
case 'mix'
for iColor = 1:3
mr_ = uint8(RGB(:,:,iColor)*mixRatio + RGBbk(:,:,iColor)*(1-mixRatio));
if isempty(MASK)
RGB(:,:,iColor) = mr_;
else
mr1_ = RGB(:,:,iColor);
mr1_(MASK) = mr_(MASK);
RGB(:,:,iColor) = mr1_;
end
end
case 'transparent'
%mask is not used, instead RGBbk and RGB are simply added 50/50
for iColor = 1:3
RGB(:,:,iColor) = uint8(RGB(:,:,iColor)*mixRatio + RGBbk(:,:,iColor)*(1-mixRatio));
end
otherwise
error('rgbmix invalid mode');
end
end %func
|
github
|
jamesjun/vistrack-master
|
vistrack_20181015.m
|
.m
|
vistrack-master/vistrack_20181015.m
| 122,295 |
utf_8
|
08229098a0e298ed9b80430eefd19127
|
function varargout = vistrack(varargin)
vcCmd = 'help';
if nargin>=1, vcCmd = varargin{1}; else vcCmd = 'help'; end
if nargin>=2, vcArg1 = varargin{2}; else vcArg1 = ''; end
if nargin>=3, vcArg2 = varargin{3}; else vcArg2 = ''; end
if nargin>=4, vcArg3 = varargin{4}; else vcArg3 = ''; end
if nargin>=5, vcArg4 = varargin{5}; else vcArg4 = ''; end
if nargin>=6, vcArg5 = varargin{6}; else vcArg5 = ''; end
% Command interpreter
fReturn = 1;
switch lower(vcCmd)
case 'commit', commit_();
case 'help', help_(vcArg1);
case 'issue', issue_(vcArg1);
case 'wiki', wiki_(vcArg1);
case 'version'
if nargout>0
[varargout{1}, varargout{2}] = version_();
else
version_();
end
return;
case 'gui', GUI();
case 'edit', edit_(vcArg1);
case 'unit-test', unit_test_(vcArg1);
case 'update', update_(vcArg1);
case 'summary', varargout{1} = summary_(vcArg1);
case 'export', export_(vcArg1);
case 'videoreader', varargout{1} = VideoReader_(vcArg1);
case 'dependencies', disp_dependencies_();
case 'download-sample', download_sample_();
case 'load-cfg', varargout{1} = load_cfg_();
case 'clear-cache', clear_cache_();
case 'loadvid-preview', varargout{1} = loadvid_preview_(vcArg1, vcArg2);
case 'trial-sync', varargout{1} = trial_sync_(vcArg1);
case 'cam2adc-sync', varargout{1} = cam2adc_sync_(vcArg1, vcArg2);
case 'adc2cam-sync', varargout{1} = adc2cam_sync_(vcArg1, vcArg2);
case 'trial-visitcount', trial_timemap_(vcArg1);
case 'trial-fixsync', varargout{1} = trial_fixsync_(vcArg1);
case 'trial-save', varargout{1} = trial_save_(vcArg1);
case 'trialset-list', trialset_list_(vcArg1);
case 'trialset-learningcurve', trialset_learningcurve_(vcArg1);
case 'trialset-barplots', trialset_barplots_(vcArg1);
% case 'trialset-probe', trialset_probe_(vcArg1);
case 'trialset-exportcsv', trialset_exportcsv_(vcArg1);
case 'trialset-checkfps', trialset_checkfps_(vcArg1);
case 'trialset-coordinates', trialset_coordinates_(vcArg1);
case 'trialset-fixfps', trialset_fixfps_(vcArg1);
case 'trialset-import-track', trialset_import_track_(vcArg1);
case {'trialset-googlesheet', 'googlesheet'}, trialset_googlesheet_(vcArg1);
otherwise, help_();
end %switch
if fReturn, return; end
end %func
%--------------------------------------------------------------------------
function csMsg = summary_(handles)
t_dur = diff(handles.TC([1,end]));
[mrXYh_cam, vrT_cam] = get_traj_(handles);
[pathLen_cm, XH, YH, TC1] = trial_pathlen_(handles);
% [~, dataID, ~] = fileparts(handles.vidFname);
handles.vcVer = get_set_(handles, 'vcVer', 'pre v0.1.7');
handles.vcVer_date = get_set_(handles, 'vcVer_date', 'pre 7/20/2018');
vcFile_trial = get_(handles, 'editResultFile', 'String');
[vcFile_trial, S_dir] = fullpath_(vcFile_trial);
dataID = strrep(S_dir.name, '_Track.mat', '');
nDaysAgo = floor(now() - get_(S_dir, 'datenum'));
csMsg = {...
sprintf('DataID: %s', dataID);
sprintf(' duration: %0.3f sec', t_dur);
sprintf(' path-length: %0.3f m', pathLen_cm/100);
sprintf(' ave. speed: %0.3f m/s', pathLen_cm/100/t_dur);
sprintf(' -----');
sprintf(' Output file: %s', vcFile_trial);
sprintf(' Date analyzed: %s (%d days ago)', get_(S_dir, 'date'), nDaysAgo);
sprintf(' version used: %s (%s)', handles.vcVer, handles.vcVer_date);
sprintf(' -----');
sprintf(' Video file: %s', get_(handles, 'vidFname'));
sprintf(' FPS: %0.3f', get_(handles, 'FPS'));
sprintf(' ADC file: %s', get_(handles, 'editADCfile', 'String'));
sprintf(' ADC_TS file: %s', get_(handles, 'editADCfileTs', 'String'));
};
% csMsg = [csMsg; get_(handles, 'csSettings')];
if nargout==0, disp(csMsg); end
end %func
%--------------------------------------------------------------------------
% 7/26/2018 JJJ: Copied from GUI.m
function [vcFile_full, S_dir] = fullpath_(vcFile)
[vcDir_, vcFile_, vcExt_] = fileparts(vcFile);
if isempty(vcDir_)
vcDir_ = pwd();
vcFile_full = fullfile(vcDir_, vcFile);
else
vcFile_full = vcFile;
end
if nargout>=2, S_dir = dir(vcFile_full); end
end %func
%--------------------------------------------------------------------------
function S_dir = file_dir_(vcFile_trial)
if exist_file_(vcFile_trial)
S_dir = dir(vcFile_trial);
else
S_dir = [];
end
end %func
%--------------------------------------------------------------------------
function [mrXY_head, vrT] = get_traj_(handles)
P = load_settings_(handles);
Xs = filtPos(handles.XC, P.TRAJ_NFILT, 1);
Ys = filtPos(handles.YC, P.TRAJ_NFILT, 1);
mrXY_head = [Xs(:,2), Ys(:,2)];
vrT = get_(handles, 'TC');
end %func
%--------------------------------------------------------------------------
function commit_()
S_cfg = load_cfg_();
if exist_dir_('.git'), fprintf(2, 'Cannot commit from git repository\n'); return; end
% Delete previous files
S_warning = warning();
warning('off');
delete_empty_files_();
delete([S_cfg.vcDir_commit, '*']);
warning(S_warning);
% Copy files
copyfile_(S_cfg.csFiles_commit, S_cfg.vcDir_commit, '.');
edit_('change_log.txt');
end %func
%--------------------------------------------------------------------------
function delete_empty_files_(vcDir)
if nargin<1, vcDir=[]; end
delete_files_(find_empty_files_(vcDir));
end %func
%--------------------------------------------------------------------------
function csFiles = find_empty_files_(vcDir)
% find files with 0 bytes
if nargin==0, vcDir = []; end
if isempty(vcDir), vcDir = pwd(); end
vS_dir = dir(vcDir);
viFile = find([vS_dir.bytes] == 0 & ~[vS_dir.isdir]);
csFiles = {vS_dir(viFile).name};
csFiles = cellfun(@(vc)[vcDir, filesep(), vc], csFiles, 'UniformOutput', 0);
end %func
%--------------------------------------------------------------------------
function delete_files_(csFiles)
for iFile = 1:numel(csFiles)
try
if exist(csFiles{iFile}, 'file')
delete(csFiles{iFile});
fprintf('\tdeleted %s.\n', csFiles{iFile});
end
catch
disperr_();
end
end
end %func
%--------------------------------------------------------------------------
% 9/29/17 JJJ: Displaying the version number of the program and what's used. #Tested
function [vcVer, vcDate] = version_()
if nargin<1, vcFile_prm = ''; end
vcVer = 'v0.3.7';
vcDate = '8/29/2018';
if nargout==0
fprintf('%s (%s) installed\n', vcVer, vcDate);
edit_('change_log.txt');
end
end %func
%--------------------------------------------------------------------------
function csHelp = help_(vcCommand)
if nargin<1, vcCommand = ''; end
if ~isempty(vcCommand), wiki_(vcCommand); return; end
csHelp = {...
'';
'Usage: vistrack command arg1 arg2 ...';
'';
'# Documentation';
' vistrack help';
' Display a help menu';
' vistrack version';
' Display the version number and the updated date';
' vistrack wiki';
' Open vistrack Wiki on GitHub';
' vistrack issue';
' Post an issue at GitHub (log-in with your GitHub account)';
'';
'# Main commands';
' vistrack edit (mysettings.prm)';
' Edit .vistrack file currently working on';
' vistrack setprm myparam.prm';
' Select a .prm file to use';
' vistrack clear';
' Clear cache';
' vistrack clear myparam.prm';
' Delete previous results (files: _jrc.mat, _spkwav.jrc, _spkraw.jrc, _spkfet.jrc)';
'';
'# Batch process';
' vistrack dir myparam.prm';
' List all recording files to be clustered together (csFile_merge)';
'';
'# Deployment';
' vistrack update';
' Update from Github';
' vistrack download-sample';
' Download a sample video from Dropbox';
' vistrack update version';
' Download specific version from Github';
' vistrack commit';
' Commit vistrack code to Github';
' vistrack unit-test';
' Run a suite of unit teste.';
'';
};
if nargout==0, disp_cs_(csHelp); end
end %func
%--------------------------------------------------------------------------
function disp_cs_(cs)
% display cell string
cellfun(@(s)fprintf('%s\n',s), cs);
end %func
%--------------------------------------------------------------------------
% 9/27/17 JJJ: Created
function issue_(vcMode)
% issue_
% issue_ post
if nargin<1, vcMode = 'search'; end
switch lower(vcMode)
case 'post', web_('https://github.com/jamesjun/vistrack/issues/new')
otherwise, web_('https://github.com/jamesjun/vistrack/issues')
end %switch
end %func
%--------------------------------------------------------------------------
% 9/27/17 JJJ: Created
function wiki_(vcPage)
if nargin<1, vcPage = ''; end
if isempty(vcPage)
web_('https://github.com/jamesjun/vistrack/wiki');
else
web_(['https://github.com/jamesjun/vistrack/wiki/', vcPage]);
end
end %func
%--------------------------------------------------------------------------
function web_(vcPage)
if isempty(vcPage), return; end
if ~ischar(vcPage), return; end
try
% use system browser
if ispc()
system(['start ', vcPage]);
elseif ismac()
system(['open ', vcPage]);
elseif isunix()
system(['gnome-open ', vcPage]);
else
web(vcPage);
end
catch
web(vcPage); % use matlab default web browser
end
end %func
%--------------------------------------------------------------------------
% 10/8/17 JJJ: Created
% 3/20/18 JJJ: captures edit failure (when running "matlab -nodesktop")
function edit_(vcFile)
% vcFile0 = vcFile;
if isempty(vcFile), vcFile = mfilename(); end
if ~exist_file_(vcFile)
fprintf(2, 'File does not exist: %s\n', vcFile);
return;
end
fprintf('Editing %s\n', vcFile);
try edit(vcFile); catch, end
end %func
%--------------------------------------------------------------------------
% 9/26/17 JJJ: Created and tested
function flag = exist_file_(vcFile, fVerbose)
if nargin<2, fVerbose = 0; end
if ~ischar(vcFile), flag = 0; return; end
if isempty(vcFile)
flag = 0;
else
flag = ~isempty(dir(vcFile));
end
if fVerbose && ~flag
fprintf(2, 'File does not exist: %s\n', vcFile);
end
end %func
%--------------------------------------------------------------------------
function nFailed = unit_test_(vcArg1, vcArg2, vcArg3)
% 2017/2/24. James Jun. built-in unit test suite (request from Karel Svoboda)
% run unit test
%[Usage]
% unit_test()
% run all
% unit_test(iTest)
% run specific test again and show profile
% unit_test('show')
% run specific test again and show profile
% @TODO: test using multiple datasets and parameters.
global fDebug_ui;
if nargin<1, vcArg1 = ''; end
if nargin<2, vcArg2 = ''; end
if nargin<3, vcArg3 = ''; end
cd(fileparts(mfilename('fullpath'))); % move to jrclust folder
% if ~exist_file_('sample.bin'), jrc3('download', 'sample'); end
nFailed = 0;
profile('clear'); %reset profile stats
csCmd = {...
'close all; clear all;', ... %start from blank
'vistrack', ...
'vistrack help', ...
'vistrack version', ...
'vistrack wiki', ...
'vistrack issue', ...
}; %last one should be the manual test
if ~isempty(vcArg1)
switch lower(vcArg1)
case {'show', 'info', 'list', 'help'}
arrayfun(@(i)fprintf('%d: %s\n', i, csCmd{i}), 1:numel(csCmd));
return;
case {'manual', 'ui', 'ui-manual'}
iTest = numel(csCmd); % + [-1,0];
case {'traces', 'ui-traces'}
iTest = numel(csCmd)-2; % second last
otherwise
iTest = str2num(vcArg1);
end
fprintf('Running test %s: %s\n', vcArg1, csCmd{iTest});
csCmd = csCmd(iTest);
end
vlPass = false(size(csCmd));
[csError, cS_prof] = deal(cell(size(csCmd)));
vrRunTime = zeros(size(csCmd));
for iCmd = 1:numel(csCmd)
eval('close all; fprintf(''\n\n'');'); %clear memory
fprintf('Test %d/%d: %s\n', iCmd, numel(csCmd), csCmd{iCmd});
t1 = tic;
profile('on');
fDebug_ui = 1;
% set0_(fDebug_ui);
try
if any(csCmd{iCmd} == '(' | csCmd{iCmd} == ';') %it's a function
evalin('base', csCmd{iCmd}); %run profiler
else % captured by profile
csCmd1 = strsplit(csCmd{iCmd}, ' ');
feval(csCmd1{:});
end
vlPass(iCmd) = 1; %passed test
catch
csError{iCmd} = lasterr();
fprintf(2, '\tTest %d/%d failed\n', iCmd, numel(csCmd));
end
vrRunTime(iCmd) = toc(t1);
cS_prof{iCmd} = profile('info');
end
nFailed = sum(~vlPass);
fprintf('Unit test summary: %d/%d failed.\n', sum(~vlPass), numel(vlPass));
for iCmd = 1:numel(csCmd)
if vlPass(iCmd)
fprintf('\tTest %d/%d (''%s'') took %0.1fs.\n', iCmd, numel(csCmd), csCmd{iCmd}, vrRunTime(iCmd));
else
fprintf(2, '\tTest %d/%d (''%s'') failed:%s\n', iCmd, numel(csCmd), csCmd{iCmd}, csError{iCmd});
end
end
if numel(cS_prof)>1
assignWorkspace_(cS_prof);
disp('To view profile, run: profview(0, cS_prof{iTest});');
else
profview(0, cS_prof{1});
end
fDebug_ui = [];
% set0_(fDebug_ui);
end %func
%--------------------------------------------------------------------------
% 9/26/17 JJJ: Output message is added
% 8/2/17 JJJ: Test and documentation
function vcMsg = assignWorkspace_(varargin)
% Assign variables to the Workspace
vcMsg = {};
for i=1:numel(varargin)
if ~isempty(varargin{i})
assignin('base', inputname(i), varargin{i});
vcMsg{end+1} = sprintf('assigned ''%s'' to workspace\n', inputname(i));
end
end
vcMsg = cell2mat(vcMsg);
if nargout==0, fprintf(vcMsg); end
end %func
%--------------------------------------------------------------------------
function update_(vcVersion)
fOverwrite = 1;
if ~exist_dir_('.git')
fprintf(2, 'Not a git repository. run "git clone https://github.com/jamesjun/vistrack"\n');
return;
end
if nargin<1, vcVersion = ''; end
S_cfg = load_cfg_();
% delete_file_(get_(S_cfg, 'csFiles_delete'));
repoURL = 'https://github.com/jamesjun/vistrack';
try
if isempty(vcVersion)
if fOverwrite
code = system('git fetch --all');
code = system('git reset --hard origin/master');
else
code = system('git pull'); % do not overwrite existing changes
end
else
code = system('git fetch --all');
code = system(sprintf('git reset --hard "%s"', vcVersion));
end
catch
code = -1;
end
if code ~= 0
fprintf(2, 'Not a git repository. Please run the following command to clone from GitHub.\n');
fprintf(2, '\tRun system(''git clone %s.git''\n', repoURL);
fprintf(2, '\tor install git from https://git-scm.com/downloads\n');
else
edit('change_log.txt');
end
end %func
%--------------------------------------------------------------------------
% 11/5/17 JJJ: added vcDir_from
% 9/26/17 JJJ: multiple targeting copy file. Tested
function copyfile_(csFiles, vcDir_dest, vcDir_from)
% copyfile_(vcFile, vcDir_dest)
% copyfile_(csFiles, vcDir_dest)
% copyfile_(csFiles, csDir_dest)
if nargin<3, vcDir_from = ''; end
% Recursion if cell is used
if iscell(vcDir_dest)
csDir_dest = vcDir_dest;
for iDir = 1:numel(csDir_dest)
try
copyfile_(csFiles, csDir_dest{iDir});
catch
disperr_();
end
end
return;
end
if ischar(csFiles), csFiles = {csFiles}; end
for iFile=1:numel(csFiles)
vcPath_from_ = csFiles{iFile};
if ~isempty(vcDir_from), vcPath_from_ = fullfile(vcDir_from, vcPath_from_); end
if exist_dir_(vcPath_from_)
[vcPath_,~,~] = fileparts(vcPath_from_);
vcPath_from_ = sprintf('%s%s*', vcPath_, filesep());
vcPath_to_ = sprintf('%s%s%s', vcDir_dest, filesep(), dir_filesep_(csFiles{iFile}));
mkdir_(vcPath_to_);
% disp([vcPath_from_, '; ', vcPath_to_]);
else
vcPath_to_ = vcDir_dest;
fCreatedDir_ = mkdir_(vcPath_to_);
if fCreatedDir_
disp(['Created a folder ', vcPath_to_]);
end
end
try
vcEval1 = sprintf('copyfile ''%s'' ''%s'' f;', vcPath_from_, vcPath_to_);
eval(vcEval1);
fprintf('\tCopied ''%s'' to ''%s''\n', vcPath_from_, vcPath_to_);
catch
fprintf(2, '\tFailed to copy ''%s''\n', vcPath_from_);
end
end
end %func
%--------------------------------------------------------------------------
% 8/7/2018 JJJ
function flag = exist_dir_(vcDir)
if isempty(vcDir)
flag = 0;
else
S_dir = dir(vcDir);
if isempty(S_dir)
flag = 0;
else
flag = sum([S_dir.isdir]) > 0;
end
% flag = exist(vcDir, 'dir') == 7;
end
end %func
%--------------------------------------------------------------------------
function fCreatedDir = mkdir_(vcDir)
% make only if it doesn't exist. provide full path for dir
fCreatedDir = exist_dir_(vcDir);
if ~fCreatedDir
try
mkdir(vcDir);
catch
fCreatedDir = 0;
end
end
end %func
%--------------------------------------------------------------------------
% 17/12/5 JJJ: Error info is saved
% Display error message and the error stack
function disperr_(vcMsg, hErr)
% disperr_(vcMsg): error message for user
% disperr_(vcMsg, hErr): hErr: MException class
% disperr_(vcMsg, vcErr): vcErr: error string
try
dbstack('-completenames'); % display an error stack
if nargin<1, vcMsg = ''; end
if nargin<2, hErr = lasterror('reset'); end
if ischar(hErr) % properly formatted error
vcErr = hErr;
else
% save_err_(hErr, vcMsg); % save hErr object?
vcErr = hErr.message;
end
catch
vcErr = '';
end
if nargin==0
fprintf(2, '%s\n', vcErr);
elseif ~isempty(vcErr)
fprintf(2, '%s:\n\t%s\n', vcMsg, vcErr);
else
fprintf(2, '%s:\n', vcMsg);
end
% try gpuDevice(1); disp('GPU device reset'); catch, end
end %func
%--------------------------------------------------------------------------
function hFig = create_figure_(vcTag, vrPos, vcName, fToolbar, fMenubar)
if nargin<2, vrPos = []; end
if nargin<3, vcName = ''; end
if nargin<4, fToolbar = 0; end
if nargin<5, fMenubar = 0; end
if isempty(vcTag)
hFig = figure();
elseif ischar(vcTag)
hFig = figure_new_(vcTag);
else
hFig = vcTag;
end
set(hFig, 'Name', vcName, 'NumberTitle', 'off', 'Color', 'w');
clf(hFig);
set(hFig, 'UserData', []); %empty out the user data
if ~fToolbar
set(hFig, 'ToolBar', 'none');
else
set(hFig, 'ToolBar', 'figure');
end
if ~fMenubar
set(hFig, 'MenuBar', 'none');
else
set(hFig, 'MenuBar', 'figure');
end
if ~isempty(vrPos), resize_figure_(hFig, vrPos); end
end %func
%--------------------------------------------------------------------------
function close_(varargin)
for i=1:nargin
v_ = varargin{i};
try
if iscell(v_)
close_(v_{:});
elseif numel(v_)>1
close_(v_);
elseif numel(v_) == 1
close(v_);
end
catch
;
end
end
end %func
%--------------------------------------------------------------------------
function hFig = figure_new_(vcTag, vcTitle, vrPos)
if nargin<1, vcTag = ''; end
if nargin<2, vcTitle = ''; end
if nargin<3, vrPos = []; end
if ~isempty(vcTag)
%remove prev tag duplication
delete_multi_(findobj('Tag', vcTag, 'Type', 'Figure'));
end
hFig = figure('Tag', vcTag, 'Color', 'w', 'NumberTitle', 'off', 'Name', vcTitle);
if ~isempty(vrPos), resize_figure_(hFig, vrPos); drawnow; end
end %func
%--------------------------------------------------------------------------
function hFig = resize_figure_(hFig, posvec0, fRefocus)
if nargin<3, fRefocus = 1; end
height_taskbar = 40;
pos0 = get(groot, 'ScreenSize');
width = pos0(3);
height = pos0(4) - height_taskbar;
% width = width;
% height = height - 132; %width offset
% width = width - 32;
posvec = [0 0 0 0];
posvec(1) = max(round(posvec0(1)*width),1);
posvec(2) = max(round(posvec0(2)*height),1) + height_taskbar;
posvec(3) = min(round(posvec0(3)*width), width);
posvec(4) = min(round(posvec0(4)*height), height);
% drawnow;
if isempty(hFig)
hFig = figure; %create a figure
else
hFig = figure(hFig);
end
drawnow;
set(hFig, 'OuterPosition', posvec, 'Color', 'w', 'NumberTitle', 'off');
end %func
%--------------------------------------------------------------------------
function delete_multi_(varargin)
% provide cell or multiple arguments
for i=1:nargin
try
vr1 = varargin{i};
if numel(vr1)==1
delete(varargin{i});
elseif iscell(vr1)
for i1=1:numel(vr1)
try
delete(vr1{i1});
catch
end
end
else
for i1=1:numel(vr1)
try
delete(vr1(i1));
catch
end
end
end
catch
end
end
end %func
%--------------------------------------------------------------------------
function delete_(varargin)
for i=1:nargin()
try
v_ = varargin{i};
if iscell(v_)
delete_(v_{:});
elseif numel(v_) > 1
for i=1:numel(v_), delete_(v_(i)); end
elseif numel(v_) == 1
delete(v_);
end
catch
;
end
end
end %func
%--------------------------------------------------------------------------
% 7/19/18: Copied from jrc3.m
function val = get_set_(S, vcName, def_val)
% set a value if field does not exist (empty)
if isempty(S), S = get(0, 'UserData'); end
if isempty(S), val = def_val; return; end
if ~isstruct(S)
val = [];
fprintf(2, 'get_set_: %s must be a struct\n', inputname(1));
return;
end
val = get_(S, vcName);
if isempty(val), val = def_val; end
end %func
%--------------------------------------------------------------------------
% 7/19/18: Copied from jrc3.m
function varargout = get_(varargin)
% retrieve a field. if not exist then return empty
% [val1, val2] = get_(S, field1, field2, ...)
% val = get_(S, 'struct1', 'struct2', 'field');
if nargin==0, varargout{1} = []; return; end
S = varargin{1};
if isempty(S), varargout{1} = []; return; end
if nargout==1 && nargin > 2
varargout{1} = get_recursive_(varargin{:}); return;
end
for i=2:nargin
vcField = varargin{i};
try
varargout{i-1} = S.(vcField);
catch
varargout{i-1} = [];
end
end
end %func
%--------------------------------------------------------------------------
function out = get_recursive_(varargin)
% recursive get
out = [];
if nargin<2, return; end
S = varargin{1};
for iField = 2:nargin
try
out = S.(varargin{iField});
if iField == nargin, return; end
S = out;
catch
out = [];
end
end % for
end %func
%--------------------------------------------------------------------------
% 7/19/2018
function P = load_settings_(handles)
% P = load_settings_()
% P = load_settings_(handles)
if nargin<1, handles = []; end
P = load_cfg_();
P_ = [];
try
csSettings = get(handles.editSettings, 'String');
P_ = file2struct(csSettings);
catch
P_ = file2struct(P.vcFile_settings);
end
P = struct_merge_(P, P_);
end %func
%--------------------------------------------------------------------------
% 7/19/2018 JJJ: Copied from jrc3.m
function P = struct_merge_(P, P1, csNames)
% Merge second struct to first one
% P = struct_merge_(P, P_append)
% P = struct_merge_(P, P_append, var_list) : only update list of variable names
if isempty(P), P=P1; return; end % P can be empty
if isempty(P1), return; end
if nargin<3, csNames = fieldnames(P1); end
if ischar(csNames), csNames = {csNames}; end
for iField = 1:numel(csNames)
vcName_ = csNames{iField};
if isfield(P1, vcName_), P.(vcName_) = P1.(vcName_); end
end
end %func
%--------------------------------------------------------------------------
function [mrPath, mrDur, S_trialset, cS_trial] = trialset_learningcurve_(vcFile_trialset)
% It loads the files
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
S_trialset = load_trialset_(vcFile_trialset);
[pixpercm, angXaxis] = struct_get_(S_trialset.P, 'pixpercm', 'angXaxis');
[tiImg, vcType_uniq, vcAnimal_uniq, viImg, csFiles_Track] = ...
struct_get_(S_trialset, 'tiImg', 'vcType_uniq', 'vcAnimal_uniq', 'viImg', 'csFiles_Track');
hMsg = msgbox('Analyzing... (This closes automatically)');
[trDur, trPath, trFps] = deal(nan(size(tiImg)));
fprintf('Analyzing\n\t');
warning off;
t1 = tic;
cS_trial = {};
csField_load = setdiff(S_trialset.P.csFields, {'MOV', 'ADC','img1','img00'}); % do not load 'MOV' field since it's big and unused
for iTrial = 1:numel(viImg)
try
S_ = load(csFiles_Track{iTrial}, csField_load{:});
S_.vcFile_Track = csFiles_Track{iTrial};
iImg_ = viImg(iTrial);
cS_trial{end+1} = S_;
if ~S_trialset.vlProbe(iTrial)
trPath(iImg_) = trial_pathlen_(S_, pixpercm, angXaxis);
trDur(iImg_) = diff(S_.TC([1,end]));
end
trFps(iImg_) = get_set_(S_, 'FPS', nan);
fprintf('.');
catch
fprintf(2, '\n\tExport error: %s\n\t%s\n', csFiles_Track{iTrial}, lasterr());
end
end %for
fprintf('\n\ttook %0.1fs\n', toc(t1));
close_(hMsg);
% compact by removing nan.
% date x session x animal (trPath,trDur) -> session x date x animal (trPath_,trDur_)
[nDates, nSessions, nAnimals] = size(tiImg);
[trPath_, trDur_] = deal(nan(nSessions, nDates, nAnimals));
for iAnimal = 1:size(tiImg,3)
[mrPath1, mrDur1] = deal(trPath(:,:,iAnimal)', trDur(:,:,iAnimal)');
vi1 = find(~isnan(mrPath1));
vi2 = 1:numel(vi1);
[mrPath2, mrDur2] = deal(nan(nSessions, nDates));
[mrPath2(vi2), mrDur2(vi2)] = deal(mrPath1(vi1), mrDur1(vi1));
trPath_(:,:,iAnimal) = mrPath2;
trDur_(:,:,iAnimal) = mrDur2;
end
[trPath_, trDur_] = deal(permute(trPath_,[1,3,2]), permute(trDur_,[1,3,2])); % nSessions x nAnimals x nDate
[mrPath, mrDur] = deal(reshape(trPath_,[],nDates)/100, reshape(trDur_,[],nDates));
viCol = find(~any(isnan(mrPath)));
[mrPath, mrDur] = deal(mrPath(:,viCol), mrDur(:,viCol));
% Export to csv
vcAnimals = cell2mat(S_trialset.csAnimals);
vcFile_path = subsFileExt_(vcFile_trialset, sprintf('_pathlen_%s.csv', vcAnimals));
vcFile_dur = subsFileExt_(vcFile_trialset, sprintf('_duration_%s.csv', vcAnimals));
csvwrite_(vcFile_path, mrPath', 'Learning-curve path-length (m), [sessions, trials]');
csvwrite_(vcFile_dur, mrDur', 'Learning-curve: duration (s), [sessions, trials]');
if nargout==0
% FPS integrity check
hFig = plot_trialset_img_(S_trialset, trFps);
set(hFig, 'Name', sprintf('FPS: %s', vcFile_trialset));
% Plot learning curve
figure_new_('', ['Learning curve: ', vcFile_trialset, '; Animals:', cell2mat(S_trialset.csAnimals)]);
subplot 211; errorbar_iqr_(mrPath); ylabel('Dist (m)'); grid on; xlabel('Session #');
subplot 212; errorbar_iqr_(mrDur); ylabel('Duration (s)'); grid on; xlabel('Sesision #');
end
end %func
%--------------------------------------------------------------------------
function vcMsg = csvwrite_(vcFile, var, vcMsg)
if nargin<3, vcVar = inputname(2); end
try
csvwrite(vcFile, var);
vcMsg = sprintf('"%s" wrote to %s', vcMsg, vcFile);
catch
vcMsg = sprintf('Failed to write "s" to %s', vcMsg, vcFile);
end
if nargout==0, disp(vcMsg); end
end %func
%--------------------------------------------------------------------------
function [S_trialset, trFps] = trialset_checkfps_(vcFile_trialset)
% It loads the files
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
% fFix_sync = 0;
S_trialset = load_trialset_(vcFile_trialset);
% [pixpercm, angXaxis] = struct_get_(S_trialset.P, 'pixpercm', 'angXaxis');
[tiImg, vcType_uniq, vcAnimal_uniq, viImg, csFiles_Track] = ...
struct_get_(S_trialset, 'tiImg', 'vcType_uniq', 'vcAnimal_uniq', 'viImg', 'csFiles_Track');
warning off;
hMsg = msgbox('Analyzing... (This closes automatically)');
t1=tic;
trFps = nan(size(tiImg));
for iTrial = 1:numel(viImg)
try
S_ = load(csFiles_Track{iTrial}, 'TC', 'XC', 'YC', 'xy0', 'vidFname', 'FPS', 'img0');
if isempty(get_(S_, 'FPS')) || isempty(get_(S_, 'TC')), error('FPS or TC not found'); end
S_.vcFile_Track = csFiles_Track{iTrial};
% if fFix_sync, S_ = trial_fixsync_(S_, 0); end
iImg_ = viImg(iTrial);
trFps(iImg_) = get_set_(S_, 'FPS', nan);
fprintf('.');
catch
fprintf('\n\t%s: %s\n', csFiles_Track{iTrial}, lasterr());
end
end %for
fprintf('\n\ttook %0.1fs\n', toc(t1));
close_(hMsg);
if nargout==0
hFig = plot_trialset_img_(S_trialset, trFps);
set(hFig, 'Name', sprintf('FPS: %s', vcFile_trialset));
end
msgbox('Click to display file locations (copies to the clipboard)');
% open a FPS fix tool
end %func
%--------------------------------------------------------------------------
function mr_ = errorbar_iqr_(mr)
mr_ = quantile_mr_(mr, [.25,.5,.75]);
errorbar(1:size(mr_,1), mr_(:,2), mr_(:,2)-mr_(:,1), mr_(:,3)-mr_(:,2));
set(gca, 'XLim', [.5, size(mr_,1)+.5]);
end %func
%--------------------------------------------------------------------------
function mr1 = quantile_mr_(mr, vrQ)
mr1 = zeros(numel(vrQ), size(mr,2), 'like', mr);
for i=1:size(mr,2)
mr1(:,i) = quantile(mr(:,i), vrQ);
end
mr1 = mr1';
end %func
%--------------------------------------------------------------------------
function [pathLen_cm, XH, YH, TC1] = trial_pathlen_(S_trial, pixpercm, angXaxis)
if nargin<2
P = load_settings_();
[pixpercm, angXaxis] = deal(P.pixpercm, P.angXaxis);
end %if
[TC, XHc, YHc] = deal(S_trial.TC, S_trial.XC(:,2), S_trial.YC(:,2));
TC1 = linspace(TC(1), TC(end), numel(TC)*10);
XH = interp1(TC, XHc, TC1, 'spline');
YH = interp1(TC, YHc, TC1, 'spline');
pathLen = sum(sqrt(diff(XH).^2 + diff(YH).^2));
xyStart = trial_xyStart_(S_trial, pixpercm, angXaxis);
pathLen = pathLen + sqrt((XH(1) - xyStart(1)).^2 + (YH(1) - xyStart(2)).^2);
pathLen_cm = pathLen / pixpercm;
end %func
%--------------------------------------------------------------------------
function [xyStart, xyFood] = trial_xyStart_(S_trial, pixpercm, angXaxis)
[dataID, fishID] = trial_id_(S_trial);
switch fishID
case 'A'
xyStart = [55, 50]; xyFood = [0 -10]; angRot = 0;
case 'B'
xyStart = [50, -55]; xyFood = [-10 0]; angRot = 90;
case 'C'
xyStart = [-55, -50]; xyFood = [0 10]; angRot = 180;
case 'D'
xyStart = [-50, 55]; xyFood = [10 0]; angRot = 270;
end
iAnimal = fishID - 'A' + 1;
rotMat = rotz(angXaxis); rotMat = rotMat(1:2, 1:2);
xyStart = (xyStart * rotMat) .* [1, -1] * pixpercm + S_trial.xy0; %convert to pixel unit
xyFood = (xyFood * rotMat) .* [1, -1] * pixpercm + S_trial.xy0; %convert to pixel unit
end %func
%--------------------------------------------------------------------------
function export_(handles)
assignWorkspace_(handles);
% export heading angles to CVS file
[vcFile_cvs, mrTraj, vcMsg_cvs, csFormat] = trial2csv_(handles, [], 0);
assignWorkspace_(mrTraj);
P = load_cfg_();
csMsg = {'"handles" struct and "mrTraj" assigned to the Workspace.', vcMsg_cvs};
csMsg = [csMsg, csFormat(:)'];
msgbox_(csMsg);
end %func
%--------------------------------------------------------------------------
% 10/15/2018 JJJ: cvs renamed to csv
function [vcFile_cvs, mrTraj, vcMsg, csFormat] = trial2csv_(S_trial, P, fPlot)
if nargin<2, P = []; end
if nargin<3, fPlot = 0; end
if isempty(P), P = load_settings_(); end
[vcDir_, ~, ~] = fileparts(S_trial.vidFname);
if exist_file_(get_(S_trial, 'vcFile_Track'))
vcFile_cvs = subsFileExt_(S_trial.vcFile_Track, '.csv');
elseif exist_dir_(vcDir_)
vcFile_cvs = subsFileExt_(S_trial.vidFname, '_Track.csv');
else
vcFile_Track = get_(S_trial.editResultFile, 'String');
vcFile_cvs = strrep(vcFile_Track, '.mat', '.csv');
end
P1 = setfield(P, 'xy0', S_trial.xy0);
mrTraj = resample_trial_(S_trial, P1);
csvwrite(vcFile_cvs, mrTraj);
vcMsg = sprintf('Trajectory exported to %s\n', vcFile_cvs);
% Export shape
if isfield(S_trial, 'mrPos_shape')
vcFile_shapes = strrep(vcFile_cvs, '_Track.csv', '_shapes.csv');
cm_per_grid = get_set_(P, 'cm_per_grid', 5);
mrPos_shape_meter = S_trial.mrPos_shape;
mrPos_shape_meter(:,1:2) = mrPos_shape_meter(:,1:2) * cm_per_grid / 100;
csvwrite(vcFile_shapes, mrPos_shape_meter);
vcMsg = sprintf('%sShapes exported to %s\n', vcMsg, vcFile_shapes);
vcFile_relations = strrep(vcFile_cvs, '_Track.csv', '_relations.csv');
mrRelations = calc_relations_(mrTraj, mrPos_shape_meter, P1);
csvwrite(vcFile_relations, mrRelations);
vcMsg = sprintf('%srelations exported to %s\n', vcMsg, vcFile_relations);
else
fprintf(2, '%s: Shape positions field does not exist.\n', vcFile_cvs);
end
csShapes = get_(P, 'csShapes');
csFormat = {...
'_Track.csv files:',
' Columns: T(s), X(m), Y(m), A(deg), R(Hz), D(m), V(m/s), S(m):',
' T: camera frame time',
' X: x coordinate of the head tip @ grid frame of reference',
' Y: y coordinate of the head tip @ grid frame of reference',
' A: head orientation',
' R: EOD rate',
' D: Distance per EOD pulse (=1/sampling_density)',
' V: Head speed (m/s, signed)',
' S: Distance per Escan (=1/escan_density)',
'_shapes.csv files:',
' Columns: X(m), Y(m), A(deg):',
' X(m): x coordinate of the shape center @ grid frame of reference',
' Y(m): y coordinate of the shape center @ grid frame of reference',
' A(deg): Shape orientation',
sprintf(' Rows: %s', sprintf('"%s", ', csShapes{:})),
'_relations.csv files:',
sprintf(' Columns: T(s), D_F(m), A_E(deg), %s', sprintf('L_"%s"(bool), ', csShapes{:})),
' T: camera frame time',
' D_F: distance to the food',
' A_E: heading angle error (food_vec - head_vec, 0..90 deg)',
' L_"x": Is shape "x" adjacent to the head position? 0:no, 1:yes'};
if fPlot
hFig = figure_new_('', vcFile_cvs);
imshow(S_trial.img0); hold on;
resize_figure_(hFig, [0,0,.5,1]);
plot_chevron_(S_trial.XC(:,2:3), S_trial.YC(:,2:3));
end
if nargout==0
fprintf('%s', vcMsg);
disp_cs_(csFormat);
end
end %func
%--------------------------------------------------------------------------
function [mrTXYARDVS_rs, P1] = resample_trial_(S_trial, P)
% Output
% -----
% mrTXYARDV_rs:
% Time(s), X-pos(m), Y-pos(m), Angle(deg), Sampling Rate(Hz),
% Dist/pulse(m), Velocity(m/s), Dist/E-Scan (m)
% smooth the trajectory
% if fFilter
fh_filt = @(x)filtPos(x, P.TRAJ_NFILT, 1);
P1 = setfield(P, 'xy0', S_trial.xy0);
sRateHz_rs = get_set_(P, 'sRateHz_resample', 100);
vrT_rs = (S_trial.TC(1):1/sRateHz_rs:S_trial.TC(end))';
fh_interp = @(x)interp1(S_trial.TC(:), x, vrT_rs);
mrXY_pix_2 = [fh_filt(S_trial.XC(:,2)), fh_filt(S_trial.YC(:,2))];
mrXY_pix_3 = [fh_filt(S_trial.XC(:,3)), fh_filt(S_trial.YC(:,3))];
mrXY_m_2_rs = fh_interp(pix2cm_(mrXY_pix_2, P1) / 100);
mrXY_m_3_rs = fh_interp(pix2cm_(mrXY_pix_3, P1) / 100);
vrA_rs = fh_interp(pix2cm_deg_(S_trial.AC(:,2), P1));
% add EOD and sampling density
[vtEodr, vrEodr] = getEodr_adc_(S_trial, P);
vrR_rs = interp1(vtEodr, vrEodr, vrT_rs);
% Compute velocity
mrXY_23_rs = mrXY_m_2_rs - mrXY_m_3_rs;
[VX, VY] = deal(diff3_(mrXY_m_2_rs(:,1)), diff3_(mrXY_m_2_rs(:,2)));
vrV_rs = hypot(VX, VY) .* sign(mrXY_23_rs(:,1).*VX + mrXY_23_rs(:,2).*VY) * sRateHz_rs;
% Count sampling density
vrLr = cumsum(hypot(VX, VY));
vtEodr_ = vtEodr(vtEodr>=vrT_rs(1) & vtEodr <= vrT_rs(end));
vrD = diff3_(interp1(vrT_rs, vrLr, vtEodr_, 'spline')); % distance between EOD
vrD_rs = interp1(vtEodr_, vrD, vrT_rs);
vrD_rs(isnan(vrD_rs)) = 0;
% calc ESCAN rate
viDs = findDIsac(diff3_(diff3_(vtEodr)));
vtEscan = vtEodr(viDs);
vrDs = diff3_(interp1(vrT_rs, vrLr, vtEscan, 'spline')); % distance between EOD
vrS_rs = interp1(vtEscan, vrDs, vrT_rs, 'spline');
vrS_rs(isnan(vrS_rs)) = 0;
% get EOD timestamps
mrTXYARDVS_rs = [vrT_rs, mrXY_m_2_rs, vrA_rs(:), vrR_rs(:), vrD_rs(:), vrV_rs(:), vrS_rs(:)];
% figure; quiver(mrXY_m_2_rs(:,1),mrXY_m_2_rs(:,2), VX, VY, 2, 'r.')
end %func
%--------------------------------------------------------------------------
function data = diff3_(data, dt) % three point diff
%data = differentiate5(data, dt)
%data: timeseries to differentiate
%dt: time step (default of 1)
% http://en.wikipedia.org/wiki/Numerical_differentiation
dimm = size(data);
data=data(:)';
data = filter([1 0 -1], 2, data);
data = data(3:end);
data = [data(1), data, data(end)];
if nargin > 1
data = data / dt;
end
if dimm(1) == 1 %row vector
data=data(:)';
else
data=data(:); %col vector
end
end %func
%--------------------------------------------------------------------------
function mrRelations = calc_relations_(mrTraj, mrPos_shape_meter, P)
if nargin<3, P = []; end
if isempty(P), P = load_settings_(); end
[T, mrXY_h, A_H] = deal(mrTraj(:,1), mrTraj(:,2:3), mrTraj(:,4));
vrXY_food = mrPos_shape_meter(end,1:2);
mrV_F = bsxfun(@minus, vrXY_food, mrXY_h);
[A_F, D_F] = cart2pol_(mrV_F(:,1), mrV_F(:,2));
% A_E = min(mod(A_F-A_H, 180), mod(A_H-A_F, 180));
A_E = mod(A_F-A_H+90, 180) - 90;
% determine shape mask
dist_cut = get_set_(P, 'dist_cm_shapes', 3) / 100; % in meters
nShapes = size(mrPos_shape_meter,1);
mlL_shapes = false(numel(T), nShapes);
for iShape = 1:nShapes
vcShape = strtok(P.csShapes{iShape}, ' ');
xya_ = mrPos_shape_meter(iShape,:);
len_ = P.vrShapes(iShape)/100;
[mrXY_poly_, fCircle] = get_polygon_(vcShape, xya_(1:2), len_, xya_(3));
if fCircle
vrD_ = hypot(xya_(1)-mrXY_h(:,1), xya_(2)-mrXY_h(:,2)) - len_/2;
else %polygon
vrD_ = nearest_perimeter_(mrXY_poly_/100, mrXY_h); % convert to meter
end
mlL_shapes(:,iShape) = vrD_ <= dist_cut;
end
mrRelations = [T, D_F, A_E, mlL_shapes];
end %func
%--------------------------------------------------------------------------
function vrD_ = nearest_perimeter_(mrXY_p, mrXY_h)
% mrXY_p: polygon vertices
nInterp = 100;
mrXY_ = [mrXY_p; mrXY_p(1,:)]; % wrap
mrXY_int = interp1(1:size(mrXY_,1), mrXY_, 1:1/nInterp:size(mrXY_,1));
vrD_ = min(pdist2(mrXY_int, mrXY_h))';
if nargout==0
figure; hold on;
plot(mrXY_int(:,1), mrXY_int(:,2), 'b.-');
plot(mrXY_h(:,1), mrXY_h(:,2), 'r.-');
end
end %func
%--------------------------------------------------------------------------
function [th_deg, r] = cart2pol_(x,y)
% th: degrees
th_deg = atan2(y,x).*(180/pi);
r = hypot(x,y);
end %func
%--------------------------------------------------------------------------
function mrA1 = pix2cm_deg_(mrA, P1)
angXaxis = get_set_(P1, 'angXaxis', 0);
mrA1 = mod(-mrA - angXaxis,360);
end
%--------------------------------------------------------------------------
function plot_chevron_(mrX, mrY)
nFrames = size(mrX,1);
hold on;
for iFrame=1:nFrames
plotChevron(mrX(iFrame,:), mrY(iFrame,:), [], 90, .3);
end
end %func
%--------------------------------------------------------------------------
% 8/2/17 JJJ: added '.' if dir is empty
% 7/31/17 JJJ: Substitute file extension
function varargout = subsFileExt_(vcFile, varargin)
% Substitute the extension part of the file
% [out1, out2, ..] = subsFileExt_(filename, ext1, ext2, ...)
[vcDir_, vcFile_, ~] = fileparts(vcFile);
if isempty(vcDir_), vcDir_ = '.'; end
for i=1:numel(varargin)
vcExt_ = varargin{i};
varargout{i} = [vcDir_, filesep(), vcFile_, vcExt_];
end
end %func
%--------------------------------------------------------------------------
% 7/20/2018 JJJ: list trialset files
function trialset_list_(vcFile_trialset)
S_trialset = load_trialset_(vcFile_trialset);
if isempty(S_trialset)
errordlg(sprintf('%s does not exist', vcFile_trialset)); return;
end
if ~exist_dir_(get_(S_trialset, 'vcDir'))
errordlg(sprintf('vcDir=''%s''; does not exist', vcFile_trialset), vcFile_trialset);
return;
end
% S_trialset = load_trialset_(vcFile_trialset);
csFiles_Track = get_(S_trialset, 'csFiles_Track');
if isempty(csFiles_Track)
errordlg(sprintf('No _Track.mat files are found in "%s".', vcFile_trialset), vcFile_trialset);
return;
end
[tiImg, vcType_uniq, vcAnimal_uniq, csDir_trial, csFiles_Track] = ...
struct_get_(S_trialset, 'tiImg', 'vcType_uniq', 'vcAnimal_uniq', 'csDir_trial', 'csFiles_Track');
% output
msgbox(S_trialset.csMsg, file_part_(vcFile_trialset));
disp_cs_(S_trialset.csMsg);
disp_cs_(S_trialset.csMsg2);
hFig = plot_trialset_img_(S_trialset, tiImg);
set(hFig, 'Name', sprintf('Integrity check: %s', vcFile_trialset));
end %func
%--------------------------------------------------------------------------
function [hFig, vhImg] = plot_trialset_img_(S_trialset, tiImg, clim)
% make a click callback and show video location
if nargin<2, tiImg = S_trialset.tiImg; end
if nargin<3, clim = [min(tiImg(:)), max(tiImg(:))]; end
vhImg = zeros(size(tiImg,3), 1);
hFig = figure_new_('FigOverview', S_trialset.vcFile_trialset, [.5,0,.5,1]);
set0_(S_trialset);
% set0_(S_trialset);
% vhAx = zeros(size(tiImg,3), 1);
for iAnimal = 1:size(tiImg,3)
hAx_ = subplot(1,size(tiImg,3),iAnimal);
hImg_ = imagesc_(tiImg(:,:,iAnimal), clim);
vhImg(iAnimal) = hImg_;
ylabel('Dates'); xlabel('Trials');
title(sprintf('Animal %s', S_trialset.vcAnimal_uniq(iAnimal)));
% hAx_.UserData = [];
hImg_.ButtonDownFcn = @(h,e)button_FigOverview_(h,e,iAnimal);
end %for
end %func
%--------------------------------------------------------------------------
function button_FigOverview_(hImg, event, iAnimal)
% S_axes = get(hAxes, 'UserData');
xy = get(hImg.Parent, 'CurrentPoint');
xy = round(xy(1,1:2));
[iSession, iTrial, cAnimal] = deal(xy(2), xy(1), 'A' + iAnimal - 1);
fprintf('Session:%d, Trial:%d, Animal:%c\n', iSession, iTrial, cAnimal);
S_trialset = get0_('S_trialset');
vcVidExt = get_set_(S_trialset.P, 'vcVidExt', '.wmv');
% vcFormat = sprintf('*%02d%c%d.%s$', iSession, cAnimal, iTrial, vcVidExt)
vcFormat = sprintf('%02d%c%d(\\w*)_Track.mat', iSession, cAnimal, iTrial);
cs = cellfun(@(x)regexpi(x, vcFormat, 'match'), S_trialset.csFiles_Track, 'UniformOutput', 0);
iFind = find(~cellfun(@isempty, cs));
if ~isempty(iFind)
vcFile_Track = S_trialset.csFiles_Track{iFind};
vcFile_vid = strrep(vcFile_Track, '_Track.mat', vcVidExt);
switch event.Button
case 1
clipboard('copy', vcFile_Track);
fprintf('\t%s (copied)\n\t%s\n', vcFile_Track, vcFile_vid);
case 3
clipboard('copy', vcFile_vid);
fprintf('\t%s\n\t%s (copied)\n', vcFile_Track, vcFile_vid);
end
end
end %func
%--------------------------------------------------------------------------
function varargout = struct_get_(varargin)
% deal struct elements
if nargin==0, varargout{1} = []; return; end
S = varargin{1};
if isempty(S), varargout{1} = []; return; end
for i=2:nargin
vcField = varargin{i};
try
varargout{i-1} = S.(vcField);
catch
varargout{i-1} = [];
end
end
end %func
%--------------------------------------------------------------------------
function S_trialset = load_trialset_(vcFile_trialset)
% return [] if vcFile_trialset does not exist or
if ~exist_file_(vcFile_trialset), S_trialset = []; return; end
P = load_settings_();
S_trialset = file2struct(vcFile_trialset);
[csFiles_Track, csDir_trial] = find_files_(S_trialset.vcDir, '*_Track.mat');
if isempty(csFiles_Track), S_trialset.P=P; return; end
[csDataID, S_trialset_, csFiles_Track] = get_dataid_(csFiles_Track, get_(S_trialset, 'csAnimals'));
S_trialset = struct_merge_(S_trialset, S_trialset_);
[vcAnimal_uniq, vnAnimal_uniq] = unique_(S_trialset.vcAnimal);
[viDate_uniq, vnDate_uniq] = unique_(S_trialset.viDate);
[vcType_uniq, vnType_uniq] = unique_(S_trialset.vcType);
[viTrial_uniq, vnTrial_uniq] = unique_(S_trialset.viTrial);
fh1_ = @(x,y,z)cell2mat(arrayfun(@(a,b)sprintf(z,a,b),x,y,'UniformOutput',0));
fh2_ = @(cs_)cell2mat(cellfun(@(vc_)sprintf(' %s\n',vc_),cs_,'UniformOutput',0));
csMsg = { ...
sprintf('Trial types(#trials): %s\n', fh1_(vcType_uniq, vnType_uniq, '%c(%d), '));
sprintf('Animals(#trials): %s\n', fh1_(vcAnimal_uniq, vnAnimal_uniq, '%c(%d), '));
sprintf('Dates(#trials):\n %s\n', fh1_(viDate_uniq, vnDate_uniq, '%d(%d), '));
sprintf('# Probe trials: %d', sum(S_trialset.vlProbe));
sprintf('%s', fh2_(csFiles_Track(S_trialset.vlProbe)));
sprintf('Figure color scheme: blue:no data, green:analyzed, yellow:probe trial');
sprintf('See the console output for further details');
};
% image output
tiImg = zeros(max(viDate_uniq), max(viTrial_uniq), numel(vcAnimal_uniq));
viDate = S_trialset.viDate;
viAnimal = S_trialset.vcAnimal - min(S_trialset.vcAnimal) + 1;
viTrial = S_trialset.viTrial;
viImg = sub2ind(size(tiImg), viDate, viTrial, viAnimal);
tiImg(viImg) = 1;
tiImg(viImg(S_trialset.vlProbe)) = 2;
% find missing trials
[viDate_missing, viTrial_missing, viAnimal_missing] = ind2sub(size(tiImg), find(tiImg==0));
csDataID_missing = arrayfun(@(a,b,c)sprintf('%c%02d%c%d',vcType_uniq(1),a,b,c), ...
viDate_missing, toVec_(vcAnimal_uniq(viAnimal_missing)), viTrial_missing, ...
'UniformOutput', 0);
fh3_ = @(cs)(cell2mat(cellfun(@(x)sprintf(' %s\n',x),cs, 'UniformOutput', 0)));
fh4_ = @(cs)(cell2mat(cellfun(@(x)sprintf('%s ',x),cs, 'UniformOutput', 0)));
% secondary message
csMsg2 = { ...
sprintf('\n[Folders]');
fh3_(csDir_trial);
sprintf('[Files]');
fh3_(csFiles_Track);
sprintf('[Probe trials]');
fh2_(csFiles_Track(S_trialset.vlProbe));
sprintf('[Missing trials (%d)]', numel(csDataID_missing));
[' ', fh4_(sort(csDataID_missing'))]
};
S_trialset = struct_add_(S_trialset, P, vcFile_trialset, ...
csFiles_Track, csDir_trial, csMsg, csMsg2, ...
tiImg, viDate, viTrial, viAnimal, viImg, ...
vcAnimal_uniq, viDate_uniq, vcType_uniq, viTrial_uniq);
end %func
%--------------------------------------------------------------------------
function vr = toVec_(vr)
vr = vr(:);
end %func
%--------------------------------------------------------------------------
function vr = toRow_(vr)
vr = vr(:)';
end %func
%--------------------------------------------------------------------------
function S = struct_add_(S, varargin)
for i=1:numel(varargin)
S.(inputname(i+1)) = varargin{i};
end
end %func
%--------------------------------------------------------------------------
function hImg = imagesc_(mr, clim)
if nargin<2, clim = []; end
if isempty(clim)
hImg = imagesc(mr, 'xdata', 1:size(mr,2), 'ydata', 1:size(mr,1));
else
hImg = imagesc(mr, 'xdata', 1:size(mr,2), 'ydata', 1:size(mr,1), clim);
end
set(gca,'XTick', 1:size(mr,2));
set(gca,'YTick', 1:size(mr,1));
axis([.5, size(mr,2)+.5, .5, size(mr,1)+.5]);
grid on;
end %func
%--------------------------------------------------------------------------
function vc = file_part_(vc)
[~,a,b] = fileparts(vc);
vc = [a, b];
end %func
%--------------------------------------------------------------------------
function [vi_uniq, vn_uniq] = unique_(vi)
[vi_uniq, ~, vi_] = unique(vi);
vn_uniq = hist(vi_, 1:numel(vi_uniq));
end %func
%--------------------------------------------------------------------------
function [csDataID, S, csFiles] = get_dataid_(csFiles, csAnimals)
if nargin<2, csAnimals = {}; end
csDataID = cell(size(csFiles));
[viDate, viTrial] = deal(zeros(size(csFiles)));
vlProbe = false(size(csFiles));
[vcType, vcAnimal] = deal(repmat(' ', size(csFiles)));
for iFile=1:numel(csFiles)
[~, vcFile_, ~] = fileparts(csFiles{iFile});
vcDateID_ = strrep(vcFile_, '_Track', '');
csDataID{iFile} = vcDateID_;
vcType(iFile) = vcDateID_(1);
vcAnimal(iFile) = vcDateID_(4);
viDate(iFile) = str2num(vcDateID_(2:3));
viTrial(iFile) = str2num(vcDateID_(5));
vlProbe(iFile) = numel(vcDateID_) > 5;
end %for
% Filter by animals
if ~isempty(csAnimals)
vcAnimal_plot = cell2mat(csAnimals);
viKeep = find(ismember(vcAnimal, vcAnimal_plot));
[vcType, viDate, vcAnimal, viTrial, vlProbe, csFiles] = ...
deal(vcType(viKeep), viDate(viKeep), vcAnimal(viKeep), viTrial(viKeep), vlProbe(viKeep), csFiles(viKeep));
end
S = makeStruct_(vcType, viDate, vcAnimal, viTrial, vlProbe, csFiles);
end %func
%--------------------------------------------------------------------------
% 7/20/18: Copied from jrc3.m
function S = makeStruct_(varargin)
%MAKESTRUCT all the inputs must be a variable.
%don't pass function of variables. ie: abs(X)
%instead create a var AbsX an dpass that name
S = struct();
for i=1:nargin, S.(inputname(i)) = varargin{i}; end
end %func
%--------------------------------------------------------------------------
function [csFiles, csDir] = find_files_(csDir, vcFile)
% consider using (dir('**/*.mat') for example instead of finddir
if ischar(csDir)
if any(csDir=='*')
csDir = find_dir_(csDir);
else
csDir = {csDir};
end
end
csFiles = {};
for iDir=1:numel(csDir)
vcDir_ = csDir{iDir};
S_dir_ = dir(fullfile(vcDir_, vcFile));
csFiles_ = cellfun(@(x)fullfile(vcDir_, x), {S_dir_.name}, 'UniformOutput', 0);
csFiles = [csFiles, csFiles_];
end %for
end %func
%--------------------------------------------------------------------------
function csDir = find_dir_(vcDir)
% accepts if vcDir contains a wildcard
if ~any(vcDir=='*'), csDir = {vcDir}; return; end
[vcDir_, vcFile_, vcExt_] = fileparts(vcDir);
if ~isempty(vcExt_), csDir = {vcDir_}; return ;end
S_dir = dir(vcDir);
csDir = {S_dir.name};
csDir_ = csDir([S_dir.isdir]);
csDir = cellfun(@(x)fullfile(vcDir_, x), csDir_, 'UniformOutput', 0);
end %func
%--------------------------------------------------------------------------
function vidobj = VideoReader_(vcFile_vid, nRetry)
if nargin<2, nRetry = []; end
if isempty(nRetry), nRetry = 3; end % number of frames can change
nThreads = 1; % disable parfor by setting it to 1. Parfor is slower
fprintf('Opening Video: %s\n', vcFile_vid); t1=tic;
cVidObj = cell(nRetry,1);
fParfor = is_parfor_(nThreads);
if fParfor
try
parfor iRetry = 1:nRetry
[cVidObj{iRetry}, vnFrames(iRetry)] = load_vid_(vcFile_vid);
fprintf('\t#%d: %d frames\n', iRetry, vnFrames(iRetry));
end %for
catch
fParfor = 0;
end
end
if ~fParfor
for iRetry = 1:nRetry
[cVidObj{iRetry}, vnFrames(iRetry)] = load_vid_(vcFile_vid);
fprintf('\t#%d: %d frames\n', iRetry, vnFrames(iRetry));
end %for
end
[NumberOfFrames, iMax] = max(vnFrames);
vidobj = cVidObj{iMax};
fprintf('\ttook %0.1fs\n', toc(t1));
end %func
%--------------------------------------------------------------------------
function [vidobj, nFrames] = load_vid_(vcFile_vid);
try
vidobj = VideoReader(vcFile_vid);
nFrames = vidobj.NumberOfFrames;
catch
vidobj = [];
nFrames = 0;
end
end %func
%--------------------------------------------------------------------------
function fParfor = is_parfor_(nThreads)
if nargin<1, nThreads = []; end
if nThreads == 1
fParfor = 0;
else
fParfor = license('test', 'Distrib_Computing_Toolbox');
end
end %func
%--------------------------------------------------------------------------
% 11/5/17 JJJ: Created
function vc = dir_filesep_(vc)
% replace the file seperaation characters
if isempty(vc), return; end
vl = vc == '\' | vc == '/';
if any(vl), vc(vl) = filesep(); end
end %func
%--------------------------------------------------------------------------
function trialset_barplots_(vcFile_trialset)
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
% [mrPath, mrDur, S_trialset, cS_trial] = trialset_learningcurve_(vcFile_trialset);
[cS_trial, S_trialset, mrPath, mrDur] = loadShapes_trialset_(vcFile_trialset);
viEarly = get_(S_trialset, 'viEarly_trial');
viLate = get_(S_trialset, 'viLate_trial');
if isempty(viEarly) || isempty(viLate)
msgbox('Set "viEarly_trial" and "viLate_trial" in .trialset file');
return;
end
[vrPath_early, vrPath_late] = deal(mrPath(:,viEarly), mrPath(:,viLate));
[vrDur_early, vrDur_late] = deal(mrDur(:,viEarly), mrDur(:,viLate));
[vrSpeed_early, vrSpeed_late] = deal(vrPath_early./vrDur_early, vrPath_late./vrDur_late);
quantLim = get_set_(S_trialset, 'quantLim', [1/8, 7/8]);
[vrPath_early, vrPath_late, vrDur_early, vrDur_late, vrSpeed_early, vrSpeed_late] = ...
trim_quantile_(vrPath_early, vrPath_late, vrDur_early, vrDur_late, vrSpeed_early, vrSpeed_late, quantLim);
vcAnimal_use = cell2mat(S_trialset.csAnimals);
figure_new_('', ['Early vs Late: ', vcFile_trialset, '; Animals: ', vcAnimal_use]);
subplot 131;
bar_mean_sd_({vrPath_early, vrPath_late}, {'Early', 'Late'}, 'Pathlen (m)');
subplot 132;
bar_mean_sd_({vrDur_early, vrDur_late}, {'Early', 'Late'}, 'Duration (s)');
subplot 133;
bar_mean_sd_({vrSpeed_early, vrSpeed_late}, {'Early', 'Late'}, 'Speed (m/s)');
msgbox(sprintf('Early Sessions: %s\nLate Sessions: %s', sprintf('%d ', viEarly), sprintf('%d ', viLate)));
% Plot probe trials
S_shape = pool_probe_trialset_(S_trialset, cS_trial);
vcFigName = sprintf('%s; Animals: %s; Probe trials', S_trialset.vcFile_trialset, cell2mat(S_trialset.csAnimals));
hFig = figure_new_('', vcFigName, [0 .5 .5 .5]);
viShapes = 1:6;
subplot 241; bar(1./S_shape.mrDRVS_shape(1,viShapes)); ylabel('Sampling density'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 242; bar(S_shape.mrDRVS_shape(2,viShapes)); ylabel('Sampling Rate (Hz)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 243; bar(S_shape.mrDRVS_shape(3,viShapes)); ylabel('Speed (m/s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 244; bar(1./S_shape.mrDRVS_shape(4,viShapes)); ylabel('EScan density'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 245; bar(S_shape.vnVisit_shape(viShapes)); ylabel('# visits'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 246; bar(S_shape.vtVisit_shape(viShapes)); ylabel('t visit (s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 247; bar(S_shape.vtVisit_shape(viShapes) ./ S_shape.vnVisit_shape(viShapes)); ylabel('t per visit (s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 248; bar(S_shape.vpBackward_shape(viShapes)); ylabel('Backward swim prob.'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
xtickangle(hFig.Children, -30);
% Export to csv
vcAnimals = cell2mat(S_trialset.csAnimals);
vcFile_shapes_probe = subsFileExt_(vcFile_trialset, sprintf('_shapes_probe_%s.csv', vcAnimals));
[m1_,v2_,v3_,v4_] = struct_get_(S_shape, 'mrDRVS_shape', 'vnVisit_shape', 'vtVisit_shape', 'vpBackward_shape');
mrStats_shapes = [m1_;v2_;v3_;v2_./v3_;v4_]';
csStats = {'Sampling density (counts/m)', 'Sampling rate (Hz)', 'Speed (m/s)', ...
'Escan density (counts/m)', 'Visit count', 'Visit duration (s)', 'Duration per visit', 'Freq. backward swimming'};
csvwrite_(vcFile_shapes_probe, mrStats_shapes, 'States by shapes (probe trials); [shapes, stats]');
fprintf('\tRows: %s\n', sprintf('"%s", ', S_shape.csDist_shape{:}));
fprintf('\tColumns: %s\n', sprintf('"%s", ', csStats{:}));
end %func
%--------------------------------------------------------------------------
function S_shape = pool_probe_trialset_(S_trialset, cS_trial)
cS_probe = cS_trial(S_trialset.vlProbe);
cS_shape = cell(size(cS_probe));
for i=1:numel(cS_shape)
cS_shape{i} = nearShapes_trial_(cS_probe{i}, S_trialset.P);
end
vS_shape = cell2mat(cS_shape)';
% fh_pool = @(vc)cell2mat({vS_shape.(vc)}');
% csName = fieldnames(vS_shape(1));
% csName = setdiff(csName, 'csDist_shape');
csName = {'mlDist_shape', 'vrD', 'vrR', 'vrS', 'vrV'};
S_shape = struct();
for i=1:numel(csName)
eval(sprintf('S_shape.%s=cell2mat({vS_shape.%s}'');', csName{i}, csName{i}));
end
S_shape.csDist_shape = vS_shape(1).csDist_shape;
S_shape = S_shape_calc_(S_shape, S_trialset.P);
end %func
%--------------------------------------------------------------------------
function trialset_coordinates_(vcFile_trialset)
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
% errordlg('Not implemented yet.'); return;
[cS_trial, S_trialset] = loadShapes_trialset_(vcFile_trialset);
P = get_set_(S_trialset, 'P', load_cfg_());
% show chart
tnShapes = countShapes_trialset_(S_trialset, cS_trial);
[hFig_overview, vhImg_overview] = plot_trialset_img_(S_trialset, single(tnShapes), [0, numel(P.csShapes)]);
set(hFig_overview, 'Name', sprintf('# Shapes: %s', vcFile_trialset));
% create a table. make it navigatable
nFiles = numel(cS_trial);
hFig_tbl = figure_new_('FigShape', ['Shape locations: ', vcFile_trialset], [0,0,.5,1]);
iTrial = 1;
hFig_tbl.UserData = makeStruct_(S_trialset, P, iTrial, tnShapes, vhImg_overview);
set0_(cS_trial);
hFig_tbl.KeyPressFcn = @(h,e)keypress_FigShape_(h,e);
plotShapes_trial_(hFig_tbl, iTrial);
% uiwait(msgbox('Right-click on the shapes and food to fill the table. Press "OK" when finished.'));
msgbox('Right-click on the shapes and food to fill the table. Close the figure when finished.');
uiwait(hFig_tbl);
% save
% if ~isvalid(hFig_tbl), msgbox('Table is closed by user, nothing is saved.'); return; end
if ~questdlg_('Save the coordinates?'), return; end
hMsgbox = msgbox('Saving... (This closes automatically)');
vcFile_mat = strrep(vcFile_trialset, '.trialset', '_trialset.mat');
save_var_(vcFile_mat, 'cS_trial', get0_('cS_trial'));
close_(hFig_tbl, hFig_overview, hMsgbox);
msgbox_(['Shape info saved to ', vcFile_mat]);
end %func
%--------------------------------------------------------------------------
% 08/12/18 JJJ: Get yes or no answer from the user
function flag = questdlg_(vcTitle, flag)
% flag: default is yes (1) or no (0)
if nargin<2, flag = 1; end
if flag
flag = strcmpi(questdlg(vcTitle,'','Yes','No','Yes'), 'Yes');
else
flag = strcmpi(questdlg(vcTitle,'','Yes','No','No'), 'Yes');
end
end %func
%--------------------------------------------------------------------------
function save_var_(vcFile_mat, vcName, val)
fAppend = exist_file_(vcFile_mat);
eval(sprintf('%s=val;', vcName));
if fAppend
try
save(vcFile_mat, vcName, '-v7.3', '-append', '-nocompression'); %faster
catch
save(vcFile_mat, vcName, '-v7.3', '-append'); % backward compatible
end
else
try
save(vcFile_mat, vcName, '-v7.3', '-nocompression'); %faster
catch
save(vcFile_mat, vcName, '-v7.3'); % backward compatible
end
end
end %func
%--------------------------------------------------------------------------
function plotTraj_trial_(hFig_tbl, iTrial)
S_fig = hFig_tbl.UserData;
delete_(get_(S_fig, 'hTraj'));
hTraj = plot(S_fig);
hFig_tbl.UserData = struct_add_(S_fig, hTraj);
end %func
%--------------------------------------------------------------------------
function plotShapes_trial_(hFig_tbl, iTrial)
S_fig = hFig_tbl.UserData;
cS_trial = get0_('cS_trial');
S_ = cS_trial{iTrial};
P1 = S_fig.P;
P1.nSkip_img = get_set_(P1, 'nSkip_img', 2);
P1.xy0 = S_.xy0 / P1.nSkip_img;
P1.pixpercm = P1.pixpercm / P1.nSkip_img;
img0 = imadjust_mask_(binned_image_(S_.img0, P1.nSkip_img));
[~,dataID_,~] = fileparts(S_.vidFname);
% Crate axes
hAxes = get_(S_fig, 'hAxes');
if isempty(hAxes)
hAxes = axes(hFig_tbl, 'Units', 'pixels', 'Position', [10,220,800,600]);
end
% draw figure
hImage = get_(S_fig, 'hImage');
if isempty(hImage)
hImage = imshow(img0, 'Parent', hAxes);
hold(hAxes, 'on');
else
hImage.CData = img0;
end
hImage.UserData = P1;
% draw a grid
delete_(get_(S_fig, 'hGrid'));
hGrid = draw_grid_(hImage, -10:5:10);
% Title
vcTitle = [dataID_, ' [H]elp, [T]rajectory, [L/R/PgDn/PgUp]:Next/Prev, [G]oto, [E]xport ...'];
hTitle = get_(S_fig, 'hTitle');
if isempty(hTitle)
hTitle = title_(hAxes, vcTitle);
else
hTitle.String = vcTitle;
end
% Draw a table
hTable = get_(S_fig, 'hTable');
if isempty(hTable)
hTable = uitable(hFig_tbl, 'Data', S_.mrPos_shape, ...
'Position', [10 10 400 200], 'RowName', P1.csShapes, ...
'ColumnName', {'X pos (grid)', 'Y pos (grid)', 'Angle (deg)'});
hTable.ColumnEditable = true(1, 3);
hTable.CellEditCallback = @(a,b)draw_shapes_tbl_(hImage, hTable, iTrial);
else
hTable.Data = S_.mrPos_shape;
end
% Update
delete_(get_(S_fig, 'vhShapes'));
vhShapes = draw_shapes_tbl_(hImage, hTable, iTrial);
contextmenu_(hImage, hTable);
hFig_tbl.UserData = struct_add_(S_fig, hAxes, hImage, hTable, hGrid, iTrial, vhShapes, vhShapes);
end %func
%--------------------------------------------------------------------------
function img_adj = imadjust_mask_(img, mlMask)
if nargin<2, mlMask = []; end
if isempty(mlMask)
int_lim = quantile(single(img(img>0)), [.01, .99]);
else
int_lim = quantile(single(img(~mlMask)), [.01, .99]);
end
% imadjust excluding the mask
img_adj = imadjust(img, (int_lim)/255, [0, 1]);
end %func
%--------------------------------------------------------------------------
function keypress_FigShape_(hFig, event)
S_fig = get(hFig, 'UserData');
nStep = 1 + key_modifier_(event, 'shift')*3;
cS_trial = get0_('cS_trial');
nTrials = numel(cS_trial);
S_trial = cS_trial{S_fig.iTrial};
switch lower(event.Key)
case 'h'
msgbox(...
{'[H]elp',
'(Shift)+[L/R]: next trial (Shift: quick jump)',
'[G]oto trial',
'[Home]: First trial',
'[END]: Last trial',
'[E]xport coordinates to csv',
'[T]rajectory toggle',
'[S]ampling density',
'[C]opy trialset path'}, ...
'Shortcuts');
case {'leftarrow', 'rightarrow', 'home', 'end'}
% move to different trials and draw
iTrial_prev = S_fig.iTrial;
if strcmpi(event.Key, 'home')
iTrial = 1;
elseif strcmpi(event.Key, 'end')
iTrial = nTrials;
elseif strcmpi(event.Key, 'leftarrow')
iTrial = max(S_fig.iTrial - nStep, 1);
elseif strcmpi(event.Key, 'rightarrow')
iTrial = min(S_fig.iTrial + nStep, nTrials);
end
if iTrial ~= iTrial_prev
plotShapes_trial_(hFig, iTrial);
end
if isvalid_(get_(S_fig, 'hTraj')) % update the trajectory if turned on
draw_traj_trial_(hFig, iTrial);
end
case 'g'
vcTrial = inputdlg('Trial ID: ');
vcTrial = vcTrial{1};
if isempty(vcTrial), return; end
vcTrial = path2DataID_(vcTrial);
csDataID = getDataID_cS_(cS_trial);
iTrial = find(strcmp(vcTrial, csDataID));
if isempty(iTrial)
msgbox(['Trial not found: ', vcTrial]);
return;
end
plotShapes_trial_(hFig, iTrial);
if isvalid_(get_(S_fig, 'hTraj')) % update the trajectory if turned on
draw_traj_trial_(hFig, iTrial);
end
case 'e'
trial2csv_(S_trial);
case 't' % draw trajectory
if isvalid_(get_(S_fig, 'hTraj'))
delete_plot_(hFig, 'hTraj');
else
draw_traj_trial_(hFig, S_fig.iTrial);
end
case 's' % Sampling density
[S_shape, mrTXYARDVS_rs, P1] = nearShapes_trial_(S_trial, S_fig.P);
[vrX, vrY] = cm2pix_(mrTXYARDVS_rs(:,2:3)*100, P1);
vrD = mrTXYARDVS_rs(:,6);
S_trial = struct_add_(S_trial, vrX, vrY, vrD);
hFig_grid = figure_new_('FigGrid', S_trial.vcFile_Track, [0,0,.5,.5]);
[RGB, mrPlot] = gridMap_(S_trial, P1, 'density');
imshow(RGB); title('Sampling density');
hFig = figure_new_('',S_trial.vcFile_Track, [0 .5 .5 .5]);
viShapes = 1:6;
subplot 241; bar(1./S_shape.mrDRVS_shape(1,viShapes)); ylabel('Sampling density'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 242; bar(S_shape.mrDRVS_shape(2,viShapes)); ylabel('Sampling Rate (Hz)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 243; bar(S_shape.mrDRVS_shape(3,viShapes)); ylabel('Speed (m/s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 244; bar(1./S_shape.mrDRVS_shape(4,viShapes)); ylabel('EScan density'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 245; bar(S_shape.vnVisit_shape(viShapes)); ylabel('# visits'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 246; bar(S_shape.vtVisit_shape(viShapes)); ylabel('t visit (s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 247; bar(S_shape.vtVisit_shape(viShapes) ./ S_shape.vnVisit_shape(viShapes)); ylabel('t per visit (s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 248; bar(S_shape.vpBackward_shape(viShapes)); ylabel('Backward swim prob.'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
case 'c'
clipboard('copy', S_trial.vcFile_Track);
msgbox(sprintf('%s copied to clipboard', S_trial.vcFile_Track));
otherwise
return;
end
end %func
%--------------------------------------------------------------------------
function [S_shape, mrTXYARDVS_rs, P1] = nearShapes_trial_(S_trial, P)
P1 = setfield(P, 'xy0', S_trial.xy0);
mrTXYARDVS_rs = resample_trial_(S_trial, P1);
[mrXY_h, vrD, vrR, vrV, vrS] = ...
deal(mrTXYARDVS_rs(:,2:3), mrTXYARDVS_rs(:,6), mrTXYARDVS_rs(:,5), mrTXYARDVS_rs(:,7), mrTXYARDVS_rs(:,8));
% vrV = hypot(diff3_(mrXY_h(:,1)), diff3_(mrXY_h(:,2))) * get_set_(P, 'sRateHz_resample', 100); % meter per sec
cm_per_grid = get_set_(P, 'cm_per_grid', 5);
mrPos_shape_meter = S_trial.mrPos_shape;
mrPos_shape_meter(:,1:2) = mrPos_shape_meter(:,1:2) * cm_per_grid / 100;
nShapes = size(mrPos_shape_meter,1);
mlDist_shape = false(size(mrXY_h,1), nShapes);
dist_cut = get_set_(P, 'dist_cm_shapes', 3) / 100;
for iShape = 1:nShapes
vcShape = strtok(P.csShapes{iShape}, ' ');
xya_ = mrPos_shape_meter(iShape,:);
len_ = P.vrShapes(iShape)/100; % in meter
[mrXY_poly_, fCircle] = get_polygon_(vcShape, xya_(1:2), len_, xya_(3));
if fCircle
vrD_ = hypot(xya_(1)-mrXY_h(:,1), xya_(2)-mrXY_h(:,2)) - len_/2;
else %polygon
vrD_ = nearest_perimeter_(mrXY_poly_, mrXY_h); % convert to meter
end
mlDist_shape(:,iShape) = vrD_ <= dist_cut;
end
% distance to the wall
r_wall = get_set_(P, 'diameter_cm_wall', 150) / 2 / 100;
dist_wall = get_set_(P, 'dist_cm_wall', 15) / 100; % 15 cm from the wall
vl_wall = hypot(mrXY_h(:,1), mrXY_h(:,2)) >= (r_wall - dist_wall);
mlDist_shape = [mlDist_shape, vl_wall, ~vl_wall];
csDist_shape = [P.csShapes, 'Wall', 'Not Wall'];
S_shape = makeStruct_(mlDist_shape, csDist_shape, vrD, vrR, vrV, vrS);
S_shape = S_shape_calc_(S_shape, P);
end %func
%--------------------------------------------------------------------------
function S_shape = S_shape_calc_(S_shape, P)
% output
% ------
% mrDRVS_shape
% vnVisit_shape
% vtVisit_shape
% vpBackward_shape
[vrD, vrR, vrV, vrS, mlDist_shape] = struct_get_(S_shape, 'vrD', 'vrR', 'vrV', 'vrS', 'mlDist_shape');
% sampling density by shapes
sRateHz_rs = get_set_(P, 'sRateHz_resample', 100);
mrDRVS_shape = region_median_([vrD, vrR, abs(vrV), vrS], mlDist_shape, @nanmedian); %@nanmean
[~, vnVisit_shape] = findup_ml_(mlDist_shape, sRateHz_rs);
% vnVisit_shape = sum(diff(mlDist_shape)>0); % clean up transitions
vtVisit_shape = sum(mlDist_shape) / sRateHz_rs;
vpBackward_shape = region_median_(sign(vrV)<0, mlDist_shape, @nanmean);
S_shape = struct_add_(S_shape, mrDRVS_shape, vnVisit_shape, vtVisit_shape, vpBackward_shape);
end %func
%--------------------------------------------------------------------------
function [cvi, vn] = findup_ml_(ml, nRefrac)
cvi = cell(1, size(ml,2));
vn = zeros(1, size(ml,2));
for iCol=1:size(ml,2)
vi_ = find(diff(ml(:,iCol))>0);
vn_ = diff(vi_);
viiKill_ = find(vn_<nRefrac);
if ~isempty(viiKill_)
vi_(viiKill_ + 1) = []; % remove
end
cvi{iCol} = vi_;
vn(iCol) = numel(vi_);
end
% vn = cell2mat(cellfun(@(x)diff(x), cvi', 'UniformOutput', 0));
end %func
%--------------------------------------------------------------------------
function mrMed = region_median_(mr, ml, fh)
if nargin<3, fh = @median; end
mrMed = nan(size(mr,2), size(ml,2));
for iCol = 1:size(ml,2)
vi_ = find(ml(:,iCol));
if ~isempty(vi_)
mrMed(:,iCol) = fh(mr(vi_,:));
end
end
end %func
%--------------------------------------------------------------------------
function S_fig = delete_plot_(hFig, vcTag)
S_fig = hFig.UserData;
if isempty(S_fig), return; end
delete_(get_(S_fig, vcTag));
S_fig.(vcTag) = [];
hFig.UserData = S_fig;
end %func
%--------------------------------------------------------------------------
function [S_fig, hPlot] = draw_traj_trial_(hFig, iTrial)
S_fig = hFig.UserData;
cS_trial = get0_('cS_trial');
S_trial = cS_trial{iTrial};
P = get_set_(S_fig, 'P', load_cfg_());
nSkip_img = get_set_(P, 'nSkip_img', 2);
[S_shape, mrTXYARDVS_rs, P1] = nearShapes_trial_(S_trial, P);
mrXY_pix = cm2pix_(mrTXYARDVS_rs(:,2:3)*100, P1);
try
% [X,Y] = deal(S_trial.XC(:,2)/nSkip_img, S_trial.YC(:,2)/nSkip_img);
[X,Y] = deal(mrXY_pix(:,1)/nSkip_img, mrXY_pix(:,2)/nSkip_img);
% vl = ~S_shape.mlDist_shape(:,end); % location query
% [X(vl),Y(vl)] = deal(nan(sum(vl),1));
hPlot = get_(S_fig, 'hTraj');
if isvalid_(hPlot)
[hPlot.XData, hPlot.YData] = deal(X, Y);
else
S_fig.hTraj = plot(S_fig.hAxes, X, Y, 'b');
hFig.UserData = S_fig;
end
catch
; % pass
end
end %func
%--------------------------------------------------------------------------
% Check for shift, alt, ctrl press
function flag = key_modifier_(event, vcKey)
try
flag = any(strcmpi(event.Modifier, vcKey));
catch
flag = 0;
end
end %func
%--------------------------------------------------------------------------
% Count number of shapes input
function tnShapes = countShapes_trialset_(S_trialset, cS_trial)
[viImg, tiImg] = struct_get_(S_trialset, 'viImg', 'tiImg');
tnShapes = zeros(size(tiImg), 'uint8');
for iTrial = 1:numel(cS_trial)
S_ = cS_trial{iTrial};
mrPos_shape = get_(S_, 'mrPos_shape');
if ~isempty(mrPos_shape)
tnShapes(viImg(iTrial)) = sum(~any(isnan(mrPos_shape), 2));
end
end %for
end %func
%--------------------------------------------------------------------------
function contextmenu_(hImg, tbl)
c = uicontextmenu;
hImg.UIContextMenu = c;
P1 = hImg.UserData;
% Create child menu items for the uicontextmenu
csShapes = P1.csShapes;
for iShape=1:numel(csShapes)
uimenu(c, 'Label', csShapes{iShape}, 'Callback',@setTable_);
end
uimenu(c, 'Label', '--------');
uimenu(c, 'Label', 'Rotate CW', 'Callback',@setTable_);
uimenu(c, 'Label', 'Rotate CCW', 'Callback',@setTable_);
uimenu(c, 'Label', 'Delete', 'Callback',@setTable_);
function setTable_(source,callbackdata)
xy = get(hImg.Parent, 'CurrentPoint');
xy_cm = pix2cm_(xy(1,1:2), P1); % scale factor
xy_grid = round(xy_cm / P1.cm_per_grid);
iRow_nearest = findNearest_grid_(xy_grid, tbl.Data, 1);
switch lower(source.Label)
case {'rotate cw', 'rotate ccw'}
if isempty(iRow_nearest), return; end
dAng = ifeq_(strcmpi(source.Label, 'rotate cw'), 90, -90);
tbl.Data(iRow_nearest,3) = mod(tbl.Data(iRow_nearest,3)+dAng,360);
case 'delete'
if isempty(iRow_nearest), return; end
tbl.Data(iRow_nearest,:) = nan; %delete
otherwise
if ~isempty(iRow_nearest)
tbl.Data(iRow_nearest,:) = nan; %delete
end
iRow = find(strcmp(tbl.RowName, source.Label));
tbl.Data(iRow,:) = [xy_grid(:)', 0];
end %switch
draw_shapes_tbl_(hImg, tbl);
end
end %func
%--------------------------------------------------------------------------
function iRow_nearest = findNearest_grid_(xy_grid, mrGrid, d_max);
d = pdist2(xy_grid(:)', mrGrid(:,1:2));
iRow_nearest = find(d<=d_max, 1, 'first');
end %func
%--------------------------------------------------------------------------
function h = draw_grid_(hImg, viGrid)
P1 = hImg.UserData;
[xx_cm, yy_cm] = meshgrid(viGrid);
mrXY_pix = cm2pix_([xx_cm(:), yy_cm(:)] * P1.cm_per_grid, P1);
h = plot(hImg.Parent, mrXY_pix(:,1), mrXY_pix(:,2), 'r.');
end %func
%--------------------------------------------------------------------------
function vhPlot = draw_shapes_tbl_(hImg, tbl, iTrial)
hFig = hImg.Parent.Parent;
S_fig = hFig.UserData;
if nargin<3, iTrial = S_fig.iTrial; end
P1 = hImg.UserData;
delete_(get_(P1, 'vhPlot'));
mrXY = tbl.Data;
mrXY(:,1:2) = mrXY(:,1:2) * P1.cm_per_grid;
nShapes = size(mrXY,1);
vhPlot = zeros(nShapes, 1);
for iShape = 1:nShapes
vcShape_ = strtok(tbl.RowName{iShape}, ' ');
vhPlot(iShape) = draw_shapes_img_(hImg, mrXY(iShape,:), P1.vrShapes(iShape), vcShape_);
end
P1.vhPlot = vhPlot;
set(hImg, 'UserData', P1);
% Save table data to fig userdata
cS_trial = get0_('cS_trial');
cS_trial{iTrial}.mrPos_shape = tbl.Data;
set0_(cS_trial);
S_fig.vhShapes = vhPlot;
hFig.UserData = S_fig;
end %func
%--------------------------------------------------------------------------
function flag = isvalid_(h)
if isempty(h), flag = 0; return ;end
try
flag = isvalid(h);
catch
flag = 0;
end
end %func
%--------------------------------------------------------------------------
function h = draw_shapes_img_(hImg, xya, dimm, vcShape)
% xya: xy0 and angle (cm and deg)
h = nan;
if any(isnan(dimm)), return; end
xy_ = xya(1:2);
if any(isnan(xy_)), return; end
P1 = hImg.UserData;
if numel(xya)==3
ang = xya(3);
else
ang = 0;
end
mrXY_cm = get_polygon_(vcShape, xy_, dimm, ang);
mrXY_pix = cm2pix_(mrXY_cm, P1);
h = plot(hImg.Parent, mrXY_pix(:,1), mrXY_pix(:,2), 'g-', 'LineWidth', 1);
end %func
%--------------------------------------------------------------------------
function [mrXY_cm, fCircle] = get_polygon_(vcShape, xy_, dimm, ang)
fCircle = 0;
switch upper(vcShape)
case 'TRIANGLE' % length is given
r_ = dimm(1)/sqrt(3);
vrA_ = [0, 120, 240, 0];
case {'CIRCLE', 'FOOD'} % diameter is given
r_ = dimm(1)/2;
vrA_ = [0:9:360];
fCircle = 1;
case {'SQUARE', 'RECT', 'RECTANGLE'} % length is given
r_ = dimm(1);
vrA_ = [45:90:360+45];
otherwise, error(['draw_shapes_img_: invalid shape: ', vcShape]);
end %switch
mrXY_cm = bsxfun(@plus, xy_(:)', rotate_line_(vrA_ + ang, r_));
end %func
%--------------------------------------------------------------------------
function xy_cm = pix2cm_(xy_pix, P1)
xy_cm = bsxfun(@minus, xy_pix, P1.xy0(:)') / P1.pixpercm;
xy_cm(:,2) = -xy_cm(:,2); % image coordinate to xy coordinate
xy_cm = rotatexy_(xy_cm, -P1.angXaxis);
end %func
%--------------------------------------------------------------------------
function varargout = cm2pix_(xy_cm, P1)
xy_pix = xy_cm * P1.pixpercm;
xy_pix(:,2) = -xy_pix(:,2); % change y axis
xy_pix = bsxfun(@plus, rotatexy_(xy_pix, -P1.angXaxis), P1.xy0(:)');
if nargout==1
varargout{1} = xy_pix;
else
[varargout{1}, varargout{2}] = deal(xy_pix(:,1), xy_pix(:,2));
end
end %func
%--------------------------------------------------------------------------
function [ xy_rot ] = rotatexy_( xy, ang)
%ROTATEXY rotate a vector with respect to the origin, ang in degree
% xy = xy(:);
CosA = cos(deg2rad(ang));
SinA = sin(deg2rad(ang));
M = [CosA, -SinA; SinA, CosA];
xy_rot = (M * xy')';
end
%--------------------------------------------------------------------------
% rotate a line and project. rotate from North
function xy = rotate_line_(vrA_deg, r)
if nargin<2, r=1; end
vrA_ = pi/2 - vrA_deg(:)/180*pi;
xy = r * [cos(vrA_), sin(vrA_)];
end %func
%--------------------------------------------------------------------------
function img1 = binned_image_(img, nSkip, fFast)
% fFast: set to 0 to do averaging (higher image quality)
if nargin<3, fFast = 1; end
if ndims(img)==3, img = img(:,:,1); end
if fFast
img1 = img(1:nSkip:end, 1:nSkip:end); % faster
else
dimm1 = floor(size(img)/nSkip);
viY = (0:dimm1(1)-1) * nSkip;
viX = (0:dimm1(2)-1) * nSkip;
img1 = zeros(dimm1, 'single');
for ix = 1:nSkip
for iy = 1:nSkip
img1 = img1 + single(img(viY+iy, viX+ix));
end
end
img1 = img1 / (nSkip*nSkip);
if isa(img, 'uint8'), img1 = uint8(img1); end
end
end %func
%--------------------------------------------------------------------------
function [cS_trial, S_trialset, mrPath, mrDur] = loadShapes_trialset_(vcFile_trialset)
[mrPath, mrDur, S_trialset, cS_trial] = trialset_learningcurve_(vcFile_trialset);
nSkip_img = get_set_(S_trialset.P, 'nSkip_img', 2);
% if nargout>=3
% trImg0 = cellfun(@(x)imadjust(binned_image_(x.img0, nSkip_img)), cS_trial, 'UniformOutput', 0);
% trImg0 = cat(3, trImg0{:});
% end
% default shape table
csShapes = get_set_(S_trialset, 'csShapes', {'Triangle Lg', 'Triangle Sm', 'Square Lg', 'Square Sm', 'Circle Lg', 'Circle Sm', 'Food'});
csShapes = csShapes(:);
nShapes = numel(csShapes);
mrData0 = [nan(nShapes, 2), zeros(nShapes,1)];
% load prev result
vcFile_mat = strrep(vcFile_trialset, '.trialset', '_trialset.mat');
[cTable_data, cS_trial_prev] = load_mat_(vcFile_mat, 'cTable_data', 'cS_trial');
% fill in mrPos_shape
csDataID = getDataID_cS_(cS_trial);
csDataID_prev = getDataID_cS_(cS_trial_prev);
for iFile = 1:numel(cS_trial)
S_ = cS_trial{iFile};
if isfield(S_, 'mrPos_shape'), continue; end
iPrev = find(strcmp(csDataID{iFile}, csDataID_prev));
mrData_ = mrData0;
if ~isempty(iPrev)
mrData_prev = cS_trial_prev{iPrev}.mrPos_shape;
nCol = min(nShapes, size(mrData_prev,1));
mrData_(1:nCol,:) = mrData_prev(1:nCol,:);
end
S_.mrPos_shape = mrData_;
cS_trial{iFile} = S_;
end
end %func
%--------------------------------------------------------------------------
function csDataID = getDataID_cS_(cS)
csDataID = cell(size(cS));
for i=1:numel(cS)
[~,csDataID{i},~] = fileparts(cS{i}.vidFname);
end
end %func
%--------------------------------------------------------------------------
function dataID = path2DataID_(vc)
if iscell(vc), vc = vc{1}; end
[~, dataID, ~] = fileparts(vc);
dataID = strrep(dataID, '_Track', '');
end %func
%--------------------------------------------------------------------------
function h = msgbox_(vcMsg, fEcho)
if nargin<2, fEcho = 1; end
h = msgbox(vcMsg);
if fEcho, disp(vcMsg); end
end %func
%--------------------------------------------------------------------------
% 7/26/2018 JJJ: save mat file
% function save_mat_(varargin)
% vcFile = varargin{1};
% for i=2:nargin
% eval('%s=varargin{%d};', inputname(i));
% end
% if exist_file_(vcFile)
% save(vcFile, varargin{2:end}, '-append');
% else
% save(vcFile, varargin{2:end});
% end
% end %func
%--------------------------------------------------------------------------
function varargout = load_mat_(varargin)
if nargin<1, return; end
vcFile_mat = varargin{1};
varargout = cell(1, nargout());
if ~exist_file_(vcFile_mat), return; end
if nargin==1, S = load(vcFile_mat); return; end
S = load(vcFile_mat, varargin{2:end});
for iArg = 1:nargout()
try
varargout{iArg} = getfield(S, varargin{iArg+1});
catch
;
end
end %for
end %func
%--------------------------------------------------------------------------
function varargout = bar_mean_sd_(cvr, csXLabel, vcYLabel)
if nargin<2, csXLabel = {}; end
if nargin<3, vcYLabel = ''; end
if isempty(csXLabel), csXLabel = 1:numel(cvr); end
vrMean = cellfun(@(x)nanmean(x(:)), cvr);
vrSd = cellfun(@(x)nanstd(x(:)), cvr);
vrX = 1:numel(cvr);
errorbar(vrX, vrMean, [], vrSd, 'k', 'LineStyle', 'none');
hold on; grid on;
h = bar(vrX, vrMean);
set(h, 'EdgeColor', 'None');
set(gca, 'XTick', vrX, 'XTickLabel', csXLabel, 'XLim', vrX([1,end]) + [-.5, .5]);
ylabel(vcYLabel);
[h,pa]=ttest2(cvr{1},cvr{2});
fprintf('%s: E vs L, p=%f\n', vcYLabel, pa);
end %func
%--------------------------------------------------------------------------
function varargout = trim_quantile_(varargin)
qlim = varargin{end};
for iArg = 1:nargout
vr_ = varargin{iArg};
varargout{iArg} = quantFilt_(vr_(:), qlim);
end %for
end %func
%--------------------------------------------------------------------------
function vr = quantFilt_(vr, quantLim)
qlim = quantile(vr(:), quantLim);
vr = vr(vr >= qlim(1) & vr < qlim(end));
end %func
%--------------------------------------------------------------------------
% Display list of toolbox and files needed
% 7/26/17 JJJ: Code cleanup and test
function [fList, pList] = disp_dependencies_(vcFile)
if nargin<1, vcFile = []; end
if isempty(vcFile), vcFile = mfilename(); end
[fList,pList] = matlab.codetools.requiredFilesAndProducts(vcFile);
if nargout==0
disp('Required toolbox:');
disp({pList.Name}');
disp('Required files:');
disp(fList');
end
end % func
%--------------------------------------------------------------------------
function download_sample_()
S_cfg = load_cfg_();
csLink = get_(S_cfg, 'csLink_sample');
if isempty(csLink), fprintf(2, 'Sample video does not exist\n'); return; end
t1 = tic;
fprintf('Downloading sample files. This can take up to several minutes.\n');
vlSuccess = download_files_(csLink);
fprintf('\t%d/%d files downloaded. Took %0.1fs\n', ...
sum(vlSuccess), numel(vlSuccess), toc(t1));
end %func
%--------------------------------------------------------------------------
function vlSuccess = download_files_(csLink, csDest)
% download file from the web
nRetry = 5;
if nargin<2, csDest = link2file_(csLink); end
vlSuccess = false(size(csLink));
for iFile=1:numel(csLink)
for iRetry = 1:nRetry
try
% download from list of files
fprintf('\tDownloading %s: ', csLink{iFile});
vcFile_out1 = websave(csDest{iFile}, csLink{iFile});
fprintf('saved to %s\n', vcFile_out1);
vlSuccess(iFile) = 1;
break;
catch
fprintf('\tRetrying %d/%d\n', iRetry, nRetry);
if iRetry==nRetry
fprintf(2, '\n\tDownload failed. Please download manually from the link below.\n');
fprintf(2, '\t%s\n', csLink{iFile});
end
end
end
end %for
end %func
%--------------------------------------------------------------------------
function csFile = link2file_(csLink)
csFile = cell(size(csLink));
for i=1:numel(csLink)
vcFile1 = csLink{i};
iBegin = find(vcFile1=='/', 1, 'last'); % strip ?
if ~isempty(iBegin), vcFile1 = vcFile1(iBegin+1:end); end
iEnd = find(vcFile1=='?', 1, 'last'); % strip ?
if ~isempty(iEnd), vcFile1 = vcFile1(1:iEnd-1); end
csFile{i} = vcFile1;
end
end %func
%--------------------------------------------------------------------------
% 7/25/2018 JJJ: Wait for file to get deleted
function delete_file_(csFiles)
if isempty(csFiles), return; end
if ischar(csFiles), csFiles = {csFiles}; end
nRetry = 5;
for iRetry = 1:nRetry
for iFile = 1:numel(csFiles)
if ~exist_file_(csFiles{iFile}), continue; end
delete_(csFiles{iFile});
end
end
for i=1:nRetry, pause(.2); end % wait for file deletion
end %func
%--------------------------------------------------------------------------
% 7/25/2018 JJJ: Wait for file to get deleted
function S_cfg = load_cfg_()
try
S_cfg = file2struct('default.cfg');
catch
S_cfg = struct(); % return an empty struct
end
% default field
S_cfg.vcDir_commit = get_set_(S_cfg, 'vcDir_commit', 'D:\Dropbox\Git\vistrack\');
S_cfg.csFiles_commit = get_set_(S_cfg, 'csFiles_commit', {'*.m', 'GUI.fig', 'change_log.txt', 'readme.txt', 'example.trialset', 'default.cfg'});
S_cfg.csFiles_delete = get_set_(S_cfg, 'csFiles_delete', {'settings_vistrack.m', 'example.trialset', 'R12A2_Track.mat'});
S_cfg.quantLim = get_set_(S_cfg, 'quantLim', [1/8, 7/8]);
S_cfg.vcFile_settings = get_set_(S_cfg, 'vcFile_settings', 'settings_vistrack.m');
S_cfg.pixpercm = get_set_(S_cfg, 'pixpercm', 7.238);
S_cfg.angXaxis = get_set_(S_cfg, 'angXaxis', -0.946);
end %func
%--------------------------------------------------------------------------
function trialset_exportcsv_(vcFile_trialset)
csMsg = {'Exporting the trialset to csv files...(this will close when done)', 'It can take up to several minutes'};
h = msgbox(csMsg, 'modal');
% S_trialset = load_trialset_(vcFile_trialset);
[cS_trial, S_trialset] = loadShapes_trialset_(vcFile_trialset);
% csFiles_track = S_trialset.csFiles_Track;
% csFiles_failed = {};
% for iFile = 1:numel(csFiles_track)
for iFile = 1:numel(cS_trial)
S_ = cS_trial{iFile};
if isempty(S_), continue; end
try
[~,~,vcMsg,csFormat] = trial2csv_(S_, S_trialset.P);
fprintf('%s\n', vcMsg);
catch
disp(lasterr());
end
end %for
disp_cs_(csFormat);
close_(h);
end %func
%--------------------------------------------------------------------------
function trial_gridmap_(vcFile_Track)
S_trial = load_(vcFile_Track);
P = load_settings_(S_trial);
% LOADSETTINGS;
h = msgbox('Calculating... (this will close automatically)');
S_ = importTrial(S_trial, P.pixpercm, P.angXaxis);
[RGB, mrPlot] = gridMap_(S_, P, 'time');
% [mnVisit1, mnVisit] = calcVisitCount(S_, S_.img0);
% dataID = S_trial
figure_new_('', S_trial.vidFname); imshow(RGB);
title('Time spent');
try close(h); catch, end;
end %func
%--------------------------------------------------------------------------
function trial_timemap_(S_trial)
P = load_settings_(S_trial);
%track head
h = msgbox('Calculating... (This closes automatically)');
[VISITCNT, TIMECNT] = calcVisitDensity(S_trial.img0, S_trial.TC, S_trial.XC(:,2), S_trial.YC(:,2), P.TRAJ_NFILT);
% trialID = trial_id_(handles);
img0_adj = imadjust(S_trial.img0);
hFig = figure_new_('', S_trial.vidFname);
imshow(rgbmix_(img0_adj, TIMECNT));
resize_figure_(hFig, [0,0,.5,1]);
title('Time map');
close_(h);
end %func
%--------------------------------------------------------------------------
function [dataID, fishID, iSession, iTrial, fProbe] = trial_id_(S_trial)
[~,dataID,~] = fileparts(S_trial.vidFname);
fishID = dataID(4);
iSession = str2num(dataID(2:3));
iTrial = str2num(dataID(5));
fProbe = numel(dataID) > 5;
end %func
%--------------------------------------------------------------------------
function [RGB, mrPlot] = gridMap_(vsTrial, P, vcMode, lim, mlMask)
% vcMode: {'time', 'visit', 'time/visit', 'density'}
if nargin < 2, P = []; end
if nargin < 3, vcMode = 'time'; end % visit, time, time/visit
if nargin < 4, lim = []; end
if nargin < 5, mlMask = []; end
nGrid_map = get_set_(P, 'nGrid_map', 20);
nTime_map = get_set_(P, 'nTime_map', 25);
angXaxis = get_set_(P, 'angXaxis', -1.1590); %deg
if iscell(vsTrial), vsTrial = cell2mat(vsTrial); end % make it an array
%background image processing
xy0 = vsTrial(1).xy0;
img0 = vsTrial(1).img0(:,:,1);
% mlMask = getImageMask(img0, [0 60], 'CENTRE');
img0 = imrotate(imadjust(img0), -angXaxis, 'nearest', 'crop');
%rotate vrX, vrY, and images
vrX = poolVecFromStruct(vsTrial, 'vrX'); % in meters
vrY = poolVecFromStruct(vsTrial, 'vrY'); % in meters
try vrD = poolVecFromStruct(vsTrial, 'vrD'); catch, vrD = []; end
rotMat = rotz(-angXaxis); rotMat = rotMat(1:2, 1:2);
mrXY = [vrX(:) - xy0(1), vrY(:) - xy0(2)] * rotMat;
vrX = mrXY(:,1) + xy0(1);
vrY = mrXY(:,2) + xy0(2);
viX = ceil(vrX/nGrid_map);
viY = ceil(vrY/nGrid_map);
[h, w] = size(img0);
h = h / nGrid_map;
w = w / nGrid_map;
[mrDensity, mnVisit, mnTime] = deal(zeros(h,w));
for iy=1:h
vlY = (viY == iy);
for ix=1:w
viVisit = find(vlY & (viX == ix));
if isempty(viVisit), continue; end
mnTime(iy,ix) = numel(viVisit);
nRepeats = sum(diff(viVisit) < nTime_map); % remove repeated counts
mnVisit(iy,ix) = numel(viVisit) - nRepeats;
if ~isempty(vrD)
mrDensity(iy,ix) = 1 ./ mean(vrD(viVisit));
fprintf('.');
end
end
end
mrTperV = mnTime ./ mnVisit;
switch lower(vcMode)
case 'time'
mrPlot = mnTime;
case 'visit'
mrPlot = mnVisit;
case 'time/visit'
mrPlot = mrTperV;
case {'density', 'samplingdensity'}
mrPlot = mrDensity;
end
mnPlot_ = imresize(mrPlot, nGrid_map, 'nearest');
if isempty(lim), lim = [min(mnPlot_(:)) max(mnPlot_(:))]; end
mrVisit = uint8((mnPlot_ - lim(1)) / diff(lim) * 255);
RGB = rgbmix_(img0, mrVisit, mlMask);
if nargout==0
figure; imshow(RGB); title(sprintf('%s, clim=[%f, %f]', vcMode, lim(1), lim(2)));
end
end %func
%--------------------------------------------------------------------------
function img = rgbmix_(img_bk, img, MASK, mixRatio)
if nargin<3, MASK = []; end
if nargin<4, mixRatio = []; end
if isempty(mixRatio), mixRatio = .25; end
if numel(size(img_bk)) == 2 %gray scale
if ~isa(img_bk, 'uint8')
img_bk = uint8(img_bk/max(img_bk(:)));
end
img_bk = imgray2rgb(img_bk, [0 255], 'gray');
end
if numel(size(img)) == 2 %gray scale
if ~isempty(MASK), img(~MASK) = 0; end % clear non masked area (black)
if ~isa(img, 'uint8')
img = uint8(img/max(img(:))*255);
end
img = imgray2rgb(img, [0 255], 'jet');
end
for iColor = 1:3
mr1_ = single(img(:,:,iColor));
mr0_ = single(img_bk(:,:,iColor));
mr_ = mr1_*mixRatio + mr0_*(1-mixRatio);
if isempty(MASK)
img(:,:,iColor) = uint8(mr_);
else
mr0_(MASK) = mr_(MASK);
img(:,:,iColor) = uint8(mr0_);
end
end
end %func
%--------------------------------------------------------------------------
function handles = trial_fixsync1_(handles, fAsk)
% Load video file from handle
if nargin<2, fAsk = 1; end
% Load video
h=msgbox('Loading... (this will close automatically)');
[vidobj, vcFile_vid] = load_vid_handle_(handles);
if isempty(vidobj)
fprintf(2, 'Video file does not exist: %s\n', handles.vidFname);
close_(h);
return;
end
P = load_settings_(handles);
% load video, load LED until end of the video
try
nFrames_load = handles.FLIM(2);
catch
nFrames_load = vidobj.NumberOfFrames;
end
[vrLed_cam, viT_cam] = loadLed_vid_(vidobj, [], nFrames_load);
[viT_cam, viiFilled_led] = fill_pulses_(viT_cam);
close_(h);
% figure; plot(vrLed); hold on; plot(viT_cam, vrLed(viT_cam), 'o');
% get ADC timestamp
vrT_adc = getSync_adc_(handles);
nBlinks = min(numel(viT_cam), numel(vrT_adc));
[viT_cam, vrT_adc] = deal(viT_cam(1:nBlinks), vrT_adc(1:nBlinks));
% Compare errors
vtLed_cam = interp1(viT_cam, vrT_adc, (1:numel(vrLed_cam)), 'linear', 'extrap');
[vrX, vrY, TC] = deal(handles.XC(:,2), handles.YC(:,2), handles.TC(:));
vrTC_new = interp1(viT_cam, vrT_adc, (handles.FLIM(1):handles.FLIM(2))', 'linear', 'extrap');
vrT_err = TC - vrTC_new;
vrV = sqrt((vrX(3:end)-vrX(1:end-2)).^2 + (vrY(3:end)-vrY(1:end-2)).^2) / P.pixpercm / 100;
vrV_prev = vrV ./ (TC(3:end) - TC(1:end-2));
vrV_new = vrV ./ (vrTC_new(3:end) - vrTC_new(1:end-2));
% plot
hFig = figure_new_('', vcFile_vid);
ax(1) = subplot(3,1,1);
plot(vtLed_cam, vrLed_cam); grid on; hold on;
plot(vtLed_cam(viT_cam), vrLed_cam(viT_cam), 'ro');
ylabel('LED');
title(sprintf('FPS: %0.3f Hz', handles.FPS));
ax(2) = subplot(3,1,2);
plot(vrTC_new, vrT_err, 'r.'); grid on;
title(sprintf('Sync error SD: %0.3fs', std(vrT_err)));
ax(3) = subplot(3,1,3); hold on;
plot(vrTC_new(2:end-1), vrV_prev, 'ro-');
plot(vrTC_new(2:end-1), vrV_new, 'go-'); grid on;
ylabel('Speed (m/s)'); xlabel('Time (s)');
linkaxes(ax,'x');
xlim(vrTC_new([1, end]));
title(sprintf('Ave speed: %0.3f(old), %0.3f(new) m/s', mean(vrV_prev), mean(vrV_new)));
if fAsk
vcAns = questdlg('Save time sync?', vcFile_vid, ifeq_(std(vrT_err) > .01, 'Yes', 'No'));
fSave = strcmpi(vcAns, 'Yes');
else
fSave = 1;
end
if fSave % save to file
handles.TC = vrTC_new;
handles.FPS = diff(handles.FLIM([1,end])) / diff(handles.TC([1,end]));
trial_save_(handles);
end
end %func
%--------------------------------------------------------------------------
function hPlot = plot_vline_(hAx, vrX, ylim1, lineStyle)
if nargin<4, lineStyle = []; end
mrX = repmat(vrX(:)', [3,1]);
mrY = nan(size(mrX));
mrY(1,:) = ylim1(1);
mrY(2,:) = ylim1(2);
if isempty(lineStyle)
hPlot = plot(hAx, mrX(:), mrY(:));
else
hPlot = plot(hAx, mrX(:), mrY(:), lineStyle);
end
end %func
%--------------------------------------------------------------------------
function keypress_FigSync_(hFig, event)
S_fig = get(hFig, 'UserData');
if key_modifier_(event, 'shift')
nStep = 10;
elseif key_modifier_(event, 'control')
nStep = 100;
else
nStep = 1;
end
nFrames = size(S_fig.mov, 3);
switch lower(event.Key)
case 'h'
msgbox(...
{'[H]elp',
'(Shift/Ctrl)+[L/R]: Next Frame (Shift:10x, Ctrl:100x)',
'[PgDn/PgUp]: Next/Prev Event Marker'
'[G]oto trial',
'[Home]: First trial',
'[END]: Last trial'
}, ...
'Shortcuts');
return;
case {'leftarrow', 'rightarrow', 'home', 'end', 'pagedown', 'pageup'}
% move to different trials and draw
iFrame_prev = S_fig.iFrame;
if strcmpi(event.Key, 'home')
iFrame = 1;
elseif strcmpi(event.Key, 'end')
iFrame = nFrames;
elseif strcmpi(event.Key, 'leftarrow')
iFrame = S_fig.iFrame - nStep;
elseif strcmpi(event.Key, 'rightarrow')
iFrame = S_fig.iFrame + nStep;
elseif strcmpi(event.Key, 'pageup')
iFrame = find_event_sync_(S_fig, 0);
elseif strcmpi(event.Key, 'pagedown')
iFrame = find_event_sync_(S_fig, 1);
end
iFrame = setlim_(iFrame, [1, nFrames]);
if iFrame ~= iFrame_prev
refresh_FigSync_(hFig, iFrame);
end
case 'g'
vcFrame = inputdlg('Frame#: ');
if isempty(vcFrame), return; end
iFrame = str2num(vcFrame);
if isempty(iFrame) || isnan(iFrame)
msgbox(['Invalid Frame#: ', vcFrame]);
return;
end
refresh_FigSync_(hFig, iFrame);
otherwise
return;
end %switch
end %func
%--------------------------------------------------------------------------
function iFrame = find_event_sync_(S_fig, fForward)
if nargin<2, fForward = 1; end
% find event
iFrame_now = S_fig.iFrame;
viText_cam = adc2cam_sync_([], S_fig.vtText);
if fForward
iText = find(viText_cam > iFrame_now, 1, 'first');
else
iText = find(viText_cam < iFrame_now, 1, 'last');
end
iFrame = ifeq_(isempty(iText), iFrame_now, viText_cam(iText));
if iFrame<1, iFrame = iFrame_now; end
end %func
%--------------------------------------------------------------------------
function [vtText, csText] = getText_adc_(handles, P)
if nargin<2, P=[]; end
if isempty(P), P = load_settings_(handles); end
ADCTS = get_(handles, 'ADCTS');
if isempty(ADCTS), vtText = []; return; end
ADC_CH_TEXT = get_set_(P, 'ADC_CH_TEXT', 30);
S_text = getfield(ADCTS, sprintf('%s_Ch%d', getSpike2Prefix_(ADCTS), ADC_CH_TEXT));
[vtText, vcText_] = struct_get_(S_text, 'times', 'text');
csText = cellstr(vcText_);
end %func
%--------------------------------------------------------------------------
function [vtEodr, vrEodr] = getEodr_adc_(handles, P)
if nargin<2, P=[]; end
if isempty(P), P = load_settings_(handles); end
[vtEodr, vrEodr] = deal([]);
ADCTS = get_(handles, 'ADCTS');
if isempty(ADCTS), return; end
ADC_CH_EOD = get_set_(P, 'ADC_CH_EOD', 10);
S_eod = getfield(ADCTS, sprintf('%s_Ch%d', getSpike2Prefix_(ADCTS), ADC_CH_EOD));
vtEod = S_eod.times;
vrEodr = 2 ./ (vtEod(3:end) - vtEod(1:end-2));
vtEodr = vtEod(2:end-1);
end %func
%--------------------------------------------------------------------------
function [vrLed, viT_cam] = loadLed_vid_(vidobj, xyLed, nFrames)
if nargin<2, xyLed = []; end
if nargin<3, nFrames = []; end
nStep = 300;
nParfor = 4;
t1=tic;
% Find LED
if isempty(nFrames), nFrames = vidobj.NumberOfFrames; end
flim = [1,min(nStep,nFrames)];
mov_ = vid_read(vidobj, flim(1):flim(2));
if isempty(xyLed), xyLed = findLed_mov_(mov_); end
vrLed = mov2led_(mov_, xyLed);
if flim(2) == nFrames, return; end
% Load rest of the movie
viFrame_start = (1:nStep:nFrames)';
cvrLed = cell(size(viFrame_start));
cvrLed{1} = vrLed;
try
parfor (i = 2:numel(cvrLed), nParfor)
flim_ = viFrame_start(i) + [0, nStep-1];
flim_(2) = min(flim_(2), nFrames);
cvrLed{i} = mov2led_(vid_read(vidobj, flim_(1):flim_(2)), xyLed);
end
catch
for iFrame1 = 2:numel(cvrLed)
flim_ = viFrame_start(i) + [0, nStep-1];
flim_(2) = min(flim_(2), nFrames);
cvrLed{i} = mov2led_(vid_read(vidobj, flim_(1):flim_(2)), xyLed);
end
end
vrLed = cell2mat(cvrLed);
if nargout>=2
thresh_led = (max(vrLed) + median(vrLed))/2;
viT_cam = find(diff(vrLed > thresh_led)>0) + 1;
end
fprintf('LED loading took %0.1fs\n', toc(t1));
end %func
%--------------------------------------------------------------------------
% Remove pulses
function [viT_new, viRemoved] = remove_pulses_(viT)
% remove pulses out of the range
tol = .01; % allow tolerence
int_med = median(diff(viT));
int_lim = int_med * [1-tol, 1+tol];
viInt2 = viT(3:end) - viT(1:end-2);
viRemoved = find(viInt2 >= int_lim(1) & viInt2 <= int_lim(2))+1;
viT_new = viT;
if ~isempty(viRemoved)
viT_new(viRemoved) = [];
fprintf('Removed %d ADC pulses\n', numel(viRemoved));
end
end %func
%--------------------------------------------------------------------------
% Fill missing LED pulses
function [viT_new, viT_missing] = fill_pulses_(viT_cam)
% vlPulse = false(1, numel(viT_cam));
% vlPulse(viT_cam) = 1;
viT_ = [0; viT_cam(:)];
vrTd = diff(viT_);
vnInsert_missing = round(vrTd / median(vrTd)) - 1;
viMissing = find(vnInsert_missing > 0);
if isempty(viMissing)
viT_new = viT_cam;
viT_missing = [];
else
cviT_missing = cell(1, numel(viMissing));
for iMissing1 = 1:numel(viMissing)
iMissing = viMissing(iMissing1);
n_ = vnInsert_missing(iMissing);
vi_ = linspace(viT_(iMissing), viT_(iMissing+1), n_+2);
cviT_missing{iMissing1} = vi_(2:end-1);
end
viT_missing = round(cell2mat(cviT_missing));
viT_new = sort([viT_cam(:); viT_missing(:)]);
end
if numel(viT_missing)>0
fprintf('%d pulses inserted (before: %d, after: %d)\n', numel(viT_missing), numel(viT_cam), numel(viT_new));
end
if nargout==0
figure; hold on; grid on;
plot(viT_cam, ones(size(viT_cam)), 'bo');
plot(viT_missing, ones(size(viT_missing)), 'ro');
end
end %func
%--------------------------------------------------------------------------
function vrLed = mov2led_(mov, xyLed)
vrLed = squeeze(mean(mean(mov(xyLed(2)+[-1:1], xyLed(1)+[-1:1], :),1),2));
end %func
%--------------------------------------------------------------------------
function vrT_adc = getSync_adc_(handles, P)
if nargin<2, P=[]; end
if isempty(P), P = load_settings_(handles); end
ADCTS = get_(handles, 'ADCTS');
if isempty(ADCTS), vrT_adc = []; return; end
S_adc = getfield(ADCTS, sprintf('%s_Ch%d', getSpike2Prefix_(ADCTS), P.ADC_CH_TCAM));
vrT_adc = get_(S_adc, 'times');
end %func
%--------------------------------------------------------------------------
function [vidobj, vcFile_vid] = load_vid_handle_(handles);
vidobj = [];
vcFile_vid = handles.vidFname;
if ~exist_file_(vcFile_vid)
try
vcFile_Track = get_(handles.editResultFile, 'String');
catch
vcFile_Track = get_(handles, 'vcFile_Track');
end
vcFile_vid_ = subsDir_(vcFile_vid, vcFile_Track);
if ~exist_file_(vcFile_vid_)
return;
else
vcFile_vid = vcFile_vid_;
end
end
vidobj = get_(handles, 'vidobj');
if isempty(vidobj)
vidobj = VideoReader_(vcFile_vid);
end
end %func
%--------------------------------------------------------------------------
% 9/26/17 JJJ: Created and tested
function vcFile_new = subsDir_(vcFile, vcDir_new)
% vcFile_new = subsDir_(vcFile, vcFile_copyfrom)
% vcFile_new = subsDir_(vcFile, vcDir_copyfrom)
% Substitute dir
if isempty(vcDir_new), vcFile_new = vcFile; return; end
[vcDir_new,~,~] = fileparts(vcDir_new); % extrect directory part. danger if the last filesep() doesn't exist
[vcDir, vcFile, vcExt] = fileparts(vcFile);
vcFile_new = fullfile(vcDir_new, [vcFile, vcExt]);
end % func
%--------------------------------------------------------------------------
function xyLed = findLed_mov_(trImg, nFrames_led)
if nargin<2, nFrames_led = []; end
if ~isempty(nFrames_led)
nFrames_led = min(size(trImg,3), nFrames_led);
trImg = trImg(:,:,1:nFrames_led);
end
img_pp = (max(trImg,[],3) - min(trImg,[],3));
[~,imax_pp] = max(img_pp(:));
[yLed, xLed] = ind2sub(size(img_pp), imax_pp);
xyLed = [xLed, yLed];
end %func
%--------------------------------------------------------------------------
% 7/30/2018 JJJ: Moved from GUI.m
function vcFile_Track = trial_save_(handles)
handles.ESAC = calcESAC(handles);
[handles.vcVer, handles.vcVer_date] = version_();
S_cfg = vistrack('load-cfg');
S_save = struct_copy_(handles, S_cfg.csFields);
if isfield(handles, 'vcFile_Track')
vcFile_Track = handles.vcFile_Track;
elseif exist_file_(handles.vidFname)
vcFile_Track = subsFileExt_(handles.vidFname, '_Track.mat');
else
vcFile_Track = get(handles.editResultFile, 'String');
end
h = msgbox('Saving... (this will close automatically)');
try
struct_save_(S_save, vcFile_Track, 0);
if isfield(handles, 'editResultFile')
set(handles.editResultFile, 'String', vcFile_Track);
msgbox_(sprintf('Output saved to %s', fullpath_(vcFile_Track)));
else
fprintf('Output saved to %s\n', fullpath_(vcFile_Track)); % batch mode
end
catch
fprintf(2, 'Save file failed: %s\n', vcFile_Track);
end
close_(h);
end %func
%--------------------------------------------------------------------------
% 7/30/2018 JJJ: Moved from GUI.m
function S_save = struct_copy_(handles, csField)
for i=1:numel(csField)
try
S_save.(csField{i}) = handles.(csField{i});
catch
S_save.(csField{i}) = []; % not copied
end
end
end %func
%--------------------------------------------------------------------------
% 7/24/2018: Copied from jrc3.m
function out = ifeq_(if_, true_, false_)
if (if_)
out = true_;
else
out = false_;
end
end %func
%--------------------------------------------------------------------------
% 7/30/18 JJJ: Copied from jrc3.m
function struct_save_(S, vcFile, fVerbose)
nRetry = 3;
if nargin<3, fVerbose = 0; end
if fVerbose
fprintf('Saving a struct to %s...\n', vcFile); t1=tic;
end
version_year = version('-release');
version_year = str2double(version_year(1:end-1));
if version_year >= 2017
for iRetry=1:nRetry
try
save(vcFile, '-struct', 'S', '-v7.3', '-nocompression'); %faster
break;
catch
pause(.5);
end
fprintf(2, 'Saving failed: %s\n', vcFile);
end
else
for iRetry=1:nRetry
try
save(vcFile, '-struct', 'S', '-v7.3');
break;
catch
pause(.5);
end
fprintf(2, 'Saving failed: %s\n', vcFile);
end
end
if fVerbose
fprintf('\ttook %0.1fs.\n', toc(t1));
end
end %func
%--------------------------------------------------------------------------
function [S_sync, mov] = calc_sync_(handles, mov)
% handles.{ADCTS, vidFname, vidobj}
if nargin<2, mov = []; end
if isempty(mov), mov = handles2mov_(handles); end
% Find LED timing
vtLed_adc = getSync_adc_(handles);
[vtLed_adc, viLed_adc_removed] = remove_pulses_(vtLed_adc);
xyLed = findLed_mov_(mov, 300);
vrLed = mov2led_(mov, xyLed);
vrLed = vrLed - medfilt1(vrLed,5);
thresh_led = max(vrLed) * .2;
viLed_cam = find(diff(vrLed > thresh_led)>0) + 1;
[viLed_cam, viiLed_filled] = fill_pulses_(viLed_cam);
if numel(viLed_cam) > numel(vtLed_adc), viLed_cam(1) = []; end % remove the first
S_sync = struct('vrT_adc', vtLed_adc, 'viT_cam', viLed_cam);
end %func
%--------------------------------------------------------------------------
function mov = handles2mov_(handles, P)
if nargin<2, P = []; end
if isempty(P), P = load_settings_(handles); end
vcFile_vid = handles.vidFname;
vcVidExt = get_set_(P, 'vcVidExt', '.wmv');
if ~exist_file_(vcFile_vid)
vcFile_vid = strrep(get_(handles, 'vcFile_Track'), '_Track.mat', vcVidExt);
end
h = msgbox_('Loading video... (this closes automatically)');
[mov, dimm_vid] = loadvid_(vcFile_vid, get_set_(P, 'nSkip_vid', 4));
close_(h);
end %func
%--------------------------------------------------------------------------
function [handles, hFig] = trial_fixsync_(handles, fPlot)
% fPlot: 0 (no-plot, save), 1 (plot, save), 2 (plot, no save)
persistent mov
if nargin==0, mov = []; return; end % clear cache
if nargin<2, fPlot = 1; end
P = load_settings_(handles);
if isempty(mov)
mov = handles2mov_(handles, P);
else
fprintf('Using cached video.\n');
end
S_sync = calc_sync_(handles, mov);
% [vrT_adc, viT_cam] = struct_get_(S_sync, 'vrT_adc', 'viT_cam');
[tlim_adc, flim_cam] = sync_limit_(S_sync.vrT_adc, S_sync.viT_cam);
% save if not plotting
if fPlot == 0
TC = cam2adc_sync_(S_sync, handles.FLIM(1):handles.FLIM(2));
FPS = diff(handles.FLIM([1,end])) / diff(handles.TC([1,end]));
save(handles.vcFile_Track, 'TC', 'FPS', 'S_sync', '-append');
return;
end
[vtText, csText] = getText_adc_(handles, P);
xoff_ = 50;
csPopup = {'First frame', csText{:}, 'Last frame'};
hFig = figure_new_('FigSync', [handles.vidFname, ' press "h" for help'], [0,0,.5,1]);
hFig.KeyPressFcn = @keypress_FigSync_;
hPopup = uicontrol('Style', 'popup', 'String', csPopup, ...
'Position', [xoff_ 0 200 50], 'Callback', @popup_sync_);
hPopup.KeyPressFcn = @(h,e)keypress_FigSync_(hFig,e);
% Create axes
iFrame = 1;
hAxes1 = axes(hFig, 'Units', 'pixels', 'Position', [xoff_,60,800,600]);
hImage = imshow(mov(:,:,iFrame), 'Parent', hAxes1);
hold(hAxes1, 'on');
hTitle = title_(hAxes1, sprintf('Frame %d', iFrame));
% Create Line plot
tFrame_adc = cam2adc_sync_(S_sync, iFrame);
hAxes2 = axes(hFig, 'Units', 'pixels', 'Position', [xoff_,750,800,50]);
hold(hAxes2, 'on');
plot_vline_(hAxes2, S_sync.vrT_adc, [0,1], 'k');
plot_vline_(hAxes2, vtText, [0,1], 'm');
hLine_cam = plot_vline_(hAxes2, cam2adc_sync_(S_sync, S_sync.viT_cam), [0,1], 'r--');
set(hAxes2, 'XTick', S_sync.vrT_adc);
xlabel('ADC Time (s)');
set(hAxes2, 'XLim', tlim_adc);
hCursor_adc = plot(hAxes2, tFrame_adc, .5, 'ro');
% Create Line plot
hAxes3 = axes(hFig, 'Units', 'pixels', 'Position', [xoff_,850,800,50]);
hold(hAxes3, 'on');
hPlot3 = plot_vline_(hAxes3, S_sync.viT_cam, [0,1], 'r--');
xlabel('Camera Frame #');
set(hAxes3, 'XLim', flim_cam);
set(hAxes3, 'XTick', S_sync.viT_cam);
hCursor_cam = plot(hAxes3, iFrame, .5, 'ro');
% Show EOD plot
hAxes4 = axes(hFig, 'Units', 'pixels', 'Position', [xoff_,950,800,100]);
hold(hAxes4, 'on');
xlabel('ADC Time (s)');
ylabel('EOD Rate (Hz)');
[vtEodr, vrEodr] = getEodr_adc_(handles, P);
hPlot_eod = plot(hAxes4, vtEodr, vrEodr, 'k');
hCursor_eod = plot(hAxes4, tFrame_adc, median(vrEodr), 'ro');
set(hAxes4, 'XLim', tlim_adc, 'YLim', median(vrEodr) * [1/2, 2]);
hFig.UserData = makeStruct_(iFrame, mov, hImage, vtText, csText, hTitle, ...
S_sync, hCursor_adc, hCursor_cam, hPopup, hPlot_eod, hCursor_eod);
set0_(S_sync);
if fPlot == 2, return; end
% close the figure after done
msgbox_('Close the figure when finished.');
uiwait(hFig);
S_sync = get0_('S_sync');
TC = cam2adc_sync_(S_sync, handles.FLIM(1):handles.FLIM(2));
if questdlg_(sprintf('Save time sync? (mean error: %0.3fs)', std(TC-handles.TC)))
handles.TC = TC;
handles.FPS = diff(handles.FLIM([1,end])) / diff(handles.TC([1,end]));
trial_save_(handles);
end
end %func
%--------------------------------------------------------------------------
function vrT1_adc = cam2adc_sync_(S_sync, viT1_cam)
if isempty(S_sync), S_sync = get0_('S_sync'); end
[vrT_adc, viT_cam] = struct_get_(S_sync, 'vrT_adc', 'viT_cam');
nBlinks = min(numel(viT_cam), numel(vrT_adc));
[viT_cam, vrT_adc] = deal(viT_cam(end-nBlinks+1:end), vrT_adc(1:nBlinks));
vrT1_adc = interp1(viT_cam, vrT_adc, viT1_cam, 'linear', 'extrap');
end %func
%--------------------------------------------------------------------------
function [tlim_adc, flim_cam] = sync_limit_(vtLed_adc, viLed_cam)
nBlinks = min(numel(vtLed_adc), numel(viLed_cam));
tlim_adc = vtLed_adc([1, nBlinks]);
flim_cam = viLed_cam([end-nBlinks+1, end]);
end %func
%--------------------------------------------------------------------------
function viT1_cam = adc2cam_sync_(S_sync, vrT1_adc)
if isempty(S_sync), S_sync = get0_('S_sync'); end
[vrT_adc, viT_cam] = struct_get_(S_sync, 'vrT_adc', 'viT_cam');
nBlinks = min(numel(viT_cam), numel(vrT_adc));
[viT_cam, vrT_adc] = deal(viT_cam(1:nBlinks), vrT_adc(1:nBlinks));
viT1_cam = round(interp1(vrT_adc, viT_cam, vrT1_adc, 'linear', 'extrap'));
end %func
%--------------------------------------------------------------------------
function vc = popup_sync_(h,e)
hFig = h.Parent;
S_fig = hFig.UserData;
vcLabel = h.String{h.Value};
[iFrame_prev, mov, S_sync, hTitle, hImage] = ...
struct_get_(S_fig, 'iFrame', 'mov', 'S_sync', 'hTitle', 'hImage');
nFrames = size(mov,3);
switch lower(vcLabel)
case 'first frame'
iFrame = 1;
case 'last frame'
iFrame = nFrames;
otherwise
t_adc = S_fig.vtText(h.Value-1);
iFrame = setlim_(adc2cam_sync_(S_sync, t_adc), [1, nFrames]);
end
if iFrame_prev==iFrame, return ;end
refresh_FigSync_(hFig, iFrame);
end %func
%--------------------------------------------------------------------------
function refresh_FigSync_(hFig, iFrame)
S_fig = hFig.UserData;
[iFrame_prev, mov, S_sync, hTitle, hImage] = ...
struct_get_(S_fig, 'iFrame', 'mov', 'S_sync', 'hTitle', 'hImage');
hImage.CData = mov(:,:,iFrame);
set(S_fig.hCursor_cam, 'XData', iFrame);
tFrame_adc = cam2adc_sync_(S_sync, iFrame);
set(S_fig.hCursor_adc, 'XData', tFrame_adc);
set(S_fig.hCursor_eod, 'XData', tFrame_adc);
% Update title
viText_cam = adc2cam_sync_(S_sync, S_fig.vtText);
viMatch = find(viText_cam==iFrame);
if isempty(viMatch)
hTitle.String = sprintf('Frame %d', iFrame);
else
iMatch = viMatch(1);
hTitle.String = sprintf('Frame %d: %s', iFrame, S_fig.csText{iMatch});
S_fig.hPopup.Value = iMatch+1;
end
% update current frame
S_fig.iFrame = iFrame;
hFig.UserData = S_fig;
set0_(S_fig); % push to global
end %func
%--------------------------------------------------------------------------
function vr = setlim_(vr, lim_)
% Set low and high limits
vr = min(max(vr, lim_(1)), lim_(2));
end %func
%--------------------------------------------------------------------------
function hTitle = title_(hAx, vc)
% title_(vc)
% title_(hAx, vc)
if nargin==1, vc=hAx; hAx=[]; end
% Set figure title
if isempty(hAx), hAx = gca; end
hTitle = get_(hAx, 'Title');
if isempty(hTitle)
hTitle = title(hAx, vc, 'Interpreter', 'none', 'FontWeight', 'normal');
else
set_(hTitle, 'String', vc, 'Interpreter', 'none', 'FontWeight', 'normal');
end
end %func
%--------------------------------------------------------------------------
function vc = set_(vc, varargin)
% Set handle to certain values
% set_(S, name1, val1, name2, val2)
if isempty(vc), return; end
if isstruct(vc)
for i=1:2:numel(varargin)
vc.(varargin{i}) = varargin{i+1};
end
return;
end
if iscell(vc)
for i=1:numel(vc)
try
set(vc{i}, varargin{:});
catch
end
end
elseif numel(vc)>1
for i=1:numel(vc)
try
set(vc(i), varargin{:});
catch
end
end
else
try
set(vc, varargin{:});
catch
end
end
end %func
%--------------------------------------------------------------------------
function clear_cache_()
trial_fixsync_();
end %func
%--------------------------------------------------------------------------
function [mov, vcFile_bin] = loadvid_(vcFile_vid, nSkip, fSave_bin)
% using the 2018a VideoReader
% Extracts red channel only
t1=tic;
if nargin<2, nSkip = []; end
if nargin<3, fSave_bin = []; end
if isempty(nSkip), nSkip = 1; end
if isempty(fSave_bin), fSave_bin = 1; end
fFast = 0; %subsampling instead of averaging the pixels
try
vidobj = VideoReader(vcFile_vid);
catch
[dimm, mov] = deal([]);
return;
end
% vidInfo = mmfileinfo(vcFile_vid);
% vidInfo.Duration;
fprintf('Loading video: %s\n', vcFile_vid);
vidHeight = floor(vidobj.Height / nSkip);
vidWidth = floor(vidobj.Width / nSkip);
% check cache
vcFile_bin = sprintf('%s_mov%dx%d.bin', vcFile_vid, vidHeight, vidWidth);
mov = loadvid_bin_(vcFile_bin);
if ~isempty(mov)
dimm = size(mov);
fprintf('\tLoaded from %s (%d frames), took %0.1fs\n', vcFile_bin, size(mov,3), toc(t1));
return;
end
nFrames_est = round(vidobj.Duration * vidobj.FrameRate);
mov = zeros(vidHeight, vidWidth, nFrames_est, 'uint8');
fTrim = (vidHeight * nSkip) < vidobj.Height || (vidWidth * nSkip) < vidobj.Width;
iFrame = 0;
while hasFrame(vidobj)
iFrame = iFrame + 1;
img_ = readFrame(vidobj);
if fFast
mov(:,:,iFrame) = img_(1:nSkip:vidHeight*nSkip, 1:nSkip:vidWidth*nSkip, 1);
continue;
end
img_ = img_(:,:,1); % red extraction
if nSkip>1
if fTrim
img_ = img_(1:(vidHeight*nSkip), 1:(vidWidth*nSkip));
end
img_ = sum(uint16(reshape(img_, nSkip, [])));
img_ = sum(permute(reshape(img_, vidHeight, nSkip, vidWidth), [2,1,3]));
img_ = reshape(uint8(img_/(nSkip^2)), vidHeight, vidWidth);
end
mov(:,:,iFrame) = img_;
end
nFrames = iFrame;
dimm = [vidHeight, vidWidth, nFrames];
if nFrames < nFrames_est
mov = mov(:,:,1:nFrames); %trim
end
% bulk save
if fSave_bin
try
fid_w = fopen(vcFile_bin, 'w');
fwrite(fid_w, mov, class(mov));
fclose(fid_w);
fprintf('\twrote to %s (%d frames), took %0.1fs\n', vcFile_bin, size(mov,3), toc(t1));
catch
;
end
else
fprintf('\tLoaded %d frames, took %0.1fs\n', size(mov,3), toc(t1));
end
end %func
%--------------------------------------------------------------------------
function mov = loadvid_bin_(vcFile_bin)
% vcFile_bin: string format: vidfile_mov%dx%d.bin (wxh)
mov=[];
if ~exist_file_(vcFile_bin), return; end
vcFormat = regexpi(vcFile_bin, '_mov(\d+)[x](\d+)[.]bin$', 'match');
if isempty(vcFormat), return; end % invalid format
try
vcFormat = strrep(strrep(vcFormat{1}, '_mov', ''), '.bin', '');
dimm = sscanf(vcFormat, '%dx%d');
[height, width] = deal(dimm(1), dimm(2));
nBytes_file = filesize_(vcFile_bin);
dimm(3) = floor(nBytes_file/height/width);
fid = fopen(vcFile_bin, 'r');
mov = fread_(fid, dimm, 'uint8');
fclose(fid);
catch
return;
end
end %func
%--------------------------------------------------------------------------
function mnWav1 = fread_(fid_bin, dimm_wav, vcDataType)
% Get around fread bug (matlab) where built-in fread resize doesn't work
dimm_wav = dimm_wav(:)';
try
if isempty(dimm_wav)
mnWav1 = fread(fid_bin, inf, ['*', vcDataType]);
else
if numel(dimm_wav)==1, dimm_wav = [dimm_wav, 1]; end
mnWav1 = fread(fid_bin, prod(dimm_wav), ['*', vcDataType]);
if numel(mnWav1) == prod(dimm_wav)
mnWav1 = reshape(mnWav1, dimm_wav);
else
dimm2 = floor(numel(mnWav1) / dimm_wav(1));
if dimm2 >= 1
mnWav1 = reshape(mnWav1, dimm_wav(1), dimm2);
else
mnWav1 = [];
end
end
end
catch
disperr_();
end
end %func
%--------------------------------------------------------------------------
% Return [] if multiple files are found
function nBytes = filesize_(vcFile)
S_dir = dir(vcFile);
if numel(S_dir) ~= 1
nBytes = [];
else
nBytes = S_dir(1).bytes;
end
end %func
%--------------------------------------------------------------------------
function [S_trialset, trFps] = trialset_fixfps_(vcFile_trialset)
% It loads the files
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
fFix_sync = 1;
S_trialset = load_trialset_(vcFile_trialset);
% [pixpercm, angXaxis] = struct_get_(S_trialset.P, 'pixpercm', 'angXaxis');
[tiImg, vcType_uniq, vcAnimal_uniq, viImg, csFiles_Track] = ...
struct_get_(S_trialset, 'tiImg', 'vcType_uniq', 'vcAnimal_uniq', 'viImg', 'csFiles_Track');
hMsg = msgbox('Analyzing... (This closes automatically)');
t1=tic;
trFps = nan(size(tiImg));
for iTrial = 1:numel(viImg)
try
clear_cache_();
S_ = load(csFiles_Track{iTrial}, 'TC', 'XC', 'YC', 'xy0', 'vidFname', 'FPS', 'img0', 'ADCTS', 'FLIM');
S_.vcFile_Track = csFiles_Track{iTrial};
if fFix_sync, S_ = trial_fixsync_(S_, 0); end
iImg_ = viImg(iTrial);
trFps(iImg_) = get_set_(S_, 'FPS', nan);
fprintf('\n');
catch
disp(csFiles_Track{iTrial});
end
end %for
fprintf('\n\ttook %0.1fs\n', toc(t1));
close_(hMsg);
if nargout==0
hFig = plot_trialset_img_(S_trialset, trFps);
set(hFig, 'Name', sprintf('FPS: %s', vcFile_trialset));
end
end %func
%--------------------------------------------------------------------------
% 8/9/2018 JJJ: copied from irc.m
function varargout = get0_(varargin)
% returns get(0, 'UserData') to the workspace
% [S0, P] = get0_();
S0 = get(0, 'UserData');
if nargin==0
if nargout==0
assignWorkspace_(S0);
else
varargout{1} = S0;
end
else
for iArg=1:nargin
try
eval(sprintf('%s = S0.%s;', varargin{iArg}, varargin{iArg}));
varargout{iArg} = S0.(varargin{iArg});
catch
varargout{iArg} = [];
end
end
end
end %func
%--------------------------------------------------------------------------
% 8/9/2018 JJJ: copied from irc.m
function S0 = set0_(varargin)
S0 = get(0, 'UserData');
for i=1:nargin
try
S0.(inputname(i)) = varargin{i};
catch
disperr_();
end
end
set(0, 'UserData', S0);
end %func
%--------------------------------------------------------------------------
function mov = loadvid_preview_(vcFile_vid, viFrames)
if nargin<2, viFrames = []; end
if ~ischar(vcFile_vid)
vcFile_vid = fullfile(vcFile_vid.Path, vcFile_vid.Name);
end
P = load_cfg_();
mov = loadvid_(vcFile_vid, get_set_(P, 'nSkip_vid', 4));
if ~isempty(viFrames), mov = mov(:,:,viFrames); end
end %func
%--------------------------------------------------------------------------
function handles = trial_sync_(handles)
[handles.S_sync, mov] = calc_sync_(handles);
[vrT_adc, viT_cam] = struct_get_(handles.S_sync, 'vrT_adc', 'viT_cam');
handles.TLIM0 = vrT_adc([1, end]);
handles.FLIM0 = viT_cam([1, end]);
handles.FPS = diff(handles.FLIM0) / diff(handles.TLIM0);
% plot sync
[~, hFig] = trial_fixsync_(handles, 2);
msgbox({'Close the figure after checking the sync.', 'Press PageUp/PageDown/Left/Right to navigate'});
uiwait(hFig);
vcAns = questdlg('Synchronized correctly?');
if strcmpi(vcAns, 'Yes')
set(handles.btnBackground, 'Enable', 'on');
else
set(handles.btnBackground, 'Enable', 'off');
end
end %func
%--------------------------------------------------------------------------
function trialset_import_track_(vcFile_trialset)
% Find destination
S_trialset = load_trialset_(vcFile_trialset);
if isempty(S_trialset), errordlg('No trials exist', vcFile_trialset); return; end
vcVidExt = get_set_(S_trialset.P, 'vcVidExt');
[csFiles_vid, csDir_vid] = find_files_(S_trialset.vcDir, ['*', vcVidExt]);
% ask from where
vcDir_copyfrom = fileparts(S_trialset.vcDir);
vcDir_copyfrom = uigetdir(vcDir_copyfrom, 'Select a folder to copy from');
if ~ischar(vcDir_copyfrom), return; end
csFiles_Track = find_files_(vcDir_copyfrom, '*_Track.mat');
if isempty(csFiles_Track), return; end
fprintf('Copying %d files\n', numel(csFiles_Track));
nCopied = 0;
for iFile_Track = 1:numel(csFiles_Track)
try
vcFile_from_ = csFiles_Track{iFile_Track};
[~,vcFile_to_,~] = fileparts(vcFile_from_);
vcFile_to_ = cellstr_find_(csFiles_vid, strrep(vcFile_to_, '_Track', vcVidExt));
vcFile_to_ = strrep(vcFile_to_, vcVidExt, '_Track.mat');
copyfile(vcFile_from_, vcFile_to_, 'f');
fprintf('\tCopying %s to %s\n', vcFile_from_, vcFile_to_);
nCopied = nCopied + 1;
catch
fprintf(2, '\tCopy error: %s to %s\n', vcFile_from_, vcFile_to_);
end
end %for
fprintf('\t%d/%d copied\n', nCopied, numel(csFiles_Track));
end %func
%--------------------------------------------------------------------------
function vc_match = cellstr_find_(csFrom, vcFind)
cs = cellfun(@(vcFrom)regexpi(vcFrom, vcFind, 'match'), csFrom, 'UniformOutput', 0);
iFind = find(~cellfun(@isempty, cs));
if isempty(iFind)
vc_match = [];
else
vc_match = csFrom{iFind(1)};
end
end %func
%--------------------------------------------------------------------------
function trialset_googlesheet_(vcFile_trialset)
S_trialset = load_trialset_(vcFile_trialset);
vcLink_googlesheet = get_(S_trialset, 'vcLink_googlesheet');
if isempty(vcLink_googlesheet)
fprintf('"vcLink_googlesheet" is not set in %d\n', vcArg1);
else
web_(vcLink_googlesheet);
end
end %func
%--------------------------------------------------------------------------
function prefix = getSpike2Prefix_(S)
prefix = fields(S);
prefix = prefix{1};
k = strfind(prefix, '_Ch');
k=k(end);
prefix = prefix(1:k-1);
end
|
github
|
jamesjun/vistrack-master
|
GUI1.m
|
.m
|
vistrack-master/GUI1.m
| 39,474 |
utf_8
|
73c7bcc6f99941d6a80fc883cdefffa5
|
function varargout = GUI(varargin)
% GUI MATLAB code for GUI.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before GUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to GUI_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help GUI
% Last Modified by GUIDE v2.5 19-Mar-2014 15:24:51
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @GUI_OpeningFcn, ...
'gui_OutputFcn', @GUI_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 GUI is made visible.
function GUI_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 GUI (see VARARGIN)
% Choose default command line output for GUI
handles.output = hObject;
% Update settings window
csSettings = importdata('settings.m', '\n');
set(handles.editSettings, 'String', csSettings);
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes GUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = GUI_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;
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in btnLoadVideo.
function btnLoadVideo_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadVideo (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles in: {handles.edit1}
% out: {vidfile, vidobj}
[FileName,PathName,FilterIndex] = uigetfile('*.wmv;*.avi;*.mpg;*.mp4', ...
'Select video file',get(handles.edit1, 'String'));
if FilterIndex
try
handles.vidFname = fullfile(PathName, FileName);
set(handles.edit1, 'String', handles.vidFname);
h = msgbox('Loading... (this will close automatically)');
handles.vidobj = VideoReader(handles.vidFname);
handles.vidobj
try close(h); catch, end;
set(handles.btnSync, 'Enable', 'on');
set(handles.btnBackground, 'Enable', 'off');
set(handles.btnTrack, 'Enable', 'off');
set(handles.btnPreview, 'Enable', 'off');
set(handles.btnSave, 'Enable', 'off');
set(handles.panelPlot, 'Visible', 'off');
msgstr = 'Video';
% set the ADC file and ADC timestamp paths
[~, fname, ~] = fileparts(FileName);
handles.ADCfile = [PathName, fname, '_Rs.mat'];
handles.ADCfileTs = [PathName, fname, '_Ts.mat'];
set(handles.editADCfile, 'String', handles.ADCfile);
set(handles.editADCfileTs, 'String', handles.ADCfileTs);
try handles.ADC = load(handles.ADCfile);
msgstr = [msgstr, ', ADC_Rs'];
catch, errordlg('ADC_Rs load error'); end
try handles.ADCTS = load(handles.ADCfileTs);
msgstr = [msgstr, ', ADC_Ts'];
catch, errordlg('ADC_Ts load error'); end
guidata(hObject, handles);
msgbox([msgstr ' file(s) loaded']);
catch
errordlg(lasterr);
end
end
function editSettings_Callback(hObject, eventdata, handles)
% hObject handle to editSettings (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 editSettings as text
% str2double(get(hObject,'String')) returns contents of editSettings as a double
% --- Executes during object creation, after setting all properties.
function editSettings_CreateFcn(hObject, eventdata, handles)
% hObject handle to editSettings (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 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 in: editSettings
% --- Executes on button press in btnBackground.
function btnBackground_Callback(hObject, eventdata, handles)
% hObject handle to btnBackground (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
FLIM0 = handles.FLIM0;
% Get time range from spike2
if ~exist('TLIM')
try
ADCTC = load(get(handles.editADCfileTs, 'String'));
prefix = getSpike2Prefix(ADCTC);
chTEXT = getfield(ADCTC, sprintf('%s_Ch%d', prefix, ADC_CH_TEXT));
[EODR, TEOD, chName] = getSpike2Chan(handles.ADC, ADC_CH_EODR);
AMPL = getSpike2Chan(handles.ADC, ADC_CH_AMPL);
hfig = figure; AX = [];
subplot 212; plot(TEOD, AMPL); AX(2) = gca; grid on;
subplot 211; plot(TEOD, EODR); AX(1) = gca; grid on;
linkaxes(AX, 'x');
hold on;
xlabel('Time (s)'); ylabel('EOD Rate (Hz)'); axis tight;
title({'Set time range and double-click', ...
'r: GATE OPEN, m: ENTERED ARENA; g: GATE CLOSE', ...
'c: FOUND FOOD; b: LIGHT BLINK; k: Default'});
set(hfig, 'Name', handles.vidFname);
TLIM = [nan, nan];
for i=1:numel(chTEXT.times)
if ~isempty(strfind(chTEXT.text(i,:), 'GATE_OPEN'));
color = '-r';
elseif ~isempty(strfind(chTEXT.text(i,:), 'ENTERED_ARENA'));
color = '-m';
elseif ~isempty(strfind(chTEXT.text(i,:), 'GATE_CLOSE'));
color = '-g';
elseif ~isempty(strfind(chTEXT.text(i,:), 'FOUND_FOOD'));
color = '-c';
elseif ~isempty(strfind(chTEXT.text(i,:), 'LIGHT_BLINK'));
color = '-b';
else
color = '-k';
end
plot(chTEXT.times(i)*[1 1], get(gca, 'YLim'), color);
end
gcax = get(gca, 'XLim');
gcay = get(gca, 'YLim');
h = imrect(gca, [gcax(1) gcay(1) diff(gcax) diff(gcay)]);
hpos = wait(h);
TLIM(1) = hpos(1);
TLIM(2) = sum(hpos([1 3]));
fprintf('TLIM: ');
disp(TLIM(:)');
try close(hfig), catch, end;
catch
errordlg('Specify TLIM = [First, Last]; in the Settings');
disp(lasterr);
handles.ADC
return;
end
end
% Set time range to track
FLIM1 = round(interp1(handles.TLIM0, FLIM0, TLIM, 'linear', 'extrap'));
FLIM1(1) = max(FLIM1(1), 1);
FLIMa = FLIM1(1) + [-149,150]; FLIMa(1) = max(FLIMa(1), 1);
FLIMb = FLIM1(2) + [-149,150]; FLIMb(1) = max(FLIMb(1), 1);
% Refine the first and last frames to track
try
% first frame to track
h=msgbox('Loading... (this will close automatically)');
trImg = read(handles.vidobj, FLIMa);
trImg = trImg(:,:,1,:);
try close(h); catch, end;
implay(trImg);
uiwait(msgbox('Find the first frame to track and background, and close the movie'));
answer = inputdlg({'First frame', 'Background frame'}, 'Get frames', 1, {'150', '300'});
firstFrame = str2num(answer{1});
img1 = trImg(:, :, 1, firstFrame);
FLIM(1) = firstFrame + FLIM1(1) - 150;
bgFrame = str2num(answer{2});
img00 = trImg(:, :, 1, bgFrame);
% last frame to track
h=msgbox('Loading... (this will close automatically)');
trImg = read(handles.vidobj, FLIMb);
trImg = trImg(:,:,1,:);
try close(h); catch, end;
implay(trImg);
uiwait(msgbox('Find the last frame to track, and close the movie'));
ans = inputdlg('Frame Number', 'Last frame', 1, {'150'});
FLIM(2) = str2num(ans{1}) + FLIM1(2) - 150;
% camera time unit
TC = interp1(FLIM0, handles.TLIM0, FLIM(1):FLIM(2), 'linear');
% Create background
[img00, MASK, xy_init, vec0, xy0] = makeBackground(img1, img00);
catch
disp(lasterr);
return;
end
% Create a background
% ans = inputdlg({'Second image frame #'}, 'Background', 1, {sprintf('%0.0f', FLIM(2))});
% Frame2 = str2double(ans{1});
% h=msgbox('Loading... (this will close automatically)');
% img1 = read(handles.vidobj, Frame1); img1=img1(:,:,1);
% img2 = read(handles.vidobj, Frame2); img2=img2(:,:,1);
% try close(h); catch, end;
% [img00, MASK, xy_init, vec0, xy0] = makeBackground(img1, img2);
% Update handles structure
handles.MASK = MASK;
handles.xy_init = xy_init;
handles.vec0 = vec0;
handles.xy0 = xy0;
handles.TC = TC;
handles.TLIM = TC([1, end]);
handles.FLIM = FLIM;
handles.img1 = img1;
handles.img00 = img00;
guidata(hObject, handles);
set(handles.btnPreview, 'Enable', 'on');
% --- Executes on button press in btnTrack.
function btnTrack_Callback(hObject, eventdata, handles)
% hObject handle to btnTrack (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
handles.SE = strel('disk', BW_SMOOTH,0); %use disk size 3 for 640 480
handles.img0 = handles.img00 * (1-IM_MINCONTRAST); %make it darker
handles.fShow = TRACK_SHOW;
handles.ThreshLim = ThreshLim;
handles.fBWprev = TRACK_SHOW;
TC = handles.TC;
try
[XC, YC, AC, Area, S1, MOV, XC_off, YC_off] = trackFish(handles, handles.FLIM);
catch
disp(lasterr)
errordlg('Cancelled by user');
return;
end
% Update figure handle
handles.XC = XC;
handles.YC = YC;
handles.AC = AC;
handles.MOV = MOV;
handles.XC_off = XC_off;
handles.YC_off = YC_off;
handles.xy_names = S1.xy_names;
handles.ang_names = S1.ang_names;
handles.csSettings = get(handles.editSettings, 'String');
set(handles.panelPlot, 'Visible', 'on');
set(handles.btnSave, 'Enable', 'on');
guidata(hObject, handles);
% Save
btnSave_Callback(hObject, eventdata, handles);
% --- Executes on button press in btnSync.
function btnSync_Callback(hObject, eventdata, handles)
% hObject handle to btnSync (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
vidobj = handles.vidobj;
if ~exist('FPS_cam')
FPS_cam = get(vidobj, 'FrameRate');
end
if ~exist('TLIM0')
try
%load from spike2 TC channel
ADCTC = load(get(handles.editADCfileTs, 'String'));
prefix = getSpike2Prefix(ADCTC);
chTCAM = getfield(ADCTC, sprintf('%s_Ch%d', prefix, ADC_CH_TCAM));
chTCAM = chTCAM.times;
TLIM0 = chTCAM([1 end]);
fprintf('TLIM0: ');
disp(TLIM0(:)');
catch
disp(lasterr);
errordlg('Specify TLIM0 = [First, Last]; in the Settings');
return;
end
end
FLIM1 = [1, 300];
try
h=msgbox('Loading... (this will close automatically)');
if ~isempty(vidobj.NumberOfFrames)
FLIM1(2) = min(FLIM1(2), vidobj.NumberOfFrames);
end
trImg = read(vidobj, FLIM1);
trImg = trImg(:,:,1,:);
try close(h); catch, end;
implay(trImg);
uiwait(msgbox({'Find the first brightest blink, and close the movie', handles.vidFname}));
ans = inputdlg('Frame Number', 'First frame',1,{'164'});
FLIM0(1) = str2num(ans{1});
FLIM0(2) = round(FLIM0(1) + FPS_cam * diff(TLIM0));
FLIM1 = FLIM0(2) + [-100, 100];
if ~isempty(vidobj.NumberOfFrames)
% if FLIM1(1) < vidobj.NumberOfFrames
FLIM1(2) = min(FLIM1(2), vidobj.NumberOfFrames);
% end
end
h=msgbox('Loading... (this will close automatically)');
trImg = read(vidobj,FLIM1);
trImg = trImg(:,:,1,:);
try close(h); catch, end;
implay(trImg);
uiwait(msgbox({'Find the first brightest blink, and close the movie', handles.vidFname}));
ans = inputdlg('Frame Number', 'Last frame',1,{'102'});
temp = str2num(ans{1});
FLIM0(2) = FLIM0(2)-100+temp-1;
catch
disp(lasterr);
disp(FLIM1);
errordlg('Check the TLIM0 setting (ADC time range)');
return;
end
% TLIM = interp1(FLIM0, TLIM0, FLIM([1 end]), 'linear');
FPS = diff(FLIM0)/diff(TLIM0);
str = sprintf('FPS = %0.6f Hz, TLIM0=[%d, %d], FLIM0=[%d, %d]\n', FPS, TLIM0(1), TLIM0(2), FLIM0(1), FLIM0(2));
msgbox(str);
disp(str);
% Update handles structure
handles.TLIM0 = TLIM0;
handles.FLIM0 = FLIM0;
handles.FPS = FPS;
guidata(hObject, handles);
set(handles.btnBackground, 'Enable', 'on');
% --- Executes on button press in btnPreview.
function btnPreview_Callback(hObject, eventdata, handles)
% hObject handle to btnPreview (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
% Obrain mask and initial location
img0 = handles.img00 * (1-IM_MINCONTRAST); %make it darker
% Initial
SE = strel('disk', BW_SMOOTH,0); %use disk size 3 for 640 480
[WINPOS, ~] = getBoundingBoxPos(handles.xy_init, size(img0), winlen*[1 1]);
img = handles.img1(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2));
img0c = img0(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2));
% img00c = handles.img00(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2));
dimg = uint8(img0c - img);
% absimg = imabsdiff(handles.img00, handles.img1);
% absimg(~handles.MASK) = 0;
% absimg = absimg(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2));
% figure; subplot 121; imagesc(absimg); title('absdiff');
% subplot 122; imagesc(dimg); title('diff');
% return;
BW = imdilate(bwmorph((dimg > IM_THRESH), 'clean', inf), SE);
BW = imfill(BW, 'holes');
BW = imclearborder(BW);
% dimg1 = dimg;
% dimg1(bwperim(BW)) = 256;
% imgabs = im(handles.img00, handles.img1);
% imgabs(~handles.MASK) = 0;
% figure; imagesc(imgabs);
% figure; imagesc(dimg1);
% return;
[BW, AreaTarget] = bwgetlargestblob(BW);
% Update
handles.SE = SE;
handles.thresh = IM_THRESH;
handles.AreaTarget = AreaTarget;
handles.WINPOS = WINPOS;
handles.img0 = img0;
guidata(hObject, handles);
set(handles.btnTrack, 'Enable', 'on');
% Preview images
figure;
subplot 221;
imagesc(img, INTENSITY_LIM);
axis equal; axis tight;
set(gca, {'XTick', 'YTick'}, {[],[]});
title('1. Original image');
subplot 222;
imagesc(dimg);
axis equal; axis tight;
set(gca, {'XTick', 'YTick'}, {[], []});
title('2. Difference image');
subplot 223; imshow(BW);
title(sprintf('3. Binary image (Area=%d)', AreaTarget));
subplot 224;
BW1 = bwperim(BW);
img4 = img; img4(BW1)=255;
% imshow(img4);
imagesc(img4, INTENSITY_LIM);
axis equal; axis tight;
set(gca, {'XTick', 'YTick'}, {[],[]});
title('4. Superimposed');
colormap gray;
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
writeText('settings.m', get(handles.editSettings, 'String'));
delete(hObject);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
writeText('settings.m', get(handles.editSettings, 'String'));
handles.csSettings = get(handles.editSettings, 'String');
guidata(hObject, handles);
function editADCfile_Callback(hObject, eventdata, handles)
% hObject handle to editADCfile (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 editADCfile as text
% str2double(get(hObject,'String')) returns contents of editADCfile as a double
% --- Executes during object creation, after setting all properties.
function editADCfile_CreateFcn(hObject, eventdata, handles)
% hObject handle to editADCfile (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 btnLoadADC.
function btnLoadADC_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadADC (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[FileName,PathName,FilterIndex] = uigetfile('*.mat','Select ADC file',get(handles.editADCfile, 'String'));
if FilterIndex
try
handles.ADCfile = fullfile(PathName, FileName);
set(handles.editADCfile, 'String', handles.ADCfile);
h = msgbox('Loading... (this will close automatically)');
handles.ADC = load(handles.ADCfile);
try close(h); catch, end;
guidata(hObject, handles);
msgbox('ADC File loaded');
catch
set(handles.editADCfile, 'String', '');
errordlg(lasterr);
end
end
% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton11 (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 pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton12 (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 pushbutton13.
function pushbutton13_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton13 (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 pushbutton16.
function pushbutton16_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton16 (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 btnPlot2.
function btnPlot2_Callback(hObject, eventdata, handles)
% hObject handle to btnPlot2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
XC = handles.XC;
YC = handles.YC;
figure; imshow(gray2rgb(handles.img0)); title('Posture trajectory (red: more recent, circle: head)');
hold on;
nframes = size(XC,1);
nxy = size(XC,2);
mrColor = jet(nframes);
for iframe=1:TRAJ_STEP:nframes
XI = interp1(2:nxy, XC(iframe,2:end), 2:.1:nxy, 'spline');
YI = interp1(2:nxy, YC(iframe,2:end), 2:.1:nxy, 'spline');
plot(XI, YI, 'color', mrColor(iframe,:));
plot(XI(1), YI(1), 'o', 'color', mrColor(iframe,:));
end
% --- Executes on button press in btnPlot4.
function btnPlot4_Callback(hObject, eventdata, handles)
% hObject handle to btnPlot4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
TC = handles.TC;
try
ADC = handles.ADC;
[EODR, TEOD, chName] = getSpike2Chan(ADC, ADC_CH_PLOT);
fprintf('Loaded Spike2 %s (Ch%d)\n', chName, ADC_CH_PLOT);
catch
disp(lasterr);
errordlg('Load ADC file');
return;
end
%smooth and interpolate position
TCi = TC(1):(1/EODR_SR):TC(end);
X2i = interp1(handles.TC, filtPos(handles.XC(:,2), TRAJ_NFILT), TCi, 'spline', 'extrap');
Y2i = interp1(handles.TC, filtPos(handles.YC(:,2), TRAJ_NFILT), TCi, 'spline', 'extrap');
X3i = interp1(handles.TC, filtPos(handles.XC(:,3), TRAJ_NFILT), TCi, 'spline', 'extrap');
Y3i = interp1(handles.TC, filtPos(handles.YC(:,3), TRAJ_NFILT), TCi, 'spline', 'extrap');
%convert rate to 0..255 color level at the camera time
R = interp1(TEOD, EODR, TCi);
R = (R-min(R))/(max(R)-min(R));
viColorRate = ceil(R * 256);
viColorRate(viColorRate<=0)=1;
mrColor = jet(256);
% figure; plot(handles.TC, viColorRate);
% Plot the EOD color representation
figure; imagesc(handles.img0);
set(gca, {'XTick', 'YTick'}, {[],[]}); axis equal; axis tight;
hold on;
title(sprintf('EOD (%s) at the head trajectory (red: higher rate)', chName));
for i=1:numel(viColorRate)
plotChevron([X2i(i), X3i(i)], [Y2i(i), Y3i(i)], mrColor(viColorRate(i),:), 90, .3);
% plot(Xi(i), Yi(i), '.', 'color', mrColor(viColorRate(i),:));
end
colormap gray;
% --- Executes on button press in btnPlot1.
function btnPlot1_Callback(hObject, eventdata, handles)
% hObject handle to btnPlot1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
XC = handles.XC;
YC = handles.YC;
% filter position
nf = TRAJ_NFILT;
XCf_h = filtPos(XC(:,2),nf); YCf_h = filtPos(YC(:,2),nf);
XCf_hm = filtPos(XC(:,3),nf); YCf_hm = filtPos(YC(:,3),nf);
XCf_m = filtPos(XC(:,4),nf); YCf_m = filtPos(YC(:,4),nf);
XCf_tm = filtPos(XC(:,5),nf); YCf_tm = filtPos(YC(:,5),nf);
XCf_t = filtPos(XC(:,6),nf); YCf_t = filtPos(YC(:,6),nf);
figure; imshow(handles.img0); title('Trajectory of the rostral tip');
hold on; plot(XCf_h, YCf_h);
pause(.4);
hold on; comet(XCf_h, YCf_h, .1);
% --- Executes on button press in btnPlot3.
function btnPlot3_Callback(hObject, eventdata, handles)
% hObject handle to btnPlot3 (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 btnMovOut.
function btnMovOut_Callback(hObject, eventdata, handles)
% hObject handle to btnMovOut (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% load data
LOADSETTINGS;
TC = handles.TC;
XC = handles.XC;
YC = handles.YC;
try
ADC = handles.ADC;
[EODR, TEOD, chName] = getSpike2Chan(ADC, ADC_CH_PLOT);
fprintf('Loaded Spike2 %s (Ch%d)\n', chName, ADC_CH_PLOT);
% Resample EOD Rate to camera time
RC = interp1(TEOD, EODR, TC);
% RC = filtfilt(ones(1,TRAJ_STEP), TRAJ_STEP, RC);
catch
disp(lasterr)
errordlg('Load ADC file');
return;
end
% figure; plot(TEOD, EODR, 'r.', TC, RC, 'b-');
% Plot the EOD color representation
writerObj = VideoWriter(MOV_FILEOUT, 'MPEG-4');
set(writerObj, 'FrameRate', handles.FPS); %30x realtime
% set(writerObj, 'Quality', 90); %30x realtime
open(writerObj);
figure; title('Reposition'); pause;
subplot(4,1,1:3);
hfig = imshow(gray2rgb(handles.img0, INTENSITY_LIM));
% hfig = imagesc(handles.img0, INTENSITY_LIM);
set(gca, {'XTick', 'YTick'}, {[],[]});
axis equal; axis tight; hold on;
title('EOD rate at the head (red: higher rate)');
%plot locations
nframes = size(XC,1);
% mrColor = jet(nframes);
[mrColor, vrRateSrt, vrQuantSrt] = quantile2color(RC);
%colorbar
plotColorbar(size(handles.img0), vrRateSrt, vrQuantSrt);
EODR1 = EODR(TEOD > TLIM(1) & TEOD < TLIM(2));
RLIM = [quantile(EODR1, .001), quantile(EODR1, .999)];
htext = [];
vhChevron = [];
for iframe=1:nframes
%------------------
subplot(4,1,1:3);
frameNum = iframe + handles.FLIM(1) - 1;
mrImg = readFrame(handles.vidobj, frameNum);
mrImg(~handles.MASK) = 0;
mrImg = gray2rgb(mrImg, INTENSITY_LIM);
set(hfig, 'cdata', mrImg);
try delete(htext); catch, end;
htext(1) = text(10, 30, sprintf('EOD (%s): %0.1f Hz', chName, RC(iframe)), ...
'FontSize', 12, 'Color', [1 1 1]);
htext(2) = text(10, 75, sprintf('Time: %0.1f s', TC(iframe)), ...
'FontSize', 12, 'Color', [1 1 1]);
htext(3) = text(10, 120, sprintf('Frame: %d', frameNum), ...
'FontSize', 12, 'Color', [1 1 1]);
if mod(iframe, MOV_PLOTSTEP) == 0
vhChevron(end+1) = plotChevron(XC(iframe, 2:3), YC(iframe, 2:3), mrColor(iframe,:), 90, .3);
if numel(vhChevron) > MOV_PLOTLEN
delete(vhChevron(1:end-MOV_PLOTLEN));
vhChevron(1:end-MOV_PLOTLEN) = [];
end
end
%------------------
subplot(4,1,4);
hold off;
plot(TEOD - TC(iframe), EODR, 'k.'); hold on;
axis([MOV_TimeWin(1), MOV_TimeWin(2), RLIM(1), RLIM(2)]);
plot([0 0], get(gca, 'YLim'), 'r-');
grid on;
xlabel('Time (sec)');
ylabel(sprintf('EOD (%s) Hz', chName));
colormap jet;
% drawnow;
try
writeVideo(writerObj, getframe(gcf));
catch
disp('Movie output cancelled by user');
close(writerObj);
return;
end
end
close(writerObj);
msgbox(sprintf('File written to %s', MOV_FILEOUT));
% --- Executes on button press in btnSoundOut
function btnSoundOut_Callback(hObject, eventdata, handles)
% hObject handle to btnSoundOut (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% load data
LOADSETTINGS;
TC = handles.TC;
TLIM = [TC(1), TC(end)];
try
S = handles.ADCTS;
csFieldnames = fieldnames(S);
S = getfield(S, csFieldnames{1});
Teod = S.times;
Teod1 = Teod(Teod > TLIM(1) & Teod < TLIM(2));
viEod1 = round((Teod1 - TLIM(1)) * WAV_Fs);
tdur = diff(TLIM);
ns = round(tdur * WAV_Fs);
%make a binary vector
mlBinvec = zeros(ns,1);
mlBinvec(viEod1) = 1;
wavwrite(mlBinvec, WAV_Fs, WAV_FILEOUT);
msgbox(sprintf('File written to %s', WAV_FILEOUT));
catch
disp(lasterr)
errordlg('Load ADC Timestamp');
return;
end
function editADCfileTs_Callback(hObject, eventdata, handles)
% hObject handle to editADCfileTs (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 editADCfileTs as text
% str2double(get(hObject,'String')) returns contents of editADCfileTs as a double
% --- Executes during object creation, after setting all properties.
function editADCfileTs_CreateFcn(hObject, eventdata, handles)
% hObject handle to editADCfileTs (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 btnLoadADCTS.
function btnLoadADCTS_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadADCTS (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[FileName,PathName,FilterIndex] = uigetfile('*.mat','Select ADC Timestamp',get(handles.editADCfileTs, 'String'));
if FilterIndex
try
handles.ADCfileTs = fullfile(PathName, FileName);
set(handles.editADCfileTs, 'String', handles.ADCfileTs);
h = msgbox('Loading... (this will close automatically)');
handles.ADCTS = load(handles.ADCfileTs);
try close(h); catch, end;
guidata(hObject, handles);
msgbox('ADC File loaded');
catch
set(handles.editADCfileTs, 'String', '');
errordlg(lasterr);
end
end
% --- Executes during object creation, after setting all properties.
function btnPreview_CreateFcn(hObject, eventdata, handles)
% hObject handle to btnPreview (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes on button press in pushbutton28.
function pushbutton28_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton28 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
h = msgbox('Calculating... (this will close automatically)');
%track head
[VISITCNT, TIMECNT] = calcVisitDensity(handles.img0, handles.TC, handles.XC(:,2), handles.YC(:,2), TRAJ_NFILT);
try close(h); catch, end;
[~, exprID, ~] = fileparts(handles.vidFname);
figure;
subplot 121;
imshow(rgbmix(handles.img0, imgray2rgb((TIMECNT))));
title(['Time density map: ', exprID]);
subplot 122;
imshow(rgbmix(handles.img0, imgray2rgb((VISITCNT))));
title(['Visit density map: ', exprID]);
%update
handles.TIMECNT = TIMECNT;
handles.VISITCNT = VISITCNT;
guidata(hObject, handles);
function editResultFile_Callback(hObject, eventdata, handles)
% hObject handle to editResultFile (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 editResultFile as text
% str2double(get(hObject,'String')) returns contents of editResultFile as a double
% --- Executes during object creation, after setting all properties.
function editResultFile_CreateFcn(hObject, eventdata, handles)
% hObject handle to editResultFile (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 btnLoadPrev.
function btnLoadPrev_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadPrev (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[FileName,PathName,FilterIndex] = uigetfile('*_Track.mat','Select *_Track.mat file',get(handles.editResultFile, 'String'));
if FilterIndex
try
resultFile = fullfile(PathName, FileName);
set(handles.editResultFile, 'String', resultFile);
h = msgbox('Loading... (this will close automatically)');
S = load(resultFile);
try close(h); catch, end;
% Apply settings
set(handles.editSettings, 'String', S.csSettings);
csFields = {'TLIM0', 'FLIM0', 'FPS', ...
'MASK' ,'xy_init' ,'vec0' ,'xy0' ,'TC' ,'TLIM' ,'FLIM' ,'img1' ,'img00', ...
'SE' ,'thresh' ,'AreaTarget' ,'WINPOS' ,'img0', ...
'XC' ,'YC' ,'AC' ,'xy_names' ,'ang_names' ,'csSettings', ...
'ADC', 'ADCTS', ...
'MOV', 'XC_off', 'YC_off', 'vidFname', 'ESAC'};
for i=1:numel(csFields)
eval(sprintf('handles.%s = S.%s;', csFields{i}, csFields{i}));
end
set(handles.edit1, 'String', handles.vidFname);
set(handles.editADCfile, 'String', [handles.vidFname(1:end-4), '_Rs.mat']);
set(handles.editADCfileTs, 'String', [handles.vidFname(1:end-4), '_Ts.mat']);
set(handles.btnSync, 'Enable', 'on');
set(handles.btnBackground, 'Enable', 'on');
set(handles.btnTrack, 'Enable', 'on');
set(handles.btnPreview, 'Enable', 'on');
set(handles.btnSave, 'Enable', 'on');
set(handles.panelPlot, 'Visible', 'on');
guidata(hObject, handles);
msgbox('Tracking Result loaded');
catch
set(handles.editResultFile, 'String', '');
errordlg(lasterr);
end
end
% --- Executes on button press in btnSave.
function btnSave_Callback(hObject, eventdata, handles)
% hObject handle to btnSave (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.ESAC = calcESAC(handles);
%save file
h = msgbox('Saving... (this will close automatically)');
[pathstr, name, ext] = fileparts(handles.vidFname);
outfname = fullfile(pathstr, [name, '_Track.mat']);
eval(sprintf('save(''%s'', ''-struct'', ''handles'');', outfname));
try close(h); catch, end;
set(handles.editResultFile, 'String', outfname);
msgbox(sprintf('Output saved to %s', outfname));
% --- Executes during object creation, after setting all properties.
function btnSave_CreateFcn(hObject, eventdata, handles)
% hObject handle to btnSave (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes on button press in btnReplay.
function btnReplay_Callback(hObject, eventdata, handles)
% hObject handle to btnReplay (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
warning off;
LOADSETTINGS;
FLIM = handles.FLIM;
MOV = handles.MOV;
% figure; implay(MOV);return;
% figure; implay(MOV);
TC1 = handles.TC - handles.TC(1);
mrXC = bsxfun(@minus, handles.XC, handles.XC_off);
mrYC = bsxfun(@minus, handles.YC, handles.YC_off);
hfig = figure;
nF = size(MOV, 3);
tic1 = tic;
if ~exist('REPLAY_FLIM', 'var')
REPLAY_FLIM = [1, nF];
end
iF=1;
try
for iF=REPLAY_FLIM(1):REPLAY_STEP:REPLAY_FLIM(2)
img1 = MOV(:,:,iF);
XC = mrXC(iF,:);
YC = mrYC(iF,:);
% interpolated curve
nxy = numel(XC);
X1 = interp1(2:nxy, XC(2:end), 2:.1:nxy, 'spline');
Y1 = interp1(2:nxy, YC(2:end), 2:.1:nxy, 'spline');
clf(hfig);
imshow(img1); hold on;
figure(hfig);
set(hfig, 'Name', handles.vidFname);
plot(XC(2), YC(2), 'wo', XC(3:end), YC(3:end), 'ro',...
X1, Y1, 'r-', XC(1), YC(1), 'g+'); %Mark the centroid
title(sprintf('F1: %d; T1: %0.3f s', iF, TC1(iF)));
drawnow;
if exist('REPLAY_PAUSE', 'var')
if REPLAY_PAUSE == 1
pause;
end
end
end
catch
disp(lasterr);
iF0 = iF + FLIM(1) - 1;
tc0 = TC1(iF) + handles.TC(1);
tc1 = TC1(iF);
msgbox(sprintf('Closed at F0: %d, T0: %0.3f s; F1: %d, T1: %0.3f s\n', ...
iF0, tc0, iF, tc1));
% disp(lasterr);
end
fprintf('Replay took %0.3f s; Realtime %0.3f s\n', toc(tic1), diff(TC1([1 end])));
% --- Executes on button press in btnFlip.
function btnFlip_Callback(hObject, eventdata, handles)
% hObject handle to btnFlip (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
ans = inputdlg('Frame #:', 'Flip orientation', 1, {''});
ans = str2double(ans);
if isnan(ans) || isempty(ans)
return;
else
viF = ans:numel(handles.TC);
end
%Flip X, Y
%xy_names = {'CoM', 'head', 'head-mid', 'mid', 'tail-mid', 'tail'};
handles.XC(viF, 2:6) = handles.XC(viF, 6:-1:2);
handles.YC(viF, 2:6) = handles.YC(viF, 6:-1:2);
%ang_names = {'CoM', 'head-mid', 'tail-mid', 'body-bend', 'tail-bend'};
AC(viF, :) = handles.AC(viF, :) + 180;
AC = mod(AC, 360);
AC(AC>180) = AC(AC>180) - 360;
handles.AC = AC;
%update
guidata(hObject, handles);
msgbox('Orientation Flipped');
% Save
btnSave_Callback(hObject, eventdata, handles);
% --- Executes on button press in btnCustom.
function btnCustom_Callback(hObject, eventdata, handles)
% hObject handle to btnCustom (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
GUI_ESACPLOT;
% --- Executes on button press in btnESAC.
function btnESAC_Callback(hObject, eventdata, handles)
% hObject handle to btnESAC (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
GUI_ESACCADES;
% --- Executes on button press in btnEODMovie.
function btnEODMovie_Callback(hObject, eventdata, handles)
% hObject handle to btnEODMovie (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
GUI_EODMOVIE;
|
github
|
jamesjun/vistrack-master
|
trackFish_old.m
|
.m
|
vistrack-master/trackFish_old.m
| 8,690 |
utf_8
|
528800942109768d306dcddfdff7ad25
|
function [XC, YC, AC, Area, S] = trackFish(S, FLIM)
% S.{AreaTarget, ThreshLim, img0, fShow, vec0, thresh, WINPOS}
MEMLIM = 200; %number of frames to load to memory at a time
nRetry = 3; %number of retries for loading a video file
% Parse input variables
WINPOS = S.WINPOS;
vecPrev = S.vec0;
thresh = S.thresh;
nframes = diff(FLIM) + 1;
% Allocate output arrays
XC = nan(nframes,6);
YC = nan(nframes,6);
AC = nan(nframes,5);
Area = nan(nframes,1);
if nargin < 2
FLIM = [1 S.vidobj.NumberOfFrames];
end
% Call itself recursively if the number of frames is over the memory limit
if nframes > MEMLIM
for iF=FLIM(1):MEMLIM:FLIM(2)
FLIM1 = [iF, iF+MEMLIM-1];
FLIM1(2) = min(FLIM1(2), FLIM(2));
LLIM1 = FLIM1 - FLIM(1) + 1;
L = LLIM1(1):LLIM1(2);
[XC(L,:), YC(L,:), AC(L,:), Area(L,:), S] = trackFish(S, FLIM1);
end
return;
end
tic; %start the timer
% Load video frames to the memory
for itry=1:nRetry
try
h=msgbox(sprintf('Tracking frames %d ~ %d... (this will close automatically)', FLIM(1), FLIM(2)));
IMG = read(S.vidobj, FLIM);
try close(h); catch, end;
IMG = IMG(:,:,1,:); %use red channel only
break;
catch
disp(lasterr);
fprintf('failed to load %d times. reloading...\n', itry);
S.vidobj = VideoReader(S.vidFname);
end
end
if itry == nRetry
error('video load failure');
end
if S.fShow
hfig = figure;
end
% Process each frame
for iF=1:nframes
[img, dimg] = getFrame(IMG, iF, WINPOS, S.img0);
BW0 = (dimg > thresh);
BW = imdilate(bwmorph(BW0, 'clean', inf), S.SE);
BW = imclearborder(BW,8); %remove boundary touching
%Isolate the largest blob
stats = largestBlob(...
regionprops(BW, {'Area', 'Centroid', 'Orientation', 'FilledImage', 'BoundingBox'}));
try
ang = -stats.Orientation;
area = stats.Area;
xy_cm = stats.Centroid;
catch
disp(lasterr);
end
%Check for the orientation flip
vec = [cos(deg2rad(ang)), sin(deg2rad(ang))];
if dot(vec, vecPrev) < 0
ang = mod(ang + 180, 360);
if ang>180, ang=ang-360; end
vec = [cos(deg2rad(ang)), sin(deg2rad(ang))];
stats.Orientation = -ang;
end
%Compute posture
[XY, ANG, xy_names, ang_names] = blobPosture(stats);
%Display output
if S.fShow
img1 = img;
BW1 = bwperim(bwgetlargestblob(BW));
img1(BW1) = 255;
clf(hfig);
figure(hfig);
imshow(img1); hold on;
plot(XY(2, 1), XY(2, 2), 'wo'); %head
plot(XY(3:end, 1), XY(3:end, 2), 'ro');
% interpolated curve
nxy = size(XY,1);
X1 = interp1(2:nxy, XY(2:end, 1), 2:.1:nxy, 'spline');
Y1 = interp1(2:nxy, XY(2:end, 2), 2:.1:nxy, 'spline');
plot(X1, Y1, 'r-');
plot(XY(1,1), XY(1,2), 'g+'); %Mark the centroid
title(sprintf('Frame = %d', iF + FLIM(1) - 1));
drawnow;
end
%Save output
Area(iF) = area;
xy_off = [WINPOS(1), WINPOS(3)] - [1, 1];
XC(iF,:) = round(XY(:,1)' + xy_off(1));
YC(iF,:) = round(XY(:,2)' + xy_off(2));
AC(iF,:) = normAng(ANG');
%Update the bounding box
[WINPOS, ~] = getBoundingBoxPos(xy_cm + xy_off, size(S.img0), size(BW));
%adjust intensity threshold
if area > S.AreaTarget*1.1
thresh = min(thresh+1, S.ThreshLim(2));
elseif area < S.AreaTarget*.9
thresh = max(thresh-1, S.ThreshLim(1));
end
vecPrev = vec; %next orientation vector
end %for
%Return the last iteration info
S.thresh = thresh;
S.vec0 = vec;
S.WINPOS = WINPOS;
S.xy_names = xy_names;
S.ang_names = ang_names;
%Measure the processing time
tdur = toc;
fprintf('Took %0.1f images/sec, %s, Frames: [%d ~ %d]\n', ...
nframes/tdur, S.vidobj.Name, FLIM(1), FLIM(2));
try close(hfig); catch, end;
end %func
%--------------------------------------------------------------------------
function [img, dimg] = getFrame(IMG, iF, WINPOS, img0)
%GETFRAME Get image frame and crop and subtract the background
% [img] = getFrame(IMG, iF) %Obtain current frame from array of images
% [img] = getFrame(IMG, iF, WINPOS) %crops the image
% [img, dimg] = getFrame(IMG, iF, WINPOS, img0) %crop and subtract
% background
if nargin < 3
WINPOS = [1, size(IMG, 2), 1, size(IMG,1)];
end
img = IMG(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2), 1, iF);
% Calculate the intensity difference (background subtraction)
if nargin >= 4
dimg = img0(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2)) - img;
end
end %func
%--------------------------------------------------------------------------
%NORMANG Normalize the angle to range between -180 to 180 degrees
% [A] = normAng(A)
function A = normAng(A)
A = mod(A, 360);
A(A>180) = A(A>180) - 360;
end %func
%--------------------------------------------------------------------------
%LARGESTBLOB Return stats for the largest blob
% [stat, idx, area] = largestBlob(stats)
function [stat, idx, area] = largestBlob(stats)
[area, idx] = max([stats.Area]);
stat = stats(idx);
end
%--------------------------------------------------------------------------
% Measure posture angle from a binary blob
function [XY, ANG, xy_names, ang_names] = blobPosture(stats)
BW0 = stats.FilledImage;
ang0 = -stats.Orientation; %counter-clockwise is positive in pixel
xy_ref = [stats.BoundingBox(1), stats.BoundingBox(2)];
xy_ref = round(xy_ref + [stats.BoundingBox(3), stats.BoundingBox(4)]/2);
xy_cm = stats.Centroid;
%Rotate original image (BW0) parallel to the major axis
BWr = imrotate(BW0, ang0);
xy_r = round([size(BWr, 2), size(BWr, 1)]/2); %rotation center. use this as a reference
stats_r = regionprops(BWr, 'Area', 'BoundingBox'); %have area for safety
[~, idx] = max([stats_r.Area]);
stats_r = stats_r(idx);
% find head CM
BWh = BWr(1:end, xy_r(1):end);
stats_h = largestBlob(regionprops(BWh, 'Orientation', 'Centroid', 'Image', 'Area'));
ang_h = -stats_h.Orientation;
xy_hm = round(stats_h.Centroid);
xy_hm(1) = xy_hm(1) + xy_r(1) - 1;
xy_hm(2) = median(find(BWr(:, xy_hm(1))));
% find tail CM
BWt = BWr(1:end, 1:xy_r(1));
stats_t = largestBlob(regionprops(BWt, 'Orientation', 'Centroid', 'Image', 'Area'));
ang_t = -stats_t.Orientation;
xy_tm = round(stats_t.Centroid);
xy_tm(2) = median(find(BWr(:, xy_tm(1))));
%find middle points
xy_m = [xy_r(1), nan];
xy_m(2) = median(find(BWr(:, xy_r(1))));
%find tail tip
xy_t = [ceil(stats_r.BoundingBox(1)) , nan];
xy_t(2) = find(BWr(:,xy_t(1)), 1, 'first');
%find head tip
% xy_h = [floor(sum(stats_r.BoundingBox([1, 3]))) , nan];
% dx = xy_h(1) - xy_hm(1);
% xy_h(2) = round(dx * tan(deg2rad(ang_h)) + xy_hm(2));
% xy_h(2) = round(find(BWr(:,xy_h(1)), 1, 'first'));
%find head tip
BWrr = imrotate(BWr, ang_h);
stats_rr = largestBlob(regionprops(BWrr, 'Orientation', 'BoundingBox', 'Area'));
xy_rr = [size(BWrr, 2), size(BWrr, 1)]/2; %rotation center. use this as a reference
xy_h = [floor(sum(stats_rr.BoundingBox([1, 3]))) , nan];
xy_h(2) = median(find(BWrr(:, xy_hm(1))));
% xy_h(2) = round(median(find(BWrr(:, xy_h(1)))));
% compute angles
vec1 = xy_hm - xy_m;
vec2 = xy_m - xy_t;
ang_tb = rad2deg(atan2(vec2(2),vec2(1)) - atan2(vec1(2),vec1(1)));
%format output
ang_names = {'CoM', 'head-mid', 'tail-mid', 'body-bend', 'tail-bend'};
ANG = zeros(numel(ang_names), 1);
ANG(1) = ang0;
ANG(2) = ang_h + ang0;
ANG(3) = ang_t + ang0;
ANG(4) = ang_t - ang_h;
ANG(5) = ang_tb;
%compute positions
xy_r = [size(BWr, 2), size(BWr, 1)]/2; %do not round for higher precision
xy_names = {'CoM', 'head', 'head-mid', 'mid', 'tail-mid', 'tail'};
XY = zeros(numel(xy_names), 2);
XY(1,:) = xy_cm;
XY(2,:) = xy_ref + rotatexy(xy_h - xy_rr, ang0 + ang_h)';
XY(3,:) = xy_ref + rotatexy(xy_hm - xy_r, ang0)';
XY(4,:) = xy_ref + rotatexy(xy_m - xy_r, ang0)';
XY(5,:) = xy_ref + rotatexy(xy_tm - xy_r, ang0)';
XY(6,:) = xy_ref + rotatexy(xy_t - xy_r, ang0)';
end %func
%--------------------------------------------------------------------------
function [ xyp ] = rotatexy( xy, ang )
%ROTATEXY rotate a vector with respect to the origin, ang in degree
xy = xy(:);
CosA = cos(deg2rad(ang));
SinA = sin(deg2rad(ang));
M = [CosA, -SinA; SinA, CosA];
xyp = M * xy;
end
%--------------------------------------------------------------------------
function [ rad ] = deg2rad( deg )
%DEG2RAD convert an angle from degrees to radians
rad = deg / 180 * pi;
end
%--------------------------------------------------------------------------
function [ deg ] = rad2deg( rad )
%RAD2DEG convert an angle from radians to degrees
deg = rad / pi * 180;
end
|
github
|
jamesjun/vistrack-master
|
plotChevron.m
|
.m
|
vistrack-master/plotChevron.m
| 899 |
utf_8
|
353d8f5e104f3e11b650ff03086b3985
|
function h = plotChevron(XI, YI, vrColor, ANGLE, scale)
% XI: [x_tip, x_tail], YI: [y_tip, y_tail]
if nargin<3, vrColor = []; end
if nargin<4, ANGLE = 60; end
if nargin<5, scale = 1; end
if isempty(vrColor), vrColor = [1,0,0]; end % plot red
% tip of the chevron
vrX(2) = XI(1);
vrY(2) = YI(1);
% Rotate vectors
vec0 = [XI(2) - XI(1), YI(2) - YI(1)];
vecP = rotatexy_(vec0, ANGLE/2) * scale;
vecN = rotatexy_(vec0, -ANGLE/2) * scale;
vrX(1) = vecP(1) + vrX(2);
vrX(3) = vecN(1) + vrX(2);
vrY(1) = vecP(2) + vrY(2);
vrY(3) = vecN(2) + vrY(2);
% plot chevron
h = plot(vrX, vrY, '-', 'color', vrColor);
end %func
%--------------------------------------------------------------------------
function [ xyp ] = rotatexy_( xy, ang )
%ROTATEXY rotate a vector wrt origin, ang in degree
xy = xy(:);
CosA = cos(deg2rad(ang));
SinA = sin(deg2rad(ang));
M = [CosA, -SinA; SinA, CosA];
xyp = M * xy;
end
|
github
|
jamesjun/vistrack-master
|
vid_read.m
|
.m
|
vistrack-master/vid_read.m
| 2,724 |
utf_8
|
248ffb5c942eee1a4619fdc52b8591c5
|
% 7/22/2018 JJJ: created
function tmr = vid_read(vidobj, viF, nSkip_img)
if nargin<3, nSkip_img = []; end
if isempty(nSkip_img), nSkip_img = 1; end
if isempty(viF), viF = 1:vidobj.NumberOfFrames; end
nFrames_parfor = 300;
nThreads = 4; % number of parallel threads to run for loading video
fprintf('Loading video (%s: %d-%d, %d frames)\n', ...
vidobj.Name, viF(1), viF(end), numel(viF));
t1=tic;
if nSkip_img == 1
tmr = zeros(vidobj.Height, vidobj.Width, numel(viF), 'uint8');
else
n1 = numel(1:nSkip_img:vidobj.Height);
n2 = numel(1:nSkip_img:vidobj.Width);
tmr = zeros(n1, n2, numel(viF), 'uint8');
end
% parfor loading
if numel(viF)<=nFrames_parfor || nThreads == 1
fParfor = 0;
elseif median(diff(viF)) == 1
fParfor = 0;
else
fParfor = license('test', 'Distrib_Computing_Toolbox');
end
if fParfor
fprintf('\tusing parfor\n');
try
parfor (iF1=1:numel(viF), nThreads)
tmr(:,:,iF1) = read_(vidobj, viF(iF1), nSkip_img);
end
catch
fprintf('parfor failed, retrying using for loop\n\t');
fParfor = 0;
end %try
end
if ~fParfor
% if all(diff(viF)==1)
% tmr = read_(vidobj, viF([1,end]), nSkip_img);
% % tmr = squeeze(tmr(:,:,1,:));
% else
fprintf('\t');
for iF1=1:numel(viF)
tmr(:,:,iF1) = read_(vidobj, viF(iF1), nSkip_img);
% tmr(:,:,iF1) = img(:,:,1);
% fprintf('.');
end
fprintf('\n');
% end
end
fprintf('\ttook %0.1fs\n', toc(t1));
end %func
function img = read_(vidobj, iFrame, nSkip_img)
if nargin<3, nSkip_img = 1; end
img = read(vidobj, iFrame);
img = img(:,:,1);
if nSkip_img>1
img = binned_image_(img, nSkip_img, 0);
end
end %func
function img1 = binned_image_(img, nSkip, iMode)
% iMode: set to 0:averaging, 1:fast, 2:max
if nargin<3, iMode = 1; end
if ndims(img)==3, img = img(:,:,1); end
if iMode == 1 %fast mode
img1 = img(1:nSkip:end, 1:nSkip:end); % faster
else
dimm1 = floor(size(img)/nSkip);
viY = (0:dimm1(1)-1) * nSkip;
viX = (0:dimm1(2)-1) * nSkip;
switch iMode
case 0
img1 = zeros(dimm1, 'single');
for ix = 1:nSkip
for iy = 1:nSkip % TODO: reshape and use adjacent elements
img1 = img1 + single(img(viY+iy, viX+ix));
end
end
img1 = img1 / (nSkip*nSkip);
if isa(img, 'uint8'), img1 = uint8(img1); end
case 2
img1 = zeros(dimm1, 'like', img);
for ix = 1:nSkip
for iy = 1:nSkip
img1 = max(img1, img(viY+iy, viX+ix));
end
end
end
end
end %func
|
github
|
jamesjun/vistrack-master
|
makeMask.m
|
.m
|
vistrack-master/makeMask.m
| 1,671 |
utf_8
|
0252571c9fc244b8f288068c944853cb
|
function mlMask = makeMask(xy0, d1, img0, strShape, r)
% d1: diameter
% r: range expansion
if nargin < 5
r = 0;
end
d1 = round(d1);
if d1 < 1
mlMask = false(size(img0)); %none included
return;
end
if nargin < 4
strShape = 'CIRCLE';
end
fig = figure;
warning off;
image(false(size(img0)));
switch upper(strShape)
case 'CIRCLE'
h = imellipse(gca, [xy0(1)-d1/2, xy0(2)-d1/2, d1, d1]); %[x y w h]
case 'SQUARE'
h = imrect(gca, [xy0(1)-d1/2, xy0(2)-d1/2, d1, d1]); %[x y w h]
case {'RECT', 'SQUARE'} %square
h = imrect(gca, [xy0(1)-d1(1)/2, xy0(2)-d1(2)/2, d1(1), d1(2)]); %[x y w h]
case 'TRIANGLE' % equilateral triangle
mrXY = bsxfun(@plus, xy0(:)', d1 / sqrt(3) * rotate_([0, 120, 240]));
h = impoly(gca, mrXY);
end
mlMask = createMask(h);
% make a round square
if r >= 1 && strcmpi(strShape, 'SQUARE')
mlMask1 = makeMask(xy0 + [+1,+1]*d1/2, 2*r, img0, 'CIRCLE');
mlMask2 = makeMask(xy0 + [+1,-1]*d1/2, 2*r, img0, 'CIRCLE');
mlMask3 = makeMask(xy0 + [-1,+1]*d1/2, 2*r, img0, 'CIRCLE');
mlMask4 = makeMask(xy0 + [-1,-1]*d1/2, 2*r, img0, 'CIRCLE');
mlMask5 = makeMask(xy0, [d1, d1+2*r], img0, 'RECT');
mlMask6 = makeMask(xy0, [d1+2*r, d1], img0, 'RECT');
mlMask = mlMask1 | mlMask2 | mlMask3 | mlMask4 | mlMask5 | mlMask6;
end
%expand
if nargout > 0
close(fig);
else
img1 = imadjust(img0);
img1(mlMask) = 0;
imshow(img1);
end
end %func
%--------------------------------------------------------------------------
% rotate a line and project. rotate from North
function xy = rotate_(vrA_deg)
vrA_ = pi/2 - vrA_deg(:)/180*pi;
xy = [cos(vrA_), sin(vrA_)];
end %func
|
github
|
jamesjun/vistrack-master
|
imgray2rgb.m
|
.m
|
vistrack-master/imgray2rgb.m
| 1,225 |
utf_8
|
9c6ace56ed8de2c203251d5385fb1379
|
function RGB = imgray2rgb(I, inputrange, vcColorMap)
% imgray2rgb converts image to RGB scaled image, unit8
% JJJ function
if nargin<3, vcColorMap = 'jet'; end % PARULA, HSV, HOT, PINK
if ~exist('inputrange')
if strcmp(class(I), 'uint8')
inputrange = [0 255];
else
inputrange = [min(I(:)) max(I(:))];
end
else
if isempty(inputrange)
if ~strcmp(class(I), 'uint8')
inputrange = [min(I(:)) max(I(:))];
end
end
end
if strcmp(class(I), 'uint8')
if ~isempty(inputrange)
I = imadjust(I, double(inputrange)/255, [0 1]);
end
I = uint8(I);
RGB = ind2rgb_(I, vcColorMap);
else
I = double(I);
I = uint8((I-inputrange(1)) / (inputrange(2)-inputrange(1)) * size(theCmap, 1));
RGB = ind2rgb_(I, vcColorMap);
end
end %func
%--------------------------------------------------------------------------
function [RGB, mrCmap] = ind2rgb_(miImg, vcColorMap)
% I: int8, vcColorMap: char
eval(sprintf('mrCmap = uint8(%s(256)*255);', lower(vcColorMap)));
RGB = zeros([size(miImg), 3], 'uint8');
miImg = miImg + 1; % 0 base to 1 base
for iColor = 1:3
viMap_ = mrCmap(:,iColor);
RGB(:,:,iColor) = viMap_(miImg);
end
end %func
|
github
|
jamesjun/vistrack-master
|
plotErrorbar2014.m
|
.m
|
vistrack-master/plotErrorbar2014.m
| 1,706 |
utf_8
|
e4615e604347ae8ce8426016bff657db
|
function plotErrorbar(mrX, mlPath_E1, mlPath_L1, bootFcn, ystr)
%n by 3 (val, low, high)
[vrY, vrE, p] = bootCI_P(bootFcn, mrX(mlPath_E1), mrX(mlPath_L1));
% [bootFcn(mrX(mlPath_E1)), bootFcn(mrX(mlPath_L1))];
n = numel(vrY);
vrX = 1:n;
errorbar(vrX, vrY, vrE, 'r.'); hold on;
bar(vrX, vrY, .5);
set(gca, 'XLim', [.5 n+.5]);
set(gca, {'XTick', 'XTickLabel'}, {[1,2], {'Early', 'Late'}});
ylabel(ystr);
% [h p] = kstest2(mrX(mlPath_E1), mrX(mlPath_L1));
% [h p] = ttest2(mrX(mlPath_E1), mrX(mlPath_L1));
% title(sprintf('p = 10^{%f}', log10(p)));
if p < .0001
title(sprintf('****, p = %f', p));
elseif p < .001
title(sprintf('***, p = %f', p));
elseif p < .01
title(sprintf('**, p = %f', p));
elseif p < .05
title(sprintf('*, p = %f', p));
else
title(sprintf('p = %f', p));
end
end
function [vrY, vrE, p] = bootCI_P(bootFcn, vrA, vrB)
nboot = 1000;
vrY = [bootFcn(vrA), bootFcn(vrB)];
[ciA, vrBootA] = bootci(nboot, {bootFcn, vrA});
[ciB, vrBootB] = bootci(nboot, {bootFcn, vrB});
vrE = abs(vrY - [ciA(1), ciB(1)]);
p=nan;
%p = ttest2_jjj(vrBootA, vrBootB, vrE(1), vrE(2), numel(vrA), numel(vrB));
% p = pval_kstest2(vrBootA, vrBootB, numel(vrA), numel(vrB));
% star rating
% * P ? 0.05
% ** P ? 0.01
% *** P ? 0.001
% **** P ? 0.0001 (see note)
% http://faculty.psy.ohio-state.edu/myung/personal/course/826/bootstrap_hypo.pdf
% two-sample bootstrap hypothesis test
% tobs = vrY(1) - vrY(2);
% nboot1 = 3000;
% [bootstat, bootsam] = bootstrp(nboot1, bootFcn, [vrA(:); vrB(:)]);
% n = 0;
% for i=1:nboot1
% t = bootFcn(bootsam(1:numel(vrA), i)) - bootFcn(bootsam(end-numel(vrB)+1:end, i));
% n = n + (t > tobs);
% end
% p = (n / nboot1); %two-tailed
end %func
|
github
|
jamesjun/vistrack-master
|
GUI.m
|
.m
|
vistrack-master/GUI.m
| 55,337 |
utf_8
|
fc24bd99ae97b09ea6eef5e96f186e54
|
function varargout = GUI(varargin)
% GUI MATLAB code for GUI.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before GUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to GUI_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help GUI
% Last Modified by GUIDE v2.5 22-Nov-2018 12:52:57
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @GUI_OpeningFcn, ...
'gui_OutputFcn', @GUI_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 GUI is made visible.
function GUI_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 GUI (see VARARGIN)
% Choose default command line output for GUI
handles.output = hObject;
% Update settings window
% csSettings = importdata('settings_vistrack.m', '\n');
csSettings = file2cellstr_('settings_vistrack.m');
set(handles.editSettings, 'String', csSettings);
[vcVer, vcVer_date] = version_();
set(handles.textVer, 'String', sprintf('%s (%s) James Jun', vcVer, vcVer_date));
set(handles.btnUpdate, 'Enable', ifeq_(exist_dir_('.git'), 'on', 'off'));
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes GUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
function csLines = file2cellstr_(vcFile)
% read text file to a cell string
fid = fopen(vcFile, 'r');
csLines = {};
while ~feof(fid), csLines{end+1} = fgetl(fid); end
fclose(fid);
csLines = csLines';
% --- Outputs from this function are returned to the command line.
function varargout = GUI_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;
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in btnLoadVideo.
function btnLoadVideo_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadVideo (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles in: {handles.edit1}
% out: {vidfile, vidobj}
vidFname = get_str_(handles.edit1);
if ~exist_file_(vidFname)
[FileName,PathName,FilterIndex] = uigetfile('*.wmv;*.avi;*.mpg;*.mp4', ...
'Select video file', vidFname);
if ~FilterIndex, return; end
vidFname = fullfile(PathName, FileName);
end
handles.vidFname = vidFname;
buttons_off_(handles);
clear_cache_();
% Set result field
vcFile_out = subsFileExt_(vidFname, '_Track.mat');
if exist_file_(vcFile_out)
set(handles.editResultFile, 'String', vcFile_out);
if ask_user_('Load previous tracking result?')
try
btnLoadPrev_Callback(handles.btnLoadPrev, eventdata, handles);
set(handles.btnSync, 'Enable', 'off');
set(handles.btnBackground, 'Enable', 'off');
set(handles.btnTrack, 'Enable', 'off');
set(handles.btnPreview, 'Enable', 'off');
set(handles.btnSave, 'Enable', 'on');
set(handles.panelPlot, 'Visible', 'on');
return;
catch
msgbox('Loading tracking result failed');
end
end
else
set(handles.editResultFile, 'String', '');
end
try
set(handles.edit1, 'String', handles.vidFname);
h = msgbox('Loading... (this will close automatically)', 'modal');
% handles.vidobj = VideoReader(handles.vidFname);
handles.vidobj = vistrack('VideoReader', vidFname);
fprintf('Video file info: %s\n', handles.vidFname);
disp(handles.vidobj);
% fprintf('Calculating number of frames...\n');
fprintf('\t# video frames: %d\n', handles.vidobj.NumberOfFrames);
close_(h);
set(handles.btnSync, 'Enable', 'on');
set(handles.btnBackground, 'Enable', 'off');
set(handles.btnTrack, 'Enable', 'off');
set(handles.btnPreview, 'Enable', 'off');
set(handles.btnSave, 'Enable', 'off');
set(handles.panelPlot, 'Visible', 'off');
msgstr = 'Video';
% set the ADC file and ADC timestamp paths
% [PathName, fname, ~] = fileparts(vidFname);
% set timestamps if exists
vcFile_Rs = subsFileExt_(vidFname, '_Rs.mat');
if ~exist_file_(vcFile_Rs), vcFile_Rs = ''; end
handles.ADCfile = vcFile_Rs;
set(handles.editADCfile, 'String', vcFile_Rs);
handles.ADC = try_load_(handles.ADCfile);
vcFile_Ts = subsFileExt_(vidFname, '_Ts.mat');
if ~exist_file_(vcFile_Ts), vcFile_Ts = ''; end
handles.ADCfileTs = vcFile_Ts;
set(handles.editADCfileTs, 'String', vcFile_Ts);
handles.ADCTS = try_load_(handles.ADCfileTs);
if isempty(handles.ADC) || isempty(handles.ADCTS)
set(handles.btnBackground, 'Enable', 'on');
set(handles.btnSync, 'Enable', 'off');
end
guidata(hObject, handles);
msgbox([msgstr ' file(s) loaded']);
catch
errordlg(lasterr);
end
function buttons_off_(handles)
set(handles.btnSync, 'Enable', 'off');
set(handles.btnBackground, 'Enable', 'off');
set(handles.btnTrack, 'Enable', 'off');
set(handles.btnPreview, 'Enable', 'off');
set(handles.btnSave, 'Enable', 'off');
set(handles.panelPlot, 'Visible', 'off');
function editSettings_Callback(hObject, eventdata, handles)
% hObject handle to editSettings (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 editSettings as text
% str2double(get(hObject,'String')) returns contents of editSettings as a double
% --- Executes during object creation, after setting all properties.
function editSettings_CreateFcn(hObject, eventdata, handles)
% hObject handle to editSettings (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 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 in: editSettings
% --- Executes on button press in btnBackground.
function btnBackground_Callback(hObject, eventdata, handles)
% hObject handle to btnBackground (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
% Get time range from spike2
vcFile_adc_ts = get_str_(handles.editADCfileTs);
fSkipAdc = ~exist_file_(vcFile_adc_ts);
% if fSkipAdc
try
[FLIM, TC, img1, img00] = mov_flim_(handles.vidobj);
[img00, MASK, xy_init, vec0, xy0] = makeBackground(img1, img00);
try
TC = vistrack('cam2adc-sync', handles.S_sync, FLIM(1):FLIM(2));
% TC = interp1(handles.FLIM0, handles.TLIM0, FLIM(1):FLIM(2), 'linear');
catch
;
end
catch
return;
end
% Update handles structure
handles.MASK = MASK;
handles.xy_init = xy_init;
handles.vec0 = vec0;
handles.xy0 = xy0;
handles.TC = TC;
handles.TLIM = TC([1, end]);
handles.FLIM = FLIM;
handles.img1 = img1;
handles.img00 = img00;
guidata(hObject, handles);
set(handles.btnPreview, 'Enable', 'on');
% --- Executes on button press in btnTrack.
function btnTrack_Callback(hObject, eventdata, handles)
% hObject handle to btnTrack (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
handles.SE = strel('disk', BW_SMOOTH,0); %use disk size 3 for 640 480
handles.img0 = handles.img00 * (1-IM_MINCONTRAST); %make it darker
handles.fShow = TRACK_SHOW;
handles.ThreshLim = ThreshLim;
handles.fBWprev = 1;
TC = handles.TC;
try
[XC, YC, AC, Area, S1, MOV, XC_off, YC_off] = trackFish(handles, handles.FLIM);
catch
disp(lasterr)
errordlg('Cancelled by user');
return;
end
% Update figure handle
handles.XC = XC;
handles.YC = YC;
handles.AC = AC;
handles.MOV = MOV;
handles.XC_off = XC_off;
handles.YC_off = YC_off;
handles.xy_names = S1.xy_names;
handles.ang_names = S1.ang_names;
handles.csSettings = get_str_(handles.editSettings);
set(handles.panelPlot, 'Visible', 'on');
set(handles.btnSave, 'Enable', 'on');
guidata(hObject, handles);
vistrack('trial-save', handles);
% --- Executes on button press in btnSync.
function btnSync_Callback(hObject, eventdata, handles)
% hObject handle to btnSync (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = vistrack('trial-sync', handles);
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in btnSync.
function btnSync_Callback1(hObject, eventdata, handles)
% S_sync = calc_sync_(handles);
LOADSETTINGS;
vidobj = handles.vidobj;
% mov1 = vistrack('loadvid-preview', handles.vidobj);
try
handles.xyLED = xyLED;
catch
handles.xyLED = round([vidobj.height, vidobj.width]/2);
end
if ~exist('FPS0', 'var'), FPS0 = get(vidobj, 'FrameRate'); end
ADCTC = load(get_str_(handles.editADCfileTs));
disp_adc_title_(ADCTC);
if ~exist('TLIM0', 'var')
try
%load from spike2 TC channel
prefix = getSpike2Prefix(ADCTC);
chTCAM = getfield(ADCTC, sprintf('%s_Ch%d', prefix, ADC_CH_TCAM));
chTCAM = chTCAM.times;
if ~exist('SYNC_PERIOD', 'var'), SYNC_PERIOD = median(diff(chTCAM)); end
TLIM0 = chTCAM([1 end]);
fprintf('TLIM0: ');
disp(TLIM0(:)');
catch
disp(lasterr);
errordlg('Specify TLIM0 = [First, Last]; in the Settings');
return;
end
end
% vistrack('checkLedPos', handles.vidobj, handles.xyLED);
try
if ~exist('FLIM0', 'var')
FLIM0 = [];
[FLIM0(1), handles.xyLed] = detectBlink(handles, 'first');
FLIM0(2) = detectBlink(handles, 'last');
end
if ~exist('SYNC_FIRST', 'var'), SYNC_FIRST = 0; end
FPS = diff(FLIM0) / diff(TLIM0);
SYNC_SKIP0 = (diff(FLIM0)/FPS0 - diff(TLIM0))/SYNC_PERIOD;
fprintf('TLIM: [%f, %f], SYNC_SKIP: %f\n', TLIM0(1), TLIM0(2), SYNC_SKIP0);
SYNC_SKIP = round(SYNC_SKIP0);
if SYNC_FIRST
TLIM0(2) = TLIM0(2) + SYNC_SKIP*SYNC_PERIOD;
else
TLIM0(1) = TLIM0(1) - SYNC_SKIP*SYNC_PERIOD;
end
FPS = diff(FLIM0) / diff(TLIM0);
fCheckSync = 0;
%check if correct
if fCheckSync
[viBlink, vrBlinkInt] = findBlink(handles.vidobj, SYNC_PERIOD, FLIM0(1), FPS);
chTCAM = getfield(ADCTC, sprintf('%s_Ch%d', prefix, ADC_CH_TCAM));
vtBlink = chTCAM.times;
n = min(numel(viBlink), numel(vtBlink));
viBlink2 = round(interp1(TLIM0, FLIM0, TLIM0(1):SYNC_PERIOD:TLIM0(end)));
hFig = figure;
set(gcf, 'OuterPosition', get(0, 'ScreenSize')); drawnow;
AX = [];
subplot 311; plot(vtBlink(1:n), viBlink(1:n), 'b.', vtBlink(1:n), viBlink(1:n), 'bo', vtBlink(1:n), viBlink2, 'r.-');
AX(1) = gca; title('Blue: Observed, Red: Predicted');
xlabel('ADC Time (s)'); ylabel('Frame #');
subplot 312; plot(vtBlink(1:n), viBlink(1:n) - viBlink2); ylabel('Frame# difference');
AX(2) = gca;
subplot 313; plot(vtBlink(1:n), vrBlinkInt(1:n)); ylabel('Brightness');
set(gca, 'YLim', [1 2]);
AX(3) = gca;
linkaxes(AX, 'x');
end
catch
disp(lasterr);
errordlg('Check the TLIM0 setting (ADC time range)');
return;
end
TLIM0 = round(TLIM0);
str = sprintf('FPS = %0.6f Hz, TLIM0=[%d, %d], FLIM0=[%d, %d]\n', FPS, TLIM0(1), TLIM0(2), FLIM0(1), FLIM0(2));
msgbox(str);
disp(str);
% Update handles structure
handles.TLIM0 = TLIM0;
handles.FLIM0 = FLIM0;
handles.FPS = FPS;
guidata(hObject, handles);
set(handles.btnBackground, 'Enable', 'on');
% --- Executes on button press in btnPreview.
function btnPreview_Callback(hObject, eventdata, handles)
% hObject handle to btnPreview (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
% Obrain mask and initial location
img0 = handles.img00 * (1-IM_MINCONTRAST); %make it darker
% Initial
SE = strel('disk', BW_SMOOTH,0); %use disk size 3 for 640 480
[WINPOS, ~] = getBoundingBoxPos(handles.xy_init, size(img0), winlen*[1 1]);
img = handles.img1(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2), :);
img0c = img0(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2), :);
dimg = uint8_diff(img0c, img, 0);
BW = imdilate(bwmorph((dimg > IM_THRESH), 'clean', inf), SE);
BW = imfill(BW, 'holes');
BW = imclearborder(BW);
regions = regionprops(BW, {'Area', 'Centroid', 'Orientation', 'FilledImage', 'BoundingBox'});
if numel(regions)>1
L = bwlabel(BW, 8);
[iRegion] = region_nearest(regions, handles.xy0 - WINPOS([1,3]));
regions = regions(iRegion);
BW = L==iRegion;
end
[BW, AreaTarget] = bwgetlargestblob(BW);
% Update
handles.SE = SE;
handles.thresh = IM_THRESH;
handles.AreaTarget = AreaTarget;
handles.WINPOS = WINPOS;
handles.img0 = img0;
guidata(hObject, handles);
set(handles.btnTrack, 'Enable', 'on');
% Preview images
hFig = figure;
set(hFig, 'OuterPosition', get(0, 'ScreenSize'), ...
'Color', 'w', 'Name', handles.vidFname, 'NumberTitle', 'off');
drawnow;
subplot(2,2,1);
imagesc(img, INTENSITY_LIM);
axis equal; axis tight;
set(gca, {'XTick', 'YTick'}, {[],[]});
title('1. Original image');
subplot(2,2,2);
imagesc(dimg);
axis equal; axis tight;
set(gca, {'XTick', 'YTick'}, {[], []});
title('2. Difference image');
subplot(2,2,3);
imshow(BW);
title(sprintf('3. Binary image (Area=%d)', AreaTarget));
subplot(2,2,4);
BW1 = bwperim(BW);
img4 = img; img4(BW1)=255;
% imshow(img4);
imagesc(img4, INTENSITY_LIM);
axis equal; axis tight;
set(gca, {'XTick', 'YTick'}, {[],[]});
title_('4. Superimposed (if incorrect, lower "IM_THRESH")');
colormap gray;
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% do not auto save the settings unless manually saved
% writeText('settings.m', get(handles.editSettings, 'String'));
delete(hObject);
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
writeText('settings_vistrack.m', get_str_(handles.editSettings));
handles.csSettings = get_str_(handles.editSettings);
guidata(hObject, handles);
function editADCfile_Callback(hObject, eventdata, handles)
% hObject handle to editADCfile (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 editADCfile as text
% str2double(get(hObject,'String')) returns contents of editADCfile as a double
% --- Executes during object creation, after setting all properties.
function editADCfile_CreateFcn(hObject, eventdata, handles)
% hObject handle to editADCfile (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 btnLoadADC.
function btnLoadADC_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadADC (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[FileName,PathName,FilterIndex] = uigetfile('*.mat','Select ADC file',get_str_(handles.editADCfile));
if FilterIndex
try
handles.ADCfile = fullfile(PathName, FileName);
set(handles.editADCfile, 'String', handles.ADCfile);
h = msgbox('Loading... (this will close automatically)');
handles.ADC = load(handles.ADCfile);
try close(h); catch, end;
guidata(hObject, handles);
msgbox('ADC File loaded');
catch
set(handles.editADCfile, 'String', '');
errordlg(lasterr);
end
end
% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton11 (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 pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton12 (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 pushbutton13.
function pushbutton13_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton13 (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 pushbutton16.
function pushbutton16_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton16 (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 btnPlot2.
function btnPlot2_Callback(hObject, eventdata, handles)
% hObject handle to btnPlot2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
XC = handles.XC;
YC = handles.YC;
hFig = figure;
imshow((handles.img0)); title('Posture trajectory (red: more recent, circle: head)');
resize_figure(hFig, [0,0,.5,1]);
hold on;
nframes = size(XC,1);
nxy = size(XC,2);
mrColor = jet(nframes);
for iframe=1:TRAJ_STEP:nframes
XI = interp1(2:nxy, XC(iframe,2:end), 2:.1:nxy, 'spline');
YI = interp1(2:nxy, YC(iframe,2:end), 2:.1:nxy, 'spline');
plot(XI, YI, 'color', mrColor(iframe,:));
plot(XI(1), YI(1), 'o', 'color', mrColor(iframe,:));
end
% --- Executes on button press in btnEodRate.
function btnEodRate_Callback(hObject, eventdata, handles)
% hObject handle to btnEodRate (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
TC = handles.TC;
try
ADC = handles.ADC;
[EODR, TEOD, chName] = getSpike2Chan(ADC, ADC_CH_PLOT);
fprintf('Loaded Spike2 %s (Ch%d)\n', chName, ADC_CH_PLOT);
catch
disp(lasterr);
errordlg('Load ADC file');
return;
end
%smooth and interpolate position
TCi = TC(1):(1/EODR_SR):TC(end);
X2i = interp1(handles.TC, filtPos(handles.XC(:,2), TRAJ_NFILT), TCi, 'spline', 'extrap');
Y2i = interp1(handles.TC, filtPos(handles.YC(:,2), TRAJ_NFILT), TCi, 'spline', 'extrap');
X3i = interp1(handles.TC, filtPos(handles.XC(:,3), TRAJ_NFILT), TCi, 'spline', 'extrap');
Y3i = interp1(handles.TC, filtPos(handles.YC(:,3), TRAJ_NFILT), TCi, 'spline', 'extrap');
%convert rate to 0..255 color level at the camera time
R = interp1(TEOD, EODR, TCi);
R = (R-min(R))/(max(R)-min(R));
viColorRate = ceil(R * 256);
viColorRate(viColorRate<=0)=1;
mrColor = jet(256);
% figure; plot(handles.TC, viColorRate);
% Plot the EOD color representation
hFig = figure;
imagesc(handles.img0);
set(gca, {'XTick', 'YTick'}, {[],[]}); axis equal; axis tight;
hold on;
title(sprintf('EOD (%s) at the head trajectory (red: higher rate)', chName));
for i=1:numel(viColorRate)
plotChevron([X2i(i), X3i(i)], [Y2i(i), Y3i(i)], mrColor(viColorRate(i),:), 90, .3);
% plot(Xi(i), Yi(i), '.', 'color', mrColor(viColorRate(i),:));
end
colormap gray;
resize_figure(hFig, [0 0 .5 1]);
% --- Executes on button press in btnPlot1.
function btnPlot1_Callback(hObject, eventdata, handles)
% hObject handle to btnPlot1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
XC = handles.XC;
YC = handles.YC;
% filter position
nf = TRAJ_NFILT;
XCf_h = filtPos(XC(:,2),nf); YCf_h = filtPos(YC(:,2),nf);
XCf_hm = filtPos(XC(:,3),nf); YCf_hm = filtPos(YC(:,3),nf);
XCf_m = filtPos(XC(:,4),nf); YCf_m = filtPos(YC(:,4),nf);
XCf_tm = filtPos(XC(:,5),nf); YCf_tm = filtPos(YC(:,5),nf);
XCf_t = filtPos(XC(:,6),nf); YCf_t = filtPos(YC(:,6),nf);
figure; imshow(handles.img0); title('Trajectory of the rostral tip');
hold on; plot(XCf_h, YCf_h);
pause(.4);
hold on; comet(XCf_h, YCf_h, .1);
% --- Executes on button press in btnPlot3.
function btnPlot3_Callback(hObject, eventdata, handles)
% hObject handle to btnPlot3 (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 btnMovOut.
function btnMovOut_Callback(hObject, eventdata, handles)
% hObject handle to btnMovOut (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% load data
LOADSETTINGS;
TC = handles.TC;
XC = handles.XC;
YC = handles.YC;
try
ADC = handles.ADC;
[EODR, TEOD, chName] = getSpike2Chan(ADC, ADC_CH_PLOT);
fprintf('Loaded Spike2 %s (Ch%d)\n', chName, ADC_CH_PLOT);
% Resample EOD Rate to camera time
RC = interp1(TEOD, EODR, TC);
% RC = filtfilt(ones(1,TRAJ_STEP), TRAJ_STEP, RC);
catch
disp(lasterr)
errordlg('Load ADC file');
return;
end
% figure; plot(TEOD, EODR, 'r.', TC, RC, 'b-');
% Plot the EOD color representation
writerObj = VideoWriter(MOV_FILEOUT, 'MPEG-4');
set(writerObj, 'FrameRate', handles.FPS); %30x realtime
% set(writerObj, 'Quality', 90); %30x realtime
open(writerObj);
figure; title('Reposition'); pause;
subplot(4,1,1:3);
hfig = imshow(gray2rgb(handles.img0, INTENSITY_LIM));
% hfig = imagesc(handles.img0, INTENSITY_LIM);
set(gca, {'XTick', 'YTick'}, {[],[]});
axis equal; axis tight; hold on;
title('EOD rate at the head (red: higher rate)');
%plot locations
nframes = size(XC,1);
% mrColor = jet(nframes);
[mrColor, vrRateSrt, vrQuantSrt] = quantile2color(RC);
%colorbar
plotColorbar(size(handles.img0), vrRateSrt, vrQuantSrt);
EODR1 = EODR(TEOD > TLIM(1) & TEOD < TLIM(2));
RLIM = [quantile_(EODR1, .001), quantile_(EODR1, .999)];
htext = [];
vhChevron = [];
for iframe=1:nframes
%------------------
subplot(4,1,1:3);
frameNum = iframe + handles.FLIM(1) - 1;
mrImg = readFrame(handles.vidobj, frameNum);
mrImg(~handles.MASK) = 0;
mrImg = gray2rgb(mrImg, INTENSITY_LIM);
set(hfig, 'cdata', mrImg);
try delete(htext); catch, end;
htext(1) = text(10, 30, sprintf('EOD (%s): %0.1f Hz', chName, RC(iframe)), ...
'FontSize', 12, 'Color', [1 1 1]);
htext(2) = text(10, 75, sprintf('Time: %0.1f s', TC(iframe)), ...
'FontSize', 12, 'Color', [1 1 1]);
htext(3) = text(10, 120, sprintf('Frame: %d', frameNum), ...
'FontSize', 12, 'Color', [1 1 1]);
if mod(iframe, MOV_PLOTSTEP) == 0
vhChevron(end+1) = plotChevron(XC(iframe, 2:3), YC(iframe, 2:3), mrColor(iframe,:), 90, .3);
if numel(vhChevron) > MOV_PLOTLEN
delete(vhChevron(1:end-MOV_PLOTLEN));
vhChevron(1:end-MOV_PLOTLEN) = [];
end
end
%------------------
subplot(4,1,4);
hold off;
plot(TEOD - TC(iframe), EODR, 'k.'); hold on;
axis([MOV_TimeWin(1), MOV_TimeWin(2), RLIM(1), RLIM(2)]);
plot([0 0], get(gca, 'YLim'), 'r-');
grid on;
xlabel('Time (sec)');
ylabel(sprintf('EOD (%s) Hz', chName));
colormap jet;
% drawnow;
try
writeVideo(writerObj, getframe(gcf));
catch
disp('Movie output cancelled by user');
close(writerObj);
return;
end
end
close(writerObj);
msgbox(sprintf('File written to %s', MOV_FILEOUT));
% --- Executes on button press in btnSoundOut
function btnSoundOut_Callback(hObject, eventdata, handles)
% hObject handle to btnSoundOut (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% load data
LOADSETTINGS;
TC = handles.TC;
TLIM = [TC(1), TC(end)];
try
S = handles.ADCTS;
csFieldnames = fieldnames(S);
S = getfield(S, csFieldnames{1});
Teod = S.times;
Teod1 = Teod(Teod > TLIM(1) & Teod < TLIM(2));
viEod1 = round((Teod1 - TLIM(1)) * WAV_Fs);
tdur = diff(TLIM);
ns = round(tdur * WAV_Fs);
%make a binary vector
mlBinvec = zeros(ns,1);
mlBinvec(viEod1) = 1;
wavwrite(mlBinvec, WAV_Fs, WAV_FILEOUT);
msgbox(sprintf('File written to %s', WAV_FILEOUT));
catch
disp(lasterr)
errordlg('Load ADC Timestamp');
return;
end
function editADCfileTs_Callback(hObject, eventdata, handles)
% hObject handle to editADCfileTs (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 editADCfileTs as text
% str2double(get(hObject,'String')) returns contents of editADCfileTs as a double
% --- Executes during object creation, after setting all properties.
function editADCfileTs_CreateFcn(hObject, eventdata, handles)
% hObject handle to editADCfileTs (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 btnLoadADCTS.
function btnLoadADCTS_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadADCTS (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[FileName,PathName,FilterIndex] = uigetfile('*.mat','Select ADC Timestamp', get_str_(handles.editADCfileTs));
if FilterIndex
try
handles.ADCfileTs = fullfile(PathName, FileName);
set(handles.editADCfileTs, 'String', handles.ADCfileTs);
h = msgbox('Loading... (this will close automatically)');
handles.ADCTS = load(handles.ADCfileTs);
try close(h); catch, end;
guidata(hObject, handles);
msgbox('ADC File loaded');
catch
set(handles.editADCfileTs, 'String', '');
errordlg(lasterr);
end
end
% --- Executes during object creation, after setting all properties.
function btnPreview_CreateFcn(hObject, eventdata, handles)
% hObject handle to btnPreview (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes on button press in btnPlotDensity.
function btnPlotDensity_Callback(hObject, eventdata, handles)
% hObject handle to btnPlotDensity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% vistrack('trial-visitcount', handles);
vistrack('trial-visitcount', handles);
% LOADSETTINGS;
% h = msgbox('Calculating... (this will close automatically)');
%
% % [mnVisit1, mnVisit] = calcVisitCount(vsTrialPool, img0, mlMask, nGrid);
%
% %track head
% [VISITCNT, TIMECNT] = calcVisitDensity(handles.img0, handles.TC, handles.XC(:,2), handles.YC(:,2), TRAJ_NFILT);
% try close(h); catch, end;
%
% [~, exprID, ~] = fileparts(handles.vidFname);
% img0_adj = imadjust(handles.img0);
% figure;
% subplot 121;
% imshow(rgbmix(img0_adj, imgray2rgb(TIMECNT), [], 'transparent'));
% title(['Time density map: ', exprID]);
%
% subplot 122;
% imshow(rgbmix(img0_adj, imgray2rgb(VISITCNT), [], 'transparent'));
% title(['Visit density map: ', exprID]);
%
% %update
% handles.TIMECNT = TIMECNT;
% handles.VISITCNT = VISITCNT;
% guidata(hObject, handles);
function editResultFile_Callback(hObject, eventdata, handles)
% hObject handle to editResultFile (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 editResultFile as text
% str2double(get(hObject,'String')) returns contents of editResultFile as a double
% --- Executes during object creation, after setting all properties.
function editResultFile_CreateFcn(hObject, eventdata, handles)
% hObject handle to editResultFile (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 btnLoadPrev.
function btnLoadPrev_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadPrev (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
resultFile = get_str_(handles.editResultFile);
if ~exist_file_(resultFile)
[FileName,PathName,FilterIndex] = uigetfile('*_Track.mat','Select *_Track.mat file', resultFile);
if ~FilterIndex, return; end
resultFile = fullfile(PathName, FileName);
end
try
% resultFile = fullfile(PathName, FileName);
set(handles.editResultFile, 'String', resultFile);
h = msgbox('Loading... (this will close automatically)');
warning off;
S = load(resultFile);
try close(h); catch, end;
% Apply settings
set(handles.editSettings, 'String', S.csSettings);
S_cfg = vistrack('load-cfg');
handles = struct_merge_(handles, S, S_cfg.csFields);
handles.vcFile_Track = resultFile;
set(handles.edit1, 'String', handles.vidFname);
set(handles.editADCfile, 'String', [handles.vidFname(1:end-4), '_Rs.mat']);
set(handles.editADCfileTs, 'String', [handles.vidFname(1:end-4), '_Ts.mat']);
set(handles.btnSync, 'Enable', 'off');
set(handles.btnBackground, 'Enable', 'off');
set(handles.btnTrack, 'Enable', 'off');
set(handles.btnPreview, 'Enable', 'off');
set(handles.btnSave, 'Enable', 'on');
set(handles.panelPlot, 'Visible', 'on');
guidata(hObject, handles);
clear_cache_();
msgbox('Tracking Result loaded');
catch
set(handles.editResultFile, 'String', '');
errordlg(lasterr);
end
% --- Executes on button press in btnSave.
function btnSave_Callback(hObject, eventdata, handles)
% hObject handle to btnSave (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trial-save', handles);
% --- Executes during object creation, after setting all properties.
function btnSave_CreateFcn(hObject, eventdata, handles)
% hObject handle to btnSave (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes on button press in btnReplay.
function btnReplay_Callback(hObject, eventdata, handles)
% hObject handle to btnReplay (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
warning off;
LOADSETTINGS;
MOV = handles.MOV;
TC1 = handles.TC - handles.TC(1);
mrXC = bsxfun(@minus, handles.XC, handles.XC_off);
mrYC = bsxfun(@minus, handles.YC, handles.YC_off);
%setup fig
timer1 = timer('Period', 1/15, 'ExecutionMode', 'fixedRate', 'TasksToExecute', inf);
hFig = figure('NumberTitle', 'off', 'Name', ...
'[H]elp; (Sft)+[L/R/U/D]; SPACEBAR:Pause; [F]lip; [C]ut upto here; [G]oto Frame');
hImg = imshow(imadjust(MOV(:,:,1))); hold on;
iFrame = 1;
XC = mrXC(iFrame,:);
YC = mrYC(iFrame,:);
nxy = numel(XC);
X1 = interp1(2:nxy, XC(2:end), 2:.1:nxy, 'spline');
Y1 = interp1(2:nxy, YC(2:end), 2:.1:nxy, 'spline');
hPlot = plot(XC(2), YC(2), 'go', XC(3:end), YC(3:end), 'mo',...
X1, Y1, 'm-', XC(1), YC(1), 'g+', 'LineWidth', 2); %Mark the centroid
hTitle = title(sprintf('F1: %d; T1: %0.3f s, Step: %d', ...
iFrame, TC1(iFrame), REPLAY_STEP));
resize_figure(hFig, [0,0,.5,1]);
%setup timer
Stimer = struct('hImg', hImg, 'TC1', TC1, 'hFig', hFig, 'hPlot', hPlot, 'iFrame', iFrame, ...
'hTitle', hTitle, 'REPLAY_STEP', REPLAY_STEP, 'hObject', hObject);
set(timer1, 'UserData', Stimer);
set(hFig, 'UserData', timer1, 'KeyPressFcn', @keyFcnPreview, ...
'CloseRequestFcn', @closeFcnPreview);
set(timer1, 'TimerFcn', @timerFcnPreview);
start(timer1);
% --- Executes on button press in btnFlip.
function btnFlip_Callback(hObject, eventdata, handles)
% hObject handle to btnFlip (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
iFrame = str2double(inputdlg('Frame #:', 'Flip orientation', 1, {''}));
if isempty(iFrame), return ;end
GUI_FLIP;
% Save
% btnSave_Callback(hObject, eventdata, handles);
% --- Executes on button press in btnCustom.
function btnCustom_Callback(hObject, eventdata, handles)
% hObject handle to btnCustom (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
GUI_ESACPLOT;
% --- Executes on button press in btnESAC.
function btnESAC_Callback(hObject, eventdata, handles)
% hObject handle to btnESAC (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
GUI_ESACCADES;
% --- Executes on button press in btnEODMovie.
function btnEODMovie_Callback(hObject, eventdata, handles)
% hObject handle to btnEODMovie (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
GUI_EODMOVIE;
function msgbox_(vcMsg)
fprintf('%s\n', vcMsg);
msgbox(vcMsg);
function disp_adc_title_(ADCTC)
S_adc = ADCTC;
fprintf('Spike2 ADC output:\n');
cellfun(@(vc)fprintf('\t%s: %s (%0.3f-%0.3fs)\n', ...
vc, S_adc.(vc).title, S_adc.(vc).times(1), S_adc.(vc).times(end)), ...
fieldnames(S_adc));
fprintf('\n');
%--------------------------------------------------------------------------
% 9/26/17 JJJ: Created and tested
function flag = exist_file_(vcFile)
if nargin<2, fVerbose = 0; end
if isempty(vcFile)
flag = 0;
else
S_dir = dir(vcFile);
if numel(S_dir) == 1
flag = ~S_dir.isdir;
else
flag = 0;
end
end
if fVerbose && ~flag
fprintf(2, 'File does not exist: %s\n', vcFile);
end
%--------------------------------------------------------------------------
% 8/2/17 JJJ: added '.' if dir is empty
% 7/31/17 JJJ: Substitute file extension
function varargout = subsFileExt_(vcFile, varargin)
% Substitute the extension part of the file
% [out1, out2, ..] = subsFileExt_(filename, ext1, ext2, ...)
[vcDir_, vcFile_, ~] = fileparts(vcFile);
if isempty(vcDir_), vcDir_ = '.'; end
for i=1:numel(varargin)
vcExt_ = varargin{i};
varargout{i} = [vcDir_, filesep(), vcFile_, vcExt_];
end
%--------------------------------------------------------------------------
function flag = ask_user_(vcMsg, fYes)
if nargin<2, fYes = 1; end
if fYes
vcAns = questdlg(vcMsg, '', 'Yes', 'No', 'Yes');
else
vcAns = questdlg(vcMsg, '', 'Yes', 'No', 'Yes');
end
flag = strcmp(vcAns, 'Yes');
%--------------------------------------------------------------------------
function S = try_load_(vcFile)
S = [];
if isempty(vcFile), return; end
try
S = load(vcFile);
fprintf('%s loaded\n', vcFile);
catch
errordlg(sprintf('%s load error', vcFile));
end
% --- Executes on button press in btnUpdate.
function btnUpdate_Callback(hObject, eventdata, handles)
% hObject handle to btnUpdate (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('update');
msgbox('Update successful, Restart the app');
%--------------------------------------------------------------------------
% 9/29/17 JJJ: Displaying the version number of the program and what's used. #Tested
function [vcVer, vcDate] = version_()
if nargin<1, vcFile_prm = ''; end
% vcVer = 'v0.1.2';
% vcDate = '7/11/2018';
[vcVer, vcDate] = vistrack('version');
if nargout==0
fprintf('%s (%s) installed\n', vcVer, vcDate);
end
% --- Executes on button press in btnLoadTrialSet.
function btnLoadTrialSet_Callback(hObject, eventdata, handles)
% hObject handle to btnLoadTrialSet (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vcFile_trialset = get_str_(handles.editTrialSet);
if ~exist_file_(vcFile_trialset)
[FileName,PathName,FilterIndex] = uigetfile('*.trialset', ...
'Select trialset', vcFile_trialset);
if ~FilterIndex, return; end
vcFile_trialset = fullfile(PathName, FileName);
else
vcFile_trialset = fullpath_(vcFile_trialset);
end
set(handles.editTrialSet, 'String', vcFile_trialset);
set(handles.panelTrialSet, 'Visible', 'on');
edit(vcFile_trialset);
msgbox(sprintf('Loaded %s', vcFile_trialset), 'Loading Trialset');
% --- Executes on button press in btnEditTrialset.
function btnEditTrialset_Callback(hObject, eventdata, handles)
% hObject handle to btnEditTrialset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
edit(get_str_(handles.editTrialSet));
% --- Executes on button press in btnLearningCurve.
function btnLearningCurve_Callback(hObject, eventdata, handles)
% hObject handle to btnLearningCurve (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-learningcurve', get_str_(handles.editTrialSet));
% [cvrPathLen, cvrDuration] = vistrack('measure_trials', get_str_(handles.editTrialSet));
% --- Executes on button press in btnSamplingDensity.
function btnSamplingDensity_Callback(hObject, eventdata, handles)
% hObject handle to btnSamplingDensity (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 btnESCAN.
function btnESCAN_Callback(hObject, eventdata, handles)
% hObject handle to btnESCAN (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 btnBSCAN.
function btnBSCAN_Callback(hObject, eventdata, handles)
% hObject handle to btnBSCAN (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 btnVisitDensity.
function btnVisitDensity_Callback(hObject, eventdata, handles)
% hObject handle to btnVisitDensity (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 btnProbeTrials.
function btnProbeTrials_Callback(hObject, eventdata, handles)
% hObject handle to btnProbeTrials (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-probe', get_str_(handles.editTrialSet));
% --- Executes on button press in btnListFiles.
function btnListFiles_Callback(hObject, eventdata, handles)
% hObject handle to btnListFiles (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-list', get_str_(handles.editTrialSet));
function vc = get_str_(hObj)
try
vc = strtrim(get(hObj, 'String'));
catch
vc = '';
end
function set_str_(hObj, vc)
try
set(hObj, 'String', strtrim(vc));
catch
;
end
% --- Executes on button press in btnBarPlots.
function btnBarPlots_Callback(hObject, eventdata, handles)
% hObject handle to btnBarPlots (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-barplots', get_str_(handles.editTrialSet));
% --- Executes on button press in btnExportCsv.
function btnExportCsv_Callback(hObject, eventdata, handles)
% hObject handle to btnExportCsv (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-exportcsv', get_str_(handles.editTrialSet));
% --- Executes on button press in btnTrialsetFps.
function btnTrialsetFps_Callback(hObject, eventdata, handles)
% hObject handle to btnTrialsetFps (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-checkfps', get_str_(handles.editTrialSet));
% --- Executes on button press in btnTrialsetCoordinates.
function btnTrialsetCoordinates_Callback(hObject, eventdata, handles)
% hObject handle to btnTrialsetCoordinates (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-coordinates', get_str_(handles.editTrialSet));
% --- Executes on button press in btnFixFps_trialset.
function btnFixFps_trialset_Callback(hObject, eventdata, handles)
% hObject handle to btnFixFps_trialset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-fixfps', get_str_(handles.editTrialSet));
% --- Executes on button press in pushbutton70.
function pushbutton70_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton70 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
function [FLIM, TC, img1, img00] = mov_flim_(vidobj, nFrames_load)
% mov_flim_(): clear cache
persistent csAns1 csAns2 csAns3
if nargin==0, [csAns1, csAns2, csAns3] = deal([]); return; end %clear cache
if nargin<2, nFrames_load = 300; end % skip every 10 frames
% if isempty(nFrames_skip), nFrames_skip = 75; end
warning off;
nFrames = vidobj.NumberOfFrames;
% nFrames_skip = floor(nFrames / nFrames_load);
TC = linspace(0, vidobj.Duration, nFrames); % use sync function
% viF = 1:nFrames_skip:nFrames;
viF = unique(round(linspace(1, nFrames, nFrames_load)));
% viF = 1:nFrames_load; % much faster to load
% if isempty(mov1)
mov1 = vistrack('loadvid-preview', vidobj);
% mov1 = mov_shrink_(read_(vidobj, viF), 2);
% end
% rough scan
implay(mov1(:,:,viF));
uiwait(msgbox('Find the first and last frame to track, and close the movie'));
if isempty(csAns1), csAns1 = {'1', sprintf('%d', numel(viF))}; end
csAns = inputdlg({'First frame', 'Last frame'}, 'Get frames', 1, csAns1);
csAns1 = csAns;
frame_first = viF(str2num(csAns{1}));
frame_last = viF(str2num(csAns{2}));
fprintf('#1: First frame: %s; Last frame: %s\n', csAns{1}, csAns{2});
% Find first frame to track
viF_first = trim_(frame_first + (-150:149), 1, nFrames);
% tmr = read_(vidobj, viF_first);
implay(mov1(:,:,viF_first));
% implay(mov_shrink_(tmr, 2));
uiwait(msgbox('Find the first frame to track and background, and close the movie'));
if isempty(csAns2), csAns2 = {'1', num2str(numel(viF_first))}; end
csAns = inputdlg({'First frame', 'Background frame'}, 'Get frames', 1, csAns2);
csAns2 = csAns;
frame_first = viF_first(str2num(csAns{1}));
frame_background = viF_first(str2num(csAns{2}));
img1 = read_(vidobj, frame_first);
img00 = read_(vidobj, frame_background);
fprintf('#2: First frame: %s; Background frame: %s\n', csAns{1}, csAns{2});
% Find last frame to track
viF_last = trim_(frame_last + (-150:149), 1, nFrames);
implay(mov1(:,:,viF_last));
uiwait(msgbox('Find the last frame to track, and close the movie'));
iFrame3 = ceil(numel(viF_last)/2);
if isempty(csAns3), csAns3 = {num2str(iFrame3)}; end
csAns = inputdlg({'Last frame'}, 'Get frames', 1, csAns3);
csAns3 = csAns;
frame_last = viF_last(str2num(csAns{1}));
fprintf('#3: Last frame: %s\n', csAns{1});
FLIM = [frame_first, frame_last];
TC = TC(frame_first:frame_last);
function close_(h)
try close(h); catch; end
function tmr = read_(vidobj, viF)
h=msgbox('Loading video... (this will close automatically)'); drawnow;
tmr = vid_read(vidobj, viF);
close_(h);
function vi=trim_(vi, a, b)
vi = vi(vi>=a & vi<=b);
% --- Executes on button press in btnImport_Track.
function btnImport_Track_Callback(hObject, eventdata, handles)
% hObject handle to btnImport_Track (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-import-track', get_str_(handles.editTrialSet));
% --- Executes on button press in btnOpenSheet.
function btnOpenSheet_Callback(hObject, eventdata, handles)
% hObject handle to btnOpenSheet (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('trialset-googlesheet', get_str_(handles.editTrialSet));
% --- Executes on button press in btnSummary.
function btnSummary_Callback(hObject, eventdata, handles)
% hObject handle to btnSummary (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
csMsg = vistrack('summary', handles);
disp_cs_(csMsg);
msgbox(csMsg);
% --- Executes on button press in btnExport.
function btnExport_Callback(hObject, eventdata, handles)
% hObject handle to btnExport (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vistrack('export', handles);
%--------------------------------------------------------------------------
% display cell string
function disp_cs_(cs)
cellfun(@(s)fprintf('%s\n',s), cs);
%--------------------------------------------------------------------------
% Retreive full path of a file
function vcFile_full = fullpath_(vcFile)
[vcDir_, vcFile_, vcExt_] = fileparts(vcFile);
if isempty(vcDir_)
vcDir_ = pwd();
vcFile_full = fullfile(vcDir_, vcFile);
else
vcFile_full = vcFile;
end
if nargout>=2, S_dir = dir(vcFile_full); end
%--------------------------------------------------------------------------
% 7/20/2018 Copied from jrc3.m
% If field doesn't exist copy empty
function P = struct_merge_(P, P1, csNames)
% Merge second struct to first one
% P = struct_merge_(P, P_append)
% P = struct_merge_(P, P_append, var_list) : only update list of variable names
if isempty(P), P=P1; return; end % P can be empty
if isempty(P1), return; end
if nargin<3, csNames = fieldnames(P1); end
if ischar(csNames), csNames = {csNames}; end
for iField = 1:numel(csNames)
vcName_ = csNames{iField};
if isfield(P1, vcName_)
P.(vcName_) = P1.(vcName_);
else
P.(vcName_) = [];
end
end
%--------------------------------------------------------------------------
% 7/24/2018 JJJ: Copied from jrc3.m
function flag = exist_dir_(vcDir)
if isempty(vcDir)
flag = 0;
else
flag = exist(vcDir, 'dir') == 7;
end
%--------------------------------------------------------------------------
% 7/24/2018: Copied from jrc3.m
function flag = key_modifier_(event, vcKey)
% Check for shift, alt, ctrl press
try
flag = any(strcmpi(event.Modifier, vcKey));
catch
flag = 0;
end
%--------------------------------------------------------------------------
% 7/24/2018: Copied from jrc3.m
function out = ifeq_(if_, true_, false_)
if (if_)
out = true_;
else
out = false_;
end
%--------------------------------------------------------------------------
% 7/24/2018 JJJ: Clear persistent memories
function clear_cache_()
mov_flim_(); % clear cache;
vistrack('clear-cache');
%--------------------------------------------------------------------------
% 7/24/2018 JJJ: resize movie by a scale factor
function mov = mov_shrink_(mov, nSkip)
if nSkip==1, return; end
mov = mov(1:nSkip:end, 1:nSkip:end, :);
%--------------------------------------------------------------------------
function hTItle = title_(vc)
hTItle = title(vc, 'Interpreter', 'none');
% --- Executes on button press in btnFixSync.
function btnFixSync_Callback(hObject, eventdata, handles)
% hObject handle to btnFixSync (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = vistrack('trial-fixsync', handles);
guidata(hObject, handles);
% --- Executes on button press in btnEncounter.
function btnEncounter_Callback(hObject, eventdata, handles)
% hObject handle to btnEncounter (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
LOADSETTINGS;
XC = handles.XC;
YC = handles.YC;
csAns = inputdlg('Frames encountered (last:food)', 'Frames since tracking', 1, {'1 21 100 182'});
if isempty(csAns), return; end
viFrames_encounter = str2num(csAns{1});
% show background
hFig = figure;
img_bk = handles.img0;
mlMask = img_bk==0;
img_lim = quantile(double(img_bk(~mlMask))/255, [0, 1]);
img_bk = imadjust(img_bk, img_lim, [0 1]);
img_bk(mlMask) = 255;
imshow(img_bk); title('Posture trajectory (color: inverse time duration since last object encounter)');
% compute frames of encounter
nframes = size(XC,1);
viFrames = 1:nframes;
mrDist = bsxfun(@minus, viFrames(:)', viFrames_encounter(:));
mrDist(mrDist<0) = nan;
switch 2
case 2
nColors = 1000;
vrColor = log(1 ./ (min(mrDist) + 1));
vrColor = vrColor - min(vrColor); % rescale to 0..1
vrColor = vrColor / max(vrColor);
viColor = max(ceil(vrColor * nColors), 1);
mrColor = [zeros(1000, 2), linspace(0, 1, nColors)'];
case 1
[~, viSrt] = sort(min(mrDist), 'descend');
viColor(viSrt) = 1:numel(vrColor);
mrColor = hot(numel(vrColor));
end %switch
resize_figure(hFig, [0,0,.5,1]);
hold on;
nxy = size(XC,2);
TRAJ_STEP = 4;
for iframe=1:TRAJ_STEP:nframes
if iframe < viFrames_encounter(end)
vrColor1 = mrColor(viColor(iframe),:);
else
vrColor1 = [1 0 0];
end
XI = interp1(2:nxy, XC(iframe,2:end), 2:.1:nxy, 'spline');
YI = interp1(2:nxy, YC(iframe,2:end), 2:.1:nxy, 'spline');
plot(XI, YI, 'color', vrColor1, 'LineWidth', .5);
plot(XI(1), YI(1), '.', 'color', vrColor1, 'MarkerSize', 8);
end
% --- Executes on button press in pushbutton81.
function pushbutton81_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton81 (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 pushbutton82.
function pushbutton82_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton82 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
|
github
|
jamesjun/vistrack-master
|
vistrack.m
|
.m
|
vistrack-master/vistrack.m
| 125,344 |
utf_8
|
6eccf114256329640ec7f83ea2a3f60c
|
function varargout = vistrack(varargin)
vcCmd = 'help';
if nargin>=1, vcCmd = varargin{1}; else vcCmd = 'help'; end
if nargin>=2, vcArg1 = varargin{2}; else vcArg1 = ''; end
if nargin>=3, vcArg2 = varargin{3}; else vcArg2 = ''; end
if nargin>=4, vcArg3 = varargin{4}; else vcArg3 = ''; end
if nargin>=5, vcArg4 = varargin{5}; else vcArg4 = ''; end
if nargin>=6, vcArg5 = varargin{6}; else vcArg5 = ''; end
% Command interpreter
fReturn = 1;
switch lower(vcCmd)
case 'commit', commit_();
case 'help', help_(vcArg1);
case 'issue', issue_(vcArg1);
case 'wiki', wiki_(vcArg1);
case 'version'
if nargout>0
[varargout{1}, varargout{2}] = version_();
else
version_();
end
return;
case 'gui', GUI();
case 'edit', edit_(vcArg1);
case 'unit-test', unit_test_(vcArg1);
case 'update', update_(vcArg1);
case 'summary', varargout{1} = summary_(vcArg1);
case 'export', export_(vcArg1);
case 'videoreader', varargout{1} = VideoReader_(vcArg1);
case 'dependencies', disp_dependencies_();
case 'download-sample', download_sample_();
case 'load-cfg', varargout{1} = load_cfg_();
case 'clear-cache', clear_cache_();
case 'loadvid-preview', varargout{1} = loadvid_preview_(vcArg1, vcArg2);
case 'trial-sync', varargout{1} = trial_sync_(vcArg1);
case 'cam2adc-sync', varargout{1} = cam2adc_sync_(vcArg1, vcArg2);
case 'adc2cam-sync', varargout{1} = adc2cam_sync_(vcArg1, vcArg2);
case 'trial-visitcount', trial_timemap_(vcArg1);
case 'trial-fixsync', varargout{1} = trial_fixsync_(vcArg1);
case 'trial-save', varargout{1} = trial_save_(vcArg1);
case 'trialset-list', trialset_list_(vcArg1);
case 'trialset-learningcurve', trialset_learningcurve_(vcArg1);
case 'trialset-barplots', trialset_barplots_(vcArg1);
% case 'trialset-probe', trialset_probe_(vcArg1);
case 'trialset-exportcsv', trialset_exportcsv_(vcArg1);
case 'trialset-checkfps', trialset_checkfps_(vcArg1);
case 'trialset-coordinates', trialset_coordinates_(vcArg1);
case 'trialset-fixfps', trialset_fixfps_(vcArg1);
case 'trialset-import-track', trialset_import_track_(vcArg1);
case {'trialset-googlesheet', 'googlesheet'}, trialset_googlesheet_(vcArg1);
case 'trialset-load', trialset_load_(vcArg1);
otherwise, help_();
end %switch
if fReturn, return; end
end %func
%--------------------------------------------------------------------------
function csMsg = summary_(handles)
t_dur = diff(handles.TC([1,end]));
[mrXYh_cam, vrT_cam] = get_traj_(handles);
[pathLen_cm, XH, YH, TC1] = trial_pathlen_(handles);
% [~, dataID, ~] = fileparts(handles.vidFname);
handles.vcVer = get_set_(handles, 'vcVer', 'pre v0.1.7');
handles.vcVer_date = get_set_(handles, 'vcVer_date', 'pre 7/20/2018');
vcFile_trial = get_(handles, 'editResultFile', 'String');
[vcFile_trial, S_dir] = fullpath_(vcFile_trial);
dataID = strrep(S_dir.name, '_Track.mat', '');
nDaysAgo = floor(now() - get_(S_dir, 'datenum'));
csMsg = {...
sprintf('DataID: %s', dataID);
sprintf(' duration: %0.3f sec', t_dur);
sprintf(' path-length: %0.3f m', pathLen_cm/100);
sprintf(' ave. speed: %0.3f m/s', pathLen_cm/100/t_dur);
sprintf(' -----');
sprintf(' Output file: %s', vcFile_trial);
sprintf(' Date analyzed: %s (%d days ago)', get_(S_dir, 'date'), nDaysAgo);
sprintf(' version used: %s (%s)', handles.vcVer, handles.vcVer_date);
sprintf(' -----');
sprintf(' Video file: %s', get_(handles, 'vidFname'));
sprintf(' FPS: %0.3f', get_(handles, 'FPS'));
sprintf(' ADC file: %s', get_(handles, 'editADCfile', 'String'));
sprintf(' ADC_TS file: %s', get_(handles, 'editADCfileTs', 'String'));
};
% csMsg = [csMsg; get_(handles, 'csSettings')];
if nargout==0, disp(csMsg); end
end %func
%--------------------------------------------------------------------------
% 7/26/2018 JJJ: Copied from GUI.m
function [vcFile_full, S_dir] = fullpath_(vcFile)
[vcDir_, vcFile_, vcExt_] = fileparts(vcFile);
if isempty(vcDir_)
vcDir_ = pwd();
vcFile_full = fullfile(vcDir_, vcFile);
else
vcFile_full = vcFile;
end
if nargout>=2, S_dir = dir(vcFile_full); end
end %func
%--------------------------------------------------------------------------
function S_dir = file_dir_(vcFile_trial)
if exist_file_(vcFile_trial)
S_dir = dir(vcFile_trial);
else
S_dir = [];
end
end %func
%--------------------------------------------------------------------------
function [mrXY_head, vrT] = get_traj_(handles)
P = load_settings_(handles);
Xs = filtPos(handles.XC, P.TRAJ_NFILT, 1);
Ys = filtPos(handles.YC, P.TRAJ_NFILT, 1);
mrXY_head = [Xs(:,2), Ys(:,2)];
vrT = get_(handles, 'TC');
end %func
%--------------------------------------------------------------------------
function commit_()
S_cfg = load_cfg_();
if exist_dir_('.git'), fprintf(2, 'Cannot commit from git repository\n'); return; end
% Delete previous files
S_warning = warning();
warning('off');
delete_empty_files_();
delete([S_cfg.vcDir_commit, '*']);
warning(S_warning);
% Copy files
copyfile_(S_cfg.csFiles_commit, S_cfg.vcDir_commit, '.');
edit_('changelog.md');
end %func
%--------------------------------------------------------------------------
function delete_empty_files_(vcDir)
if nargin<1, vcDir=[]; end
delete_files_(find_empty_files_(vcDir));
end %func
%--------------------------------------------------------------------------
function csFiles = find_empty_files_(vcDir)
% find files with 0 bytes
if nargin==0, vcDir = []; end
if isempty(vcDir), vcDir = pwd(); end
vS_dir = dir(vcDir);
viFile = find([vS_dir.bytes] == 0 & ~[vS_dir.isdir]);
csFiles = {vS_dir(viFile).name};
csFiles = cellfun(@(vc)[vcDir, filesep(), vc], csFiles, 'UniformOutput', 0);
end %func
%--------------------------------------------------------------------------
function delete_files_(csFiles)
for iFile = 1:numel(csFiles)
try
if exist(csFiles{iFile}, 'file')
delete(csFiles{iFile});
fprintf('\tdeleted %s.\n', csFiles{iFile});
end
catch
disperr_();
end
end
end %func
%--------------------------------------------------------------------------
% 9/29/17 JJJ: Displaying the version number of the program and what's used. #Tested
function [vcVer, vcDate] = version_()
if nargin<1, vcFile_prm = ''; end
vcVer = 'v0.4.1';
vcDate = '08/19/2019';
if nargout==0
fprintf('%s (%s) installed\n', vcVer, vcDate);
edit_('changelog.md');
end
end %func
%--------------------------------------------------------------------------
function csHelp = help_(vcCommand)
if nargin<1, vcCommand = ''; end
if ~isempty(vcCommand), wiki_(vcCommand); return; end
csHelp = {...
'';
'Usage: vistrack command arg1 arg2 ...';
'';
'# Documentation';
' vistrack help';
' Display a help menu';
' vistrack version';
' Display the version number and the updated date';
' vistrack wiki';
' Open vistrack Wiki on GitHub';
' vistrack issue';
' Post an issue at GitHub (log-in with your GitHub account)';
'';
'# Main commands';
' vistrack edit (mysettings.prm)';
' Edit .vistrack file currently working on';
' vistrack setprm myparam.prm';
' Select a .prm file to use';
' vistrack clear';
' Clear cache';
' vistrack clear myparam.prm';
' Delete previous results (files: _jrc.mat, _spkwav.jrc, _spkraw.jrc, _spkfet.jrc)';
'';
'# Batch process';
' vistrack dir myparam.prm';
' List all recording files to be clustered together (csFile_merge)';
'';
'# Deployment';
' vistrack update';
' Update from Github';
' vistrack download-sample';
' Download a sample video from Dropbox';
' vistrack update version';
' Download specific version from Github';
' vistrack commit';
' Commit vistrack code to Github';
' vistrack unit-test';
' Run a suite of unit teste.';
'';
};
if nargout==0, disp_cs_(csHelp); end
end %func
%--------------------------------------------------------------------------
function disp_cs_(cs)
% display cell string
cellfun(@(s)fprintf('%s\n',s), cs);
end %func
%--------------------------------------------------------------------------
% 9/27/17 JJJ: Created
function issue_(vcMode)
% issue_
% issue_ post
if nargin<1, vcMode = 'search'; end
switch lower(vcMode)
case 'post', web_('https://github.com/jamesjun/vistrack/issues/new')
otherwise, web_('https://github.com/jamesjun/vistrack/issues')
end %switch
end %func
%--------------------------------------------------------------------------
% 9/27/17 JJJ: Created
function wiki_(vcPage)
if nargin<1, vcPage = ''; end
if isempty(vcPage)
web_('https://github.com/jamesjun/vistrack/wiki');
else
web_(['https://github.com/jamesjun/vistrack/wiki/', vcPage]);
end
end %func
%--------------------------------------------------------------------------
function web_(vcPage)
if isempty(vcPage), return; end
if ~ischar(vcPage), return; end
try
% use system browser
if ispc()
system(['start ', vcPage]);
elseif ismac()
system(['open ', vcPage]);
elseif isunix()
system(['gnome-open ', vcPage]);
else
web(vcPage);
end
catch
web(vcPage); % use matlab default web browser
end
end %func
%--------------------------------------------------------------------------
% 10/8/17 JJJ: Created
% 3/20/18 JJJ: captures edit failure (when running "matlab -nodesktop")
function edit_(vcFile)
% vcFile0 = vcFile;
if isempty(vcFile), vcFile = mfilename(); end
if ~exist_file_(vcFile)
fprintf(2, 'File does not exist: %s\n', vcFile);
return;
end
fprintf('Editing %s\n', vcFile);
try edit(vcFile); catch, end
end %func
%--------------------------------------------------------------------------
% 9/26/17 JJJ: Created and tested
function flag = exist_file_(vcFile, fVerbose)
if nargin<2, fVerbose = 0; end
if ~ischar(vcFile), flag = 0; return; end
if isempty(vcFile)
flag = 0;
else
flag = ~isempty(dir(vcFile));
end
if fVerbose && ~flag
fprintf(2, 'File does not exist: %s\n', vcFile);
end
end %func
%--------------------------------------------------------------------------
function nFailed = unit_test_(vcArg1, vcArg2, vcArg3)
% 2017/2/24. James Jun. built-in unit test suite (request from Karel Svoboda)
% run unit test
%[Usage]
% unit_test()
% run all
% unit_test(iTest)
% run specific test again and show profile
% unit_test('show')
% run specific test again and show profile
% @TODO: test using multiple datasets and parameters.
global fDebug_ui;
if nargin<1, vcArg1 = ''; end
if nargin<2, vcArg2 = ''; end
if nargin<3, vcArg3 = ''; end
cd(fileparts(mfilename('fullpath'))); % move to jrclust folder
% if ~exist_file_('sample.bin'), jrc3('download', 'sample'); end
nFailed = 0;
profile('clear'); %reset profile stats
csCmd = {...
'close all; clear all;', ... %start from blank
'vistrack', ...
'vistrack help', ...
'vistrack version', ...
'vistrack wiki', ...
'vistrack issue', ...
}; %last one should be the manual test
if ~isempty(vcArg1)
switch lower(vcArg1)
case {'show', 'info', 'list', 'help'}
arrayfun(@(i)fprintf('%d: %s\n', i, csCmd{i}), 1:numel(csCmd));
return;
case {'manual', 'ui', 'ui-manual'}
iTest = numel(csCmd); % + [-1,0];
case {'traces', 'ui-traces'}
iTest = numel(csCmd)-2; % second last
otherwise
iTest = str2num(vcArg1);
end
fprintf('Running test %s: %s\n', vcArg1, csCmd{iTest});
csCmd = csCmd(iTest);
end
vlPass = false(size(csCmd));
[csError, cS_prof] = deal(cell(size(csCmd)));
vrRunTime = zeros(size(csCmd));
for iCmd = 1:numel(csCmd)
eval('close all; fprintf(''\n\n'');'); %clear memory
fprintf('Test %d/%d: %s\n', iCmd, numel(csCmd), csCmd{iCmd});
t1 = tic;
profile('on');
fDebug_ui = 1;
% set0_(fDebug_ui);
try
if any(csCmd{iCmd} == '(' | csCmd{iCmd} == ';') %it's a function
evalin('base', csCmd{iCmd}); %run profiler
else % captured by profile
csCmd1 = strsplit(csCmd{iCmd}, ' ');
feval(csCmd1{:});
end
vlPass(iCmd) = 1; %passed test
catch
csError{iCmd} = lasterr();
fprintf(2, '\tTest %d/%d failed\n', iCmd, numel(csCmd));
end
vrRunTime(iCmd) = toc(t1);
cS_prof{iCmd} = profile('info');
end
nFailed = sum(~vlPass);
fprintf('Unit test summary: %d/%d failed.\n', sum(~vlPass), numel(vlPass));
for iCmd = 1:numel(csCmd)
if vlPass(iCmd)
fprintf('\tTest %d/%d (''%s'') took %0.1fs.\n', iCmd, numel(csCmd), csCmd{iCmd}, vrRunTime(iCmd));
else
fprintf(2, '\tTest %d/%d (''%s'') failed:%s\n', iCmd, numel(csCmd), csCmd{iCmd}, csError{iCmd});
end
end
if numel(cS_prof)>1
assignWorkspace_(cS_prof);
disp('To view profile, run: profview(0, cS_prof{iTest});');
else
profview(0, cS_prof{1});
end
fDebug_ui = [];
% set0_(fDebug_ui);
end %func
%--------------------------------------------------------------------------
% 9/26/17 JJJ: Output message is added
% 8/2/17 JJJ: Test and documentation
function vcMsg = assignWorkspace_(varargin)
% Assign variables to the Workspace
vcMsg = {};
for i=1:numel(varargin)
if ~isempty(varargin{i})
assignin('base', inputname(i), varargin{i});
vcMsg{end+1} = sprintf('assigned ''%s'' to workspace\n', inputname(i));
end
end
vcMsg = cell2mat(vcMsg);
if nargout==0, fprintf(vcMsg); end
end %func
%--------------------------------------------------------------------------
function update_(vcVersion)
fOverwrite = 1;
if ~exist_dir_('.git')
fprintf(2, 'Not a git repository. run "git clone https://github.com/jamesjun/vistrack"\n');
return;
end
if nargin<1, vcVersion = ''; end
S_cfg = load_cfg_();
% delete_file_(get_(S_cfg, 'csFiles_delete'));
repoURL = 'https://github.com/jamesjun/vistrack';
try
if isempty(vcVersion)
if fOverwrite
code = system('git fetch --all');
code = system('git reset --hard origin/master');
else
code = system('git pull'); % do not overwrite existing changes
end
else
code = system('git fetch --all');
code = system(sprintf('git reset --hard "%s"', vcVersion));
end
catch
code = -1;
end
if code ~= 0
fprintf(2, 'Not a git repository. Please run the following command to clone from GitHub.\n');
fprintf(2, '\tRun system(''git clone %s.git''\n', repoURL);
fprintf(2, '\tor install git from https://git-scm.com/downloads\n');
else
edit('changelog.md');
end
end %func
%--------------------------------------------------------------------------
% 11/5/17 JJJ: added vcDir_from
% 9/26/17 JJJ: multiple targeting copy file. Tested
function copyfile_(csFiles, vcDir_dest, vcDir_from)
% copyfile_(vcFile, vcDir_dest)
% copyfile_(csFiles, vcDir_dest)
% copyfile_(csFiles, csDir_dest)
if nargin<3, vcDir_from = ''; end
% Recursion if cell is used
if iscell(vcDir_dest)
csDir_dest = vcDir_dest;
for iDir = 1:numel(csDir_dest)
try
copyfile_(csFiles, csDir_dest{iDir});
catch
disperr_();
end
end
return;
end
if ischar(csFiles), csFiles = {csFiles}; end
for iFile=1:numel(csFiles)
vcPath_from_ = csFiles{iFile};
if ~isempty(vcDir_from), vcPath_from_ = fullfile(vcDir_from, vcPath_from_); end
if exist_dir_(vcPath_from_)
[vcPath_,~,~] = fileparts(vcPath_from_);
vcPath_from_ = sprintf('%s%s*', vcPath_, filesep());
vcPath_to_ = sprintf('%s%s%s', vcDir_dest, filesep(), dir_filesep_(csFiles{iFile}));
mkdir_(vcPath_to_);
% disp([vcPath_from_, '; ', vcPath_to_]);
else
vcPath_to_ = vcDir_dest;
fCreatedDir_ = mkdir_(vcPath_to_);
if fCreatedDir_
disp(['Created a folder ', vcPath_to_]);
end
end
try
vcEval1 = sprintf('copyfile ''%s'' ''%s'' f;', vcPath_from_, vcPath_to_);
eval(vcEval1);
fprintf('\tCopied ''%s'' to ''%s''\n', vcPath_from_, vcPath_to_);
catch
fprintf(2, '\tFailed to copy ''%s''\n', vcPath_from_);
end
end
end %func
%--------------------------------------------------------------------------
% 8/7/2018 JJJ
function flag = exist_dir_(vcDir)
if isempty(vcDir)
flag = 0;
else
S_dir = dir(vcDir);
if isempty(S_dir)
flag = 0;
else
flag = sum([S_dir.isdir]) > 0;
end
% flag = exist(vcDir, 'dir') == 7;
end
end %func
%--------------------------------------------------------------------------
function fCreatedDir = mkdir_(vcDir)
% make only if it doesn't exist. provide full path for dir
fCreatedDir = exist_dir_(vcDir);
if ~fCreatedDir
try
mkdir(vcDir);
catch
fCreatedDir = 0;
end
end
end %func
%--------------------------------------------------------------------------
% 17/12/5 JJJ: Error info is saved
% Display error message and the error stack
function disperr_(vcMsg, hErr)
% disperr_(vcMsg): error message for user
% disperr_(vcMsg, hErr): hErr: MException class
% disperr_(vcMsg, vcErr): vcErr: error string
try
dbstack('-completenames'); % display an error stack
if nargin<1, vcMsg = ''; end
if nargin<2, hErr = lasterror('reset'); end
if ischar(hErr) % properly formatted error
vcErr = hErr;
else
% save_err_(hErr, vcMsg); % save hErr object?
vcErr = hErr.message;
end
catch
vcErr = '';
end
if nargin==0
fprintf(2, '%s\n', vcErr);
elseif ~isempty(vcErr)
fprintf(2, '%s:\n\t%s\n', vcMsg, vcErr);
else
fprintf(2, '%s:\n', vcMsg);
end
% try gpuDevice(1); disp('GPU device reset'); catch, end
end %func
%--------------------------------------------------------------------------
function hFig = create_figure_(vcTag, vrPos, vcName, fToolbar, fMenubar)
if nargin<2, vrPos = []; end
if nargin<3, vcName = ''; end
if nargin<4, fToolbar = 0; end
if nargin<5, fMenubar = 0; end
if isempty(vcTag)
hFig = figure();
elseif ischar(vcTag)
hFig = figure_new_(vcTag);
else
hFig = vcTag;
end
set(hFig, 'Name', vcName, 'NumberTitle', 'off', 'Color', 'w');
clf(hFig);
set(hFig, 'UserData', []); %empty out the user data
if ~fToolbar
set(hFig, 'ToolBar', 'none');
else
set(hFig, 'ToolBar', 'figure');
end
if ~fMenubar
set(hFig, 'MenuBar', 'none');
else
set(hFig, 'MenuBar', 'figure');
end
if ~isempty(vrPos), resize_figure_(hFig, vrPos); end
end %func
%--------------------------------------------------------------------------
function close_(varargin)
for i=1:nargin
v_ = varargin{i};
try
if iscell(v_)
close_(v_{:});
elseif numel(v_)>1
close_(v_);
elseif numel(v_) == 1
close(v_);
end
catch
;
end
end
end %func
%--------------------------------------------------------------------------
function hFig = figure_new_(vcTag, vcTitle, vrPos)
if nargin<1, vcTag = ''; end
if nargin<2, vcTitle = ''; end
if nargin<3, vrPos = []; end
if ~isempty(vcTag)
%remove prev tag duplication
delete_multi_(findobj('Tag', vcTag, 'Type', 'Figure'));
end
hFig = figure('Tag', vcTag, 'Color', 'w', 'NumberTitle', 'off', 'Name', vcTitle);
if ~isempty(vrPos), resize_figure_(hFig, vrPos); drawnow; end
end %func
%--------------------------------------------------------------------------
function hFig = resize_figure_(hFig, posvec0, fRefocus)
if nargin<3, fRefocus = 1; end
height_taskbar = 40;
pos0 = get(groot, 'ScreenSize');
width = pos0(3);
height = pos0(4) - height_taskbar;
% width = width;
% height = height - 132; %width offset
% width = width - 32;
posvec = [0 0 0 0];
posvec(1) = max(round(posvec0(1)*width),1);
posvec(2) = max(round(posvec0(2)*height),1) + height_taskbar;
posvec(3) = min(round(posvec0(3)*width), width);
posvec(4) = min(round(posvec0(4)*height), height);
% drawnow;
if isempty(hFig)
hFig = figure; %create a figure
else
hFig = figure(hFig);
end
drawnow;
set(hFig, 'OuterPosition', posvec, 'Color', 'w', 'NumberTitle', 'off');
end %func
%--------------------------------------------------------------------------
function delete_multi_(varargin)
% provide cell or multiple arguments
for i=1:nargin
try
vr1 = varargin{i};
if numel(vr1)==1
delete(varargin{i});
elseif iscell(vr1)
for i1=1:numel(vr1)
try
delete(vr1{i1});
catch
end
end
else
for i1=1:numel(vr1)
try
delete(vr1(i1));
catch
end
end
end
catch
end
end
end %func
%--------------------------------------------------------------------------
function delete_(varargin)
for i=1:nargin()
try
v_ = varargin{i};
if iscell(v_)
delete_(v_{:});
elseif numel(v_) > 1
for i=1:numel(v_), delete_(v_(i)); end
elseif numel(v_) == 1
delete(v_);
end
catch
;
end
end
end %func
%--------------------------------------------------------------------------
% 7/19/18: Copied from jrc3.m
function val = get_set_(S, vcName, def_val)
% set a value if field does not exist (empty)
if isempty(S), S = get(0, 'UserData'); end
if isempty(S), val = def_val; return; end
if ~isstruct(S)
val = [];
fprintf(2, 'get_set_: %s must be a struct\n', inputname(1));
return;
end
val = get_(S, vcName);
if isempty(val), val = def_val; end
end %func
%--------------------------------------------------------------------------
% 7/19/18: Copied from jrc3.m
function varargout = get_(varargin)
% retrieve a field. if not exist then return empty
% [val1, val2] = get_(S, field1, field2, ...)
% val = get_(S, 'struct1', 'struct2', 'field');
if nargin==0, varargout{1} = []; return; end
S = varargin{1};
if isempty(S), varargout{1} = []; return; end
if nargout==1 && nargin > 2
varargout{1} = get_recursive_(varargin{:}); return;
end
for i=2:nargin
vcField = varargin{i};
try
varargout{i-1} = S.(vcField);
catch
varargout{i-1} = [];
end
end
end %func
%--------------------------------------------------------------------------
function out = get_recursive_(varargin)
% recursive get
out = [];
if nargin<2, return; end
S = varargin{1};
for iField = 2:nargin
try
out = S.(varargin{iField});
if iField == nargin, return; end
S = out;
catch
out = [];
end
end % for
end %func
%--------------------------------------------------------------------------
% 7/19/2018
function P = load_settings_(handles)
% P = load_settings_()
% P = load_settings_(handles)
if nargin<1, handles = []; end
P = load_cfg_();
P_ = [];
try
csSettings = get(handles.editSettings, 'String');
P_ = file2struct(csSettings);
catch
P_ = file2struct(P.vcFile_settings);
end
P = struct_merge_(P, P_);
end %func
%--------------------------------------------------------------------------
% 7/19/2018 JJJ: Copied from jrc3.m
function P = struct_merge_(P, P1, csNames)
% Merge second struct to first one
% P = struct_merge_(P, P_append)
% P = struct_merge_(P, P_append, var_list) : only update list of variable names
if isempty(P), P=P1; return; end % P can be empty
if isempty(P1), return; end
if nargin<3, csNames = fieldnames(P1); end
if ischar(csNames), csNames = {csNames}; end
for iField = 1:numel(csNames)
vcName_ = csNames{iField};
if isfield(P1, vcName_), P.(vcName_) = P1.(vcName_); end
end
end %func
%--------------------------------------------------------------------------
function [mrPath, mrDur, S_trialset, cS_trial] = trialset_learningcurve_(vcFile_trialset)
% It loads the files
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
S_trialset = load_trialset_(vcFile_trialset);
[pixpercm, angXaxis] = struct_get_(S_trialset.P, 'pixpercm', 'angXaxis');
[tiImg, vcType_uniq, vcAnimal_uniq, viImg, csFiles_Track] = ...
struct_get_(S_trialset, 'tiImg', 'vcType_uniq', 'vcAnimal_uniq', 'viImg', 'csFiles_Track');
hMsg = msgbox('Analyzing... (This closes automatically)');
[trDur, trPath, trFps] = deal(nan(size(tiImg)));
fprintf('Analyzing\n\t');
warning off;
t1 = tic;
cS_trial = {};
csField_load = setdiff(S_trialset.P.csFields, {'MOV', 'ADC','img1','img00'}); % do not load 'MOV' field since it's big and unused
for iTrial = 1:numel(viImg)
try
S_ = load(csFiles_Track{iTrial}, csField_load{:});
S_.vcFile_Track = csFiles_Track{iTrial};
iImg_ = viImg(iTrial);
cS_trial{end+1} = S_;
if ~S_trialset.vlProbe(iTrial)
trPath(iImg_) = trial_pathlen_(S_, pixpercm, angXaxis);
trDur(iImg_) = diff(S_.TC([1,end]));
end
trFps(iImg_) = get_set_(S_, 'FPS', nan);
fprintf('.');
catch
fprintf(2, '\n\tExport error: %s\n\t%s\n', csFiles_Track{iTrial}, lasterr());
end
end %for
fprintf('\n\ttook %0.1fs\n', toc(t1));
close_(hMsg);
% compact by removing nan.
% date x session x animal (trPath,trDur) -> session x date x animal (trPath_,trDur_)
[nDates, nSessions, nAnimals] = size(tiImg);
[trPath_, trDur_] = deal(nan(nSessions, nDates, nAnimals));
for iAnimal = 1:size(tiImg,3)
[mrPath1, mrDur1] = deal(trPath(:,:,iAnimal)', trDur(:,:,iAnimal)');
vi1 = find(~isnan(mrPath1));
vi2 = 1:numel(vi1);
[mrPath2, mrDur2] = deal(nan(nSessions, nDates));
[mrPath2(vi2), mrDur2(vi2)] = deal(mrPath1(vi1), mrDur1(vi1));
trPath_(:,:,iAnimal) = mrPath2;
trDur_(:,:,iAnimal) = mrDur2;
end
[trPath_, trDur_] = deal(permute(trPath_,[1,3,2]), permute(trDur_,[1,3,2])); % nSessions x nAnimals x nDate
[mrPath, mrDur] = deal(reshape(trPath_,[],nDates)/100, reshape(trDur_,[],nDates));
viCol = find(~any(isnan(mrPath)));
[mrPath, mrDur] = deal(mrPath(:,viCol), mrDur(:,viCol));
if nargout==0
% FPS integrity check
hFig = plot_trialset_img_(S_trialset, trFps);
set(hFig, 'Name', sprintf('FPS: %s', vcFile_trialset));
% Plot learning curve
figure_new_('', ['Learning curve: ', vcFile_trialset, '; Animals:', cell2mat(S_trialset.csAnimals)]);
subplot 211; errorbar_iqr_(mrPath); ylabel('Dist (m)'); grid on; xlabel('Session #');
subplot 212; errorbar_iqr_(mrDur); ylabel('Duration (s)'); grid on; xlabel('Sesision #');
end
end %func
%--------------------------------------------------------------------------
function [S_trialset, trFps] = trialset_checkfps_(vcFile_trialset)
% It loads the files
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
% fFix_sync = 0;
S_trialset = load_trialset_(vcFile_trialset);
% [pixpercm, angXaxis] = struct_get_(S_trialset.P, 'pixpercm', 'angXaxis');
[tiImg, vcType_uniq, vcAnimal_uniq, viImg, csFiles_Track] = ...
struct_get_(S_trialset, 'tiImg', 'vcType_uniq', 'vcAnimal_uniq', 'viImg', 'csFiles_Track');
warning off;
hMsg = msgbox('Analyzing... (This closes automatically)');
t1=tic;
trFps = nan(size(tiImg));
for iTrial = 1:numel(viImg)
try
S_ = load(csFiles_Track{iTrial}, 'TC', 'XC', 'YC', 'xy0', 'vidFname', 'FPS', 'img0');
if isempty(get_(S_, 'FPS')) || isempty(get_(S_, 'TC')), error('FPS or TC not found'); end
S_.vcFile_Track = csFiles_Track{iTrial};
% if fFix_sync, S_ = trial_fixsync_(S_, 0); end
iImg_ = viImg(iTrial);
trFps(iImg_) = get_set_(S_, 'FPS', nan);
fprintf('.');
catch
fprintf('\n\t%s: %s\n', csFiles_Track{iTrial}, lasterr());
end
end %for
fprintf('\n\ttook %0.1fs\n', toc(t1));
close_(hMsg);
if nargout==0
hFig = plot_trialset_img_(S_trialset, trFps);
set(hFig, 'Name', sprintf('FPS: %s', vcFile_trialset));
end
msgbox('Click to display file locations (copies to the clipboard)');
% open a FPS fix tool
end %func
%--------------------------------------------------------------------------
function mr_ = errorbar_iqr_(mr)
mr_ = quantile_mr_(mr, [.25,.5,.75]);
errorbar(1:size(mr_,1), mr_(:,2), mr_(:,2)-mr_(:,1), mr_(:,3)-mr_(:,2));
set(gca, 'XLim', [.5, size(mr_,1)+.5]);
end %func
%--------------------------------------------------------------------------
function mr1 = quantile_mr_(mr, vrQ)
mr1 = zeros(numel(vrQ), size(mr,2), 'like', mr);
for i=1:size(mr,2)
mr1(:,i) = quantile(mr(:,i), vrQ);
end
mr1 = mr1';
end %func
%--------------------------------------------------------------------------
function [pathLen_cm, XH, YH, TC1] = trial_pathlen_(S_trial, pixpercm, angXaxis)
if nargin<2
P = load_settings_();
[pixpercm, angXaxis] = deal(P.pixpercm, P.angXaxis);
end %if
[TC, XHc, YHc] = deal(S_trial.TC, S_trial.XC(:,2), S_trial.YC(:,2));
TC1 = linspace(TC(1), TC(end), numel(TC)*10);
XH = interp1(TC, XHc, TC1, 'spline');
YH = interp1(TC, YHc, TC1, 'spline');
pathLen = sum(sqrt(diff(XH).^2 + diff(YH).^2));
xyStart = trial_xyStart_(S_trial, pixpercm, angXaxis);
pathLen = pathLen + sqrt((XH(1) - xyStart(1)).^2 + (YH(1) - xyStart(2)).^2);
pathLen_cm = pathLen / pixpercm;
end %func
%--------------------------------------------------------------------------
function [xyStart, xyFood] = trial_xyStart_(S_trial, pixpercm, angXaxis)
[dataID, fishID] = trial_id_(S_trial);
switch fishID
case 'A'
xyStart = [55, 50]; xyFood = [0 -10]; angRot = 0;
case 'B'
xyStart = [50, -55]; xyFood = [-10 0]; angRot = 90;
case 'C'
xyStart = [-55, -50]; xyFood = [0 10]; angRot = 180;
case 'D'
xyStart = [-50, 55]; xyFood = [10 0]; angRot = 270;
end
iAnimal = fishID - 'A' + 1;
rotMat = rotz(angXaxis); rotMat = rotMat(1:2, 1:2);
xyStart = (xyStart * rotMat) .* [1, -1] * pixpercm + S_trial.xy0; %convert to pixel unit
xyFood = (xyFood * rotMat) .* [1, -1] * pixpercm + S_trial.xy0; %convert to pixel unit
end %func
%--------------------------------------------------------------------------
function export_(handles)
assignWorkspace_(handles);
% export heading angles to CVS file
[vcFile_cvs, mrTraj, vcMsg_cvs, csFormat] = trial2csv_(handles, [], 0);
assignWorkspace_(mrTraj);
P = load_cfg_();
csMsg = {'"handles" struct and "mrTraj" assigned to the Workspace.', vcMsg_cvs};
csMsg = [csMsg, csFormat(:)'];
msgbox_(csMsg);
end %func
%--------------------------------------------------------------------------
% 08/19/2019 JJJ: export body posture
function [vcFile_cvs, mrTraj, vcMsg, csFormat] = trial2csv_(S_trial, P, fPlot)
if nargin<2, P = []; end
if nargin<3, fPlot = 0; end
if isempty(P), P = load_settings_(); end
[vcDir_, ~, ~] = fileparts(S_trial.vidFname);
if exist_file_(get_(S_trial, 'vcFile_Track'))
vcFile_cvs = subsFileExt_(S_trial.vcFile_Track, '.csv');
elseif exist_dir_(vcDir_)
vcFile_cvs = subsFileExt_(S_trial.vidFname, '_Track.csv');
else
vcFile_Track = get_(S_trial.editResultFile, 'String');
vcFile_cvs = strrep(vcFile_Track, '.mat', '.csv');
end
vcFile_base = strrep(vcFile_cvs, '_Track.csv', ''); % base name
P1 = setfield(P, 'xy0', S_trial.xy0);
[mrTraj, mrPosture, mrAngle] = resample_trial_(S_trial, P1);
csMsg = {};
csMsg{end+1} = csvwrite_(vcFile_cvs, mrTraj, 'Trajectory');
csMsg{end+1} = csvwrite_([vcFile_base, '_posture.csv'], mrPosture, 'Postures');
csMsg{end+1} = csvwrite_([vcFile_base, '_angle.csv'], mrAngle, 'Angles');
% Export shape
if isfield(S_trial, 'mrPos_shape')
cm_per_grid = get_set_(P, 'cm_per_grid', 5);
mrPos_shape_meter = S_trial.mrPos_shape;
mrPos_shape_meter(:,1:2) = mrPos_shape_meter(:,1:2) * cm_per_grid / 100;
csMsg{end+1} = csvwrite_([vcFile_base, '_shapes.csv'], mrPos_shape_meter, 'Shapes');
mrRelations = calc_relations_(mrTraj, mrPos_shape_meter, P1);
csMsg{end+1} = csvwrite_([vcFile_base, '_relations.csv'], mrRelations, 'Relations');
else
fprintf(2, '%s: Shape positions field does not exist.\n', vcFile_cvs);
end
vcMsg = cell2mat(cellfun(@(x)sprintf('%s\n', x), csMsg, 'UniformOutput', 0));
csShapes = get_(P, 'csShapes');
csFormat = {...
'_Track.csv files:',
' Columns: T(s), X(m), Y(m), A(deg), R(Hz), D(m), V(m/s), S(m):',
' T: camera frame time',
' X: x coordinate of the head tip @ grid frame of reference',
' Y: y coordinate of the head tip @ grid frame of reference',
' A: head orientation',
' R: EOD rate',
' D: Distance per EOD pulse (=1/sampling_density)',
' V: Head speed (m/s, signed)',
' S: Distance per Escan (=1/escan_density)',
'_shapes.csv files:',
' Columns: X(m), Y(m), A(deg):',
' X(m): x coordinate of the shape center @ grid frame of reference',
' Y(m): y coordinate of the shape center @ grid frame of reference',
' A(deg): Shape orientation',
'_posture.csv files: (stores five points along the body (head to tail)',
' Columns: x1(m), y1(m), x2(m), y2(m), x3(m), y3(m), x4(m), y4(m), x5(m), y5(m)',
' x1(m): x coordinate of the head tip @ grid frame of reference',
' y1(m): y coordinate of the head tip @ grid frame of reference',
' x2(m): x coordinate of the head-mid section @ grid frame of reference',
' x3(m): x coordinate of the mid section @ grid frame of reference',
' x4(m): x coordinate of the mid-tail section @ grid frame of reference',
' x5(m): x coordinate of the tail tip @ grid frame of reference',
'_angles.csv files:',
' Columns: a_hm(deg), a_tm(deg), a_bb(deg), a_tb(deg)',
' a_hm(deg): head-mid section orientation (head half of the fish)',
' a_tm(deg): tail-mid section orientation (tail half of the fish)',
' a_bb(deg): body bend angle',
' a_tb(deg): tail bend angle',
sprintf(' Rows: %s', sprintf('"%s", ', csShapes{:})),
'_relations.csv files:',
sprintf(' Columns: T(s), D_F(m), A_E(deg), %s', sprintf('L_"%s"(bool), ', csShapes{:})),
' T: camera frame time',
' D_F: distance to the food',
' A_E: heading angle error (food_vec - head_vec, 0..90 deg)',
' L_"x": Is shape "x" adjacent to the head position? 0:no, 1:yes'};
if fPlot
hFig = figure_new_('', vcFile_cvs);
imshow(S_trial.img0); hold on;
resize_figure_(hFig, [0,0,.5,1]);
plot_chevron_(S_trial.XC(:,2:3), S_trial.YC(:,2:3));
end
if nargout==0
fprintf('%s', vcMsg);
disp_cs_(csFormat);
end
end %func
%--------------------------------------------------------------------------
function vcMsg = csvwrite_(vcFile, mr, var_name)
if nargin<3, var_name = ''; end
if isempty(var_name), var_name = inputname(2); end
if isempty(mr)
fprintf(2, 'csvwrite_: Empty matrix, not written.\n');
vcMsg = '';
return;
end
csvwrite(vcFile, mr);
vcMsg = sprintf('%s exported to %s', var_name, vcFile);
if nargout==0, fprintf('%s\n', vcMsg); end
end %func
%--------------------------------------------------------------------------
function [mrTXYARDVS_rs, mrPosture_rs, mrAngle_rs] = resample_trial_(S_trial, P)
% Output
% -----
% mrTXYARDV_rs:
% Time(s), X-pos(m), Y-pos(m), Angle(deg), Sampling Rate(Hz),
% Dist/pulse(m), Velocity(m/s), Dist/E-Scan (m)
% smooth the trajectory
% if fFilter
P1 = setfield(P, 'xy0', S_trial.xy0);
fh_filt = @(x)filtPos(x, P.TRAJ_NFILT, 1);
sRateHz_rs = get_set_(P, 'sRateHz_resample', 100);
vrT = S_trial.TC(:);
vrT_rs = (vrT(1):1/sRateHz_rs:vrT(end))';
fh_interp = @(x)interp1(vrT, x, vrT_rs);
fh_interp_deg = @(x)mod(interp1(vrT, unwrap(x-180,180), vrT_rs)+180, 360); % input 0..360
fh_conv = @(x)fh_interp(pix2cm_(fh_filt(x), P1) / 100);
fh_conv_deg = @(x)fh_interp_deg(pix2cm_deg_(x, P1));
switch 2
case 2 %new method, should be the same result
mrXY_m_2_rs = fh_conv([S_trial.XC(:,2), S_trial.YC(:,2)]);
mrXY_m_3_rs = fh_conv([S_trial.XC(:,3), S_trial.YC(:,3)]);
vrA_rs = fh_conv_deg(S_trial.AC(:,2));
case 1
mrXY_pix_2 = [fh_filt(S_trial.XC(:,2)), fh_filt(S_trial.YC(:,2))];
mrXY_pix_3 = [fh_filt(S_trial.XC(:,3)), fh_filt(S_trial.YC(:,3))];
mrXY_m_2_rs = fh_interp(pix2cm_(mrXY_pix_2, P1) / 100);
mrXY_m_3_rs = fh_interp(pix2cm_(mrXY_pix_3, P1) / 100);
vrA_rs = fh_interp_deg(pix2cm_deg_(S_trial.AC(:,2), P1));
end %switch
if nargout>=2
try
cXY_cam = arrayfun(@(i)[S_trial.XC(:,i), S_trial.YC(:,i)], 2:6, 'UniformOutput',0);
mrPosture_rs = cell2mat(cellfun(@(x)fh_conv(x), cXY_cam, 'UniformOutput', 0));
catch
mrPosture_rs = [];
end
end
if nargout>=3
try
mrAngle_rs = fh_conv_deg(S_trial.AC(:,2:end));
catch
mrAngle_rs = [];
end
end
% add EOD and sampling density
[vtEodr, vrEodr] = getEodr_adc_(S_trial, P);
vrR_rs = interp1(vtEodr, vrEodr, vrT_rs);
% Compute velocity
mrXY_23_rs = mrXY_m_2_rs - mrXY_m_3_rs;
[VX, VY] = deal(diff3_(mrXY_m_2_rs(:,1)), diff3_(mrXY_m_2_rs(:,2)));
vrV_rs = hypot(VX, VY) .* sign(mrXY_23_rs(:,1).*VX + mrXY_23_rs(:,2).*VY) * sRateHz_rs;
% Count sampling density
vrLr = cumsum(hypot(VX, VY));
vtEodr_ = vtEodr(vtEodr>=vrT_rs(1) & vtEodr <= vrT_rs(end));
vrD = diff3_(interp1(vrT_rs, vrLr, vtEodr_, 'spline')); % distance between EOD
vrD_rs = interp1(vtEodr_, vrD, vrT_rs);
vrD_rs(isnan(vrD_rs)) = 0;
% calc ESCAN rate
viDs = findDIsac(diff3_(diff3_(vtEodr)));
vtEscan = vtEodr(viDs);
vrDs = diff3_(interp1(vrT_rs, vrLr, vtEscan, 'spline')); % distance between EOD
vrS_rs = interp1(vtEscan, vrDs, vrT_rs, 'spline');
vrS_rs(isnan(vrS_rs)) = 0;
% get EOD timestamps
mrTXYARDVS_rs = [vrT_rs, mrXY_m_2_rs, vrA_rs(:), vrR_rs(:), vrD_rs(:), vrV_rs(:), vrS_rs(:)];
% figure; quiver(mrXY_m_2_rs(:,1),mrXY_m_2_rs(:,2), VX, VY, 2, 'r.')
end %func
%--------------------------------------------------------------------------
function data = diff3_(data, dt) % three point diff
%data = differentiate5(data, dt)
%data: timeseries to differentiate
%dt: time step (default of 1)
% http://en.wikipedia.org/wiki/Numerical_differentiation
dimm = size(data);
data=data(:)';
data = filter([1 0 -1], 2, data);
data = data(3:end);
data = [data(1), data, data(end)];
if nargin > 1
data = data / dt;
end
if dimm(1) == 1 %row vector
data=data(:)';
else
data=data(:); %col vector
end
end %func
%--------------------------------------------------------------------------
function mrRelations = calc_relations_(mrTraj, mrPos_shape_meter, P)
if nargin<3, P = []; end
if isempty(P), P = load_settings_(); end
[T, mrXY_h, A_H] = deal(mrTraj(:,1), mrTraj(:,2:3), mrTraj(:,4));
vrXY_food = mrPos_shape_meter(end,1:2);
mrV_F = bsxfun(@minus, vrXY_food, mrXY_h);
[A_F, D_F] = cart2pol_(mrV_F(:,1), mrV_F(:,2));
% A_E = min(mod(A_F-A_H, 180), mod(A_H-A_F, 180));
A_E = mod(A_F-A_H+90, 180) - 90;
% determine shape mask
dist_cut = get_set_(P, 'dist_cm_shapes', 3) / 100; % in meters
nShapes = size(mrPos_shape_meter,1);
mlL_shapes = false(numel(T), nShapes);
for iShape = 1:nShapes
vcShape = strtok(P.csShapes{iShape}, ' ');
xya_ = mrPos_shape_meter(iShape,:);
len_ = P.vrShapes(iShape)/100;
[mrXY_poly_, fCircle] = get_polygon_(vcShape, xya_(1:2), len_, xya_(3));
if fCircle
vrD_ = hypot(xya_(1)-mrXY_h(:,1), xya_(2)-mrXY_h(:,2)) - len_/2;
else %polygon
vrD_ = nearest_perimeter_(mrXY_poly_/100, mrXY_h); % convert to meter
end
mlL_shapes(:,iShape) = vrD_ <= dist_cut;
end
mrRelations = [T, D_F, A_E, mlL_shapes];
end %func
%--------------------------------------------------------------------------
function vrD_ = nearest_perimeter_(mrXY_p, mrXY_h)
% mrXY_p: polygon vertices
nInterp = 100;
mrXY_ = [mrXY_p; mrXY_p(1,:)]; % wrap
mrXY_int = interp1(1:size(mrXY_,1), mrXY_, 1:1/nInterp:size(mrXY_,1));
vrD_ = min(pdist2(mrXY_int, mrXY_h))';
if nargout==0
figure; hold on;
plot(mrXY_int(:,1), mrXY_int(:,2), 'b.-');
plot(mrXY_h(:,1), mrXY_h(:,2), 'r.-');
end
end %func
%--------------------------------------------------------------------------
function [th_deg, r] = cart2pol_(x,y)
% th: degrees
th_deg = atan2(y,x).*(180/pi);
r = hypot(x,y);
end %func
%--------------------------------------------------------------------------
function mrA1 = pix2cm_deg_(mrA, P1)
angXaxis = get_set_(P1, 'angXaxis', 0);
mrA1 = mod(-mrA - angXaxis,360);
end
%--------------------------------------------------------------------------
function plot_chevron_(mrX, mrY)
nFrames = size(mrX,1);
hold on;
for iFrame=1:nFrames
plotChevron(mrX(iFrame,:), mrY(iFrame,:), [], 90, .3);
end
end %func
%--------------------------------------------------------------------------
% 8/2/17 JJJ: added '.' if dir is empty
% 7/31/17 JJJ: Substitute file extension
function varargout = subsFileExt_(vcFile, varargin)
% Substitute the extension part of the file
% [out1, out2, ..] = subsFileExt_(filename, ext1, ext2, ...)
[vcDir_, vcFile_, ~] = fileparts(vcFile);
if isempty(vcDir_), vcDir_ = '.'; end
for i=1:numel(varargin)
vcExt_ = varargin{i};
varargout{i} = [vcDir_, filesep(), vcFile_, vcExt_];
end
end %func
%--------------------------------------------------------------------------
% 7/20/2018 JJJ: list trialset files
function trialset_list_(vcFile_trialset)
S_trialset = load_trialset_(vcFile_trialset);
if isempty(S_trialset)
errordlg(sprintf('%s does not exist', vcFile_trialset)); return;
end
if ~exist_dir_(get_(S_trialset, 'vcDir'))
errordlg(sprintf('vcDir=''%s''; does not exist', vcFile_trialset), vcFile_trialset);
return;
end
% S_trialset = load_trialset_(vcFile_trialset);
csFiles_Track = get_(S_trialset, 'csFiles_Track');
if isempty(csFiles_Track)
errordlg(sprintf('No _Track.mat files are found in "%s".', vcFile_trialset), vcFile_trialset);
return;
end
[tiImg, vcType_uniq, vcAnimal_uniq, csDir_trial, csFiles_Track] = ...
struct_get_(S_trialset, 'tiImg', 'vcType_uniq', 'vcAnimal_uniq', 'csDir_trial', 'csFiles_Track');
% output
msgbox(S_trialset.csMsg, file_part_(vcFile_trialset));
disp_cs_(S_trialset.csMsg);
disp_cs_(S_trialset.csMsg2);
hFig = plot_trialset_img_(S_trialset, tiImg);
set(hFig, 'Name', sprintf('Integrity check: %s', vcFile_trialset));
end %func
%--------------------------------------------------------------------------
function [hFig, vhImg] = plot_trialset_img_(S_trialset, tiImg, clim)
% make a click callback and show video location
if nargin<2, tiImg = S_trialset.tiImg; end
if nargin<3, clim = [min(tiImg(:)), max(tiImg(:))]; end
vhImg = zeros(size(tiImg,3), 1);
hFig = figure_new_('FigOverview', S_trialset.vcFile_trialset, [.5,0,.5,1]);
set0_(S_trialset);
% set0_(S_trialset);
% vhAx = zeros(size(tiImg,3), 1);
for iAnimal = 1:size(tiImg,3)
hAx_ = subplot(1,size(tiImg,3),iAnimal);
hImg_ = imagesc_(tiImg(:,:,iAnimal), clim);
vhImg(iAnimal) = hImg_;
ylabel('Dates'); xlabel('Trials');
title(sprintf('Animal %s', S_trialset.vcAnimal_uniq(iAnimal)));
% hAx_.UserData = [];
hImg_.ButtonDownFcn = @(h,e)button_FigOverview_(h,e,iAnimal);
end %for
end %func
%--------------------------------------------------------------------------
function button_FigOverview_(hImg, event, iAnimal)
% S_axes = get(hAxes, 'UserData');
xy = get(hImg.Parent, 'CurrentPoint');
xy = round(xy(1,1:2));
[iSession, iTrial, cAnimal] = deal(xy(2), xy(1), 'A' + iAnimal - 1);
fprintf('Session:%d, Trial:%d, Animal:%c\n', iSession, iTrial, cAnimal);
S_trialset = get0_('S_trialset');
vcVidExt = get_set_(S_trialset.P, 'vcVidExt', '.wmv');
% vcFormat = sprintf('*%02d%c%d.%s$', iSession, cAnimal, iTrial, vcVidExt)
vcFormat = sprintf('%02d%c%d(\\w*)_Track.mat', iSession, cAnimal, iTrial);
cs = cellfun(@(x)regexpi(x, vcFormat, 'match'), S_trialset.csFiles_Track, 'UniformOutput', 0);
iFind = find(~cellfun(@isempty, cs));
if ~isempty(iFind)
vcFile_Track = S_trialset.csFiles_Track{iFind};
vcFile_vid = strrep(vcFile_Track, '_Track.mat', vcVidExt);
switch event.Button
case 1
clipboard('copy', vcFile_Track);
fprintf('\t%s (copied)\n\t%s\n', vcFile_Track, vcFile_vid);
case 3
clipboard('copy', vcFile_vid);
fprintf('\t%s\n\t%s (copied)\n', vcFile_Track, vcFile_vid);
end
end
end %func
%--------------------------------------------------------------------------
function varargout = struct_get_(varargin)
% deal struct elements
if nargin==0, varargout{1} = []; return; end
S = varargin{1};
if isempty(S), varargout{1} = []; return; end
for i=2:nargin
vcField = varargin{i};
try
varargout{i-1} = S.(vcField);
catch
varargout{i-1} = [];
end
end
end %func
%--------------------------------------------------------------------------
function [S_trialset, cS_trial] = load_trialset_(vcFile_trialset)
% Usage
% -----
% load_trialset_(myfile.trialset)
% load_trialset_(myfile_trialset.mat)
%
% return [] if vcFile_trialset does not exist
P = load_settings_();
if ~exist_file_(vcFile_trialset), S_trialset.P=P; return; end
if matchFileEnd_(vcFile_trialset, '_trialset.mat')
vcFile_trialset_mat_ = vcFile_trialset;
vcFile_trialset = strrep(vcFile_trialset, '_trialset.mat', '.trialset');
cS_trial = load_mat_(vcFile_trialset, 'cS_trial');
else
S_trialset = file2struct(vcFile_trialset);
[csFiles_Track, csDir_trial] = find_files_(S_trialset.vcDir, '*_Track.mat');
if isempty(csFiles_Track), S_trialset.P=P; return; end
cS_trial = [];
end
[csDataID, S_trialset_, csFiles_Track] = get_dataid_(csFiles_Track, get_(S_trialset, 'csAnimals'));
S_trialset = struct_merge_(S_trialset, S_trialset_);
[vcAnimal_uniq, vnAnimal_uniq] = unique_(S_trialset.vcAnimal);
[viDate_uniq, vnDate_uniq] = unique_(S_trialset.viDate);
[vcType_uniq, vnType_uniq] = unique_(S_trialset.vcType);
[viTrial_uniq, vnTrial_uniq] = unique_(S_trialset.viTrial);
fh1_ = @(x,y,z)cell2mat(arrayfun(@(a,b)sprintf(z,a,b),x,y,'UniformOutput',0));
fh2_ = @(cs_)cell2mat(cellfun(@(vc_)sprintf(' %s\n',vc_),cs_,'UniformOutput',0));
csMsg = { ...
sprintf('Trial types(#trials): %s\n', fh1_(vcType_uniq, vnType_uniq, '%c(%d), '));
sprintf('Animals(#trials): %s\n', fh1_(vcAnimal_uniq, vnAnimal_uniq, '%c(%d), '));
sprintf('Dates(#trials):\n %s\n', fh1_(viDate_uniq, vnDate_uniq, '%d(%d), '));
sprintf('# Probe trials: %d', sum(S_trialset.vlProbe));
sprintf('%s', fh2_(csFiles_Track(S_trialset.vlProbe)));
sprintf('Figure color scheme: blue:no data, green:analyzed, yellow:probe trial');
sprintf('See the console output for further details');
};
% image output
tiImg = zeros(max(viDate_uniq), max(viTrial_uniq), numel(vcAnimal_uniq));
viDate = S_trialset.viDate;
viAnimal = S_trialset.vcAnimal - min(S_trialset.vcAnimal) + 1;
viTrial = S_trialset.viTrial;
viImg = sub2ind(size(tiImg), viDate, viTrial, viAnimal);
tiImg(viImg) = 1;
tiImg(viImg(S_trialset.vlProbe)) = 2;
% find missing trials
[viDate_missing, viTrial_missing, viAnimal_missing] = ind2sub(size(tiImg), find(tiImg==0));
csDataID_missing = arrayfun(@(a,b,c)sprintf('%c%02d%c%d',vcType_uniq(1),a,b,c), ...
viDate_missing, toVec_(vcAnimal_uniq(viAnimal_missing)), viTrial_missing, ...
'UniformOutput', 0);
fh3_ = @(cs)(cell2mat(cellfun(@(x)sprintf(' %s\n',x),cs, 'UniformOutput', 0)));
fh4_ = @(cs)(cell2mat(cellfun(@(x)sprintf('%s ',x),cs, 'UniformOutput', 0)));
% secondary message
csMsg2 = { ...
sprintf('\n[Folders]');
fh3_(csDir_trial);
sprintf('[Files]');
fh3_(csFiles_Track);
sprintf('[Probe trials]');
fh2_(csFiles_Track(S_trialset.vlProbe));
sprintf('[Missing trials (%d)]', numel(csDataID_missing));
[' ', fh4_(sort(csDataID_missing'))]
};
S_trialset = struct_add_(S_trialset, P, vcFile_trialset, ...
csFiles_Track, csDir_trial, csMsg, csMsg2, ...
tiImg, viDate, viTrial, viAnimal, viImg, ...
vcAnimal_uniq, viDate_uniq, vcType_uniq, viTrial_uniq);
end %func
%--------------------------------------------------------------------------
function vr = toVec_(vr)
vr = vr(:);
end %func
%--------------------------------------------------------------------------
function vr = toRow_(vr)
vr = vr(:)';
end %func
%--------------------------------------------------------------------------
function S = struct_add_(S, varargin)
for i=1:numel(varargin)
S.(inputname(i+1)) = varargin{i};
end
end %func
%--------------------------------------------------------------------------
function hImg = imagesc_(mr, clim)
if nargin<2, clim = []; end
if isempty(clim)
hImg = imagesc(mr, 'xdata', 1:size(mr,2), 'ydata', 1:size(mr,1));
else
hImg = imagesc(mr, 'xdata', 1:size(mr,2), 'ydata', 1:size(mr,1), clim);
end
set(gca,'XTick', 1:size(mr,2));
set(gca,'YTick', 1:size(mr,1));
axis([.5, size(mr,2)+.5, .5, size(mr,1)+.5]);
grid on;
end %func
%--------------------------------------------------------------------------
function vc = file_part_(vc)
[~,a,b] = fileparts(vc);
vc = [a, b];
end %func
%--------------------------------------------------------------------------
function [vi_uniq, vn_uniq] = unique_(vi)
[vi_uniq, ~, vi_] = unique(vi);
vn_uniq = hist(vi_, 1:numel(vi_uniq));
end %func
%--------------------------------------------------------------------------
function [csDataID, S, csFiles] = get_dataid_(csFiles, csAnimals)
if nargin<2, csAnimals = {}; end
csDataID = cell(size(csFiles));
[viDate, viTrial] = deal(zeros(size(csFiles)));
vlProbe = false(size(csFiles));
[vcType, vcAnimal] = deal(repmat(' ', size(csFiles)));
for iFile=1:numel(csFiles)
[~, vcFile_, ~] = fileparts(csFiles{iFile});
vcDateID_ = strrep(vcFile_, '_Track', '');
csDataID{iFile} = vcDateID_;
vcType(iFile) = vcDateID_(1);
vcAnimal(iFile) = vcDateID_(4);
viDate(iFile) = str2num(vcDateID_(2:3));
viTrial(iFile) = str2num(vcDateID_(5));
vlProbe(iFile) = numel(vcDateID_) > 5;
end %for
% Filter by animals
if ~isempty(csAnimals)
vcAnimal_plot = cell2mat(csAnimals);
viKeep = find(ismember(vcAnimal, vcAnimal_plot));
[vcType, viDate, vcAnimal, viTrial, vlProbe, csFiles] = ...
deal(vcType(viKeep), viDate(viKeep), vcAnimal(viKeep), viTrial(viKeep), vlProbe(viKeep), csFiles(viKeep));
end
S = makeStruct_(vcType, viDate, vcAnimal, viTrial, vlProbe, csFiles);
end %func
%--------------------------------------------------------------------------
% 7/20/18: Copied from jrc3.m
function S = makeStruct_(varargin)
%MAKESTRUCT all the inputs must be a variable.
%don't pass function of variables. ie: abs(X)
%instead create a var AbsX an dpass that name
S = struct();
for i=1:nargin, S.(inputname(i)) = varargin{i}; end
end %func
%--------------------------------------------------------------------------
function [csFiles, csDir] = find_files_(csDir, vcFile)
% consider using (dir('**/*.mat') for example instead of finddir
if ischar(csDir)
if any(csDir=='*')
csDir = find_dir_(csDir);
else
csDir = {csDir};
end
end
csFiles = {};
for iDir=1:numel(csDir)
vcDir_ = csDir{iDir};
S_dir_ = dir(fullfile(vcDir_, vcFile));
csFiles_ = cellfun(@(x)fullfile(vcDir_, x), {S_dir_.name}, 'UniformOutput', 0);
csFiles = [csFiles, csFiles_];
end %for
end %func
%--------------------------------------------------------------------------
function csDir = find_dir_(vcDir)
% accepts if vcDir contains a wildcard
if ~any(vcDir=='*'), csDir = {vcDir}; return; end
[vcDir_, vcFile_, vcExt_] = fileparts(vcDir);
if ~isempty(vcExt_), csDir = {vcDir_}; return ;end
S_dir = dir(vcDir);
csDir = {S_dir.name};
csDir_ = csDir([S_dir.isdir]);
csDir = cellfun(@(x)fullfile(vcDir_, x), csDir_, 'UniformOutput', 0);
end %func
%--------------------------------------------------------------------------
function vidobj = VideoReader_(vcFile_vid, nRetry)
if nargin<2, nRetry = []; end
if isempty(nRetry), nRetry = 3; end % number of frames can change
nThreads = 1; % disable parfor by setting it to 1. Parfor is slower
fprintf('Opening Video: %s\n', vcFile_vid); t1=tic;
cVidObj = cell(nRetry,1);
fParfor = is_parfor_(nThreads);
if fParfor
try
parfor iRetry = 1:nRetry
[cVidObj{iRetry}, vnFrames(iRetry)] = load_vid_(vcFile_vid);
fprintf('\t#%d: %d frames\n', iRetry, vnFrames(iRetry));
end %for
catch
fParfor = 0;
end
end
if ~fParfor
for iRetry = 1:nRetry
[cVidObj{iRetry}, vnFrames(iRetry)] = load_vid_(vcFile_vid);
fprintf('\t#%d: %d frames\n', iRetry, vnFrames(iRetry));
end %for
end
[NumberOfFrames, iMax] = max(vnFrames);
vidobj = cVidObj{iMax};
fprintf('\ttook %0.1fs\n', toc(t1));
end %func
%--------------------------------------------------------------------------
function [vidobj, nFrames] = load_vid_(vcFile_vid);
try
vidobj = VideoReader(vcFile_vid);
nFrames = vidobj.NumberOfFrames;
catch
vidobj = [];
nFrames = 0;
end
end %func
%--------------------------------------------------------------------------
function fParfor = is_parfor_(nThreads)
if nargin<1, nThreads = []; end
if nThreads == 1
fParfor = 0;
else
fParfor = license('test', 'Distrib_Computing_Toolbox');
end
end %func
%--------------------------------------------------------------------------
% 11/5/17 JJJ: Created
function vc = dir_filesep_(vc)
% replace the file seperaation characters
if isempty(vc), return; end
vl = vc == '\' | vc == '/';
if any(vl), vc(vl) = filesep(); end
end %func
%--------------------------------------------------------------------------
function trialset_barplots_(vcFile_trialset)
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
% [mrPath, mrDur, S_trialset, cS_trial] = trialset_learningcurve_(vcFile_trialset);
[cS_trial, S_trialset, mrPath, mrDur] = loadShapes_trialset_(vcFile_trialset);
viEarly = get_(S_trialset, 'viEarly_trial');
viLate = get_(S_trialset, 'viLate_trial');
if isempty(viEarly) || isempty(viLate)
msgbox('Set "viEarly_trial" and "viLate_trial" in .trialset file');
return;
end
[vrPath_early, vrPath_late] = deal(mrPath(:,viEarly), mrPath(:,viLate));
[vrDur_early, vrDur_late] = deal(mrDur(:,viEarly), mrDur(:,viLate));
[vrSpeed_early, vrSpeed_late] = deal(vrPath_early./vrDur_early, vrPath_late./vrDur_late);
quantLim = get_set_(S_trialset, 'quantLim', [1/8, 7/8]);
[vrPath_early, vrPath_late, vrDur_early, vrDur_late, vrSpeed_early, vrSpeed_late] = ...
trim_quantile_(vrPath_early, vrPath_late, vrDur_early, vrDur_late, vrSpeed_early, vrSpeed_late, quantLim);
vcAnimal_use = cell2mat(S_trialset.csAnimals);
figure_new_('', ['Early vs Late: ', vcFile_trialset, '; Animals: ', vcAnimal_use]);
subplot 131;
bar_mean_sd_({vrPath_early, vrPath_late}, {'Early', 'Late'}, 'Pathlen (m)');
subplot 132;
bar_mean_sd_({vrDur_early, vrDur_late}, {'Early', 'Late'}, 'Duration (s)');
subplot 133;
bar_mean_sd_({vrSpeed_early, vrSpeed_late}, {'Early', 'Late'}, 'Speed (m/s)');
msgbox(sprintf('Early Sessions: %s\nLate Sessions: %s', sprintf('%d ', viEarly), sprintf('%d ', viLate)));
% Plot probe trials
S_shape = pool_probe_trialset_(S_trialset, cS_trial);
vcFigName = sprintf('%s; Animals: %s; Probe trials', S_trialset.vcFile_trialset, cell2mat(S_trialset.csAnimals));
hFig = figure_new_('', vcFigName, [0 .5 .5 .5]);
viShapes = 1:6;
subplot 241; bar(1./S_shape.mrDRVS_shape(1,viShapes)); ylabel('Sampling density'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 242; bar(S_shape.mrDRVS_shape(2,viShapes)); ylabel('Sampling Rate (Hz)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 243; bar(S_shape.mrDRVS_shape(3,viShapes)); ylabel('Speed (m/s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 244; bar(1./S_shape.mrDRVS_shape(4,viShapes)); ylabel('EScan density'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 245; bar(S_shape.vnVisit_shape(viShapes)); ylabel('# visits'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 246; bar(S_shape.vtVisit_shape(viShapes)); ylabel('t visit (s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 247; bar(S_shape.vtVisit_shape(viShapes) ./ S_shape.vnVisit_shape(viShapes)); ylabel('t per visit (s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 248; bar(S_shape.vpBackward_shape(viShapes)); ylabel('Backward swim prob.'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
xtickangle(hFig.Children, -30);
% xtickangle(S_fig.hAx, -20);
end %func
%--------------------------------------------------------------------------
function S_shape = pool_probe_trialset_(S_trialset, cS_trial)
cS_probe = cS_trial(S_trialset.vlProbe);
cS_shape = cell(size(cS_probe));
for i=1:numel(cS_shape)
cS_shape{i} = nearShapes_trial_(cS_probe{i}, S_trialset.P);
end
vS_shape = cell2mat(cS_shape)';
% fh_pool = @(vc)cell2mat({vS_shape.(vc)}');
% csName = fieldnames(vS_shape(1));
% csName = setdiff(csName, 'csDist_shape');
csName = {'mlDist_shape', 'vrD', 'vrR', 'vrS', 'vrV'};
S_shape = struct();
for i=1:numel(csName)
eval(sprintf('S_shape.%s=cell2mat({vS_shape.%s}'');', csName{i}, csName{i}));
end
S_shape.csDist_shape = vS_shape(1).csDist_shape;
S_shape = S_shape_calc_(S_shape, S_trialset.P);
end %func
%--------------------------------------------------------------------------
function trialset_coordinates_(vcFile_trialset)
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
% errordlg('Not implemented yet.'); return;
[cS_trial, S_trialset] = loadShapes_trialset_(vcFile_trialset);
P = get_set_(S_trialset, 'P', load_cfg_());
% show chart
tnShapes = countShapes_trialset_(S_trialset, cS_trial);
[hFig_overview, vhImg_overview] = plot_trialset_img_(S_trialset, single(tnShapes), [0, numel(P.csShapes)]);
set(hFig_overview, 'Name', sprintf('# Shapes: %s', vcFile_trialset));
% create a table. make it navigatable
nFiles = numel(cS_trial);
hFig_tbl = figure_new_('FigShape', ['Shape locations: ', vcFile_trialset], [0,0,.5,1]);
iTrial = 1;
hFig_tbl.UserData = makeStruct_(S_trialset, P, iTrial, tnShapes, vhImg_overview);
set0_(cS_trial);
hFig_tbl.KeyPressFcn = @(h,e)keypress_FigShape_(h,e);
plotShapes_trial_(hFig_tbl, iTrial);
% uiwait(msgbox('Right-click on the shapes and food to fill the table. Press "OK" when finished.'));
msgbox('Right-click on the shapes and food to fill the table. Close the figure when finished.');
uiwait(hFig_tbl);
% save
% if ~isvalid(hFig_tbl), msgbox('Table is closed by user, nothing is saved.'); return; end
if ~questdlg_('Save the coordinates?'), return; end
hMsgbox = msgbox('Saving... (This closes automatically)');
vcFile_mat = strrep(vcFile_trialset, '.trialset', '_trialset.mat');
save_var_(vcFile_mat, 'cS_trial', get0_('cS_trial'));
close_(hFig_tbl, hFig_overview, hMsgbox);
msgbox_(['Shape info saved to ', vcFile_mat]);
end %func
%--------------------------------------------------------------------------
% 08/12/18 JJJ: Get yes or no answer from the user
function flag = questdlg_(vcTitle, flag)
% flag: default is yes (1) or no (0)
if nargin<2, flag = 1; end
if flag
flag = strcmpi(questdlg(vcTitle,'','Yes','No','Yes'), 'Yes');
else
flag = strcmpi(questdlg(vcTitle,'','Yes','No','No'), 'Yes');
end
end %func
%--------------------------------------------------------------------------
function save_var_(vcFile_mat, vcName, val)
fAppend = exist_file_(vcFile_mat);
eval(sprintf('%s=val;', vcName));
if fAppend
try
save(vcFile_mat, vcName, '-v7.3', '-append', '-nocompression'); %faster
catch
save(vcFile_mat, vcName, '-v7.3', '-append'); % backward compatible
end
else
try
save(vcFile_mat, vcName, '-v7.3', '-nocompression'); %faster
catch
save(vcFile_mat, vcName, '-v7.3'); % backward compatible
end
end
end %func
%--------------------------------------------------------------------------
function plotTraj_trial_(hFig_tbl, iTrial)
S_fig = hFig_tbl.UserData;
delete_(get_(S_fig, 'hTraj'));
hTraj = plot(S_fig);
hFig_tbl.UserData = struct_add_(S_fig, hTraj);
end %func
%--------------------------------------------------------------------------
function plotShapes_trial_(hFig_tbl, iTrial)
S_fig = hFig_tbl.UserData;
cS_trial = get0_('cS_trial');
S_ = cS_trial{iTrial};
P1 = S_fig.P;
P1.nSkip_img = get_set_(P1, 'nSkip_img', 2);
P1.xy0 = S_.xy0 / P1.nSkip_img;
P1.pixpercm = P1.pixpercm / P1.nSkip_img;
img0 = imadjust_mask_(binned_image_(S_.img0, P1.nSkip_img));
[~,dataID_,~] = fileparts(S_.vidFname);
% Crate axes
hAxes = get_(S_fig, 'hAxes');
if isempty(hAxes)
hAxes = axes(hFig_tbl, 'Units', 'pixels', 'Position', [10,220,800,600]);
end
% draw figure
hImage = get_(S_fig, 'hImage');
if isempty(hImage)
hImage = imshow(img0, 'Parent', hAxes);
hold(hAxes, 'on');
else
hImage.CData = img0;
end
hImage.UserData = P1;
% draw a grid
delete_(get_(S_fig, 'hGrid'));
hGrid = draw_grid_(hImage, -10:5:10);
% Title
vcTitle = [dataID_, ' [H]elp, [T]rajectory, [L/R/PgDn/PgUp]:Next/Prev, [G]oto, [E]xport ...'];
hTitle = get_(S_fig, 'hTitle');
if isempty(hTitle)
hTitle = title_(hAxes, vcTitle);
else
hTitle.String = vcTitle;
end
% Draw a table
hTable = get_(S_fig, 'hTable');
if isempty(hTable)
hTable = uitable(hFig_tbl, 'Data', S_.mrPos_shape, ...
'Position', [10 10 400 200], 'RowName', P1.csShapes, ...
'ColumnName', {'X pos (grid)', 'Y pos (grid)', 'Angle (deg)'});
hTable.ColumnEditable = true(1, 3);
hTable.CellEditCallback = @(a,b)draw_shapes_tbl_(hImage, hTable, iTrial);
else
hTable.Data = S_.mrPos_shape;
end
% Update
delete_(get_(S_fig, 'vhShapes'));
vhShapes = draw_shapes_tbl_(hImage, hTable, iTrial);
contextmenu_(hImage, hTable);
hFig_tbl.UserData = struct_add_(S_fig, hAxes, hImage, hTable, hGrid, iTrial, vhShapes, vhShapes);
end %func
%--------------------------------------------------------------------------
function img_adj = imadjust_mask_(img, mlMask)
if nargin<2, mlMask = []; end
if isempty(mlMask)
int_lim = quantile(single(img(img>0)), [.01, .99]);
else
int_lim = quantile(single(img(~mlMask)), [.01, .99]);
end
% imadjust excluding the mask
img_adj = imadjust(img, (int_lim)/255, [0, 1]);
end %func
%--------------------------------------------------------------------------
function keypress_FigShape_(hFig, event)
S_fig = get(hFig, 'UserData');
nStep = 1 + key_modifier_(event, 'shift')*3;
cS_trial = get0_('cS_trial');
nTrials = numel(cS_trial);
S_trial = cS_trial{S_fig.iTrial};
switch lower(event.Key)
case 'h'
msgbox(...
{'[H]elp',
'(Shift)+[L/R]: next trial (Shift: quick jump)',
'[G]oto trial',
'[Home]: First trial',
'[END]: Last trial',
'[E]xport coordinates to csv',
'[T]rajectory toggle',
'[S]ampling density',
'[C]opy trialset path'}, ...
'Shortcuts');
case {'leftarrow', 'rightarrow', 'home', 'end'}
% move to different trials and draw
iTrial_prev = S_fig.iTrial;
if strcmpi(event.Key, 'home')
iTrial = 1;
elseif strcmpi(event.Key, 'end')
iTrial = nTrials;
elseif strcmpi(event.Key, 'leftarrow')
iTrial = max(S_fig.iTrial - nStep, 1);
elseif strcmpi(event.Key, 'rightarrow')
iTrial = min(S_fig.iTrial + nStep, nTrials);
end
if iTrial ~= iTrial_prev
plotShapes_trial_(hFig, iTrial);
end
if isvalid_(get_(S_fig, 'hTraj')) % update the trajectory if turned on
draw_traj_trial_(hFig, iTrial);
end
case 'g'
vcTrial = inputdlg('Trial ID: ');
vcTrial = vcTrial{1};
if isempty(vcTrial), return; end
vcTrial = path2DataID_(vcTrial);
csDataID = getDataID_cS_(cS_trial);
iTrial = find(strcmp(vcTrial, csDataID));
if isempty(iTrial)
msgbox(['Trial not found: ', vcTrial]);
return;
end
plotShapes_trial_(hFig, iTrial);
if isvalid_(get_(S_fig, 'hTraj')) % update the trajectory if turned on
draw_traj_trial_(hFig, iTrial);
end
case 'e'
trial2csv_(S_trial);
case 't' % draw trajectory
if isvalid_(get_(S_fig, 'hTraj'))
delete_plot_(hFig, 'hTraj');
else
draw_traj_trial_(hFig, S_fig.iTrial);
end
case 's' % Sampling density
[S_shape, mrTXYARDVS_rs, P1] = nearShapes_trial_(S_trial, S_fig.P);
[vrX, vrY] = cm2pix_(mrTXYARDVS_rs(:,2:3)*100, P1);
vrD = mrTXYARDVS_rs(:,6);
S_trial = struct_add_(S_trial, vrX, vrY, vrD);
hFig_grid = figure_new_('FigGrid', S_trial.vcFile_Track, [0,0,.5,.5]);
[RGB, mrPlot] = gridMap_(S_trial, P1, 'density');
imshow(RGB); title('Sampling density');
hFig = figure_new_('',S_trial.vcFile_Track, [0 .5 .5 .5]);
viShapes = 1:6;
subplot 241; bar(1./S_shape.mrDRVS_shape(1,viShapes)); ylabel('Sampling density'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 242; bar(S_shape.mrDRVS_shape(2,viShapes)); ylabel('Sampling Rate (Hz)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 243; bar(S_shape.mrDRVS_shape(3,viShapes)); ylabel('Speed (m/s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 244; bar(1./S_shape.mrDRVS_shape(4,viShapes)); ylabel('EScan density'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 245; bar(S_shape.vnVisit_shape(viShapes)); ylabel('# visits'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 246; bar(S_shape.vtVisit_shape(viShapes)); ylabel('t visit (s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 247; bar(S_shape.vtVisit_shape(viShapes) ./ S_shape.vnVisit_shape(viShapes)); ylabel('t per visit (s)'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
subplot 248; bar(S_shape.vpBackward_shape(viShapes)); ylabel('Backward swim prob.'); set(gca,'XTickLabel', S_shape.csDist_shape); grid on;
case 'c'
clipboard('copy', S_trial.vcFile_Track);
msgbox(sprintf('%s copied to clipboard', S_trial.vcFile_Track));
otherwise
return;
end
end %func
%--------------------------------------------------------------------------
function [S_shape, mrTXYARDVS_rs, P1] = nearShapes_trial_(S_trial, P)
P1 = setfield(P, 'xy0', S_trial.xy0);
mrTXYARDVS_rs = resample_trial_(S_trial, P1);
[mrXY_h, vrD, vrR, vrV, vrS] = ...
deal(mrTXYARDVS_rs(:,2:3), mrTXYARDVS_rs(:,6), mrTXYARDVS_rs(:,5), mrTXYARDVS_rs(:,7), mrTXYARDVS_rs(:,8));
% vrV = hypot(diff3_(mrXY_h(:,1)), diff3_(mrXY_h(:,2))) * get_set_(P, 'sRateHz_resample', 100); % meter per sec
cm_per_grid = get_set_(P, 'cm_per_grid', 5);
mrPos_shape_meter = S_trial.mrPos_shape;
mrPos_shape_meter(:,1:2) = mrPos_shape_meter(:,1:2) * cm_per_grid / 100;
nShapes = size(mrPos_shape_meter,1);
mlDist_shape = false(size(mrXY_h,1), nShapes);
dist_cut = get_set_(P, 'dist_cm_shapes', 3) / 100;
for iShape = 1:nShapes
vcShape = strtok(P.csShapes{iShape}, ' ');
xya_ = mrPos_shape_meter(iShape,:);
len_ = P.vrShapes(iShape)/100; % in meter
[mrXY_poly_, fCircle] = get_polygon_(vcShape, xya_(1:2), len_, xya_(3));
if fCircle
vrD_ = hypot(xya_(1)-mrXY_h(:,1), xya_(2)-mrXY_h(:,2)) - len_/2;
else %polygon
vrD_ = nearest_perimeter_(mrXY_poly_, mrXY_h); % convert to meter
end
mlDist_shape(:,iShape) = vrD_ <= dist_cut;
end
% distance to the wall
r_wall = get_set_(P, 'diameter_cm_wall', 150) / 2 / 100;
dist_wall = get_set_(P, 'dist_cm_wall', 15) / 100; % 15 cm from the wall
vl_wall = hypot(mrXY_h(:,1), mrXY_h(:,2)) >= (r_wall - dist_wall);
mlDist_shape = [mlDist_shape, vl_wall, ~vl_wall];
csDist_shape = [P.csShapes, 'Wall', 'Not Wall'];
S_shape = makeStruct_(mlDist_shape, csDist_shape, vrD, vrR, vrV, vrS);
S_shape = S_shape_calc_(S_shape, P);
end %func
%--------------------------------------------------------------------------
function S_shape = S_shape_calc_(S_shape, P)
% output
% ------
% mrDRVS_shape
% vnVisit_shape
% vtVisit_shape
% vpBackward_shape
[vrD, vrR, vrV, vrS, mlDist_shape] = struct_get_(S_shape, 'vrD', 'vrR', 'vrV', 'vrS', 'mlDist_shape');
% sampling density by shapes
sRateHz_rs = get_set_(P, 'sRateHz_resample', 100);
mrDRVS_shape = region_median_([vrD, vrR, abs(vrV), vrS], mlDist_shape, @nanmedian); %@nanmean
[~, vnVisit_shape] = findup_ml_(mlDist_shape, sRateHz_rs);
% vnVisit_shape = sum(diff(mlDist_shape)>0); % clean up transitions
vtVisit_shape = sum(mlDist_shape) / sRateHz_rs;
vpBackward_shape = region_median_(sign(vrV)<0, mlDist_shape, @nanmean);
S_shape = struct_add_(S_shape, mrDRVS_shape, vnVisit_shape, vtVisit_shape, vpBackward_shape);
end %func
%--------------------------------------------------------------------------
function [cvi, vn] = findup_ml_(ml, nRefrac)
cvi = cell(1, size(ml,2));
vn = zeros(1, size(ml,2));
for iCol=1:size(ml,2)
vi_ = find(diff(ml(:,iCol))>0);
vn_ = diff(vi_);
viiKill_ = find(vn_<nRefrac);
if ~isempty(viiKill_)
vi_(viiKill_ + 1) = []; % remove
end
cvi{iCol} = vi_;
vn(iCol) = numel(vi_);
end
% vn = cell2mat(cellfun(@(x)diff(x), cvi', 'UniformOutput', 0));
end %func
%--------------------------------------------------------------------------
function mrMed = region_median_(mr, ml, fh)
if nargin<3, fh = @median; end
mrMed = nan(size(mr,2), size(ml,2));
for iCol = 1:size(ml,2)
vi_ = find(ml(:,iCol));
if ~isempty(vi_)
mrMed(:,iCol) = fh(mr(vi_,:));
end
end
end %func
%--------------------------------------------------------------------------
function S_fig = delete_plot_(hFig, vcTag)
S_fig = hFig.UserData;
if isempty(S_fig), return; end
delete_(get_(S_fig, vcTag));
S_fig.(vcTag) = [];
hFig.UserData = S_fig;
end %func
%--------------------------------------------------------------------------
function [S_fig, hPlot] = draw_traj_trial_(hFig, iTrial)
S_fig = hFig.UserData;
cS_trial = get0_('cS_trial');
S_trial = cS_trial{iTrial};
P = get_set_(S_fig, 'P', load_cfg_());
nSkip_img = get_set_(P, 'nSkip_img', 2);
[S_shape, mrTXYARDVS_rs, P1] = nearShapes_trial_(S_trial, P);
mrXY_pix = cm2pix_(mrTXYARDVS_rs(:,2:3)*100, P1);
try
% [X,Y] = deal(S_trial.XC(:,2)/nSkip_img, S_trial.YC(:,2)/nSkip_img);
[X,Y] = deal(mrXY_pix(:,1)/nSkip_img, mrXY_pix(:,2)/nSkip_img);
% vl = ~S_shape.mlDist_shape(:,end); % location query
% [X(vl),Y(vl)] = deal(nan(sum(vl),1));
hPlot = get_(S_fig, 'hTraj');
if isvalid_(hPlot)
[hPlot.XData, hPlot.YData] = deal(X, Y);
else
S_fig.hTraj = plot(S_fig.hAxes, X, Y, 'b');
hFig.UserData = S_fig;
end
catch
; % pass
end
end %func
%--------------------------------------------------------------------------
% Check for shift, alt, ctrl press
function flag = key_modifier_(event, vcKey)
try
flag = any(strcmpi(event.Modifier, vcKey));
catch
flag = 0;
end
end %func
%--------------------------------------------------------------------------
% Count number of shapes input
function tnShapes = countShapes_trialset_(S_trialset, cS_trial)
[viImg, tiImg] = struct_get_(S_trialset, 'viImg', 'tiImg');
tnShapes = zeros(size(tiImg), 'uint8');
for iTrial = 1:numel(cS_trial)
S_ = cS_trial{iTrial};
mrPos_shape = get_(S_, 'mrPos_shape');
if ~isempty(mrPos_shape)
tnShapes(viImg(iTrial)) = sum(~any(isnan(mrPos_shape), 2));
end
end %for
end %func
%--------------------------------------------------------------------------
function contextmenu_(hImg, tbl)
c = uicontextmenu;
hImg.UIContextMenu = c;
P1 = hImg.UserData;
% Create child menu items for the uicontextmenu
csShapes = P1.csShapes;
for iShape=1:numel(csShapes)
uimenu(c, 'Label', csShapes{iShape}, 'Callback',@setTable_);
end
uimenu(c, 'Label', '--------');
uimenu(c, 'Label', 'Rotate CW', 'Callback',@setTable_);
uimenu(c, 'Label', 'Rotate CCW', 'Callback',@setTable_);
uimenu(c, 'Label', 'Delete', 'Callback',@setTable_);
function setTable_(source,callbackdata)
xy = get(hImg.Parent, 'CurrentPoint');
xy_cm = pix2cm_(xy(1,1:2), P1); % scale factor
xy_grid = round(xy_cm / P1.cm_per_grid);
iRow_nearest = findNearest_grid_(xy_grid, tbl.Data, 1);
switch lower(source.Label)
case {'rotate cw', 'rotate ccw'}
if isempty(iRow_nearest), return; end
dAng = ifeq_(strcmpi(source.Label, 'rotate cw'), 90, -90);
tbl.Data(iRow_nearest,3) = mod(tbl.Data(iRow_nearest,3)+dAng,360);
case 'delete'
if isempty(iRow_nearest), return; end
tbl.Data(iRow_nearest,:) = nan; %delete
otherwise
if ~isempty(iRow_nearest)
tbl.Data(iRow_nearest,:) = nan; %delete
end
iRow = find(strcmp(tbl.RowName, source.Label));
tbl.Data(iRow,:) = [xy_grid(:)', 0];
end %switch
draw_shapes_tbl_(hImg, tbl);
end
end %func
%--------------------------------------------------------------------------
function iRow_nearest = findNearest_grid_(xy_grid, mrGrid, d_max);
d = pdist2(xy_grid(:)', mrGrid(:,1:2));
iRow_nearest = find(d<=d_max, 1, 'first');
end %func
%--------------------------------------------------------------------------
function h = draw_grid_(hImg, viGrid)
P1 = hImg.UserData;
[xx_cm, yy_cm] = meshgrid(viGrid);
mrXY_pix = cm2pix_([xx_cm(:), yy_cm(:)] * P1.cm_per_grid, P1);
h = plot(hImg.Parent, mrXY_pix(:,1), mrXY_pix(:,2), 'r.');
end %func
%--------------------------------------------------------------------------
function vhPlot = draw_shapes_tbl_(hImg, tbl, iTrial)
hFig = hImg.Parent.Parent;
S_fig = hFig.UserData;
if nargin<3, iTrial = S_fig.iTrial; end
P1 = hImg.UserData;
delete_(get_(P1, 'vhPlot'));
mrXY = tbl.Data;
mrXY(:,1:2) = mrXY(:,1:2) * P1.cm_per_grid;
nShapes = size(mrXY,1);
vhPlot = zeros(nShapes, 1);
for iShape = 1:nShapes
vcShape_ = strtok(tbl.RowName{iShape}, ' ');
vhPlot(iShape) = draw_shapes_img_(hImg, mrXY(iShape,:), P1.vrShapes(iShape), vcShape_);
end
P1.vhPlot = vhPlot;
set(hImg, 'UserData', P1);
% Save table data to fig userdata
cS_trial = get0_('cS_trial');
cS_trial{iTrial}.mrPos_shape = tbl.Data;
set0_(cS_trial);
S_fig.vhShapes = vhPlot;
hFig.UserData = S_fig;
end %func
%--------------------------------------------------------------------------
function flag = isvalid_(h)
if isempty(h), flag = 0; return ;end
try
flag = isvalid(h);
catch
flag = 0;
end
end %func
%--------------------------------------------------------------------------
function h = draw_shapes_img_(hImg, xya, dimm, vcShape)
% xya: xy0 and angle (cm and deg)
h = nan;
if any(isnan(dimm)), return; end
xy_ = xya(1:2);
if any(isnan(xy_)), return; end
P1 = hImg.UserData;
if numel(xya)==3
ang = xya(3);
else
ang = 0;
end
mrXY_cm = get_polygon_(vcShape, xy_, dimm, ang);
mrXY_pix = cm2pix_(mrXY_cm, P1);
h = plot(hImg.Parent, mrXY_pix(:,1), mrXY_pix(:,2), 'g-', 'LineWidth', 1);
end %func
%--------------------------------------------------------------------------
function [mrXY_cm, fCircle] = get_polygon_(vcShape, xy_, dimm, ang)
fCircle = 0;
switch upper(vcShape)
case 'TRIANGLE' % length is given
r_ = dimm(1)/sqrt(3);
vrA_ = [0, 120, 240, 0];
case {'CIRCLE', 'FOOD'} % diameter is given
r_ = dimm(1)/2;
vrA_ = [0:9:360];
fCircle = 1;
case {'SQUARE', 'RECT', 'RECTANGLE'} % length is given
r_ = dimm(1);
vrA_ = [45:90:360+45];
otherwise, error(['draw_shapes_img_: invalid shape: ', vcShape]);
end %switch
mrXY_cm = bsxfun(@plus, xy_(:)', rotate_line_(vrA_ + ang, r_));
end %func
%--------------------------------------------------------------------------
function xy_cm = pix2cm_(xy_pix, P1)
xy_cm = bsxfun(@minus, xy_pix, P1.xy0(:)') / P1.pixpercm;
xy_cm(:,2) = -xy_cm(:,2); % image coordinate to xy coordinate
xy_cm = rotatexy_(xy_cm, -P1.angXaxis);
end %func
%--------------------------------------------------------------------------
function varargout = cm2pix_(xy_cm, P1)
xy_pix = xy_cm * P1.pixpercm;
xy_pix(:,2) = -xy_pix(:,2); % change y axis
xy_pix = bsxfun(@plus, rotatexy_(xy_pix, -P1.angXaxis), P1.xy0(:)');
if nargout==1
varargout{1} = xy_pix;
else
[varargout{1}, varargout{2}] = deal(xy_pix(:,1), xy_pix(:,2));
end
end %func
%--------------------------------------------------------------------------
function [ xy_rot ] = rotatexy_( xy, ang)
%ROTATEXY rotate a vector with respect to the origin, ang in degree
% xy = xy(:);
CosA = cos(deg2rad(ang));
SinA = sin(deg2rad(ang));
M = [CosA, -SinA; SinA, CosA];
xy_rot = (M * xy')';
end
%--------------------------------------------------------------------------
% rotate a line and project. rotate from North
function xy = rotate_line_(vrA_deg, r)
if nargin<2, r=1; end
vrA_ = pi/2 - vrA_deg(:)/180*pi;
xy = r * [cos(vrA_), sin(vrA_)];
end %func
%--------------------------------------------------------------------------
function img1 = binned_image_(img, nSkip, fFast)
% fFast: set to 0 to do averaging (higher image quality)
if nargin<3, fFast = 1; end
if ndims(img)==3, img = img(:,:,1); end
if fFast
img1 = img(1:nSkip:end, 1:nSkip:end); % faster
else
dimm1 = floor(size(img)/nSkip);
viY = (0:dimm1(1)-1) * nSkip;
viX = (0:dimm1(2)-1) * nSkip;
img1 = zeros(dimm1, 'single');
for ix = 1:nSkip
for iy = 1:nSkip
img1 = img1 + single(img(viY+iy, viX+ix));
end
end
img1 = img1 / (nSkip*nSkip);
if isa(img, 'uint8'), img1 = uint8(img1); end
end
end %func
%--------------------------------------------------------------------------
function [cS_trial, S_trialset, mrPath, mrDur] = loadShapes_trialset_(vcFile_trialset)
[mrPath, mrDur, S_trialset, cS_trial] = trialset_learningcurve_(vcFile_trialset);
nSkip_img = get_set_(S_trialset.P, 'nSkip_img', 2);
% if nargout>=3
% trImg0 = cellfun(@(x)imadjust(binned_image_(x.img0, nSkip_img)), cS_trial, 'UniformOutput', 0);
% trImg0 = cat(3, trImg0{:});
% end
% default shape table
csShapes = get_set_(S_trialset, 'csShapes', {'Triangle Lg', 'Triangle Sm', 'Square Lg', 'Square Sm', 'Circle Lg', 'Circle Sm', 'Food'});
csShapes = csShapes(:);
nShapes = numel(csShapes);
mrData0 = [nan(nShapes, 2), zeros(nShapes,1)];
% load prev result
vcFile_mat = strrep(vcFile_trialset, '.trialset', '_trialset.mat');
[cTable_data, cS_trial_prev] = load_mat_(vcFile_mat, 'cTable_data', 'cS_trial');
% fill in mrPos_shape
csDataID = getDataID_cS_(cS_trial);
csDataID_prev = getDataID_cS_(cS_trial_prev);
for iFile = 1:numel(cS_trial)
S_ = cS_trial{iFile};
if isfield(S_, 'mrPos_shape'), continue; end
iPrev = find(strcmp(csDataID{iFile}, csDataID_prev));
mrData_ = mrData0;
if ~isempty(iPrev)
mrData_prev = cS_trial_prev{iPrev}.mrPos_shape;
nCol = min(nShapes, size(mrData_prev,1));
mrData_(1:nCol,:) = mrData_prev(1:nCol,:);
end
S_.mrPos_shape = mrData_;
cS_trial{iFile} = S_;
end
end %func
%--------------------------------------------------------------------------
function [csDataID, viAnimal, vlProbe] = getDataID_cS_(csFiles)
csDataID = cell(size(csFiles));
for i=1:numel(csFiles)
[~,csDataID{i},~] = fileparts(csFiles{i}.vidFname);
end
if nargout>=2
viAnimal = cellfun(@(x)x(4)-'A'+1, csDataID);
end
if nargout>=3
vlProbe = cellfun(@(x)numel(x)>5, csDataID);
end
end %func
%--------------------------------------------------------------------------
function dataID = path2DataID_(vc)
if iscell(vc), vc = vc{1}; end
[~, dataID, ~] = fileparts(vc);
dataID = strrep(dataID, '_Track', '');
end %func
%--------------------------------------------------------------------------
function h = msgbox_(vcMsg, fEcho)
if nargin<2, fEcho = 1; end
h = msgbox(vcMsg);
if fEcho, disp(vcMsg); end
end %func
%--------------------------------------------------------------------------
% 7/26/2018 JJJ: save mat file
% function save_mat_(varargin)
% vcFile = varargin{1};
% for i=2:nargin
% eval('%s=varargin{%d};', inputname(i));
% end
% if exist_file_(vcFile)
% save(vcFile, varargin{2:end}, '-append');
% else
% save(vcFile, varargin{2:end});
% end
% end %func
%--------------------------------------------------------------------------
function varargout = load_mat_(varargin)
% Usage
% [var1, var2, ...], = load_mat_(file_mat, var1_name, var2_name, ...)
if nargin<1, return; end
vcFile_mat = varargin{1};
varargout = cell(1, nargout());
if ~exist_file_(vcFile_mat), return; end
if nargin==1, S = load(vcFile_mat); return; end
S = load(vcFile_mat, varargin{2:end});
for iArg = 1:nargout()
try
varargout{iArg} = getfield(S, varargin{iArg+1});
catch
;
end
end %for
end %func
%--------------------------------------------------------------------------
function varargout = bar_mean_sd_(cvr, csXLabel, vcYLabel)
if nargin<2, csXLabel = {}; end
if nargin<3, vcYLabel = ''; end
if isempty(csXLabel), csXLabel = 1:numel(cvr); end
vrMean = cellfun(@(x)nanmean(x(:)), cvr);
vrSd = cellfun(@(x)nanstd(x(:)), cvr);
vrX = 1:numel(cvr);
errorbar(vrX, vrMean, [], vrSd, 'k', 'LineStyle', 'none');
hold on; grid on;
h = bar(vrX, vrMean);
set(h, 'EdgeColor', 'None');
set(gca, 'XTick', vrX, 'XTickLabel', csXLabel, 'XLim', vrX([1,end]) + [-.5, .5]);
ylabel(vcYLabel);
[h,pa]=ttest2(cvr{1},cvr{2});
fprintf('%s: E vs L, p=%f\n', vcYLabel, pa);
end %func
%--------------------------------------------------------------------------
function varargout = trim_quantile_(varargin)
qlim = varargin{end};
for iArg = 1:nargout
vr_ = varargin{iArg};
varargout{iArg} = quantFilt_(vr_(:), qlim);
end %for
end %func
%--------------------------------------------------------------------------
function vr = quantFilt_(vr, quantLim)
qlim = quantile(vr(:), quantLim);
vr = vr(vr >= qlim(1) & vr < qlim(end));
end %func
%--------------------------------------------------------------------------
% Display list of toolbox and files needed
% 7/26/17 JJJ: Code cleanup and test
function [fList, pList] = disp_dependencies_(vcFile)
if nargin<1, vcFile = []; end
if isempty(vcFile), vcFile = mfilename(); end
[fList,pList] = matlab.codetools.requiredFilesAndProducts(vcFile);
if nargout==0
disp('Required toolbox:');
disp({pList.Name}');
disp('Required files:');
disp(fList');
end
end % func
%--------------------------------------------------------------------------
function download_sample_()
S_cfg = load_cfg_();
csLink = get_(S_cfg, 'csLink_sample');
if isempty(csLink), fprintf(2, 'Sample video does not exist\n'); return; end
t1 = tic;
fprintf('Downloading sample files. This can take up to several minutes.\n');
vlSuccess = download_files_(csLink);
fprintf('\t%d/%d files downloaded. Took %0.1fs\n', ...
sum(vlSuccess), numel(vlSuccess), toc(t1));
end %func
%--------------------------------------------------------------------------
function vlSuccess = download_files_(csLink, csDest)
% download file from the web
nRetry = 5;
if nargin<2, csDest = link2file_(csLink); end
vlSuccess = false(size(csLink));
for iFile=1:numel(csLink)
for iRetry = 1:nRetry
try
% download from list of files
fprintf('\tDownloading %s: ', csLink{iFile});
vcFile_out1 = websave(csDest{iFile}, csLink{iFile});
fprintf('saved to %s\n', vcFile_out1);
vlSuccess(iFile) = 1;
break;
catch
fprintf('\tRetrying %d/%d\n', iRetry, nRetry);
if iRetry==nRetry
fprintf(2, '\n\tDownload failed. Please download manually from the link below.\n');
fprintf(2, '\t%s\n', csLink{iFile});
end
end
end
end %for
end %func
%--------------------------------------------------------------------------
function csFile = link2file_(csLink)
csFile = cell(size(csLink));
for i=1:numel(csLink)
vcFile1 = csLink{i};
iBegin = find(vcFile1=='/', 1, 'last'); % strip ?
if ~isempty(iBegin), vcFile1 = vcFile1(iBegin+1:end); end
iEnd = find(vcFile1=='?', 1, 'last'); % strip ?
if ~isempty(iEnd), vcFile1 = vcFile1(1:iEnd-1); end
csFile{i} = vcFile1;
end
end %func
%--------------------------------------------------------------------------
% 7/25/2018 JJJ: Wait for file to get deleted
function delete_file_(csFiles)
if isempty(csFiles), return; end
if ischar(csFiles), csFiles = {csFiles}; end
nRetry = 5;
for iRetry = 1:nRetry
for iFile = 1:numel(csFiles)
if ~exist_file_(csFiles{iFile}), continue; end
delete_(csFiles{iFile});
end
end
for i=1:nRetry, pause(.2); end % wait for file deletion
end %func
%--------------------------------------------------------------------------
% 7/25/2018 JJJ: Wait for file to get deleted
function S_cfg = load_cfg_()
try
S_cfg = file2struct('default.cfg');
catch
S_cfg = struct(); % return an empty struct
end
% default field
S_cfg.vcDir_commit = get_set_(S_cfg, 'vcDir_commit', 'D:\Dropbox\Git\vistrack\');
S_cfg.csFiles_commit = get_set_(S_cfg, 'csFiles_commit', {'*.m', 'GUI.fig', 'changelog.md', 'readme.txt', 'example.trialset', 'default.cfg'});
S_cfg.csFiles_delete = get_set_(S_cfg, 'csFiles_delete', {'settings_vistrack.m', 'example.trialset', 'R12A2_Track.mat'});
S_cfg.quantLim = get_set_(S_cfg, 'quantLim', [1/8, 7/8]);
S_cfg.vcFile_settings = get_set_(S_cfg, 'vcFile_settings', 'settings_vistrack.m');
S_cfg.pixpercm = get_set_(S_cfg, 'pixpercm', 7.238);
S_cfg.angXaxis = get_set_(S_cfg, 'angXaxis', -0.946);
end %func
%--------------------------------------------------------------------------
function trialset_exportcsv_(vcFile_trialset)
csMsg = {'Exporting the trialset to csv files...(this will close when done)', 'It can take up to several minutes'};
h = msgbox(csMsg, 'modal');
% S_trialset = load_trialset_(vcFile_trialset);
[cS_trial, S_trialset] = loadShapes_trialset_(vcFile_trialset);
for iFile = 1:numel(cS_trial)
S_ = cS_trial{iFile};
if isempty(S_), continue; end
try
[~,~,vcMsg,csFormat] = trial2csv_(S_, S_trialset.P);
fprintf('%s\n', vcMsg);
catch
disp(lasterr());
end
end %for
disp_cs_(csFormat);
close_(h);
end %func
%--------------------------------------------------------------------------
function trial_gridmap_(vcFile_Track)
S_trial = load_(vcFile_Track);
P = load_settings_(S_trial);
% LOADSETTINGS;
h = msgbox('Calculating... (this will close automatically)');
S_ = importTrial(S_trial, P.pixpercm, P.angXaxis);
[RGB, mrPlot] = gridMap_(S_, P, 'time');
% [mnVisit1, mnVisit] = calcVisitCount(S_, S_.img0);
% dataID = S_trial
figure_new_('', S_trial.vidFname); imshow(RGB);
title('Time spent');
try close(h); catch, end;
end %func
%--------------------------------------------------------------------------
function trial_timemap_(S_trial)
P = load_settings_(S_trial);
%track head
h = msgbox('Calculating... (This closes automatically)');
[VISITCNT, TIMECNT] = calcVisitDensity(S_trial.img0, S_trial.TC, S_trial.XC(:,2), S_trial.YC(:,2), P.TRAJ_NFILT);
% trialID = trial_id_(handles);
img0_adj = imadjust(S_trial.img0);
hFig = figure_new_('', S_trial.vidFname);
imshow(rgbmix_(img0_adj, TIMECNT));
resize_figure_(hFig, [0,0,.5,1]);
title('Time map');
close_(h);
end %func
%--------------------------------------------------------------------------
function [dataID, fishID, iSession, iTrial, fProbe] = trial_id_(S_trial)
[~,dataID,~] = fileparts(S_trial.vidFname);
fishID = dataID(4);
iSession = str2num(dataID(2:3));
iTrial = str2num(dataID(5));
fProbe = numel(dataID) > 5;
end %func
%--------------------------------------------------------------------------
function [RGB, mrPlot] = gridMap_(vsTrial, P, vcMode, lim, mlMask)
% vcMode: {'time', 'visit', 'time/visit', 'density'}
if nargin < 2, P = []; end
if nargin < 3, vcMode = 'time'; end % visit, time, time/visit
if nargin < 4, lim = []; end
if nargin < 5, mlMask = []; end
nGrid_map = get_set_(P, 'nGrid_map', 20);
nTime_map = get_set_(P, 'nTime_map', 25);
angXaxis = get_set_(P, 'angXaxis', -1.1590); %deg
if iscell(vsTrial), vsTrial = cell2mat(vsTrial); end % make it an array
%background image processing
xy0 = vsTrial(1).xy0;
img0 = vsTrial(1).img0(:,:,1);
% mlMask = getImageMask(img0, [0 60], 'CENTRE');
img0 = imrotate(imadjust(img0), -angXaxis, 'nearest', 'crop');
%rotate vrX, vrY, and images
vrX = poolVecFromStruct(vsTrial, 'vrX'); % in meters
vrY = poolVecFromStruct(vsTrial, 'vrY'); % in meters
try vrD = poolVecFromStruct(vsTrial, 'vrD'); catch, vrD = []; end
rotMat = rotz(-angXaxis); rotMat = rotMat(1:2, 1:2);
mrXY = [vrX(:) - xy0(1), vrY(:) - xy0(2)] * rotMat;
vrX = mrXY(:,1) + xy0(1);
vrY = mrXY(:,2) + xy0(2);
viX = ceil(vrX/nGrid_map);
viY = ceil(vrY/nGrid_map);
[h, w] = size(img0);
h = h / nGrid_map;
w = w / nGrid_map;
[mrDensity, mnVisit, mnTime] = deal(zeros(h,w));
for iy=1:h
vlY = (viY == iy);
for ix=1:w
viVisit = find(vlY & (viX == ix));
if isempty(viVisit), continue; end
mnTime(iy,ix) = numel(viVisit);
nRepeats = sum(diff(viVisit) < nTime_map); % remove repeated counts
mnVisit(iy,ix) = numel(viVisit) - nRepeats;
if ~isempty(vrD)
mrDensity(iy,ix) = 1 ./ mean(vrD(viVisit));
fprintf('.');
end
end
end
mrTperV = mnTime ./ mnVisit;
switch lower(vcMode)
case 'time'
mrPlot = mnTime;
case 'visit'
mrPlot = mnVisit;
case 'time/visit'
mrPlot = mrTperV;
case {'density', 'samplingdensity'}
mrPlot = mrDensity;
end
mnPlot_ = imresize(mrPlot, nGrid_map, 'nearest');
if isempty(lim), lim = [min(mnPlot_(:)) max(mnPlot_(:))]; end
mrVisit = uint8((mnPlot_ - lim(1)) / diff(lim) * 255);
RGB = rgbmix_(img0, mrVisit, mlMask);
if nargout==0
figure; imshow(RGB); title(sprintf('%s, clim=[%f, %f]', vcMode, lim(1), lim(2)));
end
end %func
%--------------------------------------------------------------------------
function img = rgbmix_(img_bk, img, MASK, mixRatio)
if nargin<3, MASK = []; end
if nargin<4, mixRatio = []; end
if isempty(mixRatio), mixRatio = .25; end
if numel(size(img_bk)) == 2 %gray scale
if ~isa(img_bk, 'uint8')
img_bk = uint8(img_bk/max(img_bk(:)));
end
img_bk = imgray2rgb(img_bk, [0 255], 'gray');
end
if numel(size(img)) == 2 %gray scale
if ~isempty(MASK), img(~MASK) = 0; end % clear non masked area (black)
if ~isa(img, 'uint8')
img = uint8(img/max(img(:))*255);
end
img = imgray2rgb(img, [0 255], 'jet');
end
for iColor = 1:3
mr1_ = single(img(:,:,iColor));
mr0_ = single(img_bk(:,:,iColor));
mr_ = mr1_*mixRatio + mr0_*(1-mixRatio);
if isempty(MASK)
img(:,:,iColor) = uint8(mr_);
else
mr0_(MASK) = mr_(MASK);
img(:,:,iColor) = uint8(mr0_);
end
end
end %func
%--------------------------------------------------------------------------
function handles = trial_fixsync1_(handles, fAsk)
% Load video file from handle
if nargin<2, fAsk = 1; end
% Load video
h=msgbox('Loading... (this will close automatically)');
[vidobj, vcFile_vid] = load_vid_handle_(handles);
if isempty(vidobj)
fprintf(2, 'Video file does not exist: %s\n', handles.vidFname);
close_(h);
return;
end
P = load_settings_(handles);
% load video, load LED until end of the video
try
nFrames_load = handles.FLIM(2);
catch
nFrames_load = vidobj.NumberOfFrames;
end
[vrLed_cam, viT_cam] = loadLed_vid_(vidobj, [], nFrames_load);
[viT_cam, viiFilled_led] = fill_pulses_(viT_cam);
close_(h);
% figure; plot(vrLed); hold on; plot(viT_cam, vrLed(viT_cam), 'o');
% get ADC timestamp
vrT_adc = getSync_adc_(handles);
nBlinks = min(numel(viT_cam), numel(vrT_adc));
[viT_cam, vrT_adc] = deal(viT_cam(1:nBlinks), vrT_adc(1:nBlinks));
% Compare errors
vtLed_cam = interp1(viT_cam, vrT_adc, (1:numel(vrLed_cam)), 'linear', 'extrap');
[vrX, vrY, TC] = deal(handles.XC(:,2), handles.YC(:,2), handles.TC(:));
vrTC_new = interp1(viT_cam, vrT_adc, (handles.FLIM(1):handles.FLIM(2))', 'linear', 'extrap');
vrT_err = TC - vrTC_new;
vrV = sqrt((vrX(3:end)-vrX(1:end-2)).^2 + (vrY(3:end)-vrY(1:end-2)).^2) / P.pixpercm / 100;
vrV_prev = vrV ./ (TC(3:end) - TC(1:end-2));
vrV_new = vrV ./ (vrTC_new(3:end) - vrTC_new(1:end-2));
% plot
hFig = figure_new_('', vcFile_vid);
ax(1) = subplot(3,1,1);
plot(vtLed_cam, vrLed_cam); grid on; hold on;
plot(vtLed_cam(viT_cam), vrLed_cam(viT_cam), 'ro');
ylabel('LED');
title(sprintf('FPS: %0.3f Hz', handles.FPS));
ax(2) = subplot(3,1,2);
plot(vrTC_new, vrT_err, 'r.'); grid on;
title(sprintf('Sync error SD: %0.3fs', std(vrT_err)));
ax(3) = subplot(3,1,3); hold on;
plot(vrTC_new(2:end-1), vrV_prev, 'ro-');
plot(vrTC_new(2:end-1), vrV_new, 'go-'); grid on;
ylabel('Speed (m/s)'); xlabel('Time (s)');
linkaxes(ax,'x');
xlim(vrTC_new([1, end]));
title(sprintf('Ave speed: %0.3f(old), %0.3f(new) m/s', mean(vrV_prev), mean(vrV_new)));
if fAsk
vcAns = questdlg('Save time sync?', vcFile_vid, ifeq_(std(vrT_err) > .01, 'Yes', 'No'));
fSave = strcmpi(vcAns, 'Yes');
else
fSave = 1;
end
if fSave % save to file
handles.TC = vrTC_new;
handles.FPS = diff(handles.FLIM([1,end])) / diff(handles.TC([1,end]));
trial_save_(handles);
end
end %func
%--------------------------------------------------------------------------
function hPlot = plot_vline_(hAx, vrX, ylim1, lineStyle)
if nargin<4, lineStyle = []; end
mrX = repmat(vrX(:)', [3,1]);
mrY = nan(size(mrX));
mrY(1,:) = ylim1(1);
mrY(2,:) = ylim1(2);
if isempty(lineStyle)
hPlot = plot(hAx, mrX(:), mrY(:));
else
hPlot = plot(hAx, mrX(:), mrY(:), lineStyle);
end
end %func
%--------------------------------------------------------------------------
function keypress_FigSync_(hFig, event)
S_fig = get(hFig, 'UserData');
if key_modifier_(event, 'shift')
nStep = 10;
elseif key_modifier_(event, 'control')
nStep = 100;
else
nStep = 1;
end
nFrames = size(S_fig.mov, 3);
switch lower(event.Key)
case 'h'
msgbox(...
{'[H]elp',
'(Shift/Ctrl)+[L/R]: Next Frame (Shift:10x, Ctrl:100x)',
'[PgDn/PgUp]: Next/Prev Event Marker'
'[G]oto trial',
'[Home]: First trial',
'[END]: Last trial'
}, ...
'Shortcuts');
return;
case {'leftarrow', 'rightarrow', 'home', 'end', 'pagedown', 'pageup'}
% move to different trials and draw
iFrame_prev = S_fig.iFrame;
if strcmpi(event.Key, 'home')
iFrame = 1;
elseif strcmpi(event.Key, 'end')
iFrame = nFrames;
elseif strcmpi(event.Key, 'leftarrow')
iFrame = S_fig.iFrame - nStep;
elseif strcmpi(event.Key, 'rightarrow')
iFrame = S_fig.iFrame + nStep;
elseif strcmpi(event.Key, 'pageup')
iFrame = find_event_sync_(S_fig, 0);
elseif strcmpi(event.Key, 'pagedown')
iFrame = find_event_sync_(S_fig, 1);
end
iFrame = setlim_(iFrame, [1, nFrames]);
if iFrame ~= iFrame_prev
refresh_FigSync_(hFig, iFrame);
end
case 'g'
vcFrame = inputdlg('Frame#: ');
if isempty(vcFrame), return; end
iFrame = str2num(vcFrame);
if isempty(iFrame) || isnan(iFrame)
msgbox(['Invalid Frame#: ', vcFrame]);
return;
end
refresh_FigSync_(hFig, iFrame);
otherwise
return;
end %switch
end %func
%--------------------------------------------------------------------------
function iFrame = find_event_sync_(S_fig, fForward)
if nargin<2, fForward = 1; end
% find event
iFrame_now = S_fig.iFrame;
viText_cam = adc2cam_sync_([], S_fig.vtText);
if fForward
iText = find(viText_cam > iFrame_now, 1, 'first');
else
iText = find(viText_cam < iFrame_now, 1, 'last');
end
iFrame = ifeq_(isempty(iText), iFrame_now, viText_cam(iText));
if iFrame<1, iFrame = iFrame_now; end
end %func
%--------------------------------------------------------------------------
function [vtText, csText] = getText_adc_(handles, P)
if nargin<2, P=[]; end
if isempty(P), P = load_settings_(handles); end
ADCTS = get_(handles, 'ADCTS');
if isempty(ADCTS), vtText = []; return; end
ADC_CH_TEXT = get_set_(P, 'ADC_CH_TEXT', 30);
S_text = getfield(ADCTS, sprintf('%s_Ch%d', getSpike2Prefix_(ADCTS), ADC_CH_TEXT));
[vtText, vcText_] = struct_get_(S_text, 'times', 'text');
csText = cellstr(vcText_);
end %func
%--------------------------------------------------------------------------
function [vtEodr, vrEodr] = getEodr_adc_(handles, P)
if nargin<2, P=[]; end
if isempty(P), P = load_settings_(handles); end
[vtEodr, vrEodr] = deal([]);
ADCTS = get_(handles, 'ADCTS');
if isempty(ADCTS), return; end
ADC_CH_EOD = get_set_(P, 'ADC_CH_EOD', 10);
S_eod = getfield(ADCTS, sprintf('%s_Ch%d', getSpike2Prefix_(ADCTS), ADC_CH_EOD));
vtEod = S_eod.times;
vrEodr = 2 ./ (vtEod(3:end) - vtEod(1:end-2));
vtEodr = vtEod(2:end-1);
end %func
%--------------------------------------------------------------------------
function [vrLed, viT_cam] = loadLed_vid_(vidobj, xyLed, nFrames)
if nargin<2, xyLed = []; end
if nargin<3, nFrames = []; end
nStep = 300;
nParfor = 4;
t1=tic;
% Find LED
if isempty(nFrames), nFrames = vidobj.NumberOfFrames; end
flim = [1,min(nStep,nFrames)];
mov_ = vid_read(vidobj, flim(1):flim(2));
if isempty(xyLed), xyLed = findLed_mov_(mov_); end
vrLed = mov2led_(mov_, xyLed);
if flim(2) == nFrames, return; end
% Load rest of the movie
viFrame_start = (1:nStep:nFrames)';
cvrLed = cell(size(viFrame_start));
cvrLed{1} = vrLed;
try
parfor (i = 2:numel(cvrLed), nParfor)
flim_ = viFrame_start(i) + [0, nStep-1];
flim_(2) = min(flim_(2), nFrames);
cvrLed{i} = mov2led_(vid_read(vidobj, flim_(1):flim_(2)), xyLed);
end
catch
for iFrame1 = 2:numel(cvrLed)
flim_ = viFrame_start(i) + [0, nStep-1];
flim_(2) = min(flim_(2), nFrames);
cvrLed{i} = mov2led_(vid_read(vidobj, flim_(1):flim_(2)), xyLed);
end
end
vrLed = cell2mat(cvrLed);
if nargout>=2
thresh_led = (max(vrLed) + median(vrLed))/2;
viT_cam = find(diff(vrLed > thresh_led)>0) + 1;
end
fprintf('LED loading took %0.1fs\n', toc(t1));
end %func
%--------------------------------------------------------------------------
% Remove pulses
function [viT_new, viRemoved] = remove_pulses_(viT)
% remove pulses out of the range
tol = .01; % allow tolerence
int_med = median(diff(viT));
int_lim = int_med * [1-tol, 1+tol];
viInt2 = viT(3:end) - viT(1:end-2);
viRemoved = find(viInt2 >= int_lim(1) & viInt2 <= int_lim(2))+1;
viT_new = viT;
if ~isempty(viRemoved)
viT_new(viRemoved) = [];
fprintf('Removed %d ADC pulses\n', numel(viRemoved));
end
end %func
%--------------------------------------------------------------------------
% Fill missing LED pulses
function [viT_new, viT_missing] = fill_pulses_(viT_cam)
% vlPulse = false(1, numel(viT_cam));
% vlPulse(viT_cam) = 1;
viT_ = [0; viT_cam(:)];
vrTd = diff(viT_);
vnInsert_missing = round(vrTd / median(vrTd)) - 1;
viMissing = find(vnInsert_missing > 0);
if isempty(viMissing)
viT_new = viT_cam;
viT_missing = [];
else
cviT_missing = cell(1, numel(viMissing));
for iMissing1 = 1:numel(viMissing)
iMissing = viMissing(iMissing1);
n_ = vnInsert_missing(iMissing);
vi_ = linspace(viT_(iMissing), viT_(iMissing+1), n_+2);
cviT_missing{iMissing1} = vi_(2:end-1);
end
viT_missing = round(cell2mat(cviT_missing));
viT_new = sort([viT_cam(:); viT_missing(:)]);
end
if numel(viT_missing)>0
fprintf('%d pulses inserted (before: %d, after: %d)\n', numel(viT_missing), numel(viT_cam), numel(viT_new));
end
if nargout==0
figure; hold on; grid on;
plot(viT_cam, ones(size(viT_cam)), 'bo');
plot(viT_missing, ones(size(viT_missing)), 'ro');
end
end %func
%--------------------------------------------------------------------------
function vrLed = mov2led_(mov, xyLed)
vrLed = squeeze(mean(mean(mov(xyLed(2)+[-1:1], xyLed(1)+[-1:1], :),1),2));
end %func
%--------------------------------------------------------------------------
function vrT_adc = getSync_adc_(handles, P)
if nargin<2, P=[]; end
if isempty(P), P = load_settings_(handles); end
ADCTS = get_(handles, 'ADCTS');
if isempty(ADCTS), vrT_adc = []; return; end
S_adc = getfield(ADCTS, sprintf('%s_Ch%d', getSpike2Prefix_(ADCTS), P.ADC_CH_TCAM));
vrT_adc = get_(S_adc, 'times');
end %func
%--------------------------------------------------------------------------
function [vidobj, vcFile_vid] = load_vid_handle_(handles);
vidobj = [];
vcFile_vid = handles.vidFname;
if ~exist_file_(vcFile_vid)
try
vcFile_Track = get_(handles.editResultFile, 'String');
catch
vcFile_Track = get_(handles, 'vcFile_Track');
end
vcFile_vid_ = subsDir_(vcFile_vid, vcFile_Track);
if ~exist_file_(vcFile_vid_)
return;
else
vcFile_vid = vcFile_vid_;
end
end
vidobj = get_(handles, 'vidobj');
if isempty(vidobj)
vidobj = VideoReader_(vcFile_vid);
end
end %func
%--------------------------------------------------------------------------
% 9/26/17 JJJ: Created and tested
function vcFile_new = subsDir_(vcFile, vcDir_new)
% vcFile_new = subsDir_(vcFile, vcFile_copyfrom)
% vcFile_new = subsDir_(vcFile, vcDir_copyfrom)
% Substitute dir
if isempty(vcDir_new), vcFile_new = vcFile; return; end
[vcDir_new,~,~] = fileparts(vcDir_new); % extrect directory part. danger if the last filesep() doesn't exist
[vcDir, vcFile, vcExt] = fileparts(vcFile);
vcFile_new = fullfile(vcDir_new, [vcFile, vcExt]);
end % func
%--------------------------------------------------------------------------
function xyLed = findLed_mov_(trImg, nFrames_led)
if nargin<2, nFrames_led = []; end
if ~isempty(nFrames_led)
nFrames_led = min(size(trImg,3), nFrames_led);
trImg = trImg(:,:,1:nFrames_led);
end
img_pp = (max(trImg,[],3) - min(trImg,[],3));
[~,imax_pp] = max(img_pp(:));
[yLed, xLed] = ind2sub(size(img_pp), imax_pp);
xyLed = [xLed, yLed];
end %func
%--------------------------------------------------------------------------
% 7/30/2018 JJJ: Moved from GUI.m
function vcFile_Track = trial_save_(handles)
handles.ESAC = calcESAC(handles);
[handles.vcVer, handles.vcVer_date] = version_();
S_cfg = vistrack('load-cfg');
S_save = struct_copy_(handles, S_cfg.csFields);
if isfield(handles, 'vcFile_Track')
vcFile_Track = handles.vcFile_Track;
elseif exist_file_(handles.vidFname)
vcFile_Track = subsFileExt_(handles.vidFname, '_Track.mat');
else
vcFile_Track = get(handles.editResultFile, 'String');
end
h = msgbox('Saving... (this will close automatically)');
try
struct_save_(S_save, vcFile_Track, 0);
if isfield(handles, 'editResultFile')
set(handles.editResultFile, 'String', vcFile_Track);
msgbox_(sprintf('Output saved to %s', fullpath_(vcFile_Track)));
else
fprintf('Output saved to %s\n', fullpath_(vcFile_Track)); % batch mode
end
catch
fprintf(2, 'Save file failed: %s\n', vcFile_Track);
end
close_(h);
end %func
%--------------------------------------------------------------------------
% 7/30/2018 JJJ: Moved from GUI.m
function S_save = struct_copy_(handles, csField)
for i=1:numel(csField)
try
S_save.(csField{i}) = handles.(csField{i});
catch
S_save.(csField{i}) = []; % not copied
end
end
end %func
%--------------------------------------------------------------------------
% 7/24/2018: Copied from jrc3.m
function out = ifeq_(if_, true_, false_)
if (if_)
out = true_;
else
out = false_;
end
end %func
%--------------------------------------------------------------------------
% 7/30/18 JJJ: Copied from jrc3.m
function struct_save_(S, vcFile, fVerbose)
nRetry = 3;
if nargin<3, fVerbose = 0; end
if fVerbose
fprintf('Saving a struct to %s...\n', vcFile); t1=tic;
end
version_year = version('-release');
version_year = str2double(version_year(1:end-1));
if version_year >= 2017
for iRetry=1:nRetry
try
save(vcFile, '-struct', 'S', '-v7.3', '-nocompression'); %faster
break;
catch
pause(.5);
end
fprintf(2, 'Saving failed: %s\n', vcFile);
end
else
for iRetry=1:nRetry
try
save(vcFile, '-struct', 'S', '-v7.3');
break;
catch
pause(.5);
end
fprintf(2, 'Saving failed: %s\n', vcFile);
end
end
if fVerbose
fprintf('\ttook %0.1fs.\n', toc(t1));
end
end %func
%--------------------------------------------------------------------------
function [S_sync, mov] = calc_sync_(handles, mov)
% handles.{ADCTS, vidFname, vidobj}
if nargin<2, mov = []; end
if isempty(mov), mov = handles2mov_(handles); end
% Find LED timing
vtLed_adc = getSync_adc_(handles);
[vtLed_adc, viLed_adc_removed] = remove_pulses_(vtLed_adc);
xyLed = findLed_mov_(mov, 300);
vrLed = mov2led_(mov, xyLed);
vrLed = vrLed - medfilt1(vrLed,5);
thresh_led = max(vrLed) * .2;
viLed_cam = find(diff(vrLed > thresh_led)>0) + 1;
[viLed_cam, viiLed_filled] = fill_pulses_(viLed_cam);
if numel(viLed_cam) > numel(vtLed_adc), viLed_cam(1) = []; end % remove the first
S_sync = struct('vrT_adc', vtLed_adc, 'viT_cam', viLed_cam);
end %func
%--------------------------------------------------------------------------
function mov = handles2mov_(handles, P)
if nargin<2, P = []; end
if isempty(P), P = load_settings_(handles); end
vcFile_vid = handles.vidFname;
vcVidExt = get_set_(P, 'vcVidExt', '.wmv');
if ~exist_file_(vcFile_vid)
vcFile_vid = strrep(get_(handles, 'vcFile_Track'), '_Track.mat', vcVidExt);
end
h = msgbox_('Loading video... (this closes automatically)');
[mov, dimm_vid] = loadvid_(vcFile_vid, get_set_(P, 'nSkip_vid', 4));
close_(h);
end %func
%--------------------------------------------------------------------------
function [handles, hFig] = trial_fixsync_(handles, fPlot)
% fPlot: 0 (no-plot, save), 1 (plot, save), 2 (plot, no save)
persistent mov
if nargin==0, mov = []; return; end % clear cache
if nargin<2, fPlot = 1; end
P = load_settings_(handles);
if isempty(mov)
mov = handles2mov_(handles, P);
else
fprintf('Using cached video.\n');
end
S_sync = calc_sync_(handles, mov);
% [vrT_adc, viT_cam] = struct_get_(S_sync, 'vrT_adc', 'viT_cam');
[tlim_adc, flim_cam] = sync_limit_(S_sync.vrT_adc, S_sync.viT_cam);
% save if not plotting
if fPlot == 0
TC = cam2adc_sync_(S_sync, handles.FLIM(1):handles.FLIM(2));
FPS = diff(handles.FLIM([1,end])) / diff(handles.TC([1,end]));
save(handles.vcFile_Track, 'TC', 'FPS', 'S_sync', '-append');
return;
end
[vtText, csText] = getText_adc_(handles, P);
xoff_ = 50;
csPopup = {'First frame', csText{:}, 'Last frame'};
hFig = figure_new_('FigSync', [handles.vidFname, ' press "h" for help'], [0,0,.5,1]);
hFig.KeyPressFcn = @keypress_FigSync_;
hPopup = uicontrol('Style', 'popup', 'String', csPopup, ...
'Position', [xoff_ 0 200 50], 'Callback', @popup_sync_);
hPopup.KeyPressFcn = @(h,e)keypress_FigSync_(hFig,e);
% Create axes
iFrame = 1;
hAxes1 = axes(hFig, 'Units', 'pixels', 'Position', [xoff_,60,800,600]);
hImage = imshow(mov(:,:,iFrame), 'Parent', hAxes1);
hold(hAxes1, 'on');
hTitle = title_(hAxes1, sprintf('Frame %d', iFrame));
% Create Line plot
tFrame_adc = cam2adc_sync_(S_sync, iFrame);
hAxes2 = axes(hFig, 'Units', 'pixels', 'Position', [xoff_,750,800,50]);
hold(hAxes2, 'on');
plot_vline_(hAxes2, S_sync.vrT_adc, [0,1], 'k');
plot_vline_(hAxes2, vtText, [0,1], 'm');
hLine_cam = plot_vline_(hAxes2, cam2adc_sync_(S_sync, S_sync.viT_cam), [0,1], 'r--');
set(hAxes2, 'XTick', S_sync.vrT_adc);
xlabel('ADC Time (s)');
set(hAxes2, 'XLim', tlim_adc);
hCursor_adc = plot(hAxes2, tFrame_adc, .5, 'ro');
% Create Line plot
hAxes3 = axes(hFig, 'Units', 'pixels', 'Position', [xoff_,850,800,50]);
hold(hAxes3, 'on');
hPlot3 = plot_vline_(hAxes3, S_sync.viT_cam, [0,1], 'r--');
xlabel('Camera Frame #');
set(hAxes3, 'XLim', flim_cam);
set(hAxes3, 'XTick', S_sync.viT_cam);
hCursor_cam = plot(hAxes3, iFrame, .5, 'ro');
% Show EOD plot
hAxes4 = axes(hFig, 'Units', 'pixels', 'Position', [xoff_,950,800,100]);
hold(hAxes4, 'on');
xlabel('ADC Time (s)');
ylabel('EOD Rate (Hz)');
[vtEodr, vrEodr] = getEodr_adc_(handles, P);
hPlot_eod = plot(hAxes4, vtEodr, vrEodr, 'k');
hCursor_eod = plot(hAxes4, tFrame_adc, median(vrEodr), 'ro');
set(hAxes4, 'XLim', tlim_adc, 'YLim', median(vrEodr) * [1/2, 2]);
hFig.UserData = makeStruct_(iFrame, mov, hImage, vtText, csText, hTitle, ...
S_sync, hCursor_adc, hCursor_cam, hPopup, hPlot_eod, hCursor_eod);
set0_(S_sync);
if fPlot == 2, return; end
% close the figure after done
msgbox_('Close the figure when finished.');
uiwait(hFig);
S_sync = get0_('S_sync');
TC = cam2adc_sync_(S_sync, handles.FLIM(1):handles.FLIM(2));
if questdlg_(sprintf('Save time sync? (mean error: %0.3fs)', std(TC-handles.TC)))
handles.TC = TC;
handles.FPS = diff(handles.FLIM([1,end])) / diff(handles.TC([1,end]));
trial_save_(handles);
end
end %func
%--------------------------------------------------------------------------
function vrT1_adc = cam2adc_sync_(S_sync, viT1_cam)
if isempty(S_sync), S_sync = get0_('S_sync'); end
[vrT_adc, viT_cam] = struct_get_(S_sync, 'vrT_adc', 'viT_cam');
nBlinks = min(numel(viT_cam), numel(vrT_adc));
[viT_cam, vrT_adc] = deal(viT_cam(end-nBlinks+1:end), vrT_adc(1:nBlinks));
vrT1_adc = interp1(viT_cam, vrT_adc, viT1_cam, 'linear', 'extrap');
end %func
%--------------------------------------------------------------------------
function [tlim_adc, flim_cam] = sync_limit_(vtLed_adc, viLed_cam)
nBlinks = min(numel(vtLed_adc), numel(viLed_cam));
tlim_adc = vtLed_adc([1, nBlinks]);
flim_cam = viLed_cam([end-nBlinks+1, end]);
end %func
%--------------------------------------------------------------------------
function viT1_cam = adc2cam_sync_(S_sync, vrT1_adc)
if isempty(S_sync), S_sync = get0_('S_sync'); end
[vrT_adc, viT_cam] = struct_get_(S_sync, 'vrT_adc', 'viT_cam');
nBlinks = min(numel(viT_cam), numel(vrT_adc));
[viT_cam, vrT_adc] = deal(viT_cam(1:nBlinks), vrT_adc(1:nBlinks));
viT1_cam = round(interp1(vrT_adc, viT_cam, vrT1_adc, 'linear', 'extrap'));
end %func
%--------------------------------------------------------------------------
function vc = popup_sync_(h,e)
hFig = h.Parent;
S_fig = hFig.UserData;
vcLabel = h.String{h.Value};
[iFrame_prev, mov, S_sync, hTitle, hImage] = ...
struct_get_(S_fig, 'iFrame', 'mov', 'S_sync', 'hTitle', 'hImage');
nFrames = size(mov,3);
switch lower(vcLabel)
case 'first frame'
iFrame = 1;
case 'last frame'
iFrame = nFrames;
otherwise
t_adc = S_fig.vtText(h.Value-1);
iFrame = setlim_(adc2cam_sync_(S_sync, t_adc), [1, nFrames]);
end
if iFrame_prev==iFrame, return ;end
refresh_FigSync_(hFig, iFrame);
end %func
%--------------------------------------------------------------------------
function refresh_FigSync_(hFig, iFrame)
S_fig = hFig.UserData;
[iFrame_prev, mov, S_sync, hTitle, hImage] = ...
struct_get_(S_fig, 'iFrame', 'mov', 'S_sync', 'hTitle', 'hImage');
hImage.CData = mov(:,:,iFrame);
set(S_fig.hCursor_cam, 'XData', iFrame);
tFrame_adc = cam2adc_sync_(S_sync, iFrame);
set(S_fig.hCursor_adc, 'XData', tFrame_adc);
set(S_fig.hCursor_eod, 'XData', tFrame_adc);
% Update title
viText_cam = adc2cam_sync_(S_sync, S_fig.vtText);
viMatch = find(viText_cam==iFrame);
if isempty(viMatch)
hTitle.String = sprintf('Frame %d', iFrame);
else
iMatch = viMatch(1);
hTitle.String = sprintf('Frame %d: %s', iFrame, S_fig.csText{iMatch});
S_fig.hPopup.Value = iMatch+1;
end
% update current frame
S_fig.iFrame = iFrame;
hFig.UserData = S_fig;
set0_(S_fig); % push to global
end %func
%--------------------------------------------------------------------------
function vr = setlim_(vr, lim_)
% Set low and high limits
vr = min(max(vr, lim_(1)), lim_(2));
end %func
%--------------------------------------------------------------------------
function hTitle = title_(hAx, vc)
% title_(vc)
% title_(hAx, vc)
if nargin==1, vc=hAx; hAx=[]; end
% Set figure title
if isempty(hAx), hAx = gca; end
hTitle = get_(hAx, 'Title');
if isempty(hTitle)
hTitle = title(hAx, vc, 'Interpreter', 'none', 'FontWeight', 'normal');
else
set_(hTitle, 'String', vc, 'Interpreter', 'none', 'FontWeight', 'normal');
end
end %func
%--------------------------------------------------------------------------
function vc = set_(vc, varargin)
% Set handle to certain values
% set_(S, name1, val1, name2, val2)
if isempty(vc), return; end
if isstruct(vc)
for i=1:2:numel(varargin)
vc.(varargin{i}) = varargin{i+1};
end
return;
end
if iscell(vc)
for i=1:numel(vc)
try
set(vc{i}, varargin{:});
catch
end
end
elseif numel(vc)>1
for i=1:numel(vc)
try
set(vc(i), varargin{:});
catch
end
end
else
try
set(vc, varargin{:});
catch
end
end
end %func
%--------------------------------------------------------------------------
function clear_cache_()
trial_fixsync_();
end %func
%--------------------------------------------------------------------------
function [mov, vcFile_bin] = loadvid_(vcFile_vid, nSkip, fSave_bin)
% using the 2018a VideoReader
% Extracts red channel only
t1=tic;
if nargin<2, nSkip = []; end
if nargin<3, fSave_bin = []; end
if isempty(nSkip), nSkip = 1; end
if isempty(fSave_bin), fSave_bin = 1; end
fFast = 0; %subsampling instead of averaging the pixels
try
vidobj = VideoReader(vcFile_vid);
catch
[dimm, mov] = deal([]);
return;
end
% vidInfo = mmfileinfo(vcFile_vid);
% vidInfo.Duration;
fprintf('Loading video: %s\n', vcFile_vid);
vidHeight = floor(vidobj.Height / nSkip);
vidWidth = floor(vidobj.Width / nSkip);
% check cache
vcFile_bin = sprintf('%s_mov%dx%d.bin', vcFile_vid, vidHeight, vidWidth);
mov = loadvid_bin_(vcFile_bin);
if ~isempty(mov)
dimm = size(mov);
fprintf('\tLoaded from %s (%d frames), took %0.1fs\n', vcFile_bin, size(mov,3), toc(t1));
return;
end
nFrames_est = round(vidobj.Duration * vidobj.FrameRate);
mov = zeros(vidHeight, vidWidth, nFrames_est, 'uint8');
fTrim = (vidHeight * nSkip) < vidobj.Height || (vidWidth * nSkip) < vidobj.Width;
iFrame = 0;
while hasFrame(vidobj)
iFrame = iFrame + 1;
img_ = readFrame(vidobj);
if fFast
mov(:,:,iFrame) = img_(1:nSkip:vidHeight*nSkip, 1:nSkip:vidWidth*nSkip, 1);
continue;
end
img_ = img_(:,:,1); % red extraction
if nSkip>1
if fTrim
img_ = img_(1:(vidHeight*nSkip), 1:(vidWidth*nSkip));
end
img_ = sum(uint16(reshape(img_, nSkip, [])));
img_ = sum(permute(reshape(img_, vidHeight, nSkip, vidWidth), [2,1,3]));
img_ = reshape(uint8(img_/(nSkip^2)), vidHeight, vidWidth);
end
mov(:,:,iFrame) = img_;
end
nFrames = iFrame;
dimm = [vidHeight, vidWidth, nFrames];
if nFrames < nFrames_est
mov = mov(:,:,1:nFrames); %trim
end
% bulk save
if fSave_bin
try
fid_w = fopen(vcFile_bin, 'w');
fwrite(fid_w, mov, class(mov));
fclose(fid_w);
fprintf('\twrote to %s (%d frames), took %0.1fs\n', vcFile_bin, size(mov,3), toc(t1));
catch
;
end
else
fprintf('\tLoaded %d frames, took %0.1fs\n', size(mov,3), toc(t1));
end
end %func
%--------------------------------------------------------------------------
function mov = loadvid_bin_(vcFile_bin)
% vcFile_bin: string format: vidfile_mov%dx%d.bin (wxh)
mov=[];
if ~exist_file_(vcFile_bin), return; end
vcFormat = regexpi(vcFile_bin, '_mov(\d+)[x](\d+)[.]bin$', 'match');
if isempty(vcFormat), return; end % invalid format
try
vcFormat = strrep(strrep(vcFormat{1}, '_mov', ''), '.bin', '');
dimm = sscanf(vcFormat, '%dx%d');
[height, width] = deal(dimm(1), dimm(2));
nBytes_file = filesize_(vcFile_bin);
dimm(3) = floor(nBytes_file/height/width);
fid = fopen(vcFile_bin, 'r');
mov = fread_(fid, dimm, 'uint8');
fclose(fid);
catch
return;
end
end %func
%--------------------------------------------------------------------------
function mnWav1 = fread_(fid_bin, dimm_wav, vcDataType)
% Get around fread bug (matlab) where built-in fread resize doesn't work
dimm_wav = dimm_wav(:)';
try
if isempty(dimm_wav)
mnWav1 = fread(fid_bin, inf, ['*', vcDataType]);
else
if numel(dimm_wav)==1, dimm_wav = [dimm_wav, 1]; end
mnWav1 = fread(fid_bin, prod(dimm_wav), ['*', vcDataType]);
if numel(mnWav1) == prod(dimm_wav)
mnWav1 = reshape(mnWav1, dimm_wav);
else
dimm2 = floor(numel(mnWav1) / dimm_wav(1));
if dimm2 >= 1
mnWav1 = reshape(mnWav1, dimm_wav(1), dimm2);
else
mnWav1 = [];
end
end
end
catch
disperr_();
end
end %func
%--------------------------------------------------------------------------
% Return [] if multiple files are found
function nBytes = filesize_(vcFile)
S_dir = dir(vcFile);
if numel(S_dir) ~= 1
nBytes = [];
else
nBytes = S_dir(1).bytes;
end
end %func
%--------------------------------------------------------------------------
function [S_trialset, trFps] = trialset_fixfps_(vcFile_trialset)
% It loads the files
% iData: 1, ang: -0.946 deg, pixpercm: 7.252, x0: 793.2, y0: 599.2
% run S141106_LearningCurve_Control.m first cell
fFix_sync = 1;
S_trialset = load_trialset_(vcFile_trialset);
% [pixpercm, angXaxis] = struct_get_(S_trialset.P, 'pixpercm', 'angXaxis');
[tiImg, vcType_uniq, vcAnimal_uniq, viImg, csFiles_Track] = ...
struct_get_(S_trialset, 'tiImg', 'vcType_uniq', 'vcAnimal_uniq', 'viImg', 'csFiles_Track');
hMsg = msgbox('Analyzing... (This closes automatically)');
t1=tic;
trFps = nan(size(tiImg));
for iTrial = 1:numel(viImg)
try
clear_cache_();
S_ = load(csFiles_Track{iTrial}, 'TC', 'XC', 'YC', 'xy0', 'vidFname', 'FPS', 'img0', 'ADCTS', 'FLIM');
S_.vcFile_Track = csFiles_Track{iTrial};
if fFix_sync, S_ = trial_fixsync_(S_, 0); end
iImg_ = viImg(iTrial);
trFps(iImg_) = get_set_(S_, 'FPS', nan);
fprintf('\n');
catch
disp(csFiles_Track{iTrial});
end
end %for
fprintf('\n\ttook %0.1fs\n', toc(t1));
close_(hMsg);
if nargout==0
hFig = plot_trialset_img_(S_trialset, trFps);
set(hFig, 'Name', sprintf('FPS: %s', vcFile_trialset));
end
end %func
%--------------------------------------------------------------------------
% 8/9/2018 JJJ: copied from irc.m
function varargout = get0_(varargin)
% returns get(0, 'UserData') to the workspace
% [S0, P] = get0_();
S0 = get(0, 'UserData');
if nargin==0
if nargout==0
assignWorkspace_(S0);
else
varargout{1} = S0;
end
else
for iArg=1:nargin
try
eval(sprintf('%s = S0.%s;', varargin{iArg}, varargin{iArg}));
varargout{iArg} = S0.(varargin{iArg});
catch
varargout{iArg} = [];
end
end
end
end %func
%--------------------------------------------------------------------------
% 8/9/2018 JJJ: copied from irc.m
function S0 = set0_(varargin)
S0 = get(0, 'UserData');
for i=1:nargin
try
S0.(inputname(i)) = varargin{i};
catch
disperr_();
end
end
set(0, 'UserData', S0);
end %func
%--------------------------------------------------------------------------
function mov = loadvid_preview_(vcFile_vid, viFrames)
if nargin<2, viFrames = []; end
if ~ischar(vcFile_vid)
vcFile_vid = fullfile(vcFile_vid.Path, vcFile_vid.Name);
end
P = load_cfg_();
mov = loadvid_(vcFile_vid, get_set_(P, 'nSkip_vid', 4));
if ~isempty(viFrames), mov = mov(:,:,viFrames); end
end %func
%--------------------------------------------------------------------------
function handles = trial_sync_(handles)
[handles.S_sync, mov] = calc_sync_(handles);
[vrT_adc, viT_cam] = struct_get_(handles.S_sync, 'vrT_adc', 'viT_cam');
handles.TLIM0 = vrT_adc([1, end]);
handles.FLIM0 = viT_cam([1, end]);
handles.FPS = diff(handles.FLIM0) / diff(handles.TLIM0);
% plot sync
[~, hFig] = trial_fixsync_(handles, 2);
msgbox({'Close the figure after checking the sync.', 'Press PageUp/PageDown/Left/Right to navigate'});
uiwait(hFig);
vcAns = questdlg('Synchronized correctly?');
if strcmpi(vcAns, 'Yes')
set(handles.btnBackground, 'Enable', 'on');
else
set(handles.btnBackground, 'Enable', 'off');
end
end %func
%--------------------------------------------------------------------------
function trialset_import_track_(vcFile_trialset)
% Find destination
S_trialset = load_trialset_(vcFile_trialset);
if isempty(S_trialset), errordlg('No trials exist', vcFile_trialset); return; end
vcVidExt = get_set_(S_trialset.P, 'vcVidExt');
[csFiles_vid, csDir_vid] = find_files_(S_trialset.vcDir, ['*', vcVidExt]);
% ask from where
vcDir_copyfrom = fileparts(S_trialset.vcDir);
vcDir_copyfrom = uigetdir(vcDir_copyfrom, 'Select a folder to copy from');
if ~ischar(vcDir_copyfrom), return; end
csFiles_Track = find_files_(vcDir_copyfrom, '*_Track.mat');
if isempty(csFiles_Track), return; end
fprintf('Copying %d files\n', numel(csFiles_Track));
nCopied = 0;
for iFile_Track = 1:numel(csFiles_Track)
try
vcFile_from_ = csFiles_Track{iFile_Track};
[~,vcFile_to_,~] = fileparts(vcFile_from_);
vcFile_to_ = cellstr_find_(csFiles_vid, strrep(vcFile_to_, '_Track', vcVidExt));
vcFile_to_ = strrep(vcFile_to_, vcVidExt, '_Track.mat');
copyfile(vcFile_from_, vcFile_to_, 'f');
fprintf('\tCopying %s to %s\n', vcFile_from_, vcFile_to_);
nCopied = nCopied + 1;
catch
fprintf(2, '\tCopy error: %s to %s\n', vcFile_from_, vcFile_to_);
end
end %for
fprintf('\t%d/%d copied\n', nCopied, numel(csFiles_Track));
end %func
%--------------------------------------------------------------------------
function vc_match = cellstr_find_(csFrom, vcFind)
cs = cellfun(@(vcFrom)regexpi(vcFrom, vcFind, 'match'), csFrom, 'UniformOutput', 0);
iFind = find(~cellfun(@isempty, cs));
if isempty(iFind)
vc_match = [];
else
vc_match = csFrom{iFind(1)};
end
end %func
%--------------------------------------------------------------------------
function trialset_googlesheet_(vcFile_trialset)
S_trialset = load_trialset_(vcFile_trialset);
vcLink_googlesheet = get_(S_trialset, 'vcLink_googlesheet');
if isempty(vcLink_googlesheet)
fprintf('"vcLink_googlesheet" is not set in %d\n', vcArg1);
else
web_(vcLink_googlesheet);
end
end %func
%--------------------------------------------------------------------------
function prefix = getSpike2Prefix_(S)
prefix = fields(S);
prefix = prefix{1};
k = strfind(prefix, '_Ch');
k=k(end);
prefix = prefix(1:k-1);
end %func
%--------------------------------------------------------------------------
function flag = matchFileEnd_(vcFile, vcEnd)
flag = ~isempty(regexpi(vcFile, [vcEnd, '$']));
end %func
%--------------------------------------------------------------------------
function flag = strmatch_start_(vcFile, vcStart)
flag = ~isempty(regexpi(vcFile, ['^', vcEnd]));
end %func
%--------------------------------------------------------------------------
function cmr = cellstruct_get_(cS, vcName)
cmr = cell(size(cS));
for i=1:numel(cS)
try
cmr{i} = cS{i}.(vcName);
catch
end
end
end %func
%--------------------------------------------------------------------------
function trialset_load_(vcFile)
% Usage
% -----
% trialset_load_(myfile_trialset.mat)
% trialset_load_(myfile.trialset)
trialset_coordinates_(vcFile);
% % Load trial info
% if matchFileEnd_(vcFile, '.trialset')
% vcFile_trialset_mat = strrep(vcFile, '.trialset', '_trialset.mat');
% elseif matchFileEnd_(vcFile, '_trialset.mat')
% vcFile_trialset_mat = vcFile;
% else
% fprintf(2, 'Must provide .trialset file or _trialset.mat file');
% return;
% end
% cS_trial = load_mat_(vcFile_trialset_mat, 'cS_trial');
% cmrPos_shape = cellstruct_get_(cS_trial, 'mrPos_shape');
% [csDataID, viAnimal, vlProbe] = getDataID_cS_(cS_trial);
% plot shapes
% [csDataID, S_info] = get_dataid_(cellstruct_get_(cS_trial, 'vidFname'));
% vlFilled = cellfun(@(x)all(any(isnan(x),2)), cmrPos_shape)
% mrPos_all = cell2mat(cellfun(@(x)x(:), cmrPos_shape, 'UniformOutput', 0));
end %func
|
github
|
jamesjun/vistrack-master
|
plotAll.m
|
.m
|
vistrack-master/plotAll.m
| 4,148 |
utf_8
|
94238f7577558d1809a95ef0fbd2995a
|
function plotAll(csTrials, csCmd, viZone, csX, nCols)
% csCmd: pair: command, ylabel
% iZone: optional. default 1
% csX: optional. default: {E,L,P}
% pair: condition, XTickLabel
vcAnimal = 'o^sd'; %animal's shape
vcPhase = 'rbg';
csLine = ':';
mrMean = zeros(4,3);
mrSem = zeros(4,3);
if nargin < 3
viZone = 1;
strZone = '';
end
if isempty(viZone)
viZone = 1;
end
if nargin < 4
csX = [];
end
if nargin < 5
nCols = [];
end
nPlot = size(csCmd,1);
if numel(viZone) ~= nPlot
viZone = ones(nPlot,1) * viZone(1);
end
vlDep = @(S)(S.vrD1 <= 3 & differentiate3(S.vrD1) > 0) |...
(S.vrD2 <= 3 & differentiate3(S.vrD2) > 0) |...
(S.vrD3 <= 3 & differentiate3(S.vrD3) > 0) |...
(S.vrD4 <= 3 & differentiate3(S.vrD4) > 0);
vlApp = @(S)(S.vrD1 <= 3 & differentiate3(S.vrD1) < 0) |...
(S.vrD2 <= 3 & differentiate3(S.vrD2) < 0) |...
(S.vrD3 <= 3 & differentiate3(S.vrD3) < 0) |...
(S.vrD4 <= 3 & differentiate3(S.vrD4) < 0);
nansem = @(x)nanstd(x) / sqrt(sum(~isnan(x)));
nPlot = size(csCmd,1);
switch size(csCmd,2)
case 2
fun1 = @(x)nanmean(x);
fun2 = @(x)nansem(x);
case 3
fun1 = [];
fun2 = @(x)nansem(x);
end
if isempty(nCols)
nCols = size(csCmd, 1);
end
nRows = ceil(nPlot/nCols);
nAnimals = numel(vcAnimal);
if isempty(csX)
nX = numel(csTrials);
csXstr = {'E', 'L', 'P'};
elseif min(size(csX)) == 1
csXstr = csX;
nX = numel(csX);
csX = [];
else
nX = size(csX, 1);
csXstr = csX(:,2);
end
vrX = 1:nX;
figure;
for iCmd=1:nPlot
subplot(nRows, nCols, iCmd); hold on;
strCmd = csCmd{iCmd,1};
if size(csCmd,2) >= 3
eval(sprintf('fun1 = %s;', csCmd{iCmd,3}));
end
if size(csCmd,2) >= 4
eval(sprintf('fun2 = %s;', csCmd{iCmd,4}));
end
mrY = zeros(nAnimals, nX);
mrE = zeros(nAnimals, nX);
for iPhase = 1:numel(csTrials)
vsTrialPool = csTrials{iPhase};
for iAnimal = 1:nAnimals
if ~isempty(strfind(strCmd, 'RS'))
RS = poolTrials_RS(vsTrialPool, iAnimal, [], viZone(iCmd));
[vlZ0, strZone] = getZone(RS, viZone(iCmd));
elseif ~isempty(strfind(strCmd, 'IPI'))
IPI = poolTrials_IPI(vsTrialPool, iAnimal, [], viZone(iCmd));
[vlZ0, strZone] = getZone(IPI, viZone(iCmd));
else
error('%s not found', strCmd);
end
eval(sprintf('vrZ = %s;', strCmd));
if ~isempty(csX)
for iX=1:nX
eval(sprintf('vlZ = vlZ0 & %s;', csX{iX,1}));
[vrY(iX), vrE(iX)] = calcZstats(vrZ, vlZ, fun1, fun2);
end
else
[mrY(iAnimal,iPhase), mrE(iAnimal,iPhase)] = ...
calcZstats(vrZ, vlZ0, fun1, fun2);
end
%plot here
if ~isempty(csX)
errorbar(vrX, vrY, vrE, [vcPhase(iPhase), vcAnimal(iAnimal), csLine]);
end
end %iAnimal
end %iPhase
if isempty(csX)
for iAnimal=1:nAnimals
errorbar(vrX, mrY(iAnimal,:), mrE(iAnimal,:), ...
['k', vcAnimal(iAnimal), csLine]);
end
end
%plot
ylabel(csCmd{iCmd,2});
set(gca, 'XTick', 1:nX);
set(gca, 'XLim', [.5, nX+.5]);
set(gca, 'XTickLabel', csXstr);
end %for
suptitle(strZone);
end %func
function [v1, v2] = calcZstats(vrZ, vlZ, fun1, fun2)
% Zone filtering
if ~isempty(vlZ)
if min(size(vrZ)) > 1
vrZ1 = vrZ(:,1);
vrZ2 = vrZ(:,2);
vrZ = [vrZ1(vlZ), vrZ2(vlZ)];
elseif numel(vrZ) == numel(vlZ)
vrZ = vrZ(vlZ);
else
warning('vlZ not edited');
end
end
% compute stats
if nargin < 3 %MEAN
v1 = nanmean(vrZ);
else
v1 = fun1(vrZ);
end
if nargin < 4 %SEM
v2 = nanstd(vrZ) / sqrt(sum(~isnan(vrZ)));
else
v2 = fun2(vrZ);
end
end
|
github
|
jamesjun/vistrack-master
|
semcorr.m
|
.m
|
vistrack-master/semcorr.m
| 308 |
utf_8
|
01320eb8567e22c3cddc96fde0a5bbaa
|
function semc = semcorr(vr)
% sem based on correlation time
vr = vr(~isnan(vr));
sd = std(vr);
n = numel(vr) / corrTime(vr);
semc = sd / sqrt(n);
end
function tau = corrTime(vrX)
thresh = 1/exp(1);
vrC = xcorr(vrX - mean(vrX), 'coeff');
vrC = vrC(ceil(end/2):end);
tau = find(vrC < thresh, 1, 'first');
end
|
github
|
jamesjun/vistrack-master
|
plotAll_pooled.m
|
.m
|
vistrack-master/plotAll_pooled.m
| 3,983 |
utf_8
|
710272e9cba4738938be88a56d3d8eff
|
function plotAll_pooled(csTrials, csCmd, viZone, csX, nCols)
% csCmd: pair: command, ylabel
% iZone: optional. default 1
% csX: optional. default: {E,L,P}
% pair: condition, XTickLabel
vcPhase = 'rbg';
csLine = ':';
mrMean = zeros(4,3);
mrSem = zeros(4,3);
if nargin < 3
viZone = 1;
strZone = '';
end
if isempty(viZone)
viZone = 1;
end
if nargin < 4
csX = [];
end
if nargin < 5
nCols = [];
end
nPlot = size(csCmd,1);
if numel(viZone) ~= nPlot
viZone = ones(nPlot,1) * viZone(1);
end
vlDep = @(S)(S.vrD1 <= 3 & differentiate3(S.vrD1) > 0) |...
(S.vrD2 <= 3 & differentiate3(S.vrD2) > 0) |...
(S.vrD3 <= 3 & differentiate3(S.vrD3) > 0) |...
(S.vrD4 <= 3 & differentiate3(S.vrD4) > 0);
vlApp = @(S)(S.vrD1 <= 3 & differentiate3(S.vrD1) < 0) |...
(S.vrD2 <= 3 & differentiate3(S.vrD2) < 0) |...
(S.vrD3 <= 3 & differentiate3(S.vrD3) < 0) |...
(S.vrD4 <= 3 & differentiate3(S.vrD4) < 0);
nansem = @(x)nanstd(x) / sqrt(sum(~isnan(x)));
nPlot = size(csCmd,1);
switch size(csCmd,2)
case 2
fun1 = @(x)nanmean(x);
fun2 = @(x)nansem(x);
case 3
fun1 = [];
fun2 = @(x)nansem(x);
end
if isempty(nCols)
nCols = size(csCmd, 1);
end
nRows = ceil(nPlot/nCols);
nAnimals = 1;
if isempty(csX)
nX = numel(csTrials);
csXstr = {'E', 'L', 'P'};
elseif min(size(csX)) == 1
csXstr = csX;
nX = numel(csX);
csX = [];
else
nX = size(csX, 1);
csXstr = csX(:,2);
end
vrX = 1:nX;
figure;
AX = zeros(nPlot,1);
for iCmd=1:nPlot
subplot(nRows, nCols, iCmd); hold on;
strCmd = csCmd{iCmd,1};
if size(csCmd,2) >= 3
eval(sprintf('fun1 = %s;', csCmd{iCmd,3}));
end
if size(csCmd,2) >= 4
eval(sprintf('fun2 = %s;', csCmd{iCmd,4}));
end
mrY = zeros(nAnimals, nX);
mrE = zeros(nAnimals, nX);
for iPhase = 1:numel(csTrials)
vsTrialPool = csTrials{iPhase};
if ~isempty(strfind(strCmd, 'RS'))
RS = poolTrials_RS(vsTrialPool, [], [], viZone(iCmd));
[vlZ0, strZone] = getZone(RS, viZone(iCmd));
elseif ~isempty(strfind(strCmd, 'IPI'))
IPI = poolTrials_IPI(vsTrialPool, [], [], viZone(iCmd));
[vlZ0, strZone] = getZone(IPI, viZone(iCmd));
else
error('%s not found', strCmd);
end
eval(sprintf('vrZ = %s;', strCmd));
if ~isempty(csX)
for iX=1:nX
eval(sprintf('vlZ = vlZ0 & %s;', csX{iX,1}));
[vrY(iX), vrE(iX)] = calcZstats(vrZ, vlZ, fun1, fun2);
end
else
[mrY(iAnimal,iPhase), mrE(iAnimal,iPhase)] = ...
calcZstats(vrZ, vlZ0, fun1, fun2);
end
%plot here
if ~isempty(csX)
errorbar(vrX, vrY, vrE, [vcPhase(iPhase), vcAnimal(iAnimal), csLine]);
end
end %iPhase
if isempty(csX)
for iAnimal=1:nAnimals
errorbar(vrX, mrY(iAnimal,:), mrE(iAnimal,:), ...
['k', vcAnimal(iAnimal), csLine]);
end
end
%plot
ylabel(csCmd{iCmd,2});
set(gca, 'XTick', 1:nX);
set(gca, 'XLim', [.5, nX+.5]);
set(gca, 'XTickLabel', csXstr);
AX(iCmd) = gca;
end %for
set(gcf, 'Name', strZone);
linkaxes(AX, 'xy');
end %func
function [v1, v2] = calcZstats(vrZ, vlZ, fun1, fun2)
% Zone filtering
if ~isempty(vlZ)
if min(size(vrZ)) > 1
vrZ1 = vrZ(:,1);
vrZ2 = vrZ(:,2);
vrZ = [vrZ1(vlZ), vrZ2(vlZ)];
elseif numel(vrZ) == numel(vlZ)
vrZ = vrZ(vlZ);
else
warning('vlZ not edited');
end
end
% compute stats
if nargin < 3 %MEAN
v1 = nanmean(vrZ);
else
v1 = fun1(vrZ);
end
if nargin < 4 %SEM
v2 = nanstd(vrZ) / sqrt(sum(~isnan(vrZ)));
else
v2 = fun2(vrZ);
end
end
|
github
|
jamesjun/vistrack-master
|
delete_empty_files.m
|
.m
|
vistrack-master/delete_empty_files.m
| 715 |
utf_8
|
92ed2cb4e4d9a756a8faa526079062f5
|
function delete_empty_files(vcDir)
if nargin<1, vcDir=[]; end
delete_files_(find_empty_files_(vcDir));
end %func
function csFiles = find_empty_files_(vcDir)
% find files with 0 bytes
if nargin==0, vcDir = []; end
if isempty(vcDir), vcDir = pwd(); end
vS_dir = dir(vcDir);
viFile = find([vS_dir.bytes] == 0 & ~[vS_dir.isdir]);
csFiles = {vS_dir(viFile).name};
csFiles = cellfun(@(vc)[vcDir, filesep(), vc], csFiles, 'UniformOutput', 0);
end %func
function delete_files_(csFiles)
for iFile = 1:numel(csFiles)
try
if exist(csFiles{iFile}, 'file')
delete(csFiles{iFile});
fprintf('\tdeleted %s.\n', csFiles{iFile});
end
catch
disperr_();
end
end
end %func
|
github
|
jamesjun/vistrack-master
|
plotAnimals.m
|
.m
|
vistrack-master/plotAnimals.m
| 4,347 |
utf_8
|
ddb97126edb10da86acc2d8a550cdbd9
|
function [AX, AX1, cvZ] = plotAnimals(vsTrialPool_E, vsTrialPool_L, vsTrialPool_P, strVar, fun1, strY)
% cvZ: cell of animal, zone, phase
% plot correlatoin coefficient
csPhase = {'E', 'L', 'P'};
csPhaseColor = {'r', 'b', 'g'};
csDiffColor = {'m', 'c'};
csAnimal = {'All', 'A', 'B', 'C', 'D'};
csZone = {'AZ', 'LM', 'NF', 'F'};
mrMean = zeros(4,3);
mrSem = zeros(4,3);
vlDep = @(S)(S.vrD1 <= 3 & differentiate3(S.vrD1) > 0) |...
(S.vrD2 <= 3 & differentiate3(S.vrD2) > 0) |...
(S.vrD3 <= 3 & differentiate3(S.vrD3) > 0) |...
(S.vrD4 <= 3 & differentiate3(S.vrD4) > 0);
vlApp = @(S)(S.vrD1 <= 3 & differentiate3(S.vrD1) < 0) |...
(S.vrD2 <= 3 & differentiate3(S.vrD2) < 0) |...
(S.vrD3 <= 3 & differentiate3(S.vrD3) < 0) |...
(S.vrD4 <= 3 & differentiate3(S.vrD4) < 0);
if nargin < 5
fun1 = [];
end
if isempty(fun1)
fun1 = @(x)nanmean(x);
% fun2 = @(x)nanstd(x);
fun2 = @(x)nanstd(x) / sqrt(numel(x)); %sem
else
fun2 = @(x)0;
end
if nargin < 6
strY = strVar;
end
figure;
% suptitle([strVar ', ' func2str(fun1)]);
%-------------------
% Plot per animal stats
AX = []; %individual bars
AX1 = []; %change bars
cvZ = cell(numel(csAnimal), numel(csZone), numel(csPhase));
for iAnimal = 1:numel(csAnimal)
%----------------------------------------------
% Plot bars per phase
subplot(2,5,iAnimal);
for iZone = 1:numel(csZone);
for iPhase = 1:numel(csPhase)
eval(sprintf('vsTrialPool = vsTrialPool_%s;', csPhase{iPhase}));
lim = [];
% if iPhase == 3
% lim = [1, 60*2*100]; %limit duration length
% end
%Load var
if ~isempty(strfind(strVar, 'RS.'))
RS = poolTrials_RS(vsTrialPool, iAnimal-1, lim);
vlZ = getZone(RS, iZone);
elseif ~isempty(strfind(strVar, 'IPI.'))
IPI = poolTrials_IPI(vsTrialPool, iAnimal-1, lim);
vlZ = getZone(IPI, iZone);
else
error('%s not found', strVar);
end
eval(sprintf('vrZ = %s;', strVar));
% Zone filtering
if min(size(vrZ)) > 1
vrZ1 = vrZ(:,1);
vrZ2 = vrZ(:,2);
vrZ = [vrZ1(vlZ), vrZ2(vlZ)];
elseif numel(vrZ) == numel(vlZ)
vrZ = vrZ(vlZ);
else
disp('not edited');
end
% compute stats
mrMean(iZone, iPhase) = fun1(vrZ);
mrSem(iZone, iPhase) = fun2(vrZ);
cvZ{iAnimal, iZone, iPhase} = vrZ;
end
end
plotBarError(mrMean, mrSem, csPhaseColor, csZone);
AX(end+1) = gca;
if iAnimal > 1
set(gca, 'YTick', []);
else
mrMean0 = mrMean;
end
title(csAnimal{iAnimal});
bar(mrMean0, 1, 'FaceColor', 'none', 'EdgeColor', 'k');
%----------------------------------------------
% Plot differential
subplot(2,5,iAnimal + 5);
mrMeanA = [mrMean(:,2) - mrMean(:,1), mrMean(:,3) - mrMean(:,2)];
mrMeanB = [mrMean(:,2) + mrMean(:,1), mrMean(:,3) + mrMean(:,2)]/2;
mrMean = mrMeanA./mrMeanB * 100;
plotBarError(mrMean, [], csDiffColor, csZone);
AX1(end+1) = gca;
if iAnimal > 1
set(gca, 'YTick', []);
else
mrMean1 = mrMean;
end
bar(mrMean1, 1, 'FaceColor', 'none', 'EdgeColor', 'k');
end %for
linkaxes(AX);
linkaxes(AX1);
ylabel(AX1(1), '% change');
ylabel(AX(1), strY);
set(AX(1), 'XLim', [1.5 3.5]);
set(AX1(1), 'XLim', [1.5 3.5]);
end %func
function [vlZone, strZone] = getZone(S, iZone)
vlNF = S.vrDf < 14 & S.vrDf >= 3;
vlLM = S.vrD1 < 3 | S.vrD2 < 3 | S.vrD3 < 3 | S.vrD4 < 3;
vlF = S.vrDf < 3;
switch (iZone)
case 1 %all
% vlZone = S.tvlZone & ~vlNF & ~vlLM & ~vlF;
% vlZone = S.vlZone & ~vlLM & ~vlF;
vlZone = S.vlZone;
strZone = 'AZ';
case 2 %LM
vlZone = vlLM;
strZone = 'LM<3';
case 3 %Fc<15
vlZone = vlNF;
strZone = 'Fc4~15';
case 4 %F<3
vlZone = vlF;
strZone = 'F<3';
end
vlZone = vlZone(:);
end %func
|
github
|
jamesjun/vistrack-master
|
file2struct.m
|
.m
|
vistrack-master/file2struct.m
| 2,959 |
utf_8
|
4c6f8fed62b505c3807c064499fbc400
|
% James Jun
% 7/19/2018: Can pass cell strings to evaluate
% 2017 May 23
% Run a text file as .m script and result saved to a struct P
% _prm and _prb can now be called .prm and .prb files
function S_file2struct = file2struct(vcFile_file2struct)
% S_file2struct = file2struct(vcFile_txt)
% S_file2struct = file2struct(csLines)
S_file2struct = [];
if iscell(vcFile_file2struct)
csLines_file2struct = vcFile_file2struct;
vcFile_file2struct = '';
else % file name is passed
if ~exist_file_(vcFile_file2struct), return; end
csLines_file2struct = file2lines_(vcFile_file2struct);
end
csLines_file2struct = strip_comments_(csLines_file2struct);
if isempty(csLines_file2struct), return; end
S_file2struct = struct();
try
eval(cell2mat(csLines_file2struct'));
S_ws = whos();
csVars = {S_ws.name};
csVars = setdiff(csVars, {'csLines_file2struct', 'vcFile_file2struct', 'S_file2struct'});
for i=1:numel(csVars)
eval(sprintf('a = %s;', csVars{i}));
S_file2struct.(csVars{i}) = a;
end
catch
fprintf(2, 'Error in %s:\n\t', vcFile_file2struct);
fprintf(2, '%s\n', lasterr());
S_file2struct=[];
end
end %func
%--------------------------------------------------------------------------
% 9/26/17 JJJ: Created and tested
function flag = exist_file_(vcFile, fVerbose)
% Different from exist(vcFile, 'file') which uses search path
if nargin<2, fVerbose = 0; end
if isempty(vcFile)
flag = 0;
else
flag = ~isempty(dir(vcFile));
end
if fVerbose && ~flag
fprintf(2, 'File does not exist: %s\n', vcFile);
end
end %func
%--------------------------------------------------------------------------
% Strip comments from cell string
% 7/24/17 JJJ: Code cleanup
function csLines = strip_comments_(csLines)
csLines = csLines(cellfun(@(x)~isempty(x), csLines));
csLines = cellfun(@(x)strtrim(x), csLines, 'UniformOutput', 0);
csLines = csLines(cellfun(@(x)x(1)~='%', csLines));
% remove comments in the middle
for i=1:numel(csLines)
vcLine1 = csLines{i};
iComment = find(vcLine1=='%', 1, 'first');
if ~isempty(iComment)
vcLine1 = vcLine1(1:iComment-1);
end
vcLine1 = strrep(vcLine1, '...', '');
if ismember(strsplit(vcLine1), {'for', 'end', 'if'})
csLines{i} = [strtrim(vcLine1), ', ']; %add blank at the end
else
csLines{i} = [strtrim(vcLine1), ' ']; %add blank at the end
end
end
% csLines = cellfun(@(x)strtrim(x), csLines, 'UniformOutput', 0);
csLines = csLines(cellfun(@(x)~isempty(x), csLines));
end %func
%--------------------------------------------------------------------------
% Read a text file and output cell strings separated by new lines
% 7/24/17 JJJ: Code cleanup
function csLines = file2lines_(vcFile_file2struct)
csLines = {};
if ~exist_file_(vcFile_file2struct, 1), return; end
fid = fopen(vcFile_file2struct, 'r');
csLines = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
csLines = csLines{1};
end %func
|
github
|
jamesjun/vistrack-master
|
trackFish.m
|
.m
|
vistrack-master/trackFish.m
| 11,490 |
utf_8
|
be76bcc7d067cac5471e3806dc0cd88b
|
function [XC, YC, AC, Area, S, MOV, XC_off, YC_off] = trackFish(S, FLIM)
% S.{AreaTarget, ThreshLim, img0, fShow, vec0, thresh, WINPOS}
% AC: degree unit
% XC, YC: pixel unit
MEMLIM = 300; %number of frames to load to memory at a time
nRetry = 3; %number of retries for loading a video file
% Parse input variables
WINPOS = S.WINPOS;
vecPrev = S.vec0;
thresh = S.thresh;
nframes = diff(FLIM) + 1;
% Allocate output arrays
XC = nan(nframes,6);
YC = nan(nframes,6);
AC = nan(nframes,5);
Area = nan(nframes,1);
height = diff(WINPOS([3 4])) + 1;
width = diff(WINPOS([1 2])) + 1;
MOV = zeros(height, width, nframes, 'uint8');
XC_off = nan(nframes, 1);
YC_off = nan(nframes, 1);
if nargin < 2
FLIM = [1 S.vidobj.NumberOfFrames];
end
% Call itself recursively if the number of frames is over the memory limit
if nframes > MEMLIM
for iF=FLIM(1):MEMLIM:FLIM(2)
FLIM1 = [iF, iF+MEMLIM-1];
FLIM1(2) = min(FLIM1(2), FLIM(2));
LLIM1 = FLIM1 - FLIM(1) + 1;
L = LLIM1(1):LLIM1(2);
try
[XC(L,:), YC(L,:), AC(L,:), Area(L,:), S1, MOV(:,:,L), XC_off(L), YC_off(L)] ...
= trackFish(S, FLIM1);
catch
disperr();
end
S = S1;
end
return;
end
tic; %start the timer
% Load video frames to the memory
for itry=1:nRetry
try
h=msgbox(sprintf('Tracking frames %d ~ %d... (close to cancel)', FLIM(1), FLIM(2)));
IMG = read(S.vidobj, FLIM);
% IMG = IMG(:,:,1,:); %use red channel only
try close(h);
catch, error('Cancelled by user'); end;
break;
catch
disp(lasterr);
fprintf('failed to load %d times. reloading...\n', itry);
S.vidobj = VideoReader(S.vidFname);
end
end
if itry == nRetry
error('video load failure');
end
if S.fShow
hfig = figure;
end
% Process each frame
[hAx, hImg, hPlot1, hPlot2] = deal([]);
BWprev=[]; BWprev1=[];
for iF=1:nframes
[img, dimg, dimg1] = getFrame_(IMG, iF, WINPOS, S.img0);
BW0 = (dimg(:,:,1) > thresh);
BW = imdilate(bwmorph(BW0, 'clean', inf), S.SE);
BW1 = BW;
iF1 = FLIM(1) + iF - S.FLIM(1);
regions = regionprops(BW, {'Area', 'Centroid', 'Orientation', 'FilledImage', 'BoundingBox'});
%remove blobs not touching the fish's blob from the prev. frame
if numel(regions) > 1
L = bwlabel(BW, 8);
if iF1<=10 % first frame, pick closest to the center
[iRegion] = region_nearest(regions, S.xy0 - WINPOS([1,3]));
regions = regions(iRegion);
BW = L==iRegion;
else
[iRegion] = region_largest(regions);
regions = regions(iRegion);
BW = L==iRegion;
end
end
%Isolate the largest blob
if isempty(regions)
BW=BWprev; % revert to the
regions = regionprops(BW, {'Area', 'Centroid', 'Orientation', 'FilledImage', 'BoundingBox'});
stats = largestBlob_(regions);
else
stats = regions;
end
ang = -stats.Orientation;
area = stats.Area;
xy_cm = stats.Centroid;
%Check for the orientation flip
vec = [cos(deg2rad(ang)), sin(deg2rad(ang))];
if dot(vec, vecPrev) < 0
ang = mod(ang + 180, 360);
if ang>180, ang=ang-360; end
vec = [cos(deg2rad(ang)), sin(deg2rad(ang))];
stats.Orientation = -ang;
end
%Compute posture
try
[XY, ANG, xy_names, ang_names] = blobPosture(stats);
catch
img1 = img;
img1(bwperim(BW)) = 255;
figure(101); imshow(img1); title('Blob processing error'); drawnow;
fprintf(2, 'Blob processing error\n'); continue;
end
%Display output
if S.fShow
img1 = img;
img1(bwperim(BW)) = 255;
try
delete(hPlot1);
delete(hPlot2);
catch
end
if isempty(hImg)
figure(hfig);
hImg = imshow(img1);
hAx = gca;
else
set(hImg,'CData', img1);
end
hold on;
hPlot1 = plot(hAx, XY(2, 1), XY(2, 2), 'go', ...
XY(3:end, 1), XY(3:end, 2), 'mo', 'LineWidth', 2);
% interpolated curve
nxy = size(XY,1);
X1 = interp1(2:nxy, XY(2:end, 1), 2:.1:nxy, 'spline');
Y1 = interp1(2:nxy, XY(2:end, 2), 2:.1:nxy, 'spline');
hPlot2 = plot(hAx, X1, Y1, 'm-', XY(1,1), XY(1,2), 'g+', 'LineWidth', 2); %Mark the centroid
title(hAx, sprintf('Frame = %d', iF + FLIM(1) - 1));
drawnow;
end
%Save output
Area(iF) = area;
xy_off = [WINPOS(1), WINPOS(3)] - [1, 1];
XC(iF,:) = round(XY(:,1)' + xy_off(1));
YC(iF,:) = round(XY(:,2)' + xy_off(2));
AC(iF,:) = normAng(ANG');
MOV(:,:,iF) = img;
XC_off(iF) = xy_off(1);
YC_off(iF) = xy_off(2);
%Update the bounding box
% xy_center = xy_cm + xy_off;
xy_center = getMedian(XC(:,1), YC(:,1), iF); %fault tolerent
[WINPOS, ~] = getBoundingBoxPos(xy_center, size(S.img0), size(BW));
%adjust intensity threshold
if area > S.AreaTarget*1.1
thresh = min(thresh+1, S.ThreshLim(2));
elseif area < S.AreaTarget*.9
thresh = max(thresh-1, S.ThreshLim(1));
end
%next orientation vector
% vecPrev = vec;
vecPrev = getMedian(cos(deg2rad(AC(:,1))), sin(deg2rad(AC(:,1))), iF);
vecPrev = vecPrev ./ norm(vecPrev);
BWprev1 = BWprev;
BWprev = BW;
if isempty(BWprev1), BWprev1=BWprev; end
end %for
%Return the last iteration info
S.thresh = thresh;
S.vec0 = vec;
S.WINPOS = WINPOS;
S.xy_names = xy_names;
S.ang_names = ang_names;
%Measure the processing time
tdur = toc;
fprintf('Processed %0.1f images/sec, %s, Frames: [%d ~ %d]\n', ...
nframes/tdur, S.vidobj.Name, FLIM(1), FLIM(2));
try close(hfig); catch, end;
end %func
%--------------------------------------------------------------------------
function xy = getMedian(vrX, vrY, idx)
n = 5;
idxrng = [idx-n+1:idx];
idxrng(1) = max(idxrng(1), 1);
try
xy = [median(vrX(idxrng)), median(vrY(idxrng))];
catch
xy = [vrX(idx), vrY(idx)];
end
end
%--------------------------------------------------------------------------
function [img, dimg, dimg1] = getFrame_(IMG, iF, WINPOS, img0)
%GETFRAME Get image frame and crop and subtract the background
% [img] = getFrame(IMG, iF) %Obtain current frame from array of images
% [img] = getFrame(IMG, iF, WINPOS) %crops the image
% [img, dimg] = getFrame(IMG, iF, WINPOS, img0) %crop and subtract
% background
if nargin < 3
WINPOS = [1, size(IMG, 2), 1, size(IMG,1)];
end
img = IMG(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2), 1, iF);
% Calculate the intensity difference (background subtraction)
if nargout >= 2
img0c = img0(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2), :);
dimg = uint8_diff(img0c, img, 0);
if nargout>=3
dimg1 = uint8_diff(img0c, img, 1);
end
% dimg = img0(WINPOS(3):WINPOS(4), WINPOS(1):WINPOS(2)) - img;
end
img = uint8(single(mean(img,3)));
end %func
%--------------------------------------------------------------------------
%NORMANG Normalize the angle to range between -180 to 180 degrees
% [A] = normAng(A)
function A = normAng(A)
A = mod(A, 360);
A(A>180) = A(A>180) - 360;
end %func
%--------------------------------------------------------------------------
%LARGESTBLOB Return stats for the largest blob
% [stat, idx, area] = largestBlob(stats)
function [stat, idx, area] = largestBlob_(stats)
[area, idx] = max([stats.Area]);
stat = stats(idx);
end
%--------------------------------------------------------------------------
% Measure posture angle from a binary blob
function [XY, ANG, xy_names, ang_names] = blobPosture(stats)
BW0 = stats.FilledImage;
ang0 = -stats.Orientation; %counter-clockwise is positive in pixel
xy_ref = [stats.BoundingBox(1), stats.BoundingBox(2)];
xy_ref = round(xy_ref + [stats.BoundingBox(3), stats.BoundingBox(4)]/2);
xy_cm = stats.Centroid;
%Rotate original image (BW0) parallel to the major axis
% BWr = imrotate(BW0, ang0);
BWr = imdilate(imrotate(BW0, ang0), ones(3));
xy_r = round([size(BWr, 2), size(BWr, 1)]/2); %rotation center. use this as a reference
% stats_r = regionprops(BWr, 'Area', 'BoundingBox'); %have area for safety
% [~, idx] = max([stats_r.Area]);
% stats_r = stats_r(idx);
stats_r = largestBlob_(regionprops(BWr, 'BoundingBox', 'Area'));
% find head CM
BWh = BWr(1:end, xy_r(1):end);
% stats_h = largestBlob(regionprops(BWh, 'Orientation', 'Centroid', 'Image', 'Area'));
stats_h = largestBlob_(regionprops(BWh, 'Orientation', 'Centroid', 'Area'));
ang_h = -stats_h.Orientation;
xy_hm = round(stats_h.Centroid);
xy_hm(1) = xy_hm(1) + xy_r(1) - 1;
xy_hm(2) = median(find(BWr(:, xy_hm(1))));
% find tail CM
BWt = BWr(1:end, 1:xy_r(1));
% stats_t = largestBlob(regionprops(BWt, 'Orientation', 'Centroid', 'Image', 'Area'));
stats_t = largestBlob_(regionprops(BWt, 'Orientation', 'Centroid', 'Area'));
ang_t = -stats_t.Orientation;
xy_tm = round(stats_t.Centroid);
xy_tm(2) = median(find(BWr(:, xy_tm(1))));
%find middle points
xy_m = [xy_r(1), nan];
xy_m(2) = median(find(BWr(:, xy_r(1))));
%find tail tip
xy_t = [ceil(stats_r.BoundingBox(1)) , nan];
% xy_t(2) = find(BWr(:,xy_t(1)), 1, 'first');
xy_t(2) = median(find(BWr(:, xy_t(1))));
%find head tip
% xy_h = [floor(sum(stats_r.BoundingBox([1, 3]))) , nan];
% dx = xy_h(1) - xy_hm(1);
% xy_h(2) = round(dx * tan(deg2rad(ang_h)) + xy_hm(2));
% xy_h(2) = round(find(BWr(:,xy_h(1)), 1, 'first'));
%find head tip
BWrr = imrotate(BWr, ang_h);
stats_rr = largestBlob_(regionprops(BWrr, 'Orientation', 'BoundingBox', 'Area'));
xy_rr = [size(BWrr, 2), size(BWrr, 1)]/2; %rotation center. use this as a reference
xy_h = [floor(sum(stats_rr.BoundingBox([1, 3]))) , nan];
try
% xy_h(2) = median(find(BWrr(:, xy_hm(1))));
xy_h(2) = median(find(BWrr(:, xy_h(1))));
catch
disperr();
end
% xy_h(2) = round(median(find(BWrr(:, xy_h(1)))));
% compute angles
vec1 = xy_hm - xy_m;
vec2 = xy_m - xy_t;
ang_tb = rad2deg(atan2(vec2(2),vec2(1)) - atan2(vec1(2),vec1(1)));
%format output
ang_names = {'CoM', 'head-mid', 'tail-mid', 'body-bend', 'tail-bend'};
ANG = zeros(numel(ang_names), 1);
ANG(1) = ang0;
ANG(2) = ang_h + ang0;
ANG(3) = ang_t + ang0;
ANG(4) = ang_t - ang_h;
ANG(5) = ang_tb;
%compute positions
xy_r = [size(BWr, 2), size(BWr, 1)]/2; %do not round for higher precision
xy_names = {'CoM', 'head', 'head-mid', 'mid', 'tail-mid', 'tail'};
XY = zeros(numel(xy_names), 2);
XY(1,:) = xy_cm;
XY(2,:) = xy_ref + rotatexy(xy_h - xy_rr, ang0 + ang_h)';
XY(3,:) = xy_ref + rotatexy(xy_hm - xy_r, ang0)';
XY(4,:) = xy_ref + rotatexy(xy_m - xy_r, ang0)';
XY(5,:) = xy_ref + rotatexy(xy_tm - xy_r, ang0)';
XY(6,:) = xy_ref + rotatexy(xy_t - xy_r, ang0)';
end %func
%--------------------------------------------------------------------------
function [ xyp ] = rotatexy( xy, ang )
%ROTATEXY rotate a vector with respect to the origin, ang in degree
xy = xy(:);
CosA = cos(deg2rad(ang));
SinA = sin(deg2rad(ang));
M = [CosA, -SinA; SinA, CosA];
xyp = M * xy;
end
%--------------------------------------------------------------------------
function [ rad ] = deg2rad( deg )
%DEG2RAD convert an angle from degrees to radians
rad = deg / 180 * pi;
end
%--------------------------------------------------------------------------
function [ deg ] = rad2deg( rad )
%RAD2DEG convert an angle from radians to degrees
deg = rad / pi * 180;
end
|
github
|
g4idrijs/DeepLearnToolbox-master
|
myOctaveVersion.m
|
.m
|
DeepLearnToolbox-master/util/myOctaveVersion.m
| 169 |
utf_8
|
d4603482a968c496b66a4ed4e7c72471
|
% return OCTAVE_VERSION or 'undefined' as a string
function result = myOctaveVersion()
if isOctave()
result = OCTAVE_VERSION;
else
result = 'undefined';
end
|
github
|
g4idrijs/DeepLearnToolbox-master
|
isOctave.m
|
.m
|
DeepLearnToolbox-master/util/isOctave.m
| 108 |
utf_8
|
4695e8d7c4478e1e67733cca9903f9ef
|
%detects if we're running Octave
function result = isOctave()
result = exist('OCTAVE_VERSION') ~= 0;
end
|
github
|
g4idrijs/DeepLearnToolbox-master
|
makeLMfilters.m
|
.m
|
DeepLearnToolbox-master/util/makeLMfilters.m
| 1,895 |
utf_8
|
21950924882d8a0c49ab03ef0681b618
|
function F=makeLMfilters
% Returns the LML filter bank of size 49x49x48 in F. To convolve an
% image I with the filter bank you can either use the matlab function
% conv2, i.e. responses(:,:,i)=conv2(I,F(:,:,i),'valid'), or use the
% Fourier transform.
SUP=49; % Support of the largest filter (must be odd)
SCALEX=sqrt(2).^[1:3]; % Sigma_{x} for the oriented filters
NORIENT=6; % Number of orientations
NROTINV=12;
NBAR=length(SCALEX)*NORIENT;
NEDGE=length(SCALEX)*NORIENT;
NF=NBAR+NEDGE+NROTINV;
F=zeros(SUP,SUP,NF);
hsup=(SUP-1)/2;
[x,y]=meshgrid([-hsup:hsup],[hsup:-1:-hsup]);
orgpts=[x(:) y(:)]';
count=1;
for scale=1:length(SCALEX),
for orient=0:NORIENT-1,
angle=pi*orient/NORIENT; % Not 2pi as filters have symmetry
c=cos(angle);s=sin(angle);
rotpts=[c -s;s c]*orgpts;
F(:,:,count)=makefilter(SCALEX(scale),0,1,rotpts,SUP);
F(:,:,count+NEDGE)=makefilter(SCALEX(scale),0,2,rotpts,SUP);
count=count+1;
end;
end;
count=NBAR+NEDGE+1;
SCALES=sqrt(2).^[1:4];
for i=1:length(SCALES),
F(:,:,count)=normalise(fspecial('gaussian',SUP,SCALES(i)));
F(:,:,count+1)=normalise(fspecial('log',SUP,SCALES(i)));
F(:,:,count+2)=normalise(fspecial('log',SUP,3*SCALES(i)));
count=count+3;
end;
return
function f=makefilter(scale,phasex,phasey,pts,sup)
gx=gauss1d(3*scale,0,pts(1,:),phasex);
gy=gauss1d(scale,0,pts(2,:),phasey);
f=normalise(reshape(gx.*gy,sup,sup));
return
function g=gauss1d(sigma,mean,x,ord)
% Function to compute gaussian derivatives of order 0 <= ord < 3
% evaluated at x.
x=x-mean;num=x.*x;
variance=sigma^2;
denom=2*variance;
g=exp(-num/denom)/(pi*denom)^0.5;
switch ord,
case 1, g=-g.*(x/variance);
case 2, g=g.*((num-variance)/(variance^2));
end;
return
function f=normalise(f), f=f-mean(f(:)); f=f/sum(abs(f(:))); return
|
github
|
g4idrijs/DeepLearnToolbox-master
|
caenumgradcheck.m
|
.m
|
DeepLearnToolbox-master/CAE/caenumgradcheck.m
| 3,618 |
utf_8
|
6c481fc15ab7df32e0f476514100141a
|
function cae = caenumgradcheck(cae, x, y)
epsilon = 1e-4;
er = 1e-6;
disp('performing numerical gradient checking...')
for i = 1 : numel(cae.o)
p_cae = cae; p_cae.c{i} = p_cae.c{i} + epsilon;
m_cae = cae; m_cae.c{i} = m_cae.c{i} - epsilon;
[m_cae, p_cae] = caerun(m_cae, p_cae, x, y);
d = (p_cae.L - m_cae.L) / (2 * epsilon);
e = abs(d - cae.dc{i});
if e > er
disp('OUTPUT BIAS numerical gradient checking failed');
disp(e);
disp(d / cae.dc{i});
keyboard
end
end
for a = 1 : numel(cae.a)
p_cae = cae; p_cae.b{a} = p_cae.b{a} + epsilon;
m_cae = cae; m_cae.b{a} = m_cae.b{a} - epsilon;
[m_cae, p_cae] = caerun(m_cae, p_cae, x, y);
d = (p_cae.L - m_cae.L) / (2 * epsilon);
% cae.dok{i}{a}(u) = d;
e = abs(d - cae.db{a});
if e > er
disp('BIAS numerical gradient checking failed');
disp(e);
disp(d / cae.db{a});
keyboard
end
for i = 1 : numel(cae.o)
for u = 1 : numel(cae.ok{i}{a})
p_cae = cae; p_cae.ok{i}{a}(u) = p_cae.ok{i}{a}(u) + epsilon;
m_cae = cae; m_cae.ok{i}{a}(u) = m_cae.ok{i}{a}(u) - epsilon;
[m_cae, p_cae] = caerun(m_cae, p_cae, x, y);
d = (p_cae.L - m_cae.L) / (2 * epsilon);
% cae.dok{i}{a}(u) = d;
e = abs(d - cae.dok{i}{a}(u));
if e > er
disp('OUTPUT KERNEL numerical gradient checking failed');
disp(e);
disp(d / cae.dok{i}{a}(u));
% keyboard
end
end
end
for i = 1 : numel(cae.i)
for u = 1 : numel(cae.ik{i}{a})
p_cae = cae;
m_cae = cae;
p_cae.ik{i}{a}(u) = p_cae.ik{i}{a}(u) + epsilon;
m_cae.ik{i}{a}(u) = m_cae.ik{i}{a}(u) - epsilon;
[m_cae, p_cae] = caerun(m_cae, p_cae, x, y);
d = (p_cae.L - m_cae.L) / (2 * epsilon);
% cae.dik{i}{a}(u) = d;
e = abs(d - cae.dik{i}{a}(u));
if e > er
disp('INPUT KERNEL numerical gradient checking failed');
disp(e);
disp(d / cae.dik{i}{a}(u));
end
end
end
end
disp('done')
end
function [m_cae, p_cae] = caerun(m_cae, p_cae, x, y)
m_cae = caeup(m_cae, x); m_cae = caedown(m_cae); m_cae = caebp(m_cae, y);
p_cae = caeup(p_cae, x); p_cae = caedown(p_cae); p_cae = caebp(p_cae, y);
end
%function checknumgrad(cae,what,x,y)
% epsilon = 1e-4;
% er = 1e-9;
%
% for i = 1 : numel(eval(what))
% if iscell(eval(['cae.' what]))
% checknumgrad(cae,[what '{' num2str(i) '}'], x, y)
% else
% p_cae = cae;
% m_cae = cae;
% eval(['p_cae.' what '(' num2str(i) ')']) = eval([what '(' num2str(i) ')']) + epsilon;
% eval(['m_cae.' what '(' num2str(i) ')']) = eval([what '(' num2str(i) ')']) - epsilon;
%
% m_cae = caeff(m_cae, x); m_cae = caedown(m_cae); m_cae = caebp(m_cae, y);
% p_cae = caeff(p_cae, x); p_cae = caedown(p_cae); p_cae = caebp(p_cae, y);
%
% d = (p_cae.L - m_cae.L) / (2 * epsilon);
% e = abs(d - eval(['cae.d' what '(' num2str(i) ')']));
% if e > er
% error('numerical gradient checking failed');
% end
% end
% end
%
% end
|
github
|
pervadepyy/robust-initialization-rcpr-master
|
rcprTrain.m
|
.m
|
robust-initialization-rcpr-master/rcprTrain.m
| 6,314 |
utf_8
|
d65cc055a4566913791100b0b64fccb5
|
function [regModel,pAll] = rcprTrain( Is, pGt, varargin )
% Train multistage robust cascaded shape regressor
%
% USAGE
% [regModel,pAll] = rcprTrain( Is, pGt, varargin )
%
% INPUTS
% Is - cell(N,1) input images
% pGt - [NxR] ground truth shape for each image
% varargin - additional params (struct or name/value pairs)
% .model - [REQ] shape model
% .pStar - [] initial shape
% .posInit - [] known object position (e.g. tracking output)
% .T - [REQ] number of stages
% .L - [1] data augmentation factor
% .regPrm - [REQ] param struct for regTrain
% .ftrPrm - [REQ] param struct for shapeGt>ftrsGen
% .regModel - [Tx1] previously learned single stage shape regressors
% .pad - amount of padding around bbox
% .verbose - [0] method verbosity during training
% .initData - initialization parameters (see shapeGt>initTr)
%
% OUTPUTS
% regModel - learned multi stage shape regressor:
% .model - shape model
% .pStar - [1xR] average shape
% .pDstr - [NxR] ground truth shapes
% .T - number of stages
% .pGtN - [NxR] normalized ground truth shapes
% .th - threshold for occlusion detection
% .regs - [Tx1] struct containing learnt cascade of regressors
% .regInfo - [KxStot] regressors
% .ysFern - [2^MxR] fern bin averages
% .thrs - [Mx1] thresholds
% .fids - [2xM] features used
% .ftrPos - feature information
% .type - type of features
% .F - number of features
% .nChn - number of channels used
% .xs - [Fx3] features position
% .pids - obsolete
%
% pAll - shape estimation at each iteration T
%
% EXAMPLE
%
% See also demoRCPR, FULL_demoRCPR
%
% Copyright 2013 X.P. Burgos-Artizzu, P.Perona and Piotr Dollar.
% [xpburgos-at-gmail-dot-com]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see bsd.txt]
%
% Please cite our paper if you use the code:
% Robust face landmark estimation under occlusion,
% X.P. Burgos-Artizzu, P. Perona, P. Dollar (c)
% ICCV'13, Sydney, Australia
% get additional parameters and check dimensions
dfs={'model','REQ','pStar',[],'posInit',[],'T','REQ',...
'L',1,'regPrm','REQ','ftrPrm','REQ','regModel',[],...
'pad',10,'verbose',0,'initData',[]};
[model,pStar,posInit,T,L,regPrm,ftrPrm,regModel,pad,verbose,initD] = ...
getPrmDflt(varargin,dfs,1);
[regModel,pAll]=rcprTrain1(Is, pGt,model,pStar,posInit,...
T,L,regPrm,ftrPrm,regModel,pad,verbose,initD);
end
function [regModel,pAll]=rcprTrain1(Is, pGt,model,pStar,posInit,...
T,L,regPrm,ftrPrm,regModel,pad,verbose,initD)
% Initialize shape and assert correct image/ground truth format
if(isempty(initD))
[pCur,pGt,pGtN,pStar,imgIds,N,N1]=shapeGt('initTr',Is,pGt,...
model,pStar,posInit,L,pad);
else
pCur=initD.pCur;pGt=initD.pGt;pGtN=initD.pGtN;
pStar=initD.pStar;imgIds=initD.imgIds;N=initD.N;N1=initD.N1;
clear initD;
end
D=size(pGt,2);
% remaining initialization, possibly continue training from
% previous model
pAll = zeros(N1,D,T+1);
regs = repmat(struct('regInfo',[],'ftrPos',[]),T,1);
if(isempty(regModel)), t0=1; pAll(:,:,1)=pCur(1:N1,:);
else
t0=regModel.T+1; regs(1:regModel.T)=regModel.regs;
[~,pAll1]=cprApply(Is,regModel,'imgIds',imgIds,'pInit',pCur);
pAll(:,:,1:t0)=pAll1(1:N1,:,:); pCur=pAll1(:,:,end);
end
loss = mean(shapeGt('dist',model,pCur,pGt));
if(verbose),
fprintf(' t=%i/%i loss=%f ',t0-1,T,loss);
end
tStart = clock;%pCur_t=zeros(N,D,T+1);
bboxes=posInit(imgIds,:);
for t=t0:T
% get target value for shape
pTar = shapeGt('inverse',model,pCur,bboxes);
pTar = shapeGt('compose',model,pTar,pGt,bboxes);
if(ftrPrm.type>2)
ftrPos = shapeGt('ftrsGenDup',model,ftrPrm);
[ftrs,regPrm.occlD] = shapeGt('ftrsCompDup',...
model,pCur,Is,ftrPos,...
imgIds,pStar,posInit,regPrm.occlPrm);
else
ftrPos = shapeGt('ftrsGenIm',model,pStar,ftrPrm);
[ftrs,regPrm.occlD] = shapeGt('ftrsCompIm',...
model,pCur,Is,ftrPos,...
imgIds,pStar,posInit,regPrm.occlPrm);
end
%Regress
regPrm.ftrPrm=ftrPrm;
[regInfo,pDel] = regTrain(ftrs,pTar,regPrm);
pCur = shapeGt('compose',model,pDel,pCur,bboxes);
pCur = shapeGt('reprojectPose',model,pCur,bboxes);
pAll(:,:,t+1)=pCur(1:N1,:);
%loss scores
loss = mean(shapeGt('dist',model,pCur,pGt));
% store result
regs(t).regInfo=regInfo;
regs(t).ftrPos=ftrPos;
%If stickmen, add part info
if(verbose),
msg=tStatus(tStart,t,T);
fprintf([' t=%i/%i loss=%f ' msg],t,T,loss);
end
if(loss<1e-5), T=t; break; end
end
% create output structure
regs=regs(1:T); pAll=pAll(:,:,1:T+1);
regModel = struct('model',model,'pStar',pStar,...
'pDstr',pGt(1:N1,:),'T',T,'regs',regs);
if(~strcmp(model.name,'ellipse')),regModel.pGtN=pGtN(1:N1,:); end
% Compute precision recall curve for occlusion detection and find
% desired occlusion detection performance (default=90% precision)
if(strcmp(model.name,'cofw'))
nfids=D/3;
occlGt=pGt(:,(nfids*2)+1:end);
op=pCur(:,(nfids*2)+1:end);
indO=find(occlGt==1);
th=0:.01:1;
prec=zeros(length(th),1);
recall=zeros(length(th),1);
for i=1:length(th)
indPO=find(op>th(i));
prec(i)=length(find(occlGt(indPO)==1))/numel(indPO);
recall(i)=length(find(op(indO)>th(i)))/numel(indO);
end
%precision around 90% (or closest)
pos=find(prec>=0.9);
if(~isempty(pos)),pos=pos(1);
else [~,pos]=max(prec);
end
%maximum f1score
% f1score=(2*prec.*recall)./(prec+recall);
% [~,pos]=max(f1score);
regModel.th=th(pos);
end
end
function msg=tStatus(tStart,t,T)
elptime = etime(clock,tStart);
fracDone = max( t/T, .00001 );
esttime = elptime/fracDone - elptime;
if( elptime/fracDone < 600 )
elptimeS = num2str(elptime,'%.1f');
esttimeS = num2str(esttime,'%.1f');
timetypeS = 's';
else
elptimeS = num2str(elptime/60,'%.1f');
esttimeS = num2str(esttime/60,'%.1f');
timetypeS = 'm';
end
msg = ['[elapsed=' elptimeS timetypeS ...
' / remaining~=' esttimeS timetypeS ']\n' ];
end
|
github
|
pervadepyy/robust-initialization-rcpr-master
|
lbp.m
|
.m
|
robust-initialization-rcpr-master/lbp.m
| 6,516 |
utf_8
|
6d971cd03cebfaf0d188a7321674f26a
|
%LBP returns the local binary pattern image or LBP histogram of an image.
% J = LBP(I,R,N,MAPPING,MODE) returns either a local binary pattern
% coded image or the local binary pattern histogram of an intensity
% image I. The LBP codes are computed using N sampling points on a
% circle of radius R and using mapping table defined by MAPPING.
% See the getmapping function for different mappings and use 0 for
% no mapping. Possible values for MODE are
% 'h' or 'hist' to get a histogram of LBP codes
% 'nh' to get a normalized histogram
% Otherwise an LBP code image is returned.
%
% J = LBP(I) returns the original (basic) LBP histogram of image I
%
% J = LBP(I,SP,MAPPING,MODE) computes the LBP codes using n sampling
% points defined in (n * 2) matrix SP. The sampling points should be
% defined around the origin (coordinates (0,0)).
%
% Examples
% --------
% I=imread('rice.png');
% mapping=getmapping(8,'u2');
% H1=LBP(I,1,8,mapping,'h'); %LBP histogram in (8,1) neighborhood
% %using uniform patterns
% subplot(2,1,1),stem(H1);
%
% H2=LBP(I);
% subplot(2,1,2),stem(H2);
%
% SP=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1];
% I2=LBP(I,SP,0,'i'); %LBP code image using sampling points in SP
% %and no mapping. Now H2 is equal to histogram
% %of I2.
function result = lbp(varargin) % image,radius,neighbors,mapping,mode)
% Version 0.3.3
% Authors: Marko Heikkil?and Timo Ahonen
% Changelog
% Version 0.3.2: A bug fix to enable using mappings together with a
% predefined spoints array
% Version 0.3.1: Changed MAPPING input to be a struct containing the mapping
% table and the number of bins to make the function run faster with high number
% of sampling points. Lauge Sorensen is acknowledged for spotting this problem.
% Check number of input arguments.
error(nargchk(1,5,nargin));
image=varargin{1};
d_image=double(image);
if nargin==1
spoints=[-1 -1; -1 0; -1 1; 0 -1; -0 1; 1 -1; 1 0; 1 1];
neighbors=8;
mapping=0;
mode='mix';
end
if (nargin == 2) && (length(varargin{2}) == 1)
error('Input arguments');
end
if (nargin > 2) && (length(varargin{2}) == 1)
radius=varargin{2};
neighbors=varargin{3};
spoints=zeros(neighbors,2);
% Angle step.
a = 2*pi/neighbors;
for i = 1:neighbors
spoints(i,1) = -radius*sin((i-1)*a);
spoints(i,2) = radius*cos((i-1)*a);
end
if(nargin >= 4)
mapping=varargin{4};
if(isstruct(mapping) && mapping.samples ~= neighbors)
error('Incompatible mapping');
end
else
mapping=0;
end
if(nargin >= 5)
mode=varargin{5};
else
mode='h';
end
end
if (nargin > 1) && (length(varargin{2}) > 1)
spoints=varargin{2};
neighbors=size(spoints,1);
if(nargin >= 3)
mapping=varargin{3};
if(isstruct(mapping) && mapping.samples ~= neighbors)
error('Incompatible mapping');
end
else
mapping=0;
end
if(nargin >= 4)
mode=varargin{4};
else
mode='h';
end
end
% Determine the dimensions of the input image.
[ysize xsize] = size(image);
miny=min(spoints(:,1));
maxy=max(spoints(:,1));
minx=min(spoints(:,2));
maxx=max(spoints(:,2));
% Block size, each LBP code is computed within a block of size bsizey*bsizex
bsizey=ceil(max(maxy,0))-floor(min(miny,0))+1;
bsizex=ceil(max(maxx,0))-floor(min(minx,0))+1;
% Coordinates of origin (0,0) in the block
origy=1-floor(min(miny,0));
origx=1-floor(min(minx,0));
% Minimum allowed size for the input image depends
% on the radius of the used LBP operator.
if(xsize < bsizex || ysize < bsizey)
error('Too small input image. Should be at least (2*radius+1) x (2*radius+1)');
end
% Calculate dx and dy;
dx = xsize - bsizex;
dy = ysize - bsizey;
% Fill the center pixel matrix C.
C = image(origy:origy+dy,origx:origx+dx);
d_C = double(C);
bins = 2^neighbors;
% Initialize the result matrix with zeros.
result=zeros(dy+1,dx+1);
%Compute the LBP code image
for i = 1:neighbors
y = spoints(i,1)+origy;
x = spoints(i,2)+origx;
% Calculate floors, ceils and rounds for the x and y.
fy = floor(y); cy = ceil(y); ry = round(y);
fx = floor(x); cx = ceil(x); rx = round(x);
% Check if interpolation is needed.
if (abs(x - rx) < 1e-6) && (abs(y - ry) < 1e-6)
% Interpolation is not needed, use original datatypes
N = image(ry:ry+dy,rx:rx+dx);
D = N >= C;
else
% Interpolation needed, use double type images
ty = y - fy;
tx = x - fx;
% Calculate the interpolation weights.
w1 = roundn((1 - tx) * (1 - ty),-6);
w2 = roundn(tx * (1 - ty),-6);
w3 = roundn((1 - tx) * ty,-6) ;
% w4 = roundn(tx * ty,-6) ;
w4 = roundn(1 - w1 - w2 - w3, -6);
% Compute interpolated pixel values
N = w1*d_image(fy:fy+dy,fx:fx+dx) + w2*d_image(fy:fy+dy,cx:cx+dx) + ...
w3*d_image(cy:cy+dy,fx:fx+dx) + w4*d_image(cy:cy+dy,cx:cx+dx);
N = roundn(N,-4);
D = N >= d_C;
end
% Update the result matrix.
v = 2^(i-1);
result = result + v*D;
end
%Apply mapping if it is defined
if isstruct(mapping)
bins = mapping.num;
for i = 1:size(result,1)
for j = 1:size(result,2)
result(i,j) = mapping.table(result(i,j)+1);
end
end
end
if (strcmp(mode,'h') || strcmp(mode,'hist') || strcmp(mode,'nh'))
% Return with LBP histogram if mode equals 'hist'.
result=hist(result(:),0:(bins-1));
if (strcmp(mode,'nh'))
result=result/sum(result);
end
else
%Otherwise return a matrix of unsigned integers
if ((bins-1)<=intmax('uint8'))
result=uint8(result);
elseif ((bins-1)<=intmax('uint16'))
result=uint16(result);
else
result=uint32(result);
end
end
end
function x = roundn(x, n)
error(nargchk(2, 2, nargin, 'struct'))
validateattributes(x, {'single', 'double'}, {}, 'ROUNDN', 'X')
validateattributes(n, ...
{'numeric'}, {'scalar', 'real', 'integer'}, 'ROUNDN', 'N')
if n < 0
p = 10 ^ -n;
x = round(p * x) / p;
elseif n > 0
p = 10 ^ n;
x = p * round(x / p);
else
x = round(x);
end
end
|
github
|
pervadepyy/robust-initialization-rcpr-master
|
getmapping.m
|
.m
|
robust-initialization-rcpr-master/getmapping.m
| 5,410 |
utf_8
|
69a52d082d09c6f19245bcbdc8124233
|
%GETMAPPING returns a structure containing a mapping table for LBP codes.
% MAPPING = GETMAPPING(SAMPLES,MAPPINGTYPE) returns a
% structure containing a mapping table for
% LBP codes in a neighbourhood of SAMPLES sampling
% points. Possible values for MAPPINGTYPE are
% 'u2' for uniform LBP
% 'ri' for rotation-invariant LBP
% 'riu2' for uniform rotation-invariant LBP.
%
% Example:
% I=imread('rice.tif');
% MAPPING=getmapping(16,'riu2');
% LBPHIST=lbp(I,2,16,MAPPING,'hist');
% Now LBPHIST contains a rotation-invariant uniform LBP
% histogram in a (16,2) neighbourhood.
%
function mapping = getmapping(samples,mappingtype)
% Version 0.2
% Authors: Marko Heikkil?, Timo Ahonen and Xiaopeng Hong
% Changelog
% 0.1.1 Changed output to be a structure
% Fixed a bug causing out of memory errors when generating rotation
% invariant mappings with high number of sampling points.
% Lauge Sorensen is acknowledged for spotting this problem.
% Modified by Xiaopeng HONG and Guoying ZHAO
% Changelog
% 0.2
% Solved the compatible issue for the bitshift function in Matlab
% 2012 & higher
matlab_ver = ver('MATLAB');
matlab_ver = str2double(matlab_ver.Version);
if matlab_ver < 8
mapping = getmapping_ver7(samples,mappingtype);
else
mapping = getmapping_ver8(samples,mappingtype);
end
end
function mapping = getmapping_ver7(samples,mappingtype)
% disp('For Matlab version 7.x and lower');
table = 0:2^samples-1;
newMax = 0; %number of patterns in the resulting LBP code
index = 0;
if strcmp(mappingtype,'u2') %Uniform 2
newMax = samples*(samples-1) + 3;
for i = 0:2^samples-1
j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left
numt = sum(bitget(bitxor(i,j),1:samples)); %number of 1->0 and
%0->1 transitions
%in binary string
%x is equal to the
%number of 1-bits in
%XOR(x,Rotate left(x))
if numt <= 2
table(i+1) = index;
index = index + 1;
else
table(i+1) = newMax - 1;
end
end
end
if strcmp(mappingtype,'ri') %Rotation invariant
tmpMap = zeros(2^samples,1) - 1;
for i = 0:2^samples-1
rm = i;
r = i;
for j = 1:samples-1
r = bitset(bitshift(r,1,samples),1,bitget(r,samples)); %rotate
%left
if r < rm
rm = r;
end
end
if tmpMap(rm+1) < 0
tmpMap(rm+1) = newMax;
newMax = newMax + 1;
end
table(i+1) = tmpMap(rm+1);
end
end
if strcmp(mappingtype,'riu2') %Uniform & Rotation invariant
newMax = samples + 2;
for i = 0:2^samples - 1
j = bitset(bitshift(i,1,samples),1,bitget(i,samples)); %rotate left
numt = sum(bitget(bitxor(i,j),1:samples));
if numt <= 2
table(i+1) = sum(bitget(i,1:samples));
else
table(i+1) = samples+1;
end
end
end
mapping.table=table;
mapping.samples=samples;
mapping.num=newMax;
end
function mapping = getmapping_ver8(samples,mappingtype)
% disp('For Matlab version 8.0 and higher');
table = 0:2^samples-1;
newMax = 0; %number of patterns in the resulting LBP code
index = 0;
if strcmp(mappingtype,'u2') %Uniform 2
newMax = samples*(samples-1) + 3;
for i = 0:2^samples-1
i_bin = dec2bin(i,samples);
j_bin = circshift(i_bin',-1)'; %circularly rotate left
numt = sum(i_bin~=j_bin); %number of 1->0 and
%0->1 transitions
%in binary string
%x is equal to the
%number of 1-bits in
%XOR(x,Rotate left(x))
if numt <= 2
table(i+1) = index;
index = index + 1;
else
table(i+1) = newMax - 1;
end
end
end
if strcmp(mappingtype,'ri') %Rotation invariant
tmpMap = zeros(2^samples,1) - 1;
for i = 0:2^samples-1
rm = i;
r_bin = dec2bin(i,samples);
for j = 1:samples-1
r = bin2dec(circshift(r_bin',-1*j)'); %rotate left
if r < rm
rm = r;
end
end
if tmpMap(rm+1) < 0
tmpMap(rm+1) = newMax;
newMax = newMax + 1;
end
table(i+1) = tmpMap(rm+1);
end
end
if strcmp(mappingtype,'riu2') %Uniform & Rotation invariant
newMax = samples + 2;
for i = 0:2^samples - 1
i_bin = dec2bin(i,samples);
j_bin = circshift(i_bin',-1)';
numt = sum(i_bin~=j_bin);
if numt <= 2
table(i+1) = sum(bitget(i,1:samples));
else
table(i+1) = samples+1;
end
end
end
mapping.table=table;
mapping.samples=samples;
mapping.num=newMax;
end
|
github
|
pervadepyy/robust-initialization-rcpr-master
|
rcprTest1.m
|
.m
|
robust-initialization-rcpr-master/rcprTest1.m
| 8,554 |
utf_8
|
3900532ff3790e91ae4488605b09076d
|
function pout = rcprTest1( Is, regModel, p, regPrm, iniData, ...
verbose, corrindex, prunePrm)
% Apply robust cascaded shape regressor.
%
% USAGE
% p = rcprTest1( Is, regModel, p, regPrm, bboxes, verbose, prunePrm)
%
% INPUTS
% Is - cell(N,1) input images
% regModel - learned multi stage shape regressor (see rcprTrain)
% p - [NxDxRT1] initial shapes
% regPrm - struct with regression parameters (see regTrain)
% iniData - [Nx2] or [Nx4] bbounding boxes/initial positions
% verbose - [1] show progress or not
% prunePrm - [REQ] parameters for smart restarts
% .prune - [0] whether to use or not smart restarts
% .maxIter - [2] number of iterations
% .th - [.15] threshold used for pruning
% .tIni - [10] iteration from which to prune
%
% OUTPUTS
% p - [NxD] shape returned by multi stage regressor
%
% EXAMPLE
%
% See also rcprTest, rcprTrain
%
% Copyright 2013 X.P. Burgos-Artizzu, P.Perona and Piotr Dollar.
% [xpburgos-at-gmail-dot-com]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see bsd.txt]
%
% Please cite our paper if you use the code:
% Robust face landmark estimation under occlusion,
% X.P. Burgos-Artizzu, P. Perona, P. Dollar (c)
% ICCV'13, Sydney, Australia
% Apply each single stage regressor starting from shape p.
model=regModel.model; T=regModel.T; [N,D,RT1]=size(p);
p=reshape(permute(p,[1 3 2]),[N*RT1,D]);
imgIds = repmat(1:N,[1 RT1]); regs = regModel.regs;
%Get prune parameters
maxIter=prunePrm.maxIter;prune=prunePrm.prune;
th=prunePrm.th;tI=prunePrm.tIni;
%Set up data
p_t=zeros(size(p,1),D,T+1);p_t(:,:,1)=p;
if(model.isFace),bbs=iniData(imgIds,:,1);else bbs=[];end
done=0;Ntot=0;k=0;
N1=N;p1=p;imgIds1=imgIds;
%Iterate while not finished
while(~done)
%Apply cascade
tStart=clock;
%If pruning is active, each loop returns the shapes of the examples
%that passed the smart restart threshold (good) and
%those that did not (bad)
tI=T;
[good1,bad1,p_t1,p1]=cascadeLoop(Is,model,regModel,regPrm,T,N1,D,RT1,...
p1,imgIds1,regs,tStart,iniData,bbs,verbose,...
prune,1,th,tI);
%Separate into good/bad (smart restarts)
p_t(:,:,:)=p_t1;
Ntot=Ntot+length(good1); done=Ntot==N;
p1=permute(reshape(p1,[N,RT1,D]),[1 3 2]);
pgood=p1(good1,:,:);
if(~done)
%Keep iterating only on bad
N1=length(bad1);
pbad1=p1(bad1,:,:);
pbad=zeros(N1,D);
for i=1:N1
pnlbp=pbad1(i,:,1:RT1/2);mdlbp=median(pnlbp,3);
%lbp variance=distance from median of all predictions
conflbp=shapeGt('dist',model,pnlbp,mdlbp);
dislbp(i,:)=mean(conflbp,3);
pnpose=pbad1(i,:,RT1/2+1:RT1);mdpose=median(pnpose,3);
%pose variance=distance from median of all predictions
confpose=shapeGt('dist',model,pnpose,mdpose);
dispose(i,:)=mean(confpose,3);
end
indlbp=find(dislbp<dispose);
indpose=find(dislbp-0.4>dispose);
indboth=setdiff(1:N1,union(indlbp,indpose));
% indboth=find(dislbp>=dispose);
N2=length(indlbp);
% for j=1:N2
% pnlbp1=pbad1(indlbp(j),:,:);mdlbp1=pnlbp1(1,:,1);
% %lbp variance=distance from median of all predictions
% conflbp1=shapeGt('dist',model,pnlbp1,mdlbp1);
% indlbp1=conflbp1<0.1;
% pbad(indlbp(j),:)=median(pbad1(indlbp(j),:,indlbp1),3);
% end
pbad(indlbp,:)=median(pbad1(indlbp,:,1),3);
pbad(indpose,:)=median(pbad1(indpose,:,RT1/2+1:RT1),3);
pbad(indboth,:)=median(pbad1(indboth,:,:),3);
done=1;
pout(bad1,:) = pbad;
end
end
%reconvert p from [N*RT1xD] to [NxDxRT1]
pout(good1,:) = median(pgood,3);
%p_t=permute(reshape(p_t,[N,RT1,D,T+1]),[1 3 2 4]);
end
%Apply full RCPR cascade with check in between if smart restart is enabled
function [good,bad,p_t,p]=cascadeLoop(Is,model,regModel,regPrm,T,N,D,RT1,p,...
imgIds,regs,tStart,bboxes,bbs,verbose,prune,t0,th,tI)
p_t=zeros(size(p,1),D,T+1);p_t(:,:,1)=p;
good=1:N;bad=[];
for t=t0:T
%Compute shape-indexed features
ftrPos=regs(t).ftrPos;
if(ftrPos.type>2)
[ftrs,regPrm.occlD] = shapeGt('ftrsCompDup',model,p,Is,ftrPos,...
imgIds,regModel.pStar,bboxes,regPrm.occlPrm);
else
[ftrs,regPrm.occlD] = shapeGt('ftrsCompIm',model,p,Is,ftrPos,...
imgIds,regModel.pStar,bboxes,regPrm.occlPrm);
end
%Retrieve learnt regressors
regt=regs(t).regInfo;
%Apply regressors
p1=shapeGt('projectPose',model,p,bbs);
pDel=regApply(p1,ftrs,regt,regPrm);
p=shapeGt('compose',model,pDel,p,bbs);
p=shapeGt('reprojectPose',model,p,bbs);
p_t(:,:,t+1)=p;
% % If reached checkpoint, check state of restarts
if((prune && T>=tI && t==tI))
[p_t,p,good,bad]=checkState(p_t,model,imgIds,N,t,th,RT1);
% if(isempty(good)),return; end
% Is=Is(good);N=length(good);imgIds=repmat(1:N,[1 RT1]);
% if(model.isFace),bboxes=bboxes(good,:);bbs=bboxes(imgIds,:);end
end
if((t==1 || mod(t,5)==0) && verbose)
msg=tStatus(tStart,t,T);fprintf(['Applying ' msg]);
end
end
end
% function [p_t,p,good,bad,p2]=checkState(p_t,model,imgIds,N,t,th,RT1)
% %Confidence computation=variance between different restarts
% %If output has low variance and low distance, continue (good)
% %ow recurse with new initialization (bad)
% p=permute(p_t(:,:,t+1),[3 2 1]);conf=zeros(N,RT1);
% corroccl=zeros(N,RT1);
% for n=1:N
% pn=p(:,:,imgIds==n);md=median(pn,3);
% %variance=distance from median of all predictions
% conf(n,:)=shapeGt('dist',model,pn,md);
% poccl = permute(pn(1,model.nfids*2+1:end,:),[2 3 1]);
% md=median(poccl,2);
% corroccl1 = sqrt((poccl - repmat(md,[1 RT1])).^2);
% corroccl(n,:) = mean(corroccl1,1);
% end
% dist=mean(conf,2);
% distoccl = mean(corroccl,2);
% bad=unique([find(dist>th);find(distoccl>th)]);
% good=~ismember(1:N,bad);
% good = find(good==1);
% p2=p_t(ismember(imgIds,bad),:,t+1);
% p_t=p_t(ismember(imgIds,good),:,:);p=p_t(:,:,t+1);
% if(isempty(good)),return; end
% end
function [p_t,p,good,bad]=checkState(p_t,model,imgIds,N,t,th,RT1)
%Confidence computation=variance between different restarts
%If output has low variance and low distance, continue (good)
%ow recurse with new initialization (bad)
p=permute(p_t(:,:,t+1),[3 2 1]);conf=zeros(N,RT1);
for n=1:N
pn=p(:,:,imgIds==n);md=median(pn,3);
%variance=distance from median of all predictions
conf(n,:)=shapeGt('dist',model,pn,md);
end
dist=mean(conf,2);
bad=find(dist>th);good=find(dist<=th);
% p2=p_t(ismember(imgIds,bad),:,t+1);
% p_t=p_t(ismember(imgIds,good),:,:);
p=p_t(:,:,t+1);
% if(isempty(good)),return; end
end
% function [p_t,p,good,bad]=checkState(p_t,model,imgIds,N,t,th,RT1)
% %Confidence computation=variance between different restarts
% %If output has low variance and low distance, continue (good)
% %ow recurse with new initialization (bad)
% p=permute(p_t(:,:,t+1),[3 2 1]);conf=zeros(N,RT1);
% for n=1:N
% pn=p(:,:,imgIds==n);
% md=median(pn(:,:,:),3);
% % mdlbp=median(pn(:,:,1:RT1/2),3);
% %variance=distance from median of all predictions
% conflbp(n,:)=shapeGt('dist',model,pn(:,:,1:RT1/2),md);
%
% % mdpose=median(pn(:,:,RT1/2+1:RT1),3);
% %variance=distance from median of all predictions
% confpose(n,:)=shapeGt('dist',model,pn(:,:,RT1/2+1:RT1),md);
% end
% dist(:,1)=mean(conflbp,2);
% dist(:,2)=mean(confpose,2);
% distdiff=abs(dist(:,1)-dist(:,2));
% bad=find(distdiff>th*1);good=find(distdiff<=th*1);
% % p2=p_t(ismember(imgIds,bad),:,t+1);
% % p_t=p_t(ismember(imgIds,good),:,:);
% p=p_t(:,:,t+1);
% if(isempty(good)),return; end
% end
function msg=tStatus(tStart,t,T)
elptime = etime(clock,tStart);
fracDone = max( t/T, .00001 );
esttime = elptime/fracDone - elptime;
if( elptime/fracDone < 600 )
elptimeS = num2str(elptime,'%.1f');
esttimeS = num2str(esttime,'%.1f');
timetypeS = 's';
else
elptimeS = num2str(elptime/60,'%.1f');
esttimeS = num2str(esttime/60,'%.1f');
timetypeS = 'm';
end
msg = [' [elapsed=' elptimeS timetypeS ...
' / remaining~=' esttimeS timetypeS ']\n' ];
end
|
github
|
pervadepyy/robust-initialization-rcpr-master
|
regTrain.m
|
.m
|
robust-initialization-rcpr-master/regTrain.m
| 9,295 |
utf_8
|
89b7e0fe00811be7ba431a49658b6411
|
function [regInfo,ysPr]=regTrain(data,ys,varargin)
% Train boosted regressor.
%
% USAGE
% [regInfo,ysPr] = regTrain( data, ys, [varargin] )
%
% INPUTS
% data - [NxF] N length F feature vectors
% ys - [NxD] target output values
% varargin - additional params (struct or name/value pairs)
% .type - [1] type of regression
% 1=fern, 2=linear
% .ftrPrm - [REQ] prm struct (see shapeGt>ftrsGen)
% .K - [1] number of boosted regressors
% .M - [5] number of features used by each regressor
% .R - [0] number repetitions per fern (if =0 uses correlation
% selection instead of random optimization)
% .loss - ['L2'] loss function (used if R>0) for
% random step optimization
% options include {'L1','L2'}
% .model - [] optional, if special treatment is required for regression
% .prm - [REQ] regression parameters, relative to type
% .occlD - feature occlusion info, see shapeGt>ftrsCompDup
% .occlPrm - occlusion params for occlusion-centered (struct)
% regression, output of shapeGt>ftrsComp
% .nrows - [3] number of rows into which divide face
% .ncols - [3] number of cols into which divide face
% .nzones - [1] number of face zone from which regressors draw features
% .Stot - [3] number of regressors to train at each round
% .th - [.5] occlusion threshold
%
% OUTPUTS
% regInfo - [K x Stot] cell with learnt regressors models
% .ysFern - [2^MxR] fern bin averages
% .thrs - [Mx1] thresholds
% .fids - [2xS] features used
% ysPr - [NxD] predicted output values
%
% See also
% rcprTrain, regTrain>trainFern, regTrain>trainLin, regApply
%
% Copyright 2013 X.P. Burgos-Artizzu, P.Perona and Piotr Dollar.
% [xpburgos-at-gmail-dot-com]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see bsd.txt]
%
% Please cite our paper if you use the code:
% Robust face landmark estimation under occlusion,
% X.P. Burgos-Artizzu, P. Perona, P. Dollar (c)
% ICCV'13, Sydney, Australia
% get/check parameters
dfs={'type',1,'ftrPrm','REQ','K',1,...
'loss','L2','R',0,'M',5,'model',[],'prm',{},...
'occlD',[],'occlPrm',struct('Stot',1)};
[regType,ftrPrm,K,loss,R,M,model,prm,occlD,occlPrm]=...
getPrmDflt(varargin,dfs,1);
%Set base regression type
switch(regType)
case 1, regFun = @trainFern;%fern regressor
case 2, regFun = @trainLin;%linear regressor
otherwise, error('unknown regressor type');
end
%Set loss type
assert(any(strcmp(loss,{'L1','L2'})));
%precompute feature std to be used by selectCorrFeat
if(R==0), [stdFtrs,dfFtrs]=statsFtrs(data,ftrPrm);
else%random step optimization selection
switch(loss)
case 'L1', lossFun=@(ys,ysGt) mean(abs(ys(:)-ysGt(:)));
case 'L2', lossFun=@(ys,ysGt) mean((ys(:)-ysGt(:)).^2);
end
end
Stot=occlPrm.Stot;
[N,D]=size(ys);ysSum=zeros(N,D);
regInfo = cell(K,Stot);
%If using occlusion-centered approach, set up masks
if(Stot>1 && ~isempty(occlD))
nGroups=occlPrm.nrows*occlPrm.ncols;
masks=zeros(Stot,min(nGroups,occlPrm.nzones));
for s=1:Stot
masks(s,:)=randSample(nGroups,min(nGroups,occlPrm.nzones));
end
if(D>10),mg=median(occlD.group);
else mg=occlD.group;
end
ftrsOccl=zeros(N,K,Stot);
end
%Iterate through K boosted regressors
for k=1:K
%Update regression target
ysTar=ys-ysSum;
%Train Stot different regressors
ysPred = zeros(N,D,Stot);
for s=1:Stot
%Select features from correlation score directly
if(R==0)
%If occlusion-centered approach, enforce feature variety
if(s>1 && Stot>1 && ~isempty(occlD))
keep=find(ismember(mg,masks(s-1,:)));
if(~isempty(keep))
data2=data(:,keep);dfFtrs2=dfFtrs(:,keep);
stdFtrs2=stdFtrs(keep,keep);
ftrPrm1=ftrPrm;ftrPrm1.F=length(keep);
[use,ftrs] = selectCorrFeat(M,ysTar,data2,...
ftrPrm1,stdFtrs2,dfFtrs2);
use=keep(use);
else
[use,ftrs] = selectCorrFeat(M,ysTar,data,...
ftrPrm,stdFtrs,dfFtrs);
end
%ow use all features
else
[use,ftrs] = selectCorrFeat(M,ysTar,data,...
ftrPrm,stdFtrs,dfFtrs);
end
%Train regressor using selected features
[reg1,ys1]=regFun(ysTar,ftrs,M,prm);
reg1.fids=use; best={reg1,ys1};
%Select features using random step optimization
else
%If occlusion-centered approach, enforce feature variety
if(s>1 && Stot>1 && ~isempty(occlD))
if(Stot==5),keep=find(ismember(mg,masks(s-1,:)));
elseif(Stot==12), keep=find(ismember(mg,masks{s-1}));
end
data2=data(:,keep); F=length(keep);
%ow use all features
else
data2=data;F=ftrPrm.F;keep=1:F;
end
%Select features with random step optimization
e = lossFun(ysTar,zeros(N,D));
type=ftrPrm.type;if(type>2),type=type-2;end
for r=1:R
if(type==1),
use=randSample(F,M);ftrs = data2(:,use);
else
use=randSample(F,M*2);use=reshape(use,2,M);
ftrs=data2(:,use(1,:))-data2(:,use(2,:));
end
%Train regressor using selected features
[reg1,ys1]=regFun(ysTar,ftrs,M,prm);
e1 = lossFun(ysTar,ys1);use=keep(use);
%fprintf('%f - %f \n',e,e1);
if(e1<=e), e=e1; reg1.fids=use; best={reg1,ys1}; end
end
end
%Get output of regressor
[regInfo{k,s},ysPred(:,:,s)]=deal(best{:});clear best;
%If occlusion-centered, get occlusion averages by group
if(D>10 && Stot>1 && ~isempty(occlD))
ftrsOccl(:,k,s)=sum(occlD.featOccl(:,regInfo{k,s}.fids),2)./K;
end
end
%Combine S1 regressors to form prediction (Occlusion-centered)
if(D>10 && Stot>1 && ~isempty(occlD))
%(WEIGHTED MEAN)
%ftrsOccl contains total occlusion of each Regressor
% weight should be inversely proportional, summing up to 1
weights=1-normalize(ftrsOccl(:,k,:));ss=sum(weights,3);
weights=weights./repmat(ss,[1,1,Stot]);
%when all are fully occluded, all get proportional weight
% (regular mean)
weights(ss==0,1,:)=1/Stot;
weights=repmat(weights,[1,D,1]);
%OLD
for s=1:Stot
ysSum=ysSum+ysPred(:,:,s).*weights(:,:,s);
end
else
%Update output
ysSum=ysSum+ysPred;
end
end
% create output struct
clear data ys; ysPr=ysSum;
if(R==0), clear stdFtrs dfFtrs; end
end
function [regSt,Y_pred]=trainFern(Y,X,M,prm)
% Train single random fern regressor.
%
% USAGE
% [regSt,Y_pred]=trainFern(Y,X,M,prm)
%
% INPUTS
% Y - [NxD] target output values
% X - [NxF] data measurements (features)
% M - fern depth
% prm - additional parameters
% .thrr - fern bin thresholding
% .reg - fern regularization term
%
% OUTPUTS
% regSt - struct with learned regressors models
% .ysFern - average values for fern bins
% .thrs - thresholds used at each M level
% ysPr - [NxD] predicted output values
%
% See also
% get/check parameters
dfs={'thrr',[-1 1]/5,'reg',.01}; [thrr,reg]=getPrmDflt(prm,dfs,1);
[N,D]=size(Y); fids=uint32(1:M);
thrs = rand(1,M)*(thrr(2)-thrr(1))+thrr(1);
[inds,mu,ysFern,count,~] = fernsInds2(X,fids,thrs,Y);
cnts = repmat(count,[1,D]);clear count;S=size(cnts,1);
for d=1:D
%ysFern(:,d) = ysFern(:,d) ./ max(cnts(:,d)+(1+1000/cnts(:,d))',eps) + mu(d);
ysFern(:,d) = ysFern(:,d) ./ max(cnts(:,d)+reg*N,eps) + mu(d);
end
Y_pred = ysFern(inds,:);
clear dfYs;
clear cnts vars inds mu;%conf
regSt = struct('ysFern',ysFern,'thrs',thrs);
end
function [regSt,Y_pred]=trainLin(Y,X,~,~)
% Train single linear regressor.
%
% USAGE
% [regSt,Y_pred]=linFern(Y,X)
%
% INPUTS
% Y - [NxD] target output values
% X - [NxF] data measurements (features)
%
% OUTPUTS
% regSt - struct with learned regressors models
% .W - linear reg weights
% Y_pred - [NxD] predicted output values
%
% See also
W = X\Y; Y_pred = X*W;regSt = struct('W',W);
end
%Compute std and diff between ftrs to be used by fast correlation selection
function [stdFtrs,dfFtrs]=statsFtrs(ftrs,ftrPrm)
[N,~]=size(ftrs);
if(ftrPrm.type==1)
stdFtrs = std(ftrs); muFtrs = mean(ftrs);
dfFtrs = ftrs-repmat(muFtrs,[N,1]);
else
muFtrs = mean(ftrs);
dfFtrs = ftrs-repmat(muFtrs,[N,1]);
stdFtrs=stdFtrs1(ftrs);
end
end
|
github
|
pervadepyy/robust-initialization-rcpr-master
|
shapeGt.m
|
.m
|
robust-initialization-rcpr-master/shapeGt.m
| 26,026 |
utf_8
|
e11051d7e887e7704a94fa95300474f5
|
function varargout = shapeGt( action, varargin )
%
% Wrapper with utils for handling shape as list of landmarks
%
% shapeGt contains a number of utility functions, accessed using:
% outputs = shapeGt( 'action', inputs );
%
% USAGE
% varargout = shapeGt( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action
%
% OUTPUTS
% varargout - depends on action
%
% FUNCTION LIST
%
%%%% Model creation and visualization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% shapeGt>createModel, shapeGt>draw
%
%%%% Shape composition, inverse, distances, projection %%%%%%%%%%%%%%%
%
% shapeGt>compose,shapeGt>inverse, shapeGt>dif, shapeGt>dist
% shapeGt>compPhiStar, shapeGt>reprojectPose, shapeGt>projectPose
%
%%%% Shape-indexed features computation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% shapeGt>ftrsGenIm,shapeGt>ftrsCompIm
% shapeGt>ftrsGenDup,shapeGt>ftrsCompDup
% shapeGt>ftrsOcclMasks, shapeGt>codifyPos
% shapeGt>getLinePoint, shapeGt>getSzIm
%
%%%%% Random shape generation for initialization %%%%%%%%%%%%%%%%%%%%
%
% shapeGt>initTr, shapeGt>initTest
%
% EXAMPLES
%
%%create COFW model
% model = shapeGt( 'createModel', 'cofw' );
%%draw shape on top of image
% shapeGt( 'draw',model,Image,shape);
%%compute distance between two set of shapes (phis1 and phis2)
% d = shapeGt( 'dist',model,phis1,phis2);
%
% For full function example usage, see individual function help and how
% they are used in: demoRCPR, FULL_demoRCPR, rcprTrain, rcprTest
%
% Copyright 2013 X.P. Burgos-Artizzu, P.Perona and Piotr Dollar.
% [xpburgos-at-gmail-dot-com]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see bsd.txt]
%
% Please cite our paper if you use the code:
% Robust face landmark estimation under occlusion,
% X.P. Burgos-Artizzu, P. Perona, P. Dollar (c)
% ICCV'13, Sydney, Australia
varargout = cell(1,max(1,nargout));
[varargout{:}] = feval(action,varargin{:});
end
function model = createModel( type )
% Create shape model (model is necessary for all other actions).
model=struct('nfids',0,'D',0,'isFace',1,'name',[]);
switch type
case 'cofw' % COFW dataset (29 landmarks: X,Y,V)
model.nfids=29;model.D=model.nfids*3; model.name='cofw';
case 'lfpw' % LFPW dataset (29 landmarks: X,Y)
model.nfids=29;model.D=model.nfids*2; model.name='lfpw';
case 'helen' % HELEN dataset (194 landmarks: X,Y)
model.nfids=194;model.D=model.nfids*2;model.name='helen';
case 'lfw' % LFW dataset (10 landmarks: X,Y)
model.nfids=10;model.D=model.nfids*2; model.name='lfw';
case 'pie' %Multi-pie & 300-Faces in the wild dataset (68 landmarks)
model.nfids=68;model.D=model.nfids*2;model.name='pie';
case 'apf' %anonimous portrait faces
model.nfids=55;model.D=model.nfids*2;model.name='apf';
otherwise
error('unknown type: %s',type);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function h = draw( model, Is, phis, varargin )
% Draw shape with parameters phis using model on top of image Is.
dfs={'n',25, 'clrs','gcbm', 'drawIs',1, 'lw',10, 'is',[]};
[n,cs,drawIs,lw,is]=getPrmDflt(varargin,dfs,1);
% display I
if(drawIs), im(Is); colorbar off; axis off; title(''); axis('ij'); end%clf
% special display for face model (draw face points)
hold on,
if( isfield(model,'isFace') && model.isFace ),
[N,D]=size(phis);
if(strcmp(model.name,'cofw')),
%WITH OCCLUSION
nfids = D/3;
for n=1:N
occl=phis(n,(nfids*2)+1:nfids*3);
vis=find(occl==0);novis=find(occl==1);
plot(phis(n,vis),phis(n,vis+nfids),'.','Color',[0 1 0],...
'MarkerSize',lw);
h=plot(phis(n,novis),phis(n,novis+nfids),'r.',...
'MarkerSize',lw);
end
else
%REGULAR
if(N==1),cs='g';end, nfids = D/2;
for n=1:N
h=plot(phis(n,1:nfids),phis(n,nfids+1:nfids*2),[cs(n) '.'],...
'MarkerSize',lw);
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pos=ftrsOcclMasks(xs)
%Generate 9 occlusion masks for varied feature locations
pos=cell(9,1);
for m=1:9
switch(m)
case 1,pos{m}=(1:numel(xs(:,1)))';
case 2,%top half
pos{m}=find(xs(:,2)<=0);
case 3,%bottom half
pos{m}=find(xs(:,2)>0);
case 4,%right
pos{m}=find(xs(:,1)>=0);
case 5,%left
pos{m}=find(xs(:,1)<0);
case 6,%right top diagonal
pos{m}=find(xs(:,1)>=xs(:,2));
case 7,%left bottom diagonal
pos{m}=find(xs(:,1)<xs(:,2));
case 8,%left top diagonal
pos{m}=find(xs(:,1)*-1>=xs(:,2));
case 9,%right bottom diagonal
pos{m}=find(xs(:,1)*-1<xs(:,2));
end
end
end
function ftrData = ftrsGenDup( model, varargin )
% Generate random shape indexed features, relative to
% two landmarks (points in a line, RCPR contribution)
% Features are then computed using frtsCompDup
%
% USAGE
% ftrData = ftrsGenDup( model, varargin )
%
% INPUTS
% model - shape model (see createModel())
% varargin - additional params (struct or name/value pairs)
% .type - [2] feature type (1 or 2)
% .F - [100] number of ftrs to generate
% .radius - [2] sample initial x from circle of given radius
% .nChn - [1] number of image channels (e.g. 3 for color images)
% .pids - [] part ids for each x
%
% OUTPUTS
% ftrData - struct containing generated ftrs
% .type - feature type (1 or 2)
% .F - total number of features
% .nChn - number of image channels
% .xs - feature locations relative to unit circle
% .pids - part ids for each x
%
% EXAMPLE
%
% See also shapeGt>ftrsCompDup
dfs={'type',4,'F',20,'radius',1,'nChn',3,'pids',[],'mask',[]};
[type,F,radius,nChn,pids,mask]=getPrmDflt(varargin,dfs,1);
F2=max(100,ceil(F*1.5));
xs=[];nfids=model.nfids;
while(size(xs,1)<F),
%select two random landmarks
xs(:,1:2)=randint2(F2,2,[1 nfids]);
%make sure they are not the same
neq = (xs(:,1)~=xs(:,2));
xs=xs(neq,:);
end
xs=xs(1:F,:);
%select position in line
xs(:,3)=(2*radius*rand(F,1))-radius;
if(nChn>1),
if(type==4),%make sure subbtractions occur inside same channel
chns = randint2(F/2,1,[1 nChn]);
xs(1:2:end,4) = chns; xs(2:2:end,4) = chns;
else xs(:,4)=randint2(F,1,[1 nChn]);
end
end
if(isempty(pids)), pids=floor(linspace(0,F,2)); end
ftrData=struct('type',type,'F',F,'nChn',nChn,'xs',xs,'pids',pids);
end
function ftrData = ftrsGenIm( model, pStar, varargin )
% Generate random shape indexed features,
% relative to closest landmark (similar to Cao et al., CVPR12)
% Features are then computed using frtsCompIm
%
% USAGE
% ftrData = ftrsGenIm( model, pStar, varargin )
%
% INPUTS
% model - shape model (see createModel())
% pStar - average shape (see initTr)
% varargin - additional params (struct or name/value pairs)
% .type - [2] feature type (1 or 2)
% .F - [100] number of ftrs to generate
% .radius - [2] sample initial x from circle of given radius
% .nChn - [1] number of image channels (e.g. 3 for color images)
% .pids - [] part ids for each x
%
% OUTPUTS
% ftrData - struct containing generated ftrs
% .type - feature type (1 or 2)
% .F - total number of features
% .nChn - number of image channels
% .xs - feature locations relative to unit circle
% .pids - part ids for each x
%
% EXAMPLE
%
% See also shapeGt>ftrsCompIm
dfs={'type',2,'F',20,'radius',1,'nChn',3,'pids',[],'mask',[]};
[type,F,radius,nChn,pids,mask]=getPrmDflt(varargin,dfs,1);
%Generate random features on image
xs1=[];
while(size(xs1,1)<F),
xs1=rand(F*1.5,2)*2-1;
xs1=xs1(sum(xs1.^2,2)<=1,:);
end
xs1=xs1(1:F,:)*radius;
if(strcmp(model.name,'cofw'))
nfids=size(pStar,2)/3;
else
nfids=size(pStar,2)/2;
end
%Reproject each into closest pStar landmark
xs=zeros(F,3);%X,Y,landmark
for f=1:F
posX=xs1(f,1)-pStar(1:nfids);
posY=xs1(f,2)-pStar(nfids+1:nfids*2);
dist = (posX.^2)+(posY.^2);
[~,l]=min(dist);xs(f,:)=[posX(l) posY(l) l];
end
if(nChn>1),
if(mod(type,2)==0),%make sure subbtractions occur inside same channel
chns = randint2(F,1,[1 nChn]);
xs(1:2:end,4) = chns; xs(2:2:end,4) = chns;
else xs(:,4)=randint2(F,1,[1 nChn]);
end
end
if(isempty(pids)), pids=floor(linspace(0,F,2)); end
ftrData=struct('type',type,'F',F,'nChn',nChn,'xs',xs,'pids',pids);
end
function [ftrs,occlD] = ftrsCompDup( model, phis, Is, ftrData,...
imgIds, pStar, bboxes, occlPrm)
% Compute features from ftrsGenDup on Is
%
% USAGE
% [ftrs,Vs] = ftrsCompDup( model, phis, Is, ftrData, imgIds, pStar, ...
% bboxes, occlPrm )
%
% INPUTS
% model - shape model
% phis - [MxR] relative shape for each image
% Is - cell [N] input images [w x h x nChn] variable w, h
% ftrData - define ftrs to actually compute, output of ftrsGen
% imgIds - [Mx1] image id for each phi
% pStar - [1xR] average shape (see initTr)
% bboxes - [Nx4] face bounding boxes
% occlPrm - struct containing occlusion reasoning parameters
% .nrows - [3] number of rows in face region
% .ncols - [3] number of columns in face region
% .nzones - [1] number of zones from where each regs draws
% .Stot - total number of regressors at each stage
% .th - [0.5] occlusion threshold used during cascade
%
% OUTPUTS
% ftrs - [MxF] computed features
% occlD - struct containing occlusion info (if using full RCPR)
% .group - [MxF] to which face region each features belong
% .featOccl - [MxF] amount of total occlusion in that area
%
% EXAMPLE
%
% See also demoRCPR, shapeGt>ftrsGenDup
N = length(Is); nfids=model.nfids;
if(nargin<5 || isempty(imgIds)), imgIds=1:N; end
if(nargin<6 || isempty(pStar)),
pStar=compPhiStar(model,phis,Is,0,[],[]);
end
M=size(phis,1); assert(length(imgIds)==M);nChn=ftrData.nChn;
if(size(bboxes,1)==length(Is)), bboxes=bboxes(imgIds,:); end
if(ftrData.type==3),
FTot=ftrData.F;
ftrs = zeros(M,FTot);
else
FTot=ftrData.F;ftrs = zeros(M,FTot);
end
posrs = phis(:,nfids+1:nfids*2);poscs = phis(:,1:nfids);
useOccl=occlPrm.Stot>1;
if(useOccl && (strcmp(model.name,'cofw')))
occl = phis(:,(nfids*2)+1:nfids*3);
occlD=struct('featOccl',zeros(M,FTot),'group',zeros(M,FTot));
else occl = zeros(M,nfids);occlD=[];
end
%GET ALL POINTS
if(nargout>1)
[csStar,rsStar]=getLinePoint(ftrData.xs,pStar(1:nfids),...
pStar(nfids+1:nfids*2));
pos=ftrsOcclMasks([csStar' rsStar']);
end
%relative to two points
[cs1,rs1]=getLinePoint(ftrData.xs,poscs,posrs);
nGroups=occlPrm.nrows*occlPrm.ncols;
%ticId =ticStatus('Computing feats',1,1,1);
for n=1:M
img = Is{imgIds(n)}; [h,w,ch]=size(img);
if(ch==1 && nChn==3), img = cat(3,img,img,img);
elseif(ch==3 && nChn==1), img = rgb2gray(img);
end
cs1(n,:)=max(1,min(w,cs1(n,:)));
rs1(n,:)=max(1,min(h,rs1(n,:)));
%where are the features relative to bbox?
if(useOccl && (strcmp(model.name,'cofw')))
%to which group (zone) does each feature belong?
occlD.group(n,:)=codifyPos((cs1(n,:)-bboxes(n,1))./bboxes(n,3),...
(rs1(n,:)-bboxes(n,2))./bboxes(n,4),...
occlPrm.nrows,occlPrm.ncols);
%to which group (zone) does each landmark belong?
groupF=codifyPos((poscs(n,:)-bboxes(n,1))./bboxes(n,3),...
(posrs(n,:)-bboxes(n,2))./bboxes(n,4),...
occlPrm.nrows,occlPrm.ncols);
%NEW
%therefore, what is the occlusion in each group (zone)
occlAm=zeros(1,nGroups);
for g=1:nGroups
occlAm(g)=sum(occl(n,groupF==g));
end
%feature occlusion = sum of occlusion on that area
occlD.featOccl(n,:)=occlAm(occlD.group(n,:));
end
% boxxy = sqrt(bboxes(n,3)^2 + bboxes(n,4)^2);
% for i=1:FTot
% dis = sqrt( (poscs(n,:)-cs1(n,i)).^2+(posrs(n,:)-rs1(n,i)).^2 )/boxxy;
% inCir = dis - 0.20<=0;
% indis = dis(inCir)*15;
% wg = normpdf(indis,0,3)*7.52;
% occ = occl(n,inCir==1);
% occlAm = sum(occ.*wg);
% occlD.featOccl(n,i)=occlAm;
% end
inds1 = (rs1(n,:)) + (cs1(n,:)-1)*h;
if(nChn>1), inds1 = inds1+(chs'-1)*w*h; end
if(isa(img,'uint8')), ftrs1=double(img(inds1)')/255;
else ftrs1=double(img(inds1)'); end
if(ftrData.type==3),ftrs1=ftrs1*2-1; ftrs(n,:)=reshape(ftrs1,1,FTot);
else ftrs(n,:)=ftrs1;
end
%tocStatus(ticId,n/M);
end
end
function group=codifyPos(x,y,nrows,ncols)
%codify position of features into regions
nr=1/nrows;nc=1/ncols;
%Readjust positions so that they falls in [0,1]
x=min(1,max(0,x));y=min(1,max(0,y));
y2=y;x2=x;
for c=1:ncols,
if(c==1), x2(x<=nc)=1;
elseif(c==ncols), x2(x>=nc*(c-1))=ncols;
else x2(x>nc*(c-1) & x<=nc*c)=c;
end
end
for r=1:nrows,
if(r==1), y2(y<=nr)=1;
elseif(r==nrows), y2(y>=nc*(r-1))=nrows;
else y2(y>nr*(r-1) & y<=nr*r)=r;
end
end
group=sub2ind2([nrows ncols],[y2' x2']);
end
function [cs1,rs1]=getLinePoint(FDxs,poscs,posrs)
%get pixel positions given coordinates as points in a line between
%landmarks
%INPUT NxF, OUTPUT NxF
if(size(poscs,1)==1)%pStar normalized
l1= FDxs(:,1);l2= FDxs(:,2);xs=FDxs(:,3);
x1 = poscs(:,l1);y1 = posrs(:,l1);
x2 = poscs(:,l2);y2 = posrs(:,l2);
a=(y2-y1)./(x2-x1); b=y1-(a.*x1);
distX=(x2-x1)/2; ctrX= x1+distX;
cs1=ctrX+(repmat(xs',size(distX,1),1).*distX);
rs1=(a.*cs1)+b;
else
if(size(FDxs,2)<4)%POINTS IN A LINE (ftrsGenDup)
%2 points in a line with respect to center
l1= FDxs(:,1);l2= FDxs(:,2);xs=FDxs(:,3);
%center
muX = mean(poscs,2);
muY = mean(posrs,2);
poscs=poscs-repmat(muX,1,size(poscs,2));
posrs=posrs-repmat(muY,1,size(poscs,2));
%landmark
x1 = poscs(:,l1);y1 = posrs(:,l1);
x2 = poscs(:,l2);y2 = posrs(:,l2);
a=(y2-y1)./(x2-x1); b=y1-(a.*x1);
distX=(x2-x1)/2; ctrX= x1+distX;
cs1=ctrX+(repmat(xs',size(distX,1),1).*distX);
rs1=(a.*cs1)+b;
cs1=round(cs1+repmat(muX,1,size(FDxs,1)));
rs1=round(rs1+repmat(muY,1,size(FDxs,1)));
end
end
end
function [ftrs,occlD] = ftrsCompIm( model, phis, Is, ftrData,...
imgIds, pStar, bboxes, occlPrm )
% Compute features from ftrsGenIm on Is
%
% USAGE
% [ftrs,Vs] = ftrsCompIm( model, phis, Is, ftrData, [imgIds] )
%
% INPUTS
% model - shape model
% phis - [MxR] relative shape for each image
% Is - cell [N] input images [w x h x nChn] variable w, h
% ftrData - define ftrs to actually compute, output of ftrsGen
% imgIds - [Mx1] image id for each phi
% pStar - [1xR] average shape (see initTr)
% bboxes - [Nx4] face bounding boxes
% occlPrm - struct containing occlusion reasoning parameters
% .nrows - [3] number of rows in face region
% .ncols - [3] number of columns in face region
% .nzones - [1] number of zones from where each regs draws
% .Stot - total number of regressors at each stage
% .th - [0.5] occlusion threshold used during cascade
%
% OUTPUTS
% ftrs - [MxF] computed features
% occlD - [] empty structure
%
% EXAMPLE
%
% See also demoCPR, shapeGt>ftrsGenIm, shapeGt>ftrsCompDup
N = length(Is); nChn=ftrData.nChn;
if(nargin<5 || isempty(imgIds)), imgIds=1:N; end
M=size(phis,1); assert(length(imgIds)==M);
[pStar,phisN,distPup,sz,bboxes] = ...
compPhiStar( model, phis, Is, 10, imgIds, bboxes );
if(size(bboxes,1)==length(Is)), bboxes=bboxes(imgIds,:); end
F=size(ftrData.xs,1);ftrs = zeros(M,F);
useOccl=occlPrm.Stot>1;
if(strcmp(model.name,'cofw'))
nfids=size(phis,2)/3;occlD=[];
else
nfids=size(phis,2)/2;occlD=[];
end
%X,Y,landmark,Channel
rs = ftrData.xs(:,2);cs = ftrData.xs(:,1);xss = [cs';rs'];
ls = ftrData.xs(:,3);if(nChn>1),chs = ftrData.xs(:,4);end
%Actual phis positions
poscs=phis(:,1:nfids);posrs=phis(:,nfids+1:nfids*2);
%get positions of key landmarks
posrs=posrs(:,ls);poscs=poscs(:,ls);
%Reference points
X=[pStar(1:nfids);pStar(nfids+1:nfids*2)];
for n=1:M
img = Is{imgIds(n)}; [h,w,ch]=size(img);
if(ch==1 && nChn==3), img = cat(3,img,img,img);
elseif(ch==3 && nChn==1), img = rgb2gray(img);
end
%Compute relation between phisN and pStar (scale, rotation)
Y=[phisN(n,1:nfids);phisN(n,nfids+1:nfids*2)];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[~,~,Sc,Rot] = translate_scale_rotate(Y,X);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Compute feature locations by reprojecting
aux=Sc*Rot*xss;
%Resize accordingly to bbox size
szX=bboxes(n,3)/2;szY=bboxes(n,4)/2;
aux = [(aux(1,:)*szX);(aux(2,:)*szY)];
%Add to respective landmark
rs1 = round(posrs(n,:)+aux(2,:));
cs1 = round(poscs(n,:)+aux(1,:));
cs1 = max(1,min(w,cs1)); rs1=max(1,min(h,rs1));
inds1 = (rs1) + (cs1-1)*h;
if(nChn>1), chs = repmat(chs,1,m); inds1 = inds1+(chs-1)*w*h; end
if(isa(img,'uint8')), ftrs1=double(img(inds1)')/255;
else ftrs1=double(img(inds1)'); end
if(ftrData.type==1),
ftrs1=ftrs1*2-1; ftrs(n,:)=reshape(ftrs1,1,F);
else ftrs(n,:)=ftrs1;
end
end
end
function [h,w]=getSzIm(Is)
%get image sizes
N=length(Is); w=zeros(1,N);h=zeros(1,N);
for i=1:N, [w(i),h(i),~]=size(Is{i}); end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function phis = compose( model, phis0, phis1, bboxes )
% Compose two shapes phis0 and phis1: phis = phis0 + phis1.
phis1=projectPose(model,phis1,bboxes);
phis=phis0+phis1;
end
function phis = inverse( model, phis0, bboxes )
% Compute inverse of two shapes phis0 so that phis0+phis=phis+phis0=identity.
phis=-projectPose(model,phis0,bboxes);
end
function [phiStar,phisN,distPup,sz,bboxes] = ...
compPhiStar( model, phis, Is, pad, imgIds, bboxes )
% Compute phi that minimizes sum of distances to phis (average shape)
[N,D] = size(phis);sz=zeros(N,2);
if(isempty(imgIds)),imgIds=1:N; end
if(strcmp(model.name,'cofw')), nfids = (D/3);
else nfids=D/2;
end
phisN=zeros(N,D);
if(strcmp(model.name,'lfpw') || strcmp(model.name,'cofw'))
distPup=sqrt(((phis(:,17)-phis(:,18)).^2)+...
((phis(:,17+nfids)-phis(:,18+nfids)).^2));
elseif(strcmp(model.name,'mouseP'))
distPup=68;
elseif(strcmp(model.name,'lfw'))
leyeX=mean(phis(:,1:2),2);leyeY=mean(phis(:,(1:2)+nfids),2);
reyeX=mean(phis(:,7:8),2);reyeY=mean(phis(:,(7:8)+nfids),2);
distPup=sqrt(((leyeX-reyeX).^2) + ((leyeY-reyeY).^2));
else distPup=0;
end
if(nargin<6), bboxes = zeros(N,4); end
for n=1:N
if(nargin<6)
%left top width height
bboxes(n,1:2)=[min(phis(n,1:nfids))-pad ...
min(phis(n,nfids+1:end))-pad];
bboxes(n,3)=max(phis(n,1:nfids))-bboxes(n,1)+2*pad;
bboxes(n,4)=max(phis(n,nfids+1:nfids*2))-bboxes(n,2)+2*pad;
end
img = Is{imgIds(n)}; [sz(n,1),sz(n,2),~]=size(img);
sz(n,:)=sz(n,:)/2;
%All relative to centroid, using bbox size
if(nargin<6)
szX=bboxes(n,3)/2;szY=bboxes(n,4)/2;
ctr(1)=bboxes(n,1)+szX;ctr(2) = bboxes(n,2)+szY;
else
szX=bboxes(imgIds(n),3)/2;szY=bboxes(imgIds(n),4)/2;
ctr(1)=bboxes(imgIds(n),1)+szX;ctr(2) = bboxes(imgIds(n),2)+szY;
end
if(strcmp(model.name,'cofw'))
phisN(n,:) = [(phis(n,1:nfids)-ctr(1))./szX ...
(phis(n,nfids+1:nfids*2)-ctr(2))./szY ...
phis(n,(nfids*2)+1:nfids*3)];
else phisN(n,:) = [(phis(n,1:nfids)-ctr(1))./szX ...
(phis(n,nfids+1:nfids*2)-ctr(2))./szY];
end
end
phiStar = mean(phisN,1);
end
function phis1=reprojectPose(model,phis,bboxes)
%reproject shape given bounding box of object location
[N,D]=size(phis);
if(strcmp(model.name,'cofw')), nfids = D/3;
else nfids = D/2;
end
szX=bboxes(:,3)/2;szY=bboxes(:,4)/2;
ctrX = bboxes(:,1)+szX;ctrY = bboxes(:,2)+szY;
szX=repmat(szX,1,nfids);szY=repmat(szY,1,nfids);
ctrX=repmat(ctrX,1,nfids);ctrY=repmat(ctrY,1,nfids);
if(strcmp(model.name,'cofw'))
phis1 = [(phis(:,1:nfids).*szX)+ctrX (phis(:,nfids+1:nfids*2).*szY)+ctrY...
phis(:,(nfids*2)+1:nfids*3)];
else
phis1 = [(phis(:,1:nfids).*szX)+ctrX (phis(:,nfids+1:nfids*2).*szY)+ctrY];
end
end
function phis=projectPose(model,phis,bboxes)
%project shape onto bounding box of object location
[N,D]=size(phis);
if(strcmp(model.name,'cofw')), nfids=D/3;
else nfids=D/2;
end
szX=bboxes(:,3)/2;szY=bboxes(:,4)/2;
ctrX=bboxes(:,1)+szX;ctrY=bboxes(:,2)+szY;
szX=repmat(szX,1,nfids);szY=repmat(szY,1,nfids);
ctrX=repmat(ctrX,1,nfids);ctrY=repmat(ctrY,1,nfids);
if(strcmp(model.name,'cofw'))
phis = [(phis(:,1:nfids)-ctrX)./szX (phis(:,nfids+1:nfids*2)-ctrY)./szY ...
phis(:,(nfids*2)+1:nfids*3)];
else phis = [(phis(:,1:nfids)-ctrX)./szX (phis(:,nfids+1:nfids*2)-ctrY)./szY];
end
end
function del = dif( phis0, phis1 )
% Compute diffs between phis0(i,:,t) and phis1(i,:) for each i and t.
[N,R,T]=size(phis0); assert(size(phis1,3)==1);
del = phis0-phis1(:,:,ones(1,1,T));
end
function [ds,dsAll] = dist( model, phis0, phis1 )
% Compute distance between phis0(i,:,t) and phis1(i,:) for each i and t.
%relative to the distance between pupils in the image (phis1 = gt)
[N,R,T]=size(phis0); del=dif(phis0,phis1);
if(strcmp(model.name,'cofw'))
nfids = size(phis1,2)/3;
else nfids = size(phis1,2)/2;
end
%Distance between pupils
if(strcmp(model.name,'lfpw') || strcmp(model.name,'cofw'))
distPup=sqrt(((phis1(:,17)-phis1(:,18)).^2) + ...
((phis1(:,17+nfids)-phis1(:,18+nfids)).^2));
distPup = repmat(distPup,[1,nfids,T]);
elseif(strcmp(model.name,'lfw'))
leyeX=mean(phis1(:,1:2),2);leyeY=mean(phis1(:,(1:2)+nfids),2);
reyeX=mean(phis1(:,7:8),2);reyeY=mean(phis1(:,(7:8)+nfids),2);
distPup=sqrt(((leyeX-reyeX).^2) + ((leyeY-reyeY).^2));
distPup = repmat(distPup,[1,nfids,T]);
elseif(strcmp(model.name,'helen'))
leye = [mean(phis1(:,135:154),2) mean(phis1(:,nfids+(135:154)),2)];
reye = [mean(phis1(:,115:134),2) mean(phis1(:,nfids+(115:134)),2)];
distPup=sqrt(((reye(:,1)-leye(:,1)).^2)+...
((reye(:,2)-leye(:,2)).^2));
distPup = repmat(distPup,[1,nfids,T]);
elseif(strcmp(model.name,'pie'))
leye = [mean(phis1(:,37:42),2) mean(phis1(:,nfids+(37:42)),2)];
reye = [mean(phis1(:,43:48),2) mean(phis1(:,nfids+(43:48)),2)];
distPup=sqrt(((reye(:,1)-leye(:,1)).^2)+...
((reye(:,2)-leye(:,2)).^2));
distPup = repmat(distPup,[1,nfids,T]);
elseif(strcmp(model.name,'apf'))
leye = [mean(phis1(:,7:8),2) mean(phis1(:,nfids+(7:8)),2)];
reye = [mean(phis1(:,9:10),2) mean(phis1(:,nfids+(9:10)),2)];
distPup=sqrt(((reye(:,1)-leye(:,1)).^2)+...
((reye(:,2)-leye(:,2)).^2));
end
dsAll = sqrt((del(:,1:nfids,:).^2) + (del(:,nfids+1:nfids*2,:).^2));
dsAll = dsAll./distPup; ds=mean(dsAll,2);%2*sum(dsAll,2)/R;
end
function [pCur,pGt,pGtN,pStar,imgIds,N,N1]=initTr(Is,faceHist,pGt,...
model,pStar,posInit,L,pad)
%Randomly initialize each training image with L shapes
[N,D]=size(pGt);assert(length(Is)==N);
if(isempty(pStar)),
[pStar,pGtN]=compPhiStar(model,pGt,Is,pad,[],posInit);
end
% augment data amount by random permutations of initial shape
pCur=repmat(pGt,[1,1,L]);
if(strcmp(model.name,'cofw'))
nfids = size(pGt,2)/3;
else nfids = size(pGt,2)/2;
end
for n=1:N
%select other images
imgsIds = 1:N;
nface = faceHist{n};
cor = zeros(N,1);
for i=1:N
cor(i,1) = corr2(nface,faceHist{imgsIds(i)});
end
[~,index] = sort(cor,'descend');
for l=1:L
bbox=posInit(n,:);
% maxDisp = posInit(n,3:4)/16;
% uncert=(2*rand(1,2)-1).*maxDisp;
% bbox(1:2)=bbox(1:2)+uncert;
pCur(n,:,l)=reprojectPose(model,pGtN(index(l+1),:),bbox);
end
end
if(strcmp(model.name,'cofw'))
pCur = reshape(permute(pCur,[1 3 2]),N*L,nfids*3);
else pCur = reshape(permute(pCur,[1 3 2]),N*L,nfids*2);
end
imgIds=repmat(1:N,[1 L]);pGt=repmat(pGt,[L 1]);pGtN=repmat(pGtN,[L 1]);
N1=N; N=N*L;
end
function [p, corindexT]=initTest(faceTrlbpHist,faceHist,bboxes,model,pStar,pGtN,RT1)
%Randomly initialize testing shapes using training shapes (RT1 different)
N=length(faceHist);N1=length(faceTrlbpHist);
D=size(pStar,2);phisN=pGtN;
if(isempty(bboxes)), p=pStar(ones(N,1),:);
%One bbox provided per image
elseif(ismatrix(bboxes) && size(bboxes,2)==4),
p=zeros(N,D,RT1);NTr=size(phisN,1);
corindexT = zeros(N1,N);
for n=1:N
%select other images
imgsIds = 1:NTr;
nface = faceHist{n};
cor = zeros(N1,1);
for i=1:N1
cor(i,1) = corr2(nface,faceTrlbpHist{imgsIds(i)});
end
[~,index] = sort(cor,'descend');
corindexT(:,n) = index;
for l=1:RT1
%permute bbox location slightly (not scale)
bbox=bboxes(n,:);
% maxDisp = bboxes(n,3:4)/16;
% uncert=(2*rand(1,2)-1).*maxDisp;
% bbox(1:2)=bbox(1:2)+uncert;
p(n,:,l)=reprojectPose(model,phisN(index(l),:),bbox);
end
end
%RT1 bboxes given, just reproject
elseif(size(bboxes,2)==4 && size(bboxes,3)==RT1)
p=zeros(N,D,RT1);NTr=size(phisN,1);
for n=1:N
imgsIds = randSample(NTr,RT1);
for l=1:RT1
p(n,:,l)=reprojectPose(model,phisN(imgsIds(l),:),...
bboxes(n,:,l));
end
end
%Previous results are given, use as is
elseif(size(bboxes,2)==D && size(bboxes,3)==RT1)
p=bboxes;
%VIDEO
elseif(iscell(bboxes))
p=zeros(N,D,RT1);NTr=size(pGtN,1);
for n=1:N
bb=bboxes{n}; ndet=size(bb,1);
imgsIds = randSample(NTr,RT1);
if(ndet<RT1), bbsIds=randint2(1,RT1,[1,ndet]);
else bbsIds=1:RT1;
end
for l=1:RT1
p(n,:,l)=reprojectPose(model,pGtN(imgsIds(l),:),...
bb(bbsIds(l),1:4));
end
end
end
end
|
github
|
pervadepyy/robust-initialization-rcpr-master
|
regApply.m
|
.m
|
robust-initialization-rcpr-master/regApply.m
| 4,183 |
utf_8
|
0194db40af69d752f32ff351e055bdfc
|
function ysSum = regApply(p,X,regInfo,regPrm)
% Apply boosted regressor.
%
% USAGE
% ysSum = regApply(p,X,regInfo,regPrm)
%
% INPUTS
% p - [NxD] initial pose
% X - [NxF] N length F feature vectors
% regInfo - structure containing regressor info, output of regTrain
% regPrm
% .type - [1] type of regression
% 1=fern, 2=linear
% .model - [] optional, model to use (see shapeGt)
% .ftrPrm - [REQ] prm struct (see shapeGt>ftrsGen)
% .K - [1] number of boosted regressors
% .Stot - [1] number of regressors trained at each round
% .prm - [REQ] regression parameters, relative to type
% .occlD - feature occlusion info, see shapeGt>ftrsCompDup
% .occlPrm - occlusion params for occlusion-centered (struct)
% regression, output of shapeGt>ftrsComp
% .nrows - [3] number of rows into which divide face
% .ncols - [3] number of cols into which divide face
% .nzones - [1] number of face zone from which regressors draw features
% .Stot - [3] number of regressors to train at each round
% .th - [.5] occlusion threshold
%
% OUTPUTS
% ysSum - [NxD] predicted output values
%
% See also
% demoRCPR, FULL_demoRCPR, rcprTrain, regTrain
%
% Copyright 2013 X.P. Burgos-Artizzu, P.Perona and Piotr Dollar.
% [xpburgos-at-gmail-dot-com]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Simplified BSD License [see bsd.txt]
%
% Please cite our paper if you use the code:
% Robust face landmark estimation under occlusion,
% X.P. Burgos-Artizzu, P. Perona, P. Dollar (c)
% ICCV'13, Sydney, Australia
type=regPrm.type;K=regPrm.K;Stot=regPrm.occlPrm.Stot;occlD=regPrm.occlD;
%Set up reg function
[N,D]=size(p);
switch(type)
case 1, regFun=@applyFern;
case 2, regFun=@applyLin;
end
%Prepare data
ysSum=zeros(N,D);
if(D>10 && Stot>1 && ~isempty(occlD))
ftrsOccl=zeros(N,K,Stot);
end
%For each boosted regressor
for k=1:K
%Occlusion-centered weighted mean
if(D>10 && Stot>1 && ~isempty(occlD))
ysPred = zeros(N,D,Stot);
for s=1:Stot
ysPred(:,:,s)=regFun(X,regInfo{k,s},regPrm);
ftrsOccl(:,k,s)=sum(occlD.featOccl(:,regInfo{k,s}.fids),2)./K;
end
%(WEIGHTED MEAN)
%ftrsOccl contains total occlusion of each Regressor
% weight should be inversely proportional, summing up to 1
weights=1-normalize(ftrsOccl(:,k,:));ss=sum(weights,3);
weights=weights./repmat(ss,[1,1,Stot]);
%when all are fully occluded, all get proportional weight
% (regular mean)
weights(ss==0,1,:)=1/Stot;
weights=repmat(weights,[1,D,1]);
for s=1:Stot
ysSum=ysSum+ysPred(:,:,s).*weights(:,:,s);
end
%Normal
else
ysPred=regFun(X,regInfo{k,:},regPrm);
ysPred = median(ysPred,3);
ysSum=ysSum+ysPred;
end
end
end
function Y_pred=applyFern(X,regInfo,regPrm)
% Apply single random fern regressor.
%
% USAGE
% Y_pred=applyFern(X,regInfo,regPrm)
%
% INPUTS
% X - [NxF] data measurements (features)
% regInfo - structure containing trained fern
% regPrm - regression parameters used
% .M - fern depth
%
% OUTPUTS
% Y_pred - [NxD] predicted output values
%
% See also
type=size(regInfo.fids,1);M=regPrm.M;
if(type==1), ftrs=X(:,regInfo.fids);
else ftrs=X(:,regInfo.fids(1,:))-X(:,regInfo.fids(2,:));
end
inds = fernsInds(ftrs,uint32(1:M),regInfo.thrs);
Y_pred=regInfo.ysFern(inds,:);
end
function Y_pred=applyLin(X,regInfo,~)
% Apply single linear regressor.
%
% USAGE
% [Y_pred,Y_conf]=applyLin(X,regInfo,~)
%
% INPUTS
% X - [NxF] data measurements (features)
% regInfo - structure containing trained linear regressor
%
% OUTPUTS
% Y_pred - [NxD] predicted output values
%
% See also
type=size(regInfo.fids,1);
if(type==1), ftrs=X(:,regInfo.fids);
else ftrs=X(:,regInfo.fids(1,:))-X(:,regInfo.fids(2,:));
end
Y_pred=ftrs*regInfo.W;
end
|
github
|
janismac/RacingTrajectoryOptimization-master
|
SL_acceleration_constraint_tangent.m
|
.m
|
RacingTrajectoryOptimization-master/SL_acceleration_constraint_tangent.m
| 834 |
utf_8
|
23a7dcf138c6c6075d65520f18e8f361
|
% Calculates a tangent to the elliptical acceleration constraints.
% p = parameter struct
% i = index of tangent
% x = [px,py,vx,vy] (previous state vector)
% Resulting constraint: Au * [ax,ay] <= b
function [Au,b] = acceleration_constraint_tangent(p,i,x)
vx = x(3);
vy = x(4);
v_sq = vx*vx + vy*vy;
v = sqrt(v_sq);
delta_angle = 2*pi / p.n_acceleration_limits;
c = cos(i*delta_angle);
s = sin(i*delta_angle);
v_idx = p.v_idx(v);
ay_max = p.a_lateral_max_list(v_idx);
ax_forward_max = p.a_forward_max_list(v_idx);
ax_backward_max = p.a_backward_max_list(v_idx);
if c > 0
ax_max = ax_forward_max;
else
ax_max = ax_backward_max;
end
Au = 1/sqrt(v_sq + 0.01) * [ay_max*c ax_max*s] * [vx vy; -vy vx];
b = ax_max * ay_max;
end
|
github
|
janismac/RacingTrajectoryOptimization-master
|
testTrack1.m
|
.m
|
RacingTrajectoryOptimization-master/testTrack1.m
| 1,856 |
utf_8
|
aa34787390e575cba25e6438fcb6cc98
|
function checkpoints = testTrack1
trackWidth = 7;
checkpoints = struct;
checkpoints.left = [0; trackWidth/2];
checkpoints.right = [0; -trackWidth/2];
checkpoints.center = [0; 0];
checkpoints.yaw = 0;
checkpoints.forward_vector = [1; 0];
checkpoints = add_turn(checkpoints, 0, 76, trackWidth);
checkpoints = add_turn(checkpoints, -0.25, 50, trackWidth);
checkpoints = add_turn(checkpoints, -0.25, 8, trackWidth);
checkpoints = add_turn(checkpoints, -0.1, 30, trackWidth);
checkpoints = add_turn(checkpoints, 0.1, 30, trackWidth);
checkpoints = add_turn(checkpoints, 0.5, 15, trackWidth);
checkpoints = add_turn(checkpoints, -0.5, 30, trackWidth);
checkpoints = add_turn(checkpoints, 0.5, 15, trackWidth);
checkpoints = add_turn(checkpoints, 0, 60, trackWidth);
checkpoints = add_turn(checkpoints, -0.25, 10, trackWidth);
checkpoints = add_turn(checkpoints, -0.25, 20, trackWidth);
checkpoints = add_turn(checkpoints, 0, 55, trackWidth);
checkpoints = add_turn(checkpoints, -0.25, 90.3, trackWidth);
checkpoints = add_turn(checkpoints, 0, 5.3, trackWidth);
checkpoints = add_turn(checkpoints, -0.25, 20, trackWidth);
checkpoints = checkpoints(2:end);
end
function checkpoints = add_turn(checkpoints, phi, L, width)
kappa = (phi*(2*pi))/L;
N = 40;
ds = L / N;
for i=1:N
checkpoints(end+1).yaw = checkpoints(end).yaw + kappa * ds;
c = cos(checkpoints(end).yaw);
s = sin(checkpoints(end).yaw);
f = [c;s];
n = [-s;c];
checkpoints(end).center = checkpoints(end-1).center + f * ds;
checkpoints(end).left = checkpoints(end).center + n * width/2;
checkpoints(end).right = checkpoints(end).center - n * width/2;
checkpoints(end).forward_vector = f;
end
end
|
github
|
janismac/RacingTrajectoryOptimization-master
|
mod1.m
|
.m
|
RacingTrajectoryOptimization-master/track_polygons/mod1.m
| 80 |
utf_8
|
6792ced4447cf40b17de293cde024282
|
% Modulo for one-based indices
function y = mod1(i,N)
y = mod(i-1,N)+1;
end
|
github
|
janismac/RacingTrajectoryOptimization-master
|
add_overlaps.m
|
.m
|
RacingTrajectoryOptimization-master/track_polygons/add_overlaps.m
| 2,956 |
utf_8
|
09372d8e3c3b5ccd2c19d0b72383ca46
|
function new_track = add_overlaps(track)
% convert to constraints
for i = 1:length(track.polygons)
[track.polygons(i).A,track.polygons(i).b] = vert2con(track.vertices(:,track.polygons(i).vertex_indices)');
end
% find neighbor intersections
for i1 = 1:length(track.polygons)
% find shared vertices
i2 = mod1(i1+1, length(track.polygons));
nv1 = length(track.polygons(i1).vertex_indices);
nv2 = length(track.polygons(i2).vertex_indices);
[I,~] = find(repmat(track.polygons(i1).vertex_indices, nv2, 1) == repmat(track.polygons(i2).vertex_indices', 1, nv1));
shared_vertices = track.polygons(i2).vertex_indices(I);
assert(numel(shared_vertices) == 2);
% find shared (opposite) constraints
p1 = track.vertices(:, shared_vertices(1));
p2 = track.vertices(:, shared_vertices(2));
n = [0 -1;1 0]* (p1-p2);
n = n ./ norm(n);
b = n'*p1;
I1 = find(abs(abs(track.polygons(i1).b) - abs(b)) < 1e-10);
I2 = find(abs(abs(track.polygons(i2).b) - abs(b)) < 1e-10);
assert(numel(I1) == 1);
assert(numel(I2) == 1);
% remove shared constraints
A1 = track.polygons(i1).A;
b1 = track.polygons(i1).b;
A2 = track.polygons(i2).A;
b2 = track.polygons(i2).b;
A1(I1,:) = [];
b1(I1,:) = [];
A2(I2,:) = [];
b2(I2,:) = [];
track.polygons(i1).A_intersection = [A1;A2];
track.polygons(i1).b_intersection = [b1;b2];
end
new_track = struct;
new_track.vertices = nan(2,0);
% add overlaps
for i1 = 1:length(track.polygons)
i0 = mod1(i1-1, length(track.polygons));
i2 = mod1(i1+1, length(track.polygons));
vertices_0 = con2vert([track.polygons(i0).A_intersection; track.polygons(i0).A], [track.polygons(i0).b_intersection; track.polygons(i0).b]);
vertices_1 = track.vertices(:, track.polygons(i1).vertex_indices)';
vertices_2 = con2vert([track.polygons(i1).A_intersection; track.polygons(i2).A], [track.polygons(i1).b_intersection; track.polygons(i2).b]);
vertices_union = [vertices_0; vertices_1; vertices_2];
[~,vol_0] = convhull(vertices_0);
[~,vol_1] = convhull(vertices_1);
[~,vol_2] = convhull(vertices_2);
[K,vol_union] = convhull(vertices_union,'simplify',true);
assert(abs(vol_0+vol_1+vol_2-vol_union) < 1e-10);
vertices_union = vertices_union(K(2:end),:);
indices = size(new_track.vertices,2) + (1 : size(vertices_union, 1));
new_track.vertices = [new_track.vertices vertices_union'];
new_track.polygons(i1).vertex_indices = indices;
[new_track.polygons(i1).A, new_track.polygons(i1).b] = vert2con(vertices_union);
end
end
|
github
|
scstein/fSOFI-master
|
fourierInterpolation.m
|
.m
|
fSOFI-master/fourierInterpolation.m
| 17,839 |
utf_8
|
520266ebc2bfb7df2c9cf8cc13445ebc
|
function [ img ] = fourierInterpolation( img, itp_fac, mirrorMode )
% USAGE: [ img ] = fourierInterpolation( img, itp_fac, padding )
% Interpolation of a 2D or 3D input image using zero padding in the Fourier
% domain. The input data can be mirrored along the lateral/axial or both
% dimensions to make the borders periodic, which reduces artifacts.
% img - 2D or 3D input image
% itp_fac - Interpolation factor along each dimension [ipX,ipY] / [ipX,ipY,ipZ]
% If a single number is given, the same factor is used for all
% dimensions. The output is of size itp_fac.*size(img)
% mirror - Specifies wether to use periodic mirroring of the input data or
% not (example see fSOFI publication). The padding prevents
% artifacts from non-periodic borders and is essential if a low
% number of pixels is available along a specific dimension.
% Possible values: 'none','lateral','axial','both'
%
% Author: Simon Christoph Stein
% E-Mail: [email protected]
% Date: 2017
itp_fac = itp_fac(:).';
if ~( numel(itp_fac) == 1 || numel(itp_fac) == ndims(img))
error('%i interpolation factors specified. Give either one for all dimension or one per dimension!', numel(itp_fac))
end
% If all interpolation factors are 1, skip the interpolation
if sum(itp_fac == ones(1,numel(itp_fac))) == numel(itp_fac)
return
end
if numel(itp_fac) == 1
itp_fac = repmat(itp_fac,[1,ndims(img)]);
end
noip = (itp_fac==1); % for interpolation factors of 1, we perform neither padding nor interpolation
if nargin < 3 || isempty(mirrorMode)
mirrorMode = 'none';
end
input_sz = size(img); % Input size
% Starting index to cut out from upsampled periodic image
sz = input_sz;
sz = sz - ~mod(sz,2);
idx = ceil(sz/2)+1 + (itp_fac-1).*floor(sz/2);
switch ndims(img)
case 2
switch mirrorMode
case 'none'
% img = interpft(img, itp_fac*size(img,1), 1);% Interpolate x-dir
% img = interpft(img, itp_fac*size(img,2), 2);% Interpolate y-dir
newsz = round(itp_fac.*size(img));
img = fInterp_2D(img, newsz);
return
case 'lateral'
padsize = [size(img,1)/2,size(img,2)/2];
padsize(noip) = 0;
img = padarray(img,ceil(padsize),'symmetric','pre');
img = padarray(img,floor(padsize),'symmetric','post');
% Fourier interpolation
% img = interpft(img, itp_fac*size(img,1)-(itp_fac-1), 1);% Interpolate x-dir
% img = interpft(img, itp_fac*size(img,2)-(itp_fac-1), 2);% Interpolate y-dir
newsz = round(itp_fac.*size(img)-(itp_fac-1));
img = fInterp_2D(img, newsz);
% Cut out relevant part of padded image
img = get_valid_part(img);
return
case 'axial'
error('Padding ''axial'' only possible for 3D data.')
case 'both'
error('Padding ''both'' only possible for 3D data.')
otherwise
error('Unknown padding option ''%s''.', mirrorMode);
end
case 3
switch mirrorMode
case 'none'
% img = interpft3D(img, itp_fac*size(img,1), 1);% Interpolate x-dir
% img = interpft3D(img, itp_fac*size(img,2), 2);% Interpolate y-dir
% img = interpft3D(img, itp_fac*size(img,3), 3);% Interpolate z-di
newsz = round(itp_fac.*size(img));
img = fInterp_3D(img, newsz);
return
case 'lateral'
padsize = [size(img,1)/2,size(img,2)/2, 0];
padsize(noip) = 0;
img = padarray(img,ceil(padsize),'symmetric','pre');
img = padarray(img,floor(padsize),'symmetric','post');
% Fourier interpolation
%img = interpft3D(img, itp_fac*size(img,1)-(itp_fac-1), 1);% Interpolate x-dir
%img = interpft3D(img, itp_fac*size(img,2)-(itp_fac-1), 2);% Interpolate y-dir
%img = interpft3D(img, itp_fac*size(img,3), 3);% Interpolate z-dir
newsz = round([itp_fac(1)*size(img,1)-(itp_fac(1)-1), itp_fac(2)*size(img,2)-(itp_fac(2)-1), itp_fac(3)*size(img,3)]);
img = fInterp_3D(img, newsz);
% Cut out relevant part of padded image
img = get_valid_part(img);
return
case 'axial'
padsize = [0,0, size(img,3)/2];
padsize(noip) = 0;
img = padarray(img,ceil(padsize),'symmetric','pre');
img = padarray(img,floor(padsize),'symmetric','post');
% Fourier interpolation
% img = interpft3D(img, itp_fac*size(img,1), 1);% Interpolate x-dir
% img = interpft3D(img, itp_fac*size(img,2), 2);% Interpolate y-dir
% img = interpft3D(img, itp_fac*size(img,3)-(itp_fac-1), 3);% Interpolate z-dir
newsz = round([itp_fac(1)*size(img,1), itp_fac(2)*size(img,2), itp_fac(3)*size(img,3)-(itp_fac(3)-1)]);
img = fInterp_3D(img, newsz);
% Cut out relevant part of padded image
img = get_valid_part(img);
return
case 'both'
padsize = size(img)/2;
padsize(noip) = 0;
img = padarray(img,ceil(padsize),'symmetric','pre');
img = padarray(img,floor(padsize),'symmetric','post');
% Fourier interpolation
% img = interpft3D(img, itp_fac*size(img,1)-(itp_fac-1), 1);% Interpolate x-dir
% img = interpft3D(img, itp_fac*size(img,2)-(itp_fac-1), 2);% Interpolate y-dir
% img = interpft3D(img, itp_fac*size(img,3)-(itp_fac-1), 3);% Interpolate z-dir
newsz = round(itp_fac.*size(img)-(itp_fac-1));
img = fInterp_3D(img, newsz);
% Cut out relevant part of padded image
img = get_valid_part(img);
return
otherwise
error('Unknown padding option ''%s''.', mirrorMode);
end
end
%% Nested functions
function img = get_valid_part(img)
% What part of the image to cut out depends on the dimensions
% padding was applied to before interpolation
%
% doip(iDim): interpolation (with padding) was performed,
% noip(iDim): no interpolation (with padding) was performed
doip = ~noip;
switch ndims(img)
case 2
if noip(1) && noip(2)
return
else
if noip(1) && doip(2)
img = img(:, idx(2):idx(2)+itp_fac(2)*input_sz(2)-1);
else
if doip(1) && noip(2)
img = img(idx(1):idx(1)+itp_fac(1)*input_sz(1)-1, :);
else
if doip(1) && doip(2)
img = img(idx(1):idx(1)+itp_fac(1)*input_sz(1)-1, idx(2):idx(2)+itp_fac(2)*input_sz(2)-1);
end
end
end
end
return
case 3
switch mirrorMode
case 'lateral'
if noip(1) && noip(2)
return
else
if noip(1) && doip(2)
img = img(:, idx(2):idx(2)+itp_fac(2)*input_sz(2)-1,:);
else
if doip(1) && noip(2)
img = img(idx(1):idx(1)+itp_fac(1)*input_sz(1)-1, :,:);
else
if doip(1) && doip(2)
img = img(idx(1):idx(1)+itp_fac(1)*input_sz(1)-1, idx(2):idx(2)+itp_fac(2)*input_sz(2)-1,:);
end
end
end
end
case 'axial'
if doip(3)
img = img(:,:, idx(3):idx(3)+itp_fac(3)*input_sz(3)-1);
else
return
end
return
case 'both'
if noip(3) %% No z-interpolation (with padding)
if noip(1) && noip(2)
return
else
if noip(1) && doip(2)
img = img(:, idx(2):idx(2)+itp_fac(2)*input_sz(2)-1,:);
else
if doip(1) && noip(2)
img = img(idx(1):idx(1)+itp_fac(1)*input_sz(1)-1, :,:);
else
if doip(1) && doip(2)
img = img(idx(1):idx(1)+itp_fac(1)*input_sz(1)-1, idx(2):idx(2)+itp_fac(2)*input_sz(2)-1,:);
end
end
end
end
else %% With z-interpolation
if noip(1) && noip(2)
img = img(:,:,idx(3):idx(3)+itp_fac*input_sz(3)-1);
else
if noip(1) && doip(2)
img = img(:, idx(2):idx(2)+itp_fac(2)*input_sz(2)-1,idx(3):idx(3)+itp_fac(3)*input_sz(3)-1);
else
if doip(1) && noip(2)
img = img(idx(1):idx(1)+itp_fac(1)*input_sz(1)-1, :,idx(3):idx(3)+itp_fac(3)*input_sz(3)-1);
else
if doip(1) && doip(2)
img = img(idx(1):idx(1)+itp_fac(1)*input_sz(1)-1, idx(2):idx(2)+itp_fac(2)*input_sz(2)-1,idx(3):idx(3)+itp_fac(3)*input_sz(3)-1);
end
end
end
end
end
end
end
end
end
function img_ip = fInterp_3D(img, newsz)
% Fourier interpolation of 3D image 'img' to new size 'newsz' = [nx,ny,nz]
% This is similar to performing MATLABs interpft along all dimensions
% individually, but faster.
% Fourier interpolation
sz = size(img);
% If necessary, increase ny by an integer multiple to make ny > m.
if sum(newsz == 0) >= 1
img_ip = [];
return
end
isgreater = newsz >= sz;
incr = zeros(3,1);
for iDim = 1:3
if isgreater(iDim)
incr(iDim) = 1;
else
incr = floor(sz(iDim)/newsz(iDim)) + 1;
newsz(iDim) = incr(iDim)*newsz(iDim);
end
end
img_ip = zeros(newsz);
nyqst = ceil((sz+1)/2);
img = newsz(1)/sz(1)*newsz(2)/sz(2)*newsz(3)/sz(3)* fftn(img);% multiplicative factor conserves the counts at the original positions
% zero padding, need to copy all 8 edges of the image cube
% note: xl:'x low', xh:'x high'
img_ip(1:nyqst(1),1:nyqst(2),1:nyqst(3)) = img(1:nyqst(1),1:nyqst(2),1:nyqst(3)); % xl, yl, zl
img_ip(end-(sz(1)-nyqst(1))+1:end, 1:nyqst(2), 1:nyqst(3)) = img(nyqst(1)+1:sz(1),1:nyqst(2),1:nyqst(3)); % xh, yl, zl
img_ip(1:nyqst(1),end-(sz(2)-nyqst(2))+1:end,1:nyqst(3)) = img(1:nyqst(1), nyqst(2)+1:sz(2) ,1:nyqst(3)); % xl, yh, zl
img_ip(1:nyqst(1),1:nyqst(2),end-(sz(3)-nyqst(3))+1:end) = img(1:nyqst(1),1:nyqst(2), nyqst(3)+1:sz(3)); % xl, yl, zh
img_ip(end-(sz(1)-nyqst(1))+1:end, end-(sz(2)-nyqst(2))+1:end, 1:nyqst(3)) = img(nyqst(1)+1:sz(1), nyqst(2)+1:sz(2),1:nyqst(3)); % xh, yh, zl
img_ip(end-(sz(1)-nyqst(1))+1:end, 1:nyqst(2), end-(sz(3)-nyqst(3))+1:end) = img(nyqst(1)+1:sz(1),1:nyqst(2), nyqst(3)+1:sz(3)); % xh, yl, zh
img_ip(1:nyqst(1), end-(sz(2)-nyqst(2))+1:end, end-(sz(3)-nyqst(3))+1:end) = img(1:nyqst(1),nyqst(2)+1:sz(2),nyqst(3)+1:sz(3)); % xl, yh, zh
img_ip(end-(sz(1)-nyqst(1))+1:end, end-(sz(2)-nyqst(2))+1:end, end-(sz(3)-nyqst(3))+1:end) = img(nyqst(1)+1:sz(1),nyqst(2)+1:sz(2),nyqst(3)+1:sz(3)); % xh, yh, zh
rm = rem(sz,2);
if rm(1) == 0 && newsz(1) ~= sz(1)
img_ip(nyqst(1), :, :) = img_ip(nyqst(1), :, :)/2;
img_ip(nyqst(1) + newsz(1)-sz(1), :, :) = img_ip(nyqst(1), :, :);
end
if rm(2) == 0 && newsz(2) ~= sz(2)
img_ip(:, nyqst(2), :) = img_ip(:, nyqst(2), :)/2;
img_ip(:, nyqst(2) + newsz(2)-sz(2), :) = img_ip(:, nyqst(2), :);
end
if rm(3) == 0 && newsz(3) ~= sz(3)
img_ip(:, :, nyqst(3)) = img_ip(:, :, nyqst(3))/2;
img_ip(:, :, nyqst(3) + newsz(3)-sz(3)) = img_ip(:, :, nyqst(3));
end
img_ip = real(ifftn(img_ip));
% Skip points if neccessary
img_ip = img_ip(1:incr(1):newsz(1), 1:incr(2):newsz(2), 1:incr(3):newsz(3));
end
function img_ip = fInterp_2D(img, newsz)
% Fourier interpolation of 2D image 'img' to new size 'newsz' = [nx,ny]
% This is similar to performing MATLABs interpft along all dimensions
% individually, but faster.
% Fourier interpolation
sz = size(img);
% If necessary, increase ny by an integer multiple to make ny > m.
if sum(newsz == 0) >= 1
img_ip = [];
return
end
isgreater = newsz >= sz;
incr = zeros(2,1);
for iDim = 1:2
if isgreater(iDim)
incr(iDim) = 1;
else
incr = floor(sz(iDim)/newsz(iDim)) + 1;
newsz(iDim) = incr(iDim)*newsz(iDim);
end
end
img_ip = zeros(newsz);
nyqst = ceil((sz+1)/2);
img = newsz(1)/sz(1)*newsz(2)/sz(2)* fft2(img);% multiplicative factor conserves the counts at the original positions
% zero padding, need to copy all 4 edges of the image plane
% note: xl:'x low', xh:'x high'
img_ip(1:nyqst(1),1:nyqst(2)) = img(1:nyqst(1),1:nyqst(2)); % xl, yl
img_ip(end-(sz(1)-nyqst(1))+1:end, 1:nyqst(2)) = img(nyqst(1)+1:sz(1),1:nyqst(2)); % xh, yl
img_ip(1:nyqst(1),end-(sz(2)-nyqst(2))+1:end) = img(1:nyqst(1), nyqst(2)+1:sz(2)); % xl, yh
img_ip(end-(sz(1)-nyqst(1))+1:end, end-(sz(2)-nyqst(2))+1:end) = img(nyqst(1)+1:sz(1), nyqst(2)+1:sz(2)); % xh, yh, zl
rm = rem(sz,2);
if rm(1) == 0 && newsz(1) ~= sz(1)
img_ip(nyqst(1), :) = img_ip(nyqst(1), :)/2;
img_ip(nyqst(1) + newsz(1)-sz(1), :) = img_ip(nyqst(1), :);
end
if rm(2) == 0 && newsz(2) ~= sz(2)
img_ip(:, nyqst(2)) = img_ip(:, nyqst(2))/2;
img_ip(:, nyqst(2) + newsz(2)-sz(2)) = img_ip(:, nyqst(2));
end
img_ip = real(ifft2(img_ip));
% Skip points if neccessary
img_ip = img_ip(1:incr(1):newsz(1), 1:incr(2):newsz(2));
end
function y = interpft3D(x,ny,dim)
% !! Patched Mathworks interpft function which works on 3D data !!
%
%
%INTERPFT 1-D interpolation using FFT method.
% Y = INTERPFT(X,N) returns a vector Y of length N obtained
% by interpolation in the Fourier transform of X.
%
% If X is a matrix, interpolation is done on each column.
% If X is an array, interpolation is performed along the first
% non-singleton dimension.
%
% INTERPFT(X,N,DIM) performs the interpolation along the
% dimension DIM.
%
% Assume x(t) is a periodic function of t with period p, sampled
% at equally spaced points, X(i) = x(T(i)) where T(i) = (i-1)*p/M,
% i = 1:M, M = length(X). Then y(t) is another periodic function
% with the same period and Y(j) = y(T(j)) where T(j) = (j-1)*p/N,
% j = 1:N, N = length(Y). If N is an integer multiple of M,
% then Y(1:N/M:N) = X.
%
% Example:
% % Set up a triangle-like signal signal to be interpolated
% y = [0:.5:2 1.5:-.5:-2 -1.5:.5:0]; % equally spaced
% factor = 5; % Interpolate by a factor of 5
% m = length(y)*factor;
% x = 1:factor:m;
% xi = 1:m;
% yi = interpft(y,m);
% plot(x,y,'o',xi,yi,'*')
% legend('Original data','Interpolated data')
%
% Class support for data input x:
% float: double, single
%
% See also INTERP1.
% Robert Piche, Tampere University of Technology, 10/93.
% Copyright 1984-2006 The MathWorks, Inc.
% $Revision: 5.15.4.5 $ $Date: 2010/08/23 23:11:51 $
error(nargchk(2,3,nargin,'struct'));
if nargin==2,
[x,nshifts] = shiftdim(x);
if isscalar(x), nshifts = 1; end % Return a row for a scalar
elseif nargin==3,
perm = [dim:max(length(size(x)),dim) 1:dim-1];
x = permute(x,perm);
end
siz = size(x);
[m,n,l] = size(x);
if ~isscalar(ny)
error(message('MATLAB:interpft:NonScalarN'));
end
% If necessary, increase ny by an integer multiple to make ny > m.
if ny > m
incr = 1;
else
if ny==0, y=[]; return, end
incr = floor(m/ny) + 1;
ny = incr*ny;
end
a = fft(x,[],1);
nyqst = ceil((m+1)/2);
b = [a(1:nyqst,:,:) ; zeros(ny-m,n,l) ; a(nyqst+1:m,:,:)];
if rem(m,2) == 0
b(nyqst,:,:) = b(nyqst,:,:)/2;
b(nyqst+ny-m,:,:) = b(nyqst,:,:);
end
y = ifft(b,[],1);
if isreal(x), y = real(y); end
y = y * ny / m;
y = y(1:incr:ny,:,:); % Skip over extra points when oldny <= m.
if nargin==2,
y = reshape(y,[ones(1,nshifts) size(y,1) siz(2:end)]);
elseif nargin==3,
y = ipermute(y,perm);
end
end
|
github
|
wmacnair/TreeTop-master
|
install_treetop.m
|
.m
|
TreeTop-master/install_treetop.m
| 6,879 |
utf_8
|
f80b92397578e60037a763ef93353b2f
|
%% install_treetop: function to add treetop to the path, and check that several necessary compiled functions are functional
function [] = install_treetop()
% set up path
treetop_path()
% check compiled functions
check_compiled_functions()
end
function treetop_path()
% save changes to path and startup.m
prompt = 'TreeTop needs to be added to MATLAB''s path to run.\nWould you like to save this change to the path?\n(Saving the change means the path variable is slightly larger.\nNot saving means that you will need to run this function again, the next time you want to use TreeTop.)\nY/N [default is N]:';
str = input(prompt, 's');
if isempty(str)
str = 'N';
end
str = upper(str);
if ~ismember(str, {'Y', 'N'})
error('input must be one of: Y, y, N, n')
end
SAVE_PERMANENTLY = strcmp(str, 'Y');
% add paths
[install_dir, ~, ~] = fileparts(mfilename('fullpath'));
addpath(genpath(install_dir));
if (SAVE_PERMANENTLY)
savepath;
end
end
function check_compiled_functions()
% check this function
dijk_mex = check_mex_function('dijkstra.cpp', './TreeTop/private');
mi_mex = check_mi_toolbox('MIToolboxMex.c', './MIToolbox/matlab');
% check each function works
dijk_works = false;
if dijk_mex
dijk_works = check_dijkstra_works();
end
mi_works = false;
if mi_mex
mi_works = check_mi_works();
end
% report results
if dijk_works & mi_works
fprintf('All compiled files available and working; TreeTop should run without any problems\n');
elseif dijk_works & ~mi_works
fprintf('The relevant compiled file for the mutual information toolbox was either not available or not working.\n')
fprintf('treetop should run ok, but outputs from the optional treetop_pre_run script will be incomplete.\n')
fprintf('To fix this, make sure you have a valid compiler installed and\n')
fprintf('compile the function ./MIToolbox/matlab/MIToolboxMex.\n');
elseif ~dijk_works
fprintf('The relevant compiled file for the function dijkstra was either not available or not working.\n')
fprintf('treetop needs this to run; to fix this, make sure you have a valid compiler installed and\n')
fprintf('compile the function ./TreeTop/private/dijkstra.\n');
end
end
function mex_exists = check_mex_function(fn_name, fn_dir)
start_dir = cd;
cd(fn_dir)
fprintf('testing whether function %s is compiled\n', fn_name)
% Check input filename
assert(ischar(fn_name),'source_file must be a string')
% Check extension is specified
assert(~isempty(strfind(fn_name,'.')),'source_file: no file extension specified')
% Locate source file
[pathstr, name, ext] = fileparts(which(fn_name));
% Create filename, mex filename
filename = [pathstr filesep name ext];
mexfilename = [pathstr filesep name '.' mexext];
% check whether source exists
mex_exists = false;
if strcmp(pathstr,'')
% source file not found
fprintf([source_file ': not found'])
% now check whether mexfile exists
elseif exist(mexfilename, 'file') ~= 3
% if source file does not exist, try to compile
disp(['Compiling "' name ext '".'])
% compile, with options if appropriate
try
mex(fn_name)
fprintf('Function %s successfully compiled\n', fn_name);
mex_exists = true;
catch lasterr
fprintf('Could not compile function %s. \n', fn_name);
end
else
mex_exists = true;
end
% switch back to original directory
cd(start_dir)
end
function mex_exists = check_mi_toolbox(fn_name, fn_dir)
start_dir = cd;
cd(fn_dir)
fprintf('testing whether function %s is compiled\n', fn_name)
% Check input filename
assert(ischar(fn_name),'source_file must be a string')
% Check extension is specified
assert(~isempty(strfind(fn_name,'.')),'source_file: no file extension specified')
% Locate source file
[pathstr, name, ext] = fileparts(which(fn_name));
% Create filename, mex filename
filename = [pathstr filesep name ext];
mexfilename = [pathstr filesep name '.' mexext];
% check whether source exists
mex_exists = false;
if strcmp(pathstr,'')
% source file not found
fprintf([source_file ': not found'])
% now check whether mexfile exists
elseif exist(mexfilename, 'file') ~= 3
% if source file does not exist, try to compile
disp(['Compiling "' name ext '".'])
% compile, with options if appropriate
try
CompileMIToolbox
fprintf('Function %s successfully compiled\n', fn_name);
mex_exists = true;
catch lasterr
fprintf('Could not compile function %s. \n', fn_name);
end
else
mex_exists = true;
end
% switch back to original directory
cd(start_dir)
end
%% check_dijkstra_works:
function [dijk_works] = check_dijkstra_works()
dijk_works = false;
% define things to test with
n_nodes = 10;
G = zeros(n_nodes);
for ii = 1:n_nodes-1
G(ii, ii+1) = 1;
G(ii+1, ii) = 1;
end
G = sparse(G);
D_true = zeros(n_nodes);
for ii = 1:n_nodes
D_true(ii, :) = abs((1:n_nodes) - ii);
end
% check dijkstra works on simple test case
current_dir = cd;
cd('./TreeTop/private')
try
D = dijkstra(G, (1:n_nodes)');
dijk_works = all(all(abs(D - D_true) < 1e-14));
catch lasterr
% fprintf('dijkstra did not work\n')
end
cd(current_dir)
end
%% check_mi_works:
function [mi_works] = check_mi_works()
mi_works = false;
% define things to test with
n_entries = 10;
X = repmat(1:n_entries, 1, n_entries);
mi_true = n_entries;
% check MI works on simple test case
current_dir = cd;
cd('./TreeTop/private')
try
mi_val = MIToolboxMex(7, X', X');
mi_works = abs(mi_true - 2^mi_val) < 1e-14;
catch lasterr
fprintf('MI toolbox did not work\n')
end
cd(current_dir)
end
% Max's comments:
% Firstly: I would add a disclaimer at the start that matlab needs to have a C compiler installed (which has to be done manually for mac)
% Secondly: regarding the output_dir variable which holds the string for the output path. You state that this path "has the form /parent_folder/output_name," with parent_folder existing but output_name not and only being generated by the pre run function. For me the whole path needs to already exist otherwise it throws an error.
% Regarding the treetop_pre_run function: here I first had to go to: path/TreeTop-master/MIToolbox/matlab and manually compile the MIToolbox.m function otherwise it would throw an error. (It does not compile automatically)
% Then when running treetop(input_struct, options_struct): I had to rename the (TreeTop-master/TreeTop/private folder because I could not add it to the path when it was named private^^
% Also the compiled version of the dijkstra.m inside TreeTop/private does not work.
% I had to download the whole Toolbox and then also manually compile the dijkstra function. Then I had to make sure that treetop uses this version and not the one inside /TreeTop/private
% But thats already all. Everything else runs smoothly
|
github
|
wmacnair/TreeTop-master
|
treetop_trees.m
|
.m
|
TreeTop-master/TreeTop/treetop_trees.m
| 14,107 |
utf_8
|
2a595d55ff801ddcce2abf31f74b5d49
|
%% treetop_trees: (1) load data, calculate density, take subsample (2) identify outlier / downsample points
% (3) do kmeans++ seeding, allocate each point to closest seed (4) repeatedly: sample one point from each cluster, fit tree
% between them, record marker values and which celltypes these were (5) do layouts
function treetop_trees(input_struct, options_struct)
% do seed
rng(options_struct.seed);
% load up data, calculate density if necessary, take subsample to make it more manageable
[sample_struct, options_struct] = load_and_process_data(input_struct, options_struct);
% find appropriate outlier and threshold points
[outlier_idx, downsample_idx] = calc_outlier_downsample_idx(sample_struct, options_struct);
% do k-means ++ seeding (start with small # of clusters, for ease of HK layouts)
% also allocate each point to one of these clusters (basically like )
[centroids_idx, cell_assignments] = partition_cells(sample_struct, outlier_idx, downsample_idx, options_struct);
% error('stop here')
% set up tree variables
n_nodes = numel(centroids_idx);
n_trees = options_struct.n_trees;
tree_cell = cell(n_trees, 1);
tree_dist_cell = cell(n_trees, 1);
node_idx_array = NaN(n_trees, n_nodes);
% set up reproducible rng
if options_struct.pool_flag
spmd
cmrg = RandStream('mrg32k3a', 'seed', options_struct.seed);
RandStream.setGlobalStream(cmrg);
end
% sample all the trees
fprintf('sampling %d trees (. = 50): ', n_trees)
parfor ii = 1:n_trees
% set up random stream
s = RandStream.getGlobalStream();
s.Substream = ii;
if mod(ii, 50) == 0
fprintf([char(8), '. '])
end
% sample one point from each cluster, connect as MST
[this_node_idx, this_tree, this_tree_dist] = get_a_tree(sample_struct, cell_assignments, options_struct);
% store output
node_idx_array(ii, :) = this_node_idx;
tree_cell{ii} = this_tree;
tree_dist_cell{ii} = this_tree_dist;
end
else
% sample all the trees
fprintf('sampling %d trees (. = 50): ', n_trees)
for ii = 1:n_trees
% set up random stream
rng(ii);
if mod(ii, 50) == 0
fprintf('.')
end
% sample one point from each cluster, connect as MST
[this_node_idx, this_tree, this_tree_dist] = get_a_tree(sample_struct, cell_assignments, options_struct);
% store output
node_idx_array(ii, :) = this_node_idx;
tree_cell{ii} = this_tree;
tree_dist_cell{ii} = this_tree_dist;
end
fprintf('\n')
end
% save output as union / freq graph
[union_graph, freq_union_graph] = calculate_union_graphs(tree_cell, tree_dist_cell, input_struct, options_struct);
% save assignment of every cell to a reference cell
save_cell_assignments(input_struct, sample_struct, cell_assignments);
% save marker values
save_marker_values(input_struct, sample_struct, centroids_idx, cell_assignments);
% save tree values
save_sampled_trees(input_struct, options_struct, outlier_idx, downsample_idx, centroids_idx, cell_assignments, node_idx_array, tree_cell, tree_dist_cell, sample_struct);
end
%% load_and_process_data:
function [sample_struct, options_struct] = load_and_process_data(input_struct, options_struct)
% open all files, stitch together (with sample labels)
all_struct = get_all_files(input_struct);
% possibly remove ball around zero
all_struct = remove_zero_ball(all_struct, options_struct);
% take subsample to make things more manageable (maybe 100k?)
sample_struct = take_sample(all_struct, options_struct);
% check # ref cells
options_struct = check_ref_cells(all_struct, options_struct);
% get density values
sample_struct = add_density_values(sample_struct, options_struct);
end
%% take_sample:
function sample_struct = take_sample(all_struct, options_struct)
% skip if not specified
if ~isfield(options_struct, 'sample_size')
sample_struct = all_struct;
return
end
% otherwise, unpack
fprintf('taking smaller sample\n')
sample_size = options_struct.sample_size;
used_data = all_struct.used_data;
extra_data = all_struct.extra_data;
% pick sample
n_cells = size(used_data, 1);
if sample_size < n_cells
sample_idx = randsample(n_cells, sample_size);
else
fprintf('requested sample size (%d) >= # cells (%d); all cells taken as sample\n', sample_size, n_cells);
sample_idx = 1:n_cells;
end
% restrict to this
sample_used = used_data(sample_idx, :);
sample_labels = all_struct.all_labels(sample_idx);
if isempty(extra_data)
sample_extra = [];
else
sample_extra = extra_data(sample_idx, :);
end
% assemble output
sample_struct = all_struct;
sample_struct.used_data = sample_used;
sample_struct.extra_data = sample_extra;
sample_struct.all_labels = sample_labels;
% do bit for keeping track of recursion
if isfield(all_struct, 'cell_assignments_top')
sample_struct.cell_assignments_top = all_struct.cell_assignments_top(sample_idx);
end
% do bit for keeping track of recursion
if isfield(all_struct, 'branch_parent_point')
sample_struct.branch_parent_point = all_struct.branch_parent_point(sample_idx);
end
end
%% check_ref_cells: check # ref cells
function options_struct = check_ref_cells(all_struct, options_struct)
% unpack
n_ref_cells = options_struct.n_ref_cells;
n_total = size(all_struct.used_data, 1);
% checks there are at least 10 cells per node
ratio_threshold = 10;
cell_ratio = n_total / n_ref_cells;
ratio_check = cell_ratio >= ratio_threshold;
if ~ratio_check
% change to smallest multiple of 10 achieving this threshold
n_ref_cells = floor(n_total / ratio_threshold / 10 )*10;
end
% check there are at least 20 nodes
n_ref_cutoff = 20;
n_ref_check = n_ref_cells >= n_ref_cutoff;
if ~n_ref_check
if ratio_check
fprintf('attempting to learn presence of branch points with only 20 nodes; stopping\n');
fprintf('try increasing number of reference nodes\n');
else
fprintf('this seems to be too small a dataset for TreeTop\n');
end
error('too few reference cells')
else
if ~ratio_check
fprintf('too few cells per ref node; reducing # ref nodes to %d\n', n_ref_cells);
end
end
end
%% add_density_values: add density values to the structure
function sample_struct = add_density_values(sample_struct, options_struct)
% if no downsampling specified, don't do it
if options_struct.outlier == 0 & options_struct.threshold == 1
density_vector = ones(size(sample_struct.used_data, 1), 1);
else
% otherwise calculate density
density_vector = calc_density(sample_struct, options_struct);
end
% add to sample_struct
sample_struct.density = density_vector;
end
%% calc_outlier_downsample_idx:
function [outlier_idx, downsample_idx] = calc_outlier_downsample_idx(sample_struct, options_struct);
if isempty(options_struct.outlier)
options_struct.outlier = 0;
end
if isempty(options_struct.threshold)
options_struct.threshold = 1;
end
% unpack
density_vector = sample_struct.density;
% exclude outlier
outlier_idx = exclude_outliers(density_vector, options_struct);
% downsample by density
downsample_idx = downsample_to_target(density_vector, options_struct, outlier_idx);
end
%% exclude_outliers: exclude outlier
function [outlier_idx] = exclude_outliers(density_vector, options_struct)
% unpack
outlier = options_struct.outlier;
% define any outliers to remove
if outlier == 0
% if 0, no outliers
outlier_idx = [];
else
% find appropriate density value
outlier_q = quantile(density_vector, outlier);
outlier_idx = find(outlier_q > density_vector);
end
end
%% downsample_to_target: downsample by density
function [downsample_idx] = downsample_to_target(density_vector, options_struct, outlier_idx)
% unpack
threshold = options_struct.threshold;
% define any cells to downsample on basis of high density
if threshold == 1
% if 1, don't downsample
downsample_idx = outlier_idx;
else
% histogram(density_vector)
% find quantile
threshold_q = quantile(density_vector, threshold);
% define probabilities for keeping during downsampling
keep_prob = min(1, threshold_q./density_vector);
% exclude outliers
keep_prob(outlier_idx) = 0;
% so outlier_idx is always subset of downsample_idx
% pick some cells
rand_vector = rand(numel(density_vector), 1);
downsample_idx = find(rand_vector > keep_prob);
end
end
%% get_a_tree:
function [this_node_idx, this_tree, this_tree_dist] = get_a_tree(sample_struct, cell_assignments, options_struct)
% sample one point from each cluster
cluster_list = setdiff(unique(cell_assignments), 0);
this_node_idx = arrayfun(@(ii) sample_fn(cell_assignments, ii), cluster_list);
% now get the corresponding locations in space
cluster_data = sample_struct.used_data(this_node_idx, :);
% and do a tree on it
switch options_struct.metric_name
case 'L1'
[this_tree, this_tree_dist] = mst_expanded(cluster_data, 'L1');
case 'L2'
[this_tree, this_tree_dist] = mst_expanded(cluster_data, 'euclidean');
case 'correlation'
[this_tree, this_tree_dist] = mst_expanded(cluster_data, 'corr');
case 'angle'
[this_tree, this_tree_dist] = mst_expanded(cluster_data, 'angle');
otherwise
error('options_struct.metric_name is not a valid option')
end
end
%% sample_fn:
function sample_idx = sample_fn(cell_assignments, ii)
cluster_idx = find(cell_assignments == ii);
n_in_cluster = length(cluster_idx);
sample_idx = cluster_idx(randsample(n_in_cluster, 1));
end
%% calculate_union_tree: superimpose all trees to calculate edge frequencies and mean edge lengths
function [union_graph, freq_union_graph] = calculate_union_graphs(tree_cell, tree_dist_cell, input_struct, options_struct)
fprintf('calculating summaries of ensemble of trees\n')
% unpack
n_trees = options_struct.n_trees;
n_ref_cells = options_struct.n_ref_cells;
% define variables
sparse_total_length = sparse(n_ref_cells, n_ref_cells);
sparse_total_freq = sparse(n_ref_cells, n_ref_cells);
% cycle through each cluster file
for ii = 1:n_trees
% get current one
this_tree_dist = tree_dist_cell{ii};
% update total length, total freq
sparse_total_length = sparse_total_length + this_tree_dist;
sparse_total_freq = sparse_total_freq + (this_tree_dist > 0);
end
% calculate sparse_mean_output, remove any NaNs resulting from division by zero
union_graph = sparse_total_length ./ sparse_total_freq;
union_graph(find(isnan(union_graph))) = 0;
% use frequency to define alternative distance
[non_zero_ii, non_zero_jj] = find(sparse_total_freq);
total_freq_vals = 1 ./ nonzeros(sparse_total_freq);
freq_union_graph = sparse(non_zero_ii, non_zero_jj, total_freq_vals);
% save both graphs
tree_filename = fullfile(input_struct.output_dir, sprintf('%s_union_tree.mat', input_struct.save_stem));
save(tree_filename, 'union_graph');
tree_filename = fullfile(input_struct.output_dir, sprintf('%s_freq_union_tree.mat', input_struct.save_stem));
save(tree_filename, 'freq_union_graph');
end
%% save_cell_assignments: save assignment of every cell to a reference cell
function [] = save_cell_assignments(input_struct, sample_struct, cell_assignments)
fprintf('counting celltype composition of each reference cell\n')
% convert to indexing variable
[this_tab, ~, ~, this_labels] = crosstab(cell_assignments, sample_struct.all_labels);
% outliers labelled as 0; remove these
if strcmp(this_labels(1), '0')
this_tab = this_tab(2:end, :);
end
non_empty = find(cellfun(@(ii) ~isempty(ii), this_labels(:, 2)));
this_header = this_labels(non_empty, 2)';
% save output
samples_file = fullfile(input_struct.output_dir, sprintf('%s_sample_counts.txt', input_struct.save_stem));
save_txt_file(samples_file, this_header, this_tab);
end
%% save_marker_values:
function [] = save_marker_values(input_struct, sample_struct, centroids_idx, cell_assignments)
% unpack
output_dir = input_struct.output_dir;
save_stem = input_struct.save_stem;
% restrict to cluster centres
used_data = sample_struct.used_data;
used_markers = sample_struct.used_markers;
cluster_used = sample_struct.used_data(centroids_idx, :);
extra_data = sample_struct.extra_data;
% save outputs for used markers
markers_file = fullfile(output_dir, sprintf('%s_mean_used_markers.txt', save_stem));
save_txt_file(markers_file, sample_struct.used_markers, cluster_used);
markers_file = fullfile(output_dir, sprintf('%s_all_used_markers.mat', save_stem));
save(markers_file, 'used_markers', 'used_data');
if ~isempty(extra_data)
extra_markers = sample_struct.extra_markers;
cluster_extra = sample_struct.extra_data(centroids_idx, :);
% save extra marker values
markers_file = fullfile(output_dir, sprintf('%s_mean_extra_markers.txt', save_stem));
save_txt_file(markers_file, sample_struct.extra_markers, cluster_extra);
markers_file = fullfile(output_dir, sprintf('%s_all_extra_markers.mat', save_stem));
save(markers_file, 'extra_markers', 'extra_data');
end
end
%% save_sampled_trees:
function [] = save_sampled_trees(input_struct, options_struct, outlier_idx, downsample_idx, centroids_idx, cell_assignments, node_idx_array, tree_cell, tree_dist_cell, sample_struct)
% restrict to just samples for label
celltype_vector = sample_struct.all_labels;
density = sample_struct.density;
% save union graph as mat file
tree_filename = fullfile(input_struct.output_dir, 'tree_variables.mat');
% define which variables to save
save_vars = {'outlier_idx', 'downsample_idx', 'density', 'centroids_idx', 'cell_assignments', 'node_idx_array', 'tree_cell', 'tree_dist_cell', 'celltype_vector', 'input_struct', 'options_struct'};
if isfield(sample_struct, 'cell_assignments_top')
cell_assignments_top = sample_struct.cell_assignments_top;
save_vars = {save_vars{:}, 'cell_assignments_top'};
end
if isfield(sample_struct, 'branch_parent_point')
branch_parent_point = sample_struct.branch_parent_point;
save_vars = {save_vars{:}, 'branch_parent_point'};
end
% do saving
save(tree_filename, save_vars{:})
end
|
github
|
wmacnair/TreeTop-master
|
treetop_example_runs.m
|
.m
|
TreeTop-master/TreeTop/treetop_example_runs.m
| 13,165 |
utf_8
|
93c8b8279cbdd776aef54f94d9d3d23e
|
%% treetop_example_runs: Set of runs which reproduce the results in the paper.
% These are based on the entries in zip file treetop_data.
% data_dir is the parent path of where treetop_data was unzipped.
% output_dir is the parent path of where you would like outputs to be stored.
% run_switch is the index of which run you would like to do, out of the following:
% 1 T cell thymic maturation data, preprocessed with diffusion maps
% 2 Healthy human bone marrow, mass cytometry data
% 3 Hierarchically branching synthetic data (generated by Stefan Ganscha)
% 4 Linear synthetic data
% 5 Gaussian synthetic data
% 6 Circular synthetic data
% 7 Triangular synthetic data
% 8 B cell maturation
% 9 Healthy human bone marrow, scRNAseq data (Paul et al., 2015)
% 10 Healthy human bone marrow, scRNAseq data (Velten et al., 2017)
% 11 Swiss roll synthetic data
function treetop_example_runs(data_dir, output_dir, run_switch)
% set up pool
current_pool = gcp('nocreate');
if numel(current_pool) == 0
error('Please call parpool before running treetop_example_runs')
end
switch run_switch
case 1
% T cell thymic maturation data, preprocessed with diffusion maps
% Setty et al. 2016. “Wishbone Identifies Bifurcating Developmental Trajectories from Single-Cell Data.” Nature Biotechnology, May. doi:10.1038/nbt.3569.
fprintf('running treetop on T cell thymic maturation data, preprocessed with diffusion maps\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'thymus'), ...
'output_dir', fullfile(output_dir, 'thymus'), ...
'used_markers', {{'DC02', 'DC03', 'DC04'}}, ...
'extra_markers', {{'CD27', 'CD4', 'CD5', 'CD127', 'CD44', 'CD69', 'CD117', 'CD62L', 'CD24', 'CD3', ...
'CD8', 'CD25', 'TCRb', 'BCL11b', 'CD11b', 'CD11c', 'CD161', 'CD19', 'CD38', 'CD45', ...
'CD90', 'Foxp3', 'GATA3', 'IA', 'Notch1', 'Notch3', 'RORg', 'Runx1', 'TCRgd', 'ki67'}}, ...
'filenames', {{'wishbone thymus 2.fcs'}}, ...
'file_annot', {{'thymus'}} ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.2, ...
'sigma', 1e-4, ...
'layout_seed', 2 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
treetop_recursive(input_struct, options_struct)
case 2
% Healthy human bone marrow, mass cytometry data
% Amir et al. 2013. “viSNE Enables Visualization of High Dimensional Single-Cell Data and Reveals Phenotypic Heterogeneity of Leukemia.” Nature Biotechnology 31 (6).
fprintf('running treetop on healthy human bone marrow, mass cytometry data\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'bone marrow cytof'), ...
'output_dir', fullfile(output_dir, 'bone marrow cytof'), ...
'used_markers', {{'CD11c(Tb159)Di', 'CD14(Gd160)Di', 'CD33(Yb173)Di', 'CD3(Er170)Di', 'CD45(Sm154)Di', 'CD15(Dy164)Di', ...
'CD24(Dy161)Di', 'CD19(Nd142)Di', 'CD22(Nd143)Di', 'CD20(Sm147)Di', 'CD117(Yb171)Di', 'IgM-s(Lu175)Di', ...
'IgM-i(Eu153)Di', 'HLADR(Yb174)Di', 'CD79b(Nd146)Di', 'CD38(Er168)Di', 'CD235-62-66b(In113)Di', ...
'CD72(Eu151)Di', 'CD7(Yb176)Di', 'CD47(Nd145)Di'}}, ...
'extra_markers', {{'CD49d(Yb172)Di', 'Pax5(Ho165)Di', 'CD127(Dy162)Di', 'TdT(Dy163)Di', 'CD34(Nd148)Di', 'CD10(Gd156)Di', ...
'CD179b(Gd158)Di', 'CD179a(Sm149)Di'}}, ...
'filenames', {{'bone_marrow_T_cells.fcs', 'bone_marrow_Myeloid.fcs', ...
'bone_marrow_ungated_CD7_low.fcs', 'bone_marrow_CD24_hi.fcs', ...
'bone_marrow_B_cells.fcs', 'bone_marrow_NK_cells.fcs', ...
'bone_marrow_HSCs.fcs', 'bone_marrow_ungated_CD20hi_-_CD3hi.fcs'}}, ...
'file_annot', {{'T cells', 'Myeloid', 'ungated CD7 low', 'Granulocytes', 'B cells', 'NK cells', 'HSCs', 'ungated CD20hi - CD3hi'}} ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.5, ...
'sigma', 2 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
treetop_recursive(input_struct, options_struct)
case 3
% Hierarchically branching synthetic data (generated by Stefan Ganscha)
% Ocone et al. 2015. “Reconstructing Gene Regulatory Dynamics from High-Dimensional Single-Cell Snapshot Data.” Bioinformatics 31 (12): i89–96.
fprintf('running treetop on hierarchically branching synthetic data\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'synthetic hierarchical'), ...
'output_dir', fullfile(output_dir, 'synthetic hierarchical'), ...
'used_markers', {arrayfun(@(ii) sprintf('D%02d', ii), 1:12, 'unif', false)}, ...
'extra_markers', {{'time'}}, ...
'filenames', {{'synthetic hierarchically branching.fcs'}}, ...
'file_annot', {{'branching'}} ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.5, ...
'sigma', 1 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
treetop_recursive(input_struct, options_struct)
case 4
% Linear synthetic data
fprintf('running treetop on linear synthetic data\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'synthetic linear'), ...
'output_dir', fullfile(output_dir, 'synthetic linear'), ...
'used_markers', {arrayfun(@(ii) sprintf('D%02d', ii), 1:10, 'unif', false)}, ...
'used_cofactor', 0, ...
'filenames', {{'synthetic linear.fcs'}}, ...
'file_annot', {{'linear'}} ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.5, ...
'sigma', 0.05 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
case 5
% Gaussian synthetic data
fprintf('running treetop on Gaussian synthetic data\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'synthetic gaussian'), ...
'output_dir', fullfile(output_dir, 'synthetic gaussian'), ...
'used_markers', {arrayfun(@(ii) sprintf('D%02d', ii), 1:10, 'unif', false)}, ...
'used_cofactor', 0, ...
'filenames', {{'synthetic gaussian.fcs'}}, ...
'file_annot', {{'gaussian'}} ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.5, ...
'sigma', 1 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
case 6
% Circular synthetic data
fprintf('running treetop on circular synthetic data\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'synthetic circle'), ...
'output_dir', fullfile(output_dir, 'synthetic circle'), ...
'used_markers', {arrayfun(@(ii) sprintf('readout%d', ii), 1:10, 'unif', false)}, ...
'extra_markers', {{'angle'}}, ...
'used_cofactor', 0, ...
'extra_cofactor', 0, ...
'filenames', {{'synthetic circle.fcs'}}, ...
'file_annot', {{'circle'}} ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.5, ...
'sigma', 0.05 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
case 7
% Triangular synthetic data
fprintf('running treetop on triangular synthetic data\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'synthetic triangle'), ...
'output_dir', fullfile(output_dir, 'synthetic triangle'), ...
'used_markers', {arrayfun(@(ii) sprintf('D%02d', ii), 1:10, 'unif', false)}, ...
'used_cofactor', 0, ...
'filenames', {{'synthetic triangle.fcs'}}, ...
'file_annot', {{'triangle'}} ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.5, ...
'sigma', 0.05 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
case 8
% B cell maturation
% Bendall et al. 2014. “Single-Cell Trajectory Detection Uncovers Progression and Regulatory Coordination in Human B Cell Development.” Cell 157 (3). Elsevier Inc.: 714–25.
fprintf('running treetop on B cell maturation data\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'B cell'), ...
'output_dir', fullfile(output_dir, 'B cell'), ...
'used_markers', {arrayfun(@(ii) sprintf('PC%02d', ii), 1:10, 'unif', false)}, ...
'extra_markers', {{'CD10', 'CD117', 'CD179a', 'CD179b', 'CD19', 'CD20', 'CD24', 'CD34', 'CD38', 'CD45', 'CD72', 'CD79b', ...
'HLADR', 'IgD', 'IgM-i', 'IgM-s', 'Kappa', 'Lambda'}}, ...
'used_cofactor', 0, ...
'extra_cofactor', 5, ...
'mat_file', 'B cells.mat' ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.2, ...
'sigma', 5 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
treetop_recursive(input_struct, options_struct)
case 9
% Healthy human bone marrow, scRNAseq data
% Velten et al. 2017. “Human Haematopoietic Stem Cell Lineage Commitment Is a Continuous Process.” Nature Cell Biology 19 (4): 271–81.
fprintf('running treetop on healthy human bone marrow, scRNAseq data (Paul et al.)\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'bone marrow scRNAseq Paul'), ...
'output_dir', fullfile(output_dir, 'bone marrow scRNAseq Paul'), ...
'used_markers', {arrayfun(@(ii) sprintf('diff%02d', ii), 1:8, 'unif', false);}, ...
'used_cofactor', 0, ...
'mat_file', 'paul diffusion maps.mat' ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'outlier', 0, ...
'threshold', 0.2, ...
'sample_size', 1e5, ...
'n_ref_cells', 100, ...
'n_dens_ref', 500, ...
'n_trees', 1000, ...
'layout_tree_idx', 4, ...
'sigma', 1e-2 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
treetop_recursive(input_struct, options_struct)
case 10
% Healthy human bone marrow, scRNAseq data
% Velten et al. 2017. “Human Haematopoietic Stem Cell Lineage Commitment Is a Continuous Process.” Nature Cell Biology 19 (4): 271–81.
fprintf('running treetop on healthy human bone marrow, scRNAseq data (Velten et al.)\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'bone marrow scRNAseq Velten'), ...
'output_dir', fullfile(output_dir, 'bone marrow scRNAseq Velten'), ...
'used_markers', {arrayfun(@(ii) sprintf('DC%02d', ii), 1:11, 'unif', false);}, ...
'extra_markers', {{'stemnet_p'}}, ...
'mat_file', 'velten diffusion maps, STEMNET labels.mat' ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'outlier', 0, ...
'threshold', 0.1, ...
'sample_size', 1e5, ...
'n_ref_cells', 100, ...
'n_dens_ref', 500, ...
'n_trees', 1000, ...
'layout_tree_idx', 2, ...
'sigma', 1 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
treetop_recursive(input_struct, options_struct)
case 11
% Swiss roll synthetic data
fprintf('running treetop on Swiss roll synthetic data\n')
input_struct = struct( ...
'data_dir', fullfile(data_dir, 'synthetic swiss roll'), ...
'output_dir', fullfile(output_dir, 'synthetic swiss roll'), ...
'used_markers', {arrayfun(@(ii) sprintf('S%02d', ii), 1:10, 'unif', false)}, ...
'extra_markers', {{'angle'}}, ...
'used_cofactor', 0, ...
'extra_cofactor', 0, ...
'mat_file', 'swiss_roll.mat' ...
);
options_struct = struct( ...
'metric_name', 'L1', ...
'sample_size', 1e5, ...
'n_ref_cells', 200, ...
'n_trees', 1000, ...
'outlier', 0.01, ...
'threshold', 0.5, ...
'sigma', 1 ...
);
treetop_pre_run(input_struct, options_struct)
treetop(input_struct, options_struct)
otherwise
error('invalid run_switch')
end
end
|
github
|
wmacnair/TreeTop-master
|
treetop_layout.m
|
.m
|
TreeTop-master/TreeTop/treetop_layout.m
| 7,508 |
utf_8
|
7f075097a93221d57942407aa812496d
|
%% treetop_layout: do layouts for this run
function [] = treetop_layout(input_struct, options_struct)
% check inputs
[input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct);
% do force-directed graph layout
calc_force_directed_layout(input_struct, options_struct);
% which markers show greatest differences between branches?
calc_most_significant_branching_markers(input_struct, options_struct)
end
%% calc_force_directed_layout:
function calc_force_directed_layout(input_struct, options_struct)
fprintf('calculating TreeTop layouts\n')
% unpack
output_dir = input_struct.output_dir;
save_stem = input_struct.save_stem;
% get graph structure
graph_struct = get_graph_struct(input_struct);
n_graphs = size(graph_struct, 2);
% define storage variable
G_cell = cell(n_graphs, 1);
layout_cell = cell(n_graphs, 1);
title_cell = cell(n_graphs, 1);
if options_struct.pool_flag
% set up reproducible rng
spmd
cmrg = RandStream('mrg32k3a', 'seed', options_struct.seed);
RandStream.setGlobalStream(cmrg);
end
% loop through all graphs
parfor ii = 1:n_graphs
% set up random stream
s = RandStream.getGlobalStream();
s.Substream = ii;
% define graph to use,calculate layout
G = graph_struct(ii).inv_adj_matrix;
layout = harel_koren_layout_faster(G);
% store outputs
G_cell{ii} = G;
layout_cell{ii} = layout;
title_cell{ii} = graph_struct(ii).name;
end
else
% loop through all graphs
for ii = 1:n_graphs
% set up random stream
rng(ii);
% define graph to use,calculate layout
G = graph_struct(ii).inv_adj_matrix;
layout = harel_koren_layout_faster(G);
% store outputs
G_cell{ii} = G;
layout_cell{ii} = layout;
title_cell{ii} = graph_struct(ii).name;
end
end
% assemble into one figure
put_all_figures_together(G_cell, layout_cell, title_cell, input_struct)
end
%% do_layout:
function do_layout(G, layout, plot_title)
% prepare plot outputs
[ii jj ss] = find(G);
[mm nn] = size(G);
adjacency_matrix = sparse(ii, jj, repmat(1, numel(ii), 1), mm, nn);
% plot
hold on
grey_gplot(G, layout);
plot(layout(:, 1), layout(:, 2), '.', 'markersize', 20);
hold off
xlabel('TreeTop 1')
ylabel('TreeTop 2')
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
title(plot_title, 'interpreter', 'none');
end
%% grey_gplot:
function h2 = grey_gplot(layout_graph, layout_xy)
gplot(layout_graph, layout_xy, '-k');
h = gca;
h2 = get(h, 'Children');
grey_val = 0.8;
set(h2, 'color', [grey_val, grey_val, grey_val]);
end
%% put_all_figures_together:
function put_all_figures_together(G_cell, layout_cell, title_cell, input_struct)
% unpack
output_dir = input_struct.output_dir;
save_stem = input_struct.save_stem;
% set up figure
fig = figure('visible', 'off');
n_rows = 2;
n_cols = 3;
% plot each layout
for ii = 1:numel(G_cell)
% do this one
subplot(n_rows, n_cols, ii);
do_layout(G_cell{ii}, layout_cell{ii}, title_cell{ii})
end
% save result as png
name_stem = fullfile(output_dir, sprintf('%s all layouts', save_stem));
fig_size = [12 8];
plot_fig(fig, name_stem, 'png', fig_size)
end
%% calc_most_significant_branching_markers:
function calc_most_significant_branching_markers(input_struct, options_struct)
% get treetop outputs
treetop_struct = get_treetop_outputs(input_struct);
% calculate mean branching distance from this node to all other nodes
mean_tree_dist = calculate_dists_from_branching_point(input_struct, options_struct, treetop_struct);
% do ANOVA on the induced branches
anova_results = identify_de_markers_with_anova(input_struct, options_struct, treetop_struct, mean_tree_dist);
% save outputs
save_branching_markers(mean_tree_dist, anova_results, input_struct)
end
%% calculate_dists_from_branching_point: calculates mean mst distance matrix for branching point
function [mean_tree_dist] = calculate_dists_from_branching_point(input_struct, options_struct, treetop_struct)
% get tree distance bits
tree_cell = treetop_struct.tree_cell;
best_branches = treetop_struct.best_branches;
branch_point = find(best_branches == 0);
if length(branch_point) ~= 1
error('something wrong with branches')
end
% do dijkstra for each tree
n_nodes = options_struct.n_ref_cells;
n_trees = options_struct.n_trees;
fprintf('calculating mean mst distances from branching point\n');
% define output array
all_dijk_dists = zeros(n_trees, n_nodes);
% loop
for ii = 1:n_trees
all_dijk_dists(ii, :) = dijkstra(tree_cell{ii}, branch_point);
end
% take mean
mean_tree_dist = mean(all_dijk_dists, 1);
% scale to have max distance 1
max_dist = max(mean_tree_dist);
mean_tree_dist = mean_tree_dist / max_dist;
% have biggest branch on LHS (i.e. negative distances)
one_idx = best_branches == 1;
mean_tree_dist(one_idx) = -mean_tree_dist(one_idx);
end
%% identify_de_markers_with_anova: find which markers are most strongly differentially expressed between branches
function [anova_results] = identify_de_markers_with_anova(input_struct, options_struct, treetop_struct, mean_tree_dist)
fprintf('calculating markers which are significantly different between branches\n')
% unpack
best_branches = treetop_struct.best_branches;
used_values = treetop_struct.used_values;
extra_values = treetop_struct.extra_values;
n_used = size(used_values, 2);
n_extra = size(extra_values, 2);
% check we can actually do this
group_size_check = check_anova_sizes(best_branches);
if ~group_size_check
% skip
anova_results = struct( ...
'anova_used', ones(1, n_used), ...
'anova_extra', ones(1, n_extra) ...
);
fprintf('at least some branches too small to calculate which markers differentially expressed on branches\n')
return
end
% do ANOVA to find which markers show greatest difference between branches
branch_idx = best_branches ~= 0;
anova_used = do_one_anova(branch_idx, best_branches, used_values);
if ~isempty(extra_values)
anova_extra = do_one_anova(branch_idx, best_branches, extra_values);
else
anova_extra = [];
end
% store outputs
anova_results = struct( ...
'anova_used', anova_used, ...
'anova_extra', anova_extra ...
);
end
%% check_anova_sizes:
function [group_size_check] = check_anova_sizes(best_branches)
% check that it is ok to do anova (need n >= # groups + 1)
[branch_count, labels] = grpstats(best_branches, best_branches, {'numel', 'gname'});
labels = cellfun(@str2num, labels);
% remove branch point
keep_idx = labels ~= 0;
branch_count = branch_count(keep_idx);
labels = labels(keep_idx);
% check number of branches against branch sizes
n_branches = numel(labels);
group_size_check = all( branch_count > n_branches + 1 );
end
%% do_one_anova:
function [p_vals] = do_one_anova(branch_idx, best_branches, val_matrix)
branch_vals = val_matrix(branch_idx, :);
n_sel = size(val_matrix, 2);
actual_branches = best_branches(branch_idx);
p_vals = arrayfun( @(ii) anova1(branch_vals(:, ii), actual_branches, 'off'), 1:n_sel );
% correct for multiple testing
p_vals = p_vals / size(val_matrix, 2);
end
%% save_branching_markers:
function save_branching_markers(mean_tree_dist, anova_results, input_struct)
output_file = fullfile(input_struct.output_dir, sprintf('%s marker significance.mat', input_struct.save_stem));
save(output_file, 'mean_tree_dist', 'anova_results')
end
|
github
|
wmacnair/TreeTop-master
|
treetop.m
|
.m
|
TreeTop-master/TreeTop/treetop.m
| 4,712 |
utf_8
|
563f191b9e4f61a4d12ecae367db4bee
|
%% treetop: Runs treetop for specified inputs, with specified options.
%
% Data for input into TreeTop is specified via the input_struct object. The
% required fields of input_struct are as follows:
% data_dir String defining path to directory where input files
% are stored
% output_dir String defining path to directory for outputs.
% this path has the form /parent_folder/output_name,
% and that parent_folder already exists. The
% output_name subdirectory is then created, and
% output_name is used as a label for TreeTop
% intermediate and output files.
% used_markers Cell array of markers to be used for this run. All
% must be present in the input files.
% One of the following two must be given:
% filenames Cell array of fcs filenames, defining input files.
% All input files should contain the same
% mat_file Inputs to TreeTop can alternatively be given via a
% single mat file, which should contain:
% Additional possible inputs are:
% extra_markers Cell array of additional markers which are not used
% in the run, but are of interest, for example for
% validation. All must be present in the input files.
% file_annot Cell array of shorthand labels for fcs filenames.
% If omitted, values in filenames are used.
%
% Options for running TreeTop are specified via the options_struct object.
% The fields of input_struct are as follows:
% sigma Bandwidth used for calculating cell density
% values. Once TreeTop has been run, the png file
% '[output_name] density distribution.png' can be
% used as a diagnostic to check whether the value
% of sigma is appropriate.
% The following options are optional
% metric_name Distance metric to be used. Valid options are
% 'L1', 'L2', 'angle'; if omitted, default value
% is 'L1'.
% n_ref_cells Number of reference nodes used by TreeTop; if
% omitted, default value is 200.
% n_trees Number of trees sampled by TreeTop; if
% omitted, default value is 1000.
% outlier Quantile of density distribution below which a
% cell is regarded as an outlier and excluded; if
% omitted, default value is 0.01.
% threshold Quantile of density distribution above which a
% cell is regarded as high density, and subject
% to downsampling; if omitted, default value is
% 0.5.
% used_cofactor Cofactor for calculating arcsinh for
% used_markers. Value of 0 results in no arcsinh
% transformation being performed. If omitted,
% default value is 5.
% extra_cofactor Cofactor for calculating arcsinh for
% extra_markers. Value of 0 results in no arcsinh
% transformation being performed. If omitted,
% default value is 5.
% file_ext Specifies format of output image files. Valid
% values are 'png', 'eps' and 'pdf'; if omitted,
% default value is 'png'.
%
% Example code for running treetop:
% input_struct = struct( ...
% 'data_dir', 'path_to_data/wishbone clean 2', ...
% 'output_dir', 'parent_folder_for_outputs/wishbone_clean_2_dc', ...
% 'used_markers', {{'DC02', 'DC03', 'DC04'}}, ...
% 'extra_markers', {{'CD27', 'CD4', 'CD5', 'CD127', 'CD44', 'CD69', 'CD117', 'CD62L', 'CD24', 'CD3', ...
% 'CD8', 'CD25', 'TCRb', 'BCL11b', 'CD11b', 'CD11c', 'CD161', 'CD19', 'CD38', 'CD45', ...
% 'CD90', 'Foxp3', 'GATA3', 'IA', 'Notch1', 'Notch3', 'RORg', 'Runx1', 'TCRgd', 'ki67'}}, ...
% 'filenames', {{'sample destiny full.fcs'}}, ...
% 'file_annot', {{'sample'}} ...
% );
% options_struct = struct( ...
% 'metric_name', 'L1', ...
% 'n_ref_cells', 200, ...
% 'n_trees', 1000, ...
% 'outlier', 0.01, ...
% 'threshold', 0.2, ...
% 'sigma', 1e-4, ...
% 'used_cofactor', 0, ...
% 'extra_cofactor', 0 ...
% );
% parpool(4)
% treetop(input_struct, options_struct)
function treetop(input_struct, options_struct)
fprintf('\nrunning TreeTop\n')
% check inputs
[input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct);
% check whether pool is present
pool_check(options_struct);
% sample ensemble of trees
fprintf('\n1/4 Sampling ensemble of trees from data\n')
treetop_trees(input_struct, options_struct)
% calculate bifurcation score
fprintf('\n2/4 Calculating branch scores for each reference node\n')
treetop_branching_scores(input_struct, options_struct)
% do layouts for these
fprintf('\n3/4 Calculating layouts based on ensemble of trees\n')
treetop_layout(input_struct, options_struct)
% do plots
fprintf('\n4/4 Plotting treetop outputs\n')
treetop_plots(input_struct, options_struct)
fprintf('\ndone.\n\n')
end
|
github
|
wmacnair/TreeTop-master
|
treetop_recursive.m
|
.m
|
TreeTop-master/TreeTop/treetop_recursive.m
| 29,988 |
utf_8
|
c8fc2f52359836c95db63e8fee443049
|
%% treetop_recursive: First sample ensemble of trees, do layouts. Then check whether we think there are further bifurcations.
function treetop_recursive(input_struct, options_struct)
fprintf('\nrunning TreeTop recursively\n')
% check whether pool is present
[input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct);
pool_check(options_struct);
% do recursion bit
treetop_one_recursion(input_struct, options_struct)
% draw results together, plot
recursive_struct = process_recursive_outputs(input_struct, options_struct);
% do some plotting
plot_recursive_outputs(input_struct, options_struct, recursive_struct);
fprintf('\ndone.\n\n')
end
%% treetop_one_recursion:
function treetop_one_recursion(input_struct, options_struct)
% check inputs
[input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct);
% define things that might already be save
tree_vars_file = fullfile(input_struct.output_dir, 'tree_variables.mat');
branching_file = fullfile(input_struct.output_dir, sprintf('%s branching scores.txt', input_struct.save_stem));
if ~exist(tree_vars_file, 'file') | ~exist(branching_file, 'file')
% sample ensemble of trees
treetop_trees(input_struct, options_struct)
% calculate bifurcation score
treetop_branching_scores(input_struct, options_struct)
end
% get treetop outputs
treetop_struct = get_treetop_outputs(input_struct);
% check whether branch has score above non-branching distribution
[has_branch, n_branches] = check_for_branches(input_struct, options_struct, treetop_struct);
if has_branch
fprintf('branch point found for %s; zooming in to %d branches\n', input_struct.save_stem, n_branches);
% split and save
[branch_input_cell, branch_options_cell, branch_check] = split_treetop_branches(input_struct, options_struct, treetop_struct);
% tidy up some memory before we recurse
clear treetop_struct
for ii = 1:length(branch_input_cell)
% run recursion on this one
branch_input = branch_input_cell{ii};
branch_options = branch_options_cell{ii};
% run recursive on this
if branch_check(ii)
treetop_one_recursion(branch_input, branch_options);
else
save_dummy_outputs_for_tiny_branches(branch_input, branch_options);
end
end
else
fprintf('no branch point found for %s; stopping recursion\n', input_struct.save_stem)
end
end
%% check_for_branches:
function [has_branch, n_branches] = check_for_branches(input_struct, options_struct, treetop_struct)
% get non-branching distribution
[n_points, n_dims] = size(treetop_struct.used_data);
n_ref_cells = options_struct.n_ref_cells;
non_branching_distn = get_non_branching_distn(n_ref_cells, n_points, n_dims);
% get scores, normalize
branch_scores = treetop_struct.branch_scores;
cutoff_q = quantile(non_branching_distn, options_struct.p_cutoff);
normed_scores = branch_scores / cutoff_q;
best_score = max(normed_scores);
% check whether higher than 1
has_branch = best_score > 1;
% calculate n_branches
n_branches = numel(unique(treetop_struct.best_branches)) - 1 ;
end
%% split_treetop_branches:
function [branch_input_cell, branch_options_cell, branch_check] = split_treetop_branches(input_struct, options_struct, treetop_struct)
% get branches, scores
best_branches = treetop_struct.best_branches;
branch_point = find(best_branches == 0);
unique_branches = setdiff(unique(best_branches), 0);
n_branches = length(unique_branches);
branch_input_cell = cell(n_branches, 1);
branch_options_cell = cell(n_branches, 1);
branch_check = true(n_branches, 1);
% unpack
save_stem = input_struct.save_stem;
cell_assignments = treetop_struct.cell_assignments;
used_data = treetop_struct.used_data;
extra_data = treetop_struct.extra_data;
celltype_vector = treetop_struct.celltype_vector;
% we want to keep track of the labels at the top level for all cells
if isfield(treetop_struct, 'cell_assignments_top')
cell_assignments_top = treetop_struct.cell_assignments_top;
else
cell_assignments_top = cell_assignments;
end
% remove filenames etc from input_struct
if isfield(input_struct, 'filenames')
input_struct = rmfield(input_struct, 'filenames');
input_struct = rmfield(input_struct, 'file_annot');
end
% cycle through branches
for ii = 1:n_branches
% restrict to this branch
this_branch = unique_branches(ii);
% which datapoints to keep? (we also pass the branch point through)
node_idx = find(ismember(best_branches, [0, this_branch]));
nodes_to_keep = ismember(cell_assignments, node_idx);
% check whether there are enough
n_nodes = sum(nodes_to_keep);
if n_nodes < 200
branch_check(ii) = false;
end
% make new input_struct
branch_input = input_struct;
if regexp(save_stem, '^branch_')
branch_stem = sprintf('%s_%d', save_stem, this_branch);
else
branch_stem = sprintf('branch_%d', this_branch);
end
branch_input.save_stem = branch_stem;
% make new directory
branch_dir = fullfile(input_struct.output_dir, branch_stem);
if ~exist(branch_dir, 'dir')
mkdir(branch_dir)
end
branch_input.output_dir = branch_dir;
% restrict to this branch
branch_used = used_data(nodes_to_keep, :);
if ~isempty(extra_data)
branch_extra = extra_data(nodes_to_keep, :);
else
branch_extra = [];
end
branch_celltypes = celltype_vector(nodes_to_keep);
branch_assign_top = cell_assignments_top(nodes_to_keep);
% which ones correspond to the parent branch point?
branch_parent_point = cell_assignments(nodes_to_keep) == branch_point;
% put into struct
all_struct = struct( ...
'all_data', {[branch_used, branch_extra]}, ...
'all_labels', {branch_celltypes}, ...
'all_markers', {{input_struct.used_markers{:}, input_struct.extra_markers{:}}}, ...
'cell_assignments_top', {branch_assign_top}, ...
'branch_parent_point', {branch_parent_point} ...
);
% save required outputs in new directory
branch_file = sprintf('%s treetop inputs.mat', branch_stem);
branch_path = fullfile(branch_dir, branch_file);
save(branch_path, 'all_struct');
% add this location to branch_input
branch_input.data_dir = branch_dir;
branch_input.mat_file = branch_file;
% define options for this branch, including whether to do this branch
branch_options = make_branch_options(all_struct, options_struct);
% store this branch_input
branch_input_cell{ii} = branch_input;
branch_options_cell{ii} = branch_options;
end
end
%% make_branch_options: check # ref cells:
function branch_options = make_branch_options(all_struct, options_struct)
% unpack
n_ref_cells = options_struct.n_ref_cells;
n_total = size(all_struct.all_data, 1);
% checks there are at least 10 cells per node
ratio_threshold = 10;
cell_ratio = n_total / n_ref_cells;
ratio_check = cell_ratio >= ratio_threshold;
if ~ratio_check
% change to smallest multiple of 10 achieving this threshold
n_ref_cells = floor(n_total / ratio_threshold / 10 ) * 10;
end
% check there are at least 20 nodes; use this to decide whether to do this branch or not
n_ref_cutoff = 20;
n_ref_check = n_ref_cells >= n_ref_cutoff;
% make options
branch_options = options_struct;
branch_options.n_ref_cells = n_ref_cells;
branch_options.n_ref_check = n_ref_check;
branch_options.outlier = 0;
end
%% save_dummy_outputs_for_tiny_branches:
function save_dummy_outputs_for_tiny_branches(branch_input, branch_options)
% define things that might already be saved
tiny_branch_file = fullfile(branch_input.output_dir, 'outputs_for_tiny_branch.mat');
% save if necessary
% if ~exist(tiny_branch_file, 'file')
if true
% unpack
branch_dir = branch_input.output_dir;
branch_stem = branch_input.save_stem;
% load up inputs
inputs_file = sprintf('%s treetop inputs.mat', branch_stem);
inputs_path = fullfile(branch_dir, inputs_file);
load(inputs_path);
% fake tree_variables file
cell_assignments_top = all_struct.cell_assignments_top;
cell_assignments = cell_assignments_top;
% save
save(tiny_branch_file, 'cell_assignments_top', 'cell_assignments');
end
end
%% process_recursive_outputs: rejoin all recursive outputs, somehow...
function recursive_struct = process_recursive_outputs(input_struct, options_struct)
% recursively look for branches, get outputs for each
fprintf('getting outputs for each recursive branch\n')
% if already done, load
recursive_output_file = fullfile(input_struct.output_dir, sprintf('%s recursive outputs.mat', input_struct.save_stem));
% if exist(recursive_output_file, 'file')
if false
load(recursive_output_file, 'recursive_struct')
else
[stem_outputs, struct_outputs] = get_all_branch_outputs(input_struct.output_dir);
% edit top
stem_outputs{1} = 'top';
% put everything together, do some double-checking along the way
recursive_struct = assemble_struct_outputs(stem_outputs, struct_outputs, input_struct, options_struct);
recursive_struct.celltype_vector = struct_outputs{1}.celltype_vector;
recursive_struct.cell_assignments = struct_outputs{1}.cell_assignments;
end
end
%% get_all_branch_outputs:
function [stem_outputs, struct_outputs] = get_all_branch_outputs(input_dir)
% what is there in this directory?
dir_details = dir(input_dir);
dir_details = dir_details([dir_details.isdir]);
dir_names = {dir_details.name};
% get the outputs from this level
[~, this_stem, ext] = fileparts(input_dir);
if ~isempty(ext)
this_stem = [this_stem, ext];
end
input_struct = struct('output_dir', input_dir, 'save_stem', this_stem);
this_struct = get_treetop_outputs_recursive(input_struct);
% put outputs together
stem_outputs = {this_stem};
struct_outputs = {this_struct};
% find those which start with 'branch'
branch_boolean = ~cellfun(@isempty, regexp(dir_names, '^branch'));
if sum(branch_boolean) > 1
% if we have branch directories, then go further down
branch_dirs = cellfun(@(str) fullfile(input_dir, str), dir_names(branch_boolean), 'unif', false);
[next_outputs, next_structs] = cellfun(@(this_dir) get_all_branch_outputs(this_dir), branch_dirs, 'unif', false);
% mess about with cells
if numel(next_structs) > 1
% next_structs = cellfun( @(this_cell) this_cell{:}, next_structs, 'unif', false);
next_structs = [ next_structs{:} ];
end
% turn into contiguous cell outputs
stem_outputs = [stem_outputs{:}, next_outputs{:}];
struct_outputs = {struct_outputs{:}, next_structs{:}};
end
end
%% get_treetop_outputs_recursive:
function this_struct = get_treetop_outputs_recursive(input_struct)
% define file to check
tiny_branch_file = fullfile(input_struct.output_dir, 'outputs_for_tiny_branch.mat');
% if the branch was too small to run, load up the dummy outputs
if exist(tiny_branch_file, 'file')
load(tiny_branch_file, 'cell_assignments_top', 'cell_assignments');
this_struct = struct( ...
'cell_assignments_top', {cell_assignments_top}, ...
'cell_assignments', {cell_assignments} ...
);
this_struct.run_flag = false;
% otherwise load real outputs
else
this_struct = get_treetop_outputs(input_struct);
this_struct.run_flag = true;
end
end
%% assemble_struct_outputs:
function recursive_struct = assemble_struct_outputs(stem_outputs, struct_outputs, input_struct, options_struct)
% unpack
n_nodes = options_struct.n_ref_cells;
% calculate branch depth for each branch
branch_depths = cellfun(@(str) length(regexp(str, '_')), stem_outputs);
max_depth = max(branch_depths);
% trim names
short_branch_names = cellfun(@(str) regexprep(str, 'branch_', ''), stem_outputs, 'unif', false);
if max_depth == 0
% we don't need to do all the stuff below if there's no branching
[final_labels, branch_tree] = make_no_branch_variables(n_nodes);
else
% define storage
all_branch_labels = cell(n_nodes, max_depth);
% start our tree
branch_tree = initialize_branch_tree(stem_outputs);
% cycle through branch depths
for ii = 1:max_depth
% restrict to this depth
depth_idx = branch_depths == ii;
depth_structs = struct_outputs( depth_idx );
depth_names = short_branch_names( depth_idx );
% join all together
top_assigns_cell = cellfun(@(this_struct) this_struct.cell_assignments_top, depth_structs', 'unif', false);
top_assigns_names = arrayfun(@(ii) repmat(depth_names(ii), 1, size(top_assigns_cell{ii}, 1)), 1:length(top_assigns_cell), 'unif', false);
top_assigns = cell2mat(top_assigns_cell);
top_assigns_names = [top_assigns_names{:}]';
% do crosstab to count
[depth_branch_votes, ~, ~, labels] = crosstab(top_assigns, top_assigns_names);
depth_labels = labels(:, 2);
depth_labels = depth_labels(~cellfun(@isempty, depth_labels));
% define labels
[~, max_branch_idx] = max(depth_branch_votes, [], 2);
node_labels = arrayfun(@(idx) depth_labels{idx}, max_branch_idx, 'unif', false);
% store these in the right place
node_idx = cellfun(@str2num, labels(:, 1));
all_branch_labels(node_idx, ii) = node_labels;
% % do some tweaking of branch_tree
% branch_tree = update_branch_tree(ii, branch_depths, short_branch_names, struct_outputs, branch_tree);
end
% make tree symmetric
branch_tree = branch_tree + branch_tree';
% fill in missing labels where necessary
top_best_branches = struct_outputs{1}.best_branches;
missing_idx = find(cellfun(@isempty, all_branch_labels(:, 1)));
all_branch_labels(missing_idx, 1) = arrayfun(@(idx) num2str(top_best_branches(idx)), missing_idx, 'unif', false);
% label each cell according to deepest level
empty_matrix = cellfun(@isempty, all_branch_labels);
node_max_depth = arrayfun(@(ii) max(find(~empty_matrix(ii, :))), 1:n_nodes);
final_labels = arrayfun(@(ii) all_branch_labels{ii, node_max_depth(ii)}, 1:n_nodes, 'unif', false);
end
% make branching point lookup table
[branch_points, point_scores] = cellfun(@(this_struct) find_branch_point_xys(this_struct, options_struct), struct_outputs);
% one option:
% for every cell
% get deepest label possible
% then label each node according to most popular
% somehow also some checking?
% have we covered all nodes?
% are any inappropriately duplicated?
% assemble output
recursive_struct = struct( ...
'node_labels', {final_labels}, ...
'branch_tree', {branch_tree}, ...
'branch_points', {branch_points}, ...
'branch_names', {short_branch_names}, ...
'point_scores', {point_scores} ...
);
% save outputs
recursive_output_file = fullfile(input_struct.output_dir, sprintf('%s recursive outputs.mat', input_struct.save_stem));
save(recursive_output_file, 'recursive_struct')
end
%% make_no_branch_variables:
function [final_labels, branch_tree] = make_no_branch_variables(n_nodes)
final_labels = repmat({'1'}, 1, n_nodes);
branch_tree = 0;
end
%% initialize_branch_tree: outputs vector of parents for each node
function branch_tree = initialize_branch_tree(stem_outputs)
% tweak first entry
stem_outputs{1} = 'branch';
% define storage
n_branches = numel(stem_outputs);
branch_tree = zeros(n_branches);
for ii = 2:n_branches
% get this branch
this_branch = stem_outputs{ii};
% trim, match
end_idx = regexp(this_branch, '_[0-9]+$')-1;
trimmed_branch = this_branch(1:end_idx);
parent_idx = find(strcmp(trimmed_branch, stem_outputs));
% store
branch_tree(parent_idx, ii) = 1;
end
end
%% update_branch_tree:
% if at top level, do nothing. otherwise, for each sub-branch:
% find which branch has biggest connection to previous branch point
% need branch flag for parent run (i.e. label for each cell,
% stating whether it's part of the parent branch point. then let
% the branches vote. this branch is connected to self and to
function branch_tree = update_branch_tree(ii, branch_depths, short_branch_names, struct_outputs, branch_tree)
% first allocate all branches to parent
if ii > 1
% find parent branch points for each one at this depth
depth_idx = branch_depths == ii;
% depth_names = short_branch_names(depth_idx);
% parent_branches = unique(cellfun(@(this_name) this_name(1:end-2), depth_names, 'unif', false));
depth_names = short_branch_names(depth_idx);
end_idxs = cellfun(@(this_name) regexp(this_name, '_[0-9]+$')-1, depth_names);
parent_branches = unique(cellfun(@(ii) depth_names{ii}(1:end_idxs(ii)), 1:length(depth_names), 'unif', false));
for this_branch = parent_branches
% which is parent, and which are children
this_branch = this_branch{1};
parent_idx = find(strcmp(this_branch, short_branch_names));
% get parent outputs to decide split
parent_struct = struct_outputs{parent_idx};
% unpack a bit
branch_parent_point = parent_struct.branch_parent_point;
cell_assignments = parent_struct.cell_assignments;
best_branches = parent_struct.best_branches;
% exclude outliers
outlier_idx = cell_assignments == 0;
if sum(outlier_idx) > 0
fprintf('we have outliers')
branch_parent_point = branch_parent_point(~outlier_idx);
cell_assignments = cell_assignments(~outlier_idx);
end
% count how much of the parent branch point ends up in each child branch
branches_by_cell = best_branches(cell_assignments);
[branch_point_votes, branch_name_checks] = grpstats(branch_parent_point, branches_by_cell, {'sum', 'gname'});
if strcmp(branch_name_checks{1}, '0')
branch_point_votes = branch_point_votes(2:end);
branch_name_checks = branch_name_checks(2:end);
else
error('first branch name should be 0')
end
% find max
[~, max_branch] = max(branch_point_votes);
max_branch_name = sprintf('%s_%d', this_branch, max_branch);
% find where this is in tree
max_child_idx = find(strcmp(max_branch_name, short_branch_names));
grandparent_idx = find(branch_tree(:, parent_idx));
% do editing
branch_tree(grandparent_idx, parent_idx) = 0;
branch_tree(parent_idx, max_child_idx) = 0;
branch_tree(grandparent_idx, max_child_idx) = 1;
branch_tree(max_child_idx, parent_idx) = 1;
end
end
end
%% find_branch_point_xys:
function [branch_point, point_score] = find_branch_point_xys(this_struct, options_struct)
% check if treetop was run on this branch
if this_struct.run_flag == true
% unpack
branch_scores = this_struct.branch_scores;
cell_assignments = this_struct.cell_assignments;
% get appropriate non-branching distribution, normalize scores
[n_ref_cells, n_dims] = size(this_struct.used_values);
n_points = size(this_struct.cell_assignments, 1);
non_branching_distn = get_non_branching_distn(n_ref_cells, n_points, n_dims);
cutoff_q = quantile(non_branching_distn, options_struct.p_cutoff);
normed_scores = branch_scores / cutoff_q;
% now calculate location of best branch point
if isfield(this_struct, 'cell_assignments_top')
% unpack
cell_assignments_top = this_struct.cell_assignments_top;
% calculate where the branch point lines up at the top
[max_score, max_idx] = max(normed_scores);
branch_idx = cell_assignments == max_idx;
branch_top = cell_assignments_top(branch_idx);
% find which node is best fit
[node_counts, node_labels] = grpstats(branch_top, branch_top, {'numel', 'gname'});
[~, max_node] = max(node_counts);
branch_point = str2num(node_labels{max_node});
else
[max_score, branch_point] = max(normed_scores);
end
point_score = max_score;
else
% dummy branch_point
branch_point = 0;
% give branch score of 0
point_score = 0;
end
end
%% plot_recursive_outputs:
function [] = plot_recursive_outputs(input_struct, options_struct, recursive_struct)
fprintf('plotting outputs for recursive TreeTop\n')
% get layout
recursive_flag = true;
layout_struct = get_layout_struct(input_struct, options_struct, recursive_flag);
% unpack
node_labels = recursive_struct.node_labels;
branch_points = recursive_struct.branch_points;
branch_names = recursive_struct.branch_names;
point_scores = recursive_struct.point_scores;
branch_tree = recursive_struct.branch_tree;
celltype_vector = recursive_struct.celltype_vector;
cell_assignments = recursive_struct.cell_assignments;
n_samples = length(unique(celltype_vector));
file_ext = options_struct.file_ext;
layout_xy = layout_struct.layout_xy;
layout_graph = layout_struct.layout_graph;
% edit where branch points are for branches where treetop not run
branch_points = tweak_branch_point_xys(layout_xy, node_labels, branch_names, branch_points);
branch_xy = layout_xy(branch_points, :);
% set up figure
fig = figure('visible', 'off');
n_cols = 2;
n_rows = 2;
plot_ii = 1;
grey_val = 0.8;
% plot branches as colour
subplot(n_rows, n_cols, plot_ii)
plot_ii = plot_ii+1;
plot_branches_coloured(layout_graph, layout_xy, grey_val, node_labels)
% plot branches as text
subplot(n_rows, n_cols, plot_ii)
plot_ii = plot_ii+1;
plot_branches_labelled(layout_graph, layout_xy, grey_val, node_labels)
% plot contingency table
if n_samples > 1
subplot(n_rows, n_cols, plot_ii)
plot_ii = plot_ii+1;
plot_contingency_table_recursive(recursive_struct)
end
% plot branch points
subplot(n_rows, n_cols, plot_ii)
plot_ii = plot_ii+1;
plot_branch_tree(layout_graph, layout_xy, grey_val, branch_tree, branch_xy, point_scores)
% save outputs
plot_stem = fullfile(input_struct.output_dir, sprintf('%s recursive branches', input_struct.save_stem));
plot_unit = 4;
fig_size = [plot_unit*n_cols*1.1, plot_unit*n_rows];
plot_fig(fig, plot_stem, file_ext, fig_size)
end
%% tweak_branch_point_xys:
function branch_points = tweak_branch_point_xys(layout_xy, node_labels, branch_names, branch_points)
for ii = 1:length(branch_points)
if branch_points(ii) == 0
% find which points correspond to this branch
this_name = branch_names{ii};
% find point closest to centre
branch_idx = find(strcmp(node_labels, this_name));
branch_xy = layout_xy(branch_idx, :);
mean_xy = mean(branch_xy, 1);
temp = branch_xy - repmat(mean_xy, size(branch_xy, 1), 1);
[~, near_idx] = min( sum(temp.^2,2) );
branch_points(ii) = branch_idx(near_idx);
end
end
end
%% plot_branch_tree:
function plot_branch_tree(layout_graph, layout_xy, grey_val, branch_tree, branch_xy, point_scores)
hold on
% plot whole graph behind
gplot(layout_graph, layout_xy, '-k');
h = gca;
h2 = get(h, 'Children');
set(h2, 'color', [grey_val, grey_val, grey_val])
% plot graph connecting branch points
gplot(branch_tree, branch_xy, '-k');
% plot branch scores in order
[~, point_idx] = sort(point_scores);
scatter(branch_xy(point_idx, 1), branch_xy(point_idx, 2), [], point_scores(point_idx)', 'filled');
score_range = [0, ceil(max([point_scores(:); 1]))];
% point_size = 40;
% size_vector = point_size * ones(size(branch_xy, 1), 1);
% size_vector(1) = point_size * 2;
plot_size = get(gca, 'Position');
bar_obj = colorbar;
set(gca, 'Position', plot_size);
bar_pos = get(bar_obj, 'position');
bar_pos(3:4) = bar_pos(3:4) / 2;
bar_pos(1) = bar_pos(1) - bar_pos(3);
bar_pos(2) = bar_pos(2) + bar_pos(4)/2;
set(bar_obj, 'position', bar_pos)
ylabel(bar_obj, 'Relative branching score', 'interpreter', 'none')
% where the position arguments are [xposition yposition width height].
caxis( score_range )
xlim([0,1])
ylim([0,1])
xlabel('TreeTop 1'); ylabel('TreeTop 2')
% labels
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
hold off
end
%% plot_branches_coloured:
function plot_branches_coloured(layout_graph, layout_xy, grey_val, node_labels)
hold on
gplot(layout_graph, layout_xy, '-k');
h = gca;
h2 = get(h, 'Children');
grey_val = 0.8;
set(h2, 'color', [grey_val, grey_val, grey_val])
gscatter_for_recursive(layout_xy(:,1), layout_xy(:,2), node_labels);
% % plot branch scores in order
% [~, point_idx] = sort(point_scores);
% gplot(branch_tree, branch_xy, '-k');
% scatter(branch_xy(point_idx, 1), branch_xy(point_idx, 2), 60, point_scores(point_idx)', 'filled');
% score_range = [0, ceil(max([point_scores(:); 1]))];
% sort out plot
xlim([0, 1])
ylim([0, 1])
xlabel('TreeTop 1'); ylabel('TreeTop 2')
hold off
% label graph
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
end
%% gscatter_for_recursive: slightly fancy plotting for recursive plots
function [h_legend] = gscatter_for_recursive(x, y, node_labels, options)
% sort out holding
hold_status = ishold;
if ~hold_status
hold on
end
% get palette
ctype = 'qual';
palette = 'Set1';
point_size = 10;
legend_flag = false;
location = 'EastOutside';
if nargin > 3
if isfield(options, 'palette')
palette = options.palette;
end
if isfield(options, 'size')
point_size = options.size;
end
if isfield(options, 'legend')
legend_flag = options.legend;
end
if isfield(options, 'leg_pos')
location = options.leg_pos;
end
end
% regex to get top level of branches, then see where they are
g_top = cellfun(@(c) regexp(c, '^[0-9]+', 'match'), node_labels);
[top_vals, ~, g_idx] = unique(g_top);
if ~iscell(top_vals)
top_vals = arrayfun(@num2str, top_vals, 'unif', false);
end
% how many top branches, sub-branches?
n_top = length(top_vals);
n_all = length(unique(node_labels));
% set up plots
h = zeros(n_all, 1);
% if more than nine of those, don't do anything fancy
if n_top > 9
[~, ~, all_idx] = unique(node_labels);
scatter(x, y, point_size, g_idx, 'filled');
else
% define top-level palette
n_pal = max(n_top, 3);
pal_top = cbrewer(ctype, palette, n_pal);
% define counter for top branches
col_inc = 1;
% loop through top branches
for ii = 1:n_top
% which branch is this?
ii_val = top_vals{ii};
branch_idx = g_idx == ii;
% how many sub-branches?
sub_vals = unique(node_labels(branch_idx));
n_sub = length(sub_vals);
if n_sub==1
this_idx = strcmp(node_labels, sub_vals{1});
h(col_inc) = plot(x(this_idx), y(this_idx), '.', 'color', pal_top(ii, :), 'markersize', point_size*2);
col_inc = col_inc + 1;
else
% make palette for sub_branches based on top branch colour
hsv_top = rgb2hsv(pal_top(ii, :));
hsv_sub = repmat(hsv_top, n_sub, 1);
s_range = [0.95, 0.05];
s_vector = linspace(s_range(1), s_range(2), n_sub);
v_vector = 1 - 0.6*(1-max(s_range))./(1 - s_vector);
hsv_sub(:, 2) = s_vector;
hsv_sub(:, 3) = v_vector;
pal_sub = hsv2rgb(hsv_sub);
% plot each sub-branch individually
for jj = 1:n_sub
this_sub = sub_vals{jj};
this_idx = strcmp(node_labels, this_sub);
h(col_inc) = plot(x(this_idx), y(this_idx), '.', 'color', pal_sub(jj, :), 'markersize', point_size*2);
col_inc = col_inc + 1;
end
end
end
end
% add branch points on top?
if legend_flag
h_legend = legend(h, g_vals{:}, 'Location', location);
else
h_legend = [];
end
if ~hold_status
hold off
end
end
%% plot_branches_labelled:
function plot_branches_labelled(layout_graph, layout_xy, grey_val, node_labels)
hold on
gplot(layout_graph, layout_xy, '-k');
h = gca;
h2 = get(h, 'Children');
set(h2, 'color', [grey_val, grey_val, grey_val])
text(layout_xy(:,1), layout_xy(:,2), node_labels, 'fontsize', 6, 'interpreter', 'none', 'horizontalalignment', 'center', 'verticalalignment', 'middle');
xlim([0, 1])
ylim([0, 1])
xlabel('TreeTop 1'); ylabel('TreeTop 2')
hold off
% label graph
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
end
%% plot_contingency_table_recursive:
function plot_contingency_table_recursive(recursive_struct)
% unpack
cell_assignments = recursive_struct.cell_assignments;
celltype_vector = recursive_struct.celltype_vector;
node_labels = recursive_struct.node_labels;
[branch_names, ~, node_idx] = unique(node_labels);
% remove any outliers
non_outlier_idx = cell_assignments ~= 0;
cell_assignments = cell_assignments(non_outlier_idx);
celltype_vector = celltype_vector(non_outlier_idx);
% % assign branches to all original cells
% branches_by_cell = node_idx(cell_assignments);
% % recalculate counts
% [branch_counts, count_labels] = grpstats(branches_by_cell, branches_by_cell, {'numel', 'gname'});
% count_labels = cellfun(@(str) str2num(str), count_labels);
% % lookup table which has new label for each branch, according to order
% [~, count_order] = sort(-branch_counts);
% [~, ranked_labels] = sort(count_order);
% branches_by_size = branch_names(count_order);
% % put in order from top left to top right, plot table
% [mean_branch_by_celltype, labels] = grpstats(ranked_labels(branches_by_cell), celltype_vector, {'mean', 'gname'});
% [~, sort_idx] = sort(mean_branch_by_celltype);
% col_order = labels(sort_idx);
% plot_contingency_table(branch_names(branches_by_cell), celltype_vector, branches_by_size, col_order)
% recalculate counts
[branch_counts, count_labels] = grpstats(node_idx, node_idx, {'numel', 'gname'});
count_labels = cellfun(@(str) str2num(str), count_labels);
% lookup table which has new label for each branch, according to order
[~, count_order] = sort(-branch_counts);
[~, ranked_labels] = sort(count_order);
branches_by_size = branch_names(count_order);
% put in order from top left to top right, plot table
[mean_branch_by_celltype, labels] = grpstats(ranked_labels(node_idx(cell_assignments)), celltype_vector, {'mean', 'gname'});
[~, sort_idx] = sort(mean_branch_by_celltype);
col_order = labels(sort_idx);
plot_contingency_table(branch_names(node_idx(cell_assignments)), celltype_vector, branches_by_size, col_order)
end
|
github
|
wmacnair/TreeTop-master
|
treetop_branching_scores.m
|
.m
|
TreeTop-master/TreeTop/treetop_branching_scores.m
| 12,172 |
utf_8
|
d294c6bd413cf9fe16918dc07944ee21
|
%% treetop_branching_scores: calculate bifurcation score for given treetop run
function [] = treetop_branching_scores(input_struct, options_struct)
% check inputs
[input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct);
% define set of thresholds
threshold_list = 0.99:-0.01:0.01;
% get outputs we need
treetop_struct = get_treetop_outputs(input_struct);
% get consensus matrices for the branch points
consistency_array = get_consistency_matrices(input_struct, options_struct, treetop_struct);
% what happens when we gradually increase the threshold at which we keep edges?
consensus_branch_sizes = calc_consensus_branch_sizes(consistency_array, input_struct, options_struct, threshold_list);
% calculate mean size of these
branching_scores = calc_branching_scores(consensus_branch_sizes, input_struct);
% save best branches
calc_and_save_best_branches(branching_scores, consistency_array, consensus_branch_sizes, threshold_list, input_struct, options_struct)
end
%% get_consistency_matrices: cut each tree at each node, take average across all trees
function consistency_array = get_consistency_matrices(input_struct, options_struct, treetop_struct, selected_nodes)
% unpack
n_nodes = options_struct.n_ref_cells;
n_trees = options_struct.n_trees;
tree_dist_cell = treetop_struct.tree_dist_cell;
% initialize various things (third dimension in arrays is cut point)
consistency_array = zeros(n_nodes, n_nodes, n_nodes);
% do bifurcation scores for each tree
fprintf('splitting each tree at each node (%d trees, . = 50): ', n_trees);
if options_struct.pool_flag
parfor ii = 1:n_trees
if mod(ii, 50) == 0
fprintf([char(8), '. '])
end
% get tree, calculate consensus matrix
this_dist_tree = tree_dist_cell{ii};
this_consistency = calc_one_consistency_matrix(this_dist_tree);
% store
consistency_array = consistency_array + this_consistency;
end
else
for ii = 1:n_trees
if mod(ii, 50) == 0, fprintf('.'); end
% get tree, calculate consensus matrix
this_dist_tree = tree_dist_cell{ii};
this_consistency = calc_one_consistency_matrix(this_dist_tree);
% store
consistency_array = consistency_array + this_consistency;
end
fprintf('\n')
end
% normalize
consistency_array = consistency_array / n_trees;
% put -1s in columns and rows
for ii = 1:n_nodes
neg_idx = 1:n_nodes ~= ii;
consistency_array(neg_idx, ii, ii) = -1;
consistency_array(ii, neg_idx, ii) = -1;
end
end
%% calc_one_consistency_matrix:
function this_consistency = calc_one_consistency_matrix(this_dist_tree)
% unpack, initialize
n_nodes = size(this_dist_tree, 1);
this_consistency = zeros(n_nodes, n_nodes, n_nodes);
this_counts = zeros(n_nodes, n_nodes, n_nodes);
% loop through all selected nodes
for this_node = 1:n_nodes
% make tree with this node removed
split_tree = this_dist_tree;
split_tree(this_node, :) = 0;
split_tree(:, this_node) = 0;
% calculate components
blocks = components(split_tree);
% update consensus matrix
branch_list = unique(blocks);
for kk = branch_list
kk_idx = blocks == kk;
this_consistency(kk_idx, kk_idx, this_node) = 1;
end
% but remove info from the node we cut at
this_consistency(this_node, this_node, this_node) = 0;
end
end
%% calc_consensus_branch_sizes:
function [consensus_branch_sizes] = calc_consensus_branch_sizes(consistency_array, input_struct, options_struct, threshold_list)
% unpack
n_nodes = options_struct.n_ref_cells;
% check if size file already exists
size_file = fullfile(input_struct.output_dir, sprintf('%s consensus branch sizes.mat', input_struct.save_stem));
% define thresholds, cutoffs to use
threshold_max = 1;
cutoff_list = threshold_max - threshold_list;
n_thresholds = length(threshold_list);
n_cutoffs = length(cutoff_list);
% define storage variable
consensus_branch_sizes = cell(n_nodes, 1);
% do clustering etc for each consensus matrix
fprintf('calculating branches with hierarchical clustering\n');
if options_struct.pool_flag
parfor this_node = 1:n_nodes
% get relevant point and matrix
this_consistency = squeeze(consistency_array(:, :, this_node));
% remove negative values
this_idx = 1:n_nodes == this_node;
this_consistency = this_consistency( ~this_idx, ~this_idx );
% convert similarity matrix into dissimilarity, then vector
dis_mat = 1 - this_consistency;
dis_vec = squareform(dis_mat, 'tovector');
% apply linkage (i.e. group nodes according to linkage specified in link_str)
this_link = linkage(dis_vec, 'single');
% extract clusters at each cutpoint
cluster_mat = cluster(this_link, 'cutoff', cutoff_list, 'criterion', 'distance');
% how many clusters is this?
this_max = max(cluster_mat(:));
% count how many clusters at each cutoff, reorder by size
[mesh_ii, mesh_jj] = meshgrid(1:n_cutoffs, 1:this_max);
cluster_sizes = arrayfun( @(ii, jj) sum(cluster_mat(:, ii) == jj), mesh_ii, mesh_jj);
cluster_sizes = cell2mat(arrayfun(@(ii) sort(cluster_sizes(:, ii), 'descend'), 1:n_cutoffs, 'unif', false))';
% remove singletons, then remove any empty columns
cluster_sizes(cluster_sizes == 1) = 0;
empty_cols = sum(cluster_sizes, 1) == 0;
cluster_sizes(:, empty_cols) = [];
% store
consensus_branch_sizes{this_node} = cluster_sizes;
end
else
for this_node = 1:n_nodes
% get relevant point and matrix
this_consistency = squeeze(consistency_array(:, :, this_node));
% remove negative values
this_idx = 1:n_nodes == this_node;
this_consistency = this_consistency( ~this_idx, ~this_idx );
% convert similarity matrix into dissimilarity, then vector
dis_mat = 1 - this_consistency;
dis_vec = squareform(dis_mat, 'tovector');
% apply linkage (i.e. group nodes according to linkage specified in link_str)
this_link = linkage(dis_vec, 'single');
% extract clusters at each cutpoint
cluster_mat = cluster(this_link, 'cutoff', cutoff_list, 'criterion', 'distance');
% how many clusters is this?
this_max = max(cluster_mat(:));
% count how many clusters at each cutoff, reorder by size
[mesh_ii, mesh_jj] = meshgrid(1:n_cutoffs, 1:this_max);
cluster_sizes = arrayfun( @(ii, jj) sum(cluster_mat(:, ii) == jj), mesh_ii, mesh_jj);
cluster_sizes = cell2mat(arrayfun(@(ii) sort(cluster_sizes(:, ii), 'descend'), 1:n_cutoffs, 'unif', false))';
% remove singletons, then remove any empty columns
cluster_sizes(cluster_sizes == 1) = 0;
empty_cols = sum(cluster_sizes, 1) == 0;
cluster_sizes(:, empty_cols) = [];
% store
consensus_branch_sizes{this_node} = cluster_sizes;
end
end
% save outputs
save(size_file, 'consensus_branch_sizes', 'threshold_list', 'threshold_max');
end
%% calc_branching_scores:
function branching_scores = calc_branching_scores(consensus_branch_sizes, input_struct)
% unpack, initialize
n_nodes = numel(consensus_branch_sizes);
branching_scores = zeros(n_nodes, 1);
% exclude clusters accounting for 1% or less of nodes
cutoff = 0.01;
% loop through all
fprintf('calculating branching scores\n');
for ii = 1:n_nodes
% get this branch size value
this_branch_sizes = consensus_branch_sizes{ii};
this_branch_sizes = this_branch_sizes / n_nodes * 100;
% check whether there are at least 3 clusters
n_clusters = size(this_branch_sizes, 2);
% if not, set to 0
if n_clusters <= 2
branching_scores(ii) = 0;
% use mean size of all clusters above third, above a given threshold
else
% apply cutoff
this_branch_sizes( this_branch_sizes(:)<=cutoff ) = 0;
% define cols to use
smaller_branches = sum(this_branch_sizes(:, 3:end), 2);
branching_scores(ii) = mean(smaller_branches);
end
end
% save bifurcation scores
fprintf('saving branching scores\n');
scores_file = fullfile(input_struct.output_dir, sprintf('%s branching scores.txt', input_struct.save_stem));
save_txt_file(scores_file, {'score'}, branching_scores);
end
%% calc_and_save_best_branches: finds best branches, saves them
function calc_and_save_best_branches(branching_scores, consistency_array, consensus_branch_sizes, threshold_list, input_struct, options_struct)
% unpack
n_nodes = options_struct.n_ref_cells;
% get best one
[~, best_point] = max(branching_scores);
best_point = best_point(1);
best_boolean = 1:n_nodes == best_point;
% pick threshold giving largest 3rd branch
this_sizes = consensus_branch_sizes{best_point};
if size(this_sizes, 2) < 3
best_branches = ones(size(branching_scores));
fprintf('no branches found at all for run %s\n', input_struct.save_stem);
else
[~, size_idx] = max( this_sizes(:,3) );
best_thresh = threshold_list(size_idx);
% get and process consensus matrix
this_consistency = squeeze(consistency_array(:, :, best_boolean));
this_consistency = this_consistency( ~best_boolean, ~best_boolean );
% do clustering
best_branches = cluster_consistency_matrix(this_consistency, best_thresh);
% put in sensible order which also excludes singletons
best_branches = process_best_branches(best_branches, this_consistency, best_boolean, options_struct);
end
% save
branches_file = fullfile(input_struct.output_dir, sprintf('%s best branches.txt', input_struct.save_stem));
save_txt_file(branches_file, {'branch'}, best_branches)
end
%% cluster_consistency_matrix:
function best_branches = cluster_consistency_matrix(this_consistency, best_thresh)
% convert similarity matrix into dissimilarity, then vector
dis_mat = 1 - this_consistency;
dis_vec = squareform(dis_mat, 'tovector');
% apply linkage (i.e. group nodes via single linkage)
this_link = linkage(dis_vec, 'single');
best_branches = cluster(this_link, 'cutoff', 1 - best_thresh, 'criterion', 'distance');
end
%% process_best_branches: we want to remove singletons from our clustering
function [best_branches] = process_best_branches(best_branches, this_consistency, best_boolean, options_struct)
% get components, and their sizes
[counts, labels] = grpstats(best_branches, best_branches, {'numel', 'gname'});
labels = cellfun(@(str) str2num(str), labels);
% option to force 3 branches to be returned
if options_struct.three_flag
% find top 3 clusters
[~, count_idx] = sort(-counts);
n_counts = length(counts);
top_3 = min(n_counts, 3);
multiples = labels(count_idx(1:top_3));
else
% find non-singleton labels
cutoff = 0.01;
multiples_idx = counts / sum(counts) > cutoff & counts > 1;
multiples = labels(multiples_idx);
end
% get node locations
singles = setdiff(labels, multiples);
singles_idx = find(ismember(best_branches, singles));
multiples_idx = find(ismember(best_branches, multiples));
% find nearest multiple for every single
simil_matrix = this_consistency( singles_idx, multiples_idx );
[~, closest_multiple] = max(simil_matrix, [], 2);
% relabel
branches_no_singles = best_branches;
branches_no_singles(singles_idx) = best_branches(multiples_idx(closest_multiple));
% relabel to shorter list
[~, ~, branches_no_singles] = unique(branches_no_singles);
% recalculate counts
[new_counts, new_labels] = grpstats(branches_no_singles, branches_no_singles, {'numel', 'gname'});
new_labels = cellfun(@(str) str2num(str), new_labels);
% lookup table which has new label for each branch, according to order
[~, count_order] = sort(-new_counts);
[~, ranked_labels] = sort(count_order);
branches_by_size = ranked_labels(branches_no_singles);
% check it has worked
check_table = tabulate(branches_by_size);
if any( check_table(2:end, 1) - check_table(1:end-1, 1) ~= 1)
error('relabelling went wrong');
end
if any( check_table(2:end, 2) > check_table(1:end-1, 2) )
error('relabelling went wrong');
end
% put together into full branch, with 0 at branch point
best_branches = zeros(size(best_boolean))';
best_branches(best_boolean) = 0;
best_branches(~best_boolean) = branches_by_size;
end
|
github
|
wmacnair/TreeTop-master
|
treetop_plots.m
|
.m
|
TreeTop-master/TreeTop/treetop_plots.m
| 19,357 |
utf_8
|
9683e1a142bffa061aca23c794782fcb
|
%% treetop_plots: plot marker values on layout, sample arrangement, and bifurcation outputs
% maybe also do ANOVA thing?
function treetop_plots(input_struct, options_struct)
% parse inputs
[input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct);
% get outputs we need
treetop_struct = get_treetop_outputs(input_struct);
% do / get layout
layout_struct = get_layout_struct(input_struct, options_struct);
% plot marker values nicely (both used and extra markers)
plot_marker_values_on_treetop(treetop_struct, layout_struct, input_struct, options_struct);
% plot samples over layout
plot_samples_on_treetop(treetop_struct, layout_struct, input_struct, options_struct);
% plot density distribution
plot_density(treetop_struct, layout_struct, input_struct, options_struct);
% plot scores for all points over graph layout
plot_branching_scores(treetop_struct, layout_struct, input_struct, options_struct);
% plot scores for all points over graph layout
plot_branch_profiles(treetop_struct, input_struct, options_struct);
end
%% plot_marker_values_on_treetop:
function [] = plot_marker_values_on_treetop(treetop_struct, layout_struct, input_struct, options_struct)
% unpack
layout_xy = layout_struct.layout_xy;
layout_graph = layout_struct.layout_graph;
% define data to loop through
values_cell = {treetop_struct.used_values, treetop_struct.extra_values};
markers_cell = {input_struct.used_markers, input_struct.extra_markers};
names_cell = {'used', 'extra'};
for ii = 1:length(values_cell)
% unpack
this_values = values_cell{ii};
this_markers = markers_cell{ii};
this_name = names_cell{ii};
if isempty(this_values)
continue
end
fprintf('plotting mean %s marker values\n', this_name);
% start figure
fig = figure('Visible','off');
n_plots = size(this_values, 2);
plot_ratio = 1.5;
n_rows = ceil(sqrt(n_plots / plot_ratio));
n_cols = ceil(n_plots / n_rows);
clim = [0, 1];
% scale marker values
max_vals = max(this_values, [], 1);
min_vals = min(this_values, [], 1);
scaled_vals = bsxfun( ...
@times, ...
bsxfun(@minus, this_values, min_vals), ...
1./(max_vals - min_vals) ...
);
% loop through all selected markers
for ii = 1:n_plots
% set up plot
subplot(n_rows, n_cols, ii)
% order values
these_vals = scaled_vals(:, ii);
[~, idx] = sort(these_vals);
% plot
hold on
gplot(layout_graph, layout_xy, '-k');
scatter(layout_xy(idx, 1), layout_xy(idx, 2), [], these_vals(idx), 'filled')
xlim([0, 1])
ylim([0, 1])
caxis(clim);
% labels
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
title(this_markers{ii}, 'interpreter', 'none')
xlabel('TreeTop 1'); ylabel('TreeTop 2');
hold off
end
last_plot = get(subplot(n_rows, n_cols, n_cols), 'Position');
% [left bottom width height]
colorbar('Position', [last_plot(1)+last_plot(3)+0.01 last_plot(2) 0.02 last_plot(4)])
% remove white space
set(gca,'LooseInset', get(gca,'TightInset'));
% save figure
plot_stem = fullfile(input_struct.output_dir, sprintf('%s %s marker values', input_struct.save_stem, this_name));
plot_unit = 4;
fig_size = [plot_unit*n_cols plot_unit*n_rows];
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size)
end
end
%% plot_samples_on_treetop:
function [] = plot_samples_on_treetop(treetop_struct, layout_struct, input_struct, options_struct)
fprintf('plotting samples\n');
% unpack
layout_xy = layout_struct.layout_xy;
layout_graph = layout_struct.layout_graph;
sample_counts = treetop_struct.sample_counts;
sample_names = treetop_struct.sample_names;
% start figure
fig = figure('Visible','off');
n_plots = size(sample_counts, 2);
plot_ratio = 2;
n_rows = ceil(sqrt(n_plots / plot_ratio));
n_cols = ceil(n_plots / n_rows);
% scale values
max_size = 500;
scale_factor = max_size / max(sample_counts(:));
% loop through all selected markers
for ii = 1:n_plots
% set up plot
subplot(n_rows, n_cols, ii)
% order values
these_vals = scale_factor * sample_counts(:, ii);
non_zeros = these_vals > 0;
% plot
hold on
grey_gplot(layout_graph, layout_xy);
scatter(layout_xy(non_zeros, 1), layout_xy(non_zeros, 2), these_vals(non_zeros), 'filled');
xlim([0, 1])
ylim([0, 1])
% labels
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
xlabel('TreeTop 1')
ylabel('TreeTop 2')
title(sample_names{ii}, 'interpreter', 'none')
hold off
end
% save figure
plot_stem = fullfile(input_struct.output_dir, sprintf('%s all samples', input_struct.save_stem));
plot_unit = 4;
fig_size = [plot_unit*n_cols plot_unit*n_rows];
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size);
% only plot largest sample plot if we have more than one sample
if numel(sample_names) == 1
return
end
% prepare weights
sample_totals = sum(sample_counts, 1);
sample_props = bsxfun(@rdivide, sample_counts, sample_totals);
[~, max_sample] = max(sample_props, [], 2);
% do plotting
fig = figure('Visible','off');
% subplot(2, 3, [1:2, 4:5])
hold on
gplot(layout_graph, layout_xy, '-k');
better_gscatter(layout_xy(:, 1), layout_xy(:, 2), max_sample);
xlim([0, 1])
ylim([0, 1])
hold off
% add legend, adjust position
h_all = findobj(gca,'Type','line');
h_legend = legend(h_all(end-1:-1:1), sample_names, 'fontsize', 6, 'location', 'eastoutside');
% pos_legend = get(h_legend, 'position');
% pos_legend(1) = 0.9;
% pos_legend(2) = 0.4;
% set(h_legend, 'position', pos_legend);
% labels
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
title('Sample with highest proportion at each point')
% save figure
plot_stem = fullfile(input_struct.output_dir, sprintf('%s largest sample', input_struct.save_stem));
fig_size = [6, 4];
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size);
end
%% plot_density: mainly for diagnostics on density
function [] = plot_density(treetop_struct, layout_struct, input_struct, options_struct)
fprintf('plotting density\n');
% unpack
layout_xy = layout_struct.layout_xy;
layout_graph = layout_struct.layout_graph;
density = treetop_struct.density;
cell_assignments = treetop_struct.cell_assignments;
celltypes = treetop_struct.celltype_vector;
% calculate mean density at each point
[mean_density, labels] = grpstats(density, cell_assignments, {'mean', 'gname'});
% remove any zeros
if strcmp(labels{1}, '0')
mean_density = mean_density(2:end);
end
% start figure
fig = figure('Visible','off');
n_rows = 1;
n_cols = 3;
plot_ii = 1;
% plot mean density at each point
subplot(n_rows, n_cols, plot_ii)
plot_ii = plot_ii + 1;
hold on
gplot(layout_graph, layout_xy, '-k');
scatter(layout_xy(:, 1), layout_xy(:, 2), [], mean_density, 'filled')
xlim([0, 1])
ylim([0, 1])
% labels
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
xlabel('TreeTop 1')
ylabel('TreeTop 2')
title({'Mean density at each point', sprintf('(sigma = %.1e)', options_struct.sigma)})
hold off
% plot histogram of all density values
subplot(n_rows, n_cols, plot_ii)
plot_ii = plot_ii + 1;
histogram(density);
xlim_vals = xlim;
xlim([0, xlim_vals(2)]);
xlabel('Density')
ylabel('# cells')
title('Distribution of all density values')
% set up celltypes
celltype_list = unique(celltypes);
n_labels = numel(celltype_list);
% plot density distributions by label
subplot(n_rows, n_cols, plot_ii)
plot_ii = plot_ii + 1;
if n_labels > 9
clr = jet(n_labels);
elseif n_labels < 3
clr = cbrewer('qual', 'Set1', 3);
clr = clr(1:n_labels, :);
else
clr = cbrewer('qual', 'Set1', n_labels);
end
hold on
for kk = 1:n_labels
% restrict to this label
this_label = celltype_list(kk);
this_idx = celltypes == this_label;
% plot ECDF
h(kk) = cdfplot(density(this_idx));
set(h(kk), 'Color', clr(kk,:))
end
hold off
% add legend, adjust position
h_legend = legend({char(celltype_list)}, 'FontSize', 4);
pos_legend = get(h_legend,'position');
pos_legend(1) = 0.8;
pos_legend(2) = 0.2;
set(h_legend, 'position', pos_legend);
% add other labels
xlabel('Density')
ylabel('F(x)')
title('ECDF of density values by label')
% save figure
plot_stem = fullfile(input_struct.output_dir, sprintf('%s density distribution', input_struct.save_stem));
plot_unit = 4;
fig_size = [plot_unit*n_cols*1.1 plot_unit*n_rows];
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size)
end
%% plot_branching_scores:
function [] = plot_branching_scores(treetop_struct, layout_struct, input_struct, options_struct)
fprintf('plotting branching scores\n');
% unpack
branch_scores = treetop_struct.branch_scores;
best_branches = treetop_struct.best_branches;
n_ref_cells = length(best_branches);
[n_points, n_dims] = size(treetop_struct.used_data);
file_ext = options_struct.file_ext;
layout_xy = layout_struct.layout_xy;
layout_graph = layout_struct.layout_graph;
% get cell labelling data
sample_names = treetop_struct.sample_names;
n_samples = length(sample_names);
% set up figure
fig = figure('visible', 'off');
if n_samples > 1
n_cols = 4;
else
n_cols = 3;
end
n_rows = 1;
% normalize branch scores with reference to scores from non-branching distribution
non_branching_distn = get_non_branching_distn(n_ref_cells, n_points, n_dims);
q_cutoff = quantile(non_branching_distn, options_struct.p_cutoff);
normed_scores = branch_scores / q_cutoff;
% plot scores in increasing order
subplot(n_rows, n_cols, 1)
[~, score_idx] = sort(normed_scores);
hold on
gplot(layout_graph, layout_xy, '-k');
scatter(layout_xy(score_idx, 1), layout_xy(score_idx, 2), 30, normed_scores(score_idx), 'filled');
xlim([0, 1])
ylim([0, 1])
hold off
% label graph
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
xlabel('TreeTop 1')
ylabel('TreeTop 2')
max_score = max(normed_scores);
title_str = {'Relative branching scores', sprintf('(max = %.1f)', max_score)};
title(title_str)
% plot distribution of scores relative to defined cutoff
subplot(n_rows, n_cols, 2)
hold on
ecdf(normed_scores)
ylim_vals = ylim(gca);
line([1, 1], ylim_vals, 'linestyle', '--', 'color', 'k');
hold off
% label graph
n_branch_pts = sum(normed_scores > 1);
xlabel('Relative branching score')
ylabel('ECDF(score)')
title_str = {'Distribution of scores', sprintf('(%d higher than non-branching distribution)', n_branch_pts)};
title(title_str)
% plot branches for highest score
subplot(n_rows, n_cols, 3)
% plot graph as background
hold on
grey_gplot(layout_graph, layout_xy);
% identify non-singleton, non branching point branches
branch_counts = tabulate(best_branches);
branch_list = branch_counts(:, 1);
disp_branches = branch_list(branch_counts(:, 1) > 0 & branch_counts(:, 2) > 1);
show_idx = ismember(best_branches, disp_branches);
if max_score > 1
better_gscatter(layout_xy(show_idx, 1), layout_xy(show_idx, 2), best_branches(show_idx));
else
plot(layout_xy(:, 1), layout_xy(:, 2), '.', 'markersize', 10);
end
% plot branching point itself
split_idx = best_branches == 0;
plot(layout_xy(split_idx, 1), layout_xy(split_idx, 2), '.k', 'markersize', 40);
xlim([0, 1])
ylim([0, 1])
hold off
% labels
set(gca, 'XTickLabel', '')
set(gca, 'YTickLabel', '')
xlabel('TreeTop 1')
ylabel('TreeTop 2')
title('Consensus branches')
h_all = findobj(gca,'Type','line');
branch_names = arrayfun(@num2str, disp_branches, 'unif', false);
h_legend = legend(h_all(end-1:-1:2), branch_names, 'fontsize', 6);
% if worthwhile, plot contingency table of branches vs celltypes
if n_samples > 1
% unpack
cell_assignments = treetop_struct.cell_assignments;
celltype_vector = treetop_struct.celltype_vector;
% remove any outliers
non_outlier_idx = cell_assignments ~= 0;
cell_assignments = cell_assignments(non_outlier_idx);
celltype_vector = celltype_vector(non_outlier_idx);
% assign branches to all original cells
branches_by_cell = best_branches(cell_assignments);
% remove singleton branch assignments
cells_to_keep = ismember(branches_by_cell, disp_branches);
branches_by_cell = branches_by_cell(cells_to_keep);
celltype_vector = celltype_vector(cells_to_keep);
% put in order from top left to top right
[mean_branch_by_celltype, labels] = grpstats(branches_by_cell, celltype_vector, {'mean', 'gname'});
[~, sort_idx] = sort(mean_branch_by_celltype);
col_order = labels(sort_idx);
subplot(n_rows, n_cols, 4)
plot_contingency_table(branches_by_cell, celltype_vector, [], col_order)
end
% save outputs
plot_stem = fullfile(input_struct.output_dir, sprintf('%s branching outputs', input_struct.save_stem));
plot_unit = 4;
fig_size = [plot_unit*n_cols*1.1, plot_unit*n_rows];
plot_fig(fig, plot_stem, file_ext, fig_size)
end
%% grey_gplot:
function h2 = grey_gplot(layout_graph, layout_xy)
gplot(layout_graph, layout_xy, '-k');
h = gca;
h2 = get(h, 'Children');
grey_val = 0.8;
set(h2, 'color', [grey_val, grey_val, grey_val]);
end
%% plot_branch_profiles: plot scores for all points over graph layout
function plot_branch_profiles(treetop_struct, input_struct, options_struct)
if isfield(treetop_struct, 'mean_tree_dist')
fprintf('plotting markers by branch\n')
else
fprintf('MST distance to branch point not calculated; not plotting markers by branch\n')
return
end
% unpack
mean_tree_dist = treetop_struct.mean_tree_dist;
best_branches = treetop_struct.best_branches;
% set up branch vars
branch_point = find(best_branches == 0);
unique_branches = setdiff(unique(best_branches), 0);
n_branches = numel(unique_branches);
palette = cbrewer('qual', 'Set1', n_branches);
% get ordering for each branch
branch_struct_cell = arrayfun(@(kk) get_branch_order(best_branches, mean_tree_dist, kk), 1:n_branches, 'unif', false);
% loop through used, extra
values_cell = {treetop_struct.used_values, treetop_struct.extra_values};
plot_names = {'used', 'extra'};
markers_cell = {input_struct.used_markers, input_struct.extra_markers};
anova_cell = {treetop_struct.anova_used, treetop_struct.anova_extra};
for ii = 1:2
% unpack
sel_values = values_cell{ii};
sel_name = plot_names{ii};
sel_markers = markers_cell{ii};
sel_anova = anova_cell{ii};
if isempty(sel_values)
fprintf('no %s markers; skipping\n', sel_name)
continue
end
% set up figure
fig = figure('visible', 'off');
plot_ratio = 1.5;
n_plots = size(sel_values, 2);
n_rows = ceil(sqrt(n_plots / plot_ratio));
n_cols = ceil(n_plots / n_rows);
% order markers by anova
[~, anova_idx] = sort(sel_anova);
% separate plot for each marker
for jj = 1:n_plots
subplot(n_rows, n_cols, jj)
hold on
% do in order of biggest differences
marker_idx = anova_idx(jj);
% get branch_1 values
% report predictions for branches 1 and kk
% store all branch_1 predictions
% define variable for branch_1_predictions
smooth_1_all = zeros(n_branches-1, sum(branch_struct_cell{1}.this_branch));
int_lo_1_all = zeros(n_branches-1, sum(branch_struct_cell{1}.this_branch));
int_hi_1_all = zeros(n_branches-1, sum(branch_struct_cell{1}.this_branch));
% separate line for each branch
for kk = 2:n_branches
% calculate smoothed values along branch
[smooth_1, int_1, smooth_kk, int_kk] = get_branch_vals(branch_struct_cell, kk, sel_values, marker_idx);
smooth_1_all(kk-1, :) = smooth_1;
int_lo_1_all(kk-1, :) = int_1(:, 1);
int_hi_1_all(kk-1, :) = int_1(:, 2);
% set up colour
branch_col = palette(kk, :);
% % plot original values
% plot(sorted_dist, branch_vals, '.', 'color', branch_col);
% put smoothed values in right order
sort_dist_kk = branch_struct_cell{kk}.sorted_dist;
plot(sort_dist_kk, smooth_kk, '-', 'color', branch_col, 'linewidth', 2);
plot(sort_dist_kk, smooth_kk - int_kk(:,1), ':', 'color', branch_col, 'linewidth', 1);
plot(sort_dist_kk, smooth_kk + int_kk(:,2), ':', 'color', branch_col, 'linewidth', 1);
end
% plot branch 1
smooth_1_mean = mean(smooth_1_all, 1);
int_lo_1_mean = mean(int_lo_1_all, 1);
int_hi_1_mean = mean(int_hi_1_all, 1);
branch_col = palette(1, :);
sort_dist_1 = branch_struct_cell{1}.sorted_dist;
plot(sort_dist_1, smooth_1_mean, '-', 'color', branch_col, 'linewidth', 2);
plot(sort_dist_1, smooth_1_mean - int_lo_1_mean, ':', 'color', branch_col, 'linewidth', 1);
plot(sort_dist_1, smooth_1_mean + int_hi_1_mean, ':', 'color', branch_col, 'linewidth', 1);
% % plot cutpoint itself
% cutpoint_val = sel_values(branch_point, marker_idx);
% plot(0, cutpoint_val, '.', 'color', 'k', 'markersize', 10)
% tidy up plot
ylabel('Marker value')
xlabel('Distance from branching point')
title_str = sprintf('%s (p = %.1e)', sel_markers{marker_idx}, sel_anova(marker_idx));
title(title_str, 'interpreter', 'none')
hold off
% ylim([0,1])
end
% save outputs
plot_stem = fullfile(input_struct.output_dir, sprintf('%s %s marker profiles', input_struct.save_stem, sel_name));
plot_unit = 4;
fig_size = [plot_unit*n_cols*1.1, plot_unit*n_rows];
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size)
end
end
%% get_branch_order:
function [branch_struct] = get_branch_order(best_branches, mean_tree_dist, jj)
% extract data
this_branch = best_branches == jj | best_branches == 0;
branch_dist = mean_tree_dist(this_branch);
[sorted_dist, branch_order] = sort(branch_dist);
% put into struct
branch_struct = struct( ...
'this_branch', this_branch, ...
'branch_dist', branch_dist, ...
'branch_order', branch_order, ...
'sorted_dist', sorted_dist ...
);
end
%% get_branch_vals:
function [smooth_1, int_1, smooth_kk, int_kk] = get_branch_vals(branch_struct_cell, kk, sel_values, marker_idx)
% get values along branch 1 in right order
branch_1_struct = branch_struct_cell{1};
branch_1 = branch_1_struct.this_branch;
order_1 = branch_1_struct.branch_order;
sort_dist_1 = branch_1_struct.sorted_dist;
vals_1 = sel_values(branch_1, marker_idx);
vals_1 = vals_1(order_1);
% get values along branch kk in right order
branch_kk_struct = branch_struct_cell{kk};
branch_kk = branch_kk_struct.this_branch;
order_kk = branch_kk_struct.branch_order;
sort_dist_kk = branch_kk_struct.sorted_dist;
vals_kk = sel_values(branch_kk, marker_idx);
vals_kk = vals_kk(order_kk);
% do smoothed fit to both branches together
% gp_fit = fitrgp(sorted_dist(:), branch_vals(:), 'fitmethod', 'fic', 'predictmethod', 'fic');
fit_obj = fitrgp([sort_dist_1(:); sort_dist_kk(:)], [vals_1(:); vals_kk(:)]);
% do separate predictions
[smooth_1, int_1] = predict(fit_obj, sort_dist_1');
[smooth_kk, int_kk] = predict(fit_obj, sort_dist_kk');
% double up
int_1 = [int_1, int_1];
int_kk = [int_kk, int_kk];
% alternative smoothers considered:
% smooth_vals = smooth(sorted_dist, branch_vals, 50, 'rlowess');
% fit_obj = fit([sorted_dist(:); 0], [branch_vals(:); point_val], 'poly2');
% smooth_vals = feval(fit_obj, [sorted_dist(:); 0]);
end
|
github
|
wmacnair/TreeTop-master
|
treetop_pre_run.m
|
.m
|
TreeTop-master/TreeTop/treetop_pre_run.m
| 9,717 |
utf_8
|
5b3c54d00801b3d973120a385b9c70d5
|
%% treetop_pre_run: Run this before running TreeTop, to check that the markers used are useful.
% Outputs are plots of marginal distributions of all markers, split by input file, and plots of
% mutual information (MI) between markers. High MI between two markers indicates that they share
% information, and therefore might be involved in the same process. For each marker, the maximum
% MI with all other markers is shown; markers with low maximum MI share little information with
% any other marker, and can be considered for exclusion to improve signal in the data.
function treetop_pre_run(input_struct, options_struct)
fprintf('\nrunning pre-run analysis for TreeTop\n')
% get data
[input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct);
fprintf('1/6 Getting data\n')
all_struct = get_all_files(input_struct);
% plot marginals
plot_marginals(all_struct, input_struct, options_struct)
% calculate and plot MI
plot_mi(all_struct, input_struct, options_struct)
fprintf('\ndone.\n\n')
end
%% plot_marginals:
function plot_marginals(all_struct, input_struct, options_struct)
% unpack
all_labels = all_struct.all_labels;
used_data = all_struct.used_data;
used_markers = all_struct.used_markers;
extra_data = all_struct.extra_data;
extra_markers = all_struct.extra_markers;
% identify labels
unique_labels = unique(all_labels);
label_idx = cellfun(@(this_label) strcmp(this_label, all_labels), unique_labels, 'unif', false);
% plot used_markers
fprintf('2/6 Plotting marginals of used markers');
[fig, fig_size] = plot_marginals_once(used_data, used_markers, unique_labels, label_idx, input_struct.used_cofactor);
plot_stem = fullfile(input_struct.output_dir, sprintf('%s used marginals', input_struct.save_stem));
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size);
if ~isempty(extra_data)
fprintf(', and of extra markers');
% plot used_markers
[fig, fig_size] = plot_marginals_once(extra_data, extra_markers, unique_labels, label_idx, input_struct.extra_cofactor);
plot_stem = fullfile(input_struct.output_dir, sprintf('%s extra marginals', input_struct.save_stem));
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size);
end
fprintf('\n')
end
%% plot_marginals_once:
function [fig, fig_size] = plot_marginals_once(this_data, this_markers, unique_labels, label_idx, cofactor)
% set up plot
fig = figure('visible', 'off');
n_plots = size(this_data, 2);
plot_ratio = 1.5;
n_rows = ceil(sqrt(n_plots / plot_ratio));
n_cols = ceil(n_plots / n_rows);
plot_unit = 4;
fig_size = [plot_unit*n_cols plot_unit*n_rows];
if cofactor == 5
cytof_edges = 0:0.5:8;
else
cytof_edges = [];
end
% do plots
for ii = 1:n_plots
subplot(n_rows, n_cols, ii)
this_col = this_data(:, ii);
hold on
if isempty(cytof_edges)
[~, bin_edges] = histcounts(this_col, 20);
else
bin_edges = cytof_edges;
end
for jj = 1:size(label_idx, 1)
histogram(this_col(label_idx{jj}), bin_edges);
end
hold off
xlim([min(bin_edges), max(bin_edges)])
xlabel('Marker value')
ylabel('# cells')
title(this_markers{ii}, 'interpreter', 'none')
if ii == n_plots
legend(unique_labels{:})
end
end
end
%% plot_mi: plot matrix of MI values, and max / mean MI values by marker
function plot_mi(all_struct, input_struct, options_struct)
% calculate all MI pairs
try
mi_mat = calc_mi_mat(all_struct);
catch lasterr
fprintf('Seems like the MIToolboxMex is not working. Try compiling it?\nMutual information not calculated.\n');
return
end
% order by max
max_mi = max(mi_mat);
mean_mi = mean(mi_mat);
n_used = size(all_struct.used_data, 2);
n_total = size(mi_mat, 1);
used_idx = 1:n_total <= n_used;
[~, order_idx] = sortrows(-[used_idx; max_mi]');
% tidy up marker names
all_markers = {all_struct.used_markers{:}, all_struct.extra_markers{:}};
all_markers = cellfun(@(str) regexprep(str, '^[0-9]{3}[A-Z][a-z]_', ''), all_markers, 'unif', false);
all_markers = cellfun(@(str) regexprep(str, '_', ' '), all_markers, 'unif', false);
% put things in right order
all_markers = all_markers(order_idx);
mi_mat = mi_mat(order_idx, order_idx);
max_mi = max_mi(order_idx);
mean_mi = mean_mi(order_idx);
% plot all MI pairs
plot_mi_mat(mi_mat, all_markers, n_used, n_total, input_struct, options_struct)
% plot max and mean values of MI for each marker
plot_max_mi(mean_mi, max_mi, n_used, n_total, all_markers, input_struct, options_struct)
% print MI outputs into console
print_mi_values(n_used, n_total, max_mi, mean_mi, all_markers)
end
%% calc_mi_mat: calculate matrix of MI values between markers
function [mi_mat] = calc_mi_mat(all_struct)
% calculate MI
all_data = [all_struct.used_data, all_struct.extra_data];
[n_points, n_total] = size(all_data);
n_bins = ceil(n_points^(1/3));
% do discretization
fprintf('3/6 Discretizing data\n')
discrete_type = 'equalwidth';
switch discrete_type
case 'equalwidth'
% find bin edges for each column
xmin = min(all_data, [], 1);
xmax = max(all_data, [], 1);
xrange = xmax - xmin;
edges = arrayfun(@(jj) binpicker(xmin(jj), xmax(jj), n_bins, xrange(jj)/n_bins), 1:n_total, 'unif', false);
% do discretization
data_discrete_cell = arrayfun(@(jj) discretize(all_data(:, jj), edges{jj}), 1:n_total, 'unif', false);
data_discrete = cell2mat(data_discrete_cell);
case 'equalfreq'
% calculate quantiles
quants = arrayfun(@(jj) [-Inf, unique(quantile(all_data(:, jj), n_bins-1)), Inf], 1:n_total, 'unif', false);
% do discretization
data_discrete_cell = arrayfun(@(jj) discretize(all_data(:, jj), quants{jj}), 1:n_total, 'unif', false);
data_discrete = cell2mat(data_discrete_cell);
otherwise
error('invalid discretization type')
end
% calculate MI
fprintf('4/6 Calculating MI\n')
[mesh_ii, mesh_jj] = meshgrid(1:n_total, 1:n_total);
keep_idx = mesh_ii < mesh_jj;
mesh_ii = mesh_ii(keep_idx);
mesh_jj = mesh_jj(keep_idx);
% plot MI
mi_mat_long = arrayfun(@(ii, jj) mi(data_discrete(:, ii), data_discrete(:, jj)), mesh_ii(:), mesh_jj(:));
mi_mat = zeros(n_total);
utri_idx = sub2ind([n_total, n_total], mesh_ii, mesh_jj);
mi_mat(utri_idx) = mi_mat_long;
mi_mat = mi_mat + mi_mat';
end
%% plot_mi_mat:
function plot_mi_mat(mi_mat, all_markers, n_used, n_total, input_struct, options_struct)
% do plotting
fprintf('5/6 Plotting matrix of MI values\n')
fig = figure('visible', 'off');
imagesc(mi_mat)
hold on
ylim_vals = ylim();
n_total = size(mi_mat, 1);
set(gca, 'xtick', 1:n_total);
set(gca, 'ytick', 1:n_total);
% remove annoying bit of markers
set(gca, 'yticklabels', all_markers);
set(gca, 'xticklabels', all_markers);
set(gca, 'XTickLabelRotation', -45)
% if necessary, add line between used and extra markers
if n_used < n_total
line([n_used, n_used] + 0.5, ylim_vals, 'linestyle', '-', 'color', 'k');
line(ylim_vals, [n_used, n_used] + 0.5, 'linestyle', '-', 'color', 'k');
end
xlim(ylim_vals)
ylim(ylim_vals)
hold off
% add colorbar in a nice place (position = [left bottom width height])
plot_pos = get(gca, 'Position');
bar_obj = colorbar('Position', [plot_pos(1)+plot_pos(3)+0.01, plot_pos(2) + plot_pos(4)/4, 0.02, plot_pos(4)/2]);
ylabel(bar_obj, 'MI (bits)')
% plot
plot_stem = fullfile(input_struct.output_dir, sprintf('%s MI matrix', input_struct.save_stem));
fig_size = [n_total*0.2*1.2, n_total*0.2];
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size);
end
%% plot_max_mi: plots max and mean MI values for each marker
function plot_max_mi(mean_mi, max_mi, n_used, n_total, all_markers, input_struct, options_struct)
fprintf('6/6 Plotting max and mean MI values\n')
% set up figure
fig = figure('visible', 'off');
n_rows = 2;
n_cols = 1;
% plot maximum MI observed per marker
subplot(n_rows, n_cols, 1)
plot(1:n_total, mean_mi, '.', 'markersize', 20)
hold on
set(gca, 'xtick', 1:n_total);
set(gca, 'xticklabels', all_markers);
set(gca, 'XTickLabelRotation', -45)
ylim_vals = ylim();
ylim_vals(1) = 0;
% if necessary, add divider between used and extra
if n_used < n_total
line([n_used, n_used] + 0.5, ylim_vals, 'linestyle', '-', 'color', 'k');
end
% label
ylabel('Mean MI (bits)')
ylim(ylim_vals)
hold off
% plot maximum MI observed per marker
subplot(n_rows, n_cols, 2)
plot(1:n_total, max_mi, '.', 'markersize', 20)
hold on
set(gca, 'xtick', 1:n_total);
set(gca, 'xticklabels', all_markers);
set(gca, 'XTickLabelRotation', -45)
ylim_vals = ylim();
ylim_vals(1) = 0;
% if necessary, add divider between used and extra
if n_used < n_total
line([n_used, n_used] + 0.5, ylim_vals, 'linestyle', '-', 'color', 'k');
end
% label
xlabel('Marker (ordered by max value)')
ylabel('Maximum MI (bits)')
ylim(ylim_vals)
hold off
% plot
plot_stem = fullfile(input_struct.output_dir, sprintf('%s max MI', input_struct.save_stem));
fig_size = [6, 6];
plot_fig(fig, plot_stem, options_struct.file_ext, fig_size);
end
%% print_mi_values:
function print_mi_values(n_used, n_total, max_mi, mean_mi, all_markers)
% order MI differently
type_list = [repmat({'used'}, n_used, 1); repmat({'extra'}, n_total - n_used, 1)];
[~, mi_order] = sort(-max_mi);
% print out MI details
fprintf('\nList of markers ordered by maximum pairwise MI observed with other markers:\n\n')
fprintf('Type\tMax MI\tMean MI\tMarker name\n')
for ii = 1:n_total
this_idx = mi_order(ii);
fprintf('%s\t%.2f\t%.2f\t%s\n', type_list{this_idx}, max_mi(this_idx), mean_mi(this_idx), all_markers{this_idx});
end
end
|
github
|
wmacnair/TreeTop-master
|
nmi.m
|
.m
|
TreeTop-master/TreeTop/private/nmi.m
| 961 |
utf_8
|
141d32dc4a49246746638949cb2e05c8
|
%% nmi:
function z = nmi(x, y)
% Compute normalized mutual information I(x,y)/sqrt(H(x)*H(y)) of two discrete variables x and y.
% Input:
% x, y: two integer vector of the same length
% Ouput:
% z: normalized mutual information z=I(x,y)/sqrt(H(x)*H(y))
% Written by Mo Chen ([email protected]).
assert(numel(x) == numel(y));
n = numel(x);
x = reshape(x,1,n);
y = reshape(y,1,n);
l = min(min(x),min(y));
x = x-l+1;
y = y-l+1;
k = max(max(x),max(y));
idx = 1:n;
Mx = sparse(idx,x,1,n,k,n);
My = sparse(idx,y,1,n,k,n);
Pxy = nonzeros(Mx'*My/n); %joint distribution of x and y
Hxy = -dot(Pxy,log2(Pxy));
% hacking, to elimative the 0log0 issue
Px = nonzeros(mean(Mx,1));
Py = nonzeros(mean(My,1));
% entropy of Py and Px
Hx = -dot(Px,log2(Px));
Hy = -dot(Py,log2(Py));
% mutual information
MI = Hx + Hy - Hxy;
% normalized mutual information
z = sqrt((MI/Hx)*(MI/Hy));
z = max(0,z);
end
|
github
|
wmacnair/TreeTop-master
|
remove_zero_ball.m
|
.m
|
TreeTop-master/TreeTop/private/remove_zero_ball.m
| 993 |
utf_8
|
5670cf42c5b637c9e1be2959cf2faa23
|
%% remove_zero_ball: removes 'ball' of observations which are close to zero
function [all_struct] = remove_zero_ball(all_struct, options_struct)
if ~isfield(options_struct, 'zero_ball_flag') || options_struct.zero_ball_flag == false
return
end
% calculate L1 values
used_data = all_struct.used_data;
switch options_struct.metric_name
case {'L1', 'angle'}
dist_vals = sum(abs(used_data), 2);
case 'L2'
dist_vals = sum(used_data.^2, 2);
otherwise
error('haven''t implemented this distance yet...')
end
% apply cutoff
cutoff_val = quantile(dist_vals, 0.01);
keep_idx = dist_vals > cutoff_val;
all_struct.used_data = all_struct.used_data(keep_idx, :);
all_struct.all_labels = all_struct.all_labels(keep_idx);
if ~isempty(all_struct.extra_data)
all_struct.extra_data = all_struct.extra_data(keep_idx, :);
end
if isfield(all_struct, 'cell_assignments_top')
all_struct.cell_assignments_top = all_struct.cell_assignments_top(keep_idx, :);
end
end
|
github
|
wmacnair/TreeTop-master
|
kmedoids_fn.m
|
.m
|
TreeTop-master/TreeTop/private/kmedoids_fn.m
| 1,927 |
utf_8
|
83c71dabdc7d731eb22c816d235b5f06
|
%% kmedoids_fn: calculates kmedoids algorithm with given distance matrix, and weights
% inputs are: D, distance matrix; kk, number of clusters; weights, vector of weights
% uses algorithm from Park and Jun, 2009
function [cluster_labels, medoids_idx, energy] = kmedoids_fn(D, kk, weights)
% check inputs
[weights, nn] = check_inputs(D, weights);
% calculate weighted distance matrix
weighted_D = bsxfun(@times, D, weights);
% pick starting medoids
start_idx = randsample(nn, kk);
% initialize
medoids_idx = start_idx;
[~, cluster_new] = min(D(medoids_idx, :), [], 1);
continue_flag = true;
% loop
while continue_flag
% calculate total weighted distance to these medoids
total_weighted_D = weighted_D' * sparse(1:nn, cluster_new, 1, nn, kk, nn);
% which is best medoid for each of these clusters?
[~, medoids_idx] = min(total_weighted_D,[],1);
% remember old cluster
cluster_old = cluster_new;
% assignment step
[energy, cluster_new] = min(D(medoids_idx, :), [], 1);
% check whether to continue
continue_flag = any(cluster_new ~= cluster_old);
end
% tidy up for outputs
cluster_labels = cluster_new;
end
%% check_inputs:
function [weights, nn] = check_inputs(D, weights)
nn = size(D, 1);
% are dist matrix and weights appropriate sizes?
if nn ~= numel(weights)
error('D and weights must be equal dimensions')
end
% is weights a column vector?
if size(weights, 2) ~= 1
weights = weights';
end
end
%% calc_v_i: v_i used to find which nodes are closest to the centre of the data
% implemented in a non-memory hungry way
function [v_i] = calc_v_i(D, weighted_D);
% sum_D = sum(D, 2);
% prop_D = bsxfun(@rdivide, weighted_D, sum_D);
% v_i = sum(prop_D, 1);
n_nodes = size(D, 1);
v_i = NaN(1, n_nodes);
sum_D = sum(D, 2);
for ii = 1:n_nodes
prop_D_ii = weighted_D(:, ii)./sum_D;
v_i(ii) = sum(prop_D_ii, 1);
end
end
|
github
|
wmacnair/TreeTop-master
|
calc_density.m
|
.m
|
TreeTop-master/TreeTop/private/calc_density.m
| 4,683 |
utf_8
|
2cdba04b91ef6e9de4e371923c0b8ce1
|
%% calc_density: calculates density values
function [density_vector] = calc_density(sample_struct, options_struct)
% do we want to save some of these outputs?
kmedoids_flag = isfield(options_struct, 'kmedoids_flag') && options_struct.kmedoids_flag;
% define how big a reference to do
% and sigma values
% unpack
used_data = sample_struct.used_data;
sigma = options_struct.sigma;
metric_name = options_struct.metric_name;
n_dens_ref = options_struct.n_dens_ref;
n_samples = size(used_data, 1);
n_dens_ref = min(n_dens_ref, n_samples);
% define maximum matrix size
max_mat_entries = 1e6;
% split data into chunks
chunk_cell = calculate_chunks(used_data, n_dens_ref, max_mat_entries);
chunk_idx = cell2mat(chunk_cell);
% sample reference cells for calculating density
sample_idx = randsample(n_samples, n_dens_ref);
dens_ref_mat = used_data(sample_idx, :);
% loop through chunks
n_chunks = numel(chunk_cell);
density_cell = cell(n_chunks, 1);
% CHECK THIS
kk = 100;
if kmedoids_flag
knn_chunk = cell(n_chunks, 1);
end
fprintf('calculating density for all points in sample\n')
if options_struct.pool_flag
% define function for each chunk
parfor ii = 1:n_chunks
% restrict samples to just this chunk
this_idx = find(chunk_idx == ii);
this_mat = used_data(this_idx, :);
% calculate distance matrix
dist_mat = all_distance_fn(this_mat, dens_ref_mat, options_struct.metric_name);
% zero_idx = dist_mat(:) == 0;
% dist_mat(zero_idx) = Inf;
% check whether they overlap with dens sample
overlap_idx = ismember(this_idx, sample_idx);
% if sum(overlap_idx) ~= sum(zero_idx)
% error('overlaps don''t match')
% end
% do gaussian kernel of these for each sigma
gauss_dist = sum(exp( -(dist_mat/sigma).^2 /2 ), 2);
% remove value of one where there's an overlap
gauss_dist = gauss_dist - overlap_idx;
% store
density_cell{ii} = gauss_dist;
if kmedoids_flag
% also do knn density
knn_dens = arrayfun(@(ii) kk_th_val(dist_mat(ii, :), kk), 1:size(dist_mat, 1));
knn_chunk{ii} = knn_dens;
end
end
else
% define function for each chunk
for ii = 1:n_chunks
% restrict samples to just this chunk
this_idx = find(chunk_idx == ii);
this_mat = used_data(this_idx, :);
% calculate distance matrix
dist_mat = all_distance_fn(this_mat, dens_ref_mat, options_struct.metric_name);
% zero_idx = dist_mat(:) == 0;
% dist_mat(zero_idx) = Inf;
% check whether they overlap with dens sample
overlap_idx = ismember(this_idx, sample_idx);
% if sum(overlap_idx) ~= sum(zero_idx)
% error('overlaps don''t match')
% end
% do gaussian kernel of these for each sigma
gauss_dist = sum(exp( -(dist_mat/sigma).^2 /2 ), 2);
% remove value of one where there's an overlap
gauss_dist = gauss_dist - overlap_idx;
% store
density_cell{ii} = gauss_dist;
if kmedoids_flag
% also do knn density
knn_dens = arrayfun(@(ii) kk_th_val(dist_mat(ii, :), kk), 1:size(dist_mat, 1));
knn_chunk{ii} = knn_dens;
end
end
end
% put into vector
density_vector = cell2mat(density_cell);
% save knn density
if kmedoids_flag
% put all knns together
knn_dens = cell2mat(knn_chunk);
% save outputs
save(fullfile(options_struct.outlier_dir, 'dens_values.mat'), 'density_vector', 'knn_dens')
end
% check sizes ok
if size(density_vector, 1) ~= n_samples
error('density_vector doesn''t have same number of entries as used_data')
end
% check no NaNs
if any(isnan(density_vector))
error('NaN in density_vector')
end
end
%% calculate_chunks:
function chunk_cell = calculate_chunks(used_data, n_dens_ref, max_mat_entries)
% how big should chunks be?
n_samples = size(used_data, 1);
n_dens_ref = min(n_dens_ref, n_samples);
chunk_size = floor(max_mat_entries / n_dens_ref);
% want at most M entries in matrix
% n_dens_ref * chunk_size <= M
% so divide into chunks of size at most
n_chunks = ceil(n_samples / chunk_size);
remainder = n_chunks * chunk_size - n_samples;
size_vector = repmat(chunk_size, n_chunks, 1);
size_vector(end) = chunk_size - remainder;
% double check that size_vector has right number
if sum(size_vector) ~= n_samples
error('chunks wrong')
end
% make chunk indices
chunk_cell = arrayfun(@(ii) repmat(ii, size_vector(ii), 1), (1:n_chunks)', 'unif', false);
chunk_idx = cell2mat(chunk_cell);
if numel(chunk_idx) ~= n_samples
error('chunks wrong')
end
end
%% kk_th_val:
function [val] = kk_th_val(row, kk)
sorted_row = sort(row);
val = sorted_row(kk);
end
|
github
|
wmacnair/TreeTop-master
|
pool_check.m
|
.m
|
TreeTop-master/TreeTop/private/pool_check.m
| 632 |
utf_8
|
bd821e843005cd6bbc79a85d6268541d
|
%% pool_check: checks that a pool is running
function [pool_flag] = pool_check(options_struct)
if options_struct.pool_flag == false
pool_flag = false;
fprintf('running without pool\n')
return
end
% is matlab version earlier than 2013b?
version_str = version('-release');
[~, idx] = sort({'2013b', version_str});
old_flag = idx(1) == 2;
if old_flag
error('TreeTop requires MATLAB version 2013b or newer to run')
else
p = gcp('nocreate'); % If no pool, do not create new one.
pool_flag = ~isempty(p);
end
if ~pool_flag
error('TreeTop must be run with a pool (use parpool to initialize)')
end
end
|
github
|
wmacnair/TreeTop-master
|
get_non_branching_distn.m
|
.m
|
TreeTop-master/TreeTop/private/get_non_branching_distn.m
| 1,440 |
utf_8
|
d9c419340abdeebd3f45c844c5be2522
|
%% get_non_branching_distn:
function non_branching_distn = get_non_branching_distn(n_ref_cells, n_points, n_dims)
if n_points <= 1000
fprintf('too few observations for proper non-branching comparison distribution; all scores normalized to 0\n');
non_branching_distn = Inf;
return
end
% load all non-branching distributions
load('treetop non-branching distns.mat', 'lookup_table', 'non_branching_cell')
% find closest distribution
n_ref_cells_list = unique(lookup_table.n_ref_cells);
n_points_list = unique(lookup_table.n_points);
n_dims_list = unique(lookup_table.n_dims);
% find which are closest
ref_cells_idx = max(find(n_ref_cells_list <= n_ref_cells));
if isempty(ref_cells_idx)
ref_cells_idx = 1;
end
n_ref_cells_match = n_ref_cells_list(ref_cells_idx);
points_idx = max(find(n_points_list <= n_points));
if isempty(points_idx)
points_idx = 1;
end
n_points_match = n_points_list(points_idx);
dims_idx = max(find(n_dims_list <= n_dims));
if isempty(dims_idx)
dims_idx = 1;
end
n_dims_match = n_dims_list(dims_idx);
% get this non-branching distribution as outputs
this_idx = find( ...
lookup_table.n_ref_cells == n_ref_cells_match & ...
lookup_table.n_points== n_points_match & ...
lookup_table.n_dims == n_dims_match ...
);
if numel(this_idx) ~= 1
error('non-branching distribution matching went wrong')
end
non_branching_distn = non_branching_cell{this_idx};
end
|
github
|
wmacnair/TreeTop-master
|
mst_expanded.m
|
.m
|
TreeTop-master/TreeTop/private/mst_expanded.m
| 5,640 |
utf_8
|
a223982eef8698514c8b6eae8fb64923
|
function [adj, adj2, cost_value] = mst_expanded(X, working_mode, exclude_adj)
% Minimal or Minimum Spanning Tree based on Euclidian distances
% MST in short: use (X)(n x p) to form (n-1) lines to connect (n) objects in the shortest possible way in the (p)
% dimensional variable-space, under the condition 'no closed loops allowed'.
% working_mode : 'euclidean' (default)
% 'L1'
% 'angle'
% 'corr'
% 'abs_corr'
% out:Xmst (objects-1 x 2) link set between 'objects' indexed as rows in X
% adj adjacency matrix
cost_value = 0;
if ~exist('working_mode')
working_mode = 'euclidean';
end
if isempty(intersect({'euclidean', 'L1', 'corr', 'angle', 'abs_corr'}, working_mode))
working_mode = 'euclidean';
end
if ~isempty(intersect({'corr', 'angle', 'abs_corr'}, working_mode))
X = per_gene_normalization(X); % this makes computing correlation easier
% X = X./norm(X(1, :));
end
if ~exist('exclude_adj') || isempty(exclude_adj)
exclude_adj = sparse(size(X, 1), size(X, 1));
end
[nX, mX] = size(X);
components = []; active_components =[];
adj = sparse(size(X, 1), size(X, 1));
adj2 = sparse(size(X, 1), size(X, 1));
count = 0; % fprintf('constructing a total of %d MST edges ... %6d', size(X, 1)-1, count);
for ii = 1:nX
if isequal(working_mode, 'euclidean')
dist = comp_dist_euclidean(X, ii, 1:nX);
elseif isequal(working_mode, 'L1')
dist = comp_dist_L1(X, ii, 1:nX);
elseif isequal(working_mode, 'corr')
dist = comp_dist_corr(X, ii, 1:nX);
elseif isequal(working_mode, 'angle')
dist = comp_dist_angle(X, ii, 1:nX);
elseif isequal(working_mode, 'abs_corr')
dist = comp_dist_abs_corr(X, ii, 1:nX);
end
dist(ii) = max(dist)+1;
dist = dist + exclude_adj(ii, :).*(max(dist)+1);
dist = full(dist);
[Dmin, Dwin] = min(dist);
Xmst(ii, :) = [ii Dwin];
if adj(ii, Dwin)==0 && adj(Dwin, ii)==0
adj(ii, Dwin)=1;adj(Dwin, ii)=1;
adj2(ii, Dwin)=Dmin;adj2(Dwin, ii)=Dmin;
cost_value = cost_value + Dmin;
count = count + 1;
end
if isempty(components)
components = sparse(zeros(size(X, 1), 1)); components([ii, Dwin], 1) = 1; active_components=1;
else
[existing_comp1] = find(components(ii, :)==1 & active_components==1);
[existing_comp2] = find(components(Dwin, :)==1 & active_components==1);
if isempty(existing_comp1) && isempty(existing_comp2)
components = [components, zeros(size(X, 1), 1)]; components([ii, Dwin], end) = 1; active_components = [active_components, 1];
elseif ~isempty(existing_comp1) && isempty(existing_comp2)
components([ii, Dwin], existing_comp1)=1;
elseif isempty(existing_comp1) && ~isempty(existing_comp2)
components([ii, Dwin], existing_comp2)=1;
elseif ~isempty(existing_comp1) && ~isempty(existing_comp2) && existing_comp1~=existing_comp2
components = [components, components(:, existing_comp1)+components(:, existing_comp2)];
active_components = [active_components, 1];
active_components([existing_comp1, existing_comp2])=0;
end
end
end
while sum(active_components)>1
% sum(active_components)
components_sizes = sum(components); components_sizes(active_components==0) = max(components_sizes+1);
[dummy, existing_comp1] = min(components_sizes);
ind1 = find(components(:, existing_comp1)==1); ind1 = ind1(:)';
ind2 = setdiff(1:size(components, 1), ind1); ind2 = ind2(:)';
if isequal(working_mode, 'euclidean')
dist = comp_dist_euclidean(X, ind1, ind2);
elseif isequal(working_mode, 'L1')
dist = comp_dist_L1(X, ind1, ind2);
elseif isequal(working_mode, 'corr')
dist = comp_dist_corr(X, ind1, ind2);
elseif isequal(working_mode, 'angle')
dist = comp_dist_angle(X, ind1, ind2);
elseif isequal(working_mode, 'abs_corr')
dist = comp_dist_abs_corr(X, ind1, ind2);
end
dist = dist + exclude_adj(ind1, ind2).*(max(max(dist))+1); dist = full(dist);
[Dmin, ind] = min(reshape(dist, length(ind1)*length(ind2), 1));
j = ceil(ind/length(ind1));
ii = ind - (j-1)*length(ind1);
Xmst = [Xmst; [ind1(ii), ind2(j)]];
adj(ind1(ii), ind2(j))=1; adj(ind2(j), ind1(ii))=1;
adj2(ind1(ii), ind2(j))=Dmin; adj2(ind2(j), ind1(ii))=Dmin;
cost_value = cost_value + Dmin;
[existing_comp2] = find(components(ind2(j), :)==1 & active_components==1);
components(:, existing_comp1) = components(:, existing_comp1) + components(:, existing_comp2);
active_components(existing_comp2)=0;
count = count + 1;
end
end
function dist = comp_dist_euclidean(X, ind1, ind2)
% dist = zeros(length(ind1), length(ind2));
for ii = 1:length(ind1)
dist(ii, :) = sqrt(sum((repmat(X(ind1(ii), :), length(ind2), 1) - X(ind2, :)).^2, 2));
end
end
function dist = comp_dist_L1(X, ind1, ind2)
% dist = zeros(length(ind1), length(ind2));
for ii = 1:length(ind1)
dist(ii, :) = sum(abs(repmat( X(ind1(ii), :), length(ind2), 1) - X(ind2, :)), 2);
end
end
function dist = comp_dist_corr(X, ind1, ind2)
% dist = zeros(length(ind1), length(ind2));
corr = X(ind1, :)*X(ind2, :)';
dist = 1-corr;
end
function dist = comp_dist_angle(X, ind1, ind2)
% dist = zeros(length(ind1), length(ind2));
corr = X(ind1, :)*X(ind2, :)';
dist = acos(corr)/pi;
end
function dist = comp_dist_abs_corr(X, ind1, ind2)
% dist = zeros(length(ind1), length(ind2));
corr = X(ind1, :)*X(ind2, :)';
dist = 1-abs(corr);
end
%% per_gene_normalization: my guess at what this function should be
function [X_out] = per_gene_normalization(X_in)
X_norm = arrayfun(@(idx) norm(X_in(idx, :)), (1:size(X_in, 1))');
X_out = bsxfun(@rdivide, X_in, X_norm);
end
|
github
|
wmacnair/TreeTop-master
|
check_treetop_inputs.m
|
.m
|
TreeTop-master/TreeTop/private/check_treetop_inputs.m
| 4,879 |
utf_8
|
89c40b12c90908f15bbf49307f8669cf
|
%% CHECK_TREETOP_INPUTS: Checks that inputs to TreeTop are ok. Adds default values where none given.
% [input_struct, options_struct] = CHECK_TREETOP_INPUTS(input_struct, options_struct) checks both input_struct
% and options_struct, and amends them with default values where necessary.
% [input_struct, ~] = CHECK_TREETOP_INPUTS(input_struct, []) checks only input_struct, returning
% an empty object for options_struct.
% [~, options_struct] = CHECK_TREETOP_INPUTS([], options_struct) checks only options_struct,
% returning an empty object for input_struct.
function [input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct)
if exist('input_struct', 'var')
input_struct = check_input_struct(input_struct);
else
fprintf('no input_struct given as input; returning empty value\n')
input_struct = [];
end
if exist('options_struct', 'var')
options_struct = check_options_struct(options_struct);
else
fprintf('no options_struct given as input; returning empty value\n')
options_struct = [];
end
end
%% check_input_struct:
function [input_struct] = check_input_struct(input_struct)
if isempty(input_struct)
error('input_struct is empty; check that extra_markers is specified as {{}}, not {}')
end
% check all fieldnames
fields_list = fieldnames(input_struct);
input_required = {'data_dir', 'output_dir', 'used_markers'};
missing_fields = setdiff(input_required, fields_list);
if ~isempty(missing_fields)
error(sprintf('the following fields are missing from input_struct: %s', strjoin(missing_fields, ', ')))
end
if ~isfield(input_struct, 'filenames') & ~isfield(input_struct, 'mat_file')
error('input_struct must have one of mat_file or filenames as field names')
end
% % save_stem can't have branch in it
% if ~isempty(regexp(input_struct.save_stem, '^branch'))
% error('save_stem can''t start with "branch"')
% end
% check data_dir
if ~exist(input_struct.data_dir, 'dir')
error('data_dir does not exist\n')
end
% if fcs files specified, check that they exist
% if mat_file specified, check that it exists
if isfield(input_struct, 'mat_file') && ~exist(fullfile(input_struct.data_dir, input_struct.mat_file), 'file')
error('specified mat_file does not exist')
end
% add save_stem from output directory
[parent_dir, name, ext] = fileparts(input_struct.output_dir);
% deal with full stops
if ~isempty(ext)
name = [name, ext];
end
input_struct.save_stem = name;
% check parent_dir
if ~exist(parent_dir, 'dir')
error('parent directory of output_dir does not exist\n')
end
% make output_dir
if ~exist(input_struct.output_dir, 'dir')
mkdir(input_struct.output_dir)
end
% if extra_markers missing, make it empty
if ~isfield(input_struct, 'extra_markers')
input_struct.extra_markers = {};
elseif any(cellfun(@isempty, input_struct.extra_markers))
error('some extra_markers are empty (to have no extra markers, use {}, or leave extra_markers undefined')
end
% if file_annot missing, make it same as filenames
if isfield(input_struct, 'filenames') & ~isfield(input_struct, 'file_annot')
input_struct.file_annot = {input_struct.filenames};
end
% if cofactor missing, make it 5
if ~isfield(input_struct, 'used_cofactor')
input_struct.used_cofactor = 5;
end
if ~isfield(input_struct, 'extra_cofactor')
input_struct.extra_cofactor = 5;
end
end
%% check_options_struct:
function [options_struct] = check_options_struct(options_struct);
% same for options:
fields_list = fieldnames(options_struct);
options_required = {'sigma'};
missing_fields = setdiff(options_required, fields_list);
if ~isempty(missing_fields)
error(sprintf('the following fields are missing from options_struct: %s', strjoin(missing_fields, ', ')))
end
% set defaults if missing
if ~isfield(options_struct, 'metric_name')
options_struct.metric_name = 'L1';
end
if ~isfield(options_struct, 'outlier')
options_struct.outlier = 0.01;
end
if ~isfield(options_struct, 'threshold')
options_struct.threshold = 0.5;
end
if ~isfield(options_struct, 'sample_size')
options_struct.sample_size = 1e5;
end
if ~isfield(options_struct, 'n_ref_cells')
options_struct.n_ref_cells = 200;
end
if ~isfield(options_struct, 'n_dens_ref')
options_struct.n_dens_ref = 5000;
end
if ~isfield(options_struct, 'n_trees')
options_struct.n_trees = 1000;
end
if ~isfield(options_struct, 'file_ext')
options_struct.file_ext = 'png';
end
if ~isfield(options_struct, 'seed')
options_struct.seed = 73;
end
if ~isfield(options_struct, 'layout_tree_idx')
options_struct.layout_tree_idx = 6;
end
if ~isfield(options_struct, 'p_cutoff')
options_struct.p_cutoff = 0.95;
end
if ~isfield(options_struct, 'three_flag')
options_struct.three_flag = false;
end
if ~isfield(options_struct, 'pool_flag')
options_struct.pool_flag = true;
end
end
|
github
|
wmacnair/TreeTop-master
|
get_layout_struct.m
|
.m
|
TreeTop-master/TreeTop/private/get_layout_struct.m
| 3,135 |
utf_8
|
d0483d0d744fd9e573fd5d0d69db737d
|
%% get_layout_struct:
function layout_struct = get_layout_struct(input_struct, options_struct, recursive_flag)
% define default input
if ~exist('recursive_flag', 'var')
recursive_flag = false;
end
% double check inputs
[input_struct, options_struct] = check_treetop_inputs(input_struct, options_struct);
% define save file
layout_file = fullfile(input_struct.output_dir, sprintf('best layout %s.mat', input_struct.save_stem));
% if idx given, pick which type of layout to use, check input is ok, and force computation of layout
if isfield(options_struct, 'layout_tree_idx')
layout_tree_idx = options_struct.layout_tree_idx;
if ~ismember(layout_tree_idx, 1:6)
error('invalid layout_tree_idx')
end
% otherwise use previously calculated layout if it exists
else
layout_tree_idx = 6;
% check if exists
if exist(layout_file, 'file')
% if exists, check the date
tree_vars_file = fullfile(input_struct.output_dir, 'tree_variables.mat');
tree_vars_info = dir(tree_vars_file);
layout_info = dir(layout_file);
if tree_vars_info.datenum < layout_info.datenum | recursive_flag
load(layout_file, 'layout_struct');
return
end
end
end
% get graphs
graph_struct = get_graph_struct(input_struct);
% get details
layout_graph_name = graph_struct(layout_tree_idx).name;
layout_graph = graph_struct(layout_tree_idx).inv_adj_matrix;
% run thing
fprintf('doing layout for %s\n', layout_graph_name);
if isfield(options_struct, 'layout_seed')
layout_seed = options_struct.layout_seed;
else
layout_seed = 1;
end
layout_xy = get_best_layout(layout_graph, layout_seed, options_struct);
layout_struct = struct( ...
'layout_xy', {layout_xy}, ...
'layout_graph', {layout_graph} ...
);
save(layout_file, 'layout_struct');
end
%% get_best_layout:
function [layout_xy] = get_best_layout(this_dist_tree, layout_seed, options_struct)
% do multiple HK layouts
n_layouts = 16;
layout_cell = cell(n_layouts, 1);
energy = zeros(n_layouts, 1);
energy_hk = zeros(n_layouts, 1);
if options_struct.pool_flag
% set up reproducible rng
spmd
cmrg = RandStream('mrg32k3a', 'seed', layout_seed);
RandStream.setGlobalStream(cmrg);
end
parfor ii = 1:n_layouts
% set up random stream
s = RandStream.getGlobalStream();
s.Substream = ii;
% do layout
[this_layout, this_energy, this_energy_hk] = harel_koren_layout_faster(this_dist_tree);
layout_cell{ii} = this_layout;
energy(ii) = this_energy;
energy_hk(ii) = this_energy_hk;
end
else
for ii = 1:n_layouts
% set up random stream
rng(ii);
% do layout
[this_layout, this_energy, this_energy_hk] = harel_koren_layout_faster(this_dist_tree);
layout_cell{ii} = this_layout;
energy(ii) = this_energy;
energy_hk(ii) = this_energy_hk;
end
end
% take best
[~, best_idx] = min(energy);
layout_xy = layout_cell{best_idx};
% scale layout nicely
min_xy = min(layout_xy, [], 1);
max_xy = max(layout_xy, [], 1);
layout_xy = bsxfun(@rdivide, bsxfun(@minus, layout_xy, min_xy), max_xy - min_xy)*0.8 + 0.1;
end
|
github
|
wmacnair/TreeTop-master
|
set_up_figure_size.m
|
.m
|
TreeTop-master/TreeTop/private/set_up_figure_size.m
| 358 |
utf_8
|
8d4a148f9e69dac457392036608109be
|
%% set_up_figure_size: helper function to make figure ok for printing to pdf
function [] = set_up_figure_size(fig, units, fig_size)
set(fig, 'units', units);
set(fig, 'paperunits', units);
set(fig, 'paperposition', [0, 0, fig_size]);
set(fig, 'papersize', fig_size);
set(fig, 'position', [0, 0, fig_size]);
set(fig, 'paperpositionmode', 'manual');
end
|
github
|
wmacnair/TreeTop-master
|
kmeans_plus_plus.m
|
.m
|
TreeTop-master/TreeTop/private/kmeans_plus_plus.m
| 17,733 |
utf_8
|
eee2fee42f73274bef501dd1dfb7ad4f
|
% kmeans_plus_plus.m
% See Scalable K-Means++, Bahmani et al., 2012
% Initializes first cluster selection for k-means, using squared distances from other points to ensure points are well spaced
% Approximate but distributed method.
% X rows = observations, columns = fields
% kk number of clusters
% ll oversampling factor (default is to equal k)
% rr number of rounds to run
function [cluster_labels, centroid_idx] = kmeans_plus_plus(X, kk, ll, rr, options, paramset)
% check inputs ok
parameters = check_inputs(X, kk, ll, rr, options);
% partition X as evenly as possible amongst cores
partition_idx = calc_partition_idx(parameters);
X_split = mat2cell(X, partition_idx, parameters.n_var);
continue_flag = true;
while continue_flag
% do clustering, but check that right number of entries is coming out
[cluster_labels, centroid_idx] = do_clustering(parameters, X, X_split, partition_idx, paramset);
% check that we have right number, if not, repeat
n_unique_centroids = numel(unique(centroid_idx));
if n_unique_centroids == kk
continue_flag = false;
else
fprintf('didn''t find kk points; repeating seeding\n')
end
end
end
%% check_inputs:
function [parameters] = check_inputs(X, kk, ll, rr, options)
% verbosity flag
if ~isfield(options, 'verbose')
verbose = false;
else
verbose = options.verbose;
end
% check what distance measure to use
if ~isfield(options, 'metric')
metric = 'L1';
else
metric = options.metric;
end
% check whether we should use parfor or for
if ~isfield(options, 'pool_flag')
% default to no
pool_flag = false;
else
pool_flag = options.pool_flag;
end
% set default number of cores
n_cores = 1;
% if we're running with a pool, check that the pool actually exists
if pool_flag
matlab_version = version;
switch matlab_version
case '8.1.0.604 (R2013a)'
pool_size = matlabpool('size');
if pool_size == 0
warning('No pool; run done without parallelisation.')
pool_flag = false;
else
n_cores = pool_size;
end
otherwise
current_pool = gcp('nocreate'); % If no pool, do not create new one.
% n_cores = matlabpool('size');
if isempty(current_pool)
warning('no pool present; running in serial')
pool_flag = false;
else
% if pool does exist, use this as number of cores
n_cores = current_pool.NumWorkers;
end
end
end
% check whether we have enough observations
if size(X, 1) < kk
error('Fewer observations than clusters');
end
%
% ensure that we get enough values in each iteration
if ll * rr < kk
rr = max(ceil(kk / ll), 5);
warning(['Insufficient rounds, value of ', int2str(rr), ' used instead (= ceiling(k/l) )']);
end
% set up variables
[n_obs, n_var] = size(X);
parameters = struct();
parameters.kk = kk;
parameters.rr = rr;
parameters.ll = ll;
parameters.n_cores = n_cores;
parameters.n_obs = n_obs;
parameters.n_var = n_var;
parameters.metric = metric;
parameters.pool_flag = pool_flag;
parameters.verbose = verbose;
end
%% partition_idx:
function [partition_idx] = calc_partition_idx(parameters)
% define useful variables
n_obs = parameters.n_obs;
n_cores = parameters.n_cores;
% calculate requirements for partition
n_per_partition = floor(n_obs / n_cores);
n_remainder = mod(n_obs, n_cores);
% make partition
partition_idx = ones(n_cores,1) * n_per_partition;
partition_idx(1:n_remainder) = partition_idx(1:n_remainder) + 1;
end
%% do_clustering: have this separate so can repeat if necessary
function [cluster_labels, centroids_idx] = do_clustering(parameters, X, X_split, partition_idx, paramset)
% unpack
kk = parameters.kk;
rr = parameters.rr;
% pick first point uniformly at random
raw_centroids_idx = randsample(parameters.n_obs, 1);
% use this to define centroid_X
centroid_X = X(raw_centroids_idx, :);
% keep adding new points until we have done at least rr rounds, and we have at least k points
% check that # centroid_X is at least k
fprintf('k-means++ to identify reference nodes');
continue_flag = true;
ii = 1;
while continue_flag
if ii <= rr
fprintf('\nextra round to ensure sufficient nodes');
end
% calculate induced probability distribution (in distributed way)
phi = par_calc_distn(X_split, centroid_X, parameters);
% pick next points to be included and update raw_centroids_idx
[raw_centroids_idx, centroid_X] = next_points(X, raw_centroids_idx, phi);
% loop admin
ii = ii + 1;
n_centroids = numel(raw_centroids_idx);
% want to carry on until we have reached the right number of rounds, and have sufficient centroid_X
continue_flag = ii <= rr | n_centroids < kk;
end
fprintf('\n');
% recluster points into k clusters
centroids_idx = cluster_into_k(X, X_split, raw_centroids_idx, parameters, paramset);
% pick centroid closest to cluster_centroids
cluster_labels = get_cluster_labels(X, X_split, centroids_idx, parameters);
end
%% par_calc_distn: calculates distribution in distributed way
function [phi] = par_calc_distn(X_split, centroid_X, parameters)
% define useful variable
n_cores = parameters.n_cores;
% define storage variable
phi_split = cell(n_cores, 1);
% calculate distribution for each individual section
if parameters.pool_flag
parfor ii = 1:n_cores
phi_split{ii} = calc_distn(X_split{ii}, centroid_X, parameters);
end
else
for ii = 1:n_cores
phi_split{ii} = calc_distn(X_split{ii}, centroid_X, parameters);
end
end
% combine split phis back into one, and add upscaling factor
phi = cell2mat(phi_split);
phi = parameters.ll * phi / sum(phi);
end
%% calc_distn:
function [phi_split] = calc_distn(X, centroid_X, parameters)
if parameters.verbose
show_var_size(size(X,1), 1);
end
switch parameters.metric
case 'L1'
% calculate distances between points in X and points in the set of centroid_X ()
phi_split = comp_phi_L1(X, centroid_X);
case 'L2'
% calculate distances between points in X and points in the set of centroid_X ()
phi_split = comp_phi_euclidean(X, centroid_X);
case 'angle'
% calculate distances between points in X and points in the set of centroid_X ()
phi_split = comp_phi_angle(X, centroid_X);
case 'corr'
% calculate distances between points in X and points in the set of centroid_X ()
phi_split = comp_phi_corr(X, centroid_X);
case 'abs_corr'
% calculate distances between points in X and points in the set of centroid_X ()
phi_split = comp_phi_abs_corr(X, centroid_X);
otherwise
error('metric not recognised')
end
end
%% next_points: selects next points in non-distributed way
function [C, centroid_X] = next_points(X, C, phi)
% do random sample of uniform variable
rand_sample = rand(numel(phi), 1);
% compare to distribution to decide which were selected
cluster_idx = find(rand_sample < phi);
% add new cluster points
C = union(C, cluster_idx);
centroid_X = X(C, :);
end
%% cluster_into_k:
function [centroids_idx] = cluster_into_k(X, X_split, raw_centroids_idx, parameters, paramset)
fprintf('choosing k centroids from initial points\n')
% not_done_yet = true;
% while not_done_yet
% unpack
kk = parameters.kk;
% where are the centroids?
centroid_X = X(raw_centroids_idx, :);
% calculate weights for each centroids
% centroid_weights = par_calc_centroid_weights(X_split, centroid_X, parameters);
centroid_weights = ones(size(raw_centroids_idx));
if parameters.verbose
show_var_size(size(centroid_X,1),size(centroid_X,1));
end
% remove some unnecessary variables to improve memory
clear X X_split
% calc appropriate distance matrix
switch parameters.metric
case 'L1'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_L1(centroid_X, centroid_X);
case 'L2'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_euclidean(centroid_X, centroid_X);
case 'angle'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_angle(centroid_X, centroid_X);
case 'corr'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_corr(centroid_X, centroid_X);
case 'abs_corr'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_abs_corr(centroid_X, centroid_X);
otherwise
error('metric not recognised')
end
% remove some unnecessary variables to improve memory
clear centroid_X
% calculate weighted cluster
[~, centroids_idx_idx] = kmedoids_fn(D, kk, centroid_weights);
% which of the original centroids does this correspond to?
centroids_idx = raw_centroids_idx(centroids_idx_idx);
% have we got the right number of clusters?
if numel(centroids_idx) ~= kk
error('got wrong number of clusters')
end
end
%% par_calc_centroid_weights: calculates how many cells each centroid represents, in a distributed way
function [centroid_weights] = par_calc_centroid_weights(X_split, centroid_X, parameters)
% define useful variable
n_cores = parameters.n_cores;
% define storage variable
centroid_weights_split = cell(n_cores, 1);
% choose parallel or not
if parameters.pool_flag
% find how many points in X are closest to each centroid
parfor ii = 1:n_cores
centroid_weights_split{ii} = calc_centroid_weights(X_split{ii}, centroid_X, parameters);
end
else
% find how many points in X are closest to each centroid
for ii = 1:n_cores
centroid_weights_split{ii} = calc_centroid_weights(X_split{ii}, centroid_X, parameters);
end
end
% take total across difference sections of X
centroid_weights = sum(cell2mat(centroid_weights_split), 1)';
end
%% calc_centroid_weights: calculates how many cells each centroid represents
function [centroid_weights] = calc_centroid_weights(X, centroid_X, parameters)
% calc appropriate distance matrix
switch parameters.metric
case 'L1'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_L1(X, centroid_X);
case 'L2'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_euclidean(X, centroid_X);
case 'angle'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_angle(X, centroid_X);
case 'corr'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_corr(X, centroid_X);
case 'abs_corr'
% calculate distances between points in X and points in the set of centroids ()
D = comp_dist_abs_corr(X, centroid_X);
otherwise
error('metric not recognised')
end
% find minimal distances
[min_dist, min_idx] = min(D, [], 2);
% find where these minimal distances occur
% min_boolean = bsxfun(@eq, sq_dist, min_dist);
nn = size(X, 1);
kk = size(centroid_X, 1);
min_boolean = sparse(1:nn, min_idx, 1, nn, kk);
% get total for each centroid
centroid_weights = full(sum(min_boolean, 1));
end
%% get_cluster_labels:
function [cluster_labels] = get_cluster_labels(X, X_split, centroids_idx, parameters)
% fprintf('labelling each cell with closest reference node\n')
% define useful variable
n_cores = parameters.n_cores;
% define storage variable
cluster_labels_split = cell(n_cores, 1);
centroid_X = X(centroids_idx, :);
% choose parallel or not
if parameters.pool_flag
% find how many points in X are closest to each centroid
parfor ii = 1:n_cores
cluster_labels_split{ii} = get_cluster_labels_one(X_split{ii}, centroid_X, parameters);
end
else
% find how many points in X are closest to each centroid
for ii = 1:n_cores
cluster_labels_split{ii} = get_cluster_labels_one(X_split{ii}, centroid_X, parameters);
end
end
cluster_labels = cell2mat(cluster_labels_split);
end
%% get_cluster_labels_one:
function [cluster_labels] = get_cluster_labels_one(X, centroid_X, parameters)
if parameters.verbose
show_var_size(size(X,1), 1);
end
% calc appropriate distance matrix
switch parameters.metric
case 'L1'
% calculate distances between points in X and points in the set of centroids ()
[~, cluster_labels] = comp_phi_L1(X, centroid_X);
case 'L2'
% calculate distances between points in X and points in the set of centroids ()
[~, cluster_labels] = comp_phi_euclidean(X, centroid_X);
case 'angle'
% calculate distances between points in X and points in the set of centroids ()
[~, cluster_labels] = comp_phi_angle(X, centroid_X);
case 'corr'
% calculate distances between points in X and points in the set of centroids ()
[~, cluster_labels] = comp_phi_corr(X, centroid_X);
case 'abs_corr'
% calculate distances between points in X and points in the set of centroids ()
[~, cluster_labels] = comp_phi_abs_corr(X, centroid_X);
otherwise
error('metric not recognised')
end
% % find which centroid is closest to each cluster_centroid
% [~, cluster_labels] = min(D, [], 2);
end
%% comp_dist_euclidean:
function [phi_split, idx_split] = comp_phi_euclidean(X, centroid_X)
% X has size m*d, centroid_X n*d
m = size(X, 1);
n = size(centroid_X, 1);
phi_split = zeros(m, 1);
idx_split = zeros(m, 1, 'int32');
for ii = 1:m
% calculate squared distance to all centroids
temp_dist_sq = sum((repmat(X(ii,:),n,1) - centroid_X).^2,2);
% find minimum squared distance, return as distribution
[phi_split(ii), idx_split(ii)] = min(temp_dist_sq);
end
end
%% comp_phi_L1:
function [phi_split, idx_split] = comp_phi_L1(X, centroid_X)
% set up
m = size(X, 1);
n = size(centroid_X, 1);
phi_split = zeros(m, 1);
idx_split = zeros(m, 1, 'int32');
for ii = 1:m
% calculate squared distance to all centroids
temp_dist_sq = sum(abs(repmat(X(ii,:), n, 1) - centroid_X),2).^2;
% find minimum squared distance, return as distribution
[phi_split(ii), idx_split(ii)] = min(temp_dist_sq);
end
end
%% comp_phi_corr:
function [phi_split, idx_split] = comp_phi_corr(X, centroid_X)
error('corr distance not implemented yet')
corr = calc_corr(X,centroid_X);
dist = 1-corr;
% squared_distances_from_centroids = pdist_faster(X, centroid_X);
sq_dist_to_centroids = dist_to_centroids.^2;
% find minimum squared distance, return as distribution
phi_split = min(sq_dist_to_centroids, [], 2);
end
%% comp_phi_angle:
function [phi_split, idx_split] = comp_phi_angle(X, centroid_X)
% L2-normalization
X = bsxfun(@times, X, 1./sqrt(sum(X.^2, 2)));
centroid_X = bsxfun(@times, centroid_X, 1./sqrt(sum(centroid_X.^2, 2)));
% set up
m = size(X, 1);
n = size(centroid_X, 1);
phi_split = zeros(m, 1);
idx_split = zeros(m, 1, 'int32');
for ii = 1:m
dot_prod = X(ii, :) * centroid_X';
temp_dist_sq = (acos(dot_prod)/pi).^2;
% close to zero we sometimes get complex values
temp_dist_sq = real(temp_dist_sq);
% find minimum squared distance, return as distribution
[phi_split(ii), idx_split(ii)] = min(temp_dist_sq);
end
end
%% comp_phi_abs_corr:
function [phi_split, idx_split] = comp_phi_abs_corr(X, centroid_X)
error('abs_corr distance not implemented yet')
corr = calc_corr(X,centroid_X);
dist = 1-abs(corr);
% squared_distances_from_centroids = pdist_faster(X, centroid_X);
sq_dist_to_centroids = dist_to_centroids.^2;
% find minimum squared distance, return as distribution
phi_split = min(sq_dist_to_centroids, [], 2);
end
%% comp_dist_euclidean:
function dist = comp_dist_euclidean(X, centroid_X)
% X has size m*d, centroid_X n*d
m = size(X, 1);
n = size(centroid_X, 1);
dist = zeros(m,n);
for ii = 1:m
dist(ii,:) = sqrt(sum((repmat(X(ii,:),n,1) - centroid_X).^2,2));
end
end
%% comp_dist_L1:
function dist = comp_dist_L1(X, centroid_X)
% set up
m = size(X, 1);
n = size(centroid_X, 1);
dist = zeros(m, n);
for ii = 1:m
dist(ii,:) = sum(abs(repmat(X(ii,:), n, 1) - centroid_X),2);
end
end
%% comp_dist_corr:
function dist = comp_dist_corr(X, centroid_X)
corr = calc_corr(X,centroid_X);
dist = 1-corr;
end
%% comp_dist_angle:
function dist = comp_dist_angle(X, centroid_X)
% L2-normalization
X = bsxfun(@times, X, 1./sqrt(sum(X.^2, 2)));
centroid_X = bsxfun(@times, centroid_X, 1./sqrt(sum(centroid_X.^2, 2)));
% dot_prod = X*centroid_X';
% dist = acos(dot_prod)/pi;
% set up
m = size(X, 1);
n = size(centroid_X, 1);
dist = zeros(m, n);
for ii = 1:m
dot_prod = X(ii, :) * centroid_X';
dist(ii, :) = real(acos(dot_prod)/pi);
end
end
%% comp_dist_abs_corr:
function dist = comp_dist_abs_corr(X, centroid_X)
corr = calc_corr(X,centroid_X);
dist = 1-abs(corr);
end
%% calc_corr:
function [corr] = calc_corr(X, centroid_X)
% corr = zeros(m,n);
% for ii = 1:m
% corr(ii,:) = X(ii,:) * centroid_X';
% end
% corr = X*centroid_X';
% X = X';
% centroid_X = centroid_X';
% zero-mean
An = bsxfun(@minus, X, mean(X, 1));
Bn = bsxfun(@minus, centroid_X, mean(centroid_X, 1));
% L2-normalization
An = bsxfun(@times, An, 1./sqrt(sum(An.^2, 1)));
Bn = bsxfun(@times, Bn, 1./sqrt(sum(Bn.^2, 1)));
% correlation
corr = sum(An*Bn', 1);
end
%% pdist_faster: faster implementation of distance measure
function [squared_distances] = pdist_faster(X,Y)
squared_distances = bsxfun(@plus,dot(X',X',1)',dot(Y',Y',1))-2*(X*Y');
end
%% show_var_size: display size of variables
function [] = show_var_size(m, n)
% X has size m*d, centroid_X n*d
size_test = zeros(m, n);
size_whos = whos('size_test');
clear('size_test')
fprintf('\ndistn matrix is %d by %d, size is %.2f MB\n', m, n, size_whos.bytes / 2^20);
end
|
github
|
wmacnair/TreeTop-master
|
get_graph_struct.m
|
.m
|
TreeTop-master/TreeTop/private/get_graph_struct.m
| 9,355 |
utf_8
|
d23289c93133ab594cdb057e3decda77
|
%% get_graph_struct:
function [graph_struct] = get_graph_struct(input_struct)
fprintf('loading summaries of ensemble of trees\n')
% open needed graphs
[inv_freq_graph, dist_graph] = get_tree_files(input_struct);
% calculate maximally sparse connected graphs for each of these
[sparse_inv_freq_graph, sparse_dist_graph] = calc_sparse_graphs(inv_freq_graph, dist_graph);
% calculate graphs which are 10% sparser than full graphs
[q10_inv_freq_graph, q10_dist_graph] = calc_10_percent_graphs(inv_freq_graph, dist_graph);
% put all six into graph structure, with names
graph_struct = struct( ...
'inv_adj_matrix', {dist_graph, q10_dist_graph, sparse_dist_graph, inv_freq_graph, q10_inv_freq_graph, sparse_inv_freq_graph}, ...
'name', {'Distance graph', 'Semi-sparse distance graph', 'Maximally sparse distance graph', 'Freq graph', 'Semi-sparse freq graph', 'Maximally sparse freq graph'}, ...
'file_suffix', {'_full_dist_layout', '_semi_dist_layout', '_sparse_dist_layout', '_full_freq_layout', '_semi_freq_layout', '_sparse_freq_layout'} ...
);
% apply inversion to all graphs, then add outputs back into the structure
adj_matrix = cellfun(@invert_sparse_graph, {graph_struct.inv_adj_matrix}, 'Unif', false);
[graph_struct(:).adj_matrix] = adj_matrix{:};
% apply booleanisation to all graphs, then add outputs back into the structure
boolean_adj_matrix = cellfun(@booleanise_sparse_graph, {graph_struct.inv_adj_matrix}, 'Unif', false);
[graph_struct(:).boolean_adj_matrix] = boolean_adj_matrix{:};
end
%% get_tree_files:
function [inv_freq_graph, union_graph] = get_tree_files(input_struct)
% unpack
output_dir = input_struct.output_dir;
save_stem = input_struct.save_stem;
% open tree based on frequency of edges
inv_freq_graph_file = fullfile(output_dir, sprintf('%s_freq_union_tree.mat', save_stem));
inv_freq_graph = sparse(importdata(inv_freq_graph_file));
% open tree based on mean treeSNE distances
union_graph_file = fullfile(output_dir, sprintf('%s_union_tree.mat', save_stem));
union_graph = sparse(importdata(union_graph_file));
end
%% calc_10_percent_graphs: calculates graphs with bottom 10% frequency edges removed
function [q10_inv_freq_graph, q10_union_graph] = calc_10_percent_graphs(inv_freq_graph, union_graph)
% get info from inverse frequency graph
[ii jj ss] = find(inv_freq_graph);
[mm nn] = size(inv_freq_graph);
% extract quantiles of frequencies
[cdf_quantiles cdf_inv_freqs] = ecdf(ss);
% find which corresponds best to 10% (errs on less sparse side)
this_quantile = 0.9;
ecdf_quantile_idx = max( find(this_quantile > cdf_quantiles) );
% specify quantile and inverse frequency corresponding to 10% less
ecdf_quantile = cdf_quantiles(ecdf_quantile_idx);
cdf_inv_freq = cdf_inv_freqs(ecdf_quantile_idx);
% mess about to turn this into a new graph
keep_idx = ss <= cdf_inv_freq;
sparse_graph = sparse(ii(keep_idx), jj(keep_idx), ss(keep_idx), mm, nn);
% how many components in this test graph?
no_components = max(components(sparse_graph));
% count how many components, only true if there is only one components
is_connected = no_components == 1;
if ~is_connected
q10_inv_freq_graph = [];
q10_union_graph = [];
else
% disp(['10 percent graph corresponds to cutoff of ' num2str(cdf_inv_freq) ' and exclusion of ' num2str(round((1-ecdf_quantile)*100)) '% of the edges']);
[union_ii union_jj union_ss] = find(union_graph);
% check that graphs are same as above
if ~and(isequal(ii, union_ii), isequal(jj, union_jj))
error('union graph and inv freq graph don''t have matching non-zero locations')
end
% put sparse union graph together
sparse_union_graph = sparse(union_ii(keep_idx), union_jj(keep_idx), union_ss(keep_idx), mm, nn);
% make outputs
q10_inv_freq_graph = sparse_graph;
q10_union_graph = sparse_union_graph;
end
end
%% calc_sparse_graphs: calculates maximally sparse graphs from the inputs, by removing edges with low
% frequency until it is not possible to exclude more without disconnecting the graph
function [sparse_inv_freq_graph, sparse_union_graph] = calc_sparse_graphs(inv_freq_graph, union_graph)
% test cases:
% - graph is unconnected:
% nn = 100; A = magic(nn); A = A + A'; A(:,1) = 0; A(1,:) = 0; A(1:nn+1:nn*nn) = 0;
% inv_freq_graph = sparse(A);
% - graph is connected even at maximal freq requirement
% nn = 100; A = magic(nn); A = A + A'; A(:,1) = 1; A(1,:) = 1; A(1:nn+1:nn*nn) = 0;
% inv_freq_graph = sparse(A);
% get list of inverse frequencies
inv_freq_list = full(unique(inv_freq_graph));
% set initial unconnected_freq and connected_freq
unconnected_freq_idx = 1; connected_freq_idx = numel(inv_freq_list) + 1;
% have we found the cutoff yet?
while connected_freq_idx - unconnected_freq_idx > 1
% set test_freq
test_freq_idx = get_test_idx(unconnected_freq_idx, connected_freq_idx);
% test for connectedness
% is_connected = test_connectedness(inv_freq_graph, inv_freq_list, test_freq_idx);
is_connected = test_proposed_idx(inv_freq_graph, inv_freq_list, test_freq_idx);
% update connected / unconnected frequencies
if is_connected
connected_freq_idx = test_freq_idx;
else
unconnected_freq_idx = test_freq_idx;
end
end
% use identified connected_freq_idx to define output graphs
if connected_freq_idx > numel(inv_freq_list)
error('Graph not connected');
else
freq_boolean = inv_freq_graph <= inv_freq_list(connected_freq_idx);
sparse_inv_freq_graph = inv_freq_graph .* freq_boolean;
sparse_union_graph = union_graph .* freq_boolean;
end
end
%% invert_sparse_graph: takes sparse graph as input, returns sparse graph with inverted values for non-zero entries
function [inverted_graph] = invert_sparse_graph(input_graph)
if ~issparse(input_graph)
error('input_graph must be sparse')
end
% get original graph entries
[ii jj ss] = find(input_graph);
[mm nn] = size(input_graph);
% invert nonzeros
inverted_ss = 1./ss;
% make new graph
inverted_graph = sparse(ii, jj, inverted_ss, mm, nn);
end
%% booleanise_sparse_graph: takes sparse graph as input, returns sparse graph with inverted values for non-zero entries
function [boolean_graph] = booleanise_sparse_graph(input_graph)
if ~issparse(input_graph)
error('input_graph must be sparse')
end
% get original graph entries
[ii jj ss] = find(input_graph);
[mm nn] = size(input_graph);
% invert nonzeros
boolean_ss = repmat(1, size(ss));
% make new graph
boolean_graph = sparse(ii, jj, boolean_ss, mm, nn);
end
%% get_test_freq_idx: finds midpoint between two input indices
function [test_idx] = get_test_idx(unconnected_idx, connected_idx)
test_idx = floor((connected_idx - unconnected_idx)/2) + unconnected_idx;
end
%% test_connectedness: checks whether a graph is connected for a given test frequency
function [is_connected] = test_connectedness(inv_freq_graph, inv_freq_list, test_freq_idx)
% define graph to test by setting to zero values with too high inverse freqencies
[ii jj ss] = find(inv_freq_graph);
[mm nn] = size(inv_freq_graph);
sparse_ss = ss <= inv_freq_list(test_freq_idx);
test_graph = sparse(ii, jj, sparse_ss, mm, nn);
% how many components in this test graph?
no_components = max(components(test_graph));
% count how many components, only true if there is only one components
is_connected = no_components == 1;
end
%% test_proposed_idx: checks whether a graph is connected for a given test frequency
function [is_connected] = test_proposed_idx(input_graph, edge_value_list, test_edge_value_idx, varargin)
% define which direction to test in
if nargin == 3
test_le = true;
elseif nargin == 4
test_le = varargin{1};
else
error('arg')
end
% define graph to test by setting to zero values with too high inverse freqencies
[ii jj ss] = find(input_graph);
[mm nn] = size(input_graph);
if test_le
sparse_ss = ss <= edge_value_list(test_edge_value_idx);
else
sparse_ss = ss >= edge_value_list(test_edge_value_idx);
end
test_graph = sparse(ii, jj, sparse_ss, mm, nn);
% check whether this graph is connected
is_connected = test_connected(test_graph);
end
%% test_connected:
function [is_connected] = test_connected(test_graph)
% how many components in this test graph?
no_components = max(components(test_graph));
% count how many components, only true if there is only one components
is_connected = no_components == 1;
end
% %% report_sparsity:
% function [] = report_sparsity(graph_struct)
% % get graphs
% graphs_cell = {graph_struct.inv_adj_matrix};
% names_cell = {graph_struct.name};
% % calculate sparsity
% non_zeros = cellfun(@nnz, graphs_cell);
% total_size = cellfun(@numel, graphs_cell);
% sparsity = non_zeros ./ total_size;
% % display
% max_name_length = max(cellfun(@length, names_cell));
% name_col_length = max_name_length + 5;
% fprintf('sparsity of outputs:\n');
% spacer = horzcat(repmat(' ', 1, max_name_length - length('graph')));
% fprintf('graph%snnz\tsize\tsparsity\n', spacer);
% for ii = 1:numel(graph_struct)
% this_name = names_cell{ii};
% name_length = length(this_name);
% spacer = horzcat(repmat(' ', 1, max_name_length - name_length));
% fprintf('%s%s%d\t%d\t%.2f%%\n', this_name, spacer, non_zeros(ii), total_size(ii), sparsity(ii)*100);
% end
% end
|
github
|
wmacnair/TreeTop-master
|
partition_cells.m
|
.m
|
TreeTop-master/TreeTop/private/partition_cells.m
| 4,780 |
utf_8
|
436bd8e1e5ccf64c107d06aea4ff5e15
|
%% partition_cells: given a list of points to be downsampled and a list of ouliers, identifies
% centroids via k-means ++ seeding amongst those that have been downsampled (downsample_idx includes outlier_idx)
function [centroids_idx, cell_assignments] = partition_cells(sample_struct, outlier_idx, downsample_idx, options_struct)
fprintf('selecting reference nodes\n')
% unpack
used_data = sample_struct.used_data;
n_cells = size(used_data, 1);
% make list of nodes to keep, select these
keep_idx = setdiff(1:n_cells, downsample_idx);
selected_data = used_data(keep_idx, :);
n_selected = size(selected_data, 1);
% find some start points
kk = options_struct.n_ref_cells;
seed_options = struct('metric', options_struct.metric_name, 'pool_flag', options_struct.pool_flag, 'verbose', false);
[~, cents_idx_idx] = kmeans_plus_plus(selected_data, kk, kk, 3, seed_options, options_struct);
cents_idx_idx = sort(cents_idx_idx);
% turn this into indices for whole set rather than just downsampled cells
centroids_idx = keep_idx(cents_idx_idx);
% which points are not centroids?
not_outliers = setdiff(1:n_cells, outlier_idx);
not_centroids = setdiff(not_outliers, centroids_idx);
% check that this makes sense
partition_check = isequal(sort([outlier_idx(:); not_centroids(:); centroids_idx(:)])', 1:n_cells);
if ~partition_check
error('something went wrong in calculation of reference nodes')
end
% assign clusters to each
X = used_data(centroids_idx, :);
Y = used_data(not_centroids, :);
% get distance matrix: # centroids * # datapoints
fprintf('calculating distance from all cells to reference nodes\n')
if options_struct.pool_flag
D = all_distance_fn_par(X, Y, options_struct.metric_name);
else
D = all_distance_fn(X, Y, options_struct.metric_name);
end
fprintf('labelling each cell with closest reference node\n')
cell_assignments = calc_cell_assignments(options_struct, D, centroids_idx, not_centroids, outlier_idx);
end
%% plot_centroid_marker_distns:
function [] = plot_centroid_marker_distns(centroids_idx, sample_struct, paramset)
% define parameters
n_col = 4;
edge_vector = -2:1:9;
% unpack
used_data = sample_struct.used_data;
used_markers = sample_struct.used_markers;
n_markers = size(used_data, 2);
n_row = ceil(n_markers / n_col);
% restrict to just these values
centroid_data = used_data(centroids_idx, :);
% plot histogram of each
figure('name', 'Centroid univariate distributions')
for ii = 1:n_markers
subplot(n_row, n_col, ii);
histogram(centroid_data(:, ii), edge_vector);
title(used_markers{ii});
end
%
figure('name', 'Centroid bivariate distributions')
% ii is the y axis marker
for ii = 1:(n_markers-1)
% jj is the y axis marker
for jj = (ii+1):n_markers
% which plot?
subplot_idx = (ii-1)*(n_markers-1) + (jj-1);
subplot(n_markers-1, n_markers-1, subplot_idx);
% plot distn
plot(centroid_data(:, jj), centroid_data(:, ii), '.');
xlim([min(edge_vector), max(edge_vector)]);
ylim([min(edge_vector), max(edge_vector)]);
% label appropriately
title_str = [used_markers{ii} ' vs ' used_markers{jj}];
title(title_str);
set(gca,'FontSize',8)
end
end
% save outputs
plot_file = fullfile(paramset.output_dir, 'marker biaxials.png');
set(gcf, 'PaperUnits', 'inches', 'PaperPosition', [0 0 20 20]);
r = 300; % pixels per inch
print(gcf, '-dpng', sprintf('-r%d', r), plot_file);
end
%% get_closest_cluster: finds which centroid each point is closest to
function [closest_cluster] = get_closest_cluster(this_column)
% close_options = find( this_column == min(this_column) );
% if numel(close_options) > 1
% fprintf('joint closest!\n');
% end
% n_options = length(close_options);
% selected_option = randsample(n_options, 1);
% closest_cluster = close_options(selected_option);
[~, closest_cluster] = min(this_column);
end
%% calc_cell_assignments:
function [cell_assignments] = calc_cell_assignments(options_struct, D, centroids_idx, not_centroids, outlier_idx)
% which is closest?
n_non_centroids = numel(not_centroids);
closest_clusters = NaN(n_non_centroids, 1);
% loop!
if options_struct.pool_flag
parfor ii = 1:n_non_centroids
closest_clusters(ii) = get_closest_cluster(D(:, ii));
end
else
for ii = 1:n_non_centroids
closest_clusters(ii) = get_closest_cluster(D(:, ii));
end
end
% how many cells overall?
n_cells = sum([numel(centroids_idx), numel(not_centroids), numel(outlier_idx)]);
% put together into cell_assignments
cell_assignments = NaN(n_cells, 1);
cell_assignments(centroids_idx) = 1:length(centroids_idx);
cell_assignments(not_centroids) = closest_clusters;
cell_assignments(outlier_idx) = 0;
end
|
github
|
wmacnair/TreeTop-master
|
save_txt_file.m
|
.m
|
TreeTop-master/TreeTop/private/save_txt_file.m
| 1,067 |
utf_8
|
ecf553c2da76347fc2365241e62baf87
|
%% save_txt_file:
function [] = save_txt_file(save_filename, header, save_data)
if isempty(header)
dataSpec = ['%4.4f' repmat('\t%4.4f', 1, size(save_data,2) -1) '\n'];;
fid = fopen(save_filename, 'w');
for ii = 1:size(save_data,1)
fprintf(fid, dataSpec, save_data(ii,:));
end
fclose(fid);
else
% if necessary, transpose header so that it has the expected dimensions
if size(header,2) == 1
header = header';
elseif size(header,1) == 1
else
error('At least one dimension of variable header must equal one');
end
if size(header,2) ~= size(save_data,2)
error(['Problem saving ' save_filename ': header and data are not compatible lengths.']);
else
fprintf('saving file %s\n', save_filename);
end
headerSpec = ['%s' repmat('\t%s', 1, size(header,2) -1) '\n'];
dataSpec = ['%4.4f' repmat('\t%4.4f', 1, size(save_data,2) -1) '\n'];
fid = fopen(save_filename, 'w');
fprintf(fid, headerSpec, header{:});
for ii = 1:size(save_data,1)
fprintf(fid, dataSpec, save_data(ii,:));
end
fclose(fid);
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.