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
|
drbenvincent/darc-experiments-matlab-master
|
plotDiscountSurface.m
|
.m
|
darc-experiments-matlab-master/darc-experiments/@Model_hyperbolic1ME_time/plotDiscountSurface.m
| 3,941 |
UNKNOWN
|
5e5f8fc832f6a6154c0225d60dd272f9
|
function plotDiscountSurface(obj, thetaStruct, varargin)
p = inputParser;
p.FunctionName = mfilename;
p.addRequired('thetaStruct',@isstruct);
p.addParameter('xScale','linear',@(x)any(strcmp(x,{'linear','log'})));
p.addParameter('data',[],@isstruct_or_table)
p.addParameter('pointEstimateType','mean',@isstr);
p.addParameter('discounting_function_handle','', @(x) isa(x,'function_handle'))
p.parse(thetaStruct, varargin{:});
data = p.Results.data;
plotSurface(data, thetaStruct, p.Results.discounting_function_handle, p)
plotData(data)
formatAxes(data);
end
function plotSurface(data, thetaStruct, discounting_function_handle, p)
% create set of delays to calculate & plot
N_DELAYS = 10;
if isempty(data)
delays = linspace(0,365,N_DELAYS);
else
max_delay_of_data = max([ data.D_A; data.D_B]);
delays = linspace(0, max_delay_of_data, N_DELAYS);
end
opts = calc_opts(data);
%% x-axis = b
N_REWARDS = 10;
logbvec = log(logspace(1, opts.pow, N_REWARDS));
% %% y-axis = d
% dvec = linspace(0, opts.maxD, 15);
%% z-axis (AB)
[logB,D] = meshgrid(logbvec,delays); % create x,y (b,d) grid values
% -------------------------------------------------------------------------
warning('Stop doing this kludge and do it properly (see below)')
m = median(thetaStruct.m);
c = median(thetaStruct.c);
k = exp(m .* logB + c); % magnitude effect
AB = 1 ./ (1 + k.*D); % hyperbolic discount function
% DO IT PROPERLY, LIKE BELOW ----------------------------------------------
% delays = D;
% reward = exp(logB);
% prospect.reward = reward';
% prospect.delay = delays';
% pointEst.m = median(thetaStruct.m);
% pointEst.c = median(thetaStruct.c);
% AB = discounting_function_handle(prospect, pointEst);
% -------------------------------------------------------------------------
%% PLOT
R_B = exp(logB);
hmesh = mesh(R_B, D, AB);
% shading
hmesh.FaceColor ='w';
hmesh.FaceAlpha =0.7;
% edges
hmesh.MeshStyle ='both';
hmesh.EdgeColor ='k';
hmesh.EdgeAlpha =1;
% plot isolines
hold on
[c,h] = contour3(R_B, D, AB, [0.2:0.2:0.8]);
h.LineColor = 'k';
h.LineWidth = 4;
end
function plotData(data)
if isempty(data)
return
end
[x,y,z,markerCol,markerSize] = convertDataIntoMarkers(data);
plotMarkers(x, y, z, markerCol, markerSize)
end
function [x,y,z,markerCol,markerSize] = convertDataIntoMarkers(data)
% find unique experimental designs
D=[abs(data.R_A), abs(data.R_B), data.D_A, data.D_B];
[C, ia, ic] = unique(D,'rows');
% loop over unique designs (ic)
for n=1:max(ic)
% binary set of which trials this design was used on
myset=ic==n;
% markerSize = number of times this design has been run
markerSize(n) = sum(myset);
% Colour = proportion of times participant chose immediate for that design
markerCol(n) = sum(data.R(myset)==0) ./ markerSize(n);
x(n) = abs(data.R_B( ia(n) )); % �R_B
y(n) = data.D_B( ia(n) ); % delay to get �R_B
%z(n) = abs(data.R_A_over_R_B( ia(n) ).*data.R_B( ia(n) )) ./ abs(data.R_B( ia(n) ));
z(n) = abs(data.R_A(ia(n))) ./ abs(data.R_B( ia(n)));
end
end
function plotMarkers(x, y, z, markerCol, markerSize)
hold on
for i=1:numel(x)
h = stem3(x(i), y(i), z(i));
h.Color='k';
h.MarkerFaceColor=[1 1 1] .* (1-markerCol(i));
h.MarkerSize = markerSize(i)+4;
hold on
end
end
function formatAxes(data)
xlabel('$|R^L|$', 'interpreter','latex')
ylabel('delay $D^b$', 'interpreter','latex')
zlabel('discount factor (and $\frac{R_A}{R_B}$)', 'interpreter','latex')
opts = calc_opts(data);
view([90+45, 20])
axis vis3d
axis tight
axis square
zlim([0 1])
set(gca,...
'XDir','reverse',...
'XScale','log',...
'XTick',logspace(1,opts.pow,opts.pow-1+1))
set(gca,'ZTick',[0:0.2:1])
camproj('perspective')
end
function opts = calc_opts(data)
if ~isempty(data)
opts.maxlogB = max( abs(data.R_B) );
opts.maxD = max( data.D_B );
else
opts.maxlogB = 1000;
opts.maxD = 365;
end
% what does this even do?
opts.nIndifferenceLines = 10;
pow=1; while opts.maxlogB > 10^pow; pow=pow+1; end
opts.pow = pow;
end
|
github
|
drbenvincent/darc-experiments-matlab-master
|
generate_designs.m
|
.m
|
darc-experiments-matlab-master/darc-experiments/response_error_types/@ChoiceFuncPsychometric/generate_designs.m
| 9,159 |
utf_8
|
76956e5e60901d47f17673051e41dc9a
|
function designs_allowed = generate_designs(obj, previous_designs, responses, thetas)
%generate_designs
%
% Create a matrix of possible designs. These will be considered by our
% optimization procedure.
%
% Inputs
%
% Outputs
% designs_allowed: A matrix of designs. Each column is one component of the
% design space. Each row is one design.
%
% Tom Rainforth 01/10/16
%% Setup options and variables
free_design_fields = obj.design_variables(~obj.is_design_variable_fixed());
free_design_vals = struct;
for n=1:numel(free_design_fields)
free_design_vals.(free_design_fields{n}) = obj.(free_design_fields{n});
end
fixed_design_fields = obj.design_variables(obj.is_design_variable_fixed());
fixed_design_vals = struct;
for n=1:numel(fixed_design_fields)
fixed_design_vals.(fixed_design_fields{n}) = obj.(fixed_design_fields{n});
end
% Load previous designs into the workspace
obj.unpackDesigns(previous_designs);
n_d = size(previous_designs,1);
mod_h = mod(n_d,1/obj.heuristic_rate);
b_use_heuristic = ~isnan(mod_h) && mod_h<0.9999; % Numerical stability
if b_use_heuristic
strategy = obj.heuristic_strategy;
else
strategy = 'no_heuristic';
end
%% Read in designs
if strcmpi(strategy,'random_no_replacement')
% This is the old strategy that uses the heuristic order and then
% randomly chooses all but the number. For this not all designs are
% evaluated
free_params = obj.params(~obj.is_theta_fixed());
free_params = setdiff(free_params,{'alpha','epsilon'}); % Ignore alpha and epsilon
n_design_allowed = numel(free_params);
n_designs_to_set = numel(free_design_fields)-n_design_allowed;
heuristic_counter = 1;
for n=1:numel(obj.heuristic_order)
if heuristic_counter > n_designs_to_set
break
end
if any(strcmp(obj.heuristic_order{n},free_design_fields))
eval(['heuristic_value = random_no_replacement(obj,' obj.heuristic_order{n} ',''' obj.heuristic_order{n} ''');']);
free_design_vals = rmfield(free_design_vals,obj.heuristic_order{n});
fixed_design_vals.(obj.heuristic_order{n}) = heuristic_value;
heuristic_counter = heuristic_counter+1;
end
end
designs_allowed = gen_designs(obj,free_design_vals,fixed_design_vals);
else
% Other strategies start by laying out all the designs
% First generate all the possible designs
designs_allowed = gen_designs(obj,free_design_vals,fixed_design_vals);
end
%% Eliminate designs already tried of with no chance of being helpful
% Eliminate designs already tried
if ~isempty(previous_designs)
designs_allowed = setdiff(designs_allowed,previous_designs,'rows');
end
% Eliminate designs whose response is effectively known using the point
% estimate
% Now make a point estimate for theta and use it to calculate the
% sooner and later subjective values for all of these possible
% designs
theta = point_estimate_theta(obj,thetas,'mean');
alpha = [];
obj.unpackTheta(theta);
[VA, VB] = obj.subjective_values(theta,designs_allowed);
Vsum = VA+VB;
Vdiff = VB-VA;
% Eliminate Vsum points where the response is effectively certain
% such that these are clearly poor designs
p_raw = normcdf(Vdiff/alpha); % Prob response ignoring epsilon
b_extreme = p_raw<0.005 | p_raw>0.995;
n_not_extreme = sum(~b_extreme);
if n_not_extreme<10
% Cop out as we don't have a reasonable number of sensible
% designs left, take the ten smallest differences (with some
% noise to split ties randomly)
[~,is] = sort(abs(Vdiff)+(1e-10)*rand(size(Vdiff)));
n_take = min(10,numel(is));
designs_allowed = designs_allowed(is(1:n_take),:);
return
end
Vsum = Vsum(~b_extreme);
p_raw = p_raw(~b_extreme);
designs_allowed = designs_allowed(~b_extreme,:);
%% Do further design elimination heuristics
if any(strcmpi(strategy,{'no_heuristic','random_no_replacement'}))
% For no_heuristic heuristic and random_no_replacement we are now done
elseif strcmpi(strategy,'subjective_value_spreading')
if size(previous_designs,1)<4 % Old was 2
% Not enough previous designs. Let the experimental design
% method do its magic
return
end
% Use a kernel density estimator to get the distribution of
% Vsum and evaluate at the Vsum points.
[VSp,VLp] = obj.subjective_values(theta,previous_designs);
Vpsum = VSp+VLp;
Vpdiff = VLp-VSp;
p_raw_p = normcdf(Vpdiff/alpha);
b_p_extreme = p_raw_p<0.005 | p_raw_p>0.995;
if sum(~b_p_extreme) > 3 % Old was 1
% We don't care about even spacing with what turned out to
% be useless questions. We want an even spacing of the
% pertinent ones. Therefore we only look at distance to
% helpful questions for choosing were to go.
Vpsum = Vpsum(~b_p_extreme);
Vpdiff = Vpdiff(~b_p_extreme);
else
% There are 3 or less useful questions remain so again don't
% care about even space. Let the optimizer do its magic
return
end
% Find the point in Vsum space that is further from previous
% values using
hard_coded_scale = 0.1;
Vden = kernel_dist(Vsum,Vpsum,hard_coded_scale*(max(Vsum)-min(Vsum)));
[~,imin] = min(Vden);
% Now only look at points that are close to this in Vsum space.
% What we will do is to chop up the p_raw space (i.e. bin the
% output probabilities, ignoring epsilon) and then choose the
% closest sample to Vsum(imin) in each bin. This gives a good
% spread of probabilities while maintaining points close the target
% Vsum.
VsumDiff = Vsum-Vsum(imin);
% Partitions are uneven as more likely to want to be near the
% middle, for now will be even though
bin_pos = 0:(1/obj.n_design_opt):1;
%bin_pos = betacdf(0:(1/obj.n_design_opt):1,0.5,0.5); % Alternative
%for uneven
[~,i_bin] = histc(p_raw,bin_pos);
% Sort first by bin then the absolute difference to target point.
[i_p,i_s] = sortrows([i_bin,abs(VsumDiff)]);
% Take the first of each type
i_take = [1;1+find(diff(i_p(:,1))~=0)];
prob_diffs_take = i_p(i_take,2)/(max(Vsum)-min(Vsum));
% We want to eliminate any differences that are too high without
% removing all of them
hard_closeness_coded_threshold = 0.4/sqrt(size(previous_designs,1));
b_too_far = prob_diffs_take>hard_closeness_coded_threshold;
i_take = i_take(~b_too_far);
designs_allowed = designs_allowed(i_s(i_take),:);
% To see whats going on set below to true
b_debug_plot = false;
if b_debug_plot && size(previous_designs,1)>2 && size(previous_designs,1)>5 && mod(size(previous_designs,1),5)==0
% First lets look at Vsum vs p_raw for the candidates (blue),
% previous designs (red), and designes selected to be allowed
% (green).
figure;
plot(VA+VB,normcdf((VB-VA)/alpha),'x');
hold on;
plot([Vsum(imin),Vsum(imin)],[0,1],'--g','LineWidth',2);
plot(Vpsum,normcdf(Vpdiff/alpha),'rx','MarkerSize',6,'LineWidth',4);
[VSdebug,VLdebug] = obj.subjective_values(theta,designs_allowed);
plot(VSdebug+VLdebug,normcdf((VLdebug-VSdebug)/alpha),'gx','MarkerSize',6,'LineWidth',4);
% Now lets look at the density of previously chosen Vrank's
% along with their positions and the new allowed positions.
figure;
plot(Vsum,Vden,'x');
hold on;
plot(Vpsum,zeros(size(Vpsum)),'rx','MarkerSize',6,'LineWidth',4);
plot(VSdebug+VLdebug,zeros(size(VSdebug)),'gx','MarkerSize',6,'LineWidth',4);
% Pause to let us look
keyboard;
end
end
end
function designs_allowed = gen_designs(obj,free_design_vals,fixed_design_vals)
free_design_fields = fields(free_design_vals);
% Generates variables in this file for the previous design variables
design_vars = fixed_design_vals;
for m=1:numel(free_design_fields)
design_vars.(free_design_fields{m}) = free_design_vals.(free_design_fields{m});
end
nd_grid_string = '[';
for m=1:numel(obj.design_variables)
nd_grid_string = [nd_grid_string, obj.design_variables{m} ','];
end
nd_grid_string = [nd_grid_string(1:end-1) '] = ndgrid('];
for m=1:numel(obj.design_variables)
nd_grid_string = [nd_grid_string, 'design_vars.' obj.design_variables{m} ','];
end
nd_grid_string = [nd_grid_string(1:end-1) ');'];
eval(nd_grid_string);
designs_allowed = [];
for m=1:numel(fields(design_vars))
eval(['designs_allowed = [designs_allowed,' obj.design_variables{m} '(:)];']);
end
end
function v = random_no_replacement(obj,previous_vals,var_name)
allowed_vals = obj.(var_name);
left_vals = setdiff(allowed_vals,previous_vals);
if isempty(left_vals)
[~,i_int] = unique(previous_vals);
i_left = setdiff(1:numel(previous_vals),i_int);
twice_vals = previous_vals(i_left);
if isempty(twice_vals)
left_vals = previous_vals;
else
v = random_no_replacement(obj,twice_vals,var_name);
return
end
end
v = datasample(left_vals,1);
end
function d = kernel_dist(V1,V2,scale)
d = mean(exp(-(bsxfun(@minus,V1,V2').^2)/scale^2),2);
end
|
github
|
drbenvincent/darc-experiments-matlab-master
|
SCRIPT_logk_comparison_of_methods.m
|
.m
|
darc-experiments-matlab-master/generate_figs_for_paper/SCRIPT_logk_comparison_of_methods.m
| 3,145 |
utf_8
|
e64012ec647f029f09c5a77568cecc0c
|
function SCRIPT_logk_comparison_of_methods()
addpath('darc-experiments')
%% Sort figure and subpanel arrangement
fh = figure(56); clf, drawnow
set(fh, 'WindowStyle','normal')
nrows = 4;
subplot_handles = layout([1,2,3,4; 5,6,7,8; 9,10,11,12]');
drawnow
%% Load data for the 3 example participants
examples = makeExamples();
assert(numel(examples)==3, 'expecting 3 examples')
%% Iterate over the 3 examples, plotting as we go
for n=1:numel(examples)
fprintf('%d of %d\n',n, numel(examples))
ind = nrows*(n-1)+1;
process_this_example( examples(n), subplot_handles([ind:ind+(nrows-1)]))
end
% NOTE (x,y) position is in DATA units
%% Add column titles (example name)
top_plots = subplot_handles([1, 5, 9]);
for n=1:numel(top_plots)
subplot(top_plots(n))
h = text(365/2, 1.25, examples(n).title);
h.HorizontalAlignment = 'center';
h.FontWeight = 'bold';
h.FontSize = 16;
end
%% Add row titles
row_title_labels = {'Kirby (2009)',...
'Koffarnus & Bickel (2014)',...
'Frye et al (2016)',...
'our approach'};
top_plots = subplot_handles([1, 2, 3, 4]);
for n=1:numel(top_plots)
subplot(top_plots(n))
h = text(-100, 0.5, row_title_labels{n});
h.Rotation = 90;
h.HorizontalAlignment = 'center';
h.FontWeight = 'bold';
h.FontSize = 16;
end
% save data
save('figs/saved_data_logk_comparison_of_models')
%% Export
setAllSubplotOptions(gcf, {'LineWidth', 1.5, 'FontSize',12})
set(subplot_handles, 'PlotBoxAspectRatio',[1.5 1 1])
set(gcf,'Position',[10 10 1200 1300])
ensureFolderExists('figs')
savefig('figs/logk_comparison_of_models')
%export_fig('figs/logk_comparison_of_models', '-pdf')
export_fig('figs/logk_comparison_of_models', '-png', '-m6');
end
function process_this_example(example, subplot_handles)
% Run models
true_logk = example.true_theta;
% [kirby_Model_to_plot, ktheta, kdata, ~,...
% adaptive_Model_to_plot, adaptive_theta, adaptive_data, ~]...
% = runKirbyAndAdaptive(true_logk);
trials = 27;
MAX_DELAY = 365;
%% Kirby example
[model, theta, data, ~] = runKirby(true_logk, 27);
subplot(subplot_handles(1))
model.plotDiscountFunction(theta(:,1),...
'data', data,...
'discounting_function_handle', @model.delayDiscountingFunction, ...
'maxDelay', MAX_DELAY);
drawnow
%% KoffarnusAndBickel
[model, theta, data, ~] = runKoffarnusAndBickel(true_logk, 5);
subplot(subplot_handles(2))
model.plotDiscountFunction(theta(:,1),...
'data', data,...
'discounting_function_handle', @model.delayDiscountingFunction, ...
'maxDelay', MAX_DELAY);
drawnow
%% Fry Et al
[model, theta, data, ~] = runFryeEtAl(true_logk, 5*5);
subplot(subplot_handles(3))
model.plotDiscountFunction(theta(:,1),...
'data', data,...
'discounting_function_handle', @model.delayDiscountingFunction, ...
'maxDelay', MAX_DELAY);
drawnow
%% Our method
% override default delays with this
%tempD_B = default_D_B(); D_B = tempD_B(tempD_B<=190);
D_B = [1:7:MAX_DELAY];
[model, theta, data, ~] = runAdaptiveLogK(true_logk, 30,...
'D_B', D_B);
subplot(subplot_handles(4))
model.plotDiscountFunction(theta(:,1),...
'data', data,...
'discounting_function_handle', @model.delayDiscountingFunction, ...
'maxDelay', MAX_DELAY);
drawnow
end
|
github
|
drbenvincent/darc-experiments-matlab-master
|
SCRIPT_logk_param_recovery_role_of_prior.m
|
.m
|
darc-experiments-matlab-master/generate_figs_for_paper/SCRIPT_logk_param_recovery_role_of_prior.m
| 1,364 |
utf_8
|
8356fade05ebefc58e78eb445bb1ed3a
|
function SCRIPT_logk_param_recovery_role_of_prior()
%% Setup
addpath('darc-experiments')
save_path = fullfile(pwd,'data');
logk_list = [-8:0.05:-1];
%% Run parameter sweeps
result_adaptive2 = parameter_sweep(logk_list, @param_recovery_adaptive_logk, 2);
result_adaptive4 = parameter_sweep(logk_list, @param_recovery_adaptive_logk, 4);
result_adaptive8 = parameter_sweep(logk_list, @param_recovery_adaptive_logk, 8);
result_adaptive16 = parameter_sweep(logk_list, @param_recovery_adaptive_logk, 16);
%% PLOTTING
figure_handle = figure(3); clf
set(figure_handle,'WindowStyle', 'Normal')
subplot(2,2,1)
result_adaptive2.plot_param_recovery(), title('2 trials')
axis([-8.2 -0.8 -8 0])
subplot(2,2,2)
result_adaptive4.plot_param_recovery(), title('4 trials')
axis([-8.2 -0.8 -8 0])
subplot(2,2,3)
result_adaptive8.plot_param_recovery(), title('8 trials')
axis([-8.2 -0.8 -8 0])
subplot(2,2,4)
result_adaptive16.plot_param_recovery(), title('16 trials')
axis([-8.2 -0.8 -8 0])
%% Export
setAllSubplotOptions(gcf, {'LineWidth', 2, 'FontSize', 16})
set(figure_handle, 'Position',[10 0 800 800])
ensureFolderExists('figs')
export_fig('figs/logk_param_recovery_role_of_prior.pdf', '-pdf')
beep
end
function logk_theta_record = param_recovery_adaptive_logk(true_logk, trials)
[model, theta, data, logk_theta_record] = runAdaptiveLogK(true_logk, trials);
end
|
github
|
drbenvincent/darc-experiments-matlab-master
|
SCRIPT_logk_param_recovery.m
|
.m
|
darc-experiments-matlab-master/generate_figs_for_paper/SCRIPT_logk_param_recovery.m
| 1,837 |
utf_8
|
8cd207bb03305b7bd749d5315336357b
|
function SCRIPT_logk_param_recovery()
%% Setup
addpath('darc-experiments')
save_path = fullfile(pwd,'data');
logk_list = [-8:0.05:-1];
%% Run parameter sweeps
result_kirby = parameter_sweep(logk_list, @param_recovery_kirby_logk, 27);
result_koffarnus = parameter_sweep(logk_list, @param_recovery_koffarnus, 5);
result_fry = parameter_sweep(logk_list, @param_recovery_frye, 5*4);
result_adaptive20 = parameter_sweep(logk_list, @param_recovery_adaptive_logk, 20);
%% PLOTTING
figure_handle = figure(3); clf
set(figure_handle,'WindowStyle', 'Normal')
subplot(2,2,1)
result_kirby.plot_param_recovery(), title('Kirby (2009), 27 trials')
axis([-8.2 -0.8 -8 0])
subplot(2,2,2)
result_koffarnus.plot_param_recovery(), title('Koffarnus & Bickel (2014), 5 trials')
axis([-8.2 -0.8 -8 0])
subplot(2,2,3)
result_fry.plot_param_recovery(), title('Frye et al (2016), 20 trials')
axis([-8.2 -0.8 -8 0])
subplot(2,2,4)
result_adaptive20.plot_param_recovery(), title('Our approach, 20 trials')
axis([-8.2 -0.8 -8 0])
%% Export
setAllSubplotOptions(gcf, {'LineWidth', 2, 'FontSize', 16})
set(figure_handle, 'Position',[10 0 800 800])
ensureFolderExists('figs')
export_fig('figs/logk_param_recovery', '-pdf')
beep
end
function logk_theta_record = param_recovery_kirby_logk(true_logk, trials)
[model, theta, data, logk_theta_record] = runKirby(true_logk, trials);
end
function logk_theta_record = param_recovery_frye(true_logk, trials)
[model, theta, data, logk_theta_record] = runFryeEtAl(true_logk, trials);
end
function logk_theta_record = param_recovery_adaptive_logk(true_logk, trials)
[model, theta, data, logk_theta_record] = runAdaptiveLogK(true_logk, trials);
end
function logk_theta_record = param_recovery_koffarnus(true_logk, trials)
[model, theta, data, logk_theta_record] = runKoffarnusAndBickel(true_logk, trials);
end
|
github
|
drbenvincent/darc-experiments-matlab-master
|
SCRIPT_models_parameter_recovery.m
|
.m
|
darc-experiments-matlab-master/generate_figs_for_paper/SCRIPT_models_parameter_recovery.m
| 4,615 |
utf_8
|
1626fe0b1ac43a7f3a36ffd0fca2874a
|
function SCRIPT_models_parameter_recovery()
%% Setup
addpath('darc-experiments')
trials = 30; %30
K = 51; % 51
% CALCULATIONS: Do parameter recovery for all models ===========================
%% Hyperbolic discounting of time (with magnitude effect)
true_m_vec = linspace(-1, -0.5, K);
true_c_vec = linspace(-0.5, -2.5, K);
[m_array, c_array] = do_param_recovery_me(trials, true_m_vec, true_c_vec);
%% Hyperbolic discounting of odds against
true_h_vec = logspace(-1,1,K);
h_array = do_param_recovery_h(trials, true_h_vec);
%% Hyperbolic discounting of time AND odds against
true_logk_vec = linspace(-8,-1,K);
true_h_vec = logspace(-1,1,K);
[TO_logk_array, TO_h_array] = do_param_recovery_time_and_odds(trials, true_logk_vec, true_h_vec);
save 'other_models_parameter_recovery.mat'
beep
%% PLOTTING
figure_handle = figure(3); clf
set(figure_handle, 'WindowStyle', 'Normal')
[figure_handle, h_row_labels, h_col_labels, h_main] = ...
make_subplot_grid({ {'time discounting', '(with magnitude effect)'},...
{'probability', 'discounting'},...
{'time and probabilty', 'discounting'}},...
{'',''});
subplot(h_main(1, 1)), m_array.plot_param_recovery(), title('m'), setTickIntervals(0.25, 0.25)
subplot(h_main(1, 2)), c_array.plot_param_recovery(), title('c'), setTickIntervals(0.5, 0.5)
subplot(h_main(2, 1)), h_array.plot_param_recovery(), title('h'), %setTickIntervals(2,2)
set(gca,'XScale','log', 'YScale','log')
axis([10^-1 10^1 10^-1 10^1])
set(gca,'XTickLabel',{0.1, 1, 10},...
'YTickLabel',{0.1, 1, 10})
delete(h_main(2, 2))
subplot(h_main(3, 1)), TO_logk_array.plot_param_recovery(), title('log(k)'), setTickIntervals(2,2)
axis([min(true_logk_vec) max(true_logk_vec) min(true_logk_vec) max(true_logk_vec)])
subplot(h_main(3, 2)), TO_h_array.plot_param_recovery(), title('h'), %setTickIntervals(2,2)
set(gca,'XScale','log', 'YScale','log')
axis([10^-1 10^1 10^-1 10^1])
set(gca,'XTickLabel',{0.1, 1, 10},...
'YTickLabel',{0.1, 1, 10})
%% Export
figure_handle.Units = 'pixels';
set(figure_handle,'Position',[10 10 600 1000])
ensureFolderExists('figs')
savefig('figs/multiple_Model_param_recovery')
export_fig('figs/multiple_Model_param_recovery', '-pdf')
beep
end
function [m_array, c_array] = do_param_recovery_me(trials, true_m_vec, true_c_vec)
display('Hyperbolic discounting of time (with magnitude effect)')
% Define parameters
% Alpha and Epsilon are treated as fixed parameters
[alpha, epsilon] = common_parameters();
m_array = [];
c_array = [];
parfor n=1:numel(true_m_vec)
fprintf('%d of %d\n',n, numel(true_m_vec))
true_m = true_m_vec(n);
true_c = true_c_vec(n);
model = Model_hyperbolic1ME_time(...
'epsilon', epsilon);
expt = Experiment(model,...
'agent', 'simulated_agent',...
'trials', trials,...
'true_theta', struct('m', true_m, 'c', true_c, 'alpha', alpha),...
'plotting','none');
expt = expt.runTrials();
m = expt.get_specific_theta_record_parameter('m');
m_array = [m_array m];
c = expt.get_specific_theta_record_parameter('c');
c_array = [c_array c];
end
end
function h_array = do_param_recovery_h(trials, true_h_vec)
display('Hyperbolic discounting of log odds')
% Alpha and Epsilon are treated as fixed parameters
[alpha, epsilon] = common_parameters();
h_array = [];
parfor n=1:numel(true_h_vec)
fprintf('%d of %d\n',n, numel(true_h_vec))
true_h = true_h_vec(n);
model = Model_hyperbolic1_prob(...
'epsilon', epsilon,... % fixed value
'R_B', 100);
expt = Experiment(...
model,...
'agent', 'simulated_agent',...
'trials', trials,...
'true_theta', struct('h', true_h, 'alpha', alpha),...
'plotting','none');
expt = expt.runTrials();
h = expt.get_specific_theta_record_parameter('h');
h_array = [h_array h];
end
end
function [logk_array, h_array] = do_param_recovery_time_and_odds(trials, true_logk_vec, true_h_vec);
display('Hyperbolic discounting of time AND log odds against')
% Alpha and Epsilon are treated as fixed parameters
[alpha, epsilon] = common_parameters();
logk_array = [];
h_array = [];
parfor n=1:numel(true_logk_vec)
fprintf('%d of %d\n',n, numel(true_logk_vec))
true_logk = true_logk_vec(n);
true_h = true_h_vec(n);
model = Model_hyperbolic1_time_and_prob(...
'epsilon', epsilon);
expt = Experiment(...
model,...
'agent', 'simulated_agent',...
'trials', trials,...
'true_theta', struct('logk', true_logk, 'h', true_h, 'alpha', alpha),...
'plotting','none');
expt = expt.runTrials();
logk = expt.get_specific_theta_record_parameter('logk');
logk_array = [logk_array logk];
h = expt.get_specific_theta_record_parameter('h');
h_array = [h_array h];
end
end
|
github
|
drbenvincent/darc-experiments-matlab-master
|
fig_darc_schematic.m
|
.m
|
darc-experiments-matlab-master/generate_figs_for_paper/fig_darc_schematic.m
| 3,127 |
utf_8
|
419ae13f8cc195dcb598b39ba7512225
|
% fig_darc_schematic
% Create the basic structure of the figure to demonstrate the approaches:
% - Expected Utility Theory
% - Prospect Theory
% - Discounting
f = figure(1);
clf
h = layout([1, 2, 3; 4 5 6; 7 8 9]);
reward = linspace(-10,10,100);
probability = linspace(0,1,1000);
delays = linspace(0,365, 3650);
odds = (1-probability)./probability;
%% EUT
% linear utility
subplot(h(1))
p = plot(reward, reward, 'k-','Linewidth',2);
h(1).XAxisLocation = 'origin';
h(1).YAxisLocation = 'origin';
xlabel('$R$', 'interpreter', 'latex')
ylabel('$u(R)$', 'interpreter', 'latex')
axis equal
axis square
box off
% linear probability
subplot(h(2))
p = plot(probability, probability, 'k-','Linewidth',2);
xlabel('$P$', 'interpreter', 'latex')
ylabel('$\pi (P)$', 'interpreter', 'latex')
axis equal
box off
axis([0 1 0 1])
% exponential discounting
subplot(h(3))
plot(delays, exp(-0.005.*delays), 'k-','Linewidth',2);
xlabel('$D$', 'interpreter', 'latex')
ylabel('$d(D)$', 'interpreter', 'latex')
xlim([0, 365])
box off
axis square
%% prospect theory
% value function
subplot(h(4))
alpha = 0.6;
beta = 0.6;
loss = 1.5;
p = plot(reward, pt_util_function(reward, alpha, beta, loss),...
'k-','Linewidth',2);
xlabel('$R$', 'interpreter', 'latex')
ylabel('$u(R)$', 'interpreter', 'latex')
axis equal
axis square
box off
h(4).XAxisLocation = 'origin';
h(4).YAxisLocation = 'origin';
% prospect theory weighting function
% linear probability
subplot(h(5))
delta = 0.6;
gamma = 0.4;
wf = @(p) (delta.*p.^gamma) ./ ((delta.*p.^gamma) + (1-p).^gamma);
p = plot(probability, wf(probability), 'k-','Linewidth',2);
hold on
plot([0 1],[0 1], 'k-')
xlabel('$P$', 'interpreter', 'latex')
ylabel('$\pi (P)$', 'interpreter', 'latex')
axis equal
axis square
box off
axis([0 1 0 1])
% no time discounting
subplot(h(6))
plot(delays, ones(size(delays)), 'k-','Linewidth',2);
xlabel('$D$', 'interpreter', 'latex')
ylabel('$d(D)$', 'interpreter', 'latex')
xlim([0, 365])
ylim([0 1.1])
box off
axis square
%% Discounting approaches
% linear utility function
subplot(h(7))
p = plot(reward, reward, 'k-','Linewidth',2);
xlabel('$R$', 'interpreter', 'latex')
ylabel('$u(R)$', 'interpreter', 'latex')
axis equal
axis square
box off
h(6).XAxisLocation = 'origin';
h(6).YAxisLocation = 'origin';
% hyperbolic discounting of odds
subplot(h(8))
plot(odds, 1./(1+1.*odds), 'k-','Linewidth',2);
xlabel('$ odds = \frac{1-P}{P}$', 'interpreter', 'latex')
ylabel('$ \pi(\frac{1-P}{P}) $', 'interpreter', 'latex')
xlim([0, 10])
axis square
box off
addTextToFigure('BL',' risk averse', 12)
addTextToFigure('TR','risk seeking', 12)
% hyperbolic discounting of delay
subplot(h(9))
plot(delays, 1./(1+exp(-3).*delays), 'k-','Linewidth',2);
xlabel('$D$', 'interpreter', 'latex')
ylabel('$d(D)$', 'interpreter', 'latex')
xlim([0, 365])
axis square
box off
%% Export
set(gcf,'Position',[10 10 900 700])
savefig('figs/darc_schematic_raw')
export_fig('figs/darc_schematic_raw', '-pdf')
function u = pt_util_function(reward, alpha, beta, loss)
u(reward>=0) = reward(reward>=0).^alpha;
u(reward<0) = -loss.*((-reward(reward<0)).^beta);
end
|
github
|
ajit2704/underwater-image-enhancement-master
|
vanherk.m
|
.m
|
underwater-image-enhancement-master/mat/vanherk.m
| 4,841 |
utf_8
|
5b0cf60c12e2432af9a978d4bad7ff3b
|
function Y = vanherk(X,N,TYPE,varargin)
% VANHERK Fast max/min 1D filter
%
% Y = VANHERK(X,N,TYPE) performs the 1D max/min filtering of the row
% vector X using a N-length filter.
% The filtering type is defined by TYPE = 'max' or 'min'. This function
% uses the van Herk algorithm for min/max filters that demands only 3
% min/max calculations per element, independently of the filter size.
%
% If X is a 2D matrix, each row will be filtered separately.
%
% Y = VANHERK(...,'col') performs the filtering on the columns of X.
%
% Y = VANHERK(...,'shape') returns the subset of the filtering specified
% by 'shape' :
% 'full' - Returns the full filtering result,
% 'same' - (default) Returns the central filter area that is the
% same size as X,
% 'valid' - Returns only the area where no filter elements are outside
% the image.
%
% X can be uint8 or double. If X is uint8 the processing is quite faster, so
% dont't use X as double, unless it is really necessary.
%
% Initialization
[direc, shape] = parse_inputs(varargin{:});
if strcmp(direc,'col')
X = X';
end
if strcmp(TYPE,'max')
maxfilt = 1;
elseif strcmp(TYPE,'min')
maxfilt = 0;
else
error([ 'TYPE must be ' char(39) 'max' char(39) ' or ' char(39) 'min' char(39) '.'])
end
% Correcting X size
fixsize = 0;
addel = 0;
if mod(size(X,2),N) ~= 0
fixsize = 1;
addel = N-mod(size(X,2),N);
if maxfilt
f = [ X zeros(size(X,1), addel) ];
else
f = [X repmat(X(:,end),1,addel)];
end
else
f = X;
end
lf = size(f,2);
lx = size(X,2);
clear X
% Declaring aux. mat.
g = f;
h = g;
% Filling g & h (aux. mat.)
ig = 1:N:size(f,2);
ih = ig + N - 1;
g(:,ig) = f(:,ig);
h(:,ih) = f(:,ih);
if maxfilt
for i = 2 : N
igold = ig;
ihold = ih;
ig = ig + 1;
ih = ih - 1;
g(:,ig) = max(f(:,ig),g(:,igold));
h(:,ih) = max(f(:,ih),h(:,ihold));
end
else
for i = 2 : N
igold = ig;
ihold = ih;
ig = ig + 1;
ih = ih - 1;
g(:,ig) = min(f(:,ig),g(:,igold));
h(:,ih) = min(f(:,ih),h(:,ihold));
end
end
clear f
% Comparing g & h
if strcmp(shape,'full')
ig = [ N : 1 : lf ];
ih = [ 1 : 1 : lf-N+1 ];
if fixsize
if maxfilt
Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ];
else
Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end-addel) ];
end
else
if maxfilt
Y = [ g(:,1:N-1) max(g(:,ig), h(:,ih)) h(:,end-N+2:end) ];
else
Y = [ g(:,1:N-1) min(g(:,ig), h(:,ih)) h(:,end-N+2:end) ];
end
end
elseif strcmp(shape,'same')
if fixsize
if addel > (N-1)/2
disp('hoi')
ig = [ N : 1 : lf - addel + floor((N-1)/2) ];
ih = [ 1 : 1 : lf-N+1 - addel + floor((N-1)/2)];
if maxfilt
Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) ];
else
Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) ];
end
else
ig = [ N : 1 : lf ];
ih = [ 1 : 1 : lf-N+1 ];
if maxfilt
Y = [ g(:,1+ceil((N-1)/2):N-1) max(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ];
else
Y = [ g(:,1+ceil((N-1)/2):N-1) min(g(:,ig), h(:,ih)) h(:,lf-N+2:lf-N+1+floor((N-1)/2)-addel) ];
end
end
else % not fixsize (addel=0, lf=lx)
ig = [ N : 1 : lx ];
ih = [ 1 : 1 : lx-N+1 ];
if maxfilt
Y = [ g(:,N-ceil((N-1)/2):N-1) max( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ];
else
Y = [ g(:,N-ceil((N-1)/2):N-1) min( g(:,ig), h(:,ih) ) h(:,lx-N+2:lx-N+1+floor((N-1)/2)) ];
end
end
elseif strcmp(shape,'valid')
ig = [ N : 1 : lx];
ih = [ 1 : 1: lx-N+1];
if maxfilt
Y = [ max( g(:,ig), h(:,ih) ) ];
else
Y = [ min( g(:,ig), h(:,ih) ) ];
end
end
if strcmp(direc,'col')
Y = Y';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [direc, shape] = parse_inputs(varargin)
direc = 'lin';
shape = 'same';
flag = [0 0]; % [dir shape]
for i = 1 : nargin
t = varargin{i};
if strcmp(t,'col') & flag(1) == 0
direc = 'col';
flag(1) = 1;
elseif strcmp(t,'full') & flag(2) == 0
shape = 'full';
flag(2) = 1;
elseif strcmp(t,'same') & flag(2) == 0
shape = 'same';
flag(2) = 1;
elseif strcmp(t,'valid') & flag(2) == 0
shape = 'valid';
flag(2) = 1;
else
error(['Too many / Unkown parameter : ' t ])
end
end
|
github
|
ajit2704/underwater-image-enhancement-master
|
maxfilt2.m
|
.m
|
underwater-image-enhancement-master/mat/maxfilt2.m
| 1,849 |
utf_8
|
45cc67fb2afee0dc77cfc7798629574f
|
function Y = maxfilt2(X,varargin)
% MAXFILT2 Two-dimensional max filter
%
% Y = MAXFILT2(X,[M N]) performs two-dimensional maximum
% filtering on the image X using an M-by-N window. The result
% Y contains the maximun value in the M-by-N neighborhood around
% each pixel in the original image.
% This function uses the van Herk algorithm for max filters.
%
% Y = MAXFILT2(X,M) is the same as Y = MAXFILT2(X,[M M])
%
% Y = MAXFILT2(X) uses a 3-by-3 neighborhood.
%
% Y = MAXFILT2(..., 'shape') returns a subsection of the 2D
% filtering specified by 'shape' :
% 'full' - Returns the full filtering result,
% 'same' - (default) Returns the central filter area that is the
% same size as X,
% 'valid' - Returns only the area where no filter elements are outside
% the image.
%
% See also : MINFILT2, VANHERK
%
% Initialization
[S, shape] = parse_inputs(varargin{:});
% filtering
Y = vanherk(X,S(1),'max',shape);
Y = vanherk(Y,S(2),'max','col',shape);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [S, shape] = parse_inputs(varargin)
shape = 'same';
flag = [0 0]; % size shape
for i = 1 : nargin
t = varargin{i};
if strcmp(t,'full') & flag(2) == 0
shape = 'full';
flag(2) = 1;
elseif strcmp(t,'same') & flag(2) == 0
shape = 'same';
flag(2) = 1;
elseif strcmp(t,'valid') & flag(2) == 0
shape = 'valid';
flag(2) = 1;
elseif flag(1) == 0
S = t;
flag(1) = 1;
else
error(['Too many / Unkown parameter : ' t ])
end
end
if flag(1) == 0
S = [3 3];
end
if length(S) == 1;
S(2) = S(1);
end
if length(S) ~= 2
error('Wrong window size parameter.')
end
|
github
|
ajit2704/underwater-image-enhancement-master
|
bilateralFilter.m
|
.m
|
underwater-image-enhancement-master/mat/bilateralFilter.m
| 6,703 |
utf_8
|
a76d6aab0840ad8b7e6e749526f36660
|
%
% output = bilateralFilter( data, edge, ...
% edgeMin, edgeMax, ...
% sigmaSpatial, sigmaRange, ...
% samplingSpatial, samplingRange )
%
% Bilateral and Cross-Bilateral Filter using the Bilateral Grid.
%
% Bilaterally filters the image 'data' using the edges in the image 'edge'.
% If 'data' == 'edge', then it the standard bilateral filter.
% Otherwise, it is the 'cross' or 'joint' bilateral filter.
% For convenience, you can also pass in [] for 'edge' for the normal
% bilateral filter.
%
% Note that for the cross bilateral filter, data does not need to be
% defined everywhere. Undefined values can be set to 'NaN'. However, edge
% *does* need to be defined everywhere.
%
% data and edge should be of the greyscale, double-precision floating point
% matrices of the same size (i.e. they should be [ height x width ])
%
% data is the only required argument
%
% edgeMin and edgeMax specifies the min and max values of 'edge' (or 'data'
% for the normal bilateral filter) and is useful when the input is in a
% range that's not between 0 and 1. For instance, if you are filtering the
% L channel of an image that ranges between 0 and 100, set edgeMin to 0 and
% edgeMax to 100.
%
% edgeMin defaults to min( edge( : ) ) and edgeMax defaults to max( edge(:)).
% This is probably *not* what you want, since the input may not span the
% entire range.
%
% sigmaSpatial and sigmaRange specifies the standard deviation of the space
% and range gaussians, respectively.
% sigmaSpatial defaults to min( width, height ) / 16
% sigmaRange defaults to ( edgeMax - edgeMin ) / 10.
%
% samplingSpatial and samplingRange specifies the amount of downsampling
% used for the approximation. Higher values use less memory but are also
% less accurate. The default and recommended values are:
%
% samplingSpatial = sigmaSpatial
% samplingRange = sigmaRange
%
function output = bilateralFilter( data, edge, edgeMin, edgeMax,...
sigmaSpatial, sigmaRange, samplingSpatial, samplingRange )
if( ndims( data ) > 2 ),
error( 'data must be a greyscale image with size [ height, width ]' );
end
if( ~isa( data, 'double' ) ),
error( 'data must be of class "double"' );
end
if ~exist( 'edge', 'var' ),
edge = data;
elseif isempty( edge ),
edge = data;
end
if( ndims( edge ) > 2 ),
error( 'edge must be a greyscale image with size [ height, width ]' );
end
if( ~isa( edge, 'double' ) ),
error( 'edge must be of class "double"' );
end
inputHeight = size( data, 1 );
inputWidth = size( data, 2 );
if ~exist( 'edgeMin', 'var' ),
edgeMin = min( edge( : ) );
%warning( 'edgeMin not set! Defaulting to: %f\n', edgeMin );
end
if ~exist( 'edgeMax', 'var' ),
edgeMax = max( edge( : ) );
%warning( 'edgeMax not set! Defaulting to: %f\n', edgeMax );
end
edgeDelta = edgeMax - edgeMin;
if ~exist( 'sigmaSpatial', 'var' ),
sigmaSpatial = min( inputWidth, inputHeight ) / 16;
%fprintf( 'Using default sigmaSpatial of: %f\n', sigmaSpatial );
end
if ~exist( 'sigmaRange', 'var' ),
sigmaRange = 0.1 * edgeDelta;
%fprintf( 'Using default sigmaRange of: %f\n', sigmaRange );
end
if ~exist( 'samplingSpatial', 'var' ),
samplingSpatial = sigmaSpatial;
end
if ~exist( 'samplingRange', 'var' ),
samplingRange = sigmaRange;
end
if size( data ) ~= size( edge ),
error( 'data and edge must be of the same size' );
end
% parameters
derivedSigmaSpatial = sigmaSpatial / samplingSpatial;
derivedSigmaRange = sigmaRange / samplingRange;
paddingXY = floor( 2 * derivedSigmaSpatial ) + 1;
paddingZ = floor( 2 * derivedSigmaRange ) + 1;
% allocate 3D grid
downsampledWidth = floor( ( inputWidth - 1 ) / samplingSpatial )...
+ 1 + 2 * paddingXY;
downsampledHeight = floor( ( inputHeight - 1 ) / samplingSpatial )...
+ 1 + 2 * paddingXY;
downsampledDepth = floor( edgeDelta / samplingRange ) + 1 + 2 * paddingZ;
gridData = zeros( downsampledHeight, downsampledWidth, downsampledDepth );
gridWeights = zeros( downsampledHeight, downsampledWidth, downsampledDepth );
% compute downsampled indices
[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 );
% ii =
% 0 0 0 0 0
% 1 1 1 1 1
% 2 2 2 2 2
% jj =
% 0 1 2 3 4
% 0 1 2 3 4
% 0 1 2 3 4
% so when iterating over ii( k ), jj( k )
% get: ( 0, 0 ), ( 1, 0 ), ( 2, 0 ), ... (down columns first)
di = round( ii / samplingSpatial ) + paddingXY + 1;
dj = round( jj / samplingSpatial ) + paddingXY + 1;
dz = round( ( edge - edgeMin ) / samplingRange ) + paddingZ + 1;
% perform scatter (there's probably a faster way than this)
% normally would do downsampledWeights( di, dj, dk ) = 1, but we have to
% perform a summation to do box downsampling
for k = 1 : numel( dz ),
dataZ = data( k ); % traverses the image column wise, same as di( k )
if ~isnan( dataZ ),
dik = di( k );
djk = dj( k );
dzk = dz( k );
gridData( dik, djk, dzk ) = gridData( dik, djk, dzk ) + dataZ;
gridWeights( dik, djk, dzk ) = gridWeights( dik, djk, dzk ) + 1;
end
end
% make gaussian kernel
kernelWidth = 2 * derivedSigmaSpatial + 1;
kernelHeight = kernelWidth;
kernelDepth = 2 * derivedSigmaRange + 1;
halfKernelWidth = floor( kernelWidth / 2 );
halfKernelHeight = floor( kernelHeight / 2 );
halfKernelDepth = floor( kernelDepth / 2 );
[gridX, gridY, gridZ] = meshgrid( 0 : kernelWidth - 1,...
0 : kernelHeight - 1, 0 : kernelDepth - 1 );
gridX = gridX - halfKernelWidth;
gridY = gridY - halfKernelHeight;
gridZ = gridZ - halfKernelDepth;
gridRSquared = ( gridX .* gridX + gridY .* gridY ) /...
( derivedSigmaSpatial * derivedSigmaSpatial ) +...
( gridZ .* gridZ ) / ( derivedSigmaRange * derivedSigmaRange );
kernel = exp( -0.5 * gridRSquared );
% convolve
blurredGridData = convn( gridData, kernel, 'same' );
blurredGridWeights = convn( gridWeights, kernel, 'same' );
% divide
% avoid divide by 0, won't read there anyway
blurredGridWeights( blurredGridWeights == 0 ) = -2;
normalizedBlurredGrid = blurredGridData ./ blurredGridWeights;
% put 0s where it's undefined
normalizedBlurredGrid( blurredGridWeights < -1 ) = 0;
% for debugging
% blurredGridWeights( blurredGridWeights < -1 ) = 0; % put zeros back
% upsample
% meshgrid does x, then y, so output arguments need to be reversed
[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 );
% no rounding
di = ( ii / samplingSpatial ) + paddingXY + 1;
dj = ( jj / samplingSpatial ) + paddingXY + 1;
dz = ( edge - edgeMin ) / samplingRange + paddingZ + 1;
% interpn takes rows, then cols, etc
% i.e. size(v,1), then size(v,2), ...
output = interpn( normalizedBlurredGrid, di, dj, dz );
|
github
|
ajit2704/underwater-image-enhancement-master
|
autolevel.m
|
.m
|
underwater-image-enhancement-master/mat/autolevel.m
| 2,027 |
utf_8
|
42c51c0ef7df19d0766b3376c3b1500b
|
function imDst = autolevel(varargin)
[I,lowCut,highCut] =parse_inputs(varargin{:});
[hei,wid,~] = size(I);
PixelAmount = wid * hei;
if size(I,3)==3
[HistRed,~] = imhist(I(:,:,1));
[HistGreen,~] = imhist(I(:,:,2));
[HistBlue,~] = imhist(I(:,:,3));
CumRed = cumsum(HistRed);
CumGreen = cumsum(HistGreen);
CumBlue = cumsum(HistBlue);
minR =find(CumRed>=PixelAmount*lowCut,1,'first');
minG = find(CumGreen>=PixelAmount*lowCut,1,'first');
minB =find(CumBlue>=PixelAmount*lowCut,1,'first');
maxR =find(CumRed>=PixelAmount*(1-highCut),1,'first');
maxG =find(CumGreen>=PixelAmount*(1-highCut),1,'first');
maxB = find(CumBlue>=PixelAmount*(1-highCut),1,'first');
RedMap = linearmap(minR,maxR);
GreenMap = linearmap(minG,maxG);
BlueMap = linearmap(minB,maxB);
imDst = zeros(hei,wid,3,'uint8');
imDst(:,:,1) = RedMap (I(:,:,1)+1);
imDst(:,:,2) = GreenMap(I(:,:,2)+1);
imDst(:,:,3) = BlueMap(I(:,:,3)+1);
else
HistGray = imhist(I(:,:));
CumGray = cumsum(HistRed);
minGray =find(CumGray>=PixelAmount*lowCut,1,'first');
maxGray =find(CumGray>=PixelAmount*(1-highCut),1,'first');
GrayMap = linearmap(minGray,maxGray);
imDst = zeros(hei,wid,'uint8');
imDst(:,:) = GrayMap (I(:,:)+1);
end
%--------------------------------------------------------------------
function map = linearmap(low,high)
map = [0:1:255];
for i=0:255
if(i<low)
map(i+1) = 0;
elseif (i>high)
map(i+1) = 255;
else
map(i+1) =uint8((i-low)/(high-low)*255);
end
end
%-------------------------------------------------------------------
function [I,lowCut,highCut] = parse_inputs(varargin)
narginchk(1,3)
I = varargin{1};
validateattributes(I,{'double','logical','uint8','uint16','int16','single'},{},...
mfilename,'Image',1);
if nargin == 1
lowCut = 0.005;
highCut = 0.005;
elseif nargin == 3
lowCut = varargin{2};
highCut = varargin{3};
else
error(message('images:im2double:invalidIndexedImage','single, or logical.'));
end
|
github
|
ajit2704/underwater-image-enhancement-master
|
saliency_detection.m
|
.m
|
underwater-image-enhancement-master/mat/saliency_detection.m
| 2,484 |
utf_8
|
d13d25afa6342e87bb05929451469b52
|
%---------------------------------------------------------
% Copyright (c) 2009 Radhakrishna Achanta [EPFL]
% Contact: [email protected]
%---------------------------------------------------------
% Citation:
% @InProceedings{LCAV-CONF-2009-012,
% author = {Achanta, Radhakrishna and Hemami, Sheila and Estrada,
% Francisco and S?strunk, Sabine},
% booktitle = {{IEEE} {I}nternational {C}onference on {C}omputer
% {V}ision and {P}attern {R}ecognition},
% year = 2009
% }
%---------------------------------------------------------
% Please note that the saliency maps generated using this
% code may be slightly different from those of the paper.
% This seems to be because the RGB to Lab conversion is
% different from the one used for the results in the C++ code.
% The C++ code is available on the same page as this matlab
% code (http://ivrg.epfl.ch/supplementary_material/RK_CVPR09/index.html)
% One should preferably use the C++ as reference and use
% this matlab implementation mostly as proof of concept
% demo code.
%---------------------------------------------------------
function sm = saliency_detection(img)
%
%---------------------------------------------------------
% Read image and blur it with a 3x3 or 5x5 Gaussian filter
%---------------------------------------------------------
%img = imread('input_image.jpg');%Provide input image path
gfrgb = imfilter(img, fspecial('gaussian', 3, 3), 'symmetric', 'conv');
%---------------------------------------------------------
% Perform sRGB to CIE Lab color space conversion (using D65)
%---------------------------------------------------------
%cform = makecform('srgb2lab', 'whitepoint', whitepoint('d65'));
cform = makecform('srgb2lab');
lab = applycform(gfrgb,cform);
%---------------------------------------------------------
% Compute Lab average values (note that in the paper this
% average is found from the unblurred original image, but
% the results are quite similar)
%---------------------------------------------------------
l = double(lab(:,:,1)); lm = mean(mean(l));
a = double(lab(:,:,2)); am = mean(mean(a));
b = double(lab(:,:,3)); bm = mean(mean(b));
%---------------------------------------------------------
% Finally compute the saliency map and display it.
%---------------------------------------------------------
sm = (l-lm).^2 + (a-am).^2 + (b-bm).^2;
%imshow(sm,[]);
%---------------------------------------------------------
|
github
|
ajit2704/underwater-image-enhancement-master
|
white_balance.m
|
.m
|
underwater-image-enhancement-master/mat/white_balance.m
| 2,152 |
utf_8
|
86ed46f043a7b9801c456cde675ebdda
|
%my own white-balance function, created by Qu Jingwei
function new_image = white_balance3(src_image)
[height,width,dim] = size(src_image);
temp = zeros(height,width);
%transform the RGB color space to YCbCr color space
ycbcr_image = rgb2ycbcr(src_image);
Y = ycbcr_image(:,:,1);
Cb = ycbcr_image(:,:,2);
Cr = ycbcr_image(:,:,3);
%calculate the average value of Cb,Cr
Cb_ave = mean(mean(Cb));
Cr_ave = mean(mean(Cr));
%calculate the mean square error of Cb, Cr
Db = sum(sum(abs(Cb-Cb_ave))) / (height*width);
Dr = sum(sum(abs(Cr-Cr_ave))) / (height*width);
%find the candidate reference white point
%if meeting the following requriments
%then the point is a candidate reference white point
temp1 = abs(Cb - (Cb_ave + Db * sign(Cb_ave)));
temp2 = abs(Cb - (1.5 * Cr_ave + Dr * sign(Cr_ave)));
idx_1 = find(temp1<1.5*Db);
idx_2 = find(temp2<1.5*Dr);
idx = intersect(idx_1,idx_2);
point = Y(idx);
temp(idx) = Y(idx);
count = length(point);
count = count - 1;
%sort the candidate reference white point set with descend value of Y
temp_point = sort(point,'descend');
%get the 10% points of the candidate reference white point set, which is
%closer to the white region, as the reference white point set
n = round(count/10);
white_point(1:n) = temp_point(1:n);
temp_min = min(white_point);
idx0 = find(temp<temp_min);
temp(idx0) = 0;
idx1 = find(temp>=temp_min);
temp(idx1) = 1;
%get the reference white points' R,G,B
white_R = double(src_image(:,:,1)).*temp;
white_G = double(src_image(:,:,2)).*temp;
white_B = double(src_image(:,:,3)).*temp;
%get the averange value of the reference white points' R,G,B
white_R_ave = mean(mean(white_R));
white_G_ave = mean(mean(white_G));
white_B_ave = mean(mean(white_B));
%the maximum Y value of the source image
Ymax = double(max(max(Y))) / 15;
%calculate the white-balance gain
R_gain = Ymax / white_R_ave;
G_gain = Ymax / white_G_ave;
B_gain = Ymax / white_B_ave;
%white-balance correction
new_image(:,:,1) = R_gain * src_image(:,:,1);
new_image(:,:,2) = G_gain * src_image(:,:,2);
new_image(:,:,3) = B_gain * src_image(:,:,3);
new_image = uint8(new_image);
end
|
github
|
atdemarco/svrlsmgui-master
|
svrlsmgui.m
|
.m
|
svrlsmgui-master/svrlsmgui.m
| 62,702 |
utf_8
|
32070ab04e38ec6e5a30f181f8bf30c6
|
function varargout = svrlsmgui(varargin)
% SVRLSMGUI MATLAB code for svrlsmgui.fig
% SVRLSMGUI, by itself, creates a new SVRLSMGUI or raises the existing
% singleton*.
%
% H = SVRLSMGUI returns the handle to a new SVRLSMGUI or the handle to
% the existing singleton*.
%
% SVRLSMGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SVRLSMGUI.M with the given input arguments.
%
% SVRLSMGUI('Property','Value',...) creates a new SVRLSMGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before svrlsmgui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to svrlsmgui_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 svrlsmgui
% Last Modified by GUIDE v2.5 04-Nov-2019 12:48:03
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename,'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @svrlsmgui_OpeningFcn, 'gui_OutputFcn', @svrlsmgui_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 svrlsmgui is made visible.
function svrlsmgui_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject; % Choose default command line output for svrlsmgui
% Do we need to add the functions subdirectory to the path?
pathCell = regexp(path, pathsep, 'split');
myPath = fileparts(mfilename('fullpath'));
if ~any(strcmp(myPath,pathCell))
addpath(myPath)
end
functionsPath = fullfile(myPath,'functions');
if ~any(strcmp(functionsPath,pathCell))
addpath(functionsPath)
end
handles = ConfigureSVRLSMGUIOptions(handles);
handles.details = CheckIfNecessaryFilesAreInstalled(handles);
if handles.details.stats_toolbox && handles.details.spm && handles.details.libsvm
handles = UpdateProgress(handles,'All necessary functions are available...',1);
handles.parameters = GetDefaultParameters(handles);
handles = PopulateGUIFromParameters(handles);
elseif ~handles.details.spm
handles = UpdateProgress(handles,'SPM12 functions not available. Download and/or add SPM12 to the MATLAB path and relaunch the SVRLSMGUI.',1);
handles = DisableAll(handles);
elseif ~handles.details.stats_toolbox && ~handles.details.libsvm
handles = UpdateProgress(handles,'No SVR algorithm available. Install Statistics Toolbox in MATLAB or compile and install libSVM and relaunch the GUI.',1);
handles = DisableAll(handles);
elseif ~handles.details.stats_toolbox && handles.details.libsvm % yes stats toolbox, no libsvm
handles = UpdateProgress(handles,'Only libSVM is available to compute images. MATLAB''s SVM will not be available.',1);
handles.parameters = GetDefaultParameters(handles);
handles = PopulateGUIFromParameters(handles);
elseif handles.details.stats_toolbox && ~handles.details.libsvm % no stats toolbox, yes libsvm
handles = UpdateProgress(handles,'Only MATLAB''s Stats Toolbox is available to compute images. libSVM will not be available.',1);
handles.parameters = GetDefaultParameters(handles);
handles = PopulateGUIFromParameters(handles);
end
handles.parameters.parallelize = handles.details.can_parallelize; % override default
% 0.02 - trying to clean it up to run on a variety of systems - 4/24/17
% 0.03 - first version to be used by other individuals officially - 5/1/17
% 0.04 - 5/2/17
% 0.05 - 7/26/17 - moved to the linux machine, working on improving stability and fixing bugs
% 0.06 - August 2017 - added parallelization, continued development with paper
% 0.07 - September 2017 - summary output, fixed bug in two tail thresholding, public release...
% 0.08 - added diagnostic plot for behavioral nuisance model in summary
% output file (corrplot); added custom support vector scaling
% other than max of the map when backprojecting the analysis
% hyperplane
% 0.10 - January 2018 - fixing reported bugs
% 0.15 - massive code refactoring and implementation of CFWER
handles.parameters.gui_version = 0.15; % version of the the gui
guidata(hObject, handles); % Update handles structure
function handles = DisableAll(handles)
set(get(handles.analysispreferencespanel,'children'),'enable','off')
set(get(handles.covariatespanel,'children'),'enable','off')
set(get(handles.permutationtestingpanel,'children'),'enable','off')
set([handles.viewresultsbutton handles.interrupt_button handles.runanalysisbutton],'Enable','off') % handles.cancelanalysisbutton
set(handles.optionsmenu,'enable','off') % since viewing this menu references parameters that may not be loaded.
msgbox('One or more necessary component is missing from MATLAB''s path. Address the message in the SVRLSMgui window and restart this gui.')
function handles = UpdateCurrentAnalysis(handles,hObject)
changemade = true; % default
switch get(gcbo,'tag') % use gcbo to see what the cbo is and determine what field it goes to -- and to validate
case 'no_map_crossvalidation' % turns off crossvalidation...
handles.parameters.crossval.do_crossval = false;
case 'kfold_map_crossvalidation'
if handles.parameters.useLibSVM
changemade=false;
msgbox('Map crossvalidation not currently supported for libSVM - please switch implementation to MATLAB and try again.')
return
end
answer = inputdlg(sprintf('Enter the numbers of folds for crossvalidation.'), ...
'Number of folds', 1,{num2str(handles.parameters.crossval.nfolds)});
if isempty(answer), return; end % cancel pressed
str = str2num(answer{1});
if isempty(str) || str <= 0 || ~isint(str)
changemade=false;
warndlg('Input must be a positive integer.');
else % update the parameter value.
handles.parameters.crossval.do_crossval = true;
handles.parameters.crossval.method = 'kfold';
handles.parameters.crossval.nfolds = str;
end
case 'hyperparm_quality_report_options'
set(handles.hyperparm_qual_n_folds,'Label',['Folds: ' num2str(handles.parameters.hyperparameter_quality.report.nfolds)])
set(handles.repro_index_subset_percentage,'Label',['Subset %: ' num2str(handles.parameters.hyperparameter_quality.report.repro_ind_subset_pct)])
set(handles.hyperparm_qual_n_replications,'Label',['Replications: ' num2str(handles.parameters.hyperparameter_quality.report.n_replications)])
case 'hyperparm_qual_n_folds'
answer = inputdlg(sprintf('Enter the number of folds for hyperparameter quality testing:'), ...
'Number of folds', 1,{num2str(handles.parameters.hyperparameter_quality.report.nfolds)});
if isempty(answer), return; end % cancel pressed
str = str2num(answer{1});
if isempty(str) || str <= 1 || ~isint(str)
changemade=false;
warndlg('Input must be a positive integer greater than 1.');
else % update the parameter value.
handles.parameters.hyperparameter_quality.report.nfolds = str;
end
case 'repro_index_subset_percentage'
answer = inputdlg('Enter the % of sample to use for computing w-map reproducibility index [0-1]:', ...
'Sample percent', 1,{num2str(handles.parameters.hyperparameter_quality.report.repro_ind_subset_pct)});
if isempty(answer), return; end % cancel pressed
str = str2num(answer{1});
if isempty(str) || str <= 0 || str >= 1 % ~isint(str)
changemade=false;
warndlg('Input must be a value between 0 and 1 (i.e. 0 and 100%).');
else % update the parameter value.
handles.parameters.hyperparameter_quality.report.repro_ind_subset_pct = str;
end
case 'hyperparm_qual_n_replications'
answer = inputdlg(sprintf('Enter the number of replications for hyperparameter quality testing:'), ...
'Number of replications', 1,{num2str(handles.parameters.hyperparameter_quality.report.n_replications)});
if isempty(answer), return; end % cancel pressed
str = str2num(answer{1});
if isempty(str) || str <= 1 || ~isint(str)
changemade=false;
warndlg('Input must be a positive integer greater than 1.');
else % update the parameter value.
handles.parameters.hyperparameter_quality.report.n_replications = str;
end
case 'image_data_options_parent_menu'
set(handles.do_binarize_data_menu_option,'Checked',myif(handles.parameters.imagedata.do_binarize,'on','off'))
case 'do_binarize_data_menu_option'
handles.parameters.imagedata.do_binarize = ~handles.parameters.imagedata.do_binarize;
case 'set_resolution_parent_menu_option'
set(handles.manual_analysis_resolution_menu,'Label',['Manual: ' num2str(handles.parameters.imagedata.resample_to) ' mm'], ...
'checked',myif(handles.parameters.imagedata.do_resample,'on','off'));
set(handles.do_not_resample_images_menu,'Checked',myif(handles.parameters.imagedata.do_resample,'off','on'));
%set(handles.manual_analysis_resolution_menu,'Enable','on') % Until we finish implementation.
case 'do_not_resample_images_menu'
handles.parameters.imagedata.do_resample = false; % turn resampling off.
case 'manual_analysis_resolution_menu'
answer = inputdlg(sprintf('Enter the size in mm for voxels to be resampled to.'), ...
'Resample size (mm)', 1,{num2str(handles.parameters.imagedata.resample_to)});
if isempty(answer), return; end % cancel pressed
str = str2num(answer{1});
if isempty(str) || str <= 0 || ~isint(str)
changemade=false;
warndlg('Input must be a positive integer in millimeters.');
else % update the parameter value.
handles.parameters.imagedata.do_resample = true;
handles.parameters.imagedata.resample_to = str;
end
case 'open_lesion_folder_button'
OpenDirectoryInNativeWindow(handles.parameters.lesion_img_folder)
case 'open_score_file_button'
openFileInSystemViewer(handles.parameters.score_file)
case 'open_output_folder_button'
OpenDirectoryInNativeWindow(handles.parameters.analysis_out_path)
case 'ica_lesion_decompose_option'
handles.parameters.beta.do_ica_on_lesiondata = ~handles.parameters.beta.do_ica_on_lesiondata;
case 'requirements_menu'
case 'search_strategy_options'
set(handles.optimization_iterations_menu_option,'Label',['Iterations: ' num2str(handles.parameters.optimization.iterations)])
set(handles.griddivs_optimization_menu_option,'Label',['Grid Divs: ' num2str(handles.parameters.optimization.grid_divisions)])
return
case 'summary_prediction_menu'
handles.parameters.summary.predictions = ~handles.parameters.summary.predictions;
case 'lsm_method_parent_menu'
set(get(handles.lsm_method_parent_menu,'children'),'checked','off')
if handles.parameters.method.mass_univariate
set(handles.mass_univariate_menu_option,'checked','on')
set(handles.svr_parent_menu,'enable','off')
else
set(handles.multivariate_lsm_option,'checked','on')
set(handles.svr_parent_menu,'enable','on')
end
if handles.details.libsvm || handles.details.stats_toolbox
set(handles.multivariate_lsm_option,'enable','on')
else
handles.parameters.method.mass_univariate = true; % at least...
set(handles.multivariate_lsm_option,'enable','off')
end
case 'mass_univariate_menu_option'
handles.parameters.method.mass_univariate = true;
case 'multivariate_lsm_option'
handles.parameters.method.mass_univariate = false;
case 'svr_parent_menu'
case 'optimization_is_verbose_menu'
handles.parameters.optimization.verbose_during_optimization = ~handles.parameters.optimization.verbose_during_optimization;
case 'summary_lesionoverlap'
handles.parameters.summary.lesion_overlap = ~handles.parameters.summary.lesion_overlap;
case 'summary_paramoptimization'
handles.parameters.summary.hyperparameter_optimization_record = ~handles.parameters.summary.hyperparameter_optimization_record;
case 'summary_create_summary'
handles.parameters.do_make_summary = ~handles.parameters.do_make_summary;
case 'summary_narrative_summary'
handles.parameters.summary.narrative = ~handles.parameters.summary.narrative;
case 'summary_svrbetamap'
handles.parameters.summary.beta_map = ~handles.parameters.summary.beta_map;
case 'summary_voxelwise_thresholded'
handles.parameters.summary.voxelwise_thresholded = ~handles.parameters.summary.voxelwise_thresholded;
case 'summary_clusterwise_thresholded'
handles.parameters.summary.clusterwise_thresholded = ~handles.parameters.summary.clusterwise_thresholded;
case 'summary_cfwerdiagnostics'
handles.parameters.summary.cfwer_diagnostics = ~handles.parameters.summary.cfwer_diagnostics;
case 'model_variablediagnostics'
handles.parameters.summary.variable_diagnostics = ~handles.parameters.summary.variable_diagnostics;
case 'summary_clusterstability'
handles.parameters.summary.cluster_stability = ~handles.parameters.summary.cluster_stability;
case 'summary_parameterassessment'
handles.parameters.summary.parameter_assessment = ~handles.parameters.summary.parameter_assessment;
case 'do_use_cache_menu'
handles.parameters.do_use_cache_when_available = ~handles.parameters.do_use_cache_when_available;
case 'crossval_menu_option_none'
handles.parameters.optimization.crossval.do_crossval = false; % disable crossvalidation.
case 'crossval_menu_option_kfold'
msg = sprintf('Enter the number of folds for cross-validation (default = %d):',handles.parameters.optimization.crossval.nfolds_default);
answer = inputdlg(msg, ...
'Number of folds', 1,{num2str(handles.parameters.optimization.crossval.nfolds)});
warning('bug here - if you click cancel it causes an error - in future, embed the str<=0 and isint within the isempty... and do that with other str2num(answer{1})''s as well')
if isempty(answer), return; end % cancel pressed
str = str2num(answer{1});
if isempty(str) || str <= 0 || ~isint(str)
changemade=false;
warndlg('Input must be a positive integer.');
else % update the parameter value.
handles.parameters.optimization.crossval.do_crossval = true; % enable crossvalidation.
handles.parameters.optimization.crossval.nfolds = str;
end
case 'do_repartition_menu_option' % flip this choice.
handles.parameters.optimization.crossval.repartition = ~handles.parameters.optimization.crossval.repartition;
case 'standardize_menu' % set the value to use if not optimization
vals = {'true','false'};
msg = sprintf('Standardize value (default = %s):',myif(handles.parameters.svr_defaults.standardize,'true','false'));
s = listdlg('PromptString',msg,'SelectionMode','single', ...
'ListString',vals,'InitialValue',myif(handles.parameters.standardize,1,2), ...
'Name','Standardize Parameter','ListSize',[250 80]);
if isempty(s)
changemade=false; % cancelled...
else
handles.parameters.standardize = str2num(vals{s}); % myif(v==1,true,false); % new value.
end
case 'epsilon_menu' % set the value to use if not optimization
msg = sprintf('Enter new value for epsilon (default = %0.2f):',handles.parameters.svr_defaults.epsilon);
% add min and max range - dev1
answer = inputdlg(msg,'Epsilon Parameter',1,{num2str(handles.parameters.epsilon)});
if isempty(answer), return; end % cancel pressed
numval = str2num(answer{1});
if isnumeric(numval) && ~isempty(numval)
handles.parameters.epsilon = numval;
end
% Whether to allow optimization of given hyperparameter
case 'do_optimize_cost_menu'
if ~handles.parameters.optimization.params_to_optimize.cost % then enabling it will prompt for new values...
minmsg = sprintf('Minimum (default = %0.3f):',handles.parameters.optimization.params_to_optimize.cost_range_default(1));
maxmsg = sprintf('Maximum (default = %0.2f):',handles.parameters.optimization.params_to_optimize.cost_range_default(2));
msg = {minmsg,maxmsg};
defaultans = {num2str(handles.parameters.optimization.params_to_optimize.cost_range(1)),num2str(handles.parameters.optimization.params_to_optimize.cost_range(2))};
answer = inputdlg(msg,'Cost Range',1,defaultans);
if isempty(answer), return; end % cancel pressed
if any(cellfun(@isempty,answer)), warndlg('Invalid Cost range.'); return; end
minval = str2num(answer{1}); maxval = str2num(answer{2});
if ~all([isnumeric(minval) isnumeric(maxval)]), warndlg('Cost range values must be numbers.'); return; end
if ~all([minval maxval] > 0), warndlg('Cost range values must be positive.'); return; end
handles.parameters.optimization.params_to_optimize.cost_range = sort([minval maxval]);
end
handles.parameters.optimization.params_to_optimize.cost = ~handles.parameters.optimization.params_to_optimize.cost;
case 'do_optimize_gamma_menu'
if ~handles.parameters.optimization.params_to_optimize.sigma % then enabling it will prompt for new values...
useLibSVM = handles.parameters.useLibSVM; % for convenience.
parmname = myif(useLibSVM,'Gamma','Sigma'); % depending on what algorithm the user is using.
defaultmin = handles.parameters.optimization.params_to_optimize.sigma_range_default(1);
defaultmax = handles.parameters.optimization.params_to_optimize.sigma_range_default(2);
minmsg = sprintf('Minimum (default = %0.3f):',myif(useLibSVM,sigma2gamma(defaultmin),defaultmin)); % convert to gamma if necessary
maxmsg = sprintf('Maximum (default = %0.2f):',myif(useLibSVM,sigma2gamma(defaultmax),defaultmax)); % convert to gamma if necessary
msg = {minmsg,maxmsg};
oldmin = handles.parameters.optimization.params_to_optimize.sigma_range(1);
oldmax = handles.parameters.optimization.params_to_optimize.sigma_range(2);
defaultans = {num2str(myif(useLibSVM,sigma2gamma(oldmin),oldmin)),num2str(myif(useLibSVM,sigma2gamma(oldmax),oldmax))}; % convert to gamma if necessary
answer = inputdlg(msg,[parmname ' Range'],1,defaultans); % display as gamma if necessary
if isempty(answer), return; end % cancel pressed
if any(cellfun(@isempty,answer)), warndlg(['Invalid ' parmname ' range.']); return; end
minval = str2num(answer{1}); maxval = str2num(answer{2});
if ~all([isnumeric(minval) isnumeric(maxval)]), warndlg([parmname ' range values must be numbers.']); return; end % display as gamma if necessary
if ~all([minval maxval] > 0), warndlg([parmname ' range values must be positive.']); return; end % display as gamma if necessary
handles.parameters.optimization.params_to_optimize.sigma_range = sort([myif(useLibSVM,sigma2gamma(minval),minval) myif(useLibSVM,sigma2gamma(maxval),maxval)]); % convert gamma back to sigma if necessary.
end
handles.parameters.optimization.params_to_optimize.sigma = ~handles.parameters.optimization.params_to_optimize.sigma;
case 'do_optimize_epsilon_menu'
if ~handles.parameters.optimization.params_to_optimize.epsilon % then enabling it will prompt for new values...
minmsg = sprintf('Minimum (default = %0.3f):',handles.parameters.optimization.params_to_optimize.epsilon_range_default(1));
maxmsg = sprintf('Maximum (default = %0.2f):',handles.parameters.optimization.params_to_optimize.epsilon_range_default(2));
msg = {minmsg,maxmsg};
defaultans = {num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(1)),num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(2))};
answer = inputdlg(msg,'Epsilon Range',1,defaultans);
if isempty(answer), return; end % cancel pressed
if any(cellfun(@isempty,answer)), warndlg('Invalid Epsilon range.'); return; end
minval = str2num(answer{1}); maxval = str2num(answer{2});
if ~all([isnumeric(minval) isnumeric(maxval)]), warndlg('Epsilon range values must be numbers.'); return; end
if ~all([minval maxval] > 0), warndlg('Epsilon range values must be positive.'); return; end
handles.parameters.optimization.params_to_optimize.epsilon_range = sort([minval maxval]);
end
handles.parameters.optimization.params_to_optimize.epsilon = ~handles.parameters.optimization.params_to_optimize.epsilon;
case 'do_optimize_standardize_menu'
handles.parameters.optimization.params_to_optimize.standardize = ~handles.parameters.optimization.params_to_optimize.standardize;
% Optimization misc choices
case 'optimization_iterations_menu_option'
answer = inputdlg('Enter a new number of iterations:','Number of optimization iterations',1,{num2str(handles.parameters.optimization.iterations)});
if isempty(answer), return; end % cancel pressed
str = str2num(answer{1});
if isempty(str) || str <= 0 || ~isint(str)
changemade=false;
warndlg('Input must be a positive integer.');
else % update the parameter value.
handles.parameters.optimization.iterations = str;
end
case 'griddivs_optimization_menu_option'
answer = inputdlg('Enter a new number of grid divisions:','Number of optimization grid divisions',1,{num2str(handles.parameters.optimization.grid_divisions)});
if isempty(answer), return; end % cancel pressed
str = str2num(answer{1});
if isempty(str) || str <= 0 || ~isint(str)
changemade=false;
warndlg('Input must be a positive integer.');
else % update the parameter value.
handles.parameters.optimization.grid_divisions = str;
end
% Optimization search strategy choice
case 'random_search_menu_option'
handles.parameters.optimization.search_strategy = 'Random Search';
case 'bayes_optimization_menu_choice'
handles.parameters.optimization.search_strategy = 'Bayes Optimization';
case 'gridsearch_option'
handles.parameters.optimization.search_strategy = 'Grid Search';
% Optimization objective function choice
case 'predictbehavior_optimize_menu_choice' % bayes opt predict behavior
handles.parameters.optimization.objective_function = 'Predict Behavior';
case 'correlation_optimize_menu_choice' % maximum correlation w behavior
handles.parameters.optimization.objective_function = 'Maximum Correlation';
case 'resubloss_optimize_menu_choice'
handles.parameters.optimization.objective_function = 'Resubstitution Loss';
% Whether or not to optimize hyperparameters
case 'no_optimize_menu_choice'
handles.parameters.optimization.do_optimize = false;
case 'current_optimization_menu_option'
handles.parameters.optimization.do_optimize = true; % will use whatever setting is configured.
% Which SVR algorithm to use
case 'use_lib_svm'
handles.parameters.useLibSVM = 1;
handles.parameters.crossval.do_crossval = false; % not currently supported for libsvm...
case 'use_matlab_svr'
handles.parameters.useLibSVM = 0;
case 'save_pre_thresh'
handles.parameters.SavePreThresholdedPermutations = ~handles.parameters.SavePreThresholdedPermutations;
case 'retain_big_binary_file'
handles.parameters.SavePermutationData = ~handles.parameters.SavePermutationData;
case 'save_post_vox_thresh'
handles.parameters.SavePostVoxelwiseThresholdedPermutations = ~handles.parameters.SavePostVoxelwiseThresholdedPermutations;
case 'save_post_clusterwise_thresholded'
handles.parameters.SavePostClusterwiseThresholdedPermutations= ~handles.parameters.SavePostClusterwiseThresholdedPermutations;
case 'save_unthresholded_pmaps_cfwer'
handles.parameters.SaveNullPMapsPreThresholding = ~handles.parameters.SaveNullPMapsPreThresholding;
case 'save_thresholded_pmaps_cfwer'
handles.parameters.SaveNullPMapsPostThresholding = ~handles.parameters.SaveNullPMapsPostThresholding;
case 'retain_big_binary_pval_file'
handles.parameters.SavePermutationPData = ~handles.parameters.SavePermutationPData;
case 'parallelizemenu'
handles.parameters.parallelize = ~handles.parameters.parallelize;
case 'applycovariatestobehaviorcheckbox'
handles.parameters.apply_covariates_to_behavior = get(gcbo,'value');
case 'applycovariatestolesioncheckbox'
handles.parameters.apply_covariates_to_lesion = get(gcbo,'value');
case 'lesionvolumecorrectiondropdown'
contents = get(handles.lesionvolumecorrectiondropdown,'string');
newval = contents{get(handles.lesionvolumecorrectiondropdown,'value')};
handles.parameters.lesionvolcorrection = newval;
case 'hypodirectiondropdown'
contents = get(handles.hypodirectiondropdown,'string');
newval = contents{get(handles.hypodirectiondropdown,'value')};
if find(strcmp(newval,handles.options.hypodirection)) == 3 % Disable two-tails from the GUI
warndlg('Two-tailed hypothesis tests are not available in this version of SVRLSMGUI.')
changemade = false;
else
handles.parameters.tails = newval;
end
case 'addcovariate'
% first, what are we trying to add?
contents = get(handles.potentialcovariateslist,'String');
newcovariate = contents{get(handles.potentialcovariateslist,'Value')};
if strcmp(newcovariate,handles.parameters.score_name) % check if it's our main score name...
warndlg('This variable is already chosen as the main outcome in the analysis. If you''d like to add it as a covariate, remove it from "Score Name."')
changemade = false;
elseif any(strcmp(newcovariate,handles.parameters.control_variable_names)) % only if it's not on our list of covariates already.
warndlg('This variable is already on the list of covariates. You may not add it twice.')
changemade = false;
else % it's new
handles.parameters.control_variable_names{end+1} = newcovariate;
end
case 'removecovariate'
contents = get(handles.potentialcovariateslist,'String'); % what are we trying to remove?
newcovariate = contents{get(handles.potentialcovariateslist,'Value')};
if any(strcmp(newcovariate,handles.parameters.control_variable_names)) % only if it IS on our list!
index_to_remove = strcmp(newcovariate,handles.parameters.control_variable_names);
handles.parameters.control_variable_names(index_to_remove) = [];
else
changemade = false;
end
case 'chooselesionfolderbutton'
folder_name = uigetdir(handles.parameters.lesion_img_folder,'Choose a folder containing lesion files for this analysis.');
if folder_name % if folder_name == 0 then cancel was clicked.
[~,attribs] = fileattrib(folder_name); % we need read access from here.
if attribs.UserRead
handles.parameters.lesion_img_folder = folder_name;
else
warndlg('You do not have read access to the directory you selected for the lesion files. Adjust the permissions and try again.')
changemade = false;
end
else
changemade = false;
end
case 'choosescorefilebutton'
[FileName,PathName] = uigetfile(fullfile(fileparts(handles.parameters.score_file),'*.csv'),'Select a file with behavioral scores.');
if FileName
scorefile_name = fullfile(PathName,FileName);
handles.parameters.score_file = scorefile_name;
handles.parameters.control_variable_names = {}; % also clear covariates...
else % cancel was clicked.
changemade = false;
end
case 'chooseoutputfolderbutton'
folder_name = uigetdir(handles.parameters.analysis_out_path,'Choose a folder in which to save this analysis.');
if folder_name
[~,attribs] = fileattrib(folder_name); % we need read/write access from here.
if attribs.UserRead && attribs.UserWrite
handles.parameters.analysis_out_path = folder_name;
else
warndlg('You do not have read and write access to the directory you selected to save your output. Adjust the permissions and try again.')
changemade = false;
end
else
changemade = false;
end
case 'scorenamepopupmenu' % User has changed the one_score in question...
contents = get(gcbo,'string');
newval = contents{get(gcbo,'value')};
if any(strcmp(newval,handles.parameters.control_variable_names))
warndlg('This variable is already chosen as a covariate. If you''d like to use it as the outcome of interest, remove it as a covariate.')
changemade = false;
else
handles.parameters.score_name = newval;
end
case 'analysisnameeditbox'
handles.parameters.analysis_name = get(gcbo,'string');
case 'lesionthresholdeditbox'
str = str2num(get(gcbo,'string')); %TO ADD: also make sure this doesn''t exceed the number of lesions available in the data
if isempty(str) || ~isint(str)
warndlg('Input must be a positive integer.');
changemade = false;
else % update the parameter value.
handles.parameters.lesion_thresh = str;
end
case 'computebetamapcheckbox'
handles.parameters.beta_map = get(gcbo,'value');
case 'computesensitivitymapcheckbox'
handles.parameters.sensitivity_map = get(gcbo,'value');
case 'cluster_voxelwise_p_editbox'
str = str2num(get(gcbo,'string'));
if isempty(str) || str <= 0 || str >= 1
changemade = false;
warndlg('Input must be a number between 0 and 1.');
else % update the parameter value.
handles.parameters.voxelwise_p = str;
end
case 'clusterwisepeditbox'
str = str2num(get(gcbo,'string'));
if isempty(str) || str <= 0 || str >= 1
warndlg('Input must be a number between 0 and 1.');
changemade = false;
else % update the parameter value.
handles.parameters.clusterwise_p = str;
end
case 'sv_scaling_95th_percentile'
handles.parameters.svscaling = 95;
case 'sv_scaling_99th_percentile'
handles.parameters.svscaling = 99;
case 'maxsvscaling'
handles.parameters.svscaling = 100; % default
case 'npermutationseditbox' % This is voxelwise permutations
str = str2num(get(gcbo,'string'));
if isempty(str) || str<=0 || ~isint(str)
changemade = false;
warndlg('Input must be a positive integer.');
else % update the parameter value.
handles.parameters.PermNumVoxelwise = str;
end
case 'permutationtestingcheckbox' % enable/disable permutation testing.
handles.parameters.DoPerformPermutationTesting = get(gcbo,'value');
case 'do_cfwer_checkbox'
handles.parameters.do_CFWER = get(gcbo,'value');
case 'cfwer_v_value_editbox'
str = str2num(get(gcbo,'string'));
if isempty(str) || str <= 0 || ~isint(str)
changemade=false;
warndlg('Input must be a positive integer.');
else % update the parameter value.
handles.parameters.cfwer_v_value = str; % note that this is cubic millimeters and will later be converted into # voxels (in read_lesioned_images)
end
case 'cfwer_p_value_editbox'
str = str2num(get(gcbo,'string'));
if isempty(str) || str<=0 || str >= 1 % not a valid p value...
changemade=false;
warndlg('Input must be a positive number less than 1.');
else % update the parameter value.
handles.parameters.cfwer_p_value = str;
end
case 'analysismask_menu_option_parent'
if strcmp(handles.parameters.analysis_mask_file,'')
maskstring = 'Select mask...';
else
maskstring = handles.parameters.analysis_mask_file;
end
handles.datamask_to_use_menu_option.Text = maskstring;
if handles.parameters.use_analysis_mask % then populate the menu item and set the checkbox...
handles.do_not_apply_datamask_menu_option.Checked = false;
handles.datamask_to_use_menu_option.Checked = true;
else % don't use mask.
handles.do_not_apply_datamask_menu_option.Checked = true;
handles.datamask_to_use_menu_option.Checked = false;
end
case 'do_not_apply_datamask_menu_option'
handles.parameters.use_analysis_mask = false;
changemade = true;
case 'datamask_to_use_menu_option'
disp('a')
handles.parameters.use_analysis_mask = true;
[FileName,PathName] = uigetfile('*.nii','Select a mask file within which to run the analysis.');
filepath = fullfile(PathName,FileName);
if ~exist(filepath,'file'), return; end
handles.parameters.analysis_mask_file = filepath;
changemade = true;
otherwise
warndlg(['Unknown callback object ' get(gcbo,'tag') ' - has someone modified the code?'])
end
if changemade % then set to not saved...
handles.parameters.is_saved = 0;
end
if ~handles.parameters.is_saved % then the analysis configuration was modified, so it hasn't been completed in its current state.
handles.parameters.analysis_is_completed = 0; % set "is completed" to 0 (in its current state) so the user can click run button, and cannot click show output button.
handles = PopulateGUIFromParameters(handles);
end
guidata(hObject, handles); % Update handles structure
UpdateTitleBar(handles); % update title bar to show if we have any changes made.
function doignore = IgnoreUnsavedChanges(handles)
if ~isfield(handles,'parameters') % something bad probably happened with gui initiation.
doignore = 1;
elseif isfield(handles.parameters,'is_saved') && ~handles.parameters.is_saved % then prompt if the user wants to continue or cancel.
choice = questdlg('If you continue you will lose unsaved changes to this analysis configuration.', 'Unsaved Changes', 'Continue Anyway','Cancel','Cancel');
switch choice
case 'Continue Anyway', doignore = 1;
case 'Cancel', doignore = 0;
end
else % don't hang
doignore = 1;
end
% --- Outputs from this function are returned to the command line.
function varargout = svrlsmgui_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
function newmenu_Callback(hObject, eventdata, handles) %#ok<*DEFNU>
if IgnoreUnsavedChanges(handles)
handles.parameters = GetDefaultParameters(handles);
handles = PopulateGUIFromParameters(handles);
end
function openmenu_Callback(hObject, eventdata, handles)
if IgnoreUnsavedChanges(handles)
[FileName,PathName] = uigetfile('*.mat','Select an SVRLSMGUI parameters file.');
filepath = fullfile(PathName,FileName);
if ~exist(filepath,'file'), return; end
handles = LoadParametersFromSVRLSMFile(handles,hObject,filepath);
end
function closemenu_Callback(hObject, eventdata, handles)
if IgnoreUnsavedChanges(handles)
delete(gcf)
end
function savemenu_Callback(hObject, eventdata, handles)
if exist(handles.parameters.parameter_file_name,'file')
handles = SaveSVRLSMGUIFile(handles,hObject); % do the actual save.
else
saveasmenu_Callback(hObject, eventdata, handles)
end
function saveasmenu_Callback(hObject, eventdata, handles)
if exist(handles.parameters.parameter_file_name,'file')
defaultsavename = handles.parameters.parameter_file_name; % fileparts(handles.parameters.parameter_file_name);
else
defaultsavename = fullfile(pwd,'Unnamed.mat');
end
[file,path] = uiputfile('*.mat','Save SVRLSM GUI parameter file as...',defaultsavename);
if file == 0 % then cancel was pressed
return;
end
handles.parameters.parameter_file_name = fullfile(path,file);
handles = SaveSVRLSMGUIFile(handles,hObject); % do the actual save.
function quitmenu_Callback(hObject, eventdata, handles)
close(gcf) % to trigger close request fcn which handles unsaved changes...
function onlinehelpmenu_Callback(hObject, eventdata, handles)
web('https://github.com/atdemarco/svrlsmgui/wiki')
function figure1_CreateFcn(hObject, eventdata, handles)
function aboutmenu_Callback(hObject, eventdata, handles)
helpstr = ['SVRLSM GUI ' num2str(handles.parameters.gui_version) ', Andrew DeMarco 2017-2018, based on Zhang et al. (2014)'];
helpdlg(helpstr,'About');
function runanalysisbutton_Callback(hObject, eventdata, handles)
[success,handles] = RunAnalysis(hObject,eventdata,handles); % now returns handles 10/26/17
set(handles.runanalysisbutton,'Enable','on') %set(handles.cancelanalysisbutton,'visible','off')
% Re-enable interface...
set(get(handles.permutationtestingpanel,'children'),'enable','on')
set(get(handles.analysispreferencespanel,'children'),'enable','on')
set(get(handles.covariatespanel,'children'),'enable','on')
switch success
case 1 % success
handles.parameters.analysis_is_completed = 1; % Completed...
handles = UpdateProgress(handles,'Analysis has completed successfully.',1);
case 0 % failure
handles.parameters.analysis_is_completed = 2; % Error...
handles = UpdateProgress(handles,'Analysis encountered an error and did not complete...',1);
set(handles.interrupt_button,'enable','off') % disable.
rethrow(handles.error)
case 2 % interrupted
handles.parameters.analysis_is_completed = 2; % Error...
handles = UpdateProgress(handles,'Analysis was interrupted by user...',1);
end
guidata(hObject, handles); % Update handles structure
handles = PopulateGUIFromParameters(handles); % refresh gui so we can enable/disable control variable as necessary.
% Select in the dropdown list the selected item.
function realcovariateslistbox_Callback(hObject, eventdata, handles)
if isempty(get(hObject,'String')), return; end % hack for error
contents = cellstr(get(hObject,'String'));
val = contents{get(hObject,'Value')};
dropdownoptions = get(handles.potentialcovariateslist,'string');
set(handles.potentialcovariateslist,'value',find(strcmp(val,dropdownoptions)))
function optionsmenu_Callback(hObject, eventdata, handles)
yn = {'off','on'};
set(handles.parallelizemenu,'Checked',yn{1+handles.parameters.parallelize}) % is parallelization selected by user?
set(handles.parallelizemenu,'Enable',yn{1+handles.details.can_parallelize}) % can we parallelize on this platform?
function SVscalingmenu_Callback(hObject, eventdata, handles)
children = get(handles.SVscalingmenu,'children');
set(children,'Checked','off')
switch handles.parameters.svscaling
case 100 % these are ordered "backward" seeming, so 3rd is top in list
set(children(3),'Checked','on')
case 99
set(children(2),'Checked','on')
case 95
set(children(1),'Checked','on')
end
function save_perm_data_Callback(hObject, eventdata, handles) % update the subitems with checkboxes
yn = {'off','on'};
set(handles.save_post_clusterwise_thresholded,'Checked',yn{1+handles.parameters.SavePostClusterwiseThresholdedPermutations})
set(handles.save_post_vox_thresh,'Checked',yn{1+handles.parameters.SavePostVoxelwiseThresholdedPermutations})
set(handles.save_pre_thresh,'Checked',yn{1+handles.parameters.SavePreThresholdedPermutations})
% the cfwer files...
set(handles.save_unthresholded_pmaps_cfwer,'Checked',yn{1+handles.parameters.SaveNullPMapsPreThresholding})
set(handles.save_thresholded_pmaps_cfwer,'Checked',yn{1+handles.parameters.SaveNullPMapsPostThresholding})
function svrmenu_Callback(hObject, eventdata, handles)
if handles.parameters.useLibSVM
set(handles.use_lib_svm,'checked','on')
set(handles.use_matlab_svr,'checked','off')
else
set(handles.use_lib_svm,'checked','off')
set(handles.use_matlab_svr,'checked','on')
end
if handles.details.stats_toolbox
set(handles.use_matlab_svr,'enable','on')
else
set(handles.use_matlab_svr,'enable','off')
end
if handles.details.libsvm
set(handles.use_lib_svm,'enable','on')
else
set(handles.use_lib_svm,'enable','off')
end
function cost_menu_Callback(hObject, eventdata, handles)
msg = sprintf('Enter new parameter value for Cost/BoxConstraint (default = %0.1f)',handles.parameters.svr_defaults.cost);
answer = inputdlg(msg,'Cost Parameter',1,{num2str(handles.parameters.cost)});
if isempty(answer), return; end % cancel pressed
numval = str2num(answer{1}); %#ok<*ST2NM>
if isnumeric(numval) && ~isempty(numval)
handles.parameters.cost = numval;
handles.parameters.is_saved = 0;
guidata(hObject, handles);
handles = PopulateGUIFromParameters(handles);
end
function gamma_menu_Callback(hObject, eventdata, handles)
useLibSVM = handles.parameters.useLibSVM; % for convenience.
parmname = myif(useLibSVM,'Gamma','Sigma'); % depending on what algorithm the user is using.
defaultval = handles.parameters.svr_defaults.sigma;
msg = sprintf('Enter new parameter value for %s (default = %0.1f)',parmname,myif(useLibSVM,sigma2gamma(defaultval),defaultval)); % convert to gamma if necessary
oldval = handles.parameters.sigma;
answer = inputdlg(msg,[parmname ' Parameter'],1,{num2str(myif(useLibSVM,sigma2gamma(oldval),oldval))}); % convert to gamma if necessary
if isempty(answer), return; end % cancel pressed
numval = str2num(answer{1});
if isnumeric(numval) && ~isempty(numval)
handles.parameters.sigma = myif(useLibSVM,gamma2sigma(numval),numval); % store as sigma, so convert input gamma to sigma if necessary...
handles.parameters.is_saved = 0;
guidata(hObject, handles);
handles = PopulateGUIFromParameters(handles);
end
function open_batch_job_Callback(hObject, eventdata, handles)
folder_name = uigetdir(pwd,'Choose a folder containing .mat config files of your analyses.');
if ~folder_name, return; end % if folder_name == 0 then cancel was clicked.
files = dir(fullfile(folder_name,'*.mat'));
fname = {files.name};
[s,v] = listdlg('PromptString','Choose the analyses to run:','SelectionMode','multi','ListString',fname);
if ~v, return; end % cancelled..
for f = 1:numel(s)
curs=s(f);
curfname = fname{curs};
curfile = fullfile(folder_name,curfname);
% try % so one or more can fail without stopping them all.
handles = UpdateProgress(handles,['Batch: Starting file ' curfname '...'],1);
[success,handles] = RunAnalysisNoGUI(curfile,handles); % second parm, handles, allows access to gui elements, etc.
handles = UpdateProgress(handles,['Batch: Finished file ' curfname '.'],1);
switch success
case 1 % success
handles.parameters.analysis_is_completed = 1; % Completed...
handles = UpdateProgress(handles,['Batch: Finished file successfully ' curfname '.'],1);
case 0 % failure
handles.parameters.analysis_is_completed = 2; % Error...
%handles = UpdateProgress(handles,'Analysis encountered an error and did not complete...',1);
handles = UpdateProgress(handles,['Batch: Analysis encountered an error and did not complete: ' curfname '.'],1);
if isfield(handles,'interrupt_button')
set(handles.interrupt_button,'enable','off') % disable.
end
rethrow(handles.error)
end
% catch
% disp('return from open_batch_job in svrlsmgui() with error')
% msg = ['A batch job specified by file ' fname{curs} ' encountered an error and was aborted.'];
% warning(msg)
% end
end
handles = UpdateProgress(handles,'Batch: All batch jobs done.',1);
function figure1_CloseRequestFcn(hObject, eventdata, handles)
if IgnoreUnsavedChanges(handles), delete(hObject); end
function checkforupdates_Callback(hObject, eventdata, handles)
update_available = check_for_updates;
if ~update_available
msgbox('There are no updates available.')
return
end
choice = questdlg('New updates are available, would you like to download them?','Update SVRLSMGUI','Not now','Update now','Update now');
if strcmp(choice,'Not now'), return, end
get_new_version(handles)
%% callbacks -- replace these in the future.
function controlvariablepopupmenu_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function computebetamapcheckbox_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function computesensitivitymapcheckbox_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function analysisnameeditbox_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function permutation_unthresholded_checkbox_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function permutation_voxelwise_checkbox_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function permutation_largest_cluster_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function progresslistbox_Callback(hObject, eventdata, handles)
function maxsvscaling_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function potentialcovariateslist_Callback(hObject, eventdata, handles)
function viewresultsbutton_Callback(hObject, eventdata, handles)
LaunchResultsDirectory(hObject,eventdata,handles);
function npermutationsclustereditbox_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function parallelizemenu_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function sv_scaling_99th_percentile_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function sv_scaling_95th_percentile_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function debug_menu_Callback(hObject, eventdata, handles)
function use_lib_svm_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function use_matlab_svr_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function interrupt_button_Callback(hObject, eventdata, handles) % attempt to interrupt an ongoing analysis
set(hObject,'enable','off') % so user doesn't click a bunch...
% poolobj = gcp('nocreate'); % < this doesn't stop, it just relaunches the parpool...
% delete(poolobj); % try to stop what's happening if there's parallelization happening
set(gcf,'userdata','cancel')
guidata(hObject, handles); % Update handles structure so it saves...
function no_optimize_menu_choice_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function correlation_optimize_menu_choice_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function resubloss_optimize_menu_choice_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function predictbehavior_optimize_menu_choice_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function optimize_menu_Callback(hObject, eventdata, handles)
set(get(hObject,'Children'),'Checked','off') % uncheck all child menus
cur_optim_string = CurrentOptimString(handles.parameters);
set(handles.current_optimization_menu_option,'Label',cur_optim_string)
opts = [handles.parameters_to_optimize_menu handles.search_strategy_menu_option handles.objective_function_menu_option handles.crossvalidation_parent_menu handles.optimization_is_verbose_menu];
if ~handles.parameters.optimization.do_optimize % then no optimization...
set(handles.no_optimize_menu_choice,'Checked','on')
set(opts,'enable','off') % Visual cue that these don't apply when optimization is off
else
set(handles.current_optimization_menu_option,'Checked','on')
set(opts,'enable','on') % Visual cue that these don't apply when optimization is off
end
if handles.parameters.optimization.verbose_during_optimization
set(handles.optimization_is_verbose_menu,'Checked','on')
end
function current_optimization_menu_option_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function parameters_menu_Callback(hObject, eventdata, handles)
do_opt = handles.parameters.optimization.do_optimize; % for convenience
if do_opt && handles.parameters.optimization.params_to_optimize.cost
label = ['Cost: optimize (' num2str(handles.parameters.optimization.params_to_optimize.cost_range(1)) ' - ' num2str(handles.parameters.optimization.params_to_optimize.cost_range(2)) ')'];
set(handles.cost_menu,'label',label,'enable','off');
else
set(handles.cost_menu,'label',['Cost: ' num2str(handles.parameters.cost) myif(handles.parameters.svr_defaults.cost == handles.parameters.cost,' (default)','')],'enable','on');
end
useLibSVM = handles.parameters.useLibSVM; % for convenience.
parmname = myif(useLibSVM,'Gamma','Sigma'); % depending on what algorithm the user is using.
if do_opt && handles.parameters.optimization.params_to_optimize.sigma
oldmin = handles.parameters.optimization.params_to_optimize.sigma_range(1);
oldmax = handles.parameters.optimization.params_to_optimize.sigma_range(2);
label = [parmname ': optimize (' num2str(myif(useLibSVM,sigma2gamma(oldmin),oldmin)) ' - ' num2str(myif(useLibSVM,sigma2gamma(oldmax),oldmax)) ')'];
set(handles.gamma_menu,'label',label,'enable','off');
else
cursigma = handles.parameters.sigma; % Display as gamma if use libSVM
cursigma = myif(useLibSVM,sigma2gamma(cursigma),cursigma); % Display as gamma if use libSVM
set(handles.gamma_menu,'label',[parmname ': ' num2str(cursigma) myif(handles.parameters.svr_defaults.sigma == handles.parameters.sigma,' (default)','')],'enable','on'); % Display as gamma if use libSVM
end
if do_opt && handles.parameters.optimization.params_to_optimize.epsilon
label = ['Epsilon: optimize (' num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(1)) ' - ' num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(2)) ')'];
set(handles.epsilon_menu,'label',label,'enable','off');
else
set(handles.epsilon_menu,'label',['Epsilon: ' num2str(handles.parameters.epsilon) myif(handles.parameters.svr_defaults.epsilon == handles.parameters.epsilon,' (default)','')],'enable','on');
end
if do_opt && handles.parameters.optimization.params_to_optimize.standardize
set(handles.standardize_menu,'label','Standardize: optimize (yes/no)','enable','off');
else
set(handles.standardize_menu,'label',['Standardize: ' myif(handles.parameters.standardize,'true','false') myif(handles.parameters.svr_defaults.standardize == handles.parameters.standardize,' (default)','')],'enable','on');
end
function epsilon_menu_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function standardize_menu_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
%% Objective function...
function objective_function_menu_option_Callback(hObject, eventdata, handles)
set(get(hObject,'Children'),'Checked','off') % uncheck all child menus
set([handles.predictbehavior_optimize_menu_choice handles.correlation_optimize_menu_choice],'enable','off')
switch handles.parameters.optimization.objective_function
case 'Predict Behavior'
set(handles.predictbehavior_optimize_menu_choice,'Checked','on')
case 'Maximum Correlation'
set(handles.correlation_optimize_menu_choice,'Checked','on')
case 'Resubstitution Loss'
set(handles.resubloss_optimize_menu_choice,'Checked','on')
otherwise
error('Unknown optimization objective function.')
end
%% Search strategy ...
function search_strategy_menu_option_Callback(hObject, eventdata, handles)
set(get(hObject,'Children'),'Checked','off') % uncheck all child menus
switch handles.parameters.optimization.search_strategy
case 'Bayes Optimization'
set(handles.bayes_optimization_menu_choice,'Checked','on')
case 'Grid Search'
set(handles.gridsearch_option,'Checked','on')
case 'Random Search'
set(handles.random_search_menu_option,'Checked','on')
otherwise
error('Unknown optimization objective function.')
end
function parameters_to_optimize_menu_Callback(hObject, eventdata, handles)
set(get(hObject,'children'),'checked','off')
if handles.parameters.optimization.params_to_optimize.cost
label = ['Cost (' num2str(handles.parameters.optimization.params_to_optimize.cost_range(1)) ' - ' num2str(handles.parameters.optimization.params_to_optimize.cost_range(2)) ')'];
set(handles.do_optimize_cost_menu,'label',label,'checked','on')
end
useLibSVM = handles.parameters.useLibSVM; % for convenience.
parmname = myif(useLibSVM,'Gamma','Sigma'); % depending on what algorithm the user is using, show gamma vs sigma...
curmin = handles.parameters.optimization.params_to_optimize.sigma_range(1); % convert to sigma if necessary...
curmax = handles.parameters.optimization.params_to_optimize.sigma_range(2); % convert to sigma if necessary...
label = [parmname ' (' num2str(myif(useLibSVM,sigma2gamma(curmin),curmin)) ' - ' num2str(myif(useLibSVM,sigma2gamma(curmax),curmax)) ')']; % convert to sigma if necessary...
set(handles.do_optimize_gamma_menu,'label',label,'checked',myif(handles.parameters.optimization.params_to_optimize.sigma,'on','off'))
if handles.parameters.optimization.params_to_optimize.epsilon
label = ['Epsilon (' num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(1)) ' - ' num2str(handles.parameters.optimization.params_to_optimize.epsilon_range(2)) ')'];
set(handles.do_optimize_epsilon_menu,'label',label,'checked','on')
end
if handles.parameters.optimization.params_to_optimize.standardize
label = 'Standardize (yes/no)';
set(handles.do_optimize_standardize_menu,'label',label,'checked','on')
end
%set(handles.do_optimize_epsilon_menu,'enable','on')
%dev1
%set(handles.do_optimize_standardize_menu,'enable','on') % there's a problem passing 'Standardize' hyperopt range to bayesopt... so don't allow optimization of it.
%set(get(hObject,'children'),'enable','on')
function crossvalidation_parent_menu_Callback(hObject, eventdata, handles)
set(get(hObject,'children'),'checked','off')
set(handles.crossval_menu_option_kfold,'label',['K-Fold: ' num2str(handles.parameters.optimization.crossval.nfolds) ' folds' myif(handles.parameters.optimization.crossval.nfolds == handles.parameters.optimization.crossval.nfolds_default,' (default)','')])
if ~handles.parameters.optimization.crossval.do_crossval
set(handles.crossval_menu_option_none,'checked','on')
set(handles.do_repartition_menu_option,'enable','off')
else
if handles.parameters.optimization.crossval.repartition
set(handles.do_repartition_menu_option,'checked','on','enable','on')
end
if strcmp(handles.parameters.optimization.crossval.method,'kfold')
set(handles.crossval_menu_option_kfold,'checked','on')
else
error('Unknown crossvalidation option string.')
end
end
function parent_cache_menu_Callback(hObject, eventdata, handles)
yn = {'off','on'};
set(handles.do_use_cache_menu,'Checked',yn{1+handles.parameters.do_use_cache_when_available})
set(handles.retain_big_binary_file,'Checked',yn{1+handles.parameters.SavePermutationData})
set(handles.retain_big_binary_pval_file,'Checked',yn{1+handles.parameters.SavePermutationPData})
function output_summary_menu_Callback(hObject, eventdata, handles)
yn = {'off','on'};
set(handles.summary_create_summary,'checked',yn{1+handles.parameters.do_make_summary});
set(handles.summary_narrative_summary,'checked',yn{1+handles.parameters.summary.narrative});
set(handles.summary_svrbetamap,'checked',yn{1+handles.parameters.summary.beta_map});
set(handles.summary_voxelwise_thresholded,'checked',yn{1+handles.parameters.summary.voxelwise_thresholded});
set(handles.summary_clusterwise_thresholded,'checked',yn{1+handles.parameters.summary.clusterwise_thresholded});
set(handles.summary_cfwerdiagnostics,'checked',yn{1+handles.parameters.summary.cfwer_diagnostics});
set(handles.model_variablediagnostics,'checked',yn{1+handles.parameters.summary.variable_diagnostics});
set(handles.summary_clusterstability,'checked',yn{1+handles.parameters.summary.cluster_stability});
set(handles.summary_parameterassessment,'checked',yn{1+handles.parameters.summary.parameter_assessment});
set(handles.summary_paramoptimization,'checked',yn{1+handles.parameters.summary.hyperparameter_optimization_record});
set(handles.summary_lesionoverlap,'checked',yn{1+handles.parameters.summary.lesion_overlap});
set(handles.summary_prediction_menu,'checked',yn{1+handles.parameters.summary.predictions});
if handles.parameters.do_make_summary
set(get(hObject,'children'),'enable','on')
else
set(get(hObject,'children'),'enable','off')
set(handles.summary_create_summary,'enable','on')
end
disabled_objs = [handles.summary_paramoptimization handles.summary_prediction_menu];
set(disabled_objs,'checked','off','enable','off') % since this is disabled in this first release
function requirements_menu_Callback(hObject, eventdata, handles)
%set(get(handles.requirements_menu,'children'),'checked',false)
set(handles.spm12_installed_menu,'checked',myif(handles.details.spm,'on','off')) % this will not specifically detect spm12 though!
set(handles.libsvm_installed_menu,'checked',myif(handles.details.libsvm,'on','off'))
set(handles.parcomp_toolbox_installed_menu,'checked',myif(handles.details.can_parallelize,'on','off'))
set(handles.stats_toolbox_installed_menu,'checked',myif(handles.details.stats_toolbox,'on','off'))
set(handles.matlab_version_installed_menu,'checked','on') % what's the requirement?
set(get(handles.requirements_menu,'children'),'enable','off')
function beta_options_menu_Callback(hObject, eventdata, handles)
set(handles.ica_lesion_decompose_option,'checked',myif(handles.parameters.beta.do_ica_on_lesiondata,'on','off'))
function crossvalidate_map_parent_menu_Callback(hObject, eventdata, handles)
set(get(hObject,'children'),'checked','off')
% parameters.crossval.do_crossval = false; % by default do not do crossvalidated output...
% parameters.crossval.method = 'kfold';
% parameters.crossval.nfolds = 5;
% parameters.crossval.nfolds_default = parameters.crossval.nfolds;
set(handles.kfold_map_crossvalidation,'label',['K-Fold: ' num2str(handles.parameters.crossval.nfolds) ' folds' myif(handles.parameters.optimization.crossval.nfolds == handles.parameters.crossval.nfolds_default,' (default)','')])
if ~handles.parameters.crossval.do_crossval
set(handles.no_map_crossvalidation,'checked','on')
%set(handles.do_repartition_menu_option,'enable','off')
else
% if handles.parameters.optimization.crossval.repartition
% set(handles.do_repartition_menu_option,'checked','on','enable','on')
% end
if strcmp(handles.parameters.crossval.method,'kfold')
set(handles.kfold_map_crossvalidation,'checked','on')
else
error('Unknown crossvalidation option string.')
end
end
function no_map_crossvalidation_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
function kfold_map_crossvalidation_Callback(hObject, eventdata, handles)
handles = UpdateCurrentAnalysis(handles,hObject);
|
github
|
atdemarco/svrlsmgui-master
|
lm2table.m
|
.m
|
svrlsmgui-master/functions/lm2table.m
| 6,711 |
utf_8
|
91866ec8af0be9264d12a99b61a74344
|
function html = lm2table(mdl,caption)
%% Pretty css ...
% table {
% color: #333;
% font-family: Helvetica, Arial, sans-serif;
% width: 640px;
% /* Table reset stuff */
% border-collapse: collapse; border-spacing: 0;
% }
%
% td, th { border: 0 none; height: 30px; }
%
% th {
% /* Gradient Background */
% background: linear-gradient(#333 0%,#444 100%);
% color: #FFF; font-weight: bold;
% height: 40px;
% }
%
% td { background: #FAFAFA; text-align: center; }
%
% /* Zebra Stripe Rows */
%
% tr:nth-child(even) td { background: #EEE; }
% tr:nth-child(odd) td { background: #FDFDFD; }
%
% /* First-child blank cells! */
% tr td:first-child, tr th:first-child {
% background: none;
% font-style: italic;
% font-weight: bold;
% font-size: 14px;
% text-align: right;
% padding-right: 10px;
% width: 80px;
% }
%
% /* Add border-radius to specific cells! */
% tr:first-child th:nth-child(2) {
% border-radius: 5px 0 0 0;
% }
%
% tr:first-child th:last-child {
% border-radius: 0 5px 0 0;
% }
%
% <style>
% table, th, td {
% border: 1px solid black;
% }
% </style>
% f=figure;a=axes(f);
% mdl.plot('parent',a)
% can we pass a model title in the model object?
% the goal here is to imitate something like Mdl.display in html format...
html = createheaders({'Term','Estimate','SE','T Stat','P Value'});
html = add_coefficient_data(html,mdl);
html = add_gen_lm_info(html,mdl);
html = wrap_w_table_html(html,caption);% finish this off...
function rout = nice_r(rho)
rout = strrep(sprintf('r = %.2f', rho),'0.','.'); % enforce no leading unnecessary 0
function rout = nice_r_nolet(rho)
rout = strrep(sprintf('%.2f', rho),'0.','.'); % enforce no leading unnecessary 0
function pout= nice_p(pval)
pout= myif(pval < .001,'P < .001',strrep(sprintf('P = %.2f', pval),' 0.',' .')); % enforce no leading unnecessary 0
function pout= nice_p_nolet(pval) % ie no p = or p < ...
pout= strrep(myif(pval < .001,'<.001',sprintf('%.3f', pval)),'0.','.'); % enforce no leading unnecessary 0
function html = add_gen_lm_info(html,mdl)
% Add in the num obs, err df, rmse, rsquared, adj rsquared, f--stat ...
[fstat_vs_constant_pval,fstat_vs_constant_fval] = coefTest(mdl);
[dw_P,dw_DW] = mdl.dwtest;
% new rows to add in this cell array...
rows = {add_col(5,'',sprintf('Number of observation: %d, Error degrees freedom: %d',mdl.NumObservations,mdl.DFE)), ...
add_col(5,'',sprintf('Root Mean Square Error: %0.2f',mdl.RMSE)), ...
add_col(5,'',sprintf('R²: %s, Adjusted R²: %s',nice_r_nolet(mdl.Rsquared.Ordinary),nice_r_nolet(mdl.Rsquared.Adjusted))), ...
add_col(5,'',sprintf('F-statistic vs. constant model: %0.2f, %s',fstat_vs_constant_fval,nice_p(fstat_vs_constant_pval))), ...
add_col(5,'',sprintf('Durbin-Watson test for corr. resids, DW = %0.2f, %s',dw_DW,nice_p(dw_P)))};
for r = 1 : numel(rows) % go through and append each...
newrow = rows{r};
%newrow = ['<font size="9">' newrow '</font>'];
html = [html wrap_w_row_html(newrow)]; % add the row wrapper.
end
% Add in the durbin watson test - info from http://www.statisticshowto.com/durbin-watson-test-coefficient/
% The Hypotheses for the Durbin Watson test are:
% H0 = no first order autocorrelation.
% H1 = first order correlation exists.
% (For a first order correlation, the lag is one time unit).
%
% Assumptions are:
% That the errors are normally distributed with a mean of 0.
% The errors are stationary.
%
% The Durbin Watson test reports a test statistic, with a value from 0 to 4, where:
%
% 2 is no autocorrelation.
% 0 to <2 is positive autocorrelation (common in time series data).
% >2 to 4 is negative autocorrelation (less common in time series data).
function html = add_coefficient_data(html,mdl)
ncoeffs = numel(mdl.CoefficientNames);
for c = 1 : ncoeffs
newrow = [];
newrow = add_col(1,newrow,mdl.CoefficientNames{c}); % Coefficient name
newrow = add_col(1,newrow,mdl.Coefficients.Estimate(c)); % Estimate
newrow = add_col(1,newrow,mdl.Coefficients.SE(c)); % SE
newrow = add_col(1,newrow,mdl.Coefficients.tStat(c)); % tStat
newrow = add_col(1,newrow,nice_p_nolet(mdl.Coefficients.pValue(c))); % pValue
html = [html wrap_w_row_html(newrow)]; % add the row wrapper.
end
function rowdat = add_col(span,rowdat,newval)
if span > 1 % e.g., %colspan="2"
spanstring = [' colspan="' num2str(span) '"'];
else
spanstring ='';
end
switch class(newval)
case 'double'
htmladd = sprintf('<td%s>%0.3f</td>',spanstring,newval); % insert span here as necessary
case 'char'
htmladd = sprintf('<td%s>%s</td>',spanstring,newval); % insert span here as necessary
otherwise
error('unknown data class')
end
rowdat = [rowdat htmladd]; % concat and return
% {'(Intercept)'} {'x1'} {'x2'} {'x3'} {'x4'} {'x5'}
%mdl.anova
% SumSq DF MeanSq F pValue
% ______ __ ______ ______ __________
%
% x1 116.77 1 116.77 108.57 2.3674e-17
% x2 490.59 1 490.59 456.14 7.7393e-38
% x3 728.86 1 728.86 677.67 9.3215e-45
% x4 1189 1 1189 1105.5 9.0239e-54
% x5 1832.2 1 1832.2 1703.5 4.9317e-62
% Error 101.1 94 1.0755
% addTerms dwtest plotEffects random
% anova feval plotInteraction removeTerms
% coefCI plot plotPartialDependence step
% coefTest plotAdded plotResiduals
% compact plotAdjustedResponse plotSlice
% disp plotDiagnostics predict
function html = createheaders(headers)
html = [];
for h = 1 : numel(headers)
curheader = headers{h}; % {'Coefficient','Estimate','SE','tStat','pValue'};
html = [html '<th>' curheader '</th>'];
end
html = wrap_w_row_html(html);
function wrapped = wrap_w_row_html(html)
wrapped = [newline '<tr>' newline html newline '</tr>'];
function wrapped = wrap_w_table_html(html,caption)
cap = [newline '<caption>' caption '</caption>' newline];
wrapped = ['<center><table style="width:80%">' cap html '</table></center>'];
|
github
|
atdemarco/svrlsmgui-master
|
step2_parallel.m
|
.m
|
svrlsmgui-master/functions/step2_parallel.m
| 7,925 |
utf_8
|
122e2f4b9e8fd73099f44977fe49aaaa
|
function [parameters,variables,thresholds] = step2_parallel(handles,parameters,variables,thresholds,all_perm_data)
handles = UpdateProgress(handles,'Sorting null betas for each lesioned voxel in the dataset (parallelized).',1);
L = length(variables.m_idx);
tail = parameters.tailshort; % so not a broadcast variable.
ori_beta_vals = variables.ori_beta_vals; % for parfor...
do_CFWER = parameters.do_CFWER; % for parfor...
total_cols = length(variables.m_idx); % note this must be m_idx since the data in our giant file is stored in frames of length m_idx not length l_idx.
nperms = parameters.PermNumVoxelwise;
outpath = variables.output_folder.clusterwise;
pos_thresh_index = thresholds.pos_thresh_index;
neg_thresh_index = thresholds.neg_thresh_index;
onetail_thresh_index = thresholds.onetail_cutoff_index; % for use with compare_real_beta()
% two_tailed_thresh_index = thresholds.two_tailed_thresh_index;
% two_tailed_thresh_index_neg = thresholds.two_tailed_thresh_index_neg;
%% Begin parfeval code
batch_job_size = 500; % this is going to be optimal for different systems/#cores/jobs
njobs = ceil(total_cols/batch_job_size); % gotta round up to capture all indices
%% Schedule the jobs...
p = gcp(); % get current parallel pool
for j = 1 : njobs
this_job_start_index = ((j-1)*batch_job_size) + 1;
this_job_end_index = min(this_job_start_index + batch_job_size-1,total_cols); % need min so we don't go past valid indices
job_indices = this_job_start_index:this_job_end_index;
f(j) = parfeval(p,@parallel_step2_batch_fcn,2,job_indices,all_perm_data,total_cols,tail,ori_beta_vals,onetail_thresh_index,L,nperms,do_CFWER,outpath,neg_thresh_index,pos_thresh_index);
end
alphas = cell(1,njobs); %reserve space - note we want to accumulate in a row here
betamapcutoff = cell(1,njobs); %reserve space - note we want to accumulate in a row here
%% Monitor job progress...
msg = 'Sorting null betas for each lesioned voxel in the dataset (parallelized).';
svrlsm_waitbar(parameters.waitbar,0,msg) % update waitbar progress...
for j = 1 : njobs
check_for_interrupt(parameters) % allow user to interrupt
[idx, jobalphas,jobbetamapcutoffs] = fetchNext(f);
alphas{idx} = jobalphas; % combine these cells afterward
betamapcutoff{idx} = jobbetamapcutoffs; % combine these cells afterward
svrlsm_waitbar(parameters.waitbar,j/njobs) % update waitbar progress...
end
alphas = cell2mat(alphas); % combine afterward
betamapcutoff = cell2mat(betamapcutoff); % combine afterward
%% Now compute beta cutoff values and a pvalue map for the observed betas.
% ...we do this now since we can't index into fields of the 'thresholds'variable in a parfor loop
switch tail
case 'pos' % pos - high scores bad
thresholds.one_tail_pos_alphas = alphas;
thresholds.pos_beta_map_cutoff = betamapcutoff;
case 'neg' % neg - high scores good
thresholds.one_tail_neg_alphas = alphas;
thresholds.neg_beta_map_cutoff = betamapcutoff;
% case 'two' % two-tailed
% thresholds.two_tailed_beta_map_cutoff_pos =two_tailed_beta_map_cutoff_pos;
% thresholds.two_tailed_beta_map_cutoff_neg =two_tailed_beta_map_cutoff_neg;
% thresholds.twotails_alphas = twotails_alphas;
end
%% Now, since we're parallelized, like in step 1, get all those individual files into one big file that we can memmap
if do_CFWER
svrlsm_waitbar(parameters.waitbar,0,'Consolidating null p-map files...');
parameters.outfname_big_p = fullfile(variables.output_folder.clusterwise,['pmu_p_maps_N_' num2str(total_cols) '.bin']);
fileID = fopen(parameters.outfname_big_p,'w');
% this data is output such that each numel(variables.m_idx) contiguous sequential values refer to a voxel across all permutations: [P1V1, P2V1, P3V1, P4V1, ..., npermutations]
for col = 1 : total_cols % can't parallelize this since we need order to be right.
if ~mod(500,col) % to reduce num of calls...
check_for_interrupt(parameters)
svrlsm_waitbar(parameters.waitbar,col/total_cols);
end
curpermfilepath = fullfile(outpath,['pmu_p_map_' num2str(col) '_of_' num2str(total_cols) '.bin']);
cur_perm_data = memmapfile(curpermfilepath,'Format','single');
fwrite(fileID, cur_perm_data.Data,'single');
clear cur_perm_data; % remove memmap from memory.
delete(curpermfilepath); % delete it since we don't want the data hanging around...
end
fclose(fileID); % close big file
svrlsm_waitbar(parameters.waitbar,0,'');
end
%% For each voxel, calculate the beta cutoff and p-value based on our permutation data - also, convert to pvalue volumes if CFWER is requested.
function [alphas,betamapcutoffs] = parallel_step2_batch_fcn(this_job_cols,all_perm_data,total_cols,tail,ori_beta_vals,onetail_thresh_index,L,nperms,do_CFWER,outpath,neg_thresh_index,pos_thresh_index)
alphas = nan(1,numel(this_job_cols)); % pre-allocate spac
betamapcutoffs = nan(1,numel(this_job_cols)); % pre-allocate spac
for jobcolind = 1:numel(this_job_cols) % this is for each voxel in the brain, cutting across permutations
col = this_job_cols(jobcolind);
curcol = extractSlice(all_perm_data,col,L);
observed_beta = ori_beta_vals(col); % original observed beta value.
curcol_sorted = sort(curcol); % Smallest values at the left/top
%% Calculate P values for the single *observed beta map* relative to the null permutation beta volumes.
switch tail
case {'pos','neg'}
[alphas(jobcolind),betamapcutoffs(jobcolind)] = compare_real_beta(observed_beta,curcol,tail,onetail_thresh_index); % we can do both tails without the switch as long as it's one-tailed.
% case 'pos' % high scores bad
% % 'ascend' is the default assort behavior.
% alphas(jobcolind) = sum(observed_beta < curcol_sorted)/nperms;
% %[alphas(jobcolind),betamapcutoffs(jobcolind)] = compare_real_beta(observed_beta,curcol,tail,onetail_thresh_index);
% betamapcutoffs(jobcolind) = curcol_sorted(pos_thresh_index); % so the 9500th at p of 0.05 on 10,000 permutations
% case 'neg' % high scores good
% alphas(jobcolind) = sum(observed_beta > curcol_sorted)/nperms;
% %[alphas(jobcolind),betamapcutoffs(jobcolind)] = compare_real_beta(observed_beta,curcol,tail,onetail_thresh_index);
% betamapcutoffs(jobcolind) = curcol_sorted(neg_thresh_index); % so the 500th at p of 0.05 on 10,000 permutations
case 'two' % two-tailed...
warning('Check that these tails are right after code refactor') % ad 2/14/18
% % two_tailed_beta_map_cutoff_pos(col) = curcol_sorted(two_tailed_thresh_index); % 250...
% % two_tailed_beta_map_cutoff_neg(col) = curcol_sorted(two_tailed_thresh_index_neg); % 9750...
% % twotails_alphas(col) = sum(abs(observed_beta) > abs(curcol_sorted))/numel(curcol_sorted); % percent of values observed_beta is greater than.
end
% Save this permutation as p values.
if do_CFWER % then we need to make a billion files and combine them like in parallelized step 1...
p_vec = betas2pvals(curcol,tail); % each of these files corresponds to the p values for all the permutations of a single voxel
fileID = fopen(fullfile(outpath,['pmu_p_map_' num2str(col) '_of_' num2str(total_cols) '.bin']),'w');
fwrite(fileID, p_vec,'single');
fclose(fileID);
end
end
|
github
|
atdemarco/svrlsmgui-master
|
generic_hyperopts.m
|
.m
|
svrlsmgui-master/functions/generic_hyperopts.m
| 4,224 |
utf_8
|
cb65bf7a69325a21821ec0c7ce414ec8
|
function results = generic_hyperopts(parameters,variables)
% This attempts to optimize using matlab's default hyperparameter optimization options ...
% because it doesn't use bayesopt, it cannot update the progress bar (not output function)
% For clarity...
lesiondata = variables.lesion_dat;
behavdata = variables.one_score;
%% Configure hyperparam options
params = hyperparameters('fitrsvm',lesiondata,behavdata);
% Turn optimize off for all hyperparams by default
for N = 1:numel(params)
params(N).Optimize = false;
end
% Then turn them on as necessary, and set their ranges from the user analysis config
if parameters.optimization.params_to_optimize.sigma
params(strcmp({params.Name},'KernelScale')).Optimize = true;
params(strcmp({params.Name},'KernelScale')).Range = [parameters.optimization.params_to_optimize.sigma_range];
end
if parameters.optimization.params_to_optimize.cost
params(strcmp({params.Name},'BoxConstraint')).Optimize = true;
params(strcmp({params.Name},'BoxConstraint')).Range = [parameters.optimization.params_to_optimize.cost_range];
end
if parameters.optimization.params_to_optimize.epsilon
params(strcmp({params.Name},'Epsilon')).Optimize = true;
params(strcmp({params.Name},'Epsilon')).Range = [parameters.optimization.params_to_optimize.epsilon_range];
end
if parameters.optimization.params_to_optimize.standardize
params(strcmp({params.Name},'Standardize')).Optimize = true;
end
optimizeropts = resolveoptimizeropts(parameters);
hyperoptoptions = struct('AcquisitionFunctionName','expected-improvement-plus', optimizeropts{:});
% 'Optimizer', resolveoptimizer(parameters)
% 'MaxObjectiveEvaluations',parameters.optimization.iterations, ...
% 'UseParallel',parameters.parallelize, ...
% 'Repartition',parameters.optimization.crossval.repartition, ...
% 'KFold',parameters.optimization.crossval.nfolds, ... %'PlotFcn',[], ...
% 'Verbose',myif(parameters.optimization.verbose_during_optimization,2,0));
% 'OutputFcn',@optim_outputfun); % verbose is either 0 or 2...
% disp('OptimizeHyperparameters')
% params
% disp('HyperparameterOptimizationOptions')
% hyperoptoptions
Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf', 'OptimizeHyperparameters',params, 'HyperparameterOptimizationOptions', hyperoptoptions);
results = Mdl.HyperparameterOptimizationResults;
%
% assignin('base','results',results)
% assignin('base','Mdl',Mdl)
%
%
function optimizeropts = resolveoptimizeropts(parameters)
switch parameters.optimization.search_strategy
case 'Bayes Optimization'
optimchoice = 'bayesopt';
case 'Grid Search'
optimchoice = 'gridsearch';
case 'Random Search'
optimchoice = 'randomsearch';
end
% parameters.optimization.crossval.do_crossval = true
% warning('forcing repartinioning on for testing')
repartitionopt = myif(parameters.optimization.crossval.do_crossval, ...
{'Repartition',parameters.optimization.crossval.repartition},{});
itersornumdivsstr = myif(strcmp(optimchoice,'gridsearch'),'NumGridDivisions','MaxObjectiveEvaluations'); % do we need grid divs or do we need max objective evaluations...?
itersornumdivs = myif(strcmp(optimchoice,'gridsearch'),parameters.optimization.grid_divisions,parameters.optimization.iterations);
parameters.optimization.crossval.do_crossval = true;
nfolds = myif(parameters.optimization.crossval.do_crossval,parameters.optimization.crossval.nfolds,1);
if nfolds == 1 % we'll throw an error... switch back to 5.
nfolds = 5;
warning('Crossvalidation set to on for hyperparam opt.')
end
optimizeropts = {'Optimizer', optimchoice, ...
itersornumdivsstr,itersornumdivs, ...
'UseParallel',parameters.parallelize, ...
repartitionopt{:}, ...
'KFold', nfolds, ...
'Verbose',myif(parameters.optimization.verbose_during_optimization,2,0), ...
'ShowPlots',false};
%optimizeropts{:}
|
github
|
atdemarco/svrlsmgui-master
|
svrlsm_prepare_ica.m
|
.m
|
svrlsmgui-master/functions/svrlsm_prepare_ica.m
| 7,989 |
utf_8
|
1731883379f898e0e583d4ca6325a72e
|
function [parameters,variables] = svrlsm_prepare_ica(parameters,variables)
% We'll decompose the lesion data into ICs... and use percent damage to those ROIs as the lesion data values...
% Reread in each subject in the analysis, the mask, and make concatenated ICA file for fsl
for ni= 1 : variables.SubNum % numel(variables.SubjectID)
fname = [variables.SubjectID{ni}, '.nii'];
fullfname = fullfile(parameters.lesion_img_folder, fname);
svrlsm_waitbar(parameters.waitbar,ni / length(variables.SubjectID),sprintf('Rereading lesion file %s...',fname));
%vo = spm_vol(fullfname); % The true voxel intensities of the jth image are given by: val*V.pinfo(1,j) + V.pinfo(2,j)
%tmp = spm_read_vols(vo);
[hdr,tmp]=read_nifti(fullfname); % cause i dunn how to output 4d files from the spm's header.
tmp(isnan(tmp)) = 0; % Denan the image.
tmp = tmp > 0; % Binarize
Ldat(:,:,:,ni) = uint8(tmp);
check_for_interrupt(parameters)
end
% Make the ica output directory..
mkdir(variables.output_folder.ica)
% Write a 3D mask of ANY lesions!
fname = fullfile(variables.output_folder.ica,'3DAnyLesionMask.nii');
write_nifti(hdr,double(sum(Ldat,4)>0),fname); % double so it's not booleans.
variables.files_created.ica_3D_any_lesion_mask = fname; % so we know we made this file.
% Write out the 4D concatted lesions we'll need for FSL to run melodic...
hdr.dim(1) = 4;
hdr.dim(5) = variables.SubNum;
fname = fullfile(variables.output_folder.ica,'4DConcattedLesionMasks.nii');
write_nifti(hdr,Ldat,fname);
variables.files_created.ica_4d_all_lesions = fname; % so we know we made this file.
variables.output_folder.ica_icadata = fullfile(variables.output_folder.ica,'data.ica');
setup_ica % add the right stuff to the path...
wd=pwd;
cd(variables.output_folder.ica)
[~,cattedfroot]=fileparts(variables.files_created.ica_4d_all_lesions); % ica_concat_file); % -d or --dim should be the number of components, but adding it to the end of the call just causes it to fail and come back...
[~,outmaskfroot]=fileparts(variables.files_created.ica_3D_any_lesion_mask);
%% Compute the ICA decomposition...!
ncomps = 35; % variables.SubNum - 5; % cause nsubs is too many, and nsubs-1 is too many too. will a different "method" allow more components to be deflated?
unix(sprintf(['melodic -i "' cattedfroot '" -v -d ' num2str(ncomps) ' -m "' outmaskfroot '" -a concat --Oall --nobet --report']));
% Write out the component overlaps in 3D...
[max_prob_ic_map_inds,max_prob_ic_map_vals] = write_max_ics(variables.output_folder.ica);
variables.files_created.ica_max_prob_ic_map_inds = max_prob_ic_map_inds;
variables.files_created.ica_max_prob_ic_map_vals = max_prob_ic_map_vals;
cd(wd); % go back to wd...
% now build our ica components - ica has already been run at this point.
%[~,cattedfroot]=fileparts(ica_concat_file);
%icadir = [cattedfroot '.ica'];
buildComponentType = 2;
disp(['Building ICA component type ' num2str(buildComponentType) '.'])
switch buildComponentType
case 1
%% read in the component loadings for each subject
% reports = dir(fullfile(ica_path,icadir,'report','t*.txt'));
% componentData=[];
% for c = 1 : numel(reports)
% tmp =readtable(fullfile(reports(c).folder,reports(c).name));
% componentData(:,c) = tmp.Var1; % first column...
% end
case 2
[~,alllesiondata] = read_nifti(variables.files_created.ica_4d_all_lesions); % ica_concat_file); % check for percent overlap with this...
%% or write_max_ics() output ...
%[~,componentimg]=read_nifti(fullfile(pwd,icadir,'stats','maxprob_ic_map_inds.nii'));
%[~,componentimg]=read_nifti('maxprob_ic_map_inds.nii');
[~,componentimg]=read_nifti(variables.files_created.ica_max_prob_ic_map_inds); % 'maxprob_ic_map_inds.nii');
for s = 1:size(alllesiondata,4)
curlesion = alllesiondata(:,:,:,s);
for component = 1 : max(componentimg(:))
curcomponentmask = componentimg==component;
curcomponent_nvox = sum(curcomponentmask(:));
curlesion_overlap_w_curcomp = curlesion&curcomponentmask;
n_curlesion_overlap_w_curcomp = sum(curlesion_overlap_w_curcomp(:));
tmp = n_curlesion_overlap_w_curcomp / curcomponent_nvox;
% if isnan(tmp)
% variables.SubjectID{s}
% component
% n_curlesion_overlap_w_curcomp
% curcomponent_nvox
% disp('---')
% end
componentData(s,component) = tmp; %#ok<AGROW>
end
end
case 3 % multiply out the probabilities...
% [~,alllesiondata] = read_nifti(ica_concat_file); % check for percent overlap with this...
% componentData=[];
% reports = dir(fullfile(ica_path,icadir,'report','t*.txt'));
% ncomps = numel(reports);
% for c = 1 : ncomps
% [~,curcomponent] = read_nifti(fullfile(ica_path,icadir,'stats',['probmap_' num2str(c) '.nii']));
% curcomponent_maxprob = sum(curcomponent(:)); % let the probabilities sum up without binarizing.
%
% for s = 1 : size(alllesiondata,4)
% curlesion = alllesiondata(:,:,:,s);
% multoutprob = curcomponent(curlesion>0); % just add up the probability values...
% componentData(s,c) = 100 * (sum(multoutprob(:)) / curcomponent_maxprob); % percent damage to this component prob map....
% end
% end
end
% now that we've collected our component data, replace the lesion data matrix...
variables.lesion_dat_voxelwise = variables.lesion_dat;
variables.lesion_dat = componentData; % these are percent damage per component!
variables.l_idx_voxelwise = variables.l_idx;
variables.m_idx_voxelwise = variables.m_idx;
variables.l_idx = variables.l_idx_voxelwise(1:ncomps); % We'll put these back later!
variables.m_idx = variables.l_idx_voxelwise(1:ncomps); % We'll put these back later!
%assignin('base','variables',variables)
%assignin('base','parameters',parameters)
% size(componentData)
% tmp = readtable(lesion_text_file);
% data.lesion_vol = tmp.lesion_vol;
function [max_prob_ic_map_inds,max_prob_ic_map_vals] = write_max_ics(ica_path)
disp('Writing max IC maps')
%wd = '/home/crl/Documents/Projects/svrica/concat_lesions_N=48.ica/stats';
wd = fullfile(ica_path,'4DConcattedLesionMasks.ica','stats');
cd(wd); % gotta go there cause the spaces and stuff in the folder names...
files=dir('prob*.nii');
if numel(files) < 10 % probably need to unzip them...
unix('gunzip *.nii.gz')
files=dir('prob*.nii');
end
for f = 1 : numel(files)
curf = fullfile(files(f).folder,['probmap_' num2str(f) '.nii']);
[hdr,img]=read_nifti(curf);
allimgs(:,:,:,f) = img; %#ok<AGROW>
end
outimg = zeros(size(img));
outimg2 = zeros(size(img));
for x = 1 : size(allimgs,1)
for y = 1 : size(allimgs,2)
for z = 1 : size(allimgs,3)
curvec = squeeze(allimgs(x,y,z,:));
if any(curvec)
[val,ind] = max(curvec);
outimg(x,y,z) = ind;
outimg2(x,y,z) = val;
end
end
end
end
max_prob_ic_map_inds = fullfile(ica_path,'maxprob_ic_map_inds.nii');
write_nifti(hdr,outimg,max_prob_ic_map_inds)
max_prob_ic_map_vals = fullfile(ica_path,'maxprob_ic_map_vals.nii');
write_nifti(hdr,outimg2,max_prob_ic_map_vals)
function setup_ica
setenv('PATH', [getenv('PATH') ':/usr/share/fsl/5.0/bin:/usr/lib/fsl/5.0']);
setenv('LD_LIBRARY_PATH',[getenv('LD_LIBRARY_PATH') ':/usr/lib/fsl/5.0/'])
setenv('FSLOUTPUTTYPE','NIFTI_GZ')
setenv('FSLDIR','/usr/share/fsl/5.0')
|
github
|
atdemarco/svrlsmgui-master
|
step1_notparallel_old.m
|
.m
|
svrlsmgui-master/functions/step1_notparallel_old.m
| 5,199 |
utf_8
|
ab0fe65d23076e5b40c6aac94ecc66fd
|
function [handles,parameters] = step1_notparallel(handles,parameters,variables)
% This is where we'll save our GBs of permutation data output...
parameters.outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);
%% Try to use cache to skip this step by relying on cached permutation data
if can_skip_generating_beta_perms(parameters,variables)
warndlg('Relying on cached data not fully supported/reliable yet.')
error('This is not supported')
handles = UpdateProgress(handles,'Using cached beta map permutation data...',1);
return
else
handles = UpdateProgress(handles,'Computing beta map permutations (not parallelized)...',1);
svrlsm_waitbar(parameters.waitbar,0,'Computing beta permutations...');
end
%% If we got here then we need to generate the permutation data
fileID = fopen(parameters.outfname_big,'w');
for PermIdx=1:parameters.PermNumVoxelwise
check_for_interrupt(parameters)
% random permute subjects order for this permutation.
trial_score = variables.one_score(randperm(length(variables.one_score)));
% Which package to use to compute SVM solution
if parameters.useLibSVM % then use libSVM ...
% box = myif(parameters.optimization.do_optimize & parameters.optimization.params_to_optimize.cost, parameters.optimization.best.cost, parameters.cost);
% gamma = myif(parameters.optimization.do_optimize & parameters.optimization.params_to_optimize.sigma, sigma2gamma(parameters.optimization.best.sigma), sigma2gamma(parameters.sigma)); % now derive from sigma...
% epsilon = myif(parameters.optimization.do_optimize & parameters.optimization.params_to_optimize.epsilon, parameters.optimization.best.epsilon, parameters.epsilon);
% libsvmstring = get_libsvm_spec(box,gamma,epsilon);
hyperparms = hyperparmstruct(parameters);
libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % Standardization is already applied.
m = svmtrain(trial_score,sparse(variables.lesion_dat),libsvmstring); %#ok<SVMTRAIN>
else % otherwise use MATLAB...
if PermIdx == 1
variables.orig_one_score = variables.one_score; % store this.
end
variables.one_score = trial_score; % this is so we can use the same ComputeMatlabSVRLSM function :)
[m,~,~] = ComputeMatlabSVRLSM(parameters,variables); % ComputeMatlabSVRLSM will utilize our optimized parameters if available...
if PermIdx == parameters.PermNumVoxelwise % put it back after we've done all permutations...
variables.one_score = variables.orig_one_score; % restore this.
end
end
% Compute the beta map
% if parameters.useLibSVM
% alpha = m.sv_coef';
% SVs = m.SVs;
% else % MATLAB's version.
% alpha = m.Alpha';
% SVs = m.SupportVectors;
% end
%
% Compute the beta map
alpha = m.(myif(parameters.useLibSVM,'sv_coef','Alpha'))'; % note dynamic field reference
SVs = m.(myif(parameters.useLibSVM,'SVs','SupportVectors')); % note dynamic field reference
pmu_beta_map = variables.beta_scale * alpha * SVs;
tmp_map = zeros(variables.vo.dim(1:3)); % make a zeros template....
tmp_map(variables.l_idx) = pmu_beta_map;
pmu_beta_map = tmp_map(variables.m_idx).';
% Save this permutation to our single giant file.
fwrite(fileID, pmu_beta_map,'single');
if ~mod(PermIdx,20) % update every 20 indices...
% Display progress.
% elapsed_time = toc;
% remain_time = round(elapsed_time * (parameters.PermNumVoxelwise - PermIdx)/(PermIdx));
% remain_time_h = floor(remain_time/3600);
% remain_time_m = floor((remain_time - remain_time_h*3600)/60);
% remain_time_s = floor(remain_time - remain_time_h*3600 - remain_time_m*60);
% prompt_str = sprintf('Permutation %d/%d: Est. remaining time: %dh %dh %ds', PermIdx, parameters.PermNumVoxelwise, remain_time_h, remain_time_m,remain_time_s);
prompt_str = get_step1_prog_string(PermIdx,parameters);
svrlsm_waitbar(parameters.waitbar,PermIdx/parameters.PermNumVoxelwise,prompt_str);
end
end
svrlsm_waitbar(parameters.waitbar,0,''); % clear
fclose(fileID); % close the pmu data output file.
function prompt_str = get_step1_prog_string(PermIdx,parameters)
elapsed_time = toc;
remain_time = round(elapsed_time * (parameters.PermNumVoxelwise - PermIdx)/(PermIdx));
remain_time_h = floor(remain_time/3600);
remain_time_m = floor((remain_time - remain_time_h*3600)/60);
remain_time_s = floor(remain_time - remain_time_h*3600 - remain_time_m*60);
prompt_str = sprintf('Permutation %d/%d: Est. remaining time: %dh %dh %ds', PermIdx, parameters.PermNumVoxelwise, remain_time_h, remain_time_m,remain_time_s);
|
github
|
atdemarco/svrlsmgui-master
|
step1_notparallel.m
|
.m
|
svrlsmgui-master/functions/step1_notparallel.m
| 5,174 |
utf_8
|
f2d672f41a6a70b48e3d7ed78b5b812a
|
function [handles,parameters] = step1_notparallel(handles,parameters,variables)
% This is where we'll save our GBs of permutation data output...
parameters.outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);
%% Try to use cache to skip this step by relying on cached permutation data
if can_skip_generating_beta_perms(parameters,variables)
warndlg('Relying on cached data not fully supported/reliable yet. Aborting.')
error('This is not supported')
handles = UpdateProgress(handles,'Using cached beta map permutation data...',1);
return
else
handles = UpdateProgress(handles,'Computing beta map permutations (not parallelized)...',1);
svrlsm_waitbar(parameters.waitbar,0,['Computing beta permutations (' myif(parameters.method.mass_univariate,'mass univariate','multivariate') ')...']);
end
%% If we got here then we need to generate the permutation data
fileID = fopen(parameters.outfname_big,'w');
for PermIdx=1:parameters.PermNumVoxelwise
% Random permute subjects order for this permutation.
trial_score = variables.one_score(randperm(length(variables.one_score)));
if parameters.method.mass_univariate % Estimate via mass-univariate
pmu_beta_map = nan(size(variables.lesion_dat,2),1); % reserve space
for vox = 1 : size(variables.lesion_dat,2)
[Q, R] = qr(trial_score, 0); % use the householder transformations to compute the qr factorization of an n by p matrix x.
y = double(variables.lesion_dat(:,vox));% / 10000; % why divide by 10,000?
%betas(vox) = R \ (Q' * y); % equivalent to fitlm's output: lm.Coefficients.Estimate
pmu_beta_map(vox) = R \ (Q' * y); % equivalent to fitlm's output: lm.Coefficients.Estimate
end
else % Estimate via multivariate svr
% Which package to use to compute SVR solution
if parameters.useLibSVM % then use libSVM
hyperparms = hyperparmstruct(parameters);
libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % Standardization is already applied.
m = svmtrain(trial_score,sparse(variables.lesion_dat),libsvmstring); %#ok<SVMTRAIN>
else % use MATLAB
if PermIdx == 1, variables.orig_one_score = variables.one_score; end % store this
variables.one_score = trial_score; % this is so we can use the same ComputeMatlabSVRLSM function :)
[m,w,~] = ComputeMatlabSVRLSM(parameters,variables); % ComputeMatlabSVRLSM will utilize our optimized parameters if available...
if PermIdx == parameters.PermNumVoxelwise, variables.one_score = variables.orig_one_score; end % restore this once we're done all our permutations
end
% Compute the beta map here (but only if we didn't already compute it already by necessity via crossvalidation)
if ~parameters.crossval.do_crossval % conditional added to support crossvalidated betamap option in June 2019
alpha = m.(myif(parameters.useLibSVM,'sv_coef','Alpha'))'; % note dynamic field reference
SVs = m.(myif(parameters.useLibSVM,'SVs','SupportVectors')); % note dynamic field reference
pmu_beta_map = variables.beta_scale * alpha * SVs;
else % use pre-computed (and averaged) beta map(s) -- this should only be available with svr in matlab specifically (not mass univariate, and not libsvm right now)
pmu_beta_map = w; % here contains an average of the crossvalidated fold models' beta values, so we don't have to scale or do anything here, it's already all done in the ComputeMatlabSVRLSM() function
end
end
tmp_map = zeros(variables.vo.dim(1:3)); % make a zeros template....
tmp_map(variables.l_idx) = pmu_beta_map;
pmu_beta_map = tmp_map(variables.m_idx).';
% Save this permutation to our single giant file.
fwrite(fileID, pmu_beta_map,'single');
check_for_interrupt(parameters)
if ~mod(PermIdx,20) % update every 20 indices - Display progress.
prompt_str = get_step1_prog_string(PermIdx,parameters);
svrlsm_waitbar(parameters.waitbar,PermIdx/parameters.PermNumVoxelwise,prompt_str);
end
end
svrlsm_waitbar(parameters.waitbar,0,''); % clear
fclose(fileID); % close the pmu data output file.
% The string we print saying the progress.
function prompt_str = get_step1_prog_string(PermIdx,parameters)
elapsed_time = toc;
remain_time = round(elapsed_time * (parameters.PermNumVoxelwise - PermIdx)/(PermIdx));
remain_time_h = floor(remain_time/3600);
remain_time_m = floor((remain_time - remain_time_h*3600)/60);
remain_time_s = floor(remain_time - remain_time_h*3600 - remain_time_m*60);
prompt_str = sprintf('Permutation %d/%d: Est. remaining time: %dh %dm %ds', PermIdx, parameters.PermNumVoxelwise, remain_time_h, remain_time_m,remain_time_s);
|
github
|
atdemarco/svrlsmgui-master
|
build_and_write_pmaps.m
|
.m
|
svrlsmgui-master/functions/build_and_write_pmaps.m
| 10,054 |
utf_8
|
a98d12f50beab6567543d822657e3661
|
function [thresholded,variables] = build_and_write_pmaps(options,parameters,variables,thresholds)
switch parameters.tailshort % parameters.tails
case 'pos' % options.hypodirection{1} % One-tailed positive tail... high scores BAD
[thresholded,variables] = write_p_maps_pos_tail(parameters,variables,thresholds);
case 'neg' % options.hypodirection{2} % One-tailed negative tail... high scores GOOD
[thresholded,variables] = write_p_maps_neg_tail(parameters,variables,thresholds);
case 'two' % options.hypodirection{3} % Both tails..
[thresholded,variables] = write_p_maps_two_tailed(parameters,variables,thresholds);
end
function [thresholded,variables] = write_p_maps_pos_tail(parameters,variables,thresholds)
if parameters.do_CFWER % note that the parameters struct isn't returned by this function so nothing changes outside this function scope
parameters.voxelwise_p = variables.cfwerinfo.cfwer_single_pval_answer;
end
write_z = true;
%% Create and write the un-inverted versions...
thresholded.thresholded_pos = zeros(variables.vo.dim(1:3)); % make a zeros template....
thresholded.thresholded_pos(variables.m_idx) = thresholds.one_tail_pos_alphas;
% Write unthresholded P-map for the positive tail
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P map.nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);
variables.files_created.unthresholded_pmap = variables.vo.fname;
% % Calculate z map
%zmap = p2z(thresholded.thresholded_pos); % note the call to p2z() here
% calculate z map
zmap = zeros(variables.vo.dim(1:3));
if write_z
zmap(variables.m_idx) = p2z(thresholds.one_tail_pos_alphas); % so we don't try to convert 0 values in the rest of the brain volume...
% write out unthresholded positive Z map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded Z map.nii');
svrlsmgui_write_vol(variables.vo, zmap);
variables.files_created.unthresholded_zmap = variables.vo.fname;
end
% Now write out the thresholded P-map for the positive tail
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded P map.nii');
zero_these_vox = thresholded.thresholded_pos > parameters.voxelwise_p;
thresholded.thresholded_pos(zero_these_vox) = 0; % zero out voxels whose values are greater than p
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);
variables.files_created.thresholded_pmap = variables.vo.fname;
if write_z
% write out thresholded positive Z map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded Z map.nii');
zmap(zero_these_vox) = 0; % apply the mask we calculated like 20 lines ago
svrlsmgui_write_vol(variables.vo, zmap);
variables.files_created.thresholded_zmap = variables.vo.fname;
end
%% Create and write the inverted versions.
thresholded.thresholded_pos = zeros(variables.vo.dim(1:3)); % make a zeros template....
thresholded.thresholded_pos(variables.m_idx) = 1 - thresholds.one_tail_pos_alphas;
% Write unthresholded P-map for the positive tail
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P map (inv).nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);
variables.files_created.unthresholded_pmap_inv = variables.vo.fname;
% Now write out the thresholded P-map for the positive tail
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded P map (inv).nii');
thresholded.thresholded_pos(thresholded.thresholded_pos < (1-parameters.voxelwise_p)) = 0; % zero out sub-threshold p value voxels (note the 1-p)
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);
variables.files_created.thresholded_pmap_inv = variables.vo.fname;
function [thresholded,variables] = write_p_maps_neg_tail(parameters,variables,thresholds)
if parameters.do_CFWER % note that the parameters struct isn't returned by this function so nothing changes outside this function scope
parameters.voxelwise_p = variables.cfwerinfo.cfwer_single_pval_answer;
end
write_z = true;
%% Create and write the non-inverted versions.
thresholded.thresholded_neg = zeros(variables.vo.dim(1:3)); % make a zeros template....
thresholded.thresholded_neg(variables.m_idx) = thresholds.one_tail_neg_alphas;
% write out unthresholded negative p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P map.nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);
variables.files_created.unthresholded_pmap = variables.vo.fname;
% calculate z map
zmap = zeros(variables.vo.dim(1:3));
if write_z
zmap(variables.m_idx) = p2z(thresholds.one_tail_neg_alphas); % so we don't try to convert 0 values in the rest of the brain volume...
% write out unthresholded negative Z map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded Z map.nii');
svrlsmgui_write_vol(variables.vo, zmap);
variables.files_created.unthresholded_zmap = variables.vo.fname;
end
% write out thresholded negative p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded P map.nii');
zero_these_vox = thresholded.thresholded_neg > parameters.voxelwise_p;
thresholded.thresholded_neg(zero_these_vox) = 0; % zero out voxels whose values are greater than p
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);
variables.files_created.thresholded_pmap = variables.vo.fname;
if write_z
% write out thresholded negative Z map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded Z map.nii');
zmap(zero_these_vox) = 0; % apply the mask we calculated like 20 lines ago
svrlsmgui_write_vol(variables.vo, zmap);
variables.files_created.thresholded_zmap = variables.vo.fname;
end
%% Create and write the inverted versions (P maps, not Z maps)
thresholded.thresholded_neg = zeros(variables.vo.dim(1:3)); % make a zeros template....
thresholded.thresholded_neg(variables.m_idx) = 1 - thresholds.one_tail_neg_alphas;
% write out unthresholded negative p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P map (inv).nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);
variables.files_created.unthresholded_pmap_inv = variables.vo.fname;
% write out thresholded negative p map
thresholded.thresholded_neg(thresholded.thresholded_neg < (1-parameters.voxelwise_p)) = 0; % zero out subthreshold p value voxels (note 1-p)
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Voxelwise thresholded P map (inv).nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);
variables.files_created.thresholded_pmap_inv = variables.vo.fname;
function [thresholded,variables] = write_p_maps_two_tailed(parameters,variables,thresholds)
error('There should be an abs() around here but there isn''t, make sure this works right, especially with CFWER')
if parameters.do_CFWER % note that the parameters struct isn't returned by this function so nothing changes outside this function scope
parameters.voxelwise_p = variables.cfwerinfo.cfwer_single_pval_answer.onetail.pos;
end
thresholded.thresholded_twotails = zeros(variables.vo.dim(1:3)); % make a zeros template....
if parameters.invert_p_map_flag % it's already inverted...
thresholded.thresholded_twotails(variables.m_idx) = thresholds.twotails_alphas;
% write out unthresholded p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values (inv).nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotails);
% variables.files_created.unthresholded_pmap{1} = variables.vo.fname;
% variables.files_created.unthresholded_pmap{2} = variables.vo.fname;
% write out thresholded p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');
thresholded.thresholded_twotails(thresholded.thresholded_twotails < (1-(parameters.voxelwise_p/2))) = 0; % zero out subthreshold p value voxels (note 1-p)
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotails);
% variables.files_created.unthresholded_pmap{1} = variables.vo.fname;
% variables.files_created.unthresholded_pmap{2} = variables.vo.fname;
warning('add writing z map thresholded and unthresholded here')
else
thresholded.thresholded_twotails(variables.m_idx) = 1 - thresholds.twotails_alphas;
% write out unthresholded p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values.nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotails);
% variables.files_created.unthresholded_pmap{1} = variables.vo.fname;
% variables.files_created.unthresholded_pmap{2} = variables.vo.fname;
warning('add writing z map thresholded and unthresholded here')
% write out thresholded p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');
thresholded.thresholded_twotails(thresholded.thresholded_twotails > (parameters.voxelwise_p/2)) = 0; % zero out supra-alpha p value voxels
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotails);
% variables.files_created.unthresholded_pmap{1} = variables.vo.fname;
% variables.files_created.unthresholded_pmap{2} = variables.vo.fname;
end
|
github
|
atdemarco/svrlsmgui-master
|
svrlsm_bayesopt.m
|
.m
|
svrlsmgui-master/functions/svrlsm_bayesopt.m
| 15,549 |
utf_8
|
2215a0e43cc0ed243fb6b154de1f8378
|
function results = svrlsm_bayesopt(parameters,variables)
% For clarity...
lesiondata = variables.lesion_dat;
behavdata = variables.one_score;
%% Which parameters to optimize and ranges to optim over
params = hyperparameters('fitrsvm',lesiondata,behavdata);
standrange = params(strcmp('Standardize',{params.Name})).Range;
sigma = optimizableVariable('sigma',parameters.optimization.params_to_optimize.sigma_range,'Transform','log','optimize',parameters.optimization.params_to_optimize.sigma); % gamma ~ sigma...
box = optimizableVariable('box',parameters.optimization.params_to_optimize.cost_range,'Transform','log','optimize',parameters.optimization.params_to_optimize.cost); % cost == boxconstraint
epsilon = optimizableVariable('epsilon',parameters.optimization.params_to_optimize.epsilon_range,'Transform','none','optimize',parameters.optimization.params_to_optimize.epsilon);
%standardize = optimizableVariable('standardize',standrange,'Transform','none','Type','categorical','optimize',parameters.optimization.params_to_optimize.standardize);
%standrange = [0 1]; % [true false]; % {categorical(true), categorical(false)}; % ?!
standardize = optimizableVariable('standardize',standrange,'Transform','none','Type','categorical','optimize',parameters.optimization.params_to_optimize.standardize);
svrlsm_waitbar(parameters.waitbar,0,['Hyperparameter optimization (bayesopt: ' parameters.optimization.objective_function ')...'])
% Has the user requested cross-validation or not?
% if parameters.optimization.crossval.do_crossval
% % Switch definition of anonymous function for objective function for optimization
% switch parameters.optimization.objective_function
% case 'Predict Behavior'
% minfn = @(x) predict_behavior_w_crossval(x,lesiondata,behavdata,parameters);
% case 'Maximum Correlation'
% minfn = @(x) max_correlation_w_crossval(x,lesiondata,behavdata,parameters);
% case 'Resubstitution Loss'
% minfn = @(x) resubstitution_loss_w_crossval(x,lesiondata,behavdata,parameters);
% otherwise
% error(['Unknown objective function string: ' parameters.optimization.objective_function])
% end
%
% % Start with this partition -- it will be replaced each call to the objective function if Repartition is 'true'
% parameters.initialPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);
%
% %results = bayesopt(minfn,[sigma,box], ...
% results = bayesopt(minfn,[gamma,box,epsilon,standardize], ...
% 'IsObjectiveDeterministic',false,'AcquisitionFunctionName','expected-improvement-plus', ...
% 'MaxObjectiveEvaluations',parameters.optimization.iterations, 'UseParallel',parameters.parallelize, ...
% 'PlotFcn',[],'Verbose',0);
%
% else % No cross-validation was requested, so run these without cross-validation...
%
% % Switch definition of anonymous function for objective function for optimization
% switch parameters.optimization.objective_function
% case 'Predict Behavior'
% minfn = @(x) predict_behavior(x,lesiondata,behavdata,parameters);
% %minfn = @(x)sqrt(sum((behavdata - resubPredict(fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.box,'KernelScale',x.sigma,'Epsilon',parameters.epsilon,'Standardize',false,'true')))).^2);
% case 'Maximum Correlation'
% minfn = @(x) max_correlation(x,lesiondata,behavdata,parameters);
% case 'Resubstitution Loss'
% minfn = @(x) resubstitution_loss(x,lesiondata,behavdata,parameters);
% otherwise
% error(['Unknown objective function string: ' parameters.optimization.objective_function])
% end
%
% results = bayesopt(minfn,[sigma,box], ... % ,epsilon,standardize], ... % the parameters we're going to try to optimize
% 'IsObjectiveDeterministic',true,'AcquisitionFunctionName','expected-improvement-plus', ...
% 'MaxObjectiveEvaluations',parameters.optimization.iterations, 'UseParallel',parameters.parallelize, ...
% 'PlotFcn',[],'Verbose',0,'OutputFcn',@optim_outputfun);
%
% end
%%
% % Start with this partition -- it will be replaced each call to the objective function if Repartition is 'true'
parameters.initialPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);
% assignin('base','lesiondata',lesiondata)
% error('s')
minfn = @(x)combined_bayesopt_objective_functions3(x,sparse(lesiondata),behavdata,parameters);
results = bayesopt(minfn,[sigma box epsilon standardize], ...
'IsObjectiveDeterministic',false, ... % parameters.optimization.crossval.do_crossval, ...
'AcquisitionFunctionName','expected-improvement-plus', ... % 'ExplorationRatio', 0.7, ... % 0.5 default
'MaxObjectiveEvaluations',parameters.optimization.iterations, ...
'UseParallel',parameters.parallelize, ...
'NumCoupledConstraints', 1, 'AreCoupledConstraintsDeterministic', false, ... % ~parameters.optimization.crossval.do_crossval, ... % if crossval, then it's not deterministic.
'PlotFcn',[],'OutputFcn',@optim_outputfun, ...
'Verbose',myif(parameters.optimization.verbose_during_optimization,2,0)); % verbose is either 0 or 2...
svrlsm_waitbar(parameters.waitbar,0,''); % clear this.
% %% Objective function: Maximum correlation - no cross-validation
% function objective = max_correlation(x,lesiondata,behavdata,parameters)
% svrtype = myif(parameters.useLibSVM,'libSVM','MATLAB');
% switch svrtype
% case 'libSVM'
% error('transform gamma to sigma here?')
% m = svmtrain(behavdata,sparse(lesiondata),get_libsvm_spec(x.cost,x.gamma,parameters.epsilon));% note get_libsvm_spec() function
% predicted = svmpredict(behavdata, sparse(lesiondata), m, '-q');
% case 'MATLAB' % since we take care of standardization in preprocessing
% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.box,'KernelScale',x.sigma,'Epsilon',parameters.epsilon,'Standardize',false);
% predicted = predict(Mdl,lesiondata);
% end
% corrvals = corrcoef(predicted,behavdata); % compute the correlation...
% objective = -1 * corrvals(2,1); % grab the r. --- and multiply by negative one since we want to maximize the value...
%
% %% Objective function: Predict behavior - no cross-validation
function objective = predict_behavior(x,lesiondata,behavdata,parameters)
% svrtype = myif(parameters.useLibSVM,'libSVM','MATLAB');
% switch svrtype
% case 'libSVM'
% error('transform gamma to sigma here?')
% m = svmtrain(behavdata,sparse(lesiondata),get_libsvm_spec(x.cost,x.gamma,parameters.epsilon));% note get_libsvm_spec() function
% predicted = svmpredict(behavdata, sparse(lesiondata), m, '-q');
% case 'MATLAB' % since we take care of standardization in preprocessing
% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on
% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.sigma,'Standardize',touse.standardize,'Epsilon',touse.epsilon);
Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.cost,'KernelScale',x.sigma,'Standardize',false,'Epsilon',parameters.epsilon);
predicted = predict(Mdl,lesiondata);
% end
difference = behavdata(:) - predicted(:);
mean_abs_diff = mean(abs(difference));
objective = mean_abs_diff; % we want to minimize this value.
%
% %% Objective function: Resubstitution loss - no cross-validation
% function objective = resubstitution_loss(x,lesiondata,behavdata,parameters)
%
% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on
% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.gamma,'Standardize',touse.standardize,'Epsilon',touse.epsilon);
% % Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.box,'KernelScale',x.sigma,'Epsilon',parameters.epsilon,'Standardize',false);
% objective = resubLoss(Mdl);
%
% %% Objective function: Resubstitution loss - with K-fold cross-validation
% function objective = resubstitution_loss_w_crossval(x,lesiondata,behavdata,parameters)
% if parameters.optimization.crossval.repartition
% curPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);
% else
% curPartition = parameters.initialPartition;
% end
%
% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on
% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.gamma,'Standardize',touse.standardize,'Epsilon',touse.epsilon,'CVPartition',curPartition);
%
% % Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',x.box,'KernelScale',x.sigma,'Standardize',false,'Epsilon',parameters.epsilon,'CVPartition', curPartition);
% % myif(parameters.optimization.crossval.repartition,partition,partition.repartition));
%
% objective = kfoldLoss(Mdl);
%
% %% Objective function: Predict behavior - with K-fold cross-validation
% function objective = predict_behavior_w_crossval(x,lesiondata,behavdata,parameters)
% % svrtype = myif(parameters.useLibSVM,'libSVM','MATLAB');
% % switch svrtype
% % case 'libSVM'
% % error('transform gamma to sigma here?')
% % m = svmtrain(behavdata,sparse(lesiondata),get_libsvm_spec(x.cost,x.gamma,parameters.epsilon));% note get_libsvm_spec() function
% % predicted = svmpredict(behavdata, sparse(lesiondata), m, '-q');
% % case 'MATLAB' % since we take care of standardization in preprocessing
%
% if parameters.optimization.crossval.repartition
% curPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);
% else
% curPartition = parameters.initialPartition;
% end
%
% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on
% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.gamma,'Standardize',touse.standardize,'Epsilon',touse.epsilon,'CVPartition',curPartition);
% predicted = kfoldPredict(Mdl);
% % end
% difference = behavdata(:) - predicted(:);
% mean_abs_diff = mean(abs(difference));
% objective = mean_abs_diff; % we want to minimize this value.
%
%
% %% Objective function: Maximum correlation - with K-fold cross-validation
% function objective = max_correlation_w_crossval(x,lesiondata,behavdata,parameters)
% % svrtype = myif(parameters.useLibSVM,'libSVM','MATLAB');
% % switch svrtype
% % case 'libSVM'
% % error('transform gamma to sigma here?')
% % m = svmtrain(behavdata,sparse(lesiondata),get_libsvm_spec(x.cost,x.gamma,parameters.epsilon));% note get_libsvm_spec() function
% % predicted = svmpredict(behavdata, sparse(lesiondata), m, '-q');
% % case 'MATLAB' % since we take care of standardization in preprocessing
% if parameters.optimization.crossval.repartition
% curPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);
% else
% curPartition = parameters.initialPartition.repartition;
% end
% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on
% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.gamma,'Standardize',touse.standardize,'Epsilon',touse.epsilon,'CVPartition',curPartition);
%
% predicted = kfoldPredict(Mdl);
% %end
% corrvals = corrcoef(predicted,behavdata); % compute the correlation...
% objective = -1 * corrvals(2,1); % grab the r. --- and multiply by negative one since we want to maximize the value...
%
% function objective = combined_bayesopt_objective_functions(x,lesiondata,behavdata,parameters)
%
% % hyperparameter values to use for this iteration
% touse = get_cur_optim_iter_parms(x,parameters); % returns constants for parms we're not optimizing on
%
% % add in cross-validation parameters dynamically as necessary...
% crossvalparms = {}; % default
% if parameters.optimization.crossval.do_crossval
% if parameters.optimization.crossval.repartition
% curPartition = cvpartition(behavdata,'k',parameters.optimization.crossval.nfolds);
% else
% curPartition = parameters.initialPartition.repartition;
% end
% crossvalparms ={'CVPartition',curPartition};
% end
%
% Mdl = fitrsvm(lesiondata,behavdata,'KernelFunction','rbf','BoxConstraint',touse.cost,'KernelScale',touse.sigma,'Standardize',touse.standardize,'Epsilon',touse.epsilon,crossvalparms{:}); % 'CVPartition',curPartition);
%
% switch parameters.optimization.objective_function
% case 'Predict Behavior' % embedded conditional of whether we predict or kfoldpredict
% if parameters.optimization.crossval.do_crossval
% predicted = kfoldPredict(Mdl);
% else
% predicted = predict(Mdl,lesiondata);
% end
%
% difference = behavdata(:) - predicted(:);
% mean_abs_diff = mean(abs(difference));
% objective = mean_abs_diff; % we want to minimize this value.
%
% case 'Maximum Correlation' % embedded conditional of whether we predict or kfoldpredict
% if parameters.optimization.crossval.do_crossval
% predicted = kfoldPredict(Mdl);
% else
% predicted = predict(Mdl,lesiondata);
% end
%
% corrvals = corrcoef(predicted,behavdata); % compute the correlation...
% objective = -1 * corrvals(2,1); % grab the r. --- and multiply by negative one since we want to maximize the value...
%
% case 'Resubstitution Loss'
% if parameters.optimization.crossval.do_crossval
% objective = kfoldLoss(Mdl);
% else
% objective = resubLoss(Mdl);
% end
% otherwise
% error(['Unknown objective function string: ' parameters.optimization.objective_function])
% end
%
% function touse = get_cur_optim_iter_parms(x,parameters)
% parms = {'cost','sigma','epsilon','standardize'};
% for f = parms
% if isfield(x,f{1}) % then we're asked to optimize it so return:
% touse.(f{1}) = x.(f{1}); % the dynamic value for each iteration
% else
% touse.(f{1}) = parameters.(f{1}); % or the constant supplied by the user
% end
% end
|
github
|
atdemarco/svrlsmgui-master
|
svrlsm_waitbar.m
|
.m
|
svrlsmgui-master/functions/svrlsm_waitbar.m
| 726 |
utf_8
|
5732f213c7d380dbecbb6ffa4179a9d8
|
function svrlsm_waitbar(waitbar_handles,newval,message)
if isempty(waitbar_handles)
return
end
% if numel(waitbar_handles) ~= 2 % < caused by multiple svrlsmgui's open at once
% error('Too many handles in input array')
% end
set_progress_percent(waitbar_handles(1),newval)
if nargin > 2
set_progress_text(waitbar_handles(2),message)
end
drawnow
% update percent progress
function set_progress_percent(rectangle_handle,newval)
pos = get(rectangle_handle,'position');
pos(3) = 100*newval; %update the width parameter....
set(rectangle_handle,'position',pos)
% update message
function set_progress_text(txt_handle,message)
set(txt_handle,'string',message)
|
github
|
atdemarco/svrlsmgui-master
|
step1_parallel.m
|
.m
|
svrlsmgui-master/functions/step1_parallel.m
| 8,340 |
utf_8
|
9ce154f0ddd002dfff3717ec0effd46d
|
function [handles,parameters] = step1_parallel(handles,parameters,variables)
% This is where we'll save our GBs of permutation data output...
parameters.outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);
%% Try to use cache to skip this step by relying on cached permutation data
if can_skip_generating_beta_perms(parameters,variables)
error('caching disabled, cause it''s not completely supported')
handles = UpdateProgress(handles,'Using cached beta map permutation data...',1); return
else
handles = UpdateProgress(handles,'Computing beta map permutations (parallelized)...',1);
svrlsm_waitbar(parameters.waitbar,0,'Computing beta permutations (parallelized)...');
end
%% If we got here then we need to generate the permutation data
%% Cute way to create the permuted behavioral data... each column is one permutation.
permdata = variables.one_score(cell2mat(cellfun(@(x) randperm(x)',repmat({numel(variables.one_score)},1,parameters.PermNumVoxelwise),'uni',false)));
outpath = variables.output_folder.clusterwise;
totalperms = parameters.PermNumVoxelwise;
hyperparms = hyperparmstruct(parameters);
%% Figure out what parameters we'll be using:
if parameters.useLibSVM
parameters.step1.libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % Standardization is already applied.
tmp.libsvmstring = parameters.step1.libsvmstring;
else % use matlab's -- note the cell array we're creating - it's fancy since later we'll parameters.step1.matlab_svr_parms{:}
parameters.step1.matlab_svr_parms = [{'BoxConstraint', hyperparms.cost, ...
'KernelScale', hyperparms.sigma, ...
'Standardize', hyperparms.standardize, ...
'Epsilon', hyperparms.epsilon} ...
myif(parameters.crossval.do_crossval,{'KFold',parameters.crossval.nfolds},[])]; % this is for the crossvalidation option...
tmp.matlab_svr_parms = parameters.step1.matlab_svr_parms;
tmp.do_crossval = parameters.crossval.do_crossval; % also save this here too.
end
%% parfeval code
batch_job_size = 100; % this is going to be optimal for different systems/#cores/jobs - set this through gui?
nperms = parameters.PermNumVoxelwise;
njobs = ceil(nperms/batch_job_size); % gotta round up to capture all indices
%% to reduce overhead transfering data to workers...
tmp.dims = variables.vo.dim(1:3);
tmp.lesiondata = sparse(variables.lesion_dat); % full() it on the other end - does that save time with transfer to worker overhead?!
tmp.outpath = variables.output_folder.clusterwise;
if ~parameters.method.mass_univariate % then we need to save beta_scale as well...
tmp.beta_scale = variables.beta_scale;
end
tmp.m_idx = variables.m_idx;
tmp.l_idx = variables.l_idx;
tmp.totalperms = totalperms;
tmp.permdata = permdata;
tmp.useLibSVM = parameters.useLibSVM;
tmp.use_mass_univariate = parameters.method.mass_univariate;
%% Schedule the jobs...
p = gcp(); % get current parallel pool
for j = 1 : njobs
this_job_start_index = ((j-1)*batch_job_size) + 1;
this_job_end_index = min(this_job_start_index + batch_job_size-1,nperms); % need min so we don't go past valid indices
this_job_perm_indices = this_job_start_index:this_job_end_index;
tmp.this_job_perm_indices = this_job_perm_indices; % update for each set of jobs...
f(j) = parfeval(p,@parallel_step1_batch_fcn_lessoverhead,0,tmp);
end
%% Monitor job progress and allow user to bail, hopefully...
for j = 1 : njobs
check_for_interrupt(parameters) % allow user to interrupt
idx = fetchNext(f);
svrlsm_waitbar(parameters.waitbar,j/njobs) % update waitbar progress...
end
%% Now assemble all those individual files from each parfored permutation into one big file that we can memmap
handles = UpdateProgress(handles,'Consolidating beta map permutation data...',1);
svrlsm_waitbar(parameters.waitbar,0,'Consolidating beta map permutation data...');
fileID = fopen(parameters.outfname_big,'w');
for PermIdx=1:parameters.PermNumVoxelwise
if ~mod(PermIdx,100)
svrlsm_waitbar(parameters.waitbar,PermIdx/parameters.PermNumVoxelwise); % update user on progress
check_for_interrupt(parameters)
end
curpermfilepath = fullfile(outpath,['pmu_beta_map_' num2str(PermIdx) '_of_' num2str(totalperms) '.bin']);
cur_perm_data = memmapfile(curpermfilepath,'Format','single');
fwrite(fileID, cur_perm_data.Data,'single');
clear cur_perm_data; % remove memmap from memory.
delete(curpermfilepath); % delete it since we don't want the data hanging around...
end
svrlsm_waitbar(parameters.waitbar,0,''); % reset.
fclose(fileID); % close big file
function parallel_step1_batch_fcn_lessoverhead(tmp)
if ~tmp.useLibSVM || tmp.use_mass_univariate, tmp.lesiondata = full(tmp.lesiondata); end % we transfer it as sparse... so we need to full() it for all non-libSVM methods
for PermIdx = tmp.this_job_perm_indices % each loop iteration will compute one whole-brain permutation result (regardless of LSM method)
trial_score = tmp.permdata(:,PermIdx); % extract the row of permuted data.
if tmp.use_mass_univariate % solve whole-brain permutation PermIdx on a voxel-by-voxel basis.
pmu_beta_map = nan(size(tmp.lesiondata,2),1); % reserve space -- are these dims right?
for vox = 1 : size(tmp.lesiondata,2)
[Q, R] = qr(trial_score, 0); % use the householder transformations to compute the qr factorization of an n by p matrix x.
y = double(tmp.lesiondata(:,vox));% / 10000; % why divide by 10,000? %betas(vox) = R \ (Q' * y); % equivalent to fitlm's output: lm.Coefficients.Estimate
pmu_beta_map(vox) = R \ (Q' * y); % equivalent to fitlm's output: lm.Coefficients.Estimate
end
else % use an SVR method
if tmp.useLibSVM
m = svmtrain(trial_score,tmp.lesiondata,tmp.libsvmstring); %#ok<SVMTRAIN> % alpha = m.sv_coef'; % SVs = m.SVs;
else % use matlab's...
m = fitrsvm(tmp.lesiondata,trial_score,'KernelFunction','rbf', tmp.matlab_svr_parms{:});
end
if ~tmp.do_crossval % then compute the beta map as usual...
pmu_beta_map = tmp.beta_scale * m.(myif(tmp.useLibSVM,'sv_coef','Alpha'))' * m.(myif(tmp.useLibSVM,'SVs','SupportVectors'));
else % we don't need to do any computations since w should already contain a scaled/averaged model
ws = []; % we'll accumulate in here
for mm = 1 : numel(m.Trained)
curMdl = m.Trained{mm};
w = curMdl.Alpha.'*curMdl.SupportVectors;
beta_scale = 10/max(abs(w));
w = w.'*beta_scale;
ws(1:numel(w),mm) = w; % accumulate here...
end
w = mean(ws,2);
pmu_beta_map = w; % here contains an average of the crossvalidated fold models' beta values
end
end
tmp_map = zeros(tmp.dims); % make a zeros template....
tmp_map(tmp.l_idx) = pmu_beta_map; % return the lesion data to their lidx indices...
pmu_beta_map = tmp_map(tmp.m_idx).'; % extract only the midx indices, since these are the only voxels that will be output in the results -- midx contains only voxels that exceed the lesion threshold
% Save this permutation (PermIdx)....
fileID = fopen(fullfile(tmp.outpath,['pmu_beta_map_' num2str(PermIdx) '_of_' num2str(tmp.totalperms) '.bin']),'w');
fwrite(fileID, pmu_beta_map,'single');
fclose(fileID);
end
function [Bouts,lesiondataout] = parallel_step1_batch_muvlsm(lesiondata,modelspec)
for vox = 1 : size(lesiondata,2) % run of the mill loop now...
[B,~,resids] = regress(lesiondata(:,vox),modelspec);
lesiondataout(:,vox) = resids + repmat(B(1),size(resids));
Bouts(:,vox) = B;
end
|
github
|
atdemarco/svrlsmgui-master
|
build_and_write_beta_cutoffs.m
|
.m
|
svrlsmgui-master/functions/build_and_write_beta_cutoffs.m
| 3,366 |
utf_8
|
f724334d6a434ee45dc9f8b9b64c223f
|
function [thresholded,variables] = build_and_write_beta_cutoffs(options,parameters,variables,thresholds,thresholded)
switch parameters.tailshort % parameters.tails
case 'pos' % One-tailed positive tail... high scores bad
[thresholded,variables] = write_beta_cutoff_pos_tail(variables,thresholds,thresholded);
case 'neg' % One-tailed negative tail... high scores good
[thresholded,variables] = write_beta_cutoff_neg_tail(variables,thresholds,thresholded);
case 'two' % Both tails..
warning('not enabled at the moment...')
[thresholded,variables] = write_beta_cutoff_two_tailed(variables,thresholds,thresholded);
end
function [thresholded,variables] = write_beta_cutoff_pos_tail(variables,thresholds,thresholded)
% Now write out beta cutoff map.
thresholded.thresholded_pos = zeros(variables.vo.dim(1:3)); % make a zeros template....
thresholded.thresholded_pos(variables.m_idx) = thresholds.pos_beta_map_cutoff; % put the 95th percentil beta values back into the lesion indices in a full volume
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (positive tail).nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_pos);
variables.files_created.betamask = variables.vo.fname;
function [thresholded,variables] = write_beta_cutoff_neg_tail(variables,thresholds,thresholded)
% Now beta cutoff map for one-taled negative tail...
thresholded.thresholded_neg = zeros(variables.vo.dim(1:3)); % make a zeros template....
thresholded.thresholded_neg(variables.m_idx) = thresholds.neg_beta_map_cutoff; % put the 5th percentil beta values back into the lesion indices in a full volume
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (negative tail).nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_neg);
variables.files_created.betamask = variables.vo.fname;
function [thresholded,variables] = write_beta_cutoff_two_tailed(variables,thresholds,thresholded)
warning('make sure these tails are right after code refactor') % ad 2/14/18
% Two-tailed upper tail
thresholded.thresholded_twotail_upper = zeros(variables.vo.dim(1:3)); % make a zeros template....
thresholded.thresholded_twotail_upper(variables.m_idx) = thresholds.two_tailed_beta_map_cutoff_pos; % put the 2.5th percentil beta values back into the lesion indices in a full volume
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (two tail, upper).nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotail_upper);
variables.files_created.betamask{1} = variables.vo.fname;
% Two-tailed lower tail
thresholded.thresholded_twotail_lower = zeros(variables.vo.dim(1:3)); % make a zeros template....
thresholded.thresholded_twotail_lower(variables.m_idx) = thresholds.two_tailed_beta_map_cutoff_neg; % put the 2.5th percentil beta values back into the lesion indices in a full volume
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (two tail, lower).nii');
svrlsmgui_write_vol(variables.vo, thresholded.thresholded_twotail_lower);
variables.files_created.betamask{2} = variables.vo.fname; % note second cell index
|
github
|
atdemarco/svrlsmgui-master
|
svrinteract.m
|
.m
|
svrlsmgui-master/functions/svrinteract.m
| 10,295 |
utf_8
|
844fdc5833c36244c16ecf3dc90d0faf
|
function varargout = svrinteract(varargin)
% SVRINTERACT MATLAB code for svrinteract.fig
% SVRINTERACT, by itself, creates a new SVRINTERACT or raises the existing
% singleton*.
%
% H = SVRINTERACT returns the handle to a new SVRINTERACT or the handle to
% the existing singleton*.
%
% SVRINTERACT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SVRINTERACT.M with the given input arguments.
%
% SVRINTERACT('Property','Value',...) creates a new SVRINTERACT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before svrinteract_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to svrinteract_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 svrinteract
% Last Modified by GUIDE v2.5 19-Mar-2018 12:55:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @svrinteract_OpeningFcn, ...
'gui_OutputFcn', @svrinteract_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 svrinteract is made visible.
function svrinteract_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 svrinteract (see VARARGIN)
% Choose default command line output for svrinteract
handles.output = hObject;
handles.variables = varargin{1};
handles.opts.stand = false;
handles.opts.ep = .1;
handles.opts.box = 30;
handles.opts.ks = 2;
handles.opts.nfolds = 1; % nfolds = 1 is no crossval
handles.opts.zslice = 25;
tmp = 10 .* randn(handles.variables.vo.dim(1:3));
if (numel(handles.variables.vo.dim) > 3) && (handles.variables.vo.dim(4) > 1) % then it's 4D % handles.variables.vo.dim(4) > 1 % then it's 4d...
handles.ndims = 4;
else
handles.ndims = 3;
end
if handles.ndims == 4
handles.I = imagesc(tmp(:,:,20),'parent',handles.axes1,[-50 50]);
else % it's 3d...
handles.I = imagesc(tmp(:,:,20),'parent',handles.axes1,[-10 10]);
end
handles.montage_zslices = 5:10:(size(tmp,3)-1);
if handles.ndims == 4
montage(tmp, 'Indices',handles.montage_zslices,'DisplayRange', [-50 50],'parent',handles.axes1);
else
montage(tmp, 'Indices',handles.montage_zslices,'DisplayRange', [-10 10],'parent',handles.axes1);
end
colormap jet;
colorbar(handles.axes1)
realdata=handles.variables.one_score;
handles.real = plot(1:numel(handles.variables.one_score),realdata,'sg-','parent',handles.axes2);
hold on;
set(gca,'ylim',[min(realdata)-.1*min(realdata) max(realdata)+.1*max(realdata)])
hold on;
handles.pred = plot(1:numel(handles.variables.one_score),zeros(1,numel(handles.variables.one_score)),'rx-','parent',handles.axes2);
% Update handles structure
guidata(hObject, handles);
paint_current(hObject,handles)
% UIWAIT makes svrinteract wait for user response (see UIRESUME)
% uiwait(handles.figure1);
function paint_current(hObject,handles)
set(handles.standardize_toggle,'value',handles.opts.stand)
set(handles.epsilon_editbox,'string',num2str(handles.opts.ep));
set(handles.cost_editbox,'string',num2str(handles.opts.box));
set(handles.kenelscale_editbox,'string',num2str(handles.opts.ks));
set(handles.zslice,'string',num2str(handles.opts.zslice));
set(handles.crossval_nfolds_editbox,'string',num2str(handles.opts.nfolds));
if handles.ndims == 4 % then use linear kernel
Mdl = fitrsvm(handles.variables.lesion_dat,handles.variables.one_score,'KernelFunction','linear',... % 'rbf', ...
'KernelScale',handles.opts.ks,'BoxConstraint',handles.opts.box,'Standardize', ...
handles.opts.stand,'Epsilon',handles.opts.ep);
else % rbf
Mdl = fitrsvm(handles.variables.lesion_dat,handles.variables.one_score,'KernelFunction','rbf', ...
'KernelScale',handles.opts.ks,'BoxConstraint',handles.opts.box,'Standardize', ...
handles.opts.stand,'Epsilon',handles.opts.ep);
end
w = Mdl.Alpha.'*Mdl.SupportVectors;
handles.variables.beta_scale = 10/max(abs(w));
if handles.ndims == 4
disp('4D data input...')
tmp = zeros(handles.variables.vo.dim(1:4)); % THIS IS DIFFERENT FOR 4D DATA
beta_map = tmp;
tmp(handles.variables.l_idx) = w'*handles.variables.beta_scale; % return all lesion data to its l_idx indices.
beta_map(handles.variables.m_idx) = tmp(handles.variables.m_idx); % m_idx -> m_idx
beta_map = sum(beta_map,4); % THIS IS DIFFERENT FOR 4D DATA
beta_map_bin = beta_map~=0;
relslices = find(squeeze(sum(squeeze(sum(beta_map_bin,1)),1)));
handles.montage_zslices = min(relslices):2:max(relslices);
montage(beta_map,'indices',handles.montage_zslices, 'DisplayRange', [-20 20],'parent',handles.axes1);
else
disp('3D data input...')
tmp = zeros(handles.variables.vo.dim(1:3));
beta_map = tmp;
tmp(handles.variables.l_idx) = w'*handles.variables.beta_scale; % return all lesion data to its l_idx indices.
beta_map(handles.variables.m_idx) = tmp(handles.variables.m_idx); % m_idx -> m_idx
%set(handles.I,'cdata',beta_map(:,:,handles.opts.zslice));
%montage(beta_map, 'Indices',handles.montage_zslices,'DisplayRange', [-10 10],'parent',handles.axes1);
%handles.montage_zslices = 5:10:(size(tmp,3)-1);
%handles.variables.lesion_dat
beta_map_bin = beta_map~=0;
relslices = find(squeeze(sum(squeeze(sum(beta_map_bin,1)),1)));
handles.montage_zslices = min(relslices):2:max(relslices);
montage(beta_map,'indices',handles.montage_zslices, 'DisplayRange', [-10 10],'parent',handles.axes1);
end
colormap jet;
colorbar(handles.axes1)
disp(['Proportion is support vectors = ' num2str(sum(Mdl.IsSupportVector)/numel(Mdl.IsSupportVector))])
if handles.opts.nfolds == 1 % no crossval
predicted = Mdl.predict(handles.variables.lesion_dat);
else
XVMdl = crossval(Mdl,'KFold',handles.opts.nfolds);
predicted = XVMdl.kfoldPredict;
end
set(handles.pred,'ydata',predicted)
hold on;
set(handles.real,'ydata',handles.variables.one_score)
%
% realdata=handles.variables.one_score;
% handles.real = plot(1:numel(handles.variables.one_score),realdata,'sg-','parent',handles.axes2);
% hold on;
% set(handles.axes2,'ylim',[min(realdata)-.1*min(realdata) max(realdata)+.1*max(realdata)])
% preddata = Mdl.predict(handles.variables.lesion_dat);
% handles.pred = plot(1:numel(handles.variables.one_score),preddata,'rx-','parent',handles.axes2);
guidata(hObject, handles);
function varargout = svrinteract_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
function epsilon_editbox_Callback(hObject, eventdata, handles)
handles.opts.ep = str2double(get(hObject,'String'));
paint_current(hObject,handles)
% --- Executes during object creation, after setting all properties.
function epsilon_editbox_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function cost_editbox_Callback(hObject, eventdata, handles)
handles.opts.box = str2double(get(hObject,'String'));
paint_current(hObject,handles)
% --- Executes during object creation, after setting all properties.
function cost_editbox_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function kenelscale_editbox_Callback(hObject, eventdata, handles)
handles.opts.ks = str2double(get(hObject,'String'));
paint_current(hObject,handles)
% --- Executes during object creation, after setting all properties.
function kenelscale_editbox_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in standardize_toggle.
function standardize_toggle_Callback(hObject, eventdata, handles)
handles.opts.stand = ~handles.opts.stand;
paint_current(hObject,handles)
% --- Executes on button press in pushbutton2refre.
function pushbutton2refre_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2refre (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
function zslice_Callback(hObject, eventdata, handles)
handles.opts.zslice = str2double(get(hObject,'String'));
paint_current(hObject,handles)
% --- Executes during object creation, after setting all properties.
function zslice_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function crossval_nfolds_editbox_Callback(hObject, eventdata, handles)
handles.opts.nfolds = str2double(get(hObject,'String'));
paint_current(hObject,handles)
% --- Executes during object creation, after setting all properties.
function crossval_nfolds_editbox_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
|
github
|
atdemarco/svrlsmgui-master
|
optimalParameterReport.m
|
.m
|
svrlsmgui-master/functions/optimalParameterReport.m
| 10,418 |
utf_8
|
f029005bdb9ec73ef901438e0e2fcdf8
|
function variables = optimalParameterReport(parameters,variables)
mkdir(variables.output_folder.hyperparameterinfo)
%variables = optimalParameterReport(parameters,variables);
%variables.files_created.cfwerinfo = fullcfwerout;
% based on Zhang et al (2014)
% returns results for two measures of hyper parameter optimality:
% 1. reproducibility index and
% 2. prediction accuracy
% 3. mean absolute difference...
[hyperparameter_quality.pred_accuracy, ...
hyperparameter_quality.mean_abs_diff] = computePredictionAccuracy(parameters,variables);
hyperparameter_quality.repro_index = computeReproducibilityIndex(parameters,variables);
hyperparameter_quality.behavioral_predictions = computerBehavioralPrediction(parameters,variables); % this will be used for our WritePredictBehaviorReport in summary output.
%% Save the results so we can use them later
fname = 'hyperparameter_quality.mat';
fpath = fullfile(variables.output_folder.hyperparameterinfo,fname);
save(fpath,'hyperparameter_quality','-v7.3') % if it's bigger than 2 GB we need v7.3 anyway...
variables.files_created.hyperparameter_quality = fpath;
variables.hyperparameter_quality = hyperparameter_quality;
function behavioral_predictions = computerBehavioralPrediction(parameters,variables)
behavdata = variables.one_score; % for clarity extract these.
lesiondata = variables.lesion_dat;
%nfolds = 5; % Zhang et al., 2014
nfolds = parameters.hyperparameter_quality.report.nfolds;
hyperparms = hyperparmstruct(parameters);
svrlsm_waitbar(parameters.waitbar,0,'Hyperparameter optimization: Storing behavioral predictions.');
if parameters.useLibSVM
libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % we may need to re-apply standardization...?
crossvalinds = crossvalind('KFold', variables.SubNum, nfolds);
lesiondata=sparse(lesiondata);
m = svmtrain(behavdata, lesiondata, libsvmstring); %#ok<SVMTRAIN> -- use all data
behavioral_predictions.Mdl = m;
for curfold=1:nfolds
infold = crossvalinds == curfold;
outoffold = crossvalinds ~= curfold;
m = svmtrain(behavdata(outoffold), lesiondata(outoffold,:), libsvmstring); %#ok<SVMTRAIN>
behavioral_predictions.XVMdl_predicted(infold) = svmpredict(behavdata(infold), lesiondata(infold,:), m, '-q'); % predict OOF observations based on cur fold data.
end
behavioral_predictions.XVMdl = [];
else % Run with MATLAB machinery.
Mdl = fitrsvm(lesiondata,behavdata,'ObservationsIn','rows','KernelFunction','rbf', 'KernelScale',hyperparms.sigma,'BoxConstraint',hyperparms.cost,'Standardize',hyperparms.standardize,'Epsilon',hyperparms.epsilon);
XVMdl = crossval(Mdl,'KFold',nfolds); % this is a 5-fold
behavioral_predictions.Mdl = Mdl;
behavioral_predictions.XVMdl = XVMdl;
behavioral_predictions.XVMdl_predicted = kfoldPredict(XVMdl);
end
svrlsm_waitbar(parameters.waitbar,0,'');
% 1. reproducibility index
% - solve the SVRLSM N times for a random subset of 80% of subjects (Zhang et al used 85 of 106 pts for each rerun)
% - compute pairwise correlations between all the resulting SVR-B maps
% - mean of the correlation coefficients is the REPRODUCIBILITY INDEX
function repro_index = computeReproducibilityIndex(parameters,variables)
% For clarity extract these.
behavdata = variables.one_score;
lesiondata = variables.lesion_dat;
% restore to 40 crossval steps once we introduce parallelization -- maybe make it user-configurable
%N_subsets_to_perform = 2; % 10; % Zhang et al., 2015
%subset_include_percentage = .8; % Zhang et al., 2015
subset_include_percentage = parameters.hyperparameter_quality.report.repro_ind_subset_pct;
N_subsets_to_perform = parameters.hyperparameter_quality.report.n_replications;
nsubs = numel(behavdata);
nholdin = round(subset_include_percentage*nsubs); % how many subjects should be in each subset?
hyperparms = hyperparmstruct(parameters);
N_subset_results = cell(1,N_subsets_to_perform); % save the correlation coefficients in this vector, then average them
percent_obs_are_SVs = nan(1,N_subsets_to_perform); % count the number of SVs...
svrlsm_waitbar(parameters.waitbar,0,'Hyperparameter optimization: Measuring reproducibility index.');
for N = 1 : N_subsets_to_perform
svrlsm_waitbar(parameters.waitbar,N/N_subsets_to_perform);
includesubs = randperm(nsubs,nholdin); % each column contains a unique permutation
if parameters.useLibSVM % do libsvm...
libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % we may need to re-apply standardization...?
lesiondata=sparse(lesiondata);
m = svmtrain(behavdata(includesubs), lesiondata(includesubs,:), libsvmstring); %#ok<SVMTRAIN>
percent_obs_are_SVs(N) = m.totalSV / variables.SubNum; % should we instead use: sum(m.sv_coef == parameters.cost)) % (this is the number of bounded SVs)
w = m.sv_coef'*m.SVs;
else % do with MATLAB
Mdl = fitrsvm(lesiondata(includesubs,:),behavdata(includesubs,:),'ObservationsIn','rows','KernelFunction','rbf', 'KernelScale',hyperparms.sigma,'BoxConstraint',hyperparms.cost,'Standardize',hyperparms.standardize,'Epsilon',hyperparms.epsilon);
percent_obs_are_SVs(N) = sum(Mdl.IsSupportVector) / numel(Mdl.IsSupportVector);
w = Mdl.Alpha.'*Mdl.SupportVectors;
end
if N == 1 % compute initial beta_scale to reuse...
beta_scale = 10 / prctile(abs(w),parameters.svscaling); % parameters.svscaling is e.g, 100 or 99 or 95
end
w = w'*beta_scale; % the beta here is kind of irrelevant because it just scales the data, and correlation is insensitive to scaling...
N_subset_results{N} = w; % save the w-map...
end
% Now for each pair of w maps in N_subset_results{:}, compute a correlation coefficient...
C = nchoosek(1:numel(N_subset_results),2); % rows of pairwise indices to correlate...
repro_index_correlation_results = nan(size(C,1),1); % reseve space...
for row = 1 : size(C,1)
corrvals = corrcoef(N_subset_results{C(row,1)},N_subset_results{C(row,2)}); % compute the correlation...
r = corrvals(2,1); % grab the r
repro_index_correlation_results(row) = r; % store.
end
repro_index.data = repro_index_correlation_results;
repro_index.mean = mean(repro_index_correlation_results);
repro_index.std = std(repro_index_correlation_results);
repro_index.percent_obs_are_SVs = percent_obs_are_SVs; % number of support vectors...
% 2. prediction accuracy
% - mean correlation coefficient between predixcted scores and testing scores with 40 5-fold cross-validations.
function [pred_accuracy,mean_abs_diff] = computePredictionAccuracy(parameters,variables)
behavdata = variables.one_score; % for clarity extract these.
lesiondata = variables.lesion_dat;
% restore to 40 crossval steps once we introduce parallelization -- maybe make it user-configurable
%N_crossvals_to_perform = 2; % 10; % Zhang et al., 2015
% nfolds = 5; % Zhang et al., 2014
nfolds = parameters.hyperparameter_quality.report.nfolds;
N_crossvals_to_perform = parameters.hyperparameter_quality.report.n_replications;
hyperparms = hyperparmstruct(parameters);
N_crossval_correl_results = nan(1,N_crossvals_to_perform); % save the correlation coefficients in this vector, then average them
N_crossval_MAD_results = nan(1,N_crossvals_to_perform); % average mean absolute difference between predicted and real.
percent_obs_are_SVs = nan(1,N_crossvals_to_perform); % count the number of SVs...
if parameters.useLibSVM % try to save time by only doing this once...
lesiondata=sparse(lesiondata);
end
svrlsm_waitbar(parameters.waitbar,0,'Hyperparameter optimization: Measuring prediction accuracy.');
predicted = nan(variables.SubNum,1); % reserve space.
for N = 1 : N_crossvals_to_perform
svrlsm_waitbar(parameters.waitbar,N/N_crossvals_to_perform);
if parameters.useLibSVM
libsvmstring = get_libsvm_spec(hyperparms.cost,hyperparms.gamma,hyperparms.epsilon); % we may need to re-apply standardization...?
crossvalinds = crossvalind('KFold', variables.SubNum, nfolds);
for curfold=1:nfolds
infold = crossvalinds == curfold;
outoffold = crossvalinds ~= curfold;
m = svmtrain(behavdata(outoffold), lesiondata(outoffold,:), libsvmstring); %#ok<SVMTRAIN>
predicted(infold) = svmpredict(behavdata(infold), lesiondata(infold,:), m, '-q'); % predict OOF observations based on cur fold data.
end
else
Mdl = fitrsvm(lesiondata,behavdata,'ObservationsIn','rows','KernelFunction','rbf', 'KernelScale',hyperparms.sigma,'BoxConstraint',hyperparms.cost,'Standardize',hyperparms.standardize,'Epsilon',hyperparms.epsilon);
percent_obs_are_SVs(N) = sum(Mdl.IsSupportVector) / numel(Mdl.IsSupportVector);
XVMdl = crossval(Mdl,'Kfold',nfolds); % this is a 5-fold
predicted = kfoldPredict(XVMdl);
end
corrvals = corrcoef(predicted,behavdata); % compute the correlation...
r = corrvals(2,1); % grab the r
N_crossval_correl_results(N) = r; % save.
N_crossval_MAD_results(N) = mean(abs(predicted-behavdata));
end
svrlsm_waitbar(parameters.waitbar,0,'');
pred_accuracy.data = N_crossval_correl_results; % can plot a distribution if we like...
pred_accuracy.mean = mean(N_crossval_correl_results);
pred_accuracy.std = std(N_crossval_correl_results);
pred_accuracy.percent_obs_are_SVs = percent_obs_are_SVs; % number of support vectors...
mean_abs_diff.data = N_crossval_MAD_results; % can plot a distribution if we like... redundant w pred_accuracy
mean_abs_diff.mean = mean(N_crossval_MAD_results);
mean_abs_diff.std = std(N_crossval_MAD_results);
mean_abs_diff.percent_obs_are_SVs = percent_obs_are_SVs; % number of support vectors... redundant w pred_accuracy
|
github
|
atdemarco/svrlsmgui-master
|
continuize_lesions.m
|
.m
|
svrlsmgui-master/functions/continuize_lesions.m
| 3,445 |
utf_8
|
4c8d28c69af12f9066e66e03d26ae518
|
function variables = continuize_lesions(variables,parameters)
% 8/7/17 - added support for parallelization
% 8/7/17 - fixed bug - intercept term and adding its beta back into residuals
% 11/16/17 - added check for user interrupt
% 2/19/18 - added in-gui waitbar in parallelized and non-parallelized loop
% waitbar for the par loop involved replacing the pre-existing parfor code
% with 'parfeval' which was introduced in MATLAB 2013b
lesiondataout = nan(size(variables.lesion_dat));
modelcols = variables.lesion_nuisance_model;
lesiondata = variables.lesion_dat;
const = ones(size(modelcols,1),1);
modelspec = [const modelcols];
Bouts = nan(size(modelspec,2),size(variables.lesion_dat,2));
if parameters.parallelize
svrlsm_waitbar(parameters.waitbar,0,'Running lesion nuisance model (parallelized)...')
batch_job_size = 2500; % this is going to be optimal for different systems/#cores
nvox = size(lesiondata,2);
njobs = ceil(nvox/batch_job_size); % gotta round up to capture all indices
p = gcp(); % get current parallel pool
for j = 1 : njobs
this_job_start_index = ((j-1)*batch_job_size) + 1;
this_job_end_index = min(this_job_start_index + batch_job_size-1,nvox); % need min so we don't go past valid indices
job_indices = this_job_start_index:this_job_end_index;
f(j) = parfeval(p, @parallel_lesion_batch_fcn, 2,lesiondata(:,job_indices),modelspec); % 2 outputs
end
Bouts = cell(1,njobs); %reserve space - note we want to accumulate in a row here
lesiondataout = cell(1,njobs); %reserve space - note we want to accumulate in a row here
for j = 1 : njobs
check_for_interrupt(parameters) % allow user to interrupt
[idx, value1,value2] = fetchNext(f);
Bouts{idx} = value1; % combine these cells afterward
lesiondataout{idx} = value2; % combine these cells afterward
svrlsm_waitbar(parameters.waitbar,j/njobs) % update waitbar progress...
end
Bouts = cell2mat(Bouts); % combine afterward
lesiondataout = cell2mat(lesiondataout); % combine afterward
else % not parallelized.
svrlsm_waitbar(parameters.waitbar,0,'Running lesion nuisance model...')
for vox = 1 : size(variables.lesion_dat,2)
if ~mod(vox,100), svrlsm_waitbar(parameters.waitbar,vox/size(variables.lesion_dat,2)); end
check_for_interrupt(parameters) % allow user to interrupt
[B,~,resids] = regress(lesiondata(:,vox),modelspec);
lesiondataout(:,vox) = resids + repmat(B(1),size(resids));
Bouts(:,vox) = B;
end
end
svrlsm_waitbar(parameters.waitbar,0,'') % clear the waitbar
variables.lesion_nuisance_model_betas = Bouts;
variables.lesion_dat2 = lesiondataout;
% Parallel batch helper function for parallelizing the lesion nuisance model
function [Bouts,lesiondataout] = parallel_lesion_batch_fcn(lesiondata,modelspec)
for vox = 1 : size(lesiondata,2) % run of the mill loop now...
[B,~,resids] = regress(lesiondata(:,vox),modelspec);
lesiondataout(:,vox) = resids + repmat(B(1),size(resids));
Bouts(:,vox) = B;
end
% old parallelized version without batch:
% parfor vox = 1 : size(variables.lesion_dat,2)
% check_for_interrupt(parameters)
% [B,~,resids] = regress(lesiondata(:,vox),modelspec);
% lesiondataout(:,vox) = resids + repmat(B(1),size(resids));
% Bouts(:,vox) = B;
% end
|
github
|
atdemarco/svrlsmgui-master
|
write_nifti_hdr.m
|
.m
|
svrlsmgui-master/functions/nifti/write_nifti_hdr.m
| 2,762 |
utf_8
|
82987cccd27d7f60b004bdbec61b6d24
|
function write_nifti_hdr(h, fname)
% WRITE_NIFTI_HDR Write NIFTI header
%
% WRITE_NIFTI_HDR(H, FNAME) writes the header structure H into the file
% FNAME. The validity of H is not checked.
[pathstr, basename, ext] = fileparts(fname);
if strcmp(ext, '.img')
fname = fullfile(pathstr, [basename '.hdr']);
end
if strcmp(ext, '.nii') && exist(fname, 'file')
fid = fopen(fname, 'r+');
else
fid = fopen(fname, 'w');
end
fwrite(fid, h.sizeof_hdr(1), 'int32');
fwrite(fid, padchar(h.data_type, 10), 'char');
fwrite(fid, padchar(h.db_name, 18), 'char');
fwrite(fid, h.extents(1), 'int32');
fwrite(fid, h.session_error(1), 'int16');
fwrite(fid, h.regular(1), 'char');
fwrite(fid, h.dim_info(1), 'char');
fwrite(fid, h.dim(1:8), 'int16');
fwrite(fid, h.intent_p1(1), 'float32');
fwrite(fid, h.intent_p2(1), 'float32');
fwrite(fid, h.intent_p3(1), 'float32');
fwrite(fid, h.intent_code(1), 'int16');
fwrite(fid, h.datatype(1), 'int16');
fwrite(fid, h.bitpix(1), 'int16');
fwrite(fid, h.slice_start(1), 'int16');
fwrite(fid, h.pixdim(1:8), 'float32');
fwrite(fid, h.vox_offset(1), 'float32');
fwrite(fid, h.scl_slope(1), 'float32');
fwrite(fid, h.scl_inter(1), 'float32');
fwrite(fid, h.slice_end(1), 'int16');
fwrite(fid, h.slice_code(1), 'uchar');
fwrite(fid, h.xyzt_units(1), 'uchar');
fwrite(fid, h.cal_max(1), 'float32');
fwrite(fid, h.cal_min(1), 'float32');
fwrite(fid, h.slice_duration(1), 'float32');
fwrite(fid, h.toffset(1), 'float32');
fwrite(fid, h.glmax(1), 'int32');
fwrite(fid, h.glmin(1), 'int32');
fwrite(fid, padchar(h.descrip, 80), 'char');
fwrite(fid, padchar(h.aux_file, 24), 'char');
fwrite(fid, h.qform_code(1), 'int16');
fwrite(fid, h.sform_code(1), 'int16');
fwrite(fid, h.quatern_b(1), 'float32');
fwrite(fid, h.quatern_c(1), 'float32');
fwrite(fid, h.quatern_d(1), 'float32');
fwrite(fid, h.qoffset_x(1), 'float32');
fwrite(fid, h.qoffset_y(1), 'float32');
fwrite(fid, h.qoffset_z(1), 'float32');
fwrite(fid, h.srow_x(1:4), 'float32');
fwrite(fid, h.srow_y(1:4), 'float32');
fwrite(fid, h.srow_z(1:4), 'float32');
fwrite(fid, padchar(h.intent_name, 16), 'char');
fwrite(fid, padchar(h.magic, 4), 'char');
if h.qform_code == 0 && h.sform_code == 0 && isfield(h, 'originator') && ...
all(h.originator(1:3) >= 1) && all(h.originator(1:3) <= h.dim(2:4))
warning('Writing ANALYZE originator over the top of NIFTI orientation fields');
fseek(fid, 253, 'bof');
fwrite(fid, h.originator, 'int16')'; % over the top of qform_code and the following few fields
end
fclose(fid);
function outstr = padchar(instr, n)
if length(instr) <= n
outstr = char(zeros(1, n));
outstr(1:length(instr)) = instr;
else
outstr = instr(1:n);
end
|
github
|
atdemarco/svrlsmgui-master
|
analyze_to_nifti.m
|
.m
|
svrlsmgui-master/functions/nifti/analyze_to_nifti.m
| 1,235 |
utf_8
|
18757b17671315605f0fda9ab06b7129
|
function analyze_to_nifti(fname)
% ANALYZE_TO_NIFTI(FNAME)
%
% Converts the ANALYZE image FNAME to .nii (one file) format. If no FNAME
% is provided, converts every .img file in the current directory.
%
% The header information is set up based on what SPM5 does if you reslice.
% The origin is set to the center.
if nargin == 0
d = dir('*.img');
if length(d) >= 1
for i = 1:length(d)
fprintf('%s\n', d(i).name);
do(d(i).name);
end
end
else
do(fname);
end
function do(fname)
[hdr, img] = read_nifti(fname);
nhdr = make_nifti_hdr(hdr.datatype, hdr.dim(2:4), abs(hdr.pixdim(2:4)));
x = (nhdr.dim(2) / 2 - 0.5) * nhdr.pixdim(2);
y = (nhdr.dim(3) / 2 - 0.5) * nhdr.pixdim(3);
z = (nhdr.dim(4) / 2 - 0.5) * nhdr.pixdim(4);
nhdr.pixdim(1) = -1;
nhdr.vox_offset = 352;
nhdr.qform_code = 2;
nhdr.sform_code = 2;
nhdr.quatern_b = 0;
nhdr.quatern_c = 1;
nhdr.quatern_d = 0;
nhdr.qoffset_x = x;
nhdr.qoffset_y = -y;
nhdr.qoffset_z = -z;
nhdr.srow_x = [-nhdr.pixdim(2) 0 0 x];
nhdr.srow_y = [0 nhdr.pixdim(3) 0 -y];
nhdr.srow_z = [0 0 nhdr.pixdim(4) -z];
nhdr.magic = 'n+1 ';
nhdr.magic(4) = 0;
fname((end - 2):end) = 'nii';
write_nifti(nhdr, img, fname);
|
github
|
atdemarco/svrlsmgui-master
|
nifti2jpg.m
|
.m
|
svrlsmgui-master/functions/nifti/nifti2jpg.m
| 1,178 |
utf_8
|
534ca9fc2dd45fab241045c7a7d29e53
|
function nifti2jpg(fname, skip, flip)
if nargin < 2
skip = 1;
end
if nargin < 3
flip = [0 0 1; 1 0 1]; % works for NIC T1s after dicom2analyze
end
[hdr, img] = read_nifti(fname);
vals = img(:);
vals = sort(vals(1:10:end));
anatmin = vals(round(length(vals) * 10 / 100));
anatmax = vals(round(length(vals) * 95 / 100));
for o = 1:3
for i = 1:skip:hdr.dim(o + 1)
if o == 1
slice = squeeze(img(i, :, :));
elseif o == 2
slice = squeeze(img(:, i, :));
else
slice = squeeze(img(:, :, i));
end
if flip(1, o)
slice = slice';
end
if flip(2, o)
slice = flipud(slice);
end
slice = scaleimg(slice, anatmin, anatmax, 0.15, 1);
imwrite(slice, sprintf('%d_%03d.jpg', o, i), 'JPEG', 'Quality', 50);
end
end
function sd = scaleimg(img, imin, imax, omin, omax)
% scales an image such that values between imin and imax now lie between
% omin and omax. values above and below are clipped.
sd = omin + (img - imin) / (imax - imin) * (omax - omin);
sd(sd < omin) = omin;
sd(sd > omax) = omax;
|
github
|
atdemarco/svrlsmgui-master
|
run_beta_PMU_old.m
|
.m
|
svrlsmgui-master/functions/unused/run_beta_PMU_old.m
| 24,927 |
utf_8
|
245c8f57bb62a9aebd3d04d065c89441
|
function variables = run_beta_PMU(parameters, variables, cmd, beta_map,handles)
options = handles.options;
zerostemplate = zeros(variables.vo.dim(1:3)); % make a zeros template....
ori_beta_val = beta_map(variables.m_idx).'; % Original observed beta values.
tic;
if parameters.parallelize % try to parfor it...
handles = UpdateProgress(handles,'Computing beta map permutations (parallelized)...',1);
sparseLesionData = sparse(variables.lesion_dat);
lidx = variables.l_idx;
midx = variables.m_idx;
betascale = variables.beta_scale;
% create permutations beforehand.
permdata = nan(numel(variables.one_score),parameters.PermNumVoxelwise); % each COL will be a permutation.
npermels = size(permdata,1);
for r = 1 : size(permdata,2) % each col...
permdata(:,r) = variables.one_score(randperm(npermels));
end
outpath = variables.output_folder.clusterwise;
totalperms = parameters.PermNumVoxelwise;
uselibsvm = parameters.useLibSVM;
parfor PermIdx=1:parameters.PermNumVoxelwise
check_for_interrupt(parameters)
trial_score = permdata(:,PermIdx); % extract the row of permuted data.
if uselibsvm
m = svmtrain(trial_score,sparseLesionData,cmd); %#ok<SVMTRAIN>
alpha = m.sv_coef';
SVs = m.SVs;
else
[m,~,~] = ComputeMatlabSVRLSM(parameters,variables);
alpha = m.Alpha';
SVs = m.SupportVectors;
end
pmu_beta_map = betascale * alpha * SVs;
tmp_map = zerostemplate; % zeros(nx, ny, nz);
tmp_map(lidx) = pmu_beta_map;
pmu_beta_map = tmp_map(midx).';
% Save this permutation....
fileID = fopen(fullfile(outpath,['pmu_beta_map_' num2str(PermIdx) '_of_' num2str(totalperms) '.bin']),'w');
fwrite(fileID, pmu_beta_map,'single');
fclose(fileID);
end
% now get all those individual files into one big file that we can memmap to.
outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);
fileID = fopen(outfname_big,'w');
for PermIdx=1:parameters.PermNumVoxelwise
check_for_interrupt(parameters)
curpermfilepath = fullfile(outpath,['pmu_beta_map_' num2str(PermIdx) '_of_' num2str(totalperms) '.bin']);
cur_perm_data = memmapfile(curpermfilepath,'Format','single');
fwrite(fileID, cur_perm_data.Data,'single');
clear cur_perm_data; % remove memmap from memory.
delete(curpermfilepath); % delete it since we don't want the data hanging around...
end
fclose(fileID); % close big file
else
handles = UpdateProgress(handles,'Computing beta map permutations (not parallelized)...',1);
% This is where we'll save our GBs of permutation data output...
outfname_big = fullfile(variables.output_folder.clusterwise,['pmu_beta_maps_N_' num2str(parameters.PermNumVoxelwise) '.bin']);
fileID = fopen(outfname_big,'w');
h = waitbar(0,'Computing beta permutations...','Tag','WB');
for PermIdx=1:parameters.PermNumVoxelwise
check_for_interrupt(parameters)
% random permute subjects order
loc = randperm(length(variables.one_score));
trial_score = variables.one_score(loc);
% Which package to use to compute SVM solution
if parameters.useLibSVM
m = svmtrain(trial_score,sparse(variables.lesion_dat),cmd); %#ok<SVMTRAIN>
else
if PermIdx == 1
variables.orig_one_score = variables.one_score;
end
variables.one_score = trial_score;
[m,~,~] = ComputeMatlabSVRLSM(parameters,variables);
if PermIdx == parameters.PermNumVoxelwise % put it back after we've done all permutations...
variables.one_score = variables.orig_one_score;
end
end
% compute the beta map
if parameters.useLibSVM
alpha = m.sv_coef';
SVs = m.SVs;
else % MATLAB's version.
alpha = m.Alpha';
SVs = m.SupportVectors;
end
pmu_beta_map = variables.beta_scale * alpha*SVs;
tmp_map = zerostemplate;
tmp_map(variables.l_idx) = pmu_beta_map;
pmu_beta_map = tmp_map(variables.m_idx).';
% Save this permutation....
fwrite(fileID, pmu_beta_map,'single');
% Display progress.
elapsed_time = toc;
remain_time = round(elapsed_time * (parameters.PermNumVoxelwise - PermIdx)/(PermIdx));
remain_time_h = floor(remain_time/3600);
remain_time_m = floor((remain_time - remain_time_h*3600)/60);
remain_time_s = floor(remain_time - remain_time_h*3600 - remain_time_m*60);
prompt_str = sprintf(['Permutation ', num2str(PermIdx), '/', num2str(parameters.PermNumVoxelwise), ': Est. remaining time: ', num2str(remain_time_h), ' h ', num2str(remain_time_m), ' m ' num2str(remain_time_s), 's\n']);
waitbar(PermIdx/parameters.PermNumVoxelwise,h,prompt_str) % show progress.
end
close(h) % close the waitbar...
fclose(fileID); % close the pmu data output file.
end
% Read in gigantic memory mapped file... no matter whether we parallelized or not.
all_perm_data = memmapfile(outfname_big,'Format','single'); % does the single precision hurt the analysis?
%% FWE cluster correction based on permutation analysis
voxelwise_p_value = parameters.voxelwise_p;
pos_thresh_index = median([1 round((1-voxelwise_p_value) * parameters.PermNumVoxelwise) parameters.PermNumVoxelwise]); % row 9500 in 10000 permutations.
pos_beta_map_cutoff = nan(1,length(variables.m_idx));
one_tail_pos_alphas = nan(1,length(variables.m_idx));
neg_thresh_index = median([1 round(voxelwise_p_value * parameters.PermNumVoxelwise) parameters.PermNumVoxelwise]); % so row 500 in 10000 permutations
neg_beta_map_cutoff = nan(1,length(variables.m_idx));
one_tail_neg_alphas = nan(1,length(variables.m_idx));
two_tailed_thresh_index_neg = median([1 round(((voxelwise_p_value/2)) * parameters.PermNumVoxelwise) parameters.PermNumVoxelwise]); % row 250 in 10000 permutations.
two_tailed_thresh_index = median([1 round((1-(voxelwise_p_value/2)) * parameters.PermNumVoxelwise) parameters.PermNumVoxelwise]); % row 9750 in 10000 permutations.
two_tailed_beta_map_cutoff_pos = nan(1,length(variables.m_idx));
two_tailed_beta_map_cutoff_neg = nan(1,length(variables.m_idx));
twotails_alphas = nan(1,length(variables.m_idx));
if parameters.parallelize % try to parfor it...
handles = UpdateProgress(handles,'Sorting null betas for each lesioned voxel in the dataset (parallelized).',1);
L = length(variables.m_idx);
tails = parameters.tails; % so not a broadcast variable.
Opt1 = options.hypodirection{1};
Opt2 = options.hypodirection{2};
Opt3 = options.hypodirection{3};
parfor col = 1 : length(variables.m_idx)
check_for_interrupt(parameters)
curcol = extractSlice(all_perm_data,col,L); % note this is a function at the bottom of this file..
observed_beta = ori_beta_val(col); % original observed beta value.
curcol_sorted = sort(curcol); % smallest values at the top..
switch tails
case Opt1
one_tail_pos_alphas(col) = sum(observed_beta > curcol_sorted)/numel(curcol_sorted); % percent of values observed_beta is greater than.
pos_beta_map_cutoff(col) = curcol_sorted(pos_thresh_index); % so the 9500th at p of 0.05 on 10,000 permutations
case Opt2
one_tail_neg_alphas(col) = sum(observed_beta < curcol_sorted)/numel(curcol_sorted); % percent of values observed_beta is greater than.
neg_beta_map_cutoff(col) = curcol_sorted(neg_thresh_index); % so the 500th at p of 0.05 on 10,000 permutations
case Opt3
two_tailed_beta_map_cutoff_pos(col) = curcol_sorted(two_tailed_thresh_index); % 250...
two_tailed_beta_map_cutoff_neg(col) = curcol_sorted(two_tailed_thresh_index_neg); % 9750...
twotails_alphas(col) = sum(abs(observed_beta) > abs(curcol_sorted))/numel(curcol_sorted); % percent of values observed_beta is greater than.
end
end
else
handles = UpdateProgress(handles,'Sorting null betas for each lesioned voxel in the dataset (not parallelized).',1);
h = waitbar(0,sprintf('Sorting null betas for each lesioned voxel in the dataset (N = %d).\n',length(variables.m_idx)),'Tag','WB');
dataRef = all_perm_data.Data; % will this eliminate some overhead
L = length(variables.m_idx);
for col = 1 : length(variables.m_idx)
check_for_interrupt(parameters)
curcol = dataRef(col:L:end); % index out each column using skips the length of the data...
observed_beta = ori_beta_val(col); % original observed beta value.
curcol_sorted = sort(curcol); % smallest values at the top..
% hist(curcol_sorted)
% histogram(curcol_sorted,35)
% hold on
% title(num2str(col))
% pause
% fitdists{col} = fitdist(
% pd = fitdist(x,'Kernel','Kernel','epanechnikov')
% p_vec=nan(size(curcol_sorted)); % allocate space
% all_ind = 1:numel(curcol_sorted); % we'll reuse this vector
% for i = all_ind % for each svr beta value in the vector
% ind_to_compare = setdiff(all_ind,i);
% p_vec(i) = 1 - mean(curcol_sorted(i) < curcol_sorted(ind_to_compare));
% end
% disp([num2str(i) ' of ' num2str(numel(p_vec)) ' - observed svrB = ' num2str(observed_beta)])
% [numel(unique(curcol_sorted)) numel(unique(p_vec))]
% Compute beta cutoff values and a pvalue map for the observed betas.
switch parameters.tails
case options.hypodirection{1} % 'one_positive'
one_tail_pos_alphas(col) = sum(observed_beta > curcol_sorted)/numel(curcol_sorted); % percent of values observed_beta is greater than.
pos_beta_map_cutoff(col) = curcol_sorted(pos_thresh_index); % so the 9500th at p of 0.05 on 10,000 permutations
case options.hypodirection{2} %'one_negative'
one_tail_neg_alphas(col) = sum(observed_beta < curcol_sorted)/numel(curcol_sorted); % percent of values observed_beta is greater than.
neg_beta_map_cutoff(col) = curcol_sorted(neg_thresh_index); % so the 500th at p of 0.05 on 10,000 permutations
case options.hypodirection{3} % 'two'
two_tailed_beta_map_cutoff_pos(col) = curcol_sorted(two_tailed_thresh_index); % 250...
two_tailed_beta_map_cutoff_neg(col) = curcol_sorted(two_tailed_thresh_index_neg); % 9750...
twotails_alphas(col) = sum(abs(observed_beta) > abs(curcol_sorted))/numel(curcol_sorted); % percent of values observed_beta is greater than.
end
waitbar(col/L,h) % show progress.
end
close(h)
end
%% Construct volumes of the solved alpha values and write them out - and write out beta cutoff maps, too
switch parameters.tails
case options.hypodirection{1} % 'one_positive' % One-tailed positive tail...
thresholded_pos = zerostemplate;
if parameters.invert_p_map_flag % it's already inverted
thresholded_pos(variables.m_idx) = one_tail_pos_alphas;
% Write unthresholded P-map for the positive tail
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values (inv).nii');
svrlsmgui_write_vol(variables.vo, thresholded_pos);
% Now write out the thresholded P-map for the positive tail
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');
thresholded_pos(thresholded_pos < (1-parameters.voxelwise_p)) = 0; % zero out sub-threshold p value voxels (note the 1-p)
svrlsmgui_write_vol(variables.vo, thresholded_pos);
else
thresholded_pos(variables.m_idx) = 1 - one_tail_pos_alphas;
% Write unthresholded P-map for the positive tail
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values.nii');
svrlsmgui_write_vol(variables.vo, thresholded_pos);
% Now write out the thresholded P-map for the positive tail
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values.nii');
thresholded_pos(thresholded_pos > parameters.voxelwise_p) = 0; % zero out voxels whose values are greater than p
svrlsmgui_write_vol(variables.vo, thresholded_pos);
end
% Now write out beta cutoff map.
thresholded_pos = zerostemplate; % zeros(nx,ny,nz); % reserve space
thresholded_pos(variables.m_idx) = pos_beta_map_cutoff; % put the 95th percentil beta values back into the lesion indices in a full volume
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (positive tail).nii');
svrlsmgui_write_vol(variables.vo, thresholded_pos);
case options.hypodirection{2} % 'one_negative' % One-tailed negative tail...
thresholded_neg = zerostemplate;
if parameters.invert_p_map_flag % it's already inverted...
thresholded_neg(variables.m_idx) = one_tail_neg_alphas;
% write out unthresholded negative p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values (inv).nii');
svrlsmgui_write_vol(variables.vo, thresholded_neg);
% write out thresholded negative p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');
thresholded_neg(thresholded_neg < (1-parameters.voxelwise_p)) = 0; % zero out subthreshold p value voxels (note 1-p)
svrlsmgui_write_vol(variables.vo, thresholded_neg);
else
thresholded_neg(variables.m_idx) = 1 - one_tail_neg_alphas;
% write out unthresholded negative p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values.nii');
svrlsmgui_write_vol(variables.vo, thresholded_neg);
% write out thresholded negative p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values.nii');
thresholded_neg(thresholded_neg > parameters.voxelwise_p) = 0; % zero out voxels whose values are greater than p
svrlsmgui_write_vol(variables.vo, thresholded_neg);
end
% Now beta cutoff map for one-taled negative tail...
thresholded_neg = zerostemplate; % reserve space;
thresholded_neg(variables.m_idx) = neg_beta_map_cutoff; % put the 5th percentil beta values back into the lesion indices in a full volume
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (negative tail).nii');
svrlsmgui_write_vol(variables.vo, thresholded_neg);
case options.hypodirection{3} %'two'% Both tails..
thresholded_twotails = zerostemplate;% reserve space;
if parameters.invert_p_map_flag % it's already inverted...
thresholded_twotails(variables.m_idx) = twotails_alphas;
% write out unthresholded p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values (inv).nii');
svrlsmgui_write_vol(variables.vo, thresholded_twotails);
% write out thresholded p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');
thresholded_twotails(thresholded_twotails < (1-(parameters.voxelwise_p/2))) = 0; % zero out subthreshold p value voxels (note 1-p)
svrlsmgui_write_vol(variables.vo, thresholded_twotails);
else
thresholded_twotails(variables.m_idx) = 1 - twotails_alphas;
% write out unthresholded p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Unthresholded P values.nii');
svrlsmgui_write_vol(variables.vo, thresholded_twotails);
% write out thresholded p map
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Thresholded P values (inv).nii');
thresholded_twotails(thresholded_twotails > (parameters.voxelwise_p/2)) = 0; % zero out supra-alpha p value voxels
svrlsmgui_write_vol(variables.vo, thresholded_twotails);
end
% Beta cutoff maps
% Two-tailed upper tail
thresholded_twotail_upper = zerostemplate; %zeros(nx,ny,nz); % reserve space;
thresholded_twotail_upper(variables.m_idx) = two_tailed_beta_map_cutoff_pos; % put the 2.5th percentil beta values back into the lesion indices in a full volume
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (two tail, upper).nii');
svrlsmgui_write_vol(variables.vo, thresholded_twotail_upper);
% Two-tailed lower tail
thresholded_twotail_lower = zerostemplate; % zeros(nx,ny,nz); % reserve space;
thresholded_twotail_lower(variables.m_idx) = two_tailed_beta_map_cutoff_neg; % put the 2.5th percentil beta values back into the lesion indices in a full volume
variables.vo.fname = fullfile(variables.output_folder.voxelwise,'Beta value cutoff mask (two tail, lower).nii');
svrlsmgui_write_vol(variables.vo, thresholded_twotail_lower);
end
% Now for each permuted beta map, apply the beta mask and determine largest surviving cluster.
h = waitbar(0,'Applying voxelwise beta mask to null data and noting largest null clusters...','Tag','WB');
% Reconstruct the volumes so we can threshold and examine cluster sizes
all_max_cluster_sizes = nan(parameters.PermNumClusterwise,1); % reserve space.
if parameters.PermNumClusterwise > parameters.PermNumVoxelwise, error('Cannot sample more cluster permutations than have been generated by the voxelwise permutation procedure.'); end
handles = UpdateProgress(handles,'Applying voxelwise beta mask to null data and noting largest null clusters...',1);
for f = 1 : parameters.PermNumVoxelwise % go through each frame of generated betas in the null data...
waitbar(f/parameters.PermNumVoxelwise,h) % show progress.
check_for_interrupt(parameters)
frame_length = length(variables.m_idx);
frame_start_index = 1+((f-1)*frame_length); % +1 since not zero indexing
frame_end_index = (frame_start_index-1)+frame_length; % -1 so we are not 1 too long.
relevant_data_frame = all_perm_data.Data(frame_start_index:frame_end_index); % extract the frame
templatevol = zerostemplate; % zeros(nx,ny,nz); % reserve space
templatevol(variables.m_idx) = relevant_data_frame; % put the beta values back in indices.
if parameters.SavePreThresholdedPermutations % then write out raw voxel NON-thresholded images for this permutation.
variables.vo.fname = fullfile(variables.output_folder.clusterwise,['UNthreshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumVoxelwise) '.nii']);
svrlsmgui_write_vol(variables.vo, templatevol);
end
switch parameters.tails
case options.hypodirection{1}
pos_threshed = templatevol .* (templatevol>=thresholded_pos); % elementwise greater than operator to threshold positive tail of test betas
case options.hypodirection{2}
neg_threshed = templatevol .* (templatevol<=thresholded_neg); % elementwise less than operator to threshold negative tail of test betas.
case options.hypodirection{3} % Now build a two-tailed thresholded version
threshmask = and(templatevol > 0,templatevol >= thresholded_twotail_upper) | and(templatevol < 0,templatevol <= thresholded_twotail_lower);
twotail_threshed = templatevol .* threshmask; % mask the two-tailed beta mask for this null data...
end
if parameters.SavePostVoxelwiseThresholdedPermutations % then write out raw voxel thresholded images for this permutation.
switch parameters.tails
case options.hypodirection{1} % 'one_positive'
variables.vo.fname = fullfile(variables.output_folder.clusterwise,['pos_threshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumVoxelwise) '.nii']);
svrlsmgui_write_vol(variables.vo, pos_threshed);
case options.hypodirection{2} %'one_negative'
variables.vo.fname = fullfile(variables.output_folder.clusterwise,['neg_threshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumVoxelwise) '.nii']);
svrlsmgui_write_vol(variables.vo, neg_threshed);
case options.hypodirection{3} %'two'
variables.vo.fname = fullfile(variables.output_folder.clusterwise,['twotail_threshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumVoxelwise) '.nii']);
svrlsmgui_write_vol(variables.vo, twotail_threshed);
end
end
if f <= parameters.PermNumClusterwise
switch parameters.tails
case options.hypodirection{1}
permtype='pos';
thresholded_mask=pos_threshed;
case options.hypodirection{2}
permtype='neg';
thresholded_mask=neg_threshed;
case options.hypodirection{3}
permtype='twotail';
thresholded_mask=twotail_threshed;
end
testvol_thresholded = thresholded_mask; % now evaluate the surviving voxels for clusters...
CC = bwconncomp(testvol_thresholded, 6);
largest_cluster_size = max(cellfun(@numel,CC.PixelIdxList(1,:))); % max val for numels in each cluster object found
if isempty(largest_cluster_size)
largest_cluster_size = 0;
else % threshold the volume and write it out.
if parameters.SavePostClusterwiseThresholdedPermutations % then save them...
out_map = remove_scatter_clusters(testvol_thresholded, largest_cluster_size-1);
variables.vo.fname = fullfile(variables.output_folder.clusterwise,[permtype '_threshed_perm_' num2str(f) '_of_' num2str(parameters.PermNumClusterwise) '_largest_cluster.nii']);
svrlsmgui_write_vol(variables.vo, out_map);
end
end
all_max_cluster_sizes(f) = largest_cluster_size; % record...
end
end
close(h)
% Save the resulting cluster lists
fname = 'Largest clusters.mat';
save(fullfile(variables.output_folder.clusterwise,fname),'all_max_cluster_sizes');
handles = UpdateProgress(handles,'Cleaning up null data...',1);
% Clean up as necessary
if ~parameters.SavePermutationData
fclose all;
delete(outfname_big); % delete the monster bin file with raw permutation data in it.
if exist(outfname_big,'file') % if it still exists...
warning('Was not able to delete large binary file with raw permutation data in it. This file can be quite large, so you may want to manually clean up the file and adjust your permissions so that this is not a problem in the future.')
end
end
% for parallelization to eliminate large overhead transfering to and from workers
function sliceData = extractSlice(all_perm_data,col,L)
sliceData = all_perm_data.Data(col:L:end);
|
github
|
atdemarco/svrlsmgui-master
|
crossval_diagnostics.m
|
.m
|
svrlsmgui-master/functions/unused/crossval_diagnostics.m
| 3,065 |
utf_8
|
02ba5b4ce471ec375db0f8ee55bbdfad
|
function varargout = crossval_diagnostics(varargin)
% CROSSVAL_DIAGNOSTICS MATLAB code for crossval_diagnostics.fig
% CROSSVAL_DIAGNOSTICS, by itself, creates a new CROSSVAL_DIAGNOSTICS or raises the existing
% singleton*.
%
% H = CROSSVAL_DIAGNOSTICS returns the handle to a new CROSSVAL_DIAGNOSTICS or the handle to
% the existing singleton*.
%
% CROSSVAL_DIAGNOSTICS('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CROSSVAL_DIAGNOSTICS.M with the given input arguments.
%
% CROSSVAL_DIAGNOSTICS('Property','Value',...) creates a new CROSSVAL_DIAGNOSTICS or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before crossval_diagnostics_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to crossval_diagnostics_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 crossval_diagnostics
% Last Modified by GUIDE v2.5 21-Feb-2018 11:09:25
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @crossval_diagnostics_OpeningFcn, ...
'gui_OutputFcn', @crossval_diagnostics_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 crossval_diagnostics is made visible.
function crossval_diagnostics_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 crossval_diagnostics (see VARARGIN)
% Choose default command line output for crossval_diagnostics
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes crossval_diagnostics wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = crossval_diagnostics_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;
|
github
|
HelmchenLabSoftware/OCIA-master
|
eventDetector.m
|
.m
|
OCIA-master/caImgAnalysis/eventDetection/eventDetector.m
| 15,135 |
utf_8
|
64d69083f3f62775510da94cfc8f656b
|
function varargout = eventDetector(ROIStats, stim, ROISet, eventDetectMethod, frameRate, bpfilter, psConfig, saveName)
% event detection function - wrapper to different event detection algorithms
% input: structure created by GetRoiStats (*_RoiStats)
dbgLevel = 2;
% required folders
folderList = {'Projects/EventDetect','Projects/TwoPhotonAnalyzer'};
addFolders2Path(folderList,1);
maxRuns = Inf; % for testing
% maxRuns = 2; % for testing
doCaTracesPlot = 1;
doPlotEvents = doCaTracesPlot && 1; %%#ok<NASGU>
doRasterPlot = 1;
doStimEventRasterPlot = 1;
% doPsStimPlot = 1;
doEventCountPlot = 0;
doEventDetection = 1;
o(' #eventDetector: method: "%s", maxRuns = %d ...', eventDetectMethod, maxRuns, 1, dbgLevel);
%% Event detection parameters
[config, V, P] = getDefaultParameters(eventDetectMethod, frameRate); %%#ok<NASGU,ASGLU>
o(' #eventDetector: event detection parameters configured.', 3, dbgLevel);
%% Event detection
% event detection on roiStats
% % last row is neuropil, remove it
% allDFFData(end, :) = [];
% init sizes of data set
nROIs = size(ROIStats, 1);
nRuns = size(ROIStats, 2);
nFrames = size(ROIStats{1, 1}, 2);
% only process requested runs
if nRuns > maxRuns;
nRuns = maxRuns;
ROIStats(:, maxRuns + 1 : end) = [];
end
o(' #eventDetector: variables initialized.', 3, dbgLevel);
o(' #eventDetector: starting event detection ... ', 2, dbgLevel);
eventDetectStartTime = tic;
eventData = cell(size(ROIStats));
residuals = cell(size(ROIStats));
models = cell(size(ROIStats));
eventMatAllRuns = zeros(nROIs, nRuns * size(ROIStats{1, 1}, 2));
stimVectorAllRuns = zeros(1, nRuns * size(ROIStats{1, 1}, 2));
% outerDffData = ROIStats;
nRunsWithError = 0;
nTotEvents = 0;
% nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);
% for iRun = 1 : nRuns;
nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);
for iRun = 7;
try
% ROIStats = outerDffData;
startIndex = (iRun - 1) * nFrames + 1;
endIndex = iRun * nFrames;
eventDetect = config.EventDetect;
o(' #eventDetector: run %d/%d, %d rois...', iRun, nRuns, nROIs, 4, dbgLevel);
if size(stim{iRun}, 2) ~= endIndex - startIndex + 1;
o(' #eventDetector: run %d/%d, %d rois: skip for bad size.', iRun, nRuns, nROIs, 1, dbgLevel);
continue;
end;
stimVectorAllRuns(startIndex : endIndex) = stim{iRun};
eventDetect.rate = frameRate;
% eventCounts = zeros(1, nROIs);
% residuals = zeros(1, nROIs);
currentEventMat = zeros(nROIs, nFrames);
if doEventDetection;
% parfor iROI = 1 : nROIs;
% for iROI = 1 : nROIs;
for iROI = 1 : 3;
o(' #eventDetector: run %d/%d - roi %d/%d ...', iRun, nRuns, iROI, nROIs, 5, dbgLevel);
caTrace = ROIStats{iROI, iRun};
% caTrace = mpi_BandPassFilterTimeSeries(caTrace, 1 / frameRate, bpfilter.low, bpfilter.high); %#ok<PFBNS>
if isempty(caTrace);
warning('eventDetector:caTraceEmpty', 'caTrace is empty!');
continue;
elseif isnan(caTrace);
% warning('eventDetector:caTraceNaN', 'caTrace is NaN!');
eventData{iROI, iRun} = nan(1, nFrames);
continue;
end;
switch lower(eventDetectMethod)
case 'fast_oopsi'
oopsiOut = fast_oopsi(caTrace, V, P);
oopsiOut(oopsiOut < config.EventDetect.oopsi_thr) = 0; %#ok<PFBNS>
currentEventMat(iROI, :) = oopsiOut';
eventData{iROI, iRun} = oopsiOut';
case 'peeling'
% eventOut = doPeeling(eventDetect, caTrace);
[~, ~, peelRes] = Peeling(caTrace, frameRate);
residuals{iROI, iRun} = peelRes.peel;
models{iROI, iRun} = peelRes.model;
% eventCounts(iROI) = sum(peelRes.spiketrain); %%#ok<PFOUS>
% residualVector(iROI) = sum(abs(eventOut.data.peel)) / length(eventOut.data.peel);
currentEventMat(iROI, :) = peelRes.spiketrain;
eventData{iROI, iRun} = peelRes.spiketrain;
end;
nEventsFound = sum(currentEventMat(iROI, :));
nTotEvents = nTotEvents + nEventsFound;
o(' #eventDetector: run %d/%d - roi %d/%d done, %d event(s) found.', ...
iRun, nRuns, iROI, nROIs, nEventsFound, 4, dbgLevel);
end ;
end;
eventMatAllRuns(:, startIndex : endIndex) = currentEventMat;
o(' #eventDetector: run %d/%d done.', iRun, nRuns, 3, dbgLevel);
catch err;
nRunsWithError = nRunsWithError + 1; %#ok<NASGU>
o(' #eventDetector: problem in run %d/%d.', iRun, nRuns, 2, dbgLevel);
rethrow(err);
end;
end;
eventDetectEndTime = toc(eventDetectStartTime);
% PSTraceRoi = PsPlotAnalysisCellArray(ROIStats, stim, psConfig);
o(' #eventDetector: event detection done for %d runs (%d error(s), %d total events, %.2f sec).', ...
nRuns, nRunsWithError, nTotEvents, eventDetectEndTime, 2, dbgLevel);
if ~isempty(eventMatAllRuns) && nTotEvents > 0;
o(' #eventDetector: extracting peri-stimulus events...', 3, dbgLevel);
PSEventRoi = PsPlotAnalysis(eventMatAllRuns, stimVectorAllRuns, psConfig);
config.PsPlotEventRoi = PSEventRoi;
o(' #eventDetector: extracting peri-stimulus events done.', 2, dbgLevel);
else
o(' #eventDetector: no events found (%d).', nTotEvents, 1, dbgLevel);
end
o(' #eventDetector: moving to plotting section ...', 3, dbgLevel);
%% Calcium DFF / DRR Plot - with events
if doCaTracesPlot; % only plot if required
o(' #eventDetector: plotting the calcium DFF (or DRR) Plot with events...', 2, dbgLevel); %#ok<*UNRCH>
% go through each run
% nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);
% for iRun = 1 : nRuns;
nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);
for iRun = 7;
o(' #eventDetector: plotting run %d/%d ...', iRun, nRuns, 4, dbgLevel);
fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name
cell2mat(ROIStats(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix
cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix
stim{iRun}, ... % stimulus as a nFrames long vector
ROISet, ... % name and coordinates of the rois
frameRate, ... % frame rate
bpfilter, ... % band-pass filter settings
eventDetectMethod, ... % used detection method
doPlotEvents); % tells whether to plot the events or not
fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name
cell2mat(residuals(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix
cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix
stim{iRun}, ... % stimulus as a nFrames long vector
ROISet, ... % name and coordinates of the rois
frameRate, ... % frame rate
[], ... % band-pass filter settings
eventDetectMethod, ... % used detection method
doPlotEvents); % tells whether to plot the events or not
fig = plotROICaTracesWithEvent(iRun, saveName, ... % run number and figure name
cell2mat(models(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix
cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix
stim{iRun}, ... % stimulus as a nFrames long vector
ROISet, ... % name and coordinates of the rois
frameRate, ... % frame rate
[], ... % band-pass filter settings
eventDetectMethod, ... % used detection method
doPlotEvents); % tells whether to plot the events or not
o(' #eventDetector: plotting run %d/%d done, saving...', iRun, nRuns, 4, dbgLevel);
% set(fig, 'WindowStyle', 'docked');
if doCaTracesPlot > 1;
if doPlotEvents;
saveName = sprintf('%s_ROICaTracesWithEvents_run%02d_%s', saveName, iRun, ...
eventDetectMethod);
else
saveName = sprintf('%s_ROICaTracesWithoutEvents_run%02d_%s', saveName, iRun, ...
eventDetectMethod);
end;
saveas(fig, saveName);
saveas(fig, [saveName '.png']);
close(fig);
end;
o(' #eventDetector: plotting & saving run %d/%d done.', iRun, nRuns, 3, dbgLevel);
end
o(' #eventDetector: plotting %d run(s) done.', nRuns, 2, dbgLevel);
end;
%% Event count plot
if doEventCountPlot;
o(' #eventDetector: plotting the event counts for ROI image...', 2, dbgLevel); %#ok<*UNRCH>
fig = plotCountROIMap( ...
eventCounts, ... % event counts for each ROI
256, 256, ... % dimensions of the frame
ROISet(1 : end - 1, 2)); % the positions of the ROI
%% TODO HARD CODED IMAGE DIMS
if doEventCountPlot > 1;
set(fig, 'WindowStyle', 'docked');
saveas(fig, sprintf('%s_ROIEventCount_%s', saveName, eventDetectMethod));
saveas(fig, sprintf('%s_ROIEventCount_%s.png', saveName, eventDetectMethod));
close(fig);
end;
o(' #eventDetector: plotting the event counts for ROI image done.', 3, dbgLevel); %#ok<*UNRCH>
end;
%% Population stimulus event raster plot
if doStimEventRasterPlot;
o(' #eventDetector: plotting the peri-stimulus event raster plot ...', 2, dbgLevel); %#ok<*UNRCH>
fig = plotStimEventRaster( ...
'PopRasterSinglePlot', ... % title of the plot
PSEventRoi, ... % event counts around the stimulus
stim{1}, ... % stimuli for extracting their 'name'
psConfig.base, ... % number of frames looked before the stimulus
psConfig.evoked, ... % number of frames looked after the stimulus
frameRate); % frame rate
% set(fig, 'WindowStyle', 'docked');
if doStimEventRasterPlot > 1;
saveas(fig, sprintf('%s_EventStimRaster_%s', saveName, eventDetectMethod));
saveas(fig, sprintf('%s_EventStimRaster_%s.png', saveName, eventDetectMethod));
close(fig);
end;
o(' #eventDetector: plotting the peri-stimulus event raster plot done.', 2, dbgLevel); %#ok<*UNRCH>
end;
% %% Population stimulus plot
% if doPsStimPlot;
% o(' #eventDetector: plotting the peri-stimulus plot ...', 2, dbgLevel); %#ok<*UNRCH>
% fig = plotPSStimPlot( ...
% 'PopPeriStimPlot', ... % title of the plot
% PSTraceRoi, ... % all traces around the stimulus
% stim{1}, ... % stimuli for extracting their 'name'
% psConfig.base, ... % number of frames looked before the stimulus
% psConfig.evoked, ... % number of frames looked after the stimulus
% frameRate); % frame rate
% if doPsStimPlot > 1;
% % set(fig, 'WindowStyle', 'docked');
% saveas(fig, sprintf('%s_PSStimAverage_%s', roiStats.saveName, eventDetectMethod));
% saveas(fig, sprintf('%s_PSStimAverage_%s.png', roiStats.saveName, eventDetectMethod));
% close(fig);
% end;
% o(' #eventDetector: plotting the peri-stimulus plot done.', 2, dbgLevel); %#ok<*UNRCH>
% end;
%% Population raster plot
if doRasterPlot;
o(' #eventDetector: plotting the population raster plot ...', 2, dbgLevel); %#ok<*UNRCH>
cellIDaxes = ROISet(:, 1);
switch lower(eventDetectMethod)
case {'peeling', 'fast_oopsi'};
titleStr = 'PopRaster';
[fig, ~] = PsPlot2Raster(PSEventRoi, frameRate, ...
psConfig.base + 1, cellIDaxes(1 : length(cellIDaxes) - 1), 1, 0);
set(fig, 'Name', titleStr, 'NumberTitle', 'off');
% set(fig, 'WindowStyle', 'docked');
if doRasterPlot > 1;
saveas(fig,sprintf('%s_EventRasterByRoi_%s', saveName, eventDetectMethod));
saveas(fig,sprintf('%s_EventRasterByRoi_%s.png', saveName, eventDetectMethod));
close(fig);
end;
end
o(' #eventDetector: plotting the population raster plot done.', 2, dbgLevel); %#ok<*UNRCH>
end;
%% end
varargout{1} = config;
end
function [config, V, P] = getDefaultParameters(eventDetectMethod, frameRate)
amp = 10;
tau = 2;
onsettau = 0.01;
switch lower(eventDetectMethod);
case 'fast_oopsi';
config.EventDetect.amp = amp;
config.EventDetect.tau = tau;
config.EventDetect.onsettau = onsettau;
config.EventDetect.doPlot = 0; % should be switched off
config.EventDetect.lam = 0.2; % firing rate(ish)
config.EventDetect.base_frames = 10;
config.EventDetect.oopsi_thr = 0.3;
config.EventDetect.integral_thr = 5;
config.EventDetect.filter = [7 2];
config.EventDetect.minGof = 0.5;
P.lam = config.EventDetect.lam;
% P.gam = (1-(1/freq_ca)) / ca_tau;
V.dt = 1/frameRate;
V.est_gam = 1; % estimate decay time parameter (does not work)
V.est_sig = 1; % estimate baseline noise SD
V.est_lam = 1; % estimate firing rate
V.est_a = 0; % estimate spatial filter
V.est_b = 0; % estimate background fluo.
V.fast_thr = 1;
V.fast_iter_max = 3;
case 'peeling';
V = [];
P = [];
config.EventDetect.optimizeSpikeTimes = 0;
config.EventDetect.schmittHi = [1.75 0 3];
config.EventDetect.schmittLo = [-1 -3 0];
config.EventDetect.schmittMinDur = [0.3 0.05 3];
config.EventDetect.A1 = amp;
config.EventDetect.tau1 = tau;
config.EventDetect.onsettau = onsettau;
config.EventDetect.optimMethod = 'none';
config.EventDetect.minPercentChange = 0.1;
config.EventDetect.maxIter = 20;
config.EventDetect.plotFinal = 0;
case 'none';
config = [];
V = [];
P = [];
warning('Nothing to do here! Exit ...')
return;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
eventDetector_old.m
|
.m
|
OCIA-master/caImgAnalysis/eventDetection/eventDetector_old.m
| 12,802 |
utf_8
|
ad7f17e5b4904c061333c7f354dac6c0
|
function varargout = eventDetector(roiStats, eventDetectMethod)
% event detection function - wrapper to different event detection algorithms
% input: structure created by GetRoiStats (*_RoiStats)
dbgLevel = 2;
% required folders
folderList = {'Projects/EventDetect','Projects/TwoPhotonAnalyzer'};
addFolders2Path(folderList,1);
maxRuns = Inf; % for testing
% maxRuns = 2; % for testing
doCaTracesPlot = 1;
doPlotEvents = doCaTracesPlot && 0; %%#ok<NASGU>
doRasterPlot = 0;
doStimEventRasterPlot = 0;
doPsStimPlot = 0;
doEventCountPlot = 0;
doEventDetection = 0;
o(' #eventDetector: method: "%s", maxRuns = %d ...', eventDetectMethod, maxRuns, 1, dbgLevel);
%% Event detection parameters
[config, V, P] = getDefaultParameters(eventDetectMethod, roiStats.frameRate{1}); %%#ok<NASGU,ASGLU>
o(' #eventDetector: event detection parameters configured.', 3, dbgLevel);
%% Event detection
% event detection on roiStats
allDFFData = roiStats.dataRoi;
% last row is neuropil, remove it
allDFFData(end, :) = [];
% init sizes of data set
nROIs = size(allDFFData, 1);
nRuns = size(allDFFData, 2);
nFrames = size(allDFFData{1, 1}, 2);
% only process requested runs
if nRuns > maxRuns;
nRuns = maxRuns;
allDFFData(:, maxRuns + 1 : end) = [];
end
o(' #eventDetector: variables initialized.', 3, dbgLevel);
o(' #eventDetector: starting event detection ... ', 2, dbgLevel);
eventDetectStartTime = tic;
eventData = cell(size(allDFFData));
eventMatAllRuns = zeros(nROIs, nRuns * size(allDFFData{1, 1}, 2));
StimVectorAllRuns = zeros(1, nRuns * size(allDFFData{1, 1}, 2));
outerDffData = allDFFData;
nRunsWithError = 0;
nTotEvents = 0;
% nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);
for iRun = 1 : nRuns;
try
allDFFData = outerDffData;
startIndex = (iRun - 1) * nFrames + 1;
endIndex = iRun * nFrames;
eventDetect = config.EventDetect;
o(' #eventDetector: run %d/%d, %d rois...', iRun, nRuns, nROIs, 4, dbgLevel);
if size(roiStats.stim{iRun}, 2) ~= startIndex - endIndex + 1;
o(' #eventDetector: run %d/%d, %d rois: skip for bad size.', iRun, nRuns, nROIs, 1, dbgLevel);
continue;
end;
StimVectorAllRuns(startIndex : endIndex) = roiStats.stim{iRun};
eventDetect.rate = roiStats.frameRate{iRun};
eventCounts = zeros(1, nROIs);
% residualVector = zeros(1,nROIs);
currentEventMat = zeros(nROIs, nFrames);
if doEventDetection;
parfor iRoi = 1 : nROIs;
o(' #eventDetector: run %d/%d - roi %d/%d ...', iRun, nRuns, iRoi, nROIs, 5, dbgLevel);
dff = allDFFData{iRoi, iRun};
if isempty(dff);
warning('eventDetector:dffEmpty', 'dff is empty!');
continue;
end;
switch lower(eventDetectMethod)
case 'fast_oopsi'
oopsiOut = fast_oopsi(dff, V, P);
oopsiOut(oopsiOut < config.EventDetect.oopsi_thr) = 0; %#ok<PFBNS>
currentEventMat(iRoi, :) = oopsiOut';
eventData{iRoi, iRun} = oopsiOut';
case 'peeling'
eventOut = doPeeling(eventDetect,dff);
% residual{iRoi,iRun} = eventOut.data.peel;
% model{iRoi,iRun} = eventOut.data.model;
eventCounts(iRoi) = sum(eventOut.data.spiketrain); %%#ok<PFOUS>
% residualVector(iRoi) = sum(abs(eventOut.data.peel)) / length(eventOut.data.peel);
currentEventMat(iRoi, :) = eventOut.data.spiketrain;
eventData{iRoi, iRun} = eventOut.data.spiketrain;
end;
nEventsFound = sum(currentEventMat(iRoi, :));
nTotEvents = nTotEvents + nEventsFound;
o(' #eventDetector: run %d/%d - roi %d/%d done, %d event(s) found.', ...
iRun, nRuns, iRoi, nROIs, nEventsFound, 4, dbgLevel);
end ;
end;
eventMatAllRuns(:, startIndex : endIndex) = currentEventMat;
o(' #eventDetector: run %d/%d done.', iRun, nRuns, 3, dbgLevel);
catch err;
nRunsWithError = nRunsWithError + 1; %#ok<NASGU>
o(' #eventDetector: problem in run %d/%d.', iRun, nRuns, 2, dbgLevel);
rethrow(err);
end;
end;
eventDetectEndTime = toc(eventDetectStartTime);
PSTraceRoi = PsPlotAnalysis(cell2mat(allDFFData(:, :)), StimVectorAllRuns, roiStats.psConfig);
o(' #eventDetector: event detection done for %d runs (%d error(s), %d total events, %.2f sec).', ...
nRuns, nRunsWithError, nTotEvents, eventDetectEndTime, 2, dbgLevel);
if ~isempty(eventMatAllRuns) && nTotEvents > 0;
o(' #eventDetector: extracting peri-stimulus events...', 3, dbgLevel);
PSEventRoi = PsPlotAnalysis(eventMatAllRuns, StimVectorAllRuns, roiStats.psConfig);
config.PsPlotEventRoi = PSEventRoi;
o(' #eventDetector: extracting peri-stimulus events done.', 2, dbgLevel);
else
o(' #eventDetector: no events found (%d).', nTotEvents, 1, dbgLevel);
end
o(' #eventDetector: moving to plotting section ...', 3, dbgLevel);
%% Calcium DFF / DRR Plot - with events
if doCaTracesPlot; % only plot if required
o(' #eventDetector: plotting the calcium DFF (or DRR) Plot with events...', 2, dbgLevel); %#ok<*UNRCH>
% go through each run
% nRuns = 1; o('/!\\ WARNING: overriding nRuns! nRuns is now = %d.', nRuns, 0, 0);
for iRun = 1 : nRuns;
o(' #eventDetector: plotting run %d/%d ...', iRun, nRuns, 4, dbgLevel);
fig = plotROICaTraces(iRun, roiStats.saveName, ... % run number and figure name
cell2mat(allDFFData(:, iRun)), ... % calcium traces as a nROI-by-nFrames matrix
cell2mat(eventData(:, iRun)), ... % detected events as a nROI-by-nFrames matrix
roiStats.stim{iRun}, ... % stimulus as a nFrames long vector
roiStats.ROISet, ... % name and coordinates of the rois
roiStats.frameRate{1}, ... % frame rate
eventDetectMethod, ... % used detection method
doPlotEvents); % tells whether to plot the events or not
o(' #eventDetector: plotting run %d/%d done, saving...', iRun, nRuns, 4, dbgLevel);
set(fig, 'WindowStyle', 'docked');
if doPlotEvents;
saveName = sprintf('%s_ROICaTracesWithEvents_run%02d_%s', roiStats.saveName, iRun, ...
eventDetectMethod);
else
saveName = sprintf('%s_ROICaTracesWithoutEvents_run%02d_%s', roiStats.saveName, iRun, ...
eventDetectMethod);
end;
saveas(fig, saveName);
saveas(fig, [saveName '.png']);
close(fig);
o(' #eventDetector: plotting & saving run %d/%d done.', iRun, nRuns, 3, dbgLevel);
end
o(' #eventDetector: plotting %d run(s) done.', nRuns, 2, dbgLevel);
end;
%% Event count plot
if doEventCountPlot;
o(' #eventDetector: plotting the event counts for ROI image...', 2, dbgLevel); %#ok<*UNRCH>
fig = plotCountROIMap( ...
eventCounts, ... % event counts for each ROI
roiStats.img_dims(1), roiStats.img_dims(2), ... % dimensions of the frame
roiStats.ROISet(1 : end - 1, 2)); % the positions of the ROI
set(fig, 'WindowStyle', 'docked');
saveas(fig, sprintf('%s_ROIEventCount_%s', roiStats.saveName, eventDetectMethod));
saveas(fig, sprintf('%s_ROIEventCount_%s.png', roiStats.saveName, eventDetectMethod));
close(fig);
o(' #eventDetector: plotting the event counts for ROI image done.', 3, dbgLevel); %#ok<*UNRCH>
end;
%% Population stimulus event raster plot
if doStimEventRasterPlot;
o(' #eventDetector: plotting the peri-stimulus event raster plot ...', 2, dbgLevel); %#ok<*UNRCH>
fig = plotStimEventRaster( ...
'PopRasterSinglePlot', ... % title of the plot
PSEventRoi, ... % event counts around the stimulus
roiStats.stim{1}, ... % stimuli for extracting their 'name'
roiStats.psConfig.baseFrames, ... % number of frames looked before the stimulus
roiStats.psConfig.evokedFrames, ... % number of frames looked after the stimulus
roiStats.frameRate{1}); % frame rate
set(fig, 'WindowStyle', 'docked');
saveas(fig, sprintf('%s_EventStimRaster_%s', roiStats.saveName, eventDetectMethod));
saveas(fig, sprintf('%s_EventStimRaster_%s.png', roiStats.saveName, eventDetectMethod));
close(fig);
o(' #eventDetector: plotting the peri-stimulus event raster plot done.', 2, dbgLevel); %#ok<*UNRCH>
end;
%% Population stimulus plot
if doPsStimPlot;
o(' #eventDetector: plotting the peri-stimulus plot ...', 2, dbgLevel); %#ok<*UNRCH>
fig = plotPSStimPlot( ...
'PopPeriStimPlot', ... % title of the plot
PSTraceRoi, ... % all traces around the stimulus
roiStats.stim{1}, ... % stimuli for extracting their 'name'
roiStats.psConfig.baseFrames, ... % number of frames looked before the stimulus
roiStats.psConfig.evokedFrames, ... % number of frames looked after the stimulus
roiStats.frameRate{1}); % frame rate
set(fig, 'WindowStyle', 'docked');
saveas(fig, sprintf('%s_PSStimAverage_%s', roiStats.saveName, eventDetectMethod));
saveas(fig, sprintf('%s_PSStimAverage_%s.png', roiStats.saveName, eventDetectMethod));
close(fig);
o(' #eventDetector: plotting the peri-stimulus plot done.', 2, dbgLevel); %#ok<*UNRCH>
end;
%% Population raster plot
if doRasterPlot;
o(' #eventDetector: plotting the population raster plot ...', 2, dbgLevel); %#ok<*UNRCH>
roiSet = roiStats.ROISet;
cellIDaxes = roiSet(:, 1);
switch lower(eventDetectMethod)
case {'peeling', 'fast_oopsi'};
titleStr = 'PopRaster';
[fig, ~] = PsPlot2Raster(PSEventRoi, roiStats.frameRate{1}, ...
roiStats.psConfig.baseFrames + 1, cellIDaxes(1 : length(cellIDaxes) - 1), 1, 0);
set(fig, 'Name', titleStr, 'NumberTitle', 'off');
set(fig, 'WindowStyle', 'docked');
saveas(fig,sprintf('%s_EventRasterByRoi_%s', roiStats.saveName, eventDetectMethod));
saveas(fig,sprintf('%s_EventRasterByRoi_%s.png', roiStats.saveName, eventDetectMethod));
close(fig);
end
o(' #eventDetector: plotting the population raster plot done.', 2, dbgLevel); %#ok<*UNRCH>
end;
%% end
varargout{1} = config;
end
function [config, V, P] = getDefaultParameters(eventDetectMethod, frameRate)
amp = 10;
tau = 2;
onsettau = 0.01;
switch lower(eventDetectMethod);
case 'fast_oopsi';
config.EventDetect.amp = amp;
config.EventDetect.tau = tau;
config.EventDetect.onsettau = onsettau;
config.EventDetect.doPlot = 0; % should be switched off
config.EventDetect.lam = 0.2; % firing rate(ish)
config.EventDetect.base_frames = 10;
config.EventDetect.oopsi_thr = 0.3;
config.EventDetect.integral_thr = 5;
config.EventDetect.filter = [7 2];
config.EventDetect.minGof = 0.5;
P.lam = config.EventDetect.lam;
% P.gam = (1-(1/freq_ca)) / ca_tau;
V.dt = 1/frameRate;
V.est_gam = 1; % estimate decay time parameter (does not work)
V.est_sig = 1; % estimate baseline noise SD
V.est_lam = 1; % estimate firing rate
V.est_a = 0; % estimate spatial filter
V.est_b = 0; % estimate background fluo.
V.fast_thr = 1;
V.fast_iter_max = 3;
case 'peeling';
V = [];
P = [];
config.EventDetect.optimizeSpikeTimes = 0;
config.EventDetect.schmittHi = [1.75 0 3];
config.EventDetect.schmittLo = [-1 -3 0];
config.EventDetect.schmittMinDur = [0.3 0.05 3];
config.EventDetect.A1 = amp;
config.EventDetect.tau1 = tau;
config.EventDetect.onsettau = onsettau;
config.EventDetect.optimMethod = 'none';
config.EventDetect.minPercentChange = 0.1;
config.EventDetect.maxIter = 20;
config.EventDetect.plotFinal = 0;
case 'none';
config = [];
V = [];
P = [];
warning('Nothing to do here! Exit ...')
return;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
PeelingOptimizeSpikeTimesSaturation.m
|
.m
|
OCIA-master/caImgAnalysis/eventDetection/newPeeling/PeelingOptimizeSpikeTimesSaturation.m
| 4,465 |
utf_8
|
82892eced9f5fb70e0d8ad3f544df164
|
function [spkTout,output] = PeelingOptimizeSpikeTimesSaturation(dff,spkTin,lowerT,upperT,...
ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas, kd, conc, dffmax, frameRate, dur, optimMethod,maxIter,doPlot)
% optimization of spike times found by Peeling algorithm
% minimize the sum of the residual squared
% while several optimization algorithms are implemented (see below), we have only used pattern
% search. Other algorithms are only provided for convenience and are not tested sufficiently.
%
% Henry Luetcke ([email protected])
% Brain Research Institut
% University of Zurich
% Switzerland
spkTout = spkTin;
t = (1:numel(dff))./frameRate;
ca = spkTimes2FreeCalcium(spkTin,ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas,...
kd, conc,frameRate,dur);
modeltmp = Calcium2Fluor(ca,ca_rest,kd,dffmax);
model = modeltmp(1:length(dff));
if doPlot
figure('Name','Before Optimization')
plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b')
legend('DFF','Model','Residual')
end
residual = dff - model;
resInit = sum(residual.^2);
% start optimization
x0 = spkTin;
lbound = spkTin - lowerT;
lbound(lbound<0) = 0;
ubound = spkTin + upperT;
ubound(ubound>max(t)) = max(t);
lbound = zeros(size(spkTin));
ubound = repmat(max(t),size(spkTin));
opt_args.dff = dff;
opt_args.ca_rest = ca_rest;
opt_args.ca_amp = ca_amp;
opt_args.ca_gamma = ca_gamma;
opt_args.ca_onsettau = ca_onsettau;
opt_args.ca_kappas = ca_kappas;
opt_args.kd = kd;
opt_args.conc = conc;
opt_args.dffmax = dffmax;
opt_args.frameRate = frameRate;
opt_args.dur = dur;
optimClock = tic;
switch lower(optimMethod)
case 'simulated annealing'
options = saoptimset;
case 'pattern search'
options = psoptimset;
case 'genetic'
options = gaoptimset;
otherwise
error('Optimization method %s not supported.',optimMethod)
end
% options for optimization algorithms
% not all options are used for all algorithms
options.Display = 'off';
options.MaxIter = maxIter;
options.MaxIter = Inf;
options.UseParallel = 'always';
options.ObjectiveLimit = 0;
options.TimeLimit = 10; % in s / default is Inf
% experimental
options.MeshAccelerator = 'on'; % off by default
options.TolFun = 1e-9; % default is 1e-6
options.TolMesh = 1e-9; % default is 1e-6
options.TolX = 1e-9; % default is 1e-6
% options.MaxFunEvals = numel(spkTin)*100; % default is 2000*numberOfVariables
% options.MaxFunEvals = 20000;
options.Display = 'none';
% options.Display = 'final';
% options.PlotFcns = {@psplotbestf @psplotbestx};
% options.OutputFcns = @psoutputfcn_peel;
switch lower(optimMethod)
case 'simulated annealing'
[x, fval , exitFlag, output] = simulannealbnd(...
@(x) objectiveFunc(x,opt_args),x0,lbound,ubound,options);
case 'pattern search'
[x, fval , exitFlag, output] = patternsearch(...
@(x) objectiveFunc(x,opt_args),x0,[],[],[],[],lbound,...
ubound,[],options);
case 'genetic'
[x, fval , exitFlag, output] = ga(...
@(x) objectiveFunc(x,opt_args),numel(x0),[],[],[],[],lbound,...
ubound,[],options);
end
if fval < resInit
spkTout = x;
else
disp('Optimization did not improve residual. Keeping input spike times.')
end
if doPlot
fprintf('Optimization time (%s): %1.2f s\n',optimMethod,toc(optimClock))
fprintf('Final squared residual: %1.2f (Change: %1.2f)\n',fval,resInit-fval);
spkVector = zeros(1,numel(t));
for i = 1:numel(spkTout)
[~,idx] = min(abs(spkTout(i)-t));
spkVector(idx) = spkVector(idx)+1;
end
model = conv(spkVector,modelTransient);
model = model(1:length(t));
figure('Name','After Optimization')
plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b')
legend('DFF','Model','Residual')
end
function residual = objectiveFunc(spkTin,opt_args)
dff = opt_args.dff;
ca_rest = opt_args.ca_rest;
ca_amp = opt_args.ca_amp;
ca_gamma = opt_args.ca_gamma;
ca_onsettau = opt_args.ca_onsettau;
ca_kappas = opt_args.ca_kappas;
kd = opt_args.kd;
conc = opt_args.conc;
dffmax = opt_args.dffmax;
frameRate = opt_args.frameRate;
dur = opt_args.dur;
ca = spkTimes2FreeCalcium(sort(spkTin),ca_amp,ca_gamma,ca_onsettau,ca_rest, ca_kappas,...
kd, conc,frameRate,dur);
modeltmp = Calcium2Fluor(ca,ca_rest,kd,dffmax);
model = modeltmp(1:length(dff));
residual = dff-model;
residual = sum(residual.^2);
|
github
|
HelmchenLabSoftware/OCIA-master
|
PeelingOptimizeSpikeTimes.m
|
.m
|
OCIA-master/caImgAnalysis/eventDetection/newPeeling/PeelingOptimizeSpikeTimes.m
| 4,159 |
utf_8
|
61e419a2e0808657c62b39f38bc0fb60
|
function [spkTout,output] = PeelingOptimizeSpikeTimes(dff,spkTin,lowerT,upperT,...
rate,tauOn,A1,tau1,optimMethod,maxIter,doPlot)
% optimization of spike times found by Peeling algorithm
% minimize the sum of the residual squared
% while several optimization algorithms are implemented (see below), we have only used pattern
% search. Other algorithms are only provided for convenience and are not tested sufficiently.
%
% Henry Luetcke ([email protected])
% Brain Research Institut
% University of Zurich
% Switzerland
t = (1:numel(dff))./rate;
modelTransient = modelCalciumTransient(t,t(1),tauOn,A1,tau1);
modelTransient = modelTransient';
spkTout = spkTin;
spkVector = zeros(1,numel(t));
for i = 1:numel(spkTin)
[~,idx] = min(abs(spkTin(i)-t));
spkVector(idx) = spkVector(idx)+1;
end
model = conv(spkVector,modelTransient);
model = model(1:length(t));
if doPlot
figure('Name','Before Optimization')
plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b')
legend('DFF','Model','Residual')
end
residual = dff - model;
resInit = sum(residual.^2);
% start optimization
x0 = spkTin;
lbound = spkTin - lowerT;
lbound(lbound<0) = 0;
ubound = spkTin + upperT;
ubound(ubound>max(t)) = max(t);
lbound = zeros(size(spkTin));
ubound = repmat(max(t),size(spkTin));
opt_args.dff = dff;
opt_args.rate = rate;
opt_args.tauOn = tauOn;
opt_args.A1 = A1;
opt_args.tau1 = tau1;
optimClock = tic;
switch lower(optimMethod)
case 'simulated annealing'
options = saoptimset;
case 'pattern search'
options = psoptimset;
case 'genetic'
options = gaoptimset;
otherwise
error('Optimization method %s not supported.',optimMethod)
end
% options for optimization algorithms
% not all options are used for all algorithms
options.Display = 'off';
options.MaxIter = maxIter;
options.MaxIter = Inf;
options.UseParallel = 'always';
options.ObjectiveLimit = 0;
% options.TimeLimit = 10; % in s / default is Inf
% experimental
options.MeshAccelerator = 'on'; % off by default
options.TolFun = 1e-9; % default is 1e-6
options.TolMesh = 1e-9; % default is 1e-6
options.TolX = 1e-9; % default is 1e-6
% options.MaxFunEvals = numel(spkTin)*100; % default is 2000*numberOfVariables
% options.MaxFunEvals = 20000;
options.Display = 'none';
% options.Display = 'final';
% options.PlotFcns = {@psplotbestf @psplotbestx};
% options.OutputFcns = @psoutputfcn_peel;
switch lower(optimMethod)
case 'simulated annealing'
[x, fval , exitFlag, output] = simulannealbnd(...
@(x) objectiveFunc(x,opt_args),x0,lbound,ubound,options);
case 'pattern search'
[x, fval , exitFlag, output] = patternsearch(...
@(x) objectiveFunc(x,opt_args),x0,[],[],[],[],lbound,...
ubound,[],options);
case 'genetic'
[x, fval , exitFlag, output] = ga(...
@(x) objectiveFunc(x,opt_args),numel(x0),[],[],[],[],lbound,...
ubound,[],options);
end
if fval < resInit
spkTout = x;
else
disp('Optimization did not improve residual. Keeping input spike times.')
end
if doPlot
fprintf('Optimization time (%s): %1.2f s\n',optimMethod,toc(optimClock))
fprintf('Final squared residual: %1.2f (Change: %1.2f)\n',fval,resInit-fval);
spkVector = zeros(1,numel(t));
for i = 1:numel(spkTout)
[~,idx] = min(abs(spkTout(i)-t));
spkVector(idx) = spkVector(idx)+1;
end
model = conv(spkVector,modelTransient);
model = model(1:length(t));
figure('Name','After Optimization')
plot(t,dff,'k'), hold on, plot(t,model,'r'), plot(t,dff-model,'b')
legend('DFF','Model','Residual')
end
function residual = objectiveFunc(spkTin,opt_args)
dff = opt_args.dff;
rate = opt_args.rate;
tauOn = opt_args.tauOn;
A1 = opt_args.A1;
tau1 = opt_args.tau1;
t = (1:numel(dff))./rate;
modelTransient = spkTimes2Calcium(0,tauOn,A1,tau1,0,0,rate,max(t));
spkVector = zeros(1,numel(t));
for i = 1:numel(spkTin)
[~,idx] = min(abs(spkTin(i)-t));
spkVector(idx) = spkVector(idx)+1;
end
model = conv(spkVector,modelTransient);
model = model(1:length(t));
residual = dff-model;
residual = sum(residual.^2);
|
github
|
HelmchenLabSoftware/OCIA-master
|
Peeling.m
|
.m
|
OCIA-master/caImgAnalysis/eventDetection/newPeeling/Peeling.m
| 9,350 |
utf_8
|
feca5c14c59423537078bfaf885a57e7
|
function [ca_p, peel_p, data] = Peeling(dff, rate, varargin)
% this is the main routine of the peeling algorithm
%
% Peeling algorithm was developed by Fritjof Helmchen
% Brain Research Institute
% University of Zurich
% Switzerland
%
% Matlab implementation and spike timing optimization by Henry Luetcke & Fritjof Helmchen
% Brain Research Institute
% University of Zurich
% Switzerland
%
% Please cite:
% Grewe BF, Langer D, Kasper H, Kampa BM, Helmchen F. High-speed in vivo calcium imaging
% reveals neuronal network activity with near-millisecond precision.
% Nat Methods. 2010 May;7(5):399-405.
maxRate_peel = Inf;
if rate > maxRate_peel
peel_rate = maxRate_peel;
fit_rate = rate;
x = 1/rate:1/rate:numel(dff)/rate;
xi = 1/peel_rate:1/peel_rate:max(x);
peel_dff = interp1(x,dff,xi);
else
peel_rate = rate;
fit_rate = rate;
peel_dff = dff;
end
[ca_p,exp_p,peel_p, data] = InitPeeling(peel_dff, peel_rate);
if nargin > 2
for n = 1:numel(varargin)
S = varargin{n};
if n == 1
ca_p = overrideFieldValues(ca_p,S);
elseif n == 2
exp_p = overrideFieldValues(exp_p,S);
elseif n == 3
peel_p = overrideFieldValues(peel_p,S);
end
end
end
data.model = 0;
data.freecamodel = ca_p.ca_rest;
data.spikes = zeros(1,1000);
data.numspikes = 0;
data.peel = data.dff;
wsiz = round(peel_p.slidwinsiz*exp_p.acqrate);
checkwsiz = round(peel_p.negintwin*exp_p.acqrate);
peel_p.smttmindurFrames = ceil(peel_p.smttmindur*exp_p.acqrate);
peel_p.smttlowMinEvents = 1;
nexttim = 1/exp_p.acqrate;
[ca_p, peel_p, data] = FindNextEvent(ca_p, exp_p, peel_p, data, nexttim);
if (peel_p.evtfound == 1)
data.numspikes = data.numspikes + 1;
data.spikes(data.numspikes) = peel_p.nextevt;
[ca_p, exp_p, data] = SingleFluorTransient(ca_p, exp_p, data, peel_p.spk_recmode, peel_p.nextevt);
data.model = data.model + data.singleTransient;
end
maxiter = 999999;
iter = 0;
nexttimMem = Inf;
nexttimCounter = 0;
timeStepForward = 2./exp_p.acqrate;
while (peel_p.evtfound == 1)
% check integral after subtracting Ca transient
if (peel_p.spk_recmode == 'linDFF')
elseif (peel_p.spk_recmode == 'satDFF')
ca_p.onsetposition = peel_p.nextevt;
ca_p = IntegralofCaTransient(ca_p, peel_p, exp_p, data);
end
dummy = data.peel - data.singleTransient;
[~,startIdx] = min(abs(data.tim-data.spikes(data.numspikes)));
[~,stopIdx] = min(abs(data.tim-(data.spikes(data.numspikes)+...
peel_p.intcheckwin)));
if startIdx < stopIdx
currentTim = data.tim(startIdx:stopIdx);
currentPeel = dummy(startIdx:stopIdx);
currentIntegral = trapz(currentTim,currentPeel);
else
% if this is true, startIdx is the last data point and we should
% not accept it as a spike
currentIntegral = ca_p.negintegral*peel_p.negintacc;
end
if currentIntegral > (ca_p.negintegral*peel_p.negintacc)
data.peel = data.peel - data.singleTransient;
nexttim = data.spikes(data.numspikes) - peel_p.stepback;
if (nexttim < 0)
nexttim = 1/exp_p.acqrate;
end
else
data.spikes(data.numspikes) = [];
data.numspikes = data.numspikes-1;
data.model = data.model - data.singleTransient;
nexttim = peel_p.nextevt + timeStepForward;
end
peel_p.evtaccepted = 0;
[ca_p, peel_p, data] = FindNextEvent(ca_p, exp_p, peel_p, data, nexttim);
if peel_p.evtfound
data.numspikes = data.numspikes + 1;
data.spikes(data.numspikes) = peel_p.nextevt;
[ca_p, exp_p, data] = SingleFluorTransient(ca_p, exp_p, data, peel_p.spk_recmode, peel_p.nextevt);
data.model = data.model + data.singleTransient;
else
break
end
iter = iter + 1;
if nexttim == nexttimMem
nexttimCounter = nexttimCounter + 1;
else
nexttimMem = nexttim;
nexttimCounter = 0;
end
%%
if nexttimCounter > 50
nexttim = nexttim + timeStepForward;
end
if (iter > maxiter)
% warning('Reached maxiter (%1.0f). nexttim=%1.2f. Timeout!',maxiter,nexttim);
% save
% error('Covergence failed!')
break
end
end
if length(data.spikes) > data.numspikes
data.spikes(data.numspikes+1:end) = [];
end
% go back to original frame rate
if rate > maxRate_peel
spikes = data.spikes;
[ca_p,exp_p,peel_p, data] = InitPeeling(dff, fit_rate);
if nargin > 2
for n = 1:numel(varargin)
S = varargin{n};
if n == 1
ca_p = overrideFieldValues(ca_p,S);
elseif n == 2
exp_p = overrideFieldValues(exp_p,S);
elseif n == 3
peel_p = overrideFieldValues(peel_p,S);
end
end
end
data.spikes = spikes;
end
% optimization of reconstructed spike times to improve timing
optMethod = 'pattern search';
optMaxIter = 100000;
%lowerT = 1; % relative to x0
%upperT = 1; % relative to x0
lowerT = 0.1; % relative to x0
upperT = 0.1; % relative to x0
if numel(data.spikes) && peel_p.optimizeSpikeTimes
if (peel_p.spk_recmode == 'linDFF')
spikes = PeelingOptimizeSpikeTimes(data.dff,data.spikes,lowerT,upperT,...
exp_p.acqrate,ca_p.onsettau,ca_p.amp1,ca_p.tau1,optMethod,optMaxIter,0);
elseif (peel_p.spk_recmode == 'satDFF')
spikes = PeelingOptimizeSpikeTimesSaturation(data.dff,data.spikes,lowerT,upperT,...
ca_p.ca_amp,ca_p.ca_gamma,ca_p.ca_onsettau,ca_p.ca_rest,ca_p.ca_kappas, exp_p.kd,...
exp_p.conc,exp_p.dffmax, exp_p.acqrate, length(data.dff)./exp_p.acqrate, optMethod,optMaxIter,0);
else
error('Undefined mode');
end
data.spikes = sort(spikes);
end
% fit onset to improve timing accuracy
if peel_p.fitonset
onsetfittype = fittype('modelCalciumTransient(t,onsettime,onsettau,amp1,tau1)',...
'independent','t','coefficients',{'onsettime','onsettau','amp1'},...
'problem',{'tau1'});
wleft = round(peel_p.fitwinleft*exp_p.acqrate); % left window for onset fit
wright = round(peel_p.fitwinright*exp_p.acqrate); % right window for onset fit
for i = 1:numel(data.spikes)
[~,idx] = min(abs(data.spikes(i)-data.tim));
if (idx-wleft) < 1
currentwin = data.dff(1:idx+wright);
currenttim = data.tim(1:idx+wright);
elseif (idx+wright) > numel(data.dff)
currentwin = data.dff(idx-wleft:numel(data.dff));
currenttim = data.tim(idx-wleft:numel(data.dff));
currentwin = currentwin - mean(data.dff(idx-wleft:idx));
else
currentwin = data.dff(idx-wleft:idx+wright);
currenttim = data.tim(idx-wleft:idx+wright);
currentwin = currentwin - mean(data.dff(idx-wleft:idx));
end
lowerBounds = [currenttim(1) 0.1*ca_p.onsettau 0.5*ca_p.amp1];
upperBounds = [currenttim(end) 5*ca_p.onsettau 10*ca_p.amp1];
startPoint = [data.spikes(i) ca_p.onsettau ca_p.amp1];
problemParams = {ca_p.tau1};
fOptions = fitoptions('Method','NonLinearLeastSquares','Lower',...
lowerBounds,...
'Upper',upperBounds,'StartPoint',startPoint);
[fitonset,gof] = fit(currenttim',currentwin',onsetfittype,...
'problem',problemParams,fOptions);
if gof.rsquare < 0.95
% fprintf('\nBad onset fit (t=%1.3f, r^2=%1.3f)\n',...
% data.spikes(i),gof.rsquare);
else
% fprintf('\nGood onset fit (r^2=%1.3f)\n',gof.rsquare);
data.spikes(i) = fitonset.onsettime;
end
end
end
% loop to create spike train vector from spike times
data.spiketrain = zeros(1,numel(data.tim));
for i = 1:numel(data.spikes)
[~,idx] = min(abs(data.spikes(i)-data.tim));
data.spiketrain(idx) = data.spiketrain(idx)+1;
end
% re-derive model and residuals after optimization
if (peel_p.spk_recmode == 'linDFF')
modelTransient = spkTimes2Calcium(0,ca_p.onsettau,ca_p.amp1,ca_p.tau1,...
ca_p.amp2,ca_p.tau2,exp_p.acqrate,max(data.tim));
data.model = conv(data.spiketrain,modelTransient);
data.model = data.model(1:length(data.tim));
elseif (peel_p.spk_recmode == 'satDFF')
modeltmp = spkTimes2FreeCalcium(data.spikes,ca_p.ca_amp,ca_p.ca_gamma,ca_p.ca_onsettau,ca_p.ca_rest, ca_p.ca_kappas,...
exp_p.kd, exp_p.conc,exp_p.acqrate,max(data.tim));
data.model = Calcium2Fluor(modeltmp,ca_p.ca_rest,exp_p.kd, exp_p.dffmax);
end
data.peel = data.dff - data.model;
% plotting parameter
if isfield(peel_p,'doPlot')
if peel_p.doPlot
doPlot = 1;
else
doPlot = 0;
end
else
doPlot = 0;
end
if doPlot % plots at interpolation rate
figure; plot(data.tim,data.peel); hold all
plot(data.tim,data.dff); hold all
plot(data.tim,data.spiketrain,'LineWidth',2)
legend({'Residual','Calcium','UPAPs'}) % unverified putative action potential
end
end
function Sout = overrideFieldValues(Sout,Sin)
fieldIDs = fieldnames(Sin);
for n = 1:numel(fieldIDs)
Sout.(fieldIDs{n}) = Sin.(fieldIDs{n});
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
CalciumDecay.m
|
.m
|
OCIA-master/caImgAnalysis/eventDetection/newPeeling/CalciumDecay.m
| 1,116 |
utf_8
|
67138b4224a9d6e8edefa5aa8b387b8e
|
function [t,X] = CalciumDecay(p_gamma,p_carest,p_cacurrent,p_kappas,p_kd,p_conc,tspan)
% Uses ODE45 to solve Single-compartment model differential equation
%
% Fritjof Helmchen ([email protected])
% Brain Research Institute,University of Zurich, Switzerland
% created: 7.10.2013, last update: 25.10.2013 fh
options=odeset('RelTol',1e-6); % set an error
Xo = p_cacurrent; % initial conditions
mypar = [p_gamma,p_carest,p_kappas,p_kd,p_conc]; % parameters
[t,X] = ode45(@Relax2CaRest,tspan,Xo,options, mypar); % call the solver, tspan should contain time vector with more than two elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dx_dt]= Relax2CaRest(t,x,pp)
% differential equation describing the decay of calcium conc level to resting level in the presence
% of indicator dye with variable buffering capacity.
% paramters pp: 1 - gamma, 2 - ca_rest, 3 - kappaS, 4 - kd, 5 - indicator total concentration (all conc in nM)
dx_dt = -pp(1)* (x - pp(2))/(1 + pp(3) + pp(4)*pp(5)/(x + pp(4))^2);
return
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
comparingReferences.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/misc/comparingReferences.m
| 2,914 |
utf_8
|
fd9fe5ba3dd91c9f7ff76ab741405cee
|
function comparingReferences
load('refImg_fromMapping');
refImgMapping = refImg;
load('refImg');
load('ROIs');
figure('NumberTitle', 'off', 'Name', 'Reference compare', 'Position', [30, 80, 1850, 910], 'Color', 'white');
makeSubplot(1, refImg, 'Reference from session', ROIs, [-0.05, 1.05]); %#ok<*USENS,*NODEF>
makeSubplot(2, refImgMapping, 'Reference from mapping (ROIs)', ROIs, [-0.05, 1.05]);
corrCoeffs = corrcoef(refImg, refImgMapping, 'rows', 'pairwise');
makeSubplot(3, refImgMapping - refImg, sprintf('Ref_{session} - Ref_{mapping}, corr: %.3f', corrCoeffs(2, 1)), ROIs, [-0.5 0.2]);
% register reference onto local session reference
CP = fix(256 / 2); % center point
TTP = fix(2 * 256 / 3); % two third point
refPoints = [CP TTP CP TTP TTP CP TTP CP CP CP CP CP];
[~, targPoints, srcPoints] = turboReg(refImgMapping, refImg, 'rigidBody', 3, refPoints, 0);
% get the transformation matrix
tForm = cp2tform(squeeze(srcPoints), squeeze(targPoints), 'affine'); %#ok<DCPTF>
% get the transformed frame
refImgMappingReg = imtransform(refImgMapping, tForm, 'XData', [1, 256], 'YData', [1, 256], 'FillValues', NaN); %#ok<DIMTRNS>
% shift ROIs
ROIsShift = ROIs;
translationShifts = squeeze(srcPoints(:, 1, :) - targPoints(:, 1, :));
for iROI = 1 : size(ROIs, 1);
% adjust mask
ROIsShift{iROI, 3} = imtransform(ROIs{iROI, 3}, tForm, 'XData', [1, 256], 'YData', [1, 256], 'FillValues', NaN) == 1; %#ok<DIMTRNS>
% adjust coordinates
ROIsShift{iROI, 2} = round(ROIsShift{iROI, 2} + repmat(translationShifts', size(ROIsShift{iROI, 2}, 1), 1));
end;
corrCoeffs = corrcoef(refImg, refImgMappingReg, 'rows', 'pairwise');
makeSubplot(4, refImgMappingReg - refImg, sprintf('Ref_{mapReg} - Ref_{session}, corr: %.3f', corrCoeffs(2, 1)), ROIsShift, [-0.5 0.2]);
corrCoeffs = corrcoef(refImgMapping, refImgMappingReg, 'rows', 'pairwise');
makeSubplot(5, refImgMappingReg - refImgMapping, sprintf('Ref_{mapReg} - Ref_{mapping}, corr: %.3f', corrCoeffs(2, 1)), ROIsShift, [-0.5 0.2]);
makeSubplot(6, refImgMappingReg, 'Reference from mapping registered', ROIsShift, [-0.05, 1.05]); %#ok<*NODEF>
ROIsOri = ROIs; %#ok<NASGU>
ROIs = ROIsShift; %#ok<NASGU>
save('ROIs_registered', 'ROIs');
clear ROIs iROI CP TTP corrCoeffs;
save('registration');
export_fig('registration.fig', gcf);
export_fig('registration.png', '-r300', gcf);
end
function makeSubplot(iSubPlot, data, titleStr, ROIs, cLim)
subplot(2, 3, iSubPlot);
imagesc(1 : 256, 1 : 256, data);
title(titleStr);
colormap('gray');
set(gca, 'CLim', cLim);
% axis('square');
hold('on');
ROIColors = [0 1 1; 1 0 1; 0 1 0; 1 1 0; 1 0 0; 0 0 1];
for iROI = 1 : size(ROIs, 1);
contour(ROIs{iROI, 3}, 'Color', ROIColors(iROI, :), 'LineStyle', '-');
end;
legend(ROIs(:, 1));
hold('off');
end
% export_fig('analysis/ref_withROIs.png', '-r300', gcf);
% export_fig('analysis/ref_withROIs.fig', gcf);
|
github
|
HelmchenLabSoftware/OCIA-master
|
plotWideFieldMaps_old.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/misc/plotWideFieldMaps_old.m
| 5,024 |
utf_8
|
df2406424fd659898e4fbbbb5e365bf9
|
% plot Wide-Field maps
sessDirs = dir();
sessDirs(arrayfun(@(i) isempty(regexp(sessDirs(i).name, '^session\d\d_\d+$', 'once')), 1 : numel(sessDirs))) = [];
sessDirs = sessDirs([1, 2, 4 6]);
if ~exist('sessMat', 'var');
sessMat = struct();
sessMat(numel(sessDirs)) = struct();
end;
trialTypesRegexp = { 'hit', 'CR', 'quiet', 'moveDur', 'moveBef', ...
'hit_AND_moveDur', 'hit_AND_quiet', 'hit_AND_moveBef', 'hit_AND_[quiet|moveBef]', ...
'CR_AND_moveDur', 'CR_AND_quiet', 'CR_AND_moveBef', 'CR_AND_[quiet|moveBef]' };
trialTypeSaveName = { 'hit', 'CR', 'strict_quiet', 'move', 'early_move', ...
'strict_quiet_hit', 'move_hit', 'early_move_hit', 'quiet_hit', ...
'strict_quiet_CR', 'move_CR', 'early_move_CR', 'quiet_CR' };
%% delay
timePeriod = 'delay';
framesToAvg = 104 : 140;
cLim = [-0.005, 0.02];
figure('NumberTitle', 'off', 'Name', timePeriod, 'Position', [67, 432, 1803, 505]);
iPlot = 1;
for iSess = 1 : numel(sessDirs);
if ~isfield(sessMat(iSess), 'hit') || isempty(sessMat(iSess).hit);
hitAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_hit_average.mat']);
sessMat(iSess).hit = hitAvgMat;
end;
subplot(2, numel(sessDirs), iPlot);
imagesc(1 : 256, 1 : 256, smoothn(nanmean(sessMat(iSess).hit.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));
set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);
title(sprintf('Hit - %s', sessDirs(iSess).name), 'Interpreter', 'none');
colorbar();
colormap(gca, 'mapgeog');
iPlot = iPlot + 1;
end;
for iSess = 1 : numel(sessDirs);
if ~isfield(sessMat(iSess), 'CR') || isempty(sessMat(iSess).CR);
CRAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_CR_average.mat']);
sessMat(iSess).CR = CRAvgMat;
end;
subplot(2, numel(sessDirs), iPlot);
imagesc(1 : 256, 1 : 256, smoothn(nanmean(sessMat(iSess).CR.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));
set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);
title(sprintf('CR - %s', sessDirs(iSess).name), 'Interpreter', 'none');
colorbar();
colormap(gca, 'mapgeog');
iPlot = iPlot + 1;
end;
%% sensation
timePeriod = 'sensation';
framesToAvg = 60 : 100;
cLim = [-0.005, 0.02];
figure('NumberTitle', 'off', 'Name', timePeriod, 'Position', [67, 432, 1803, 505]);
iPlot = 1;
for iSess = 1 : numel(sessDirs);
if ~isfield(sessMat(iSess), 'hit') || isempty(sessMat(iSess).hit);
hitAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_hit_average.mat']);
sessMat(iSess).hit = hitAvgMat;
end;
subplot(2, numel(sessDirs), iPlot);
imagesc(1 : 256, 1 : 256, smoothn(nanmean(hitAvgMat.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));
set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);
title(sprintf('Hit - %s', sessDirs(iSess).name), 'Interpreter', 'none');
colorbar();
colormap(gca, 'mapgeog');
iPlot = iPlot + 1;
end;
for iSess = 1 : numel(sessDirs);
if ~isfield(sessMat(iSess), 'CR') || isempty(sessMat(iSess).CR);
CRAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_CR_average.mat']);
sessMat(iSess).CR = CRAvgMat;
end;
subplot(2, numel(sessDirs), iPlot);
imagesc(1 : 256, 1 : 256, smoothn(nanmean(CRAvgMat.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));
set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);
title(sprintf('CR - %s', sessDirs(iSess).name), 'Interpreter', 'none');
colorbar();
colormap(gca, 'mapgeog');
iPlot = iPlot + 1;
end;
%{
function doPlot(timePeriod, framesToAvg, cLim);
figure('NumberTitle', 'off', 'Name', timePeriod, 'Position', [67, 432, 1803, 505]);
iPlot = 1;
for iSess = 1 : numel(sessDirs);
if ~isfield(sessMat(iSess), 'hit') || isempty(sessMat(iSess).hit);
hitAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_hit_average.mat']);
sessMat(iSess).hit = hitAvgMat;
end;
subplot(2, numel(sessDirs), iPlot);
imagesc(1 : 256, 1 : 256, smoothn(nanmean(hitAvgMat.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));
set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);
title(sprintf('Hit - %s', sessDirs(iSess).name), 'Interpreter', 'none');
colorbar();
colormap(gca, 'mapgeog');
iPlot = iPlot + 1;
end;
for iSess = 1 : numel(sessDirs);
if ~isfield(sessMat(iSess), 'CR') || isempty(sessMat(iSess).CR);
CRAvgMat = load([sessDirs(iSess).name, '/Matt_files/cond_CR_average.mat']);
sessMat(iSess).CR = CRAvgMat;
end;
subplot(2, numel(sessDirs), iPlot);
imagesc(1 : 256, 1 : 256, smoothn(nanmean(CRAvgMat.tr_ave(:, :, framesToAvg), 3) - 1, [5 5], 'Gauss'));
set(gca, 'CLim', cLim, 'XLim', [1 256], 'YLim', [1 256], 'XTick', [], 'YTick', []);
title(sprintf('CR - %s', sessDirs(iSess).name), 'Interpreter', 'none');
colorbar();
colormap(gca, 'mapgeog');
iPlot = iPlot + 1;
end;
%}
|
github
|
HelmchenLabSoftware/OCIA-master
|
changing_frame_0_balazs.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/misc/changing_frame_0_balazs.m
| 6,227 |
utf_8
|
4da913c737f7e68564f0e3529a5fd541
|
function changing_frame_0_balazs()
fr0 = [];
load('stimStartFrames');
load('trials_ind');
load('norm_frame');
load('rois_OCIA_old');
load('ROIs_registered');
fr2=57:58;
fr_dev2 = nan(size(fr_dev)); %#ok<*NODEF>
stimFrames = 59:68;
fixedStartFrame = max(stimStartFrame);
% trialTypes = { 'hit', 'CR' };
trialTypes = { 'hit' };
nMaxTrials = 1;
% exclTrials = { [4 5 7 8 11 12 15 19 22 27 28 29], [] };
exclTrials = { [], [] };
doSinglePlots = true;
doAvgPlot = false;
avgYLims = [-0.01 0.01];
trialYLims = [-0.05 0.05]; %#ok<*NASGU>
avgCLim = [-0.001 0.001];
trialCLim = [-0.005 0.01]; %#ok<*NASGU>
% ROINames = { 'V1', 'M2', 'A1', 'S1FL' };
% ROIColors = { 'b', 'k', 'g', 'r' };
% ROINames = { 'V1', 'A1', 'S1FL' };
% ROIColors = { 'b', 'g', 'c' };
ROINames = { };
ROIColors = { };
ROI2Inds = 1 : 6;
ROIColors2 = [0 1 1; 1 0 1; 0 1 0; 1 1 0; 1 0 0; 0 0 1];
% ROI2Inds = [6, 3, 1];
% ROIColors2 = [0 0 1; 0 1 0; 0 1 1;];
ROIs = ROIs(ROI2Inds, :);
%% HIT trials
for iType = 1 : numel(trialTypes);
listTrials = dir(['cond_' trialTypes{iType} '_trial*']);
cond_avg = zeros(256, 256, 240);
cond_avg_0 = zeros(256, 256, 240);
cond_avgNoAlign = zeros(256, 256, 240);
cond_avgNoAlign_0 = zeros(256, 256, 240);
nTrials = 0;
trialInd = eval(['tr_', trialTypes{iType}]);
for iTrial = 1 : min(nMaxTrials, size(listTrials, 1));
if ismember(iTrial, exclTrials{iType}); continue; end;
trialPath = sprintf('cond_%s_trial%d.mat', trialTypes{iType}, iTrial);
if ~exist(trialPath, 'file'); continue; end;
fprintf('Loading trial %s %03d ...\n', trialTypes{iType}, iTrial);
load(trialPath);
% reset the baseline
tr = tr .* repmat(fr_dev(:, :, trialInd(iTrial)), [1, 1, size(tr, 3)]);
trNoAlign = tr;
% re-align frames
stimStartFrameTrial = stimStartFrame(trialInd(iTrial));
nFramesDiff = fixedStartFrame - stimStartFrameTrial;
if nFramesDiff > 0;
tr = cat(3, nan(size(tr, 1), size(tr, 2), nFramesDiff), tr(:, :, 1 : (end - nFramesDiff)));
elseif nFramesDiff < 0;
tr = cat(3, tr(:, :, (nFramesDiff + 1) : end), nan(size(tr, 1), size(tr, 2), nFramesDiff));
end;
% re-normalize with baseline
tr0 = tr;
tr0 = tr0 ./ repmat(fr_dev(:, :, trialInd(iTrial)), [1 1 size(tr0, 3)]);
fr_dev2(:, :, trialInd(iTrial)) = nanmean(tr(:, :, fr2), 3);
tr = tr ./ repmat(fr_dev2(:, :, trialInd(iTrial)), [1 1 size(tr, 3)]);
% re-normalize with baseline
trNoAlign0 = trNoAlign;
trNoAlign0 = trNoAlign0 ./ repmat(fr_dev(:, :, trialInd(iTrial)), [1 1 size(trNoAlign0, 3)]);
fr_dev2(:, :, trialInd(iTrial)) = nanmean(trNoAlign(:, :, fr2), 3);
trNoAlign = trNoAlign ./ repmat(fr_dev2(:, :, trialInd(iTrial)), [1 1 size(trNoAlign, 3)]);
% add average
cond_avg = cond_avg + tr;
cond_avg_0 = cond_avg_0 + tr0;
cond_avgNoAlign = cond_avgNoAlign + tr;
cond_avgNoAlign_0 = cond_avgNoAlign_0 + tr0;
nTrials = nTrials + 1;
% plot
if doSinglePlots;
createPlot(sprintf('%s %03d - trial %03d', trialTypes{iType}, iTrial, trialInd(iTrial)), ...
tr0, tr, trNoAlign0, trNoAlign, fr0, fr2, stimFrames, roi_V1, roi_M2, roi_A1, roi_S1FL, ROINames, ...
ROIColors, ROIColors2, ROIs, trialCLim, trialYLims); %#ok<*UNRCH>
end;
end
% compute average
cond_avg = cond_avg ./ nTrials;
cond_avg_0 = cond_avg_0 ./ nTrials;
cond_avgNoAlign = cond_avgNoAlign ./ nTrials;
cond_avgNoAlign_0 = cond_avgNoAlign_0 ./ nTrials;
% plot
if doAvgPlot;
createPlot(sprintf('%s average - %03d trial(s)', trialTypes{iType}, nTrials), ...
cond_avg_0, cond_avg, cond_avgNoAlign, cond_avgNoAlign_0, fr0, fr2, stimFrames, ...
roi_V1, roi_M2, roi_A1, roi_S1FL, ROINames, ROIColors, ROIColors2, ROIs, avgCLim, avgYLims);
end;
end;
end
function createPlot(figTitle, dataFr0, dataFr2, dataNoAlignFr0, dataNoAlignFr2, fr0, fr2, ...
stimFrames, roi_V1, roi_M2, roi_A1, roi_S1FL, ROINames, ROIColors, ROIColors2, ROIs, cLim, yLims) %#ok<INUSL>
subPlotTitles = { sprintf('Sound aligned, norm. %02d:%02d', fr0(1), fr0(end)), ...
sprintf('Sound aligned, norm. %02d:%02d, stim. %02d:%02d', fr0([1 end]), stimFrames([1 end])), ...
sprintf('Trig. aligned, norm %02d:%02d', fr2([1 end])), ...
sprintf('Trig. aligned, norm. %02d:%02d, stim. %02d:%02d', fr2([1 end]), stimFrames([1 end])) };
legendParams = { [ROINames ROIs(:, 1)'], 'Location', 'NorthOutside', 'Orientation', 'Horizontal', 'FontSize', 6 };
figure('Name', figTitle, 'NumberTitle', 'off', 'Position', [30 100 1850 970]);
dataToPlot = { dataFr0, dataFr2, dataNoAlignFr0, dataNoAlignFr2 };
iSubPlot = 1;
for iData = 1 : 4;
subplot(2, 4, iSubPlot);
title(subPlotTitles{1});
hold on;
linTr = reshape(dataToPlot{iData}, size(dataToPlot{iData}, 2) * size(dataToPlot{iData}, 2), size(dataToPlot{iData}, 3));
for iROI = 1 : numel(ROINames);
plot(squeeze(nanmean(linTr(eval(['roi_' ROINames{iROI}]), :), 1)) - 1, ['--', ROIColors{iROI}]);
end;
for iROI = 1 : size(ROIs, 1);
trace = nanmean(GetRoiTimeseries(dataFr2, ROIs{iROI, 3})) - 1;
plot(trace, 'Color', ROIColors2(iROI, :), 'LineStyle', '-');
end;
plot(repmat(stimFrames(1), 1, 2), yLims, ':k');
plot(repmat(stimFrames(end), 1, 2), yLims, ':k');
set(gca, 'YLim', yLims);
hold off;
legend(legendParams{:});
iSubPlot = iSubPlot + 1;
subplot(2, 4, iSubPlot);
title(subPlotTitles{2});
imagesc(1 : 256, 1 : 256, smoothn(nanmean(dataToPlot{iData}(:, :, stimFrames) - 1, 3), [5 5], 'Gauss'), cLim);
colorbar();
axis('square');
colormap(mapgeog);
hold on;
for iROI = 1 : numel(ROINames);
h = zeros(256 * 256, 1);
h(eval(['roi_' ROINames{iROI}])) = 1;
contour(reshape(h, 256, 256), ROIColors{iROI});
end;
for iROI = 1 : size(ROIs, 1);
contour(ROIs{iROI, 3}, 'Color', ROIColors2(iROI, :), 'LineStyle', '-');
end;
hold off;
iSubPlot = iSubPlot + 1;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
BEGetTrialInfo.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/BEGetTrialInfo.m
| 2,254 |
utf_8
|
ecb6e0a8914941c49d705be87c4ca6df
|
%% #BEGetTrialInfo
function trialInfo = BEGetTrialInfo(this, iTrial)
% default is empty
freq = ''; spotIndex = ''; isTargetOrNTones = ''; resp = ''; respTime = ''; corr = ''; rew = '';
if iTrial > 0 && iTrial <= this.be.config.training.nTrials && isfield(this.be, 'stims');
if isfield(this.be, 'spotMatrix') && ~isempty(this.be.spotMatrix);
spotIndex = this.be.spotMatrix(iTrial);
end;
freq = round(this.be.config.tone.freqs(this.be.stims(iTrial)) / 1000);
% no goStim = no behavior
if ~isempty(this.be.config.tone.goStim);
% oddball discrimination
if isfield(this.be.config.tone, 'oddProba') && this.be.config.tone.oddProba > 0;
isTargetOrNTones = double(this.be.stims(iTrial) ~= this.be.odds(iTrial) && this.be.config.tone.goStim);
% frequency/cloud of tone discrimination
else
isTargetOrNTones = double(ismember(this.be.stims(iTrial), this.be.config.tone.goStim));
end;
elseif strcmp(this.be.taskType, 'cotOdd') && numel(this.be.nTones) > 1;
% fill with number of tones
isTargetOrNTones = this.be.nTones(iTrial);
end;
if ~isempty(this.be.config.tone.goStim) && isfield(this.be, 'resps') && ~isnan(this.be.resps(iTrial));
resp = this.be.resps(iTrial);
if ~isnan(this.be.respDelays(iTrial));
respTime = sprintf('%.2f', this.be.respDelays(iTrial));
else
respTime = ' - ';
end;
corr = double((isTargetOrNTones && resp) || (~isTargetOrNTones && ~resp));
if corr; corr = ' T '; else corr = ' F '; end;
if ~isnan(this.be.giveRewards(iTrial)) && this.be.giveRewards(iTrial);
rew = ' T ';
else
rew = ' F';
end;
if this.be.resps(iTrial); resp = ' T '; else resp = ' F'; end;
if this.be.autoRewardGiven(iTrial) && strcmp(corr, ' T '); corr = ' F*'; end;
end;
if isTargetOrNTones; isTargetOrNTones = ' T '; else isTargetOrNTones = ' F'; end;
% no trial number
else
iTrial = '';
end;
trialInfo = {iTrial, spotIndex, freq, isTargetOrNTones, resp, respTime, corr, rew};
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
DWMatchBehavTrialsToImagingData.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/DWMatchBehavTrialsToImagingData.m
| 6,399 |
utf_8
|
afd7fe9d63c0d81ca6439a845346cc6f
|
function DWMatchBehavTrialsToImagingData(this)
% DWMatchBehavTrialsToImagingData - [no description]
%
% DWMatchBehavTrialsToImagingData(this)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% match the behavior trials and the data files
% update the wait bar
DWWaitBar(this, 0);
% get the behavior rows with no animal ID and figure it out from the data structure
behavRows = DWFilterTable(this, 'animal !~= \w+ AND rowType = Behavior data');
for iBehavRow = 1 : size(behavRows, 1);
% get the DataWatcher table's row index for this row
iDWRow = str2double(get(this, iBehavRow, 'rowNum', behavRows));
% load the row
DWLoadRow(this, iDWRow, 'full');
% get the behavior data
behavData = getData(this, iDWRow, 'behav', 'data');
% set the new animal ID
set(this, iDWRow, 'animal', regexprep(['mou_bl_', behavData.animalID], 'mou_bl_mou_bl', 'mou_bl'));
end;
% get the list of all animals
uniqueAnimals = get(this, 'animal');
if ~iscell(uniqueAnimals) && ischar(uniqueAnimals) && ~isempty(uniqueAnimals); uniqueAnimals = { uniqueAnimals }; end;
uniqueAnimals(cellfun(@isempty, uniqueAnimals)) = { '' };
uniqueAnimals = unique(uniqueAnimals);
% get the list of all days
uniqueDays = get(this, 'day');
if ~iscell(uniqueDays) && ischar(uniqueDays) && ~isempty(uniqueDays); uniqueDays = { uniqueDays }; end;
uniqueDays(cellfun(@isempty, uniqueDays)) = [];
uniqueDays = unique(uniqueDays);
% get the selected animal IDs
selectedAnimalIDs = this.dw.animalIDs(get(this.GUI.handles.dw.filt.animalID, 'Value'));
% if the dash '-' is selected, select all IDs
if numel(selectedAnimalIDs) == 1 && strcmp(selectedAnimalIDs{1}, '-');
selectedAnimalIDs = uniqueAnimals;
end;
% get the selected day IDs
selectedDayIDs = this.dw.dayIDs(get(this.GUI.handles.dw.filt.dayID, 'Value'));
% if the dash '-' is selected, select all IDs
if numel(selectedDayIDs) == 1 && strcmp(selectedDayIDs{1}, '-');
selectedDayIDs = uniqueDays;
end;
% cell array storing all the informations to process each session
allSessionInfos = cell(1000, 6);
% first get all the information for each sessions to process
% go through each animal
for iAnim = 1 : numel(uniqueAnimals);
animalID = uniqueAnimals{iAnim}; % get the current animal
% skip irrelevant animal IDs
if ~ismember(animalID, selectedAnimalIDs); continue; end;
% go through each day
for iDay = 1 : numel(uniqueDays);
dayID = uniqueDays{iDay}; % get the current day
% skip irrelevant days
if ~ismember(dayID, selectedDayIDs); continue; end;
% empty spot filters
spotID = '';
spotFilter = '';
% create animal filter
if isempty(animalID);
animalFilter = 'animal !~= \w AND ';
else
animalFilter = sprintf('animal = %s AND ', animalID);
end;
% use different filters for different locations
locFilter = {
'', '';
};
if ismember('loc', this.dw.tableIDs);
locFilter = {
'', ' AND loc !~= \w+';
'local', ' AND loc = local';
'remote', ' AND loc = remote';
};
end;
% go through each location filter
for iLocFilter = 1 : size(locFilter, 1);
% get the imaging rows indexes
imagingRows = DWFilterTable(this, ...
sprintf('%s%sday = %s AND rowType = Imaging data AND runType !~= \\w+%s', ...
animalFilter, spotFilter, dayID, locFilter{iLocFilter, 2}));
imagingRowIndexes = str2double(get(this, 'all', 'rowNum', imagingRows));
% if no imaging data, skip
if isempty(imagingRowIndexes) || any(isnan(imagingRowIndexes));
continue;
% if only one row found, label it as session 1
elseif numel(imagingRowIndexes) == 1;
sessIDs = 1;
% if several rows, cluster them by session using time
else
sessIDs = clusterRowsBySession(this, imagingRowIndexes);
end;
% go through session by session
for iSess = 1 : size(unique(sessIDs), 1);
% get the indexes of this session
sessRowIndexes = imagingRowIndexes(sessIDs == iSess);
% store the data to process
allSessionInfos(end + 1, :) = { animalID, dayID, spotID, iSess, sessRowIndexes, ...
locFilter{iLocFilter, 2} }; %#ok<AGROW>
end;
end; % end of location filter
end; % end of day loop
end; % end of animal loop
% remove empty lines
allSessionInfos(cellfun(@isempty, allSessionInfos(:, 1)), :) = [];
nTotSessions = size(allSessionInfos, 1);
% match all sessions
for iTotSess = 1 : nTotSessions;
% match the behavior trials using the stored informations
DWMatchBehavTrialsToImagingDataForSession(this, allSessionInfos{iTotSess, :});
% update the wait bar
DWWaitBar(this, 99 * (iTotSess / nTotSessions));
end;
% % remove raw behavior data for the current session
% behavRows = DWFilterTable(this, 'rowType = Behavior data');
% DWFlushData(this, str2double(get(this, 'all', 'rowNum', behavRows)), false, 'behav');
% final update of the wait bar
DWWaitBar(this, 100);
end
%% - #clusterRowsBySession
function sessIDs = clusterRowsBySession(this, rowNums)
% do not process if not at least 2 rows
if numel(rowNums) < 2;
sessIDs = repmat('1', numel(rowNums), 1);
return;
end;
% separate rows into morning and afternoon sessions
nUnknRows = size(rowNums, 1);
dateNums = zeros(nUnknRows, 1);
for iUnknRow = 1 : nUnknRows;
dateAndTime = get(this, rowNums(iUnknRow), { 'day', 'time' });
dateNums(iUnknRow) = datenum(sprintf('%s__%s', dateAndTime{:}), 'yyyy_mm_dd__HH_MM_SS');
end;
sessIDs = clusterdata(dateNums, 'maxclust', 2);
nearbySessDiffInHours = (dn2unix(dateNums(find(sessIDs == sessIDs(end), 1, 'first'))) ...
- dn2unix(dateNums(find(sessIDs == sessIDs(1), 1, 'last')))) / 1000 / 60 / 60;
% if sessions are too close, it means that it was a single session with a missing trial/interruption
if nearbySessDiffInHours < 3; % minimum 3 hours between sessions
sessIDs = clusterdata(dateNums, 'maxclust', 1);
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
DWMatchBehavTrialsToImagingDataForSession.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/DWMatchBehavTrialsToImagingDataForSession.m
| 16,055 |
utf_8
|
3a28c46a1d44236c27a5d27a8ab6b9fb
|
%% - #DWMatchBehavTrialsToImagingDataForSession
function DWMatchBehavTrialsToImagingDataForSession(this, animalID, dayID, spotID, iSess, rowIndexes, locFilter)
% get the number of imaging trials found
nTrialsFound = size(rowIndexes, 1);
% abort if no trials
if ~nTrialsFound; return; end;
% find the right behavior out file : get the behavior rows
behavRows = DWFilterTable(this, sprintf('animal = %s AND day = %s AND rowType = Behavior data%s', animalID, dayID, ...
locFilter));
nBehavs = size(behavRows, 1); % count them
% go through all behavior files by comparing behavior trial and data file times
allBehavUNIXTimes = []; % behaviorally recorded times
allBehavBelongInds = []; % behavior file IDs (B01, B02, etc.)
% extract all behavior times from the behavior files
for iBehav = 1 : nBehavs;
% get the DataWatcher table's row index for this row
iDWRow = str2double(get(this, iBehav, 'rowNum', behavRows));
% make sure behavior data is loaded
DWLoadRow(this, iDWRow, 'full');
% get the output structure
behavData = getData(this, iDWRow, 'behav', 'data');
% skip empty structures
if isempty(behavData); continue; end;
% find the end timing name (backward compatibility)
fieldName = 'endImagExp';
if ~isfield(behavData.times, fieldName);
fieldName = 'endImagExpect';
end;
if ~isfield(behavData.times, fieldName);
fieldName = 'imgStopExp';
end;
if ~isfield(behavData.times, fieldName);
showWarning(this, 'OCIA:DW:DWMatchBehavTrialsToImagingDataForSession:NoEndImagingFieldName', ...
sprintf('Cannot find an imaging end time field for row %03d: %s.', iDWRow, DWGetRowID(this, iDWRow)));
continue;
end;
% extract the behavior UNIX times
behavUNIXTimes = (behavData.times.(fieldName) + behavData.times.start) * 1000;
behavUNIXTimes(behavUNIXTimes == 0) = [];
% concatenate the times
allBehavUNIXTimes = [allBehavUNIXTimes behavUNIXTimes]; %#ok<AGROW>
allBehavBelongInds = [allBehavBelongInds repmat(iBehav, 1, size(behavUNIXTimes, 2))]; %#ok<AGROW>
end;
% remove NaN trials because they were not recorded
allBehavBelongInds(isnan(allBehavUNIXTimes)) = [];
allBehavUNIXTimes(isnan(allBehavUNIXTimes)) = [];
% use a time threshold to check for time mismatchs
timeThresh = this.dw.trialMatchingTimeDifferenceThreshold;
% minimum time differences between behavior timestamps and data file timestamps
[allMinTDiffs, allMinTInds] = compareImgFileTimeWithBehavTimes(this, allBehavUNIXTimes, rowIndexes, timeThresh);
% abort if no rows to process
if isempty(allMinTDiffs) || isempty(allMinTInds); return; end;
% best fitting behavior file are the ones with less than 3 hours
iBestBehav = unique(allBehavBelongInds(allMinTDiffs < 3 * 60 * 60));
nMatchBehavs = size(iBestBehav, 2);
iBestBehavMask = ismember(allBehavBelongInds, iBestBehav);
% abort if no behavior match found
if isempty(iBestBehav); return; end;
% extract the adjusted time differences
minTDiff = abs(allMinTDiffs(iBestBehavMask) - nanmedian(allMinTDiffs(iBestBehavMask)));
% calculate the number of expected trials
nTrialsExp = 0;
for iBehav = 1 : nMatchBehavs;
% get the DataWatcher table's row index for this row
iDWRow = str2double(get(this, iBestBehav(iBehav), 'rowNum', behavRows));
% get the output structure
behavData = getData(this, iDWRow, 'behav', 'data');
% count the number of trials that are expected
nTrialsExp = nTrialsExp + find(~isnan(behavData.times.end) & ~isnan(behavData.resps), 1, 'last');
end;
% calculate the difference in trial numbers
diffTrials = nTrialsExp - nTrialsFound;
% get whether the difference is in missing or extra trials
missExtraInd = []; % indexes of rows that are missing or extra
missExtraLabel = ''; % label specifying whether the trials are missing or extra
% no trial number difference and no timing mismatch => no missmatch
if diffTrials == 0 && ~any(minTDiff > timeThresh);
% nothing to do
% missing/extra trials
elseif diffTrials ~= 0;
% difference is positive => missing trials
if diffTrials > 0;
missExtraLabel = 'missing'; % label the mismatch
% loop to find all missing trials using a stepwise decreasing time threshold
while size(missExtraInd, 1) < diffTrials;
missExtraInd = find(minTDiff > timeThresh); % get the missing trials
timeThresh = timeThresh - 100; % update the threshold
end;
% get the most different missing trials
[~, missExtraIndOrdered] = sort(minTDiff(missExtraInd)); % sort by most different timing
missExtraInd = sort(missExtraInd(missExtraIndOrdered(end - diffTrials + 1 : end)));
% % get the first missing trials
% missExtraInd = sort(missExtraInd(1 : abs(diffTrials)));
% difference is negative => extra trials
else
missExtraLabel = 'extra'; % label the mismatch
diffTrials = - diffTrials; % invert the sign
% find the extra trials
missExtraInd = find(~ismember(1 : nTrialsExp, allMinTInds(iBestBehavMask)), diffTrials);
% if no extra trials found, try to find them using setdiff
if isempty(missExtraInd); missExtraInd = setdiff(1 : nTrialsFound, allMinTInds); end;
% only take the required number of different trials
missExtraInd = sort(missExtraInd(1 : abs(diffTrials)));
end;
% create a list of mismatched indexes
missList = regexprep(sprintf('%02d ', missExtraInd), ' $', '');
% if the list is too long, make it shorter: find the space characters
spaceCharStart = find(missList == ' ', 3, 'first');
% find the second and before last space character
if isempty(spaceCharStart); spaceCharStart = min(8, round(numel(missList) * 0.5));
else spaceCharStart = spaceCharStart(end);
end;
spaceCharEnd = find(missList == ' ', 3, 'last');
if isempty(spaceCharEnd); spaceCharEnd = max(numel(missList) - 8, round(numel(missList) * 0.5));
else spaceCharEnd = spaceCharEnd(1);
end;
if size(missList, 2) > 30; missList = [missList(1 : spaceCharStart) ' ... ' missList(spaceCharEnd : end)]; end;
% show the warning
showWarning(this, 'OCIA:DWMatchBehavTrialsToImagingDataForSession:MissingTrials', ...
sprintf('Found %d %s trial(s) ( %s ) for %s %s %s session %d.', diffTrials, missExtraLabel, ...
missList, animalID, dayID, spotID, iSess));
end;
% label the stimuli
if strcmp(behavData.taskType, 'cotOdd');
stimLabels = { 'lowStd ', 'highStd' };
else
stimLabels = { 'low', 'high' };
end;
% create the annotations for the imaging rows
behavIDs = cell(nTrialsExp, 1);
runTypes = cell(nTrialsExp, 1);
trialNums = cell(nTrialsExp, 1);
spotIDs = cell(nTrialsExp, 1);
behavInfo = cell(nTrialsExp, 1);
% initialize the current behavior data to use for annotation
iBehav = 1;
iDWRowBehav = str2double(get(this, iBestBehav(iBehav), 'rowNum', behavRows)); % get the DW table's row index
behavID = DWGetRowID(this, iDWRowBehav); % get the behavior row's ID
behavData = getData(this, iDWRowBehav, 'behav', 'data'); % get the behavior data
currMaxTrial = find(~isnan(behavData.times.end) & ~isnan(behavData.resps), 1, 'last'); % get the number of trials for this behavior
% loop through all trials
iTrial = 1;
for iTotTrial = 1 : nTrialsExp;
% annotate this trial using the behavior's informations
behavIDs{iTotTrial} = behavID;
runTypes{iTotTrial} = 'Trial';
trialNums{iTotTrial} = sprintf('%02d', iTrial);
spotIDs{iTotTrial} = sprintf('spot%02d', behavData.spotMatrix(iTrial));
% gather some information about the behavior
behavInfo{iTotTrial} = sprintf('[ %s', stimLabels{behavData.stims(iTrial)});
% response type
if ~isnan(behavData.respTypes(iTrial));
% target
if ismember(behavData.respTypes(iTrial), [1 4]);
behavInfo{iTotTrial} = sprintf('%s / targ', behavInfo{iTotTrial});
% distractor
elseif ismember(behavData.respTypes(iTrial), [2 3]);
behavInfo{iTotTrial} = sprintf('%s / distr', behavInfo{iTotTrial});
end;
% correct
if ismember(behavData.respTypes(iTrial), [1 2]);
behavInfo{iTotTrial} = sprintf('%s / corr', behavInfo{iTotTrial});
% wrong
elseif ismember(behavData.respTypes(iTrial), [3 4]);
behavInfo{iTotTrial} = sprintf('%s / false', behavInfo{iTotTrial});
end;
end;
% cloud of tones oddball case
if strcmp(behavData.taskType, 'cotOdd') && numel(behavData.nTones) >= iTrial;
behavInfo{iTotTrial} = sprintf('%s / %02d tones', behavInfo{iTotTrial}, behavData.nTones(iTrial));
end;
% close the information section
behavInfo{iTotTrial} = sprintf('%s ]', behavInfo{iTotTrial});
% update the trial count
iTrial = iTrial + 1;
% if we reach the start of a new behavior file
if iTrial > currMaxTrial && iBehav < nMatchBehavs;
% update the current behavior data to use for annotation
iTrial = 1;
iBehav = iBehav + 1;
iDWRowBehav = str2double(get(this, iBestBehav(iBehav), 'rowNum', behavRows)); % get the DW table's row index
behavID = DWGetRowID(this, iDWRowBehav); % get the behavior row's ID
behavData = getData(this, iDWRowBehav, 'behav', 'data'); % get the behavior data
currMaxTrial = find(~isnan(behavData.times.end) & ~isnan(behavData.resps), 1, 'last'); % get the number of trials for this behavior
end;
end;
% re-order the rows according to the minimum time indexes
rowIndexes = rowIndexes(allMinTInds(iBestBehavMask));
% remove the annotations for the missing trials
if strcmp(missExtraLabel, 'missing');
behavIDs(missExtraInd) = [];
runTypes(missExtraInd) = [];
trialNums(missExtraInd) = [];
spotIDs(missExtraInd) = [];
behavInfo(missExtraInd) = [];
rowIndexes(missExtraInd) = [];
end;
% update in the table
set(this, rowIndexes, 'behav', behavIDs);
set(this, rowIndexes, 'runType', runTypes);
set(this, rowIndexes, 'runNum', trialNums);
set(this, rowIndexes, 'spot', spotIDs);
set(this, rowIndexes, 'comments', behavInfo);
%% extract behavior data to imaging rows and get spot ID for behavior rows
% go through each behavior file and try to get a spot ID annotation for them
for iBehav = 1 : nBehavs;
% get the DataWatcher table's row index for this row
iDWRowBehav = str2double(get(this, iBehav, 'rowNum', behavRows)); % get the DW table's row index
behavID = DWGetRowID(this, iDWRowBehav); % get the behavior row's ID
% get the imaging trial rows that have a matching behavior ID
trialRows = DWFilterTable(this, sprintf('rowType = Imaging data AND behav = %s AND runNum ~= \\d+', behavID));
% skip the process if no imaging rows have this behavior ID
if isempty(trialRows); continue; end;
% get the behavior data
behavDataForRow = getData(this, iDWRowBehav, 'behav', 'data');
% go through each trial
for iTrialLoop = 1 : size(trialRows, 1);
iTrial = str2double(get(this, iTrialLoop, 'runNum', trialRows)); % get the trial number
iDWRowTrial = str2double(get(this, iTrialLoop, 'rowNum', trialRows)); % get the row's index
% extract the behavior data for this trial and store it in the imaging row's data
setData(this, iDWRowTrial, 'behavExtr', 'data', DWExtractBehavDataForImagingRow(this, iTrial, behavDataForRow));
setData(this, iDWRowTrial, 'behavExtr', 'loadStatus', 'full');
end;
% if the behavior file does not have a spot annotation
if isempty(get(this, iDWRowBehav, 'spot'));
% create a spot annotation using the one from the frist trial
set(this, iDWRowBehav, 'spot', get(this, iTrialLoop, 'spot', trialRows));
end;
end;
end
%% - #compareImgFileTimeWithBehavTimes
function [minTDiffs, minTInds] = compareImgFileTimeWithBehavTimes(this, behavUNIXTimes, DWTableRowInds, timeDiffThresh)
% do not process if no rows
DWTableRowInds(isnan(DWTableRowInds)) = []; % remove nans
if isempty(DWTableRowInds);
minTDiffs = [];
minTInds = [];
return;
end;
nTrialsExp = size(behavUNIXTimes, 2);
nTrialsFound = size(DWTableRowInds, 1);
fileTimes = arrayfun(@(i) dn2unix(datenum(sprintf('%s__%s', get(this, DWTableRowInds(i), 'day'), ...
get(this, DWTableRowInds(i), 'time')), 'yyyy_mm_dd__HH_MM_SS')), 1 : nTrialsFound);
% nFrames = arrayfun(@(i) str2double(regexprep(get(this, DWTableRowInds(i), 'dim'), '^\d+x\d+x', '')), 1 : nTrialsFound);
% fileTimes = fileTimes(nFrames >= this.an.img.funcMovieNFramesLimit);
minTDiffs = zeros(nTrialsExp, 1);
minTInds = zeros(nTrialsExp, 1);
for iTrial = 1 : nTrialsExp;
tDiffs = abs(behavUNIXTimes(iTrial) - fileTimes);
[minTDiffs(iTrial), minTInds(iTrial)] = min(abs(tDiffs));
end;
%% show debug plot if required
if get(this.GUI.handles.dw.SLROpts.procDataShowDebug, 'Value');
figure('Name', 'Time comparison for trial matching', 'NumberTitle', 'off', 'WindowStyle', 'docked');
% match lines
lineHandles = plot([fileTimes(minTInds); behavUNIXTimes(1 : nTrialsExp)], ...
[ones(1, nTrialsExp); 2 * ones(1, nTrialsExp)], 'green');
hold on;
% imaging files scatter
filePointHandles = scatter(fileTimes, ones(1, numel(fileTimes)), 10, 's', 'blue', 'fill');
fileTrialList = regexp(regexprep(sprintf('%d,', 1 : numel(fileTimes)), ',$', ''), ',', 'split');
behavTrialList = regexp(regexprep(sprintf('%d,', 1 : numel(behavUNIXTimes)), ',$', ''), ',', 'split');
text(fileTimes, ones(1, numel(fileTimes)) - 0.05, fileTrialList, 'FontSize', 5, ...
'HorizontalAlignment', 'center');
% extract which are the deviant times
deviantTimes = find(minTDiffs > timeDiffThresh);
% time differences
scaledTDiffs = linScale([0; timeDiffThresh; minTDiffs; max(minTDiffs)], 0, 0.5);
timeDiffHandle = plot(behavUNIXTimes, scaledTDiffs(3 : end - 1) + 1.25, 'k', 'LineWidth', 1.5);
plot([behavUNIXTimes(1) - 10E5 behavUNIXTimes(end) + 10E5], repmat(scaledTDiffs(1), 1, 2) + 1.25, ':k', 'LineWidth', 0.5);
plot([behavUNIXTimes(1) - 10E5 behavUNIXTimes(end) + 10E5], repmat(scaledTDiffs(end), 1, 2) + 1.25, ':k', 'LineWidth', 0.5);
text(behavUNIXTimes(1) - 10E5, scaledTDiffs(end) + 1.25, sprintf('%.1f', max(minTDiffs)), 'FontSize', 5, ...
'HorizontalAlignment', 'right');
text(behavUNIXTimes(1) - 10E5, scaledTDiffs(1) + 1.25, '0.0', 'FontSize', 5, 'HorizontalAlignment', 'right');
% threshold
plot([behavUNIXTimes(1) - 10E5 behavUNIXTimes(end) + 10E5], repmat(scaledTDiffs(2), 1, 2) + 1.25, ':r', 'LineWidth', 0.5);
text(behavUNIXTimes(1) - 10E5, scaledTDiffs(2) + 1.25, sprintf('%.1f', timeDiffThresh), 'FontSize', 5, ...
'HorizontalAlignment', 'right', 'Color', 'red');
if ~isempty(deviantTimes);
deviantTimesHandle = scatter(behavUNIXTimes(deviantTimes), scaledTDiffs(2 + deviantTimes) + 1.25, 65, 'red', ...
'filled');
else
deviantTimesHandle = [];
end;
% behavior trials scatter
behavPointHandles = scatter(behavUNIXTimes, 2 * ones(1, numel(behavUNIXTimes)), 10, 's', 'red', 'fill');
text(behavUNIXTimes, 2 * ones(1, numel(behavUNIXTimes)) + 0.05, behavTrialList, 'FontSize', 5, ...
'HorizontalAlignment', 'center');
ylim([0.8 2.1]);
if ~isempty(deviantTimesHandle);
legend([filePointHandles, behavPointHandles, lineHandles(1), timeDiffHandle], ...
{ 'imaging files', 'behavior times', 'potential matches', 'time differences' });
else
legend([filePointHandles, behavPointHandles, lineHandles(1), timeDiffHandle, deviantTimesHandle], ...
{ 'imaging files', 'behavior times', 'potential matches', 'time differences', 'deviant time points' });
end;
hold off;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
INRunExp_standard.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/INRunExp_standard.m
| 6,976 |
utf_8
|
0ca07cd497925df810b83f5c082ea448
|
function INRunExp_standard(this)
% INRunExp_standard - [no description]
%
% INRunExp_standard(this)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
o('#%s ...', mfilename, 3, this.verb);
%% init
% extract the parameters structure
params = this.in.standard;
comParams = this.in.common;
% timing reference
t0 = nowUNIX();
this.in.expStartTime = t0;
this.in.timestamp = datestr(unix2dn(t0), 'HHMMSS');
% update experiment counter
this.in.common.expNumber = this.in.common.expNumber + 1;
% stores the baseline 1 frames for each run
this.in.data.base1Frames = cell(params.nRuns, 1);
% stores the baseline 2 frames for each run
this.in.data.base2Frames = cell(params.nRuns, 1);
% stores the stimulus frames for each run
this.in.data.stimFrames = cell(params.nRuns, 1);
% stores the DFF average frame for each run
this.in.data.baseDFFAvg = cell(params.nRuns, 1);
this.in.data.stimDFFAvg = cell(params.nRuns, 1);
% set the include states
this.in.data.includeInAvg = ones(params.nRuns, 1);
% initialize stimulation
INInitStim(this);
%% init camera
% flush the previous data
stop(this.in.camH);
flushdata(this.in.camH);
% switch to non-stop collection mode and set logging to memory
triggerconfig(this.in.camH, 'manual');
set(this.in.camH, 'FramesPerTrigger', Inf, 'LoggingMode', 'memory');
% start camera but it waits for trigger
start(this.in.camH);
%% starting delay
showMessage(this, sprintf('%s | Intrinsic: starting delay (%.1f sec) ...', INGetTime(this), comParams.startDelay), ...
'yellow');
pause(comParams.startDelay);
if ~this.in.expRunning; INEndExp(this); return; end;
%% run loop
% loop over all runs
for iRun = 1 : params.nRuns;
% create the title string
titleString = sprintf(' | Intrinsic: Run %02d/%02d:', iRun, params.nRuns);
% collect the baseline frames
showMessage(this, sprintf('%s%s baseline 1 frames collection ...', INGetTime(this), titleString), 'yellow');
this.in.data.base1Frames{iRun} = collectData(this, params.baselineAvgDur);
if ~this.in.expRunning; INEndExp(this); return; end;
% wait until stimulus time
showMessage(this, sprintf('%s%s waiting for second baseline ...', INGetTime(this), titleString), 'yellow');
pause(params.baselineToStimDelay);
if ~this.in.expRunning; INEndExp(this); return; end;
% collect the baseline frames
showMessage(this, sprintf('%s%s baseline 2 frames collection ...', INGetTime(this), titleString), 'yellow');
this.in.data.base2Frames{iRun} = collectData(this, params.baselineAvgDur);
% calculate DFF of baseline data
this.in.data.baseDFFAvg{iRun} = getDFFAvg(this, this.in.data.base1Frames{iRun}, this.in.data.base2Frames{iRun});
% display data
INUpdateGUI(this);
if ~this.in.expRunning; INEndExp(this); return; end;
% wait until stimulus time
showMessage(this, sprintf('%s%s waiting for stimulus time ...', INGetTime(this), titleString), 'yellow');
pause(params.baselineToStimDelay);
if ~this.in.expRunning; INEndExp(this); return; end;
% stimulus
showMessage(this, sprintf('%s%s stimulus ...', INGetTime(this), titleString), 'yellow');
% play sound using TDT
if strcmp(comParams.stimMode, 'TDT');
% use the software trigger to launch the sound
this.in.RP.SoftTrg(1);
% wait for it to finish
pause(params.stdStimDur);
% play sound without TDT
elseif strcmp(comParams.stimMode, 'soundCard');
% blocking so that the program waits for the stimlus to finish
this.in.audioplayer.playblocking();
% send out a digital trigger
elseif strcmp(comParams.stimMode, 'trigOut');
outputSingleScan(this.in.daq.sessHandle, 1); % TTL high
outputSingleScan(this.in.daq.sessHandle, 0); % back to TTL low
% wait for it to finish
pause(params.stdStimDur);
end;
if ~this.in.expRunning; INEndExp(this); return; end;
% wait until stimulus data collection time
showMessage(this, sprintf('%s%s waiting for stimulus collection time ...', INGetTime(this), titleString), 'yellow');
pause(params.stimToStimAvgDelay);
if ~this.in.expRunning; INEndExp(this); return; end;
% collect the stimulus frames
showMessage(this, sprintf('%s%s stimulus frames collection ...', INGetTime(this), titleString), 'yellow');
this.in.data.stimFrames{iRun} = collectData(this, params.stimAvgDur);
% calculate DFF of stimulus data
this.in.data.stimDFFAvg{iRun} = getDFFAvg(this, this.in.data.base1Frames{iRun}, this.in.data.stimFrames{iRun});
% display data
INUpdateGUI(this);
if ~this.in.expRunning; INEndExp(this); return; end;
% wait the end period (recovery), unless it is the last run
if iRun ~= params.nRuns;
showMessage(this, sprintf('%s%s waiting for recovery period ...', INGetTime(this), titleString), 'yellow');
pause(params.waitPeriod);
end;
if ~this.in.expRunning; INEndExp(this); return; end;
end;
% clean up and free ressources
INCleanUp(this);
%% spatial downsampling loop
showMessage(this, sprintf('%s | Intrinsic: spatial down-sampling ...', INGetTime(this)));
% loop over all runs
for iRun = 1 : params.nRuns;
this.in.data.base1Frames{iRun} = INSpatialDownSample(this, this.in.data.base1Frames{iRun});
this.in.data.base2Frames{iRun} = INSpatialDownSample(this, this.in.data.base2Frames{iRun});
this.in.data.stimFrames{iRun} = INSpatialDownSample(this, this.in.data.stimFrames{iRun});
end;
showMessage(this, sprintf('%s | Intrinsic: spatial down-sampling done.', INGetTime(this)));
% set flags, update counter and update GUI
this.in.expRunning = false;
set(this.GUI.handles.in.paramPanElems.expNumber, 'String', sprintf('%d', this.in.common.expNumber)); % update in GUI
set(this.GUI.handles.in.runExpBut, 'BackgroundColor', 'red', 'Value', 0);
showMessage(this, sprintf('%s | Intrinsic: experiment number %02d done !', INGetTime(this), this.in.common.expNumber));
end
function frames = collectData(this, collectDur)
% collection start time
t0 = nowUNIXSec();
% start collecting
trigger(this.in.camH);
% start waiting loop
while nowUNIXSec() - t0 < collectDur;
pause(0.01); % avoid full-speed looping
end;
% stop and collect frames
stop(this.in.camH);
frames = getdata(this.in.camH);
o(['#%s: collected ' regexprep(repmat('%02dx', 1, ndims(frames)), 'x$', '') ' frame(s) ...'], ...
mfilename(), size(frames), 4, this.verb);
pause(0.02);
% flush data
flushdata(this.in.camH);
% restart camera
start(this.in.camH);
end
% extracts the DFF average of the frames as (F2 - F1) / F1
function DFFAvg = getDFFAvg(this, frames1, frames2)
% average frames1 over time
frames1 = INSpatialDownSample(this, nanmean(squeeze(frames1), 3));
% average frames2 over time
frames2 = INSpatialDownSample(this, nanmean(squeeze(frames2), 3));
%% calculate DFF
DFFAvg = (frames2 - frames1) ./ frames1;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
INSavePlot.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/INSavePlot.m
| 3,579 |
utf_8
|
4a457e0f84d96fe70d00758e8266075b
|
function INSavePlot(this, savePath, plotToSave, varargin)
% INSavePlot - [no description]
%
% INSavePlot(this, savePath, plotToSave, varargin)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% if no save path has been provided, create a dialog to request one
if isempty(savePath);
% create the folder if it does not exist yet
if exist(this.path.OCIASave, 'dir') ~= 7; mkdir(this.path.OCIASave); end;
% create the dialog
[saveName, savePath] = uiputfile('*.*', 'Select a path where to save the plot', this.path.OCIASave);
if ischar(saveName)
savePath = [savePath saveName];
saveName = regexprep(saveName, '(\.\w{3})?$', '');
else % otherwise abort the saving
return;
end;
else
saveName = savePath;
end;
% clean up path and show message
savePath = strrep(savePath, '\', '/');
showMessage(this, sprintf('Saving intrinsic plot to "%s" ...', savePath), 'yellow');
saveTic = tic; % for performance timing purposes
figName = saveName;
saveFig = figure('Name', figName, 'NumberTitle', 'off', 'Color', 'white', 'Units', 'pixels', ...
'Position', get(this.GUI.figH, 'Position'), 'Visible', 'off', 'MenuBar', 'none', 'Toolbar', 'none');
anAxe = this.GUI.in.fouSubAxeHands.(plotToSave);
inPanelChild = get(get(anAxe, 'Parent'), 'Children');
% gather everything that doesn't belong to the Intrinsic panel's GUI (buttons)
inPanelChild(~cellfun(@isempty, regexp(get(inPanelChild, 'Tag'), '^IN')) & inPanelChild ~= anAxe) = [];
% if the panel has no child or only the Intrinsic's axe but it's hidden, then do not save anything
if isempty(inPanelChild) || (numel(inPanelChild) == 1 && inPanelChild(1) == anAxe && strcmp(get(anAxe, 'Visible'), 'off'));
showWarning(this, 'OCIA:INSavePlot:NothingToSave', ...
sprintf('Cannot save analyser plot "%s" to "%s" because there is no plot to save.', figName, savePath));
return;
end;
% copy objects one by one starting from the last one
for iObj = fliplr(1 : numel(inPanelChild));
removeCallbacks(inPanelChild(iObj));
copyobj(inPanelChild(iObj), saveFig);
end;
% copy the colormap
set(saveFig, 'Colormap', get(this.GUI.figH, 'Colormap'));
saveFolder = regexprep(savePath, '/[\w\.]+$', '');
if exist(saveFolder, 'dir') ~= 7; mkdir(saveFolder); end;
% get extension
ext = regexprep(regexp(savePath, '\.(\w+)$', 'match'), '^\.', '');
% if extension is supported by the export_fig function, use that
if ~isempty(ext) && ~strcmp(ext, 'fig') && ~isempty(regexp(ext, 'png|pdf|jpg|eps|tif|bmp', 'once'));
if numel(varargin) > 0 && isnumeric(varargin{1});
resolution = sprintf('-r%d', varargin{1});
else
resolution = '-r150';
end;
if numel(varargin) > 1 && strcmpi(varargin{2}, 'noCrop');
export_fig(savePath, ['-' ext], resolution, '-nocrop', saveFig);
else
export_fig(savePath, ['-' ext], resolution, saveFig);
end;
% otherwise save as figure
else
savePath = [regexprep(savePath, ['\.' ext '$'], ''), '.fig'];
set(saveFig, 'Visible', 'on');
saveas(saveFig, savePath);
end;
close(saveFig);
showMessage(this, sprintf('Saving analyser plot to "%s" done (%.3f sec).', savePath, toc(saveTic)));
end
function removeCallbacks(elem)
if isprop(elem, 'Callback'); set(elem, 'Callback', []); end;
if isprop(elem, 'ButtonDownFcn'); set(elem, 'ButtonDownFcn', []); end;
childElems = get(elem, 'Children');
for iElem = 1 : numel(childElems);
removeCallbacks(childElems(iElem));
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
JTUpdateVirtualJoints.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/JTUpdateVirtualJoints.m
| 5,706 |
utf_8
|
72e85fec6b3a1f27b93113ed88dc6252
|
function JTUpdateVirtualJoints(this, iFrame, iJointType)
% JTUpdateVirtualJoints - [no description]
%
% JTUpdateVirtualJoints(this, iFrame, iJointType)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% show debug plots of virtual joints
showDebugPlot = 0;
% get the joints' x coordinate
joints = squeeze(this.jt.joints(:, iFrame, 1, iJointType));
% loop through the joint handles
for iJoint = 1 : this.jt.nJoints;
% if a joint coordinate is empty and it is a virtual joint and the previous and next coordinates are not empty,
% get the virtual joint's coordinates
if joints(iJoint) == 0 && this.jt.jointConfig{iJoint, 2} ...
&& joints(iJoint - 1) ~= 0 && joints(iJoint + 1) ~= 0;
jointCoords = squeeze(this.jt.joints(:, iFrame, :, iJointType));
p1 = jointCoords(iJoint - 1, :); % coordinates of the joint before
p2 = jointCoords(iJoint + 1, :); % coordinates of the joint after
r1 = this.jt.jointConfig{iJoint, 4}(1); % distance with the joint before
r2 = this.jt.jointConfig{iJoint, 4}(2); % distance with the joint after
o(['#JTUpdateVirtualJoints: trying to predict virtual joint %d with: p1: [%.1f,%.1f], p2: [%.1f,%.1f], ', ...
'd1: %.1f, d2: %.1f ...'], iJoint, p1, p2, r1, r2, 4, this.verb);
% iteratively try to find the interesection point with increasing distances
increaseStepR1 = r1 * 0.05; increaseStepR2 = r2 * 0.05; iLoop = 1; nMaxLoop = 10;
intersects = {}; % default is empty
while isempty(intersects) && iLoop < nMaxLoop;
% try to get the joints
[cx1, cy1, cx2, cy2, intersects] = calcVirtJoint(p1(1), p1(2), p2(1), p2(2), r1, r2); %#ok<ASGLU>
% if there is going to be another loop, increase distances
if isempty(intersects) && iLoop < nMaxLoop;
r1 = r1 + increaseStepR1;
r2 = r2 + increaseStepR2;
iLoop = iLoop + 1;
end;
end; % end while loop
% show debug informations
if showDebugPlot;
axeH = this.GUI.handles.jt.axe; %#ok<UNRCH>
hold(axeH, 'on');
% show the intersection circles
commonArgs = {'FaceColor', 'none', 'EdgeColor', [0.3 1 0], 'Curvature', [1, 1]};
rectangle('Parent', axeH, 'Position', [a - r1 b - r1 2 * r1 2 * r1], commonArgs{:});
rectangle('Parent', axeH, 'Position', [c - r2 d - r2 2 * r2 2 * r2], commonArgs{:});
% show the possible points
r = 4;
commonArgs = {'FaceColor', [0 0 1], 'EdgeColor', [0 0 1], 'Curvature', [1, 1]};
rectangle('Parent', axeH, 'Position', [cx1 - r/2 cy1 - r/2 r r], commonArgs{:});
rectangle('Parent', axeH, 'Position', [cx2 - r/2 cy2 - r/2 r r], commonArgs{:});
hold(axeH, 'off');
end;
if isempty(intersects);
o('#JTUpdateVirtualJoints: virtual joint %d could not be placed (iLoop: %d).', iJoint, iLoop, 2, this.verb);
showWarning(this, 'OCIA:JT:JTUpdateVirtualJoints:VirtualJointImpossible', ...
sprintf(['Impossible to get a virtual joint for joint %d with the distances: ', ...
'%.1f and %.1f and coordinates: [%.1f,%.1f] and [%.1f,%.1f]!'], iJoint, r1, r2, p1, p2));
% clear the joint coordinates
this.jt.joints(iJoint, iFrame, :, iJointType) = [0 0];
else
o('#JTUpdateVirtualJoints: virtual joint %d is either at: c1 [%.1f,%.1f] or c2 [%.1f,%.1f] (iLoop: %d).', ...
iJoint, intersects{1}, intersects{2}, iLoop, 3, this.verb);
% save the joint coordinates
this.jt.joints(iJoint, iFrame, :, iJointType) = intersects{1}; % hard coded, always the first intersect
end;
end; % end of virtual joint if condition
end; % end of joint looping
end
% little functino to find the virtual joint by calculating the intersecitno of two circles
function [cx1, cy1, cx2, cy2, intersects] = calcVirtJoint(a, b, c, d, r1, r2)
cx1 = NaN; cy1 = NaN; cx2 = NaN; cy2 = NaN; intersects = {};
% Finding the coordinates c (c1,c2) of the virtual joint is basically finding the intersection of two
% circles centered on p1 (a,b) and p2 (c,d) with respective radius r1 and r2:
%
% (x - a)^2 + (y - b)^2 = r1^2 AND (x - c)^2 + (y - d)^2 = r2^2
%
% First express the distance D between the two circles :
D = sqrt((c - a)^2 + (d - b)^2);
% Inter sections only happen if:
%
% r1 + r2 > D AND D > |r1 - r2|
%
% check for intersection
circlesIntersect = r1 + r2 >= D && D > abs(r1 - r2);
if ~circlesIntersect;
return;
end;
% To get the coordinates, first express gamma :
gamma = 0.25 * sqrt((D + r1 + r2) * (D + r1 - r2) * (D - r1 + r2) * (-D + r1 + r2));
% Then the coordinates can be calculated with :
cx1 = ((a + c) / 2) + (((c - a) * (r1^2 - r2^2)) / (2 * D^2)) + ((2 * gamma * (b - d)) / D^2);
cx2 = ((a + c) / 2) + (((c - a) * (r1^2 - r2^2)) / (2 * D^2)) - ((2 * gamma * (b - d)) / D^2);
cy1 = ((b + d) / 2) + (((d - b) * (r1^2 - r2^2)) / (2 * D^2)) - ((2 * gamma * (a - c)) / D^2);
cy2 = ((b + d) / 2) + (((d - b) * (r1^2 - r2^2)) / (2 * D^2)) + ((2 * gamma * (a - c)) / D^2);
% The intersection points are then:
intersects = {[cx1, cy1]; [cx2, cy2]};
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
BELightPulse.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/BELightPulse.m
| 1,073 |
utf_8
|
7d7e8d6d47649bbc740a57b9bccf2f5e
|
function BELightPulse(this, pulseDur, IPI, nPulses)
% BELightPulse - [no description]
%
% BELightPulse(this, pulseDur, IPI, nPulses)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
imagTTLState = get(this.GUI.handles.be.imagTTL, 'Value');
o('#%s(): pulseDur %.3f, IPI %.3f, nPulses %d.', mfilename, pulseDur, IPI, nPulses, 2, this.verb);
if this.be.hw.connected && isfield(this.be.hw, 'anOut');
start(timer('Name', 'PulseTimer', 'TimerFcn', { @doPulse, this.be, pulseDur, imagTTLState }, ...
'Period', pulseDur + IPI, 'TasksToExecute', nPulses, 'ExecutionMode', 'fixedRate'));
else
showWarning(this, 'OCIA:Behavior:LightHardwareDisconnected', 'Hardware is disconnected.');
set(this.GUI.handles.be.light, 'BackgroundColor', 'red', 'Value', 0);
end;
end
function doPulse(~, ~, be, pulseDur, imagTTLState)
be.hw.anOut.outputSingleScan([imagTTLState * 5, 1 * be.params.maxLight]);
pauseTicToc(pulseDur);
be.hw.anOut.outputSingleScan([imagTTLState * 5, 0 * be.params.maxLight]);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
INTestStim.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/INTestStim.m
| 3,097 |
utf_8
|
d3c965f0467534cb336f38b928666bc2
|
function INTestStim(this, ~, ~)
% INTestStim - [no description]
%
% INTestStim(this)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% update button
set(this.GUI.handles.in.testStimBut, 'Value', 1, 'Enable', 'off', 'BackgroundColor', 'yellow');
% disable run exp button
set(this.GUI.handles.in.runExpBut, 'Enable', 'off');
% extract the parameters structure
comParams = this.in.common;
try
% test stimulus differently depending on the stimulus mode
switch comParams.stimMode;
% play through the sound card
case 'soundCard';
% get the sound stimulus of the current setting
[soundToPlay, sampFreq] = INGetSoundStim(this);
if isempty(soundToPlay); return; end;
% use MATLAB sound function
this.in.audioplayer = audioplayer(soundToPlay, sampFreq);
this.in.audioplayer.playblocking();
% play by software triggering the TDT
case { 'TDT', 'trigIn' };
% get the sound stimulus of the current setting
[soundToPlay, sampFreq] = INGetSoundStim(this);
if isempty(soundToPlay); return; end;
% 1 loop for standard mode and nSweeps for fourier mode
nLoops = iff(strcmp(this.in.expMode, 'standard'), 1, this.in.fourier.nSweeps);
% calculate wait time
waitTime = 1.1 * numel(soundToPlay) * nLoops / sampFreq;
% load stimulus
this.in.RP = playTDTSound(soundToPlay, 0, this.GUI.figH, nLoops);
% launch stimulus with software trigger
this.in.RP.SoftTrg(1);
% wait for sound to finish
startWait = tic;
while ~isempty(this.in.RP) && toc(startWait) < waitTime;
pause(0.01);
end;
% send trigger out
case 'trigOut';
% show message
showMessage(this, 'Intrinsic: sending out TTL ...', 'yellow');
% suppress silly warning about on-demand channels
warning('off', 'daq:Session:onDemandOnlyChannelsAdded');
% create NI session with a digital channel
this.in.daq.sessHandle = daq.createSession(this.in.daq.vendorName);
addDigitalChannel(this.in.daq.sessHandle, this.in.daq.deviceID, this.in.daq.trigOutPort, 'OutputOnly');
% restore silly warning
warning('on', 'daq:Session:onDemandOnlyChannelsAdded');
% init to TTL low
outputSingleScan(this.in.daq.sessHandle, 0);
% send trigger
outputSingleScan(this.in.daq.sessHandle, 1); % TTL high
outputSingleScan(this.in.daq.sessHandle, 0); % back to TTL low
end;
% if something failed, capture and abort but still clean up
catch err;
showWarning(this, 'OCIA:INTestStim:TestFailed', ...
sprintf('Intrinsic: error during testing of stimulation ("%s"): %s.', err.identifier, err.message));
end;
% release resources
INCleanUp(this);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
ANSavePlot.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/ANSavePlot.m
| 6,041 |
utf_8
|
3d1614ebf1f33d5130d6d4f323ecb622
|
function ANSavePlot(this, savePath, varargin)
% ANSavePlot - [no description]
%
% ANSavePlot(this, savePath, varargin)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% if no save path has been provided, create a dialog to request one
if isempty(savePath);
% create the folder if it does not exist yet
if exist(this.path.OCIASave, 'dir') ~= 7; mkdir(this.path.OCIASave); end;
% create the dialog
[saveName, savePath] = uiputfile('*.*', 'Select a path where to save the plot', this.path.OCIASave);
if ischar(saveName)
savePath = [savePath saveName];
saveName = regexprep(saveName, '(\.\w{3})?$', '');
else % otherwise abort the saving
return;
end;
else
saveName = savePath;
end;
% clean up path and show message
savePath = strrep(savePath, '\', '/');
showMessage(this, sprintf('Saving analyser plot to "%s" ...', savePath), 'yellow');
saveTic = tic; % for performance timing purposes
figName = saveName;
if numel(varargin) > 0 && ~isempty(varargin{1}); figName = varargin{1}; end;
saveFig = figure('Name', figName, 'NumberTitle', 'off', 'Color', 'white', 'Units', 'pixels', ...
'Position', get(this.GUI.figH, 'Position'), 'Visible', 'off', 'MenuBar', 'none', 'Toolbar', 'none');
anAxe = this.GUI.handles.an.axe;
anPanelChild = get(this.GUI.handles.panels.AnalyserPanel, 'Children');
% gather everything that doesn't belong to the Analyser panel's GUI (buttons)
anPanelChild(~cellfun(@isempty, regexp(get(anPanelChild, 'Tag'), '^AN')) & anPanelChild ~= anAxe) = [];
% if the panel has no child or only the Analyser's axe but it's hidden, then do not save anything
if isempty(anPanelChild) || (numel(anPanelChild) == 1 && anPanelChild(1) == anAxe && strcmp(get(anAxe, 'Visible'), 'off'));
% get the empty or hidden plot reason
statusTextReason = get(this.GUI.handles.an.message, 'String');
if isempty(statusTextReason); statusTextReason = 'unknown'; end;
statusTextReason(1) = lower(statusTextReason(1));
statusTextReason = regexprep(statusTextReason, '\.$', '');
% show warning
showWarning(this, 'OCIA:ANSavePlot:NothingToSave', ...
sprintf('Cannot save analyser plot "%s" to "%s" because there is no plot to save. Possible cause: %s.', ...
figName, savePath, statusTextReason));
return;
end;
if ~verLessThan('matlab', '8.4.0');
% remove colorbar if a legend is present because of weird saving system
if any(arrayfun(@(i)isa(i, 'matlab.graphics.illustration.ColorBar'), anPanelChild)) ...
&& any(arrayfun(@(i)isa(i, 'matlab.graphics.illustration.Legend'), anPanelChild));
anPanelChild(arrayfun(@(i)isa(i, 'matlab.graphics.illustration.ColorBar'), anPanelChild)) = [];
end;
% copy objects one by one starting from the last one
for iObj = fliplr(1 : numel(anPanelChild));
% do not copy axes if next one is a colorbar
if isa(anPanelChild(iObj), 'matlab.graphics.axis.Axes') && iObj > 1 ...
&& (isa(anPanelChild(iObj - 1), 'matlab.graphics.illustration.ColorBar') ...
|| isa(anPanelChild(iObj - 1), 'matlab.graphics.illustration.Legend'));
continue;
% copy colorbar AND its axes
elseif isa(anPanelChild(iObj), 'matlab.graphics.illustration.ColorBar') && iObj < numel(anPanelChild) ...
&& isa(anPanelChild(iObj + 1), 'matlab.graphics.axis.Axes');
removeCallbacks(anPanelChild(iObj));
removeCallbacks(anPanelChild(iObj + 1));
copyobj([anPanelChild(iObj), anPanelChild(iObj + 1)], saveFig);
% copy legend AND its axes
elseif isa(anPanelChild(iObj), 'matlab.graphics.illustration.Legend') && iObj < numel(anPanelChild) ...
&& isa(anPanelChild(iObj + 1), 'matlab.graphics.axis.Axes');
removeCallbacks(anPanelChild(iObj));
removeCallbacks(anPanelChild(iObj + 1));
copyobj([anPanelChild(iObj), anPanelChild(iObj + 1)], saveFig);
else
% do not copy invisible stuff
if strcmp(get(anPanelChild(iObj), 'Visible'), 'off'); continue; end;
removeCallbacks(anPanelChild(iObj));
copyobj(anPanelChild(iObj), saveFig);
end;
end;
else
% copy objects one by one starting from the last one
for iObj = fliplr(1 : numel(anPanelChild));
removeCallbacks(anPanelChild(iObj));
copyobj(anPanelChild(iObj), saveFig);
end;
end;
% copy the colormap
set(saveFig, 'Colormap', get(this.GUI.figH, 'Colormap'));
saveFolder = regexprep(savePath, '/[\w\.]+$', '');
if exist(saveFolder, 'dir') ~= 7; mkdir(saveFolder); end;
% get extension
ext = regexprep(regexp(savePath, '\.(\w+)$', 'match'), '^\.', '');
% if extension is supported by the export_fig function, use that
if ~isempty(ext) && ~strcmp(ext, 'fig') && ~isempty(regexp(ext, 'png|pdf|jpg|eps|tif|bmp', 'once'));
if numel(varargin) > 1 && isnumeric(varargin{2});
resolution = sprintf('-r%d', varargin{2});
else
resolution = this.an.plotSaveResolution;
end;
warning('off', 'MATLAB:LargeImage');
if numel(varargin) > 2 && strcmpi(varargin{3}, 'noCrop');
export_fig(savePath, ['-' ext], resolution, '-nocrop', saveFig);
else
export_fig(savePath, ['-' ext], resolution, saveFig);
end;
warning('on', 'MATLAB:LargeImage');
% otherwise save as figure
else
savePath = [regexprep(savePath, ['\.' ext '$'], ''), '.fig'];
set(saveFig, 'Visible', 'on');
saveas(saveFig, savePath);
end;
close(saveFig);
showMessage(this, sprintf('Saving analyser plot to "%s" done (%.3f sec).', savePath, toc(saveTic)));
end
function removeCallbacks(elem)
if isprop(elem, 'Callback'); set(elem, 'Callback', []); end;
if isprop(elem, 'ButtonDownFcn'); set(elem, 'ButtonDownFcn', []); end;
childElems = get(elem, 'Children');
for iElem = 1 : numel(childElems);
removeCallbacks(childElems(iElem));
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
DIUpdateGUI.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/DIUpdateGUI.m
| 4,060 |
utf_8
|
7053fe17121fcccefd4ec7791bf84fb4
|
%% #DIUpdateGUI
function DIUpdateGUI(this, ~, ~)
o('#%s() ...', mfilename, 3, this.verb);
try % capture display errors
%% camera plot
try
currFrame = peekdata(this.GUI.di.camHandle, 1);
flushdata(this.GUI.di.camHandle);
currFrame(:, :, 2) = currFrame(:, :, 1);
currFrame(:, :, 3) = currFrame(:, :, 1);
% imagesc(currFrame, 'Parent', this.GUI.handles.di.camAxe);
cameAxeChild = get(this.GUI.handles.di.camAxe, 'Child');
if isempty(cameAxeChild);
cameAxeChild = imagesc(zeros(576, 720, 3), 'Parent', this.GUI.handles.di.camAxe);
axis(this.GUI.handles.di.camAxe, 'equal');
end;
set(cameAxeChild, 'CData', currFrame);
catch
imagesc(zeros(576, 720, 3), 'Parent', this.GUI.handles.di.camAxe);
end;
%% activity plot
actiW = 180; actiH = 180;
if this.GUI.di.activityRunning && ~isempty(this.GUI.di.actiMovies);
% get the current frame
activityFrame = this.GUI.di.actiMovies{this.GUI.di.actiMovieIndex}(:, :, :, this.GUI.di.actiMovieFrame);
% update the frame
this.GUI.di.actiMovieFrame = this.GUI.di.actiMovieFrame + 3;
if this.GUI.di.actiMovieFrame > size(this.GUI.di.actiMovies{1}, 4); this.GUI.di.actiMovieFrame = 1; end;
else
activityFrame = zeros(actiH, actiW, 3);
end;
% plot the frame
actiAxeChild = get(this.GUI.handles.di.actiAxe, 'Child');
if isempty(actiAxeChild);
actiAxeChild = imagesc(activityFrame, 'Parent', this.GUI.handles.di.actiAxe);
axis(this.GUI.handles.di.actiAxe, 'equal');
end;
set(actiAxeChild, 'CData', activityFrame);
% calculate zoom factors
actiWZoom = actiW / this.GUI.di.zoomLevel; actiHZoom = actiH / this.GUI.di.zoomLevel;
actiMargX = (actiW - actiWZoom) / 2; actiMargY = (actiH - actiHZoom) / 2;
xLims = [0, actiW - actiMargX]; yLims = [0, actiH - actiMargY];
set(this.GUI.handles.di.actiAxe, 'XLim', xLims, 'YLim', yLims);
%% reponse axe
% create the response rate rectangle
delete(get(this.GUI.handles.di.respRateAxe, 'Child'));
hold(this.GUI.handles.di.respRateAxe, 'on');
rectangle('Parent', this.GUI.handles.di.respRateAxe, 'FaceColor', 'blue', 'EdgeColor', 'black', 'Position', [0 0 min(abs(this.di.nResps + 0.1), 10) 1]);
% add the threshold
plot(this.GUI.handles.di.respRateAxe, ones(2, 1) * this.di.respRateThresh, [0 1], 'Color', 'red', 'LineWidth', 8);
hold(this.GUI.handles.di.respRateAxe, 'off');
set(this.GUI.handles.di.respRateAxe, 'XLim', [0, 10], 'YLim', [0 1], 'XTick', [], 'YTick', []);
% apply the decay
this.di.nResps = min(max((this.di.nResps - this.di.nRespsDecay) * 0.99, 0), 10 + 0.5);
%% time axe
% create the time rectangle
if this.di.waitingForResp;
delete(get(this.GUI.handles.di.respTimeAxe, 'Child'));
hold(this.GUI.handles.di.respTimeAxe, 'on');
remTime = min(max(this.di.waitingTime - (nowUNIX - this.di.waitingStartTime), 0) + 0.001, this.di.waitingTime);
rectangle('Parent', this.GUI.handles.di.respTimeAxe, 'FaceColor', 'green', 'EdgeColor', 'black', 'Position', [0 0 remTime 1]);
hold(this.GUI.handles.di.respTimeAxe, 'off');
set(this.GUI.handles.di.respTimeAxe, 'XLim', [0, this.di.waitingTime], 'YLim', [0 1], 'XTick', [], 'YTick', []);
set(this.GUI.handles.di.panels.time, 'Title', sprintf('Response time - %.1f sec', remTime / 1000));
end;
% check if a response was given
if this.di.waitingForResp && this.di.nResps > this.di.respRateThresh;
this.di.resp = true;
this.di.waitingForResp = false;
stimNum = this.di.stimMatrix(this.di.iTrial, this.di.iStimMat);
isTarget = stimNum == this.di.targetStim;
showMessage(this, sprintf('RESPONSE !! Trial %d: stimulus %d, target: %d, correct: %d...', this.di.iTrial, stimNum, isTarget, isTarget), 'yellow');
end;
if this.di.lockMouse;
r = java.awt.Robot();
lockCoords = this.GUI.pos(1:2) + this.GUI.pos(3:4) - [2 2];
r.mouseMove(lockCoords(1), lockCoords(2));
end;
catch err;
errStack = getStackText(err);
showWarning(this, 'OCIA:DIUpdateGUI', sprintf('Problem in the discriminator GUI update function: "%s".', err.message));
o(errStack, 0, 0);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
DWFilterTable.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/DWFilterTable.m
| 9,418 |
utf_8
|
0487d32d14dbf96aa9d050a83844249d
|
function [filtTable, filtTableIndexes] = DWFilterTable(this, filtText, tableToUse, tIDs)
% DWFilterTable - Filter the DataWatcher table and return the rows (and row indexes)
%
% [filtTable, filtTableIndexes] = DWFilterTable(this, filtText)
% [filtTable, filtTableIndexes] = DWFilterTable(this, filtText, tableToUse)
%
% Filters the rows of the 'tableToUse' (or the DataWatcher's table if none provided) based on the column names
% using the filternig string 'filtText'. The filtering string can be anything like: 'rowType = notebook' or
% 'rowType ~= imgData' for regexp match or 'spot != spot01' for *not* matching or
% 'spot = spot01 AND day = 2014_02_08' or 'rowType = imgData OR animal = mouse1', etc.
% Sub-column names are also possible like 'data.rawImg.loadStatus = full' to get all the rows where the
% data is fully loaded.
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% if no table was provided, use the default table which is the DataWatcher's table
if ~exist('tableToUse', 'var') || isempty(tableToUse);
tableToUse = this.dw.table;
end;
% if no table IDs were provided, use the DataWatcher table's IDs
if ~exist('tIDs', 'var') || isempty(tIDs);
tIDs = this.dw.tableIDs;
end;
% separate the filter into parts at the join operators
[filtParts, ~, ~, ~, ops] = regexp(filtText, '\s(OR|AND)\s', 'split');
% holder for the filtered table indexes
filtTableIndexes = [];
% go through each filter pair
for iPart = 1 : numel(filtParts);
% match the filter string for: colName (column name), eq (equality), val (value)
hit = regexp(filtParts{iPart}, '^(?<colName>[\w\.\*]+)\s+(?<eq>[!~]{0,2}\=)\s+(?<val>.+)$', 'names');
% cannot match the pair, skip it with warning
if isempty(hit);
showWarning(this, 'OCIA:DW:DWFilterTable:BadRegexp', ...
sprintf('Cannot processed regular expression part: %s. Skipping it.', filtParts{iPart}));
continue;
end;
% get the equality function
switch hit.eq;
% basic string comparison
case '='; eqfun = @strcmp;
% basic string comparison with negation
case '!='; eqfun = @(varargin)~strcmp(varargin{:});
% regular expression comparison
case '~='; eqfun = @(varargin)~isempty(regexp(varargin{1}, varargin{2}, 'once'));
% regular expression comparison with negation
case '!~='; eqfun = @(varargin)isempty(regexp(varargin{1}, varargin{2}, 'once'));
% unknown comparison sign
otherwise
showWarning(this, 'OCIA:DW:DWFilterTable:UnkownVar', ...
sprintf('Unknown comparison sign requested for filtering: %s', hit.eq));
continue;
end;
% extract the value and the filtering column's name
val = hit.val;
colName = hit.colName;
% if the column name does not contain a sub-column
if isempty(regexp(colName, '^[\w\*]+\.[\w\*]+', 'once'));
% if the requested filtering column is not part of the table's column list and is not the rowID
if ~ismember(colName, tIDs) && ~strcmp(colName, 'rowID');
% show a warning and skip
showWarning(this, 'OCIA:DW:DWFilterTable:UnkownColName', ...
sprintf('Unknown column name requested for filtering: %s', colName));
continue;
end;
% special case for the row IDs
if strcmp(colName, 'rowID');
values = DWGetRowID(this, 1 : size(tableToUse, 1), tableToUse, tIDs);
% otherwise get all the values from the table's column
else
values = get(this, 'all', colName, tableToUse, tIDs);
end;
% make sure values are cell
if ~iscell(values); values = { values }; end;
% make sure no cell is empty
values(cellfun(@isempty, values)) = { '' };
% if the variable name has a sub-variable name (like "data.rawImg"), extract the values differently
else
values = getSubColumnValues(this, tIDs, tableToUse, colName);
end;
% check if all values are strings and abort with a warning if it is not the case
isAllCell = all(cellfun(@ischar, values));
if ~isAllCell;
showWarning(this, 'OCIA:DW:DWFilterTable:NotCharCellFilter', 'Requested filtering on a non-string column. Aborting.');
return;
end;
% remove the delete tag
values = regexprep(values, ['^' this.GUI.dw.deleteTag], '');
% get the rows where the requested values match (or not) the table's values
tempTableIndexes = find(cellfun(@(valueTable) eqfun(valueTable, val), values));
% if this is the first filter pair, use if as starting filtered table
if iPart == 1;
filtTableIndexes = tempTableIndexes;
% if the previous filter was an 'AND' operator, only get the overlapping indexes
elseif strcmp(ops{iPart - 1}, ' AND ');
% only get the overlap of them
filtTableIndexes(~ismember(filtTableIndexes, tempTableIndexes), :) = []; %#ok<AGROW>
% if the previous filter was an 'OR' operator, get the unique concatenated indexes
elseif strcmp(ops{iPart - 1}, ' OR ');
% get the unique concatenated table
filtTableIndexes = unique(vertcat(filtTableIndexes, tempTableIndexes), 'rows');
end;
end; % end of filter pairs looping
% create the filtered table using the filtered indexes
filtTable = tableToUse(filtTableIndexes, :);
end
% extract the values of a non-character column
function newValues = getSubColumnValues(this, tIDs, tableToUse, colName)
% get the column name "parts"
colNameParts = regexp(colName, '\.', 'split');
% get the values for the column name
values = get(this, 'all', colNameParts{1}, tableToUse, tIDs);
% make sure values are cell
if ~iscell(values); values = { values }; end;
% make sure no empty cells exist by filling them with empty structures
values(cellfun(@isempty, values)) = { struct() };
% create a new values cell-array which will have the extract sub-column values
newValues = cell(numel(values), 1);
% go through each row of the table and asses whether the sub-column matches
for iRow = 1 : numel(values);
% get a row validity tag
isRowValid = true;
% get the remaining column parts
localColumnParts = colNameParts(2 : end);
% get the current structure
currentValue = values{iRow};
% recursively get the right field from the current structure
while ~isempty(localColumnParts);
% if the current value is still a structure and it has the right sub-field
if isstruct(currentValue) && isfield(currentValue, localColumnParts{1});
% get the "next" sub-structure and move forward in the list of the column parts
currentValue = currentValue.(localColumnParts{1});
localColumnParts(1) = [];
% if the current value is still a structure with at least one field and a numbered field was required
elseif isstruct(currentValue) && numel(fieldnames(currentValue)) ...
&& ~isempty(regexp(localColumnParts{1}, '^\s*\d+\s*$', 'once'));
fNames = fieldnames(currentValue); % get the field names
iField = str2double(localColumnParts{1}); % get the sub-field number
% if the required number is not a number or exceeds the limit, abort
if isnan(iField) || iField < 1 || iField > numel(fNames);
% mark this row as non-valid and abort
isRowValid = false;
break;
end;
% otherwise get the "next" sub-structure by getting the right sub-field using the number given as input and
% move forward in the list of the column parts
currentValue = currentValue.(fNames{iField});
localColumnParts(1) = [];
% if the current value is still a structure with at least one field and any field was required
elseif isstruct(currentValue) && numel(fieldnames(currentValue)) && strcmp(localColumnParts{1}, '*');
% get the "next" sub-structure and move forward in the list of the column parts
fNames = fieldnames(currentValue); % get the field names
currentValue = currentValue.(fNames{1});
localColumnParts(1) = [];
% if the current value is still a structure but it does *not* have the right sub-field, abort
elseif isstruct(currentValue);
% mark this row as non-valid and abort
isRowValid = false;
break;
end;
end;
% if the current row is already flagged as non-valid, do not continue
if ~isRowValid;
% fill the row with an empty string
newValues{iRow} = '';
continue;
end;
% store the extracted value
newValues{iRow} = currentValue;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIACreateParamPanelControls.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/OCIACreateParamPanelControls.m
| 26,865 |
utf_8
|
96f2eed824df54d1d3e64fbb0b6a310d
|
function OCIACreateParamPanelControls(this, modeID, varargin)
% OCIACreateParamPanelControls - Creates a parameter pannel menu
%
% OCIACreateParamPanelControls(this, modeID, optionalHandleOfNavButtons)
%
% Creates a parameter panel menu from a parameter panel configuration ("this.GUI.(modeID).paramPanConfig") and a
% data structure ("this.(modeID).(categ).(id)"). If "optionalHandleOfNavButtons" exists and is a handle to the
% parameter panel navigation buttons, the panel is not re-created but just updated to display the right page
% ("this.GUI.(modeID).paramPage").
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% abort if no configuration provided
if isempty(this.GUI.(modeID).paramPanConfig); return; end;
%% init
fontSizeAdjust = 1;
labelFontSizeAdjust = 1;
switch modeID;
% Analyser mode
case 'an';
% define the updating function
updateFunction = @ANUpdatePlot;
% define the max number of rows and the number of items to place
nMaxRows = 5; nMinRows = 5; nMaxCols = 2; nMinCols = 2; pad = 0.02; inPad = 0.01;
% nMaxRows = 4; nMinRows = 4; nMaxCols = 4; nMinCols = 3; pad = 0.02; inPad = 0.01;
% fontSizeAdjust = 3.0;
% Intrinsic mode
case 'in';
% define the updating function
updateFunction = @INUpdateParams;
% define the max number of rows and the number of items to place
nMaxRows = 10; nMinRows = 8; nMaxCols = 4; nMinCols = 3; pad = 0.025; inPad = 0.02;
% Behavior mode
case 'be';
% define the updating function
updateFunction = @BEUpdateParams;
% define the max number of rows and the number of items to place
nMaxRows = 15; nMinRows = 15; nMaxCols = 2; nMinCols = 2; pad = 0.02; inPad = 0.015;
fontSizeAdjust = 0.5;
% TrialView mode
case 'tv';
% define the updating function
updateFunction = @TVUpdateParams;
% define the max number of rows and the number of items to place
nMaxRows = 10; nMinRows = 10; nMaxCols = 2; nMinCols = 2; pad = 0.02; inPad = 0.015;
labelFontSizeAdjust = 1.1;
fontSizeAdjust = 0.7;
otherwise
return;
end;
%% init the parameter pannel dimensions
% common inputs
commons = { 'Parent', this.GUI.handles.(modeID).paramPan, 'Units', 'normalized', 'Enable', 'off' };
UICommons = struct();
callBackFcn = { 'Callback', @(h, e) updateFunction(this, h, e) };
UICommons.text = [ commons, { 'Background', 'white', 'Style', 'edit' }, callBackFcn ];
UICommons.dropdown = [ commons, { 'Background', 'white', 'Style', 'popupmenu' }, callBackFcn ];
UICommons.list = [ commons, { 'Background', 'white', 'Style', 'list', 'Min', 0, 'Max', 2 }, callBackFcn ];
UICommons.button = [ commons, { 'Style', 'pushbutton' } ];
UICommons.slider = [ commons, { 'Style', 'slider' } ];
UICommons.lab = [ commons, { 'Background', 'white', 'Style', 'text' } ];
UICommons.paramNav = [ commons, { 'Style', 'pushbutton', 'Enable', 'off', 'FontSize', ...
round(this.GUI.pos(4) / 55 * fontSizeAdjust), 'Callback', @(h, e)OCIACreateParamPanelControls(this, modeID, h) } ];
% define the max number of rows and the number of items to place
nUICtrl = size(this.GUI.(modeID).paramPanConfig, 1);
UISizes = this.GUI.(modeID).paramPanConfig{:, 5};
nUICtrlRows = sum(UISizes(:, 1));
% calculate the number of acutal columns and rows to use
nRows = min(max(ceil(nUICtrlRows / nMaxCols), nMinRows), nMaxRows);
nCols = min(max(ceil((nUICtrlRows / nRows)), nMinCols), nMaxCols) + 0.15;
elemW = (1 - (nCols + 1) * pad) / nCols; % width depends on the number of columns
elemH = (1 - (nRows + 1) * pad) / nRows; % height depends on the number of rows
iRow = 0; iCol = 0; %#ok<NASGU>, init the row and column indexes
% part of the width that is allocated for the label if it is on the side
labelWidthRatio = 0.5;
% height that is allocated for the label if it is on the top
labelHeight = 0.5;
% if call was made by one of the navigate buttons
if ~isempty(varargin) && (varargin{1} == this.GUI.handles.(modeID).nextParams...
|| varargin{1} == this.GUI.handles.(modeID).prevParams);
% get all UI elements except the arrows
UIElems = this.GUI.handles.(modeID).paramPanElems;
% compute the minimum and maximum positions of the UIControls to desactivate the next/prev buttons
minPos = Inf; maxPos = -Inf;
% get the move direction
direction = iff(varargin{1} == this.GUI.handles.(modeID).prevParams, 1, -1);
% get the IDs and go through each elements
UIIDs = fieldnames(UIElems);
for iElem = 1 : numel(UIIDs);
% get the position of this element
pos = get(this.GUI.handles.(modeID).paramPanElems.(UIIDs{iElem}), 'Position');
% update the position
pos = pos + [nMaxCols * (elemW + pad) 0 0 0] .* direction;
% move the element
set(this.GUI.handles.(modeID).paramPanElems.(UIIDs{iElem}), 'Position', pos);
% if the control is outside the visible area, hide them
isOut = pos(1) > 0 && (pos(1) + pos(3)) < 1;
set(this.GUI.handles.(modeID).paramPanElems.(UIIDs{iElem}), 'Visible', iff(isOut, 'on', 'off'));
minPos = min(minPos, pos(1));
maxPos = max(maxPos, pos(1) + pos(3));
end;
% enable/disable the navigating buttons
set(this.GUI.handles.(modeID).prevParams, 'Enable', iff(minPos > 0, 'off', 'on'));
set(this.GUI.handles.(modeID).nextParams, 'Enable', iff(maxPos < 1, 'off', 'on'));
% update the page number
this.GUI.(modeID).paramPage = this.GUI.(modeID).paramPage + direction;
return;
end;
%% clear the parameters area
paramPanChildren = get(this.GUI.handles.(modeID).paramPan, 'Children');
% do not remove the navigating buttons
if isfield(this.GUI.handles.(modeID), 'nextParams');
paramPanChildren(paramPanChildren == this.GUI.handles.(modeID).nextParams) = [];
paramPanChildren(paramPanChildren == this.GUI.handles.(modeID).prevParams) = [];
end;
delete(paramPanChildren);
this.GUI.handles.(modeID).paramPanElems = struct();
%% create the next previous settings buttons
% calculate X and Y base positions
prevButPosX = 0.25 * pad;
prevButPosY = pad;
this.GUI.handles.(modeID).prevParams = uicontrol(UICommons.paramNav{:}, 'String', '<', ...
'Tag', sprintf('%sParamPrevParams', upper(modeID)), ...
'Position', [prevButPosX prevButPosY elemW * 0.1 (elemH + pad) * nRows - pad], ...
'ToolTipString', 'Previous parameter controls');
iRow = iRow + nRows;
iCol = 0.05 + pad;
nextButPosX = (nCols - 0.1) * (pad + elemW) + 0.75 * pad;
this.GUI.handles.(modeID).nextParams = uicontrol(UICommons.paramNav{:}, 'String', '>', ...
'Tag', sprintf('%sParamNextParams', upper(modeID)), ...
'Position', [nextButPosX prevButPosY elemW * 0.1 (elemH + pad) * nRows], ...
'ToolTipString', 'Next parameter controls');
%% create the UI elements with their labels
% go through all elements, create them and place them
for iUICtrl = 1 : nUICtrl;
% get the variables of the current control element
rowParams = table2cell(this.GUI.(modeID).paramPanConfig(iUICtrl, :));
[categ, id, UIType, valueType, UISize, isLabelAbove, label, tooltip] = rowParams{:};
% adjust element height for multiple rows
elemHLocal = (1 - (nRows - UISize(1) + 2) * pad) / nRows; % height depends on the number of rows
% adjacent buttons
if strcmp(UIType, 'button') && UISize(2) > 0 && iUICtrl > 1;
rowParamsBef = table2cell(this.GUI.(modeID).paramPanConfig(iUICtrl - 1, :));
[~, ~, UITypeBef, ~, UISizeBef] = rowParamsBef{:};
% if this is the second button element that is not full width and total width is not exceeding 1
if strcmp(UITypeBef, 'button') && UISizeBef(2) > 0 && UISize(2) + UISizeBef(2) <= 1;
% put this button at the same row
iRow = iRow - 1;
end;
end;
% update row/column index
iRow = iRow + UISize(1);
% if max number of rows is reached, go to the next column update rows/columns
if iRow > nRows;
iRow = UISize(1);
iCol = iCol + 1;
end;
% calculate X and Y base positions
elemPosX = (iCol - 1) * (pad + elemW) + pad;
if UISize(1) == nRows;
elemPosY = 1 - iRow * elemHLocal - pad;
elseif UISize(1) > 1;
elemPosY = 1 - iRow * (elemHLocal + pad * (UISize(1) / nRows)) - pad;
else
elemPosY = 1 - iRow * (elemHLocal + pad) + pad;
end;
% font sizes
ctrlElemFontSize = round(this.GUI.pos(4) / (105 - 3 * nRows)) * fontSizeAdjust;
labFontSize = round(this.GUI.pos(4) / (115 - 3 * nRows + 0.1 * numel(label))) * fontSizeAdjust * labelFontSizeAdjust;
% calculate positions, depending on whether the label is above or not:
% if label is above
if isLabelAbove;
% position and size for label
labElemX = elemPosX;
% labElemY = elemPosY + (UISize(1)) * elemHLocal + (UISize(1) - 1) * pad;
labElemY = elemPosY + (UISize(1) - labelHeight) * elemHLocal + 0.5 * pad;
labElemW = elemW;
labelemHLocal = labelHeight * elemHLocal;
% position and size for GUI element
ctrlElemX = elemPosX;
ctrlElemW = elemW;
ctrlElemY = elemPosY;
ctrlelemHLocal = (UISize(1) - labelHeight) * elemHLocal + pad;
labFontSize = round(this.GUI.pos(4) / (125 - 3 * nRows + 0.1 * numel(label))) * fontSizeAdjust * labelFontSizeAdjust;
% if label is not above
else
% position and size for label
labElemX = elemPosX;
labElemY = elemPosY + (UISize(1) * 0.5 - 0.25) * elemHLocal;
labElemW = elemW * (labelWidthRatio - inPad);
labelemHLocal = elemHLocal * 0.5;
% position and size for GUI element
ctrlElemX = elemPosX + elemW * (labelWidthRatio + inPad);
ctrlElemW = elemW * (1 - labelWidthRatio - inPad);
ctrlElemY = elemPosY;
ctrlelemHLocal = UISize(1) * elemHLocal + (UISize(1) - 1) * pad;
end;
% reduce a bit the size of the dropdown menus
if strcmp(UIType, 'dropdown');
labFontSize = round(labFontSize * 0.8);
ctrlElemFontSize = round(ctrlElemFontSize * 0.8);
labElemY = elemPosY + (UISize(1) * 0.5 - 0.1) * elemHLocal;
% no label for buttons
elseif strcmp(UIType, 'button');
ctrlElemX = ctrlElemX - labElemW;
ctrlElemW = ctrlElemW + labElemW;
labElemW = 0;
% special case of two buttons next to each other
if UISize(2) > 0;
ctrlElemW = ctrlElemW * UISize(2);
% adjacent buttons
if iUICtrl > 1;
rowParamsBef = table2cell(this.GUI.(modeID).paramPanConfig(iUICtrl - 1, :));
[~, ~, UITypeBef, ~, UISizeBef] = rowParamsBef{:};
% if this is the second button element that is not full width and total width is not exceeding 1
if strcmp(UITypeBef, 'button') && UISizeBef(2) > 0 && UISize(2) + UISizeBef(2) <= 1;
% put this button to the right
ctrlElemX = ctrlElemX + ctrlElemW;
end;
end;
end;
% process differently big lists
elseif strcmp(UIType, 'list') && UISize(1) == nRows && isLabelAbove;
labelHeightLocal = 0.8;
% position and size for label
labElemY = elemPosY + (UISize(1) - labelHeightLocal * 0.9) * elemHLocal + 0.5 * pad;
labelemHLocal = labelHeightLocal * elemHLocal;
% position and size for GUI element
ctrlelemHLocal = (UISize(1) - labelHeightLocal) * elemHLocal + pad;
labFontSize = round(this.GUI.pos(4) / (125 - 3 * nRows + 0.1 * numel(label))) * 1.5;
% process differently big lists
elseif strcmp(UIType, 'list') && UISize(1) > 1 && isLabelAbove;
labelHeightLocal = 0.8;
labElemY = elemPosY + (UISize(1) - labelHeightLocal * 0.5) * elemHLocal + 0.5 * pad;
labFontSize = round(this.GUI.pos(4) / (125 - 3 * nRows + 0.1 * numel(label))) * 1.5;
end;
% create the label
this.GUI.handles.(modeID).paramPanElems.([id '_label']) = uicontrol(UICommons.lab{:}, 'String', label, ...
'Position', [labElemX labElemY labElemW labelemHLocal], 'ToolTipString', tooltip, ... 'BackgroundColor', 'red', ...
'Tag', sprintf('%sParam%s', upper(modeID), id), 'FontSize', labFontSize);
% get category parts
categParts = regexp(categ, '\.', 'split');
if numel(categParts) > 1;
categ = categParts{1};
subCateg = categParts{2};
else
subCateg = [];
end;
% if the field does not exist, create it
if (~isempty(subCateg) && ~isfield(this.(modeID).(categ).(subCateg), id)) ...
|| (isempty(subCateg) && ~isfield(this.(modeID).(categ), id));
this.(modeID).(categ).(id) = '';
end;
callbackFcn = [];
% process the different UI types
switch UIType;
% text controls
case 'text';
% get the value from the storage variable
if isempty(subCateg);
storedValue = this.(modeID).(categ).(id);
else
storedValue = this.(modeID).(categ).(subCateg).(id);
end;
% if the value is not text and its an array, display as an array between brackets
if numel(storedValue) > 1 && ~strcmp(valueType, 'text') && ~strcmp(valueType, 'cellArray');
% add semi colon at each line end
stringValue = [ num2str(storedValue), repmat(';', size(storedValue, 1), 1)];
% reshape as a single line
stringValue = reshape(stringValue', 1, numel(stringValue));
% replace all spaces by single space
stringValue = regexprep(stringValue, '\s+', ' ');
% remove all starting spaces
stringValue = regexprep(stringValue, '^\s', '');
stringValue = regexprep(stringValue, '; ', ';');
% remove all empty spaces and replace them by commas
stringValue = ['[', regexprep(stringValue, '\s+', ','), ']'];
% clean up: remove last semi colon
stringValue = regexprep(stringValue, ';\]$', ']');
% clean up: remove starting comas
stringValue = regexprep(stringValue, '[\[;]$', ']');
% clean up: add space after each colon or semi colon
stringValue = regexprep(stringValue, '([,;])', '$1 ');
% if the value is a text, keep it as a string so do nothing
elseif numel(storedValue) > 1 && strcmp(valueType, 'text');
stringValue = storedValue;
% if the value is a text, keep it as a cell array string so do nothing
elseif iscell(storedValue) && strcmp(valueType, 'cellArray');
% process each cell and transform it into a string
for iCell = 1 : numel(storedValue);
% if cell is already a string, skip
if ischar(storedValue{iCell});
continue;
% if cell is an array, transform it into a string
elseif isnumeric(storedValue{iCell});
% add semi colon at each line end
stringValue = [ num2str(storedValue{iCell}), repmat(';', size(storedValue{iCell}, 1), 1)];
% reshape as a single line
stringValue = reshape(stringValue', 1, numel(stringValue));
% replace all spaces by single space
stringValue = regexprep(stringValue, '\s+', ' ');
% remove all starting spaces
stringValue = regexprep(stringValue, '^\s', '');
stringValue = regexprep(stringValue, '; ', ';');
% remove all empty spaces and replace them by commas
stringValue = ['[', regexprep(stringValue, '\s+', ','), ']'];
% clean up: remove last semi colon
stringValue = regexprep(stringValue, ';\]$', ']');
% clean up: remove starting comas
stringValue = regexprep(stringValue, '[\[;]$', ']');
% clean up: add space after each colon or semi colon
storedValue{iCell} = regexprep(stringValue, '([,;])', '$1 ');
% if just an empty cell
elseif ~isempty(storedValue{iCell});
storedValue{iCell} = '';
% otherwise if not just and empty, abort conversion
else
storedValue{iCell} = 'unknownDataType';
showWarning(this, 'OCIA:OCIACreateParamPanelControls:UnkownDataTypeInCellArray', sprintf( ...
['An unknown data type has been found in the cell array of the parameter control ', ...
'"%s" of the mode "%s", class: %s! Skipping.'], id, modeID, class(storedValue)));
end;
end;
% non-empty cell array
if ~isempty(storedValue) && numel(storedValue) >= 1 && ~isempty(storedValue{1});
% add a semi colon after each last cell
storedValue(:, end) = arrayfun(@(iCell) [storedValue{iCell, end}, ';'], 1 : size(storedValue, 1), ...
'UniformOutput', false);
% rearrange cell-array
storedValue = storedValue';
% add a coma after each cell
storedValue = arrayfun(@(iCell) [storedValue{iCell}, ','], 1 : numel(storedValue), ...
'UniformOutput', false);
% remove the useless commas
storedValue = regexprep(storedValue, ';,$', ';');
% create the string
stringValue = ['{ ', regexprep(sprintf('%s ', storedValue{:}), ' $', '') ' }'];
% cell-array is empty
else
stringValue = '';
end;
% otherwise the value is just a number
else
stringValue = num2str(storedValue);
end;
% leave value empty
value = [];
% substitue pi
stringValue = regexprep(stringValue, '3\.14', 'pi');
stringValue = regexprep(stringValue, '6\.28', '2pi');
% drop down menu elements
case 'dropdown';
% if the value from the storage variable is empty
if (isempty(subCateg) && isempty(this.(modeID).(categ).(id))) ...
|| (~isempty(subCateg) && isempty(this.(modeID).(categ).(subCateg).(id)));
value = 1; % select the first item
% otherwise if it is a boolean drop-down and there is a value in the storage variable
elseif numel(valueType) == 2 && all(ismember(valueType, { 'true', 'false' }));
% get the values to select
if isempty(subCateg);
valueString = iff(this.(modeID).(categ).(id), 'true', 'false');
else
valueString = iff(this.(modeID).(categ).(subCateg).(id), 'true', 'false');
end;
value = find(strcmp(valueType, valueString));
% otherwise if there is a value in the storage variable
else
% get the values to select
if isempty(subCateg);
value = find(strcmp(valueType, this.(modeID).(categ).(id)));
else
value = find(strcmp(valueType, this.(modeID).(categ).(subCateg).(id)));
end;
end;
% use a string the cell-array from the configuration
stringValue = valueType;
% list elements
case 'list';
% get the stored variable
if isempty(subCateg);
storedVariable = this.(modeID).(categ).(id);
else
storedVariable = this.(modeID).(categ).(subCateg).(id);
end;
% if the value from the storage variable is empty
if isempty(storedVariable);
value = []; % select nothing
% otherwise if there is a value in the storage variable
else
% make sure the stored variable is a cell
if ~iscell(storedVariable); storedVariable = { storedVariable }; end;
% make sure the valueType is a cell
if ~iscell(valueType); valueType = { valueType }; end;
% make sure the valueType is a cell
if ~isempty(valueType) && numel(valueType) == 1 && iscell(valueType{1});
valueType = valueType{1};
end;
% get the values to select
value = find(arrayfun(@(i)ismember(valueType{i}, storedVariable), 1 : numel(valueType)));
end;
% use a string the cell-array from the configuration
stringValue = valueType;
% buttons
case 'button';
stringValue = label;
if iscell(valueType) && ~isempty(valueType) && isa(valueType{1}, 'function_handle');
callbackFcn = valueType{1};
elseif ~isempty(valueType) && isa(valueType, 'function_handle');
callbackFcn = valueType;
end;
% sliders
case 'slider';
stringValue = label;
if isempty(subCateg);
value = this.(modeID).(categ).(id);
else
value = this.(modeID).(categ).(subCateg).(id);
end;
if iscell(valueType) && ~isempty(valueType) && isa(valueType{1}, 'function_handle');
callbackFcn = valueType{1};
elseif ~isempty(valueType) && isa(valueType(1), 'function_handle');
callbackFcn = valueType;
end;
end; % end of GUI type switch
% reduce a bit the size of the lists if there are a lot elements inside
if strcmp(UIType, 'list') && ~strcmp(id, 'fileList');
nElems = numel(stringValue);
ctrlElemFontSize = min(max(round(ctrlElemFontSize * 1.2 - 0.07 * nElems), 6), 25);
end;
% % extract cell in cell
% if iscell(stringValue) && ~isempty(stringValue) && numel(stringValue) == 1 && iscell(stringValue{1});
% stringValue = stringValue{1};
% end;
% create the GUI element
this.GUI.handles.(modeID).paramPanElems.(id) = uicontrol(UICommons.(UIType){:}, ...
'String', stringValue, 'Value', value, 'Tag', sprintf('%sParam%s', upper(modeID), id), ...
'Position', [ctrlElemX ctrlElemY ctrlElemW ctrlelemHLocal], 'ToolTipString', tooltip, ...
'FontSize', ctrlElemFontSize);
% set a minimum and a maximum
if strcmp(UIType, 'slider');
set(this.GUI.handles.(modeID).paramPanElems.(id), 'Min', valueType{2}, 'Max', valueType{3}, 'SliderStep', ...
[valueType{4}, valueType{5}]);
end;
% pushbuttons should not be presset
if strcmp(UIType, 'button');
set(this.GUI.handles.(modeID).paramPanElems.(id), 'Value', 0);
end;
if ~isempty(callbackFcn);
% pass input arguments
if strcmp(UIType, 'button') && numel(valueType) > 1;
set(this.GUI.handles.(modeID).paramPanElems.(id), 'Callback', @(h, e) callbackFcn(this, valueType{2 : end}));
else
set(this.GUI.handles.(modeID).paramPanElems.(id), 'Callback', @(h, e) callbackFcn(this));
end;
% add a callback for the frame setter
if strcmp(UIType, 'slider');
jObj = findjobj(this.GUI.handles.(modeID).paramPanElems.(id));
set(jObj, 'AdjustmentValueChangedCallback', @(h, e) callbackFcn(this));
end;
end;
% if the controls are outside the visible area, hide them
if iCol > nCols;
set(this.GUI.handles.(modeID).paramPanElems.(id), 'Visible', 'off');
set(this.GUI.handles.(modeID).paramPanElems.([id '_label']), 'Visible', 'off');
% enable the navigating buttons
set(this.GUI.handles.(modeID).nextParams, 'Enable', 'on');
end;
end;
% refresh the GUI
drawnow();
% go through all elements, to update those that need a Java-based update
for iUICtrl = 1 : nUICtrl;
% get the variables of the current control element
rowParams = table2cell(this.GUI.(modeID).paramPanConfig(iUICtrl, :));
[~, id, UIType, valueType, UISize] = rowParams{:};
% if the element is a list and the UISize setting requires some Java-based updating of the uicontrol
if strcmp(UIType, 'list') && UISize(2) > 0;
% launch a timer to update the control
start(timer('StartDelay', 0.15, 'TimerFcn', @(~, ~) javaUpdateUIControl( ...
this.GUI.handles.(modeID).paramPanElems.(id), round(numel(valueType) / UISize(2)))));
end;
end;
% only show the parameter panel if there are some controls to display
set(this.GUI.handles.(modeID).paramPan, 'Visible', iff(nUICtrl > 0, 'on', 'off'));
% change the parameter page
if this.GUI.(modeID).paramPage ~= 1;
% reset to page 1
this.GUI.(modeID).paramPage = 1;
% update the pages
for iPage = 1 : this.GUI.(modeID).paramPage;
OCIACreateParamPanelControls(this, modeID, this.GUI.handles.(modeID).nextParams);
end;
end;
end
% little function to update an uicontrol
function javaUpdateUIControl(handle, nRows)
try
visState = get(handle, 'Visible'); % get visibility state
pos = get(handle, 'Position'); % get position
% make visible
set(handle, 'Position', pos + iff(strcmp(visState, 'off'), [10E5 10E5 0 0], [0 0 0 0]), 'Visible', 'on');
jObj = findjobj(handle);
jListbox = jObj.getViewport().getView();
jListbox.setLayoutOrientation(jListbox.HORIZONTAL_WRAP);
jListbox.setVisibleRowCount(nRows);
set(handle, 'Visible', visState, 'Position', pos);
catch err; %#ok<NASGU>
% Nobody cares if this fails. At least not me >.<
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
DIStartStopCamera.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/DIStartStopCamera.m
| 1,247 |
utf_8
|
72f49cb06536a9aff1927ea2ee8e228b
|
%% #DIStartStopCamera
function DIStartStopCamera(this, commandString)
o('#%s() ...', mfilename, 3, this.verb);
try % capture display errors
if strcmp(commandString, 'toggle') && strcmp(get(this.GUI.di.camHandle, 'Running'), 'on');
commandString = 'stop';
elseif strcmp(commandString, 'toggle') && strcmp(get(this.GUI.di.camHandle, 'Running'), 'off');
commandString = 'start';
end;
if strcmp(commandString, 'start');
% make sure camera is stopped
stop(this.GUI.di.camHandle);
% add disk and memory logging options
set(this.GUI.di.camHandle, 'LoggingMode', 'disk&memory');
if exist(this.path.discrDataSave, 'dir') ~= 7; mkdir(this.path.discrDataSave); end;
videoWriterHandle = VideoWriter(sprintf('%s%s.mp4', this.path.discrDataSave, datestr(now, 'yyyymmdd_HHMMSS')), 'MPEG-4');
this.GUI.di.camHandle.DiskLogger = videoWriterHandle;
% start the recording
start(this.GUI.di.camHandle);
elseif strcmp(commandString, 'stop');
stop(this.GUI.di.camHandle);
end;
catch err;
errStack = getStackText(err);
showWarning(this, 'OCIA:DIStartStopCamera', sprintf('Problem in the Discriminator camera start/stop function: "%s".', err.message));
o(errStack, 0, 0);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
INRunExp_trigInTTLOut.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/INRunExp_trigInTTLOut.m
| 5,723 |
utf_8
|
e2655bca7a3289d93c5abc75499bcb6b
|
function INRunExp_trigInTTLOut(this)
% INRunExp_trigInTTLOut - [no description]
%
% INRunExp_trigInTTLOut(this)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
params = this.in.(this.in.expMode);
if this.in.TTLOutStr.isWorking; return; end;
if ~this.in.expRunning;
exitTriggerMode(this, struct('identifier', 'OCIA:INRunExp_trigInTTLOut:Aborted', ...
'message', 'Error during stimulation ("OCIA:INRunExp_trigInTTLOut:Aborted"): aborted.'));
end;
% showMessage(this, sprintf('%s | Intrinsic: trigger time !', INGetTime(this)));
this.in.TTLOutStr.isWorking = true;
try
this.in.TTLOutStr.trigTime = nowUNIXSec();
iTrial = this.in.TTLOutStr.iTrial;
stimNum = this.in.TTLOutStr.stimVect(iTrial);
stimID = this.in.TTLOutStr.stimNames{iTrial};
if isnumeric(stimID); stimID = sprintf('%d', stimID); end;
showMessage(this, sprintf('%s | Intrinsic: trial %d / %d, current stimulus: %d (%s) ...', ...
INGetTime(this), iTrial, this.in.TTLOutStr.nTrials, stimNum, stimID));
% stimulation depends on current trial type
switch stimID;
case 'auditory';
% % launch stimulus with software trigger
% this.in.RP.SoftTrg(1);
case 'visual';
INSendTTLOutTrigger(this, [5 0], 1, [0.1, 0], this.in.trial.BLDur + this.in.TTLOutStr.fixedTrigDelay);
case 'somatosensory';
INSendTTLOutTrigger(this, [0 2], 2, [0.025, 0.025], this.in.trial.BLDur + this.in.TTLOutStr.fixedTrigDelay);
case 'blank';
% do nothing
otherwise;
% if it is a frequency
if regexp(stimID, '\d+');
% launch stimulus with software trigger
this.in.RP.SoftTrg(1);
else
exitTriggerMode(this, struct('identifier', 'OCIA:INRunExp_trigInTTLOut:UnknownStim', ...
'message', 'Error during stimulation ("OCIA:INRunExp_trigInTTLOut:UnknownStim"): unknown stimulus.'));
end;
end;
this.in.TTLOutStr.iTrial = this.in.TTLOutStr.iTrial + 1;
isMultiSensory = numel(params.stimIDs) == 4 ...
&& all(strcmp(params.stimIDs, { 'auditory', 'visual', 'somatosensory', 'blank' }));
% if number of trials is reached
if this.in.TTLOutStr.iTrial > this.in.TTLOutStr.nTrials;
pauseTicToc(1);
exitTriggerMode(this, []);
return;
% multi-sensory
elseif isMultiSensory;
% wait and prepare next stimulus
pause(1.1 * (this.in.trial.BLDur + this.in.trial.triStimDur));
iNextTrial = this.in.TTLOutStr.iTrial;
stimNumNextTrial = this.in.TTLOutStr.stimVect(iNextTrial);
stimIDNextTrial = this.in.TTLOutStr.stimNames{iNextTrial};
if isnumeric(stimIDNextTrial); stimIDNextTrial = sprintf('%d', stimIDNextTrial); end;
% next stim is auditory
if strcmp(stimIDNextTrial, 'auditory');
showMessage(this, sprintf('%s | Intrinsic: preparing next trial as auditory %d / %d, %d (%s) ...', ...
INGetTime(this), iNextTrial, this.in.TTLOutStr.nTrials, stimNumNextTrial, stimIDNextTrial));
% load sound stimulus
this.in.RP = playTDTSound(this.in.TTLOutStr.soundsToPlay .* this.in.TTLOutStr.amplif, 0, this.GUI.figH, 0);
else
showMessage(this, sprintf('%s | Intrinsic: preparing next trial as no-sound %d / %d, %d (%s) ...', ...
INGetTime(this), iNextTrial, this.in.TTLOutStr.nTrials, stimNumNextTrial, stimIDNextTrial));
% load empty stimulus
this.in.RP = playTDTSound([0 0], 0, this.GUI.figH, 0);
end;
% if not in multi-sensory mode
elseif ~isMultiSensory;
% wait and prepare next stimulus
pause(1.1 * (this.in.trial.BLDur + this.in.trial.triStimDur));
iNextTrial = this.in.TTLOutStr.iTrial;
stimNumNextTrial = this.in.TTLOutStr.stimVect(iNextTrial);
stimIDNextTrial = this.in.TTLOutStr.stimNames{iNextTrial};
if isnumeric(stimIDNextTrial); stimIDNextTrial = sprintf('%d', stimIDNextTrial); end;
showMessage(this, sprintf('%s | Intrinsic: preparing next trial with freq %d / %d, %d (%s) ...', ...
INGetTime(this), iNextTrial, this.in.TTLOutStr.nTrials, stimNumNextTrial, stimIDNextTrial));
% prepare next stimulus
currentSoundToPlay = this.in.TTLOutStr.soundsToPlay(this.in.TTLOutStr.stimVect(this.in.TTLOutStr.iTrial), :);
this.in.RP = playTDTSound(currentSoundToPlay .* this.in.TTLOutStr.amplif, 0, this.GUI.figH, 0);
end;
% if something failed
catch err;
exitTriggerMode(this, err);
end;
this.in.TTLOutStr.isWorking = false;
end
function exitTriggerMode(this, err)
warning('off', 'MATLAB:callback:error');
% stop data aquisition
stop(this.in.daq.sessHandle{1});
% stop timer
if isfield(this.in.TTLOutStr, 'timer');
stop(this.in.TTLOutStr.timer);
end;
this.in.TTLOutStr.isWorking = false;
if ~isempty(err);
showWarning(this, 'OCIA:INRunExp_trigInTTLOut:StimFailed', ...
sprintf('Error during stimulation ("%s"): %s.', err.identifier, err.message));
end;
% release resources
INCleanUp(this);
% set flags, update counter and update GUI
this.in.expRunning = false;
set(this.GUI.handles.in.runExpBut, 'BackgroundColor', 'red', 'Value', 0);
if isempty(err);
showMessage(this, sprintf('%s | Intrinsic: finished.', INGetTime(this)));
else
showMessage(this, sprintf('%s | Intrinsic: aborted.', INGetTime(this)));
end;
warning('on', 'MATLAB:callback:error');
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
BERunTrial.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/BERunTrial.m
| 41,549 |
utf_8
|
0645e93632a4428e9495406823adfe13
|
function BERunTrial(this)
% BERunTrial - [no description]
%
% BERunTrial(this)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% /!\ NOTE: all times are in seconds (with decimals though) since trial start or trial init
% init some variables
trainConf = this.be.config.training;
toneConf = this.be.config.tone;
params = this.be.params;
BETimes = this.be.times;
iTrial = this.be.iTrial;
tPhase = this.be.trialPhase;
nTrials = this.be.config.training.nTrials;
% check if experiment is paused/stopped
if ~this.be.isRunning;
return;
end;
%% PHASE SWITCH
% what we have to do depends on which phase of the trial we are
switch tPhase;
%% initialize trial
% this is not the start of the trial yet
case 'init';
% clear previous data
BEClearData(this);
% get init time
BETimes.init(iTrial) = roundn(nowUNIXSec(), -3);
o('Times:init: %.3f', BETimes.init(iTrial), 2, this.verb);
o('==================================================================', 1, this.verb);
showMessage(this, sprintf('%s | Trial %03d/%03d - start ... ', datestr(now(), this.be.logDateFormat), ...
iTrial, trainConf.nTrials), 'yellow');
o('%s | start ...', datestr(now(), this.be.logDateFormat), 2, this.verb);
% move to next phase
this.be.trialPhase = 'moveSpot';
%% move spots
case 'moveSpot';
o('%s | moveSpot ...', datestr(now(), this.be.logDateFormat), 2, this.verb);
% if spot matrix is not empty, move spots
if isfield(this.be, 'spotMatrix') && ~isempty(this.be.spotMatrix);
% get the current spot for this trial
currentSpot = this.be.spotMatrix(iTrial);
% record time
BETimes.ETLTrigStart(iTrial) = getTSinceInit();
o('Times:ETLTrigStart: %.3f', BETimes.ETLTrigStart(iTrial), 3, this.verb);
% select right spot and move there
BEETLTableAction(this, [], [], 'select', currentSpot);
BEETLTableAction(this, [], [], 'go');
% record time
BETimes.ETLTrigEnd(iTrial) = getTSinceInit();
o('Times:ETLTrigEnd: %.3f', BETimes.ETLTrigEnd(iTrial), 3, this.verb);
end;
% move to next phase
this.be.trialPhase = 'vidRec';
%% start video recording
case 'vidRec';
o('%s | vidRec ...', datestr(now(), this.be.logDateFormat), 2, this.verb);
% if video recording is enabled
if isfield(this.GUI.handles.be, 'vidRecEnableOn') && get(this.GUI.handles.be.vidRecEnableOn, 'Value') ...
&& (~isempty(regexp(this.be.phase, '^(LWP|QW)', 'once')) && iTrial == 1);
% triggering not done yet
if isnan(BETimes.vidStartTCPTrig(iTrial));
showMessage(this, sprintf('%s | Trial %03d/%03d - video start trigger ... ', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');
% record trigger time
BETimes.vidStartTCPTrig(iTrial) = getTSinceInit();
o('Times:vidStartTCPTrig: %.3f', BETimes.vidStartTCPTrig(iTrial), 3, this.verb);
% send trigger and message for the behavior movie recording on the remote computer using a timer
dateString = datestr(now, 'yyyy_mm_dd');
trialName = sprintf('%s_%s_trial%02d.avi', regexprep(dateString, '_', ''), ...
datestr(now, 'HHMMSS'), iTrial);
set(this.GUI.be.vidTrigTimer, 'UserData', trialName);
start(this.GUI.be.vidTrigTimer);
% triggering done and wait time finished
elseif getTSinceInit() > BETimes.vidStartTCPTrig(iTrial) + params.vidRecDelay(1);
% move to next phase
this.be.trialPhase = 'loadSound';
% trigger sent but wait time not yet finished
else
o('#%s(): waiting for video start trigger ...', mfilename(), 3, this.verb);
end;
% no video triggering
else
% move to next phase
this.be.trialPhase = 'loadSound';
end;
%% load sound
case 'loadSound';
o('%s | loadSound ...', datestr(now(), this.be.logDateFormat), 2, this.verb);
showMessage(this, sprintf('%s | Trial %03d/%03d - loading sound ... ', datestr(now(), this.be.logDateFormat), ...
iTrial, trainConf.nTrials), 'yellow');
% load sound into the TDT if required
if this.be.useTDT;
TDTLoadTic = tic;
BETimes.soundLoadStart(iTrial) = getTSinceInit();
% attenuation = randi(4, 1) - 1; % randomized 0 - 3 dB SPL attenuation
attenuation = 0;
this.be.TDTRP = playTDTSound(this.be.toneArray{iTrial}, attenuation, this.GUI.figH, 1);
BETimes.soundLoadEnd(iTrial) = getTSinceInit();
o('#%s(): TDT loaded, attenuation: %d dB SPL (%.3f)', mfilename(), attenuation, toc(TDTLoadTic), ...
2, this.verb);
% showMessage(this, sprintf('%s | Trial %03d/%03d - TDT loaded ... ', ...
% datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');
% initialize a standard audio player
else
BETimes.soundLoadStart(iTrial) = getTSinceInit();
this.be.audioplayer = audioplayer(this.be.toneArray{iTrial}, toneConf.samplingFreq);
BETimes.soundLoadEnd(iTrial) = getTSinceInit();
o('#%s(): normal audioplayer loaded', mfilename(), 2, this.verb);
end;
% move to next phase
this.be.trialPhase = 'start';
%% start the trial (random start delay)
case 'start';
% random start delay waiting not started yet
if isnan(BETimes.startDelay(iTrial));
% calculate a random delay for starting the sounds
randomStartDelay = trainConf.startDelay + (rand - 0.5) * 2 * trainConf.startDelayRand;
BETimes.startDelay(iTrial) = randomStartDelay;
o('Times:startDelay: %.3f', BETimes.startDelay(iTrial), 3, this.verb);
showMessage(this, sprintf('%s | Trial %03d/%03d - start delay: %.3f sec. ', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, BETimes.startDelay(iTrial)), ...
'yellow');
% mark trial as started
BETimes.start(iTrial) = BETimes.init(iTrial) + size(this.be.anInData.piezo, 1) / this.be.hw.anInSampRate;
o('Times:start: %.3f', BETimes.start(iTrial), 2, this.verb);
% start the imaging before the random start delay
BEImagingTTL(this, 1);
BETimes.imgStart(iTrial) = getTSinceStart();
o('Times:imgStart: %.3f', BETimes.imgStart(iTrial), 2, this.verb);
% random start delay not finished and one second since imaging start
elseif getTSinceStart() <= BETimes.startDelay(iTrial) && isnan(BETimes.trialStartCue(iTrial)) ...
&& getTSinceStart() > BETimes.imgStart(iTrial) + 1;
BETimes.trialStartCue(iTrial) = getTSinceStart();
% trial start cue
o('#%s(): trial start cue at %.3f ...', mfilename(), getTSinceStart(), 2, this.verb);
pulseParams = num2cell(trainConf.trialStartLightCueParams);
BELightPulse(this, pulseParams{:});
% random start delay waiting finished
elseif getTSinceStart() > BETimes.startDelay(iTrial);
% move to next phase
this.be.trialPhase = 'playSound';
% trigger sent but wait time not yet finished
else
o('#%s(): waiting for start delay ...', mfilename(), 3, this.verb);
end;
%% play sound
case 'playSound';
% play sound using TDT
if this.be.useTDT;
this.be.TDTRP.SoftTrg(1);
BETimes.sound(iTrial) = getTSinceStart();
o('Times:sound: %.3f', BETimes.sound(iTrial), 2, this.verb);
% play sound without TDT
else
% play sound using standard audio player
this.be.audioplayer.play();
BETimes.sound(iTrial) = getTSinceStart();
o('Times:sound: %.3f', BETimes.sound(iTrial), 2, this.verb);
end;
% move to next phase
this.be.trialPhase = 'initWaitResp';
%% initialize waiting response period
case 'initWaitResp';
% waiting starts now
BETimes.respWaitStart(iTrial) = getTSinceStart();
% random delay for the minimum response time (response window start)
randomRespMinDelay = (rand - 0.5) * 2 * trainConf.minRespRand;
o('randomRespMinDelay: %.3f', randomRespMinDelay, 3, this.verb);
showMessage(this, sprintf('%s | Trial %03d/%03d - resp. window delay: %.3f sec (%.3f + %.3f).', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, trainConf.minRespTime ...
+ randomRespMinDelay, trainConf.minRespTime, randomRespMinDelay), 'yellow');
% init the minimum (start) and maximum (end) times for the response window
BETimes.respMin(iTrial) = BETimes.respWaitStart(iTrial) + trainConf.minRespTime + randomRespMinDelay;
BETimes.respMax(iTrial) = BETimes.respWaitStart(iTrial) + trainConf.maxRespTime + randomRespMinDelay;
% initialize the time for the light cue to start and stop
BETimes.lightIn(iTrial) = BETimes.respWaitStart(iTrial) + trainConf.lightInTime + randomRespMinDelay;
BETimes.lightOut(iTrial) = BETimes.lightIn(iTrial) + trainConf.lightDur;
% print out all this stuff
o('Times:respWaitStart: %.3f', BETimes.respWaitStart(iTrial), 2, this.verb);
o('Times:respMin: %.3f', BETimes.respMin(iTrial), 2, this.verb);
o('Times:lightIn: %.3f', BETimes.lightIn(iTrial), 3, this.verb);
o('Times:lightOut: %.3f', BETimes.lightIn(iTrial), 3, this.verb);
o('Times:respMax: %.3f', BETimes.respMax(iTrial), 3, this.verb);
% display message appropriate message depending on whether the animal has actually to respond or not:
% presence of a GO stimulus means a response is expected
if ~isempty(toneConf.goStim);
showMessage(this, sprintf('%s | Trial %03d/%03d - waiting for response ... ', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');
% do not set a time to wait for the sound to finish
BETimes.soundDur(iTrial) = 0;
% no go stim means response is not expected
else
% calculate sound duration in seconds using number of samples and sampling frequency of the TDT
soundDur = numel(this.be.toneArray{iTrial}) / toneConf.samplingFreq;
showMessage(this, sprintf('%s | Trial %03d/%03d - playing sound (%.2f sec duration) ... ', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, soundDur), 'yellow');
% set a time to wait for the sound to finish
BETimes.soundDur(iTrial) = soundDur;
end;
o('Times:soundDur: %.3f', BETimes.soundDur(iTrial), 3, this.verb);
o('Times:sound+soundDur: %.3f', BETimes.sound(iTrial) + BETimes.soundDur(iTrial), 3, this.verb);
% move to next phase
this.be.trialPhase = 'waitResp';
%% wait for response
case 'waitResp';
% if this is the first time we are waiting for response
if isnan(BETimes.respWaitRealStart(iTrial));
% real waiting starts now
BETimes.respWaitRealStart(iTrial) = getTSinceStart();
% init some variables for this trial
this.be.lightCueGiven(iTrial) = 0;
this.be.autoRewardGiven(iTrial) = 0;
this.be.autoRewardModes{iTrial} = params.autoRewardMode;
% check if auto-reward should be given because of misses
if isfield(trainConf, 'NMissToGiveAutoRewardAfter') && ~isinf(trainConf.NMissToGiveAutoRewardAfter);
lastHit = find(this.be.respTypes == 1, 1, 'last');
if isempty(lastHit);
lastHit = 1;
end;
nMisses = numel(this.be.respTypes((lastHit + 1) : (iTrial - 1)) == 4);
if nMisses >= trainConf.NMissToGiveAutoRewardAfter;
showMessage(this, sprintf(...
'%s | Trial %03d/%03d - auto-reward because of %d miss ...', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, nMisses), 'yellow');
this.be.autoRewardModes{iTrial} = 'EarlyOn';
end;
end;
% determine whether earlies are allowed or not
if trainConf.allowEarlyLicks >= 1;
this.be.earlyAllowed(iTrial) = 1;
showMessage(this, sprintf('%s | Trial %03d/%03d - earlies allowed by config.', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');
elseif trainConf.allowEarlyLicks <= 0;
this.be.earlyAllowed(iTrial) = 0;
showMessage(this, sprintf('%s | Trial %03d/%03d - earlies *not* allowed by config.', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');
% probabilistic
else
randNum = rand();
this.be.earlyAllowed(iTrial) = randNum <= trainConf.allowEarlyLicks;
showMessage(this, sprintf( ...
'%s | Trial %03d/%03d - earlies given by probability of %.2f: rand = %.2f => %sallowed.', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, ...
trainConf.allowEarlyLicks, randNum, iff(this.be.earlyAllowed(iTrial), '', '*not* ')), 'yellow');
end;
end;
% if we are still within the waiting window
if getTSinceStart() < (BETimes.respMax(iTrial) + BETimes.soundDur(iTrial));
o('#%s: response waiting loop ... %.3f', mfilename(), getTSinceStart(), 4, this.verb);
%% - wait for response: light on
% only give reward cue if there is a reward, if light cue has not yet been given and "lightIn" is passed
if params.rewDur > 0 && isnan(BETimes.lightCueOn(iTrial)) && getTSinceStart() > BETimes.lightIn(iTrial);
% if light is not yet on, turn it on
if isnan(BETimes.lightCueOn(iTrial));
BETimes.lightCueOn(iTrial) = getTSinceStart();
this.be.lightCueGiven(iTrial) = 1;
o('#%s(): light cue on (%.3f) ...', mfilename(), BETimes.lightCueOn(iTrial), 3, this.verb);
pulseParams = num2cell(trainConf.rewardPeriodLightCueParams);
BELightPulse(this, pulseParams{:});
% light cue on but light must still be on
else
o('#%s(): lightCueOn: %d, tDiff: %.3f, timeSinceStart: %.3f ...', mfilename(), lightCueOn, ...
(BETimes.lightCueOn(iTrial) + lightOnDur) - getTSinceStart(), ...
getTSinceStart(), 2, this.verb);
end;
end;
%% - wait for response: light off
% turn light off if needed
if ~isnan(BETimes.lightCueOn(iTrial)) && isnan(BETimes.lightCueOff(iTrial)) && getTSinceStart() > BETimes.lightOut(iTrial);
BELight(this, 0);
BETimes.lightCueOff(iTrial) = getTSinceStart();
o('#%s(): light cue off (%.3f) ...', mfilename(), BETimes.lightCueOff(iTrial), 3, this.verb);
end;
%% - wait for response: 'EarlyOn' reward
% in 'EarlyOn' mode, reward happens at some fraction of time of the response window
respWindowDur = BETimes.respMax(iTrial) - BETimes.respMin(iTrial);
EORespTime = BETimes.respMin(iTrial) + params.autoRewardEarlyOnTimeFraction * respWindowDur;
isEarlyOn = strcmp(this.be.autoRewardModes{iTrial}, 'EarlyOn') && (isempty(toneConf.goStim) ...
|| ismember(this.be.stims(iTrial), toneConf.goStim));
% if 'EarlyOn' mode is on and reward has not yet been given and 'EarlyOn' time is passed and trial is target
if params.rewDur > 0 && isEarlyOn && ~this.be.autoRewardGiven(iTrial) && getTSinceStart() > EORespTime;
this.be.autoRewardGiven(iTrial) = 1;
BETimes.rewTime(iTrial) = getTSinceStart();
o('Times:rewTime: %.3f', BETimes.rewTime(iTrial), 3, this.verb);
BEGiveReward(this);
this.be.giveRewards(iTrial) = 1;
showMessage(this, sprintf('%s | Trial %03d/%03d - ''EarlyOn'' reward !', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');
% calc reward collection time
BETimes.rewCollStart(iTrial) = BETimes.rewTime(iTrial);
o('Times:rewCollStart: %.3f', BETimes.rewCollStart(iTrial), 3, this.verb);
BETimes.rewCollEnd(iTrial) = BETimes.rewTime(iTrial) + trainConf.rewCollTime;
o('Times:rewCollEnd: %.3f', BETimes.rewCollEnd(iTrial), 3, this.verb);
end;
%% - wait for response: sound detection
% only search for sound if not already found and if required
if isnan(BETimes.realSound(iTrial)) && this.be.params.adjustForDelayWithSound;
% get microphone data
micr = linScale(abs(this.be.anInData.micr))';
% get the number of samples
nSamples = size(micr, 2);
% get a range for the begining of the signal
begRange = round(nSamples * 0.01 : nSamples * 0.1);
% get thresholds factor
soundThreshFactor = 30;
% get a threshold for the sound onset
soundYThresh = soundThreshFactor * std(micr(begRange));
% get the samples that exceeds the threshold, adding the first sample to catch the
% start of the first sound
upSamples = [0 find(micr > soundYThresh)];
% get the derivative of the upSamples, drops in the sample indexes indicate interruption of upSamples,
% which means that there is a sound start
upSamplesDiff = diff(upSamples);
% use the ISI to find peaks. If no ISI, use 0.5 second
ISI = 0.5;
% difference between detected upSample derivative's peaks must be at least half of the ISI
minISI = ISI * 0.5 * this.be.hw.anInSampRate;
% get the index of the peaks where the derivative exceeds the ISI threshold and increment
% by one to get the sound start index
soundStartIndex = upSamples(find(upSamplesDiff >= minISI) + 1);
%{
% debug plot
plot((1 : nSamples) / this.be.hw.anInSampRate, micr, 'Color', 'green');
xLims = get(gca, 'XLim');
hold on;
plot(xLims, repmat(soundYThresh, 1, 2), 'Color', 'red', 'LineStyle', ':');
title(sprintf('soundYThresh: %.6f, soundStartIndex: %d\nsoundStartTime: %.2f', soundYThresh, ...
soundStartIndex, soundStartIndex / this.be.hw.anInSampRate));
hold off;
%}
% if some start index found
if ~isempty(soundStartIndex);
% only keep the first sound start
if numel(soundStartIndex > 1); soundStartIndex = soundStartIndex(1); end;
% get the sound start time
BETimes.realSound(iTrial) = (soundStartIndex / this.be.hw.anInSampRate) ...
- getTSinceInit() + getTSinceStart();
o('Times:realSound: %.3f sec ', BETimes.realSound(iTrial), 3, this.verb);
% calculate delay with actual sound
manualOffset = 0.15;
BETimes.soundDelay(iTrial) = BETimes.realSound(iTrial) - BETimes.sound(iTrial) - manualOffset;
o('Times:soundDelay: %.3f sec ', BETimes.soundDelay(iTrial), 3, this.verb);
showMessage(this, sprintf('%s | Trial %03d/%03d - soundDelay: %.3f sec. ', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials, ...
BETimes.soundDelay(iTrial)), 'yellow');
% remove delay data
BEClearData(this, round(BETimes.soundDelay(iTrial) * this.be.hw.anInSampRate));
end;
end;
%% - wait for response: response detection
% no response by default
this.be.resps(iTrial) = 0;
if ~isempty(toneConf.goStim);
% get the number of samples that we have
if isfield(this.be.anInData, 'piezo')
nSamples = size(this.be.procAnInData.piezo, 1);
else
nSamples = 0;
end;
% calculate the number of samples between init and start
nSamplesOffset = round((BETimes.start(iTrial) - BETimes.init(iTrial)) * this.be.hw.anInSampRate);
% get the indexes of the samples that are within the response window
startEarlyRespIndex = round((BETimes.respWaitStart(iTrial)) * this.be.hw.anInSampRate) + nSamplesOffset;
startRespIndex = round(BETimes.respMin(iTrial) * this.be.hw.anInSampRate) + nSamplesOffset;
endRespIndex = min(round(BETimes.respMax(iTrial) * this.be.hw.anInSampRate) + nSamplesOffset, nSamples);
% only check for responses if we have enought samples
if startEarlyRespIndex <= nSamples;
% earlies not allowed and detection *before* response time
if ~this.be.earlyAllowed(iTrial) && getTSinceStart() < BETimes.respMin(iTrial);
% get the piezo lick sensor data
piezoData = this.be.procAnInData.piezo;
% response is true if any value is above the threshold
this.be.resps(iTrial) = sum(piezoData(startEarlyRespIndex : end) > params.piezoThresh) >= 1;
% if lick detected, mark it as early
if this.be.resps(iTrial);
this.be.respTypes(iTrial) = 5;
end;
% earlies allowed or not and detection is *after* response time
elseif getTSinceStart() >= BETimes.respMin(iTrial);
% get the piezo lick sensor data
piezoData = this.be.procAnInData.piezo;
% response is true if any value is above the threshold
this.be.resps(iTrial) = sum(piezoData(startRespIndex : endRespIndex) > params.piezoThresh) >= 1;
% no response detected yet
else
this.be.resps(iTrial) = 0;
end;
% % plot things for debug purposes
% if any(piezoData > params.piezoThresh);
% this.be.isRunning = 0;
% stop(this.GUI.be.updateTimer);
% figure();
% t = (1 : nSamples) / this.be.hw.anInSampRate;
% plot(t, linScale(piezoData));
% hold on;
% line([startEarlyRespIndex, startEarlyRespIndex] / this.be.hw.anInSampRate, [0 1], 'Color', 'r');
% line([startRespIndex, startRespIndex] / this.be.hw.anInSampRate, [0 1], 'Color', 'g');
% line([endRespIndex, endRespIndex] / this.be.hw.anInSampRate, [0 1], 'Color', 'm');
% o('plot done', 0, 0);
% end;
% if not enought sample yet, no response can be detected
else
this.be.resps(iTrial) = 0;
end;
% if there was a response within the response window
if this.be.resps(iTrial);
% mark down response time and delay compared to response window start
BETimes.respTime(iTrial) = getTSinceStart(); % artifical delay correction
o('Times:resp: %.3f', BETimes.respTime(iTrial), 3, this.verb);
this.be.respDelays(iTrial) = BETimes.respTime(iTrial) - BETimes.respMin(iTrial);
o('Times:respDelays: %.3f', this.be.respDelays(iTrial), 3, this.verb);
if this.be.respTypes(iTrial) == 5;
lickType = 'EARLY';
% if not 'EarlyOn' mode or the auto-reward has not been given yet, it is a "true" lick
elseif ~isEarlyOn || ~this.be.autoRewardGiven(iTrial);
lickType = 'LICK';
% if in 'EarlyOn' mode and the auto-reward has been given, it is a "induced" (post-reward) lick
else
lickType = 'INDUCED LICK';
end;
% show the message with the lick type and the delay
showMessage(this, sprintf('%s | Trial %03d/%03d - %s! (%.3f sec)', datestr(now(), ...
this.be.logDateFormat), iTrial, nTrials, lickType, this.be.respDelays(iTrial)), 'yellow');
% move to next phase
this.be.trialPhase = 'processDecision';
end;
end;
% if we are not anymore in the waiting window
else
o('#%s(): end of response wait ... (%.3f)', mfilename(), getTSinceStart(), 3, this.verb);
% move to next phase
this.be.trialPhase = 'processDecision';
end;
%% process the decision
case 'processDecision';
% if it was turned on and not yet off, make sure light is off
if ~isnan(BETimes.lightCueOn(iTrial)) && isnan(BETimes.lightCueOff(iTrial)) ...
&& getTSinceStart() > BETimes.lightOut(iTrial);
BELight(this, 0);
BETimes.lightCueOff(iTrial) = getTSinceStart();
o('#%s(): light cue off (late) (%.3f) ...', mfilename(), BETimes.lightCueOff(iTrial), 2, this.verb);
end;
% if no response set yet, then set it to 0 (no response)
if isnan(this.be.resps(iTrial)); this.be.resps(iTrial) = 0; end;
% if goStim is empty, it means no behavior decision had to be made (no response)
if ~isempty(toneConf.goStim);
% get whether this is the target stimulus
isTargetStim = ismember(this.be.stims(iTrial), toneConf.goStim);
% only create a response type if it is not already set to "early"
if this.be.respTypes(iTrial) == 5;
% set outcome variables
this.be.punishTimeOuts(iTrial) = 1;
this.be.giveRewards(iTrial) = 0;
% response and it was a target: hit (correct response) (respType = 1)
elseif this.be.resps(iTrial) && isTargetStim;
showMessage(this, sprintf('%s | Trial %03d/%03d - HIT! (%.3f sec)', datestr(now(), ...
this.be.logDateFormat), iTrial, nTrials, this.be.respDelays(iTrial)), 'green');
% set outcome variables
this.be.respTypes(iTrial) = 1;
this.be.punishTimeOuts(iTrial) = 0;
this.be.giveRewards(iTrial) = 1;
% NO response and it was NOT a target: correct rejection (respType = 2)
elseif ~this.be.resps(iTrial) && ~isTargetStim;
showMessage(this, sprintf('%s | Trial %03d/%03d - CORRECT REJECT!', ...
datestr(now(), this.be.logDateFormat), iTrial, nTrials), 'green');
% set outcome variables
this.be.respTypes(iTrial) = 2;
this.be.punishTimeOuts(iTrial) = 0;
this.be.giveRewards(iTrial) = 0;
% response and it was NOT a target: false alarm (respType = 3)
elseif this.be.resps(iTrial) && ~isTargetStim;
showMessage(this, sprintf('%s | Trial %03d/%03d - FALSE ALARM! (%.3f sec)', ...
datestr(now(), this.be.logDateFormat), iTrial, nTrials, ...
this.be.respDelays(iTrial)), 'red');
% set outcome variables
this.be.respTypes(iTrial) = 3;
this.be.punishTimeOuts(iTrial) = 1;
this.be.giveRewards(iTrial) = 0;
% NO response and it was a target: miss (respType = 4)
elseif ~this.be.resps(iTrial) && isTargetStim;
showMessage(this, sprintf('%s | Trial %03d/%03d - MISS!', ...
datestr(now(), this.be.logDateFormat), iTrial, nTrials), 'red');
% set outcome variables
this.be.respTypes(iTrial) = 4;
this.be.punishTimeOuts(iTrial) = 0;
this.be.giveRewards(iTrial) = 0;
end;
% process the auto-reward modes for reward outcomes
switch this.be.autoRewardModes{iTrial};
% give reward only if target stim (or no targets) AND not early lick
case 'EarlyOn'; this.be.giveRewards(iTrial) ...
= (isempty(toneConf.goStim) || ismember(this.be.stims(iTrial), toneConf.goStim)) ...
&& this.be.respTypes(iTrial) ~= 5;
% give reward only if target stim (or no targets)
case 'On'; this.be.giveRewards(iTrial) ...
= (isempty(toneConf.goStim) || ismember(this.be.stims(iTrial), toneConf.goStim)) ...
&& this.be.respTypes(iTrial) ~= 5;
% never give reward
case 'Off'; this.be.giveRewards(iTrial) = 0;
% do nothing, rewarding depends on mouse's response
case 'Auto';
otherwise;
showWarning(this, 'OCIA:RunTrial:UnknownAutoRewardMode', ...
sprintf('Unknown auto-reward mode: %s. Using default "auto" (reward: %d).', ...
this.be.autoRewardModes{iTrial}, this.be.giveReards(iTrial)));
end;
% move to next phase
this.be.trialPhase = 'reward';
% no behavior decision (no response), skip to final wait time
else
% move to next phase
this.be.trialPhase = 'finalWait';
end;
%% reward
case 'reward';
if ~this.be.giveRewards(iTrial);
% move to next phase
this.be.trialPhase = 'finalWait';
% if reward was not already given for this phase
elseif isnan(BETimes.rewCollStart(iTrial)) && this.be.giveRewards(iTrial);
% only give reward if deserved and if not already given by auto-reward
if this.be.giveRewards(iTrial) && ~this.be.autoRewardGiven(iTrial) && isnan(BETimes.rewTime(iTrial));
BETimes.rewTime(iTrial) = getTSinceStart();
o('Times:rewTime: %.3f', BETimes.rewTime(iTrial), 3, this.verb);
showMessage(this, sprintf('%s | Trial %03d/%03d - reward !', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');
BEGiveReward(this);
end;
% give time to collect it
BETimes.rewCollStart(iTrial) = BETimes.rewTime(iTrial);
o('Times:rewCollStart: %.3f', BETimes.rewCollStart(iTrial), 3, this.verb);
BETimes.rewCollEnd(iTrial) = BETimes.rewTime(iTrial) + trainConf.rewCollTime;
o('Times:rewCollEnd: %.3f', BETimes.rewCollEnd(iTrial), 3, this.verb);
% prolongate light until the end of the collection period if needed
BETimes.lightOut(iTrial) = max(BETimes.rewCollEnd(iTrial), BETimes.lightOut(iTrial));
o('Times:lightOut: %.3f (prolongated (2))', BETimes.lightOut(iTrial), 3, this.verb);
% if reward was already given for this phase and reward collection is done but spout is still in
elseif ~isnan(BETimes.rewCollStart(iTrial)) && this.be.giveRewards(iTrial) ...
&& getTSinceStart() > BETimes.rewCollEnd(iTrial) && isnan(BETimes.spoutOut(iTrial));
% calculate spout out time
BETimes.spoutOut(iTrial) = getTSinceStart() + params.spoutDelay(2);
% if reward was already given for this phase and reward collection is done and spout should be out
elseif ~isnan(BETimes.rewCollStart(iTrial)) && this.be.giveRewards(iTrial) ...
&& getTSinceStart() > BETimes.rewCollEnd(iTrial) && ~isnan(BETimes.spoutOut(iTrial)) ;
% remove spout
% BESpoutPos(this, 0);
% move to next phase
this.be.trialPhase = 'finalWait';
% spout time not yet defined means it is still reward collection
elseif isnan(BETimes.spoutOut(iTrial));
o('#%s(): waiting for reward collection ...', mfilename(), 3, this.verb);
% spout time defined means it is still spout delay wait
else
o('#%s(): waiting for spout delay ...', 3, this.verb);
end;
% if it was turned on and not yet off, make sure light is off
if ~isnan(BETimes.lightCueOn(iTrial)) && isnan(BETimes.lightCueOff(iTrial)) ...
&& getTSinceStart() > BETimes.lightOut(iTrial);
BELight(this, 0);
BETimes.lightCueOff(iTrial) = getTSinceStart();
o('#%s(): light cue off (late (2)) (%.3f) ...', mfilename(), BETimes.lightCueOff(iTrial), 2, this.verb);
end;
%% final end wait (punishment & others)
case 'finalWait';
% no punishmend time yet
if isnan(BETimes.endPunish(iTrial));
% if no punish setting is not set yet, set it to 0 (no punish)
if isnan(this.be.punishTimeOuts(iTrial)); this.be.punishTimeOuts(iTrial) = 0; end;
% calculate the punishment delay
punishDelay = iff(this.be.punishTimeOuts(iTrial), trainConf.timeoutPunish, 0);
% play punishment sound
if punishDelay > 0;
o('Playing punishment sound ...', 3, this.verb);
nLoops = round(min(trainConf.endDelay + punishDelay, 3) / 0.5);
this.be.TDTRP.Halt();
this.be.TDTRP = playTDTSound(this.be.punishSound, 0, this.GUI.figH, nLoops);
this.be.TDTRP.SoftTrg(1);
end;
% calculate the end of punishment time
BETimes.endPunish(iTrial) = getTSinceStart() + trainConf.endDelay + punishDelay;
o('Times:endPunish: %.3f', BETimes.endPunish(iTrial), 3, this.verb);
% calculate the expected end of the imaging
BETimes.imgStopExp(iTrial) = BETimes.endPunish(iTrial) - punishDelay - params.imgEndStopTime;
o('Times:imgStopExp: %.3f', BETimes.imgStopExp(iTrial), 3, this.verb);
end;
% set a minimum trial duration
minTrialDuration = 13;
if (getTSinceStart() - BETimes.imgStopExp(iTrial)) < minTrialDuration;
BETimes.imgStopExp(iTrial) = minTrialDuration;
end;
% if imaging still runing and time to stop it has passed
if getTSinceStart() > BETimes.imgStopExp(iTrial);
% stop imaging
if isnan(BETimes.imgStopObs(iTrial));
% stop imaging
BEImagingTTL(this, 0);
BETimes.imgStopObs(iTrial) = getTSinceStart();
o('Times:imgStopObs: %.3f', BETimes.imgStopObs(iTrial), 3, this.verb);
end;
% if time to finish trial has passed
if getTSinceStart() > BETimes.endPunish(iTrial);
showMessage(this, sprintf('%s | Trial %03d/%03d - done. ', datestr(now(), this.be.logDateFormat), ...
iTrial, trainConf.nTrials), 'green');
% move out from the trial running
this.be.trialPhase = 'stopVidRec';
% trial still runing but stop time is not yet arrived
else
o('#%s(): waiting for trial stop ...', mfilename(), 4, this.verb);
end;
% imaging is still runing but stop time is not yet arrived
else
o('#%s(): waiting for imaging stop ...', mfilename(), 4, this.verb);
end;
% if it was turned on and not yet off, make sure light is off
if ~isnan(BETimes.lightCueOn(iTrial)) && isnan(BETimes.lightCueOff(iTrial)) ...
&& getTSinceStart() > BETimes.lightOut(iTrial);
BELight(this, 0);
BETimes.lightCueOff(iTrial) = getTSinceStart();
o('#%s(): light cue off (late (3)) (%.3f) ...', mfilename(), BETimes.lightCueOff(iTrial), 2, this.verb);
end;
%% stop video recording
case 'stopVidRec';
% if video recording is enabled
if isfield(this.GUI.handles.be, 'vidRecEnableOn') && get(this.GUI.handles.be.vidRecEnableOn, 'Value') ...
&& (~isempty(regexp(this.be.phase, '^(LWP|QW)', 'once')) && iTrial == trainConf.nTrials);
% triggering not done yet
if isnan(BETimes.vidEndTCPTrig(iTrial));
showMessage(this, sprintf('%s | Trial %03d/%03d - video stop trigger ... ', ...
datestr(now(), this.be.logDateFormat), iTrial, trainConf.nTrials), 'yellow');
% record trigger time
BETimes.vidEndTCPTrig(iTrial) = getTSinceStart();
o('Times:vidEndTCPTrig: %.3f', BETimes.vidEndTCPTrig(iTrial), 3, this.verb);
% send trigger to stop the behavior movie recording using a timer
set(this.GUI.be.vidTrigTimer, 'UserData', 'stop');
start(this.GUI.be.vidTrigTimer);
% triggering done and wait time finished
elseif getTSinceStart() > BETimes.vidEndTCPTrig(iTrial) + params.vidRecDelay(2);
% move to next phase
this.be.trialPhase = 'finished';
% trigger sent but wait time not yet finished
else
o('#%s(): waiting for video stop trigger ...', mfilename(), 3, this.verb);
end;
% no video triggering
else
% move to next phase
this.be.trialPhase = 'finished';
end;
%% paused
case 'paused';
% do nothing
%% unknown phase
otherwise;
showMessage(this, sprintf('%s | Trial %03d/%03d: unknown phase "%s" ... ', datestr(now(), ...
this.be.logDateFormat), iTrial, trainConf.nTrials, this.be.trialPhase), 'yellow');
end;
% store back the times
this.be.times = BETimes;
function t = getTSinceStart()
t = roundn(nowUNIXSec() - BETimes.start(iTrial), -3);
end
function t = getTSinceInit()
t = roundn(nowUNIXSec() - BETimes.init(iTrial), -3);
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
DWMatchROISetsToData.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/DWMatchROISetsToData.m
| 7,461 |
utf_8
|
7149efd47267f932563694835593decb
|
%% - #DWMatchROISetsToData
function DWMatchROISetsToData(this)
% update the wait bar
DWWaitBar(this, 0);
% get the list of all animals
uniqueAnimals = get(this, 'animal');
if ~isempty(uniqueAnimals) && ~iscell(uniqueAnimals); uniqueAnimals = { uniqueAnimals }; end;
if isempty(uniqueAnimals); uniqueAnimals = { '' }; end;
uniqueAnimals(cellfun(@isempty, uniqueAnimals)) = [];
uniqueAnimals = unique(uniqueAnimals);
nAnim = numel(uniqueAnimals);
% get the list of all days
uniqueDays = get(this, 'day');
if ~isempty(uniqueDays) && ~iscell(uniqueDays); uniqueDays = { uniqueDays }; end;
if isempty(uniqueDays); return; end;
uniqueDays(cellfun(@isempty, uniqueDays)) = [];
uniqueDays = unique(uniqueDays);
nDays = numel(uniqueDays);
% get the selected animal IDs
selectedAnimalIDs = this.dw.animalIDs(get(this.GUI.handles.dw.filt.animalID, 'Value'));
% if the dash '-' is selected, select all IDs
if numel(selectedAnimalIDs) == 1 && strcmp(selectedAnimalIDs{1}, '-');
selectedAnimalIDs = uniqueAnimals;
end;
% get the selected day IDs
selectedDayIDs = this.dw.dayIDs(get(this.GUI.handles.dw.filt.dayID, 'Value'));
% if the dash '-' is selected, select all IDs
if numel(selectedDayIDs) == 1 && strcmp(selectedDayIDs{1}, '-');
selectedDayIDs = uniqueDays;
end;
% go through each animal
for iAnim = 1 : nAnim;
animalID = uniqueAnimals{iAnim}; % get the current animal
% skip irrelevant animal IDs
if ~ismember(animalID, selectedAnimalIDs);
% update wait bar
DWWaitBar(this, 100 * (iAnim / nAnim));
continue;
end;
% go through each day
for iDay = 1 : nDays;
dayID = uniqueDays{iDay}; % get the current day
% skip irrelevant days
if ~ismember(dayID, selectedDayIDs);
% update wait bar
DWWaitBar(this, 100 * ((iDay / (nDays * nAnim)) + (iAnim - 1) / nAnim));
continue;
end;
% get the ROISet rows
ROISetRows = DWFilterTable(this, sprintf('animal = %s AND day = %s AND rowType = ROISet', animalID, dayID));
nROISets = size(ROISetRows, 1); % count them
% if no ROISets have been found, try without animal ID filtering
if nROISets == 0;
ROISetRows = DWFilterTable(this, sprintf('animal !~= \\w+ AND day = %s AND rowType = ROISet', dayID));
nROISets = size(ROISetRows, 1); % count them
end;
% get the imaging rows
imTypeFilter = iff(ismember(this.dw.tableIDs, 'imType'), ' AND imType = movie', '');
imagingRows = DWFilterTable(this, sprintf('animal = %s AND day = %s AND rowType = Imaging data%s', ...
animalID, dayID, imTypeFilter));
nImagingRows = size(imagingRows, 1); % count them
% go through each ROISet
for iROISet = 1 : nROISets;
% get the DataWatcher table's row index for this ROISet row
iDWRowROISet = str2double(get(this, iROISet, 'rowNum', ROISetRows));
% get the ROISet's row ID
ROISetRowID = DWGetRowID(this, iDWRowROISet);
% make sure the ROISet is loaded
DWLoadRow(this, iDWRowROISet, 'full');
% extract the data
ROISetData = getData(this, iDWRowROISet, 'ROISets', 'data');
% abort if the data cannot be found
if isempty(ROISetData);
showWarning(this, 'OCIA:DWMatchROISetsToData:ROISetDataNotFound', ...
sprintf('Could not find ROISet data for %s (row %03d). Skipping it.', ROISetRowID, iDWRowROISet));
% update wait bar
DWWaitBar(this, 100 * ((iROISet / (nROISets * nDays * nAnim)) + ((iDay - 1) / (nDays * nAnim)) + (iAnim - 1) / nAnim));
continue;
end;
% get the ROISet's "runsValidity", which tells which trials/runs are valid for this ROISet
runsValidity = ROISetData.runsValidity;
if ~iscell(runsValidity) && ~isempty(runsValidity); runsValidity = { runsValidity }; end;
% if the runsValidity are in the old format 'YYYY_MM_DD__hh_mm_ss', convert them to the new 'YYYYMMDD_hhmmss' format
if ~isempty(runsValidity) && ~isempty(regexp(runsValidity{1}, '\d{4}_\d{2}_\d{2}__\d{2}_\d{2}_\d{2}', 'once'));
runsValidity = cellfun(@(id)id([1 : 4, 6 : 7, 9 : 10, 12 : 14, 16 : 17, 19 : 20]), runsValidity, ...
'UniformOutput', false);
end;
% if no imaging rows, try to figure out the spot identity of this ROISet
if nImagingRows <= 0;
% get the ROISet's path
ROISetPath = get(this, iDWRowROISet, 'path');
% go through each possible spot
for iSpot = 1 : 10;
% get the spot folder's path
spotPath = regexprep(regexprep(ROISetPath, '/[^/]+$', '/'), 'ROISets', sprintf('spot%02d', iSpot));
% go through each possible row
for iRun = 1 : numel(runsValidity);
% get the spot folder's path
dataPath = sprintf('%s%s_%s_%s__%s_%s_%sh/', spotPath, runsValidity{iRun}(1:4), runsValidity{iRun}(5:6), ...
runsValidity{iRun}(7:8), runsValidity{iRun}(10:11), runsValidity{iRun}(12:13), runsValidity{iRun}(14:15));
% check if the data exists
if exist(dataPath, 'dir');
set(this, iDWRowROISet, 'spot', sprintf('spot%02d', iSpot));
break;
end;
end;
% if spot was found, interrupt search
if ~isempty(get(this, iDWRowROISet, 'spot')); break;
end;
end;
continue;
end;
% go through each imaging row
for iImagingRow = 1 : nImagingRows;
% get the DataWatcher table's row index for this imaging row
iDWRowImaging = str2double(get(this, iImagingRow, 'rowNum', imagingRows));
% get the row ID for the current imaging row
imagingRowID = DWGetRowID(this, iDWRowImaging);
% if there is a match compare the runs validity of the ROISet with this row's ID
if any(strcmp(runsValidity, imagingRowID));
% label the current imaging row as belonging to the current ROISet
set(this, iDWRowImaging, 'ROISet', ROISetRowID);
% if the ROISet does not have a spot ID specified, add the one from the imaging row
if isempty(get(this, iDWRowROISet, 'spot'));
set(this, iDWRowROISet, 'spot', get(this, iDWRowImaging, 'spot'));
end;
% if there is a GUI and the ROISet's reference image is from the current imaging row
if isGUI(this) && strcmp(imagingRowID, ROISetRowID);
set(this, iDWRowImaging, 'ROISet', sprintf('<html><font color="blue">%s</font>', ROISetRowID));
end;
end;
end;
% update wait bar
DWWaitBar(this, 100 * ((iROISet / (nROISets * nDays * nAnim)) + ((iDay - 1) / (nDays * nAnim)) + (iAnim - 1) / nAnim));
end;
end;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/OCIA.m
| 77,388 |
utf_8
|
77043c2f7b13e21ffd1f9a11c36961a1
|
classdef OCIA < handle
% OCIA - Online Calcium Imaging Assistant
%
% this = OCIA()
% this = OCIA(configName)
% this = OCIA(configName, DWFilt)
%
% Returns an OCIA object 'this', using the configuration file specified by 'configName' using the syntax
% "OCIA_config_[configName].m". If no configuration is specified, "OCIA_config_default.m" is used. Starting filters
% for the DataWatcher can be specified using the 'DWFilt', either as a string ('all', etc.) or cell-array of strings
% ( {'animalID1', '2014_10_30', 'spot03', ... } ). The file 'OCIA_config_generic' contains all the parameters that
% can be changed in a custom config file.
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % Originally created on 08 / 10 / 2013 %
% % Modified to v2.0 on 20 / 12 / 2013 %
% % Modified to v3.0 on 21 / 02 / 2014 %
% % Modified to v4.0 on 19 / 06 / 2014 %
% % Modified to v5.0 on 15 / 09 / 2014 %
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
%% TODO list
%{
- General
-- add the possibility to have a type of folder in multiple locations (e.g. parent of imgData could be spot OR day)
-- frame jitter, motion correction and motion detection should be independent of a ROISet
-- OCIA_config_default should not initiate the default config itself but call an initiator function "this =
initDefault(this)" or something otherwise the names are confusing
-- add icons to buttons for easier recognition
-- pre-processing GUI: uipanel with options for nFrameSkip(default=0)/fShift/fJitt/moCorr/moDet
options as checkboxes, and a "pre-process rows" button (ANPreProcRows). DWLoad('prev') should do none
of these corrections, except frameShift and frameSkip.
Add a display fig checkbox linked to the doPlots of the pre-processing functions.
-- save load modularity:
--- make the GUI dynamic for the saving options, based on the data's field and configuration
--- adapt the saving code so that it saves the right things at the right place
--- fix the save/load/reset options
-- check that flushdata works properly
- DataWatcher
-- add a "delete rows" function (hides the unwanted rows from the DataWatcher), also useful for the imagingWatcher mode
-- intrinsic imaging: access binary file content, show vessels tif files,
eventually overlap them with expression image using stiching algorithm
-- behavior movie: read the video with 'video2mat.m' and eventually match frames to trials
-- small thumbnail of the currently selected row(s) also for other data types (behavior, intrinsic, behavMovie)
--- requires frame grouping (? la imageJ ...)
-- only load imaging data once from the DataWatcher's table and then re-use it for analysis and ROI drawing
-- enable the "real" analysis pipeline support : load imaging data files (.bin)(HDF5?)
-- implement GUI items/config file for analysis parameters
NO -- add a load metadata button to avoid re-processing all folders just for the metadata
NO -- make the loaded rows' background green to show the data is loaded
NO -- store where each behavior/data file was found and dont reload it if not necessary
- ImagingWatcher
-- create a new imaging assistant mode or extend the data-watcher to help with online analysis of the imaging
--- could be on a different computer/matlab session for lower CPU on imaging computer and
eventually parallel computing for faster loading/processing
-- features:
--- loading last recorded data
--- "quick" ROIDrawing (semi-auto)
--- "quick" DRR extract
--- bleaching quantifier
--- previous days data and metadata (laser, depth, location, surface image, etc.)
- ROIDrawer
-- modularity in ROISet saving location
-- bug: remove old position callback in RDRenameROI
-- channel selection for ROI drawing, gray scale image of one channel
-- move all ROIs with small arrow GUI pushbuttons <- ^ ->
-- implement an semi-automatic segmentation tool based on cell centers and ring/filled cell body detection
-- cell identity labeling tool
- Analyser
-- implement a feature of analysing whole day/whole mice with analysRow button and watchType of only day or only animal
-- resizing of the whole panel bug, probably when saving (or plotting?) plots
-- enable the "real" analysis pipeline support (load imaging data files (HDF5?))
-- check for colorbar plot saving (resizing issue)
-- check for time-consuming sem calculation problem
-- add plots for several mice
-- implement a bleaching quantifier over multiple runs
-- fix the colorbar saving problem
-- fix the colormap problem
-- fix the analyser plotting ROISet mismatch/non-unique problem
-- when loading data in 'full' mode that was already loaded in 'prev', skip re-loading of 'prev' frames
- Behavior
-- check sound amplitude (SPL) *randomization*
-- fix licking detection or switch to lick rate
-- implement *alternative* detection system: lick rate
-- introduce a configuration editor or GUI items for mainConf.mat elements
-- save threshold and rewDur for each trial
-- perf analysis: exclude first 3-10 trials + non-responsive regions
-- auto-connect behavior box with COM port communication
- JointTracker
-- add coordinates display on mouse move
-- load X frames until memory is full and then just load frames on the fly while changing frames
-- when doing the sliding average, remove the existing frames and store them in the temp and then put it back
-- re-process on the fly the subsequent joints when placing a joint (when placing wrist, re-find the MCP)
-- crop function
-- image pre-processing not everywhere but defined by ROI
-- iJoint and iJointType from selection listbox should not be single values but must be arrays (multiple joint
manipulation)
-- prediction reaffinement
--- define an "area mask" for each joint (or each group of joints), using imfreehand, to constraint their position
--- use angles and joint distances to constraint the position of the joints
--- use field flow technique to predict where the joint will move
--- use correlation dip to change bounding box size (with a minimal box size setting)
-- improve debug plot display so that one can actually see what is going on (nJoints x nProcessSteps image with labeld axes)
-- create a progress bar to show how far we are and how is each frame annotated (manual, semi-auto validated, semi-auto not yet checked, etc.)
-- correlation frame-to-frame or frame-wise only on the bounding boxes
-- base frames pre-processing for better computer and/or manual annotation
--- subtract sliding window avg image
--- flatfield
--- contrast enhancement
-- base frames pre-processing might also only be applied to parts of the frame (like the sliding average only on the
lower part of the frame)
-- post-hoc evaluation method to get which joints are misplaced, based on:
--- interpolation of the data points from next and previous joint coordinate ('outlier' detection)
--- skelton distances
--- angle-change vs frame-to-frame correlation
-- post-hoc refinement of the match using smaller bounding box
-- computer vision algorithms / ideas
%}
%% properties
properties
% verbosity: number telling how much output should be printed out. The higher the more verbose.
verb = 2;
% general parameters: version number, start function name, modes, etc.
main = struct( ...
... software version
'version', '5.1.10', ...
... start function name
'startFunctionName', 'default', ...
... "modules" of the software that need to be included in the current instance
'modes', {{ ...
% mode name short name
'DataWatcher', 'dw';
'ROIDrawer', 'rd';
'Analyser', 'an';
'Behavior', 'be';
'Intrinsic', 'in';
'JointTracker', 'jt';
'TrialView', 'tv';
}}, ...
... data types/modes that need to be included in the current instance
'dataModes', {{ 'img', 'behav' }}, ...
... defines whether to show or hide the stack trace upon throwing a warning with the "#showWarning" method
'showWarningStackTraces', false ...
);
% paths used by the OCIA
path = struct();
% GUI related elements
GUI = struct( 'noGUI', false );
% - Data storage mode
data = struct();
% - DataWatcher mode
dw = struct();
% - ROIDrawer mode
rd = struct();
% - Analyser mode
an = struct();
% - Behavior mode
be = struct();
% - Intrinsic mode
in = struct();
% - JointTracker mode
jt = struct();
% - Discriminator mode
di = struct();
% - Discriminator mode
tv = struct();
end
%% methods - public
methods
%% - #OCIA - constructor
function this = OCIA(varargin)
% OCIA - Constructor
%
% this = OCIA()
% this = OCIA(configName)
% this = OCIA(configName, DWFilt)
% this = OCIA(configName, DWFilt, startFunctionName)
%
% Returns an OCIA object 'this', using the configuration file specified by 'configName' using the syntax
% "OCIA_config_[configName].m". If no configuration is specified, "OCIA_config_default" is used. Starting filters
% for the DataWatcher can be specified using the 'DWFilt', either as a string ('all', etc.) or cell-array of strings
% ( {'animalID1', '2014_10_30', 'spot03', ... } ). The file 'OCIA_config_generic' contains all the parameters that
% can be changed in a custom config file. Optional 'startFunctionName' string can be provided.
% Order of function calls for the creation of the object:
% - parsing inputs ('configName' and 'DWFilt')
% - call of the config specified by 'configName' (or 'default' if none provided)
% - first, the "modes" that need to be included in the OCIA should be selected in the "this.main.modes", as a
% N_MODES x 2 cell-array of strings, with first column being the mode's name ('DataWatcher') and the second
% column the short name ('dw'). This needs to be done before the call to the 'OCIA_config_default' because
% that function initializes the different modes.
% - the "data modes" that need to be included in the OCIA should also be selected in the "this.main.dataModes",
% as a cell-array of strings before the call to the 'OCIA_config_default' for the same reasons as above.
% - then, 'OCIA_config_default.m' is called. It initiates the OCIA object ('this') with default configuration
% values to start OCIA:
% - path (local, raw, ...)
% - modes (in case not initiated or dataWatcher mode not included)
% - GUI variables (window position, etc.)
% - initiate the different modes using their custom configuration functions:
% 'OCIA_modeConfig_[modeName].m'. These will initiate each mode with the default values for the
% variables needed to run those modes. For example in DataWatcher mode, the table's display, etc.
% - initiate the different data modes using their custom configuration functions:
% 'OCIA_dataConfig_[dataModeName].m'. These will initiate the 'this.main.dataConfig' cell-array which
% describes what kind of data types need to be used/stored. These custom configuration function
% can also eventually initiate some variables in the Analyser mode ('this.an.img' or 'this.an.be')
% for the analysis of those data types (for example 'this.an.img.defaultFrameRate').
% - initialization of the drop-down IDs of the DataWatcher to an empty dash ('-')
% - Java path update for Java classes
% - creation of the window
% - creation of each panel using the custom 'OCIA_createWindow_[modeName].m' functions
% - update of drop-down filters IDs based on the GUI values, which are initialized based on the 'DWFilt' input
% ('OCIA_createWindow_dataWatcher.m' calls 'DWUpdateFiltersAndWatchTypes' to do this)
% - window is made visible ('OCIA.show')
% - custom start function is called 'OCIA_startFunction_[functionName].m' based on the config file's setting stored
% under 'this.main.startFunctionName'
o('#%s(): constructor ...', mfilename, 4, this.verb);
o('Launching OCIA v%s ...', this.main.version, 0, this.verb);
%% -- #OCIA: parse inputs and load config file
o('#%s(): parsing inputs ...', mfilename, 4, this.verb);
% prepare the input parser object with the requested inputs
IP = inputParser;
addOptional(IP, 'configName', 'default', @ischar);
addOptional(IP, 'DWFilt', 'empty', @(x)isempty(x) || ischar(x) || iscell(x));
addOptional(IP, 'startFunctionName', 'empty', @(x)ischar(x));
parse(IP, varargin{:});
% get the config function's name and call it
configName = IP.Results.configName;
o('#%s(): using config file "%s" ...', mfilename, configName, 4, this.verb);
[~, thisNew] = OCIAGetCallCustomFile(this, 'config', configName, 1, { this }, 1);
% abort if no "this" anymore
if isempty(thisNew); return; end;
% otherwise go on
this = thisNew;
% if DataWatcher filtering was provided as input, overwrite config's parameter with input parameter
if ~strcmp(IP.Results.DWFilt, 'empty') && ~isempty(IP.Results.DWFilt);
this.GUI.dw.DWFilt = IP.Results.DWFilt;
end;
o('#%s(): filtering elements: " %s" ...', mfilename, sprintf('%s - ', this.GUI.dw.DWFilt{:}), 4, this.verb);
% if alternate start function name was provided
if ~strcmp(IP.Results.startFunctionName, 'empty');
this.main.startFunctionName = IP.Results.startFunctionName;
end;
o('#%s(): filtering elements: " %s" ...', mfilename, sprintf('%s - ', this.GUI.dw.DWFilt{:}), 4, this.verb);
%% -- #OCIA: update the drop-down filters and table IDs
% define the "IDs" field for each drop-down DataWatcher filter element
dropDownFiltersIDs = this.GUI.dw.filtElems{strcmp(this.GUI.dw.filtElems.GUIType, 'dropdown'), 'id'};
for iFilter = 1 : numel(dropDownFiltersIDs);
% create a list with only a dash element, which corresponds to no filtering
this.dw.([dropDownFiltersIDs{iFilter} 'IDs']) = {'-'};
end;
% fetch IDs
this.dw.tableIDs = this.GUI.dw.tableDisplay.id;
% init table to the right size
this.dw.table = cell(300, numel(this.dw.tableIDs));
% create order column if not yet present
if ~ismember('order', this.GUI.dw.tableDisplay.Properties.VariableNames)
this.GUI.dw.tableDisplay.order = (1 : size(this.GUI.dw.tableDisplay, 1))';
end;
%% -- #OCIA: turn warnings off
warning('off', 'images:imshow:magnificationMustBeFitForDockedFigure');
warning('off', 'MATLAB:hg:gltexture:TextureDataTooLargeForDevice');
warning('off', 'YMA:FindJObj:invisibleHandle');
warning('off', 'MATLAB:JavaEDTAutoDelegation');
%% --#OCIA: clean up paths
pathFields = fieldnames(this.path);
for iField = 1 : numel(pathFields);
fieldName = pathFields{iField};
this.path.(fieldName) = regexprep([regexprep(this.path.(fieldName), '\\', '/'), '/'], '//$', '/');
this.path.(fieldName) = regexprep(this.path.(fieldName), '(\.\w+)/', '$1');
end;
%% -- #OCIA: add java folders
OCIAPath = regexprep(which('OCIA'), '\\', '/');
OCIAPath = regexprep(OCIAPath, '/@OCIA/OCIA.m$', '');
javaaddpath([OCIAPath '/java/ij.jar']);
javaaddpath([OCIAPath '/java/TurboRegJava']);
o('#%s(): added Java path at "%s" ...', mfilename, OCIAPath, 4, this.verb);
%% -- #OCIA: create the window and show it
o('Creating window ...', 0, this.verb);
OCIACreateWindow(this); % create the GUI window
pause(0.5);
show(this); % make the GUI window visible
%% -- #OCIA: process start function
% process the start function
showMessage(this, sprintf('Initializing using start function "%s" ...', this.main.startFunctionName), 'yellow');
OCIAGetCallCustomFile(this, 'startFunction', this.main.startFunctionName, 1, { this }, 1); % use default if none provided
end
%% - #delete (destructor)
function delete(this)
o('#delete()', 4, this.verb);
delete(this.GUI.figH);
end
%% - GUI methods
%% -- #show
function show(this)
% show - Show the window
%
% show(this)
%
% Makes the OCIA window visible.
% do nothing if there is no GUI
if ~isGUI(this); return; end;
o('#show()', 4, this.verb);
showTic = tic; % for performance timing purposes
set(this.GUI.figH, 'Visible', 'on');
pause(0.1);
o('#show(): done (%.4f sec)', toc(showTic), 4, this.verb);
end;
%% -- #hide
function hide(this)
% hide - Hides the window
%
% hide(this)
%
% Makes the OCIA window invisible.
% do nothing if there is no GUI
if ~isGUI(this); return; end;
o('#hide()', 4, this.verb);
set(this.GUI.figH, 'Visible', 'off');
end;
%% -- #printWindowPosition
function printWindowPosition(this)
% printWindowPosition - Prints out the window's position
%
% printWindowPosition(this)
%
% Prints out the window's current position.
showMessage(this, 'Printing current window''s position:');
showMessage(this, sprintf('this.GUI.pos = [%s];', regexprep(sprintf('%.0f, ', get(this.GUI.figH, 'Position')), ', $', '')));
end;
%% -- #isGUI
function isGUIBool = isGUI(this)
% isGUI - GUI-mode check
%
% isGUIBool = isGUI(this)
%
% Returns the logical 'isGUIBool' telling whether the current instance of the OCIA ('this') is running in a
% windowed mode or not.
% if not in no-GUI mode and either in deployed mode or not in a matlab worker (parallel computing)
isGUIBool = ~this.GUI.noGUI && (isdeployed || isempty(javachk('desktop')));
end;
%% -- #showMessage
function showMessage(this, messageTxt, bgColor)
% showMessage - Display a message
%
% showMessage(this, messageTxt, bgColor)
%
% Displays the message 'messageTxt' (char) in the log bar and in the command window. If the variable 'bgColor' is
% specified, the background of the log bar is set to the color specified either as a color string ("red", "blue",
% etc.) or as an array of 3 values between 0.0 and 1.0 (RGB). Otherwise the default color (green) is used.
% print out the message in the command window
o(regexprep(messageTxt, '%', '%%'), 1, this.verb);
% do nothing if there is no GUI
if ~isGUI(this); return; end;
% if variable color not specified or neither a string nor a 3-elements RGB array
if ~exist('bgColor', 'var') || (~ischar(bgColor) && numel(bgColor) > 3);
% use the default green color
bgColor = 'green';
end;
% display the message and set the background
set(this.GUI.handles.logBar, 'String', messageTxt, 'Background', bgColor);
end;
%% -- #showWarning
function showWarning(this, warnID, warningText, bgColor)
% showMessage - Display a warning
%
% showWarning(this, warnID, warningText, bgColor)
%
% Displays the warning 'warningText' (char) with the ID 'warningID' (char) in the log bar and in the command window.
% If the variable 'bgColor' is specified, the background of the log bar is set to the color specified either as a
% color string ("red", "blue", etc.) or as an array of 3 values between 0.0 and 1.0 (RGB). Otherwise the default
% color (yellow) is used.
% if variable color not specified or neither a string nor a 3-elements RGB array
if ~exist('bgColor', 'var') || (~ischar(bgColor) && numel(bgColor) > 3);
% use the default green color
bgColor = 'yellow';
end;
% show the warning but without the stack trace
if ~this.main.showWarningStackTraces;
warning off backtrace;
end;
warning(warnID, [strrep(warningText, '\', '\\') ' (' warnID ')']);
if ~this.main.showWarningStackTraces;
warning on backtrace;
end;
% do nothing if there is no GUI or if warning is disabled
warnState = warning('query', warnID);
if ~isfield(this.GUI, 'noGUI') || ~isfield(this.GUI, 'figH') || ~isfield(this.GUI, 'handles') ...
|| ~isfield(this.GUI.handles, 'logBar') || ~isGUI(this) || strcmp(warnState.state, 'off'); return; end;
% split the warning text at end-of-line characters
warningTextSplit = regexp(warningText, '\n', 'split');
% only display the first line of the warning text and set the background
set(this.GUI.handles.logBar, 'String', warningTextSplit{1}, 'Background', bgColor);
end;
%% -- #getJTable
function jTable = getJTable(this, hTable)
% getJTable - Get a Java table
%
% jTable = getJTable(this, hTable)
%
% Returns the Java object 'jTable' associated with the uitable specified by 'hTable'. 'hTable' can be either a
% string ('DWTable', etc.) or as a uitable handle.
jTable = []; % return empty in case there is a problem
tableName = '';
% if handle is actually a string, get the appropriate uitable handle first
if ischar(hTable);
% store the table's name
tableName = hTable;
% check if the table was not already stored in memory
if isfield(this.GUI, 'jTables') && isfield(this.GUI.jTables, tableName);
jTable = this.GUI.jTables.(tableName);
return;
end;
% get the appropriate handle for the table
switch tableName;
case 'DWTable';
hTable = this.GUI.handles.dw.table;
case 'BEConfTable';
hTable = this.GUI.handles.be.confTable;
case 'BEETLTable';
hTable = this.GUI.handles.be.ETLTable;
case 'BEExpTable';
hTable = this.GUI.handles.be.expTable;
otherwise;
showWarning(this, 'OCIA:getJTable:UnknownTable', sprintf('Cannot find JTable for "%s".', hTable));
return;
end;
end;
% sometimes the Java-object fetching fails on first attempt, so try a second time
try
% get the actual java table underlying the requested uitable
jTable = findjobj(hTable); jTable = jTable.getComponents();
jTable = jTable(1); jTable = jTable.getComponents();
jTable = jTable(1);
% try a second time
catch e; %#ok<NASGU>
pause(0.5);
% get the actual java table underlying the requested uitable
jTable = findjobj(hTable); jTable = jTable.getComponents();
jTable = jTable(1); jTable = jTable.getComponents();
jTable = jTable(1);
end;
% if the table was acced by a name, store the jtable
if ~isempty(tableName);
this.GUI.jTables.(tableName) = jTable;
end;
end;
%% -- #getData
function data = getData(this, varargin)
% getData - Get data or load status from the DataWatcher's table
%
% data = getData(this, rows, dataType)
% data = getData(this, rows, dataType, subFieldName)
%
% Returns the requested data type from the DataWatcher's table data. "rows" should be a double or an array of double and
% "columns" a string or a cell-array of string, "dataType" a string. "subFieldName" should be a string that specifies
% which sub-field ('data', 'loadStatus', 'procState') should be returned.
% by default or in case of error, return nothing
data = [];
% all columns for specified row(s)
if numel(varargin) == 2 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& ischar(varargin{2});
rows = varargin{1};
dataType = varargin{2};
subFieldName = [];
% specified rows and specified column(s)
elseif numel(varargin) == 3 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& ischar(varargin{2}) && ischar(varargin{3});
rows = varargin{1};
dataType = varargin{2};
subFieldName = varargin{3};
% otherwise: bad input arguments
else
rows = [];
dataType = [];
subFieldName = [];
end;
% if all rows are required to be selected using the 'all' command
if ischar(rows) && strcmp(rows, 'all');
rows = 1 : size(this.dw.table, 1);
end;
% if the parameters where not all provided or could not be figured out, abort with warning
if isempty(rows) || isempty(dataType);
showWarning(this, 'OCIA:getData:BadInputArguments', 'Bad input arguments for function getData, please read the help.');
return;
end;
% get the data structure
dataStruct = getR(this, rows, 'data');
% if no data structure found, return nothing
if isempty(dataStruct);
return;
end;
% allocate the data as a cell array
data = cell(size(dataStruct));
% go through each fetched sub-structure
for iStruct = 1 : numel(dataStruct);
% if the dataType exists
if isfield(dataStruct{iStruct}, dataType);
% if no sub-field name provided, return the data structures themselves
if isempty(subFieldName);
data{iStruct} = dataStruct{iStruct}.(dataType);
% if the sub-field name is required and exists, return it
elseif isfield(dataStruct{iStruct}.(dataType), subFieldName);
data{iStruct} = dataStruct{iStruct}.(dataType).(subFieldName);
end;
end;
end;
% do not return a single empty cell, return an empty array instead
if iscell(data) && numel(data) == 1;
data = data{1};
end;
end
%% -- #setData
function data = setData(this, varargin)
% getData - Get data or load status from the DataWatcher's table
%
% setData(this, rows, dataType, data)
% setData(this, rows, dataType, subFieldName, data)
%
% Stores the specified data in the DataWatcher's table specified data type. "rows" should be a double or an array of double and
% "columns" a string or a cell-array of string, "dataType" a string. "subFieldName" should be a string that specifies
% which sub-field ('data', 'loadStatus', 'procState') should be returned. "data" is the data to store, can be a cell
% array.
% all columns for specified row(s)
if numel(varargin) == 3 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& ischar(varargin{2});
rows = varargin{1};
dataType = varargin{2};
subFieldName = [];
data = varargin{3};
% specified rows and specified column(s)
elseif numel(varargin) == 4 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& ischar(varargin{2}) && ischar(varargin{3});
rows = varargin{1};
dataType = varargin{2};
subFieldName = varargin{3};
data = varargin{4};
% otherwise: bad input arguments
else
rows = [];
dataType = [];
subFieldName = [];
data = [];
end;
% if all rows are required to be selected using the 'all' command
if ischar(rows) && strcmp(rows, 'all');
rows = 1 : size(tableToUse, 1);
end;
% if the parameters where not all provided or could not be figured out, abort with warning
if isempty(rows) || isempty(dataType);
showWarning(this, 'OCIA:setData:BadInputArguments', 'Bad input arguments for function setData, please read the help.');
return;
end;
% make sure the data's format is a cell-array
if ~iscell(data) || numel(rows) == 1;
data = { data };
end;
% if the number of rows is too big, abort with warning
if numel(rows) ~= numel(data);
showWarning(this, 'OCIA:setData:NumberOfRowsMismatch', ...
sprintf('Number of rows specified (%02d) is not equal to the size of the input data (%02d).', ...
numel(rows), numel(data)));
return;
end;
% go through each row
for iRow = 1 : numel(rows);
% get the data for this row
dataStruct = get(this, rows(iRow), 'data');
% if the dataType exists
if isfield(dataStruct, dataType);
% if no sub-field name provided, store the whole data data type
if isempty(subFieldName);
dataStruct.(dataType) = data{iRow};
% otherwise just set the field
else
dataStruct.(dataType).(subFieldName) = data{iRow};
end;
end;
% set the data for this row
set(this, rows(iRow), 'data', dataStruct);
end;
end
%% -- #get
function values = get(this, varargin)
% get - Get values from table
%
% values = get(this, rows)
% values = get(this, columns)
% values = get(this, rows, columns)
% values = get(this, rows, columns, tableToUse)
% values = get(this, rows, columns, tableToUse, tableIDs)
%
% Returns the requested rows/columns from the DataWatcher's table. "rows" should be a double or an array of double and
% "columns" a string or a cell-array of string. Optionnally, an alternative table "tableToUse" can be provided with
% its own columns names "tableIDs".
% get the raw values
values = getR(this, varargin{:});
% do some post-process tasks if there are some cells
if ~isempty(values);
% filter for the delete tag
charCells = cellfun(@ischar, values);
values(charCells) = regexprep(values(charCells), ['^' this.GUI.dw.deleteTag], '');
values(charCells) = regexprep(values(charCells), '^<html>(<[^>]+>)?(<[^>]+>)?([^<]+)(<[^>]+>)*', '$3');
% do not return a single cell, return the value it contains instead
if iscell(values) && numel(values) == 1;
values = values{1};
end;
end;
end
%% -- #getR
function values = getR(this, varargin)
% getR - Get raw values from table (no post-processing)
%
% values = getR(this, rows)
% values = getR(this, columns)
% values = getR(this, rows, columns)
% values = getR(this, rows, columns, tableToUse)
% values = getR(this, rows, columns, tableToUse, tableIDs)
%
% Returns the requested rows/columns from the DataWatcher's table without any further modification (delete tag removal).
% "rows" should be a double or an array of double and "columns" a string or a cell-array of string. Optionnally,
% an alternative table "tableToUse" can be provided with its own columns names "tableIDs".
% get the default table and its IDs
tableToUse = this.dw.table;
tIDs = this.dw.tableIDs;
% by default or in case of error, return nothing
values = [];
% all columns for specified row(s)
if numel(varargin) == 1 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all')));
rows = varargin{1};
columns = tIDs;
% all rows for specified column(s)
elseif numel(varargin) == 1 && (ischar(varargin{1}) || iscell(varargin{1}));
rows = 'all';
columns = varargin{1};
% specified rows and specified column(s)
elseif numel(varargin) == 2 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& (ischar(varargin{2}) || iscell(varargin{2}));
rows = varargin{1};
columns = varargin{2};
% specified rows and specified column(s) with a custom table
elseif numel(varargin) == 3 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& (ischar(varargin{2}) || iscell(varargin{2})) ...
&& iscell(varargin{3});
rows = varargin{1};
columns = varargin{2};
tableToUse = varargin{3};
% specified rows and specified column(s) with a custom table and table IDs
elseif numel(varargin) == 4 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& (ischar(varargin{2}) || iscell(varargin{2})) ...
&& iscell(varargin{3}) && iscell(varargin{4});
rows = varargin{1};
columns = varargin{2};
tableToUse = varargin{3};
tIDs = varargin{4};
% otherwise: bad input arguments
else
rows = [];
columns = [];
end;
% if all rows are required to be selected using the 'all' command
if ischar(rows) && strcmp(rows, 'all');
rows = 1 : size(tableToUse, 1);
end;
% make sure the column name(s)'format is a cell-array
if ischar(columns) && ~isempty(columns);
columns = { columns };
end;
% if no rows selected, abort
if isempty(rows);
return;
end;
% if the parameters where not all provided or could not be figured out, abort with warning
if isempty(columns) || isempty(tableToUse) || isempty(tIDs);
showWarning(this, 'OCIA:getR:BadInputArguments', 'Bad input arguments for function get, please read the help.');
return;
end;
% if the number of rows is too big, abort with warning
if numel(rows) > size(tableToUse, 1);
showWarning(this, 'OCIA:getR:NumberOfRowsExceeded', ...
sprintf('Number of rows specified (%02d) exceeds table''s dimensions (%02d).', numel(rows), size(tableToUse, 1)));
return;
end;
% if all is good, then fetch the values:
% get the indexes of the columns that are in the IDs, in the same order as requested
[~, b] = ismember(columns(ismember(columns, tIDs)), tIDs);
% fetch the values
values = tableToUse(rows, b);
% post-process the column names
for iCol = 1 : numel(columns);
switch columns{iCol};
case 'rowID';
rowID = DWGetRowID(this, rows);
if ~iscell(rowID); rowID = { rowID }; end;
values(:, iCol) = rowID;
case 'rowTypeID';
rowTypeID = DWGetRowTypeID(this, rows);
if ~iscell(rowTypeID); rowTypeID = { rowTypeID }; end;
values(:, iCol) = rowTypeID;
otherwise;
% do nothing
end;
end;
end
%% -- #set
function varargout = set(this, varargin)
% set - set values in table
%
% set(this, rows, values)
% set(this, columns, values)
% set(this, rows, columns, values)
% tableToUse = set(this, rows, columns, values, tableToUse)
% tableToUse = set(this, rows, columns, values, tableToUse, tableIDs)
%
% Stores the specified values in the rows/columns from the DataWatcher's table. "rows" should be a double or an
% array of double and "columns" a string or a cell-array of string. Optionnally, an alternative table "tableToUse"
% can be provided with its own columns names "tableIDs", in which case the new table is returned.
% by default, no output
varargout = {};
% get the default table and its IDs
tableToUse = this.dw.table;
tIDs = this.dw.tableIDs;
% set the flag specifying if the table used was from input, by default "false"
tableFromInput = false;
% all columns for specified row(s)
if numel(varargin) == 2 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all')));
rows = varargin{1};
columns = tIDs;
values = varargin{2};
% all rows for specified column(s)
elseif numel(varargin) == 2 && (ischar(varargin{1}) || iscell(varargin{1}));
rows = 'all';
columns = varargin{1};
values = varargin{2};
% specified rows and specified column(s)
elseif numel(varargin) == 3 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& (ischar(varargin{2}) || iscell(varargin{2}));
rows = varargin{1};
columns = varargin{2};
values = varargin{3};
% specified rows and specified column(s) with a custom table
elseif numel(varargin) == 4 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& (ischar(varargin{2}) || iscell(varargin{2})) ...
&& iscell(varargin{4});
rows = varargin{1};
columns = varargin{2};
values = varargin{3};
tableToUse = varargin{4};
% set the flag specifying that the table used was from input
tableFromInput = true;
% specified rows and specified column(s) with a custom table and table IDs
elseif numel(varargin) == 5 && (isnumeric(varargin{1}) || (ischar(varargin{1}) && strcmp(varargin{1}, 'all'))) ...
&& (ischar(varargin{2}) || iscell(varargin{2})) ...
&& iscell(varargin{4}) && iscell(varargin{5});
rows = varargin{1};
columns = varargin{2};
values = varargin{3};
tableToUse = varargin{4};
tIDs = varargin{5};
% set the flag specifying that the table used was from input
tableFromInput = true;
% otherwise: bad input arguments
else
columns = [];
end;
% if all rows are required to be selected using the 'all' command
if ischar(rows) && strcmp(rows, 'all');
rows = 1 : size(tableToUse, 1);
end;
% make sure the column name(s)'format is a cell-array
if ischar(columns) && ~isempty(columns);
columns = { columns };
end;
% if the parameters where not all provided or could not be figured out, abort with warning
if isempty(rows) || isempty(columns) || isempty(tableToUse) || isempty(tIDs);
showWarning(this, 'OCIA:set:BadInputArguments', 'Bad input arguments for function set, please read the help.');
return;
end;
% if the number of rows is too big, abort with warning
if numel(rows) > size(tableToUse, 1);
showWarning(this, 'OCIA:set:NumberOfRowsExceeded', ...
sprintf('Number of rows specified (%02d) exceeds table''s dimensions (%02d).', numel(rows), size(tableToUse, 1)));
return;
end;
% make sure the values' format is a cell-array
if ~iscell(values);
values = { values };
end;
% if the size of the values does not match exactly the size of what needs to be replaced, try to extend the values
tableToReplace = tableToUse(rows, ismember(tIDs, columns));
if ~all(size(values) == size(tableToReplace));
% if inputs are just transposed, transposed them back
if all(size(values') == size(tableToReplace));
values = values';
% if the values are a vector and can be expanded on one dimension to fit the right size
elseif size(values, 1) == 1 && size(values, 2) == size(tableToReplace, 2);
values = repmat(values, size(tableToReplace, 1), 1);
% if the values are a vector and can be expanded on one dimension to fit the right size
elseif size(values, 1) == 1 && size(values, 2) == size(tableToReplace, 1);
values = repmat(values', 1, size(tableToReplace, 2));
% if the values are a vector and can be expanded on one dimension to fit the right size
elseif size(values, 2) == 1 && size(values, 1) == size(tableToReplace, 1);
values = repmat(values, 1, size(tableToReplace, 1));
% if the values are a vector and can be expanded on one dimension to fit the right size
elseif size(values, 2) == 1 && size(values, 1) == size(tableToReplace, 2);
values = repmat(values', size(tableToReplace, 1), 1);
% if the values are a vector and can be expanded on one dimension to fit the right size
elseif size(values, 2) == 1 && size(values, 1) == 1;
values = repmat(values', size(tableToReplace, 1), size(tableToReplace, 2));
% if nothing can be done, abort
else
showWarning(this, 'OCIA:set:BadSizeInputValues', ...
sprintf('Input values have bad size: provided size: %d x %d, required size: %d x %d.', ...
size(values), size(tableToReplace)));
return;
end;
end;
% set the values
tableToUse(rows, ismember(tIDs, columns)) = values;
% if the table comes from input arguments, return it
if tableFromInput;
varargout = { tableToUse };
% otherwise, update the data watcher table
else
this.dw.table = tableToUse;
end;
end
%% - #event handlers
%% -- #keyPressed
function keyPressed(this, ~, e)
% get the current mode
currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};
% get whether a mode change was requested
isChangeMode = 0;
% if ismember('shift', e.Modifier);
% switch e.Key;
% case {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
% if str2double(e.Key) <= size(this.main.modes, 1);
% OCIAChangeMode(this, this.main.modes{str2double(e.Key), 1});
% end;
% isChangeMode = 1;
% end;
% end;
if ~isChangeMode;
switch currentMode
%% --- #keyPressed : ROIDrawer
case 'TrialView';
% get current object
currObj = get(this.GUI.figH, 'CurrentObject');
% check for key presses not while inside a text uicontrol element
if ~isa(currObj, 'matlab.ui.control.UIControl') || ~ismember(get(currObj, 'Style'), { 'edit' });
switch e.Key;
% print help for shortcuts
case 'h';
msgCellArray = { ...
'This is the \bfhelp\rm for the \bfshortcuts\rm of the TrialView mode of OCIA.', ...
'Following shortcuts can be used:', ...
'\bf [H] \rmdisplay this help', ...
'\bf [up/down arrows] \rmmove up/down in the file selection', ...
'\bf [left/right arrows] \rmmove 1 frame backward or forward', ...
'\bf [SHIFT] + [left/right arrows] \rmmove 3 frames backward or forward', ...
'\bf [space] \rmadd a movement point', ...
'\bf [R] \rmreset GUI', ...
'\bf [CTRL] + [R] \rmreset movement points for current trial', ...
'\bf [SHIFT] + [R] \rmreset movement points for all trials', ...
'\bf [L] \rmload current row/trial', ...
'\bf [CTRL] + [L] \rmload parameters and move vectors', ...
'\bf [SHIFT] + [L] \rmload ROIs', ...
'\bf [CTRL] + [S] \rmsave parameters and move vectors', ...
'\bf [SHIFT] + [S] \rmsave ROIs', ...
}';
% display a message box
h = msgbox( msgCellArray, 'Shortcut help for TrialView mode');
% make sure the box is big enough
boxPos = get(h, 'Position');
set(h, 'Position', boxPos + [-200, -75, 400, 150]);
% make font bigger
hChild = get(h, 'Children');
set(hChild(2), 'Units', 'Normalized', 'Position', [0, 0, 1, 1]);
hText = get(hChild(2), 'Children');
set(hText, 'FontSize', 12, 'Units', 'Normalized', 'Position', [0.01, 0.98, 0], ...
'FontName', 'Courier', 'VerticalAlignment', 'top', 'String', msgCellArray, ...
'Interpreter', 'tex');
% left/right arrow keys => move by one frame back or forward
case { 'leftarrow', 'rightarrow' };
% adjust frame
this.tv.iFrame = this.tv.iFrame + iff(ismember('shift', e.Modifier), 3, 1) ...
* iff(strcmp(e.Key, 'leftarrow'), -1, 1);
% keep frame between boundaries
this.tv.iFrame = min(max(round(this.tv.iFrame), 1), this.tv.params.WFDataSize(3));
% update GUI
OCIA_trialview_changeFrame(this);
% up/down arrow keys => move within the file selection list
case { 'uparrow', 'downarrow' };
if isfield(this.GUI.handles.tv, 'paramPanElems') ...
&& isfield(this.GUI.handles.tv.paramPanElems, 'fileList');
% get selected element and size
selElemIndex = get(this.GUI.handles.tv.paramPanElems.fileList, 'Value');
nElems = numel(get(this.GUI.handles.tv.paramPanElems.fileList, 'String'));
% adjust selection
selElemIndex = selElemIndex + iff(strcmp(e.Key, 'uparrow'), -1, 1);
% keep index between boundaries
selElemIndex = min(max(selElemIndex, 1), nElems);
% update GUI
set(this.GUI.handles.tv.paramPanElems.fileList, 'Value', selElemIndex);
% make sure parameters are updated
TVUpdateParams(this);
end;
% add a movement point
case 'space';
OCIA_trialview_addMovePoint(this);
% resets
case 'r';
% reset GUI
if isempty(e.Modifier);
OCIA_startFunction_trialView(this);
% reset move points
elseif ~isempty(e.Modifier) && all(strcmp(e.Modifier, 'control'));
OCIA_trialview_resetMovePoints(this);
% reset all move points
elseif ~isempty(e.Modifier) && all(strcmp(e.Modifier, 'shift'));
OCIA_trialview_resetMovePoints(this, 'all');
end;
% load
case 'l';
% load row
if isempty(e.Modifier);
OCIA_trialview_loadWideFieldData(this);
% load params
elseif ~isempty(e.Modifier) && all(strcmp(e.Modifier, 'control'));
OCIA_trialview_loadParams(this);
% load ROIs
elseif ~isempty(e.Modifier) && all(strcmp(e.Modifier, 'shift'));
OCIA_trialview_loadROIs(this);
end;
% save
case 's';
% save params
if all(strcmp(e.Modifier, 'control'));
OCIA_trialview_saveParams(this);
% save ROIs
elseif all(strcmp(e.Modifier, 'shift'));
OCIA_trialview_saveROIs(this);
end;
end; % switch end
end; % end of check for key presses not while inside a text uicontrol element
%% --- #keyPressed : ROIDrawer
case 'ROIDrawer';
switch e.Key;
% arrow keys
case { 'uparrow', 'downarrow', 'leftarrow', 'rightarrow' };
% move ROIs
if ~ismember('control', e.Modifier) && ~ismember('shift', e.Modifier) ...
&& ~ismember('alt', e.Modifier);
RDMoveROIs(this, strrep(e.Key, 'arrow', ''), this.rd.moveROIsStep);
% rotate ROIs
elseif ismember('control', e.Modifier) && strcmp(e.Key, 'leftarrow');
RDRotateROIs(this, - this.rd.rotateROIsStep);
% rotate ROIs
elseif ismember('control', e.Modifier) && strcmp(e.Key, 'rightarrow');
RDRotateROIs(this, this.rd.rotateROIsStep);
% scale ROIs
elseif ismember('shift', e.Modifier) && strcmp(e.Key, 'leftarrow');
RDScaleROIs(this, this.rd.scaleROIsStep, 0);
% scale ROIs
elseif ismember('shift', e.Modifier) && strcmp(e.Key, 'rightarrow');
RDScaleROIs(this, - this.rd.scaleROIsStep, 0);
% scale ROIs
elseif ismember('shift', e.Modifier) && strcmp(e.Key, 'uparrow');
RDScaleROIs(this, 0, this.rd.scaleROIsStep);
% scale ROIs
elseif ismember('shift', e.Modifier) && strcmp(e.Key, 'downarrow');
RDScaleROIs(this, 0, - this.rd.scaleROIsStep);
% change ROI
elseif ismember('alt', e.Modifier) && strcmp(e.Key, 'downarrow');
currROI = get(this.GUI.handles.rd.selROIsList, 'Value');
if isempty(currROI); currROI = 1; end;
if currROI(1) < numel(get(this.GUI.handles.rd.selROIsList, 'String'));
set(this.GUI.handles.rd.selROIsList, 'Value', currROI(1) + 1);
end;
RDSelROI(this);
% change ROI
elseif ismember('alt', e.Modifier) && strcmp(e.Key, 'uparrow');
currROI = get(this.GUI.handles.rd.selROIsList, 'Value');
if isempty(currROI);
currROI = numel(get(this.GUI.handles.rd.selROIsList, 'String'));
end;
if currROI(1) > 1;
set(this.GUI.handles.rd.selROIsList, 'Value', currROI(1) - 1);
end;
RDSelROI(this);
end;
% toggle zoom
case 'z';
RDActivateZoom(this, ~get(this.GUI.handles.rd.zTool, 'Value'));
% new ROI
case 'n';
RDDrawNewROI(this, [], []);
% compare ROISets
case 'c';
% invert target and reference
if ismember('control', e.Modifier);
selRef = get(this.GUI.handles.rd.refROISetASetter, 'Value');
selTarg = get(this.GUI.handles.rd.refROISetBSetter, 'Value');
set(this.GUI.handles.rd.refROISetASetter, 'Value', selTarg(1));
set(this.GUI.handles.rd.refROISetBSetter, 'Value', selRef(1));
RDCompareROIs(this, 'IDs');
% ?
elseif ismember('alt', e.Modifier);
compareState = get(this.GUI.handles.rd.refROISet, 'Value');
set(this.GUI.handles.rd.refROISet, 'Value', ~compareState);
RDCompareROIs(this, 'IDs');
% ?
else
RDCompareROIs(this, 'IDs');
end;
case 'l';
% load ROIs
if ismember('control', e.Modifier);
RDSaveROIs(this);
% select last ROIs
else
set(this.GUI.handles.rd.selROIsList, 'Value', numel(get(this.GUI.handles.rd.selROIsList, 'String')));
RDSelROI(this);
end;
case 'r';
% reload ROIs
if ismember('shift', e.Modifier);
spotIDs = get(this, 'all', 'spot');
spotIDs(cellfun(@isempty, spotIDs)) = [];
uniqueSpotIDs = unique([ '-'; spotIDs]);
selectedSpotIDs = get(this, this.dw.selectedTableRows, 'spot');
selectedSpotIDs(cellfun(@isempty, selectedSpotIDs)) = [];
uniqueSelectedSpotIDs = unique(selectedSpotIDs);
selRef = get(this.GUI.handles.rd.refROISetASetter, 'Value');
selTarg = get(this.GUI.handles.rd.refROISetBSetter, 'Value');
DWProcessWatchFolder(this);
DWExtractNotebookInfo(this);
pause(0.01);
set(this.GUI.handles.dw.filt.spotID, 'String', uniqueSpotIDs, ...
'Value', find(strcmp(uniqueSelectedSpotIDs{1}, uniqueSpotIDs)));
DWFilterSelectTable(this, 'new');
pause(0.01);
OCIA_dataWatcherProcess_drawROIs(this);
set(this.GUI.handles.rd.tableList, 'Value', 1 : numel(this.rd.selectedTableRows));
RDChangeRow(this, this.GUI.handles.rd.tableList);
set(this.GUI.handles.rd.refROISetASetter, 'Value', selRef);
set(this.GUI.handles.rd.refROISetBSetter, 'Value', selTarg);
set(this.GUI.handles.rd.refROISet, 'Value', 1);
RDCompareROIs(this);
RDLoadROIs(this);
% rename ROIs
elseif ismember('control', e.Modifier);
RDRenameROI(this);
% rename ROIs box
else
set(this.GUI.handles.rd.ROIName, 'String', '');
uicontrol(this.GUI.handles.rd.ROIName);
end;
case 'space';
% delete selected ROIs
case { 'd', 'delete' };
RDDeleteROI(this);
% toggle ROI display
case 'i';
RDShowHideROIs(this, 'IDs');
% toggle ROI display
case 'o';
RDShowHideROIs(this, 'ROIs');
case 's';
% save ROIs
if ismember('control', e.Modifier);
RDSaveROIs(this);
% select ROIs box
else
set(this.GUI.handles.rd.selROISetter, 'String', '');
uicontrol(this.GUI.handles.rd.selROISetter);
end;
case 'a';
% select all ROIs
if ismember('control', e.Modifier);
set(this.GUI.handles.rd.selROIsList, 'Value', ...
1 : numel(get(this.GUI.handles.rd.selROIsList, 'String')));
RDSelROI(this);
% image adjustement
else
set(this.GUI.handles.rd.imAdj, 'Value', ~get(this.GUI.handles.rd.imAdj, 'Value'));
RDUpdateImage(this, this.GUI.handles.rd.imAdj);
end;
% pseudo flat field
case 'p';
set(this.GUI.handles.rd.pseudFF, 'Value', ~get(this.GUI.handles.rd.pseudFF, 'Value'));
RDUpdateImage(this, this.GUI.handles.rd.pseudFF);
otherwise;
% showWarning(this, 'OCIA:keyPressed:UnknownKey', sprintf('Unknown key (%s) pressed.', e.Key));
end;
%% --- #keyPressed : Analyser
case 'Analyser';
switch e.Key;
case {'leftarrow', 'rightarrow'};
if ismember('control', e.Modifier);
ANSelPlot(this, strrep(e.Key, 'arrow', ''));
end;
case {'uparrow', 'downarrow'};
if ismember('control', e.Modifier);
ANSelRuns(this, strrep(e.Key, 'arrow', ''));
end;
case 'z';
if ismember('control', e.Modifier);
ANActivateZoom(this, ~get(this.GUI.handles.an.zTool, 'Value'));
end;
case 'd';
if ismember('control', e.Modifier);
ANActivateDataCursor(this, ~get(this.GUI.handles.an.cTool, 'Value'));
end;
case 's';
% save plot
if ismember('control', e.Modifier);
ANSavePlot(this, []);
end;
otherwise;
% showWarning(this, 'OCIA:keyPressed:UnknownKey', sprintf('Unknown key (%s) pressed.', e.Key));
end;
%% --- #keyPressed : JointTracker
case 'JointTracker';
% get current object
currObj = get(this.GUI.figH, 'CurrentObject');
% check for key presses not while inside a text uicontrol element
if ~isa(currObj, 'matlab.ui.control.UIControl') || ~ismember(get(currObj, 'Style'), { 'edit' });
switch e.Key;
% print help for shortcuts
case 'h';
msgCellArray = { ...
'This is the \bfhelp\rm for the \bfshortcuts\rm of the JointTracker mode of OCIA.', ...
'Following shortcuts can be used:', ...
'\bf [H] \rmDisplay this help', ...
'-------------------------------------------------------------------------------------------', ...
'\bf [A / D] \rmPrevious / next frame', ...
'\bf [left / right arrows] \rmPrevious / next frame', ...
'\bf [SHIFT] + [A / D] \rmFirst / last frame', ...
'\bf [SHIFT] + [left / right arrows] \rmFirst / last frame', ...
'-------------------------------------------------------------------------------------------', ...
'\bf [C] \rmChange the cursor display (dot <-> pointer)', ...
'-------------------------------------------------------------------------------------------', ...
'\bf [W / S] \rmChange joint type (manual <-> auto)', ...
'\bf [up / down arrow] \rmChange joint type (manual <-> auto)', ...
'-------------------------------------------------------------------------------------------', ...
'\bf [F] \rmStart / stop auto-track', ...
'\bf [V] \rmStart / stop manual-track', ...
'\bf [M] \rmStart / stop manual-track', ...
}';
% display a message box
h = msgbox(msgCellArray);
% make sure the box is big enough
boxPos = get(h, 'Position');
set(h, 'Position', boxPos + [-200, -75, 400, 150]);
% make font bigger
hChild = get(h, 'Children');
set(hChild(2), 'Units', 'Normalized', 'Position', [0, 0, 1, 1]);
hText = get(hChild(2), 'Children');
set(hText, 'FontSize', 12, 'Units', 'Normalized', 'Position', [0.01, 0.98, 0], ...
'FontName', 'Courier', 'VerticalAlignment', 'top', 'String', msgCellArray, ...
'Interpreter', 'tex');
case 'c';
JTSwapCursor(this);
case { 'a', 'leftarrow' };
if ismember('shift', e.Modifier);
set(this.GUI.handles.jt.frameSetter, 'Value', 1);
else
set(this.GUI.handles.jt.frameSetter, 'Value', max(this.GUI.jt.iFrame - 1, 1));
end;
case { 'd', 'rightarrow' };
if ismember('shift', e.Modifier);
if get(this.GUI.handles.jt.autoTrack, 'Value');
JTProcess(this, 'all');
else
set(this.GUI.handles.jt.frameSetter, 'Value', this.jt.nFrames);
end;
else
set(this.GUI.handles.jt.frameSetter, 'Value', min(this.GUI.jt.iFrame + 1, this.jt.nFrames));
end;
case {'w', 's', 'uparrow', 'downarrow', };
addValue = 1; if strcmp(e.Key, 's') || strcmp(e.Key, 'downarrow'); addValue = -1; end;
newValue = min(max(this.GUI.jt.iJointType + addValue, 1), this.jt.nJointTypes);
if newValue ~= get(this.GUI.handles.jt.jointTypeSelSetter, 'Value');
set(this.GUI.handles.jt.jointTypeSelSetter, 'Value', newValue);
JTChangeJointOrJointType(this, this.GUI.handles.jt.jointTypeSelSetter);
end;
case 'f';
set(this.GUI.handles.jt.autoTrack, 'Value', ~get(this.GUI.handles.jt.autoTrack, 'Value'));
JTProcess(this, 'autoTrackChanged');
case {'m', 'v'};
set(this.GUI.handles.jt.manuTrack, 'Value', ~get(this.GUI.handles.jt.manuTrack, 'Value'));
JTManualTrackStart(this);
case 'space';
% set(this.GUI.handles.jt.viewOpts.preProc, 'Value', ...
% ~get(this.GUI.handles.jt.viewOpts.preProc, 'Value'));
% JTUpdateGUI(this, this.GUI.handles.jt.viewOpts.preProc);
otherwise;
% showWarning(this, 'OCIA:keyPressed:UnknownKey', sprintf('Unknown key (%s) pressed.', e.Key));
end;
end; % end of check for key presses not while inside a text uicontrol element
%% --- #keyPressed : Discriminator
case 'Discriminator';
switch e.Key;
% adjust response rate threshold
case 'leftarrow';
this.di.respRateThresh = max(min(this.di.respRateThresh - 0.5, 9.5), 1);
showMessage(this, sprintf('Reponse threshold: %.1f.', this.di.respRateThresh), 'yellow');
% adjust response rate threshold
case 'rightarrow';
this.di.respRateThresh = max(min(this.di.respRateThresh + 0.5, 9.5), 1);
showMessage(this, sprintf('Reponse threshold: %.1f.', this.di.respRateThresh), 'yellow');
% zoom level of activity
case 'uparrow';
this.GUI.di.zoomLevel = max(min(this.GUI.di.zoomLevel + this.GUI.di.zoomLevel * 0.1, 10), 1);
showMessage(this, sprintf('Zoom level: %.1f.', this.GUI.di.zoomLevel), 'yellow');
% zoom level of activity
case 'downarrow';
this.GUI.di.zoomLevel = max(min(this.GUI.di.zoomLevel - this.GUI.di.zoomLevel * 0.1, 10), 1);
showMessage(this, sprintf('Zoom level: %.1f.', this.GUI.di.zoomLevel), 'yellow');
% start/stop camera
case 'c';
DIStartStopCamera(this, 'toggle');
showMessage(this, sprintf('Camera running: %s', get(this.GUI.di.camHandle, 'Running')), 'yellow');
% start/stop activity
case 'a';
this.GUI.di.activityRunning = ~this.GUI.di.activityRunning;
if this.GUI.di.activityRunning;
this.GUI.di.actiMovieIndex = this.GUI.di.actiMovieIndex + 1;
if this.GUI.di.actiMovieIndex > numel(this.GUI.di.actiMovies); this.GUI.di.actiMovieIndex = 1; end;
end;
showMessage(this, sprintf('Activity movie: %s', iff(this.GUI.di.activityRunning, 'on', 'off')), 'yellow');
% lock mouse
case 'l';
this.di.lockMouse = ~this.di.lockMouse;
showMessage(this, sprintf('Locking mouse: %s', iff(this.di.lockMouse, 'on', 'off')), 'yellow');
% trial phases:
% reset
case '0';
this.di.iTrial = 0;
this.di.iStimMat = randi(10);
this.di.targetStim = randi(2);
showMessage(this, sprintf('Reset trials, iTrial: %d, iStimMat: %d, target stimulus: %d.', ...
this.di.iTrial, this.di.iStimMat, this.di.targetStim), 'yellow');
% new trial
case '1';
set(this.GUI.handles.di.messBox, 'String', 'Trial start ...', 'Background', 'yellow');
set(this.GUI.handles.di.messBoxBack, 'Background', 'yellow');
this.di.iTrial = this.di.iTrial + 1;
showMessage(this, sprintf('Current trial: %d.', this.di.iTrial), 'yellow');
% present stimulus
case '2';
set(this.GUI.handles.di.messBox, 'String', 'Stimulus ...', 'Background', 'yellow');
set(this.GUI.handles.di.messBoxBack, 'Background', 'yellow');
stimNum = this.di.stimMatrix(this.di.iTrial, this.di.iStimMat);
isTarget = stimNum == this.di.targetStim;
showMessage(this, sprintf('Stimulus index for trial %d: %d, target: %d.', this.di.iTrial, stimNum, isTarget), 'yellow');
% get decision
case '3';
this.di.waitingForResp = true;
this.di.waitingStartTime = nowUNIX;
this.di.resp = false;
set(this.GUI.handles.di.messBox, 'String', 'Decision ...', 'Background', 'yellow');
set(this.GUI.handles.di.messBoxBack, 'Background', 'yellow');
stimNum = this.di.stimMatrix(this.di.iTrial, this.di.iStimMat);
isTarget = stimNum == this.di.targetStim;
showMessage(this, sprintf('Trial %d: stimulus %d, target: %d - waiting for decision ...', this.di.iTrial, stimNum, isTarget), 'yellow');
% reward
case '4';
this.di.waitingForResp = false;
set(this.GUI.handles.di.messBox, 'String', 'Reward !', 'Background', 'green');
set(this.GUI.handles.di.messBoxBack, 'Background', 'green');
showMessage(this, 'Reward', 'yellow');
% punishment
case '5';
this.di.waitingForResp = false;
set(this.GUI.handles.di.messBox, 'String', 'Punishment !', 'Background', 'red');
set(this.GUI.handles.di.messBoxBack, 'Background', 'red');
showMessage(this, 'Punishment', 'yellow');
end;
end;
end;
end;
%% -- #mouseDown
function mouseDown(this, ~, ~)
currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};
switch currentMode;
case 'TrialView';
% get selection type (mouse button)
selType = get(this.GUI.figH, 'SelectionType');
% get clicked object
clickedObj = get(this.GUI.figH, 'CurrentObject');
if isa(clickedObj, 'matlab.graphics.axis.Axes') || ...
(~isa(get(clickedObj, 'Parent'), 'matlab.graphics.primitive.Group') ...
&& (isa(clickedObj, 'matlab.graphics.chart.primitive.Line') ...
|| isa(clickedObj, 'matlab.graphics.primitive.Patch') ...
|| isa(clickedObj, 'matlab.graphics.primitive.Text')));
% left click
if strcmp(selType, 'normal');
this.GUI.tv.mouseDownOnAxe = true;
end;
end;
case 'JointTracker';
% make sure the click is within the axe image and not during a ROI drawing
pos = get(this.GUI.handles.jt.axe, 'CurrentPoint');
pos = pos(1, 1 : 2);
XLim = get(this.GUI.handles.jt.axe, 'XLim');
YLim = get(this.GUI.handles.jt.axe, 'YLim');
if this.GUI.jt.selectingROI || any(pos < 0) || pos(1) > XLim(2) || pos(2) > YLim(2);
return;
end;
if isempty(this.GUI.jt.placeJointIndex) && isempty(this.GUI.jt.moveJointIndex);
selectionType = get(this.GUI.figH, 'SelectionType');
JTJointClickStart(this, strcmp(selectionType, 'extend'));
end;
end;
end;
%% -- #mouseUp
function mouseUp(this, h, e)
currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};
switch currentMode;
case 'TrialView';
% get selection type (mouse button)
selType = get(this.GUI.figH, 'SelectionType');
% get clicked object
clickedObj = get(this.GUI.figH, 'CurrentObject');
if isa(clickedObj, 'matlab.graphics.axis.Axes') || ...
(~isa(get(clickedObj, 'Parent'), 'matlab.graphics.primitive.Group') ...
&& (isa(clickedObj, 'matlab.graphics.chart.primitive.Line') ...
|| isa(clickedObj, 'matlab.graphics.primitive.Patch') ...
|| isa(clickedObj, 'matlab.graphics.primitive.Text')));
% left click
if strcmp(selType, 'normal');
this.GUI.tv.mouseDownOnAxe = false;
% right click
elseif strcmp(selType, 'alt');
OCIA_trialview_addMovePoint(this);
end;
elseif isa(clickedObj, 'matlab.graphics.primitive.Image') && clickedObj == this.GUI.handles.tv.wf.img ...
&& ~this.GUI.tv.mouseDownOnWFImg;
OCIA_trialview_drawROI(this);
elseif isa(clickedObj, 'matlab.graphics.primitive.Image') && clickedObj == this.GUI.handles.tv.behav.img ...
&& ~this.GUI.tv.mouseDownOnWFImg;
OCIA_trialview_drawROI(this, this.GUI.handles.tv.behav.axe);
end;
case 'ROIDrawer';
RDUpdateGUI(this, h, e);
case 'Behavior';
BEChangePiezoThresh(this, 'mouseAdjust', []);
case 'JointTracker';
% make sure the click is within the axe image and not during a ROI drawing
pos = get(this.GUI.handles.jt.axe, 'CurrentPoint');
pos = pos(1, 1 : 2);
XLim = get(this.GUI.handles.jt.axe, 'XLim');
YLim = get(this.GUI.handles.jt.axe, 'YLim');
if this.GUI.jt.selectingROI || any(pos < 0) || pos(1) > XLim(2) || pos(2) > YLim(2);
return;
end;
% process the click event
JTImClick(this, h, e);
% reset the joint tracking/moving settings
this.GUI.jt.placeJointIndex = [];
this.GUI.jt.moveJointIndex = [];
this.GUI.jt.startFrame = [];
this.GUI.jt.endFrame = [];
this.GUI.jt.startTime = [];
% remove manual tracking
set(this.GUI.handles.jt.manuTrack, 'Value', 0);
case 'Discriminator';
this.di.nResps = this.di.nResps + 0.75;
end;
end;
%% -- #mouseMoved
function mouseMoved(this, ~, e)
currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};
switch currentMode;
case 'TrialView';
if this.GUI.tv.mouseDownOnAxe;
% get clicked object
clickedObj = get(this.GUI.figH, 'CurrentObject');
if isa(clickedObj, 'matlab.graphics.axis.Axes') || ...
(~isa(get(clickedObj, 'Parent'), 'matlab.graphics.primitive.Group') ...
&& (isa(clickedObj, 'matlab.graphics.chart.primitive.Line') ...
|| isa(clickedObj, 'matlab.graphics.primitive.Patch') ...
|| isa(clickedObj, 'matlab.graphics.primitive.Text')));
OCIA_trialview_changeFrame(this, clickedObj, e);
end;
end;
case 'JointTracker';
coords = get(this.GUI.handles.jt.axe, 'CurrentPoint');
coords = round(coords(1, 1 : 2));
if all(coords > 0) && coords(1) < size(this.GUI.jt.img, 2) && coords(2) < size(this.GUI.jt.img, 1);
this.GUI.jt.mouseCoords = coords;
% update the frame label
currTimeTotSec = this.GUI.jt.iFrame / this.jt.frameRate;
currTimeMin = floor(currTimeTotSec / 60);
currTimeSec = floor(currTimeTotSec - currTimeMin * 60);
currTimeMSec = floor((currTimeTotSec - currTimeMin * 60 - currTimeSec) * 1000);
set(this.GUI.handles.jt.frameLabel, 'String', sprintf('F %03d\nT %02d:%02d.%03d\nM %04d %04d', ...
this.GUI.jt.iFrame, currTimeMin, currTimeSec, currTimeMSec, coords));
end;
end;
end;
%% -- #windowResized
function windowResized(this, ~, ~)
% if no GUI, skip the resizing
if ~isGUI(this); return; end;
% store old position
oldPos = this.GUI.pos;
% update to new position
this.GUI.pos = get(this.GUI.figH, 'Position');
% calculate ratios
widthRatio = oldPos(3) / this.GUI.pos(3);
% heightRatio = oldPos(4) / this.GUI.pos(4);
% update the font size and the columns widths of the DataWatcher's table
columnWidths = get(this.GUI.handles.dw.table, 'ColumnWidth');
columnWidths = num2cell(cellfun(@(w)round(w / widthRatio), columnWidths));
set(this.GUI.handles.dw.table, 'ColumnWidth', columnWidths, 'FontSize', max(min(this.GUI.pos(3) / 170, 22), 8));
end;
end % end methods
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
RDSelROI.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/@OCIA/RDSelROI.m
| 3,644 |
utf_8
|
0361eb322847a59f38e2c2b6c30702ff
|
%% #OCIA:RD:RDSelROI
function RDSelROI(this, varargin)
o('#RDSelROI()', 4, this.verb);
h = []; % no handle by default
% get the handle if there is any
if nargin > 1; h = varargin{1}; end;
% if change was requested by a number, overwrite the selection
if ~isempty(h) && isnumeric(h) && ~ishandle(h);
selROIs = h;
% if change was requested by a string or cell-array of strings, overwrite the selection
elseif ~isempty(h) && (ischar(h) || iscellstr(h));
if ischar(h); h = { h }; end;
if strcmp(get(this.GUI.figH, 'SelectionType'), 'extend');
selROIs = [str2double(h), RDGetSelectedROIs(this, this.GUI.handles.rd.selROIsList)];
else
selROIs = str2double(h);
end;
selROIs(isnan(selROIs)) = [];
% if a clearing of the selection was requested, empty selection
elseif ~isempty(h) && h == this.GUI.handles.rd.selROISetterClear;
selROIs = [];
% if selection was requested by the edit field
elseif ~isempty(h) && ((h == this.GUI.handles.rd.selROI) || (h == this.GUI.handles.rd.selROISetter));
selROIs = RDGetSelectedROIs(this, h);
% otherwise use selection with the list
else
selROIs = RDGetSelectedROIs(this, this.GUI.handles.rd.selROIsList);
end;
o('#RDSelROI(): h: %d, selectedROIs: %s .', h, num2str(selROIs), 3, this.verb);
% update the color of the ROIs
for iROI = 1 : this.rd.nROIs;
if ismember(iROI, selROIs);
this.rd.ROIs{iROI, 1}.setColor('red');
if ishandle(this.rd.ROIs{iROI, 5}) && strcmp(get(this.rd.ROIs{iROI, 1}, 'Visible'), 'off');
set(this.rd.ROIs{iROI, 5}, 'Color', 'blue');
end;
else
this.rd.ROIs{iROI, 1}.setColor('blue');
if ishandle(this.rd.ROIs{iROI, 5}) && strcmp(get(this.rd.ROIs{iROI, 1}, 'Visible'), 'off');
set(this.rd.ROIs{iROI, 5}, 'Color', 'red');
end;
end;
end;
% if no ROIs, no selection text
if isempty(selROIs);
selROIsText = '';
% otherwise create the selection text
else
% start with the first number
selROIsText = sprintf('%s', this.rd.ROIs{selROIs(1), 2});
inRange = false; % determines if we are currently in a range display (1 : ...)
for iSel = 2 : numel(selROIs); % go through all numbers starting from the second
% get the ROI numbers
currROI = this.rd.ROIs{selROIs(iSel), 2};
prevROI = this.rd.ROIs{selROIs(iSel - 1), 2};
% if we are not in range and next number is just previous + 1, then start a range display
if str2double(currROI) - 1 == str2double(prevROI) && ~inRange;
selROIsText = sprintf('%s:', selROIsText);
inRange = true;
% if we are in range and next number is just previous + 1, do not display number and continue range
elseif str2double(currROI) - 1 == str2double(prevROI) && inRange;
% skip number
% if next number is not just previous + 1, then eventually finish range display and display number
else
% if we were in range, finish range display of last number
if inRange;
selROIsText = sprintf('%s%s', selROIsText, prevROI);
end
% display next number
selROIsText = sprintf('%s,%s', selROIsText, currROI);
inRange = false;
end;
end;
% if we are still in range display, it means last number could not be displayed, so display it
if inRange;
selROIsText = sprintf('%s%s', selROIsText, currROI);
end;
end;
% re-update the selection
set(this.GUI.handles.rd.selROISetter, 'String', strrep(selROIsText, '00', ''));
set(this.GUI.handles.rd.selROIsList, 'Value', selROIs);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_genStimVect_fromAnalogInWideField.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromAnalogInWideField.m
| 15,569 |
utf_8
|
db650f76208ac994600bd0dc7f54800a
|
%% #OCIA:AN:OCIA_genStimVect_fromAnalogInWideField
function [isValid, unvalidReason] = OCIA_genStimVect_fromAnalogInWideField(this, iDWRow, varargin)
% get whether to do plots or not
if nargin > 2; doPlotsTrig = varargin{1}; doPlotsMicr = varargin{1}; doPlotsSummary = varargin{1}; %#ok<NASGU>
elseif nargin > 3; doPlotsTrig = varargin{1}; doPlotsMicr = varargin{2}; doPlotsSummary = 0; %#ok<NASGU>
else doPlotsTrig = 0; doPlotsMicr = 0; doPlotsSummary = 0; %#ok<NASGU>
end;
rowID = DWGetRowID(this, iDWRow); % get the row ID
isValid = true; % by default, the row is valid
unvalidReason = ''; % by default no reason
o('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);
% get the behavior data for this row
behavData = getData(this, iDWRow, 'wfTrBehav', 'data');
% if no behavior data is found, abort
if isempty(behavData);
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf('cannot find associated behavior data (behavior data unavailable in row %03d)', iDWRow);
return; % abort processing of this row
end;
iTrial = str2double(get(this, iDWRow, 'runNum')); % get the trial number
% if no behavior row found using the behavior ID, abort
if isempty(iTrial) || isnan(iTrial) || iTrial <= 0;
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf('bad trial number ("%s" => %d")', get(this, iDWRow, 'runNum'), iTrial);
return; % abort processing of this row
end;
% fix missing fields
if isfield(behavData, 'nTones');
% if more than one element for nTones, there must be one element per trial
if numel(behavData.nTones) > 1; nTones = behavData.nTones(iTrial);
% otherwise there is only one constant number of tones
else nTones = behavData.nTones;
end;
% if no field, assume there is only one tone
else nTones = 1;
end;
%% init the stim vector
imgDim = str2dim(get(this, iDWRow, 'dim'));
% compensate for the skipped frames
if numel(imgDim) < 3; nFramesImg = 0;
else nFramesImg = imgDim(3);
end;
% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)
stimVect = zeros(1, nFramesImg);
% string storing the stimulus types for this row
stimTypes = '';
% cell-array storing the relevant time points for the imaging
stimTimeFrames = {};
% initialize variables
imgFrameRate = 20;
% calculate the number of bits to encode
nMaxStimTimes = 10; nBitsToUseForStimTimes = ceil(log2(nMaxStimTimes));
% assign bits to difference encodings
iBitTime = 1 : nBitsToUseForStimTimes; iBitCloud = iBitTime(end) + (1 : 2); iBitTarg = iBitCloud(end) + (1 : 2);
iBitResp = iBitTarg(end) + (1 : 2); iBitCorr = iBitResp(end) + (1 : 2);
%% delay analysis (trig)
trigData = behavData.analogInData(strcmp(behavData.analogInNames, 'trig'), :); % extract the triger's trace
normThresh = 3 * std(trigData(1 : 100)); % take the first frames for normalization threshold
trigData(abs(trigData) < normThresh) = 0; % normalize to remove the noise of parts when there is no trigger
trigTop = find(trigData > 0); % find all the peaks
% get the trigger delay
anInSampRate = behavData.analogInSampRate;
trigInd = trigTop(1);
trigDelay = trigInd / anInSampRate;
% store the extracted number: analog input sampling rate, trigger delay
behavData.behavSampRate = anInSampRate;
behavData.trigDelay = trigDelay;
% if doPlotsTrig > 0; % if requested, plot a figure illustrating the extraction procedure
% figure('Name', sprintf('%s_trig', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');
% plot(trigData, 'k');
% hold on;
% scatter(trigTop(1), trigData(trigTop(1)), 200, 'b');
% title(sprintf('trigDelay: %.3f', trigDelay));
% end;
%% sound start (stimulus time) analysis (micr)
% get the number of samples
nSamples = size(behavData.analogInData, 2);
% extract the stimulus sound time and duration from the recorded sound
micr = linScale(abs(behavData.analogInData(strcmp(behavData.analogInNames, 'micr'), :)));
% get a range for the begining of the signal
begRange = round(nSamples * 0.01 : nSamples * 0.1);
% incrementally search for the right threshold
nSoundsDiff = 1; soundYThresh = 0; soundThreshFactor = 5; soundThreshFactorStep = 5; nLoops = 0; %#ok<NASGU>
while nSoundsDiff && soundThreshFactor < 55;
% get a threshold for the sound onset
soundThreshFactor = soundThreshFactor + soundThreshFactorStep;
soundYThresh = soundThreshFactor * std(micr(begRange));
% get the samples that exceeds the threshold, adding the first sample to catch the start of the first sound
upSamples = [0 find(micr > soundYThresh)];
% get the derivative of the upSamples, drops in the sample indexes indicate interruption of upSamples,
% which means that there is a sound start
upSamplesDiff = diff(upSamples);
% use the ISI to find peaks. If no ISI, use 0.5 second
ISI = 0.5;
if isfield(behavData, 'ISI') && behavData.ISI > 0;
ISI = behavData.ISI;
end;
% difference between detected upSample derivative's peaks must be at least half of the ISI
minISI = ISI * 0.5 * anInSampRate;
% get the index of the peaks where the derivative exceeds the ISI threshold and increment by one to get
% the sound start index
soundStartInds = upSamples(find(upSamplesDiff >= minISI) + 1);
if ~isempty(soundStartInds);
% calculate the sound start time
soundStartTimes = soundStartInds / anInSampRate;
else
soundStartTimes = [];
end;
% check whether there is a big frame difference between the imaging and the behavior recording
nSoundsDiff = abs(nTones - numel(soundStartTimes));
nLoops = nLoops + 1;
end;
% if there is a mismatch in the number of sounds found and more sounds were found, show a warning
if nSoundsDiff && ~isempty(soundStartTimes) && numel(soundStartTimes) >= nTones;
showWarning(this, sprintf('OCIA:%s:MissingStim', mfilename()), ...
sprintf(['Problem with number of stimuli found for %s (%d)! Number of stim detected in recorded ', ...
'data: %d, expected number of stim: %d. Taking only the first %d stim(s).'], rowID, iDWRow, ...
numel(soundStartTimes), nTones, nTones));
soundStartTimes = soundStartTimes(1 : nTones);
doPlotsMicr = doPlotsMicr + 1; %#ok<NASGU>
% if there is a mismatch in the number of sounds found and less sounds were found, show a warning
elseif nSoundsDiff;
showWarning(this, sprintf('OCIA:%s:MissingStim', mfilename()), ...
sprintf(['Problem with number of stimuli found for %s (%d)! Number of stim detected in recorded ', ...
'data: %d, expected number of stim: %d.'], rowID, iDWRow, numel(soundStartTimes), nTones));
doPlotsMicr = doPlotsMicr + 1; %#ok<NASGU>
end;
% get the stimulus time, including the imaging start delay
soundStartTimesImgReference = soundStartTimes - trigDelay;
soundStartIndexesImgReference = round(soundStartTimesImgReference * imgFrameRate); % get the stimulus index
% remove stim start times that are too early
if any(soundStartIndexesImgReference < 0);
nRemStims = sum(soundStartIndexesImgReference < 0);
soundStartIndexesImgReference(soundStartIndexesImgReference <= 0) = [];
showWarning(this, sprintf('OCIA:%s:EarlyStim', mfilename()), ...
sprintf('Removed %d early stimuli found for %s (%d)!', nRemStims, rowID, iDWRow));
end;
% store the starting time
behavData.soundStartTime = soundStartTimes;
% encode the sound end stimulus
soundEndTimesImgReference = soundStartTimesImgReference + behavData.stimDur;
soundEndIndexesImgReference = round(soundEndTimesImgReference * imgFrameRate); % get the stimulus index
% if doPlotsMicr > 0; % if requested, plot a figure illustrating the extraction procedure
% figure('Name', sprintf('%s_micr', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');
% rectangle('Position', [begRange(1) 0 begRange(end) - begRange(1) soundYThresh * 1.1], ...
% 'FaceColor', [0.8 1 0.8], 'EdgeColor', [0.8 1 0.8]);
% hold on;
% plot(micr, 'k');
% yLims = get(gca, 'YLim'); xLims = get(gca, 'XLim');
% plot(upSamples(1 : end - 1) - 0.5, (upSamplesDiff / max(upSamplesDiff)) * max(micr) * 0.9, 'r');
% plot(repmat(soundStartInds, 2, 1), repmat(yLims, numel(soundStartInds), 1)', 'r:');
% plot(xLims, repmat(soundYThresh, 2, 1), 'g:');
% title(sprintf('stimYThresh: %.5f, stimStartTimes: %s', soundYThresh, sprintf(' %.2fs', soundStartTimes)));
% end;
%% other stim times based one behavior recording
% get the light time, including the imaging start delay
if isfield(behavData, 'trialStartCue') && ~isnan(behavData.trialStartCue);
trialStartCueImgReference = behavData.soundStartTime - trigDelay + (behavData.trialStartCue - behavData.soundTime);
stimStartIndexesImgReference = round(trialStartCueImgReference * imgFrameRate); % get the stimulus index
if stimStartIndexesImgReference <= nFramesImg;
stimTimeFrames{end + 1} = stimStartIndexesImgReference;
end;
end;
% add the sound stimulus frames
stimTimeFrames{end + 1} = soundStartIndexesImgReference;
stimTimeFrames{end + 1} = soundEndIndexesImgReference;
% REMOVED BECAUSE NOT ACCURATE
% get the response time, including the imaging start delay
% if isfield(behavData, 'respTime') && ~isnan(behavData.respTime);
% respTimeImgReference = behavData.soundStartTime - trigDelay + (behavData.respTime - behavData.soundTime);
% stimStartIndexesImgReference = round(respTimeImgReference * imgFrameRate); % get the stimulus index
% if stimStartIndexesImgReference <= nFramesImg;
% stimTimeFrames{end + 1} = stimStartIndexesImgReference;
% end;
% end;
% get the response window light cue time, including the imaging start delay
if isfield(behavData, 'lightTime') && ~isnan(behavData.lightTime);
lightCueTimeImgReference = behavData.soundStartTime - trigDelay + (behavData.lightTime - behavData.soundTime);
stimStartIndexesImgReference = round(lightCueTimeImgReference * imgFrameRate); % get the stimulus index
if stimStartIndexesImgReference <= nFramesImg;
stimTimeFrames{end + 1} = stimStartIndexesImgReference;
end;
end;
%% encode the stimuli
if ~isempty(stimTimeFrames);
% go through each stim time
for iStimTime = 1 : numel(stimTimeFrames);
% encode the stimulus time: get the bit code for each stimulus time
bitCode = bitget(1, 1 : nBitsToUseForStimTimes);
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUseForStimTimes;
% annotate with the stimuli with the current bit iteratively
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitTime(iBitLoop), bitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'time');
end;
% annotate the stimulus time with the cloud type using the next bit
soundType = double(behavData.stim == 1);
soundTypeBitCode = bitget(1 + soundType, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitCloud(iBitLoop), soundTypeBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'freq');
end;
% annotate the stimulus time with the target/non-target using the next bit
isTarget = double(~isempty(behavData.target) && behavData.target == 1);
isTargetBitCode = bitget(1 + isTarget, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitTarg(iBitLoop), isTargetBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'targ');
end;
% annotate the stimulus time with the response / non response using the next bit
isResp = double(~isempty(behavData.resp) && behavData.resp == 1);
isRespBitCode = bitget(1 + isResp, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitResp(iBitLoop), isRespBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'resp');
end;
% annotate the stimulus time with the correct / false using the next bit
isCorrect = double(~xor(isTarget, isResp));
isCorrectBitCode = bitget(1 + isCorrect, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitCorr(iBitLoop), isCorrectBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'corr');
end;
% annotate the stimulus time with the auto / normal using the next bit
isAuto = double(~isempty(behavData.autoReward) && behavData.autoReward == 1);
isAutoBitCode = bitget(1 + isAuto, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitCorr(iBitLoop), isAutoBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'auto');
end;
end;
% clean up the stimTypes string
stimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');
% store the created stimulus vector and the different stimulus types encoding
setData(this, iDWRow, 'stim', 'data', stimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'full');
setData(this, iDWRow, 'stim', 'stimTypes', stimTypes);
end;
% store back the data
setData(this, iDWRow, 'wfTrBehav', 'data', behavData);
%% summary plot
if doPlotsSummary > 0; % if requested, plot a figure illustrating the extraction procedure
figure('Name', sprintf('%s_summary', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');
hold on;
yLims = [- 0.3, 1.2];
% trigger
plot((1 : numel(trigData)) / anInSampRate - trigDelay, linScale(trigData, [-1, 1]), 'k');
plot(repmat(trigTop(1) / anInSampRate - trigDelay, 2, 1), yLims, 'k:');
% microphone
plot((1 : numel(micr)) / anInSampRate - trigDelay, micr, 'g');
plot(repmat(soundStartTimesImgReference, 2, 1), yLims, 'g:');
plot(repmat(soundEndTimesImgReference, 2, 1), yLims, 'g:');
% piezo
lickData = abs(behavData.analogInData(strcmp(behavData.analogInNames, 'piezo'), :)) * 15;
plot((1 : numel(lickData)) / anInSampRate - trigDelay, lickData, 'r');
plot([1, numel(lickData)] / anInSampRate - trigDelay, repmat(behavData.piezoThresh, 2, 1) * 15, 'r:');
if ~exist('respTimeImgReference', 'var'); respTimeImgReference = NaN; end;
plot(repmat(respTimeImgReference, 2, 1), yLims, 'r:');
% light
plot(repmat(trialStartCueImgReference, 2, 1), yLims, 'b:');
if ~exist('lightCueTimeImgReference', 'var'); lightCueTimeImgReference = NaN; end;
plot(repmat(lightCueTimeImgReference, 2, 1), yLims, 'b:');
hold off;
ylim(yLims);
title( { sprintf('trigDelay: %.3f, trialStartCue: %.3f, soundStart: %.3f, soundEnd: %.3f', ...
trigDelay, trialStartCueImgReference, soundStartTimesImgReference, soundEndTimesImgReference), ...
sprintf('lightCue: %.3f, respTime: %.3f, respDelay: %.3f (actual: %.3f)', lightCueTimeImgReference, ...
respTimeImgReference, behavData.respDelay, respTimeImgReference - lightCueTimeImgReference)});
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_genStimVect_fromBehavTextFile.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromBehavTextFile.m
| 5,478 |
utf_8
|
1379c5e1886d23dbf086cae8b1e60820
|
%% #OCIA:AN:OCIA_genStimVect_fromBehavTextFile
function [isValid, unvalidReason] = OCIA_genStimVect_fromBehavTextFile(this, iDWRow, varargin)
% get whether to do plots or not
if nargin > 2; doDebugPlots = varargin{1};
else doDebugPlots = 0;
end;
rowID = DWGetRowID(this, iDWRow); % get the row ID
isValid = true; % by default, the row is valid
unvalidReason = ''; % by default no reason
o('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);
%% init the stim vector
% get the number of skipped frames
nSkippedFrames = this.an.skipFrame.nFramesBegin + this.an.skipFrame.nFramesEnd;
imgDim = str2dim(get(this, iDWRow, 'dim'));
% compensate for the skipped frames
if numel(imgDim) < 3; nFramesImg = 0;
else nFramesImg = imgDim(3) - nSkippedFrames;
end;
% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)
stimVect = zeros(1, nFramesImg);
% string storing the stimulus types for this row
stimTypes = '';
% start bit encoding with bit 1
iBit = 1;
% store temporarly this empty stimulus vector (in case things get stuck later on)
setData(this, iDWRow, 'stim', 'data', stimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'partial');
setData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));
% if no imaging frames, abort
if ~nFramesImg;
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf('no imaging data for row %s %03d (frame number = 0)', rowID, iDWRow);
return; % abort processing of this row
end;
% get the behavior for this row
behavData = getData(this, iDWRow, 'behavExtr', 'data');
% get all possible textures and sort them
runTypes = get(this, 'all', 'runType');
runTypes(cellfun(@isempty, runTypes)) = [];
textureIDs = unique(runTypes);
textureRoughness = str2double(regexprep(textureIDs, '^P', ''));
[~, sortIndex] = sort(textureRoughness);
textureIDs = textureIDs(sortIndex);
% get frame rate
frameRate = this.an.img.defaultFrameRate;
% get the texture index
textureIndex = find(strcmp(textureIDs, regexprep(behavData.stimulus, 'Texture \d ', '')));
% get the decision
if strcmp(behavData.decision , 'Go');
decisionIndex = 1;
elseif strcmp(behavData.decision, 'No Response');
decisionIndex = 2;
elseif strcmp(behavData.decision, 'Inappropriate Response');
decisionIndex = 3;
elseif strcmp(behavData.decision, 'No Go');
decisionIndex = 4;
end;
% get texture's stimulus time and frame number
stimStartTimeTexture = behavData.stimulus_time / 1000;
stimStartFrameTexture = round(stimStartTimeTexture * frameRate);
% adjust for skipped frames
stimStartFrameTexture = stimStartFrameTexture - this.an.skipFrame.nFramesBegin;
% get texture's stimulus time and frame number
stimStartTimeLicking = behavData.reward_time / 1000;
stimStartFrameLicking = round(stimStartTimeLicking * frameRate);
% adjust for skipped frames
stimStartFrameLicking = stimStartFrameLicking - this.an.skipFrame.nFramesBegin;
% if no frame found, abort
if isnan(stimStartFrameTexture);
stimStartFrameTexture = [];
end;
% if no frame found, abort
if isnan(stimStartFrameLicking);
stimStartFrameLicking = [];
end;
% calculate the number of bits required for encoding 8 states (8 textures)
nMaxStims = 8; nBitsToUse = ceil(log2(nMaxStims));
% get the bit code for each stimulus number
bitCode = zeros(nBitsToUse, 1);
bitCode(:, 1) = bitget(textureIndex, 1 : nBitsToUse);
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUse;
% annotate with the stimuli with the current bit iteratively
stimVect(stimStartFrameTexture) = bitset(stimVect(stimStartFrameTexture), iBit, bitCode(iBitLoop, :));
stimTypes = sprintf('%s,%s', stimTypes, 'text_textType');
iBit = iBit + 1;
end;
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUse;
% annotate with the stimuli with the current bit iteratively
stimVect(stimStartFrameLicking) = bitset(stimVect(stimStartFrameLicking), iBit, bitCode(iBitLoop, :));
stimTypes = sprintf('%s,%s', stimTypes, 'lick_textType');
iBit = iBit + 1;
end;
% calculate the number of bits required for encoding 8 states (8 outcomes)
nMaxStims = 8; nBitsToUse = ceil(log2(nMaxStims));
% get the bit code for each stimulus number
bitCode = zeros(nBitsToUse, 1);
bitCode(:, 1) = bitget(decisionIndex, 1 : nBitsToUse);
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUse;
% annotate with the stimuli with the current bit iteratively
stimVect(stimStartFrameTexture) = bitset(stimVect(stimStartFrameTexture), iBit, bitCode(iBitLoop, :));
stimTypes = sprintf('%s,%s', stimTypes, 'text_decision');
iBit = iBit + 1;
end;
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUse;
% annotate with the stimuli with the current bit iteratively
stimVect(stimStartFrameLicking) = bitset(stimVect(stimStartFrameLicking), iBit, bitCode(iBitLoop, :));
stimTypes = sprintf('%s,%s', stimTypes, 'lick_decision');
iBit = iBit + 1;
end;
%% saving the stimulus vector
% clean up the stimTypes string
stimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');
% store the created stimulus vector and the different stimulus types encoding
setData(this, iDWRow, 'stim', 'data', stimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'full');
setData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_genStimVect_noStim.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_noStim.m
| 882 |
utf_8
|
03e130ba77be5a2d529963b4cd2fe64c
|
%% #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn
function [isValid, unvalidReason] = OCIA_genStimVect_noStim(this, iDWRow, varargin)
isValid = true; % by default, the row is valid
unvalidReason = ''; % by default no reason
%% init the stim vector
% get the number of skipped frames
nSkippedFrames = this.an.skipFrame.nFramesBegin + this.an.skipFrame.nFramesEnd;
imgDim = str2dim(get(this, iDWRow, 'dim'));
% compensate for the skipped frames
if numel(imgDim) < 3; nFramesImg = 0;
else nFramesImg = imgDim(3) - nSkippedFrames;
end;
% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)
stimVect = zeros(1, nFramesImg);
% store the extracted items: stimulus vector
setData(this, iDWRow, 'stim', 'data', stimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'full');
setData(this, iDWRow, 'stim', 'stimTypes', '');
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_genStimVect_fromInputArgument.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromInputArgument.m
| 2,411 |
utf_8
|
8cb502bb2a0dfe425818d1461d8d8ff5
|
%% #OCIA:AN:OCIA_genStimVect_fromInputArgument
function [isValid, unvalidReason] = OCIA_genStimVect_fromInputArgument(this, iDWRow, stimVectCellArray, ...
stimTypesCellArray, nMaxStimTypesCellArray)
isValid = true; % by default, the row is valid
unvalidReason = ''; % by default no reason
o('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);
%% creating the stim vector
% start bit encoding with bit 1
iBit = 0;
% initiate final stim vector
finalStimVect = zeros(size(stimVectCellArray{1}));
finalStimTypes = '';
% encode each stimulus type one after the other
for iStimVect = 1 : numel(stimVectCellArray);
currStimVect = stimVectCellArray{iStimVect};
stimIndices = find(currStimVect > 0);
stimValues = currStimVect(stimIndices);
% calculate the number of bits to encode
nMaxStimTypes = nMaxStimTypesCellArray{iStimVect};
nBitsToUseForStimTimes = max(ceil(log2(nMaxStimTypes)), 1);
% assign bits to difference encodings
iBitCurrStimVect = iBit + (1 : nBitsToUseForStimTimes);
iBit = iBit + nBitsToUseForStimTimes;
% encode the stimulus time: get the bit code for each stimulus time
for iInd = 1 : numel(stimIndices);
bitCode = bitget(stimValues(iInd), 1 : nBitsToUseForStimTimes);
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUseForStimTimes;
% annotate with the stimuli with the current bit iteratively
finalStimVect(stimIndices(iInd)) = bitset(finalStimVect(stimIndices(iInd)), iBitCurrStimVect(iBitLoop), ...
bitCode(iBitLoop));
end;
end;
% encode the stimulus type
for iBitLoop = 1 : nBitsToUseForStimTimes;
finalStimTypes = sprintf('%s,%s', finalStimTypes, stimTypesCellArray{iStimVect});
end;
% store temporarly this empty stimulus vector (in case things get stuck later on)
setData(this, iDWRow, 'stim', 'data', finalStimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'partial');
setData(this, iDWRow, 'stim', 'stimTypes', regexprep(finalStimTypes, '^,', ''));
end;
%% saving the stimulus vector
% store the created stimulus vector and the different stimulus types encoding
setData(this, iDWRow, 'stim', 'data', finalStimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'full');
setData(this, iDWRow, 'stim', 'stimTypes', regexprep(finalStimTypes, '^,', ''));
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_genStimVect_fromMicrAnalogIn.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromMicrAnalogIn.m
| 25,627 |
utf_8
|
8fb42ab887a6a62a42ac00cb7eb1782b
|
%% #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn
function [isValid, unvalidReason] = OCIA_genStimVect_fromMicrAnalogIn(this, iDWRow, varargin)
% get whether to do plots or not
if nargin > 2; doPlotsYscan = varargin{1}; doPlotsMicr = varargin{1};
elseif nargin > 3; doPlotsYscan = varargin{1}; doPlotsMicr = varargin{2};
else doPlotsYscan = 0; doPlotsMicr = 0;
end;
rowID = DWGetRowID(this, iDWRow); % get the row ID
isValid = true; % by default, the row is valid
unvalidReason = ''; % by default no reason
o('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);
% get the behavior data for this row
behavData = getData(this, iDWRow, 'behavExtr', 'data');
% if no behavior data is found, abort
if isempty(behavData);
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf('cannot find associated behavior data (behavior data unavailable in row %03d)', iDWRow);
return; % abort processing of this row
end;
iTrial = str2double(get(this, iDWRow, 'runNum')); % get the trial number
% if no behavior row found using the behavior ID, abort
if isempty(iTrial) || isnan(iTrial) || iTrial <= 0;
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf('bad trial number ("%s" => %d")', get(this, iDWRow, 'runNum'), iTrial);
return; % abort processing of this row
end;
% fix missing fields
if isfield(behavData, 'nTones');
% if more than one element for nTones, there must be one element per trial
if numel(behavData.nTones) > 1; nTones = behavData.nTones(iTrial);
% otherwise there is only one constant number of tones
else nTones = behavData.nTones;
end;
% if no field, assume there is only one tone
else nTones = 1;
end;
%% init the stim vector
% get the number of skipped frames
nSkippedFrames = this.an.skipFrame.nFramesBegin + this.an.skipFrame.nFramesEnd;
imgDim = str2dim(get(this, iDWRow, 'dim'));
% compensate for the skipped frames
if numel(imgDim) < 3; nFramesImg = 0;
else nFramesImg = imgDim(3) - nSkippedFrames;
end;
% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)
stimVect = zeros(1, nFramesImg);
% string storing the stimulus types for this row
stimTypes = '';
% initialize variables
imgDelay = NaN;
trueFrameRate = NaN;
% calculate the number of bits to encode
nMaxStimTimes = 10; nBitsToUseForStimTimes = ceil(log2(nMaxStimTimes));
% assign bits to difference encodings
iBitTime = 1 : nBitsToUseForStimTimes; iBitCloud = iBitTime(end) + (1 : 2); iBitTarg = iBitCloud(end) + (1 : 2);
iBitResp = iBitTarg(end) + (1 : 2); iBitCorr = iBitResp(end) + (1 : 2);
% other random bit
iBit = 1;
%% - #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn : delay and true frame rate analysis (yscan)
if ismember('yscan', behavData.analogInNames);
% extract the number of frames from the microscope's y scanner's position
yscan = behavData.analogInData(strcmp(behavData.analogInNames, 'yscan'), :); % extract the y scanner's trace
normThresh = 3 * std(yscan(1 : 1000)); % take the first 1000 frames for normalization threshold
yscan(abs(yscan) < normThresh) = 0; % normalize to remove the noise of parts when scanner is not moving
yscanTopPrctile = prctile(yscan, 80); % set a threshold at the 80th percentile
yscanTop = find(yscan > yscanTopPrctile); % find all the peaks
yscanTopDiff = diff(yscanTop); % get the differential of the peaks to find the real peak
yscanTopDiffPeaks = [find(yscanTopDiff > 1) size(yscanTop, 2)]; % get the peaks
nFramesBehav = size(yscanTopDiffPeaks, 2); % get the number of frames found using the recording of the y scanner
% get the middle part of the frames (20%-80%) to exclude starting and ending artifacts
middleFrames = round(nFramesBehav * 0.2) : round(nFramesBehav * 0.8);
% calculate the true frame rate (based on the y position of the scanner)
if isfield(behavData, 'analogInSampRate'); % if there is a field containing the analog input sampling rate
anInSampRate = behavData.analogInSampRate;
% calculate the true frame rate using the inter-peak interval
trueFrameRate = anInSampRate / mean(diff(yscanTop(yscanTopDiffPeaks(middleFrames))));
% no field containing the analog input rate, figure it out (backward compatibility)
else
% try to find the sampling rate from the two possible values
unknownBehavRate = [3000 3333];
% two possible frame rates
trueFrameRateOptions = unknownBehavRate / mean(diff(yscanTop(yscanTopDiffPeaks(middleFrames))));
% find the closest frame rate to the expected frame rate
[~, closestBehavRateInd] = min(abs(trueFrameRateOptions - 77.67));
% get analog input sampling rate and the true frame rate corresponding to this closest frame rate
anInSampRate = unknownBehavRate(closestBehavRateInd);
trueFrameRate = trueFrameRateOptions(closestBehavRateInd);
% show a warning for this assumption
showWarning(this, 'OCIA:OCIA_genStimVect_fromMicrAnalogIn:NoAnInSampRate', ...
sprintf(['Missing analog in sample rate for %s (%d)! Assuming it was %d Hz (=> true frame rate: ', ...
'%.2f Hz).'], rowID, iDWRow, anInSampRate, trueFrameRate));
end;
% get the imaging delay by substract the time of a single frame from the first y scanner peak
frameLength = round(anInSampRate / trueFrameRate);
firstFrameEndInd = yscanTop(yscanTopDiffPeaks(1));
firstFrameStartInd = firstFrameEndInd - frameLength;
imgDelay = firstFrameStartInd / anInSampRate;
% store the extracted number: analog input sampling rate, imaging delay and true frame rate
behavData.behavSampRate = anInSampRate;
behavData.imgDelay = imgDelay;
behavData.imgFrameRate = trueFrameRate;
% check whether there is a big frame difference between the imaging and the behavior recording
nFrameDiff = nFramesBehav - nFramesImg;
% if there is some imaging data and difference is too big (more than 1 second), abort
if nFramesImg && nFrameDiff > 1 * trueFrameRate;
showWarning(this, 'OCIA:genStimVect:fromMicrAnalogIn:missingFrames', sprintf(['Missing frames in the ', ...
'imaging data: frames from behavior = %d, from imaging = %d (~= %.1f ms difference). Going on ...'], ...
nFramesBehav, nFramesImg, 1000 * nFrameDiff / trueFrameRate));
% change the display color
frameDisplayColor = 'orange';
elseif nFramesImg && nFrameDiff < 0;
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf(['frame number mismatch (frames from behavior: %d, from imaging: %d ', ...
'(~= %.1f ms difference).'], nFramesBehav, nFramesImg, 1000 * nFrameDiff / trueFrameRate);
% change the display color
frameDisplayColor = 'red';
% no frame mismatch
else
% change the display color
frameDisplayColor = 'green';
end;
% add the number of frames from the behavior in the comments
comments = getR(this, iDWRow, 'comments');
if iscell(comments); comments = comments{1}; end;
% clean the HTML away
comments = regexprep(comments, '^<html>', ''); % remove HTML tag
comments = regexprep(comments, '<font[^>]+>', ''); % remove font tags
comments = regexprep(comments, '</font>', ''); % remove font tags
% remove the previous frame number tag
comments = regexprep(comments, '(, )?\d+ frames \(behav\.\)', '');
% add the HTML for a colored frame number comment
comments = sprintf('<html><font color="black">%s%s</font><font color="%s">%d</font><font color="black"> frames (behav.)</font>', comments, ...
iff(isempty(comments), '', ', '), frameDisplayColor, nFramesBehav);
% put back the comments in the table and update the display
set(this, iDWRow, 'comments', comments);
DWUpdateColumnsDisplay(this, iDWRow, { 'comments' }, false);
% if row is not valid, abort processing of this row
if ~isValid; return; end;
if doPlotsYscan > 0; % if requested, plot a figure illustrating the extraction procedure
figure('Name', sprintf('%s_yscan', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');
plot(yscan, 'k');
title(sprintf('nFramesBehav: %d, nFramesImag: %d', nFramesBehav, nFramesImg));
hold on;
yLims = get(gca, 'YLim');
plot(yscanTop, yscan(yscanTop), 'g');
plot(yscanTop(1 : end - 1) + 0.5, yscanTopDiff / 100, 'r');
plot(repmat(firstFrameStartInd, 2, 1), yLims, 'r:');
scatter(yscanTop(yscanTopDiffPeaks), repmat(0.8, nFramesBehav, 1), 'b*');
end;
end; % end check yscan exists
%% - #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn : sound start (stimulus time) analysis (micr)
if ismember('micr', behavData.analogInNames);
% get the number of samples
nSamples = size(behavData.analogInData, 2);
% extract the stimulus sound time and duration from the recorded sound
micr = linScale(abs(behavData.analogInData(strcmp(behavData.analogInNames, 'micr'), :))); % extract the microphone's trace
% get a range for the begining of the signal
begRange = round(nSamples * 0.01 : nSamples * 0.1);
% incrementally search for the right threshold
nSoundsDiff = 1; soundYThresh = 0; soundThreshFactor = 5; soundThreshFactorStep = 5; nLoops = 0;
while nSoundsDiff && soundThreshFactor < 55;
% get a threshold for the sound onset
soundThreshFactor = soundThreshFactor + soundThreshFactorStep;
soundYThresh = soundThreshFactor * std(micr(begRange));
% get the samples that exceeds the threshold, adding the first sample to catch the start of the first sound
upSamples = [0 find(micr > soundYThresh)];
% get the derivative of the upSamples, drops in the sample indexes indicate interruption of upSamples,
% which means that there is a sound start
upSamplesDiff = diff(upSamples);
% use the ISI to find peaks. If no ISI, use 0.5 second
ISI = 0.5;
if isfield(behavData, 'ISI') && behavData.ISI > 0;
ISI = behavData.ISI;
end;
% difference between detected upSample derivative's peaks must be at least half of the ISI
minISI = ISI * 0.5 * anInSampRate;
% get the index of the peaks where the derivative exceeds the ISI threshold and increment by one to get
% the sound start index
soundStartInds = upSamples(find(upSamplesDiff >= minISI) + 1);
if ~isempty(soundStartInds);
% calculate the sound start time
soundStartTimes = soundStartInds / anInSampRate;
else
soundStartTimes = [];
end;
% check whether there is a big frame difference between the imaging and the behavior recording
nSoundsDiff = abs(nTones - numel(soundStartTimes));
nLoops = nLoops + 1;
end;
% if there is a mismatch in the number of sounds found and more sounds were found, show a warning
if nSoundsDiff && ~isempty(soundStartTimes) && numel(soundStartTimes) >= nTones;
showWarning(this, 'OCIA:OCIA_genStimVect_fromMicrAnalogIn:MissingStim', ...
sprintf(['Problem with number of stimuli found for %s (%d)! Number of stim detected in recorded ', ...
'data: %d, expected number of stim: %d. Taking only the first %d stim(s).'], rowID, iDWRow, ...
numel(soundStartTimes), nTones, nTones));
soundStartTimes = soundStartTimes(1 : nTones);
doPlotsMicr = doPlotsMicr + 1;
% if there is a mismatch in the number of sounds found and less sounds were found, show a warning
elseif nSoundsDiff;
showWarning(this, 'OCIA:OCIA_genStimVect_fromMicrAnalogIn:MissingStim', ...
sprintf(['Problem with number of stimuli found for %s (%d)! Number of stim detected in recorded ', ...
'data: %d, expected number of stim: %d.'], rowID, iDWRow, numel(soundStartTimes), nTones));
doPlotsMicr = doPlotsMicr + 1;
end;
% if there is some imaging data and some sound start, create the simulus vector
if nFramesImg && ~isempty(soundStartTimes);
% get the stimulus time, including the imaging start delay
soundStartTimesImgReference = soundStartTimes - imgDelay;
stimStartIndexesImgReference = round(soundStartTimesImgReference * trueFrameRate); % get the stimulus index
% remove stim start times that are too early
if any(stimStartIndexesImgReference < 0);
nRemStims = sum(stimStartIndexesImgReference < 0);
stimStartIndexesImgReference(stimStartIndexesImgReference <= 0) = [];
showWarning(this, 'OCIA:OCIA_genStimVect_fromMicrAnalogIn:EarlyStim', ...
sprintf('Removed %d early stimuli found for %s (%d)!', nRemStims, rowID, iDWRow));
end;
%% annotate stimulus frames
% if this is an cloud of tone discrimination task
if strcmp(behavData.taskType, 'cotDiscr');
% encode the sound start stimulus
stimTimeFrames = { stimStartIndexesImgReference };
% go through each stim time
for iStimTime = 1 : numel(stimTimeFrames);
% encode the stimulus time: get the bit code for each stimulus time
bitCode = bitget(1, 1 : nBitsToUseForStimTimes);
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUseForStimTimes;
% annotate with the stimuli with the current bit iteratively
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitTime(iBitLoop), bitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'time');
end;
% annotate the stimulus time with the cloud type using the next bit
soundType = double(behavData.stim == 1);
soundTypeBitCode = bitget(1 + soundType, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitCloud(iBitLoop), soundTypeBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'cloud');
end;
% annotate the stimulus time with the target/non-target using the next bit
isTarget = double(~isempty(behavData.target) && behavData.target == 1);
isTargetBitCode = bitget(1 + isTarget, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitTarg(iBitLoop), isTargetBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'targ');
end;
% annotate the stimulus time with the response / non response using the next bit
isResp = double(~isempty(behavData.resp) && behavData.resp == 1);
isRespBitCode = bitget(1 + isResp, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitResp(iBitLoop), isRespBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'resp');
end;
% annotate the stimulus time with the correct / false using the next bit
isCorrect = double(~xor(isTarget, isResp));
isCorrectBitCode = bitget(1 + isCorrect, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitCorr(iBitLoop), isCorrectBitCode(iBitLoop));
stimTypes = sprintf('%s,%s', stimTypes, 'corr');
end;
end;
% if this is an oddball experiment with the right number of sounds
elseif strcmp(behavData.taskType, 'cotOdd') && isfield(behavData, 'oddPos') && numel(stimStartIndexesImgReference) >= behavData.oddPos;
% annotate with 1 on the first bit to mark it as stimulus frame
stimVect(stimStartIndexesImgReference) = bitset(stimVect(stimStartIndexesImgReference), iBit, 1);
stimTypes = sprintf('%s,%s', stimTypes, 'stim');
iBit = iBit + 1;
% calculate the number of bits required for encoding 10 states (10 stimuli)
nStims = numel(stimStartIndexesImgReference); nMaxStims = 10; nBitsToUse = ceil(log2(nMaxStims));
% get the bit code for each stimulus number
bitCode = zeros(nBitsToUse, nStims);
for iStim = 1 : nStims;
bitCode(:, iStim) = bitget(iStim, 1 : nBitsToUse);
end;
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUse;
% annotate with the stimuli with the current bit iteratively
stimVect(stimStartIndexesImgReference) = bitset(stimVect(stimStartIndexesImgReference), iBit, bitCode(iBitLoop, :));
stimTypes = sprintf('%s,%s', stimTypes, 'stimNum');
iBit = iBit + 1;
end;
% annotate with the sound type depending on the standard/odd using the next bit
soundType = behavData.stim == 1;
stimVect(stimStartIndexesImgReference) = bitset(stimVect(stimStartIndexesImgReference), iBit, soundType);
stimVect(stimStartIndexesImgReference(behavData.oddPos)) = bitset(stimVect(stimStartIndexesImgReference(behavData.oddPos)), iBit, ~soundType);
stimTypes = sprintf('%s,%s', stimTypes, 'soundType');
iBit = iBit + 1;
% calculate the number of bits required for encoding 3 states (first, pre-odd, odd)
nStims = numel(stimStartIndexesImgReference); nMaxStims = 3; nBitsToUse = ceil(log2(nMaxStims));
% get the bit code for each stimulus number
bitCode = zeros(nBitsToUse, nStims);
for iStim = 1 : nStims;
% get the stimulus state to encode for this stimulus
if iStim == 1; stimState = 1;
elseif iStim == behavData.oddPos - 1; stimState = 2;
elseif iStim == behavData.oddPos; stimState = 3;
else stimState = 0;
end;
bitCode(:, iStim) = bitget(stimState, 1 : nBitsToUse);
end;
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUse;
% annotate with the stimuli with the current bit iteratively
stimVect(stimStartIndexesImgReference) = bitset(stimVect(stimStartIndexesImgReference), iBit, bitCode(iBitLoop, :));
stimTypes = sprintf('%s,%s', stimTypes, 'oddball');
iBit = iBit + 1;
end;
end;
end;
% clean up the stimTypes string
stimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');
% store the created stimulus vector and the different stimulus types encoding
behavData.soundStartTime = soundStartTimes;
setData(this, iDWRow, 'stim', 'data', stimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'full');
setData(this, iDWRow, 'stim', 'stimTypes', stimTypes);
if doPlotsMicr > 0; % if requested, plot a figure illustrating the extraction procedure
figure('Name', sprintf('%s_micr', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');
rectangle('Position', [begRange(1) 0 begRange(end) - begRange(1) soundYThresh * 1.1], ...
'FaceColor', [0.8 1 0.8], 'EdgeColor', [0.8 1 0.8]);
hold on;
plot(micr, 'k');
yLims = get(gca, 'YLim'); xLims = get(gca, 'XLim');
plot(upSamples(1 : end - 1) - 0.5, (upSamplesDiff / max(upSamplesDiff)) * max(micr) * 0.9, 'r');
plot(repmat(soundStartInds, 2, 1), repmat(yLims, numel(soundStartInds), 1)', 'r:');
plot(xLims, repmat(soundYThresh, 2, 1), 'g:');
title(sprintf('stimYThresh: %.5f, stimStartTimes: %s', soundYThresh, sprintf(' %.2fs', soundStartTimes)));
end;
end; % end check micr exists
%% - #OCIA:AN:OCIA_genStimVect_fromMicrAnalogIn : light cue and response time
if strcmp(behavData.taskType, 'cotDiscr') && ~isnan(imgDelay) && ~isnan(trueFrameRate);
% encode the stimuli
stimTimeFrames = { };
% get the light time, including the imaging start delay
if isfield(behavData, 'lightTime') && ~isnan(behavData.lightTime);
lightTimeImgReference = behavData.soundStartTime - imgDelay + (behavData.lightTime - behavData.soundTime);
stimStartIndexesImgReference = round(lightTimeImgReference * trueFrameRate); % get the stimulus index
if stimStartIndexesImgReference <= nFramesImg;
stimTimeFrames{end + 1} = stimStartIndexesImgReference;
end;
end;
% get the response time, including the imaging start delay
if isfield(behavData, 'respTime') && ~isnan(behavData.respTime);
respTimeImgReference = behavData.soundStartTime - imgDelay + (behavData.respTime - behavData.soundTime);
stimStartIndexesImgReference = round(respTimeImgReference * trueFrameRate); % get the stimulus index
if stimStartIndexesImgReference <= nFramesImg;
stimTimeFrames{end + 1} = stimStartIndexesImgReference;
end;
end;
% get the light off time, including the imaging start delay
if isfield(behavData, 'lightOffTime') && ~isnan(behavData.lightOffTime);
lightOffTimeImgReference = behavData.soundStartTime - imgDelay + (behavData.lightOffTime - behavData.soundTime);
stimStartIndexesImgReference = round(lightOffTimeImgReference * trueFrameRate); % get the stimulus index
if stimStartIndexesImgReference <= nFramesImg;
stimTimeFrames{end + 1} = stimStartIndexesImgReference;
end;
end;
% go through each stim time
for iStimTime = 1 : numel(stimTimeFrames);
% encode the stimulus time: get the bit code for each stimulus time
bitCode = bitget(1 + iStimTime, 1 : nBitsToUseForStimTimes);
% encode the bitCode into the stimulus vector
for iBitLoop = 1 : nBitsToUseForStimTimes;
% annotate with the stimuli with the current bit iteratively
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), iBitTime(iBitLoop), ...
bitCode(iBitLoop));
end;
% annotate the stimulus time with the cloud type using the next bit
soundType = double(behavData.stim == 1);
soundTypeBitCode = bitget(1 + soundType, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitCloud(iBitLoop), soundTypeBitCode(iBitLoop));
end;
% annotate the stimulus time with the target/non-target using the next bit
isTarget = double(~isempty(behavData.target) && behavData.target == 1);
isTargetBitCode = bitget(1 + isTarget, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitTarg(iBitLoop), isTargetBitCode(iBitLoop));
end;
% annotate the stimulus time with the response / non response using the next bit
isResp = double(~isempty(behavData.resp) && behavData.resp == 1);
isRespBitCode = bitget(1 + isResp, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitResp(iBitLoop), isRespBitCode(iBitLoop));
end;
% annotate the stimulus time with the correct / false using the next bit
isCorrect = double(~xor(isTarget, isResp));
isCorrectBitCode = bitget(1 + isCorrect, 1 : 2);
for iBitLoop = 1 : 2;
stimVect(stimTimeFrames{iStimTime}) = bitset(stimVect(stimTimeFrames{iStimTime}), ...
iBitCorr(iBitLoop), isCorrectBitCode(iBitLoop));
end;
end;
% if some stimulus was found
if ~isempty(stimTypes);
% clean up the stimTypes string
stimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');
% store the created stimulus vector and the different stimulus types encoding
setData(this, iDWRow, 'stim', 'data', stimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'full');
setData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));
end;
end;
% store back the data
setData(this, iDWRow, 'behavExtr', 'data', behavData);
% % display message
% showMessage(this, sprintf(['Extracting behavior data for %s (%d) done (frames behav: %d, ', ...
% 'frames img: %d, nStims: %d, nLoops: %d, %3.1f sec).'], rowID, iDWRow, nFramesBehav, ...
% nFramesImg, numel(stimStartTimes), nLoops, toc(behavExtrTic)));
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_genStimVect_fromWhisker.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/genStimVect/OCIA_genStimVect_fromWhisker.m
| 4,088 |
utf_8
|
b073f00c4f340f8c1ab5674eb41e5d5d
|
%% #OCIA:AN:OCIA_genStimVect_fromWhisker
function [isValid, unvalidReason] = OCIA_genStimVect_fromWhisker(this, iDWRow, varargin)
% get whether to do plots or not
if nargin > 2; doDebugPlots = varargin{1};
else doDebugPlots = 0;
end;
rowID = DWGetRowID(this, iDWRow); % get the row ID
isValid = true; % by default, the row is valid
unvalidReason = ''; % by default no reason
o('#%s(): row num: %d ...', mfilename, iDWRow, 3, this.verb);
%% init the stim vector
% get the number of skipped frames
nSkippedFrames = this.an.skipFrame.nFramesBegin + this.an.skipFrame.nFramesEnd;
imgDim = str2dim(get(this, iDWRow, 'dim'));
% compensate for the skipped frames
if numel(imgDim) < 3; nFramesImg = 0;
else nFramesImg = imgDim(3) - nSkippedFrames;
end;
% stimulus vector is all zeros except where there are stimulus starts (sound, lick, spout, etc.)
stimVect = zeros(1, nFramesImg);
% string storing the stimulus types for this row
stimTypes = '';
% start bit encoding with bit 1
iBit = 1;
% store temporarly this empty stimulus vector (in case things get stuck later on)
setData(this, iDWRow, 'stim', 'data', stimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'partial');
setData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));
% if no imaging frames, abort
if ~nFramesImg;
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf('no imaging data for row %s %03d (frame number = 0)', rowID, iDWRow);
return; % abort processing of this row
end;
% get the (eventually down-sampled) whisker traces matrix for the requested rows
whiskTraces = OCIA_analysis_getRawWhiskTracesMatrix(this, iDWRow, true);
% if no whisker data is found, abort
if isempty(whiskTraces);
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf('cannot find whisker data for row %s %03d', rowID, iDWRow);
return; % abort processing of this row
end;
% normalize the traces by their mean
whiskTraces = whiskTraces - nanmean(whiskTraces);
%% Whisker peak
minPeakThresh = 10;
minPeakDist = 5;
[peakValues, stimPeakFrames] = findpeaks(whiskTraces, 'MinPeakHeight', minPeakThresh, 'MinPeakDistance', 15);
% if there are some stimulus, fill the simulus vector
if ~isempty(stimPeakFrames);
% annotate the whisking peak with 1 on the current bit to mark it as stimulus frame
stimVect(stimPeakFrames) = bitset(stimVect(stimPeakFrames), iBit, 1);
stimTypes = sprintf('%s,%s', stimTypes, 'whiskPeak');
iBit = iBit + 1;
% if requested, plot a figure illustrating the extraction procedure
if doDebugPlots > 0;
figure('Name', sprintf('%s_whiskPeak', rowID), 'WindowStyle', 'docked', 'NumberTitle', 'off');
whiskHandle = plot(whiskTraces, 'k');
hold('on');
hScatt = scatter(stimPeakFrames, peakValues, 100, 'rs', 'fill');
yLims = get(gca, 'YLim'); xLims = get(gca, 'XLim');
minPeakHeightHandle = plot(xLims, repmat(minPeakThresh, 2, 1), 'g:');
minPeakDistHandle = plot([stimPeakFrames; stimPeakFrames], repmat(yLims', 1, numel(stimPeakFrames)), 'b:');
plot([stimPeakFrames + minPeakDist; stimPeakFrames + minPeakDist], repmat(yLims', 1, numel(stimPeakFrames)), 'b:');
title(sprintf('minPeakThresh: %.1f, minPeakDist: %.1f', minPeakThresh, minPeakDist));
legend([whiskHandle, hScatt(1), minPeakHeightHandle(1), minPeakDistHandle(1)], ...
'whisker angle', 'peaks', 'minimum peak height threshold', 'minimum inter-peak distance threshold');
end;
end;
%% Other methods ...
%% saving the stimulus vector
% clean up the stimTypes string
stimTypes = regexprep(regexprep(stimTypes, '^,', ''), ',$', '');
% store the created stimulus vector and the different stimulus types encoding
setData(this, iDWRow, 'stim', 'data', stimVect);
setData(this, iDWRow, 'stim', 'loadStatus', 'full');
setData(this, iDWRow, 'stim', 'stimTypes', regexprep(stimTypes, '^,', ''));
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_startFunction_widefieldCreateAveragesForEachCondition.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/startFunctions/OCIA_startFunction_widefieldCreateAveragesForEachCondition.m
| 9,795 |
utf_8
|
eef9147a9768002dbc4259deb36d33ff
|
function OCIA_startFunction_widefieldCreateAveragesForEachCondition(this)
% OCIA_startFunction_widefieldCreateAveragesForEachCondition - [no description]
%
% OCIA_startFunction_widefieldCreateAveragesForEachCondition(this)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% iStartID = 37;
iStartID = 41;
iExcl = []; % iEndID = Inf;
% iEndID = 40;
iEndID = 43;
iTrialStart = 1;
iTrialEnd = Inf;
fixedStartFrame = 60;
% define trial types
% { '4 kHz', '28 kHz', 'miss', 'FA', 'early', 'auto' }
% { 'go', 'nogo', 'miss', 'FA', 'early', 'auto' }
trialTypesRegexp = { 'hit', 'CR', 'quiet', 'moveDur', 'moveBef', ...
'hit_AND_moveDur', 'hit_AND_quiet', 'hit_AND_moveBef', 'hit_AND_[quiet|moveBef]', ...
'CR_AND_moveDur', 'CR_AND_quiet', 'CR_AND_moveBef', 'CR_AND_[quiet|moveBef]' };
trialTypeSaveName = { 'hit', 'CR', 'strict_quiet', 'move', 'early_move', ...
'move_hit', 'strict_quiet_hit', 'early_move_hit', 'delay_quiet_hit', ...
'move_CR', 'strict_quiet_CR', 'early_move_CR', 'delay_quiet_CR' };
%% get all widefield data
OCIAChangeMode(this, 'DataWatcher');
% get the DataWatcher's and the Analyser's GUI handles
dwh = this.GUI.handles.dw;
% set the watch types
set(dwh.watchTypes.animal, 'Value', 1);
set(dwh.watchTypes.day, 'Value', 1);
set(dwh.watchTypes.wfLV, 'Value', 1);
set(dwh.watchTypes.wfLVSess, 'Value', 1);
set(dwh.watchTypes.wfLVMat, 'Value', 0);
set(dwh.watchTypes.wfAn, 'Value', 0);
set(dwh.watchTypes.behav, 'Value', 0);
% set the filters
set(dwh.filt.animalID, 'Value', 1, 'String', { '-' });
set(dwh.filt.dayID, 'Value', 1, 'String', { '-' });
set(dwh.filt.wfLVSessID, 'Value', 1, 'String', { '-' });
set(dwh.filt.rowTypeID, 'Value', 1, 'String', { '-' });
set(dwh.filt.dataLoadStatus, 'Value', 0, 'String', '');
set(dwh.filt.rowNum, 'Value', 0, 'String', '');
set(dwh.filt.runNum, 'Value', 0, 'String', '');
set(dwh.filt.all, 'Value', 0, 'String', '');
% update the table
DWProcessWatchFolder(this);
% set the watch types for processing
set(dwh.watchTypes.wfLVMat, 'Value', 1);
set(dwh.watchTypes.behav, 'Value', 1);
% get triplets
IDs = get(this, 'all', { 'animal', 'day', 'wfLVSess', 'runNum' }, DWFilterTable(this, 'rowType = WFLV session AND wfLVSess ~= \d{6}'));
%% go through each row
for iID = max(iStartID, 1) : min(size(IDs, 1), iEndID);
% do not process excluded IDs
if ismember(iID, iExcl); continue; end;
% get the IDs and set filters
[animalID, dayID, sessID, sessNum] = IDs{iID, :};
set(dwh.filt.animalID, 'Value', 2, 'String', { '-', animalID });
set(dwh.filt.dayID, 'Value', 2, 'String', { '-', dayID });
set(dwh.filt.wfLVSessID, 'Value', 2, 'String', { '-', sprintf('session%s_%s', sessNum, sessID) });
% update the table
DWProcessWatchFolder(this);
% get trial rows
[~, trialRowInds] = DWFilterTable(this, 'rowType = WF trial');
if isempty(trialRowInds);
showWarning(this, sprintf('OCIA:%s:NoTrialIndices', mfilename()), sprintf(...
'Problem with animal %s, day %s, session %s (%s): no trial index.\n', ...
animalID, dayID, sessID, sessNum));
continue;
end;
avgStruct = struct();
trialCountStruct = struct();
DWLoadRow(this, trialRowInds(1), 'full');
dims = str2dim(get(this, trialRowInds(1), 'dim'));
% re-alignment to sound onset required
pathToFirstTrial = get(this, trialRowInds(1), 'path');
stimStartPath = regexprep(pathToFirstTrial, 'stim_trial1\.mat', 'stimStartFrames.mat');
% stimulus start defining file exists
if exist(stimStartPath, 'file');
stimStartFramesMat = load(stimStartPath);
stimStartFrames = stimStartFramesMat.stimStartFrame;
else
stimStartFrames = [];
showWarning(this, sprintf('OCIA:%s:NoStimStartFrames', mfilename()), sprintf(['Problem with animal %s, ', ...
'day %s, session %s (%s): cannot find stim start frames mat file at "%s". Skipping realigning.\n'], ...
animalID, dayID, sessID, sessNum, stimStartPath));
end;
% create average for each condition
for iRow = max(iTrialStart, 1) : min(numel(trialRowInds), iTrialEnd);
iDWRow = trialRowInds(iRow);
% extract info and data for this row
commentsForRow = get(this, iDWRow, 'comments');
iTrial = str2double(get(this, iDWRow, 'runNum'));
% check each trial type for a match
for iTrialType = 1 : numel(trialTypeSaveName);
trialTypeRegexp = trialTypesRegexp{iTrialType};
trialType = trialTypeSaveName{iTrialType};
% trial is a match for this type
if ~isempty(regexp(commentsForRow, trialTypeRegexp, 'once'));
% add to data structure
[avgStruct, trialCountStruct] = addToDataStruct(this, iDWRow, animalID, dayID, sessID, sessNum, ...
stimStartFrames, iTrial, fixedStartFrame, avgStruct, trialType, dims, trialCountStruct);
end;
% multiple trial types required
if ~isempty(regexp(trialTypeRegexp, '_AND_', 'once'));
multiTrialTypes = regexp(trialTypeRegexp, '_AND_', 'split');
matchForEach = cellfun(@(triTy) ~isempty(regexp(commentsForRow, triTy, 'once')), multiTrialTypes);
% all requirements of matching are met
if all(matchForEach);
% add to data structure
[avgStruct, trialCountStruct] = addToDataStruct(this, iDWRow, animalID, dayID, sessID, ...
sessNum, stimStartFrames, iTrial, fixedStartFrame, avgStruct, trialType, ...
dims, trialCountStruct);
end;
end;
end;
% clean up by erasing data for this row
DWFlushData(this, iDWRow, false, 'wfTrIm');
end;
% save the data for each condition
for iTrialType = 1 : numel(trialTypeSaveName);
trialType = trialTypeSaveName{iTrialType};
% abort if no trials of this type
if ~isfield(trialCountStruct, trialType) || trialCountStruct.(trialType) <= 0; continue; end;
% divide by the number of trials
N = trialCountStruct.(trialType);
avgStruct.(trialType).aligned = avgStruct.(trialType).aligned ./ N;
avgStruct.(trialType).unalign = avgStruct.(trialType).unalign ./ N;
% save as "tr_ave" and "N" variable
tr_ave = avgStruct.(trialType).unalign; %#ok<NASGU>
trialPath = get(this, trialRowInds(1), 'path');
save(regexprep(trialPath, 'stim_trial1', sprintf('cond_%s_average', trialType)), 'tr_ave', 'N');
% save as "tr_ave" and "N" variable
tr_ave = avgStruct.(trialType).aligned; %#ok<NASGU>
trialPath = get(this, trialRowInds(1), 'path');
save(regexprep(trialPath, 'stim_trial1', sprintf('cond_%s_average_aligned', trialType)), 'tr_ave', 'N');
end;
end;
end
function [avgStruct, trialCountStruct] = addToDataStruct(this, iDWRow, animalID, dayID, sessID, sessNum, ...
stimStartFrames, iTrial, fixedStartFrame, avgStruct, trialType, dims, trialCountStruct)
% make sur data is loaded
DWLoadRow(this, iDWRow, 'full');
dataForRow = getData(this, iDWRow, 'wfTrIm', 'data');
imgDims = size(dataForRow);
% re-alignment to sound onset required
if ~isempty(stimStartFrames);
% calculate frame shift
stimStartFrameTrial = stimStartFrames(iTrial);
nFramesDiff = fixedStartFrame - stimStartFrameTrial;
if abs(nFramesDiff) > 10;
showWarning(this, sprintf('OCIA:%s:AlignFrameRemoval', mfilename()), sprintf(['Problem with animal %s, ', ...
'day %s, session %s (%s): removing a lot of frames (%d) for realignment ...\n'], ...
animalID, dayID, sessID, sessNum, abs(nFramesDiff)));
end;
% not enough frame before sound
dataForRowUnalign = dataForRow;
if nFramesDiff > 0;
dataForRow = cat(3, nan([imgDims(1:2), nFramesDiff]), dataForRow(:, :, 1 : (end - nFramesDiff)));
% too many frames before sound
elseif nFramesDiff < 0;
dataForRow = cat(3, dataForRow(:, :, (abs(nFramesDiff) + 1) : end), nan([imgDims(1:2), abs(nFramesDiff)]));
end;
% otherwise use nans
else
dataForRowUnalign = nan(dims);
end;
% first trial of this type
if ~isfield(avgStruct, trialType);
avgStruct.(trialType).aligned = zeros(dims);
avgStruct.(trialType).unalign = zeros(dims);
trialCountStruct.(trialType) = 0;
end;
% add average values
avgStruct.(trialType).aligned = avgStruct.(trialType).aligned + dataForRow;
avgStruct.(trialType).unalign = avgStruct.(trialType).unalign + dataForRowUnalign;
% add trial count
trialCountStruct.(trialType) = trialCountStruct.(trialType) + 1;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_analysis_wideField_drawCropRect.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_wideField_drawCropRect.m
| 820 |
utf_8
|
f4f3787ccee041fd8eb5d85d86bace20
|
function OCIA_analysis_wideField_drawCropRect(this, ~, ~)
% OCIA_analysis_wideField_drawCropRect - [no description]
%
% OCIA_analysis_wideField_drawCropRect(this)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% remove previous rectangle
axeChilds = get(this.GUI.handles.an.axe, 'Children');
delete(axeChilds(strcmp(get(axeChilds, 'Tag'), 'imrect')));
% draw the ROI
hROI = imrect(this.GUI.handles.an.axe);
hROI.addNewPositionCallback(@(h)updateCropRect(this, h));
% get position and store it
pos = roundn(hROI.getPosition(), 1);
this.an.wf.cropRect = pos;
% update parameters
ANUpdatePlot(this, 'params');
end
function updateCropRect(this, newCropRect)
this.an.wf.cropRect = roundn(newCropRect, 1);
ANUpdatePlot(this, 'params');
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_analysis_getROIStat.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_getROIStat.m
| 1,842 |
utf_8
|
0108c7662da8e7c25a69f40e48834599
|
% get the grouping from the different variables
function [ROIStat, description] = OCIA_analysis_getROIStat(ROIStatToCalc, respMethod, PSCaTracesStats, ...
stimIDIndexes, stimIDs)
% get the average responsiveness to all trials
ROIResps = reshape(nanmean(PSCaTracesStats.ROIRespTrial, 2), ...
size(PSCaTracesStats.ROIRespTrial, 1), size(PSCaTracesStats.ROIRespTrial, 3));
% select which ROI statistic to analyse
switch ROIStatToCalc;
case 'responsiveness';
ROIStat = ROIResps(stimIDIndexes, :)';
% linearize the matrix
ROIStat = ROIStat(:);
description = sprintf('Responsiveness (%s %%DRR)', respMethod);
case 'response time';
ROIStat = PSCaTracesStats.ROIRespTime(stimIDIndexes, :)';
% linearize the matrix
ROIStat = ROIStat(:);
description = 'Response time (sec)';
case 'SI';
% calculate SI
ROIStat = (ROIResps(stimIDIndexes(2), :) - ROIResps(stimIDIndexes(1), :)) ...
./ (ROIResps(stimIDIndexes(1), :) + ROIResps(stimIDIndexes(2), :));
description = sprintf('SI: %s (neg.) - %s (pos.)', stimIDs{stimIDIndexes});
case 'd''';
% calculate d''
ROIStat = squeeze(...
( ...
nanmean(PSCaTracesStats.ROIRespTrial(stimIDIndexes(2), :, :), 2) ...
- nanmean(PSCaTracesStats.ROIRespTrial(stimIDIndexes(1), :, :), 2) ...
) ...
./ ...
sqrt( ...
0.5 * nanstd(PSCaTracesStats.ROIRespTrial(stimIDIndexes(1), :, :), [], 2) .^ 2 ...
+ 0.5 * nanstd(PSCaTracesStats.ROIRespTrial(stimIDIndexes(2), :, :), [], 2) .^ 2) ...
);
description = sprintf('d'': %s (neg.) - %s (pos.)', stimIDs{stimIDIndexes});
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_analysis_getWhiskVectors.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_getWhiskVectors.m
| 1,996 |
utf_8
|
a3c25dc726e7ecc35017c2d86ec7ff70
|
%% #OCIA:AN:OCIA_analysis_caTraces_whiskvectors
function [WAEnvs, WAAmp, WASetP, WAExpWhisk, WAFovWhisk] = OCIA_analysis_getWhiskVectors(this, ...
rawWhiskTraces, whiskFrameRateCellArray)
nRuns = numel(rawWhiskTraces);
% define frequency bands
Expwhisk_low_frequ = 7; % Hz frequ. band for exploratory whisking
Expwhisk_up_frequ = 12; % Hz
Fovwhisk_low_frequ = 15; % Hz frequ. band for foveal whisking
Fovwhisk_up_frequ = 25; % Hz
EnvWinSize = 0.3; % window size in seconds for envelope and sliding mean/amp calculation
% loop through each run and calculate various whisking angle (WA) variables
WAEnvs = cell(size(rawWhiskTraces)); % envelope (max - min)
WAAmp = cell(size(rawWhiskTraces)); % amplitude (max)
WASetP = cell(size(rawWhiskTraces)); % set point (mean angle)
WAExpWhisk = cell(size(rawWhiskTraces)); % exploratory whisking
WAFovWhisk = cell(size(rawWhiskTraces)); % foveal whisking
parfor iRun = 1 : nRuns;
whiskFrameRate = whiskFrameRateCellArray{iRun};
% calculate the envelope
whiskAngle = rawWhiskTraces{iRun};
nWhiskFrames = size(whiskAngle, 2);
winSize = round(EnvWinSize * whiskFrameRate);
for iFrame = 1 : nWhiskFrames;
r = iFrame - winSize : iFrame + winSize;
r(r < 1 | r > nWhiskFrames) = [];
WAEnvs{iRun}(iFrame) = max(whiskAngle(r)) - min(whiskAngle(r)); % Whisking envelope
WAAmp{iRun}(iFrame) = max(whiskAngle(r)); % Whisking amplitude
WASetP{iRun}(iFrame) = mean(whiskAngle(r)); % Whisker set point
end;
[~, bandpow1, bandpow2] = spectralDensityAnalysis(whiskAngle, 128, 127, 128, whiskFrameRate, ...
Expwhisk_low_frequ, Expwhisk_up_frequ, Fovwhisk_low_frequ, Fovwhisk_up_frequ);
% ...(whiskAngle, windowsiz, overlap, nfft, ...)
WAExpWhisk{iRun} = bandpow1;
WAFovWhisk{iRun} = bandpow2;
end;
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_analysis_getGrouping.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_getGrouping.m
| 5,378 |
utf_8
|
71ab6791a9546bb97c7e85f287c452c3
|
% get the grouping from the different variables
function [grouping, groupLabels] = OCIA_analysis_getGrouping(this, iDWRows, stimIDIndexes, selDispStimIDs, groupBy, ROINames, ROIPhases)
% create the grouping variable
switch groupBy;
case 'ROI';
% remove the ROISet tag
cleanROINames = regexprep(ROINames, 'RS\d+_', '');
uniqueCleanROINames = unique(cleanROINames, 'stable');
% get the grouping from ROISet number
grouping = cellfun(@(ROIName)find(strcmp(ROIName, uniqueCleanROINames)), cleanROINames);
% expand the matrix for the stimulus types
grouping = repmat(grouping, 1, numel(stimIDIndexes));
% linearize the matrix
grouping = grouping(:);
% use the ROINames as group labels
groupLabels = uniqueCleanROINames';
case 'day';
% use the "ROIPhases" cell-array if provided and no DataWatcher row indexes provided
if exist('ROIPhases', 'var') && ~isempty(ROIPhases) && isempty(iDWRows);
% remove the ROISet tag
uniquePhases = unique(ROIPhases, 'stable');
% get the grouping from ROI phase
grouping = cellfun(@(ROIPhase)find(strcmp(ROIPhase, uniquePhases)), ROIPhases);
% expand the matrix for the stimulus types
grouping = repmat(grouping, 1, numel(stimIDIndexes));
% linearize the matrix
grouping = grouping(:);
% use the ROINames as group labels
groupLabels = uniquePhases;
else
% get the grouping from ROISet number
grouping = cellfun(@(ROIName)str2double(regexprep(regexp(ROIName, 'RS\d+_', 'match'), '[^\d]', '')), ROINames);
% get the days from the rows and from the ROISet IDs
allDays = regexprep(unique(get(this, iDWRows, 'day')), '_', '');
allROISetsDays = regexprep(unique(get(this, iDWRows, 'ROISet')), '_\d+$', '');
% re-map the grouping using the actual unique days
for iROISetDay = 1 : numel(allROISetsDays);
grouping(grouping == iROISetDay) = find(strcmp(allROISetsDays{iROISetDay}, allDays));
end;
% expand the matrix for the stimulus types
grouping = repmat(grouping, 1, numel(stimIDIndexes));
% linearize the matrix
grouping = grouping(:);
% use different labels for the day groups
% groupLabels = this.an.img.groupNames(unique(grouping));
groupLabels = allROISetsDays(unique(grouping));
end;
case 'stimType';
% split the stimulus IDs into stimulus ID and PSPerID
splitStimIDs = cell(2, numel(selDispStimIDs));
for iStimType = 1 : numel(selDispStimIDs);
parts = regexp(selDispStimIDs{iStimType}, ' ', 'split');
if numel(parts) > 2;
partsString = regexprep(sprintf('%s-', parts{1 : end - 1}), '-$', '');
parts = [partsString, parts(end)];
end;
splitStimIDs(:, iStimType) = parts;
end;
% extract the unique stimuli / PSPerID
uniqueStims = unique(splitStimIDs(1, :), 'stable');
% create a grouping for each stimulus type
grouping = repmat((1 : numel(stimIDIndexes)), numel(ROINames), 1);
% linearize the matrix
grouping = grouping(:);
% re-map the grouping indexes to make it only about the stimulus IDs and not the PSPerID
for iStimType = 1 : numel(selDispStimIDs);
grouping(grouping == iStimType) = find(strcmp(splitStimIDs(1, iStimType), uniqueStims));
end;
% use the stimulus IDs as group labels
groupLabels = uniqueStims;
case 'PSPer';
% split the stimulus IDs into stimulus ID and PSPerID
splitStimIDs = cell(2, numel(selDispStimIDs));
for iStimType = 1 : numel(selDispStimIDs);
parts = regexp(selDispStimIDs{iStimType}, ' ', 'split');
if numel(parts) > 2;
partsString = regexprep(sprintf('%s-', parts{1 : end - 1}), '-$', '');
parts = [partsString, parts(end)];
end;
splitStimIDs(:, iStimType) = parts;
end;
% extract the unique stimuli / PSPerID
uniquePSPer = unique(splitStimIDs(2, :), 'stable');
% create a grouping for each stimulus type
grouping = repmat((1 : numel(stimIDIndexes)), numel(ROINames), 1);
% linearize the matrix
grouping = grouping(:);
% re-map the grouping indexes to make it only about the PSPerID and not the stimulus IDs
for iStimType = 1 : numel(selDispStimIDs);
grouping(grouping == iStimType) = find(strcmp(splitStimIDs(2, iStimType), uniquePSPer));
end;
% use the stimulus IDs as group labels
groupLabels = uniquePSPer;
case 'stimTypePSPer';
% create a grouping for each stimulus type
grouping = repmat((1 : numel(stimIDIndexes)), numel(ROINames), 1);
% linearize the matrix
grouping = grouping(:);
% use the stimulus IDs as group labels
groupLabels = selDispStimIDs';
case 'none';
% return empty vectors
grouping = [];
groupLabels = [];
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_analysis_behav_getBehavVars.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/analysis/OCIA_analysis_behav_getBehavVars.m
| 32,382 |
utf_8
|
7db800f203bd40f7c6c94b65743f703a
|
function [behavVars, rowIDs, colIDs] = OCIA_analysis_behav_getBehavVars(this, allBehavStructs, ...
selectedLoadedBehavRows, includeEOTrials)
% OCIA_analysis_behav_getBehavVars - [no description]
%
% [behavVars, rowIDs, colIDs] = OCIA_analysis_behav_getBehavVars(this, allBehavStructs, ...
% selectedLoadedBehavRows, includeEOTrials)
%
% Extract the behavior variables from the input structures into a cell array.
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% count the number of strutures
nBehavStructs = numel(allBehavStructs);
% create a configuration cell-array for the different behavior variables with 3 + "nBehavData" + 2 columns:
% { id, label, grouping options, plotting parameters, data for each structure, concatenated data (one value per trial),
% concat. data without repetitions }
behavVars = { ...
... id label grouping groupMethod plotParams (plot type, unit, color)
'behavInd', 'behav. file num.', { 'trial' }, '', { 'box', '', 'black' };
'date', 'date', { 'trial' }, '', { 'box' , '', 'black' };
'days', 'days', { 'trial' }, '', { 'box' , '', 'black' };
'time', 'time', { }, '', { 'scatter', 'hour', 'black' };
'session', 'session', { 'trial' }, '', { 'box' , '', 'black' };
'dateWithSession', 'date (with session)', { }, '', { 'scatter', '', 'black' };
'trialRange', 'used trial range', { }, '', { 'scatter', '', 'black' };
'nTrials', 'n. of trials', { 'run', 'session', 'date' }, 'sum', { 'scaline', 'trial', 'black' };
'resps', 'response', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', ' % ', 'black' };
'minRespTime', 'delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', [.8 .8 .2] };
'earliesAllowed', 'allowedEarlies', { 'run', 'session', 'date' }, 'mean', { 'scaline', ' % ', [.2 .8 .8] };
% 'phase', 'training phase name', { 'trial' }, '', { 'box' , '', 'black' };
% 'phaseGroup', 'training phase', { 'trial' }, '', { 'box' , '', 'black' };
'nogoPerc', 'NoGo percent', { 'run', 'session', 'date' }, 'mean', { 'scaline', ' % ', [.8 .2 .2] };
'animalID', 'animal ID', { 'trial' }, '', { 'box' , '', 'black' };
'stimMatrixRandomIndex', 'stim. matrix num.', { 'run' }, 'mean', { 'scatter', '', 'black' };
'respTypes', 'response type', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scatter', '', 'black' };
'respDelays', 'response delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', 'black' };
% 'imagedTrials', 'imaged trials', { 'trial', }, 'sum', { 'box' , '', 'black' };
'startDelay', 'starting delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', 'black' };
% 'spoutIn', 'spout delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', 'black' };
'lightCueOn', 'light delay', { 'trial', 'run', 'session', 'date' }, 'mean', { 'scaline', 'sec.', 'black' };
'nRewards', 'n. of rew. trials', { 'trial', 'run', 'session', 'date' }, 'sum', { 'scaline', 'trial', 'green' };
% 'nRewardsEO', 'n. of EO rew. trials', { 'trial', 'run', 'session', 'date' }, 'sum', { 'scaline', 'trial', 'green' };
% 'suppliedWater', 'supplied water', { 'session', 'date' }, 'max', { 'scaline', ' ml ', [0 0.5 1] };
% 'rewardWater', 'reward water', { 'run', 'session', 'date' }, 'sum', { 'line' , ' ml ', 'cyan' };
% 'water', 'total water', { 'run', 'session', 'date' }, 'sum', { 'line' , ' ml ', 'blue' };
% 'weight', 'animal weight', { 'date' }, '', { 'scaline', ' g. ', 'black' };
'counts', 'performance counts', { }, '', { '' , '', '' };
'hitRate', 'hit rate', { 'trial', 'run', 'session', 'date' }, 'mean', { 'linesca', ' % ', 'green' };
'FARate', 'false alarm rate', { 'trial', 'run', 'session', 'date' }, 'mean', { 'linesca', ' % ', 'red' };
'earlies', 'earlies', { 'trial', 'run', 'session', 'date' }, 'mean', { 'linesca', ' % ', [0.2 0.5 1] };
'dprime', 'performance (d'')', { 'trial', 'run', 'session', 'date' }, 'max', { 'linesca', 'd'' ', 'blue' };
};
rowIDs = behavVars(:, 1); % extract the IDs
behavColIDs = regexp(regexprep(sprintf('%03d,', 1 : nBehavStructs), ',$', ''), ',', 'split');
colIDs = [{ 'id', 'label', 'grouping', 'groupMethod', 'plotParams' }, behavColIDs, { 'allDataRep', 'allData' }];
nBehavVars = size(behavVars, 1); % count the number of variables (=> rows)
% extend for each structure and for the concatenated data
behavVars(:, end + 1 : end + nBehavStructs + 2) = cell(nBehavVars, nBehavStructs + 2);
% get the mice info file's content as a cell-array with one cell per line
miceInfoLines = readMiceInfoFile(this);
% get all the starting time for each structure
expStartTimes = zeros(nBehavStructs, 1);
% go through each behavior structure
for iBehav = 1 : nBehavStructs;
% get the behavior data structure
behavStruct = allBehavStructs{iBehav};
% extract the experiment starting time as a "datenum"
expStartTimes(iBehav) = unix2dn(behavStruct.expStartTime * 1000);
end;
% create the session indexes by clustering the times
if nBehavStructs > 1;
% get the date "datenum"
expStartDates = datenum(datestr(expStartTimes, 'yyyy_mm_dd'), 'yyyy_mm_dd');
% cluster the time (without the date)
expStartTimesNoDate = expStartTimes - expStartDates;
sessionIndexes = clusterdata(expStartTimesNoDate, 'maxclust', 2);
% make sure the session labeled '1' is the one from the morning
meanStartTimesForFirstSession = mean(expStartTimesNoDate(sessionIndexes == 1));
meanStartTimesForSecondSession = mean(expStartTimesNoDate(sessionIndexes == 2));
% if session 1 is later than session 2, swap them
if meanStartTimesForFirstSession > meanStartTimesForSecondSession;
sessionIndexes(sessionIndexes == 1) = 3;
sessionIndexes(sessionIndexes == 2) = 1;
sessionIndexes(sessionIndexes == 3) = 2;
end;
else
sessionIndexes = 1;
end;
o('#%s(): gathering info about %d behavior files ...', mfilename(), nBehavStructs, 2, this.verb);
% go through each behavior variable
for iVar = 1 : nBehavVars;
% get the current behavior variable
behavVarID = get(this, iVar, 'id', behavVars, colIDs);
% go through each behavior structure
for iBehav = 1 : nBehavStructs;
% get the behavior index as string
iBehavStr = sprintf('%03d', iBehav);
% get the behavior data structure
behavStruct = allBehavStructs{iBehav};
% get the starting time for this structure
expStartTime = expStartTimes(iBehav);
% get the number of trials for this structure as the last valid trial having a trial ending time
nTotTrials = find(~isnan(behavStruct.times.end) & ~isnan(behavStruct.resps), 1, 'last');
% get early-on trials
EOTrials = ~isnan(behavStruct.autoRewardGiven) & behavStruct.autoRewardGiven > 0 ...
& strcmp(behavStruct.autoRewardModes, 'EarlyOn');
nEOTrials = nansum(EOTrials);
% remove early on auto-reward trials if required
if ~includeEOTrials;
nTotTrials = nTotTrials - nEOTrials;
end;
switch behavVarID;
%% trialRange
case 'trialRange';
% by default, use all trials
trialRange = 1 : nTotTrials;
% if the phase was is not "quite wakefulness" (no reward and no go stimulation),
% then try to remove the invalid trials
if ~strcmp(behavStruct.phase, 'QW');
% get the current day and session
currDay = get(this, find(strcmp(rowIDs, 'date')), iBehavStr, behavVars, colIDs);
currSession = get(this, find(strcmp(rowIDs, 'session')), iBehavStr, behavVars, colIDs);
% if first structure, consider this as a first of session
if iBehav == 1;
isFirstStructFromSession = true;
% otherwise check the previous structure's day and session
else
% get the day and session from the previous structure
prevDay = get(this, find(strcmp(rowIDs, 'date')), sprintf('%03d', iBehav - 1), behavVars, colIDs);
prevSession = get(this, find(strcmp(rowIDs, 'session')), sprintf('%03d', iBehav - 1), behavVars, colIDs);
% this is the first file from session only if either the day or the session does not match
isFirstStructFromSession = ~strcmp(prevDay, currDay) || prevSession ~= currSession;
end;
% if last structure, consider this as an end of session
if iBehav == nBehavStructs;
isLastStructFromSession = true;
% otherwise check the previous structure's day and session
else
% get the day and session from the next structure
nextDay = get(this, find(strcmp(rowIDs, 'date')), sprintf('%03d', iBehav + 1), behavVars, colIDs);
nextSession = get(this, find(strcmp(rowIDs, 'session')), sprintf('%03d', iBehav + 1), behavVars, colIDs);
% this is the first file from session only if either the day or the session does not match
isLastStructFromSession = ~strcmp(nextDay, currDay) || nextSession ~= currSession;
end;
% if this is the first structure from a session, remove some trials at the begining
if isFirstStructFromSession && ~isempty(this.an.be.nTrialsSkip);
o('%s#: %s is first structure from session (%s, %d).', mfilename(), iBehavStr, currDay, ...
currSession, 4, this.verb);
trialRange(1 : min(this.an.be.nTrialsSkip(1), nTotTrials)) = [];
end;
% if this is the last structure from a session, remove some trials at the end
if isLastStructFromSession && ~isempty(this.an.be.nTrialsSkip);
o('%s#: %s is last structure from session (%s, %d).', mfilename(), iBehavStr, currDay, ...
currSession, 4, this.verb);
trialRange(max(end - this.an.be.nTrialsSkip(2) + 1, 1) : end) = [];
end;
% if this is the last structure from a session, remove some trials at the end
if isLastStructFromSession && ~isempty(this.an.be.nMinRespTrialSkip);
% get the response types
respTypes = behavStruct.respTypes(trialRange);
% get the parameters for the ending non-responsive ratio mesure
minNResps = this.an.be.nMinRespTrialSkip(1);
nLastTrial = this.an.be.nMinRespTrialSkip(2);
% if there are enough trials to calculate the non-responsive trials
if numel(respTypes) > nLastTrial;
% counter for the number of trials removed
nTrialsRemoved = 0;
% get the last trials
lastRespTypes = respTypes(end - nLastTrial + 1 : end);
% get how many response there was in these last trials
nResps = sum(lastRespTypes == 1 | lastRespTypes == 3);
% as long as the number of responsive trials is not enough and there are enough trials
% to calculate the number of responses
while nResps < minNResps && numel(respTypes) > nLastTrial;
% remove the last trial
respTypes(end) = [];
% update the counter
nTrialsRemoved = nTrialsRemoved + 1;
% get the "new" last trials
lastRespTypes = respTypes(end - nLastTrial + 1 : end);
% get the "new" number of response(s) in the last trials
nResps = sum(lastRespTypes == 1 | lastRespTypes == 3);
end;
% exclude the last trials
trialRange(end - nTrialsRemoved + 1 : end) = [];
end;
end;
end; % end of QW phase check
% if Early-on trials should not be included
if ~includeEOTrials;
% remove early on trials
EOTrialIndices = find(EOTrials);
trialRange(ismember(trialRange, EOTrialIndices)) = [];
end;
% store the trial range
data = trialRange;
%% nTrials
case 'nTrials';
% update the actual number of trials
trialRange = get(this, find(strcmp(rowIDs, 'trialRange')), iBehavStr, behavVars, colIDs);
% store the number of trials
data = zeros(1, nTotTrials);
data(trialRange) = 1;
%% resps, phase, respDelays, respTypes, animalID, stimMatrixRandomIndex
case { 'resps', 'phase', 'respDelays', 'respTypes', 'animalID', 'stimMatrixRandomIndex' };
% if the behavior variable is stored in the structure's root, extract it from there
if isfield(behavStruct, behavVarID);
data = behavStruct.(behavVarID);
else
data = NaN;
end;
%% lightCueOn, spoutIn, startDelay
case { 'lightCueOn', 'spoutIn', 'startDelay' };
% if the behavior variable is stored in the structure's root, extract it from there
if isfield(behavStruct, 'times') && isfield(behavStruct.times, behavVarID);
data = behavStruct.times.(behavVarID);
% unless this variable is the starting delay, subtract the starting delay to have a time in
% seconds from the trial start
if ~strcmp(behavVarID, 'startDelay') && isfield(behavStruct.times, 'startDelay');
data = data - behavStruct.times.startDelay;
end;
else
data = NaN;
end;
%% phaseGroup
case 'phaseGroup';
phase = get(this, find(strcmp(rowIDs, 'phase')), iBehavStr, behavVars, colIDs);
if regexp(phase, '^Q', 'once');
data = 'baseline';
elseif regexp(phase, '^[ABL]', 'once');
data = 'shaping';
elseif regexp(phase, '^[CDE][A-Z]\d', 'once');
data = 'discrimination';
else
data = '[unknown]';
end
%% nogoPerc
case 'nogoPerc';
data = 100 * nanmean(~ismember(behavStruct.stims, behavStruct.config.tone.goStim));
%% behavInd
case 'behavInd';
% store the behavior index
data = iBehav;
%% date
case 'date';
% store the date as string
data = datestr(expStartTime, 'mm_dd');
%% days
case 'days';
% store the days as string of number of days since experiment start
firstDateVec = datevec(get(this, find(strcmp(rowIDs, 'date')), '001', behavVars, colIDs), 'mm_dd');
expStartVec = datevec(datestr(expStartTime, 'yyyy_mm_dd'), 'yyyy_mm_dd');
data = sprintf('%02d', 1 + etime(expStartVec, firstDateVec) / 3600 / 24);
%% dateWithSession
case 'dateWithSession';
% get the session
session = get(this, find(strcmp(rowIDs, 'session')), iBehavStr, behavVars, colIDs);
% store the date as string
data = [datestr(expStartTime, 'mm_dd'), ' ', iff(session == 1, 'am', 'pm')];
%% time
case 'time';
% get the starting hour and minute
startHour = str2double(datestr(expStartTime, 'HH'));
startMinute = str2double(datestr(expStartTime, 'MM'));
% store the time as a decimal hour
data = startHour + startMinute / 60;
%% session
case 'session';
% use the clustered sessions
data = sessionIndexes(iBehav);
%% imagedTrials
case 'imagedTrials';
% get the behavior ID of this structure
behavRowID = get(this, iBehav, 'behav', selectedLoadedBehavRows);
% check whether there is ANY imaging row
imagingRows = DWFilterTable(this, 'rowType = Imaging data');
% some imaging rows are present
if ~isempty(imagingRows);
% try to find imaging rows that have the same behavior ID
imagingRows = DWFilterTable(this, sprintf('behav = %s AND rowType = Imaging data', behavRowID));
% get the trial number of these imaging rows
imagedTrialNumbers = str2double(get(this, 'all', 'runNum', imagingRows));
% find and store which trials of the behavior structure have been imaged
data = double(arrayfun(@(i)ismember(i, imagedTrialNumbers), 1 : nTotTrials));
% get the spot number as index for the data
if ~isempty(imagingRows);
data(data > 0) = str2double(regexprep(get(this, 'all', 'spot', imagingRows), 'spot', ''));
end;
% no imaging rows, try to find it by day
else
% get the date
dateForRowNoYear = get(this, find(strcmp(rowIDs, 'date')), iBehavStr, behavVars, colIDs);
dateForRow = [datestr(expStartTime, 'yyyy'), '_', dateForRowNoYear];
% find if there are any spot folders for this day
dateSpotPath = sprintf('%smou_bl_%s/%s/spot*', this.path.localData, behavStruct.animalID, dateForRow);
spotFolders = dir(dateSpotPath);
if ~isempty(spotFolders);
data = ones(nTotTrials, 1);
else
data = zeros(nTotTrials, 1);
end;
end;
%% nRewards
case 'nRewards';
% store the rewarded trials
data = double(~isnan(behavStruct.times.end) & ~isnan(behavStruct.resps) & behavStruct.respTypes == 1);
%% nRewardsEO
case 'nRewardsEO';
% store the EO rewarded trials
if includeEOTrials;
data = double(~isnan(behavStruct.times.end) & ~isnan(behavStruct.resps) & behavStruct.respTypes == 1);
data(~EOTrials) = 0;
else
data = [];
end;
%% suppliedWater
case 'suppliedWater';
% if some info was found
if ~isempty(miceInfoLines);
% get the current structure's date in the format of the mice info file, with an "am/pm" label
% depending on the session
dateToSearch = ['-' datestr(expStartTime, 'yymmdd') iff(session == 1, 'am', 'pm')];
% get the lines that have these date
lineIndexes = find(cellfun(@(cont)~isempty(regexp(cont, dateToSearch, 'once')), miceInfoLines));
% if no line found, assume no water was supplied
if isempty(lineIndexes);
suppliedWater = 0;
% if a line was found, get the amount of supplied water
else
% get the animal index of this structure
animalIndex = str2double(behavStruct.animalID(end - 1 : end));
% get the line after the date line
suppliedWaterCellIndex = lineIndexes(animalIndex) + 1;
% extract the amount of supplied water
suppliedWater = str2double(regexp(miceInfoLines{suppliedWaterCellIndex}, '(\d\.\d+)', 'match'));
end;
% store the supplied water
data = suppliedWater;
% no info, no data
else
suppliedWater = 0;
data = NaN;
end;
%% rewardWater
case 'rewardWater';
% get the list of rewarded trials as a logical array of length "nTrials"
isReward = ~isnan(behavStruct.times.end) & ~isnan(behavStruct.resps) & behavStruct.respTypes == 1;
% get the amount of water received on trial using the opening-time <=> water amount conversion ( multiply by 3 ):
% 0.02s opening = 0.006ul water, 0.03s opening = 0.009 ul water
waterReward = isReward * behavStruct.params.rewDur * 0.3;
% store the rewarded water
data = waterReward;
%% water
case 'water';
% store the total water as the sum of the reward water and the supplied water
data = waterReward + suppliedWater / numel(waterReward);
%% weight
case 'weight';
% if some info was found
if ~isempty(miceInfoLines);
% get the current structure's date in the format of the mice info file
dateToSearch = [datestr(expStartTime, 'yymmdd'), '\s+'];
% get the lines that have these date
lineIndexes = find(cellfun(@(cont)~isempty(regexp(cont, dateToSearch, 'once')), miceInfoLines));
% if no line found, use NaN as weight
if isempty(lineIndexes);
data = NaN;
% if a line was found, get the weight from it
else
% get the line of the weights (if several lines, take the last one)
weightsLine = miceInfoLines{lineIndexes(end)};
% try to extract the weight numbers
weightHits = str2double(regexprep(regexp(weightsLine, '\s\d{2}\s?', 'match'), '\s', ''));
% if no extraction possible, use NaN as weight
if isempty(weightHits);
data = NaN;
% if a match was found, get the weight
else
% get the animal index of this structure
animalIndex = str2double(behavStruct.animalID(end));
% take the weight of that animal
data = weightHits(animalIndex);
end;
end;
% no info, no data
else
data = NaN;
end;
%% counts
case 'counts';
% analyse the response types
data = analyseBehavPerf(behavStruct.respTypes, [], [], 0);
%% hitRate
case 'hitRate';
% get the analysis of the response types
counts = get(this, find(strcmp(rowIDs, 'counts')), iBehavStr, behavVars, colIDs);
% store the percent of go trials on target trial
data = counts.TGOP;
%% FARate
case 'FARate';
% get the analysis of the response types
counts = get(this, find(strcmp(rowIDs, 'counts')), iBehavStr, behavVars, colIDs);
% store the percent of go trials on non-target trial
data = counts.NTGOP;
%% dprime
case 'dprime';
% get the analysis of the response types
counts = get(this, find(strcmp(rowIDs, 'counts')), iBehavStr, behavVars, colIDs);
% store the dprime value for this structure
data = counts.DPRIME;
%% earlies
case 'earlies';
% get the analysis of the response types
counts = get(this, find(strcmp(rowIDs, 'counts')), iBehavStr, behavVars, colIDs);
% store the dprime value for this structure
data = counts.INVALIDP;
%% minRespTime
case 'minRespTime';
data = behavStruct.times.respMin - behavStruct.times.startDelay;
%% earliesAllowed
case 'earliesAllowed';
if isfield(behavStruct.config.training, 'allowEarlyLicks');
data = behavStruct.config.training.allowEarlyLicks * 100;
else
data = NaN;
end;
%% OTHERWISE
% if variable is not found, skip and show warning
otherwise
data = [];
showWarning(this, 'OCIA:OCIA_analysis_behav_dprime:UnknownBehavVar', ...
sprintf('Unknown behavior variable: "%s". Skipping it.', behavVarID));
end; % end of behavior variable ID switch
% if data has nTrials values, apply the trial range filtering
if isnumeric(data) && numel(data) > 1 && ~strcmp(behavVarID, 'trialRange');
trialRange = get(this, find(strcmp(rowIDs, 'trialRange')), iBehavStr, behavVars, colIDs);
try
data = data(trialRange);
catch
o('stop', 0, 0);
end;
end;
% actually store the behavior variable
behavVars = set(this, iVar, iBehavStr, data, behavVars, colIDs);
end; % end of behavior structures loop
end; % end of behavior variable loop
%% create the concatenated data for all structures
% create a concatenated data where each variable has a value for each trial
% go through each behavior structure
for iBehav = 1 : nBehavStructs;
% get the behavior index as string
iBehavStr = sprintf('%03d', iBehav);
% get the number of trials
nTrials = sum(get(this, find(strcmp(rowIDs, 'nTrials')), iBehavStr, behavVars, colIDs));
% go through each behavior variable
for iVar = 1 : nBehavVars;
% get the data for this structure and this variable
data = get(this, iVar, iBehavStr, behavVars, colIDs);
% get all the data for this variable with one value per trial
allDataRep = get(this, iVar, 'allDataRep', behavVars, colIDs);
% get all the data for this variable without repetition
allData = get(this, iVar, 'allData', behavVars, colIDs);
% if data is a string, concatenate with a cell array of "nTrials" times the string
if ischar(data);
allDataRep = [ allDataRep repmat( { data }, 1, nTrials) ]; %#ok<AGROW>
allData = [ allData { data } ]; %#ok<AGROW>
% if data is a numeric of length 1, concatenate with a replicaton of "nTrials" times the data
elseif isnumeric(data) && numel(data) == 1;
allDataRep = [ allDataRep repmat( data, 1, nTrials) ]; %#ok<AGROW>
allData = [ allData data ]; %#ok<AGROW>
% if data is a numeric of length "nTrials", concatenate the data itself
elseif isnumeric(data) && size(data, 1) == nTrials;
allDataRep = [ allDataRep data' ]; %#ok<AGROW>
allData = [ allData data' ]; %#ok<AGROW>
% if data is a numeric of length "nTrials", concatenate the data itself
elseif isnumeric(data) && size(data,2) == nTrials;
allDataRep = [ allDataRep data ]; %#ok<AGROW>
allData = [ allData data ]; %#ok<AGROW>
% otherwise show a warning and use NaNs
else
allDataRep = [ allDataRep nan(1, nTrials) ]; %#ok<AGROW>
allData = [ allData NaN ]; %#ok<AGROW>
% if data is not empty, show a warning
if ~isempty(data) && ~isstruct(data);
showWarning(this, 'OCIA:OCIA_analysis_behav_getBehavVars:BadSizeBehavVar', ...
sprintf('Behavior variable "%s" has a bad size in structure %02d: %d x %d (nTrials = %02d). Using NaNs.', ...
behavVars{iVar, 1}, iBehav, size(data), nTrials));
end;
end;
% store back the concatenated data
% get all the data for this variable with one value per trial
behavVars = set(this, iVar, 'allDataRep', { allDataRep }, behavVars, colIDs);
% get all the data for this variable without repetition
behavVars = set(this, iVar, 'allData', { allData }, behavVars, colIDs);
end; % end of behavior variable loop
end; % end of behavior structures loop
end
function miceInfoLines = readMiceInfoFile(this)
% extract the lines from the mice info file
% open file
miceInfoFilePath = [this.path.localData this.an.be.miceInfoFilePath];
fID = fopen(miceInfoFilePath);
if fID == -1;
miceInfoLines = []; % return nothing
showWarning(this, 'OCIA:OCIA_analysis_behav_dprime:CannotReadMiceInfoLine', ...
sprintf('Could not read the "MiceInfo" file at "%s". Skipping it.', miceInfoFilePath));
return;
end;
% allocate a cell array for the lines
miceInfoLines = cell(1000, 1);
% read all lines
i = 1;
miceInfoLines{i} = fgetl(fID); i = i + 1;
while ischar(miceInfoLines{i - 1});
miceInfoLines{i} = fgetl(fID); i = i + 1;
end;
% close the file
fclose(fID);
% remove empty or numeric lines
miceInfoLines(cellfun(@isempty, miceInfoLines)) = [];
miceInfoLines(cellfun(@isnumeric, miceInfoLines)) = [];
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_parseNotebookFile_H45Balazs.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/parseNotebook/OCIA_parseNotebookFile_H45Balazs.m
| 9,607 |
utf_8
|
0c5a917a0ff89436458c3f52e1cb6233
|
function notebookInfo = OCIA_parseNotebookFile_H45Balazs(notebookFilePath)
% written by B. Laurenczy - 2013/10/15
%% init variables
notebookInfo = cell(1, 14);
% notebookInfo = cell(1, 10);
iRow = 1;
skipLineRead = false;
% regular expression patterns
% mouseIDPattern = '^mou_[db]l_\d{6}_\d{2}$';
mouseIDPattern = '^\w+$';
headerPattern = '^(?<spotID>sp\d{2})(?<runType>[^_ ]+)?_?(?<stimNum>\d+)?(?<comments>[\w \/-,\.]+)?$';
dateTimePattern = '^(?<date>\d{4}_\d{2}_\d{2})__(?<time>\d{2}_\d{2}_\d{2})h: +?$';
imageModePattern = ['- ImagingMode: 2PM (?<imType>[^,]+), XY(?<zOrT>[TZ])?=(?<x>\d+)x(?<y>\d+)x?(?<zt>\d+)?' ...
'(, frame rate=)?(?<rate>[\d\.]+)?( Hz)?(, z-dist=)?(?<zStep>[\d\.]+)?( um)?'];
scanHeadPattern = '- ScanHead: final intensity=(?<laserInt>[\d\.]+)%; zoom=(?<zoom>[\d\.]+)';
%% open notebook file
nbFileID = fopen(notebookFilePath);
% get the first line to start the reading
line = fgetl(nbFileID);
if line == -1;
warning('OCIA_parseNotebookFile_H45Balazs:EmptyFile', 'Notebook file at %s is empty! Aborting.', notebookFilePath);
return;
end;
% if present, extract the mouseID at the first line
if regexp(line, mouseIDPattern, 'once');
mouseID = line; % store the mouseID
line = fgetl(nbFileID); % jump to next line
else % otherwise mouseID is not present
mouseID = '-';
end;
%% mainLoop: read all lines one by one
while ischar(line); % if last line was read, next line will be -1
%% - empty lines
if numel(line) < 4; % skip empty lines
line = fgetl(nbFileID); % jump to next line
continue;
end;
% try to match the line with the "header" pattern
headerHits = regexp(line, headerPattern, 'names');
%% - headerPattern match
% if a match was found, create a row in the notebookInfo cell-array
if ~isempty(headerHits);
% store all the extracted informations
notebookInfo{iRow, 1} = mouseID;
notebookInfo{iRow, 2} = headerHits.spotID;
notebookInfo{iRow, 3} = headerHits.runType;
% store the stimulus number, but only if it's not empty
if ~isempty(headerHits.stimNum); notebookInfo{iRow, 4} = headerHits.stimNum; end;
notebookInfo{iRow, 5} = regexprep(headerHits.comments, '^ +', ''); % remove initial space character
dateTimeLine = fgetl(nbFileID);
if numel(dateTimeLine) < 4;
% store some information for the comment line
notebookInfo{iRow, 1} = mouseID;
notebookInfo{iRow, 2} = 'unknown';
notebookInfo{iRow, 3} = 'comment';
notebookInfo{iRow, 5} = line; % store the commentaries in the 'comments' column
else
extractDateTimeImModeScanHeadInfos();
end;
iRow = iRow + 1; % increment the row counter
%% - headerPattern no-match
% other non-empty lines could either be "orphan" date-time lines that didn't have any "header",
% or simple comment lines with no other date-time/imageMode/etc. informations
else
% check wether it's a date-time line
dateTimeLine = line;
dateTimeHits = regexp(dateTimeLine, dateTimePattern, 'names');
% if a match was found, process the following lines as if there had been a header
if ~isempty(dateTimeHits);
% store some informations for this row even if it didn't have a header line
notebookInfo{iRow, 1} = mouseID;
notebookInfo{iRow, 2} = 'unknown';
extractDateTimeImModeScanHeadInfos();
iRow = iRow + 1; % increment the row counter
% otherwise consider it just as a comment
else
% store some information for the comment line
notebookInfo{iRow, 1} = mouseID;
notebookInfo{iRow, 2} = 'unknown';
notebookInfo{iRow, 3} = 'comment';
notebookInfo{iRow, 5} = line; % store the commentaries in the 'comments' column
% check wether next line is a date-time line
line = fgetl(nbFileID);
% empty line, move to next row with the empty-line already read, no skip needed
if numel(line) < 4;
iRow = iRow + 1; % increment the row counter
% non-empty line, check if it's a date-time line or already a new line of something
else
dateTimeHits = regexp(line, dateTimePattern, 'names');
if ~isempty(dateTimeHits); % line was date-time for this comment
dateTimeLine = line;
extractDateTimeImModeScanHeadInfos();
iRow = iRow + 1; % increment the row counter
else % more stuff and not date-time on next line, jump to next row without re-reading a line
skipLineRead = true;
iRow = iRow + 1; % increment the row counter
end;
end;
end
end;
if ~skipLineRead; line = fgetl(nbFileID); end; % get next line
skipLineRead = false;
end;
%% close the notebook file
fclose(nbFileID);
%% check consistency
% fill in missing run types
nRows = size(notebookInfo, 1);
for iRow = 1 : nRows;
% missing runTypes : try to fill with first word from "comments"
if isempty(notebookInfo{iRow, 3});
if ~isempty(notebookInfo{iRow, 5});
commentsFirstWord = regexp(notebookInfo{iRow, 5}, '^\w+', 'match');
notebookInfo{iRow, 3} = commentsFirstWord{1};
notebookInfo{iRow, 5} = strrep(notebookInfo{iRow, 5}, commentsFirstWord{1}, ' ');
notebookInfo{iRow, 5} = regexprep(notebookInfo{iRow, 5}, '^ +', ''); % remove leading spaces
else
% warning('OCIA_parseNotebookFile_H45Balazs:NoRunType', 'Could not find a runType for row %d (spotID: "%s").', ...
% iRow, notebookInfo{iRow, 2});
end
end
end;
%% function: #extractDateTimeImModeScanHeadInfos
function extractDateTimeImModeScanHeadInfos()
% try to match the next line with the "dateTime" pattern. The date-time line is already read here.
dateTimeHits = regexp(dateTimeLine, dateTimePattern, 'names');
% if a match was found, fill the row in the notebookInfo cell-array
if ~isempty(dateTimeHits);
notebookInfo{iRow, 6} = dateTimeHits.day;
notebookInfo{iRow, 7} = dateTimeHits.time;
else % if not matching, show a warning and leave notebookInfo empty
warning('OCIA_parseNotebookFile_H45Balazs:DateTimeMatchFailure', ['Could not match date-time line "%s" with ' ...
'dateTimePattern "%s" ! Trying to continue ...'], dateTimeLine, dateTimePattern);
end;
% try to match the next line with the "imageMode" pattern
imageModeLine = fgetl(nbFileID);
imageModeHits = regexp(imageModeLine, imageModePattern, 'names');
% if a match was found, fill the row in the notebookInfo cell-array
if ~isempty(imageModeHits);
% store the image type, eventually transforming 'single frame' to 'frame'
notebookInfo{iRow, 8} = imageModeHits.imType;
notebookInfo{iRow, 8} = strrep(notebookInfo{iRow, 8}, 'single ', '');
% if recorded data had a 3rd dimension (either Z or T)
if ~isempty(imageModeHits.zOrT) || ~isempty(imageModeHits.zt);
% create a 3rd dimension tag depending on the Z/T labeling: either stack or movie
if strcmp(imageModeHits.zOrT, 'T');
notebookInfo{iRow, 9} = 'movie';
elseif strcmp(imageModeHits.zOrT, 'Z');
notebookInfo{iRow, 9} = 'stack';
else
warning('OCIA_parseNotebookFile_H45Balazs:UnknownZorT', ['3rd dimension of file unknown, neither T (time) or ' ...
'Z (stack): %s. Continuing ... '], imageModeHits.zOrT);
end;
% create a dimension tag like '256x256' or '100x100x500' if there is a 3rd dimension
if ~isempty(imageModeHits.zt);
notebookInfo{iRow, 10} = sprintf('%sx%sx%s', imageModeHits.x, imageModeHits.y, imageModeHits.zt);
else
warning('OCIA_parseNotebookFile_H45Balazs:ZorTButNoZTValue', ['File has a 3rd dimension (type: %s) but no ' ...
'dimension for that.'], imageModeHits.zt);
end;
% if there is no 3rd dimension, also create a 2D dimension tag like '256x256'
else
notebookInfo{iRow, 10} = sprintf('%sx%s', imageModeHits.x, imageModeHits.y);
end;
% store the rate and the z-dist (Z step for stacks in micro-meters) if they are not empty
if ~isempty(imageModeHits.rate); notebookInfo{iRow, 11} = imageModeHits.rate; end;
if ~isempty(imageModeHits.zStep); notebookInfo{iRow, 12} = imageModeHits.zStep; end;
else % if not matching, show a warning and leave notebookInfo empty
warning('OCIA_parseNotebookFile_H45Balazs:ImagingModeMatchFailure', ['Could not match imaging mode line "%s" with ' ...
'imageModePattern "%s" ! Trying to continue ...'], imageModeLine, imageModePattern);
end;
% try to match the next line with the "scanHead" pattern
scanHeadLine = fgetl(nbFileID);
scaneHeadHits = regexp(scanHeadLine, scanHeadPattern, 'names');
% if a match was found, fill the row in the notebookInfo cell-array
if ~isempty(dateTimeHits);
notebookInfo{iRow, 13} = scaneHeadHits.laserInt;
notebookInfo{iRow, 14} = scaneHeadHits.zoom;
else % if not matching, show a warning and leave notebookInfo row empty
warning('OCIA_parseNotebookFile_H45Balazs:ScanHeadMatchFailure', ['Could not match scan-head line "%s" with ' ...
'scanHeadPattern "%s" ! Trying to continue ...'], scanHeadLine, scanHeadPattern);
end;
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_parseNotebookFile_H37Alex.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/parseNotebook/OCIA_parseNotebookFile_H37Alex.m
| 9,570 |
utf_8
|
b92b584eb116531a7c99ab7a809f163f
|
function notebookInfo = OCIA_parseNotebookFile_H37Alex(notebookFilePath)
% written by B. Laurenczy - 2013/10/15
%% init variables
notebookInfo = cell(1, 14);
% notebookInfo = cell(1, 10);
iRow = 1;
skipLineRead = false;
% regular expression patterns
% mouseIDPattern = '^mou_[db]l_\d{6}_\d{2}$';
mouseIDPattern = '^\w+$';
headerPattern = '^(?<regionID>R\dS\d)(?<runType>, [adc][HL])?(?<comments>[\w \/-,\.\!]+)?$';
dateTimePattern = '^(?<date>\d{4}_\d{2}_\d{2})__(?<time>\d{2}_\d{2}_\d{2})h: +?$';
imageModePattern = ['- ImagingMode: 2PM (?<imType>[^,]+), XY(?<zOrT>[TZ])?=(?<x>\d+)x(?<y>\d+)x?(?<zt>\d+)?' ...
'(, frame rate=)?(?<rate>[\d\.]+)?( Hz)?(, z-dist=)?(?<zStep>[\d\.]+)?( um)?'];
scanHeadPattern = '- ScanHead: final intensity=(?<laserInt>[\d\.]+)%; zoom=(?<zoom>[\d\.]+)';
%% open notebook file
nbFileID = fopen(notebookFilePath);
% get the first line to start the reading
line = fgetl(nbFileID);
if line == -1;
warning('OCIA_parseNotebookFile_H37Alex:EmptyFile', 'Notebook file at %s is empty! Aborting.', notebookFilePath);
return;
end;
% if present, extract the mouseID at the first line
if regexp(line, mouseIDPattern, 'once');
mouseID = line; % store the mouseID
line = fgetl(nbFileID); % jump to next line
else % otherwise mouseID is not present
mouseID = '-';
end;
%% mainLoop: read all lines one by one
while ischar(line); % if last line was read, next line will be -1
%% - empty lines
if numel(line) < 4; % skip empty lines
line = fgetl(nbFileID); % jump to next line
continue;
end;
% try to match the line with the "header" pattern
headerHits = regexp(line, headerPattern, 'names');
%% - headerPattern match
% if a match was found, create a row in the notebookInfo cell-array
if ~isempty(headerHits);
% store all the extracted informations
notebookInfo{iRow, 1} = mouseID;
notebookInfo{iRow, 2} = lower(headerHits.regionID);
notebookInfo{iRow, 3} = regexprep(headerHits.runType, '^[ ,]+', '');
notebookInfo{iRow, 5} = regexprep(headerHits.comments, '^[ ,]+', ''); % remove initial space character
dateTimeLine = fgetl(nbFileID);
if numel(dateTimeLine) < 4;
% store some information for the comment line
notebookInfo{iRow, 1} = mouseID;
notebookInfo{iRow, 2} = 'unknown';
notebookInfo{iRow, 3} = 'comment';
notebookInfo{iRow, 5} = regexprep(line, '^[ ,]+', ''); % store the commentaries in the 'comments' column
else
extractDateTimeImModeScanHeadInfos();
end;
iRow = iRow + 1; % increment the row counter
%% - headerPattern no-match
% other non-empty lines could either be "orphan" date-time lines that didn't have any "header",
% or simple comment lines with no other date-time/imageMode/etc. informations
else
% check wether it's a date-time line
dateTimeLine = line;
dateTimeHits = regexp(dateTimeLine, dateTimePattern, 'names');
% if a match was found, process the following lines as if there had been a header
if ~isempty(dateTimeHits);
% store some informations for this row even if it didn't have a header line
notebookInfo{iRow, 1} = mouseID;
notebookInfo{iRow, 2} = 'unknown';
extractDateTimeImModeScanHeadInfos();
iRow = iRow + 1; % increment the row counter
% otherwise consider it just as a comment
else
% store some information for the comment line
notebookInfo{iRow, 1} = mouseID;
notebookInfo{iRow, 2} = 'unknown';
notebookInfo{iRow, 3} = 'comment';
notebookInfo{iRow, 5} = regexprep(line, '^[ ,]+', ''); % store the commentaries in the 'comments' column
% check wether next line is a date-time line
line = fgetl(nbFileID);
% empty line, move to next row with the empty-line already read, no skip needed
if numel(line) < 4;
iRow = iRow + 1; % increment the row counter
% non-empty line, check if it's a date-time line or already a new line of something
else
dateTimeHits = regexp(line, dateTimePattern, 'names');
if ~isempty(dateTimeHits); % line was date-time for this comment
dateTimeLine = line;
extractDateTimeImModeScanHeadInfos();
iRow = iRow + 1; % increment the row counter
else % more stuff and not date-time on next line, jump to next row without re-reading a line
skipLineRead = true;
iRow = iRow + 1; % increment the row counter
end;
end;
end
end;
if ~skipLineRead; line = fgetl(nbFileID); end; % get next line
skipLineRead = false;
end;
%% close the notebook file
fclose(nbFileID);
%% check consistency
% fill in missing run types
nRows = size(notebookInfo, 1);
for iRow = 1 : nRows;
% missing runTypes : try to fill with first word from "comments"
if isempty(notebookInfo{iRow, 3});
if ~isempty(notebookInfo{iRow, 5});
commentsFirstWord = regexp(notebookInfo{iRow, 5}, '^\w+', 'match');
if isempty(commentsFirstWord); continue; end;
notebookInfo{iRow, 3} = commentsFirstWord{1};
notebookInfo{iRow, 5} = strrep(notebookInfo{iRow, 5}, commentsFirstWord{1}, ' ');
notebookInfo{iRow, 5} = regexprep(notebookInfo{iRow, 5}, '^ +', ''); % remove leading spaces
else
% warning('OCIA_parseNotebookFile_H37Alex:NoRunType', 'Could not find a runType for row %d (spotID: "%s").', ...
% iRow, notebookInfo{iRow, 2});
end
end
end;
%% function: #extractDateTimeImModeScanHeadInfos
function extractDateTimeImModeScanHeadInfos()
% try to match the next line with the "dateTime" pattern. The date-time line is already read here.
dateTimeHits = regexp(dateTimeLine, dateTimePattern, 'names');
% if a match was found, fill the row in the notebookInfo cell-array
if ~isempty(dateTimeHits);
notebookInfo{iRow, 6} = dateTimeHits.day;
notebookInfo{iRow, 7} = dateTimeHits.time;
else % if not matching, show a warning and leave notebookInfo empty
warning('OCIA_parseNotebookFile_H37Alex:DateTimeMatchFailure', ['Could not match date-time line "%s" with ' ...
'dateTimePattern "%s" ! Trying to continue ...'], dateTimeLine, dateTimePattern);
end;
% try to match the next line with the "imageMode" pattern
imageModeLine = fgetl(nbFileID);
imageModeHits = regexp(imageModeLine, imageModePattern, 'names');
% if a match was found, fill the row in the notebookInfo cell-array
if ~isempty(imageModeHits);
% store the image type, eventually transforming 'single frame' to 'frame'
notebookInfo{iRow, 8} = imageModeHits.imType;
notebookInfo{iRow, 8} = strrep(notebookInfo{iRow, 8}, 'single ', '');
% if recorded data had a 3rd dimension (either Z or T)
if ~isempty(imageModeHits.zOrT) || ~isempty(imageModeHits.zt);
% create a 3rd dimension tag depending on the Z/T labeling: either stack or movie
if strcmp(imageModeHits.zOrT, 'T');
notebookInfo{iRow, 9} = 'movie';
elseif strcmp(imageModeHits.zOrT, 'Z');
notebookInfo{iRow, 9} = 'stack';
else
warning('OCIA_parseNotebookFile_H37Alex:UnknownZorT', ['3rd dimension of file unknown, neither T (time) or ' ...
'Z (stack): %s. Continuing ... '], imageModeHits.zOrT);
end;
% create a dimension tag like '256x256' or '100x100x500' if there is a 3rd dimension
if ~isempty(imageModeHits.zt);
notebookInfo{iRow, 10} = sprintf('%sx%sx%s', imageModeHits.x, imageModeHits.y, imageModeHits.zt);
else
warning('OCIA_parseNotebookFile_H37Alex:ZorTButNoZTValue', ['File has a 3rd dimension (type: %s) but no ' ...
'dimension for that.'], imageModeHits.zt);
end;
% if there is no 3rd dimension, also create a 2D dimension tag like '256x256'
else
notebookInfo{iRow, 10} = sprintf('%sx%s', imageModeHits.x, imageModeHits.y);
end;
% store the rate and the z-dist (Z step for stacks in micro-meters) if they are not empty
if ~isempty(imageModeHits.rate); notebookInfo{iRow, 11} = imageModeHits.rate; end;
if ~isempty(imageModeHits.zStep); notebookInfo{iRow, 12} = imageModeHits.zStep; end;
else % if not matching, show a warning and leave notebookInfo empty
warning('OCIA_parseNotebookFile_H37Alex:ImagingModeMatchFailure', ['Could not match imaging mode line "%s" with ' ...
'imageModePattern "%s" ! Trying to continue ...'], imageModeLine, imageModePattern);
end;
% try to match the next line with the "scanHead" pattern
scanHeadLine = fgetl(nbFileID);
scaneHeadHits = regexp(scanHeadLine, scanHeadPattern, 'names');
% if a match was found, fill the row in the notebookInfo cell-array
if ~isempty(dateTimeHits);
notebookInfo{iRow, 13} = scaneHeadHits.laserInt;
notebookInfo{iRow, 14} = scaneHeadHits.zoom;
else % if not matching, show a warning and leave notebookInfo row empty
warning('OCIA_parseNotebookFile_H37Alex:ScanHeadMatchFailure', ['Could not match scan-head line "%s" with ' ...
'scanHeadPattern "%s" ! Trying to continue ...'], scanHeadLine, scanHeadPattern);
end;
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_parseNotebookFile_default.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/parseNotebook/OCIA_parseNotebookFile_default.m
| 9,500 |
utf_8
|
ed75ced6923a9b1d824192423aad1eb1
|
function [infoTable, tIDs] = OCIA_parseNotebookFile_default(notebookFilePath)
% written by B. Laurenczy - 2014/02/11
%% init variables
infoTable = cell(1000, 9);
tIDs = { 'animal', 'spot', 'runType', 'comments', 'day', 'time', 'imType', 'imType2', 'dimNB'};
iRow = 1;
skipLineRead = false;
% regular expression patterns
% mouseIDPattern = '^mou_[db]l_\d{6}_\d{2}$';
mouseIDPattern = '^\w+$';
headerPattern = '^(?<spotID>sp\d{2})(?<runType>[^_ ]+)?_?(?<stimNum>\d+)?\s*(?<comments>.+)?';
dayTimePattern = '^(?<day>\d{4}_\d{2}_\d{2})__(?<time>\d{2}_\d{2}_\d{2})h: +?$';
imageModePattern = '- ImagingMode: 2PM (?<imType>[^,]+), XY(?<zOrT>[TZ])?=(?<x>\d+)x(?<y>\d+)x?(?<zt>\d+)?';
%% open notebook file
nbFileID = fopen(notebookFilePath);
if nbFileID == -1;
warning('OCIA_parseNotebookFile_default:CannotOpenFile', 'Notebook file at %s cannot be opened! Aborting.', notebookFilePath);
return;
end;
% get the first line to start the reading
line = fgetl(nbFileID);
if line == -1;
warning('OCIA_parseNotebookFile_default:EmptyFile', 'Notebook file at %s is empty! Aborting.', notebookFilePath);
return;
end;
% if present, extract the mouseID at the first line
if regexp(line, mouseIDPattern, 'once');
mouseID = line; % store the mouseID
line = fgetl(nbFileID); % jump to next line
else % otherwise mouseID is not present
mouseID = '-';
end;
%% mainLoop: read all lines one by one
while ischar(line); % if last line was read, next line will be -1
%% - empty lines
if numel(line) < 4; % skip empty lines
line = fgetl(nbFileID); % jump to next line
continue;
end;
% try to match the line with the "header" pattern
headerHits = regexp(line, headerPattern, 'names');
%% - headerPattern match
% if a match was found, create a row in the notebookInfo cell-array
if ~isempty(headerHits);
% store all the extracted informations
infoTable{iRow, strcmp(tIDs, 'animal')} = mouseID;
infoTable{iRow, strcmp(tIDs, 'spot')} = regexprep(headerHits.spotID, 'sp(\d+)', 'spot$1');
infoTable{iRow, strcmp(tIDs, 'runType')} = headerHits.runType;
% store the stimulus number, but only if it's not empty
if ~isempty(headerHits.stimNum); infoTable{iRow, 4} = headerHits.stimNum; end;
infoTable{iRow, strcmp(tIDs, 'comments')} = regexprep(headerHits.comments, '^ +', ''); % remove initial space character
dateTimeLine = fgetl(nbFileID);
if numel(dateTimeLine) < 4;
% store some information for the comment line
infoTable{iRow, strcmp(tIDs, 'animal')} = mouseID;
infoTable{iRow, strcmp(tIDs, 'spot')} = '';
infoTable{iRow, strcmp(tIDs, 'comments')} = 'comment';
infoTable{iRow, strcmp(tIDs, 'comments')} = line; % store the commentaries in the 'comments' column
else
extractDateTimeImModeScanHeadInfos();
end;
iRow = iRow + 1; % increment the row counter
%% - headerPattern no-match
% other non-empty lines could either be "orphan" date-time lines that didn't have any "header",
% or simple comment lines with no other date-time/imageMode/etc. informations
else
% check wether it's a date-time line
dateTimeLine = line;
dateTimeHits = regexp(dateTimeLine, dayTimePattern, 'names');
% if a match was found, process the following lines as if there had been a header
if ~isempty(dateTimeHits);
% store some informations for this row even if it didn't have a header line
infoTable{iRow, strcmp(tIDs, 'animal')} = mouseID;
infoTable{iRow, strcmp(tIDs, 'spot')} = '';
extractDateTimeImModeScanHeadInfos();
iRow = iRow + 1; % increment the row counter
% otherwise consider it just as a comment
else
% store some information for the comment line
infoTable{iRow, strcmp(tIDs, 'animal')} = mouseID;
infoTable{iRow, strcmp(tIDs, 'spot')} = '';
infoTable{iRow, strcmp(tIDs, 'runType')} = 'comment';
infoTable{iRow, strcmp(tIDs, 'comments')} = line; % store the commentaries in the 'comments' column
% check wether next line is a date-time line
line = fgetl(nbFileID);
% empty line, move to next row with the empty-line already read, no skip needed
if numel(line) < 4;
iRow = iRow + 1; % increment the row counter
% non-empty line, check if it's a date-time line or already a new line of something
else
dateTimeHits = regexp(line, dayTimePattern, 'names');
if ~isempty(dateTimeHits); % line was date-time for this comment
dateTimeLine = line;
extractDateTimeImModeScanHeadInfos();
iRow = iRow + 1; % increment the row counter
else % more stuff and not date-time on next line, jump to next row without re-reading a line
skipLineRead = true;
iRow = iRow + 1; % increment the row counter
end;
end;
end
end;
if ~skipLineRead; line = fgetl(nbFileID); end; % get next line
skipLineRead = false;
end;
%% close the notebook file
fclose(nbFileID);
%% check consistency
% fill in missing run types
nRows = size(infoTable, 1);
for iRow = 1 : nRows;
% missing runTypes : try to fill with first word from "comments"
if isempty(infoTable{iRow, strcmp(tIDs, 'runType')});
if ~isempty(infoTable{iRow, strcmp(tIDs, 'comments')});
commentsFirstWord = regexp(infoTable{iRow, strcmp(tIDs, 'comments')}, '^\w+', 'match');
infoTable{iRow, strcmp(tIDs, 'runType')} = commentsFirstWord{1};
infoTable{iRow, strcmp(tIDs, 'comments')} = strrep(infoTable{iRow, strcmp(tIDs, 'comments')}, commentsFirstWord{1}, ' ');
infoTable{iRow, strcmp(tIDs, 'comments')} = regexprep(infoTable{iRow, strcmp(tIDs, 'comments')}, '^ +', ''); % remove leading spaces
else
% warning('OCIA_parseNotebookFile_default:NoRunType', 'Could not find a runType for row %d (spotID: "%s").', ...
% iRow, notebookInfo{iRow, 2});
end
end
end;
%% remove empty lines
infoTableCell = infoTable;
emptyRows = arrayfun(@(iRow)all(cellfun(@isempty, infoTableCell(iRow, :))), 1 : size(infoTableCell, 1));
infoTable(emptyRows, :) = [];
%% function: #extractDateTimeImModeScanHeadInfos
function extractDateTimeImModeScanHeadInfos()
% try to match the next line with the "dateTime" pattern. The date-time line is already read here.
dateTimeHits = regexp(dateTimeLine, dayTimePattern, 'names');
% if a match was found, fill the row in the notebookInfo cell-array
if ~isempty(dateTimeHits);
infoTable{iRow, strcmp(tIDs, 'day')} = dateTimeHits.day;
infoTable{iRow, strcmp(tIDs, 'time')} = dateTimeHits.time;
else % if not matching, show a warning and leave notebookInfo empty
warning('OCIA_parseNotebookFile_default:DateTimeMatchFailure', ['Could not match date-time line "%s" with ' ...
'dateTimePattern "%s" ! Trying to continue ...'], dateTimeLine, dayTimePattern);
end;
% try to match the next line with the "imageMode" pattern
imageModeLine = fgetl(nbFileID);
imageModeHits = regexp(imageModeLine, imageModePattern, 'names');
% if a match was found, fill the row in the notebookInfo cell-array
if ~isempty(imageModeHits);
% store the image type, eventually transforming 'single frame' to 'frame'
infoTable{iRow, strcmp(tIDs, 'imType')} = imageModeHits.imType;
infoTable{iRow, strcmp(tIDs, 'imType')} = strrep(infoTable{iRow, strcmp(tIDs, 'imType')}, 'single ', '');
% if recorded data had a 3rd dimension (either Z or T)
if ~isempty(imageModeHits.zOrT) || ~isempty(imageModeHits.zt);
% create a 3rd dimension tag depending on the Z/T labeling: either stack or movie
if strcmp(imageModeHits.zOrT, 'T');
infoTable{iRow, strcmp(tIDs, 'imType2')} = 'movie';
elseif strcmp(imageModeHits.zOrT, 'Z');
infoTable{iRow, strcmp(tIDs, 'imType2')} = 'stack';
else
warning('OCIA_parseNotebookFile_default:UnknownZorT', ['3rd dimension of file unknown, neither T (time) or ' ...
'Z (stack): %s. Continuing ... '], imageModeHits.zOrT);
end;
% create a dimension tag like '256x256' or '100x100x500' if there is a 3rd dimension
if ~isempty(imageModeHits.zt);
infoTable{iRow, strcmp(tIDs, 'dimNB')} = sprintf('%sx%sx%s', imageModeHits.x, imageModeHits.y, imageModeHits.zt);
else
warning('OCIA_parseNotebookFile_default:ZorTButNoZTValue', ['File has a 3rd dimension (type: %s) but no ' ...
'dimension for that.'], imageModeHits.zt);
end;
% if there is no 3rd dimension, also create a 2D dimension tag like '256x256'
else
infoTable{iRow, strcmp(tIDs, 'dimNB')} = sprintf('%sx%s', imageModeHits.x, imageModeHits.y);
end;
else % if not matching, show a warning and leave notebookInfo empty
warning('OCIA_parseNotebookFile_default:ImagingModeMatchFailure', ['Could not match imaging mode line "%s" with ' ...
'imageModePattern "%s" ! Trying to continue ...'], imageModeLine, imageModePattern);
end;
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataWatcherProcess_fiberMovies.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataWatcherProcess/OCIA_dataWatcherProcess_fiberMovies.m
| 3,029 |
utf_8
|
998fce6c62245a138a9e85236238e151
|
%% #OCIA_dataWatcherProcess_fiberMovies
function OCIA_dataWatcherProcess_fiberMovies(this, ~, ~)
%% initialize movie
% get the path of the selected movie
moviePath = DWGetFullPath(this, this.dw.selectedTableRows(1));
if regexp(moviePath, '\.avi$');
% get VideoReader object for the selected movie
vrHand = VideoReader(moviePath);
% Get movie dimensions
%frameWindows = [85:135, 1185:1235, 2285:2335, 3385:4435, 4485:4535, 5585:5635, 6685:6735, 7785:7835, 8885:8935, 9985:1035];
%Generate frame Vector
frameWindows = 40:210;
for k = 1:9
frameWindows = [frameWindows (k*1100 +40):(k*1100 +210)]; %#ok<AGROW>
end;
%Testing frames:
%frameWindows = [85:135, 1185:1235];
nFrames = size(frameWindows,2);
this.jt.nFrames = nFrames; % store the number of frames
H = vrHand.Height;
W = vrHand.Width;
%% load the movie
loadTic = tic; % for performance timing purposes
showMessage(this, 'Loading movie ...', 'yellow');
% pre-allocate movie
oriFrames = zeros(H, W, nFrames);
% load movie frame by frame
DWWaitBar(this, 0);
for iFrame = 1:nFrames
oriFrames(:, :, iFrame) = nanmean(double(read(vrHand, frameWindows(iFrame))), 3);
DWWaitBar(this, 100 * (iFrame / nFrames));
end
% back up the frames
this.jt.oriFrames = oriFrames;
this.jt.frames = oriFrames;
showMessage(this, sprintf('Loading movie done (%3.1f sec).', toc(loadTic)));
end;
%% set JointTracker settings
this.jt.nJoints = size(this.jt.jointConfig, 1);
this.jt.joints = zeros(this.jt.nJoints, nFrames, 2, this.jt.nJointTypes);
this.GUI.jt.forcedJoints = false(this.jt.nJoints, nFrames, this.jt.nJointTypes);
this.GUI.jt.boundBoxPos = zeros(this.jt.nJoints, this.jt.nFrames, this.jt.nJointTypes, 4);
this.GUI.jt.jointROIHandles = cell(this.jt.nJoints, 1);
this.jt.jointROIMasks = cell(this.jt.nJoints, 1);
%% initialize GUI
% change mode
OCIAChangeMode(this, 'JointTracker');
% replace the image by a dummy one by one dark pixel
this.GUI.jt.img = zeros(1, 1);
set(this.GUI.handles.jt.img, 'CData', linScale(this.GUI.jt.img));
set(this.GUI.handles.jt.axe, 'XLim', [0.5 1.5], 'YLim', [0.5 1.5]);
% adjust the display options setter
set(this.GUI.handles.jt.viewOpts.boundBoxes, 'Value', 0);
set(this.GUI.handles.jt.viewOpts.debugPlots, 'Value', 0);
set(this.GUI.handles.jt.viewOpts.preProc, 'Value', 0);
% adjust the joint and joint type setters
set(this.GUI.handles.jt.jointSelSetter, 'Value', 1);
this.GUI.jt.iJoint = 1;
set(this.GUI.handles.jt.jointTypeSelSetter, 'Value', 1);
this.GUI.jt.iJointType = 1;
% adjust the frame setter
this.GUI.jt.iFrame = 1;
set(this.GUI.handles.jt.frameSetter, 'Enable', 'on', 'Min', 1, 'Max', nFrames, 'Value', 1, ...
'SliderStep', [1 / nFrames 3 / nFrames]);
% update the frame label
set(this.GUI.handles.jt.frameLabel, 'String', sprintf('Frame %03d', 1));
% update the GUI
JTUpdateGUI(this, 'all');
% set the focus to the frame setter
uicontrol(this.GUI.handles.jt.frameSetter);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataWatcherProcess_trackMovies.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataWatcherProcess/OCIA_dataWatcherProcess_trackMovies.m
| 8,209 |
utf_8
|
fd53cc601f82c5641c2b56e69a35c184
|
%% #OCIA_dataWatcherProcess_trackMovies
function OCIA_dataWatcherProcess_trackMovies(this, ~, ~)
% change mode
OCIAChangeMode(this, 'DataWatcher');
%% initialize movie
% get the path of the selected movie
moviePath = this.path.moviePath;
moviePathCropped = regexprep(moviePath, '\.avi', '_cropped.avi');
if regexp(moviePath, '\.avi$');
% get VideoReader object for the selected movie
vrHand = VideoReader(moviePath);
% get movie dimensions
nFrames = round(vrHand.Duration * vrHand.FrameRate);
this.jt.frameRate = vrHand.FrameRate;
this.jt.nFrames = nFrames; % store the number of frames
showMessage(this, sprintf('Video has %d frames ...', nFrames), 'yellow');
H = vrHand.Height;
W = vrHand.Width;
% H = round(vrHand.Height * 0.1);
% W = round(vrHand.Width * 0.1);
%% crop movie
% if cropping is requested
if this.jt.doCroppingStep;
% if no cropping rectangle is not defined yet
if isempty(this.jt.cropRect);
% load a frame
frame = nanmean(double(readFrame(vrHand)), 3);
% reset time so vrHand is back at the begininning of the movie
vrHand.CurrentTime = 0;
% display frame
figH = figure('NumberTitle', 'off', 'Name', 'Crop movie - [X, Y, W, H]', ...
'MenuBar', 'none', 'ToolBar', 'none', 'Units', 'Normalized');
imH = imagesc(frame);
colormap(gray);
% select an area
imRectH = imrect(get(imH, 'Parent'));
set(figH, 'Name', sprintf('Crop movie - [%d, %d, %d, %d]', round(imRectH.getPosition())));
fprintf('Cropping rectangle: [%d, %d, %d, %d]\n', round(imRectH.getPosition()));
imRectH.addNewPositionCallback(@(pos) {
set(figH, 'Name', sprintf('Crop movie - [%d, %d, %d, %d]', round(pos)));
fprintf('Cropping rectangle: [%d, %d, %d, %d]\n', round(imRectH.getPosition()));
});
return;
% if a cropping rectangle is defined but cropped movie alread exists, print warning and go on
elseif exist(moviePathCropped, 'file');
showWarning(this, 'OCIA:JTTrackMovies:CroppedMovieAlreadyExists', ...
sprintf('Cropped movie already exists at "%s". Skipping cropping...', moviePathCropped));
% switch to cropped file
this.path.moviePath = moviePathCropped;
this.jt.doCroppingStep = 0;
OCIA_dataWatcherProcess_trackMovies(this);
return;
% if a cropping rectangle is defined and file does not exist yet, crop movie
else
showMessage(this, 'Cropping movie ...', 'yellow');
% get VideoWriter object to write cropped movie
vwHand = VideoWriter(moviePathCropped, 'Uncompressed AVI');
vwHand.FrameRate = this.jt.frameRate;
open(vwHand);
% crop movie
for iFrame = 1 : nFrames;
% skip unwanted frames and switch directly to the required time
if ~isempty(this.jt.timeCrop) && iFrame < this.jt.timeCrop(1);
continue;
end;
% switch directly to the required time
if ~isempty(this.jt.timeCrop) && iFrame == this.jt.timeCrop(1);
vrHand.CurrentTime = iFrame / this.jt.frameRate;
end;
% skip unwanted frames
if ~isempty(this.jt.timeCrop) && iFrame > this.jt.timeCrop(2);
break;
end;
frame = readFrame(vrHand);
writeVideo(vwHand, imcrop(frame, this.jt.cropRect));
if ~isempty(this.jt.timeCrop);
DWWaitBar(this, 100 * ((iFrame - this.jt.timeCrop(1)) / diff(this.jt.timeCrop)));
else
DWWaitBar(this, 100 * (iFrame / nFrames));
end;
end
close(vwHand);
% switch to cropped file
this.path.moviePath = moviePathCropped;
this.jt.doCroppingStep = 0;
OCIA_dataWatcherProcess_trackMovies(this);
return;
end;
end;
%% load the movie
loadTic = tic; % for performance timing purposes
showMessage(this, 'Loading movie (avi)...', 'yellow');
% pre-allocate movie
oriFrames = zeros(H, W, nFrames);
% load movie frame by frame
DWWaitBar(this, 0);
pause(0.001); % required to let the GUI update itself
for iFrame = 1 : nFrames;
frame = nanmean(double(readFrame(vrHand)), 3);
o('Loaded frame %d', iFrame, 0, this.verb);
oriFrames(:, :, iFrame) = imcrop(frame, [0, 0, W, H]);
DWWaitBar(this, 100 * (iFrame / nFrames));
pause(0.001); % required to let the GUI update itself
end
% back up the frames
this.jt.oriFrames = oriFrames;
this.jt.frames = oriFrames;
showMessage(this, sprintf('Loading movie done (%3.1f sec).', toc(loadTic)));
elseif regexp(moviePath, '\.tif$');
loadTic = tic; % for performance timing purposes
showMessage(this, 'Loading movie (tiff)...', 'yellow');
% read the movie
tiffStruct = tiffread2(moviePath, 1, 10000, @(progressFrac)DWWaitBar(this, progressFrac * 100));
% get movie dimensions
W = tiffStruct.width;
H = tiffStruct.height;
% get the number of frames and store it
nFrames = size(tiffStruct, 2);
this.jt.nFrames = nFrames;
% pre-allocate movie and unwrap it frame by frame
this.jt.oriFrames = zeros(H, W, nFrames);
for iFrame = 1 : nFrames;
this.jt.oriFrames(:, :, iFrame) = double(tiffStruct(iFrame).data);
end
% back up the frames
this.jt.frames = this.jt.oriFrames;
showMessage(this, sprintf('Loading movie done (%3.1f sec).', toc(loadTic)));
end;
%% set JointTracker settings
this.jt.nJoints = size(this.jt.jointConfig, 1);
this.jt.joints = zeros(this.jt.nJoints, nFrames, 2, this.jt.nJointTypes);
this.GUI.jt.forcedJoints = false(this.jt.nJoints, nFrames, this.jt.nJointTypes);
this.GUI.jt.boundBoxPos = zeros(this.jt.nJoints, this.jt.nFrames, this.jt.nJointTypes, 4);
this.GUI.jt.jointValidity = nan(this.jt.nJoints, this.jt.nFrames);
this.GUI.jt.jointROIHandles = cell(this.jt.nJoints, 1);
this.jt.jointROIMasks = cell(this.jt.nJoints, 1);
%% initialize GUI
% change mode
OCIAChangeMode(this, 'JointTracker');
% replace the image by a dummy one by one dark pixel
this.GUI.jt.img = zeros(1, 1);
set(this.GUI.handles.jt.img, 'CData', linScale(this.GUI.jt.img));
set(this.GUI.handles.jt.axe, 'XLim', [0.5 1.5], 'YLim', [0.5 1.5]);
% adjust the display options setter
set(this.GUI.handles.jt.viewOpts.boundBoxes, 'Value', 0);
set(this.GUI.handles.jt.viewOpts.debugPlots, 'Value', 0);
set(this.GUI.handles.jt.viewOpts.ROIs, 'Value', 0);
set(this.GUI.handles.jt.viewOpts.jointDist, 'Value', 0);
set(this.GUI.handles.jt.viewOpts.validPlots, 'Value', 0);
set(this.GUI.handles.jt.viewOpts.preProc, 'Value', 0);
% adjust the joint and joint type setters
set(this.GUI.handles.jt.jointSelSetter, 'Value', 1);
this.GUI.jt.iJoint = 1;
set(this.GUI.handles.jt.jointTypeSelSetter, 'Value', 1);
this.GUI.jt.iJointType = 1;
% adjust the frame setter
this.GUI.jt.iFrame = 1;
set(this.GUI.handles.jt.frameSetter, 'Enable', 'on', 'Min', 1, 'Max', nFrames, 'Value', 1, ...
'SliderStep', [1 / nFrames 3 / nFrames]);
% update the frame label
currTimeTotSec = 1 / this.jt.frameRate;
currTimeMin = floor(currTimeTotSec / 60);
currTimeSec = floor(currTimeTotSec - currTimeMin * 60);
currTimeMSec = floor((currTimeTotSec - currTimeMin * 60 - currTimeSec) * 1000);
set(this.GUI.handles.jt.frameLabel, 'String', sprintf('F %03d\nT %02d:%02d.%03d\nM 0000 0000', ...
1, currTimeMin, currTimeSec, currTimeMSec));
% update the GUI
JTUpdateGUI(this, 'all');
% set the focus to the frame setter
uicontrol(this.GUI.handles.jt.frameSetter);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataWatcherProcess_importIJROIs.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataWatcherProcess/OCIA_dataWatcherProcess_importIJROIs.m
| 5,124 |
utf_8
|
01dcc93b17c38d8516f53940750a8bb4
|
%% #OCIA_dataWatcherProcess_importIJROIs
function OCIA_dataWatcherProcess_importIJROIs(this, ~, ~)
importIJROIsTic = tic; % for performance timing purposes
showMessage(this, 'Extracting and importing imageJ ROISet ...');
DWWaitBar(this, 0);
% get the index(es) of the ImageJ ROISet rows
ijROISetRows = DWFilterTable(this, 'rowType = IJ ROIs');
fullFolderPath = get(this, 1, 'path', ijROISetRows);
% check what's in the watchfolder and exclude irrelephant files
files = dir(fullFolderPath); % check out the content of the folder
files(arrayfun(@(x)x.isdir, files)) = []; % only keep files
% get the patterns for this watch type
patternsCell = this.dw.watchTypes{'ijroiset', 'subFilePatterns'};
patternsTable = patternsCell{1}; % extract the table from the cell
ijROISetPattern = patternsTable{strcmp(patternsTable.id, 'ijroisetFile'), 'pattern'};
ijROISetPattern = ijROISetPattern{1}; % extract the string from the cell
% exclude everything that is not an ImageJ ROISet
files(arrayfun(@(x) isempty(regexp(x.name, ijROISetPattern, 'once')), files)) = [];
nFiles = numel(files); % count the number of remaining files
o('#%s(): found %d roiset zip file(s).', mfilename(), nFiles, 3, this.verb);
% loop trough all existing files
for iFile = 1 : nFiles;
% get the file name
fileName = files(iFile).name;
o(' #%s(): processing file "%s".', mfilename(), fileName, 5, this.verb);
% extract the spot number
regexpHit = regexp(fileName, ijROISetPattern, 'names');
% if no hit were found
if isempty(regexpHit);
showWarning(this, 'OCIA:OCIA_dataWatcherProcess_importIJROIs:UnknownSpot', ...
sprintf('Could not extract the spot from file name "%s" using expression "%s". Skipping it.', ...
fileName, ijROISetPattern));
continue;
end;
showMessage(this, sprintf('Decoding ImageJ ROISet %02d/%02d ...', iFile, nFiles));
% extract the ImageJ ROISet
ijROISet = ij_roiDecoder(sprintf('%s%s', fullFolderPath, fileName), this.an.img.defaultImDim);
nROIs = size(ijROISet, 1); % count the number of ROIs
% pre-allocate a cell-array to store the imported/converted ROIs
ROIs = cell(nROIs, 4);
% pre-allocate a matrix for the ROI mask
ROIMask = zeros(size(ijROISet{1, 4}));
% go trough each ROI and convert it to the required form
for iROI = 1 : nROIs;
% create the ROI type
ROIs{iROI, 4} = sprintf('im%s', ijROISet{iROI, 2});
if this.dw.IJImportKeepROIName; % keep ROI's name but clean it up
ROIs{iROI, 2} = regexprep(ijROISet{iROI, 1}, '[^A-Za-z0-9]', '');
else % give a new name
ROIs{iROI, 2} = sprintf('%03d', iROI); % give ROI a name
end;
% store the coordinates
ROIs{iROI, 3} = ijROISet{iROI, 3};
% update the mask
ROIMask(ijROISet{iROI, 4}) = iROI;
end;
%% save using the ROIDrawer's save function
% check that the spot name can be recreated
if ~isfield(regexpHit, 'spot') && isfield(regexpHit, 'depth');
showWarning(this, 'OCIA:OCIA_dataWatcherProcess_importIJROIs:BadSpotHit', ...
sprintf('Could not extract the spot from regexp hit with expression "%s". Skipping it.', ...
ijROISetPattern));
continue;
end;
% get the DataWatcher indexes of the imaging data rows of that spot: create the spot filter
spotID = sprintf('Spot%s_%s', regexpHit.spot, regexpHit.depth);
imagingDataRows = DWFilterTable(this, sprintf('rowType = Imaging data AND spot = %s', spotID));
nImagingRows = size(imagingDataRows, 1);
% check whether we have some imaging rows for this spot
if isempty(imagingDataRows);
showWarning(this, 'OCIA:OCIA_dataWatcherProcess_importIJROIs:NoImagingData', ...
sprintf('Could not find any imaging data for file "%s" (spotID: %s). Skipping it.', ...
fileName, spotID));
continue;
end;
% set parameters
set(this.GUI.handles.rd.refROISet, 'Value', 0); % not ROISet mode
set(this.GUI.handles.rd.saveOpts.ROIs, 'Value', 1);
set(this.GUI.handles.rd.saveOpts.runsVal, 'Value', 1);
set(this.GUI.handles.rd.saveOpts.refIm, 'Value', 1);
this.rd.selectedTableRows = str2double(get(this, 'all', 'rowNum', imagingDataRows)); % mark selected rows
% put all rows in ROIDrawer's table, first row selected
set(this.GUI.handles.rd.tableList, 'String', cell(1, nImagingRows), 'Value', 1);
% copy ROIs, mask, etc.
this.rd.ROIs = ROIs;
this.rd.nROIs = size(ROIs, 1);
this.rd.ROIMask = ROIMask;
% save everything
RDSaveROIs(this);
% show message and update wait bar
showMessage(this, sprintf('Saving ImageJ ROISet %02/%02d to MAT-format done.', iFile, nFiles));
DWWaitBar(this, iFile * 100 / nFiles);
pause(0.5);
end;
% clear ROIDrawer mode and update wait bar
RDClearROIs(this);
set(this.GUI.handles.rd.tableList, 'String', {}, 'Value', []);
DWWaitBar(this, 100);
o('#%s(): importing ImageJ ROIs done (%3.1f sec).', mfilename(), toc(importIJROIsTic), 2, this.verb);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataWatcherProcess_onlineAnalysis.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataWatcherProcess/OCIA_dataWatcherProcess_onlineAnalysis.m
| 2,959 |
utf_8
|
be69fc0cc3a327f294c91a3b3ba66d94
|
function OCIA_dataWatcherProcess_onlineAnalysis(this, h, ~)
% OCIA_dataWatcherProcess_onlineAnalysis - [no description]
%
% OCIA_dataWatcherProcess_onlineAnalysis(this, h, ~)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
localVerb = 2;
% check if the online analysis button is actually a toggle button
set(this.GUI.handles.dw.onlineAnalysis, 'Style', 'togglebutton', 'BackgroundColor', 'yellow');
pause(0.01);
isActivateRequest = get(this.GUI.handles.dw.onlineAnalysis, 'Value');
% abort command
if ischar(h) && strcmp(h, 'abort');
isActivateRequest = false;
end;
% check if the timer is running
isOnlineAnalysisOnGoing = false;
if ~isempty(this.GUI.dw.onlineAnalysisTimer) && strcmp(this.GUI.dw.onlineAnalysisTimer.Running, 'on');
isOnlineAnalysisOnGoing = true;
end;
% re-activation of online analysis
if isOnlineAnalysisOnGoing && isActivateRequest;
o('#%s(): request for re-activating online analysis, skipping.', mfilename(), localVerb, this.verb);
% re-de-activation of online analysis
elseif ~isOnlineAnalysisOnGoing && ~isActivateRequest;
o('#%s(): request for re-de-activating online analysis, skipping.', mfilename(), localVerb, this.verb);
% activation of online analysis
elseif ~isOnlineAnalysisOnGoing && isActivateRequest;
o('#%s(): activating online analysis ...', mfilename(), localVerb, this.verb);
% stop previous eventual timer
stopOATimer(this);
% get online analysis function
onlineAnalysisFcn = OCIAGetCallCustomFile(this, 'onlineAnalysis', this.dw.onlineAnalysisFunctionName, 0, { this }, 1);
% create timer
this.GUI.dw.onlineAnalysisTimer = timer('BusyMode', 'drop', 'ExecutionMode', 'fixedSpacing', ...
'Name', 'onlineAnalysisTimer', 'Tag', 'DWOnlineAnalysisTimer', 'Period', this.GUI.dw.onlineAnalysisUpdatePeriod, ...
'TimerFcn', @(~, ~)onlineAnalysisFcn(this), 'ErrorFcn', @(~, ~)OCIA_dataWatcherProcess_onlineAnalysis(this, 'abort'), ...
'StartDelay', 0.2);
% start timer
start(this.GUI.dw.onlineAnalysisTimer);
% show message
showMessage(this, 'Started online analysis.');
% de-activation of online analysis
elseif isOnlineAnalysisOnGoing && ~isActivateRequest;
o('#%s(): de-activating online analysis ...', mfilename(), localVerb, this.verb);
stopOATimer(this);
% show message
showMessage(this, 'Stopped online analysis.');
end;
% update GUI
set(this.GUI.handles.dw.onlineAnalysis, 'BackgroundColor', iff(isActivateRequest, 'green', 'red'), ...
'Value', isActivateRequest);
o('#%s(): done.', mfilename(), localVerb, this.verb);
end
function stopOATimer(this)
% if there is a timer, stop it and delete it
if ~isempty(this.GUI.dw.onlineAnalysisTimer);
stop(this.GUI.dw.onlineAnalysisTimer);
delete(this.GUI.dw.onlineAnalysisTimer);
this.GUI.dw.onlineAnalysisTimer = [];
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataWatcherProcess_analyseRows_old.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataWatcherProcess/OCIA_dataWatcherProcess_analyseRows_old.m
| 3,918 |
utf_8
|
528fa9a37feb8773fc07c70a8c900e0e
|
%% #OCIA_dataWatcherProcess_analyseRows
function OCIA_dataWatcherProcess_analyseRows_old(this, ~, ~)
analyseRowsTic = tic; % for performance timing purposes
% store the selected rows so that even changing the selection in the DataWatcher mode does not affect the Analyser
this.an.selectedTableRows = this.dw.selectedTableRows;
% if no row selected, abort with a warning
nRows = numel(this.an.selectedTableRows); % count the number of selected rows
if nRows == 0;
showWarning(this, 'OCIA:OCIA_dataWatcherProcess_analyseRows:NoRows', 'No rows selected.');
return;
end;
o('#OCIA_dataWatcherProcess_analyseRows(): selected rows (%d): %s', nRows, ...
sprintf('%d ', this.an.selectedTableRows), 2, this.verb);
% empty/reset the table, the plot list and the ROI list
set(this.GUI.handles.an.rowList, 'String', [], 'Value', [], 'ListBoxTop', 1);
set(this.GUI.handles.an.ROIList, 'String', [], 'Value', [], 'ListBoxTop', 1);
%% - #OCIA_dataWatcherProcess_analyseRows : load/pre-process/analyse selected rows
loadDataTic = tic; % for performance timing purposes
OCIAGetCallCustomFile(this, 'preprocess', this.dw.preProcessFunctionName, 1, { this }, 1);
o('#OCIA_dataWatcherProcess_analyseRows(): pre-processing data done (%3.1f sec).', toc(loadDataTic), 2, this.verb);
%% - #OCIA_dataWatcherProcess_analyseRows : prepare analyser panel
% generate labels for the selected rows
rowLabels = cell(nRows, 1);
tIDs = this.dw.tableIDs; % get the table IDs
for iRow = 1 : nRows;
iDWRow = this.an.selectedTableRows(iRow); % get the DataWatcher's table row index
rowLabels{iRow} = ''; % empty label is default
% create the display using the column names specified in the config
colNames = this.GUI.an.DWTableColumnsToUse;
for iCol = 1 : numel(colNames);
% get the row ID using the dedicated function
if strcmp(colNames{iCol}, 'rowID');
rowLabels{iRow} = sprintf('%s - %s', rowLabels{iRow}, DWGetRowID(this, iDWRow));
% otherwise just fetch the value from the DataWatcher's table
else
rowLabels{iRow} = sprintf('%s - %s', rowLabels{iRow}, ...
this.dw.table{iDWRow, strcmp(tIDs, colNames{iCol})});
end;
end;
rowLabels{iRow} = regexprep(rowLabels{iRow}, '^\s+-\s+', ''); % clean up the label
rowLabels{iRow} = regexprep(rowLabels{iRow}, '-\s+-', '-'); % clean up the label
rowLabels{iRow} = regexprep(rowLabels{iRow}, '- $', ''); % clean up the label
end;
% fill in the listBox items of the analyser panel
set(this.GUI.handles.an.rowList, 'String', rowLabels, 'Value', [], 'ListBoxTop', 1);
set(this.GUI.handles.an.plotList, 'Value', [], 'ListBoxTop', 1);
% clear the plot area and show the loading message
ANClearPlot(this);
ANShowHideMessage(this, 1);
OCIAChangeMode(this, 'Analyser');
% reset the lists
set(this.GUI.handles.an.plotList, 'Value', [], 'ListBoxTop', 1);
set(this.GUI.handles.an.rowList, 'Value', [], 'ListBoxTop', 1);
set(this.GUI.handles.an.ROIList, 'Value', [], 'ListBoxTop', 1);
%% - #OCIA_dataWatcherProcess_analyseRows : plot
plotDataTic = tic; % for performance timing purposes
currAnalysis = [];
% select a default first plot to display depending on the data type
switch this.dw.table{this.an.selectedTableRows(1), strcmp(tIDs, 'rowType')};
case 'imgData';
currAnalysis = find(strcmp(this.an.analysisTypes.id, 'caTraces_basic'));
case 'behavData';
currAnalysis = find(strcmp(this.an.analysisTypes.id, 'behav_dprime'));
end;
% select the first row and the default plot
set(this.GUI.handles.an.rowList, 'Value', 1);
set(this.GUI.handles.an.plotList, 'Value', currAnalysis);
% do the analysis / plot
ANUpdatePlot(this, 'force');
o('#OCIA_dataWatcherProcess_analyseRows(): plotting done (%3.1f sec).', toc(plotDataTic), 2, this.verb);
o('#OCIA_dataWatcherProcess_analyseRows(): analyse rows done (%3.1f sec).', toc(analyseRowsTic), 2, this.verb);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataWatcherProcess_saveResults.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataWatcherProcess/OCIA_dataWatcherProcess_saveResults.m
| 3,035 |
utf_8
|
42d498164768321b83ac3e51df89af8c
|
%% #OCIA_dataWatcherProcess_saveResults
function OCIA_dataWatcherProcess_saveResults(this, ~, ~)
% get imaging rows
% imgRows = DWFindTableRows(this, 'imgData', '', '', '', '', '', '');
imgRows = this.dw.selectedTableRows;
% loop trough all rows
for iRow = 1 : numel(imgRows);
% get the run ID
rowID = sprintf('%s__%s', this.dw.table{imgRows(iRow), 2 : 3});
% rowIDWithUnderScoreX = sprintf('%s_X%s', rowID, this.dw.table{imgRows(iRow), 9});
% get the path for this row and modify it
fullFolderPath = DWGetFullPath(this, imgRows(iRow));
targetDir = regexprep(fullFolderPath, '/$', sprintf('/%sh_MF/', rowID));
% get the ROISet for this row
ROISet = ANGetROISetForRow(this, imgRows(iRow));
% get the data for this row
caData = this.data.img.caTraces{imgRows(iRow)};
% if there is some data
if ~isempty(caData) && ~isempty(ROISet);
% create the structure
Ca = struct();
Ca.roiLabel = ROISet(:, 1);
% create the directory if needed
if exist(targetDir, 'dir') ~= 7; mkdir(targetDir); end;
% load the calcium data in the right format
Ca.dRR = cell(numel(Ca.roiLabel), 1);
for iROI = 1 : numel(Ca.roiLabel);
Ca.dRR{iROI, 1} = repmat(caData(iROI, :), 2, 1);
end;
% save the data
save(sprintf('%somlortest_%s.mat', targetDir, rowID), 'Ca');
% copy the other files
clickJointFolder = regexprep(targetDir, '_MF/$', '_ClickJoint/');
clickJointFile = sprintf('%sMotor_Output_Parameters_%sh_Raw', clickJointFolder, this.dw.table{imgRows(iRow), 3});
if exist(clickJointFolder, 'dir') && exist(clickJointFile, 'file');
clickJointFileTarget = regexprep(clickJointFile, '_ClickJoint/', '_MF/');
copyfile(clickJointFile, clickJointFileTarget);
FID1 = fopen(clickJointFileTarget);
FMOPs = textscan(FID1, '%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %*[^\n]', ...
'Delimiter', '\t', 'HeaderLines', 1);
fclose(FID1);
FMOPs = cell2mat(FMOPs);
xlswrite([clickJointFileTarget '.xlsx'], FMOPs);
delete(clickJointFileTarget);
end;
% csv file
csvFileName = dir([fullFolderPath '*.csv']);
if ~isempty(csvFileName);
csvFileSource = [fullFolderPath csvFileName.name];
csvFileTarget = [targetDir csvFileName.name];
copyfile(csvFileSource, csvFileTarget);
FID2 = fopen(csvFileTarget);
MVs = textscan(FID2, '%f %f %*[^\n]', 'Delimiter', ';');
fclose(FID2);
MVs = cell2mat(MVs);
xlswrite(strrep(csvFileTarget, '.csv', '.xlsx'), MVs);
delete(csvFileTarget);
end;
end;
end;
o('#OCIA_dataWatcherProcess_saveResults(): saving results done.', 2, this.verb);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_moDet.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_moDet.m
| 15,192 |
utf_8
|
6feea3c4ee368f580b086b9938bd6a03
|
%% #OCIA:OCIA_dataProcess_imgData_moDet
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_moDet(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's processing state
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
rowProcState = getData(this, iDWRow, 'procImg', 'procState');
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'moDet')) || ~strcmp(get(this, iDWRow, 'rowType'), 'Imaging data') ...
|| any(strcmp(rowProcState, 'moDet'));
return;
end;
% get whether to do plots or not
if nargin > 2; doPlots = varargin{1};
else doPlots = 0;
end;
% get whether to do plots or not
if nargin > 3; iRun = varargin{2};
else iRun = 1;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% init
rowID = DWGetRowID(this, iDWRow);
rowIDTitle = sprintf('Motion detection (Z) for %s (%d)', rowID, iDWRow);
% figCommons = {'NumberTitle', 'off'}; % figure options
figCommons = {'NumberTitle', 'off', 'WindowStyle', 'docked'}; % figure options
% get the ROISet for this row and the row of the reference image
[ROISet, ~, ~, ~, avgImgRefCell] = ANGetROISetForRow(this, iDWRow);
nROIs = size(ROISet, 1);
% make sure we have an image and not a cell, use the specified pre-procesing channel if required
if iscell(avgImgRefCell); avgImgRef = avgImgRefCell{this.an.img.preProcChan};
else avgImgRef = avgImgRefCell;
end;
% if no reference average image, try to fetch it from the ROIDrawer
if isempty(avgImgRef);
currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};
selRDTableRow = get(this.GUI.handles.rd.tableList, 'Value');
% if we are in ROIDrawer mode and there is a selected row in the run table
if strcmp(currentMode, 'ROIDrawer') && ~isempty(this.rd.selectedTableRows) && ~isempty(selRDTableRow);
% get the row index of the DataWatcher's table
iDWRefRow = this.rd.selectedTableRows(selRDTableRow(1));
% get the reference average image as the mean of pre-processed frames
imgDataRefRow = get(this, iDWRefRow, 'data');
avgImgRef = nanmean(imgDataRefRow.procImg.data{this.an.img.preProcChan}, 3);
end;
end;
% if no reference average image, abort
if isempty(avgImgRef);
showWarning(this, 'OCIA:OCIA_dataProcess_imgData_moDet:NoReferenceImage', ...
sprintf('%s: No reference image found. Aborting.', rowIDTitle));
isValid = false;
return;
end;
% if no ROISet found, create fake ROISet
if ~nROIs;
o('%s: no ROISet found, using fake ROIs ...', mfilename(), 2, this.verb);
% make sure data is fully loaded
DWLoadRow(this, iDWRow, 'full');
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% get the imaging data
imgData = get(this, iDWRow, 'data');
imgData = imgData.procImg.data;
imgDim = size(imgData{this.an.img.preProcChan});
% create the fake ROISet
[ROISet, nROIs] = createFakeROISet(imgDim(1:2), imgDim(1) * 0.05, 10, 10);
end;
showMessage(this, sprintf('%s ...', rowIDTitle), 'yellow');
% make sure the data is fully loaded
DWLoadRow(this, iDWRow, 'full');
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% prepare reference image and frames
% get the imaging data
imgData = get(this, iDWRow, 'data');
imgData = imgData.procImg.data;
% get the average of all frames of the pre-processing channel
avgImg = nanmean(imgData{this.an.img.chanVect(1)}, 3);
avgImgOri = avgImg; % save a copy of the original
% get the movie of all frames of pre-processing channel
imgMovie = imgData{this.an.img.chanVect(1)};
imgMovieOri = imgMovie; % save a copy of the original
imgDim = size(imgMovie);
%% filter frames if requested
% if requested, apply a "small" filtering on the movie to have enhanced correlations
if this.an.moDet.useFilt;
filtTic = tic; % for performance timing purposes
imgMovie = zeros(imgDim);
f = fspecial('gaussian', 2, 1);
parfor iFrame = 1 : imgDim(3);
imgMovie(:, :, iFrame) = imfilter(imgMovieOri(:, :, iFrame), f, 'replicate');
% imgMovie(:, :, iFrame) = medfilt2(imgMovieOri(:, :, iFrame), [2 2], 'symmetric');
end;
% get a filtered version of the reference average
avgImgRef = imfilter(avgImgRef, f, 'replicate');
o('%s: filtering done (%3.1f sec).', rowIDTitle, toc(filtTic), 2, this.verb);
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% %{
%% ROI-pooled frame correlation based on a "bright" ROISet
percBoundBox = 0.04; % percent of image around the ROI's bounding box
% use only the 50% brightest ROIs, but at least 25 ROIs but not more than "nROIs" ROIs
nBrightROIs = min(max(round(nROIs * 0.5), 25), nROIs);
% get the ROISet of the brightest ROIs
brightROISet = getBrightROIs(ROISet, avgImgRef, nBrightROIs, percBoundBox, doPlots - 1);
% calculate and store the correlation of each ROI's image to the average image
frameCorrsROI = getFrameCorrROI(brightROISet, percBoundBox, avgImgRef, imgMovie);
% average the correlations obtained from the bright ROIs
frameCorrs = nanmean(frameCorrsROI);
%}
%{
%% Frame-wise correlation
frameCorrs = getFrameCorr(avgImgRef, imgMovie);
%}
%% calculate thresholds
frameCorrMed = nanmedian(frameCorrs); % get the median if the correlations obtained from the bright ROIs
frameCorrStd = nanstd(frameCorrs); % get the standard deviation of the correlations obtained from the bright ROIs
% get the out of focuse correlation drop tolerance based on the standard deviation
correlationDropTolerance = max(this.an.moDet.threshFactor * frameCorrStd, 0.1);
% create a threshold under which frames are classified as out of focus and should be excluded
outOfFocusThresh = frameCorrMed - correlationDropTolerance;
% create a threshold where the correlation is good enough again that frames can be classified as in focus again
backInFocusThresh = frameCorrMed - correlationDropTolerance * 0.25;
o('%s: thresholds: median: %.3f, correlation drop tolerance: %.3f, out of focus: %.3f, back in focus: %.3f.', ...
rowIDTitle, frameCorrMed, correlationDropTolerance, outOfFocusThresh, backInFocusThresh, 2, this.verb);
%% get frames to exclude
% get the excluded frames and the "mask" corresponding to them
exclFrameMask = frameCorrs < outOfFocusThresh;
exclFrames = find(exclFrameMask); % get the excluded frames' indexes
% if removing single frames is allowed, do not exclude no-neighbor frames
if ~this.an.moDet.removeSingleFrames;
% do not exclude frames that have no neighboring excluded frames
toRemoveExclFrames = false(1, imgDim(3));
nMinNeighbors = 3;
for iFrame = 2 : imgDim(3) - 1;
if ismember(iFrame, exclFrames);
nNeighbors = sum(ismember(iFrame - (nMinNeighbors - 1) : iFrame + (nMinNeighbors - 1), exclFrames));
toRemoveExclFrames(iFrame) = nNeighbors < nMinNeighbors;
end;
end;
% remove the frames that had no neighbors
exclFrames(ismember(exclFrames, find(toRemoveExclFrames))) = [];
end;
% build the excluded frame "mask"
exclFrames = sort(exclFrames);
exclFrameMask = false(1, imgDim(3));
exclFrameMask(exclFrames) = true;
exclFrameMaskBeforeExt = exclFrameMask; % get a copy before exclusion extension
% show message
plurFrame = ''; if exclFrames; plurFrame = 's'; end; % get the plural mark
o('%s: found %d frame%s to exclude before extension (%.1f%%).', ...
rowIDTitle, numel(exclFrames), plurFrame, 100 * numel(exclFrames) / imgDim(3), 2, this.verb);
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% frame exclusion extension to neighbors
% extend the excluded frames to the neighboring frames so that all motion is removed. The excluded frames are
% processed as a queue
extTic = tic; % for performance timing purposes
exclFrameQueue = exclFrames; % create the queue
if doPlots > 2; figure('Name', sprintf('%s: frame correlations', rowIDTitle), figCommons{:}); end;
while ~isempty(exclFrameQueue);
iFrame = exclFrameQueue(1); % get the first element
elemReplaced = 0; % set a flag to see if element was replaced, otherwise it should be removed
% check if the previous frame should be excluded: not first frame & not already in queue or in excluded frames &
% corr. coef. not above back in focus threshold & corr. coef. higher than current frame (going up the slope)
% if iFrame > 1 && ~ismember(iFrame - 1, exclFrameQueue) && ~ismember(iFrame - 1, exclFrames) ...
% && frameCorrs(iFrame - 1) < backInFocusThresh && frameCorrs(iFrame - 1) > frameCorrs(iFrame);
if iFrame > 1 && ~ismember(iFrame - 1, exclFrameQueue) && ~ismember(iFrame - 1, exclFrames) ...
&& frameCorrs(iFrame - 1) < backInFocusThresh;
% add the frame to the excluded frames
exclFrames(end + 1) = iFrame - 1; %#ok<AGROW>
% add the frame to the queue in place of the currently processed frame
exclFrameQueue(1) = iFrame - 1;
elemReplaced = true;
end;
% check if the next frame should be excluded: not last frame & not already in queue or in excluded frames &
% corr. coef. not above back in focus threshold & corr. coef. higher than current frame (going up the slope)
% if iFrame < imgDim(3) && ~ismember(iFrame + 1, exclFrameQueue) && ~ismember(iFrame + 1, exclFrames) ...
% && frameCorrs(iFrame + 1) < backInFocusThresh && frameCorrs(iFrame + 1) > frameCorrs(iFrame);
if iFrame < imgDim(3) && ~ismember(iFrame + 1, exclFrameQueue) && ~ismember(iFrame + 1, exclFrames) ...
&& frameCorrs(iFrame + 1) < backInFocusThresh;
% add the frame to the excluded frames
exclFrames(end + 1) = iFrame + 1; %#ok<AGROW>
% if element was not already replaced, add the frame to the queue in place of the currently processed frame
if ~elemReplaced;
exclFrameQueue(1) = iFrame + 1;
else % otherwise extend the queue
exclFrameQueue(end + 1) = iFrame + 1; %#ok<AGROW>
end;
elemReplaced = true;
end;
% if the element was not replaced by another neighbor, remove it from the queue without any replacement
if ~elemReplaced; exclFrameQueue(1) = []; end;
end
% sort the excluded frames and re-create the mask
exclFrames = sort(exclFrames);
exclFrameMask = false(1, imgDim(3));
exclFrameMask(exclFrames) = true;
plurFrame = ''; if exclFrames; plurFrame = 's'; end; % get the plural mark
o('%s: found %d frame%s to exclude after extension (%.1f%%) (%3.1f sec).', ...
rowIDTitle, numel(exclFrames), plurFrame, 100 * numel(exclFrames) / imgDim(3), toc(extTic), 2, this.verb);
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% debug plotting
if doPlots > 0; % if requested, plot a figure illustrating the motion correction procedure and result
figure('Name', sprintf('%s: frame correlations', rowIDTitle), figCommons{:});
axeHandles = zeros(2, 1);
for iSub = 1 : 2;
subplot(2, 1, iSub);
plot(frameCorrs, 'g');
hold on;
axeHandles(iSub) = gca;
% get the frame correlations and hide those from the excluded frames (before and after extension)
exclFrameCorrs = frameCorrs;
if iSub == 1; exclFrameCorrs(~exclFrameMaskBeforeExt) = NaN;
elseif iSub == 2; exclFrameCorrs(~exclFrameMask) = NaN; end;
plot(exclFrameCorrs, 'r');
plot([1 imgDim(3)], repmat(frameCorrMed, 1, 2), 'b');
plot([1 imgDim(3)], repmat(backInFocusThresh, 1, 2), 'k:');
plot([1 imgDim(3)], repmat(outOfFocusThresh, 1, 2), 'r:');
ylim([0 1]);
legend({'Valid frame corr.', 'Exc. frame corr.', 'Median', 'back-in-focus thres.', ...
'out-of-focus thresh.'}, 'FontSize', 8, 'Location', 'SouthEast');
end;
linkaxes(axeHandles, 'xy');
% get the average of all valid frames of the pre-processing channel channel
avgImgCorr = nanmean(imgData{this.an.img.chanVect(1)}(:, :, ~exclFrameMask), 3);
% get the average of all non-valid frames of the pre-processing channel channel
avgImgBadFrames = nanmean(imgData{this.an.img.chanVect(1)}(:, :, exclFrameMask), 3);
figure('Name', sprintf('%s: average', rowIDTitle), figCommons{:});
subplot(2, 2, 1); imshow(linScale(avgImgOri)); title('Original');
subplot(2, 2, 2); imshow(linScale(avgImgRef)); title('Reference');
subplot(2, 2, 3); imshow(linScale(avgImgBadFrames)); title('Bad frames average');
subplot(2, 2, 4); imshow(linScale(avgImgCorr)); title('Corrected');
end; % end of plotting if case
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% create a mask
if ~isempty(exclFrames); % if there are some excluded frames, add those to the mask
% create an exclusion mask as a matrix of nROIs x nFrames (similar to the caTraces mask)
exclMask = ones(nROIs, imgDim(3));
exclMask(1 : nROIs, exclFrames) = NaN;
% store the exclusion mask
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.exclMask.data = exclMask;
end;
%{
%% --- #OCIA:AN:MotionDetection: process and store data with motion detection
if ~isempty(exclFrames); % if there are some excluded frames, replace them with NaNs
% create a corrected data set
imgDataCorr = imgData;
% go through each channel
for iChan = 1 : numel(imgDataCorr);
% replace the exlcuded frames with NaNs
imgDataChan = imgDataCorr{iChan};
% go through each frame and replace it if necessary
parfor iFrame = 1 : size(imgDataChan, 3);
if exclFrameMask(iFrame);
imgDataChan(:, :, iFrame) = nan(size(imgDataChan(:, :, iFrame))); % replace with NaN
end;
end;
imgDataCorr{iChan} = imgDataChan; % copy back the corrected data
end;
imgData = imgDataCorr; % copy back the corrected data
setData(this, iDWRow, 'procImg', 'data', imgData); % store the corrected data
end;
%}
% if a lot of frames where to be excluded, re-run the motion detection
if numel(exclFrames) > imgDim(3) * 0.08 && iRun < 3;
[isValid, unvalidReason] = OCIA_dataProcess_imgData_moDet(this, iDWRow, doPlots, iRun + 1);
return;
end;
% mark row as processed for motion detection
setData(this, iDWRow, 'procImg', 'procState', [rowProcState { 'moDet' }]);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_skipFrame.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_skipFrame.m
| 1,915 |
utf_8
|
e6b8685e6992028e7df3f99b7ba25864
|
%% #OCIA:OCIA_dataProcess_imgData_skipFrame
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_skipFrame(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's processing state
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
rowProcState = getData(this, iDWRow, 'procImg', 'procState');
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'skipFrame')) || ~strcmp(get(this, iDWRow, 'rowType'), 'Imaging data') ...
|| any(strcmp(rowProcState, 'skipFrame')) ...
|| (this.an.skipFrame.nFramesBegin <= 0 && this.an.skipFrame.nFramesEnd <= 0);
return;
end;
% get whether to do plots or not
if nargin > 2; doPlots = varargin{1};
else doPlots = 0;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% make sure data is fully loaded
DWLoadRow(this, iDWRow, 'full');
% get the imaging data
imgData = get(this, iDWRow, 'data');
imgData = imgData.procImg.data;
% remove the first frame(s) from each channel
for iChan = 1 : numel(imgData);
imgData{iChan} = imgData{iChan}(:, :, 1 + this.an.skipFrame.nFramesBegin : end - this.an.skipFrame.nFramesEnd);
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% store the change
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.procImg.data = imgData;
% mark row as processed for this processing step
setData(this, iDWRow, 'procImg', 'procState', [rowProcState { 'skipFrame' }]);
%% plotting
% if requested, plot a figure illustrating what has been done
if doPlots > 0;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_moCorr_HMM.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_moCorr_HMM.m
| 994 |
utf_8
|
14c90ea89a699cbba11589d9202ad1fd
|
%% #OCIA:OCIA_dataProcess_imgData_moCorr_HMM
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_moCorr_HMM(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's processing state
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
rowProcState = getData(this, iDWRow, 'procImg', 'procState');
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'moCorr')) || ~strcmp(get(this, iDWRow, 'rowType'), 'Imaging data') ...
|| any(strcmp(rowProcState, 'moCorr'));
return;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%%
% mark row as processed for motion correction
setData(this, iDWRow, 'procImg', 'procState', [rowProcState { 'moCorr' }]);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData.m
| 4,270 |
utf_8
|
079515d1ffc08676c79160f68b6b1a54
|
%% #OCIA:OCIA_dataProcess_imgData
function [isValid, unvalidReason] = OCIA_dataProcess_imgData(this, iDWRow)
% set a flag that tells whether this row is valid for processing or not
isValid = false;
% create a string holding the reason why this row was flagged as not valid
unvalidReason = 'unknown reason';
rowID = DWGetRowID(this, iDWRow); % get the row ID
dimTag = get(this, iDWRow, 'dim'); % get the dimension tag
nFrames = str2double(strrep(regexp(dimTag, 'x\d+$', 'match'), 'x', '')); % get the number of frames
% if the number of frames is smaller than "funcMovieNFramesLimit" frames, movie is not a functional movie
if nFrames <= this.an.img.funcMovieNFramesLimit;
isValid = false; % set the validity flag to false
% store the reason why this row was not valid
unvalidReason = sprintf('not a functional imaging movie (nFrames = %d, limit = %d)', nFrames, ...
this.an.img.funcMovieNFramesLimit);
return; % abort processing of this row
end;
% check whether to show the debug plots or not
showDebugPlots = get(this.GUI.handles.dw.SLROpts.procDataShowDebug, 'Value');
% if calcium data is not present
if isempty(getData(this, iDWRow, 'caTraces', 'data'));
% get the selected processing steps and this row's processing state
selProcSteps = get(this.GUI.handles.dw.procOptsList, 'Value');
rowProcState = getData(this, iDWRow, 'procImg', 'procState');
% go through each step and execute the associated function
nSteps = size(this.an.procOptions.id, 1);
for iStep = 1 : nSteps;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason);
if doAbort; return; end;
% get the processing step's id and label
stepID = this.an.procOptions.id{iStep};
stepLabel = this.an.procOptions.label{iStep};
% if processing step is not selected, skip it
if ~ismember(iStep, selProcSteps); continue; end;
% if processing step if loading, load the row fully
if strcmp(stepID, 'loadData');
DWLoadRow(this, iDWRow, 'full');
continue;
end;
% if processing step is already done for the current row, skip it with a message
if any(strcmp(rowProcState, stepID));
showMessage(this, sprintf('%s for %s (%03d) already done.', stepLabel, rowID, iDWRow));
continue;
end;
% call the custom function for this processing step
warning('off', 'OCIA:dataProcess_imgData:FunctionNotFound');
[funcHandle, validityCell] = OCIAGetCallCustomFile(this, 'dataProcess_imgData', ...
stepID, 1, { this, iDWRow, showDebugPlots }, 0);
warning('on', 'OCIA:dataProcess_imgData:FunctionNotFound');
% if the function was found (function handle not empty) and the row is valid
if ~isempty(funcHandle) && ~isempty(validityCell) && numel(validityCell) >= 2 && validityCell{1};
% show step is complete
showMessage(this, sprintf('%s for %s (%03d) done.', stepLabel, rowID, iDWRow));
% if the function was not found (function handle is empty), show warning and go on
elseif isempty(funcHandle);
showWarning(this, 'OCIA:dataProcess_imgData:ProcessFunctionNotFound', ...
sprintf('%s for %s (%03d): no processing function found ("%s"), skipping this step.', ...
stepLabel, rowID, iDWRow, stepID));
% if the row was flagged as not valid
elseif ~isempty(validityCell) && numel(validityCell) >= 2;
[isValid, unvalidReason] = validityCell{:};
return;
% otherwise something else went wrong
else
isValid = false;
unvalidReason = 'unknown error';
return;
end;
% allow time for GUI update
if isGUI(this); pause(0.005); end;
end;
end;
% update the row's loading and processing status
DWGetUpdateDataLoadStatus(this, iDWRow);
% if we managed to come this far, then the row is valid and unvalidity reason is empty
isValid = true;
unvalidReason = '';
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_moCorr.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_moCorr.m
| 1,449 |
utf_8
|
e046854327443ac0fc19c58b8212ce05
|
%% #OCIA:OCIA_dataProcess_imgData_moCorr
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_moCorr(this, iDWRow, varargin)
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, [], []); if doAbort; return; end;
% call the custom function for the selected type of motion correction (TurboReg, HMM, ...)
warning('off', 'OCIA:OCIA_dataProcess_imgData_moCorrFunctionNotFound');
[funcHandle, validityCell] = OCIAGetCallCustomFile(this, 'dataProcess_imgData_moCorr', ...
this.an.moCorr.type, 1, { this, iDWRow, varargin{:} }, 0); %#ok<CCAT>
warning('on', 'OCIA:OCIA_dataProcess_imgData_moCorrFunctionNotFound');
% if the function was found (function handle not empty) and the row is valid
if ~isempty(funcHandle) && ~isempty(validityCell) && numel(validityCell) >= 2 && validityCell{1};
[isValid, unvalidReason] = validityCell{:};
% if the function was not found (function handle is empty), show warning and go on
elseif isempty(funcHandle);
isValid = false;
unvalidReason = sprintf('no processing function found for motion correction type "%s"', this.an.moCorr.type);
% if the row was flagged as not valid
elseif ~isempty(validityCell) && numel(validityCell) >= 2;
[isValid, unvalidReason] = validityCell{:};
return;
% otherwise something else went wrong
else
isValid = false;
unvalidReason = 'unknown error';
return;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_genStimVect.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_genStimVect.m
| 1,875 |
utf_8
|
6acd477616696fcc37880a714b4fb587
|
%% #OCIA:OCIA_dataProcess_imgData_genStimVect
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_genStimVect(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's processing state
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
caData = getData(this, iDWRow, 'caTraces', 'data');
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'genStimVect')) || ~strcmp(get(this, iDWRow, 'rowType'), 'Imaging data') ...
|| ~isempty(caData);
return;
end;
% get whether to do plots or not
if nargin > 2; doPlots = varargin{1};
else doPlots = 0;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% generate the stimulus vector using the custom function, and get out the validity cell-array as output
[funcHandle, validityCell] = OCIAGetCallCustomFile(this, 'genStimVect', ...
this.an.stimulusVectorGeneratingFunctionName, 1, { this, iDWRow, doPlots }, 0);
% if the generate stimulus function was not found (function handle is empty) or if no validity cell is returned
if isempty(funcHandle) || isempty(validityCell);
% create the unvalidity reason
isValid = false;
unvalidReason = 'function not found';
return; % abort processing of this row
% if there was an error and the validity was returned but is false (first element of the validity cell-array)
elseif ~isempty(validityCell) && ~validityCell{1};
% extract the validity and the unvalidity reason into the output parameters
[isValid, unvalidReason] = validityCell{:};
return; % abort processing of this row
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_wfTr_genStimVect.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_wfTr_genStimVect.m
| 1,781 |
utf_8
|
89ca04b9628644f1348a94b4b2c2f1e0
|
%% #OCIA:OCIA_dataProcess_wfTr_genStimVect
function [isValid, unvalidReason] = OCIA_dataProcess_wfTr_genStimVect(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's processing state
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'genStimVect')) || ~strcmp(get(this, iDWRow, 'rowType'), 'WF trial');
return;
end;
% get whether to do plots or not
if nargin > 2; doPlots = varargin{1};
else doPlots = 0;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% generate the stimulus vector using the custom function, and get out the validity cell-array as output
[funcHandle, validityCell] = OCIAGetCallCustomFile(this, 'genStimVect', ...
this.an.stimulusVectorGeneratingFunctionName, 1, { this, iDWRow, doPlots }, 0);
% if the generate stimulus function was not found (function handle is empty) or if no validity cell is returned
if isempty(funcHandle) || isempty(validityCell);
% create the unvalidity reason
isValid = false;
unvalidReason = 'function not found';
return; % abort processing of this row
% if there was an error and the validity was returned but is false (first element of the validity cell-array)
elseif ~isempty(validityCell) && ~validityCell{1};
% extract the validity and the unvalidity reason into the output parameters
[isValid, unvalidReason] = validityCell{:};
return; % abort processing of this row
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_behavData.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_behavData.m
| 605 |
utf_8
|
9558137229f20b8370a63ae3b653739e
|
%% #OCIA:OCIA_dataProcess_behavData
function [isValid, unvalidReason] = OCIA_dataProcess_behavData(this, iDWRow)
% set a flag that tells whether this row is valid for processing or not
isValid = false; %#ok<NASGU>
% create a string holding the reason why this row was flagged as not valid
unvalidReason = 'unknown reason'; %#ok<NASGU>
% load the row
DWLoadRow(this, iDWRow, 'full');
% update the row's loading and processing status
DWGetUpdateDataLoadStatus(this, iDWRow);
% if we managed to come this far, then the row is valid and unvalidity reason is empty
isValid = true;
unvalidReason = '';
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_fJitt.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_fJitt.m
| 13,736 |
utf_8
|
9b86b78d25f09c9835279897968bf35c
|
%% #OCIA:OCIA_dataProcess_imgData_fJitt
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_fJitt(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's processing state
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
rowProcState = getData(this, iDWRow, 'procImg', 'procState');
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'fJitt')) || ~strcmp(get(this, iDWRow, 'rowType'), 'Imaging data') ...
|| any(strcmp(rowProcState, 'fJitt'));
return;
end;
% get whether to do plots or not
if nargin > 2; doPlots = varargin{1};
else doPlots = 0;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% init
rowID = DWGetRowID(this, iDWRow);
rowIDTitle = sprintf('Frame jitter correction for %s (%d)', rowID, iDWRow);
figCommons = { 'NumberTitle', 'off', 'WindowStyle', 'docked' }; % figure options
% get the ROISet for this row
ROISet = ANGetROISetForRow(this, iDWRow);
nROIs = size(ROISet, 1);
% if no ROISet found, create fake ROISet
if ~nROIs;
o('%s: no ROISet found, using fake ROIs ...', mfilename(), 2, this.verb);
% make sure data is fully loaded
DWLoadRow(this, iDWRow, 'full');
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% get the imaging data
imgData = get(this, iDWRow, 'data');
imgData = imgData.procImg.data;
imgDim = size(imgData{this.an.img.preProcChan});
% create the fake ROISet
[ROISet, nROIs] = createFakeROISet(imgDim(1:2), imgDim(1) * 0.05, 10, 10);
end;
percBoundBox = 0.04; % percent of image around the ROI's bounding box
% range of pixel shift to test
shifts = -3 : 3;
% use only the 10% brightest ROIs, but at least 5 ROIs but not more than "nROIs" ROIs
nBrightROIs = min(max(round(nROIs * 0.1), 5), nROIs);
% make sure data is fully loaded
DWLoadRow(this, iDWRow, 'full');
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% get the imaging data
imgData = get(this, iDWRow, 'data');
imgData = imgData.procImg.data;
imgDim = size(imgData{this.an.img.preProcChan});
% number of frames in a "chunck" of data to analyse, about the tenth of the frames but at least one second of data
nFrameAvg = round(max(ceil(imgDim(3) / 10), this.an.img.defaultFrameRate));
%% - #OCIA:AN:ANFrameJitterCorrection: loop on chuncks of data
nChuncks = ceil(imgDim(3) / nFrameAvg); % calculate the number of chuncks
for iChunck = 1 : nChuncks;
% get the frame range for this chunck, removing frames exceeding limits
frameRange = ((iChunck - 1) * nFrameAvg + 1) : min(iChunck * nFrameAvg, imgDim(3));
% get the average of all frames of the pre-processing channel
avgImg = nanmean(imgData{this.an.img.preProcChan}(:, :, frameRange), 3);
%% -- #OCIA:AN:ANFrameJitterCorrection: ROI brightness
% get the brightness of the ROIs to calculate correlation only on the "nBrightROIs" brightest ROIs
ROIBrightness = zeros(1, nROIs);
parfor iROI = 1 : nROIs;
if strcmpi(ROISet{iROI, 1}, 'npil'); continue; end; % exclude neuropil
% get the ROI's mask
ROIMask = ROISet{iROI, 2};
% get the x and y positions of this ROI's pixels
ROIBrightness(iROI) = sum(avgImg(ROIMask > 0));
end;
% sort the brightness
[~, ROIBrightnessIndex] = sort(-ROIBrightness);
brighROISet = ROISet(ROIBrightnessIndex(1 : nBrightROIs), :);
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% -- #OCIA:AN:ANFrameJitterCorrection: loop on shifts: fix the jitter by applying a shift to lines
nShifts = numel(shifts);
shiftImprovs = zeros(nBrightROIs, nShifts);
parfor iShift = 1 : nShifts;
shift = shifts(iShift); % get the current shift to apply
avgImgShift = shiftImage(avgImg, imgDim, shift); % shift the image
%% --- #OCIA:AN:ANFrameJitterCorrection: loop on ROIs
for iROI = 1 : nBrightROIs;
%% ---- #OCIA:AN:ANFrameJitterCorrection: process ROI
% get the ROI's mask
ROIMask = brighROISet{iROI, 2};
% get the x and y positions of this ROI's pixels
ROIPixels = unique(find(ROIMask > 0));
[yVals, xVals] = ind2sub(imgDim([1, 2]), ROIPixels);
% get the bounding box of this ROI
ROIXRange = [round(min(xVals) * (1 - percBoundBox)), round(max(xVals) * (1 + percBoundBox))];
ROIYRange = [round(min(yVals) * (1 - percBoundBox)), round(max(yVals) * (1 + percBoundBox))];
% skip if the ROI with bounding box is not completely in the image
if ROIXRange(1) < 1 || ROIXRange(end) > imgDim(2) || ROIYRange(1) < 1 || ROIYRange(end) > imgDim(1);
continue;
end;
% image of the ROI's bounding box
ROIAvgImg = avgImg(ROIYRange(1) : ROIYRange(end), ROIXRange(1) : ROIXRange(end));
% do a line-wise correlation
yCorrsROI = zeros(1, ROIYRange(end) - ROIYRange(1));
for y = 1 : (ROIYRange(end) - ROIYRange(1));
yCorrsROI(y) = corr(ROIAvgImg(y, :)', ROIAvgImg(y + 1, :)', 'rows', 'pairwise'); %#ok<*PFBNS>
end;
% corrected image of the ROI's bounding box
ROIAvgImgShift = avgImgShift(ROIYRange(1) : ROIYRange(end), ROIXRange(1) : ROIXRange(end));
% do a line-wise correlation
yCorrsROICorrected = zeros(1, ROIYRange(end) - ROIYRange(1));
for y = 1 : (ROIYRange(end) - ROIYRange(1));
yCorrsROICorrected(y) = corr(ROIAvgImgShift(y, :)', ROIAvgImgShift(y + 1, :)', 'rows', 'pairwise');
end;
shiftImprovs(iROI, iShift) = (nanmean(yCorrsROICorrected) / nanmean(yCorrsROI)) * 100 - 100;
%% ---- #OCIA:AN:FrameJitterCorrection: ROI plotting
if doPlots > 2; % if requested, plot a figure illustrating the shift correction procedure and result
figure('Name', sprintf('%s: frames %03d-%03d (%d), ROI%d, shift %+d', ...
rowIDTitle, frameRange([1, end]), iChunck, iROI, shift), figCommons{:});
subplot(1, 2, 1); imshow(linScale(ROIAvgImg));
subplot(1, 2, 2); imshow(linScale(ROIAvgImgShift));
% add titles
subplot(1, 2, 1); title('Original');
subplot(1, 2, 2); title('Corrected');
figure('Name', sprintf('%s: frames %03d-%03d (%d), shift %+d, corr.: %.3f->%.3f (%+02.1f%%)', ...
rowIDTitle, frameRange([1, end]), iChunck, shift, nanmean(yCorrsROI), ...
nanmean(yCorrsROICorrected), shiftImprovs(iROI, iShift)), figCommons{:});
plot(1 : size(yCorrsROI, 2), yCorrsROI);
hold on;
plot((1 : size(yCorrsROI, 2)) + 0.5, yCorrsROICorrected, 'r');
ylim([0.2 1]);
legend('Original', 'Corrected');
end; % end of plotting if case
end; % end of ROI for loop
%% --- #OCIA:AN:FrameJitterCorrection: general plotting
if doPlots > 1; % if requested, plot a figure illustrating the shift correction procedure and result
% original image
figure('Name', sprintf('%s: frames %03d-%03d (%d), shift %+d', ...
rowIDTitle, frameRange([1, end]), iChunck, shift), figCommons{:});
subplot(1, 2, 1); imshow(linScale(avgImg));
subplot(1, 2, 2); imshow(linScale(avgImgShift));
% add titles
subplot(1, 2, 1); title('Original');
subplot(1, 2, 2); title('Corrected');
end; % end of plotting if case
end; % end of shifts for loop
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% extract the best shift
[~, bestShift] = sort(-nanmean(shiftImprovs, 1));
bestShift = shifts(bestShift(1));
% if some shifting was found, apply it on the frame and calculate correlations
if bestShift;
avgImgCorr = shiftImage(avgImg, imgDim, bestShift); % shift the image
% do a line-wise correlation
yCorrs = zeros(1, imgDim(1) - 1);
yCorrsCorrected = zeros(1, imgDim(1) - 1);
parfor y = 1 : (imgDim(1) - 1);
yCorrs(y) = corr(avgImg(y, :)', avgImg(y + 1, :)', 'rows', 'pairwise');
yCorrsCorrected(y) = corr(avgImgCorr(y, :)', avgImgCorr(y + 1, :)', 'rows', 'pairwise');
end;
bestShiftImprov = (nanmean(yCorrsCorrected) / nanmean(yCorrs)) * 100 - 100;
% if improvement is not big enough, do not apply it
if bestShiftImprov < 1; % less than 1% improvement
bestShift = 0;
else
o('%s: frames %03d-%03d (%d), best shift %+d, corr.: %.3f->%.3f (%+02.1f%%).', ...
rowIDTitle, frameRange([1, end]), iChunck, bestShift, nanmean(yCorrs), nanmean(yCorrsCorrected), ...
bestShiftImprov, 2, this.verb);
end;
end;
if ~bestShift; % if no correction, keep original image
avgImgCorr = avgImg;
bestShiftImprov = 0;
% do a line-wise correlation
yCorrs = zeros(1, imgDim(1) - 1);
parfor y = 1 : (imgDim(1) - 1);
yCorrs(y) = corr(avgImg(y, :)', avgImg(y + 1, :)', 'rows', 'pairwise');
end;
yCorrsCorrected = yCorrs;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% --- #OCIA:AN:FrameJitterCorrection: general plotting
if doPlots > 0; % if requested, plot a figure illustrating the shift correction procedure and result
% original image
figure('Name', sprintf('%s: frames %03d-%03d (%d), best shift %+d', ...
rowIDTitle, frameRange([1, end]), iChunck, bestShift), figCommons{:});
subplot(1, 2, 1); imshow(linScale(avgImg));
subplot(1, 2, 2); imshow(linScale(avgImgCorr));
% subplot(1, 2, 1); imagesc(avgImg);
% subplot(1, 2, 2); imagesc(avgImgCorrected);
subplot(1, 2, 1); title('Original');
subplot(1, 2, 2); title('Corrected');
figure('Name', sprintf('%s: frames %03d-%03d (%d), best shift: %+d, corr.: %.3f->%.3f (%+02.1f%%)', ...
rowIDTitle, frameRange([1, end]), iChunck, bestShift, nanmean(yCorrs), nanmean(yCorrsCorrected), ...
bestShiftImprov), figCommons{:});
plot(1 : size(yCorrs, 2), yCorrs);
hold on;
plot((1 : size(yCorrsCorrected, 2)) + 0.5, yCorrsCorrected, 'r');
ylim([0.2 1]);
legend('Original', 'Corrected');
end; % end of plotting if case
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% if some shifting was applied, shift all frames in the original data
if bestShift;
% create a corrected data set
imgDataCorrected = imgData;
% go through each channel
for iChan = 1 : this.an.img.nChans;
% skip empty channels
if isempty(imgDataCorrected{iChan}); continue; end;
% get the current data chunck (images) of the current channel
imgDataChanAllFrames = imgDataCorrected{iChan};
imgDataChan = imgDataChanAllFrames(:, :, frameRange);
% go through each frame and correct it
parfor iFrame = 1 : size(imgDataChan, 3);
imgDataChan(:, :, iFrame) = shiftImage(imgDataChan(:, :, iFrame), imgDim, bestShift); % shift the image
end;
imgDataChanAllFrames(:, :, frameRange) = imgDataChan; % copy back the corrected data
imgDataCorrected{iChan} = imgDataChanAllFrames; % copy back the corrected data
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% store the corrected data
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.procImg.data = imgDataCorrected;
end;
end; % end of chuncks for loop
% mark row as processed for frame jitter correction
setData(this, iDWRow, 'procImg', 'procState', [rowProcState { 'fJitt' }]);
end
%% - #OCIA:AN:ANFrameJitterCorrection:shiftImage
function shiftedImage = shiftImage(avgImg, imgDim, shift)
shiftedImage = avgImg; % start with the original image
for y = 1 : imgDim(1);
if mod(y, 2);
xIndexes = (1 : imgDim(2)) + shift;
xIndexes(xIndexes < 1 | xIndexes > imgDim(2)) = [];
if shift > 0;
lineValues = [avgImg(y, xIndexes), nan(1, abs(shift))];
elseif shift < 0;
lineValues = [nan(1, abs(shift)), avgImg(y, xIndexes)];
else
lineValues = avgImg(y, xIndexes);
end;
shiftedImage(y, :) = lineValues;
end;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_wfTr.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_wfTr.m
| 2,911 |
utf_8
|
49ad001f1a3801e538d264c2d9197384
|
%% #OCIA:OCIA_dataProcess_wfTr
function [isValid, unvalidReason] = OCIA_dataProcess_wfTr(this, iDWRow)
% set a flag that tells whether this row is valid for processing or not
isValid = false;
% create a string holding the reason why this row was flagged as not valid
unvalidReason = 'unknown reason';
rowID = DWGetRowID(this, iDWRow); % get the row ID
% check whether to show the debug plots or not
showDebugPlots = get(this.GUI.handles.dw.SLROpts.procDataShowDebug, 'Value');
% get the selected processing steps and this row's processing state
selProcSteps = get(this.GUI.handles.dw.procOptsList, 'Value');
% go through each step and execute the associated function
nSteps = size(this.an.procOptions.id, 1);
for iStep = 1 : nSteps;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason);
if doAbort; return; end;
% get the processing step's id and label
stepID = this.an.procOptions.id{iStep};
stepLabel = this.an.procOptions.label{iStep};
% if processing step is not selected, skip it
if ~ismember(iStep, selProcSteps); continue; end;
% if processing step if loading, load the row fully
if strcmp(stepID, 'loadData');
DWLoadRow(this, iDWRow, 'full');
continue;
end;
% call the custom function for this processing step
warning('off', 'OCIA:dataProcess_wfTr:FunctionNotFound');
[funcHandle, validityCell] = OCIAGetCallCustomFile(this, 'dataProcess_wfTr', ...
stepID, 1, { this, iDWRow, showDebugPlots }, 0);
warning('on', 'OCIA:dataProcess_wfTr:FunctionNotFound');
% if the function was found (function handle not empty) and the row is valid
if ~isempty(funcHandle) && ~isempty(validityCell) && numel(validityCell) >= 2 && validityCell{1};
% show step is complete
showMessage(this, sprintf('%s for %s (%03d) done.', stepLabel, rowID, iDWRow));
% if the function was not found (function handle is empty), show warning and go on
elseif isempty(funcHandle);
showWarning(this, 'OCIA:dataProcess_wfTr:ProcessFunctionNotFound', ...
sprintf('%s for %s (%03d): no processing function found ("%s"), skipping this step.', ...
stepLabel, rowID, iDWRow, stepID));
% if the row was flagged as not valid
elseif ~isempty(validityCell) && numel(validityCell) >= 2;
[isValid, unvalidReason] = validityCell{:};
return;
% otherwise something else went wrong
else
isValid = false;
unvalidReason = 'unknown error';
return;
end;
% allow time for GUI update
if isGUI(this); pause(0.005); end;
end;
% update the row's loading and processing status
DWGetUpdateDataLoadStatus(this, iDWRow);
% if we managed to come this far, then the row is valid and unvalidity reason is empty
isValid = true;
unvalidReason = '';
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_moCorr_TurboReg.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_moCorr_TurboReg.m
| 20,402 |
utf_8
|
fd9b7d416c0cd89e92f898625045d53d
|
%% #OCIA:OCIA_dataProcess_imgData_moCorr_TurboReg
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_moCorr_TurboReg(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's processing state
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
rowProcState = getData(this, iDWRow, 'procImg', 'procState');
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'moCorr')) || ~strcmp(get(this, iDWRow, 'rowType'), 'Imaging data') ...
|| any(strcmp(rowProcState, 'moCorr'));
return;
end;
% get whether to do plots or not
if nargin > 2; doPlots = varargin{1};
else doPlots = 0;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% init
rowID = DWGetRowID(this, iDWRow);
rowIDTitle = sprintf('Motion correction (TurboReg) for %s (%d)', rowID, iDWRow);
% get the transformation for the registration
regTransf = this.an.moCorr.regTransf;
% figCommons = {'NumberTitle', 'off'}; % figure options
figCommons = {'NumberTitle', 'off', 'WindowStyle', 'docked'}; % figure options
% get the ROISet for this row and the row of the reference image
[ROISet, ~, ~, iDWRefRowForROISet, avgImgRefCell] = ANGetROISetForRow(this, iDWRow);
nROIs = size(ROISet, 1);
% make sure we have an image and not a cell, use the specified pre-procesing channel if required
if iscell(avgImgRefCell); avgImgRef = avgImgRefCell{this.an.img.preProcChan};
else avgImgRef = avgImgRefCell;
end;
% if no reference average image, try to fetch it from the ROIDrawer
if isempty(avgImgRef);
currentMode = this.main.modes{get(this.GUI.handles.changeMode, 'Value'), 1};
selRDTableRow = get(this.GUI.handles.rd.tableList, 'Value');
% if we are in ROIDrawer mode and there is a selected row in the run table
if strcmp(currentMode, 'ROIDrawer') && ~isempty(this.rd.selectedTableRows) && ~isempty(selRDTableRow);
% get the row index of the DataWatcher's table
iDWRefRow = this.rd.selectedTableRows(selRDTableRow(1));
% get the reference average image as the mean of pre-processed frames
imgDataRefRow = get(this, iDWRefRow, 'data');
avgImgRefCell = imgDataRefRow.procImg.data;
avgImgRef = nanmean(avgImgRefCell{this.an.img.preProcChan}, 3);
end;
end;
% if no reference average image, try to fetch it from this row's data
if isempty(avgImgRef);
showWarning(this, 'OCIA:OCIA_dataProcess_imgData_moCorr_TurboReg:NoReferenceImage', ...
sprintf('%s: No reference image found. Aligning this row to itself ...', rowIDTitle));
% get the reference average image as the mean of pre-processed frames
imgDataRefRow = get(this, iDWRow, 'data');
avgImgRefCell = imgDataRefRow.procImg.data;
avgImgRef = nanmean(avgImgRefCell{this.an.img.preProcChan}, 3);
end;
% if no reference average image, abort
if isempty(avgImgRef);
showWarning(this, 'OCIA:OCIA_dataProcess_imgData_moCorr_TurboReg:NoReferenceImage', ...
sprintf('%s: No reference image found. Aborting.', rowIDTitle));
isValid = false;
return;
end;
% if no ROIs, create a fake ROISet
if ~nROIs;
% create the fake ROISet
imgDim = size(avgImgRef);
[ROISet, nROIs] = createFakeROISet(imgDim(1:2), imgDim(1) * 0.05, 20, 20);
end;
% make sure the data is fully loaded
DWLoadRow(this, iDWRow, 'full');
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% prepare reference image and frames to register
% get the imaging data
imgData = getData(this, iDWRow, 'procImg', 'data');
% get the average of all frames of the pre-processing channel for this row
avgImg = nanmean(imgData{this.an.img.preProcChan}, 3);
% get the movie of all frames of pre-processing channel
imgMovie = imgData{this.an.img.preProcChan};
imgDim = size(imgMovie);
% if requested, apply a "small" gaussian filtering on the movie to have enhanced registration
if this.an.moCorr.useFilt;
filtTic = tic; % for performance timing purposes
% save the unfiltered movie
imgMovieUnFilt = imgMovie;
imgMovie = zeros(imgDim);
parfor iFrame = 1 : imgDim(3);
% imgMovie(:, :, iFrame) = imfilter(imgMovieUnFilt(:, :, iFrame), fspecial('gaussian', 2, 1), 'replicate');
imgMovie(:, :, iFrame) = medfilt2(imgMovieUnFilt(:, :, iFrame), [2 2], 'symmetric');
% imgMovie(:, :, iFrame) = PseudoFlatfieldCorrect(imgMovieUnFilt(:, :, iFrame));
end;
o('%s: filtering done (%3.1f sec).', rowIDTitle, toc(filtTic), 2, this.verb);
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% get reference point
percBoundBox = 0.04; % percent of image around the ROI's bounding box
% if an ROISet was found, take the brightest ROI as a reference point
if nROIs;
% take brightest ROI(s) as reference point. Note that different registration methods need different
% number of reference points
if strcmpi(regTransf, 'translation');
nBrightROIs = 1;
elseif any(strcmpi(regTransf, {'affine', 'rigidBody'}));
nBrightROIs = 3;
elseif strcmpi(regTransf, 'bilinear');
nBrightROIs = 4;
end;
% get the ROISet of the brightest ROI(s)
brightROISet = getBrightROIs(ROISet, avgImgRef, nBrightROIs, percBoundBox, doPlots - 1);
% store the coordinates of those ROIs
refPpoints = zeros(nBrightROIs, 2);
for iBrightROI = 1 : nBrightROIs;
% get the indexes of the mask and calculate the center of it
[maskYVals, maskXVals] = ind2sub(imgDim([1, 2]), find(brightROISet{iBrightROI, 4}));
refPpoints(iBrightROI, :) = round([nanmean(maskXVals), nanmean(maskYVals)]);
end;
if doPlots > 0;
figure('Name', sprintf('%s: landmarks', rowIDTitle), figCommons{:});
imshow(linScale(avgImgRef));
hold on;
scatter(refPpoints(:, 1), refPpoints(:, 2), 'bx');
text(refPpoints(:, 1) - imgDim(1) * 0.03, refPpoints(:, 2) - imgDim(2) * 0.03, ...
num2cell(1 : nBrightROIs), 'Color', 'red');
end;
% transform the coordinates into source-target pairs (src1X src1Y targ1X targ1Y src2X src2Y targ2X targ2Y ...)
refPointsBlock = zeros(1, numel(refPpoints) * 2);
for iBrightROI = 1 : nBrightROIs;
refPointsBlock((iBrightROI - 1) * 4 + 1) = refPpoints(iBrightROI, 1);
refPointsBlock((iBrightROI - 1) * 4 + 2) = refPpoints(iBrightROI, 2);
refPointsBlock((iBrightROI - 1) * 4 + 3) = refPpoints(iBrightROI, 1);
refPointsBlock((iBrightROI - 1) * 4 + 4) = refPpoints(iBrightROI, 2);
end;
% otherwise leave empty and center of frame will be used
else
refPointsBlock = [];
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% perform the registration
% any NaN frame will remain NaN
showMessage(this, sprintf('%s: aligning frames ...', rowIDTitle), 'yellow');
pause(0.01);
regTic = tic; % for performance timing purposes
[imgMovieReg, targPoints, srcPoints, regTimes] = turboReg(imgMovie, avgImgRef, regTransf, 10, refPointsBlock, doPlots - 1);
showMessage(this, sprintf('%s: aligning frames done (%s, %.3f sec, align. time: %.0f +- %.0f msec).', ...
rowIDTitle, regTransf, toc(regTic), nanmean(regTimes) * 1000, nanstd(regTimes) * 1000));
% get the non-empty reference points
nonEmptyPoints = sum(sum(srcPoints, 1), 3) ~= 0;
% remove the empty reference points
srcPoints = srcPoints(:, nonEmptyPoints, :);
targPoints = targPoints(:, nonEmptyPoints, :);
% get the number of points
nRegPoints = size(srcPoints, 2);
% if there are less than 3 reference points (translation, nRegPoints = 1), applying transformation with
% affine transformation type will not work, so create new reference points with same translation
if nRegPoints == 1 && nROIs;
% get a new ROISet of the brightest ROI(s)
newBrightROISet = getBrightROIs(ROISet, avgImgRef, 3, percBoundBox, 0);
% store the coordinates of those ROIs
refPoints = zeros(size(newBrightROISet, 1), 2);
for iNewBrightROI = 1 : size(newBrightROISet, 1);
% get the indexes of the mask and calculate the center of it
[maskYVals, maskXVals] = ind2sub(imgDim([1, 2]), find(newBrightROISet{iNewBrightROI, 4}));
refPoints(iNewBrightROI, :) = round([nanmean(maskXVals), nanmean(maskYVals)]);
end;
% extract the translations
translationShifts = squeeze(srcPoints(:, 1, :) - targPoints(:, 1, :));
% recreate the source and target points using now 3 points
targPoints = zeros(imgDim(3), 3, 2);
srcPoints = zeros(imgDim(3), 3, 2);
for iPoint = 1 : 3;
targPoints(:, iPoint, :) = repmat(refPoints(iPoint, :), imgDim(3), 1);
srcPoints(:, iPoint, :) = squeeze(targPoints(:, iPoint, :)) + translationShifts;
end;
% get the new number of points
nRegPoints = size(srcPoints, 2);
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% apply registration to channels
applyTic = tic; % for performance timing purposes
% apply the motion correction to all channels
imgDataReg = cell(size(imgData)); % create a holder for the data
% go through each required channel
for iChanLoop = 1 : numel(this.an.img.chanVect);
% get the index of the current channel and it's imaging data
iChan = this.an.img.chanVect(iChanLoop);
imgDataChan = imgData{iChan};
showMessage(this, sprintf('%s: applying transformation to channel %d ...', rowIDTitle, iChan), 'yellow');
% go through each frame and apply the subpixel translation
imgMovieTrans = zeros(imgDim);
% transform all frames one by one
parfor iFrame = 1 : imgDim(3);
frame = imgDataChan(:, :, iFrame); % get the frame
inPoints = squeeze(srcPoints(iFrame, :, :));
basePoints = squeeze(targPoints(iFrame, :, :));
% get the transformation matrix
tForm = cp2tform(inPoints, basePoints, 'affine'); %#ok<DCPTF>
% get the transformed frame
tFrame = imtransform(frame, tForm, 'XData', [1, imgDim(2)], 'YData', [1, imgDim(1)], ...
'FillValues', NaN); %#ok<DIMTRNS,PFBNS>
% store the frame
imgMovieTrans(:, :, iFrame) = tFrame;
end;
% store the corrected frames
imgDataReg{iChan} = imgMovieTrans;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
end;
showMessage(this, sprintf('%s: applying transformation done (%.3f sec).', rowIDTitle, toc(applyTic)));
%% quality control & storage
qcTic = tic; % for performance timing purposes
% get the reference frame
if iscell(avgImgRefCell); avgImgRefQC = avgImgRefCell{this.an.img.chanVect(1)};
else avgImgRefQC = avgImgRefCell;
end;
avgImgRefQC = nanmean(avgImgRefQC, 3);
% get the correlations for the frames before motion correction
framesBefore = imgData{this.an.img.chanVect(1)};
avgImgBefore = nanmean(framesBefore, 3);
frameCorrBefore = prctile(getFrameCorr(avgImgRefQC, framesBefore), 1);
frameCorrToRefBefore = getFrameCorr(avgImgRefQC, avgImgBefore);
% get the correlations for the frames after motion correction
framesAfter = imgDataReg{this.an.img.chanVect(1)};
avgImgAfter = nanmean(framesAfter, 3);
frameCorrAfter = prctile(getFrameCorr(avgImgRefQC, framesAfter), 1);
frameCorrToRefAfter = getFrameCorr(avgImgRefQC, avgImgAfter);
% get the thresholds
meanFrameCorrDiffThresh = this.an.moCorr.meanFrameCorrDiffThresh;
frameCorrToRefDiffThresh = this.an.moCorr.frameCorrToRefDiffThresh;
frameCorrToRefAbsThresh = this.an.moCorr.frameCorrToRefAbsThresh;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% plotting
% get the average of all frames of corrected movie
avgImgRegTurboReg = nanmean(imgMovieReg, 3);
% get the average of all frames of the pre-processing channel
avgImgReg = nanmean(imgDataReg{this.an.img.preProcChan}, 3);
% use the functional channel if the alignement has not been applied to the pre-processing channel
if isempty(avgImgReg);
avgImgReg = nanmean(imgDataReg{this.an.img.chanVect(1)}, 3);
end;
% get the shifts applied
shifts = srcPoints - targPoints;
maxShift = ceil(max(abs(shifts(:)))) + 1;
% get the imaging data, both none-registered and registerd
imgMovieNoReg = imgData{this.an.img.preProcChan};
imgMovieWithReg = imgDataReg{this.an.img.preProcChan};
% use the functional channel if the alignement has not been applied to the pre-processing channel
if isempty(imgMovieWithReg);
imgMovieNoReg = imgData{this.an.img.chanVect(1)};
imgMovieWithReg = imgDataReg{this.an.img.chanVect(1)};
if iscell(avgImgRefCell);
avgImgRef = avgImgRefCell{this.an.img.chanVect(1)};
else
avgImgRef = mean(imgMovieNoReg, 3);
end;
end;
% get the ROISet of the brightest ROI(s)
frameCorrBrightROISet = getBrightROIs(ROISet, avgImgRef, nROIs - 1, percBoundBox, 0);
% calculate frame-wise correlation only on brightest ROIs
frameCorrNoReg = nanmean(getFrameCorrROI(frameCorrBrightROISet, percBoundBox, avgImgRef, imgMovieNoReg), 1);
frameCorrWithReg = nanmean(getFrameCorrROI(frameCorrBrightROISet, percBoundBox, avgImgRef, imgMovieWithReg), 1);
% if requested, plot a figure illustrating the result of the motion correction
if doPlots > 0;
% summary images
figure('Name', sprintf('%s: average images before/after correction', rowIDTitle), figCommons{:});
subplot(2, 2, 1); imshow(linScale(avgImgRef)); title('Reference');
subplot(2, 2, 2); imshow(linScale(avgImg)); title('Original');
subplot(2, 2, 3); imshow(linScale(avgImgReg)); title('Transformed');
subplot(2, 2, 4); imshow(linScale(avgImgRegTurboReg)); title('Registered');
figure('Name', sprintf('%s: mean frame movements and correlation', rowIDTitle), figCommons{:});
subplot(2, 1, 1);
hold on;
plot(1 : imgDim(3), nanmean(shifts(:, :, 1), 2), 'r');
plot(1 : imgDim(3), nanmean(shifts(:, :, 2), 2), 'b');
legend('XShift', 'YShift');
ylim([-maxShift maxShift]); xlim([0 imgDim(3) + 1]);
title('Frame movements');
xlabel('Frames'); ylabel('Shift [pixel]');
subplot(2, 1, 2);
hold on;
plot(1 : imgDim(3), frameCorrNoReg, 'r');
plot(1 : imgDim(3) + 0.3, frameCorrWithReg, 'b');
legend('No reg.', sprintf('%s reg.', regTransf));
ylim([0 1]); xlim([0 imgDim(3) + 1]);
title(sprintf('Frame-wise correlations (using bounding box area of %d ROIs)', size(frameCorrBrightROISet, 1)));
xlabel('Frames'); ylabel('Correlation');
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% check quality
if frameCorrAfter - frameCorrBefore < meanFrameCorrDiffThresh ...
|| frameCorrToRefAfter - frameCorrToRefBefore < frameCorrToRefDiffThresh ...
|| frameCorrToRefAfter < frameCorrToRefAbsThresh;
% if the current row is not the reference row, quality control is failed
if iDWRefRowForROISet ~= iDWRow;
showWarning(this, 'OCIA:OCIA_dataProcess_imgData_moCorr_TurboReg:QualityControlFail', ...
sprintf(['%s: registration quality control failed: mean frame-wise correlation to the reference: ', ...
'before: %.4f, after: %.4f, correlation of average image to reference: before: %.4f, after: %.4f.'], ...
rowIDTitle, frameCorrBefore, frameCorrAfter, frameCorrToRefBefore, frameCorrToRefAfter));
% summary images
figH = figure('Name', sprintf('%s: average images before/after correction', rowIDTitle), figCommons{:});
colormap('gray');
subplot(2, 2, 1); imagesc(linScale(avgImgRef));
title('Reference'); set(gca, 'XTick', [], 'YTick', []); axis('square');
subplot(2, 2, 2); imagesc(linScale(avgImg));
title('Original'); set(gca, 'XTick', [], 'YTick', []); axis('square');
subplot(2, 2, 3); imagesc(linScale(avgImgReg));
title('Transformed'); set(gca, 'XTick', [], 'YTick', []); axis('square');
subplot(2, 2, 4); imagesc(linScale(avgImgRegTurboReg));
title('Registered'); set(gca, 'XTick', [], 'YTick', []); axis('square');
if exist('moCorrFailedQC', 'dir') ~= 7; mkdir('moCorrFailedQC'); end;
rowInfos = get(this, iDWRow, { 'animal', 'spot', 'day', 'time' });
rowInfos = regexprep(regexprep(rowInfos, '_', ''), 'moubl', '');
savePath = sprintf('%s/moCorrFailedQC/%s_%s_%s_%s_moCorrFailedQCImages', regexprep(pwd(), '\', '/'), rowInfos{:});
tightfig(figH);
set(figH, 'Position', [10 10 1200 1200]);
saveas(figH, savePath, 'png');
close(figH);
figH = figure('Name', sprintf('%s: mean frame movements and correlation', rowIDTitle), figCommons{:});
subplot(2, 1, 1);
hold on;
plot(1 : imgDim(3), nanmean(shifts(:, :, 1), 2), 'r');
plot(1 : imgDim(3), nanmean(shifts(:, :, 2), 2), 'b');
legend('XShift', 'YShift');
ylim([-maxShift maxShift]); xlim([0 imgDim(3) + 1]);
title('Frame movements');
xlabel('Frames'); ylabel('Shift [pixel]');
subplot(2, 1, 2);
hold on;
plot(1 : imgDim(3), frameCorrNoReg, 'r');
plot(1 : imgDim(3) + 0.3, frameCorrWithReg, 'b');
legend('No reg.', sprintf('%s reg.', regTransf));
ylim([0 1]); xlim([0 imgDim(3) + 1]);
title(sprintf('Frame-wise correlations (using bounding box area of %d ROIs)', size(frameCorrBrightROISet, 1)));
xlabel('Frames'); ylabel('Correlation');
savePath = sprintf('%s/moCorrFailedQC/%s_%s_%s_%s_moCorrFailedQCShifts', regexprep(pwd(), '\', '/'), rowInfos{:});
tightfig(figH);
set(figH, 'Position', [10 10 1200 1200]);
saveas(figH, savePath, 'png');
close(figH);
% if the non-corrected should nevertheless be used, return by specifiying the row as valid
if this.an.moCorr.useNonCorrectedIfQualityControlFailed;
isValid = true;
showMessage(this, sprintf('%s: quality control failed, using the non-corrected frames (row is valid).', ...
rowIDTitle));
return;
% if the non-corrected should not be used, return by specifiying the row as not valid
else
showMessage(this, sprintf('%s: quality control failed, row is not valid.', rowIDTitle));
isValid = false;
end;
% if the current row is the reference row, quality control is not really failed since the correlations can anyway
% not improve
else
showMessage(this, sprintf(['%s: quality control done (mean corr. diff.: %+.4f, corr. avg. diff: %+.4f, ', ...
'corr. to ref: %.4f, ref row, %.3f sec).'], rowIDTitle, frameCorrAfter - frameCorrBefore, ...
frameCorrToRefAfter - frameCorrToRefBefore, frameCorrToRefAfter, toc(qcTic)));
end;
% quality control passed
else
showMessage(this, sprintf(['%s: quality control done (mean corr. diff.: %+.4f, corr. avg. diff: %+.4f, ', ...
'corr. to ref: %.4f, %.3f sec).'], rowIDTitle, frameCorrAfter - frameCorrBefore, ...
frameCorrToRefAfter - frameCorrToRefBefore, frameCorrToRefAfter, toc(qcTic)));
end;
% store the pre-processed data (only for non-empty channels)
for iChan = 1 : numel(imgDataReg);
if ~isempty(imgDataReg{iChan});
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.procImg.data{iChan} = imgDataReg{iChan};
end;
end;
% mark row as processed for motion correction
setData(this, iDWRow, 'procImg', 'procState', [rowProcState { 'moCorr' }]);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_fShift.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_fShift.m
| 9,776 |
utf_8
|
8bfdd6962d12089b5c936fcc3a0f0344
|
%% #OCIA:OCIA_dataProcess_imgData_fShift
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_fShift(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's processing state
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
rowProcState = getData(this, iDWRow, 'procImg', 'procState');
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'fShift')) || ~strcmp(get(this, iDWRow, 'rowType'), 'Imaging data') ...
|| any(strcmp(rowProcState, 'fShift'));
return;
end;
% get whether to do plots or not
if nargin > 2; doPlots = varargin{1};
else doPlots = 0;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% init
rowID = DWGetRowID(this, iDWRow);
rowIDTitle = sprintf('Frame shift correction for %s (%d)', rowID, iDWRow);
figCommons = { 'NumberTitle', 'off', 'WindowStyle', 'docked' }; % figure options
% make sure data is fully loaded
DWLoadRow(this, iDWRow, 'full');
% get the imaging data
imgData = get(this, iDWRow, 'data');
imgData = imgData.procImg.data;
imgDim = size(imgData{this.an.img.preProcChan});
% correct for frame shifting artifact by analysing the correlations in the average image of the selected channel
avgImg = nanmean(imgData{this.an.img.preProcChan}, 3);
% range on which the average image should be analysed (exclude side artifacts)
percExcl = 0.2;
xRange = round([imgDim(1) * percExcl, imgDim(1) * (1 - percExcl)]);
yRange = round([imgDim(2) * percExcl, imgDim(2) * (1 - percExcl)]);
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% do a line-wise correlation
xCorrs = zeros(1, xRange(end) - xRange(1) + 1);
xIndOffset = xRange(1) - 1; % offset for indexing
parfor x = xRange(1) : xRange(end);
xCorrs(x - xIndOffset) = corr(avgImg(:, x), avgImg(:, x - 1), 'rows', 'pairwise'); %#ok<*PFBNS>
end;
yCorrs = zeros(1, yRange(end) - yRange(1) + 1);
yIndOffset = yRange(1) - 1; % offset for indexing
parfor y = yRange(1) : yRange(end);
yCorrs(y - yIndOffset) = corr(avgImg(y, :)', avgImg(y - 1, :)', 'rows', 'pairwise');
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% get the correlation thresholds using a certain number of times the standard deviation
corrTheshFactor = this.an.fShift.corrThreshFactor;
% calculate correlations for X and Y differently
corrThreshX = nanmean(xCorrs) - corrTheshFactor * (max(xCorrs) - min(xCorrs));
corrThreshY = nanmean(yCorrs) - corrTheshFactor * (max(yCorrs) - min(yCorrs));
% make boundaries for correlations
corrThreshX = max(min(corrThreshX, this.an.fShift.maxCorrThresh), this.an.fShift.minCorrThresh);
corrThreshY = max(min(corrThreshY, this.an.fShift.maxCorrThresh), this.an.fShift.minCorrThresh);
% set a minimum of correlation difference in order to investigate the frame shift
corrDiffThresh = 0.1;
% correct on the X-axis
if any(xCorrs < corrThreshX);
% get the "derivative" of the correlation
diffXCorrs = abs(diff(xCorrs));
if any(diffXCorrs > corrDiffThresh);
% get a fresh copy of the data to change
imgDataToCorrect = this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.procImg.data;
% get the line where the shift occured
[maxXCorrDiff, maxXCorrDiffInd] = max(diffXCorrs);
xLineInd = maxXCorrDiffInd + xRange(1) - 1;
% reshape the images accordingly
imgDataCorr = cellfun(@(imgs) horzcat(imgs(:, xLineInd : end, :), imgs(:, 1 : xLineInd - 1, :)), ...
imgDataToCorrect, 'UniformOutput', false);
% average image of the selected channel of the corrected data
avgImgCorr = nanmean(imgDataCorr{this.an.img.preProcChan}, 3);
% see if it actually made it better: re-do a line-wise correlation
xCorrs2 = zeros(1, xRange(end) - xRange(1) + 1);
parfor x = xRange(1) : xRange(end);
xCorrs2(x - xIndOffset) = corr(avgImgCorr(:, x), avgImgCorr(:, x - 1), 'rows', 'pairwise'); %#ok<*PFBNS>
end;
% get the "derivative" of the correlation
diffXCorrs2 = abs(diff(xCorrs2));
% get the max correlation drop
maxXCorrDiff2 = max(diffXCorrs2);
% update the thresholds
corrThreshX2 = median(xCorrs) - corrTheshFactor * std(xCorrs);
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% only apply the change if the "corrected" image is actually better than the original
if ~any(xCorrs2 < corrThreshX2) || ~any(diffXCorrs2 > corrDiffThresh) || maxXCorrDiff2 < maxXCorrDiff;
% store the change
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.procImg.data = imgDataCorr;
% display message
showMessage(this, sprintf(' - %s: shift correction done on X.', rowIDTitle));
else
% keep the original image as "corrected"
avgImgCorr = avgImg;
end;
end;
end;
% correct on the Y-axis
if any(yCorrs < corrThreshY);
% get the "derivative" of the correlation
diffYCorrs = abs(diff(yCorrs));
if any(diffYCorrs > corrDiffThresh);
% get a fresh copy of the data to change
imgDataToCorrect = this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.procImg.data;
% get the line where the shift occured
[maxYCorrDiff, maxYCorrDiffInd] = max(diffYCorrs);
yLineInd = maxYCorrDiffInd + yRange(1) - 1;
% reshape the images accordingly
imgDataCorr = cellfun(@(imgs) vertcat(imgs(yLineInd : end, :, :), imgs(1 : yLineInd - 1, :, :)), ...
imgDataToCorrect, 'UniformOutput', false);
% average image of the selected channel of the corrected data
avgImgCorr = nanmean(imgDataCorr{this.an.img.preProcChan}, 3);
% see if it actually made it better: re-do a line-wise correlation
yCorrs2 = zeros(1, yRange(end) - yRange(1) + 1);
parfor y = yRange(1) : yRange(end);
yCorrs2(y - yIndOffset) = corr(avgImgCorr(y, :)', avgImgCorr(y - 1, :)', 'rows', 'pairwise');
end;
% get the "derivative" of the correlation
diffYCorrs2 = abs(diff(yCorrs2));
% get the max correlation drop
maxYCorrDiff2 = max(diffYCorrs2);
% update the thresholds
corrThreshY2 = median(yCorrs) - corrTheshFactor * std(xCorrs);
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% only apply the change if the "corrected" image is actually better than the original
if ~any(yCorrs2 < corrThreshY2) || ~any(diffYCorrs2 > corrDiffThresh) || maxYCorrDiff2 < maxYCorrDiff;
% store the change
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.procImg.data = imgDataCorr;
% display message
showMessage(this, sprintf(' - %s: shift correction done on Y.', rowIDTitle));
else
% keep the original image as "corrected"
avgImgCorr = avgImg;
end;
end;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% mark row as processed for frame shift correction
setData(this, iDWRow, 'procImg', 'procState', [rowProcState { 'fShift' }]);
%% plotting
% if requested, plot a figure illustrating what has been done
if doPlots > 0;
% correlation values
figure('Name', sprintf('%s: line-wise correlations', rowIDTitle), figCommons{:});
legendTexts = {'Corr. on X', 'Corr. on Y', 'Corr. thresh. X', 'Corr. thresh. Y'};
hold(gca, 'on');
plot(xRange(1) : xRange(end), xCorrs, 'r');
plot(yRange(1) : yRange(end), yCorrs, 'b');
xLims = get(gca, 'XLim');
plot(xLims(1) : xLims(end), repmat(corrThreshX, 1, xLims(end) - xLims(1) + 1), 'r:');
plot(xLims(1) : xLims(end), repmat(corrThreshY, 1, xLims(end) - xLims(1) + 1), 'b:');
if exist('diffXCorrs', 'var') || exist('diffYCorrs', 'var');
plot(xLims(1) : xLims(end), repmat(corrDiffThresh + 0.2, 1, xLims(end) - xLims(1) + 1), 'g--');
legendTexts{end + 1} = 'Corr. thresh. Diff.';
end;
if exist('diffXCorrs', 'var');
plot(0.5 + (xRange(1) : xRange(end) - 1), diffXCorrs + 0.2, 'r.-');
legendTexts{end + 1} = 'Diff. X corr.';
end;
if exist('diffYCorrs', 'var');
plot(0.5 + (xRange(1) : xRange(end) - 1), diffYCorrs + 0.2, 'g.-');
legendTexts{end + 1} = 'Diff. Y corr.';
end;
ylim([0 1]);
legend(legendTexts);
% if there was a correction done
if exist('avgImgCorr', 'var');
figure('Name', sprintf('%s: average images', rowIDTitle), figCommons{:});
subplot(1, 2, 1); imshow(linScale(avgImg));
subplot(1, 2, 2); imshow(linScale(avgImgCorr));
subplot(1, 2, 1); title('Original');
subplot(1, 2, 2); title('Corrected');
else
% original image
figure('Name', sprintf('%s: original average image (no correction done)', rowIDTitle), figCommons{:});
imshow(linScale(avgImg));
end;
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataProcess_imgData_extrCaTraces.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/dataProcess/OCIA_dataProcess_imgData_extrCaTraces.m
| 6,455 |
utf_8
|
9a39a9a8f93fa8489347c130b681db3d
|
%% #OCIA:OCIA_dataProcess_imgData_extrCaTraces
function [isValid, unvalidReason] = OCIA_dataProcess_imgData_extrCaTraces(this, iDWRow, varargin)
% by default, row is valid
isValid = true;
unvalidReason = '';
% get the selected processing steps and this row's calcium data
selProcOpts = this.an.procOptions.id(get(this.GUI.handles.dw.procOptsList, 'Value'));
rawChanData = get(this, iDWRow, 'data'); rawChanData = rawChanData.rawChan.data;
caTracesData = get(this, iDWRow, 'data'); caTracesData = caTracesData.caTraces.data;
% if this processing is not required or if data is not imaging data or if data was already processed, abort
if ~any(strcmp(selProcOpts, 'extrCaTraces')) || ~strcmp(get(this, iDWRow, 'rowType'), 'Imaging data') ...
|| (~isempty(caTracesData) && ~isempty(rawChanData));
return;
end;
% get whether to do plots or not
if nargin > 2; doPlots = varargin{1};
else doPlots = 0;
end;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
%% init
rowID = DWGetRowID(this, iDWRow);
rowIDTitle = sprintf('Extracting calcium trace for %s (%d)', rowID, iDWRow);
% display message
showMessage(this, sprintf('%s ...', rowIDTitle), 'yellow');
% get the ROISet for this row
ROISet = ANGetROISetForRow(this, iDWRow);
nROIs = size(ROISet, 1); % number of ROIs
% if no ROIs, abort
if ~nROIs; return; end;
% make sure the data is at least partially loaded
DWLoadRow(this, iDWRow, 'partial');
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% get the imaging data
imgData = get(this, iDWRow, 'data');
imgData = imgData.procImg.data;
% get the first channel to use for the trace extraction from the configuration
firstChan = this.an.img.chanVect(1);
imgDim = size(imgData{firstChan}); % get the image's dimension
% initialize the data set
this.data.img.caTraces{iDWRow} = nan(nROIs, size(imgData{firstChan}, 3));
% background substract images for each channel using the first percentile
for iChan = 1 : numel(imgData); % go through all channels
if isempty(imgData{iChan}) || imgDim(1) == 0; continue; end;
% calculate cutoff on the first 10% frames
nFrames = fix(imgDim(3) * 0.1);
bgPrctileCutOff = prctile(reshape(imgData{iChan}(:, :, 1 : nFrames), 1, prod(imgDim(1 : 2)) * nFrames), ...
this.an.img.bgPrctile);
imgData{iChan} = imgData{iChan} - bgPrctileCutOff; % remove cutoff
imgData{iChan}(imgData{iChan} < 0) = 0; % flatten so that there are no negative values
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
end;
% get the YFP or GFP data
YFPData = imgData{this.an.img.chanVect(1)};
% use CFP if there is a second channel
if numel(this.an.img.chanVect) > 1;
CFPData = imgData{this.an.img.chanVect(2)};
else
CFPData = [];
end;
downSampFactor = this.an.an.channelDownSampFactor;
if ~downSampFactor; downSampFactor = 1; end;
caTraces = nan(nROIs, floor(size(YFPData, 3) / downSampFactor));
chanStats = nan(nROIs, floor(size(YFPData, 3) / downSampFactor), numel(this.an.img.chanVect));
defaultFrameRate = this.an.img.defaultFrameRate;
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
% process each ROI
for iROI = 1 : nROIs;
% extract the time series for each pixel
YFPTimeSeries = GetRoiTimeseries(YFPData, ROISet{iROI, 2});
% get a threshold for the number of NaN pixels
nonNaNPixelNumberThreshold = round(size(YFPTimeSeries, 1) * 0.15);
% get how many pixels are NaN for each frame
NaNPixelsTimeSeries = sum(~isnan(YFPTimeSeries));
% remove bad frames where more than the threshold pixels are NaN, which gives an unreliable average
YFPTimeSeries(:, NaNPixelsTimeSeries < nonNaNPixelNumberThreshold) = NaN;
% get the average of all pixels
YFP = nanmean(YFPTimeSeries, 1)';
% apply the same for the CFP data (second channel) if it exists
if ~isempty(CFPData);
% extract the time series for each pixel
CFPTimeSeries = GetRoiTimeseries(CFPData, ROISet{iROI, 2});
% remove bad frames where more than the threshold pixels are NaN, which gives an unreliable average
CFPTimeSeries(:, NaNPixelsTimeSeries < nonNaNPixelNumberThreshold) = NaN;
% get the average of all pixels
CFP = nanmean(CFPTimeSeries, 1)';
else
CFP = [];
end;
% apply filter on traces if required
if this.an.an.channelSFGiltFrameSize > 1;
YFP = sgolayfilt(YFP, 1, this.an.an.channelSFGiltFrameSize);
if ~isempty(CFP);
CFP = sgolayfilt(CFP, 1, this.an.an.channelSFGiltFrameSize);
end;
end;
% apply downsampling on traces if required
if downSampFactor > 1;
YFP = interp1DS(defaultFrameRate, defaultFrameRate / downSampFactor, YFP);
YFP = YFP(1 : size(caTraces, 2));
if ~isempty(CFP);
CFP = interp1DS(defaultFrameRate, defaultFrameRate / downSampFactor, CFP);
CFP = CFP(1 : size(caTraces, 2));
end;
end;
% get the raw traces for each channel
chanStats(iROI, :, 1) = YFP;
if ~isempty(CFP);
chanStats(iROI, :, 2) = CFP;
end;
% extract the dFF/dRR from the channels
caTraces(iROI, :) = extractDFFDRR(YFP, CFP, this.an.img.f0method, this.an.img.f0params, ...
this.an.img.polyfitCorrect, this.an.img.polyfitFraction, this.an.img.expfitCorrect, ...
this.an.img.expfitWindow, defaultFrameRate, sprintf('%s_%03d_ROI%s', rowID, iDWRow, ...
ROISet{iROI, 1}), [], doPlots);
% check if the processing should be aborted
[doAbort, isValid, unvalidReason] = DWCheckProcessAbort(this, isValid, unvalidReason); if doAbort; return; end;
end;
% store the raw traces
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.rawChan.data = chanStats;
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.rawChan.loadStatus = 'full';
% store the calcium traces
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.caTraces.data = caTraces;
this.dw.table{iDWRow, strcmp(this.dw.tableIDs, 'data')}.caTraces.loadStatus = 'full';
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_annotateTable_wenrui.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/annotates/OCIA_annotateTable_wenrui.m
| 4,177 |
utf_8
|
27e9a97bb43ff75be39b4648cc4c8d45
|
function OCIA_annotateTable_wenrui(this)
% OCIA_annotateTable_wenrui - [no description]
%
% OCIA_annotateTable_wenrui(this)
%
% [No description]
%
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% extract the depth from the spot IDs
depths = regexprep(this.dw.spotIDs, '^Spot\d+_(\d+)$', '$1');
% get the list of spot for each row
spots = get(this, 'all', 'spot');
if ~iscell(spots); spots = { spots }; end;
% remove empty spot labels
spots(cellfun(@isempty, spots)) = { '' };
% extract which spot it corresponds to
[~, spotIndexes] = ismember(spots, this.dw.spotIDs);
% if no spot ID was found, use the '-' that is in the first position in the 'depths' cell-array
spotIndexes(spotIndexes == 0) = 1;
% set the corresponding depth
set(this, 'all', 'depth', depths(spotIndexes));
% match ROISets to imaging data
DWMatchROISetsToData(this);
% match whisker data to imaging data
matchWhiskerDataToImagingData(this);
% show the table
DWDisplayTable(this);
end
function matchWhiskerDataToImagingData(this)
% sub-function to load the whisker data and match it to the imaging rows
% get imaging rows
imagingRows = DWFilterTable(this, 'rowType = Imaging data');
% abort if no imaging rows
if isempty(imagingRows); return; end;
% show message and update wait bar
showMessage(this, sprintf('Extracting whisker data for %02d imaging row(s) ...', size(imagingRows, 1)), 'yellow');
DWWaitBar(this, 0);
% go through each row
for iRow = 1 : size(imagingRows, 1);
% get the DataWatcher's table index for this row
iDWRow = str2double(get(this, 1, 'rowNum', imagingRows(iRow, :)));
% get the experiment number
expNum = str2double(get(this, iDWRow, 'expNum'));
% show a warning and skip if a row has an invalid experiment number
if isempty(expNum) || isnan(expNum);
showWarning(this, 'OCIA:OCIA_annotateTable_wenrui:WhiskerDataUnknownExpNum', ...
sprintf('Row %s (%02d) has an invalid experiment number: %s. Skipping it.', ...
DWGetRowID(this, iDWRow), iDWRow, expNum));
continue;
end;
% find the whisker data folder's path
whiskerDataFolderRow = DWFilterTable(this, sprintf('rowType = Whisker data AND day = %s', get(this, iDWRow, 'day')));
whiskerDataFolderPath = get(this, 1, 'path', whiskerDataFolderRow);
% get the path to the correct file using the experiment number
whiskerDataPath = sprintf('%s/Experiment_%d_Whisker_Tracking.mat', whiskerDataFolderPath, expNum);
% show a warning and skip if file cannot be found
if ~exist(whiskerDataPath, 'file');
showWarning(this, 'OCIA:OCIA_annotateTable_wenrui:FileNotFound', ...
sprintf('Whisker data for row %s (%02d) could not be found at "%s". Skipping it.', ...
DWGetRowID(this, iDWRow), iDWRow, whiskerDataPath));
continue;
end;
% load the whisker data
whiskDataMat = load(whiskerDataPath);
if isfield(whiskDataMat, 'MovieInfo');
% store the whisker angle data and its frame rate
dataStruct = struct('angle', whiskDataMat.MovieInfo.AvgWhiskerAngle, ...
'frameRate', whiskDataMat.MovieInfo.FramesPerSecond);
elseif isfield(whiskDataMat, 'whiskingAll');
% store the whisker angle data and its frame rate (hard-coded)
dataStruct = struct('angle', whiskDataMat.whiskingAll', 'frameRate', 200);
% unknown way of load data: show a warning and skip
else
showWarning(this, 'OCIA:OCIA_annotateTable_wenrui:UnknownContent', ...
sprintf('Whisker data for row %s (%02d) was found at "%s" but content is unknown. Skipping it.', ...
DWGetRowID(this, iDWRow), iDWRow, whiskerDataPath));
continue;
end;
% load the data and set the load status to full
setData(this, iDWRow, 'whisk', 'data', dataStruct);
setData(this, iDWRow, 'whisk', 'loadStatus', 'full');
% update wait bar
DWWaitBar(this, 100 * iRow / size(imagingRows, 1));
end;
% show message and update wait bar
showMessage(this, sprintf('Extracting whisker data for %02d imaging row(s) done.', size(imagingRows, 1)));
DWWaitBar(this, 100);
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataSaveConfig_img.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/others/OCIA_dataSaveConfig_img.m
| 2,446 |
utf_8
|
157a4a7a2ff2501ff296389c33bb3222
|
function dataConf = OCIA_dataConfig_img(this, iDWRow, dataConf)
% generate a configuration that specifies how the data should be saved as a cell-array with 7 columns:
% { data field name, data to save set/get function, sub-cells save name, names of the attributes to save,
% attributes to save, display name, data's size, the data save options }
preProcType = this.data.preProcType{iDWRow};
if ~isempty(preProcType); preProcType = regexprep(sprintf('%s,', preProcType{:}), ',$', ''); end;
dataConf = [ dataConf ; { ...
'raw', @setGetData_img, 'chan%02d', { 'rawLoadType' }, @setGetData_img, ...
'raw images', [], [];
'preProc', @setGetData_img, 'chan%02d', { 'preProcType' }, @setGetData_img, ...
'pre-processed images', [], [];
'caTraces', @setGetData_img, [], {}, {}, 'calcium traces', [], [];
'stim', @setGetData_img, [], {}, {}, 'stimulus vector', [], [];
'exclMask', @setGetData_img, [], {}, {}, 'exclusion mask', [], [];
}];
% small function specifying which fields should be updated
function out = setGetData_img(fieldName, in)
switch fieldName;
case 'raw'; if isempty(in); in = this.data.raw{iDWRow}; else this.data.raw{iDWRow} = in; end;
case 'rawLoadType'; if isempty(in); in = this.data.rawLoadType{iDWRow}; else this.data.rawLoadType{iDWRow} = in; end;
case 'preProc'; if isempty(in); in = this.data.preProc{iDWRow}; else this.data.preProc{iDWRow} = in; end;
case 'preProcType'; if isempty(in); in = preProcType; else
this.data.preProcType{iDWRow} = regexp(in, ',', 'split'); end;
case 'caTraces'; if isempty(in); in = this.data.img.caTraces{iDWRow}; else this.data.img.caTraces{iDWRow} = in; end;
case 'stim'; if isempty(in); in = this.data.img.stim{iDWRow}; else this.data.img.stim{iDWRow} = in; end;
case 'exclMask'; if isempty(in); in = this.data.img.exclMask{iDWRow}; else this.data.img.exclMask{iDWRow} = in; end;
end;
out = in;
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataSaveConfig_whisk.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/others/OCIA_dataSaveConfig_whisk.m
| 1,026 |
utf_8
|
fe313ea9c3368232c2956634ebca3dbf
|
function dataConf = OCIA_dataConfig_whisk(this, iDWRow, dataConf)
% generate a configuration that specifies how the data should be saved as a cell-array with 7 columns:
% { data field name, data to save set/get function, sub-cells save name, names of the attributes to save, attributes to save,
% display name, data's size, the data save options }
dataConf = [ dataConf; { ...
'whisk', @setGetData_whisk, [], {}, {}, 'whisker data', [], [];
}];
% small function specifying which fields should be updated
function out = setGetData_whisk(fieldName, in)
switch fieldName;
case 'whisk';
if isempty(in);
in = this.data.whisk(iDWRow);
else % load each attribute field by field
fNames = fieldnames(in);
for iField = 1 : numel(fNames);
this.data.whisk(iDWRow).(fNames{iField}) = in.(fNames{iField});
end;
end;
end;
out = in;
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
OCIA_dataSaveConfig_behav.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/others/OCIA_dataSaveConfig_behav.m
| 1,031 |
utf_8
|
1350a4228175fd1cdd5c933e69c72029
|
function dataConf = OCIA_dataSaveConfig_behav(this, iDWRow, dataConf)
% generate a configuration that specifies how the data should be saved as a cell-array with 7 columns:
% { data field name, data to save set/get function, sub-cells save name, names of the attributes to save, attributes to save,
% display name, data's size, the data save options }
dataConf = [ dataConf; { ...
'behav', @setGetData_behav, [], {}, {}, 'behavior data', [], [];
}];
% small function specifying which fields should be updated
function out = setGetData_behav(fieldName, in)
switch fieldName;
case 'behav';
if isempty(in);
in = this.data.behav(iDWRow);
else % load each attribute field by field
fNames = fieldnames(in);
for iField = 1 : numel(fNames);
this.data.behav(iDWRow).(fNames{iField}) = in.(fNames{iField});
end;
end;
end;
out = in;
end
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
DWMatchBehavTrialsToImagingDataShankar.m
|
.m
|
OCIA-master/caImgAnalysis/OCIA/custom/others/DWMatchBehavTrialsToImagingDataShankar.m
| 6,333 |
utf_8
|
68a4994114b2d05a5a911a375b5a86b6
|
function DWMatchBehavTrialsToImagingDataShankar(this)
% DWMatchBehavTrialsToImagingDataShankar - [no description]
%
% DWMatchBehavTrialsToImagingDataShankar(this)
%
% Match the behavior trials and the data files.
% 2013-2016 - Copyleft and programmed by Balazs Laurenczy (blaurenczy_at_gmail.com)
% update the wait bar
DWWaitBar(this, 0);
% get the list of all animals
uniqueAnimals = get(this, 'animal');
uniqueAnimals(cellfun(@isempty, uniqueAnimals)) = [];
uniqueAnimals = unique(uniqueAnimals);
% get the list of all days
uniqueDays = get(this, 'day');
uniqueDays(cellfun(@isempty, uniqueDays)) = [];
uniqueDays = unique(uniqueDays);
% get the list of all spots
uniqueSpots = get(this, 'spot');
uniqueSpots(cellfun(@isempty, uniqueSpots)) = [];
uniqueSpots = unique(uniqueSpots);
% get the selected animal IDs
selectedAnimalIDs = this.dw.animalIDs(get(this.GUI.handles.dw.filt.animalID, 'Value'));
% if the dash '-' is selected, select all IDs
if numel(selectedAnimalIDs) == 1 && strcmp(selectedAnimalIDs{1}, '-');
selectedAnimalIDs = uniqueAnimals;
end;
% get the selected day IDs
selectedDayIDs = this.dw.dayIDs(get(this.GUI.handles.dw.filt.dayID, 'Value'));
% if the dash '-' is selected, select all IDs
if numel(selectedDayIDs) == 1 && strcmp(selectedDayIDs{1}, '-');
selectedDayIDs = uniqueDays;
end;
% cell array storing all the informations to process each session
allSessionInfos = cell(1000, 5);
commentRows = DWFilterTable(this, sprintf('rowType = Imaging data AND runType = comment'));
if ~isempty(commentRows);
commentRowIndexes = str2double(get(this, 'all', 'rowNum', commentRows));
set(this, commentRowIndexes, 'runType', '');
end;
% first get all the information for each sessions to process
% go through each animal
for iAnim = 1 : numel(uniqueAnimals);
animalID = uniqueAnimals{iAnim}; % get the current animal
% skip irrelevant animal IDs
if ~ismember(animalID, selectedAnimalIDs); continue; end;
% go through each day
for iDay = 1 : numel(uniqueDays);
dayID = uniqueDays{iDay}; % get the current day
% skip irrelevant days
if ~ismember(dayID, selectedDayIDs); continue; end;
% go through spot by spot
for iSpot = 1 : numel(uniqueSpots);
spotID = uniqueSpots{iSpot}; % get the current spot
% get the imaging rows indexes for this day and this spot
imagingRows = DWFilterTable(this, ...
sprintf('animal = %s AND day = %s AND spot = %s AND rowType = Imaging data AND runType !~= \\w+', ...
animalID, dayID, spotID));
imagingRowIndexes = str2double(get(this, 'all', 'rowNum', imagingRows));
% if no imaging data, skip
if isempty(imagingRowIndexes) || any(isnan(imagingRowIndexes));
continue;
end;
% find behavior row
behavRow = DWFilterTable(this, ...
sprintf('animal = %s AND day = %s AND spot = %s AND rowType = Behavior data', ...
animalID, dayID, spotID));
% if no behavior row, continue
if isempty(behavRow);
continue;
end;
% get the DW's table row index
iDWRowBehav = str2double(get(this, 1, 'rowNum', behavRow));
% get behavior data
DWLoadRow(this, iDWRowBehav, 'full');
behavData = getData(this, iDWRowBehav, 'behavtext', 'data');
% check consistency
if numel(behavData) ~= numel(imagingRowIndexes);
showWarning(this, 'OCIA:DWMatchBehavTrialsToImagingDataShankar:NotEnoughBehavRows', ...
'Not enough behavior rows !');
continue;
end;
% match behavior data with imaging rows
for iRow = 1 : numel(imagingRowIndexes);
% annotate in table
stimID = behavData(iRow).stimulus;
set(this, imagingRowIndexes(iRow), 'runType', regexprep(stimID, 'Texture \d+ ', ''));
set(this, imagingRowIndexes(iRow), 'comments', behavData(iRow).decision);
set(this, imagingRowIndexes(iRow), 'runNum', sprintf('%03d', iRow));
% store the structure and mark it as loaded
setData(this, imagingRowIndexes(iRow), 'behavExtr', 'data', behavData(iRow));
setData(this, imagingRowIndexes(iRow), 'behavExtr', 'loadStatus', 'full');
end;
end; % end of spot loop
end; % end of day loop
end; % end of animal loop
% remove empty lines
allSessionInfos(cellfun(@isempty, allSessionInfos(:, 1)), :) = [];
nTotSessions = size(allSessionInfos, 1);
% match all sessions
for iTotSess = 1 : nTotSessions;
% match the behavior trials using the stored informations
DWMatchBehavTrialsToImagingDataForSession(this, allSessionInfos{iTotSess, :});
% update the wait bar
DWWaitBar(this, 99 * (iTotSess / nTotSessions));
end;
% remove raw behavior data for the current session
behavRows = DWFilterTable(this, 'rowType = Behavior data');
DWFlushData(this, str2double(get(this, 'all', 'rowNum', behavRows)), false, 'behav');
% final update of the wait bar
DWWaitBar(this, 100);
end
%% - #clusterRowsBySession
function sessIDs = clusterRowsBySession(this, rowNums)
% do not process if not at least 2 rows
if numel(rowNums) < 2;
sessIDs = repmat('1', numel(rowNums), 1);
return;
end;
% separate rows into morning and afternoon sessions
nUnknRows = size(rowNums, 1);
dateNums = zeros(nUnknRows, 1);
for iUnknRow = 1 : nUnknRows;
dateAndTime = get(this, rowNums(iUnknRow), { 'day', 'time' });
dateNums(iUnknRow) = datenum(sprintf('%s__%s', dateAndTime{:}), 'yyyy_mm_dd__HH_MM_SS');
end;
sessIDs = clusterdata(dateNums, 'maxclust', 2);
nearbySessDiffInHours = (dn2unix(dateNums(find(sessIDs == sessIDs(end), 1, 'first'))) ...
- dn2unix(dateNums(find(sessIDs == sessIDs(1), 1, 'last')))) / 1000 / 60 / 60;
% if sessions are too close, it means that it was a single session with a missing trial/interruption
if nearbySessDiffInHours < 3; % minimum 3 hours between sessions
sessIDs = clusterdata(dateNums, 'maxclust', 1);
end;
end
|
github
|
HelmchenLabSoftware/OCIA-master
|
runExperiment.m
|
.m
|
OCIA-master/caImgAnalysis/caImgExperiment/@CaImgExperiment/runExperiment.m
| 16,480 |
utf_8
|
3ec18810499954502e465b6c620c9fb9
|
function CaImgExp = runExperiment(CaImgExp, nRuns)
% runExperiment method for the CaImgExperiment class. Runs the calcium imaging experiment.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Originally created on 18 / 03 / 2012 %
% Written by B. Laurenczy ([email protected]) %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% display check list
if CaImgExp.checkAbort(['Let''s go:\n' ...
' - Check if heating pad is OK ...\n' ...
' - Check if laser is OK (shutter, wavelength, etc.) ...\n' ...
' - Check if sound (TDT?) is on, with attenutation OK ...\n' ...
' - Check if heloscan trigger cable is plugged ...\n' ...
' - Check if mouse''s breathing (anesthesia) is OK ...\n']);
return;
end;
%% BF test
if CaImgExp.checkSkip('BFTest');
% do the best frequency characterization test
% attenuations = zeros(1, nRuns);
attenuations = ones(1, nRuns) * 20;
% attenuations = repmat(attenuations, 2); % 10 repetitions
CaImgExp = CaImgExp.doBFTest(attenuations);
end;
%% CaImg runs
% if CaImgExp.checkSkip('Odd10%');
% if CaImgExp.checkAbort('WARNING! Do not forget to change stimulus duration and set a BF!!'); return; end;
% % run the oddball paradigm with 10% deviants
% CaImgExp = doOddballParadigm(CaImgExp, 10, 4);
% if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
% end;
%
% if CaImgExp.checkSkip('OddTrial');
% if CaImgExp.checkAbort('WARNING! Do not forget to change stimulus duration!!'); return; end;
% % run the oddball trial paradigm with 10% deviants
% CaImgExp = doOddballTrialParadigm(CaImgExp, 5);
% if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
% end;
if CaImgExp.checkSkip('Omi10%');
if CaImgExp.checkAbort('WARNING! Do not forget to change stimulus duration!!'); return; end;
% run the omission paradigm with 10% omissions
CaImgExp = doOmissionParadigm(CaImgExp, 10, 10);
if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
end;
% % run the oddball paradigm with 50% deviants, this is the equiprobable control
% [CaImgExp, abort] = doEquiProbControl(CaImgExp);
% if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
%
% % run the oddball paradigm with 30% deviants
% [CaImgExp, abort] = doOddballParadigm(CaImgExp, 30, 2);
% if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
%
% % run the omission paradigm with 10% of deviant sound, this is the deviant alone control
% [CaImgExp, abort] = doDevAloneControl(CaImgExp, 10);
% if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
%
% % run the oddball paradigm with 30% deviants
% [CaImgExp, abort] = doOddballParadigm(CaImgExp, 30, 2);
% if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
% % run the omission paradigm with 10% omissions
% [CaImgExp, abort] = doOmissionParadigm(CaImgExp, 10, 10);
% if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
%
% % run the omission paradigm with 30% omissions
% [CaImgExp, abort] = doOmissionParadigm(CaImgExp, 30, 4);
% if CaImgExp.checkAbort('Press [ENTER] to go on to next paradigm.'); return; end;
% if CaImgExp.checkAbort('Press [ENTER] if you are happy !'); return; end;
end % runExperiment
%% doOddballTrialParadigm
% oddball trial paradigm, F1 or F2 randomly assigned to be standard
% nRunsPerFreq: number of runs to do for each frequency (F1 and F2)
function [CaImgExp, abort] = doOddballTrialParadigm(CaImgExp, nRunsPerFreq)
% create a random sequences of 'swap' for alternating F1 and F2, each one 'nRunsPerFreq' times
F1F2Sequence = [ones(nRunsPerFreq, 1); -1 * ones(nRunsPerFreq, 1)];
% mix the sequence of F1 and F2
F1F2Sequence = F1F2Sequence(randperm(size(F1F2Sequence, 1)));
% check if the sequence is okay: nRunsPerFreq runs of each and no more '1' runs than -1
if size(F1F2Sequence, 1) ~= nRunsPerFreq * 2 || sum(F1F2Sequence) ~= 0;
warning('CaImgExperiment:doOddballTrialParadigm:BadF1F2MixSeq', ...
'F1F2 mixing sequence not the right length or not equilibrated!');
% save a backup of the aborted experiment
CaImgExp.saveAll(sprintf('backup_n%dOddTrial_%d_abortedF1F2Seq', CaImgExp.nSpots, proba, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2)));
abort = 1;
return;
end;
fprintf('Sequence of stimulation will be the following:\n');
disp(F1F2Sequence');
% calculate recording duration
dutyCycle = 500;
nTones = 3 + randi(5); % random number of tones between 4 and 8
roundTo = 1000;
recDur = dutyCycle * nTones + 2000;
recDur = recDur + roundTo - mod(recDur, roundTo); % recording duration rounded to 'roundTo' ms
% loop through all 'swap' combinations and play the oddball paradigm
for i = 1:size(F1F2Sequence, 1);
% initiate the file name
fileName = sprintf('sp%02dOddTrialF%d_%d', CaImgExp.nSpots, 1.5 - F1F2Sequence(i) / 2, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2) + 1);
abort = CaImgExp.checkAbort(sprintf('Stim name: %s, recording dur.: %d ms', fileName, recDur));
if abort; return; end;
fprintf('Oddball trial, no %d of %d\n', i, size(F1F2Sequence, 1));
% run the stimulation
% parameters : attenLevel, randomSeed = 1 (oddball at end), nStimuli, BFreqIndex, freqDev, swap,
% stimDur = 100ms, dutyCycle = 500ms, ephysRate = 20'000Hz;
% [CaImgExp, abort] = CaImgExp.runSingleStimulation('ODD_TRIAL', 0, randi(3) - 1, nTones, ...
[CaImgExp, abort] = CaImgExp.runSingleStimulation('ODD_TRIAL', 0, 1, nTones, ...
CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex, 0, 0.5, F1F2Sequence(i), 'useFMSweep', 5000);
if abort;
CaImgExp.saveAll('backup_abort'); % save a backup of the aborted experiment
return;
end;
CaImgExp.saveAll(fileName); % save a backup
CaImgExp.saveAll(); % save the experiment
end;
end % doOddballTrialParadigm
%% doOddballParadigm
% [proba]% oddball paradigm, F1 or F2 randomly assigned to be standard
% nRunsPerFreq: number of runs to do for each frequency (F1 and F2)
function [CaImgExp, abort] = doOddballParadigm(CaImgExp, proba, nRunsPerFreq)
% create a random sequences of 'swap' for alternating F1 and F2, each 'nRunsPerFreq' times
F1F2Sequence = [ones(nRunsPerFreq, 1); -1 * ones(nRunsPerFreq, 1)];
% mix the sequence of F1 and F2
F1F2Sequence = F1F2Sequence(randperm(size(F1F2Sequence, 1)));
% check if the sequence is okay: nRunsPerFreq runs of each and no more '1' runs than -1
if size(F1F2Sequence, 1) ~= nRunsPerFreq * 2 || sum(F1F2Sequence) ~= 0;
warning('CaImgExperiment:doOddballParadigm:BadF1F2MixSeq', ...
'F1F2 mixing sequence not the right length or not equilibrated!');
% save a backup of the aborted experiment
CaImgExp.saveAll(sprintf('backup_n%dOdd%d_%d_abortedF1F2Seq', CaImgExp.nSpots, proba, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2)));
abort = 1;
return;
end;
fprintf('Sequence of stimulation will be the following:\n');
disp(F1F2Sequence');
autoMode = str2double(input('Use auto mode? ', 's'));
% calculate recording duration
dutyCycle = 1500;
nTones = 50;
if CaImgExp.debugMode; nTones = 20; end;
roundTo = 2000;
recDur = dutyCycle * nTones + 1000;
recDur = recDur + roundTo - mod(recDur, roundTo); % recording duration rounded to 'roundTo' ms
% loop through all 'swap' combinations and play the oddball paradigm
for i = 1:size(F1F2Sequence, 1);
% initiate the file name
fileName = sprintf('sp%02dOdd%dF%d_%d', CaImgExp.nSpots, proba, 1.5 - F1F2Sequence(i) / 2, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2) + 1);
if autoMode;
fprintf('Stim name: %s, recording dur.: %d ms\n', fileName, recDur);
else
abort = CaImgExp.checkAbort(sprintf('Stim name: %s, recording dur.: %d ms', fileName, recDur));
if abort; return; end;
end;
fprintf('Oddball %d%% no %d of %d\n', proba, i, size(F1F2Sequence, 1));
% run the stimulation
% parameters : attenLevel, randomSeed (0-4), nStimuli, BFreqIndex, proba, freqDev, swap,
% stimDur = 100ms, dutyCycle = 500ms, ephysRate = 20'000Hz;
[CaImgExp, abort] = CaImgExp.runSingleStimulation('SSA_DEV', 0, randi(5) - 1, nTones, ...
CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex, proba, 0.5, F1F2Sequence(i), ...
'useFMSweep', 0, 'dutyCycle', dutyCycle); % pure tones
% CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex, proba, 0.5, F1F2Sequence(i), ...
% 'useFMSweep', 15000, 'dutyCycle', dutyCycle); % FMSweep
% CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex, proba, 0.5, F1F2Sequence(i), ...
% 'useBLN', 5000, 'dutyCycle', dutyCycle); % Band limited noise
if abort;
CaImgExp.saveAll('backup_abort'); % save a backup of the aborted experiment
return;
end;
CaImgExp.saveAll(fileName); % save a backup
CaImgExp.saveAll(); % save the experiment
end;
end % doOddballParadigm
%% doEquiProbControl
function [CaImgExp, abort] = doEquiProbControl(CaImgExp)
% initiate the file name
fileName = sprintf('sp%02dOdd%dF1_%d', CaImgExp.nSpots, 50, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2) + 1);
abort = CaImgExp.checkAbort(sprintf('Stim name: %s, sweep dur.: %d ms', fileName, 55000));
if abort; return; end;
% equiprob control, F1 is standard, 1 run
% parameters : attenLevel, randomSeed (0-4), nStimuli, BFreqIndex, proba, freqDev, swap,
% stimDur = 100ms, dutyCycle = 500ms, ephysRate = 20'000Hz;
if CaImgExp.debugMode;
[CaImgExp, abort] = CaImgExp.runSingleOddballParadigm(0, randi(5) - 1, 20, ...
CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex, 50, 0.5, 1);
else
[CaImgExp, abort] = CaImgExp.runSingleOddballParadigm(0, randi(5) - 1, 100, ...
CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex, 50, 0.5, 1);
end;
if abort;
CaImgExp.saveAll('backup_abort'); % save a backup of the aborted experiment
return;
end;
CaImgExp.saveAll(fileName); % save a backup
CaImgExp.saveAll(); % save the experiment
% initiate the file name
fileName = sprintf('sp%02dOdd%dF2_%d', CaImgExp.nSpots, 50, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2) + 1);
abort = CaImgExp.checkAbort(sprintf('Stim name: %s, sweep dur.: %d ms', fileName, 55000));
if abort; return; end;
% equiprob control, F2 is standard, 1 run
% parameters : attenLevel, randomSeed (0-4), nStimuli, BFreqIndex, proba, freqDev, swap,
% stimDur = 100ms, dutyCycle = 500ms, ephysRate = 20'000Hz;
if CaImgExp.debugMode;
[CaImgExp, abort] = CaImgExp.runSingleStimulation('SSA_DEV', 0, randi(5) - 1, 20, ...
CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex, 50, 0.5, -1);
else
[CaImgExp, abort] = CaImgExp.runSingleStimulation('SSA_DEV', 0, randi(5) - 1, 100, ...
CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex, 50, 0.5, -1);
end;
if abort;
CaImgExp.saveAll('backup_abort'); % save a backup of the aborted experiment
return;
end;
CaImgExp.saveAll(fileName); % save a backup
CaImgExp.saveAll(); % save the experiment
end % doEquiProbControl
%% doDevAloneControl
function [CaImgExp, abort] = doDevAloneControl(CaImgExp, proba)
BFreqIndex = CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex;
if BFreqIndex == 1 || BFreqIndex == 15;
warning('CaImgExperiment:doDevAloneControl:BFOutOfRange', ...
['The deviant alone control will not be accurated as F1 or F2' ...
' cannot be played (out of range)']);
% HACK the BF so that BF + 1 and BF -1 are in range
if BFreqIndex == 1; BFreqIndex = 2;
elseif BFreqIndex == 15; BFreqIndex = 14;
end
end
% [100 - proba]% omission = proba% deviants alone, F1 or F2 as lonely deviant, 5 runs each
% number of runs to do for each frequency (F1 and F2)
nRunsPerFreq = 5;
% create a random sequences of 'swap' for alternating F1 and F2, each 'nRunsPerFreq' times
F1F2Sequence = [ones(nRunsPerFreq, 1); -1 * ones(nRunsPerFreq, 1)];
% mix the sequence of F1 and F2
F1F2Sequence = F1F2Sequence(randperm(size(F1F2Sequence, 1)));
% check if the sequence is okay: nRunsPerFreq runs of each and no more '1' runs than -1
if size(F1F2Sequence, 1) ~= nRunsPerFreq * 2 || sum(F1F2Sequence) ~= 0;
warning('CaImgExperiment:doDevAloneControl:BadF1F2MixSeq', ...
'F1F2 mixing sequence not the right length or not equilibrated!');
% save a backup of the aborted experiment
CaImgExp.saveAll(sprintf('backup_n%dDevAl%d_%d_abortedF1F2Seq', CaImgExp.nSpots, proba, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2)));
abort = 1;
return;
end;
fprintf('Sequence of stimulation will be the following:\n');
disp(F1F2Sequence');
% loop through all 'swap' combinations and play the oddball paradigm
for i = 1:size(F1F2Sequence, 1);
% initiate the file name
fileName = sprintf('sp%02dDevAl%dF%d_%d', CaImgExp.nSpots, proba, 1.5 - F1F2Sequence(i) / 2, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2) + 1);
abort = CaImgExp.checkAbort(sprintf('Stim name: %s, sweep dur.: %d ms', fileName, 55000));
if abort; return; end;
fprintf('DevAl %d%% no %d of %d\n', proba, i, size(F1F2Sequence, 1));
% run the stimulation
% parameters : attenLevel, randomSeed (0-4), nStimuli, BFreqIndex, proba, freqDev, swap,
% stimDur = 100ms, dutyCycle = 500ms, ephysRate = 20'000Hz;
if CaImgExp.debugMode;
[CaImgExp, abort] = CaImgExp.runSingleStimulation('SSA_OMI', 10, randi(5) - 1, 20, ...
BFreqIndex + F1F2Sequence(i), proba, 0.5, 1);
else
[CaImgExp, abort] = CaImgExp.runSingleStimulation('SSA_OMI', 10, randi(5) - 1, 100, ...
BFreqIndex + F1F2Sequence(i), proba, 0.5, 1);
end;
if abort;
CaImgExp.saveAll('backup_abort'); % save a backup of the aborted experiment
return;
end;
CaImgExp.saveAll(fileName); % save a backup
CaImgExp.saveAll(); % save the experiment
end;
end % doDevAloneControl
%% doOmissionParadigm
function [CaImgExp, abort] = doOmissionParadigm(CaImgExp, proba, nRuns)
BFreqIndex = CaImgExp.spots{CaImgExp.nSpots}.BFreqIndex;
% [proba]% omission, best freq is standard, nRuns runs
for i = 1:nRuns;
% initiate the file name
fileName = sprintf('sp%02dOmi%d_%d', CaImgExp.nSpots, proba, ...
size(CaImgExp.spots{CaImgExp.nSpots}.stims, 2) + 1);
abort = CaImgExp.checkAbort(sprintf('Stim name: %s, sweep dur.: %d ms', fileName, 55000));
if abort; return; end;
fprintf('Omi %d%% no %d of %d\n', proba, i, nRuns);
% parameters : attenLevel, randomSeed (0-4), nStimuli, BFreqIndex, proba, freqDev, swap,
% stimDur = 100ms, dutyCycle = 500ms, ephysRate = 20'000Hz;
if CaImgExp.debugMode;
[CaImgExp, abort] = CaImgExp.runSingleStimulation('SSA_OMI', 10, randi(5) - 1, 20, ...
BFreqIndex, proba, 0.5, -1);
else
[CaImgExp, abort] = CaImgExp.runSingleStimulation('SSA_OMI', 10, randi(5) - 1, 100, ...
BFreqIndex, proba, 0.5, -1);
end;
if abort;
CaImgExp.saveAll('backup_abort'); % save a backup of the aborted experiment
return;
end;
CaImgExp.saveAll(fileName); % save a backup
CaImgExp.saveAll(); % save the experiment
end;
end % doOmissionParadigm
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.